Compare commits

...
Author SHA1 Message Date
Dr.Lt.Data 063e845fc8 v4: An install by a git URL takes a commit and a URL with a user
`cm-cli install <url>` and Install via Git URL of the legacy UI cloned the
whole text as the URL. `https://host/owner/repo@<commit>` failed, where
`main` installs that commit, and an SSH URL of a host other than GitHub,
`git@host:owner/repo.git`, was cloned from github.com and failed (#3627).

- `extract_url_and_commit_id` moves to `common/git_utils.py` and skips the
  host part first, so the `@` of a user is not the one that names a commit.
  The copy of the glob core split at the user
- The legacy install takes the commit off the URL and checks it out, as the
  glob install does
- `cm-cli install <url>` and `cm-cli install-deps` install through the glob
  core
- On Windows the clone is made by `git_helper.py --clone`, which now takes
  the commit as one more argument and checks it out
- A clone whose checkout fails is removed, in both cores and for the clone
  of the helper script: the install failed and left the clone at the tip of
  the default branch
- `checkout` of the pygit2 backend takes a short commit id, and a branch of
  `origin` as a local branch that tracks it, when the name is nothing else,
  as git does
- `normalize_to_github_id` does not read a text with a `:` as the short
  `owner/repo` of a GitHub repository
- `normalize_to_github_id` looks for `github` in the host of the URL, not
  in the whole text: a URL of another host with that word in its user or
  its path was cloned from github.com
- Add tests: each spelling of a URL is cloned through both cores from a
  repository of the test, and ends at its commit
- Add a CHANGELOG entry

The change of the split for main is #3628.
2026-12-05 23:23:55 +09:00
Dr.Lt.Data bca61a9d27 v4: An install by a git URL is a clone, and its failure leaves the version enabled (#3662)
`gitclone_install` of the glob core asked the registry for the latest
version of the nodepack when the URL was of a repository that the registry
lists, as `main` does since #1813. The legacy core clones its nightly, and
it is the one that `cm-cli` and the route of the legacy server call. The
glob function has no caller yet.

A nightly install over an enabled version of the registry disabled that
version before the clone, and left the nodepack with no enabled version when
the clone failed.

- The glob install asks for the nightly of such a nodepack, as the legacy
  install does
- `_install_git` of both cores enables the version again when the clone
  fails. This is the install by a URL, of `<id>@nightly`, and a switch to
  nightly
- Both cores pass `instant_execution` and `no_deps` on to the install by a
  URL, which dropped them, and the URL, which `install_by_id` now takes as
  `reinstall_by_id` does. The clone is of the URL that was given: the legacy
  install cloned the repository that the channel has under the name of the
  nodepack, which can be another repository of the same name
- Add tests for both cores: the URL of a repository that the registry lists
  is cloned from a repository of the test with the flags of the caller and
  no version is asked for, also over an enabled version, and that version
  is enabled again when the clone fails
- Add CHANGELOG entries

The change for main is #3661.
2026-12-05 21:13:49 +09:00
Dr.Lt.Data ec562aab5d v4: A folder can be a channel of a private network (#3654)
A line of `channels.list` that names a folder, such as
`private::\\NAS\comfy\channel`, was refused with
`An invalid channel was used`: `normalize_channel` took an https URL,
an http URL with `http_channel_enabled`, or the name of a channel, and
raised `InvalidChannel` for the folder that the name stood for.

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

The same change for main is #2669.
2026-12-05 10:34:22 +09:00
Dr.Lt.Data ce965cdbcf v4: A list request without mode is answered (#3653)
`GET /v2/customnode/getmappings` of both servers, and
`/v2/customnode/getlist` and `/v2/externalmodel/getlist` of the legacy
server, read `mode` with `request.rel_url.query["mode"]` and answered
500 with `KeyError: 'mode'` for a request without it (#2740).

- The four handlers read `mode` with `cache` as its default
- Add a test for the four handlers: a request without `mode` gets the
  answer of `mode=cache`, which is not the answer of `mode=local`
- `tests/test_legacy_secgate_other_paths.py` puts back the `get_data` that
  it replaces for its own cases. It left the replacement in place, and a
  test that ran after it read no file
- Add a CHANGELOG entry

The same change for main is #2741.
2026-12-04 01:19:38 +09:00
Dr.Lt.Data 18ca3be301 v4: The Version column no longer shows an older registry version as an update (#3651)
The Version column of the legacy Custom Nodes Manager showed
`[↑<version>]` whenever the installed version was not the latest
version of the registry, so a nodepack installed at 1.78.1 showed
`[↑1.47.0]` when the registry had 1.47.0 as its latest (#3272).

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

The same change for main is #3364.
2026-12-03 12:50:44 +09:00
Benjamin Lu bf98e9f2cc v4: Report desktop-linux form factor for Desktop installs on Linux (#3377)
A Desktop install on Linux reported `form_factor=other` to the
registry. The Manager mapped the marker that Desktop sets,
`__COMFYUI_DESKTOP_VERSION__`, to `desktop-win` and `desktop-mac` only,
and Desktop sets the marker on Linux since its v1.1.8.

- Move the choice of the form factor out of the fetch of the registry
  list into `get_form_factor()`
- Desktop on Linux reports `desktop-linux`. Every other combination
  reports what it did before
- Add tests for each platform with and without the marker, and for the
  request carrying the value, and a CHANGELOG entry
2026-12-03 12:00:18 +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
37 changed files with 1986 additions and 138 deletions
+175
View File
@@ -9,6 +9,37 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
### Added
- A folder can be a channel of a private network. With
`network_mode = private`, a line of `channels.list` can name a folder, such
as `private::\\NAS\comfy\channel` or `private::/srv/comfy/channel`. Such a
line was refused with `An invalid channel was used`: the channel was in the
Channel menu of the legacy UI, and its list did not load. The folder is now
read as a channel, so a closed network needs no web server for its own
`custom-node-list.json`. As for every channel but the default one, its
lists are read at the start with `default_cache_as_channel_url = True`, or
with the database mode `remote`. Only a folder that is written in
`channels.list` is a channel, and only on a private network. A folder that
a request names, or that only `channel_url` of `config.ini` names, is
refused as before.
With another `network_mode` the folder is refused, and the refusal names the
channel as `channels.list` names it and the setting that it needs, not the
folder. The legacy Custom Nodes Manager shows it in place of `Failed to get
custom node list.`, an install from that channel reports it, `cm-cli show`
prints it in place of a traceback, and the start logs it as a warning. A
refused channel no longer stops the tasks of the start with a traceback. For
a channel that `channels.list` does not have, the legacy Custom Nodes
Manager, `cm-cli` and an install say that a channel has to be in
`channels.list`, without its URL or folder.
- 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
@@ -36,6 +67,150 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
### Fixed
- An install by a git URL takes a commit, and a URL with a user. `cm-cli
install <url>` and **Install via Git URL** of the legacy UI cloned the whole
text as the URL, so `https://host/owner/repo@<commit>` failed, where `main`
installs that commit. They now clone the repository and check out what
follows the last `@` of the path, a commit, a tag or a branch such as
`feature/x`. The `@` of a user is not that one:
`git@host:owner/repo.git`, `ssh://git@host/owner/repo.git` and
`https://user:token@host/owner/repo.git` are cloned whole, and each takes
`@<commit>` after it (#3627, as #3628 for `main`). An install whose commit
is not in the repository fails and leaves no clone. With the pygit2 backend,
a branch of the repository and a short commit id are checked out as well.
An SSH URL of a host other than GitHub, `git@host:owner/repo.git`, was
cloned from `https://github.com/git@host:owner/repo.git` and failed: a text
with one `/` was read as the short `owner/repo` of a GitHub repository. A
text with a `:` is no longer read that way. A URL is taken for a GitHub
repository by its host: a URL of another host with the word `github` in its
user or its path, such as `https://gitlab.example.com/owner/github-tools.git`,
was cloned from `https://github.com/owner/github-tools`. A URL of GitHub is
still cloned as `https://github.com/<owner>/<repo>`, without its user or its
token.
- A nightly install over an enabled version of the registry enables that
version again when the clone fails. The version was disabled first, and the
nodepack was left with no enabled version. This was so for
`cm-cli install <url>` of a repository that the registry lists, for
**Install via Git URL** of the legacy UI, and for an install of `nightly`
over a version.
- `cm-cli install <url>` and **Install via Git URL** of the legacy UI clone
the URL that was given when the registry lists the repository. They cloned
the repository that the channel has under the name of the nodepack, which is
another repository when the channel lists two of that name.
- `cm-cli install <url> --no-deps` leaves the requirements of a repository
that the registry lists. The install of such a repository by its URL dropped
`--no-deps`, and installed the requirements. `cm-cli install-deps` passes
its flags the same way, and they were dropped as well.
- A list request without `mode` is answered. `GET /v2/customnode/getmappings`
and, with the legacy UI, `/v2/customnode/getlist` and
`/v2/externalmodel/getlist` answered 500 with `KeyError: 'mode'` when the
request had no `mode` (#2740). Such a request is now answered as one with
`mode=cache`. The legacy pages always send `mode`, so nothing changes for
them.
- The Version column of the legacy Custom Nodes Manager no longer shows an
older registry version as an update. The column showed `[↑<version>]`
whenever the installed version was not the latest version of the registry,
so a nodepack installed at 1.78.1 showed `[↑1.47.0]` when the registry had
1.47.0 as its latest (#3272). The arrow is now shown only when the version
of the registry is newer. For a version that is not only numbers, such as
`2.0.0-rc1`, an enabled nodepack shows the arrow when an update is offered
for it, and a disabled one is as before. The **Update** button is not
changed: it was already offered only for a newer version.
- 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
+14 -5
View File
@@ -36,6 +36,7 @@ from comfyui_manager.common.git_compat import setup_git_environment
from comfyui_manager.common import manager_util
from comfyui_manager.common import cm_global
from comfyui_manager.legacy import manager_core as core
from comfyui_manager.glob import manager_core as glob_core
from comfyui_manager.common import context
from comfyui_manager.legacy.manager_core import unified_manager
from comfyui_manager.common import cnr_utils
@@ -193,9 +194,9 @@ class NodeInstallError(Exception):
def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
raise_on_fail = kwargs.get('raise_on_fail', False)
if core.is_valid_url(node_spec_str):
if glob_core.is_valid_url(node_spec_str):
# install via urls
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
res = asyncio.run(glob_core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
if not res.result:
print(res.msg)
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
@@ -446,7 +447,11 @@ def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
def show_list(kind, simple=False):
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
# collect not-installed unknown nodes
not_installed_unknown_nodes = []
@@ -1343,7 +1348,7 @@ def install_deps(
if state == 'installed':
continue
elif state == 'not-installed':
asyncio.run(core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
asyncio.run(glob_core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
else: # disabled
cnr = unified_manager.get_cnr_by_repo(k)
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
@@ -1484,7 +1489,11 @@ def export_custom_node_ids(
for x in unified_manager.cnr_map.keys():
print(x, file=output_file)
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
try:
custom_nodes = asyncio.run(unified_manager.get_custom_nodes(channel=cmd_ctx.channel, mode=cmd_ctx.mode))
except core.InvalidChannel as e:
print(f"ERROR: {e.reason}", style="bold red")
raise typer.Exit(code=1)
for x in custom_nodes.values():
if 'cnr_latest' not in x:
if len(x['files']) == 1:
+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)
+8 -7
View File
@@ -910,16 +910,17 @@ class _Pygit2Repo(GitRepo):
return
try:
oid = _pygit2.Oid(hex=ref)
obj = self._repo.get(oid)
if obj is not None:
commit = obj.peel(_pygit2.Commit)
self._repo.checkout_tree(self._repo.get(commit.id))
self._repo.set_head(commit.id)
return
commit = self._repo.revparse_single(ref).peel(_pygit2.Commit)
self._repo.checkout_tree(self._repo.get(commit.id))
self._repo.set_head(commit.id)
return
except Exception:
pass
if self._repo.references.get(f'refs/remotes/origin/{ref}') is not None:
self.checkout_new_branch(ref, f'origin/{ref}')
return
raise GitCommandError(f"Cannot resolve ref for checkout: {ref}")
def checkout_new_branch(self, branch_name, start_point):
+1 -1
View File
@@ -549,7 +549,7 @@ try:
if len(sys.argv) > 4:
repo_path = sys.argv[4]
gitclone(sys.argv[2], sys.argv[3], repo_path=repo_path)
gitclone(sys.argv[2], sys.argv[3], target_hash=sys.argv[5] if len(sys.argv) > 5 else None, repo_path=repo_path)
elif sys.argv[1] == "--check":
gitcheck(sys.argv[2], False)
elif sys.argv[1] == "--fetch":
+21 -4
View File
@@ -1,6 +1,7 @@
import os
import configparser
import logging
import re
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
@@ -147,12 +148,15 @@ def normalize_url(url) -> str:
return url
_HOST_OF_GIT_URL = re.compile(r'^(?:[A-Za-z][A-Za-z0-9+.-]*://)?(?:[^/@]*@)?([^/:]*)')
def normalize_to_github_id(url) -> str:
if 'github' in url or (GITHUB_ENDPOINT is not None and GITHUB_ENDPOINT in url):
if 'github' in _HOST_OF_GIT_URL.match(url).group(1).lower() or (GITHUB_ENDPOINT is not None and GITHUB_ENDPOINT in url):
author = os.path.basename(os.path.dirname(url))
if author.startswith('git@github.com:'):
author = author.split(':')[1]
if ':' in author:
author = author.rsplit(':', 1)[1]
repo_name = os.path.basename(url)
if repo_name.endswith('.git'):
@@ -161,7 +165,7 @@ def normalize_to_github_id(url) -> str:
return f"{author}/{repo_name}"
# Handle short format like "author/repo" (aux_id format)
if '/' in url and not url.startswith('http'):
if '/' in url and not url.startswith('http') and ':' not in url:
parts = url.split('/')
if len(parts) == 2 and parts[0] and parts[1]:
return url
@@ -169,6 +173,19 @@ def normalize_to_github_id(url) -> str:
return None
_GIT_URL_BEFORE_PATH = re.compile(r'^(?:[A-Za-z][A-Za-z0-9+.-]*://[^/]*(?:/|$)|[^/@:]+@[^/@:]+:)')
def extract_url_and_commit_id(s):
before_path = _GIT_URL_BEFORE_PATH.match(s)
path_start = before_path.end() if before_path else 0
index = s.rfind('@', path_start)
if index == -1:
return (s, '')
else:
return (s[:index], s[index+1:])
def get_url_for_clone(url):
url = normalize_url(url)
+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:
+47
View File
@@ -18,6 +18,7 @@ import subprocess
import sys
import tempfile
import re
import codecs
import logging
import platform
import shlex
@@ -1536,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.
+66 -35
View File
@@ -72,9 +72,10 @@ default_custom_nodes_path = None
class InvalidChannel(Exception):
def __init__(self, channel):
def __init__(self, channel, reason='The channel is not allowed. A channel has to be in `channels.list`.'):
self.channel = channel
super().__init__(channel)
self.reason = reason
super().__init__(reason)
def get_default_custom_nodes_path():
@@ -191,6 +192,13 @@ def normalize_channel(channel):
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
elif channel.startswith('\\\\') or os.path.isabs(channel):
network_mode = get_config()['network_mode']
if network_mode == 'private':
return channel
for name, url in get_channel_dict().items():
if url == channel:
raise InvalidChannel(channel, f"The channel '{name}' is a folder, and a folder is allowed as a channel only with `network_mode = private`. The current network_mode is `{network_mode}`.")
tmp_dict = get_channel_dict()
channel_url = tmp_dict.get(channel)
@@ -553,6 +561,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:
@@ -653,7 +667,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
@@ -1023,7 +1037,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):
@@ -1265,7 +1279,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)
@@ -1462,9 +1480,11 @@ class UnifiedManager:
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
to_path = self._git_install_path(node_id, version_spec, repo_url)
replaced_version = None
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
replaced_version = self.get_cnr_active_version(node_id)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
@@ -1477,11 +1497,13 @@ class UnifiedManager:
cnr_utils.generate_cnr_id(to_path, node_id)
self.active_nodes[node_id] = 'nightly', to_path
else:
if replaced_version is not None and not os.path.lexists(to_path):
self.unified_enable(node_id, replaced_version)
return res
return res.with_target(version_spec)
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False, repo_url=None):
"""
priority if version_spec == None
1. CNR latest
@@ -1493,8 +1515,9 @@ class UnifiedManager:
if 'comfyui-manager' in node_id.lower():
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
repo_url = None
if version_spec is None:
if node_id in self.cnr_map:
self.forget_gone_disabled_versions_if_one_is_left(node_id)
if self.is_enabled(node_id):
return ManagedResult('skip')
elif self.is_disabled(node_id):
@@ -1502,11 +1525,11 @@ class UnifiedManager:
else:
version_spec = self.resolve_unspecified_version(node_id)
if version_spec == 'unknown' or version_spec == 'nightly':
if repo_url is None and (version_spec == 'unknown' or version_spec == 'nightly'):
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
@@ -1573,7 +1596,7 @@ class UnifiedManager:
try:
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
install_path = self._git_install_path(node_id, version_spec, repo_url)
@@ -2196,11 +2219,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:
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
for line in manager_util.read_requirements_lines(requirements_path):
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
pip_fixer.fix_broken()
if os.path.exists(install_script_path):
@@ -2383,13 +2405,6 @@ def is_valid_url(url):
return False
def extract_url_and_commit_id(s):
index = s.rfind('@')
if index == -1:
return (s, '')
else:
return (s[:index], s[index+1:])
async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=False):
await unified_manager.reload('cache')
await unified_manager.get_custom_nodes('default', 'cache')
@@ -2407,9 +2422,9 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
cnr_id = cnr['id']
return await unified_manager.install_by_id(cnr_id, version_spec=None, channel='default', mode='cache')
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache', instant_execution=instant_execution, no_deps=no_deps, repo_url=url)
else:
new_url, commit_id = extract_url_and_commit_id(url)
new_url, commit_id = git_utils.extract_url_and_commit_id(url)
if commit_id != "":
url = new_url
repo_name = os.path.splitext(os.path.basename(url))[0]
@@ -2438,18 +2453,26 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
# Clone the repository from the remote URL
clone_url = git_utils.get_url_for_clone(url)
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = clone_repo(clone_url, repo_path, progress=GitProgress())
if commit_id!= "":
repo.checkout(commit_id)
repo.submodule_update()
cloned = False
try:
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path] + ([commit_id] if commit_id else []), cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = clone_repo(clone_url, repo_path, progress=GitProgress())
try:
if commit_id!= "":
repo.checkout(commit_id)
repo.submodule_update()
repo.clear_cache()
repo.close()
repo.clear_cache()
finally:
repo.close()
cloned = True
finally:
if not cloned and os.path.exists(repo_path):
try_rmtree(url, repo_path)
execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
print("Installation was successful.")
@@ -2514,6 +2537,14 @@ async def get_data_by_mode(mode, filename, channel_url=None):
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):
+7 -4
View File
@@ -1427,7 +1427,7 @@ async def fetch_customnode_mappings(request):
"""
provide unified (node -> node pack) mapping list
"""
mode = request.rel_url.query["mode"]
mode = request.rel_url.query.get("mode", "cache")
nickname_mode = False
if mode == "nickname":
@@ -2222,9 +2222,12 @@ async def default_cache_update():
await core.unified_manager.reload(
ManagerDatabaseSource.remote.value, dont_wait=False
)
await core.unified_manager.get_custom_nodes(
channel_url, ManagerDatabaseSource.remote.value
)
try:
await core.unified_manager.get_custom_nodes(
channel_url, ManagerDatabaseSource.remote.value
)
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
else:
await core.unified_manager.reload(
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
+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"]:
+2 -1
View File
@@ -422,7 +422,8 @@ export async function fetchData(route, options) {
if (status !== 200) {
return {
status,
error: new Error(statusText || "Unknown Error")
error: new Error(statusText || "Unknown Error"),
detail: await res.text().catch(() => "")
}
}
@@ -218,6 +218,7 @@
.cn-manager-grid .cn-pack-conflicts {
color: orange;
white-space: normal;
}
.cn-popover {
+45 -11
View File
@@ -22,6 +22,22 @@ const gridId = "node";
const INVALID_INSTALLATION_GUIDANCE = "This nodepack was not installed through ComfyUI-Manager, or its installation is damaged, so the Manager cannot update it. Reinstalling deletes its folder and installs the nodepack again.";
function compareVersionSpecs(a, b) {
const pa = String(a).split(".").map((x) => /^\d+$/.test(x) ? parseInt(x, 10) : NaN);
const pb = String(b).split(".").map((x) => /^\d+$/.test(x) ? parseInt(x, 10) : NaN);
if (pa.some(Number.isNaN) || pb.some(Number.isNaN)) {
return null;
}
const len = Math.max(pa.length, pb.length);
for (let i = 0; i < len; i++) {
const x = pa[i] || 0;
const y = pb[i] || 0;
if (x > y) return 1;
if (x < y) return -1;
}
return 0;
}
const pageHtml = `
<div class="cn-manager cn-manager-dark">
<div class="cn-manager-grid"></div>
@@ -850,7 +866,12 @@ export class CustomNodesManager {
if(version == 'nightly') {
return `<div>${sanitizeHTML(String(version))}</div><div>[${sanitizeHTML(String(rowItem.cnr_latest))}]</div>`;
}
return `<div>${sanitizeHTML(String(version))}</div><div>[↑${sanitizeHTML(String(rowItem.cnr_latest))}]</div>`;
const cmp = compareVersionSpecs(rowItem.cnr_latest, version);
const serverChecked = rowItem.state === 'enabled';
const newer = cmp === null && serverChecked ? rowItem['update-state'] === 'true' : cmp === null || cmp === 1;
if(newer) {
return `<div>${sanitizeHTML(String(version))}</div><div>[↑${sanitizeHTML(String(rowItem.cnr_latest))}]</div>`;
}
}
return sanitizeHTML(String(version));
}
@@ -883,6 +904,9 @@ export class CustomNodesManager {
if (rowItem.conflicts) {
list.push(`<div class="cn-pack-conflicts">${rowItem.conflicts} conflict${(rowItem.conflicts>1?'s':'')}</div>`);
}
if (rowItem.potentialConflicts) {
list.push(`<div class="cn-pack-conflicts">${rowItem.potentialConflicts} potential conflict${(rowItem.potentialConflicts>1?'s':'')}</div>`);
}
list.push('</div>');
return list.join("");
}
@@ -1326,8 +1350,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';
}
@@ -1336,8 +1361,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>`);
}
@@ -1380,6 +1406,7 @@ export class CustomNodesManager {
}
const conflictsMap = {};
const nodesMapByPack = new Map();
// add nodes data
Object.keys(data).forEach(k => {
@@ -1392,9 +1419,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
};
@@ -1406,6 +1436,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)
@@ -1422,13 +1453,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
@@ -1442,6 +1475,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;
}
})
@@ -2141,7 +2175,7 @@ export class CustomNodesManager {
// a server that was not restarted since its update still fetches every repository without skip_update
const res = await fetchData(`/v2/customnode/getlist?mode=${mode}&skip_update=true`);
if (res.error) {
this.showError("Failed to get custom node list.");
this.showError(res.status === 403 && res.detail ? sanitizeHTML(res.detail) : "Failed to get custom node list.");
this.hideLoading();
return;
}
+69 -24
View File
@@ -70,9 +70,10 @@ default_custom_nodes_path = None
class InvalidChannel(Exception):
def __init__(self, channel):
def __init__(self, channel, reason='The channel is not allowed. A channel has to be in `channels.list`.'):
self.channel = channel
super().__init__(channel)
self.reason = reason
super().__init__(reason)
def get_default_custom_nodes_path():
@@ -192,6 +193,13 @@ def normalize_channel(channel):
return normalize_channel_url(channel)
elif channel.startswith('http://') and get_config()['http_channel_enabled'] == True:
return channel
elif channel.startswith('\\\\') or os.path.isabs(channel):
network_mode = get_config()['network_mode']
if network_mode == 'private':
return channel
for name, url in get_channel_dict().items():
if url == channel:
raise InvalidChannel(channel, f"The channel '{name}' is a folder, and a folder is allowed as a channel only with `network_mode = private`. The current network_mode is `{network_mode}`.")
tmp_dict = get_channel_dict()
channel_url = tmp_dict.get(channel)
@@ -543,6 +551,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:
@@ -604,7 +618,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
@@ -972,7 +986,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):
@@ -1214,7 +1228,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)
@@ -1396,7 +1414,7 @@ class UnifiedManager:
else:
return self.cnr_switch_version(node_id, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall).with_ver('cnr')
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False):
async def install_by_id(self, node_id: str, version_spec=None, channel=None, mode=None, instant_execution=False, no_deps=False, return_postinstall=False, repo_url=None):
"""
priority if version_spec == None
1. CNR latest
@@ -1408,8 +1426,9 @@ class UnifiedManager:
if 'comfyui-manager' in node_id.lower():
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
repo_url = None
if version_spec is None:
if node_id in self.cnr_map:
self.forget_gone_disabled_versions_if_one_is_left(node_id)
if self.is_enabled(node_id):
return ManagedResult('skip')
elif self.is_disabled(node_id):
@@ -1418,11 +1437,11 @@ class UnifiedManager:
else:
version_spec = self.resolve_unspecified_version(node_id)
if version_spec in ('unknown', 'nightly'):
if repo_url is None and version_spec in ('unknown', 'nightly'):
try:
repo_url = await self.get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
@@ -1496,9 +1515,11 @@ class UnifiedManager:
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
to_path = self._git_install_path(node_id, version_spec, repo_url)
replaced_version = None
if version_spec == 'nightly':
# disable cnr nodes
if self.is_enabled(node_id, 'cnr'):
replaced_version = self.get_cnr_active_version(node_id)
res = self.disable_for_replacement(node_id, to_path)
if not res.result:
return res
@@ -1511,6 +1532,8 @@ class UnifiedManager:
cnr_utils.generate_cnr_id(to_path, node_id)
self.active_nodes[node_id] = 'nightly', to_path
else:
if replaced_version is not None and not os.path.lexists(to_path):
self.unified_enable(node_id, replaced_version)
return res
return res.with_target(version_spec)
@@ -1524,7 +1547,7 @@ class UnifiedManager:
try:
repo_url = await self.get_git_install_url(node_id, version_spec, channel, mode)
except InvalidChannel as exc:
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
return ManagedResult('fail').fail(exc.reason)
except LookupError as exc:
return ManagedResult('install').fail(str(exc))
install_path = self._git_install_path(node_id, version_spec, repo_url)
@@ -2121,11 +2144,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:
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
for line in manager_util.read_requirements_lines(requirements_path):
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args:
try_install_script(url, repo_path, manager_util.make_pip_cmd(["install", *install_args]), instant_execution=instant_execution)
pip_fixer.fix_broken()
if os.path.exists(install_script_path):
@@ -2265,8 +2287,11 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
cnr_id = cnr['id']
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache')
return await unified_manager.install_by_id(cnr_id, version_spec='nightly', channel='default', mode='cache', instant_execution=instant_execution, no_deps=no_deps, repo_url=url)
else:
new_url, commit_id = git_utils.extract_url_and_commit_id(url)
if commit_id != "":
url = new_url
repo_name = os.path.splitext(os.path.basename(url))[0]
# NOTE: Keep original name as possible if unknown node
@@ -2293,14 +2318,26 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
# Clone the repository from the remote URL
clone_url = git_utils.get_url_for_clone(url)
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path], cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
repo.git.clear_cache()
repo.close()
cloned = False
try:
if not instant_execution and platform.system() == 'Windows':
res = manager_funcs.run_script([sys.executable, context.git_script_path, "--clone", get_default_custom_nodes_path(), clone_url, repo_path] + ([commit_id] if commit_id else []), cwd=get_default_custom_nodes_path())
if res != 0:
return result.fail(f"Failed to clone '{clone_url}' into '{repo_path}'")
else:
repo = git.Repo.clone_from(clone_url, repo_path, recursive=True, progress=GitProgress())
try:
if commit_id != "":
repo.git.checkout(commit_id)
repo.git.submodule('update', '--init', '--recursive')
repo.git.clear_cache()
finally:
repo.close()
cloned = True
finally:
if not cloned and os.path.exists(repo_path):
try_rmtree(url, repo_path)
execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
print("Installation was successful.")
@@ -2377,6 +2414,14 @@ async def get_data_by_mode(mode, filename, channel_url=None):
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):
+19 -8
View File
@@ -875,7 +875,7 @@ async def fetch_customnode_mappings(request):
"""
provide unified (node -> node pack) mapping list
"""
mode = request.rel_url.query["mode"]
mode = request.rel_url.query.get("mode", "cache")
nickname_mode = False
if mode == "nickname":
@@ -1134,14 +1134,20 @@ async def fetch_customnode_list(request):
"""
provide unified custom node list
"""
if request.rel_url.query["mode"] == "local":
mode = request.rel_url.query.get("mode", "cache")
if mode == "local":
channel = 'local'
else:
channel = core.get_config()['channel_url']
node_packs = await core.get_unified_total_nodes(channel, request.rel_url.query["mode"], 'cache')
json_obj_github = core.get_data_by_mode(request.rel_url.query["mode"], 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(request.rel_url.query["mode"], 'extras.json', 'default')
try:
node_packs = await core.get_unified_total_nodes(channel, mode, 'cache')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
return web.Response(status=403, text=e.reason)
json_obj_github = core.get_data_by_mode(mode, 'github-stats.json', 'default')
json_obj_extras = core.get_data_by_mode(mode, 'extras.json', 'default')
core.populate_github_stats(node_packs, await json_obj_github)
core.populate_favorites(node_packs, await json_obj_extras)
@@ -1224,8 +1230,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']:
@@ -1235,7 +1243,7 @@ def check_model_installed(json_obj):
@routes.get("/v2/externalmodel/getlist")
async def fetch_externalmodel_list(request):
# The model list is only allowed in the default channel, yet.
json_obj = await core.get_data_by_mode(request.rel_url.query["mode"], 'model-list.json')
json_obj = await core.get_data_by_mode(request.rel_url.query.get("mode", "cache"), 'model-list.json')
check_model_installed(json_obj)
@@ -2078,7 +2086,10 @@ async def default_cache_update():
else:
# load at least once
await core.unified_manager.reload('remote', dont_wait=False)
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
try:
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
except core.InvalidChannel as e:
logging.warning(f"[ComfyUI-Manager] {e.reason}")
else:
await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
+5 -1
View File
@@ -713,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)
+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
```
+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
+50 -3
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
@@ -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"))
@@ -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")
+13 -1
View File
@@ -44,7 +44,7 @@ def cm_cli(manager, core, monkeypatch): # noqa: F811
'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,
'traceback': traceback, 'core': core, 'glob_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,
@@ -348,3 +348,15 @@ def test_restore_dependencies_runs_for_the_nodepacks_only(cm_cli, manager, folde
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')]
def test_a_list_of_a_refused_channel_says_why_and_fails(cm_cli, manager, core, monkeypatch): # noqa: F811
async def refused(channel, mode):
raise core.InvalidChannel('/srv/channel', 'the reason [of it]')
monkeypatch.setattr(manager, 'get_custom_nodes', refused)
with pytest.raises(typer.Exit) as stop:
cm_cli('show_list')['show_list']('all')
assert (cm_cli.said(), stop.value.exit_code) == (['ERROR: the reason [of it]'], 1)
+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']
+59
View File
@@ -846,6 +846,65 @@ finally:
self.assertEqual(p2['sha'], self.first_sha)
self.assertTrue(p2['detached'])
def test_checkout_branch_of_the_remote_after_a_clone(self):
snippet = """
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout('feature-branch')
print(json.dumps({"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached, "branch": repo.active_branch_name}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
branch_sha = subprocess.run(['git', 'rev-parse', 'feature-branch'], cwd=self.repo_path, capture_output=True, text=True, check=True).stdout.strip()
for result in _run_both(snippet, self.repo_path):
self.assertEqual(result, {'sha': branch_sha, 'detached': False, 'branch': 'feature-branch'})
def test_checkout_of_a_name_that_is_a_tag_and_a_branch_of_the_remote_takes_the_tag(self):
origin = os.path.join(self._tmpdir, 'tag_and_branch')
os.makedirs(origin)
def git(*args):
return subprocess.run(['git', '-c', 'user.name=Test', '-c', 'user.email=test@test.com', *args], cwd=origin, capture_output=True, text=True, check=True).stdout.strip()
git('init', '-b', 'master')
git('commit', '--allow-empty', '-m', 'tagged')
git('tag', 'both')
tagged = git('rev-parse', 'HEAD')
git('checkout', '-b', 'both')
git('commit', '--allow-empty', '-m', 'on the branch')
git('checkout', 'master')
snippet = """
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout('both')
print(json.dumps({"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
for result in _run_both(snippet, origin):
self.assertEqual(result, {'sha': tagged, 'detached': True})
def test_checkout_by_short_sha(self):
snippet = f"""
import tempfile, shutil
dest = tempfile.mkdtemp()
try:
repo = clone_repo(REPO_PATH, os.path.join(dest, 'cloned'))
repo.checkout({self.first_sha[:8]!r})
print(json.dumps({{"sha": repo.head_commit_hexsha, "detached": repo.head_is_detached}}))
repo.close()
finally:
shutil.rmtree(dest, ignore_errors=True)
"""
for result in _run_both(snippet, self.repo_path):
self.assertEqual(result, {'sha': self.first_sha, 'detached': True})
# === list_remotes fetch routing (pygit2) ===
def test_list_remotes_fetch_routing_pygit2(self):
+118
View File
@@ -0,0 +1,118 @@
import asyncio
import subprocess
from unittest.mock import AsyncMock, Mock
import pytest
from _install_flags_testutil import GIT_LOCATION, import_reader
HOST = 'git.example.invalid'
PREFIXES = [f'https://{HOST}/grp/', f'https://user:token@{HOST}/grp/', f'git@{HOST}:grp/', f'ssh://git@{HOST}/grp/']
REFS = [('zz-pack.git', 'tip'), ('zz-pack.git@{first}', 'first'), ('zz-pack.git@feature/x', 'branch')]
def git(path, *args):
return subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True, text=True).stdout.strip()
@pytest.fixture(params=['glob', 'legacy'])
def core(request):
return import_reader(request.param)
@pytest.fixture
def git_reads_the_folder_of_the_test_for_each_prefix(tmp_path, monkeypatch):
for name in GIT_LOCATION:
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv('GIT_CONFIG_COUNT', str(len(PREFIXES)))
for index, prefix in enumerate(PREFIXES):
monkeypatch.setenv(f'GIT_CONFIG_KEY_{index}', f'url.{tmp_path}/grp/.insteadOf')
monkeypatch.setenv(f'GIT_CONFIG_VALUE_{index}', prefix)
@pytest.fixture
def commits(tmp_path, git_reads_the_folder_of_the_test_for_each_prefix):
origin = tmp_path / 'grp' / 'zz-pack.git'
origin.mkdir(parents=True)
git(origin, 'init', '-q', '-b', 'main')
commits = {}
for name, branch in (('first', None), ('tip', None), ('branch', 'feature/x')):
if branch:
git(origin, 'checkout', '-q', '-b', branch)
(origin / '__init__.py').write_text(f'# {name}')
git(origin, 'add', '.')
git(origin, 'commit', '-q', '-m', name)
commits[name] = git(origin, 'rev-parse', 'HEAD')
git(origin, 'checkout', '-q', 'main')
return commits
@pytest.fixture
def install(core, monkeypatch, tmp_path):
nodes = tmp_path / 'custom_nodes'
nodes.mkdir()
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(nodes))
monkeypatch.setattr(core, 'get_custom_nodes_paths', lambda: [str(nodes)])
monkeypatch.setattr(core, 'execute_install_script', Mock(return_value=True))
monkeypatch.setattr(core.unified_manager, 'reload', AsyncMock())
monkeypatch.setattr(core.unified_manager, 'get_custom_nodes', AsyncMock(return_value={}))
monkeypatch.setattr(core.unified_manager, 'get_cnr_by_repo', lambda url: None)
def run(url, instant_execution=True):
result = asyncio.run(core.gitclone_install(url, instant_execution=instant_execution, no_deps=True))
return result.result, {path.name: git(path, 'rev-parse', 'HEAD') for path in nodes.iterdir()}
return run
@pytest.mark.parametrize('prefix', PREFIXES)
@pytest.mark.parametrize('rest, wanted', REFS, ids=[wanted for _, wanted in REFS])
def test_git_url_is_installed_at_its_commit(install, commits, prefix, rest, wanted):
assert install(prefix + rest.format(**commits)) == (True, {'zz-pack': commits[wanted]})
def test_clone_that_the_helper_script_makes_on_windows_is_at_the_commit(install, commits, core, monkeypatch, tmp_path):
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
(tmp_path / 'folder_paths.py').write_text('')
monkeypatch.setenv('COMFYUI_PATH', str(tmp_path))
assert install(f'https://{HOST}/grp/zz-pack.git@{commits["first"]}', instant_execution=False) == (True, {'zz-pack': commits['first']})
def test_git_url_whose_commit_is_not_there_fails_and_leaves_no_clone(install, commits):
assert install(f'https://{HOST}/grp/zz-pack.git@no-such-commit') == (False, {})
def test_clone_that_the_helper_script_makes_on_windows_is_removed_when_the_commit_is_not_there(install, commits, core, monkeypatch, tmp_path):
monkeypatch.setattr(core.platform, 'system', lambda: 'Windows')
(tmp_path / 'folder_paths.py').write_text('')
monkeypatch.setenv('COMFYUI_PATH', str(tmp_path))
assert install(f'https://{HOST}/grp/zz-pack.git@no-such-commit', instant_execution=False) == (False, {})
def test_user_of_a_git_url_with_no_path_is_not_a_commit(core):
assert core.git_utils.extract_url_and_commit_id(f'https://user:token@{HOST}') == (f'https://user:token@{HOST}', '')
GITHUB = 'https://github.com/owner/repo'
@pytest.mark.parametrize('url, clone_url, repository', [
('git@gitlab.example.invalid:owner/repo.git', 'git@gitlab.example.invalid:owner/repo.git', 'git@gitlab.example.invalid:owner/repo.git'),
('git@gitlab.example.invalid:github/repo.git', 'git@gitlab.example.invalid:github/repo.git', 'git@gitlab.example.invalid:github/repo.git'),
('https://gitlab.example.invalid/owner/github-tools.git', 'https://gitlab.example.invalid/owner/github-tools.git', 'https://gitlab.example.invalid/owner/github-tools.git'),
('https://github-bot:token@gitlab.example.invalid/owner/repo.git', 'https://github-bot:token@gitlab.example.invalid/owner/repo.git', 'https://github-bot:token@gitlab.example.invalid/owner/repo.git'),
('https://user:token@github.com/owner/repo.git', GITHUB, GITHUB),
('https://github.com/owner/repo.git', GITHUB, GITHUB),
('https://GitHub.com/owner/repo.git', GITHUB, GITHUB),
('git@github.com:owner/repo.git', GITHUB, GITHUB),
('git@GitHub.com:owner/repo.git', GITHUB, GITHUB),
('ssh://git@github.com/owner/repo.git', GITHUB, GITHUB),
('owner/repo', GITHUB, GITHUB),
])
def test_only_a_url_of_a_github_host_is_a_github_repository(core, monkeypatch, url, clone_url, repository):
monkeypatch.setattr(core.git_utils, 'GITHUB_ENDPOINT', None)
assert (core.git_utils.get_url_for_clone(url), core.git_utils.normalize_url(url)) == (clone_url, repository)
+106
View File
@@ -0,0 +1,106 @@
import asyncio
import subprocess
from unittest.mock import AsyncMock, Mock
import pytest
from _install_flags_testutil import GIT_LOCATION, import_reader
URL = 'https://git.example.invalid/grp/zz-pack'
ANOTHER_URL = 'https://git.example.invalid/other/zz-pack'
def git(path, *args):
return subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True, text=True).stdout.strip()
@pytest.fixture(params=['glob', 'legacy'])
def core(request):
return import_reader(request.param)
@pytest.fixture
def origin(tmp_path, monkeypatch):
for name in GIT_LOCATION:
monkeypatch.delenv(name, raising=False)
origin = tmp_path / 'grp' / 'zz-pack'
origin.mkdir(parents=True)
git(origin, 'init', '-q')
for version in (1, 2):
(origin / '__init__.py').write_text(f'VERSION = {version}')
git(origin, 'add', '.')
git(origin, 'commit', '-q', '-m', f'version {version}')
another = tmp_path / 'other' / 'zz-pack'
another.mkdir(parents=True)
git(another, 'init', '-q')
(another / '__init__.py').write_text('ANOTHER = 1')
git(another, 'add', '.')
git(another, 'commit', '-q', '-m', 'another repository of the same name')
monkeypatch.setenv('GIT_CONFIG_COUNT', '2')
monkeypatch.setenv('GIT_CONFIG_KEY_0', f'url.{tmp_path}/gone/.insteadOf')
monkeypatch.setenv('GIT_CONFIG_VALUE_0', 'https://git.example.invalid/grp/')
monkeypatch.setenv('GIT_CONFIG_KEY_1', f'url.{tmp_path}/other/.insteadOf')
monkeypatch.setenv('GIT_CONFIG_VALUE_1', 'https://git.example.invalid/other/')
return origin
@pytest.fixture
def git_reads_the_origin_for_the_url(origin, monkeypatch):
monkeypatch.setenv('GIT_CONFIG_KEY_0', f'url.{origin.parent}/.insteadOf')
@pytest.fixture
def install_by_url(core, origin, monkeypatch, tmp_path):
nodes = tmp_path / 'custom_nodes'
nodes.mkdir()
listed = {'id': 'zz-pack', 'repository': URL, 'latest_version': {'version': '1.0.0'}}
asked_for_a_version = Mock(return_value=None)
scripts_of_the_clone = Mock(return_value=True)
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(nodes))
monkeypatch.setattr(core, 'get_custom_nodes_paths', lambda: [str(nodes)])
monkeypatch.setattr(core.unified_manager, 'reload', AsyncMock())
for installed in ('active_nodes', 'cnr_inactive_nodes', 'nightly_inactive_nodes'):
monkeypatch.setattr(core.unified_manager, installed, type(getattr(core.unified_manager, installed))())
channel = {}
monkeypatch.setattr(core.unified_manager, 'get_custom_nodes', AsyncMock(return_value=channel))
monkeypatch.setattr(core.unified_manager, 'get_cnr_by_repo', lambda repo: listed)
monkeypatch.setitem(core.unified_manager.cnr_map, 'zz-pack', listed)
monkeypatch.setattr(core.unified_manager, 'execute_install_script', scripts_of_the_clone)
monkeypatch.setattr(core.cnr_utils, 'install_node', asked_for_a_version)
tip = git(origin, 'rev-parse', 'HEAD')
def run(version_is_enabled=False, channel_lists_another_repository_of_that_name=False):
if channel_lists_another_repository_of_that_name:
channel['zz-pack'] = {'repository': ANOTHER_URL, 'files': [ANOTHER_URL]}
if version_is_enabled:
(nodes / 'zz-pack').mkdir()
(nodes / 'zz-pack' / 'pyproject.toml').write_text('[project]\nname = "zz-pack"\nversion = "1.0.0"\n')
(nodes / 'zz-pack' / '.tracking').write_text('pyproject.toml')
monkeypatch.setitem(core.unified_manager.active_nodes, 'zz-pack', ('1.0.0', str(nodes / 'zz-pack')))
result = asyncio.run(core.gitclone_install(URL, instant_execution=True, no_deps=True))
left = {str(path.relative_to(nodes)): 'the tip' if git(path, 'rev-parse', 'HEAD') == tip else 'a clone' for path in nodes.rglob('*') if (path / '.git').is_dir()}
left.update({str(path.relative_to(nodes)): 'version 1.0.0' for path in nodes.rglob('*') if (path / '.tracking').is_file()})
asked_for_a_version.assert_not_called()
return result.result, left, [call.kwargs for call in scripts_of_the_clone.call_args_list]
return run
FLAGS = [{'instant_execution': True, 'no_deps': True}]
def test_url_of_a_repository_that_the_registry_lists_is_cloned(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url() == (True, {'zz-pack': 'the tip'}, FLAGS)
def test_url_is_what_is_cloned_when_the_channel_lists_another_repository_of_that_name(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url(channel_lists_another_repository_of_that_name=True) == (True, {'zz-pack': 'the tip'}, FLAGS)
def test_url_of_a_nodepack_whose_version_is_enabled_is_cloned_and_the_version_is_disabled(install_by_url, git_reads_the_origin_for_the_url):
assert install_by_url(version_is_enabled=True) == (True, {'zz-pack': 'the tip', '.disabled/zz-pack@1_0_0': 'version 1.0.0'}, FLAGS)
def test_enabled_version_is_enabled_again_when_the_clone_in_its_place_fails(install_by_url):
assert install_by_url(version_is_enabled=True) == (False, {'zz-pack': 'version 1.0.0'}, [])
+1 -1
View File
@@ -26,7 +26,7 @@ def install(node, exit_on_fail):
'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,
'glob_core': SimpleNamespace(is_valid_url=lambda spec: False), 'unified_manager': unified_manager,
})['install']([node], None, None, False, False, None, exit_on_fail)
+5 -2
View File
@@ -52,6 +52,7 @@ from _install_flags_testutil import ( # noqa: E402
)
_LEGACY_SERVER = None
_GET_DATA = None
def _import_legacy_server():
@@ -59,7 +60,7 @@ def _import_legacy_server():
(idempotent; memoized). Returns the real module object so the tests drive
the REAL gate function and REAL handlers — only the runtime *environment*
is stubbed, never the gate logic."""
global _LEGACY_SERVER
global _LEGACY_SERVER, _GET_DATA
if _LEGACY_SERVER is not None:
return _LEGACY_SERVER
@@ -108,6 +109,7 @@ def _import_legacy_server():
async def _inert_get_data(uri, *a, **k):
return {"custom_nodes": [], "models": [], "node_map": {}}
_GET_DATA = mu.get_data
mu.get_data = _inert_get_data
_LEGACY_SERVER = importlib.import_module("comfyui_manager.legacy.manager_server")
@@ -116,7 +118,8 @@ def _import_legacy_server():
@pytest.fixture(scope="module")
def ms():
return _import_legacy_server()
yield _import_legacy_server()
sys.modules["comfyui_manager.common.manager_util"].get_data = _GET_DATA
@pytest.fixture
+28
View File
@@ -0,0 +1,28 @@
import asyncio
import json
import re
from types import SimpleNamespace
import pytest
from aiohttp import web
from legacy_html_testutil import PACKAGE, load_functions
from test_default_channel import COMFY_ORG, configure, registry, route, user, write # noqa: F401
ROUTES = [('glob', 'fetch_customnode_mappings'), ('legacy', 'fetch_customnode_mappings'),
('legacy', 'fetch_customnode_list'), ('legacy', 'fetch_externalmodel_list')]
@pytest.mark.parametrize('server,name', ROUTES)
def test_a_request_without_mode_is_answered_as_mode_cache(user, registry, server, name): # noqa: F811
configure(user, None, COMFY_ORG)
write(user, f'{server} start')
handler = load_functions(PACKAGE / server / 'manager_server.py', {name}, {
'core': user.cores[server], 'web': web, 'routes': SimpleNamespace(get=route, post=route), 're': re,
'nodes': SimpleNamespace(NODE_CLASS_MAPPINGS={}), 'populate_markdown': lambda row: None,
'check_model_installed': lambda listed: None})[name]
def ask(**query):
return json.loads(asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query=query)))).text)
assert ask() == ask(mode='cache') != ask(mode='local')
+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
+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
+1 -1
View File
@@ -255,7 +255,7 @@ def test_cm_cli_install_reports_an_enable_that_failed(core, custom_nodes): # no
(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),
'asyncio': asyncio, 'core': core, 'glob_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):
+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"]}},
}
+148
View File
@@ -0,0 +1,148 @@
import asyncio
import json
import logging
import os
import sys
import traceback
from types import SimpleNamespace
import pytest
from aiohttp import web
from legacy_html_testutil import PACKAGE, load_functions
from test_default_channel import COMFY_ORG, answer, configure, handlers, idle, route, user, write # noqa: F401
SHARED_URL = 'https://github.com/example/ComfyUI-Shared'
SERVERS = ['glob', 'legacy']
NETWORKS = [((), 'public'), (('network_mode = offline',), 'offline')]
UNLISTED = 'The channel is not allowed. A channel has to be in `channels.list`.'
@pytest.fixture
def share(user): # noqa: F811
folder = user.path / 'share'
folder.mkdir()
(folder / 'custom-node-list.json').write_text(json.dumps({'custom_nodes': [
{'author': 'example', 'title': 'ComfyUI-Shared', 'reference': SHARED_URL, 'files': [SHARED_URL],
'install_type': 'git-clone', 'description': ''}]}))
read, cloned = [], []
read_data = user.util.get_data
async def recording(uri, silent=False):
read.append(uri)
return await read_data(uri, silent)
user.monkeypatch.setattr(user.util, 'get_data', recording)
custom_nodes = user.path / 'comfyui' / 'custom_nodes'
custom_nodes.mkdir(parents=True)
user.monkeypatch.setattr(sys.modules['folder_paths'], 'get_folder_paths', lambda name: [str(custom_nodes)], raising=False)
def start(server):
write(user, f'{server} start')
core = user.cores[server]
manager = core.UnifiedManager()
def repo_install(url, to_path, **kwargs):
cloned.append(url)
return core.ManagedResult('install')
user.monkeypatch.setattr(manager, 'repo_install', repo_install)
user.monkeypatch.setattr(core, 'unified_manager', manager)
read.clear()
return core
return SimpleNamespace(folder=str(folder), start=start, read=read, cloned=cloned)
def install(core, channel):
result = asyncio.run(core.unified_manager.install_by_id('ComfyUI-Shared', 'unknown', channel, 'cache'))
return result.result, result.msg
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_that_channels_list_names_is_a_channel_of_a_private_network(user, share, server): # noqa: F811
configure(user, share.folder, COMFY_ORG, 'network_mode = private', 'default_cache_as_channel_url = True')
with open(user.path / 'channels.list', 'a') as f:
f.write(f'private::{share.folder}\n')
core = share.start(server)
assert list(asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))) == ['ComfyUI-Shared']
assert answer(handlers(user, server, {'channel_url_list'})['channel_url_list'])['selected'] == 'private'
assert install(core, 'private') == (True, None)
assert share.cloned == [SHARED_URL]
@pytest.mark.parametrize('unc', [False, True], ids=['folder', 'UNC'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_request_cannot_name_a_folder_that_channels_list_does_not_have(user, share, server, unc): # noqa: F811
configure(user, None, COMFY_ORG, 'network_mode = private')
core = share.start(server)
channel = '\\\\attacker\\share' if unc else share.folder
assert install(core, channel) == (False, UNLISTED)
assert (share.cloned, share.read) == ([], [])
def needs(mode):
return ("The channel 'private' is a folder, and a folder is allowed as a channel only with `network_mode = private`. "
f'The current network_mode is `{mode}`.')
def register(user, share, *lines): # noqa: F811
configure(user, share.folder, COMFY_ORG, *lines)
with open(user.path / 'channels.list', 'a') as f:
f.write(f'private::{share.folder}\n')
@pytest.mark.parametrize('lines', [('network_mode = private',), ()], ids=['private', 'public'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_that_only_config_ini_names_is_refused(user, share, server, lines): # noqa: F811
configure(user, share.folder, COMFY_ORG, *lines)
core = share.start(server)
with pytest.raises(core.InvalidChannel) as refused:
asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))
assert refused.value.reason == UNLISTED
assert share.read == []
@pytest.mark.parametrize('lines,mode', NETWORKS, ids=['public', 'offline'])
@pytest.mark.parametrize('server', SERVERS)
def test_a_folder_on_another_network_is_refused_with_the_setting_it_needs(user, share, server, lines, mode): # noqa: F811
register(user, share, *lines)
core = share.start(server)
with pytest.raises(core.InvalidChannel) as refused:
asyncio.run(core.unified_manager.get_custom_nodes(core.get_config()['channel_url'], 'cache'))
assert refused.value.reason == needs(mode)
assert install(core, 'private') == (False, needs(mode))
assert (share.cloned, share.read) == ([], [])
def test_the_legacy_list_answers_why_a_folder_is_refused(user, share): # noqa: F811
register(user, share)
core = share.start('legacy')
handler = load_functions(PACKAGE / 'legacy/manager_server.py', {'fetch_customnode_list'}, {
'core': core, 'web': web, 'logging': logging, 'routes': SimpleNamespace(get=route, post=route)})['fetch_customnode_list']
response = asyncio.run(handler(SimpleNamespace(rel_url=SimpleNamespace(query={'mode': 'cache'}))))
assert (response.status, response.text) == (403, needs('public'))
@pytest.mark.parametrize('server', SERVERS)
def test_the_start_warns_of_a_folder_on_a_public_network_and_completes(user, share, server, caplog): # noqa: F811
register(user, share)
core = share.start(server)
user.monkeypatch.setattr(core.unified_manager, 'reload', idle)
user.monkeypatch.setattr(core, 'check_invalid_nodes', lambda: None)
start = load_functions(PACKAGE / server / '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'))})['default_cache_update']
with caplog.at_level(logging.WARNING):
asyncio.run(start())
assert [record.getMessage() for record in caplog.records if 'network_mode' in record.getMessage()] == [
f'[ComfyUI-Manager] {needs("public")}']
assert [uri for uri in share.read if uri.startswith(share.folder)] == []
+173
View File
@@ -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'],
+129
View File
@@ -0,0 +1,129 @@
import json
import os
import unittest
from pathlib import Path
from js_lift import NODE, JsSource, run_node, slice_braced, slice_object_entry
REPO_ROOT = Path(__file__).resolve().parent.parent
JS = JsSource(os.environ.get("MANAGER_JS_DIR") or (REPO_ROOT / "comfyui_manager" / "js"))
MANAGER = "custom-nodes-manager.js"
COMMON = "common.js"
VERSION_ANCHOR = "id: 'version',"
HELPER_MARKER = "function compareVersionSpecs"
def _helper_source() -> str:
return slice_braced(JS.text(MANAGER), HELPER_MARKER)
def _version_formatter() -> str:
block = slice_object_entry(JS.text(MANAGER), VERSION_ANCHOR)
marker = "formatter:"
return block[block.index(marker) + len(marker):].strip()
def _sanitize_html_source() -> str:
return JS.lift_declaration(COMMON, "export function sanitizeHTML(")
def _render(formatter_source: str, installed, cnr_latest, **row) -> str:
script = "\n".join([
_sanitize_html_source(),
_helper_source(),
"const formatter = %s;" % (formatter_source,),
"const rowItem = %s;" % json.dumps({"cnr_latest": cnr_latest, "originalData": {"id": "x"}, **row}),
"console.log(JSON.stringify({markup: String(formatter(%s, rowItem, {}))}));"
% json.dumps(installed),
])
return run_node(script)["markup"]
BADGE = "<div>%s</div><div>[↑%s]</div>"
CASES = [
("1.78.1", "1.47.0", "1.78.1",
"issue #3272: locally newer must NOT be flagged as updatable"),
("1.47.0", "1.47.0", "1.47.0",
"equal versions: no badge"),
("1.0.0", "1.47.0", BADGE % ("1.0.0", "1.47.0"),
"registry is genuinely newer: badge kept"),
("1.78.1", "0.0.0", "1.78.1",
"manager_core's 'no latest_version' sentinel must not render [↑0.0.0]"),
("0.0.0", "1.47.0", BADGE % ("0.0.0", "1.47.0"),
"a 0.0.0 install is still older than the registry: badge kept"),
("1.2", "1.10.0", BADGE % ("1.2", "1.10.0"),
"numeric compare: 1.10.0 > 1.2 (a string compare would miss this update)"),
("1.10.0", "1.2", "1.10.0",
"numeric compare: 1.10.0 > 1.2, so no badge"),
("nightly", "1.47.0", "<div>nightly</div><div>[1.47.0]</div>",
"the nightly branch is untouched: no arrow, badge-free"),
("1.2.3rc1", "1.47.0", BADGE % ("1.2.3rc1", "1.47.0"),
"unparseable spec: legacy string behavior kept"),
]
UNORDERED_CASES = [
("2.0.0rc1", "1.47.0", "enabled", "false", "2.0.0rc1",
"a release candidate of a newer version is not behind the registry"),
("1.0.0-beta.2", "0.9.0", "enabled", "false", "1.0.0-beta.2",
"a beta of a newer version is not behind the registry"),
("1.0.0", "nightly", "enabled", "false", "1.0.0",
"a nodepack without a version in the registry has nothing to update to"),
("1.2.3rc1", "1.47.0", "enabled", "true", BADGE % ("1.2.3rc1", "1.47.0"),
"the server offers the update: badge kept"),
("1.2.3rc1", "1.47.0", "disabled", "false", BADGE % ("1.2.3rc1", "1.47.0"),
"disabled: the server has no answer, legacy string behavior kept"),
("1.78.1", "1.47.0", "enabled", "true", "1.78.1",
"versions the helper orders do not read update-state"),
]
@unittest.skipIf(NODE is None, "node is required to execute the lifted production JS")
class VersionBadgeSemverTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.formatter = _version_formatter()
def _markup(self, installed, cnr_latest) -> str:
return _render(self.formatter, installed, cnr_latest)
def test_the_badge_follows_numeric_ordering(self):
for installed, latest, expected, why in CASES:
with self.subTest(installed=installed, cnr_latest=latest):
self.assertEqual(self._markup(installed, latest), expected, why)
def test_an_enabled_nodepack_follows_the_server_for_versions_the_helper_cannot_order(self):
for installed, latest, state, update_state, expected, why in UNORDERED_CASES:
with self.subTest(installed=installed, cnr_latest=latest, state=state):
row = {"state": state, "update-state": update_state}
self.assertEqual(_render(self.formatter, installed, latest, **row), expected, why)
@unittest.skipIf(NODE is None, "node is required to execute the lifted production JS")
class CompareVersionSpecsTest(unittest.TestCase):
def _compare(self, a, b):
out = run_node(
"%s\nconsole.log(JSON.stringify({r: compareVersionSpecs(%s, %s)}));"
% (_helper_source(), json.dumps(a), json.dumps(b))
)
return out["r"]
def test_dot_separated_specs_order_numerically(self):
self.assertEqual(self._compare("1.2.10", "1.2.9"), 1)
self.assertEqual(self._compare("1.10.0", "1.9"), 1)
self.assertEqual(self._compare("1.9", "1.10.0"), -1)
self.assertEqual(self._compare("1.47.0", "1.47.0"), 0)
self.assertEqual(self._compare("1.2", "1.2.0"), 0)
def test_non_numeric_specs_return_null(self):
self.assertIsNone(self._compare("nightly", "1.47.0"))
self.assertIsNone(self._compare("1.2.3rc1", "1.47.0"))
self.assertIsNone(self._compare("1.47.0", ""))
if __name__ == "__main__":
unittest.main()
+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()