Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3cabc86ee | ||
|
|
69529c6784 | ||
|
|
3902292033 | ||
|
|
c0f58ee0a7 | ||
|
|
81ca9190f9 | ||
|
|
20999f24ad | ||
|
|
768756d284 | ||
|
|
4da6862b9a | ||
|
|
5249cdea87 | ||
|
|
3407fdd404 | ||
|
|
bebdf19035 | ||
|
|
dab74c91c9 | ||
|
|
055b9cd9b6 | ||
|
|
0a04dc7ccf | ||
|
|
813d696e2c | ||
|
|
6798c6d6b2 | ||
|
|
1d360ace35 | ||
|
|
e2ef555237 | ||
|
|
8618b9ccdb | ||
|
|
b078269ccd | ||
|
|
388fb3ea27 | ||
|
|
6fabc5e0a2 | ||
|
|
dc8a83e298 | ||
|
|
a066d786cd | ||
|
|
c68f6820dd | ||
|
|
92369545f9 | ||
|
|
90a05c166c | ||
|
|
a270d3b95c | ||
|
|
5538a03d8b | ||
|
|
89329cc341 | ||
|
|
22d4e24387 | ||
|
|
f910b6e73d | ||
|
|
a17b568b42 | ||
|
|
22965fe92e | ||
|
|
30e027bedd | ||
|
|
2673d47a7e | ||
|
|
499b18b69f | ||
|
|
ea083afca6 | ||
|
|
088c149880 | ||
|
|
f92a308602 | ||
|
|
55e61bea54 | ||
|
|
ef84421c07 | ||
|
|
c58eab6703 | ||
|
|
85d0221fac | ||
|
|
d8e9dedab2 | ||
|
|
ee42311db8 | ||
|
|
9044e40f8c | ||
|
|
acd30204c6 | ||
|
|
5898cadeed | ||
|
|
41bc94c48e | ||
|
|
2dd2f10cb3 | ||
|
|
55682fb9a8 | ||
|
|
7ab6b39cd7 | ||
|
|
aa75e89e87 | ||
|
|
31d8ecea27 | ||
|
|
c39db72d1a | ||
|
|
c7dded76c3 | ||
|
|
82e8f56adb | ||
|
|
22e589905c | ||
|
|
e9dd14404f | ||
|
|
00c8503cb6 | ||
|
|
ce02fc53c8 | ||
|
|
594cf22ab7 | ||
|
|
622723ca7f | ||
|
|
1d7e39c128 | ||
|
|
5905d60ab6 | ||
|
|
106749a107 | ||
|
|
aeb0bdb898 | ||
|
|
2d74c4acb2 | ||
|
|
a90fa0f7fe | ||
|
|
ac158f7617 | ||
|
|
e8312757a4 | ||
|
|
dab0a6746f | ||
|
|
2908ccdd6f | ||
|
|
e14aafb2e3 | ||
|
|
f450f61d1f | ||
|
|
a288523cd3 | ||
|
|
480dc05d99 | ||
|
|
430209c157 | ||
|
|
aa7a04d098 | ||
|
|
5688993b0b | ||
|
|
09cac4f075 | ||
|
|
de1c60c962 | ||
|
|
8a75836a7b | ||
|
|
350c7d842e | ||
|
|
5e0e3f04ed | ||
|
|
3a2177fb24 | ||
|
|
c8bf0d48f3 | ||
|
|
afd1b1e606 | ||
|
|
d006dab2aa | ||
|
|
ab866227a4 | ||
|
|
1f64747141 | ||
|
|
1944ff724c | ||
|
|
addf80ebf4 | ||
|
|
d14dafd250 |
+815
-11
@@ -2,6 +2,816 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### The PyTorch restore after a nodepack installs the builds that were installed before
|
||||
|
||||
When a nodepack changed torch or torchvision and the torch from before had
|
||||
no local label, Manager installed the newest releases, and through uv
|
||||
nothing. For a torch with a label it installed the versions of a table that
|
||||
ends at 2.7.0, or the newest nightly build. A nodepack that removed torch,
|
||||
or removed torchvision and left torch as it was, ended the restore with
|
||||
`Failed to restore PyTorch`.
|
||||
|
||||
Now Manager installs each of torch, torchvision and torchaudio that is not
|
||||
the build it was before as that build, such as `torch===2.14.0+cu130` from
|
||||
`https://download.pytorch.org/whl/cu130`. A torchvision or torchaudio whose
|
||||
build cannot be had is replaced by one that fits that torch. A package that
|
||||
this torch requires is installed again with it when another package wrote
|
||||
over one of its files, as a torch of another CUDA version does with the
|
||||
CUDA libraries. A last command resolves torch with torchvision and
|
||||
torchaudio: what fits that torch stays, what does not is replaced, and a
|
||||
dependency that the nodepack removed comes back.
|
||||
|
||||
Then Manager checks in a separate process that torch, torchvision and
|
||||
torchaudio work. For a torch that does not, the packages it requires that
|
||||
lack a file are installed again. A torchvision or torchaudio that does not
|
||||
is installed again from torch's index. What still does not work is named in
|
||||
an ERROR line. When the torch from before cannot be had, Manager restores
|
||||
by its version table as before; the table now goes up to 2.15.0. With uv,
|
||||
the command that installs torch, or a changed torchvision or torchaudio, at
|
||||
its build is sent only in a form that a dry run resolved, and once more
|
||||
when it fails while it installs. For safety the restore does not start when
|
||||
the disk has less free space than it can take: twice the size of what it
|
||||
installs again with pip, one and a half times with uv. pip runs without its
|
||||
cache during the restore, so that it holds each wheel once.
|
||||
|
||||
### cm-cli reinstall keeps the version that is installed
|
||||
|
||||
`cm-cli reinstall <nodepack>` without a version removed the nodepack and
|
||||
installed the latest version of the registry, whatever was installed: 1.0.1
|
||||
became 1.0.2, and a nightly clone became a registry version. It now installs
|
||||
the version that is installed, enabled or disabled, and a nightly clone is
|
||||
cloned again. A registry nodepack named by its URL is reinstalled as one named
|
||||
by its id, also with `@<version>` or `@nightly`; the version that a URL named
|
||||
was dropped before, and the latest one installed. A nodepack that is not
|
||||
installed gets the latest version, and `<nodepack>@latest` or
|
||||
`<nodepack>@<version>` installs what it names, as before. When the registry no
|
||||
longer has the version that is installed, the reinstall fails with `not
|
||||
available node: <nodepack>@<version>` and the nodepack stays as it is;
|
||||
`<nodepack>@latest` installs the latest one. A nightly clone of a nodepack that
|
||||
the node list of the channel lacks is not cloned again: the reinstall says
|
||||
`Node '<nodepack>@nightly' not found` and leaves the clone as it is.
|
||||
|
||||
### cm-cli prints a value in square brackets, and a line for each nodepack it counts
|
||||
|
||||
cm-cli printed every line through rich, which reads a lowercase word in square
|
||||
brackets as markup and drops it, and typer shows a help text the same way.
|
||||
`cm-cli fix` named no version for a git nodepack (`[unknown]`, `[nightly]`),
|
||||
and an install of an id that no list has ended with `not found in` and nothing
|
||||
after it. The name of a nodepack, a reason, a title or an author of the node
|
||||
list, a changelog line, a path or the name of a snapshot lost a part in square
|
||||
brackets that starts with a lowercase letter, and a path lost a backslash
|
||||
before a bracket. cm-cli now writes every line as it is, as the Manager writes
|
||||
its own, a coloured line in its colour. A line longer than the console is wide
|
||||
is no longer broken in two, which was at 80 columns where no terminal is
|
||||
attached, as in a script, and a code such as `:bug:` in a value is no longer
|
||||
turned into an emoji. `--help` showed no text for `--mode` and for the argument
|
||||
of `show`, `simple-show`, `update`, `enable`, `disable`, `fix` and
|
||||
`cli-only-mode`. These texts are now written without their brackets, as
|
||||
`remote|local|cache`, and read the same with and without rich. `cm-cli
|
||||
simple-show` refused a word that is no list with the tags of a colour around
|
||||
the line: `[bold red]Invalid command: ...[/bold red]`. The reason of a failed
|
||||
`cm-cli fix` had an `f` before it. `cm-cli disable all` printed no line for the
|
||||
Manager and `cm-cli fix all` none for a disabled nodepack, so each skipped a
|
||||
number; both print a line now, as `update all` does. `cm-cli
|
||||
restore-dependencies` counted `__pycache__` as a nodepack. `cm-cli install`
|
||||
printed a line of its own before each nodepack: `install_node exit on
|
||||
fail:False...`.
|
||||
|
||||
### A git nodepack that a snapshot lists as disabled is restored as disabled
|
||||
|
||||
A snapshot lists each git nodepack with whether it was disabled when the
|
||||
snapshot was saved, and a restore did not read that, with `cm-cli
|
||||
restore-snapshot` and from the Snapshot Manager alike. A nodepack saved as
|
||||
disabled was enabled when it was disabled, left enabled when it was enabled,
|
||||
and cloned when it was not installed. It is now left disabled, disabled, and
|
||||
not cloned. A nodepack saved at a version of the registry keeps its git clone
|
||||
disabled: that clone is restored when the version could not be, as before,
|
||||
where the node list of the machine that restores knows the URL of the clone.
|
||||
Where a URL has an enabled and a disabled clone installed, a snapshot lists it
|
||||
as enabled, with the commit of the enabled clone; it listed the clone it read
|
||||
last.
|
||||
|
||||
### A disable or an enable does not move a nodepack into a folder that exists
|
||||
|
||||
Disabling a nodepack moves its folder into `custom_nodes/.disabled`, and
|
||||
enabling moves it back. Where the folder it moves to was already there, as with
|
||||
an enabled nodepack and a disabled copy of it, the nodepack was moved inside
|
||||
that folder (`.disabled/<name>/<name>`) and reported as disabled. `cm-cli
|
||||
disable`, the Disable button, a restore that disables a nodepack, and an enable
|
||||
or an install that first disables the enabled version all did so. The disable or
|
||||
enable now fails with `Destination already exists: <folder>` and the nodepack
|
||||
stays in its folder. An enable or an install that first disables the enabled
|
||||
version now looks at its own folder before it does so, and stops when that
|
||||
version cannot be disabled, so one that is refused changes nothing. The Disable
|
||||
and Enable buttons reported success for a disable or an enable that the Manager
|
||||
refused; they now report the failure, and the terminal says why. The Custom
|
||||
Nodes Manager shows the reason of a refused enable as well. `cm-cli install`
|
||||
printed its `ENABLED` line for an enable that failed; it now prints the error.
|
||||
An install that first enables a disabled version stops when that enable fails;
|
||||
it went on to switch the version of whatever was in the folder.
|
||||
|
||||
### Both URLs of the default channel are the default channel
|
||||
|
||||
The default channel is served at
|
||||
`https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main` and at
|
||||
`https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main`, and
|
||||
Manager took only the first as the default channel. Manager 4 writes the
|
||||
second into the same `config.ini` and `channels.list`. With the second as
|
||||
`channel_url` of `config.ini`, or as the `default` line of `channels.list`,
|
||||
the start stopped with `An invalid channel was used`, the list of the Custom
|
||||
Nodes Manager failed to load, and the channel menu showed no channel. Both
|
||||
URLs now mean the default channel: the lists are read from one set of cache
|
||||
files, the registry nodepacks are listed, and `default` is selected.
|
||||
`config.ini` and `channels.list` are left as they are.
|
||||
|
||||
### Every place reads a line of requirements.txt the same way
|
||||
|
||||
Each place that installs the `requirements.txt` of a nodepack line by line
|
||||
read a line its own way. A URL was cut at its `#`, so
|
||||
`git+https://host/repo#subdirectory=sub` installed the root of the
|
||||
repository, which pip and uv refuse as no Python project. A requirement
|
||||
followed by `--index-url URL` went to the installer as one argument, which it
|
||||
refuses, in an install from the registry, an update and a fix of a nodepack,
|
||||
and in `cm-cli install`, `fix` and `restore-dependencies`. An entry of
|
||||
`pip_overrides.json` did not apply to a line with a comment there either, nor
|
||||
in a reserved install that runs at the next start. Now a comment starts at a
|
||||
`#` at the start of the line or after whitespace, as pip reads it, and a
|
||||
requirement followed by `--index-url URL` is installed from that index in
|
||||
every place. A requirement followed by another option, such as
|
||||
`flash-attn --no-build-isolation`, still goes to the installer as one
|
||||
argument and fails as before.
|
||||
|
||||
### An option in requirements.txt applies to its own row only
|
||||
|
||||
A row of the `requirements.txt` of a nodepack that has only an option, such as
|
||||
`--extra-index-url URL`, `--trusted-host host` or `-r other.txt`, went to pip
|
||||
or uv as one argument, which both refuse. In an install from the registry, an
|
||||
update and a fix of a nodepack, and in `cm-cli install`, `fix` and
|
||||
`restore-dependencies`, that failure stopped every row after it: none of them
|
||||
was installed, and the nodepack was reported as failed. The Manager installs
|
||||
requirements one row at a time, and an option applies to the row it is
|
||||
written on only. A row with only an option has nothing to install: it is now
|
||||
left out with the line `skip '<row>': the Manager installs requirements one
|
||||
row at a time and does not apply this row`, and the rows after it are
|
||||
installed. `-r` and `-c` install nothing. A row `-e path` or
|
||||
`--editable path` is an editable requirement and goes to the installer as
|
||||
`-e` and its target, which pip and uv install as editable; before, uv
|
||||
installed `-e path` and pip refused it. With a git URL, pip installs `-e` as
|
||||
it is written. uv installs an editable from a local folder only, so with uv
|
||||
a row `-e git+URL`, with or without index options after it, is installed
|
||||
without `-e`, and a line says so; before, uv refused the row.
|
||||
`--extra-index-url URL` after a requirement now goes to the installer with
|
||||
that requirement, as `--index-url URL` does.
|
||||
|
||||
### A row that names a path is installed for each nodepack
|
||||
|
||||
In one session the Manager installs a row of `requirements.txt` once: a row
|
||||
that an earlier nodepack has installed is not installed again. A row that
|
||||
names a path, such as `-e .`, `-e ./local` or
|
||||
`./wheels/demo-1.0-py3-none-any.whl`, counted as the same row in every
|
||||
nodepack, although the installer reads the path from the folder of each
|
||||
nodepack. In an install, an update and a fix, the second nodepack with such a
|
||||
row was reported as done without its row being installed. Such a row is now
|
||||
installed for each nodepack: a row counts as one when an argument of it,
|
||||
without extras and marker, exists as a path seen from that folder. Any other
|
||||
row is installed once in a session, as before.
|
||||
|
||||
### cm-cli show snapshot prints the snapshot
|
||||
|
||||
`cm-cli show snapshot` and `cm-cli simple-show snapshot` printed only a
|
||||
`RuntimeWarning` that a coroutine was never awaited, and ended with exit code
|
||||
0. They now print the snapshot of the current state: as JSON with `show`, and
|
||||
with `simple-show` a line with the commit hash of ComfyUI and of each git
|
||||
nodepack. The hashes, the URLs and the JSON are written as they are, so a hash
|
||||
that starts with a letter is no longer left out and a long line is not broken.
|
||||
|
||||
### cm-cli enable all enables the disabled nodepacks
|
||||
|
||||
`cm-cli enable all` enabled nothing and said `Already enabled` for every
|
||||
nodepack, the disabled ones too. `all` names each nodepack with its version,
|
||||
and a nodepack named with a version counted as enabled and as disabled at
|
||||
once. `enable`, `disable`, `update` and `fix` now look at the state of the
|
||||
version that is named, also in `<id>@<version>` on the command line. `enable
|
||||
all` enables the disabled nodepacks, `disable all` says `Already disabled` for
|
||||
a disabled registry nodepack instead of `Not installed`, and `fix all` leaves
|
||||
the disabled nodepacks out instead of printing an error for each.
|
||||
`<id>@latest` names no installed version, so with it these four commands act
|
||||
on the installed nodepack, as with the id alone. A disabled version with a
|
||||
pre-release part, such as `1.0.0-rc1`, is enabled as well: it was named
|
||||
`1.0.0rc1`, which no installed version is called, so `cm-cli enable` did not
|
||||
find it. The Custom Nodes Manager shows the version of a disabled nodepack
|
||||
under that name too. For a registry nodepack that is not installed, `update`
|
||||
and `fix` say `Not installed` and `enable` and `disable` say `Not found`,
|
||||
instead of `Disabled` and `Already disabled`.
|
||||
|
||||
### cm-cli show installed lists a git nodepack that the lists do not know
|
||||
|
||||
`cm-cli show installed`, `show enabled` and `show disabled`, and the same lists
|
||||
of `simple-show`, left out a git nodepack that neither the node list of the
|
||||
channel nor the registry knows, enabled or disabled. The documentation says
|
||||
that `installed` shows all nodes that have been installed. They now list such
|
||||
a nodepack with its id and `author: N/A`, as cm-cli did before it supported
|
||||
the registry.
|
||||
|
||||
### cm-cli deps-in-workflow tells whether a registry nodepack is installed
|
||||
|
||||
`cm-cli deps-in-workflow` wrote `"state": "not-installed"` for a nodepack
|
||||
installed from the registry, enabled or disabled, and for a git nodepack
|
||||
disabled into `custom_nodes/.disabled`. It looked for a folder named after
|
||||
the repository, but a registry install has a folder named by its id, and a
|
||||
disable moves the folder into `.disabled`. The state now comes from the
|
||||
nodepacks the Manager knows to be installed, as in the Custom Nodes Manager.
|
||||
`cm-cli install-deps`, which reads the same state, enables a disabled
|
||||
nodepack as `cm-cli enable` does; a git nodepack in `.disabled` stayed
|
||||
disabled. It no longer runs an `enable.py` of the nodepack, which `cm-cli
|
||||
enable` and the Custom Nodes Manager do not run either.
|
||||
|
||||
### cm-cli restore-snapshot restores an editable install
|
||||
|
||||
`cm-cli restore-snapshot` with `--pip-non-url`, `--pip-non-local-url` or
|
||||
`--pip-local-url` ended with exit code 1 when the snapshot had a package
|
||||
installed in editable mode, as `pip install -e` makes it. `pip freeze` lists
|
||||
it as `-e <path>` after a comment line, and the restore gave both lines to
|
||||
pip as packages of PyPI, which pip refused; every package was then installed
|
||||
again one at a time. An editable install is now restored as editable with
|
||||
the option of where it is: `--pip-local-url` for a path,
|
||||
`--pip-non-local-url` for a repository URL. With uv, a git URL is
|
||||
installed without `-e`, as such a row of `requirements.txt` is, and a line
|
||||
says so. A path that the machine does not have is listed under
|
||||
`Installation failed for pip packages`, as a `file:` URL is. The comment
|
||||
line is skipped.
|
||||
|
||||
### In Workflow of the Model Manager lists only the models of the workflow
|
||||
|
||||
The Filter "In Workflow" of the Model Manager took the name of each model file
|
||||
of the workflow without its extension, and showed every row that had that text
|
||||
anywhere in its name, type, base, description, file name or save path. The
|
||||
default workflow loads `ae.safetensors`, and the filter showed 29 rows, every
|
||||
TAESD model among them, where only FLUX.1 VAE model is that file. It also
|
||||
cleared the marks of a search, and did not list a model whose file has none of
|
||||
eight extensions, such as a `.gguf` file. A row is now listed when a widget of
|
||||
the workflow names its file, also in a subfolder.
|
||||
|
||||
### The Filter of the Model Manager works together with Type and Base
|
||||
|
||||
With a Filter choice other than All, the Model Manager ignored Type and Base.
|
||||
Type TAESD with the Filter at Not Installed showed all 569 models that are not
|
||||
installed, instead of the 8 TAESD models. The list now shows the rows that
|
||||
match the Filter, Type, Base and the search together.
|
||||
|
||||
### Share = None hides the Share button of the top bar
|
||||
|
||||
The Share setting of the Manager menu says it hides the share button of the
|
||||
main menu, but it hid only the Share button of the old menu, which the
|
||||
frontend shows only when "Use new menu" is Disabled. The Share button that
|
||||
Manager puts in the top bar, beside its Manager button, stayed when Share was
|
||||
None, both right after the choice and after a reload. Share = None now hides
|
||||
the Share button in either menu, and another choice shows it again.
|
||||
|
||||
### An install without torchaudio gets the PyTorch restore, and the restore does not add torchaudio
|
||||
|
||||
ComfyUI no longer needs torchaudio (Comfy-Org/ComfyUI#16457). On an install
|
||||
without it, Manager logged `[ComfyUI-Manager] PyTorch is not installed` at
|
||||
every start and after an install, an update or a fix of a nodepack that has
|
||||
requirements, and did not restore PyTorch when a nodepack changed torch or
|
||||
torchvision. That line is no longer logged, and after such a nodepack Manager
|
||||
runs the PyTorch restore that an install with torchaudio gets. The restore
|
||||
installs torchaudio only when the install had it or the nodepack added it. A
|
||||
nodepack that changes only torchaudio no longer starts that restore. The Linux
|
||||
and Windows venv install scripts and the Colab notebook no longer install
|
||||
torchaudio.
|
||||
|
||||
### An installed registry nodepack is listed with the registry's id
|
||||
|
||||
`GET /customnode/installed` gave the id of a nodepack installed from the
|
||||
registry in lowercase, as `comfyui_sigmoidoffsetscheduler`, and a node added
|
||||
to a workflow took that id. The Custom Nodes Manager names the nodepack as
|
||||
the registry writes it, `ComfyUI_SigmoidOffsetScheduler`, and Check Missing
|
||||
and Install Missing Custom Nodes said `Failed to find the following
|
||||
ComfyRegistry list` for the id of such a workflow when the nodepack was not
|
||||
installed, and then listed the same nodepack. The id is now given as the
|
||||
`pyproject.toml` of the nodepack writes it.
|
||||
|
||||
### Check Missing finds the nodepack of a node whose id differs in case
|
||||
|
||||
A workflow saved with an earlier install keeps the lowercased id. When that
|
||||
nodepack was not installed, Check Missing and Install Missing Custom Nodes
|
||||
said `Failed to find the following ComfyRegistry list` for the id, and did
|
||||
not list the nodepack at all when the node map did not know the node. The id
|
||||
of a missing node is now matched without regard to case when the list has no
|
||||
exact match, as Custom Nodes In Workflow already did.
|
||||
|
||||
### The Custom Nodes Manager no longer offers the "Alternatives of A1111" filter
|
||||
|
||||
The Filter of the Custom Nodes Manager no longer offers "Alternatives of
|
||||
A1111", which showed the entries of `alter-list.json` in an extra Alternatives
|
||||
column. The choice and its route `GET /customnode/alternatives` are removed,
|
||||
and Manager no longer fetches `alter-list.json` at start. The file stays in the
|
||||
channels, where older versions of Manager still fetch it.
|
||||
|
||||
### Update All Custom Nodes in the desktop app shows its result
|
||||
|
||||
In the desktop app the Manager menu has Update All Custom Nodes, which does
|
||||
not update ComfyUI. When its updates were done the menu showed nothing. The
|
||||
result had no entry for ComfyUI, and the menu stopped with an error on the
|
||||
missing entry. The box now lists the nodepacks that were updated, with a
|
||||
RESTART button, and those whose update failed. When nothing was updated and
|
||||
nothing failed, it says `You are already up to date.`
|
||||
|
||||
### Check Update no longer stops the server, and shows how far it is
|
||||
|
||||
Check Update in the Custom Nodes Manager fetched every git nodepack inside the
|
||||
request for the node list. Until the last fetch had ended the server answered
|
||||
nothing else, and with many git nodepacks the page gave up after a minute with
|
||||
`Failed to get custom node list.` (#3574). The check now runs in the
|
||||
background. The page shows `Checking updates (n/total) ...` while the
|
||||
repositories are fetched, the server goes on answering, and the nodepacks that
|
||||
have an update are listed when the check has ended. A task on nodepacks that
|
||||
is started during a check, such as Update All, runs when the check has ended,
|
||||
as before. A model download and an update of ComfyUI do not wait for it. When
|
||||
the connection to the server is lost and comes back during a check, as when
|
||||
the server restarts, the page asks for the check again.
|
||||
|
||||
A git nodepack that the registry does not know was left out of the check,
|
||||
unless the node list gave it an `id` that is its repository name. Every enabled
|
||||
git nodepack of the list is fetched now, so a check can take longer than
|
||||
before.
|
||||
|
||||
On Windows, a check that found an update for a git nodepack put the install
|
||||
script of that nodepack down to run at the next start, though nothing had been
|
||||
updated. A check no longer does that.
|
||||
|
||||
`GET /customnode/getlist` no longer fetches, with or without `skip_update`,
|
||||
and `POST /customnode/fetch_updates` answers 410. A check is asked for with
|
||||
`POST /customnode/check_update` and reports by the `cm-check-update` event.
|
||||
|
||||
### A search in the Custom Nodes Manager lists the best matches first
|
||||
|
||||
A search in the Custom Nodes Manager only filtered the list. The rows stayed in
|
||||
the listed order, so for `face` a nodepack with `Interface` in its title could
|
||||
stand above one with the word `Face` (#1191). The rows of a search are now
|
||||
ordered by a score. A whole word counts more than a part of a word, in
|
||||
whichever searched column matches best, and a match in more columns and more
|
||||
stars raise the score. Rows with the same score stay in the listed order.
|
||||
|
||||
A search replaces a column sort that was made before it. Clicking a column
|
||||
header during a search sorts by that column, and typing in the search box
|
||||
again goes back to the best matches. Clearing the search box brings back the
|
||||
listed order, or keeps the column sort that was made during the search. The
|
||||
list is filtered 300 ms after the last key.
|
||||
|
||||
The first click on the Nodes, ★ and Last Update headers now sorts from the
|
||||
highest value down.
|
||||
|
||||
### A nodepack folder with neither `.git` nor `.tracking` is an invalid installation, fixed by reinstalling
|
||||
|
||||
A folder in `custom_nodes` with neither `.git` nor `.tracking`, left by an
|
||||
install that broke midway or by a download unpacked by hand, was taken for a
|
||||
git nodepack: Update All logged `ERROR: An error occurred while updating ...`
|
||||
for it, and its nodepack showed as not installed (#3330). It is now an invalid
|
||||
installation. Update All and `cm-cli update all` leave it alone, the Custom
|
||||
Nodes Manager marks its row `INVALID INSTALLATION ↗` and offers Reinstall,
|
||||
`/customnode/installed` lists it with `invalid_installation: true`, and the
|
||||
startup notice names it.
|
||||
By its folder name it is enabled, disabled and uninstalled as before.
|
||||
|
||||
A reinstall, of any nodepack, keeps the folders it replaces until the new
|
||||
installation is in place, and puts them back when the install fails. It
|
||||
deleted them first, so a failed download lost the nodepack. `cm-cli reinstall`
|
||||
makes the same reinstall and prints `[REINSTALLED]`.
|
||||
|
||||
What is in the way of a reinstall, such as a clone of a fork at the install
|
||||
path or under the name of the nodepack, is moved to
|
||||
`custom_nodes/.disabled/.archived/` and the log says where it is. It is not
|
||||
deleted and no longer loaded, and it goes back when the install fails. The
|
||||
reinstall failed there with `Install path already exists`.
|
||||
|
||||
The console line of a failed update says why the update failed.
|
||||
|
||||
### A reserved install does not install a URL requirement again
|
||||
|
||||
A requirement that is a URL, as `git+https://github.com/owner/repo` or the URL
|
||||
of a wheel, was installed again by every reserved install of its nodepack, and
|
||||
for a repository that is a clone and a build at the start of the server
|
||||
(#3575). On Windows, or with `always_lazy_install`, every install, update and
|
||||
fix that the server is asked for is reserved. The requirement is now skipped
|
||||
when a package installed from that URL is there. It is then left as it is, as a
|
||||
name without a version is: new commits of the repository are not followed.
|
||||
|
||||
### A fix installs a URL requirement again by force
|
||||
|
||||
A fix of a nodepack (**Try fix**, `cm-cli fix`) is the way to have a package
|
||||
from a URL installed again. It installs what the package needs now, and then
|
||||
the package itself from its URL, by force and without the cache of pip or uv.
|
||||
When the repository cannot be reached, what is installed is kept, and uv
|
||||
installs the installed commit once more from its cache when it has it. A fix
|
||||
also installs the requirements that an install, an update or an earlier fix of
|
||||
the same session has installed.
|
||||
|
||||
### A fix that failed is reported as failed
|
||||
|
||||
A fix of a nodepack from the page (**Try fix**) was reported as a success also
|
||||
when a requirement could not be installed or `install.py` failed: only the log
|
||||
said `install script failed`. Such a fix is now reported as failed, and the
|
||||
page shows `An error occurred while fixing '<nodepack>@<version>'.` A fix that
|
||||
is reserved for the next start, as on Windows or with `always_lazy_install`,
|
||||
is reported as soon as it is reserved, as before.
|
||||
|
||||
### No deprecation warning of aiohttp with `bypass_ssl`
|
||||
|
||||
With `bypass_ssl = true`, the fetch of the notice and the fetch of a list
|
||||
passed `verify_ssl=False` to aiohttp, which warns that the argument is
|
||||
deprecated: `DeprecationWarning: verify_ssl is deprecated, use ssl=False
|
||||
instead` (#2281). They now pass `ssl=False`. Without `bypass_ssl` nothing
|
||||
changes: the certificate is checked as before.
|
||||
|
||||
### A console that is gone does not fail a prompt
|
||||
|
||||
A server that was started with pipes for its console goes on running when the
|
||||
process that read them exits, and a write to such a pipe fails. The log hook
|
||||
of the Manager passed that failure on to whatever had printed: the prompt of a
|
||||
node that prints, or of a sampler at its progress bar, ended with
|
||||
`BrokenPipeError: [Errno 32] Broken pipe`, on Windows with
|
||||
`OSError: [Errno 22] Invalid argument` (#3223). The hook now drops what the
|
||||
console does not take and does not write to that console again, and what is
|
||||
written still goes to the log file. While stderr is gone, ComfyUI's own log
|
||||
handler fails on each record, and Python's report of that failure is now in
|
||||
the log file in full, where it broke off after its first line. This is the
|
||||
hook of the log file (`file_logging`, on by default): with it off, the streams
|
||||
are those of ComfyUI, and the progress bar still fails there.
|
||||
|
||||
### A log call that cannot be formatted does not fail its node
|
||||
|
||||
A log call that cannot be formatted failed its node in the log handler of the
|
||||
Manager, with the exception of the format: `logging.info("value %d", "text")`
|
||||
ended the node with `TypeError`. Python's logging only reports such a call
|
||||
and goes on. The handler now puts a `<<logging error>>` line with the file
|
||||
and the line of the call into the log file, and the node goes on.
|
||||
|
||||
### A snapshot restore installs a git node pack as the snapshot names it
|
||||
|
||||
A snapshot names a git node pack by its url. For a url that the registry
|
||||
knows, the restore asked for a nightly install by the id of the registry, and
|
||||
that install takes its url from the node list. When the node list had no entry
|
||||
for the node pack, as after the list went over to a fork of it, nothing was
|
||||
cloned and the summary said `[ FAILED ]` with no word of why. When the node
|
||||
list had another repository under the same name, that one was cloned. The
|
||||
restore clones the url of the snapshot, as a nightly install of that node
|
||||
pack: a version of the registry that is enabled is disabled first, and the
|
||||
node pack is checked out at the commit of the snapshot. The restore no longer
|
||||
reads the node list.
|
||||
|
||||
A node pack that was switched from its clone to a version of the registry
|
||||
keeps the clone, disabled, and a snapshot saves both. The restore enabled or
|
||||
cloned the clone and disabled the version that the snapshot names. Such a node
|
||||
pack is restored at that version, and its git entry is left alone. When that
|
||||
version cannot be installed, the clone is restored as before.
|
||||
|
||||
A clone of the restore that is refused says why in the log, as
|
||||
`Invalid git url: ...`.
|
||||
|
||||
### A failed legacy backup is reported without the text of the error, and leaves no part of a backup
|
||||
|
||||
When the legacy directory could not be moved to its backup, the startup notice
|
||||
carried the text of the error, which has paths of that directory in it. The
|
||||
notice now says only that the backup failed, and the error is in the terminal.
|
||||
When the move fails while it copies, the legacy directory is as it was and the
|
||||
next start tries again; what was copied is removed, so that the starts do not
|
||||
each leave another part of a backup.
|
||||
|
||||
### On an old ComfyUI, Manager only updates ComfyUI
|
||||
|
||||
On a ComfyUI without the System User API (before 0.3.76), Manager's data
|
||||
directory is not protected, so installs are refused there and startup scripts
|
||||
are not run. Other requests were still served, and other files of that
|
||||
directory were still acted on. Now only the update of ComfyUI is served there:
|
||||
every other request to Manager is answered with `comfyui_outdated`. A snapshot
|
||||
restore scheduled in that directory is left alone at the start, and the start
|
||||
says so; its `pip_auto_fix.list` and `pip_overrides.json` are not applied by
|
||||
the start or by the update. Update ComfyUI to use Manager again.
|
||||
|
||||
After that update, the first start moves `config.ini` to the protected
|
||||
directory. It moved every setting and raised only a security level below
|
||||
`normal`. Now it moves the settings that are preferences and leaves behind
|
||||
those that permit an install (`allow_git_url_install`, `allow_pip_install`,
|
||||
`allow_flagged_nodepack_install`) or change where Manager fetches from
|
||||
(`channel_url`, `http_channel_enabled`, `bypass_ssl`, `git_exe`), and any it
|
||||
does not know. Those are back at their defaults, and the terminal lists the
|
||||
ones that had another value; set them again if you need them. A security level
|
||||
that is not a security level is set to `normal` like one below it.
|
||||
### Every POST that changes something is taken only as `application/json`, and the share option is saved by POST
|
||||
|
||||
A page of another site can make the browser send a GET, and a POST without a
|
||||
body and without a Content-Type, for which no preflight is made. The Manager
|
||||
routes that take no body (`queue/start`, `queue/reset`, `queue/update_comfyui`,
|
||||
`snapshot/save`, `reboot`) now answer 400 unless the request has
|
||||
`Content-Type: application/json`, as the routes that read a JSON body do: a
|
||||
browser does not send that header to another site without a preflight. The
|
||||
share option is saved with `POST /manager/share_option` and a JSON body
|
||||
`{"value": ...}`; `GET /manager/share_option` only answers with the saved
|
||||
option, and a `value` given to it is ignored. The Manager's own pages send the
|
||||
header. A script that calls one of these routes has to send it too, and one
|
||||
that saved the share option with `?value=` has to POST.
|
||||
|
||||
### The file of the saved Matrix account is readable by its user only
|
||||
|
||||
The share dialog saves the Matrix account, with its password, in `matrix_auth`
|
||||
in Manager's data directory. The file was written with the default mode of
|
||||
new files, which other users of the machine can usually read. It is now written
|
||||
with mode `0600`, and a file that is already there gets that mode the next
|
||||
time an account is saved.
|
||||
|
||||
### The share option that is saved is one of the choices of the share menu
|
||||
|
||||
`/manager/share_option` saved any text as the share option. It now saves
|
||||
`all`, `none`, `youml` or `matrix`, the choices of the menu, and answers 400
|
||||
for another value.
|
||||
|
||||
### Restoring a snapshot needs the security level of a switch to an older version
|
||||
|
||||
A snapshot restore takes the node packs back to the versions that the
|
||||
snapshot recorded, older ones too. `POST /snapshot/restore` needed `middle`, which the
|
||||
default `security_level = normal` gives on any listener; a switch of ComfyUI to
|
||||
an older version needs `high`. A restore now needs `high` as well: `normal-` or
|
||||
lower on a loopback listener, `weak` otherwise. At `normal`, `Restore` in the
|
||||
Snapshot Manager is refused; `cm-cli restore-snapshot` is not changed.
|
||||
|
||||
### Routes that read a JSON body take it only as `application/json`
|
||||
|
||||
A POST route that reads a JSON body parsed it whatever the Content-Type of the
|
||||
request. These routes now answer 400 unless the Content-Type is
|
||||
`application/json`. The Manager's own scripts send it; a script or tool that
|
||||
posts JSON to the Manager without that header has to add it.
|
||||
|
||||
### Switching ComfyUI to an older version is held to the security level
|
||||
|
||||
Switching the ComfyUI version was not checked against `security_level`. A
|
||||
switch to an older release, or to anything that is not a release tag, now needs
|
||||
`normal-` or lower when ComfyUI listens on a loopback address, and `weak`
|
||||
otherwise; at the default `normal`, `Switch ComfyUI` in the Manager menu
|
||||
answers that the security level does not allow it. A switch to `nightly` or to
|
||||
a newer release is an update and works at every level, as before. A ComfyUI
|
||||
with commits after its release, as on `nightly`, would go back by a switch to
|
||||
that release, so that counts as older; in a repository without release tags,
|
||||
such as a clone without tags, every version but `nightly` does. The menu
|
||||
changes the update policy to that of the chosen version only after the switch
|
||||
has happened; it did so before asking for the switch.
|
||||
|
||||
### The server no longer returns saved sharing credentials
|
||||
|
||||
`GET /manager/get_matrix_auth` answered with the saved Matrix homeserver,
|
||||
username and password, to any client that could reach the server. It now answers
|
||||
without the password. The share dialog leaves the password field empty for the
|
||||
saved account, and the server uses the saved password for the username it was
|
||||
saved with; for another account a password has to be typed. An account is saved
|
||||
once it has logged in; a share request no longer replaces the saved account
|
||||
before that. If others could reach the server while a Matrix password was saved,
|
||||
change that password.
|
||||
|
||||
Sharing to Matrix logs in to matrix.org, where the share room is, and to no
|
||||
other homeserver. The homeserver of the share dialog can no longer be changed, a
|
||||
share request that names another homeserver is refused, and an account that was
|
||||
saved for another homeserver is not used: an account of matrix.org has to be
|
||||
entered. Before, the server logged in to any homeserver that a request named,
|
||||
with the password of the request.
|
||||
|
||||
The YouML API token is kept in the browser that shares, which is what sends it
|
||||
to YouML; the server stored it, and `GET /manager/youml/settings` answered with
|
||||
it in the same way. Both `/manager/youml/settings` routes are removed. The token
|
||||
has to be entered once more in the YouML share dialog. Delete `.youml` in
|
||||
Manager's data directory (`<USER_DIRECTORY>/__manager/`, or
|
||||
`<USER_DIRECTORY>/default/ComfyUI-Manager/` on older ComfyUI), and if others
|
||||
could reach the server while a token was saved, issue a new token.
|
||||
|
||||
### A setting chosen while the Manager menu is loading it is kept
|
||||
|
||||
The Manager menu asks the server for the database mode, the component policy,
|
||||
the update policy and the share option when it is first opened. A value chosen
|
||||
before the answer arrived was saved, but the menu went back to showing the old
|
||||
one. The menu keeps the chosen value.
|
||||
|
||||
### Setting requests with an unknown value are refused
|
||||
|
||||
The routes that set `db_mode`, `update_policy` and `component_policy` stored
|
||||
whatever value a request carried and wrote it to `config.ini`. They answer 400
|
||||
for a value that is not one of those the Manager's menu offers, and for a JSON
|
||||
body without a `value`, which ended with status 500.
|
||||
|
||||
### `git_exe` chooses the git executable
|
||||
|
||||
The path set as `git_exe` in `config.ini` was read but not used: git commands
|
||||
kept running the `git` found on `PATH`. The Manager, cm-cli and the git helper
|
||||
now run the configured executable. For the Manager it no longer has to be on
|
||||
`PATH`: the Manager also starts when the only git is the one named by
|
||||
`git_exe`. cm-cli still needs a git on `PATH` to start.
|
||||
|
||||
A value that is not a working git is reported in the log, and the default git
|
||||
is used. The value is read as it is written: with a `%` in it, as in a path
|
||||
of Windows, the Manager read every setting of `config.ini` as its default.
|
||||
`git_exe` is used only when the configuration file is in a protected
|
||||
directory, that is with a ComfyUI that has the System User API.
|
||||
|
||||
### The commit and the submodules of a git node pack
|
||||
|
||||
A snapshot recorded no commit for a git node pack whose refs were packed, as
|
||||
after `git gc`. The commit is read from `packed-refs` too. A `HEAD` that is
|
||||
not UTF-8, as one that names a branch in another encoding, raised an error
|
||||
where the commit of a node pack is read. It is read as bytes now. On Windows
|
||||
the commit of a branch whose name is not ASCII, as a Korean one, could be
|
||||
unknown as well: the file of the branch is looked for under the name that Git
|
||||
for Windows gives it. The commit is read while the Manager is loading, and an
|
||||
error there kept the Manager from loading: also for a `.git` with a folder
|
||||
where the file of the branch would be, as after
|
||||
`git checkout --orphan feature` beside a branch `feature/x`, or with a file
|
||||
that cannot be read. The commit of such a node pack is unknown now.
|
||||
|
||||
When a snapshot restore checks a git node pack out, its submodules are brought
|
||||
to the commits that the commit names, also when the node pack is at the commit
|
||||
of the snapshot already. A submodule that was never fetched is then fetched
|
||||
too in a node pack that the Manager installed, as the Manager clones a node
|
||||
pack with its submodules; in a node pack cloned without them, it is fetched
|
||||
only when the node pack itself is checked out.
|
||||
|
||||
### A node pack whose `.git/config` cannot be read
|
||||
|
||||
The Manager reads the remote url of every installed node pack from its
|
||||
`.git/config` while it is loading. A url with a `%`, such as one with `%20`,
|
||||
a key without a value, such as `bare` alone, a key on a line that is indented
|
||||
more than the one before it, a byte order mark at the start of the file, or
|
||||
text that the encoding of the system cannot decode, such as the name of a
|
||||
branch in another encoding, raised an error there, and the Manager did not
|
||||
load. These files are read now, and for a file that cannot be read the url of
|
||||
that node pack is unknown and a warning names the file once.
|
||||
|
||||
### An update whose git step fails is a failure, and can be done again
|
||||
|
||||
On Windows the pull of an update runs in a helper process, which ended with 0
|
||||
when the pull failed, and its result was not read: the update went on to the
|
||||
install script and ended as done. The helper ends with 1 now, and the update
|
||||
fails.
|
||||
|
||||
When the update of its submodules failed, a node pack stayed at the new
|
||||
commit: the next update found nothing to do, and the install script of the
|
||||
update never ran. The pull is undone, and the submodules that were updated
|
||||
before the one that failed go back with it. A node pack with a submodule
|
||||
that cannot be fetched at all is not updated until it can.
|
||||
|
||||
### A snapshot restore reports what failed, and restores the pinned commit
|
||||
|
||||
The summary of a restore listed a node pack as `INSTALLED`, `DISABLED` or
|
||||
`ENABLED` without looking at the result of the step: a clone that failed, for
|
||||
example because the directory already existed or the url could not be reached,
|
||||
was `INSTALLED`. A step that fails is now listed as `FAILED`, and the Manager
|
||||
itself is no longer listed as `DISABLED`. A registry that cannot be reached
|
||||
ended the restore at the first node pack to install from it, and so did a
|
||||
node pack whose directory could not be moved to disable or enable it; such a
|
||||
node pack is listed as `FAILED`, and the restore goes on. `cm-cli
|
||||
restore-snapshot` ends with 1 when a step failed or a pip package that a
|
||||
`--pip-*` option selects was not installed, and a scheduled restore then says
|
||||
`Restore snapshot failed.`: it ended with 0. A url of the snapshot that cannot
|
||||
be parsed ended the restore as well; the node pack is listed as `FAILED`.
|
||||
|
||||
A git node pack that the restore had to clone stayed at the newest commit. It
|
||||
is checked out at the commit of the snapshot, and its install script runs after
|
||||
that. When the commit cannot be checked out, the install script still runs, at
|
||||
the commit the clone is at, and the node pack is listed as `FAILED`. An
|
||||
installed git node pack that the registry does not know was checked out only
|
||||
when cm-cli was run from `custom_nodes`, as a scheduled restore does; it is
|
||||
checked out from any directory.
|
||||
|
||||
A git node pack of the registry that was already installed, or that the
|
||||
restore enabled, was listed a second time as `SKIPPED`; it is listed once. An
|
||||
installed one that is checked out is listed by its name, as the others are: it
|
||||
was listed by its path.
|
||||
|
||||
A registry node pack that the restore had to install was unpacked, but its
|
||||
requirements were not installed and its install script did not run. The
|
||||
restore now runs them, and lists the node pack as `FAILED` when they fail.
|
||||
|
||||
A requirement or an install script that failed was taken as done until the
|
||||
next start: the next node pack that names the requirement skipped it, and
|
||||
installing or fixing the node pack again did not run the script. Both are
|
||||
tried again. The install script of a git node pack was skipped in the same way
|
||||
when it was cloned where another version of the node pack had been installed
|
||||
since the start, as a restore does for a snapshot that has both; it runs.
|
||||
|
||||
### Install requests with an unusable body are answered with 400
|
||||
|
||||
`/customnode/install/git_url` and `/customnode/install/pip` answered 500 when
|
||||
the JSON body was not an object, or when `url` or `packages` was not a string.
|
||||
They answer 400, as they do for a missing field.
|
||||
|
||||
### What is reserved for the next start is written as UTF-8
|
||||
|
||||
The install script of an update, the removal of a node pack whose files are in
|
||||
use and a switch of version are reserved in a file that the start-up script
|
||||
reads as UTF-8, and that was written in the encoding of the system. On Windows
|
||||
a path with a character outside ASCII was lost: one that the code page cannot
|
||||
write, such as a Korean folder name with code page 1252, raised an error and
|
||||
nothing was reserved; one that it can write was read back as another path, and
|
||||
what was reserved was not carried out at the next start. The file is written
|
||||
as UTF-8.
|
||||
|
||||
A switch of version that is carried out at the next start looked for the files
|
||||
that the new version no longer has in `custom_nodes` in place of the directory
|
||||
of the node pack: they stayed in the node pack, and a file of the same name in
|
||||
`custom_nodes` was removed. They are removed from the node pack. A switch of
|
||||
version, at the next start or at once, removes the files that the new version
|
||||
no longer has before it extracts the archive of the new version: where two
|
||||
names are one file, as `./a.py` and `a.py`, or names that differ in case alone
|
||||
on Windows, a file of the new version was removed after it was extracted.
|
||||
A name of the old list that leads out of the node pack, with `..` or as an
|
||||
absolute path, removed a file outside it; nothing is removed for such a name.
|
||||
A file that the old version has alone and that cannot be removed, as one that
|
||||
another program has open on Windows, is left with a warning, and the switch
|
||||
goes on with the files of the new version.
|
||||
A folder that the files of the old version left empty, or with nothing but the
|
||||
`__pycache__` of Python, stayed, and a file of the new version could not take
|
||||
its place; such a folder is removed.
|
||||
A node pack whose directory keeps its name is no longer moved onto itself at
|
||||
the next start, which Windows refuses while a file in it is open.
|
||||
When the switch moves the node pack to another directory, the install script
|
||||
of the new version runs there; it was looked for in the directory that the
|
||||
node pack was moved from, and did not run.
|
||||
|
||||
That list is written as UTF-8 and was read in the encoding of the system. On
|
||||
Windows a switch of version of a node pack with a file name that the code page
|
||||
of the system cannot decode ended in the middle: the files of the new version
|
||||
were unpacked, its install script did not run and the files of the old version
|
||||
stayed. The list is read as UTF-8. A name of the list is read as it is written:
|
||||
a space at its start or its end was dropped, and the file of the other name was
|
||||
the one removed.
|
||||
|
||||
### A scheduled snapshot restore works with `--base-directory`
|
||||
|
||||
With `--base-directory`, where `custom_nodes` is not inside the ComfyUI
|
||||
directory, a snapshot restore scheduled for the next start failed with
|
||||
`ModuleNotFoundError: No module named 'utils'`, and the request was dropped.
|
||||
The restore now gets the path of ComfyUI, and the user directory and
|
||||
`custom_nodes` directory the server uses.
|
||||
|
||||
### Console messages show paths, URLs and package names as they are
|
||||
|
||||
Manager printed many of its messages through rich, which reads square
|
||||
brackets as markup. A package name such as `diffusers[torch]` was shown as
|
||||
`diffusers`, a text such as `:100:` as an emoji, and a line longer than the
|
||||
console was broken in the middle of a path or a URL. A text with a closing
|
||||
tag such as `[/b]` raised `MarkupError` instead of being printed, in the
|
||||
middle of the operation that reported it. These messages are now printed as
|
||||
they are; numbers and quoted strings keep their colors.
|
||||
|
||||
### The list of ComfyUI versions answers a failure with 400 again
|
||||
|
||||
When the versions of ComfyUI could not be read, the request for the list ended
|
||||
with status 500 and a `TypeError` in the log: the call that logs the cause was
|
||||
given an argument it does not take. The cause is logged, and the answer is 400.
|
||||
|
||||
### A value of config.ini is plain text, and one that a setting cannot have gives its default
|
||||
|
||||
Manager read `%(name)s` in a value of `config.ini` as a reference to another
|
||||
setting, and a `%` that is not of that form made the whole file unreadable:
|
||||
every setting was then at its default, `security_level` too, and nothing said
|
||||
so. A value is now read as it is written; `%%`, which was read as one `%`, is
|
||||
now two. `security_level`, `network_mode`, `db_mode`, `update_policy` and
|
||||
`component_policy` have their default when `config.ini` gives a value that
|
||||
they cannot have, and Manager logs a warning that names it; the other settings
|
||||
are read as before, and `config.ini` keeps the value. Before, a
|
||||
`security_level` that is not a level refused every action that needs one; now
|
||||
it is `normal`. A `config.ini` that cannot be read at all still gives the
|
||||
default settings, and is still written anew from them when a setting is
|
||||
saved; Manager now logs a warning when it reads one.
|
||||
|
||||
### After an update from an old ComfyUI, the requirements of ComfyUI are installed before the node packs are loaded
|
||||
|
||||
On Windows, or with `always_lazy_install`, the update of ComfyUI reserves the
|
||||
install of its requirements for the next start. On a ComfyUI without the
|
||||
System User API that was reserved in the legacy directory, which the updated
|
||||
ComfyUI does not read. Manager installed them only at a start that found a
|
||||
`config.ini` in both directories, after ComfyUI and the node packs had been
|
||||
loaded. It now installs them at the start that still finds the legacy
|
||||
`config.ini`, before the node packs are loaded. A ComfyUI that cannot start
|
||||
without one of its new requirements does not get as far as Manager, as
|
||||
before: install them with `pip install -r requirements.txt` then. The legacy
|
||||
directory is moved to `.legacy-manager-backup` as before; a backup that is
|
||||
already there is no longer deleted, the new one gets a numbered name, and the
|
||||
start reminds of each of them.
|
||||
|
||||
### An old ComfyUI no longer leaves `security_level = strong` in config.ini
|
||||
|
||||
On a ComfyUI without the System User API, Manager refused installs by changing
|
||||
the security level it had read to `strong`. A `config.ini` that Manager
|
||||
created there was written with that `strong`, and installs stayed refused
|
||||
after ComfyUI was updated. Now Manager does not change the security level:
|
||||
the check of the security level refuses on such a ComfyUI, whatever the level
|
||||
is. A `config.ini` that already has `security_level = strong` is not changed:
|
||||
if you did not choose it, set it to `normal`.
|
||||
|
||||
### Restarting under comfy-cli no longer reports a closed log file
|
||||
|
||||
Restarting ComfyUI from the Manager under comfy-cli printed `ValueError: I/O
|
||||
operation on closed file` on the console. The log file is closed before the
|
||||
process exits, and what was logged after that was still written to it.
|
||||
|
||||
### Libraries are told whether the console is a terminal
|
||||
|
||||
With file logging on, the logger that captures the output answered every
|
||||
@@ -232,18 +1042,12 @@ allow_pip_install = true
|
||||
|
||||
Changes take effect after a **restart** (no hot reload).
|
||||
|
||||
#### Residual-risk note — outdated ComfyUI behavior change
|
||||
#### Outdated ComfyUI
|
||||
|
||||
On outdated ComfyUI versions (no system-user API), the manager previously
|
||||
forced `security_level = strong`, which unconditionally denied the
|
||||
git-URL/pip install surfaces. After this change those surfaces are governed
|
||||
by the new flags instead: an operator who explicitly sets a flag to `true`
|
||||
on a **loopback** listener can now perform installs on outdated ComfyUI
|
||||
where the forced-strong policy previously denied them. This is an accepted,
|
||||
deliberate trade-off: it requires explicit operator opt-in, remains bounded
|
||||
to loopback listeners, and the flag-deny path on outdated ComfyUI still
|
||||
surfaces the `comfyui_outdated` notice. If you operate an outdated ComfyUI
|
||||
deployment, leave both flags at their default `false` and update ComfyUI.
|
||||
On outdated ComfyUI versions (no system-user API) the flags do not apply:
|
||||
git-URL and pip installs are refused there like every other install, whatever
|
||||
the flags and the listener are, and the answer is the `comfyui_outdated`
|
||||
notice. Update ComfyUI to use them.
|
||||
|
||||
### Removed share destinations
|
||||
|
||||
|
||||
@@ -178,7 +178,7 @@ The following settings are applied based on the section marked as `is_default`.
|
||||
* Press the "Restore" button to revert to the installation status of the respective snapshot.
|
||||
* However, for custom nodes not managed by Git, snapshot support is incomplete.
|
||||
* When you press `Restore`, it will take effect on the next ComfyUI startup.
|
||||
* The selected snapshot file is saved in `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
|
||||
* The selected snapshot file is saved in `<USER_DIRECTORY>/__manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
|
||||
|
||||

|
||||
|
||||
@@ -386,6 +386,8 @@ When you run the `scan.sh` script:
|
||||
* `high` level risky features
|
||||
* Downloading models that are not in `.safetensors` format and not
|
||||
registered in the `default channel` model list
|
||||
* Switch ComfyUI to an older version
|
||||
* Restore Snapshot
|
||||
* NOTE: `Install via git url`, `pip install`, and installation of custom nodes
|
||||
not registered in the `default channel` are **no longer governed by
|
||||
`security_level`** — they are governed by the dedicated install flags
|
||||
@@ -395,7 +397,7 @@ When you run the `scan.sh` script:
|
||||
* Uninstall/Update
|
||||
* Installation of custom nodes registered in the `default channel`.
|
||||
* Fix custom nodes
|
||||
* Restore/Remove Snapshot
|
||||
* Remove Snapshot
|
||||
* Restart
|
||||
|
||||
* `low` level risky features
|
||||
|
||||
@@ -8,7 +8,7 @@ import threading
|
||||
from typing import Optional
|
||||
|
||||
import typer
|
||||
from rich import print
|
||||
import rich
|
||||
from typing_extensions import List, Annotated
|
||||
import re
|
||||
import git
|
||||
@@ -29,7 +29,7 @@ if comfy_path is None:
|
||||
import folder_paths
|
||||
comfy_path = os.path.join(os.path.dirname(folder_paths.__file__))
|
||||
except:
|
||||
print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
|
||||
rich.print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
|
||||
comfy_path = os.path.abspath(os.path.join(manager_util.comfyui_manager_path, '..', '..'))
|
||||
|
||||
# This should be placed here
|
||||
@@ -41,6 +41,8 @@ import manager_core as core
|
||||
from manager_core import unified_manager
|
||||
import cnr_utils
|
||||
|
||||
print = core.print
|
||||
|
||||
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
|
||||
@@ -67,7 +69,7 @@ def check_comfyui_hash():
|
||||
core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
|
||||
core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
|
||||
except:
|
||||
print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
|
||||
print('INFO: Frozen ComfyUI mode.', style='bold yellow')
|
||||
core.comfy_ui_revision = 0
|
||||
core.comfy_ui_commit_datetime = 0
|
||||
|
||||
@@ -75,13 +77,12 @@ def check_comfyui_hash():
|
||||
|
||||
|
||||
check_comfyui_hash() # This is a preparation step for manager_core
|
||||
core.check_invalid_nodes()
|
||||
|
||||
|
||||
def read_downgrade_blacklist():
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(core.manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
@@ -136,25 +137,25 @@ class Ctx:
|
||||
self.no_deps = no_deps
|
||||
|
||||
def set_user_directory(self, user_directory):
|
||||
if user_directory is None:
|
||||
return
|
||||
if user_directory is not None:
|
||||
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
|
||||
if os.path.exists(extra_model_paths_yaml):
|
||||
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
|
||||
|
||||
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
|
||||
if os.path.exists(extra_model_paths_yaml):
|
||||
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
|
||||
core.update_user_directory(user_directory)
|
||||
|
||||
core.update_user_directory(user_directory)
|
||||
if os.path.exists(core.manager_pip_overrides_path):
|
||||
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
cm_global.pip_overrides = json.load(json_file)
|
||||
|
||||
if os.path.exists(core.manager_pip_overrides_path):
|
||||
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
cm_global.pip_overrides = json.load(json_file)
|
||||
if os.path.exists(core.manager_pip_blacklist_path):
|
||||
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
|
||||
for x in f.readlines():
|
||||
y = x.strip()
|
||||
if y != '':
|
||||
cm_global.pip_blacklist.add(y)
|
||||
|
||||
if os.path.exists(core.manager_pip_blacklist_path):
|
||||
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
|
||||
for x in f.readlines():
|
||||
y = x.strip()
|
||||
if y != '':
|
||||
cm_global.pip_blacklist.add(y)
|
||||
core.setup_git_executable()
|
||||
|
||||
def update_custom_nodes_dir(self, target_dir):
|
||||
import folder_paths
|
||||
@@ -186,14 +187,13 @@ cmd_ctx = Ctx()
|
||||
|
||||
def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
|
||||
exit_on_fail = kwargs.get('exit_on_fail', False)
|
||||
print(f"install_node exit on fail:{exit_on_fail}...")
|
||||
|
||||
|
||||
if 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))
|
||||
if not res.result:
|
||||
print(res.msg)
|
||||
print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
|
||||
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
|
||||
if exit_on_fail:
|
||||
sys.exit(1)
|
||||
else:
|
||||
@@ -214,7 +214,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
|
||||
|
||||
if res.action == 'skip':
|
||||
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
|
||||
elif res.action == 'enable':
|
||||
elif res.action == 'enable' and res.result:
|
||||
print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
|
||||
elif res.action == 'install-git' and res.target == 'nightly':
|
||||
print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
|
||||
@@ -229,39 +229,62 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
|
||||
show_versions(node_name)
|
||||
print("")
|
||||
else:
|
||||
print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.\n{res.msg}[/bold red]")
|
||||
print(f"ERROR: An error occurred while installing '{node_name}'.\n{res.msg}", style="bold red")
|
||||
if exit_on_fail:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
|
||||
node_spec = unified_manager.resolve_node_spec(node_spec_str)
|
||||
node_name, version_spec, is_specified = unified_manager.resolve_node_spec(node_spec_str)
|
||||
repo_url = None
|
||||
if core.is_valid_url(node_name):
|
||||
url = node_name.rstrip('/')
|
||||
cnr = unified_manager.get_cnr_by_repo(url)
|
||||
if cnr:
|
||||
node_name = cnr['id']
|
||||
if not is_specified:
|
||||
version_spec = unified_manager.resolve_unspecified_version(node_name)
|
||||
else:
|
||||
node_name, version_spec, repo_url = core.unknown_node_id(url), 'unknown', url
|
||||
|
||||
node_name, version_spec, _ = node_spec
|
||||
if not is_specified and repo_url is None:
|
||||
for guess_mode in ('active', 'inactive'):
|
||||
installed = unified_manager.resolve_unspecified_version(node_name, guess_mode=guess_mode)
|
||||
if installed not in (None, 'unknown'):
|
||||
version_spec = installed
|
||||
break
|
||||
|
||||
unified_manager.unified_uninstall(node_name, version_spec == 'unknown')
|
||||
install_node(node_name, is_all=is_all, cnt_msg=cnt_msg)
|
||||
res = asyncio.run(unified_manager.reinstall_by_id(node_name, version_spec, cmd_ctx.channel, cmd_ctx.mode, instant_execution=True,
|
||||
no_deps=cmd_ctx.no_deps, repo_url=repo_url))
|
||||
if res.action == 'skip':
|
||||
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
|
||||
return
|
||||
if not res.result:
|
||||
print(f"ERROR: An error occurred while reinstalling '{node_name}'.\n{res.msg}", style="bold red")
|
||||
return
|
||||
|
||||
target = res.target.upper() if res.target in ('nightly', 'unknown') else res.target
|
||||
print(f"{cnt_msg} [REINSTALLED] {node_name:50}[{target}]")
|
||||
|
||||
|
||||
def fix_node(node_spec_str, is_all=False, cnt_msg=''):
|
||||
def fix_node(node_spec_str, is_all=False, cnt_msg='', fixed=None):
|
||||
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
|
||||
|
||||
if node_spec is None:
|
||||
if not is_all:
|
||||
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
|
||||
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
|
||||
else:
|
||||
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
|
||||
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
|
||||
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
|
||||
else:
|
||||
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
|
||||
|
||||
return
|
||||
|
||||
node_name, version_spec, _ = node_spec
|
||||
|
||||
print(f"{cnt_msg} [ FIXING ]: {node_name:50}[{version_spec}]")
|
||||
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps)
|
||||
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps, fixed=fixed)
|
||||
|
||||
if not res.result:
|
||||
print(f"[bold red]ERROR: f{res.msg}[/bold red]")
|
||||
print(f"ERROR: {res.msg}", style="bold red")
|
||||
|
||||
|
||||
def uninstall_node(node_spec_str: str, is_all: bool = False, cnt_msg: str = ''):
|
||||
@@ -317,8 +340,9 @@ def update_parallel(nodes):
|
||||
nodes = []
|
||||
for x in unified_manager.active_nodes.keys():
|
||||
nodes.append(x)
|
||||
for x in unified_manager.unknown_active_nodes.keys():
|
||||
nodes.append(x+"@unknown")
|
||||
for k, v in unified_manager.unknown_active_nodes.items():
|
||||
if v[1] not in unified_manager.invalid_installations:
|
||||
nodes.append(k+"@unknown")
|
||||
else:
|
||||
nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui']]
|
||||
|
||||
@@ -392,6 +416,7 @@ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
|
||||
|
||||
def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
|
||||
if 'comfyui-manager' in node_spec_str.lower():
|
||||
print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not disabled: its name has 'comfyui-manager'")
|
||||
return
|
||||
|
||||
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
|
||||
@@ -445,11 +470,7 @@ def show_list(kind, simple=False):
|
||||
|
||||
if flag and kind != 'cnr':
|
||||
for k, v in unified_manager.unknown_active_nodes.items():
|
||||
item = repo_unknown.get(k)
|
||||
|
||||
if item is None:
|
||||
continue
|
||||
|
||||
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
|
||||
log_item = "[ ENABLED ] ", item['title'], k, item['author']
|
||||
unknown_processed.append(log_item)
|
||||
|
||||
@@ -476,11 +497,7 @@ def show_list(kind, simple=False):
|
||||
|
||||
if flag and kind != 'cnr':
|
||||
for k, v in unified_manager.unknown_inactive_nodes.items():
|
||||
item = repo_unknown.get(k)
|
||||
|
||||
if item is None:
|
||||
continue
|
||||
|
||||
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
|
||||
log_item = "[ DISABLED ] ", item['title'], k, item['author']
|
||||
unknown_processed.append(log_item)
|
||||
|
||||
@@ -511,7 +528,7 @@ def show_list(kind, simple=False):
|
||||
if simple:
|
||||
print(title+'@'+ver_spec)
|
||||
else:
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [{ver_spec}]")
|
||||
|
||||
for x in unknown_processed:
|
||||
prefix, title, short_id, author = x
|
||||
@@ -521,19 +538,19 @@ def show_list(kind, simple=False):
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
|
||||
|
||||
|
||||
async def show_snapshot(simple_mode=False):
|
||||
json_obj = await core.get_current_snapshot()
|
||||
def show_snapshot(simple_mode=False):
|
||||
json_obj = asyncio.run(core.get_current_snapshot())
|
||||
|
||||
if simple_mode:
|
||||
print(f"[{json_obj['comfyui']}] comfyui")
|
||||
core.print(f"[{json_obj['comfyui']}] comfyui")
|
||||
for k, v in json_obj['git_custom_nodes'].items():
|
||||
print(f"[{v['hash']}] {k}")
|
||||
core.print(f"[{v['hash']}] {k}")
|
||||
for v in json_obj['file_custom_nodes']:
|
||||
print(f"[ N/A ] {v['filename']}")
|
||||
core.print(f"[ N/A ] {v['filename']}")
|
||||
|
||||
else:
|
||||
formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
|
||||
print(formatted_json)
|
||||
core.print(formatted_json)
|
||||
|
||||
|
||||
def show_snapshot_list(simple_mode=False):
|
||||
@@ -635,7 +652,7 @@ def install(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
no_deps: Annotated[
|
||||
Optional[bool],
|
||||
@@ -677,7 +694,7 @@ def reinstall(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
no_deps: Annotated[
|
||||
Optional[bool],
|
||||
@@ -715,7 +732,7 @@ def uninstall(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
):
|
||||
cmd_ctx.set_channel_mode(channel, mode)
|
||||
@@ -726,7 +743,7 @@ def uninstall(
|
||||
def update(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to update]"
|
||||
help="all|List of custom nodes to update"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -737,7 +754,7 @@ def update(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -765,7 +782,7 @@ def update(
|
||||
def disable(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to disable]"
|
||||
help="all|List of custom nodes to disable"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -776,7 +793,7 @@ def disable(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -796,7 +813,7 @@ def disable(
|
||||
def enable(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to enable]"
|
||||
help="all|List of custom nodes to enable"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -807,7 +824,7 @@ def enable(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -827,7 +844,7 @@ def enable(
|
||||
def fix(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to fix]"
|
||||
help="all|List of custom nodes to fix"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -838,7 +855,7 @@ def fix(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -852,7 +869,7 @@ def fix(
|
||||
asyncio.run(auto_save_snapshot())
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
|
||||
for_each_nodes(nodes, fix_node, allow_all=True)
|
||||
for_each_nodes(nodes, fix_node, allow_all=True, fixed=set())
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
|
||||
@@ -869,7 +886,7 @@ def show_versions(node_name: str):
|
||||
@app.command("show", help="Show node list")
|
||||
def show(
|
||||
arg: str = typer.Argument(
|
||||
help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
|
||||
help="installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -880,7 +897,7 @@ def show(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -914,7 +931,7 @@ def show(
|
||||
@app.command("simple-show", help="Show node list (simple mode)")
|
||||
def simple_show(
|
||||
arg: str = typer.Argument(
|
||||
help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
|
||||
help="installed|enabled|not-installed|disabled|all|snapshot|snapshot-list"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -925,7 +942,7 @@ def simple_show(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -942,7 +959,7 @@ def simple_show(
|
||||
"snapshot-list",
|
||||
]
|
||||
if arg not in valid_commands:
|
||||
typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
|
||||
typer.echo(f"Invalid command: `show {arg}`", err=True)
|
||||
exit(1)
|
||||
|
||||
cmd_ctx.set_user_directory(user_directory)
|
||||
@@ -959,7 +976,7 @@ def simple_show(
|
||||
@app.command('cli-only-mode', help="Set whether to use ComfyUI-Manager in CLI-only mode.")
|
||||
def cli_only_mode(
|
||||
mode: str = typer.Argument(
|
||||
..., help="[enable|disable]"
|
||||
..., help="enable|disable"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -978,7 +995,7 @@ def cli_only_mode(
|
||||
os.remove(cli_mode_flag)
|
||||
print("\nINFO: `cli-only-mode` is disabled\n")
|
||||
else:
|
||||
print(f"\n[bold red]Invalid value for cli-only-mode: {mode}[/bold red]\n")
|
||||
print(f"\nInvalid value for cli-only-mode: {mode}\n", style="bold red")
|
||||
exit(1)
|
||||
|
||||
|
||||
@@ -1001,7 +1018,7 @@ def deps_in_workflow(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1015,7 +1032,7 @@ def deps_in_workflow(
|
||||
output_path = output
|
||||
|
||||
if not os.path.exists(input_path):
|
||||
print(f"[bold red]File not found: {input_path}[/bold red]")
|
||||
print(f"File not found: {input_path}", style="bold red")
|
||||
exit(1)
|
||||
|
||||
used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
|
||||
@@ -1060,13 +1077,13 @@ def save_snapshot(
|
||||
|
||||
if output is not None:
|
||||
if(not output.endswith('.json') and not output.endswith('.yaml')):
|
||||
print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
|
||||
print("ERROR: output path should be either '.json' or '.yaml' file.", style="bold red")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
dir_path = os.path.dirname(output)
|
||||
|
||||
if(dir_path != '' and not os.path.exists(dir_path)):
|
||||
print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
|
||||
print(f"ERROR: {output} path not exists.", style="bold red")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
|
||||
@@ -1125,18 +1142,21 @@ def restore_snapshot(
|
||||
else:
|
||||
snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
|
||||
if not os.path.exists(snapshot_path):
|
||||
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
|
||||
print(f"ERROR: `{snapshot_path}` is not exists.", style="bold red")
|
||||
exit(1)
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
|
||||
try:
|
||||
asyncio.run(core.restore_snapshot(snapshot_path, extras))
|
||||
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
|
||||
except Exception:
|
||||
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
|
||||
print("ERROR: Failed to restore snapshot.", style="bold red")
|
||||
traceback.print_exc()
|
||||
raise typer.Exit(code=1)
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
if not is_restored:
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
|
||||
@app.command(
|
||||
"restore-dependencies", help="Restore dependencies from whole installed custom nodes."
|
||||
@@ -1154,7 +1174,7 @@ def restore_dependencies(
|
||||
for base_path in cmd_ctx.get_custom_nodes_paths():
|
||||
for name in os.listdir(base_path):
|
||||
target = os.path.join(base_path, name)
|
||||
if os.path.isdir(target) and not name.endswith('.disabled'):
|
||||
if os.path.isdir(target) and not name.endswith('.disabled') and name != '__pycache__':
|
||||
node_paths.append(target)
|
||||
|
||||
total = len(node_paths)
|
||||
@@ -1201,7 +1221,7 @@ def install_deps(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1213,14 +1233,14 @@ def install_deps(
|
||||
asyncio.run(auto_save_snapshot())
|
||||
|
||||
if not os.path.exists(deps):
|
||||
print(f"[bold red]File not found: {deps}[/bold red]")
|
||||
print(f"File not found: {deps}", style="bold red")
|
||||
exit(1)
|
||||
else:
|
||||
with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
try:
|
||||
json_obj = json.load(json_file)
|
||||
except:
|
||||
print(f"[bold red]Invalid json file: {deps}[/bold red]")
|
||||
print(f"Invalid json file: {deps}", style="bold red")
|
||||
exit(1)
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
|
||||
@@ -1231,7 +1251,8 @@ def install_deps(
|
||||
elif state == 'not-installed':
|
||||
asyncio.run(core.gitclone_install(k, instant_execution=True))
|
||||
else: # disabled
|
||||
core.gitclone_set_active([k], False)
|
||||
cnr = unified_manager.get_cnr_by_repo(k)
|
||||
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
print("Dependency installation and activation complete.")
|
||||
@@ -1254,7 +1275,7 @@ def export_custom_node_ids(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1283,6 +1304,3 @@ def export_custom_node_ids(
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(app())
|
||||
|
||||
|
||||
print("")
|
||||
|
||||
+498
-248
@@ -12398,16 +12398,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes:Incrementer, Width and height from aspect ratio, Width and height for scaling image to ideal resolutio. A simple set of tooling nodes."
|
||||
},
|
||||
{
|
||||
"author": "fofr",
|
||||
"title": "ComfyUI-Replicate",
|
||||
"reference": "https://github.com/replicate/comfyui-replicate",
|
||||
"files": [
|
||||
"https://github.com/replicate/comfyui-replicate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Run [a/Replicate models](https://replicate.com/explore) in ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "fofr",
|
||||
"title": "ComfyUI-Basic-Auth",
|
||||
@@ -12930,17 +12920,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Utility custom nodes for special effects, image manipulation and quality of life tools."
|
||||
},
|
||||
{
|
||||
"author": "ruiqutech",
|
||||
"title": "RuiquNodes for ComfyUI",
|
||||
"id": "RuiquNodes",
|
||||
"reference": "https://github.com/ruiqutech/ComfyUI-RuiquNodes",
|
||||
"files": [
|
||||
"https://github.com/ruiqutech/ComfyUI-RuiquNodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes of EvaluateMultiple1, EvaluateMultiple3...\nSupport the execution of any fragment of Python code, generating multiple outputs from multiple inputs."
|
||||
},
|
||||
{
|
||||
"author": "teward",
|
||||
"title": "ComfyUI-Helper-Nodes",
|
||||
@@ -14218,17 +14197,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Use ComfyUI with RTX Remix to remaster classic games [a/https://github.com/NVIDIAGameWorks/rtx-remix](https://github.com/NVIDIAGameWorks/rtx-remix)"
|
||||
},
|
||||
{
|
||||
"author": "toxicwind",
|
||||
"title": "TTools for ComfyUI",
|
||||
"id": "ttools",
|
||||
"reference": "https://github.com/toxicwind/ComfyUI-TTools",
|
||||
"files": [
|
||||
"https://github.com/toxicwind/ComfyUI-TTools"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text Randomization and Formatting, JSON Extraction and Processing, SD3 Resolution Solver"
|
||||
},
|
||||
{
|
||||
"author": "Yanick112",
|
||||
"title": "ComfyUI-ToSVG",
|
||||
@@ -21752,12 +21720,12 @@
|
||||
{
|
||||
"author": "Kling AI",
|
||||
"title": "ComfyUI-KLingAI-API",
|
||||
"reference": "https://github.com/KwaiVGI/ComfyUI-KLingAI-API",
|
||||
"reference": "https://github.com/KlingAIResearch/ComfyUI-KLingAI-API",
|
||||
"files": [
|
||||
"https://github.com/KwaiVGI/ComfyUI-KLingAI-API"
|
||||
"https://github.com/KlingAIResearch/ComfyUI-KLingAI-API"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Provide high-quality video and image generation capabilities, meeting creators' needs for creative content production and management through more convenient operations, richer functionalities, professional parameters, and stunning effects."
|
||||
"description": "Official Kling AI ComfyUI custom nodes for image and video generation through the Kling API. Requires a Kling API key; see the repository README for setup and pricing."
|
||||
},
|
||||
{
|
||||
"author": "lujiazho",
|
||||
@@ -29694,26 +29662,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "This ComfyUI custom node processes SVG (Scalable Vector Graphics) images to ensure the artwork consistently fills its canvas, is visually centered, and optionally has a margin applied. It's designed to provide more accurate results for complex vector graphics, such as those generated by vector tracing tools, where simple geometric bounding boxes may not align with perceived visual extents."
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "ComfyUI Load Image From URL",
|
||||
"reference": "https://github.com/papcorns/ComfyUI-Papcorns-Node-LoadImageFromUrl",
|
||||
"files": [
|
||||
"https://github.com/papcorns/ComfyUI-Papcorns-Node-LoadImageFromUrl"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node that allows you to load images directly from URLs or local file paths. This node provides a convenient way to import images into your ComfyUI workflows without manually downloading them first."
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "Papcorns ComfyUI Custom Nodes",
|
||||
"reference": "https://github.com/papcorns/Papcorns-Comfyui-Custom-Nodes",
|
||||
"files": [
|
||||
"https://github.com/papcorns/Papcorns-Comfyui-Custom-Nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A collection of custom nodes for ComfyUI that enhances image processing and cloud storage capabilities."
|
||||
},
|
||||
{
|
||||
"author": "gabe-init",
|
||||
"title": "ComfyUI OpenRouter Node",
|
||||
@@ -39901,16 +39849,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom node suite integrating multiple AI image generation APIs (Gemini, Flux.1 Kontext Pro) with unified authentication via ComfyUI API Key and real-time cost tracking. (Description by CC)"
|
||||
},
|
||||
{
|
||||
"author": "StarIICraft",
|
||||
"title": "ComfyUI-Simple-Selector",
|
||||
"reference": "https://github.com/StarIICraft/ComfyUI-Simple-Selector",
|
||||
"files": [
|
||||
"https://github.com/StarIICraft/ComfyUI-Simple-Selector"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Logic control node with 5 universal input ports that checks connections in reverse priority order and outputs the index of the first valid active input, with support for muted nodes and any data type."
|
||||
},
|
||||
{
|
||||
"author": "wwzhifeng",
|
||||
"title": "comfyui-jsonprompt",
|
||||
@@ -40264,16 +40202,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "MiniMax H3 for ComfyUI: one drag-and-drop input node covering t2va/fl2va/ref2va, plus step caching, partial decode and profiling."
|
||||
},
|
||||
{
|
||||
"author": "huygiatrng",
|
||||
"title": "Facefusion_comfyui",
|
||||
"reference": "https://github.com/huygiatrng/Facefusion_comfyui",
|
||||
"files": [
|
||||
"https://github.com/huygiatrng/Facefusion_comfyui"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Advanced face swapping for ComfyUI with local ONNX inference - no API required!"
|
||||
},
|
||||
{
|
||||
"author": "obvirm",
|
||||
"title": "ComfyUI-WhisperXX",
|
||||
@@ -40458,16 +40386,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Three custom ComfyUI nodes: Empty Image RGB, Text Line Break, and Random Chars (Append) for convenient utilities. (Description by CC)"
|
||||
},
|
||||
{
|
||||
"author": "Zeknes",
|
||||
"title": "Comfyui-LLM-Chat",
|
||||
"reference": "https://github.com/Zeknes/Comfyui-LLM-Chat",
|
||||
"files": [
|
||||
"https://github.com/Zeknes/Comfyui-LLM-Chat"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom ComfyUI node providing unified access to multiple Large Language Models including OpenAI-compatible APIs and local Ollama instances with image support."
|
||||
},
|
||||
{
|
||||
"author": "xiaoshengyvlin",
|
||||
"title": "ComfyUI-MetaData-ZaKo",
|
||||
@@ -42729,16 +42647,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node pack that embeds a playable Tetris game inside a node UI, with image outputs for the live board and next-piece preview."
|
||||
},
|
||||
{
|
||||
"author": "latentastronaut",
|
||||
"title": "comfyui-latent-astronaut-suite",
|
||||
"reference": "https://github.com/latentastronaut/comfyui-latent-astronaut-suite",
|
||||
"files": [
|
||||
"https://github.com/latentastronaut/comfyui-latent-astronaut-suite"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI nodes for batch processing, loops, and iteration workflows"
|
||||
},
|
||||
{
|
||||
"author": "d3cker",
|
||||
"title": "comfyui_remove_background",
|
||||
@@ -44113,16 +44021,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "A powerful ComfyUI custom node for saving images with flexible custom metadata fields embedded in PNG files."
|
||||
},
|
||||
{
|
||||
"author": "SorenWeile",
|
||||
"title": "INDG_CustomNodes",
|
||||
"reference": "https://github.com/SorenWeile/INDG_CustomNodes",
|
||||
"files": [
|
||||
"https://github.com/SorenWeile/INDG_CustomNodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom ComfyUI nodes for the INDG toolset including flexible image batching, path utilities, and memory cleanup."
|
||||
},
|
||||
{
|
||||
"author": "SorenWeile",
|
||||
"title": "nbpOpenNode-ComfyUI",
|
||||
@@ -47956,6 +47854,16 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "DAVE (DC Attenuation for diVersity Enhancement) as a drop-in MODEL patch for Anima / Cosmos-predict2 DiT: recover same-prompt sample diversity by attenuating the DC component of early-mid blocks over the first tau fraction of steps. Self-contained — bundles the shipped block-pool mask, pulls no training-repo code."
|
||||
},
|
||||
{
|
||||
"author": "sorryhyun",
|
||||
"title": "Anima Pixel Decoder",
|
||||
"reference": "https://github.com/sorryhyun/ComfyUI-Anima-PixelDecoder",
|
||||
"files": [
|
||||
"https://github.com/sorryhyun/ComfyUI-Anima-PixelDecoder"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Decode Anima renders straight from the DiT's last-layer features with a 25M-parameter pixel head, in place of VAE Decode: a MODEL tap (works with the stock KSampler and KSampler (Spectrum)) and a decode node that outputs IMAGE. A x2 head file decodes and upscales 2x in one readout. Weights: huggingface.co/sorryhyun/anima-pixel-decoder."
|
||||
},
|
||||
{
|
||||
"author": "spacewarpstudio",
|
||||
"title": "ComfyUI Override Switch",
|
||||
@@ -48949,16 +48857,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Variables Board is a floating control center for ComfyUI workflows that centralizes parameters into a customizable overlay."
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Clone Output",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-clone-output",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-clone-output"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Clone Output"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Color Correct",
|
||||
@@ -48989,16 +48887,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Alert"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Booleangate",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-booleangate",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-booleangate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Booleangate"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Delay",
|
||||
@@ -49019,16 +48907,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Color Postpro"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Basic Nodes",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-basic-nodes",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-basic-nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Basic Nodes"
|
||||
},
|
||||
{
|
||||
"author": "hassan-mb",
|
||||
"title": "HB ComfyUI Nodes",
|
||||
@@ -51406,16 +51284,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom node to rotate OpenPose figures around their torso"
|
||||
},
|
||||
{
|
||||
"author": "evanscho",
|
||||
"title": "Advanced Mask Nodes",
|
||||
"reference": "https://github.com/evanscho/ComfyUI-advanced-mask-nodes",
|
||||
"files": [
|
||||
"https://github.com/evanscho/ComfyUI-advanced-mask-nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A collection of custom nodes for ComfyUI"
|
||||
},
|
||||
{
|
||||
"author": "initialb-util",
|
||||
"title": "InitialB Util",
|
||||
@@ -52545,16 +52413,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom nodes for uploading and loading images from S3 buckets"
|
||||
},
|
||||
{
|
||||
"author": "Herony82",
|
||||
"title": "WanAnimatePreprocess Track",
|
||||
"reference": "https://github.com/Herony82/ComfyUI-WanAnimatePreprocess-track",
|
||||
"files": [
|
||||
"https://github.com/Herony82/ComfyUI-WanAnimatePreprocess-track"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "TrackedPoseAndFaceDetection - PoseAndFaceDetection con selezione manuale dei punti di tracking e optical flow (Lucas-Kanade). Richiede ComfyUI-WanAnimatePreprocess."
|
||||
},
|
||||
{
|
||||
"author": "hiroki-abe-58",
|
||||
"title": "comfyui-acemusic",
|
||||
@@ -54582,7 +54440,7 @@
|
||||
"https://github.com/Moon-NE/MoonNe_Nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text utilities and NTD11 video mosaic nodes. Includes weighted random prompts, text concatenation, a video file picker, folder batch processing, and audio preservation. Video detection requires an NVIDIA CUDA GPU."
|
||||
"description": "Text utilities and NTD11 mosaic nodes for single videos, video folders, and still-image folders. Videos preserve audio and support optional SAM2 contour tracking. Images are saved as PNG with transparency. Detection requires an NVIDIA CUDA GPU."
|
||||
},
|
||||
{
|
||||
"author": "younestft",
|
||||
@@ -55410,16 +55268,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI node package for BYOK (bring-your-own-key) access to external generative APIs: Gemini, Veo, and more via LiteLLM."
|
||||
},
|
||||
{
|
||||
"author": "Ave-Mollan",
|
||||
"title": "civitai-sdk-api-nodes-for-comfyui",
|
||||
"reference": "https://github.com/Ave-Mollan/CivitAI-SDK-API-nodes-for-ComfyUI",
|
||||
"files": [
|
||||
"https://github.com/Ave-Mollan/CivitAI-SDK-API-nodes-for-ComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom nodes for CivitAI cloud image generation via API"
|
||||
},
|
||||
{
|
||||
"author": "stratopause-lsc",
|
||||
"title": "ComfyUI-MacMemoryMonitor",
|
||||
@@ -59071,16 +58919,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Self-contained ComfyUI remove core extension with region editing and mask processing for image inpainting. (Description by CC)"
|
||||
},
|
||||
{
|
||||
"author": "isam2024",
|
||||
"title": "ComfyUI-FluxHallucinate",
|
||||
"reference": "https://github.com/isam2024/ComfyUI-FluxHallucinate",
|
||||
"files": [
|
||||
"https://github.com/isam2024/ComfyUI-FluxHallucinate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Intentionally degrade Flux dev.1's prompt adherence to recreate the loose, random, *hallucinatory* feel of SD1.5 / SDXL."
|
||||
},
|
||||
{
|
||||
"author": "Tulut114",
|
||||
"title": "tulut_comfyui_Gadget",
|
||||
@@ -60598,72 +60436,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Copy the shot, not the actors: reference video → depth map, OpenPose skeleton (DWPose, tracked and smoothed) or canny line video for Seedance 2.0/2.5 reference video, MiniMax H3 Fun ControlNet (depth / pose / canny) and Wan VACE. Six nodes: Depth / Pose / Canny as IMAGE→IMAGE and VIDEO→VIDEO with the model presets (fps, frame-size multiples) applied. Apache-2.0."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-Kavel",
|
||||
"id": "comfyui-kavel",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-Kavel",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-Kavel"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images through the kavel.ai API. Works without an API key on the free tier; add a key to use your account's models (Nano Banana 2, GPT Image 2, Seedream)."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-SayMaker",
|
||||
"id": "comfyui-saymaker",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-SayMaker",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-SayMaker"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images and animate them into video through the SayMaker API (Veo 3.1, Kling 3.0, Seedance 2.0, Nano Banana 2, GPT Image 2.5). No local GPU; needs a SayMaker API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-emaki",
|
||||
"id": "comfyui-emaki",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-emaki",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-emaki"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Seedance 2.5 text to video and image to video through the emaki API (Seedance 2.0, MiniMax H3, Veo 3.1 and Nano Banana 2 for first frames too). No local GPU; needs an emaki API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-Veida",
|
||||
"id": "comfyui-veida",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-Veida",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-Veida"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images through the Veida AI API. Works without an API key on the free tier; add a key to use your account's models (GPT Image 2.5, GPT Image 2, Nano Banana 2, Seedream 5.0)."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-FreeImageToVideo",
|
||||
"id": "comfyui-freeimagetovideo",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-FreeImageToVideo",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-FreeImageToVideo"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to video and image to video with sound (MiniMax H3) through the Free Image to Video API: connect any IMAGE as the first frame or leave it empty for text to video; the MP4 is saved to the output folder. No local GPU; needs a Free Image to Video API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-aigifmaker",
|
||||
"id": "comfyui-aigifmaker",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-aigifmaker",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-aigifmaker"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to animated GIF through the AI GIF Maker API (native GIF generation, not a converted video). Outputs every frame as an IMAGE batch plus the saved .gif. No local GPU; needs an AI GIF Maker API key."
|
||||
},
|
||||
{
|
||||
"author": "lostmywind",
|
||||
"title": "Workflow Doctor",
|
||||
@@ -60870,6 +60642,26 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Visual timeline for MiniMax H3 video generation with shot editing, reference images, audio, and project saving. Powered by the H3 Continuum generation engine."
|
||||
},
|
||||
{
|
||||
"author": "ukr8b3g-cmyk",
|
||||
"title": "PLaMo Prompt Translator",
|
||||
"reference": "https://github.com/ukr8b3g-cmyk/ComfyUI-PLaMo-Prompt-Translator",
|
||||
"files": [
|
||||
"https://github.com/ukr8b3g-cmyk/ComfyUI-PLaMo-Prompt-Translator"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Translate image prompts and plain text locally through LM Studio with PLaMo 3 Translate. Supports 53 language choices, side-by-side editors, and automatic splitting for long text."
|
||||
},
|
||||
{
|
||||
"author": "ukr8b3g-cmyk",
|
||||
"title": "Anima Character Sheet Designer",
|
||||
"reference": "https://github.com/ukr8b3g-cmyk/Anima-Character-Sheet-Designer",
|
||||
"files": [
|
||||
"https://github.com/ukr8b3g-cmyk/Anima-Character-Sheet-Designer"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create character sheets in ComfyUI with Anima, using prompt text or local image tags. Generate up to 13 independent views with editable prompts and assemble them into a sheet."
|
||||
},
|
||||
{
|
||||
"author": "D33MO",
|
||||
"title": "ComfyUI Prompt Warehouse",
|
||||
@@ -61501,6 +61293,50 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Fast and regularized Flow Matching and Diffusion samplers (Flow-WLS Savitzky-Golay multistep, CAB-2..6, and high-order DPM++ solvers) achieving stable few-step generation in 10 steps with zero artifacts."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Adaptive-step samplers (SA-Solver stochastic strength, predictor-corrector error estimate)",
|
||||
"id": "adaptive-step-samplers",
|
||||
"reference": "https://github.com/YakovSava/adaptive-step-samplers",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/adaptive-step-samplers"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes: Adaptive SA Sampler (exposes the stochastic strength and noise window that ComfyUI hardcodes in sa_solver), Adaptive PC Sampler (Adams predictor-corrector with a free local error estimate) and Trajectory Probe (per-step diagnostics). Research code with measurements."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Flow-SDE Sampler (curvature- and error-adaptive stochasticity)",
|
||||
"id": "flow-sde-research",
|
||||
"reference": "https://github.com/YakovSava/flow-sde-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/flow-sde-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Flow-SDE Sampler node: controls how much noise an SDE sampler injects at each step for flow-matching models at low step counts. Research code; measured on Anima, Flux and MOSS-Image, with mostly negative results documented in the README."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Flow-WLS Sampler (regularized multistep, quantization study)",
|
||||
"id": "flow-wls-research",
|
||||
"reference": "https://github.com/YakovSava/flow-wls-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/flow-wls-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes: Flow-WLS Sampler and Flow Easy Sampler, regularized multistep integration for flow-matching models, plus the research code of a study of how such samplers behave under FP8/INT4 quantization errors."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Momentum samplers for flow models (EMA momentum, damped extrapolation, any-sampler filter)",
|
||||
"id": "momentum-cfg-samplers-research",
|
||||
"reference": "https://github.com/YakovSava/momentum-cfg-samplers-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/momentum-cfg-samplers-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Momentum on the data prediction for DPM-Solver++-style samplers on flow-matching models: a negative coefficient lowers the error at equal step count, a positive one only adds lag. Nodes: Sampler Momentum, Sampler Momentum Filter (wraps any one-evaluation sampler, unevaluated), Sigmas grid; KSampler entries ddim_momentum, dpmpp_2m_sde_damped and <base>_momentumized. Includes a diagnosis of why the 2023 dpmpp_dualsde_momentumized fails on flow models."
|
||||
},
|
||||
{
|
||||
"author": "zaum",
|
||||
"title": "ComfyUI Sidebar Hider",
|
||||
@@ -61551,6 +61387,36 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "BSAI H3 upscale 4K - dedicated AI video super-resolution / 4K upscaling plugin for ComfyUI (MiniMax H3, Real-ESRGAN, Tile, FP16)"
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI_ComfyUI_IndexTTS-2.5",
|
||||
"reference": "https://github.com/xm6018924/BSAI_ComfyUI_IndexTTS-2.5",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI_ComfyUI_IndexTTS-2.5"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "BSAI ComfyUI IndexTTS-2.5 - Text-to-Speech plugin with auto model download (ModelScope/HuggingFace)"
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI-MiniMAX-H3-Prompt",
|
||||
"reference": "https://github.com/xm6018924/BSAI-MiniMAX-H3-Prompt",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI-MiniMAX-H3-Prompt"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom node for optimizing MiniMax H3 video generation prompts based on the H3 model manual"
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI-ComfyUI_Contextual-Series",
|
||||
"reference": "https://github.com/xm6018924/BSAI-ComfyUI_Contextual-Series",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI-ComfyUI_Contextual-Series"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Extract reference frames from previously generated video to maintain visual consistency across sequential MiniMax H3 video generations"
|
||||
},
|
||||
{
|
||||
"author": "Strix-3D",
|
||||
"title": "ComfyUI-DLSS5-Enhancer-v15",
|
||||
@@ -61851,7 +61717,7 @@
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Suno by Ace Data Cloud",
|
||||
"title": "Suno",
|
||||
"id": "ace-suno",
|
||||
"reference": "https://github.com/AceDataCloud/SunoComfyUI",
|
||||
"files": [
|
||||
@@ -61860,6 +61726,204 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Suno music through your Ace Data Cloud account, query the same task ID, and load completed audio into ComfyUI. Requires an Ace Data Cloud API key; generation consumes Credits. Cloud API only, with no local model or GPU needed."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Ace Chat",
|
||||
"id": "ace-chat",
|
||||
"reference": "https://github.com/AceDataCloud/AceChatComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/AceChatComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "List chat model IDs and send chat messages from a ComfyUI workflow. Requires an Ace Data Cloud API key. Chat requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Face Transform",
|
||||
"id": "face-transform",
|
||||
"reference": "https://github.com/AceDataCloud/FaceTransformComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FaceTransformComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Analyze or transform a face in a supplied image. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Fish Audio",
|
||||
"id": "fish-audio",
|
||||
"reference": "https://github.com/AceDataCloud/FishAudioComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FishAudioComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate speech with Fish Audio and retrieve the resulting audio. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Flux",
|
||||
"id": "flux",
|
||||
"reference": "https://github.com/AceDataCloud/FluxComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FluxComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create images with FLUX through the hosted API. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Google Search",
|
||||
"id": "google-search",
|
||||
"reference": "https://github.com/AceDataCloud/GoogleSearchComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GoogleSearchComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Search Google from a workflow and return structured results. Requires an Ace Data Cloud API key. Searches are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Grok",
|
||||
"id": "grok",
|
||||
"reference": "https://github.com/AceDataCloud/GrokComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GrokComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Grok videos and retrieve the result of a submitted task. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Happy Horse",
|
||||
"id": "happy-horse",
|
||||
"reference": "https://github.com/AceDataCloud/HappyHorseComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/HappyHorseComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit Happy Horse videos and retrieve the original task. Requires an Ace Data Cloud API key. Video requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Kling",
|
||||
"id": "kling",
|
||||
"reference": "https://github.com/AceDataCloud/KlingComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/KlingComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit Kling videos and retrieve task results. Requires an Ace Data Cloud API key. Video requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Midjourney",
|
||||
"id": "midjourney",
|
||||
"reference": "https://github.com/AceDataCloud/MidjourneyComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/MidjourneyComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Midjourney images and retrieve the original task. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "MiniMax H3",
|
||||
"id": "ace-minimax-h3",
|
||||
"reference": "https://github.com/AceDataCloud/MiniMaxH3ComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/MiniMaxH3ComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate MiniMax H3 videos and retrieve task results. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Nano Banana",
|
||||
"id": "nano-banana",
|
||||
"reference": "https://github.com/AceDataCloud/NanoBananaComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/NanoBananaComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit images with Nano Banana and load completed images. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Qwen Image",
|
||||
"id": "qwen-image",
|
||||
"reference": "https://github.com/AceDataCloud/QwenImageComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/QwenImageComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit an image with Qwen Image. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Seedance",
|
||||
"id": "ace-seedance",
|
||||
"reference": "https://github.com/AceDataCloud/SeedanceComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/SeedanceComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate a Seedance video and load the completed video from its task ID. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Seedream",
|
||||
"id": "seedream",
|
||||
"reference": "https://github.com/AceDataCloud/SeedreamComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/SeedreamComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create, edit or decompose images with Seedream. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Veo",
|
||||
"id": "veo",
|
||||
"reference": "https://github.com/AceDataCloud/VeoComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/VeoComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate a Veo video and check its task status. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Wan",
|
||||
"id": "wan",
|
||||
"reference": "https://github.com/AceDataCloud/WanComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/WanComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Wan videos and retrieve task results. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "ACE Music",
|
||||
"id": "ace-acemusic",
|
||||
"reference": "https://github.com/AceDataCloud/ACEMusicComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/ACEMusicComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate ACE Music songs and lyrics, import reference assets, and retrieve results by task ID. Requires an Ace Data Cloud API key. Generation and reference imports are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "GPT Image",
|
||||
"id": "gpt-image",
|
||||
"reference": "https://github.com/AceDataCloud/GPTImageComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GPTImageComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images with GPT Image, retrieve task results, and load the resulting images in ComfyUI. Requires an Ace Data Cloud API key. Generation and editing are metered."
|
||||
},
|
||||
{
|
||||
"author": "NotUsingGithub",
|
||||
"title": "Wan27",
|
||||
@@ -62333,7 +62397,7 @@
|
||||
"https://github.com/PSA-Team-source/comfyui-uberllm"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes for text-to-video, image-to-video, image generation and image editing through the UberLLM API (Veo 3.1, Kling, Seedance, Wan, Hailuo, Flux, Seedream, Nano Banana and more). You need your own UberLLM API key and prepaid credit; UberLLM bills the calls. No extra dependencies."
|
||||
"description": "Nodes for text-to-video, image-to-video, image generation and image editing through the MartLLM API (Veo 3.1, Kling, Seedance, Wan, Hailuo, Flux, Seedream, Nano Banana and more). You need your own MartLLM API key and prepaid credit; MartLLM bills the calls. No extra dependencies."
|
||||
},
|
||||
{
|
||||
"author": "E2GO",
|
||||
@@ -62458,12 +62522,12 @@
|
||||
},
|
||||
{
|
||||
"author": "Statite",
|
||||
"title": "ComfyUI-SpecAR",
|
||||
"title": "ComfyUI-StrideAR",
|
||||
"id": "comfyui-specar",
|
||||
"reference": "https://github.com/statite-ai/ComfyUI-SpecAR",
|
||||
"files": ["https://github.com/statite-ai/ComfyUI-SpecAR"],
|
||||
"reference": "https://github.com/statite-ai/ComfyUI-StrideAR",
|
||||
"files": ["https://github.com/statite-ai/ComfyUI-StrideAR"],
|
||||
"install_type": "git-clone",
|
||||
"description": "SpecAR: Training-free 2.04x-2.81x speedup on Krea Realtime 14B + Self-Forcing 1.3B (up to 23.1 FPS real-time on B200, 2.67x on H100) with lazy target KV caching and low-VRAM offload."
|
||||
"description": "StrideAR: Training-free 2.04x-2.81x speedup on Krea Realtime 14B + Self-Forcing 1.3B (up to 23.1 FPS real-time on B200, 2.67x on H100) with lazy target KV caching and low-VRAM offload."
|
||||
},
|
||||
{
|
||||
"author": "bi-toru-to",
|
||||
@@ -62580,6 +62644,192 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Force PyTorch attention for a single model. Fixes 'No operator found for memory_efficient_attention_forward' on RTX 50xx with xformers (e.g. Qwen-Image 2.1) without disabling xformers globally."
|
||||
},
|
||||
{
|
||||
"author": "yamoon-jjang",
|
||||
"title": "Ultra Qwen Image Editor + PiD",
|
||||
"reference": "https://github.com/Yamoon-jjang/comfyui-Ultra-Qwen-Image-Editor",
|
||||
"files": [
|
||||
"https://github.com/Yamoon-jjang/comfyui-Ultra-Qwen-Image-Editor"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Qwen 2511/2.1 and MiniMax H3 Image multi-reference editor for ComfyUI, with optional Qwen PiD upscale"
|
||||
},
|
||||
{
|
||||
"author": "seren",
|
||||
"title": "Anima Artist Blend",
|
||||
"reference": "https://github.com/seren-alegro/ComfyUI-AnimaArtistBlend",
|
||||
"files": [
|
||||
"https://github.com/seren-alegro/ComfyUI-AnimaArtistBlend"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Blend multiple artist tags in Qwen3 0.6B hidden-state space for Anima (private test)"
|
||||
},
|
||||
{
|
||||
"author": "rasmont",
|
||||
"title": "LoRA Preset (saved in workflow)",
|
||||
"reference": "https://github.com/RasmonT/comfyui-workflow-lora-presets",
|
||||
"files": [
|
||||
"https://github.com/RasmonT/comfyui-workflow-lora-presets"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "LoRA presets saved INSIDE the workflow. One dropdown applies a whole LoRA combo; right-click to save your enabled LoRA loaders as a preset, edit, import or share. Anyone who loads your workflow gets your presets."
|
||||
},
|
||||
{
|
||||
"author": "perfectgf",
|
||||
"title": "ComfyUI Krea2 Enhancer",
|
||||
"reference": "https://github.com/perfectgf/ComfyUI-Krea2-Enhancer",
|
||||
"files": [
|
||||
"https://github.com/perfectgf/ComfyUI-Krea2-Enhancer"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Krea2 Turbo Enhancement Nodes"
|
||||
},
|
||||
{
|
||||
"author": "israeldelamoicjardin",
|
||||
"title": "Auto LoRA Prompt Plot",
|
||||
"reference": "https://github.com/israeldelamoicjardin/comfyui-auto-lora-prompt-plot",
|
||||
"files": [
|
||||
"https://github.com/israeldelamoicjardin/comfyui-auto-lora-prompt-plot"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Apply multiple LoRAs with matching trigger-word prompts in ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "daniel-ang",
|
||||
"title": "Torch Legacy",
|
||||
"reference": "https://github.com/daniel-ang/ComfyUI-Torch-Legacy",
|
||||
"files": [
|
||||
"https://github.com/daniel-ang/ComfyUI-Torch-Legacy"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Reproduce torch 2.8.0+cu129 CUDA numerics on newer torch, so MiniMax Music 3 / YuE2 seeds give the same songs as before the torch upgrade."
|
||||
},
|
||||
{
|
||||
"author": "AinJuZen",
|
||||
"title": "ComfyUI-ModelMirror",
|
||||
"reference": "https://github.com/AinJuZen/ComfyUI-ModelMirror",
|
||||
"files": [
|
||||
"https://github.com/AinJuZen/ComfyUI-ModelMirror"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Fills in missing models through a configurable mirror (hf-mirror by default): detects missing model files in the current workflow, resolves each to its official HuggingFace repo by filename, and downloads them into the correct models/ folder with resume support. Writes only inside models/ (validated allowlist, no path traversal). Does not patch any official ComfyUI file."
|
||||
},
|
||||
{
|
||||
"author": "jutsuhq",
|
||||
"title": "ComfyUI-Higgsfield",
|
||||
"id": "comfyui-higgsfield",
|
||||
"reference": "https://github.com/jutsuhq/ComfyUI-Higgsfield",
|
||||
"files": [
|
||||
"https://github.com/jutsuhq/ComfyUI-Higgsfield"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Higgsfield API video nodes: Seedance 2.5 and Kling 4.0 (text-to-video and image-to-video) and Genjutsu motion transfer, with your own API key. Each node shows its price and stops before submitting if the estimate is above max_cost_usd."
|
||||
},
|
||||
{
|
||||
"author": "codalanguez",
|
||||
"title": "CodaComfy Nodes",
|
||||
"id": "coda-comfy-tools",
|
||||
"reference": "https://github.com/codalanguez/CodaComfy-Nodes",
|
||||
"files": [
|
||||
"https://github.com/codalanguez/CodaComfy-Nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "OpenRouter video, on-screen dialogue, cast and frame stacks, and soundtrack generation. Includes a LoRA stack browser, a latent chooser, and seven example video workflows."
|
||||
},
|
||||
{
|
||||
"author": "haryai",
|
||||
"title": "Seedance 2.5 (HaryAI)",
|
||||
"id": "seedance-comfyui",
|
||||
"reference": "https://github.com/sunsiyuan/seedance-comfyui",
|
||||
"files": [
|
||||
"https://github.com/sunsiyuan/seedance-comfyui"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Seedance 2.5 and Seedance 2.5 Flash video generation through the HaryAI API: text to video, first and last frame, reference images, sound. No BytePlus account needed."
|
||||
},
|
||||
{
|
||||
"author": "zhulinyv",
|
||||
"title": "ComfyUI-RiceRabbit-Tools",
|
||||
"reference": "https://github.com/zhulinyv/ComfyUI-RiceRabbit-Tools",
|
||||
"files": [
|
||||
"https://github.com/zhulinyv/ComfyUI-RiceRabbit-Tools"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "RiceRabbit toolbox: prompt editor with Danbooru tag autocomplete, tag-chip modal, wildcard card library and online translation; image compare viewer (slide divider, wheel zoom) that auto-collects every IMAGE output of your Set/Get variables; plus resolution / date / text-join / any-type switch helpers."
|
||||
},
|
||||
{
|
||||
"author": "joykst96",
|
||||
"title": "kludge",
|
||||
"id": "kludge",
|
||||
"reference": "https://github.com/joykst96/comfyui-kludge",
|
||||
"files": [
|
||||
"https://github.com/joykst96/comfyui-kludge"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Makeshift helper nodes, mostly for Anima (2B / 2.9B): INT8 quantize on load, 2.9B LoRA remap, Spectrum, SPEED, block compile, guider model tracking, SnapRef."
|
||||
},
|
||||
{
|
||||
"author": "Zrn59",
|
||||
"title": "ComfyUI-GGUF-Next",
|
||||
"id": "comfyui-gguf-next",
|
||||
"reference": "https://github.com/Zrn59/ComfyUI-GGUF-Next",
|
||||
"files": [
|
||||
"https://github.com/Zrn59/ComfyUI-GGUF-Next"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Fork of city96/ComfyUI-GGUF with the same node IDs: all 35 ggml quant types dequantized in torch on the GPU (IQ1/IQ2/IQ3, TQ, MXFP4, NVFP4), any diffusion architecture ComfyUI detects, more text encoders (Gemma 2, Qwen2, Mistral 3, Qwen3-VL incl. 32B, the Gemma 4 encoder of LTX-2.5), and models bigger than RAM kept memory-mapped. Disable the original ComfyUI-GGUF first: both register the same node names."
|
||||
},
|
||||
{
|
||||
"author": "2867297362mjb-sketch",
|
||||
"title": "comfyui-teamorouter",
|
||||
"reference": "https://github.com/2867297362mjb-sketch/comfyui-teamorouter",
|
||||
"files": [
|
||||
"https://github.com/2867297362mjb-sketch/comfyui-teamorouter"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A chat node for the TeamoRouter API: write or expand prompts, caption an input image with a vision model, or translate text with Claude, GPT, Gemini, DeepSeek, GLM, Kimi or Qwen through one OpenAI-compatible API key. You need your own TeamoRouter API key and prepaid balance. No extra dependencies."
|
||||
},
|
||||
{
|
||||
"author": "alaintural",
|
||||
"title": "SyncTile for MiniMax H3",
|
||||
"id": "synctile-h3",
|
||||
"reference": "https://github.com/alaintural/synctile-h3",
|
||||
"files": [
|
||||
"https://github.com/alaintural/synctile-h3"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "SyncTileRefine takes a MiniMax H3 video to 1080p, 2K or 4K on one 24 GB card. Overlapping tiles are blended in latent space after every sampling step, so the result has no seams. A ready workflow is included."
|
||||
},
|
||||
{
|
||||
"author": "bewizsky",
|
||||
"title": "Eyes4AI Text Repair",
|
||||
"reference": "https://github.com/bewizsky/eyes4ai-text-repair",
|
||||
"files": [
|
||||
"https://github.com/bewizsky/eyes4ai-text-repair"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Find misspelled text in photos and AI-generated images with Gemini, then use an image-editing workflow to fix localized text and review spelling and style. Includes check-only and SenseNova U1.6 examples."
|
||||
},
|
||||
{
|
||||
"author": "Raykosan (RaykoStudio)",
|
||||
"title": "ComfyUI-RS_WorkspaceManager",
|
||||
"reference": "https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager",
|
||||
"files": [
|
||||
"https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Workflow Preset Manager and Interface Settings Backup for ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "assetfeed",
|
||||
"title": "AssetFeed",
|
||||
"reference": "https://github.com/assetfeed/comfyui-assetfeed",
|
||||
"files": [
|
||||
"https://github.com/assetfeed/comfyui-assetfeed"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes for the AssetFeed API: AssetFeed OCR reads the text in an image, and AssetFeed AI Text Check estimates the AI-written share of an English text. Needs an ASSETFEED_API_KEY environment variable; images and text are sent to api.assetfeed.com; data handling is in the README."
|
||||
},
|
||||
{
|
||||
"author": "ntdviet",
|
||||
"title": "ntdviet/comfyui-ext",
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ ComfyUI-Loopchain
|
||||
|
||||
* Detailed Operations
|
||||
* `install`: Installs the specified custom nodes.
|
||||
* `reinstall`: Removes and then reinstalls the specified custom nodes.
|
||||
* `reinstall`: Removes and then reinstalls the specified custom nodes. A nodepack named without a version is reinstalled at the version that is installed.
|
||||
* `uninstall`: Uninstalls the specified custom nodes.
|
||||
* `update`: Updates the specified custom nodes.
|
||||
* `disable`: Disables the specified custom nodes.
|
||||
|
||||
@@ -49,7 +49,18 @@ When you start ComfyUI with the new System User Protection API, Manager automati
|
||||
|
||||
### Step 1: Configuration Migration
|
||||
|
||||
Only `config.ini` is migrated automatically.
|
||||
Only `config.ini` is migrated automatically, and of it only the settings that are preferences.
|
||||
|
||||
Settings that permit an install (`allow_git_url_install`, `allow_pip_install`, `allow_flagged_nodepack_install`) or change where Manager fetches from (`channel_url`, `http_channel_enabled`, `bypass_ssl`, `git_exe`), and settings that Manager does not know, are **not** migrated: the old `config.ini` was not protected, so they may have been changed without your knowledge. They are back at their defaults after the migration, and the terminal lists those that had another value than the default:
|
||||
|
||||
```
|
||||
======================================================================
|
||||
[ComfyUI-Manager] WARNING: Settings not migrated
|
||||
- ['allow_git_url_install', 'channel_url']
|
||||
- The legacy config.ini was not protected, so these are back at their defaults.
|
||||
- Set them again in /path/to/ComfyUI/user/__manager/config.ini if you need them.
|
||||
======================================================================
|
||||
```
|
||||
|
||||
**Important**: Snapshots are **NOT** automatically migrated. You must copy them manually if needed.
|
||||
|
||||
@@ -67,6 +78,8 @@ During migration, if your security level is below `normal` (i.e., `weak` or `nor
|
||||
|
||||
If you need a lower security level, you can manually edit the config after migration.
|
||||
|
||||
A security level that is not one of `strong`, `normal`, `normal-` and `weak` is set to `normal` as well. Only that setting changes.
|
||||
|
||||
### Step 3: Legacy Backup
|
||||
|
||||
Your entire legacy directory is moved to a backup location:
|
||||
@@ -74,7 +87,13 @@ Your entire legacy directory is moved to a backup location:
|
||||
user/__manager/.legacy-manager-backup/
|
||||
```
|
||||
|
||||
This backup is preserved until you manually delete it.
|
||||
This backup is preserved until you manually delete it. If a backup is already there, it is kept, and the new one is named `.legacy-manager-backup-2`, `-3`, and so on.
|
||||
|
||||
### Requirements of ComfyUI
|
||||
|
||||
Before these steps, the start that finds the legacy `config.ini` installs the requirements of ComfyUI, before the node packs are loaded. On an old ComfyUI the update of ComfyUI could only reserve that install on Windows or with `always_lazy_install`, in the legacy directory, which is not read anymore.
|
||||
|
||||
If the updated ComfyUI does not start because one of its requirements is missing, it does not get as far as Manager. Install them yourself, with the Python that runs ComfyUI: `python -m pip install -r requirements.txt` in the ComfyUI directory.
|
||||
|
||||
---
|
||||
|
||||
@@ -91,7 +110,7 @@ As long as the backup exists, Manager will remind you on **every startup**:
|
||||
----------------------------------------------------------------------
|
||||
```
|
||||
|
||||
**To stop this notification**: Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it.
|
||||
**To stop this notification**: Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it. If there are numbered ones (`.legacy-manager-backup-2`, ...), the notification lists them as well and stops when all are deleted.
|
||||
|
||||
---
|
||||
|
||||
@@ -107,13 +126,14 @@ If you need your old snapshots, copy the contents of `.legacy-manager-backup/sna
|
||||
|
||||
If you're running an older version of ComfyUI without the System User Protection API, Manager will:
|
||||
|
||||
1. **Force security level to `strong`** - All installations are blocked
|
||||
2. **Display warning message**:
|
||||
1. **Block all installations** - They are refused at every `security_level`. The `security_level` of `config.ini` is not changed
|
||||
2. **Serve only the update of ComfyUI** - Every other request to Manager is answered with `comfyui_outdated` (HTTP 403), and files in Manager's data directory that schedule a restore or direct pip (`restore-snapshot.json`, `pip_auto_fix.list`, `pip_overrides.json`) are not acted on
|
||||
3. **Display warning message**:
|
||||
|
||||
```
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
[ComfyUI-Manager] ERROR: ComfyUI version is outdated!
|
||||
- Most operations are blocked for security.
|
||||
- Every operation but the update of ComfyUI is blocked for security.
|
||||
- ComfyUI update is still allowed.
|
||||
- Please update ComfyUI to use Manager normally.
|
||||
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
@@ -133,7 +153,7 @@ If you're running an older version of ComfyUI without the System User Protection
|
||||
| `weak` | All operations allowed, including from remote connections. |
|
||||
|
||||
**Notes:**
|
||||
- `strong` is forced on outdated ComfyUI versions.
|
||||
- On outdated ComfyUI versions all installations are blocked at every level.
|
||||
- `normal` is the default and recommended for most users.
|
||||
- `normal-` is for developers who need to install unregistered nodes locally.
|
||||
- `weak` should only be used in isolated development environments.
|
||||
@@ -154,7 +174,7 @@ security_level = normal
|
||||
|
||||
This error appears when:
|
||||
- Your ComfyUI doesn't have the System User Protection API
|
||||
- All installations are blocked until you update ComfyUI
|
||||
- Everything but the update of ComfyUI is blocked until you update ComfyUI
|
||||
|
||||
**Solution**: Update ComfyUI to the latest version.
|
||||
|
||||
@@ -190,12 +210,13 @@ On older ComfyUI versions, the `__manager` directory is not normally created. If
|
||||
### All my installations are blocked
|
||||
|
||||
**Check 1**: Is your ComfyUI updated?
|
||||
- Old ComfyUI forces `security_level = strong`
|
||||
- Old ComfyUI blocks all installations at every `security_level`
|
||||
- Update ComfyUI to resolve
|
||||
|
||||
**Check 2**: What's your security level?
|
||||
- Check `user/__manager/config.ini`
|
||||
- `security_level = strong` blocks all installations
|
||||
- Manager 3.43 and earlier wrote `security_level = strong` into a `config.ini` that it created on an old ComfyUI. If you did not choose it, set it to `normal`
|
||||
|
||||
### My snapshots are missing
|
||||
|
||||
@@ -203,11 +224,11 @@ Snapshots are not automatically migrated. You need to manually copy the `snapsho
|
||||
|
||||
### I keep seeing the backup notification
|
||||
|
||||
Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it.
|
||||
Delete the `.legacy-manager-backup` folder inside `user/__manager/`, and any numbered one (`.legacy-manager-backup-2`, ...), after confirming you don't need any data from it.
|
||||
|
||||
### Snapshot restore is blocked
|
||||
|
||||
On old ComfyUI (without System User API), snapshot restore is blocked because security is forced to `strong`. Update ComfyUI to enable snapshot restore.
|
||||
On old ComfyUI (without System User API), snapshot restore is blocked, as is everything but the update of ComfyUI. A restore that is already scheduled is not run at the start either. Update ComfyUI to enable snapshot restore.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ ComfyUI-Loopchain
|
||||
|
||||
* 세부 동작
|
||||
* `install`: 지정된 커스텀 노드들을 설치합니다
|
||||
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
|
||||
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다. 버전 없이 이름만 지정하면 설치되어 있는 버전으로 재설치합니다.
|
||||
* `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
|
||||
* `update`: 지정된 커스텀 노드들을 업데이트합니다.
|
||||
* `disable`: 지정된 커스텀 노드들을 비활성화합니다.
|
||||
|
||||
+26
-33
@@ -120,10 +120,13 @@
|
||||
"https://github.com/0xRavenBlack/ComfyUI-OOP": [
|
||||
[
|
||||
"OOPAnimalNode",
|
||||
"OOPBackgroundNode",
|
||||
"OOPClothingNode",
|
||||
"OOPEnvironmentNode",
|
||||
"OOPExpressionNode",
|
||||
"OOPEyesNode",
|
||||
"OOPHairNode",
|
||||
"OOPLightingNode",
|
||||
"OOPLocationNode",
|
||||
"OOPMouthNode",
|
||||
"OOPNode",
|
||||
@@ -14397,6 +14400,7 @@
|
||||
"IAMCCS_Drama3GPUEncodeVoice",
|
||||
"IAMCCS_Drama3GPUModelLoader",
|
||||
"IAMCCS_Drama3GenerateGPU",
|
||||
"IAMCCS_EditaMasterFinish",
|
||||
"IAMCCS_FlashVSRPanelBatchPrep",
|
||||
"IAMCCS_FlashVSRPanelBatchRestore",
|
||||
"IAMCCS_FluxKleinMultiGen",
|
||||
@@ -19320,8 +19324,13 @@
|
||||
"https://github.com/Malte0621/hordeai-comfy": [
|
||||
[
|
||||
"AIHordeImageGenerate",
|
||||
"AIHordeImageSampling",
|
||||
"AIHordeLora",
|
||||
"AIHordeModelList",
|
||||
"AIHordeModelSelect",
|
||||
"AIHordeTextGenerate",
|
||||
"AIHordeTextModelList",
|
||||
"AIHordeTextSampling",
|
||||
"AIHordeTextualInversion"
|
||||
],
|
||||
{
|
||||
@@ -23247,6 +23256,7 @@
|
||||
"PixlStashCheckpointLoader",
|
||||
"PixlStashControlNetLoader",
|
||||
"PixlStashFaceLikenessGate",
|
||||
"PixlStashLayoutTextEncode",
|
||||
"PixlStashLikenessSearch",
|
||||
"PixlStashMultiAdapterLoader",
|
||||
"PixlStashPictureLikenessGate",
|
||||
@@ -28227,6 +28237,7 @@
|
||||
"StarMinimaxLatentUpscalerOption",
|
||||
"StarMinimaxMultirefOption",
|
||||
"StarModelAIOMerge",
|
||||
"StarModelMerge",
|
||||
"StarModelPacker",
|
||||
"StarMossControl",
|
||||
"StarMultiInputsToOne",
|
||||
@@ -31396,6 +31407,7 @@
|
||||
"XB_ShenBi",
|
||||
"XB_StoryboardSlicer",
|
||||
"XB_StringMerge",
|
||||
"XB_Text2ImagePromptPreset",
|
||||
"XB_TextEncodeQwenImageEdit",
|
||||
"XB_TextEncodeQwenImageEditPlus",
|
||||
"XB_TripleLoraLoader",
|
||||
@@ -43754,6 +43766,8 @@
|
||||
"SelectModelDevice",
|
||||
"SelectVAEDevice",
|
||||
"SelfAttentionGuidance",
|
||||
"SenseNovaConditioning",
|
||||
"SenseNovaInterleaveDecode",
|
||||
"SenseNovaSamplingOptions",
|
||||
"SetFirstSigma",
|
||||
"SetLatentNoiseMask",
|
||||
@@ -62743,6 +62757,7 @@
|
||||
"ImageReceiver",
|
||||
"ImageSender",
|
||||
"ImpactAssembleSEGS",
|
||||
"ImpactAssembleSEGSList",
|
||||
"ImpactBoolean",
|
||||
"ImpactCombineConditionings",
|
||||
"ImpactCompare",
|
||||
@@ -62757,6 +62772,7 @@
|
||||
"ImpactConvertDataType",
|
||||
"ImpactCount_Elts_in_SEGS",
|
||||
"ImpactDecomposeSEGS",
|
||||
"ImpactDecomposeSEGSList",
|
||||
"ImpactDilateMask",
|
||||
"ImpactDilateMaskInSEGS",
|
||||
"ImpactDilate_Mask_SEG_ELT",
|
||||
@@ -64627,6 +64643,7 @@
|
||||
"EmptyZImageLatentImage",
|
||||
"IllustrationStylePromptEncoder",
|
||||
"ImageFilter",
|
||||
"ImageFilterStackLAB",
|
||||
"ImageGridBuilder",
|
||||
"ImageLabeler",
|
||||
"ImageLabeler2",
|
||||
@@ -66799,7 +66816,7 @@
|
||||
[
|
||||
"MVNT Audio Segment",
|
||||
"MVNT Generate Dance",
|
||||
"MVNT Image to T-Pose",
|
||||
"MVNT List Styles",
|
||||
"MVNT Render Dance Video",
|
||||
"MVNTPreviewDance3D"
|
||||
],
|
||||
@@ -70346,7 +70363,9 @@
|
||||
"PixaromaVideoTools",
|
||||
"PixaromaWH",
|
||||
"PixaromaXYPlot",
|
||||
"Pixaroma_VueReferenceNode"
|
||||
"Pixaroma_VueReferenceNode",
|
||||
"SeamlessPreviewPixaroma",
|
||||
"SeamlessTilePixaroma"
|
||||
],
|
||||
{
|
||||
"title_aux": "ComfyUI-Pixaroma"
|
||||
@@ -73387,37 +73406,6 @@
|
||||
"title_aux": "RUI-Nodes"
|
||||
}
|
||||
],
|
||||
"https://github.com/ruiqutech/ComfyUI-RuiquNodes": [
|
||||
[
|
||||
"EvaluateListMultiple1",
|
||||
"EvaluateListMultiple3",
|
||||
"EvaluateListMultiple6",
|
||||
"EvaluateListMultiple9",
|
||||
"EvaluateMultiple1",
|
||||
"EvaluateMultiple3",
|
||||
"EvaluateMultiple6",
|
||||
"EvaluateMultiple9",
|
||||
"ImageDilate",
|
||||
"ImageErode",
|
||||
"ListPath",
|
||||
"MaskDilate",
|
||||
"MaskErode",
|
||||
"PreviewMask",
|
||||
"RangeSplit",
|
||||
"SaveMask",
|
||||
"StringAsAny",
|
||||
"StringConcat1",
|
||||
"StringConcat3",
|
||||
"StringConcat6",
|
||||
"StringConcat9",
|
||||
"StringPathStem",
|
||||
"TermsToList",
|
||||
"VAEDecodeSave"
|
||||
],
|
||||
{
|
||||
"title_aux": "RuiquNodes for ComfyUI"
|
||||
}
|
||||
],
|
||||
"https://github.com/ruminar/ComfyUI-CheckpointHandpickerSuite": [
|
||||
[
|
||||
"CheckpointListSelector",
|
||||
@@ -75375,6 +75363,7 @@
|
||||
[
|
||||
"GetKeyAPI",
|
||||
"SSL_GeminiAPIKeyConfig",
|
||||
"SSL_GeminiAudioConfig",
|
||||
"SSL_GeminiInteractionsAPIKeyConfig",
|
||||
"SSL_GeminiInteractionsSafetyConfig",
|
||||
"SSL_GeminiInteractionsStore",
|
||||
@@ -75584,6 +75573,7 @@
|
||||
"ChainEditVideo",
|
||||
"CheckpointLoader_v2",
|
||||
"CreateImageList",
|
||||
"DatasetPairSave",
|
||||
"H3Frames_cut",
|
||||
"HolocineFrames",
|
||||
"ImageBlend_GPU",
|
||||
@@ -78976,6 +78966,7 @@
|
||||
"TADiscordLink",
|
||||
"TAFastLaplacianSharpen",
|
||||
"TAFilenameGenerator",
|
||||
"TAFilmGrain",
|
||||
"TAFluxGuidanceGate",
|
||||
"TAHelpLink",
|
||||
"TAKSampler",
|
||||
@@ -80776,6 +80767,7 @@
|
||||
],
|
||||
"https://github.com/veighnsche/comfyui_gr85": [
|
||||
[
|
||||
"GR85_FanServicePrompt",
|
||||
"GR85_ImageDimensionResizer",
|
||||
"GR85_ImageSizer",
|
||||
"GR85_ImageSizerAll",
|
||||
@@ -83353,6 +83345,7 @@
|
||||
"ComfyUI_EXO_DisplayText",
|
||||
"ComfyUI_EXO_FluxSampler",
|
||||
"ComfyUI_EXO_FluxSamplerMini",
|
||||
"ComfyUI_EXO_H3StillAdapter",
|
||||
"ComfyUI_EXO_ImageRescale",
|
||||
"ComfyUI_EXO_LatentImageSize",
|
||||
"ComfyUI_EXO_LatentImageSizeX",
|
||||
|
||||
+16
-10
@@ -13,7 +13,6 @@ from git.remote import RemoteProgress
|
||||
|
||||
|
||||
comfy_path = os.environ.get('COMFYUI_PATH')
|
||||
git_exe_path = os.environ.get('GIT_EXE_PATH')
|
||||
|
||||
if comfy_path is None:
|
||||
print("\nWARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.", file=sys.stderr)
|
||||
@@ -181,6 +180,14 @@ def switch_to_default_branch(repo):
|
||||
return False
|
||||
|
||||
|
||||
def undo_pull(repo, commit):
|
||||
repo.git.reset('--hard', commit)
|
||||
try:
|
||||
repo.git.submodule('update', '--recursive')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def gitpull(path):
|
||||
# Check if the path is a git repository
|
||||
if not os.path.exists(os.path.join(path, '.git')):
|
||||
@@ -220,6 +227,7 @@ def gitpull(path):
|
||||
repo.close()
|
||||
return
|
||||
|
||||
tip_before_pull = repo.head.commit.hexsha
|
||||
try:
|
||||
repo.git.pull('--ff-only')
|
||||
except git.GitCommandError:
|
||||
@@ -229,7 +237,12 @@ def gitpull(path):
|
||||
repo.git.reset('--hard', f'{remote_name}/{branch_name}')
|
||||
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
|
||||
|
||||
repo.git.submodule('update', '--init', '--recursive')
|
||||
try:
|
||||
repo.git.submodule('update', '--init', '--recursive')
|
||||
except Exception:
|
||||
undo_pull(repo, tip_before_pull)
|
||||
raise
|
||||
|
||||
new_commit_hash = repo.head.commit.hexsha
|
||||
|
||||
if commit_hash != new_commit_hash:
|
||||
@@ -239,6 +252,7 @@ def gitpull(path):
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print("CUSTOM NODE PULL: Fail") # unknown git error
|
||||
sys.exit(1)
|
||||
|
||||
repo.close()
|
||||
|
||||
@@ -492,14 +506,6 @@ def restore_pip_snapshot(pips, options):
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
|
||||
|
||||
def setup_environment():
|
||||
if git_exe_path is not None:
|
||||
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe_path)
|
||||
|
||||
|
||||
setup_environment()
|
||||
|
||||
|
||||
try:
|
||||
if sys.argv[1] == "--clone":
|
||||
repo_path = None
|
||||
|
||||
+5320
-5315
File diff suppressed because it is too large
Load Diff
@@ -211,6 +211,7 @@ def read_cnr_info(fullpath):
|
||||
|
||||
project = data.get('project', {})
|
||||
name = project.get('name').strip().lower()
|
||||
original_name = project.get('name')
|
||||
|
||||
# normalize version
|
||||
# for example: 2.5 -> 2.5.0
|
||||
@@ -222,6 +223,7 @@ def read_cnr_info(fullpath):
|
||||
if name and version: # repository is optional
|
||||
return {
|
||||
"id": name,
|
||||
"original_name": original_name,
|
||||
"version": version,
|
||||
"url": repository
|
||||
}
|
||||
@@ -231,6 +233,14 @@ def read_cnr_info(fullpath):
|
||||
return None # not valid CNR node pack
|
||||
|
||||
|
||||
def read_project_name(fullpath):
|
||||
try:
|
||||
with open(os.path.join(fullpath, 'pyproject.toml'), "r", encoding="utf-8") as f:
|
||||
return toml.load(f)['project']['name'].strip()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def generate_cnr_id(fullpath, cnr_id):
|
||||
cnr_id_path = os.path.join(fullpath, '.git', '.cnr-id')
|
||||
try:
|
||||
|
||||
+107
-21
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import configparser
|
||||
import logging
|
||||
|
||||
|
||||
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
|
||||
@@ -12,28 +13,113 @@ def is_git_repo(path: str) -> bool:
|
||||
return os.path.exists(os.path.join(path, '.git'))
|
||||
|
||||
|
||||
def get_commit_hash(fullpath):
|
||||
git_head = os.path.join(fullpath, '.git', 'HEAD')
|
||||
if os.path.exists(git_head):
|
||||
with open(git_head) as f:
|
||||
line = f.readline()
|
||||
def file_name_of_git_for_windows(name):
|
||||
"""The name that Git for Windows gives the file of a ref, whose name is `name` in bytes.
|
||||
|
||||
if line.startswith("ref: "):
|
||||
ref = os.path.join(fullpath, '.git', line[5:].strip())
|
||||
if os.path.exists(ref):
|
||||
with open(ref) as f2:
|
||||
return f2.readline().strip()
|
||||
else:
|
||||
return "unknown"
|
||||
else:
|
||||
# detached HEAD: the file holds the sha followed by a newline;
|
||||
# without the strip the pinned hash carries that newline into
|
||||
# snapshots, and the next restore's checkout of that hash fails
|
||||
return line.strip()
|
||||
A name that is not UTF-8 is no name of a file there: a byte that is not of a character becomes
|
||||
the character of its number, or below 0xa0 its two hex digits, as in `xutftowcsn` of compat/mingw.c of git."""
|
||||
file_name = ''
|
||||
at = 0
|
||||
while at < len(name):
|
||||
size = 1 if name[at] < 0xc2 else 2 if name[at] < 0xe0 else 3 if name[at] < 0xf0 else 4
|
||||
try:
|
||||
file_name += name[at:at + size].decode('utf-8', 'surrogatepass')
|
||||
at += size
|
||||
except UnicodeDecodeError:
|
||||
file_name += chr(name[at]) if name[at] >= 0xa0 else '%02x' % name[at]
|
||||
at += 1
|
||||
|
||||
return file_name
|
||||
|
||||
|
||||
def get_commit_hash(fullpath):
|
||||
git_dir = os.path.join(fullpath, '.git')
|
||||
try:
|
||||
with open(os.path.join(git_dir, 'HEAD'), 'rb') as f:
|
||||
line = f.readline().strip()
|
||||
|
||||
if not line.startswith(b"ref:"):
|
||||
# detached HEAD: the file holds the sha followed by a newline;
|
||||
# without the strip the pinned hash carries that newline into
|
||||
# snapshots, and the next restore's checkout of that hash fails
|
||||
return line.decode('ascii', errors='replace')
|
||||
|
||||
ref_name = line[4:].strip()
|
||||
# put together as git does it, and not with `os.path.join`, for which a name can lead elsewhere
|
||||
if os.name == 'nt':
|
||||
ref = git_dir + '/' + file_name_of_git_for_windows(ref_name)
|
||||
else:
|
||||
ref = os.fsencode(git_dir) + b'/' + ref_name
|
||||
# a folder there is no ref, as for git: a branch `feature/x` beside the unborn branch `feature`
|
||||
if os.path.isfile(ref):
|
||||
with open(ref, 'rb') as f:
|
||||
return f.readline().strip().decode('ascii', errors='replace')
|
||||
|
||||
# after `git pack-refs` or `git gc` the ref is a line of packed-refs
|
||||
with open(os.path.join(git_dir, 'packed-refs'), 'rb') as f:
|
||||
for packed in f:
|
||||
fields = packed.split()
|
||||
if len(fields) == 2 and fields[1] == ref_name:
|
||||
return fields[0].decode('ascii', errors='replace')
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
warned_git_configs = set()
|
||||
|
||||
|
||||
def lines_of_git_config(lines):
|
||||
"""
|
||||
the lines as git takes them: a `\\` at the end of a line makes the next line more of the same value,
|
||||
and a line may be indented by any amount
|
||||
"""
|
||||
whole, quoted = '', False
|
||||
for line in lines:
|
||||
line = line.rstrip('\n')
|
||||
goes_on = False
|
||||
i = 0
|
||||
while i < len(line):
|
||||
if line[i] == '\\':
|
||||
goes_on = i == len(line) - 1
|
||||
i += 1
|
||||
elif line[i] == '"':
|
||||
quoted = not quoted
|
||||
elif line[i] in '#;' and not quoted:
|
||||
break
|
||||
i += 1
|
||||
|
||||
if goes_on:
|
||||
whole += line[:-1]
|
||||
else:
|
||||
yield (whole + line).lstrip() + '\n'
|
||||
whole, quoted = '', False
|
||||
|
||||
if whole:
|
||||
yield whole.lstrip() + '\n'
|
||||
|
||||
|
||||
def read_git_config(git_config_path) -> 'configparser.ConfigParser | None':
|
||||
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
|
||||
# a url may hold a `%`, git accepts a key without a value, the file may start with a BOM,
|
||||
# and a value that is not UTF-8 does not make the others unreadable
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None, allow_no_value=True)
|
||||
try:
|
||||
with open(git_config_path, encoding='utf-8-sig', errors='replace') as f:
|
||||
# the parser would take a line that is indented more as more of the value before it
|
||||
config.read_file(lines_of_git_config(f))
|
||||
except (configparser.Error, OSError) as e:
|
||||
if git_config_path not in warned_git_configs:
|
||||
warned_git_configs.add(git_config_path)
|
||||
# the message of a parsing error holds lines of the file, and a url in them can hold a token
|
||||
reason = e.strerror if isinstance(e, OSError) else type(e).__name__
|
||||
logging.warning(f"[ComfyUI-Manager] Cannot read '{git_config_path}': {reason}")
|
||||
return None
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def git_url(fullpath):
|
||||
"""
|
||||
resolve version of unclassified custom node based on remote url in .git/config
|
||||
@@ -43,12 +129,12 @@ def git_url(fullpath):
|
||||
if not os.path.exists(git_config_path):
|
||||
return None
|
||||
|
||||
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read(git_config_path)
|
||||
config = read_git_config(git_config_path)
|
||||
if config is None:
|
||||
return None
|
||||
|
||||
for k, v in config.items():
|
||||
if k.startswith('remote ') and 'url' in v:
|
||||
if k.startswith('remote ') and v.get('url'):
|
||||
if 'Comfy-Org/ComfyUI-Manager' in v['url']:
|
||||
return "https://github.com/ltdrdata/ComfyUI-Manager"
|
||||
return v['url']
|
||||
|
||||
+707
-508
File diff suppressed because it is too large
Load Diff
+75
-50
@@ -4,8 +4,6 @@ Handles migration from legacy paths to new __manager path structure.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import subprocess
|
||||
import configparser
|
||||
|
||||
# Startup notices for notice board
|
||||
@@ -74,20 +72,28 @@ def run_migration_checks(user_dir, manager_files_path):
|
||||
warn_outdated_comfyui()
|
||||
|
||||
|
||||
LEGACY_BACKUP_NAME = '.legacy-manager-backup'
|
||||
|
||||
|
||||
def check_legacy_backup(manager_files_path):
|
||||
"""Check for legacy backup and notify user to verify and remove it.
|
||||
|
||||
This runs on every startup to remind users about pending legacy backup.
|
||||
"""
|
||||
backup_dir = os.path.join(manager_files_path, '.legacy-manager-backup')
|
||||
if not os.path.exists(backup_dir):
|
||||
if not os.path.isdir(manager_files_path):
|
||||
return
|
||||
|
||||
backup_dirs = [os.path.join(manager_files_path, name) for name in sorted(os.listdir(manager_files_path))
|
||||
if name.startswith(LEGACY_BACKUP_NAME)]
|
||||
if not backup_dirs:
|
||||
return
|
||||
|
||||
# Terminal output
|
||||
print("\n" + "-"*70)
|
||||
print("[ComfyUI-Manager] NOTICE: Legacy backup exists")
|
||||
print(" - Your old Manager data was backed up to:")
|
||||
print(f" {backup_dir}")
|
||||
for backup_dir in backup_dirs:
|
||||
print(f" {backup_dir}")
|
||||
print(" - Please verify and remove it when no longer needed.")
|
||||
print("-"*70 + "\n")
|
||||
|
||||
@@ -118,7 +124,7 @@ def check_suspicious_manager(user_dir):
|
||||
if not os.path.exists(config_path):
|
||||
return False
|
||||
|
||||
config = configparser.ConfigParser()
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
config.read(config_path)
|
||||
sec_level = config.get('default', 'security_level', fallback='normal').lower()
|
||||
|
||||
@@ -149,14 +155,14 @@ def warn_outdated_comfyui():
|
||||
# Terminal output
|
||||
print("\n" + "!"*70)
|
||||
print("[ComfyUI-Manager] ERROR: ComfyUI version is outdated!")
|
||||
print(" - Most operations are blocked for security.")
|
||||
print(" - Every operation but the update of ComfyUI is blocked for security.")
|
||||
print(" - ComfyUI update is still allowed.")
|
||||
print(" - Please update ComfyUI to use Manager normally.")
|
||||
print("!"*70 + "\n")
|
||||
|
||||
# Notice board output
|
||||
add_startup_notice(
|
||||
"[Security Alert] ComfyUI outdated. Installations blocked (update allowed).<BR>"
|
||||
"[Security Alert] ComfyUI outdated. Everything but its update is blocked.<BR>"
|
||||
"Update ComfyUI for normal operation.",
|
||||
level='error'
|
||||
)
|
||||
@@ -171,7 +177,6 @@ def migrate_legacy_config(user_dir, manager_files_path):
|
||||
Scenarios:
|
||||
1. Legacy exists, New doesn't exist → Migrate config.ini
|
||||
2. Legacy exists, New exists → First update after upgrade
|
||||
- Run ComfyUI dependency installation
|
||||
- Rename legacy to .backup
|
||||
3. Legacy doesn't exist → No migration needed
|
||||
|
||||
@@ -211,6 +216,7 @@ def migrate_legacy_config(user_dir, manager_files_path):
|
||||
print(f" - New: {new_config}")
|
||||
print(" - Migrating config.ini only (other files are NOT migrated).")
|
||||
print(" - Security level below 'normal' will be raised.")
|
||||
print(" - Settings that permit installs or change the channel are not migrated.")
|
||||
print("-"*70 + "\n")
|
||||
|
||||
_migrate_config_with_security_check(legacy_config, new_config)
|
||||
@@ -229,30 +235,13 @@ def _handle_first_update_migration(user_dir, legacy_dir, manager_files_path):
|
||||
- ComfyUI was updated (now has System User API)
|
||||
- Manager already created __manager on first new run
|
||||
- But legacy directory still exists
|
||||
|
||||
Actions:
|
||||
1. Run ComfyUI dependency installation
|
||||
2. Move legacy to __manager/.legacy-manager-backup
|
||||
"""
|
||||
# Terminal output
|
||||
print("\n" + "-"*70)
|
||||
print("[ComfyUI-Manager] NOTICE: First update after ComfyUI upgrade detected")
|
||||
print(" - Both legacy and new directories exist.")
|
||||
print(" - Running ComfyUI dependency installation...")
|
||||
print("-"*70 + "\n")
|
||||
|
||||
# Run ComfyUI dependency installation
|
||||
# Path: glob/manager_migration.py → glob → comfyui-manager → custom_nodes → ComfyUI
|
||||
try:
|
||||
comfyui_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
|
||||
requirements_path = os.path.join(comfyui_path, 'requirements.txt')
|
||||
if os.path.exists(requirements_path):
|
||||
subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', requirements_path],
|
||||
capture_output=True, check=False)
|
||||
print("[ComfyUI-Manager] ComfyUI dependencies installation completed.")
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] WARNING: Failed to install ComfyUI dependencies: {e}")
|
||||
|
||||
# Move legacy to backup inside __manager
|
||||
_move_legacy_to_backup(legacy_dir, manager_files_path)
|
||||
|
||||
@@ -265,11 +254,13 @@ def _move_legacy_to_backup(legacy_dir, manager_files_path):
|
||||
"""
|
||||
import shutil
|
||||
|
||||
backup_dir = os.path.join(manager_files_path, '.legacy-manager-backup')
|
||||
backup_dir = os.path.join(manager_files_path, LEGACY_BACKUP_NAME)
|
||||
count = 1
|
||||
while os.path.exists(backup_dir):
|
||||
count += 1
|
||||
backup_dir = os.path.join(manager_files_path, f'{LEGACY_BACKUP_NAME}-{count}')
|
||||
|
||||
try:
|
||||
if os.path.exists(backup_dir):
|
||||
shutil.rmtree(backup_dir) # Remove old backup if exists
|
||||
shutil.move(legacy_dir, backup_dir)
|
||||
|
||||
# Terminal output (full paths shown here only)
|
||||
@@ -287,19 +278,34 @@ def _move_legacy_to_backup(legacy_dir, manager_files_path):
|
||||
)
|
||||
return backup_dir
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] WARNING: Failed to backup legacy directory: {e}")
|
||||
copy_failed = isinstance(e, shutil.Error)
|
||||
if copy_failed:
|
||||
shutil.rmtree(backup_dir, ignore_errors=True)
|
||||
|
||||
print(f"[ComfyUI-Manager] WARNING: Failed to backup legacy directory: {str(e)!r}")
|
||||
add_startup_notice(
|
||||
f"[MIGRATION] Failed to backup legacy directory: {e}",
|
||||
"[MIGRATION] Failed to backup legacy directory. See terminal for details.",
|
||||
level='warning'
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
# The settings that are carried over from config.ini of the legacy path. That file could be written
|
||||
# through ComfyUI's /userdata, so a setting that permits an install or changes where Manager
|
||||
# fetches from, and one that is not known here, is left behind.
|
||||
MIGRATED_SETTINGS = {
|
||||
'security_level', 'network_mode', 'db_mode', 'preview_method', 'share_option', 'component_policy',
|
||||
'update_policy', 'use_uv', 'file_logging', 'always_lazy_install', 'default_cache_as_channel_url',
|
||||
'model_download_by_agent', 'downgrade_blacklist', 'windows_selector_event_loop_policy',
|
||||
}
|
||||
|
||||
VALUES_WRITTEN_BY_DEFAULT = {'false', '', 'https://raw.githubusercontent.com/ltdrdata/comfyui-manager/main'}
|
||||
|
||||
|
||||
def _migrate_config_with_security_check(legacy_path, new_path):
|
||||
"""Migrate legacy config, raising security level only if below default."""
|
||||
config = configparser.ConfigParser()
|
||||
legacy = configparser.ConfigParser(interpolation=None)
|
||||
try:
|
||||
config.read(legacy_path)
|
||||
legacy.read(legacy_path)
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] WARNING: Failed to parse config.ini: {e}")
|
||||
print(" - Creating fresh config with default settings.")
|
||||
@@ -309,6 +315,27 @@ def _migrate_config_with_security_check(legacy_path, new_path):
|
||||
)
|
||||
return # Skip migration, let Manager create fresh config
|
||||
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
if 'default' in legacy:
|
||||
settings = dict(legacy.items('default'))
|
||||
config['default'] = {key: value for key, value in settings.items() if key in MIGRATED_SETTINGS}
|
||||
not_migrated = sorted(key for key, value in settings.items()
|
||||
if key not in MIGRATED_SETTINGS and value.lower() not in VALUES_WRITTEN_BY_DEFAULT)
|
||||
|
||||
if not_migrated:
|
||||
print("\n" + "="*70)
|
||||
print("[ComfyUI-Manager] WARNING: Settings not migrated")
|
||||
print(f" - {not_migrated!r}")
|
||||
print(" - The legacy config.ini was not protected, so these are back at their defaults.")
|
||||
print(f" - Set them again in {new_path} if you need them.")
|
||||
print("="*70 + "\n")
|
||||
|
||||
add_startup_notice(
|
||||
f"[MIGRATION] Settings of the legacy config.ini that were not migrated: {len(not_migrated)}.<BR>"
|
||||
"That file was not protected, so they are back at their defaults. See terminal for details.",
|
||||
level='warning'
|
||||
)
|
||||
|
||||
# Security level hierarchy: strong > normal > normal- > weak
|
||||
# Default is 'normal', only raise if below default
|
||||
if 'default' in config:
|
||||
@@ -331,26 +358,24 @@ def _migrate_config_with_security_check(legacy_path, new_path):
|
||||
"To prevent unauthorized remote access.",
|
||||
level='warning'
|
||||
)
|
||||
elif current_level not in ('strong', 'normal'):
|
||||
config['default']['security_level'] = 'normal'
|
||||
|
||||
print("\n" + "="*70)
|
||||
print("[ComfyUI-Manager] WARNING: Security level adjusted")
|
||||
print(f" - Previous: {current_level!r} is not a security level → New: 'normal'")
|
||||
print("="*70 + "\n")
|
||||
|
||||
add_startup_notice(
|
||||
"[MIGRATION] The security level of the legacy config.ini was not a security level.<BR>"
|
||||
"It is back at 'normal'. See terminal for details.",
|
||||
level='warning'
|
||||
)
|
||||
else:
|
||||
print(f" - Security level: '{current_level}' (no change needed)")
|
||||
print(f" - Security level: {current_level!r} (no change needed)")
|
||||
|
||||
# Ensure directory exists
|
||||
os.makedirs(os.path.dirname(new_path), exist_ok=True)
|
||||
|
||||
with open(new_path, 'w') as f:
|
||||
config.write(f)
|
||||
|
||||
|
||||
def force_security_level_if_needed(config_dict):
|
||||
"""Force security level to 'strong' if on old ComfyUI.
|
||||
|
||||
Args:
|
||||
config_dict: Configuration dictionary to modify in-place
|
||||
|
||||
Returns:
|
||||
bool: True if security level was forced
|
||||
"""
|
||||
if not has_system_user_api():
|
||||
config_dict['security_level'] = 'strong'
|
||||
return True
|
||||
return False
|
||||
|
||||
+262
-173
@@ -34,7 +34,7 @@ comfy_ui_hash = "-"
|
||||
comfyui_tag = None
|
||||
|
||||
SECURITY_MESSAGE_MIDDLE_OR_BELOW = "ERROR: To use this action, security_level must be any value other than 'strong' (allowed: normal, normal-, weak). security_level is read once at ComfyUI startup, so changing it needs a restart, done with the server down: STOP ComfyUI, edit config.ini, then start it again. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. To download this model, set security_level to 'weak' - or to 'normal-' if ComfyUI is listening on a loopback address (--listen 127.0.0.1 or ::1). Both security_level and the listen address are read once at ComfyUI startup, so changing either needs a restart, done with the server down: stop ComfyUI, edit config.ini, then start it again."
|
||||
SECURITY_MESSAGE_FLAG_GIT_URL = "ERROR: This action requires BOTH: (1) 'allow_git_url_install = true' in config.ini ([default] section), AND (2) ComfyUI launched with a loopback --listen (127.0.0.1 or ::1) - currently listening on {listen}. BOTH values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again. Both are independent of security_level. Reference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
@@ -125,6 +125,9 @@ model_dir_name_map = {
|
||||
|
||||
|
||||
def is_allowed_security_level(level):
|
||||
if not manager_migration.has_system_user_api():
|
||||
return False
|
||||
|
||||
if level == 'block':
|
||||
return False
|
||||
elif level == 'high':
|
||||
@@ -140,7 +143,7 @@ def is_allowed_security_level(level):
|
||||
|
||||
async def get_risky_level(files, pip_packages):
|
||||
json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
|
||||
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main')
|
||||
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url=core.DEFAULT_CHANNEL)
|
||||
|
||||
all_urls = set()
|
||||
for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
|
||||
@@ -204,7 +207,6 @@ core.comfy_path = os.path.dirname(folder_paths.__file__)
|
||||
core.js_path = os.path.join(core.comfy_path, "web", "extensions")
|
||||
|
||||
local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
|
||||
local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
|
||||
local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "custom-node-list.json")
|
||||
local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
|
||||
|
||||
@@ -237,13 +239,24 @@ else:
|
||||
)
|
||||
|
||||
|
||||
ALLOWED_COMPONENT_POLICIES = ('workflow', 'higher', 'mine')
|
||||
ALLOWED_UPDATE_POLICIES = ('stable-comfyui', 'nightly-comfyui')
|
||||
ALLOWED_DB_MODES = ('cache', 'local', 'remote')
|
||||
|
||||
|
||||
def set_component_policy(mode):
|
||||
if mode not in ALLOWED_COMPONENT_POLICIES:
|
||||
raise ValueError(f"Invalid component_policy {mode!r}; must be one of {ALLOWED_COMPONENT_POLICIES}")
|
||||
core.get_config()['component_policy'] = mode
|
||||
|
||||
def set_update_policy(mode):
|
||||
if mode not in ALLOWED_UPDATE_POLICIES:
|
||||
raise ValueError(f"Invalid update_policy {mode!r}; must be one of {ALLOWED_UPDATE_POLICIES}")
|
||||
core.get_config()['update_policy'] = mode
|
||||
|
||||
def set_db_mode(mode):
|
||||
if mode not in ALLOWED_DB_MODES:
|
||||
raise ValueError(f"Invalid db_mode {mode!r}; must be one of {ALLOWED_DB_MODES}")
|
||||
core.get_config()['db_mode'] = mode
|
||||
|
||||
def print_comfyui_version():
|
||||
@@ -303,18 +316,8 @@ def print_comfyui_version():
|
||||
logging.info("### ComfyUI Revision: UNKNOWN (The currently installed ComfyUI is not a Git repository)")
|
||||
|
||||
|
||||
core.setup_git_executable()
|
||||
print_comfyui_version()
|
||||
core.check_invalid_nodes()
|
||||
|
||||
|
||||
def setup_environment():
|
||||
git_exe = core.get_config()['git_exe']
|
||||
|
||||
if git_exe != '':
|
||||
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
|
||||
|
||||
|
||||
setup_environment()
|
||||
|
||||
# Expand Server api
|
||||
|
||||
@@ -339,54 +342,16 @@ def security_403_response(flag_token=None):
|
||||
return web.json_response({"error": "security_level"}, status=403)
|
||||
|
||||
|
||||
# CORS "simple request" Content-Type set per Fetch spec §3.2.3. Browsers send
|
||||
# <form method=POST> submissions with one of these three MIME types and do NOT
|
||||
# trigger a CORS preflight, so a malicious cross-origin page can silently POST
|
||||
# into state-changing endpoints if we only gate on HTTP method. Blocking these
|
||||
# three Content-Types on no-body mutation endpoints forces any non-same-origin
|
||||
# POST to use a non-simple Content-Type (e.g. application/json), which triggers
|
||||
# a preflight that this server rejects by not advertising an Access-Control-
|
||||
# Allow-Origin response.
|
||||
_SIMPLE_FORM_CONTENT_TYPES = frozenset({
|
||||
'application/x-www-form-urlencoded',
|
||||
'multipart/form-data',
|
||||
'text/plain',
|
||||
})
|
||||
|
||||
|
||||
def _reject_simple_form_content_type(request):
|
||||
"""Reject Content-Types that enable preflight-less <form method=POST> CSRF.
|
||||
|
||||
Applied ONLY to POST handlers that act before consuming a request body:
|
||||
the ones that take no body (e.g., /snapshot/save,
|
||||
/manager/queue/{reset,start,update_comfyui}, /manager/reboot) and
|
||||
/manager/queue/update_all, which writes the autosave snapshot before it
|
||||
reads its body. These are vulnerable to cross-origin <form method=POST>
|
||||
attacks because the handler acts without parsing any body —
|
||||
the attacker needs no ability to forge a valid payload, only to point a
|
||||
hidden form at the URL.
|
||||
|
||||
Handlers that read a body via ``await request.json()`` before doing
|
||||
anything else are NOT gated here: their cross-origin protection is
|
||||
ComfyUI's origin middleware, not this gate.
|
||||
|
||||
DO NOT add this gate to handlers that read the body first — UX-breaking.
|
||||
DO NOT remove this gate from the handlers above — this is the bypass vector.
|
||||
|
||||
aiohttp's ``request.content_type`` normalizes the header (lower-cases,
|
||||
strips parameters), so ``multipart/form-data; boundary=----X`` is compared
|
||||
as ``multipart/form-data``.
|
||||
|
||||
Returns:
|
||||
web.Response(status=400) when the request has a simple-form
|
||||
Content-Type that must be rejected. None when the request is allowed
|
||||
to proceed (no Content-Type, application/json, or any non-simple
|
||||
Content-Type).
|
||||
def _reject_non_json_content_type(request):
|
||||
"""A page of another origin can make a browser send a POST without a CORS
|
||||
preflight: as a form, or with no Content-Type at all, with or without a body.
|
||||
``request.json()`` parses a body whatever its Content-Type. The page cannot
|
||||
send application/json without a preflight.
|
||||
"""
|
||||
if request.content_type in _SIMPLE_FORM_CONTENT_TYPES:
|
||||
if request.content_type != 'application/json':
|
||||
return web.Response(
|
||||
status=400,
|
||||
text='Invalid Content-Type for this endpoint. Use application/json or omit body.',
|
||||
text='Invalid Content-Type for this endpoint. Use application/json.',
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -453,34 +418,6 @@ def get_model_path(data, show_log=False):
|
||||
return os.path.join(base_model, data['filename'])
|
||||
|
||||
|
||||
def check_state_of_git_node_pack(node_packs, do_fetch=False, do_update_check=True, do_update=False):
|
||||
if do_fetch:
|
||||
print("Start fetching...", end="")
|
||||
elif do_update:
|
||||
print("Start updating...", end="")
|
||||
elif do_update_check:
|
||||
print("Start update check...", end="")
|
||||
|
||||
def process_custom_node(item):
|
||||
core.check_state_of_git_node_pack_single(item, do_fetch, do_update_check, do_update)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(4) as executor:
|
||||
for k, v in node_packs.items():
|
||||
if v.get('active_version') in ['unknown', 'nightly']:
|
||||
executor.submit(process_custom_node, v)
|
||||
|
||||
if do_fetch:
|
||||
print("\x1b[2K\rFetching done.")
|
||||
elif do_update:
|
||||
update_exists = any(item.get('updatable', False) for item in node_packs.values())
|
||||
if update_exists:
|
||||
print("\x1b[2K\rUpdate done.")
|
||||
else:
|
||||
print("\x1b[2K\rAll extensions are already up-to-date.")
|
||||
elif do_update_check:
|
||||
print("\x1b[2K\rUpdate check done.")
|
||||
|
||||
|
||||
def nickname_filter(json_obj):
|
||||
preemptions_map = {}
|
||||
|
||||
@@ -514,6 +451,11 @@ nodepack_result = {}
|
||||
model_result = {}
|
||||
tasks_in_progress = set()
|
||||
task_worker_lock = threading.Lock()
|
||||
update_check_done = threading.Event()
|
||||
update_check_done.set()
|
||||
update_check_lock = threading.Lock()
|
||||
update_check_paths = {}
|
||||
update_check_ui_ids = set()
|
||||
|
||||
async def task_worker():
|
||||
global task_queue
|
||||
@@ -557,7 +499,7 @@ async def task_worker():
|
||||
res = core.unified_manager.unified_update(node_name, node_ver)
|
||||
|
||||
if res.ver == 'unknown':
|
||||
url = core.unified_manager.unknown_active_nodes[node_name][0]
|
||||
url = core.unified_manager.unknown_active_nodes.get(node_name, (None,))[0]
|
||||
try:
|
||||
title = os.path.basename(url)
|
||||
except Exception:
|
||||
@@ -582,7 +524,7 @@ async def task_worker():
|
||||
return base_res
|
||||
|
||||
base_res['msg'] = res.msg or f"An error occurred while updating '{node_name}'."
|
||||
logging.error(f"\nERROR: An error occurred while updating '{node_name}'. (res.result={res.result}, res.action={res.action})")
|
||||
logging.error(f"\nERROR: An error occurred while updating '{node_name}': {res.msg} (res.result={res.result}, res.action={res.action})")
|
||||
return base_res
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
@@ -655,9 +597,10 @@ async def task_worker():
|
||||
try:
|
||||
res = core.unified_manager.unified_disable(node_name, is_unknown)
|
||||
|
||||
if res:
|
||||
if res.result:
|
||||
return 'success'
|
||||
|
||||
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
@@ -733,6 +676,10 @@ async def task_worker():
|
||||
kind, item = task_queue.get()
|
||||
tasks_in_progress.add((kind, item[0]))
|
||||
|
||||
# a check fetches the repositories of the nodepacks, which a model download and an update of ComfyUI do not touch
|
||||
if kind not in ('install-model', 'update-comfyui'):
|
||||
update_check_done.wait()
|
||||
|
||||
try:
|
||||
if kind in ('install', 'reinstall'):
|
||||
msg = await do_install(item, kind)
|
||||
@@ -821,32 +768,18 @@ async def fetch_customnode_mappings(request):
|
||||
|
||||
@routes.post("/customnode/fetch_updates")
|
||||
async def fetch_updates(request):
|
||||
try:
|
||||
json_data = await request.json()
|
||||
mode = json_data.get("mode", "default")
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if mode == "local":
|
||||
channel = 'local'
|
||||
else:
|
||||
channel = core.get_config()['channel_url']
|
||||
|
||||
await core.unified_manager.reload(mode)
|
||||
await core.unified_manager.get_custom_nodes(channel, mode)
|
||||
|
||||
res = core.unified_manager.fetch_or_pull_git_repo(is_pull=False)
|
||||
|
||||
for x in res['failed']:
|
||||
logging.error(f"FETCH FAILED: {x}")
|
||||
|
||||
logging.info("\nDone.")
|
||||
|
||||
if len(res['updated']) > 0:
|
||||
return web.Response(status=201)
|
||||
|
||||
return web.Response(status=200)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return web.Response(status=400)
|
||||
return web.json_response(
|
||||
{
|
||||
"error": "This endpoint has been deprecated",
|
||||
"message": "Repository fetching is no longer supported. Please ask for a check with /customnode/check_update.",
|
||||
"deprecated": True,
|
||||
},
|
||||
status=410,
|
||||
)
|
||||
|
||||
@routes.get("/customnode/get_node_types_in_workflows")
|
||||
async def get_node_types_in_workflows(request):
|
||||
@@ -931,9 +864,7 @@ async def get_node_types_in_workflows(request):
|
||||
|
||||
@routes.post("/manager/queue/update_all")
|
||||
async def update_all(request):
|
||||
# Keep this gate first: a form POST is refused before this handler does
|
||||
# anything. The autosave snapshot below is written before the body is read.
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -973,6 +904,9 @@ async def update_all(request):
|
||||
if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
|
||||
continue
|
||||
|
||||
if v[1] in core.unified_manager.invalid_installations:
|
||||
continue
|
||||
|
||||
update_item = k, k, 'unknown'
|
||||
task_queue.put(("update-main", update_item))
|
||||
|
||||
@@ -1060,16 +994,79 @@ async def installed_list(request):
|
||||
return web.json_response(res, content_type='application/json')
|
||||
|
||||
|
||||
@routes.post("/customnode/check_update")
|
||||
async def check_update(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
mode = json_data["mode"]
|
||||
ui_id = json_data["ui_id"]
|
||||
|
||||
if mode == "local":
|
||||
channel = 'local'
|
||||
else:
|
||||
channel = core.get_config()['channel_url']
|
||||
|
||||
paths = {}
|
||||
for k, v in (await core.get_unified_total_nodes(channel, mode, 'cache')).items():
|
||||
if v.get('active_version') == 'unknown':
|
||||
path = core.unified_manager.unknown_active_nodes[k][1]
|
||||
elif v.get('active_version') == 'nightly':
|
||||
path = core.unified_manager.active_nodes[k][1]
|
||||
else:
|
||||
continue
|
||||
|
||||
if path not in core.unified_manager.invalid_installations:
|
||||
paths[k] = path
|
||||
|
||||
def check():
|
||||
fetched = 0
|
||||
updatable = []
|
||||
|
||||
def on_fetched(done_count):
|
||||
PromptServer.instance.send_sync("cm-check-update",
|
||||
{'status': 'in_progress', 'done_count': fetched + done_count, 'total_count': len(update_check_paths)})
|
||||
|
||||
while True:
|
||||
with update_check_lock:
|
||||
added = dict(list(update_check_paths.items())[fetched:])
|
||||
if updatable is None or not added:
|
||||
# under the lock: a request is added to this check, or starts the next one
|
||||
ui_ids = list(update_check_ui_ids)
|
||||
update_check_done.set()
|
||||
break
|
||||
|
||||
try:
|
||||
updatable += core.fetch_git_node_packs(added, on_fetched)
|
||||
fetched += len(added)
|
||||
except Exception:
|
||||
# the pages that wait are told that the check failed
|
||||
traceback.print_exc()
|
||||
updatable = None
|
||||
|
||||
PromptServer.instance.send_sync("cm-check-update", {'status': 'done', 'updatable': updatable, 'ui_ids': ui_ids})
|
||||
|
||||
# a check that runs fetches these too, and its result names the requests that it answers
|
||||
with update_check_lock:
|
||||
if update_check_done.is_set():
|
||||
threading.Thread(target=check).start()
|
||||
update_check_done.clear()
|
||||
update_check_paths.clear()
|
||||
update_check_ui_ids.clear()
|
||||
|
||||
update_check_paths.update(paths)
|
||||
update_check_ui_ids.add(ui_id)
|
||||
|
||||
return web.json_response({})
|
||||
|
||||
|
||||
@routes.get("/customnode/getlist")
|
||||
async def fetch_customnode_list(request):
|
||||
"""
|
||||
provide unified custom node list
|
||||
"""
|
||||
if request.rel_url.query.get("skip_update", '').lower() == "true":
|
||||
skip_update = True
|
||||
else:
|
||||
skip_update = False
|
||||
|
||||
if request.rel_url.query["mode"] == "local":
|
||||
channel = 'local'
|
||||
else:
|
||||
@@ -1082,8 +1079,6 @@ async def fetch_customnode_list(request):
|
||||
core.populate_github_stats(node_packs, await json_obj_github)
|
||||
core.populate_favorites(node_packs, await json_obj_extras)
|
||||
|
||||
check_state_of_git_node_pack(node_packs, not skip_update, do_update_check=not skip_update)
|
||||
|
||||
for v in node_packs.values():
|
||||
populate_markdown(v)
|
||||
|
||||
@@ -1102,21 +1097,6 @@ async def fetch_customnode_list(request):
|
||||
return web.json_response(result, content_type='application/json')
|
||||
|
||||
|
||||
@routes.get("/customnode/alternatives")
|
||||
async def fetch_customnode_alternatives(request):
|
||||
alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
|
||||
|
||||
res = {}
|
||||
|
||||
for item in alter_json['items']:
|
||||
populate_markdown(item)
|
||||
res[item['id']] = item
|
||||
|
||||
res = core.map_to_unified_keys(res)
|
||||
|
||||
return web.json_response(res, content_type='application/json')
|
||||
|
||||
|
||||
def check_model_installed(json_obj):
|
||||
def is_exists(model_dir_name, filename, url):
|
||||
if filename == '<huggingface>':
|
||||
@@ -1204,6 +1184,10 @@ def get_safe_snapshot_path(target):
|
||||
|
||||
@routes.post("/snapshot/remove")
|
||||
async def remove_snapshot(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
|
||||
return security_403_response()
|
||||
@@ -1227,8 +1211,12 @@ async def remove_snapshot(request):
|
||||
|
||||
@routes.post("/snapshot/restore")
|
||||
async def restore_snapshot(request):
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('high'):
|
||||
logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
|
||||
return security_403_response()
|
||||
|
||||
try:
|
||||
@@ -1266,7 +1254,7 @@ async def get_current_snapshot_api(request):
|
||||
|
||||
@routes.post("/snapshot/save")
|
||||
async def save_snapshot(request):
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
try:
|
||||
@@ -1297,7 +1285,7 @@ def unzip_install(files):
|
||||
|
||||
os.remove(temp_filename)
|
||||
except Exception as e:
|
||||
logging.error(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
|
||||
logging.error(f"Install(unzip) error: {url} / {e}")
|
||||
return False
|
||||
|
||||
logging.info("Installation was successful.")
|
||||
@@ -1319,7 +1307,7 @@ def copy_install(files, js_path_name=None):
|
||||
download_url(url, path, filename)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Install(copy) error: {url} / {e}", file=sys.stderr)
|
||||
logging.error(f"Install(copy) error: {url} / {e}")
|
||||
return False
|
||||
|
||||
logging.info("Installation was successful.")
|
||||
@@ -1340,7 +1328,7 @@ def copy_uninstall(files, js_path_name='.'):
|
||||
elif os.path.exists(file_path + ".disabled"):
|
||||
os.remove(file_path + ".disabled")
|
||||
except Exception as e:
|
||||
logging.error(f"Uninstall(copy) error: {url} / {e}", file=sys.stderr)
|
||||
logging.error(f"Uninstall(copy) error: {url} / {e}")
|
||||
return False
|
||||
|
||||
logging.info("Uninstallation was successful.")
|
||||
@@ -1371,7 +1359,7 @@ def copy_set_active(files, is_disable, js_path_name='.'):
|
||||
os.rename(current_name, new_name)
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"{action_name}(copy) error: {url} / {e}", file=sys.stderr)
|
||||
logging.error(f"{action_name}(copy) error: {url} / {e}")
|
||||
|
||||
return False
|
||||
|
||||
@@ -1408,6 +1396,10 @@ async def get_disabled_versions(request):
|
||||
|
||||
@routes.post("/customnode/import_fail_info")
|
||||
async def import_fail_info(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
if 'cnr_id' in json_data:
|
||||
@@ -1430,7 +1422,7 @@ async def reinstall_custom_node(request):
|
||||
|
||||
@routes.post("/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
global task_queue
|
||||
@@ -1459,6 +1451,10 @@ async def install_custom_node(request):
|
||||
|
||||
|
||||
async def _queue_node_install(request, operation):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
@@ -1476,7 +1472,10 @@ async def _queue_node_install(request, operation):
|
||||
if json_data['version'] != 'unknown' and selected_version != 'unknown':
|
||||
if skip_post_install:
|
||||
if cnr_id in core.unified_manager.nightly_inactive_nodes or cnr_id in core.unified_manager.cnr_inactive_nodes:
|
||||
core.unified_manager.unified_enable(cnr_id)
|
||||
res = core.unified_manager.unified_enable(cnr_id)
|
||||
if not res.result:
|
||||
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
|
||||
return web.Response(status=400, text=res.msg)
|
||||
# Mirror the pair of events (in_progress then done) that the async
|
||||
# task_worker normally emits for queued operations. The in_progress
|
||||
# event is what sets item.restart=true on the client row so the
|
||||
@@ -1550,7 +1549,7 @@ task_worker_thread:threading.Thread = None
|
||||
|
||||
@routes.post("/manager/queue/start")
|
||||
async def queue_start(request):
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
global nodepack_result
|
||||
@@ -1571,6 +1570,10 @@ async def queue_start(request):
|
||||
|
||||
@routes.post("/manager/queue/fix")
|
||||
async def fix_custom_node(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_GENERAL)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
@@ -1593,20 +1596,22 @@ async def fix_custom_node(request):
|
||||
|
||||
@routes.post("/customnode/install/git_url")
|
||||
async def install_custom_node_git_url(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_dedicated_install_allowed(core.get_config()['allow_git_url_install'], args.listen):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(listen=args.listen))
|
||||
return security_403_response(flag_token='allow_git_url_install')
|
||||
|
||||
# Read the body as JSON (not raw text): a cross-origin <form method=POST>
|
||||
# cannot forge an application/json body without a CORS preflight, which this
|
||||
# server does not answer — same body-handler convention as every other
|
||||
# request.json() route (see _reject_simple_form_content_type docstring).
|
||||
# A malformed body or a missing 'url' is a client error (400), not a 500:
|
||||
# don't let JSONDecodeError/KeyError bubble up as a server fault.
|
||||
# A malformed body, a missing 'url' or one that is not a string is a client
|
||||
# error (400), not a 500: don't let it bubble up as a server fault.
|
||||
try:
|
||||
json_data = await request.json()
|
||||
url = json_data['url']
|
||||
except (KeyError, ValueError):
|
||||
except (KeyError, TypeError, ValueError):
|
||||
url = None
|
||||
if not isinstance(url, str):
|
||||
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'url' field")
|
||||
res = await core.gitclone_install(url)
|
||||
|
||||
@@ -1623,17 +1628,20 @@ async def install_custom_node_git_url(request):
|
||||
|
||||
@routes.post("/customnode/install/pip")
|
||||
async def install_custom_node_pip(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_dedicated_install_allowed(core.get_config()['allow_pip_install'], args.listen):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_PIP.format(listen=args.listen))
|
||||
return security_403_response(flag_token='allow_pip_install')
|
||||
|
||||
# JSON body (not raw text) for the same preflight-forcing reason as
|
||||
# /customnode/install/git_url above; malformed body or missing 'packages'
|
||||
# is a 400, not a 500.
|
||||
try:
|
||||
json_data = await request.json()
|
||||
packages = json_data['packages']
|
||||
except (KeyError, ValueError):
|
||||
except (KeyError, TypeError, ValueError):
|
||||
packages = None
|
||||
if not isinstance(packages, str):
|
||||
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'packages' field")
|
||||
core.pip_install(packages.split(' '))
|
||||
|
||||
@@ -1642,6 +1650,10 @@ async def install_custom_node_pip(request):
|
||||
|
||||
@routes.post("/manager/queue/uninstall")
|
||||
async def uninstall_custom_node(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
@@ -1665,6 +1677,10 @@ async def uninstall_custom_node(request):
|
||||
|
||||
@routes.post("/manager/queue/update")
|
||||
async def update_custom_node(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
@@ -1686,7 +1702,7 @@ async def update_custom_node(request):
|
||||
|
||||
@routes.post("/manager/queue/update_comfyui")
|
||||
async def update_comfyui(request):
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
|
||||
@@ -1700,27 +1716,39 @@ async def comfyui_versions(request):
|
||||
res, current, latest = core.get_comfyui_versions()
|
||||
return web.json_response({'versions': res, 'current': current}, status=200, content_type='application/json')
|
||||
except Exception as e:
|
||||
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
|
||||
logging.error(f"ComfyUI update fail: {e}")
|
||||
|
||||
return web.Response(status=400)
|
||||
|
||||
|
||||
@routes.post("/comfyui_manager/comfyui_switch_version")
|
||||
async def comfyui_switch_version(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
if "ver" in json_data:
|
||||
if core.is_comfyui_downgrade(json_data['ver']) and not is_allowed_security_level('high'):
|
||||
logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
|
||||
return security_403_response()
|
||||
|
||||
core.switch_comfyui(json_data['ver'])
|
||||
|
||||
return web.Response(status=200)
|
||||
except Exception as e:
|
||||
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
|
||||
logging.error(f"ComfyUI update fail: {e}")
|
||||
|
||||
return web.Response(status=400)
|
||||
|
||||
|
||||
@routes.post("/manager/queue/disable")
|
||||
async def disable_node(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
node_id = json_data.get('id')
|
||||
@@ -1756,6 +1784,10 @@ async def check_whitelist_for_model(item):
|
||||
|
||||
@routes.post("/manager/queue/install_model")
|
||||
async def install_model(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -1795,6 +1827,10 @@ async def get_preview_method(request):
|
||||
|
||||
@routes.post("/manager/preview_method")
|
||||
async def set_preview_method_handler(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
if COMFYUI_HAS_PER_QUEUE_PREVIEW:
|
||||
return web.Response(text="DISABLED", status=403)
|
||||
|
||||
@@ -1811,8 +1847,17 @@ async def get_db_mode(request):
|
||||
|
||||
@routes.post("/manager/db_mode")
|
||||
async def set_db_mode_handler(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
set_db_mode(json_data['value'])
|
||||
try:
|
||||
set_db_mode(json_data['value'])
|
||||
except (KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
@@ -1824,8 +1869,17 @@ async def get_component_policy(request):
|
||||
|
||||
@routes.post("/manager/policy/component")
|
||||
async def set_component_policy_handler(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
set_component_policy(json_data['value'])
|
||||
try:
|
||||
set_component_policy(json_data['value'])
|
||||
except (KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
@@ -1837,8 +1891,17 @@ async def get_update_policy(request):
|
||||
|
||||
@routes.post("/manager/policy/update")
|
||||
async def set_update_policy_handler(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
set_update_policy(json_data['value'])
|
||||
try:
|
||||
set_update_policy(json_data['value'])
|
||||
except (KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
@@ -1861,6 +1924,10 @@ async def get_channel_url_list(request):
|
||||
|
||||
@routes.post("/manager/channel_url_list")
|
||||
async def set_channel_url_list(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
channels = core.get_channel_dict()
|
||||
channel_url = channels.get(json_data['value'])
|
||||
@@ -1876,7 +1943,7 @@ async def get_notice(request):
|
||||
path = "/ltdrdata/ltdrdata.github.io/wiki/News"
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=not manager_util.bypass_ssl)) as session:
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=manager_util.aiohttp_connector()) as session:
|
||||
async with session.get(f"https://{url}{path}") as response:
|
||||
if response.status == 200:
|
||||
# html_content = response.read().decode('utf-8')
|
||||
@@ -1956,7 +2023,7 @@ async def get_startup_alerts(request):
|
||||
|
||||
@routes.post("/manager/reboot")
|
||||
def restart(self):
|
||||
resp = _reject_simple_form_content_type(self)
|
||||
resp = _reject_non_json_content_type(self)
|
||||
if resp is not None:
|
||||
return resp
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -1986,6 +2053,10 @@ def restart(self):
|
||||
|
||||
@routes.post("/manager/component/save")
|
||||
async def save_component(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
try:
|
||||
data = await request.json()
|
||||
name = data['name']
|
||||
@@ -2090,22 +2161,40 @@ async def default_cache_update():
|
||||
a = get_cache("custom-node-list.json")
|
||||
b = get_cache("extension-node-map.json")
|
||||
c = get_cache("model-list.json")
|
||||
d = get_cache("alter-list.json")
|
||||
e = get_cache("github-stats.json")
|
||||
d = get_cache("github-stats.json")
|
||||
|
||||
await asyncio.gather(a, b, c, d, e)
|
||||
await asyncio.gather(a, b, c, d)
|
||||
|
||||
if core.get_config()['network_mode'] == 'private':
|
||||
logging.info("[ComfyUI-Manager] The private comfyregistry is not yet supported in `network_mode=private`.")
|
||||
await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
|
||||
else:
|
||||
# load at least once
|
||||
await core.unified_manager.reload('remote', dont_wait=False)
|
||||
await core.unified_manager.get_custom_nodes(channel_url, 'remote')
|
||||
else:
|
||||
await core.unified_manager.reload('remote', dont_wait=False, update_cnr_map=False)
|
||||
|
||||
core.check_invalid_nodes()
|
||||
logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
|
||||
|
||||
|
||||
threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
|
||||
COMFYUI_UPDATE_HANDLERS = {update_comfyui, queue_start, reset_queue, queue_count, get_version, get_notice, get_startup_alerts}
|
||||
|
||||
|
||||
@web.middleware
|
||||
async def serve_only_comfyui_update(request, handler):
|
||||
matched = request.match_info.handler
|
||||
if matched.__module__ in ('manager_server', 'share_3rdparty') and matched not in COMFYUI_UPDATE_HANDLERS:
|
||||
return security_403_response()
|
||||
|
||||
return await handler(request)
|
||||
|
||||
|
||||
if manager_migration.has_system_user_api():
|
||||
threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
|
||||
else:
|
||||
PromptServer.instance.app.middlewares.append(serve_only_comfyui_update)
|
||||
|
||||
if not os.path.exists(core.manager_config_path):
|
||||
core.get_config()
|
||||
|
||||
+699
-25
@@ -2,16 +2,23 @@
|
||||
description:
|
||||
`manager_util` is the lightest module shared across the prestartup_script, main code, and cm-cli of ComfyUI-Manager.
|
||||
"""
|
||||
import csv
|
||||
import sysconfig
|
||||
import importlib.metadata
|
||||
import traceback
|
||||
import ipaddress
|
||||
import socket
|
||||
|
||||
import aiohttp
|
||||
import json
|
||||
import math
|
||||
import threading
|
||||
import os
|
||||
import shutil
|
||||
import contextlib
|
||||
from datetime import datetime
|
||||
import subprocess
|
||||
import tempfile
|
||||
import sys
|
||||
import re
|
||||
import logging
|
||||
@@ -21,6 +28,7 @@ import time
|
||||
from functools import lru_cache
|
||||
from html import escape, unescape
|
||||
from html.entities import html5
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
|
||||
cache_lock = threading.Lock()
|
||||
@@ -230,12 +238,17 @@ def is_file_created_within_one_day(file_path):
|
||||
return time_difference <= 86400
|
||||
|
||||
|
||||
def aiohttp_connector():
|
||||
# aiohttp before 3.9.2 reads ssl=True as "do not check", so ssl is passed only to turn the check off
|
||||
return aiohttp.TCPConnector(ssl=False) if bypass_ssl else None
|
||||
|
||||
|
||||
async def get_data(uri, silent=False):
|
||||
if not silent:
|
||||
print(f"FETCH DATA from: {uri}", end="")
|
||||
|
||||
if uri.startswith("http"):
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=not bypass_ssl)) as session:
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp_connector()) as session:
|
||||
headers = {
|
||||
'Cache-Control': 'no-cache',
|
||||
'Pragma': 'no-cache',
|
||||
@@ -458,6 +471,70 @@ def extract_package_as_zip(file_path, extract_path):
|
||||
return None
|
||||
|
||||
|
||||
def is_inside(directory, name):
|
||||
directory = os.path.abspath(directory)
|
||||
try:
|
||||
return os.path.commonpath((directory, os.path.abspath(os.path.join(directory, name)))) == directory
|
||||
except ValueError:
|
||||
# on Windows, a path of another drive
|
||||
return False
|
||||
|
||||
|
||||
def switch_package_files(file_path, path):
|
||||
import zipfile
|
||||
try:
|
||||
with zipfile.ZipFile(file_path, "r") as zip_ref:
|
||||
extracted = zip_ref.namelist()
|
||||
except zipfile.BadZipFile:
|
||||
logging.error(f"File '{file_path}' is not a zip or is corrupted.")
|
||||
return None
|
||||
|
||||
with open(os.path.join(path, '.tracking'), 'r', encoding='utf-8') as f:
|
||||
# as the list is written: a name can start or end with a space
|
||||
prev_files = {line.rstrip('\n') for line in f}
|
||||
root = os.path.abspath(path)
|
||||
garbage = prev_files - set(extracted)
|
||||
garbage = [os.path.abspath(os.path.join(root, x)) for x in garbage if is_inside(root, x)]
|
||||
|
||||
for x in garbage:
|
||||
try:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
except OSError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] A file of the old version is left: {e}")
|
||||
|
||||
folders = set()
|
||||
for x in garbage:
|
||||
while len(x) > len(root):
|
||||
folders.add(x)
|
||||
x = os.path.dirname(x)
|
||||
|
||||
real_root = os.path.realpath(root)
|
||||
|
||||
def reached_without_a_link(x):
|
||||
return os.path.normcase(os.path.realpath(x)) == os.path.normcase(real_root + x[len(root):])
|
||||
|
||||
for x in sorted(folders, key=len, reverse=True):
|
||||
try:
|
||||
if not os.path.isdir(x) or not reached_without_a_link(x):
|
||||
continue
|
||||
|
||||
# the files of a `__pycache__` are caches of the modules that were there, as those of Python and of numba
|
||||
cache = os.path.join(x, '__pycache__')
|
||||
if os.listdir(x) == ['__pycache__'] and reached_without_a_link(cache):
|
||||
for name in os.listdir(cache):
|
||||
os.remove(os.path.join(cache, name))
|
||||
os.rmdir(cache)
|
||||
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
except OSError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] A folder of the old version is left: {e}")
|
||||
|
||||
# after the files are removed: two names can be one file, as names that differ in case alone are on Windows
|
||||
return extract_package_as_zip(file_path, path)
|
||||
|
||||
|
||||
# The functions below import packaging where they use it: prestartup_script imports this module
|
||||
# before its ensure_dependencies() has installed a missing dependency.
|
||||
def normalize_pip_name(name):
|
||||
@@ -470,7 +547,11 @@ def normalize_pip_name(name):
|
||||
|
||||
|
||||
_PIP_LINE_TAIL_PATTERN = re.compile(r'\s[#-]') # a comment or a pip option after the requirement
|
||||
_PIP_COMMENT_PATTERN = re.compile(r'(^|\s)#.*') # as pip reads it: the '#' of a URL fragment starts no comment
|
||||
_PIP_INDEX_OPTIONS = {'--index-url', '--extra-index-url'}
|
||||
_PIP_EDITABLE_PATTERN = re.compile(r'(?:-e\s*|--editable(?:\s+|=))(\S+)') # how pip reads -e and its target
|
||||
_PIP_MALFORMED_PATTERN = re.compile(r'([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\]\s*)?[<>=!~(]')
|
||||
_PIP_URL_PATTERN = re.compile(r'[A-Za-z][A-Za-z0-9+.-]*://')
|
||||
|
||||
|
||||
def parse_pip_spec(spec):
|
||||
@@ -481,7 +562,8 @@ def parse_pip_spec(spec):
|
||||
be parsed has ('?', text); neither can be compared with an installed version. A
|
||||
trailing comment, an environment marker and pip options are ignored.
|
||||
|
||||
Returns (None, False, []) when the line does not name a package: URLs, paths and options.
|
||||
A line that is a URL is a direct reference without a name: (None, False, [('@', url)]).
|
||||
Returns (None, False, []) for the other lines that do not name a package: paths and options.
|
||||
"""
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
|
||||
@@ -493,6 +575,9 @@ def parse_pip_spec(spec):
|
||||
try:
|
||||
requirement = Requirement(text)
|
||||
except InvalidRequirement:
|
||||
if _PIP_URL_PATTERN.match(text):
|
||||
# pip splits a URL from its environment marker at '; '
|
||||
return None, False, [('@', text.split('; ', 1)[0].rstrip())]
|
||||
match = _PIP_MALFORMED_PATTERN.match(text)
|
||||
if match is None:
|
||||
return None, False, []
|
||||
@@ -505,6 +590,54 @@ def parse_pip_spec(spec):
|
||||
return name, extras, [(specifier.operator, specifier.version) for specifier in requirement.specifier]
|
||||
|
||||
|
||||
def installer_args(requirement):
|
||||
"""The arguments of a requirement as the installer in use takes them.
|
||||
|
||||
uv installs an editable from a local folder only: where the arguments are `-e`
|
||||
and a git URL, uv gets the URL alone, as a normal install, and a line says so.
|
||||
"""
|
||||
if requirement[0] == '-e' and requirement[1].startswith('git+') and 'uv' in get_pip_cmd(force_uv=use_uv):
|
||||
print(f"[ComfyUI-Manager] uv installs an editable from a local folder only: '{requirement[1]}' is installed without -e")
|
||||
return requirement[1:]
|
||||
return requirement
|
||||
|
||||
|
||||
def pip_install_args(line, overrides):
|
||||
"""The arguments that a line of requirements.txt gives to `pip install`, or [] if it has none.
|
||||
|
||||
Each line is installed on its own, and an option applies to its line only. The
|
||||
comment is left out as pip leaves it out, so a URL keeps its fragment. A line that
|
||||
`overrides` (pip_overrides.json) names is replaced. An editable requirement
|
||||
(`-e path`, `--editable=path`) is `-e` and its target. A requirement followed by
|
||||
index options, such as `--extra-index-url URL`, gives the requirement and the
|
||||
options; any other line with a requirement is one argument, with the spaces of an
|
||||
environment marker. Where `-e` and a git URL are two arguments, uv gets the URL
|
||||
alone: it installs an editable from a local folder only. A line that starts with
|
||||
another option than `-e`, such as `-r other.txt`, names no requirement and gives
|
||||
none.
|
||||
"""
|
||||
text = _PIP_COMMENT_PATTERN.sub('', line).strip()
|
||||
if text in overrides:
|
||||
print(f"[ComfyUI-Manager] '{text}' is remapped to '{overrides[text]}'")
|
||||
text = overrides[text]
|
||||
if not text:
|
||||
return []
|
||||
editable = _PIP_EDITABLE_PATTERN.match(text)
|
||||
if editable is not None:
|
||||
requirement, options = ['-e', editable.group(1)], text[editable.end():].split()
|
||||
elif text.startswith('-'):
|
||||
print(f"[ComfyUI-Manager] skip '{text}': the Manager installs requirements one row at a time and does not apply this row")
|
||||
return []
|
||||
else:
|
||||
tail = _PIP_LINE_TAIL_PATTERN.search(text)
|
||||
if tail is None:
|
||||
return [text]
|
||||
requirement, options = [text[:tail.start()].rstrip()], text[tail.start():].split()
|
||||
if len(options) % 2 == 0 and set(options[::2]) <= _PIP_INDEX_OPTIONS:
|
||||
return [*installer_args(requirement), *options]
|
||||
return [text]
|
||||
|
||||
|
||||
def _upper_bound_state(operator, version, installed):
|
||||
"""Where an installed version sits against one upper-bound clause.
|
||||
|
||||
@@ -725,6 +858,155 @@ def pip_block_reason(spec, blacklist, downgrade_blacklist):
|
||||
return 'downgrade blacklisted' if blocked else None
|
||||
|
||||
|
||||
def installed_from(url, name=None):
|
||||
"""The direct_url.json of the distribution that was installed from the URL of a direct reference, or None.
|
||||
|
||||
A URL gives no name and no version to look up, and pip has to fetch and build it to
|
||||
learn them. pip and uv record where a distribution came from in its direct_url.json
|
||||
(PEP 610), and that record is compared here.
|
||||
|
||||
A VCS URL is met by a distribution from that repository. Without a revision in the
|
||||
URL any commit meets it, and with one the distribution must have been installed with
|
||||
that revision, or be at that commit. The repository is not asked: a branch that has
|
||||
moved on is not followed. Any other URL is met by a distribution from that archive.
|
||||
A distribution from a local directory meets nothing: such a source is edited in
|
||||
place, and pip installs it without a download.
|
||||
|
||||
A record holds the URL without its fragment, and the subdirectory that the fragment
|
||||
names in a key of its own. A git repository is the same with and without '.git'.
|
||||
|
||||
`name` is the normalized name of a requirement that gives one ('name @ url'): only a
|
||||
distribution of that name meets it.
|
||||
|
||||
Only a distribution whose name `get_installed_packages()` lists counts, and only when
|
||||
the distributions of that name agree on the version and on the record. What an install
|
||||
that was cut short leaves behind still has its record: alone its name is not listed,
|
||||
and beside what took its place the two differ, and the installer is left to decide.
|
||||
"""
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
except ValueError:
|
||||
return None
|
||||
vcs, _, scheme = parts.scheme.rpartition('+')
|
||||
path, revision = parts.path, None
|
||||
if vcs and '@' in path:
|
||||
path, revision = path.rsplit('@', 1)
|
||||
paths = [path]
|
||||
if vcs == 'git':
|
||||
paths.append(path[:-4] if path.endswith('.git') else path + '.git')
|
||||
urls = [urlunsplit((scheme, parts.netloc, path, parts.query, '')) for path in paths]
|
||||
subdirectory = re.search(r'(?:^|&)subdirectory=([^&]*)', parts.fragment)
|
||||
subdirectory = subdirectory.group(1) if subdirectory else None
|
||||
|
||||
listed = get_installed_packages()
|
||||
records, said = {}, {}
|
||||
for distribution in importlib.metadata.distributions():
|
||||
try:
|
||||
metadata = distribution.metadata
|
||||
record = distribution.read_text('direct_url.json')
|
||||
origin = json.loads(record or '{}')
|
||||
except (ValueError, OSError):
|
||||
continue # cut short, or not text; Python 3.15 raises a FileNotFoundError for a folder without METADATA
|
||||
found = normalize_pip_name(metadata.get('Name') or '')
|
||||
said.setdefault(found, set()).add((metadata.get('Version'), record)) # a set: a folder that is on the path twice is read twice
|
||||
if not isinstance(origin, dict) or origin.get('url') not in urls or origin.get('subdirectory') != subdirectory:
|
||||
continue
|
||||
vcs_info = origin.get('vcs_info')
|
||||
if isinstance(vcs_info, dict):
|
||||
met = vcs_info.get('vcs') == vcs and revision in (None, vcs_info.get('requested_revision'), vcs_info.get('commit_id'))
|
||||
else:
|
||||
met = vcs_info is None and not vcs and 'archive_info' in origin
|
||||
if met and found in listed and name in (None, found):
|
||||
records.setdefault(found, origin)
|
||||
for found, origin in records.items():
|
||||
if len(said[found]) == 1:
|
||||
return origin
|
||||
return None
|
||||
|
||||
|
||||
def fix_cmd(install_args):
|
||||
"""The pip command with which a fix installs the arguments of a requirement line, from `pip_install_args()`.
|
||||
|
||||
A direct reference is installed again by force, whatever is installed: nothing but
|
||||
its URL says what it should be. That command is run with `reinstall()`. Any other
|
||||
requirement is installed as an install does it.
|
||||
"""
|
||||
cmd = make_pip_cmd(['install', *install_args])
|
||||
clauses = parse_pip_spec(install_args[0])[2]
|
||||
if clauses and clauses[0][0] == '@':
|
||||
# --no-deps: without it every package the distribution needs is installed again as well, torch among them.
|
||||
# The cache is left out: with it uv installs the wheel it has built of the commit before, forced or not, and so
|
||||
# does pip for a name with a commit. uv may link the files to its cache, and keeps none to link to here.
|
||||
uv = 'uv' in cmd[:cmd.index('install')]
|
||||
cmd += ['--force-reinstall', '--no-deps'] + (['--no-cache', '--link-mode', 'copy'] if uv else ['--no-cache-dir'])
|
||||
return cmd
|
||||
|
||||
|
||||
def is_reinstall(cmd):
|
||||
"""Whether the command is a forced install that `fix_cmd()` built."""
|
||||
requirement = pip_install_requirement(cmd)
|
||||
if requirement is None or '--force-reinstall' not in cmd:
|
||||
return False
|
||||
clauses = parse_pip_spec(requirement)[2]
|
||||
return bool(clauses) and clauses[0][0] == '@'
|
||||
|
||||
|
||||
def is_git_remote_usable(url):
|
||||
try:
|
||||
done = subprocess.run(['git', 'ls-remote', url, 'HEAD'], capture_output=True, timeout=30,
|
||||
env={**os.environ, 'GIT_TERMINAL_PROMPT': '0'})
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return done.returncode == 0
|
||||
|
||||
|
||||
def reinstall(cmd, run):
|
||||
"""Fix the URL requirement of a forced install that `fix_cmd()` built, and return the exit code.
|
||||
|
||||
`run(cmd)` runs one command and returns its exit code, or raises CalledProcessError
|
||||
for it as the `run_script` of cm-cli does. What it raised is raised again at the
|
||||
end when the fix has failed.
|
||||
|
||||
The requirement is first installed as an install does it. That brings what the
|
||||
distribution at the URL needs now, which the forced install leaves out, and changes
|
||||
nothing when it cannot be had. Then the forced install puts a clean copy from the
|
||||
URL there. If only the forced install fails, what is installed stays and meets the
|
||||
requirement, so the exit code is 0 and the rest of the pack is fixed.
|
||||
|
||||
A cache is used in one case: the first install fails and the repository does not
|
||||
answer. uv is then asked for the commit that `installed_from()` finds installed, from
|
||||
its cache. pip has no option for that.
|
||||
"""
|
||||
install = cmd.index('install')
|
||||
base, requirement = cmd[:install + 1], cmd[install + 1]
|
||||
name, _, clauses = parse_pip_spec(requirement)
|
||||
raised = []
|
||||
|
||||
def step(command):
|
||||
# flushed: cm-cli lets the command write to this stdout by itself
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {command}", flush=True)
|
||||
try:
|
||||
return run(command)
|
||||
except subprocess.CalledProcessError as error:
|
||||
raised.append(error)
|
||||
return error.returncode
|
||||
|
||||
code = step(base + [requirement])
|
||||
if code == 0:
|
||||
if step(cmd) != 0:
|
||||
print(f"[ComfyUI-Manager] could not install '{requirement}' again by force: what is installed is kept.")
|
||||
return 0
|
||||
|
||||
origin = installed_from(clauses[0][1], name) or {}
|
||||
vcs_info = origin.get('vcs_info')
|
||||
if vcs_info and vcs_info.get('vcs') == 'git' and 'uv' in base and not is_git_remote_usable(origin['url']):
|
||||
subdirectory = f"#subdirectory={origin['subdirectory']}" if 'subdirectory' in origin else ''
|
||||
code = step(base + [f"git+{origin['url']}@{vcs_info.get('commit_id')}{subdirectory}", '--force-reinstall', '--no-deps', '--offline'])
|
||||
if code != 0 and raised:
|
||||
raise raised[0]
|
||||
return code
|
||||
|
||||
|
||||
def pip_install_requirement(cmd):
|
||||
"""Return the requirement of a `pip install` command built by `make_pip_cmd()`, or None.
|
||||
|
||||
@@ -813,9 +1095,21 @@ def parse_requirement_line(line):
|
||||
|
||||
|
||||
torch_torchvision_torchaudio_version_map = {
|
||||
'2.15.0': ('0.29.2', '2.11.*'),
|
||||
'2.14.1': ('0.29.1', '2.11.*'),
|
||||
'2.14.0': ('0.29.0', '2.11.*'),
|
||||
'2.13.0': ('0.28.0', '2.11.*'),
|
||||
'2.12.1': ('0.27.1', '2.11.*'),
|
||||
'2.12.0': ('0.27.0', '2.11.*'),
|
||||
'2.11.0': ('0.26.0', '2.11.*'),
|
||||
'2.10.0': ('0.25.0', '2.10.0'),
|
||||
'2.9.1': ('0.24.1', '2.9.1'),
|
||||
'2.9.0': ('0.24.0', '2.9.0'),
|
||||
'2.8.0': ('0.23.0', '2.8.0'),
|
||||
'2.7.1': ('0.22.1', '2.7.1'),
|
||||
'2.7.0': ('0.22.0', '2.7.0'),
|
||||
'2.6.0': ('0.21.0', '2.6.0'),
|
||||
'2.5.1': ('0.20.0', '2.5.0'),
|
||||
'2.5.1': ('0.20.1', '2.5.1'),
|
||||
'2.5.0': ('0.20.0', '2.5.0'),
|
||||
'2.4.1': ('0.19.1', '2.4.1'),
|
||||
'2.4.0': ('0.19.0', '2.4.0'),
|
||||
@@ -827,19 +1121,19 @@ torch_torchvision_torchaudio_version_map = {
|
||||
'2.1.2': ('0.16.2', '2.1.2'),
|
||||
'2.1.1': ('0.16.1', '2.1.1'),
|
||||
'2.1.0': ('0.16.0', '2.1.0'),
|
||||
'2.0.1': ('0.15.2', '2.0.1'),
|
||||
'2.0.1': ('0.15.2', '2.0.2'),
|
||||
'2.0.0': ('0.15.1', '2.0.0'),
|
||||
}
|
||||
|
||||
|
||||
def torch_rollback(prev):
|
||||
def torch_rollback_by_version_table(prev, packages, options=()):
|
||||
spec = prev.split('+')
|
||||
if len(spec) > 1:
|
||||
platform = spec[1]
|
||||
else:
|
||||
cmd = make_pip_cmd(['install', '--force', 'torch', 'torchvision', 'torchaudio'])
|
||||
cmd = make_pip_cmd(['install', '--force', *packages, *options])
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch to the newest release")
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
logging.error(cmd)
|
||||
return
|
||||
|
||||
torch_ver = StrictVersion(spec[0])
|
||||
@@ -847,21 +1141,350 @@ def torch_rollback(prev):
|
||||
torch_torchvision_torchaudio_ver = torch_torchvision_torchaudio_version_map.get(torch_ver)
|
||||
|
||||
if torch_torchvision_torchaudio_ver is None:
|
||||
cmd = make_pip_cmd(['install', '--pre', 'torch', 'torchvision', 'torchaudio',
|
||||
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
|
||||
cmd = make_pip_cmd(['install', '--pre', *packages,
|
||||
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}", *options])
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch to nightly version")
|
||||
else:
|
||||
torchvision_ver, torchaudio_ver = torch_torchvision_torchaudio_ver
|
||||
cmd = make_pip_cmd(['install', f'torch=={torch_ver}', f'torchvision=={torchvision_ver}', f"torchaudio=={torchaudio_ver}",
|
||||
'--index-url', f"https://download.pytorch.org/whl/{platform}"])
|
||||
versions = {'torch': torch_ver, 'torchvision': torchvision_ver, 'torchaudio': torchaudio_ver}
|
||||
cmd = make_pip_cmd(['install', *[f'{name}=={versions[name]}' for name in packages],
|
||||
'--index-url', f"https://download.pytorch.org/whl/{platform}", *options])
|
||||
logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
|
||||
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
|
||||
|
||||
def _pytorch_index(build, option):
|
||||
from packaging.version import Version
|
||||
|
||||
version = Version(build)
|
||||
if version.is_devrelease:
|
||||
return ['--pre', option, f"https://download.pytorch.org/whl/nightly/{version.local or 'cpu'}"]
|
||||
if version.local is not None:
|
||||
return [option, f"https://download.pytorch.org/whl/{version.local}"]
|
||||
return []
|
||||
|
||||
|
||||
def _installed_version(name):
|
||||
try:
|
||||
return importlib.metadata.version(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
return None
|
||||
|
||||
|
||||
def _recorded_files(name):
|
||||
try:
|
||||
distribution = importlib.metadata.distribution(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
return []
|
||||
# From the RECORD itself: files() leaves out the missing ones from Python 3.12 on
|
||||
return [(distribution.locate_file(row[0]), int(row[2]))
|
||||
for row in csv.reader((distribution.read_text('RECORD') or '').splitlines()) if len(row) == 3 and row[2]]
|
||||
|
||||
|
||||
def _required_here(name, extras=frozenset()):
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
|
||||
found = []
|
||||
for line in importlib.metadata.requires(name) or []:
|
||||
try:
|
||||
requirement = Requirement(line)
|
||||
except InvalidRequirement:
|
||||
continue
|
||||
if requirement.marker is None or any(requirement.marker.evaluate({'extra': extra}) for extra in {*extras, ''}):
|
||||
found.append((normalize_pip_name(requirement.name), set(requirement.extras)))
|
||||
return found
|
||||
|
||||
|
||||
def _size_of_pytorch():
|
||||
extras, todo = {}, [(name, set()) for name in ('torch', 'torchvision', 'torchaudio')]
|
||||
while todo:
|
||||
name, wanted = todo.pop()
|
||||
if _installed_version(name) is None or name in extras and wanted <= extras[name]:
|
||||
continue
|
||||
extras[name] = extras.get(name, set()) | wanted
|
||||
todo += _required_here(name, extras[name])
|
||||
return {name: sum(size for _, size in _recorded_files(name)) for name in extras}
|
||||
|
||||
|
||||
def _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, times_the_size):
|
||||
return int(times_the_size * sum(size for name, size in size_of_pytorch.items()
|
||||
if installed_after.get(name) != installed_before.get(name) or name in overwritten))
|
||||
|
||||
|
||||
def _overwritten(installed_before, installed_after, required_by_torch):
|
||||
# cuDNN, cuSPARSELt, NCCL and NVSHMEM ship one distribution per CUDA version, all writing the same file paths.
|
||||
return {name: installed_after[name] for name in sorted(required_by_torch)
|
||||
if name in installed_after and installed_before.get(name) == installed_after[name]
|
||||
and any(os.path.isfile(file) and os.path.getsize(file) != size for file, size in _recorded_files(name))}
|
||||
|
||||
|
||||
def _incomplete(required_by_torch):
|
||||
return {name: _installed_version(name) for name in sorted(required_by_torch)
|
||||
if any(not os.path.isfile(file) for file, _ in _recorded_files(name))}
|
||||
|
||||
|
||||
# The metadata of a torchvision or torchaudio can fit torch while its native library does not load beside it: a build
|
||||
# for another CUDA version, or the PyPI build beside a CPU torch. torch imports beside a cuDNN older than the one it
|
||||
# was built for; cudnn.version() compares the two without a GPU, and a CPU build has none to compare.
|
||||
_PYTORCH_CHECKS = {
|
||||
'torch': 'import torch; torch.backends.cudnn.version()',
|
||||
'torchvision': 'import torch, torchvision; torchvision.ops.nms(torch.rand(3, 4) * 10, torch.rand(3), 0.5)',
|
||||
'torchaudio': 'import torch, torchaudio.functional as F; F.lowpass_biquad(torch.rand(1, 100), 16000, 300.0)',
|
||||
}
|
||||
|
||||
|
||||
_CHECK_TIME_LIMIT = 300
|
||||
|
||||
# A .pth file or a module can print to the same stdout when Python starts, and can leave its line without an end.
|
||||
_CHECK_LINE = '[ComfyUI-Manager] PyTorch check:'
|
||||
_CHECK_DID_NOT_RUN = None
|
||||
|
||||
|
||||
def _not_working(names):
|
||||
code = f"print({_CHECK_LINE!r}, flush=True)\n" + ''.join(
|
||||
f"try:\n {_PYTORCH_CHECKS[name]}\n print({f'{_CHECK_LINE} {name}'!r}, flush=True)\nexcept Exception:\n"
|
||||
f" pass\n" for name in names)
|
||||
try:
|
||||
printed = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True,
|
||||
timeout=_CHECK_TIME_LIMIT).stdout.splitlines()
|
||||
except subprocess.TimeoutExpired:
|
||||
return _CHECK_DID_NOT_RUN
|
||||
def told(line):
|
||||
return any(found.endswith(line) for found in printed)
|
||||
|
||||
if not told(_CHECK_LINE):
|
||||
return _CHECK_DID_NOT_RUN
|
||||
return [name for name in names if not told(f'{_CHECK_LINE} {name}')]
|
||||
|
||||
|
||||
class _Pip:
|
||||
# Measured: pip holds a wheel in its temporary folder while it writes the files, at the peak 1.7 times the size of
|
||||
# the files. With its cache it holds the wheel there too, at the peak 2.35 times for a CUDA torch for Windows.
|
||||
times_the_size = 2
|
||||
|
||||
@contextlib.contextmanager
|
||||
def environment(self):
|
||||
before = os.environ.get('PIP_NO_CACHE_DIR')
|
||||
os.environ['PIP_NO_CACHE_DIR'] = '1'
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if before is None:
|
||||
del os.environ['PIP_NO_CACHE_DIR']
|
||||
else:
|
||||
os.environ['PIP_NO_CACHE_DIR'] = before
|
||||
|
||||
def install(self, name, build, *options):
|
||||
command = make_pip_cmd(['install', *options, f'{name}==={build}', *_pytorch_index(build, '--extra-index-url')])
|
||||
try:
|
||||
subprocess.check_output(command, universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
return False
|
||||
return True
|
||||
|
||||
@contextlib.contextmanager
|
||||
def putting_back(self, overwritten, torch):
|
||||
# pip installs no distribution of a command again without all the others.
|
||||
pins = [f'{name}=={version}' for name, version in overwritten.items()]
|
||||
with tempfile.TemporaryDirectory() as wheels:
|
||||
if pins:
|
||||
try:
|
||||
subprocess.check_output(make_pip_cmd(['download', '--no-deps', '-d', wheels, *pins,
|
||||
*_pytorch_index(torch, '--extra-index-url')]),
|
||||
universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError(f"{', '.join(pins)} cannot be had")
|
||||
yield []
|
||||
left = [f'{name}=={version}' for name, version in overwritten.items()
|
||||
if _installed_version(name) == version]
|
||||
if left:
|
||||
subprocess.check_output(make_pip_cmd(['install', '--no-deps', '--force-reinstall', '--no-index',
|
||||
'--find-links', wheels, *left]), universal_newlines=True)
|
||||
|
||||
def own_index(self, torch):
|
||||
return _pytorch_index(torch, '--index-url')
|
||||
|
||||
def install_again(self, broken, requirements, torch):
|
||||
# pip joins PIP_EXTRA_INDEX_URL to an index and takes the highest version of all, which can be a build for
|
||||
# another CUDA version.
|
||||
index = _pytorch_index(torch, '--find-links')
|
||||
if index:
|
||||
*pre, _, url = index
|
||||
index = [*pre, '--no-index', *[option for name in broken for option in ('--find-links', f'{url}/{name}/')]]
|
||||
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps',
|
||||
*[requirements[name] for name in broken], *index]),
|
||||
universal_newlines=True)
|
||||
|
||||
def install_files_again(self, name, version, torch):
|
||||
subprocess.check_output(make_pip_cmd(['install', '--force-reinstall', '--no-deps', f'{name}=={version}',
|
||||
*_pytorch_index(torch, '--extra-index-url')]), universal_newlines=True)
|
||||
|
||||
|
||||
class _Uv:
|
||||
# Measured: uv unpacks a wheel into its cache and links the files from there, at the peak 1.06 times the size of
|
||||
# the files. Where it copies them, it removes the old build first.
|
||||
times_the_size = 1.5
|
||||
|
||||
def __init__(self):
|
||||
from packaging.version import Version
|
||||
|
||||
# uv's version line can follow what Python prints as it starts.
|
||||
try:
|
||||
printed = subprocess.check_output([*make_pip_cmd([])[:-1], '--version'], universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
printed = ''
|
||||
version = re.search(r'^uv (\d+(\.\d+)*)', printed, re.MULTILINE)
|
||||
self.reads_index = version is not None and Version(version[1]) >= Version('0.4.23')
|
||||
|
||||
def environment(self):
|
||||
return contextlib.nullcontext()
|
||||
|
||||
def install(self, name, build, *options):
|
||||
# uv does not put back what it removed when a command fails while it installs, and an install command sent
|
||||
# after it can lay the new build over what is left and report it as installed. uv ends a command when it
|
||||
# cannot reach an index that the command names. A --extra-index-url of the command takes the place of
|
||||
# UV_EXTRA_INDEX_URL.
|
||||
index = _pytorch_index(build, '--extra-index-url')
|
||||
command = make_pip_cmd(['install', *options, f'{name}==={build}', *index])
|
||||
forms = [command, [*command, '--offline']]
|
||||
if index:
|
||||
forms.append([*make_pip_cmd(['install', *options, f'{name}==={build}', *index[:-2]]), '--offline'])
|
||||
for form in forms:
|
||||
try:
|
||||
subprocess.check_output([*form, '--dry-run'], universal_newlines=True, stderr=subprocess.PIPE)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if form is command:
|
||||
reason = '\n'.join(line for line in e.stderr.strip().splitlines()
|
||||
if not line.startswith('Using Python '))
|
||||
continue
|
||||
if form is not command:
|
||||
logging.info("[ComfyUI-Manager] restore PyTorch: the command does not resolve with its indexes, "
|
||||
"installing from uv's cache alone")
|
||||
try:
|
||||
subprocess.check_output(form, universal_newlines=True)
|
||||
except subprocess.CalledProcessError:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: installing {name} {build} failed, "
|
||||
f"sending it once more")
|
||||
subprocess.check_output([*form, '--reinstall-package', name], universal_newlines=True)
|
||||
return True
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: uv does not resolve the command: {reason}")
|
||||
return False
|
||||
|
||||
def putting_back(self, overwritten, torch):
|
||||
return contextlib.nullcontext([option for name in overwritten for option in ('--reinstall-package', name)])
|
||||
|
||||
def own_index(self, torch):
|
||||
# uv reads --index before UV_INDEX, UV_EXTRA_INDEX_URL and the default index, and a --index of the command
|
||||
# takes the place of UV_INDEX.
|
||||
index = _pytorch_index(torch, '--index-url')
|
||||
return [*index, '--index' if self.reads_index else '--extra-index-url', index[-1]] if index else []
|
||||
|
||||
def install_again(self, broken, requirements, torch):
|
||||
again = [option for name in broken for option in ('--reinstall-package', name)]
|
||||
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *self.own_index(torch), *again]),
|
||||
universal_newlines=True)
|
||||
|
||||
def install_files_again(self, name, version, torch):
|
||||
subprocess.check_output(make_pip_cmd(['install', '--no-deps', f'{name}=={version}',
|
||||
*_pytorch_index(torch, '--extra-index-url'),
|
||||
'--reinstall-package', name]), universal_newlines=True)
|
||||
|
||||
|
||||
def _report_not_working(names):
|
||||
if names is _CHECK_DID_NOT_RUN:
|
||||
logging.warning("[ComfyUI-Manager] restore PyTorch: the check of what works did not run")
|
||||
elif names:
|
||||
logging.error(f"[ComfyUI-Manager] restore PyTorch: does not work after the restore: "
|
||||
f"{', '.join(f'{name} {_installed_version(name)}' for name in names)}")
|
||||
|
||||
|
||||
def torch_rollback(installed_before, installed_after, required_by_torch, size_of_pytorch):
|
||||
from packaging.version import Version
|
||||
|
||||
tool = _Uv() if 'uv' in make_pip_cmd([]) else _Pip()
|
||||
torch = installed_before['torch']
|
||||
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in installed_before or name in installed_after]
|
||||
changed = {name: installed_before[name] for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in installed_before and installed_after.get(name) != installed_before[name]}
|
||||
logging.info(f"[ComfyUI-Manager] restore PyTorch: {', '.join(f'{name} {build}' for name, build in changed.items())}")
|
||||
|
||||
companions = {name: build for name, build in changed.items() if name != 'torch'}
|
||||
overwritten = _overwritten(installed_before, installed_after, required_by_torch)
|
||||
needed = _space_to_restore(installed_before, installed_after, overwritten, size_of_pytorch, tool.times_the_size)
|
||||
free = shutil.disk_usage(sysconfig.get_path('purelib')).free
|
||||
if free < needed:
|
||||
raise RuntimeError(f"for safety the restore does not start: it can take {math.ceil(needed / 10 ** 6)} MB on "
|
||||
f"the disk of the Python environment, where {free // 10 ** 6} MB are free")
|
||||
with tool.environment():
|
||||
if 'torch' in changed or overwritten:
|
||||
with tool.putting_back(overwritten, torch) as options:
|
||||
torch_installed = tool.install('torch', torch, *options)
|
||||
if not torch_installed:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: torch {torch} cannot be had, "
|
||||
f"restoring by the version table instead")
|
||||
torch_rollback_by_version_table(torch, packages, options)
|
||||
if not torch_installed:
|
||||
_report_not_working(_not_working(packages))
|
||||
return
|
||||
|
||||
for name, build in companions.items():
|
||||
if not tool.install(name, build, '--no-deps'):
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: {name} {build} cannot be had, "
|
||||
f"installing a {name} that fits torch {torch} instead")
|
||||
|
||||
# torchaudio 2.11.0 declares no requirement on torch, so without a bound the resolver takes it beside an older
|
||||
# torch. The bound is the next minor version of torch, as a patch release of torchaudio can be newer than its
|
||||
# torch: 2.0.2 goes with 2.0.1.
|
||||
version = Version(torch)
|
||||
requirement = {'torch': f'torch==={torch}', 'torchvision': 'torchvision',
|
||||
'torchaudio': f'torchaudio<{version.major}.{version.minor + 1}'}
|
||||
requirements = {name: requirement[name] for name in packages}
|
||||
try:
|
||||
subprocess.check_output(make_pip_cmd(['install', *requirements.values(), *tool.own_index(torch)]),
|
||||
universal_newlines=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: the whole set failed to install, checking what "
|
||||
f"works: {e}")
|
||||
|
||||
broken = _not_working(packages)
|
||||
if broken and 'torch' in broken:
|
||||
# An uninstall takes the files that two distributions share.
|
||||
incomplete = _incomplete(required_by_torch)
|
||||
for name, version in incomplete.items():
|
||||
try:
|
||||
tool.install_files_again(name, version, torch)
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
if incomplete:
|
||||
broken = _not_working(packages)
|
||||
|
||||
if broken and 'torch' not in broken:
|
||||
torchvision = _installed_version('torchvision')
|
||||
if 'torchvision' in broken and torchvision is not None:
|
||||
requirements['torchvision'] = f"torchvision=={Version(torchvision).public}"
|
||||
try:
|
||||
tool.install_again(broken, requirements, torch)
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
broken = _not_working(packages)
|
||||
_report_not_working(broken)
|
||||
|
||||
|
||||
class PIPFixer:
|
||||
def __init__(self, prev_pip_versions, comfyui_path, manager_files_path):
|
||||
self.prev_pip_versions = { **prev_pip_versions }
|
||||
self.required_by_torch, self.size_of_pytorch = set(), {}
|
||||
torch = prev_pip_versions.get('torch')
|
||||
try:
|
||||
list_names_the_installed_torch = torch is not None and _installed_version('torch') == torch
|
||||
if list_names_the_installed_torch:
|
||||
self.required_by_torch, self.size_of_pytorch = ({name for name, _ in _required_here('torch')},
|
||||
_size_of_pytorch())
|
||||
except Exception as e:
|
||||
logging.warning(f"[ComfyUI-Manager] restore PyTorch: what torch requires could not be read, "
|
||||
f"a restore will put no library back: {e!r}")
|
||||
self.comfyui_path = comfyui_path
|
||||
self.manager_files_path = manager_files_path
|
||||
|
||||
@@ -881,12 +1504,12 @@ class PIPFixer:
|
||||
|
||||
# fix torch - reinstall torch packages if version is changed
|
||||
try:
|
||||
if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions or 'torchaudio' not in self.prev_pip_versions:
|
||||
if 'torch' not in self.prev_pip_versions or 'torchvision' not in self.prev_pip_versions:
|
||||
logging.error("[ComfyUI-Manager] PyTorch is not installed")
|
||||
elif self.prev_pip_versions['torch'] != new_pip_versions['torch'] \
|
||||
or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision'] \
|
||||
or self.prev_pip_versions['torchaudio'] != new_pip_versions['torchaudio']:
|
||||
torch_rollback(self.prev_pip_versions['torch'])
|
||||
elif any(self.prev_pip_versions[name] != new_pip_versions.get(name) for name in ('torch', 'torchvision')):
|
||||
clear_pip_cache()
|
||||
torch_rollback(self.prev_pip_versions, new_pip_versions, self.required_by_torch,
|
||||
self.size_of_pytorch)
|
||||
except Exception as e:
|
||||
logging.error("[ComfyUI-Manager] Failed to restore PyTorch")
|
||||
logging.error(e)
|
||||
@@ -950,6 +1573,9 @@ class PIPFixer:
|
||||
logging.error(e)
|
||||
|
||||
# restore based on custom list
|
||||
if self.manager_files_path is None:
|
||||
return
|
||||
|
||||
pip_auto_fix_path = os.path.join(self.manager_files_path, "pip_auto_fix.list")
|
||||
if os.path.exists(pip_auto_fix_path):
|
||||
from packaging.specifiers import Specifier # imported on use, as in parse_pip_spec()
|
||||
@@ -1055,13 +1681,22 @@ def restore_pip_snapshot(pips, options):
|
||||
if k.startswith("torch==") or k.startswith("torchvision==") or k.startswith("torchaudio==") or k.startswith("nvidia-"):
|
||||
continue
|
||||
|
||||
if v == "":
|
||||
# pip freeze prints an editable install as `-e <path or url>`, after a comment line
|
||||
if k.startswith('#'):
|
||||
continue
|
||||
elif k.startswith('-e '):
|
||||
v = k[3:]
|
||||
args = ['-e', v]
|
||||
elif v == "":
|
||||
non_url.append(k)
|
||||
continue
|
||||
else:
|
||||
if v.startswith('file:'):
|
||||
local_url.append(v)
|
||||
else:
|
||||
non_local_url.append(v)
|
||||
args = [v]
|
||||
|
||||
if v.startswith('file:') or '://' not in v:
|
||||
local_url.append(args)
|
||||
else:
|
||||
non_local_url.append(args)
|
||||
|
||||
|
||||
# restore other pips
|
||||
@@ -1090,22 +1725,61 @@ def restore_pip_snapshot(pips, options):
|
||||
for x in non_local_url:
|
||||
res = 1
|
||||
try:
|
||||
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', x]))
|
||||
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', *installer_args(x)]))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if res != 0:
|
||||
failed.append(x)
|
||||
failed.append(' '.join(x))
|
||||
|
||||
if '--pip-local-url' in options:
|
||||
for x in local_url:
|
||||
res = 1
|
||||
try:
|
||||
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', x]))
|
||||
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', *installer_args(x)]))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if res != 0:
|
||||
failed.append(x)
|
||||
failed.append(' '.join(x))
|
||||
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
return failed
|
||||
|
||||
|
||||
def which_on_path(name):
|
||||
"""
|
||||
the file that the directories of PATH give for the name of a command
|
||||
`shutil.which` looks in the current directory first on Windows, and takes a directory of PATH that is not absolute
|
||||
"""
|
||||
names = [name]
|
||||
if os.name == 'nt':
|
||||
extensions = [x for x in os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) if x]
|
||||
if not name.lower().endswith(tuple(x.lower() for x in extensions)):
|
||||
names = [name + x for x in extensions]
|
||||
|
||||
for directory in os.get_exec_path():
|
||||
for x in names:
|
||||
path = os.path.join(directory, x)
|
||||
if os.path.isabs(directory) and os.path.isfile(path) and os.access(path, os.X_OK):
|
||||
return path
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def find_git_executable(git_exe, timeout=10):
|
||||
# a name without a directory is a command of PATH; GitPython would take it as a file of the current directory
|
||||
path = shutil.which(git_exe) if os.path.dirname(git_exe) else which_on_path(git_exe)
|
||||
if path is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
# the answer goes to a file: with a pipe, Windows waits after the time is up for every program that holds the pipe
|
||||
with tempfile.TemporaryFile() as answer:
|
||||
res = subprocess.run([path, 'version'], stdout=answer, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, timeout=timeout)
|
||||
answer.seek(0)
|
||||
is_git = res.returncode == 0 and answer.read(11) == b'git version'
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
|
||||
return os.path.abspath(path) if is_git else None
|
||||
|
||||
+30
-4
@@ -6,6 +6,27 @@ import os
|
||||
from git_utils import get_commit_hash
|
||||
|
||||
|
||||
IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
|
||||
|
||||
|
||||
def is_link(path: str) -> bool:
|
||||
"""
|
||||
A junction is told by the reparse tag that os.lstat reads on every Python; os.path.isjunction is new in 3.12.
|
||||
"""
|
||||
try:
|
||||
return os.path.islink(path) or getattr(os.lstat(path), 'st_reparse_tag', 0) == IO_REPARSE_TAG_MOUNT_POINT
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InvalidInstallation:
|
||||
fullpath: str
|
||||
unknown_key: str
|
||||
project_name: str | None
|
||||
enabled: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class InstalledNodePackage:
|
||||
"""Information about an installed node package."""
|
||||
@@ -38,11 +59,16 @@ class InstalledNodePackage:
|
||||
def get_commit_hash(self) -> str:
|
||||
return get_commit_hash(self.fullpath)
|
||||
|
||||
def isValid(self) -> bool:
|
||||
if self.is_from_cnr:
|
||||
return os.path.exists(os.path.join(self.fullpath, '.tracking'))
|
||||
def is_exempt_from_installation_check(self) -> bool:
|
||||
name = os.path.basename(self.fullpath)
|
||||
return ('comfyui-manager' in self.id.lower() or is_link(self.fullpath)
|
||||
or name.startswith('.') or name in ('__MACOSX', '__pycache__'))
|
||||
|
||||
return True
|
||||
def isValid(self) -> bool:
|
||||
if self.is_exempt_from_installation_check():
|
||||
return True
|
||||
|
||||
return os.path.exists(os.path.join(self.fullpath, '.git')) or os.path.exists(os.path.join(self.fullpath, '.tracking'))
|
||||
|
||||
@staticmethod
|
||||
def from_fullpath(fullpath: str, resolve_from_path) -> InstalledNodePackage:
|
||||
|
||||
+47
-50
@@ -6,19 +6,38 @@ import json
|
||||
|
||||
import folder_paths
|
||||
from server import PromptServer
|
||||
from manager_server import _reject_non_json_content_type
|
||||
|
||||
|
||||
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/manager/share_option")
|
||||
async def share_option(request):
|
||||
if "value" in request.rel_url.query:
|
||||
core.get_config()['share_option'] = request.rel_url.query['value']
|
||||
core.write_config()
|
||||
else:
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
return web.Response(text=core.get_config()['share_option'], status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/manager/share_option")
|
||||
async def set_share_option(request):
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
try:
|
||||
value = (await request.json())['value']
|
||||
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
if value not in SHARE_OPTIONS:
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
core.get_config()['share_option'] = value
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
def is_matrix_org(homeserver):
|
||||
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
|
||||
|
||||
|
||||
def get_matrix_auth():
|
||||
if not os.path.exists(os.path.join(core.manager_files_path, "matrix_auth")):
|
||||
return None
|
||||
@@ -26,7 +45,7 @@ def get_matrix_auth():
|
||||
with open(os.path.join(core.manager_files_path, "matrix_auth"), "r") as f:
|
||||
matrix_auth = f.read()
|
||||
homeserver, username, password = matrix_auth.strip().split("\n")
|
||||
if not homeserver or not username or not password:
|
||||
if not is_matrix_org(homeserver) or not username or not password:
|
||||
return None
|
||||
return {
|
||||
"homeserver": homeserver,
|
||||
@@ -37,52 +56,26 @@ def get_matrix_auth():
|
||||
return None
|
||||
|
||||
|
||||
def get_youml_settings():
|
||||
if not os.path.exists(os.path.join(core.manager_files_path, ".youml")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(core.manager_files_path, ".youml"), "r") as f:
|
||||
youml_settings = f.read().strip()
|
||||
return youml_settings if youml_settings else None
|
||||
except:
|
||||
return None
|
||||
|
||||
|
||||
def set_youml_settings(settings):
|
||||
with open(os.path.join(core.manager_files_path, ".youml"), "w") as f:
|
||||
f.write(settings)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/manager/get_matrix_auth")
|
||||
async def api_get_matrix_auth(request):
|
||||
# print("Getting stored Matrix credentials...")
|
||||
matrix_auth = get_matrix_auth()
|
||||
if not matrix_auth:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(matrix_auth)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/manager/youml/settings")
|
||||
async def api_get_youml_settings(request):
|
||||
youml_settings = get_youml_settings()
|
||||
if not youml_settings:
|
||||
return web.Response(status=404)
|
||||
return web.json_response(json.loads(youml_settings))
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/manager/youml/settings")
|
||||
async def api_set_youml_settings(request):
|
||||
json_data = await request.json()
|
||||
set_youml_settings(json.dumps(json_data))
|
||||
return web.Response(status=200)
|
||||
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
|
||||
|
||||
|
||||
def set_matrix_auth(json_data):
|
||||
homeserver = json_data['homeserver']
|
||||
username = json_data['username']
|
||||
password = json_data['password']
|
||||
with open(os.path.join(core.manager_files_path, "matrix_auth"), "w") as f:
|
||||
f.write("\n".join([homeserver, username, password]))
|
||||
path = os.path.join(core.manager_files_path, "matrix_auth")
|
||||
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
|
||||
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
|
||||
try:
|
||||
os.chmod(path, 0o600)
|
||||
except OSError:
|
||||
pass # a file of another owner keeps its mode
|
||||
f.truncate()
|
||||
f.write("\n".join(["matrix.org", username, password]))
|
||||
|
||||
|
||||
def has_provided_matrix_auth(matrix_auth):
|
||||
@@ -92,11 +85,17 @@ def has_provided_matrix_auth(matrix_auth):
|
||||
@PromptServer.instance.routes.post("/manager/share")
|
||||
async def share_art(request):
|
||||
# get json data
|
||||
resp = _reject_non_json_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
matrix_auth = json_data['matrix_auth']
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
saved = get_matrix_auth()
|
||||
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
|
||||
matrix_auth['password'] = saved['password']
|
||||
|
||||
share_destinations = json_data['share_destinations']
|
||||
credits = json_data['credits']
|
||||
@@ -153,14 +152,10 @@ async def share_art(request):
|
||||
try:
|
||||
from nio import AsyncClient, LoginResponse, UploadResponse
|
||||
|
||||
homeserver = 'matrix.org'
|
||||
if matrix_auth:
|
||||
homeserver = matrix_auth.get('homeserver', 'matrix.org')
|
||||
homeserver = homeserver.replace("http://", "https://")
|
||||
if not homeserver.startswith("https://"):
|
||||
homeserver = "https://" + homeserver
|
||||
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
|
||||
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
|
||||
|
||||
client = AsyncClient(homeserver, matrix_auth['username'])
|
||||
client = AsyncClient("https://matrix.org", matrix_auth['username'])
|
||||
|
||||
# Login
|
||||
login_resp = await client.login(matrix_auth['password'])
|
||||
@@ -168,6 +163,8 @@ async def share_art(request):
|
||||
await client.close()
|
||||
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
|
||||
# Upload asset
|
||||
with open(asset_filepath, 'rb') as f:
|
||||
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
|
||||
|
||||
+3
-3
@@ -48,7 +48,7 @@ async function enableNodePack(target) {
|
||||
// A node pack from the registry is enabled while the install request is handled, and reported then.
|
||||
api.addEventListener("cm-queue-status", listener);
|
||||
try {
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
const response = await api.fetchApi(`/manager/queue/install`, {
|
||||
method: 'POST',
|
||||
@@ -70,7 +70,7 @@ async function enableNodePack(target) {
|
||||
}
|
||||
|
||||
started = true;
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// A report that does not reach the page would leave the listener in place, and a later report
|
||||
// for the same row, such as its Disable, would then restart ComfyUI unasked.
|
||||
@@ -121,7 +121,7 @@ async function tryInstallCustomNode(event) {
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await api.fetchApi("/manager/reboot", { method: 'POST' });
|
||||
response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
catch(exception) {
|
||||
// The server restarts without answering.
|
||||
|
||||
+49
-46
@@ -133,17 +133,6 @@ docStyle.innerHTML = `
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#alternatives-grid a {
|
||||
color: #5555FF;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#alternatives-grid a:hover {
|
||||
color: #7777FF;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.cm-notice-board {
|
||||
width: auto;
|
||||
height: 280px;
|
||||
@@ -235,6 +224,7 @@ var switch_comfyui_button = null;
|
||||
var update_all_button = null;
|
||||
var restart_stop_button = null;
|
||||
var update_policy_combo = null;
|
||||
var update_policy_chosen = false;
|
||||
|
||||
let share_option = 'all';
|
||||
const share_options = [
|
||||
@@ -424,13 +414,22 @@ const style = `
|
||||
#cm-manual-button-menu {
|
||||
z-index: 10000000000 !important;
|
||||
}
|
||||
.cm-share-none .cm-share-button {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
|
||||
// the frontend mounts the new style buttons into its top bar after setup(), so they are hidden by a class of the page
|
||||
function update_share_buttons() {
|
||||
document.body.classList.toggle("cm-share-none", share_option === 'none');
|
||||
}
|
||||
|
||||
async function init_share_option() {
|
||||
api.fetchApi('/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_option = to_share_option(data);
|
||||
update_share_buttons();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -488,12 +487,12 @@ async function updateComfyUI() {
|
||||
|
||||
set_inprogress_mode();
|
||||
|
||||
const response = await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST' });
|
||||
const response = await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
showTerminal();
|
||||
|
||||
is_updating = true;
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
function showVersionSelectorDialog(versions, current, onSelect) {
|
||||
@@ -641,19 +640,18 @@ async function switchComfyUI() {
|
||||
}
|
||||
|
||||
showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
|
||||
if(selected_version == 'nightly') {
|
||||
update_policy_combo.value = 'nightly-comfyui';
|
||||
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: 'nightly-comfyui' }) });
|
||||
}
|
||||
else {
|
||||
update_policy_combo.value = 'stable-comfyui';
|
||||
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: 'stable-comfyui' }) });
|
||||
}
|
||||
|
||||
let response = await api.fetchApi('/comfyui_manager/comfyui_switch_version', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ver: selected_version }), cache: "no-store" });
|
||||
if (response.status == 200) {
|
||||
const update_policy = selected_version == 'nightly' ? 'nightly-comfyui' : 'stable-comfyui';
|
||||
update_policy_chosen = true;
|
||||
update_policy_combo.value = update_policy;
|
||||
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: update_policy }) });
|
||||
|
||||
infoToast(`ComfyUI version is switched to ${selected_version}`);
|
||||
}
|
||||
else if (response.status == 403) {
|
||||
await handle403Response(response);
|
||||
}
|
||||
else {
|
||||
customAlert('Failed to switch ComfyUI version.');
|
||||
}
|
||||
@@ -706,7 +704,7 @@ async function onQueueStatus(event) {
|
||||
|
||||
let msg = "";
|
||||
|
||||
if(success_list.length == 0 && comfyui_state.startsWith('skip')) {
|
||||
if(success_list.length == 0 && (comfyui_state == null || comfyui_state.startsWith('skip'))) {
|
||||
if(failed_list.length == 0) {
|
||||
msg += "You are already up to date.";
|
||||
}
|
||||
@@ -718,7 +716,7 @@ async function onQueueStatus(event) {
|
||||
msg += "ComfyUI has been updated to latest nightly version.<BR><BR>";
|
||||
infoToast("ComfyUI has been updated to the latest nightly version.");
|
||||
}
|
||||
else if(comfyui_state.startsWith('success-stable')) {
|
||||
else if(comfyui_state?.startsWith('success-stable')) {
|
||||
const ver = comfyui_state.split("-").pop();
|
||||
msg += `ComfyUI has been updated to ${ver}.<BR><BR>`;
|
||||
infoToast(`ComfyUI has been updated to ${ver}`);
|
||||
@@ -792,7 +790,7 @@ async function updateAll(update_comfyui) {
|
||||
|
||||
if(update_comfyui) {
|
||||
update_all_button.innerText = "Updating ComfyUI...";
|
||||
await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
const response = await api.fetchApi('/manager/queue/update_all', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: mode }) });
|
||||
@@ -807,7 +805,7 @@ async function updateAll(update_comfyui) {
|
||||
}
|
||||
else if(response.status == 200) {
|
||||
is_updating = true;
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -836,7 +834,7 @@ function restartOrStop() {
|
||||
rebootAPI();
|
||||
}
|
||||
else {
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
}
|
||||
@@ -996,11 +994,14 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'Local' }, []));
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'remote', text: 'Channel (remote)' }, []));
|
||||
|
||||
// a choice made before the stored value arrives is not to be replaced by it
|
||||
let db_mode_chosen = false;
|
||||
api.fetchApi('/manager/db_mode')
|
||||
.then(response => response.text())
|
||||
.then(data => { this.datasrc_combo.value = data; });
|
||||
.then(data => { if(!db_mode_chosen) this.datasrc_combo.value = data; });
|
||||
|
||||
this.datasrc_combo.addEventListener('change', function (event) {
|
||||
db_mode_chosen = true;
|
||||
api.fetchApi('/manager/db_mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
|
||||
});
|
||||
|
||||
@@ -1142,23 +1143,22 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
|
||||
}
|
||||
|
||||
let share_option_chosen = false;
|
||||
api.fetchApi('/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_option = to_share_option(data);
|
||||
share_combo.value = share_option;
|
||||
if(!share_option_chosen) {
|
||||
share_option = to_share_option(data);
|
||||
share_combo.value = share_option;
|
||||
}
|
||||
});
|
||||
|
||||
share_combo.addEventListener('change', function (event) {
|
||||
share_option_chosen = true;
|
||||
const value = event.target.value;
|
||||
share_option = value;
|
||||
api.fetchApi(`/manager/share_option?value=${value}`);
|
||||
const shareButton = document.getElementById("shareButton");
|
||||
if (value === 'none') {
|
||||
shareButton.style.display = "none";
|
||||
} else {
|
||||
shareButton.style.display = "inline-block";
|
||||
}
|
||||
api.fetchApi('/manager/share_option', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
update_share_buttons();
|
||||
});
|
||||
|
||||
const shareSetttingItem = createSettingsCombo("Share", share_combo);
|
||||
@@ -1169,14 +1169,18 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
component_policy_combo.appendChild($el('option', { value: 'workflow', text: 'Use workflow version' }, []));
|
||||
component_policy_combo.appendChild($el('option', { value: 'higher', text: 'Use higher version' }, []));
|
||||
component_policy_combo.appendChild($el('option', { value: 'mine', text: 'Use my version' }, []));
|
||||
let component_policy_chosen = false;
|
||||
api.fetchApi('/manager/policy/component')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
component_policy_combo.value = data;
|
||||
set_component_policy(data);
|
||||
if(!component_policy_chosen) {
|
||||
component_policy_combo.value = data;
|
||||
set_component_policy(data);
|
||||
}
|
||||
});
|
||||
|
||||
component_policy_combo.addEventListener('change', function (event) {
|
||||
component_policy_chosen = true;
|
||||
api.fetchApi('/manager/policy/component', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
|
||||
set_component_policy(event.target.value);
|
||||
});
|
||||
@@ -1192,10 +1196,12 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
api.fetchApi('/manager/policy/update')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
update_policy_combo.value = data;
|
||||
if(!update_policy_chosen)
|
||||
update_policy_combo.value = data;
|
||||
});
|
||||
|
||||
update_policy_combo.addEventListener('change', function (event) {
|
||||
update_policy_chosen = true;
|
||||
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
|
||||
});
|
||||
|
||||
@@ -1608,7 +1614,8 @@ app.registerExtension({
|
||||
}
|
||||
ShareDialogChooser.instance.show();
|
||||
},
|
||||
tooltip: "Share"
|
||||
tooltip: "Share",
|
||||
classList: "comfyui-button cm-share-button"
|
||||
}).element
|
||||
);
|
||||
|
||||
@@ -1648,11 +1655,7 @@ app.registerExtension({
|
||||
// make the background color a gradient of blue to green
|
||||
shareButton.style.background = "linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%)";
|
||||
shareButton.style.color = "black";
|
||||
|
||||
// Load share option from local storage to determine whether to show
|
||||
// the share button.
|
||||
const shouldShowShareButton = share_option !== 'none';
|
||||
shareButton.style.display = shouldShowShareButton ? "inline-block" : "none";
|
||||
shareButton.className = "cm-share-button";
|
||||
|
||||
menu.append(shareButton);
|
||||
},
|
||||
|
||||
@@ -380,7 +380,7 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
}
|
||||
export class ShareDialog extends ComfyDialog {
|
||||
static instance = null;
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@@ -405,9 +405,9 @@ export class ShareDialog extends ComfyDialog {
|
||||
const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
|
||||
this.matrix_destination_checkbox.style.color = "var(--fg-color)";
|
||||
|
||||
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
|
||||
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", value: "matrix.org", readOnly: true, title: "The share room is on matrix.org; only an account of matrix.org can share." }, []);
|
||||
this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
|
||||
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
|
||||
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password" }, []);
|
||||
|
||||
this.credits_input = $el("input", {
|
||||
type: "text",
|
||||
@@ -621,15 +621,14 @@ export class ShareDialog extends ComfyDialog {
|
||||
]);
|
||||
|
||||
// get the user's existing matrix auth
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
try {
|
||||
api.fetchApi(`/manager/get_matrix_auth`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
ShareDialog.matrix_auth = data;
|
||||
this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
|
||||
this.matrix_username_input.value = ShareDialog.matrix_auth.username;
|
||||
this.matrix_password_input.value = ShareDialog.matrix_auth.password;
|
||||
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
@@ -651,7 +650,8 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
// if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
|
||||
if (destinations.includes("matrix")) {
|
||||
let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
|
||||
const usesSavedPassword = this.matrix_username_input.value == ShareDialog.matrix_auth.username;
|
||||
let definedMatrixAuth = !!this.matrix_username_input.value && (!!this.matrix_password_input.value || usesSavedPassword);
|
||||
if (!definedMatrixAuth) {
|
||||
customAlert("Please set your Matrix account details.");
|
||||
return;
|
||||
@@ -721,6 +721,7 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
if (response_json.matrix.success) {
|
||||
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
|
||||
ShareDialog.matrix_auth = { homeserver: this.matrix_homeserver_input.value, username: this.matrix_username_input.value };
|
||||
}
|
||||
|
||||
this.final_message.style.color = "green";
|
||||
|
||||
@@ -176,25 +176,12 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
this.selectedFile = null;
|
||||
}
|
||||
|
||||
async loadToken() {
|
||||
let key = ""
|
||||
try {
|
||||
const response = await api.fetchApi(`/manager/youml/settings`)
|
||||
const settings = await response.json()
|
||||
return settings.token
|
||||
} catch (error) {
|
||||
}
|
||||
return key || "";
|
||||
loadToken() {
|
||||
return localStorage.getItem("youml_token") || "";
|
||||
}
|
||||
|
||||
async saveToken(value) {
|
||||
await api.fetchApi(`/manager/youml/settings`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
token: value
|
||||
})
|
||||
});
|
||||
saveToken(value) {
|
||||
localStorage.setItem("youml_token", value);
|
||||
}
|
||||
|
||||
createLayout() {
|
||||
@@ -342,7 +329,7 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
|
||||
async handleShareButtonClick() {
|
||||
this.message.textContent = "";
|
||||
await this.saveToken(this.apiTokenInput.value);
|
||||
this.saveToken(this.apiTokenInput.value);
|
||||
try {
|
||||
this.shareButton.disabled = true;
|
||||
this.shareButton.textContent = "Sharing...";
|
||||
@@ -560,8 +547,7 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
this.message.innerHTML = "";
|
||||
this.message.textContent = "";
|
||||
|
||||
const token = await this.loadToken();
|
||||
this.apiTokenInput.value = token;
|
||||
this.apiTokenInput.value = this.loadToken();
|
||||
this.uploadedImages = [];
|
||||
|
||||
this.element.style.display = "block";
|
||||
|
||||
+59
-1
@@ -185,7 +185,7 @@ export async function rebootAPI() {
|
||||
const isConfirmed = await customConfirm("Are you sure you'd like to reboot the server?");
|
||||
if (isConfirmed) {
|
||||
try {
|
||||
const response = await api.fetchApi("/manager/reboot", { method: 'POST' });
|
||||
const response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
if (response.status == 403) {
|
||||
await handle403Response(response);
|
||||
return false;
|
||||
@@ -367,6 +367,63 @@ export function md5(inputString) {
|
||||
return rh(a)+rh(b)+rh(c)+rh(d);
|
||||
}
|
||||
|
||||
const levenArray = [];
|
||||
const levenCodeCache = [];
|
||||
export const leven = (first, second) => {
|
||||
if (first === second) {
|
||||
return 0;
|
||||
}
|
||||
const swap = first;
|
||||
if (first.length > second.length) {
|
||||
first = second;
|
||||
second = swap;
|
||||
}
|
||||
let firstLength = first.length;
|
||||
let secondLength = second.length;
|
||||
while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) {
|
||||
firstLength--;
|
||||
secondLength--;
|
||||
}
|
||||
let start = 0;
|
||||
while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) {
|
||||
start++;
|
||||
}
|
||||
firstLength -= start;
|
||||
secondLength -= start;
|
||||
if (firstLength === 0) {
|
||||
return secondLength;
|
||||
}
|
||||
let bCharacterCode;
|
||||
let result;
|
||||
let temporary;
|
||||
let temporary2;
|
||||
let index = 0;
|
||||
let index2 = 0;
|
||||
while (index < firstLength) {
|
||||
levenCodeCache[index] = first.charCodeAt(start + index);
|
||||
levenArray[index] = ++index;
|
||||
}
|
||||
while (index2 < secondLength) {
|
||||
bCharacterCode = second.charCodeAt(start + index2);
|
||||
temporary = index2++;
|
||||
result = index2;
|
||||
for (index = 0; index < firstLength; index++) {
|
||||
temporary2 = bCharacterCode === levenCodeCache[index] ? temporary : temporary + 1;
|
||||
temporary = levenArray[index];
|
||||
result = levenArray[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function generateUUID() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
||||
const r = Math.random() * 16 | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchData(route, options) {
|
||||
let err;
|
||||
const res = await api.fetchApi(route, options).catch(e => {
|
||||
@@ -691,6 +748,7 @@ export async function uninstallNodes(nodeList, options = {}) {
|
||||
|
||||
const res = await api.fetchApi(`/manager/queue/uninstall`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
|
||||
@@ -65,6 +65,10 @@ function storeGroupNode(name, data, register=true) {
|
||||
|
||||
export async function load_components() {
|
||||
let data = await api.fetchApi('/manager/component/loads', {method: "POST"});
|
||||
if(data.status != 200) {
|
||||
return;
|
||||
}
|
||||
|
||||
let components = await data.json();
|
||||
|
||||
let start_time = Date.now();
|
||||
|
||||
@@ -590,20 +590,6 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.cn-tag-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.cn-tag-list > div {
|
||||
background-color: var(--border-color);
|
||||
border-radius: 5px;
|
||||
padding: 0 5px;
|
||||
}
|
||||
|
||||
.cn-install-buttons {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -657,6 +643,13 @@
|
||||
color: white;
|
||||
}
|
||||
|
||||
.cn-manager .cn-btn-invalid-installation {
|
||||
background-color: #A65E00;
|
||||
font-size: 10px;
|
||||
font-weight: bold;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.cn-manager .cn-btn-install {
|
||||
background-color: black;
|
||||
color: white;
|
||||
|
||||
+233
-87
@@ -8,7 +8,8 @@ import {
|
||||
fetchData, md5, icons, show_message, customConfirm, customAlert, customPrompt,
|
||||
sanitizeHTML, sanitizeUrl, infoToast, showTerminal, setNeedRestart,
|
||||
storeColumnWidth, restoreColumnWidth, getTimeAgo, copyText, loadCss,
|
||||
showPopover, hidePopover, getWorkflowNodeTypes, findPackageByCnrId, analyzeWorkflowUsage, createFlyover
|
||||
showPopover, hidePopover, getWorkflowNodeTypes, findPackageByCnrId, analyzeWorkflowUsage, createFlyover, leven,
|
||||
generateUUID
|
||||
} from "./common.js";
|
||||
|
||||
// https://cenfun.github.io/turbogrid/api.html
|
||||
@@ -18,6 +19,8 @@ loadCss("./custom-nodes-manager.css");
|
||||
|
||||
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.";
|
||||
|
||||
const pageHtml = `
|
||||
<div class="cn-manager cn-manager-dark">
|
||||
<div class="cn-manager-grid"></div>
|
||||
@@ -40,7 +43,6 @@ const ShowMode = {
|
||||
UPDATE: "Update",
|
||||
MISSING: "Missing",
|
||||
FAVORITES: "Favorites",
|
||||
ALTERNATIVES: "Alternatives",
|
||||
IN_WORKFLOW: "In Workflow",
|
||||
USED_IN_ANY_WORKFLOW: "Used In Any Workflow",
|
||||
NOT_USED_IN_ANY_WORKFLOW: "Installed and Unused",
|
||||
@@ -73,6 +75,8 @@ export class CustomNodesManager {
|
||||
this.init();
|
||||
|
||||
api.addEventListener("cm-queue-status", this.onQueueStatus);
|
||||
api.addEventListener("cm-check-update", this.onCheckUpdate);
|
||||
api.addEventListener("reconnected", this.onReconnected);
|
||||
api.getNodeDefs().then(objs => {
|
||||
this.nodeMap = objs;
|
||||
})
|
||||
@@ -253,6 +257,10 @@ export class CustomNodesManager {
|
||||
label: "Import Failed",
|
||||
value: "import-fail",
|
||||
hasData: true
|
||||
}, {
|
||||
label: "Invalid Installation",
|
||||
value: "invalid-installation",
|
||||
hasData: true
|
||||
}, {
|
||||
label: "Not Installed",
|
||||
value: "not-installed",
|
||||
@@ -289,10 +297,6 @@ export class CustomNodesManager {
|
||||
label: "Favorites",
|
||||
value: ShowMode.FAVORITES,
|
||||
hasData: false
|
||||
}, {
|
||||
label: "Alternatives of A1111",
|
||||
value: ShowMode.ALTERNATIVES,
|
||||
hasData: false
|
||||
}];
|
||||
this.filterList = filterList;
|
||||
$filter.innerHTML = filterList.map(item => {
|
||||
@@ -331,7 +335,8 @@ export class CustomNodesManager {
|
||||
|
||||
"reinstall": {
|
||||
label: "Reinstall",
|
||||
mode: "reinstall"
|
||||
mode: "reinstall",
|
||||
title: INVALID_INSTALLATION_GUIDANCE
|
||||
},
|
||||
|
||||
"install": {
|
||||
@@ -384,7 +389,8 @@ export class CustomNodesManager {
|
||||
|
||||
return list.map(id => {
|
||||
const bt = buttons[id];
|
||||
return `<button class="cn-btn-${id} cm-ui-button" group="${sanitizeHTML(String(action))}" mode="${bt.mode}">${bt.label}</button>`;
|
||||
const tooltip = bt.title ? ` title="${sanitizeHTML(bt.title)}"` : "";
|
||||
return `<button class="cn-btn-${id} cm-ui-button" group="${sanitizeHTML(String(action))}" mode="${bt.mode}"${tooltip}>${bt.label}</button>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
@@ -430,11 +436,7 @@ export class CustomNodesManager {
|
||||
|
||||
".cn-manager-keywords": {
|
||||
input: (e) => {
|
||||
const keywords = `${e.target.value}`.trim();
|
||||
if (keywords !== this.keywords) {
|
||||
this.keywords = keywords;
|
||||
this.updateGrid();
|
||||
}
|
||||
this.onKeywordsChange(e);
|
||||
},
|
||||
focus: (e) => e.target.select()
|
||||
},
|
||||
@@ -471,7 +473,7 @@ export class CustomNodesManager {
|
||||
|
||||
".cn-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -555,7 +557,7 @@ export class CustomNodesManager {
|
||||
|
||||
this.addHighlight(d.rowItem);
|
||||
|
||||
if (d.columnItem.id === "nodes") {
|
||||
if (d.columnItem && d.columnItem.id === "nodes") {
|
||||
this.showNodes(d);
|
||||
return;
|
||||
}
|
||||
@@ -611,17 +613,24 @@ export class CustomNodesManager {
|
||||
bindContainerResize: true,
|
||||
|
||||
cellResizeObserver: (rowItem, columnItem) => {
|
||||
const autoHeightColumns = ['title', 'action', 'description', "alternatives"];
|
||||
const autoHeightColumns = ['title', 'action', 'description'];
|
||||
return autoHeightColumns.includes(columnItem.id)
|
||||
},
|
||||
|
||||
rowFilteredSort: () => {
|
||||
if (this.keywords) {
|
||||
return {
|
||||
id: 'sort_score',
|
||||
// rows with the same score stay in the listed order, whatever was searched before
|
||||
comparer: (a, b) => ((b.sort_score ?? 0) - (a.sort_score ?? 0)) || (a.id - b.id)
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
// updateGrid handler for filter and keywords
|
||||
rowFilter: (rowItem) => {
|
||||
|
||||
const searchableColumns = ["title", "author", "description"];
|
||||
if (this.hasAlternatives()) {
|
||||
searchableColumns.push("alternatives");
|
||||
}
|
||||
|
||||
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
|
||||
|
||||
@@ -631,14 +640,109 @@ export class CustomNodesManager {
|
||||
}
|
||||
}
|
||||
|
||||
// calculate sort score
|
||||
if (shouldShown && this.keywords) {
|
||||
rowItem.sort_score = this.calculateSortScore(rowItem, searchableColumns);
|
||||
}
|
||||
|
||||
return shouldShown;
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
hasAlternatives() {
|
||||
return this.filter === ShowMode.ALTERNATIVES
|
||||
onKeywordsChange(e) {
|
||||
this.grid.showLoading();
|
||||
// debounce for performance
|
||||
clearTimeout(this.timeKeywords);
|
||||
this.timeKeywords = setTimeout(() => {
|
||||
if (!this.loading) {
|
||||
this.grid.hideLoading();
|
||||
}
|
||||
const keywords = `${e.target.value}`.trim();
|
||||
if (keywords !== this.keywords) {
|
||||
this.keywords = keywords;
|
||||
if (keywords) {
|
||||
this.grid.removeSortColumn();
|
||||
} else if (!this.grid.sortColumn) {
|
||||
this.grid.sortRows("id", {
|
||||
sortAsc: true
|
||||
});
|
||||
}
|
||||
this.updateGrid();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
|
||||
calculateSortScore(rowItem, searchableColumns) {
|
||||
const keywords = this.keywords.split(/\s+/g).filter((s) => s);
|
||||
const lowerKeywords = keywords.map(k => k.toLowerCase());
|
||||
const matchedList = searchableColumns.map(id => {
|
||||
const { highlightKey, textKey } = this.grid.options.highlightKeywords;
|
||||
const highlight = rowItem[`${highlightKey}${id}`];
|
||||
if (!highlight) {
|
||||
return;
|
||||
}
|
||||
const text = `${rowItem[`${textKey}${id}`] || rowItem[id]}`;
|
||||
const lowerText = text.toLowerCase();
|
||||
const matchedItems = keywords.map((key, i) => {
|
||||
// multiple matched
|
||||
const lowerKey = lowerKeywords[i];
|
||||
const len = lowerKey.length;
|
||||
const matches = [];
|
||||
let index = lowerText.indexOf(lowerKey);
|
||||
while (index !== -1) {
|
||||
matches.push(index);
|
||||
index = lowerText.indexOf(lowerKey, index + len);
|
||||
}
|
||||
if (!matches.length) {
|
||||
return
|
||||
}
|
||||
const distances = matches.map(start => {
|
||||
const end = start + len
|
||||
const str = text.slice(start, end);
|
||||
// the case of all keywords together weighs less than one penalty below, so whole words in another case stay above a match inside a word
|
||||
let distance = 0.4 * leven(key, str) / len / keywords.length;
|
||||
const prev = text.slice(start - 1, start);
|
||||
if (prev) {
|
||||
if (/[A-Za-z]/.test(prev)) {
|
||||
distance += 1;
|
||||
} else if (/[0-9]/.test(prev)) {
|
||||
distance += 0.8;
|
||||
}
|
||||
}
|
||||
const next = text.slice(end, end + 1);
|
||||
if (next) {
|
||||
if (/[A-Za-z]/.test(next)) {
|
||||
distance += 0.8;
|
||||
} else if (/[0-9]/.test(next)) {
|
||||
distance += 0.5;
|
||||
}
|
||||
}
|
||||
return distance;
|
||||
});
|
||||
return {
|
||||
// min
|
||||
distance: Math.min.apply(null, distances)
|
||||
}
|
||||
}).filter(it => it);
|
||||
if (matchedItems.length < keywords.length) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
// avg
|
||||
distance: matchedItems.map(it => it.distance).reduce((p, v) => p + v, 0) / matchedItems.length
|
||||
}
|
||||
}).filter(it => it);
|
||||
// by distance
|
||||
let distance = Math.min.apply(null, matchedList.map(it => it.distance));
|
||||
// by matched count
|
||||
distance += 1 - matchedList.length / searchableColumns.length;
|
||||
// by stars, up to the top of the scale
|
||||
const stars = Math.min(Number(rowItem.stars) || 0, 10000);
|
||||
distance += 1 - stars / 10000;
|
||||
// score
|
||||
return 1 / distance;
|
||||
}
|
||||
|
||||
async handleImportFail(rowItem) {
|
||||
@@ -713,10 +817,13 @@ export class CustomNodesManager {
|
||||
const container = document.createElement('div');
|
||||
|
||||
if (rowItem.action === 'invalid-installation') {
|
||||
const invalidTag = document.createElement('span');
|
||||
invalidTag.style.color = 'red';
|
||||
invalidTag.innerHTML = '<b>(INVALID)</b>';
|
||||
container.appendChild(invalidTag);
|
||||
const button = document.createElement('button');
|
||||
button.className = 'cn-btn-invalid-installation';
|
||||
button.innerText = 'INVALID INSTALLATION ↗';
|
||||
button.title = INVALID_INSTALLATION_GUIDANCE;
|
||||
button.onclick = () => show_message(`<span style="color: var(--fg-color)"><B>The '${title}' nodepack is an invalid installation.</B><BR><HR><BR>${INVALID_INSTALLATION_GUIDANCE}<BR><BR>To fix it, click <B>Reinstall</B> in the Action column of its row.</span>`);
|
||||
container.appendChild(button);
|
||||
container.appendChild(document.createElement('br'));
|
||||
} else if (rowItem.action === 'import-fail') {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'cn-btn-import-failed';
|
||||
@@ -780,6 +887,7 @@ export class CustomNodesManager {
|
||||
id: "nodes",
|
||||
name: "Nodes",
|
||||
width: 100,
|
||||
sortAsc: false,
|
||||
formatter: (v, rowItem, columnItem) => {
|
||||
if (!rowItem.nodes) {
|
||||
return '';
|
||||
@@ -792,13 +900,6 @@ export class CustomNodesManager {
|
||||
list.push('</div>');
|
||||
return list.join("");
|
||||
}
|
||||
}, {
|
||||
id: "alternatives",
|
||||
name: "Alternatives",
|
||||
width: 400,
|
||||
maxWidth: 5000,
|
||||
invisible: !this.hasAlternatives(),
|
||||
classMap: 'cn-pack-desc'
|
||||
}, {
|
||||
id: 'description',
|
||||
name: 'Description',
|
||||
@@ -821,6 +922,7 @@ export class CustomNodesManager {
|
||||
id: 'stars',
|
||||
name: '★',
|
||||
align: 'center',
|
||||
sortAsc: false,
|
||||
classMap: "cn-pack-stars",
|
||||
formatter: (stars) => {
|
||||
if (stars < 0) {
|
||||
@@ -836,6 +938,7 @@ export class CustomNodesManager {
|
||||
name: 'Last Update',
|
||||
align: 'center',
|
||||
type: 'date',
|
||||
sortAsc: false,
|
||||
width: 100,
|
||||
classMap: "cn-pack-last-update",
|
||||
formatter: (last_update) => {
|
||||
@@ -882,11 +985,6 @@ export class CustomNodesManager {
|
||||
updateGrid() {
|
||||
if (this.grid) {
|
||||
this.grid.update();
|
||||
if (this.hasAlternatives()) {
|
||||
this.grid.showColumn("alternatives");
|
||||
} else {
|
||||
this.grid.hideColumn("alternatives");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1411,7 +1509,8 @@ export class CustomNodesManager {
|
||||
if(mode === "reinstall") {
|
||||
title = title || `${list.length} custom nodes`;
|
||||
|
||||
const confirmed = await customConfirm(`Are you sure reinstall ${title}?`);
|
||||
const what = list.length > 1 ? "their folders and installs the nodepacks" : "its folder and installs the nodepack";
|
||||
const confirmed = await customConfirm(`Reinstall ${title}? This deletes ${what} again.`);
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
@@ -1423,7 +1522,7 @@ export class CustomNodesManager {
|
||||
let needRestart = false;
|
||||
let errorMsg = "";
|
||||
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// Set install_context BEFORE per-item queue enqueue calls so that any
|
||||
// server-side synchronous completion (e.g., sync enable of an inactive
|
||||
@@ -1476,6 +1575,7 @@ export class CustomNodesManager {
|
||||
|
||||
const res = await api.fetchApi(`/manager/queue/${api_mode}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
@@ -1513,12 +1613,68 @@ export class CustomNodesManager {
|
||||
}
|
||||
}
|
||||
else {
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
this.showStop();
|
||||
showTerminal();
|
||||
}
|
||||
}
|
||||
|
||||
async checkUpdate(mode) {
|
||||
infoToast('Fetching updated information. This may take some time if many custom nodes are installed.');
|
||||
this.showStatus("Checking updates ...");
|
||||
|
||||
this.checkId = generateUUID();
|
||||
const checked = new Promise(resolve => {
|
||||
this.resumeLoad = resolve;
|
||||
});
|
||||
await this.askForCheck(mode);
|
||||
|
||||
const updatable = await checked;
|
||||
if(!updatable) {
|
||||
this.showError("Failed to check updates.");
|
||||
}
|
||||
return updatable;
|
||||
}
|
||||
|
||||
async askForCheck(mode) {
|
||||
const ui_id = this.checkId;
|
||||
const { error } = await fetchData('/customnode/check_update', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mode, ui_id })
|
||||
});
|
||||
// the answer to a request of an earlier check says nothing about the check that is waited for now
|
||||
if(error && ui_id == this.checkId) {
|
||||
this.resumeLoad?.();
|
||||
this.resumeLoad = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
onCheckUpdate(event) {
|
||||
let self = CustomNodesManager.instance;
|
||||
if(!self.resumeLoad) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { status, done_count, total_count, updatable, ui_ids } = event.detail;
|
||||
if(status == 'in_progress') {
|
||||
self.showStatus(`Checking updates (${sanitizeHTML(String(done_count))}/${sanitizeHTML(String(total_count))}) ...`);
|
||||
}
|
||||
// a check that ended before the request of this page reached it does not name the request
|
||||
else if(status == 'done' && ui_ids.includes(self.checkId)) {
|
||||
self.resumeLoad(updatable);
|
||||
self.resumeLoad = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
onReconnected() {
|
||||
let self = CustomNodesManager.instance;
|
||||
if(self.resumeLoad) {
|
||||
// the events of a check are not sent again once the connection was lost
|
||||
self.askForCheck(manager_instance.datasrc_combo.value);
|
||||
}
|
||||
}
|
||||
|
||||
async onQueueStatus(event) {
|
||||
let self = CustomNodesManager.instance;
|
||||
if(event.detail.status == 'in_progress' && event.detail.ui_target == 'nodepack_manager') {
|
||||
@@ -1671,6 +1827,21 @@ export class CustomNodesManager {
|
||||
return allUsedNodes;
|
||||
}
|
||||
|
||||
getNodepackByCnrId(cnr_id) {
|
||||
let item = this.custom_nodes[cnr_id];
|
||||
// comfy-core is ComfyUI itself, not a nodepack that is named so in another case
|
||||
if(item || cnr_id == 'comfy-core') {
|
||||
return item;
|
||||
}
|
||||
|
||||
const normalized_id = String(cnr_id).toLowerCase();
|
||||
for(let k in this.custom_nodes) {
|
||||
if(k.toLowerCase() == normalized_id) {
|
||||
return this.custom_nodes[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async getMissingNodes() {
|
||||
let unresolved_missing_nodes = new Set();
|
||||
let hashMap = {};
|
||||
@@ -1695,7 +1866,7 @@ export class CustomNodesManager {
|
||||
outdated_comfyui = true;
|
||||
}
|
||||
|
||||
let item = this.custom_nodes[node.properties.cnr_id];
|
||||
let item = this.getNodepackByCnrId(node.properties.cnr_id);
|
||||
if(item) {
|
||||
hashMap[item.hash] = true;
|
||||
}
|
||||
@@ -1881,41 +2052,6 @@ export class CustomNodesManager {
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
async getAlternatives() {
|
||||
const mode = manager_instance.datasrc_combo.value;
|
||||
this.showStatus(`Loading alternatives (${mode}) ...`);
|
||||
const res = await fetchData(`/customnode/alternatives?mode=${mode}`);
|
||||
if (res.error) {
|
||||
this.showError(`Failed to get alternatives: ${sanitizeHTML(String(res.error))}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const hashMap = {};
|
||||
const items = res.data;
|
||||
|
||||
for(let i in items) {
|
||||
let item = items[i];
|
||||
let custom_node = this.custom_nodes[i];
|
||||
|
||||
if (!custom_node) {
|
||||
console.log(`Not found custom node: ${item.id}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// tags (alter-list.json) is not server-transformed, so escape before innerHTML.
|
||||
const tags = `${item.tags}`.split(",").map(tag => {
|
||||
return `<div>${sanitizeHTML(tag.trim())}</div>`;
|
||||
}).join("");
|
||||
|
||||
hashMap[custom_node.hash] = {
|
||||
alternatives: `<div class="cn-tag-list">${tags}</div> ${item.description}`
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
async getUsedInAnyWorkflow() {
|
||||
this.showStatus(`Loading workflow usage analysis ...`);
|
||||
|
||||
@@ -1964,18 +2100,25 @@ export class CustomNodesManager {
|
||||
this.show_mode = show_mode;
|
||||
console.log("Show mode:", show_mode);
|
||||
|
||||
this.resumeLoad = undefined;
|
||||
|
||||
this.showLoading();
|
||||
|
||||
const mode = manager_instance.datasrc_combo.value;
|
||||
this.showStatus(`Loading custom nodes (${mode}) ...`);
|
||||
|
||||
const skip_update = this.show_mode === ShowMode.UPDATE ? "" : "&skip_update=true";
|
||||
|
||||
if(this.show_mode === ShowMode.UPDATE) {
|
||||
infoToast('Fetching updated information. This may take some time if many custom nodes are installed.');
|
||||
let updatable = [];
|
||||
if(show_mode === ShowMode.UPDATE) {
|
||||
updatable = await this.checkUpdate(mode);
|
||||
if(!updatable) {
|
||||
this.hideLoading();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const res = await fetchData(`/customnode/getlist?mode=${mode}${skip_update}`);
|
||||
this.showStatus(`Loading custom nodes (${mode}) ...`);
|
||||
|
||||
// a server that was not restarted since its update still fetches every repository without skip_update
|
||||
const res = await fetchData(`/customnode/getlist?mode=${mode}&skip_update=true`);
|
||||
if (res.error) {
|
||||
this.showError("Failed to get custom node list.");
|
||||
this.hideLoading();
|
||||
@@ -1984,6 +2127,12 @@ export class CustomNodesManager {
|
||||
|
||||
const { channel, node_packs } = res.data;
|
||||
|
||||
for(const k of updatable) {
|
||||
if(node_packs[k]) {
|
||||
node_packs[k]['update-state'] = "true";
|
||||
}
|
||||
}
|
||||
|
||||
if(isElectron) {
|
||||
delete node_packs['comfyui-manager'];
|
||||
}
|
||||
@@ -2021,8 +2170,6 @@ export class CustomNodesManager {
|
||||
}
|
||||
} else if(this.show_mode == ShowMode.MISSING) {
|
||||
hashMap = await this.getMissingNodes();
|
||||
} else if(this.show_mode == ShowMode.ALTERNATIVES) {
|
||||
hashMap = await this.getAlternatives();
|
||||
} else if(this.show_mode == ShowMode.FAVORITES) {
|
||||
hashMap = await this.getFavorites();
|
||||
} else if(this.show_mode == ShowMode.IN_WORKFLOW) {
|
||||
@@ -2073,9 +2220,6 @@ export class CustomNodesManager {
|
||||
if (value === ShowMode.MISSING) {
|
||||
nodeItem['missing-node'] = "true";
|
||||
}
|
||||
if (typeof hashData === "object") {
|
||||
Object.assign(nodeItem, hashData);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (nodeItem.state === value) {
|
||||
@@ -2149,6 +2293,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
showLoading() {
|
||||
this.loading = true;
|
||||
this.setDisabled(true);
|
||||
if (this.grid) {
|
||||
this.grid.showLoading();
|
||||
@@ -2159,6 +2304,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
hideLoading() {
|
||||
this.loading = false;
|
||||
this.setDisabled(false);
|
||||
if (this.grid) {
|
||||
this.grid.hideLoading();
|
||||
|
||||
+14
-24
@@ -171,7 +171,7 @@ export class ModelManager {
|
||||
|
||||
".cmm-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -256,31 +256,20 @@ export class ModelManager {
|
||||
rowFilter: (rowItem) => {
|
||||
|
||||
const searchableColumns = ["name", "type", "base", "description", "filename", "save_path"];
|
||||
const models_extensions = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'];
|
||||
|
||||
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
|
||||
|
||||
if (shouldShown) {
|
||||
if(this.filter) {
|
||||
if (this.filter == "in_workflow") {
|
||||
rowItem.in_workflow = null;
|
||||
if (Array.isArray(app.graph._nodes)) {
|
||||
app.graph._nodes.forEach((item, i) => {
|
||||
if (Array.isArray(item.widgets_values)) {
|
||||
item.widgets_values.forEach((_item, i) => {
|
||||
if (rowItem.in_workflow === null && _item !== null && models_extensions.includes("." + _item.toString().split('.').pop())) {
|
||||
let filename = _item.match(/([^\/]+)(?=\.\w+$)/)[0];
|
||||
if (grid.highlightKeywordsFilter(rowItem, searchableColumns, filename)) {
|
||||
rowItem.in_workflow = "True";
|
||||
grid.highlightKeywordsFilter(rowItem, searchableColumns, "");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return ((this.filter == "installed" && rowItem.installed == "True") || (this.filter == "not_installed" && rowItem.installed == "False") || (this.filter == "in_workflow" && rowItem.in_workflow == "True"));
|
||||
if(this.filter == "installed" && rowItem.installed !== "True") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.filter == "not_installed" && rowItem.installed !== "False") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.filter == "in_workflow" && !app.graph._nodes.some(node => Array.isArray(node.widgets_values) && node.widgets_values.some(value => String(value).split(/[\\/]/).pop() === rowItem.filename))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.type && rowItem.type !== this.type) {
|
||||
@@ -454,7 +443,7 @@ export class ModelManager {
|
||||
let needRefresh = false;
|
||||
let errorMsg = "";
|
||||
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
let target_items = [];
|
||||
|
||||
@@ -476,6 +465,7 @@ export class ModelManager {
|
||||
|
||||
const res = await api.fetchApi(`/manager/queue/install_model`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
@@ -515,7 +505,7 @@ export class ModelManager {
|
||||
}
|
||||
}
|
||||
else {
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST' });
|
||||
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
// The queue can end before this request is answered.
|
||||
if(this.install_context === context) {
|
||||
this.showStop();
|
||||
|
||||
@@ -357,6 +357,7 @@ export class NodeUsageAnalyzer {
|
||||
|
||||
const res = await api.fetchApi(`/manager/queue/install_model`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
|
||||
+1
-1
@@ -77,7 +77,7 @@ async function remove_snapshot(target) {
|
||||
|
||||
async function save_current_snapshot() {
|
||||
try {
|
||||
const response = await api.fetchApi('/snapshot/save', { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi('/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
app.ui.dialog.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ class WorkflowMetadataExtension {
|
||||
this.installedNodes[nodePackageName.toLowerCase()] ??
|
||||
{};
|
||||
|
||||
if (cnr_id === "comfy-core") return; // don't allow hijacking comfy-core name
|
||||
if (cnr_id?.toLowerCase() === "comfy-core") return; // don't allow hijacking comfy-core name
|
||||
if (cnr_id) nodeProperties.cnr_id = cnr_id;
|
||||
else nodeProperties.aux_id = aux_id;
|
||||
if (ver) nodeProperties.ver = ver.trim();
|
||||
|
||||
@@ -1973,6 +1973,51 @@
|
||||
"url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth",
|
||||
"size": "375.0MB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-H SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-H) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_h_4b8939.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_h_4b8939.safetensors",
|
||||
"size": "2.56GB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-L SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-L) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_l_0b3195.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_l_0b3195.safetensors",
|
||||
"size": "1.25GB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-B SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-B) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_b_01ec64.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_b_01ec64.safetensors",
|
||||
"size": "375.0MB"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sam3.1_multiplex_fp16.safetensors",
|
||||
"type": "sam3.1",
|
||||
"base": "SAM",
|
||||
"save_path": "checkpoints",
|
||||
"description": "Segment Anything SAM 3.1 model (multiplex, fp16), repackaged for ComfyUI by Comfy-Org",
|
||||
"reference": "https://huggingface.co/Comfy-Org/sam3.1",
|
||||
"filename": "sam3.1_multiplex_fp16.safetensors",
|
||||
"url": "https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors",
|
||||
"size": "1.75GB"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sam2.1_hiera_tiny.pt",
|
||||
|
||||
@@ -1,5 +1,26 @@
|
||||
{
|
||||
"custom_nodes": [
|
||||
{
|
||||
"author": "Raykosan",
|
||||
"title": "ComfyUI Custom Node Manager [UNSAFE]",
|
||||
"reference": "https://github.com/Raykosan/ComfyUI-Custom-Node-Manager",
|
||||
"files": [
|
||||
"https://github.com/Raykosan/ComfyUI-Custom-Node-Manager"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Alternative manager for custom_nodes that bypasses ComfyUI Manager restrictions. [w/This nodepack installs any repository from GitHub, GitLab, Bitbucket, Codeberg or Gitea at any version, without the install checks of ComfyUI-Manager.]"
|
||||
},
|
||||
{
|
||||
"author": "ruiqutech",
|
||||
"title": "RuiquNodes for ComfyUI [SECURITY ISSUE]",
|
||||
"id": "RuiquNodes",
|
||||
"reference": "https://github.com/ruiqutech/ComfyUI-RuiquNodes",
|
||||
"files": [
|
||||
"https://github.com/ruiqutech/ComfyUI-RuiquNodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes of EvaluateMultiple1, EvaluateMultiple3...\nSupport the execution of any fragment of Python code, generating multiple outputs from multiple inputs. [w/This nodepack has a remote code execution vulnerability. Its Evaluate nodes run any Python code the workflow supplies, with no restriction, so a workflow you queue, or a request sent to a ComfyUI server reachable from the network, can run any program on the host.]"
|
||||
},
|
||||
{
|
||||
"author": "rohit267",
|
||||
"title": "Champdev Custom Nodes [SECURITY ISSUE]",
|
||||
@@ -784,16 +805,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "Audio duration analysis node. (Description by CC)\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "lunaaispace-eng",
|
||||
"title": "LLM_Prompt [WIP]",
|
||||
"reference": "https://github.com/lunaaispace-eng/LLM_Prompt",
|
||||
"files": [
|
||||
"https://github.com/lunaaispace-eng/LLM_Prompt"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "LLM prompt node for ComfyUI. (Description by CC)\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "lyeeedar",
|
||||
"title": "Keep Largest Blob [WIP]",
|
||||
@@ -844,16 +855,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node that routes detected face SEGS to separate outputs by matching each face crop to text prompts via CLIP image-text cosine similarity.\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "Agnuxo1",
|
||||
"title": "silicon-comfyui-node [WIP]",
|
||||
"reference": "https://github.com/Agnuxo1/silicon-comfyui-node",
|
||||
"files": [
|
||||
"https://github.com/Agnuxo1/silicon-comfyui-node"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node that embeds and verifies cryptographic watermarks in images using SiliconSignature technology.\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "Bigornh2o",
|
||||
"title": "ComfyUI-Bigornh2oSmartResolution [WIP]",
|
||||
@@ -2517,16 +2518,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom node for sending generated videos to Telegram, enabling direct output sharing to messaging platforms. (Description by CC)[w/This nodepack contains a node that has a vulnerability allowing write to arbitrary file paths.]"
|
||||
},
|
||||
{
|
||||
"author": "Laolilzp",
|
||||
"title": "Laoli3D [UNSAFE]",
|
||||
"reference": "https://github.com/Laolilzp/Laoli3D",
|
||||
"files": [
|
||||
"https://github.com/Laolilzp/Laoli3D"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI 3D pose editor enabling visual character manipulation and ControlNet image generation for precise AI figure control without prompt description. (Description by CC)[w/This nodepack contains a node that has a vulnerability allowing write to arbitrary file paths.]"
|
||||
},
|
||||
{
|
||||
"author": "Goldlionren",
|
||||
"title": "ComfyUI_Bridge_fabric [UNSAFE]",
|
||||
@@ -6974,16 +6965,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI nodes from [Timesaver](https://github.com/AlexYez/comfyui-timesaver)."
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "ComfyUI-Papcorns-Node-UploadToGCS",
|
||||
"reference": "https://github.com/papcorns/ComfyUI-Papcorns-Node-UploadToGCS",
|
||||
"files": [
|
||||
"https://github.com/papcorns/ComfyUI-Papcorns-Node-UploadToGCS"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "NODES: Upload Image To GCS"
|
||||
},
|
||||
{
|
||||
"author": "ZHO-ZHO-ZHO",
|
||||
"title": "Qwen-2.5 in ComfyUI [NAME CONFLICT]",
|
||||
@@ -7144,16 +7125,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "A collection of utility nodes for handling condition tensors in ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "gordon123",
|
||||
"title": "ComfyUI_DreamBoard [WIP]",
|
||||
"reference": "https://github.com/gordon123/ComfyUI_DreamBoard",
|
||||
"files": [
|
||||
"https://github.com/gordon123/ComfyUI_DreamBoard"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "for making storyboard UNDERCONSTRUCTION!"
|
||||
},
|
||||
{
|
||||
"author": "erosDiffusion",
|
||||
"title": "Select key from JSON (Alpha) [UNSAFE]",
|
||||
@@ -7774,16 +7745,6 @@
|
||||
"install_type": "git-clone",
|
||||
"description": "NODES: Eagle Image Node for PNGInfo, SDXL Resolution Presets (ws), SDXL Prompt Styler, SDXL Prompt Styler Advanced"
|
||||
},
|
||||
{
|
||||
"author": "AlejandroTuzzi",
|
||||
"title": "TUZZI-ByPass [WIP]",
|
||||
"reference": "https://github.com/AlejandroTuzzi/TUZZI-ByPass",
|
||||
"files": [
|
||||
"https://github.com/AlejandroTuzzi/TUZZI-ByPass"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom nodes for automated AI pipelines\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "oxysoft",
|
||||
"title": "Comfy-Compel",
|
||||
|
||||
@@ -1,5 +1,314 @@
|
||||
{
|
||||
"custom_nodes": [
|
||||
{
|
||||
"author": "lunaaispace-eng",
|
||||
"title": "LLM_Prompt [WIP] [REMOVED]",
|
||||
"reference": "https://github.com/lunaaispace-eng/LLM_Prompt",
|
||||
"files": [
|
||||
"https://github.com/lunaaispace-eng/LLM_Prompt"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "LLM prompt node for ComfyUI. (Description by CC)\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "Laolilzp",
|
||||
"title": "Laoli3D [UNSAFE] [REMOVED]",
|
||||
"reference": "https://github.com/Laolilzp/Laoli3D",
|
||||
"files": [
|
||||
"https://github.com/Laolilzp/Laoli3D"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI 3D pose editor enabling visual character manipulation and ControlNet image generation for precise AI figure control without prompt description. (Description by CC)[w/This nodepack contains a node that has a vulnerability allowing write to arbitrary file paths.]"
|
||||
},
|
||||
{
|
||||
"author": "gordon123",
|
||||
"title": "ComfyUI_DreamBoard [WIP] [REMOVED]",
|
||||
"reference": "https://github.com/gordon123/ComfyUI_DreamBoard",
|
||||
"files": [
|
||||
"https://github.com/gordon123/ComfyUI_DreamBoard"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "for making storyboard UNDERCONSTRUCTION!"
|
||||
},
|
||||
{
|
||||
"author": "Agnuxo1",
|
||||
"title": "silicon-comfyui-node [WIP] [REMOVED]",
|
||||
"reference": "https://github.com/Agnuxo1/silicon-comfyui-node",
|
||||
"files": [
|
||||
"https://github.com/Agnuxo1/silicon-comfyui-node"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node that embeds and verifies cryptographic watermarks in images using SiliconSignature technology.\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "Zeknes",
|
||||
"title": "Comfyui-LLM-Chat [REMOVED]",
|
||||
"reference": "https://github.com/Zeknes/Comfyui-LLM-Chat",
|
||||
"files": [
|
||||
"https://github.com/Zeknes/Comfyui-LLM-Chat"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom ComfyUI node providing unified access to multiple Large Language Models including OpenAI-compatible APIs and local Ollama instances with image support."
|
||||
},
|
||||
{
|
||||
"author": "toxicwind",
|
||||
"title": "TTools for ComfyUI [REMOVED]",
|
||||
"id": "ttools",
|
||||
"reference": "https://github.com/toxicwind/ComfyUI-TTools",
|
||||
"files": [
|
||||
"https://github.com/toxicwind/ComfyUI-TTools"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text Randomization and Formatting, JSON Extraction and Processing, SD3 Resolution Solver"
|
||||
},
|
||||
{
|
||||
"author": "StarIICraft",
|
||||
"title": "ComfyUI-Simple-Selector [REMOVED]",
|
||||
"reference": "https://github.com/StarIICraft/ComfyUI-Simple-Selector",
|
||||
"files": [
|
||||
"https://github.com/StarIICraft/ComfyUI-Simple-Selector"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Logic control node with 5 universal input ports that checks connections in reverse priority order and outputs the index of the first valid active input, with support for muted nodes and any data type."
|
||||
},
|
||||
{
|
||||
"author": "latentastronaut",
|
||||
"title": "comfyui-latent-astronaut-suite [REMOVED]",
|
||||
"reference": "https://github.com/latentastronaut/comfyui-latent-astronaut-suite",
|
||||
"files": [
|
||||
"https://github.com/latentastronaut/comfyui-latent-astronaut-suite"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI nodes for batch processing, loops, and iteration workflows"
|
||||
},
|
||||
{
|
||||
"author": "isam2024",
|
||||
"title": "ComfyUI-FluxHallucinate [REMOVED]",
|
||||
"reference": "https://github.com/isam2024/ComfyUI-FluxHallucinate",
|
||||
"files": [
|
||||
"https://github.com/isam2024/ComfyUI-FluxHallucinate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Intentionally degrade Flux dev.1's prompt adherence to recreate the loose, random, *hallucinatory* feel of SD1.5 / SDXL."
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Clone Output [REMOVED]",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-clone-output",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-clone-output"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Clone Output"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Booleangate [REMOVED]",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-booleangate",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-booleangate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Booleangate"
|
||||
},
|
||||
{
|
||||
"author": "IA-gyz",
|
||||
"title": "Magik Basic Nodes [REMOVED]",
|
||||
"reference": "https://github.com/IA-gyz/comfyui-magik-basic-nodes",
|
||||
"files": [
|
||||
"https://github.com/IA-gyz/comfyui-magik-basic-nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Magik Basic Nodes"
|
||||
},
|
||||
{
|
||||
"author": "huygiatrng",
|
||||
"title": "Facefusion_comfyui [REMOVED]",
|
||||
"reference": "https://github.com/huygiatrng/Facefusion_comfyui",
|
||||
"files": [
|
||||
"https://github.com/huygiatrng/Facefusion_comfyui"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Advanced face swapping for ComfyUI with local ONNX inference - no API required!"
|
||||
},
|
||||
{
|
||||
"author": "Herony82",
|
||||
"title": "WanAnimatePreprocess Track [REMOVED]",
|
||||
"reference": "https://github.com/Herony82/ComfyUI-WanAnimatePreprocess-track",
|
||||
"files": [
|
||||
"https://github.com/Herony82/ComfyUI-WanAnimatePreprocess-track"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "TrackedPoseAndFaceDetection - PoseAndFaceDetection con selezione manuale dei punti di tracking e optical flow (Lucas-Kanade). Richiede ComfyUI-WanAnimatePreprocess."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-Veida [REMOVED]",
|
||||
"id": "comfyui-veida",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-Veida",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-Veida"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images through the Veida AI API. Works without an API key on the free tier; add a key to use your account's models (GPT Image 2.5, GPT Image 2, Nano Banana 2, Seedream 5.0)."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-SayMaker [REMOVED]",
|
||||
"id": "comfyui-saymaker",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-SayMaker",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-SayMaker"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images and animate them into video through the SayMaker API (Veo 3.1, Kling 3.0, Seedance 2.0, Nano Banana 2, GPT Image 2.5). No local GPU; needs a SayMaker API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-movoa [REMOVED]",
|
||||
"id": "comfyui-movoa",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-movoa",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-movoa"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to video and photo to video with sound via Movoa (movoa.ai). Standard library only; requires a Movoa API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-Kavel [REMOVED]",
|
||||
"id": "comfyui-kavel",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-Kavel",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-Kavel"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images through the kavel.ai API. Works without an API key on the free tier; add a key to use your account's models (Nano Banana 2, GPT Image 2, Seedream)."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-FreeImageToVideo [REMOVED]",
|
||||
"id": "comfyui-freeimagetovideo",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-FreeImageToVideo",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-FreeImageToVideo"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to video and image to video with sound (MiniMax H3) through the Free Image to Video API: connect any IMAGE as the first frame or leave it empty for text to video; the MP4 is saved to the output folder. No local GPU; needs a Free Image to Video API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-emaki [REMOVED]",
|
||||
"id": "comfyui-emaki",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-emaki",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-emaki"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Seedance 2.5 text to video and image to video through the emaki API (Seedance 2.0, MiniMax H3, Veo 3.1 and Nano Banana 2 for first frames too). No local GPU; needs an emaki API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-aigifmaker [REMOVED]",
|
||||
"id": "comfyui-aigifmaker",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-aigifmaker",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-aigifmaker"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to animated GIF through the AI GIF Maker API (native GIF generation, not a converted video). Outputs every frame as an IMAGE batch plus the saved .gif. No local GPU; needs an AI GIF Maker API key."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-abvg [REMOVED]",
|
||||
"id": "comfyui-abvg",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-abvg",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-abvg"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "AI birthday video generator from a single photo: they pop champagne on a park bench, blow out a Scorpio cake, or light a crown cake at the car window. Generate 12s 720p vertical birthday clips on Seedance 2 Mini via https://aibirthdayvideogenerator.com/."
|
||||
},
|
||||
{
|
||||
"author": "evanscho",
|
||||
"title": "Advanced Mask Nodes [REMOVED]",
|
||||
"reference": "https://github.com/evanscho/ComfyUI-advanced-mask-nodes",
|
||||
"files": [
|
||||
"https://github.com/evanscho/ComfyUI-advanced-mask-nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A collection of custom nodes for ComfyUI"
|
||||
},
|
||||
{
|
||||
"author": "Ave-Mollan",
|
||||
"title": "civitai-sdk-api-nodes-for-comfyui [REMOVED]",
|
||||
"reference": "https://github.com/Ave-Mollan/CivitAI-SDK-API-nodes-for-ComfyUI",
|
||||
"files": [
|
||||
"https://github.com/Ave-Mollan/CivitAI-SDK-API-nodes-for-ComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom nodes for CivitAI cloud image generation via API"
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "ComfyUI-Papcorns-Node-UploadToGCS [REMOVED]",
|
||||
"reference": "https://github.com/papcorns/ComfyUI-Papcorns-Node-UploadToGCS",
|
||||
"files": [
|
||||
"https://github.com/papcorns/ComfyUI-Papcorns-Node-UploadToGCS"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "NODES: Upload Image To GCS"
|
||||
},
|
||||
{
|
||||
"author": "AlejandroTuzzi",
|
||||
"title": "TUZZI-ByPass [WIP] [REMOVED]",
|
||||
"reference": "https://github.com/AlejandroTuzzi/TUZZI-ByPass",
|
||||
"files": [
|
||||
"https://github.com/AlejandroTuzzi/TUZZI-ByPass"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom nodes for automated AI pipelines\nNOTE: The files in the repo are not organized."
|
||||
},
|
||||
{
|
||||
"author": "SorenWeile",
|
||||
"title": "INDG_CustomNodes [REMOVED]",
|
||||
"reference": "https://github.com/SorenWeile/INDG_CustomNodes",
|
||||
"files": [
|
||||
"https://github.com/SorenWeile/INDG_CustomNodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Custom ComfyUI nodes for the INDG toolset including flexible image batching, path utilities, and memory cleanup."
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "Papcorns ComfyUI Custom Nodes [REMOVED]",
|
||||
"reference": "https://github.com/papcorns/Papcorns-Comfyui-Custom-Nodes",
|
||||
"files": [
|
||||
"https://github.com/papcorns/Papcorns-Comfyui-Custom-Nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A collection of custom nodes for ComfyUI that enhances image processing and cloud storage capabilities."
|
||||
},
|
||||
{
|
||||
"author": "papcorns",
|
||||
"title": "ComfyUI Load Image From URL [REMOVED]",
|
||||
"reference": "https://github.com/papcorns/ComfyUI-Papcorns-Node-LoadImageFromUrl",
|
||||
"files": [
|
||||
"https://github.com/papcorns/ComfyUI-Papcorns-Node-LoadImageFromUrl"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A ComfyUI custom node that allows you to load images directly from URLs or local file paths. This node provides a convenient way to import images into your ComfyUI workflows without manually downloading them first."
|
||||
},
|
||||
{
|
||||
"author": "fofr",
|
||||
"title": "ComfyUI-Replicate [REMOVED]",
|
||||
"reference": "https://github.com/replicate/comfyui-replicate",
|
||||
"files": [
|
||||
"https://github.com/replicate/comfyui-replicate"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Run [a/Replicate models](https://replicate.com/explore) in ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "Marigold1122",
|
||||
"title": "Chat-Image-Bridge-Node [REMOVED]",
|
||||
|
||||
@@ -1,5 +1,515 @@
|
||||
{
|
||||
"custom_nodes": [
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "GPT Image",
|
||||
"id": "gpt-image",
|
||||
"reference": "https://github.com/AceDataCloud/GPTImageComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GPTImageComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit images with GPT Image, retrieve task results, and load the resulting images in ComfyUI. Requires an Ace Data Cloud API key. Generation and editing are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "ACE Music",
|
||||
"id": "ace-acemusic",
|
||||
"reference": "https://github.com/AceDataCloud/ACEMusicComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/ACEMusicComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate ACE Music songs and lyrics, import reference assets, and retrieve results by task ID. Requires an Ace Data Cloud API key. Generation and reference imports are metered."
|
||||
},
|
||||
{
|
||||
"author": "assetfeed",
|
||||
"title": "AssetFeed",
|
||||
"reference": "https://github.com/assetfeed/comfyui-assetfeed",
|
||||
"files": [
|
||||
"https://github.com/assetfeed/comfyui-assetfeed"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes for the AssetFeed API: AssetFeed OCR reads the text in an image, and AssetFeed AI Text Check estimates the AI-written share of an English text. Needs an ASSETFEED_API_KEY environment variable; images and text are sent to api.assetfeed.com; data handling is in the README."
|
||||
},
|
||||
{
|
||||
"author": "Raykosan (RaykoStudio)",
|
||||
"title": "ComfyUI-RS_WorkspaceManager",
|
||||
"reference": "https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager",
|
||||
"files": [
|
||||
"https://github.com/Raykosan/ComfyUI-RS_WorkspaceManager"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Workflow Preset Manager and Interface Settings Backup for ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "bewizsky",
|
||||
"title": "Eyes4AI Text Repair",
|
||||
"reference": "https://github.com/bewizsky/eyes4ai-text-repair",
|
||||
"files": [
|
||||
"https://github.com/bewizsky/eyes4ai-text-repair"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Find misspelled text in photos and AI-generated images with Gemini, then use an image-editing workflow to fix localized text and review spelling and style. Includes check-only and SenseNova U1.6 examples."
|
||||
},
|
||||
{
|
||||
"author": "ukr8b3g-cmyk",
|
||||
"title": "Anima Character Sheet Designer",
|
||||
"reference": "https://github.com/ukr8b3g-cmyk/Anima-Character-Sheet-Designer",
|
||||
"files": [
|
||||
"https://github.com/ukr8b3g-cmyk/Anima-Character-Sheet-Designer"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create character sheets in ComfyUI with Anima, using prompt text or local image tags. Generate up to 13 independent views with editable prompts and assemble them into a sheet."
|
||||
},
|
||||
{
|
||||
"author": "alaintural",
|
||||
"title": "SyncTile for MiniMax H3",
|
||||
"id": "synctile-h3",
|
||||
"reference": "https://github.com/alaintural/synctile-h3",
|
||||
"files": [
|
||||
"https://github.com/alaintural/synctile-h3"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "SyncTileRefine takes a MiniMax H3 video to 1080p, 2K or 4K on one 24 GB card. Overlapping tiles are blended in latent space after every sampling step, so the result has no seams. A ready workflow is included."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Wan",
|
||||
"id": "wan",
|
||||
"reference": "https://github.com/AceDataCloud/WanComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/WanComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Wan videos and retrieve task results. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Veo",
|
||||
"id": "veo",
|
||||
"reference": "https://github.com/AceDataCloud/VeoComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/VeoComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate a Veo video and check its task status. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Seedream",
|
||||
"id": "seedream",
|
||||
"reference": "https://github.com/AceDataCloud/SeedreamComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/SeedreamComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create, edit or decompose images with Seedream. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Seedance",
|
||||
"id": "ace-seedance",
|
||||
"reference": "https://github.com/AceDataCloud/SeedanceComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/SeedanceComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate a Seedance video and load the completed video from its task ID. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Qwen Image",
|
||||
"id": "qwen-image",
|
||||
"reference": "https://github.com/AceDataCloud/QwenImageComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/QwenImageComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit an image with Qwen Image. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Nano Banana",
|
||||
"id": "nano-banana",
|
||||
"reference": "https://github.com/AceDataCloud/NanoBananaComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/NanoBananaComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit images with Nano Banana and load completed images. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "MiniMax H3",
|
||||
"id": "ace-minimax-h3",
|
||||
"reference": "https://github.com/AceDataCloud/MiniMaxH3ComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/MiniMaxH3ComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate MiniMax H3 videos and retrieve task results. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Midjourney",
|
||||
"id": "midjourney",
|
||||
"reference": "https://github.com/AceDataCloud/MidjourneyComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/MidjourneyComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Midjourney images and retrieve the original task. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Kling",
|
||||
"id": "kling",
|
||||
"reference": "https://github.com/AceDataCloud/KlingComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/KlingComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate or edit Kling videos and retrieve task results. Requires an Ace Data Cloud API key. Video requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Happy Horse",
|
||||
"id": "happy-horse",
|
||||
"reference": "https://github.com/AceDataCloud/HappyHorseComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/HappyHorseComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate and edit Happy Horse videos and retrieve the original task. Requires an Ace Data Cloud API key. Video requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Grok",
|
||||
"id": "grok",
|
||||
"reference": "https://github.com/AceDataCloud/GrokComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GrokComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate Grok videos and retrieve the result of a submitted task. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Google Search",
|
||||
"id": "google-search",
|
||||
"reference": "https://github.com/AceDataCloud/GoogleSearchComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/GoogleSearchComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Search Google from a workflow and return structured results. Requires an Ace Data Cloud API key. Searches are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Flux",
|
||||
"id": "flux",
|
||||
"reference": "https://github.com/AceDataCloud/FluxComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FluxComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Create images with FLUX through the hosted API. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Fish Audio",
|
||||
"id": "fish-audio",
|
||||
"reference": "https://github.com/AceDataCloud/FishAudioComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FishAudioComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Generate speech with Fish Audio and retrieve the resulting audio. Requires an Ace Data Cloud API key. Generation is metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Face Transform",
|
||||
"id": "face-transform",
|
||||
"reference": "https://github.com/AceDataCloud/FaceTransformComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/FaceTransformComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Analyze or transform a face in a supplied image. Requires an Ace Data Cloud API key. Image requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Ace Chat",
|
||||
"id": "ace-chat",
|
||||
"reference": "https://github.com/AceDataCloud/AceChatComfyUI",
|
||||
"files": [
|
||||
"https://github.com/AceDataCloud/AceChatComfyUI"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "List chat model IDs and send chat messages from a ComfyUI workflow. Requires an Ace Data Cloud API key. Chat requests are metered."
|
||||
},
|
||||
{
|
||||
"author": "2867297362mjb-sketch",
|
||||
"title": "comfyui-teamorouter",
|
||||
"reference": "https://github.com/2867297362mjb-sketch/comfyui-teamorouter",
|
||||
"files": [
|
||||
"https://github.com/2867297362mjb-sketch/comfyui-teamorouter"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "A chat node for the TeamoRouter API: write or expand prompts, caption an input image with a vision model, or translate text with Claude, GPT, Gemini, DeepSeek, GLM, Kimi or Qwen through one OpenAI-compatible API key. You need your own TeamoRouter API key and prepaid balance. No extra dependencies."
|
||||
},
|
||||
{
|
||||
"author": "Zrn59",
|
||||
"title": "ComfyUI-GGUF-Next",
|
||||
"id": "comfyui-gguf-next",
|
||||
"reference": "https://github.com/Zrn59/ComfyUI-GGUF-Next",
|
||||
"files": [
|
||||
"https://github.com/Zrn59/ComfyUI-GGUF-Next"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Fork of city96/ComfyUI-GGUF with the same node IDs: all 35 ggml quant types dequantized in torch on the GPU (IQ1/IQ2/IQ3, TQ, MXFP4, NVFP4), any diffusion architecture ComfyUI detects, more text encoders (Gemma 2, Qwen2, Mistral 3, Qwen3-VL incl. 32B, the Gemma 4 encoder of LTX-2.5), and models bigger than RAM kept memory-mapped. Disable the original ComfyUI-GGUF first: both register the same node names."
|
||||
},
|
||||
{
|
||||
"author": "sorryhyun",
|
||||
"title": "Anima Pixel Decoder",
|
||||
"reference": "https://github.com/sorryhyun/ComfyUI-Anima-PixelDecoder",
|
||||
"files": [
|
||||
"https://github.com/sorryhyun/ComfyUI-Anima-PixelDecoder"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Decode Anima renders straight from the DiT's last-layer features with a 25M-parameter pixel head, in place of VAE Decode: a MODEL tap (works with the stock KSampler and KSampler (Spectrum)) and a decode node that outputs IMAGE. A x2 head file decodes and upscales 2x in one readout. Weights: huggingface.co/sorryhyun/anima-pixel-decoder."
|
||||
},
|
||||
{
|
||||
"author": "joykst96",
|
||||
"title": "kludge",
|
||||
"id": "kludge",
|
||||
"reference": "https://github.com/joykst96/comfyui-kludge",
|
||||
"files": [
|
||||
"https://github.com/joykst96/comfyui-kludge"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Makeshift helper nodes, mostly for Anima (2B / 2.9B): INT8 quantize on load, 2.9B LoRA remap, Spectrum, SPEED, block compile, guider model tracking, SnapRef."
|
||||
},
|
||||
{
|
||||
"author": "zhulinyv",
|
||||
"title": "ComfyUI-RiceRabbit-Tools",
|
||||
"reference": "https://github.com/zhulinyv/ComfyUI-RiceRabbit-Tools",
|
||||
"files": [
|
||||
"https://github.com/zhulinyv/ComfyUI-RiceRabbit-Tools"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "RiceRabbit toolbox: prompt editor with Danbooru tag autocomplete, tag-chip modal, wildcard card library and online translation; image compare viewer (slide divider, wheel zoom) that auto-collects every IMAGE output of your Set/Get variables; plus resolution / date / text-join / any-type switch helpers."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-abvg",
|
||||
"id": "comfyui-abvg",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-abvg",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-abvg"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "AI birthday video generator from a single photo: they pop champagne on a park bench, blow out a Scorpio cake, or light a crown cake at the car window. Generate 12s 720p vertical birthday clips on Seedance 2 Mini via https://aibirthdayvideogenerator.com/."
|
||||
},
|
||||
{
|
||||
"author": "haryai",
|
||||
"title": "Seedance 2.5 (HaryAI)",
|
||||
"id": "seedance-comfyui",
|
||||
"reference": "https://github.com/sunsiyuan/seedance-comfyui",
|
||||
"files": [
|
||||
"https://github.com/sunsiyuan/seedance-comfyui"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Seedance 2.5 and Seedance 2.5 Flash video generation through the HaryAI API: text to video, first and last frame, reference images, sound. No BytePlus account needed."
|
||||
},
|
||||
{
|
||||
"author": "codalanguez",
|
||||
"title": "CodaComfy Nodes",
|
||||
"id": "coda-comfy-tools",
|
||||
"reference": "https://github.com/codalanguez/CodaComfy-Nodes",
|
||||
"files": [
|
||||
"https://github.com/codalanguez/CodaComfy-Nodes"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "OpenRouter video, on-screen dialogue, cast and frame stacks, and soundtrack generation. Includes a LoRA stack browser, a latent chooser, and seven example video workflows."
|
||||
},
|
||||
{
|
||||
"author": "ukr8b3g-cmyk",
|
||||
"title": "PLaMo Prompt Translator",
|
||||
"reference": "https://github.com/ukr8b3g-cmyk/ComfyUI-PLaMo-Prompt-Translator",
|
||||
"files": [
|
||||
"https://github.com/ukr8b3g-cmyk/ComfyUI-PLaMo-Prompt-Translator"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Translate image prompts and plain text locally through LM Studio with PLaMo 3 Translate. Supports 53 language choices, side-by-side editors, and automatic splitting for long text."
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI-ComfyUI_Contextual-Series",
|
||||
"reference": "https://github.com/xm6018924/BSAI-ComfyUI_Contextual-Series",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI-ComfyUI_Contextual-Series"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Extract reference frames from previously generated video to maintain visual consistency across sequential MiniMax H3 video generations"
|
||||
},
|
||||
{
|
||||
"author": "jutsuhq",
|
||||
"title": "ComfyUI-Higgsfield",
|
||||
"id": "comfyui-higgsfield",
|
||||
"reference": "https://github.com/jutsuhq/ComfyUI-Higgsfield",
|
||||
"files": [
|
||||
"https://github.com/jutsuhq/ComfyUI-Higgsfield"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Higgsfield API video nodes: Seedance 2.5 and Kling 4.0 (text-to-video and image-to-video) and Genjutsu motion transfer, with your own API key. Each node shows its price and stops before submitting if the estimate is above max_cost_usd."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
"title": "ComfyUI-movoa",
|
||||
"id": "comfyui-movoa",
|
||||
"reference": "https://github.com/hanshs474/ComfyUI-movoa",
|
||||
"files": [
|
||||
"https://github.com/hanshs474/ComfyUI-movoa"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Text to video and photo to video with sound via Movoa (movoa.ai). Standard library only; requires a Movoa API key."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Momentum samplers for flow models (EMA momentum, damped extrapolation, any-sampler filter)",
|
||||
"id": "momentum-cfg-samplers-research",
|
||||
"reference": "https://github.com/YakovSava/momentum-cfg-samplers-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/momentum-cfg-samplers-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Momentum on the data prediction for DPM-Solver++-style samplers on flow-matching models: a negative coefficient lowers the error at equal step count, a positive one only adds lag. Nodes: Sampler Momentum, Sampler Momentum Filter (wraps any one-evaluation sampler, unevaluated), Sigmas grid; KSampler entries ddim_momentum, dpmpp_2m_sde_damped and <base>_momentumized. Includes a diagnosis of why the 2023 dpmpp_dualsde_momentumized fails on flow models."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Flow-WLS Sampler (regularized multistep, quantization study)",
|
||||
"id": "flow-wls-research",
|
||||
"reference": "https://github.com/YakovSava/flow-wls-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/flow-wls-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes: Flow-WLS Sampler and Flow Easy Sampler, regularized multistep integration for flow-matching models, plus the research code of a study of how such samplers behave under FP8/INT4 quantization errors."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Flow-SDE Sampler (curvature- and error-adaptive stochasticity)",
|
||||
"id": "flow-sde-research",
|
||||
"reference": "https://github.com/YakovSava/flow-sde-research",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/flow-sde-research"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Flow-SDE Sampler node: controls how much noise an SDE sampler injects at each step for flow-matching models at low step counts. Research code; measured on Anima, Flux and MOSS-Image, with mostly negative results documented in the README."
|
||||
},
|
||||
{
|
||||
"author": "Iakov Savelev",
|
||||
"title": "Adaptive-step samplers (SA-Solver stochastic strength, predictor-corrector error estimate)",
|
||||
"id": "adaptive-step-samplers",
|
||||
"reference": "https://github.com/YakovSava/adaptive-step-samplers",
|
||||
"files": [
|
||||
"https://github.com/YakovSava/adaptive-step-samplers"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Nodes: Adaptive SA Sampler (exposes the stochastic strength and noise window that ComfyUI hardcodes in sa_solver), Adaptive PC Sampler (Adams predictor-corrector with a free local error estimate) and Trajectory Probe (per-step diagnostics). Research code with measurements."
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI-MiniMAX-H3-Prompt",
|
||||
"reference": "https://github.com/xm6018924/BSAI-MiniMAX-H3-Prompt",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI-MiniMAX-H3-Prompt"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "ComfyUI custom node for optimizing MiniMax H3 video generation prompts based on the H3 model manual"
|
||||
},
|
||||
{
|
||||
"author": "BSAI",
|
||||
"title": "BSAI_ComfyUI_IndexTTS-2.5",
|
||||
"reference": "https://github.com/xm6018924/BSAI_ComfyUI_IndexTTS-2.5",
|
||||
"files": [
|
||||
"https://github.com/xm6018924/BSAI_ComfyUI_IndexTTS-2.5"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "BSAI ComfyUI IndexTTS-2.5 - Text-to-Speech plugin with auto model download (ModelScope/HuggingFace)"
|
||||
},
|
||||
{
|
||||
"author": "AinJuZen",
|
||||
"title": "ComfyUI-ModelMirror",
|
||||
"reference": "https://github.com/AinJuZen/ComfyUI-ModelMirror",
|
||||
"files": [
|
||||
"https://github.com/AinJuZen/ComfyUI-ModelMirror"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Fills in missing models through a configurable mirror (hf-mirror by default): detects missing model files in the current workflow, resolves each to its official HuggingFace repo by filename, and downloads them into the correct models/ folder with resume support. Writes only inside models/ (validated allowlist, no path traversal). Does not patch any official ComfyUI file."
|
||||
},
|
||||
{
|
||||
"author": "daniel-ang",
|
||||
"title": "Torch Legacy",
|
||||
"reference": "https://github.com/daniel-ang/ComfyUI-Torch-Legacy",
|
||||
"files": [
|
||||
"https://github.com/daniel-ang/ComfyUI-Torch-Legacy"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Reproduce torch 2.8.0+cu129 CUDA numerics on newer torch, so MiniMax Music 3 / YuE2 seeds give the same songs as before the torch upgrade."
|
||||
},
|
||||
{
|
||||
"author": "rasmont",
|
||||
"title": "LoRA Preset (saved in workflow)",
|
||||
"reference": "https://github.com/RasmonT/comfyui-workflow-lora-presets",
|
||||
"files": [
|
||||
"https://github.com/RasmonT/comfyui-workflow-lora-presets"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "LoRA presets saved INSIDE the workflow. One dropdown applies a whole LoRA combo; right-click to save your enabled LoRA loaders as a preset, edit, import or share. Anyone who loads your workflow gets your presets."
|
||||
},
|
||||
{
|
||||
"author": "seren",
|
||||
"title": "Anima Artist Blend",
|
||||
"reference": "https://github.com/seren-alegro/ComfyUI-AnimaArtistBlend",
|
||||
"files": [
|
||||
"https://github.com/seren-alegro/ComfyUI-AnimaArtistBlend"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Blend multiple artist tags in Qwen3 0.6B hidden-state space for Anima (private test)"
|
||||
},
|
||||
{
|
||||
"author": "israeldelamoicjardin",
|
||||
"title": "Auto LoRA Prompt Plot",
|
||||
"reference": "https://github.com/israeldelamoicjardin/comfyui-auto-lora-prompt-plot",
|
||||
"files": [
|
||||
"https://github.com/israeldelamoicjardin/comfyui-auto-lora-prompt-plot"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Apply multiple LoRAs with matching trigger-word prompts in ComfyUI."
|
||||
},
|
||||
{
|
||||
"author": "yamoon-jjang",
|
||||
"title": "Ultra Qwen Image Editor + PiD",
|
||||
"reference": "https://github.com/Yamoon-jjang/comfyui-Ultra-Qwen-Image-Editor",
|
||||
"files": [
|
||||
"https://github.com/Yamoon-jjang/comfyui-Ultra-Qwen-Image-Editor"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Qwen 2511/2.1 and MiniMax H3 Image multi-reference editor for ComfyUI, with optional Qwen PiD upscale"
|
||||
},
|
||||
{
|
||||
"author": "perfectgf",
|
||||
"title": "ComfyUI Krea2 Enhancer",
|
||||
"reference": "https://github.com/perfectgf/ComfyUI-Krea2-Enhancer",
|
||||
"files": [
|
||||
"https://github.com/perfectgf/ComfyUI-Krea2-Enhancer"
|
||||
],
|
||||
"install_type": "git-clone",
|
||||
"description": "Krea2 Turbo Enhancement Nodes"
|
||||
},
|
||||
{
|
||||
"author": "rasmont",
|
||||
"title": "Force PyTorch Attention (xformers fix)",
|
||||
@@ -329,12 +839,12 @@
|
||||
},
|
||||
{
|
||||
"author": "Statite",
|
||||
"title": "ComfyUI-SpecAR",
|
||||
"title": "ComfyUI-StrideAR",
|
||||
"id": "comfyui-specar",
|
||||
"reference": "https://github.com/statite-ai/ComfyUI-SpecAR",
|
||||
"files": ["https://github.com/statite-ai/ComfyUI-SpecAR"],
|
||||
"reference": "https://github.com/statite-ai/ComfyUI-StrideAR",
|
||||
"files": ["https://github.com/statite-ai/ComfyUI-StrideAR"],
|
||||
"install_type": "git-clone",
|
||||
"description": "SpecAR: Training-free 2.04x-2.81x speedup on Krea Realtime 14B + Self-Forcing 1.3B (up to 23.1 FPS real-time on B200, 2.67x on H100) with lazy target KV caching and low-VRAM offload."
|
||||
"description": "StrideAR: Training-free 2.04x-2.81x speedup on Krea Realtime 14B + Self-Forcing 1.3B (up to 23.1 FPS real-time on B200, 2.67x on H100) with lazy target KV caching and low-VRAM offload."
|
||||
},
|
||||
{
|
||||
"author": "hanshs474",
|
||||
@@ -1262,7 +1772,7 @@
|
||||
},
|
||||
{
|
||||
"author": "AceDataCloud",
|
||||
"title": "Suno by Ace Data Cloud",
|
||||
"title": "Suno",
|
||||
"id": "ace-suno",
|
||||
"reference": "https://github.com/AceDataCloud/SunoComfyUI",
|
||||
"files": [
|
||||
|
||||
@@ -120,10 +120,13 @@
|
||||
"https://github.com/0xRavenBlack/ComfyUI-OOP": [
|
||||
[
|
||||
"OOPAnimalNode",
|
||||
"OOPBackgroundNode",
|
||||
"OOPClothingNode",
|
||||
"OOPEnvironmentNode",
|
||||
"OOPExpressionNode",
|
||||
"OOPEyesNode",
|
||||
"OOPHairNode",
|
||||
"OOPLightingNode",
|
||||
"OOPLocationNode",
|
||||
"OOPMouthNode",
|
||||
"OOPNode",
|
||||
@@ -14397,6 +14400,7 @@
|
||||
"IAMCCS_Drama3GPUEncodeVoice",
|
||||
"IAMCCS_Drama3GPUModelLoader",
|
||||
"IAMCCS_Drama3GenerateGPU",
|
||||
"IAMCCS_EditaMasterFinish",
|
||||
"IAMCCS_FlashVSRPanelBatchPrep",
|
||||
"IAMCCS_FlashVSRPanelBatchRestore",
|
||||
"IAMCCS_FluxKleinMultiGen",
|
||||
@@ -19320,8 +19324,13 @@
|
||||
"https://github.com/Malte0621/hordeai-comfy": [
|
||||
[
|
||||
"AIHordeImageGenerate",
|
||||
"AIHordeImageSampling",
|
||||
"AIHordeLora",
|
||||
"AIHordeModelList",
|
||||
"AIHordeModelSelect",
|
||||
"AIHordeTextGenerate",
|
||||
"AIHordeTextModelList",
|
||||
"AIHordeTextSampling",
|
||||
"AIHordeTextualInversion"
|
||||
],
|
||||
{
|
||||
@@ -23247,6 +23256,7 @@
|
||||
"PixlStashCheckpointLoader",
|
||||
"PixlStashControlNetLoader",
|
||||
"PixlStashFaceLikenessGate",
|
||||
"PixlStashLayoutTextEncode",
|
||||
"PixlStashLikenessSearch",
|
||||
"PixlStashMultiAdapterLoader",
|
||||
"PixlStashPictureLikenessGate",
|
||||
@@ -28227,6 +28237,7 @@
|
||||
"StarMinimaxLatentUpscalerOption",
|
||||
"StarMinimaxMultirefOption",
|
||||
"StarModelAIOMerge",
|
||||
"StarModelMerge",
|
||||
"StarModelPacker",
|
||||
"StarMossControl",
|
||||
"StarMultiInputsToOne",
|
||||
@@ -31396,6 +31407,7 @@
|
||||
"XB_ShenBi",
|
||||
"XB_StoryboardSlicer",
|
||||
"XB_StringMerge",
|
||||
"XB_Text2ImagePromptPreset",
|
||||
"XB_TextEncodeQwenImageEdit",
|
||||
"XB_TextEncodeQwenImageEditPlus",
|
||||
"XB_TripleLoraLoader",
|
||||
@@ -43754,6 +43766,8 @@
|
||||
"SelectModelDevice",
|
||||
"SelectVAEDevice",
|
||||
"SelfAttentionGuidance",
|
||||
"SenseNovaConditioning",
|
||||
"SenseNovaInterleaveDecode",
|
||||
"SenseNovaSamplingOptions",
|
||||
"SetFirstSigma",
|
||||
"SetLatentNoiseMask",
|
||||
@@ -62743,6 +62757,7 @@
|
||||
"ImageReceiver",
|
||||
"ImageSender",
|
||||
"ImpactAssembleSEGS",
|
||||
"ImpactAssembleSEGSList",
|
||||
"ImpactBoolean",
|
||||
"ImpactCombineConditionings",
|
||||
"ImpactCompare",
|
||||
@@ -62757,6 +62772,7 @@
|
||||
"ImpactConvertDataType",
|
||||
"ImpactCount_Elts_in_SEGS",
|
||||
"ImpactDecomposeSEGS",
|
||||
"ImpactDecomposeSEGSList",
|
||||
"ImpactDilateMask",
|
||||
"ImpactDilateMaskInSEGS",
|
||||
"ImpactDilate_Mask_SEG_ELT",
|
||||
@@ -64627,6 +64643,7 @@
|
||||
"EmptyZImageLatentImage",
|
||||
"IllustrationStylePromptEncoder",
|
||||
"ImageFilter",
|
||||
"ImageFilterStackLAB",
|
||||
"ImageGridBuilder",
|
||||
"ImageLabeler",
|
||||
"ImageLabeler2",
|
||||
@@ -66799,7 +66816,7 @@
|
||||
[
|
||||
"MVNT Audio Segment",
|
||||
"MVNT Generate Dance",
|
||||
"MVNT Image to T-Pose",
|
||||
"MVNT List Styles",
|
||||
"MVNT Render Dance Video",
|
||||
"MVNTPreviewDance3D"
|
||||
],
|
||||
@@ -70346,7 +70363,9 @@
|
||||
"PixaromaVideoTools",
|
||||
"PixaromaWH",
|
||||
"PixaromaXYPlot",
|
||||
"Pixaroma_VueReferenceNode"
|
||||
"Pixaroma_VueReferenceNode",
|
||||
"SeamlessPreviewPixaroma",
|
||||
"SeamlessTilePixaroma"
|
||||
],
|
||||
{
|
||||
"title_aux": "ComfyUI-Pixaroma"
|
||||
@@ -73387,37 +73406,6 @@
|
||||
"title_aux": "RUI-Nodes"
|
||||
}
|
||||
],
|
||||
"https://github.com/ruiqutech/ComfyUI-RuiquNodes": [
|
||||
[
|
||||
"EvaluateListMultiple1",
|
||||
"EvaluateListMultiple3",
|
||||
"EvaluateListMultiple6",
|
||||
"EvaluateListMultiple9",
|
||||
"EvaluateMultiple1",
|
||||
"EvaluateMultiple3",
|
||||
"EvaluateMultiple6",
|
||||
"EvaluateMultiple9",
|
||||
"ImageDilate",
|
||||
"ImageErode",
|
||||
"ListPath",
|
||||
"MaskDilate",
|
||||
"MaskErode",
|
||||
"PreviewMask",
|
||||
"RangeSplit",
|
||||
"SaveMask",
|
||||
"StringAsAny",
|
||||
"StringConcat1",
|
||||
"StringConcat3",
|
||||
"StringConcat6",
|
||||
"StringConcat9",
|
||||
"StringPathStem",
|
||||
"TermsToList",
|
||||
"VAEDecodeSave"
|
||||
],
|
||||
{
|
||||
"title_aux": "RuiquNodes for ComfyUI"
|
||||
}
|
||||
],
|
||||
"https://github.com/ruminar/ComfyUI-CheckpointHandpickerSuite": [
|
||||
[
|
||||
"CheckpointListSelector",
|
||||
@@ -75375,6 +75363,7 @@
|
||||
[
|
||||
"GetKeyAPI",
|
||||
"SSL_GeminiAPIKeyConfig",
|
||||
"SSL_GeminiAudioConfig",
|
||||
"SSL_GeminiInteractionsAPIKeyConfig",
|
||||
"SSL_GeminiInteractionsSafetyConfig",
|
||||
"SSL_GeminiInteractionsStore",
|
||||
@@ -75584,6 +75573,7 @@
|
||||
"ChainEditVideo",
|
||||
"CheckpointLoader_v2",
|
||||
"CreateImageList",
|
||||
"DatasetPairSave",
|
||||
"H3Frames_cut",
|
||||
"HolocineFrames",
|
||||
"ImageBlend_GPU",
|
||||
@@ -78976,6 +78966,7 @@
|
||||
"TADiscordLink",
|
||||
"TAFastLaplacianSharpen",
|
||||
"TAFilenameGenerator",
|
||||
"TAFilmGrain",
|
||||
"TAFluxGuidanceGate",
|
||||
"TAHelpLink",
|
||||
"TAKSampler",
|
||||
@@ -80776,6 +80767,7 @@
|
||||
],
|
||||
"https://github.com/veighnsche/comfyui_gr85": [
|
||||
[
|
||||
"GR85_FanServicePrompt",
|
||||
"GR85_ImageDimensionResizer",
|
||||
"GR85_ImageSizer",
|
||||
"GR85_ImageSizerAll",
|
||||
@@ -83353,6 +83345,7 @@
|
||||
"ComfyUI_EXO_DisplayText",
|
||||
"ComfyUI_EXO_FluxSampler",
|
||||
"ComfyUI_EXO_FluxSamplerMini",
|
||||
"ComfyUI_EXO_H3StillAdapter",
|
||||
"ComfyUI_EXO_ImageRescale",
|
||||
"ComfyUI_EXO_LatentImageSize",
|
||||
"ComfyUI_EXO_LatentImageSizeX",
|
||||
|
||||
@@ -1,6 +1,50 @@
|
||||
{
|
||||
"models": [
|
||||
|
||||
{
|
||||
"name": "sam3.1_multiplex_fp16.safetensors",
|
||||
"type": "sam3.1",
|
||||
"base": "SAM",
|
||||
"save_path": "checkpoints",
|
||||
"description": "Segment Anything SAM 3.1 model (multiplex, fp16), repackaged for ComfyUI by Comfy-Org",
|
||||
"reference": "https://huggingface.co/Comfy-Org/sam3.1",
|
||||
"filename": "sam3.1_multiplex_fp16.safetensors",
|
||||
"url": "https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors",
|
||||
"size": "1.75GB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-H SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-H) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_h_4b8939.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_h_4b8939.safetensors",
|
||||
"size": "2.56GB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-L SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-L) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_l_0b3195.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_l_0b3195.safetensors",
|
||||
"size": "1.25GB"
|
||||
},
|
||||
{
|
||||
"name": "ViT-B SAM model (safetensors)",
|
||||
"type": "sam",
|
||||
"base": "SAM",
|
||||
"save_path": "sams",
|
||||
"description": "Segment Anything SAM model (ViT-B) in the safetensors format, from Kornia",
|
||||
"reference": "https://huggingface.co/kornia/sam",
|
||||
"filename": "sam_vit_b_01ec64.safetensors",
|
||||
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_b_01ec64.safetensors",
|
||||
"size": "375.0MB"
|
||||
},
|
||||
{
|
||||
"name": "LTX-2.5 22B IC-LoRA Alpha-Gen",
|
||||
"type": "lora",
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
"!echo -= Install dependencies =-\n",
|
||||
"!pip3 install accelerate\n",
|
||||
"!pip3 install einops transformers>=4.28.1 safetensors>=0.4.2 aiohttp pyyaml Pillow scipy tqdm psutil tokenizers>=0.13.3\n",
|
||||
"!pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121\n",
|
||||
"!pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cu121\n",
|
||||
"!pip3 install torchsde\n",
|
||||
"!pip3 install kornia>=0.7.1 spandrel soundfile sentencepiece\n",
|
||||
"\n",
|
||||
|
||||
+66
-39
@@ -192,27 +192,47 @@ paths:
|
||||
|
||||
/customnode/fetch_updates:
|
||||
post:
|
||||
summary: Check for updates
|
||||
description: Fetches updates for custom nodes
|
||||
summary: Check for updates (deprecated)
|
||||
deprecated: true
|
||||
description: No longer fetches. A check for updates is asked for with `/customnode/check_update`.
|
||||
responses:
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
'410':
|
||||
description: The endpoint is gone
|
||||
|
||||
/customnode/check_update:
|
||||
post:
|
||||
summary: Check the git custom nodes for updates
|
||||
description: >-
|
||||
Starts a check in the background that fetches the repositories of the enabled git custom nodes of the list,
|
||||
and answers at once. The check reports by the websocket event `cm-check-update`:
|
||||
`{status: "in_progress", done_count, total_count}` after each repository, and at the end
|
||||
`{status: "done", updatable, ui_ids}` with the keys of the custom nodes that have an update (`null` when
|
||||
the check failed) and the `ui_id` of every request that this result answers. While a check runs, no second one is started: the custom nodes
|
||||
of this request that the check does not have are added to it, so `total_count` can grow, and its result
|
||||
answers this request too.
|
||||
requestBody:
|
||||
required: false
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [mode, ui_id]
|
||||
properties:
|
||||
mode:
|
||||
type: string
|
||||
enum: [local, remote, default]
|
||||
description: Source mode (e.g., "local", "remote")
|
||||
enum: [cache, local, remote]
|
||||
description: Source mode of the node list
|
||||
ui_id:
|
||||
type: string
|
||||
description: Chosen by the client. The `done` event of the check that answers this request names it.
|
||||
responses:
|
||||
'200':
|
||||
description: No updates available
|
||||
'201':
|
||||
description: Updates found
|
||||
description: The check runs
|
||||
'400':
|
||||
description: Error occurred
|
||||
|
||||
description: Content-Type is not application/json
|
||||
|
||||
/customnode/installed:
|
||||
get:
|
||||
summary: Get installed custom nodes
|
||||
@@ -242,7 +262,8 @@ paths:
|
||||
- $ref: '#/components/parameters/modeParam'
|
||||
- name: skip_update
|
||||
in: query
|
||||
description: Skip update check
|
||||
deprecated: true
|
||||
description: Not used. The list is given without fetching the repositories; a check for updates is asked for with `/customnode/check_update`.
|
||||
schema:
|
||||
type: boolean
|
||||
responses:
|
||||
@@ -284,22 +305,6 @@ paths:
|
||||
'500':
|
||||
description: Error occurred
|
||||
|
||||
/customnode/alternatives:
|
||||
get:
|
||||
summary: Get alternative node options
|
||||
description: Provides alternatives for nodes
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/modeParam'
|
||||
responses:
|
||||
'200':
|
||||
description: Successful operation
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: object
|
||||
|
||||
/customnode/versions/{node_name}:
|
||||
get:
|
||||
summary: Get available versions for a node
|
||||
@@ -405,9 +410,14 @@ paths:
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
text/plain:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
type: object
|
||||
required: [url]
|
||||
properties:
|
||||
url:
|
||||
type: string
|
||||
description: Git repository URL
|
||||
responses:
|
||||
'200':
|
||||
description: Installation successful or already installed
|
||||
@@ -425,9 +435,14 @@ paths:
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
text/plain:
|
||||
application/json:
|
||||
schema:
|
||||
type: string
|
||||
type: object
|
||||
required: [packages]
|
||||
properties:
|
||||
packages:
|
||||
type: string
|
||||
description: Space-separated pip packages
|
||||
responses:
|
||||
'200':
|
||||
description: Installation successful
|
||||
@@ -483,10 +498,12 @@ paths:
|
||||
/manager/queue/reset:
|
||||
post:
|
||||
summary: Reset queue
|
||||
description: Resets the operation queue
|
||||
description: Resets the operation queue. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Queue reset successfully
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
|
||||
/manager/queue/status:
|
||||
get:
|
||||
@@ -523,12 +540,14 @@ paths:
|
||||
/manager/queue/start:
|
||||
post:
|
||||
summary: Start queue processing
|
||||
description: Starts processing the operation queue
|
||||
description: Starts processing the operation queue. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Processing started
|
||||
'201':
|
||||
description: Processing already in progress
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
|
||||
/manager/queue/fix:
|
||||
post:
|
||||
@@ -619,10 +638,12 @@ paths:
|
||||
/manager/queue/update_comfyui:
|
||||
post:
|
||||
summary: Update ComfyUI
|
||||
description: Queues an update operation for ComfyUI itself
|
||||
description: Queues an update operation for ComfyUI itself. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Update queued successfully
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
|
||||
/manager/queue/install_model:
|
||||
post:
|
||||
@@ -729,12 +750,12 @@ paths:
|
||||
/snapshot/save:
|
||||
post:
|
||||
summary: Save snapshot
|
||||
description: Saves the current system state as a new snapshot
|
||||
description: Saves the current system state as a new snapshot. The request has no body and needs the Content-Type `application/json`.
|
||||
responses:
|
||||
'200':
|
||||
description: Snapshot saved successfully
|
||||
'400':
|
||||
description: Error saving snapshot
|
||||
description: Content-Type is not application/json, or error saving snapshot
|
||||
|
||||
# ComfyUI Management Endpoints
|
||||
/comfyui_manager/comfyui_versions:
|
||||
@@ -761,9 +782,11 @@ paths:
|
||||
/comfyui_manager/comfyui_switch_version:
|
||||
post:
|
||||
summary: Switch ComfyUI version
|
||||
description: Switches to a specified ComfyUI version
|
||||
description: Switches to a specified ComfyUI version. Only a switch to an older version is held to the security level.
|
||||
security:
|
||||
- securityLevel: []
|
||||
requestBody:
|
||||
required: false
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
@@ -777,16 +800,20 @@ paths:
|
||||
description: Version switch successful
|
||||
'400':
|
||||
description: Error switching version
|
||||
'403':
|
||||
description: Security policy violation
|
||||
|
||||
/manager/reboot:
|
||||
post:
|
||||
summary: Reboot ComfyUI
|
||||
description: Restarts the ComfyUI server
|
||||
description: Restarts the ComfyUI server. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
responses:
|
||||
'200':
|
||||
description: Reboot initiated
|
||||
'400':
|
||||
description: Content-Type is not application/json
|
||||
'403':
|
||||
description: Security policy violation
|
||||
|
||||
|
||||
+103
-81
@@ -108,7 +108,7 @@ def read_config():
|
||||
global default_conf
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(manager_config_path)
|
||||
default_conf = config['default']
|
||||
except Exception:
|
||||
@@ -123,15 +123,25 @@ def check_file_logging():
|
||||
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
|
||||
enable_file_logging = False
|
||||
|
||||
def set_git_executable():
|
||||
# GitPython reads this when it is imported, so that a git that is not on PATH can be named
|
||||
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
|
||||
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
|
||||
if git_exe != '' and _has_system_user_api:
|
||||
git_exe = manager_util.find_git_executable(git_exe)
|
||||
if git_exe is not None:
|
||||
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = git_exe
|
||||
|
||||
|
||||
read_config()
|
||||
set_git_executable()
|
||||
read_uv_mode()
|
||||
security_check.security_check()
|
||||
check_file_logging()
|
||||
|
||||
cm_global.pip_overrides = {}
|
||||
|
||||
if os.path.exists(manager_pip_overrides_path):
|
||||
if _has_system_user_api and os.path.exists(manager_pip_overrides_path):
|
||||
with open(manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
cm_global.pip_overrides = json.load(json_file)
|
||||
|
||||
@@ -144,15 +154,6 @@ if os.path.exists(manager_pip_blacklist_path):
|
||||
cm_global.pip_blacklist.add(y)
|
||||
|
||||
|
||||
def remap_pip_package(pkg):
|
||||
if pkg in cm_global.pip_overrides:
|
||||
res = cm_global.pip_overrides[pkg]
|
||||
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
|
||||
return res
|
||||
else:
|
||||
return pkg
|
||||
|
||||
|
||||
std_log_lock = threading.Lock()
|
||||
|
||||
|
||||
@@ -288,6 +289,7 @@ try:
|
||||
self.is_stdout = is_stdout
|
||||
self.encoding = "utf-8"
|
||||
self.last_char = ''
|
||||
self.console_is_gone = False
|
||||
|
||||
def fileno(self):
|
||||
try:
|
||||
@@ -361,36 +363,50 @@ try:
|
||||
if '100%' in message:
|
||||
self.sync_write(message)
|
||||
else:
|
||||
write_stderr(message)
|
||||
original_stderr.flush()
|
||||
self.write_console(message)
|
||||
else:
|
||||
self.sync_write(message)
|
||||
else:
|
||||
self.sync_write(message)
|
||||
|
||||
def write_console(self, message):
|
||||
# A console that is gone does not come back, and ComfyUI's stream keeps every write
|
||||
# it could not flush, so it is not written to again.
|
||||
if self.console_is_gone:
|
||||
return
|
||||
|
||||
try:
|
||||
if self.is_stdout:
|
||||
write_stdout(message)
|
||||
original_stdout.flush()
|
||||
else:
|
||||
write_stderr(message)
|
||||
original_stderr.flush()
|
||||
except BlockingIOError:
|
||||
pass
|
||||
except OSError:
|
||||
self.console_is_gone = True
|
||||
|
||||
def sync_write(self, message, file_only=False):
|
||||
with log_lock:
|
||||
timestamp = current_timestamp()
|
||||
if self.last_char != '\n':
|
||||
log_file.write(message)
|
||||
else:
|
||||
log_file.write(f"[{timestamp}] {message}")
|
||||
# after close_log() the output goes to the console only
|
||||
if not log_file.closed:
|
||||
timestamp = current_timestamp()
|
||||
if self.last_char != '\n':
|
||||
log_file.write(message)
|
||||
else:
|
||||
log_file.write(f"[{timestamp}] {message}")
|
||||
|
||||
try:
|
||||
log_file.flush()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
log_file.flush()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.last_char = message if message == '' else message[-1]
|
||||
|
||||
if not file_only:
|
||||
with std_log_lock:
|
||||
if self.is_stdout:
|
||||
write_stdout(message)
|
||||
original_stdout.flush()
|
||||
else:
|
||||
write_stderr(message)
|
||||
original_stderr.flush()
|
||||
self.write_console(message)
|
||||
|
||||
def flush(self):
|
||||
try:
|
||||
@@ -417,12 +433,15 @@ try:
|
||||
def close_log(self):
|
||||
sys.stderr = original_stderr
|
||||
sys.stdout = original_stdout
|
||||
log_file.close()
|
||||
with log_lock:
|
||||
log_file.close()
|
||||
|
||||
def close_log():
|
||||
sys.stderr = original_stderr
|
||||
sys.stdout = original_stdout
|
||||
log_file.close()
|
||||
# a write that has found the file open finishes first
|
||||
with log_lock:
|
||||
log_file.close()
|
||||
|
||||
|
||||
if enable_file_logging:
|
||||
@@ -440,7 +459,15 @@ try:
|
||||
def emit(self, record):
|
||||
global is_start_mode
|
||||
|
||||
message = record.getMessage()
|
||||
try:
|
||||
message = record.getMessage()
|
||||
except Exception as e:
|
||||
try:
|
||||
error = f"{type(e).__name__}: {e}"
|
||||
except Exception:
|
||||
# an error can carry the message that cannot be turned into text
|
||||
error = type(e).__name__
|
||||
message = f"<<logging error>>: {record.pathname}:{record.lineno} - {error}"
|
||||
|
||||
if is_start_mode:
|
||||
match = re.search(pat_import_fail, message)
|
||||
@@ -574,10 +601,10 @@ check_bypass_ssl()
|
||||
processed_install = set()
|
||||
# Use manager_files_path for consistency (fixes path inconsistency bug)
|
||||
script_list_path = os.path.join(manager_files_path, "startup-scripts", "install-scripts.txt")
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if _has_system_user_api else None)
|
||||
|
||||
|
||||
def is_installed(name):
|
||||
def is_installed(name, reinstall=False):
|
||||
name = name.strip()
|
||||
|
||||
if name.startswith('#'):
|
||||
@@ -590,8 +617,14 @@ def is_installed(name):
|
||||
return True
|
||||
|
||||
pkg_name, extras, clauses = manager_util.parse_pip_spec(name)
|
||||
if pkg_name is None or extras:
|
||||
return False # not a plain named requirement, or extras to add: let pip decide
|
||||
if extras:
|
||||
return False # extras to add: let pip decide
|
||||
|
||||
if clauses and clauses[0][0] == '@':
|
||||
return not reinstall and manager_util.installed_from(clauses[0][1], pkg_name) is not None
|
||||
|
||||
if pkg_name is None:
|
||||
return False # a path or an option: let pip decide
|
||||
|
||||
pkg = manager_util.get_installed_packages().get(pkg_name)
|
||||
if pkg is None:
|
||||
@@ -603,7 +636,10 @@ def is_installed(name):
|
||||
return True # prevent downgrade
|
||||
|
||||
|
||||
if os.path.exists(restore_snapshot_path):
|
||||
if not _has_system_user_api:
|
||||
if os.path.exists(restore_snapshot_path):
|
||||
print("[ComfyUI-Manager] Snapshot restore blocked on old ComfyUI version.")
|
||||
elif os.path.exists(restore_snapshot_path):
|
||||
try:
|
||||
cloned_repos = []
|
||||
|
||||
@@ -630,6 +666,8 @@ if os.path.exists(restore_snapshot_path):
|
||||
|
||||
print("[ComfyUI-Manager] Restore snapshot.")
|
||||
new_env = os.environ.copy()
|
||||
if 'COMFYUI_PATH' not in new_env:
|
||||
new_env["COMFYUI_PATH"] = os.path.dirname(folder_paths.__file__)
|
||||
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
|
||||
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
|
||||
|
||||
@@ -639,7 +677,8 @@ if os.path.exists(restore_snapshot_path):
|
||||
new_env['_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED'] = str(
|
||||
allow_flagged or manager_util.is_loopback_listener(args.listen)
|
||||
).lower()
|
||||
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path]
|
||||
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path,
|
||||
'--user-directory', folder_paths.get_user_directory(), '--restore-to', custom_nodes_base_path]
|
||||
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
|
||||
|
||||
if exit_code != 0:
|
||||
@@ -665,16 +704,9 @@ def execute_lazy_install_script(repo_path, executable):
|
||||
|
||||
lines = manager_util.robust_readlines(requirements_path)
|
||||
for line in lines:
|
||||
package_name = remap_pip_package(line.strip())
|
||||
package_name = package_name.split('#')[0].strip()
|
||||
if package_name and not is_installed(package_name):
|
||||
if '--index-url' in package_name:
|
||||
s = package_name.split('--index-url')
|
||||
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
|
||||
else:
|
||||
install_cmd = manager_util.make_pip_cmd(["install", package_name])
|
||||
|
||||
process_wrap(install_cmd, repo_path)
|
||||
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
|
||||
if install_args and not is_installed(install_args[0]):
|
||||
process_wrap(manager_util.make_pip_cmd(["install", *install_args]), repo_path)
|
||||
|
||||
if os.path.exists(install_script_path) and f'{repo_path}/install.py' not in processed_install:
|
||||
processed_install.add(f'{repo_path}/install.py')
|
||||
@@ -705,9 +737,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
download_path = os.path.join(custom_nodes_path, archive_name)
|
||||
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
|
||||
|
||||
# 2. extract files into <node_id>@<cur_ver>
|
||||
extracted = manager_util.extract_package_as_zip(download_path, from_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.switch_package_files(download_path, from_path)
|
||||
finally:
|
||||
os.remove(download_path)
|
||||
|
||||
if extracted is None:
|
||||
if len(os.listdir(from_path)) == 0:
|
||||
@@ -716,32 +749,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
print(f'Empty archive file: {target}')
|
||||
return False
|
||||
|
||||
if from_path != to_path:
|
||||
print(f"'{from_path}' is moved to '{to_path}'")
|
||||
shutil.move(from_path, to_path)
|
||||
|
||||
# 3. calculate garbage files (.tracking - extracted)
|
||||
tracking_info_file = os.path.join(from_path, '.tracking')
|
||||
prev_files = set()
|
||||
with open(tracking_info_file, 'r') as f:
|
||||
for line in f:
|
||||
prev_files.add(line.strip())
|
||||
garbage = prev_files.difference(extracted)
|
||||
garbage = [os.path.join(custom_nodes_path, x) for x in garbage]
|
||||
|
||||
# 4-1. remove garbage files
|
||||
for x in garbage:
|
||||
if os.path.isfile(x):
|
||||
os.remove(x)
|
||||
|
||||
# 4-2. remove garbage dir if empty
|
||||
for x in garbage:
|
||||
if os.path.isdir(x):
|
||||
if not os.listdir(x):
|
||||
os.rmdir(x)
|
||||
|
||||
# 5. rename dir name <node_id>@<prev_ver> ==> <node_id>@<cur_ver>
|
||||
print(f"'{from_path}' is moved to '{to_path}'")
|
||||
shutil.move(from_path, to_path)
|
||||
|
||||
# 6. create .tracking file
|
||||
tracking_info_file = os.path.join(to_path, '.tracking')
|
||||
with open(tracking_info_file, "w", encoding='utf-8') as file:
|
||||
file.write('\n'.join(list(extracted)))
|
||||
@@ -804,27 +815,34 @@ def execute_startup_script():
|
||||
|
||||
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
|
||||
status = script[8] if len(script) > 8 else ''
|
||||
if execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6], status):
|
||||
execute_lazy_install_script(script[3], script[7])
|
||||
to_path = script[4]
|
||||
if execute_lazy_cnr_switch(script[0], script[2], script[3], to_path, script[5], script[6], status):
|
||||
execute_lazy_install_script(to_path, script[7])
|
||||
|
||||
elif script[1] == "#LAZY-DELETE-NODEPACK":
|
||||
execute_lazy_delete(script[2])
|
||||
|
||||
elif os.path.exists(script[0]):
|
||||
reinstall = False
|
||||
if script[1] == "#FORCE":
|
||||
del script[1]
|
||||
else:
|
||||
reinstall = manager_util.is_reinstall(script[1:])
|
||||
requirement = manager_util.pip_install_requirement(script[1:])
|
||||
if requirement is not None and is_installed(requirement):
|
||||
if requirement is not None and is_installed(requirement, reinstall):
|
||||
continue
|
||||
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
|
||||
if not reinstall:
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
|
||||
print(f"\n## Execute management script for '{script[0]}'")
|
||||
|
||||
new_env = os.environ.copy()
|
||||
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
|
||||
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
|
||||
exit_code = process_wrap(script[1:], script[0], env=new_env)
|
||||
if reinstall:
|
||||
exit_code = manager_util.reinstall(script[1:], lambda cmd: process_wrap(cmd, script[0], env=new_env))
|
||||
else:
|
||||
exit_code = process_wrap(script[1:], script[0], env=new_env)
|
||||
|
||||
if exit_code != 0:
|
||||
print(f"management script failed: {script[0]}")
|
||||
@@ -851,6 +869,10 @@ if not _has_system_user_api:
|
||||
elif os.path.exists(script_list_path):
|
||||
execute_startup_script()
|
||||
|
||||
if _has_system_user_api and os.path.exists(os.path.join(folder_paths.get_user_directory(), 'default', 'ComfyUI-Manager', 'config.ini')):
|
||||
print("[ComfyUI-Manager] The legacy config.ini is still there: installing the requirements of ComfyUI.")
|
||||
execute_lazy_install_script(comfy_path, sys.executable)
|
||||
|
||||
|
||||
pip_fixer.fix_broken()
|
||||
|
||||
@@ -880,7 +902,7 @@ if script_executed:
|
||||
def check_windows_event_loop_policy():
|
||||
try:
|
||||
import configparser
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-manager"
|
||||
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
|
||||
version = "3.43"
|
||||
version = "3.44"
|
||||
license = { file = "LICENSE.txt" }
|
||||
requires-python = ">=3.9"
|
||||
dependencies = ["GitPython", "PyGithub", "matrix-nio", "transformers", "huggingface-hub>0.20", "typer", "rich", "typing-extensions", "toml", "uv", "chardet", "packaging", "nh3>=0.3.7"]
|
||||
|
||||
@@ -4,7 +4,7 @@ git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager
|
||||
cd ..
|
||||
python -m venv venv
|
||||
source venv/bin/activate
|
||||
python -m pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu130
|
||||
python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu130
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install -r custom_nodes/comfyui-manager/requirements.txt
|
||||
cd ..
|
||||
|
||||
@@ -4,7 +4,7 @@ git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager
|
||||
cd ..
|
||||
python -m venv venv
|
||||
call venv/Scripts/activate
|
||||
python -m pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu130
|
||||
python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu130
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install -r custom_nodes/comfyui-manager/requirements.txt
|
||||
cd ..
|
||||
|
||||
+2
-3
@@ -9,8 +9,7 @@ a constructed ``PromptServer``). pytest 8 collects any ancestor
|
||||
directory that carries an ``__init__.py`` as a ``Package`` node and
|
||||
IMPORTS that ``__init__.py`` during test setup (observed module name:
|
||||
``__init__``). Outside a live ComfyUI process that import can never
|
||||
succeed, so EVERY test under tests/ errors at setup — including the
|
||||
pre-existing tests/test_csrf_content_type_helper.py — whenever pytest's
|
||||
succeed, so EVERY test under tests/ errors at setup whenever pytest's
|
||||
rootdir ends up at or above the repo root (e.g. running inside a git
|
||||
worktree nested under the parent checkout).
|
||||
|
||||
@@ -21,7 +20,7 @@ executing the plugin entrypoint. Conftest files load before the setup
|
||||
phase, so the stub is always in place in time. This does NOT touch
|
||||
production code and does NOT alter what the tests import themselves
|
||||
(they use AST-extraction / subprocess isolation per the
|
||||
tests/test_csrf_content_type_helper.py precedent — ``glob/`` is never
|
||||
tests/test_json_body_content_type.py precedent — ``glob/`` is never
|
||||
added to the runner's sys.path).
|
||||
"""
|
||||
import sys
|
||||
|
||||
@@ -225,7 +225,7 @@ def install(server, node, version, operation='install'):
|
||||
async with session.post(server.base + '/manager/queue/' + operation, json=params) as response:
|
||||
if response.status != 200:
|
||||
return {'http': response.status, 'message': await response.text()}
|
||||
async with session.post(server.base + '/manager/queue/start') as response:
|
||||
async with session.post(server.base + '/manager/queue/start', headers={'Content-Type': 'application/json'}) as response:
|
||||
response.raise_for_status()
|
||||
while True:
|
||||
event = await ws.receive_json(timeout=30)
|
||||
@@ -359,7 +359,7 @@ def test_scheduled_snapshot_inherits_parent_policy(tmp_path, registry, existing,
|
||||
installed = tmp_path / 'custom_nodes/fixture-snapshot'
|
||||
marker = installed / 'installed.txt'
|
||||
reservation = tmp_path / 'user/__manager/startup-scripts/restore-snapshot.json'
|
||||
with running_server(tmp_path, '127.0.0.1', False, registry) as server:
|
||||
with running_server(tmp_path, '127.0.0.1', False, registry, security='normal-') as server:
|
||||
if existing:
|
||||
assert install(server, 'fixture-snapshot', '1.0.0')['message'] == 'success'
|
||||
assert marker.read_text() == '1.0.0'
|
||||
|
||||
@@ -37,7 +37,7 @@ def load_get_data_by_mode(manager_util, channel_url):
|
||||
assert len(nodes) == 1
|
||||
config = {"channel_url": channel_url, "network_mode": "public"}
|
||||
namespace = {"os": os, "json": json, "manager_util": manager_util,
|
||||
"get_config": lambda: config, "get_channel_dict": lambda: {}}
|
||||
"get_config": lambda: config, "normalize_channel": lambda channel: channel}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "manager_core.py", "exec"), namespace)
|
||||
return namespace["get_data_by_mode"]
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import NODE, JsSource, run_node, slice_braced
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
|
||||
REGISTERED = re.compile(r'api\.addEventListener\("(cm-check-update|reconnected)", this\.(\w+)\);')
|
||||
|
||||
ROWS = {
|
||||
"git-a": {"state": "enabled", "version": "nightly"},
|
||||
"git-b": {"state": "enabled", "version": "unknown"},
|
||||
"versioned-with-update": {"state": "enabled", "version": "1.0.0", "update-state": "true"},
|
||||
}
|
||||
TAKEN = {"data": {}}
|
||||
CHECK = 'POST /customnode/check_update {"mode":"cache","ui_id":"check-1"}'
|
||||
LIST = "GET /customnode/getlist?mode=cache&skip_update=true"
|
||||
LOADING, LOADED = "loading", "loading ended"
|
||||
WAIT = "status: Checking updates ..."
|
||||
|
||||
|
||||
def run(steps, check_answers=(TAKEN,), ends_before_the_answer=None):
|
||||
source = JS.text("custom-nodes-manager.js")
|
||||
registered = list(REGISTERED.finditer(source))
|
||||
script = """
|
||||
console.log = () => {};
|
||||
globalThis.window = {};
|
||||
%(sanitize_html)s
|
||||
%(show_mode)s;
|
||||
const calls = [];
|
||||
const updateFilter = {value: ShowMode.UPDATE, hasData: false};
|
||||
const self = {
|
||||
filterList: [updateFilter],
|
||||
restartMap: {},
|
||||
element: {querySelector: () => ({})},
|
||||
getFilterItem: (value) => value === ShowMode.UPDATE ? updateFilter : undefined,
|
||||
loadNodes: async () => {},
|
||||
showLoading: () => calls.push('loading'),
|
||||
hideLoading: () => calls.push('loading ended'),
|
||||
showStatus: (text) => calls.push('status: ' + text),
|
||||
showError: (text) => calls.push('error: ' + text),
|
||||
renderGrid() {
|
||||
const updatable = Object.values(this.custom_nodes).filter((row) => row.action === 'updatable');
|
||||
calls.push('shown as updatable: ' + updatable.map((row) => row.key).join(' '));
|
||||
},
|
||||
%(load_data)s,
|
||||
%(check_update)s,
|
||||
%(ask_for_check)s,
|
||||
%(listeners)s,
|
||||
};
|
||||
const CustomNodesManager = {instance: self};
|
||||
const manager_instance = {datasrc_combo: {value: 'cache'}};
|
||||
const md5 = (text) => 'hash of ' + text;
|
||||
let asked = 0;
|
||||
const generateUUID = () => 'check-' + (++asked);
|
||||
const infoToast = () => calls.push('toast');
|
||||
const heard = {};
|
||||
const api = {addEventListener: (name, listener) => { heard[name] = listener; }};
|
||||
(function() { %(registrations)s }).call(self);
|
||||
const checkAnswers = %(check_answers)s;
|
||||
const answeredLater = [];
|
||||
const fetchData = async (route, options = {}) => {
|
||||
calls.push((options.method ?? 'GET') + ' ' + route + (options.body ? ' ' + options.body : ''));
|
||||
if(!route.endsWith('/check_update')) {
|
||||
return {data: {channel: 'default', node_packs: structuredClone(%(rows)s)}};
|
||||
}
|
||||
if(%(ends_before_the_answer)s) {
|
||||
heard['cm-check-update']({detail: %(ends_before_the_answer)s});
|
||||
}
|
||||
const answer = checkAnswers.length > 1 ? checkAnswers.shift() : checkAnswers[0];
|
||||
return answer == 'later' ? new Promise((resolve) => answeredLater.push(resolve)) : answer;
|
||||
};
|
||||
|
||||
const settle = async () => {
|
||||
for(let i = 0; i < 20; i++) {
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
}
|
||||
};
|
||||
const done = [];
|
||||
for(const [kind, value] of %(steps)s) {
|
||||
calls.length = 0;
|
||||
if(kind == 'load') {
|
||||
self.loadData(value);
|
||||
}
|
||||
else if(kind == 'answer') {
|
||||
answeredLater.shift()(value);
|
||||
}
|
||||
else {
|
||||
await heard[kind]?.({detail: value});
|
||||
}
|
||||
await settle();
|
||||
done.push([...calls]);
|
||||
}
|
||||
process.stdout.write(JSON.stringify({steps: done, update_filter: Object.keys(updateFilter.hashMap ?? {})}));
|
||||
""" % {
|
||||
"sanitize_html": JS.lift_declaration("common.js", "export function sanitizeHTML("),
|
||||
"show_mode": slice_braced(source, "const ShowMode = "),
|
||||
"load_data": slice_braced(source, "async loadData(show_mode = ShowMode.NORMAL)"),
|
||||
"check_update": slice_braced(source, "async checkUpdate(mode)"),
|
||||
"ask_for_check": slice_braced(source, "async askForCheck(mode)"),
|
||||
"listeners": ",".join(slice_braced(source, re.search(r"\n\t(async )?%s\(" % found.group(2), source).group(0))
|
||||
for found in registered),
|
||||
"registrations": "\n".join(found.group(0) for found in registered),
|
||||
"check_answers": json.dumps(check_answers),
|
||||
"ends_before_the_answer": json.dumps(ends_before_the_answer),
|
||||
"rows": json.dumps(ROWS),
|
||||
"steps": json.dumps(steps),
|
||||
}
|
||||
return run_node(script)
|
||||
|
||||
|
||||
def progress(done_count):
|
||||
return ["cm-check-update", {"status": "in_progress", "done_count": done_count, "total_count": 2}]
|
||||
|
||||
|
||||
def result(*updatable, of="check-1"):
|
||||
return ["cm-check-update", {"status": "done", "updatable": list(updatable), "ui_ids": ["of another page", of]}]
|
||||
|
||||
|
||||
RECONNECTED = ["reconnected", None]
|
||||
|
||||
|
||||
def test_check_update_asks_for_the_check_and_loads_the_list_when_it_has_ended():
|
||||
data = run([["load", "Update"], progress(1), progress(2), result("git-b")])
|
||||
|
||||
asked, first, second, ended = data["steps"]
|
||||
assert asked == [LOADING, "toast", WAIT, CHECK]
|
||||
assert first == ["status: Checking updates (1/2) ..."]
|
||||
assert second == ["status: Checking updates (2/2) ..."]
|
||||
assert ended == ["status: Loading custom nodes (cache) ...", LIST, "shown as updatable: git-b versioned-with-update", LOADED]
|
||||
assert data["update_filter"] == ["hash of git-b", "hash of versioned-with-update"]
|
||||
|
||||
|
||||
def test_a_check_that_ends_before_the_request_for_it_is_answered_is_not_missed():
|
||||
data = run([["load", "Update"]], ends_before_the_answer=result("git-b")[1])
|
||||
|
||||
assert data["steps"] == [[LOADING, "toast", WAIT, CHECK, "status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: git-b versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
def test_a_check_that_finds_no_update_shows_the_list():
|
||||
data = run([["load", "Update"], result()])
|
||||
|
||||
assert data["steps"][1] == ["status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: versioned-with-update", LOADED]
|
||||
|
||||
|
||||
def test_a_nodepack_that_left_the_list_during_the_check_is_passed_over():
|
||||
data = run([["load", "Update"], result("git-b", "uninstalled-meanwhile")])
|
||||
|
||||
assert data["steps"][1][-2:] == ["shown as updatable: git-b versioned-with-update", LOADED]
|
||||
|
||||
|
||||
def test_the_end_of_a_check_that_does_not_answer_this_page_is_passed_over():
|
||||
data = run([["load", "Update"], result("git-a", of="of a third page"), result("git-b")])
|
||||
|
||||
assert data["steps"][1:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: git-b versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
def test_a_check_that_is_asked_for_again_waits_for_its_own_end():
|
||||
data = run([["load", "Update"], ["load", "Update"], result("git-a"), result("git-b", of="check-2")])
|
||||
|
||||
assert data["steps"][1] == [LOADING, "toast", WAIT, CHECK.replace("check-1", "check-2")]
|
||||
assert data["steps"][2:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: git-b versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
def test_a_check_that_failed_ends_the_loading_with_an_error():
|
||||
data = run([["load", "Update"], ["cm-check-update", {"status": "done", "updatable": None, "ui_ids": ["check-1"]}]])
|
||||
|
||||
assert data["steps"][1] == ["error: Failed to check updates.", LOADED]
|
||||
|
||||
|
||||
def test_the_list_alone_asks_for_no_check():
|
||||
data = run([["load", "Normal"]])
|
||||
|
||||
assert data["steps"] == [[LOADING, "status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [{"status": 400, "error": "Bad Request"}, {"status": 404, "error": "Not Found"}],
|
||||
ids=["refused", "a-server-without-the-check"])
|
||||
def test_a_check_that_the_server_does_not_take_ends_the_loading_with_an_error(answer):
|
||||
data = run([["load", "Update"], progress(1), result("git-b")], check_answers=[answer])
|
||||
|
||||
assert data["steps"] == [[LOADING, "toast", WAIT, CHECK, "error: Failed to check updates.", LOADED], [], []]
|
||||
|
||||
|
||||
def test_a_connection_that_came_back_during_the_check_asks_for_the_check_again():
|
||||
data = run([["load", "Update"], progress(1), RECONNECTED, result("git-b")])
|
||||
|
||||
assert data["steps"][2:] == [[CHECK], ["status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: git-b versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
def test_a_check_that_the_server_does_not_take_after_the_connection_came_back_ends_the_loading_with_an_error():
|
||||
data = run([["load", "Update"], RECONNECTED, result("git-b")], check_answers=[TAKEN, {"status": 404, "error": "Not Found"}])
|
||||
|
||||
assert data["steps"][1:] == [[CHECK, "error: Failed to check updates.", LOADED], []]
|
||||
|
||||
|
||||
def test_the_late_failure_of_an_earlier_request_does_not_end_the_check_that_was_asked_for_after_it():
|
||||
data = run([["load", "Update"], ["load", "Update"], ["answer", {"status": 400, "error": "Bad Request"}],
|
||||
result("git-b", of="check-2")], check_answers=["later", TAKEN])
|
||||
|
||||
assert data["steps"][2:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
|
||||
"shown as updatable: git-b versioned-with-update", LOADED]]
|
||||
|
||||
|
||||
def test_a_check_that_ends_after_another_list_was_opened_leaves_that_list():
|
||||
data = run([["load", "Update"], ["load", "Normal"], result("git-b")])
|
||||
|
||||
assert data["steps"][1][-2:] == ["shown as updatable: versioned-with-update", LOADED]
|
||||
assert data["steps"][2] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("before", [[["load", "Normal"]], [["load", "Update"], result("git-a")]],
|
||||
ids=["it-asked-for-none", "its-own-has-ended"])
|
||||
def test_the_events_of_a_check_this_page_did_not_wait_for_change_nothing(before):
|
||||
data = run([*before, progress(1), result("git-b"), RECONNECTED])
|
||||
|
||||
assert data["steps"][-3:] == [[], [], []]
|
||||
@@ -0,0 +1,350 @@
|
||||
import pytest
|
||||
|
||||
from test_invalid_installation import PRELUDE
|
||||
from test_install_flags_config import _run_child
|
||||
|
||||
CHECK = '''
|
||||
import queue, threading, traceback
|
||||
|
||||
fetched = []
|
||||
answers = {}
|
||||
during_a_fetch = []
|
||||
|
||||
def fetch(path):
|
||||
name = pathlib.Path(path).name
|
||||
fetched.append(name)
|
||||
if during_a_fetch:
|
||||
during_a_fetch.pop()()
|
||||
if isinstance(answers.get(name), Exception):
|
||||
raise answers[name]
|
||||
return answers.get(name, (False, True))
|
||||
|
||||
core.git_repo_update_check_with = fetch
|
||||
core.get_channel_dict = lambda: {'default': core.DEFAULT_CHANNEL}
|
||||
|
||||
other_lists = {}
|
||||
|
||||
async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
node_list = other_lists.get('the local mode' if mode == 'local' else channel_url, NODE_LIST)
|
||||
return {'custom-node-list.json': {'custom_nodes': [dict(item) for item in node_list]},
|
||||
'extras.json': {'favorites': []}}.get(filename, {})
|
||||
|
||||
core.get_data_by_mode = get_data_by_mode
|
||||
|
||||
def listed(name):
|
||||
url = f'https://github.com/example/{name}'
|
||||
NODE_LIST.append({'author': 'example', 'title': name, 'reference': url, 'files': [url],
|
||||
'install_type': 'git-clone', 'description': ''})
|
||||
return url
|
||||
|
||||
def request(query=None, body=None):
|
||||
async def json_body():
|
||||
return body
|
||||
return SimpleNamespace(rel_url=SimpleNamespace(query=query), json=json_body)
|
||||
|
||||
def node_list(query):
|
||||
handler = server_function('fetch_customnode_list', core=core, populate_markdown=lambda row: None,
|
||||
web=SimpleNamespace(json_response=lambda result, content_type: result))
|
||||
return asyncio.run(handler(request(query=query)))['node_packs']
|
||||
|
||||
class Lock:
|
||||
def __init__(self):
|
||||
self.held = threading.Lock()
|
||||
self.after_the_end = []
|
||||
|
||||
def __enter__(self):
|
||||
self.held.acquire()
|
||||
|
||||
def __exit__(self, *error):
|
||||
self.held.release()
|
||||
if self.after_the_end and update_check_done.is_set():
|
||||
self.after_the_end.pop()()
|
||||
|
||||
class EndMark(threading.Event):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.queue_waits = threading.Event()
|
||||
|
||||
def wait(self):
|
||||
self.queue_waits.set()
|
||||
super().wait()
|
||||
|
||||
events = []
|
||||
update_check_done = EndMark()
|
||||
update_check_done.set()
|
||||
update_check_lock = Lock()
|
||||
update_check_paths = {}
|
||||
update_check_ui_ids = set()
|
||||
started = []
|
||||
|
||||
def sent(name, data):
|
||||
events.append([name, {key: sorted(value) if isinstance(value, list) else value for key, value in data.items()}])
|
||||
|
||||
def started_later(target):
|
||||
return SimpleNamespace(start=lambda: started.append(target))
|
||||
|
||||
def ask_for_a_check(mode='cache', ui_id='the page', thread=started_later):
|
||||
ask = server_function(
|
||||
'check_update', core=core, update_check_done=update_check_done, update_check_lock=update_check_lock,
|
||||
update_check_paths=update_check_paths, update_check_ui_ids=update_check_ui_ids, traceback=traceback,
|
||||
threading=SimpleNamespace(Thread=lambda target: thread(target)),
|
||||
_reject_non_json_content_type=lambda request: None, web=SimpleNamespace(json_response=lambda data: data),
|
||||
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=sent)))
|
||||
return asyncio.run(ask(request(body={'mode': mode, 'ui_id': ui_id})))
|
||||
|
||||
def check_for_updates(mode='cache', ui_id='the page'):
|
||||
answer = ask_for_a_check(mode, ui_id)
|
||||
fetched_by_the_request = list(fetched)
|
||||
started.pop()()
|
||||
return {'answer': answer, 'fetched by the request': fetched_by_the_request, 'fetched': sorted(fetched),
|
||||
'check': [event for name, event in events if name == 'cm-check-update']}
|
||||
|
||||
DISABLE = ('disable', ('a-row', 'ComfyUI-Foo', False))
|
||||
|
||||
def run_the_queue(*tasks):
|
||||
order = []
|
||||
config['model_download_by_agent'] = True
|
||||
core.update_path = lambda path: order.append('ComfyUI is updated') or 'skipped'
|
||||
manager.unified_disable = lambda node_name, is_unknown: order.append('the task') or core.ManagedResult('disable')
|
||||
manager.unified_update = lambda node_name, node_ver: order.append('the task') or SimpleNamespace(ver='unknown', result=True, action='skip')
|
||||
task_queue = queue.Queue()
|
||||
for task in tasks:
|
||||
task_queue.put(task)
|
||||
worker = server_function(
|
||||
'task_worker', core=core, logging=logging, traceback=traceback, queue=queue, task_queue=task_queue,
|
||||
update_check_done=update_check_done, nodepack_result={}, model_result={}, tasks_in_progress=set(),
|
||||
task_worker_lock=threading.Lock(), os=os, folder_paths=SimpleNamespace(__file__=str(nodes.parent / 'folder_paths.py')),
|
||||
get_model_path=lambda data: str(nodes.parent / data['filename']),
|
||||
download_url_with_agent=lambda url, path: order.append('the model is downloaded') or True,
|
||||
manager_util=SimpleNamespace(clear_pip_cache=lambda: None),
|
||||
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=lambda name, data: None)))
|
||||
queue_run = threading.Thread(target=lambda: asyncio.run(worker()), daemon=True)
|
||||
queue_run.start()
|
||||
return order, queue_run
|
||||
|
||||
def run_the_queue_during_a_check(*tasks):
|
||||
update_check_done.clear()
|
||||
order, queue_run = run_the_queue(*tasks)
|
||||
update_check_done.queue_waits.wait(5)
|
||||
order.append('the check ends')
|
||||
update_check_done.set()
|
||||
queue_run.join()
|
||||
return order
|
||||
'''
|
||||
|
||||
|
||||
def run(body):
|
||||
return _run_child(PRELUDE + CHECK + body)
|
||||
|
||||
|
||||
def progress(total):
|
||||
return [{'status': 'in_progress', 'done_count': done, 'total_count': total} for done in range(1, total + 1)]
|
||||
|
||||
|
||||
def done(updatable, *ui_ids):
|
||||
return {'status': 'done', 'updatable': sorted(updatable), 'ui_ids': sorted(ui_ids or ['the page'])}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('query', [{'mode': 'cache'}, {'mode': 'cache', 'skip_update': 'true'}],
|
||||
ids=['without-skip_update', 'with-skip_update'])
|
||||
def test_the_request_for_the_node_list_fetches_no_repository(query):
|
||||
data = run(f'''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
rows = node_list({query!r})
|
||||
emit({{'installed': {{key: row['active_version'] for key, row in rows.items() if row['state'] == 'enabled'}}, 'fetched': fetched}})
|
||||
''')
|
||||
assert data == {'installed': {'comfyui-foo': 'nightly', 'ComfyUI-Bar': 'unknown'}, 'fetched': []}
|
||||
|
||||
|
||||
def test_a_check_fetches_the_enabled_git_nodepacks_of_the_list_once_its_request_is_answered():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('bar-clone', git_url=BAR_URL)
|
||||
pack('.disabled/ComfyUI-Bar')
|
||||
pack('comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
|
||||
pack('.disabled/ComfyUI-Disabled', git_url=listed('ComfyUI-Disabled'))
|
||||
listed('ComfyUI-Invalid')
|
||||
pack('ComfyUI-Invalid')
|
||||
pack('ComfyUI-NotListed', git_url='https://github.com/example/ComfyUI-NotListed')
|
||||
answers.update({'ComfyUI-Foo': (True, True), 'bar-clone': (True, True)})
|
||||
emit(check_for_updates())
|
||||
''')
|
||||
assert data['answer'] == {}
|
||||
assert data['fetched by the request'] == []
|
||||
assert data['fetched'] == ['ComfyUI-Foo', 'bar-clone']
|
||||
assert data['check'] == progress(2) + [done(['ComfyUI-Bar', 'comfyui-foo'])]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('shown', [
|
||||
"mode = 'local'; listed_under = 'the local mode'",
|
||||
"config['channel_url'] = listed_under = 'https://example.invalid/a-channel'; core.valid_channels.add(listed_under)",
|
||||
], ids=['the-local-list', 'the-list-of-another-channel'])
|
||||
def test_a_check_is_of_the_list_that_the_page_shows(shown):
|
||||
data = run(f'''
|
||||
mode = 'cache'
|
||||
{shown}
|
||||
other_lists[listed_under] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
emit(check_for_updates(mode=mode))
|
||||
''')
|
||||
assert data['fetched'] == ['ComfyUI-Foo']
|
||||
|
||||
|
||||
def test_a_nodepack_that_cannot_be_fetched_does_not_end_the_check():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
pack('ComfyUI-Qux', git_url=listed('ComfyUI-Qux'))
|
||||
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': OSError('no route to the remote')})
|
||||
emit(check_for_updates())
|
||||
''')
|
||||
assert data['fetched'] == ['ComfyUI-Bar', 'ComfyUI-Foo', 'ComfyUI-Qux']
|
||||
assert data['check'] == progress(3) + [done(['comfyui-foo'])]
|
||||
|
||||
|
||||
def test_a_check_of_no_nodepack_ends_with_an_empty_result():
|
||||
data = run('''
|
||||
pack('comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
|
||||
emit(check_for_updates())
|
||||
''')
|
||||
assert data['answer'] == {}
|
||||
assert data['check'] == [done([])]
|
||||
|
||||
|
||||
def test_a_check_that_is_asked_for_while_one_runs_starts_no_second_one():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
answers['ComfyUI-Foo'] = (True, True)
|
||||
answered = [ask_for_a_check(ui_id='a page'), ask_for_a_check(ui_id='another page')]
|
||||
running = len(started)
|
||||
started.pop()()
|
||||
ended = [event for name, event in events if event['status'] == 'done']
|
||||
ask_for_a_check()
|
||||
emit({'answered': answered, 'running': running, 'ended': ended, 'started after the end': len(started)})
|
||||
''')
|
||||
assert data == {'answered': [{}, {}], 'running': 1, 'ended': [done(['comfyui-foo'], 'a page', 'another page')],
|
||||
'started after the end': 1}
|
||||
|
||||
|
||||
def test_a_check_that_is_asked_for_while_one_runs_adds_the_nodepacks_that_one_does_not_have():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
|
||||
ask_for_a_check('local', ui_id='a page')
|
||||
during_a_fetch.append(lambda: ask_for_a_check(ui_id='another page'))
|
||||
started.pop()()
|
||||
emit({'fetched': fetched, 'started': len(started), 'check': [event for name, event in events]})
|
||||
''')
|
||||
assert data == {'fetched': ['ComfyUI-Foo', 'ComfyUI-Bar'], 'started': 0, 'check': [
|
||||
{'status': 'in_progress', 'done_count': 1, 'total_count': 2},
|
||||
{'status': 'in_progress', 'done_count': 2, 'total_count': 2},
|
||||
done(['comfyui-foo', 'ComfyUI-Bar'], 'a page', 'another page')]}
|
||||
|
||||
|
||||
def test_a_request_that_comes_when_the_check_has_had_its_last_look_is_answered_by_the_next_check():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
|
||||
ask_for_a_check('local', ui_id='a page')
|
||||
update_check_lock.after_the_end.append(lambda: ask_for_a_check(ui_id='another page'))
|
||||
started.pop()()
|
||||
first = [event for name, event in events]
|
||||
checks_started, a_check_runs = len(started), not update_check_done.is_set()
|
||||
del fetched[:]
|
||||
if started:
|
||||
started.pop()()
|
||||
emit({'first': first, 'checks started': checks_started, 'a check runs': a_check_runs, 'next': [event for name, event in events[len(first):]],
|
||||
'fetched by the next': sorted(fetched)})
|
||||
''')
|
||||
assert data == {'first': progress(1) + [done(['comfyui-foo'], 'a page')], 'checks started': 1, 'a check runs': True,
|
||||
'next': progress(2) + [done(['comfyui-foo', 'ComfyUI-Bar'], 'another page')],
|
||||
'fetched by the next': ['ComfyUI-Bar', 'ComfyUI-Foo']}
|
||||
|
||||
|
||||
def test_a_check_is_not_of_the_requests_of_the_check_before():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack('ComfyUI-Bar', git_url=BAR_URL)
|
||||
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
check_for_updates(ui_id='a page')
|
||||
del fetched[:]
|
||||
emit(check_for_updates('local', ui_id='another page'))
|
||||
''')
|
||||
assert data['fetched'] == ['ComfyUI-Foo']
|
||||
assert data['check'][-1] == done([], 'another page')
|
||||
|
||||
|
||||
def test_a_check_whose_thread_cannot_start_does_not_stand_in_the_way_of_the_next():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
|
||||
def no_thread(target):
|
||||
raise RuntimeError("can't start new thread")
|
||||
|
||||
try:
|
||||
ask_for_a_check(thread=no_thread)
|
||||
except RuntimeError:
|
||||
pass
|
||||
ask_for_a_check()
|
||||
emit(len(started))
|
||||
''')
|
||||
assert data == 1
|
||||
|
||||
|
||||
def test_a_check_that_fails_tells_the_pages_that_wait_for_it_and_does_not_hold_the_tasks_of_the_queue():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
during_the_check = [lambda: ask_for_a_check(ui_id='a page that asks during the check')]
|
||||
|
||||
def fails(paths, on_fetched):
|
||||
if during_the_check:
|
||||
during_the_check.pop()()
|
||||
raise RuntimeError("can't start new thread")
|
||||
|
||||
core.fetch_git_node_packs = fails
|
||||
ask_for_a_check()
|
||||
update_check_lock.after_the_end.append(lambda: ask_for_a_check(ui_id='a page that asks after it'))
|
||||
started.pop()()
|
||||
failed = [event for name, event in events]
|
||||
checks_started = len(started)
|
||||
if started:
|
||||
started.pop()()
|
||||
order, queue_run = run_the_queue(DISABLE)
|
||||
queue_run.join(5)
|
||||
emit({'failed': failed, 'checks started': checks_started, 'next': [event for name, event in events[len(failed):]], 'order': order})
|
||||
''')
|
||||
assert data == {'failed': [{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks during the check', 'the page']}],
|
||||
'checks started': 1,
|
||||
'next': [{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks after it']}],
|
||||
'order': ['the task']}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('task', [('disable', ('a-row', 'ComfyUI-Foo', False)), ('update-main', ('ComfyUI-Foo', 'ComfyUI-Foo', 'unknown'))],
|
||||
ids=['disable', 'Update-All'])
|
||||
def test_a_task_of_the_queue_waits_for_the_check_that_runs(task):
|
||||
assert run(f'emit(run_the_queue_during_a_check({task!r}))') == ['the check ends', 'the task']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('task, work', [
|
||||
(('install-model', ('a-model', {'name': 'a', 'url': 'https://example.invalid/a.safetensors', 'filename': 'a.safetensors'})),
|
||||
'the model is downloaded'),
|
||||
(('update-comfyui', ('comfyui', False)), 'ComfyUI is updated'),
|
||||
], ids=['a-model-download', 'an-update-of-ComfyUI'])
|
||||
def test_a_model_download_and_an_update_of_ComfyUI_do_not_wait_for_the_check(task, work):
|
||||
assert run(f'emit(run_the_queue_during_a_check({task!r}, DISABLE))') == [work, 'the check ends', 'the task']
|
||||
|
||||
|
||||
def test_the_request_that_fetched_inside_itself_is_gone():
|
||||
data = run('''
|
||||
pack('ComfyUI-Foo', git_url=FOO_URL)
|
||||
handler = server_function('fetch_updates', _reject_non_json_content_type=lambda request: None,
|
||||
web=SimpleNamespace(json_response=lambda data, status: [status, data['deprecated']]))
|
||||
emit({'answer': asyncio.run(handler(request(body={'mode': 'cache'}))), 'fetched': fetched})
|
||||
''')
|
||||
assert data == {'answer': [410, True], 'fetched': []}
|
||||
@@ -0,0 +1,86 @@
|
||||
from test_snapshot_restore_pins import run
|
||||
|
||||
PACKS = '''
|
||||
import ast, io, traceback
|
||||
from typing_extensions import Annotated, List
|
||||
import typer
|
||||
from rich.console import Console
|
||||
|
||||
def cm_cli(*names):
|
||||
found = [node for node in ast.parse(pathlib.Path('cm-cli.py').read_text(encoding='utf-8')).body if isinstance(node, ast.FunctionDef)
|
||||
and node.name in names]
|
||||
for node in found:
|
||||
node.decorator_list = []
|
||||
out = io.StringIO()
|
||||
scope = {'typer': typer, 'List': List, 'Annotated': Annotated, 'asyncio': asyncio, 'traceback': traceback,
|
||||
'print': Console(file=out, width=1000, color_system=None).print,
|
||||
'cmd_ctx': Mock(no_deps=False), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock()}
|
||||
exec(compile(ast.Module(body=found, type_ignores=[]), 'cm-cli.py', 'exec'), scope)
|
||||
return scope, lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if 'pack' in line]
|
||||
|
||||
def command(name):
|
||||
scope, said = cm_cli(name, 'for_each_nodes', 'get_all_installed_node_specs', 'enable_node', 'disable_node')
|
||||
scope[name](['all'], None, None, None)
|
||||
return [line.split('=>')[-1].strip() for line in said()]
|
||||
|
||||
for name in ('enabled-pack', '.disabled/registry-pack@1_0_0', '.disabled/rc-pack@1_0_0-rc1', '.disabled/git-pack'):
|
||||
(nodes / name).mkdir(parents=True)
|
||||
manager.active_nodes['enabled-pack'] = ('2.0.0', str(nodes / 'enabled-pack'))
|
||||
manager.cnr_inactive_nodes['registry-pack'] = {'1.0.0': str(nodes / '.disabled/registry-pack@1_0_0')}
|
||||
manager.cnr_inactive_nodes['rc-pack'] = {'1.0.0-rc1': str(nodes / '.disabled/rc-pack@1_0_0-rc1')}
|
||||
manager.unknown_inactive_nodes['git-pack'] = ('https://github.com/owner/git-pack', str(nodes / '.disabled/git-pack'))
|
||||
'''
|
||||
|
||||
|
||||
def all_of(name):
|
||||
return run(PACKS + f'''
|
||||
said = command({name!r})
|
||||
print(json.dumps({{'said': said, 'enabled': sorted(os.listdir(nodes)), 'disabled': sorted(os.listdir(nodes / '.disabled'))}}))
|
||||
''')
|
||||
|
||||
|
||||
def test_enable_all_enables_every_disabled_nodepack():
|
||||
result = all_of('enable')
|
||||
|
||||
assert result['enabled'] == ['.disabled', 'enabled-pack', 'git-pack', 'rc-pack', 'registry-pack']
|
||||
assert result['disabled'] == []
|
||||
assert result['said'][0] == 'Already enabled'
|
||||
|
||||
|
||||
def test_disable_all_disables_every_enabled_nodepack_and_leaves_the_disabled_ones():
|
||||
result = all_of('disable')
|
||||
|
||||
assert result['enabled'] == ['.disabled']
|
||||
assert result['disabled'] == ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1', 'registry-pack@1_0_0']
|
||||
assert result['said'][1:] == ['Already disabled', 'Already disabled', 'Already disabled']
|
||||
|
||||
|
||||
def test_latest_names_the_installed_nodepack_as_a_bare_id_does():
|
||||
result = run(PACKS + '''
|
||||
for name, latest in (('enabled-pack', '3.0.0'), ('registry-pack', '1.5.0')):
|
||||
manager.cnr_map[name] = {'id': name, 'latest_version': {'version': latest}}
|
||||
manager.unified_update = lambda node_id, version_spec=None, **kwargs: core.ManagedResult('update').with_target('3.0.0')
|
||||
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
|
||||
scope, said = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
|
||||
for act, name in (('update_node', 'enabled-pack'), ('fix_node', 'enabled-pack'), ('disable_node', 'enabled-pack'), ('enable_node', 'registry-pack')):
|
||||
scope[act](name + '@latest')
|
||||
print(json.dumps({'said': said(), 'enabled': sorted(os.listdir(nodes)), 'disabled': sorted(os.listdir(nodes / '.disabled'))}))
|
||||
''')
|
||||
|
||||
assert result['said'] == ['[ UPDATED ]: enabled-pack => (2.0.0 -> 3.0.0)', '[ FIXING ]: enabled-pack [2.0.0]', '[DISABLED] enabled-pack',
|
||||
'[ENABLED] registry-pack']
|
||||
assert result['enabled'] == ['.disabled', 'registry-pack']
|
||||
assert 'enabled-pack@2_0_0' in result['disabled']
|
||||
|
||||
|
||||
def test_a_registry_nodepack_that_is_not_installed_is_not_called_disabled():
|
||||
result = run(PACKS + '''
|
||||
manager.cnr_map['absent-pack'] = {'id': 'absent-pack', 'latest_version': {'version': '1.0.0'}}
|
||||
scope, said = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
|
||||
for name in ('absent-pack', 'absent-pack@latest'):
|
||||
for act in ('update_node', 'fix_node', 'disable_node', 'enable_node'):
|
||||
scope[act](name)
|
||||
print(json.dumps({'said': [line.split('=>')[-1].strip() for line in said()]}))
|
||||
''')
|
||||
|
||||
assert result['said'] == ['Not installed', 'Not installed', 'Not found', 'Not found'] * 2
|
||||
@@ -0,0 +1,304 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from test_snapshot_restore_pins import run
|
||||
|
||||
CLI = '''
|
||||
import ast, inspect, io, sys, threading, concurrent.futures, traceback
|
||||
from typing import Optional
|
||||
from typing_extensions import Annotated, List
|
||||
import rich, typer, typer.testing
|
||||
|
||||
def binds_print(node):
|
||||
if isinstance(node, ast.Assign):
|
||||
return any(isinstance(target, ast.Name) and target.id == 'print' for target in node.targets)
|
||||
return isinstance(node, ast.ImportFrom) and any((name.asname or name.name) == 'print' for name in node.names)
|
||||
|
||||
def cm_cli(*names, width=1000, color_system=None, **more):
|
||||
found = [node for node in ast.parse(pathlib.Path('cm-cli.py').read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name in names or binds_print(node)]
|
||||
if 'app' not in more:
|
||||
for node in found:
|
||||
node.decorator_list = []
|
||||
out = io.StringIO()
|
||||
rich.reconfigure(file=out, width=width, color_system=color_system, no_color=False)
|
||||
scope = {'typer': typer, 'List': List, 'Annotated': Annotated, 'Optional': Optional, 'asyncio': asyncio, 'traceback': traceback,
|
||||
'os': os, 'sys': sys, 'json': json, 'threading': threading, 'concurrent': concurrent,
|
||||
'core': core, 'cnr_utils': cnr_utils,
|
||||
'cmd_ctx': Mock(no_deps=False, channel='default', mode='cache'), 'unified_manager': manager,
|
||||
'auto_save_snapshot': AsyncMock(), 'manager_util': Mock(), 'comfy_path': tmp, **more}
|
||||
exec(compile(ast.Module(body=found, type_ignores=[]), 'cm-cli.py', 'exec'), scope)
|
||||
return scope, lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if line.strip()]
|
||||
|
||||
def command(scope, name, **given):
|
||||
try:
|
||||
scope[name](**{**dict.fromkeys(inspect.signature(scope[name]).parameters), **given})
|
||||
except (SystemExit, typer.Exit):
|
||||
pass
|
||||
|
||||
GIT_PACK = ('https://example.invalid/git-pack', str(nodes / 'git-pack'))
|
||||
folder = os.path.join(tmp, '[my] files')
|
||||
os.mkdir(folder)
|
||||
'''
|
||||
|
||||
|
||||
def said(body):
|
||||
return run(CLI + body + '\nprint(json.dumps(lines()))\n')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed, name, label', [
|
||||
("manager.unknown_active_nodes['git-pack'] = GIT_PACK", 'git-pack', '[unknown]'),
|
||||
("manager.active_nodes['git-pack'] = ('nightly', GIT_PACK[1])", 'git-pack@nightly', '[nightly]'),
|
||||
], ids=['unknown', 'nightly'])
|
||||
def test_fix_names_the_version_of_a_git_nodepack(installed, name, label):
|
||||
assert said(f'''
|
||||
{installed}
|
||||
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
|
||||
scope, lines = cm_cli('fix_node')
|
||||
scope['fix_node']({name!r}, cnt_msg='1/1')
|
||||
''') == [f'1/1 [ FIXING ]: git-pack {label}']
|
||||
|
||||
|
||||
def test_fix_that_fails_says_why():
|
||||
assert said('''
|
||||
manager.unknown_active_nodes['git-pack'] = GIT_PACK
|
||||
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix').fail('cannot fix [the reason]')
|
||||
scope, lines = cm_cli('fix_node')
|
||||
scope['fix_node']('git-pack', cnt_msg='1/1')
|
||||
''')[1:] == ['ERROR: cannot fix [the reason]']
|
||||
|
||||
|
||||
def test_fix_all_has_a_line_for_each_nodepack_it_counts():
|
||||
assert said('''
|
||||
manager.unknown_active_nodes['git-pack'] = GIT_PACK
|
||||
manager.unknown_inactive_nodes['old-pack'] = ('https://example.invalid/old-pack', str(nodes / '.disabled/old-pack'))
|
||||
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
|
||||
scope, lines = cm_cli('fix', 'for_each_nodes', 'get_all_installed_node_specs', 'fix_node')
|
||||
command(scope, 'fix', nodes=['all'])
|
||||
''') == ['1/2 [ FIXING ]: git-pack [unknown]', '2/2 [ SKIPPED ]: old-pack@unknown => Disabled']
|
||||
|
||||
|
||||
def test_url_that_is_not_installed_says_why():
|
||||
assert said('''
|
||||
core.gitclone_install = AsyncMock(return_value=core.ManagedResult('install-git').fail('cannot clone [the reason]'))
|
||||
scope, lines = cm_cli('install_node')
|
||||
scope['install_node'](GIT_PACK[0], cnt_msg='1/1')
|
||||
''') == ['cannot clone [the reason]', "ERROR: An error occurred while installing 'https://example.invalid/git-pack'."]
|
||||
|
||||
|
||||
def test_install_of_an_id_that_no_list_has_says_where_it_was_looked_for():
|
||||
assert said('''
|
||||
scope, lines = cm_cli('install_node')
|
||||
scope['install_node']('no-such-pack', cnt_msg='1/1')
|
||||
''') == ["ERROR: An error occurred while installing 'no-such-pack'.", "Node 'no-such-pack@unknown' not found in [default, cache]"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed, act, line', [
|
||||
("manager.unknown_inactive_nodes['git-pack'] = GIT_PACK; manager.unified_enable = lambda *args: core.ManagedResult('enable').fail(REASON)",
|
||||
'enable_node', '1/1 [ FAIL ] git-pack => cannot move [the folder]'),
|
||||
("manager.unknown_inactive_nodes['git-pack'] = GIT_PACK; manager.unified_enable = lambda *args: core.ManagedResult('skip').with_msg(REASON)",
|
||||
'enable_node', '1/1 [ SKIP ] git-pack => cannot move [the folder]'),
|
||||
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_disable = lambda *args: core.ManagedResult('disable').fail(REASON)",
|
||||
'disable_node', '1/1 [ FAIL ] git-pack => cannot move [the folder]'),
|
||||
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_disable = lambda *args: core.ManagedResult('skip').with_msg(REASON)",
|
||||
'disable_node', '1/1 [ SKIP ] git-pack => cannot move [the folder]'),
|
||||
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_update = lambda *args, **kwargs: core.ManagedResult('skip').with_msg(REASON)",
|
||||
'update_node', '1/1 [ SKIPPED ]: git-pack => cannot move [the folder]'),
|
||||
], ids=['enable_fails', 'enable_is_skipped', 'disable_fails', 'disable_is_skipped', 'update_is_skipped'])
|
||||
def test_reason_in_square_brackets_is_printed_whole(installed, act, line):
|
||||
assert said(f'''
|
||||
REASON = 'cannot move [the folder]'
|
||||
{installed}
|
||||
scope, lines = cm_cli({act!r})
|
||||
scope[{act!r}]('git-pack', cnt_msg='1/1')
|
||||
''') == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name, installed, act, line', [
|
||||
('git-pack[old]', "manager.unknown_inactive_nodes[NAME] = PACK; manager.unified_enable = lambda *args: core.ManagedResult('enable')",
|
||||
'enable_node', '1/1 [ENABLED] git-pack[old]'),
|
||||
('git-pack[old]', "manager.unknown_active_nodes[NAME] = PACK; manager.unified_disable = lambda *args: core.ManagedResult('disable')",
|
||||
'disable_node', '1/1 [DISABLED] git-pack[old]'),
|
||||
('comfyui-manager[old]', "manager.unknown_active_nodes[NAME] = PACK",
|
||||
'disable_node', "1/1 [ SKIP ] comfyui-manager[old] => Not disabled: its name has 'comfyui-manager'"),
|
||||
('git-pack[old]', "manager.unknown_inactive_nodes[NAME] = PACK", 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Disabled'),
|
||||
('git-pack[old]', "", 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
|
||||
('git-pack[old]', "", 'update_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
|
||||
], ids=['enable', 'disable', 'disable_of_the_manager', 'fix_of_a_disabled_one', 'fix_of_one_that_is_not_installed',
|
||||
'update_of_one_that_is_not_installed'])
|
||||
def test_name_in_square_brackets_is_printed_whole(name, installed, act, line):
|
||||
assert said(f'''
|
||||
NAME = {name!r}
|
||||
PACK = ('https://example.invalid/git-pack', str(nodes / NAME))
|
||||
{installed}
|
||||
scope, lines = cm_cli({act!r})
|
||||
scope[{act!r}](NAME, cnt_msg='1/1')
|
||||
''') == [line]
|
||||
|
||||
|
||||
def test_line_longer_than_the_console_is_wide_is_written_as_one_line():
|
||||
assert said('''
|
||||
manager.unknown_active_nodes['git-pack'] = GIT_PACK
|
||||
scope, lines = cm_cli('enable_node', width=80)
|
||||
scope['enable_node']('git-pack', cnt_msg='1/1')
|
||||
''') == ['1/1 [ SKIP ] git-pack => Already enabled']
|
||||
|
||||
|
||||
def test_error_of_a_nodepack_in_a_run_over_several_is_printed_whole():
|
||||
assert said('''
|
||||
def act(name, **kwargs):
|
||||
raise RuntimeError('no such [thing] for ' + name)
|
||||
|
||||
scope, lines = cm_cli('for_each_nodes', traceback=Mock())
|
||||
scope['for_each_nodes'](['git-pack'], act)
|
||||
''') == ['ERROR: no such [thing] for git-pack']
|
||||
|
||||
|
||||
def test_error_of_an_update_in_a_run_over_several_is_printed_whole():
|
||||
assert said('''
|
||||
scope, lines = cm_cli('update_parallel', update_node=Mock(side_effect=RuntimeError('no such [thing]')), traceback=Mock())
|
||||
scope['update_parallel'](['git-pack'])
|
||||
''') == ['ERROR: no such [thing]']
|
||||
|
||||
|
||||
def test_show_versions_prints_a_changelog_with_square_brackets():
|
||||
assert said('''
|
||||
cnr_utils.all_versions_of_node = lambda name: [{'createdAt': '2026-01-02T03:04:05', 'version': '1.0.1', 'changelog': '[fix] a crash'}]
|
||||
scope, lines = cm_cli('show_versions')
|
||||
scope['show_versions']('git-pack')
|
||||
''') == ['[2026-01-02] 1.0.1 -- [fix] a crash']
|
||||
|
||||
|
||||
def test_show_prints_a_title_and_an_author_with_square_brackets():
|
||||
assert said('''
|
||||
manager.get_custom_nodes = AsyncMock(return_value={
|
||||
'listed-pack': {'title': 'Listed [gist-wrapper] Pack', 'author': 'some[one]', 'files': ['https://github.com/someone/listed-pack']},
|
||||
})
|
||||
manager.cnr_map['registry-pack'] = {'id': 'registry-pack', 'name': 'Registry[official] Pack', 'publisher': {'name': 'someone'},
|
||||
'latest_version': {'version': '1.0.0'}}
|
||||
manager.active_nodes['registry-pack'] = ('1.0.0', str(nodes / 'registry-pack'))
|
||||
manager.unknown_active_nodes['listed-pack'] = ('https://github.com/someone/listed-pack', str(nodes / 'listed-pack'))
|
||||
scope, lines = cm_cli('show', 'simple_show', 'show_list')
|
||||
scope['show']('installed', None, None, None)
|
||||
scope['simple_show']('installed', None, None, None)
|
||||
''') == ['[ ENABLED ] Registry[official] Pack registry-pack (author: someone ) [1.0.0]',
|
||||
'[ ENABLED ] Listed [gist-wrapper] Pack listed-pack (author: some[one] ) [UNKNOWN]',
|
||||
'Registry[official] Pack@1.0.0', 'Listed [gist-wrapper] Pack@unknown']
|
||||
|
||||
|
||||
def test_show_of_a_word_that_is_no_list_is_refused_in_plain_words():
|
||||
assert said('''
|
||||
sys.stderr = refusal = io.StringIO()
|
||||
scope, lines = cm_cli('simple_show')
|
||||
command(scope, 'simple_show', arg='[nodes]')
|
||||
lines = lambda: refusal.getvalue().split()
|
||||
''') == ['Invalid', 'command:', '`show', '[nodes]`']
|
||||
|
||||
|
||||
def test_names_of_snapshots_are_listed_whole():
|
||||
assert said('''
|
||||
open(os.path.join(folder, 'before [the update].json'), 'w').close()
|
||||
scope, lines = cm_cli('show_snapshot_list')
|
||||
scope['cmd_ctx'].get_snapshot_path.return_value = folder
|
||||
scope['show_snapshot_list']()
|
||||
''') == ['before [the update].json']
|
||||
|
||||
|
||||
PATHS = {
|
||||
'restore-snapshot of a file that is not there': (
|
||||
"scope['cmd_ctx'].get_snapshot_path.return_value = folder; command(scope, 'restore_snapshot', snapshot_name='gone.json')",
|
||||
f'ERROR: `{{folder}}{os.sep}gone.json` is not exists.'),
|
||||
'save-snapshot into a folder that is not there': (
|
||||
"command(scope, 'save_snapshot', output=folder + '/gone/snapshot.json')", 'ERROR: {folder}/gone/snapshot.json path not exists.'),
|
||||
'save-snapshot': (
|
||||
"core.save_snapshot_with_postfix = AsyncMock(return_value=folder + '/snapshot.json'); command(scope, 'save_snapshot', output=folder + '/snapshot.json')",
|
||||
'Current snapshot is saved as `{folder}/snapshot.json`'),
|
||||
'deps-in-workflow of a file that is not there': (
|
||||
"command(scope, 'deps_in_workflow', workflow=folder + '/gone.json', output='deps.json')", 'File not found: {folder}/gone.json'),
|
||||
'deps-in-workflow': (
|
||||
"open(folder + '/workflow.json', 'w').close(); core.extract_nodes_from_workflow = AsyncMock(return_value=({}, []));"
|
||||
" command(scope, 'deps_in_workflow', workflow=folder + '/workflow.json', output=folder + '/deps.json')",
|
||||
'Workflow dependencies are being saved into {folder}/deps.json.'),
|
||||
'install-deps of a file that is not there': ("command(scope, 'install_deps', deps=folder + '/gone.json')", 'File not found: {folder}/gone.json'),
|
||||
'install-deps of a file that is not JSON': (
|
||||
"open(folder + '/deps.json', 'w').close(); command(scope, 'install_deps', deps=folder + '/deps.json')", 'Invalid json file: {folder}/deps.json'),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', PATHS)
|
||||
def test_path_with_square_brackets_is_printed_whole(case):
|
||||
call, line = PATHS[case]
|
||||
|
||||
assert said(f'''
|
||||
scope, said = cm_cli('restore_snapshot', 'save_snapshot', 'deps_in_workflow', 'install_deps')
|
||||
{call}
|
||||
lines = lambda: [line.replace(folder, '{{folder}}') for line in said()][-1:]
|
||||
''') == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path', [r'C:\ComfyUI\[My] files\deps.json', '/nodes/' + 'long-folder-name/' * 5 + 'deps.json', '/nodes/x:100:y/deps.json'],
|
||||
ids=['a backslash before a bracket', 'longer than the console is wide', 'the code of an emoji'])
|
||||
@pytest.mark.parametrize('call, line', [
|
||||
("command(scope, 'install_deps', deps=path)", 'File not found: {}'),
|
||||
("core.save_snapshot_with_postfix = AsyncMock(return_value=path); command(scope, 'save_snapshot')", 'Current snapshot is saved as `{}`'),
|
||||
], ids=['a coloured line', 'a line without a colour'])
|
||||
def test_line_is_written_as_it_is(call, line, path):
|
||||
assert said(f'''
|
||||
path = {path!r}
|
||||
scope, lines = cm_cli('install_deps', 'save_snapshot', width=80)
|
||||
{call}
|
||||
''') == [line.format(path)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('call, line', [
|
||||
("command(scope, 'install_deps', deps='deps.json')", '\x1b[1;31mFile not found: deps.json\x1b[0m'),
|
||||
("open(os.path.join(folder, \"the 'old' one.json\"), 'w').close(); scope['cmd_ctx'].get_snapshot_path.return_value = folder;"
|
||||
" scope['show_snapshot_list']()", "the \x1b[32m'old'\x1b[0m one.json"),
|
||||
], ids=['a line that cm-cli colours', 'a quoted text in another line'])
|
||||
def test_line_keeps_its_colour(call, line):
|
||||
assert said(f'''
|
||||
scope, lines = cm_cli('install_deps', 'show_snapshot_list', color_system='standard')
|
||||
{call}
|
||||
''') == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('app', ['typer.Typer()', 'typer.Typer(rich_markup_mode=None)'], ids=['with rich markup', 'without'])
|
||||
def test_help_names_the_values_that_an_argument_and_an_option_take(app):
|
||||
assert said(f'''
|
||||
scope, said = cm_cli('show', 'update', app={app})
|
||||
help = lambda name: ' '.join(typer.testing.CliRunner().invoke(scope['app'], [name, '--help'], env={{'COLUMNS': '200'}}).output.split())
|
||||
lines = lambda: [text in help(name) and chr(92) not in help(name) for name, text in (
|
||||
('show', 'installed|enabled|not-installed'), ('show', 'remote|local|cache'),
|
||||
('update', 'all|List of custom nodes to update'), ('update', 'remote|local|cache'))]
|
||||
''') == [True, True, True, True]
|
||||
|
||||
|
||||
def test_disable_says_why_the_manager_is_not_disabled():
|
||||
assert said('''
|
||||
scope, lines = cm_cli('disable_node')
|
||||
scope['disable_node']('comfyui-manager', cnt_msg='1/1')
|
||||
''') == ["1/1 [ SKIP ] comfyui-manager => Not disabled: its name has 'comfyui-manager'"]
|
||||
|
||||
|
||||
def test_disable_all_has_a_line_for_each_nodepack_it_counts():
|
||||
assert [line.split()[0] for line in said('''
|
||||
for name in ('comfyui-manager', 'git-pack'):
|
||||
(nodes / name).mkdir()
|
||||
manager.unknown_active_nodes[name] = ('https://example.invalid/' + name, str(nodes / name))
|
||||
scope, lines = cm_cli('disable', 'for_each_nodes', 'get_all_installed_node_specs', 'disable_node')
|
||||
scope['disable'](['all'], None, None, None)
|
||||
''')] == ['1/2', '2/2']
|
||||
|
||||
|
||||
def test_restore_dependencies_runs_for_the_nodepacks_only():
|
||||
assert said('''
|
||||
for name in ('a-pack', '__pycache__', 'b-pack.disabled', '.disabled'):
|
||||
os.mkdir(os.path.join(folder, name))
|
||||
manager.execute_install_script = Mock()
|
||||
scope, said = cm_cli('restore_dependencies')
|
||||
scope['cmd_ctx'].get_custom_nodes_paths.return_value = [folder]
|
||||
command(scope, 'restore_dependencies')
|
||||
lines = lambda: ([line.replace(folder, '{folder}') for line in said() if line.startswith('Restoring')]
|
||||
+ [os.path.basename(call.args[1]) for call in manager.execute_install_script.call_args_list])
|
||||
''') == ['Restoring [1/1]: {folder}' + os.sep + 'a-pack', 'a-pack']
|
||||
@@ -0,0 +1,238 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
LEVELS = ["strong", "normal", "normal-", "weak"]
|
||||
SERVER = {"is_allowed_security_level", "security_403_response", "_reject_non_json_content_type", "comfyui_switch_version"}
|
||||
CORE = {"parse_semver", "is_comfyui_downgrade"}
|
||||
|
||||
|
||||
class GitCommandError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def functions(name, names):
|
||||
source = (GLOB_DIR / name).read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names
|
||||
or isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("SECURITY_MESSAGE_")]
|
||||
assert names <= {getattr(node, "name", None) for node in nodes}
|
||||
return compile(ast.Module(body=nodes, type_ignores=[]), name, "exec")
|
||||
|
||||
|
||||
def load(security_level, loopback, described="v0.3.60"):
|
||||
def describe(*args):
|
||||
if described is None:
|
||||
raise GitCommandError("fatal: No names found, cannot describe anything.")
|
||||
return described
|
||||
|
||||
git = SimpleNamespace(Repo=lambda path: SimpleNamespace(git=SimpleNamespace(describe=describe)),
|
||||
GitCommandError=GitCommandError)
|
||||
core = {"re": re, "git": git, "comfy_path": "comfyui"}
|
||||
exec(functions("manager_core.py", CORE), core)
|
||||
|
||||
switched = []
|
||||
server = {
|
||||
"routes": web.RouteTableDef(), "web": web, "logging": logging, "sys": sys,
|
||||
"is_local_mode": loopback,
|
||||
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level},
|
||||
is_comfyui_downgrade=core["is_comfyui_downgrade"], switch_comfyui=switched.append),
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: True),
|
||||
}
|
||||
exec(functions("manager_server.py", SERVER), server)
|
||||
return server["comfyui_switch_version"], switched
|
||||
|
||||
|
||||
def call(handler, body):
|
||||
async def read_json():
|
||||
return body
|
||||
|
||||
try:
|
||||
response = asyncio.run(handler(SimpleNamespace(json=read_json, content_type="application/json")))
|
||||
except Exception:
|
||||
return 500, None
|
||||
return response.status, json.loads(response.text) if response.text else None
|
||||
|
||||
|
||||
REFUSED = (403, {"error": "security_level"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_an_older_release_needs_normal_minus_on_loopback_and_weak_otherwise(security_level, loopback):
|
||||
comfyui_switch_version, switched = load(security_level, loopback)
|
||||
|
||||
answer = call(comfyui_switch_version, {"ver": "v0.3.59"})
|
||||
|
||||
if security_level == "weak" or loopback and security_level == "normal-":
|
||||
assert answer == (200, None)
|
||||
assert switched == ["v0.3.59"]
|
||||
else:
|
||||
assert answer == REFUSED
|
||||
assert switched == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("version", ["nightly", "v0.3.60", "v0.3.61", "v0.4.0", "v1.0.0"],
|
||||
ids=["nightly", "the same release", "a newer patch", "a newer minor", "a newer major"])
|
||||
def test_an_update_is_not_held_to_a_level(version, security_level, loopback):
|
||||
comfyui_switch_version, switched = load(security_level, loopback)
|
||||
|
||||
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
|
||||
assert switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described, version, older", [
|
||||
("v0.3.60-12-gabc1234", "v0.3.60", True), ("v0.3.60-12-gabc1234", "v0.3.61", False),
|
||||
("v0.3.60-12-gabc1234", "v0.3.59", True), ("v0.3.60-1-gabc1234", "v0.3.60", True),
|
||||
("v0.45.0-32-g0123abc", "v0.45.0", True), ("v0.45.0-32-g0123abc", "v0.45.4", False),
|
||||
("v0.9.0", "v0.10.0", False), ("v0.10.0", "v0.9.0", True), ("v0.10.0", "v0.9.99", True),
|
||||
("v1.0.0", "v0.99.99", True), ("v0.3.60", "v0.3.060", False), ("v0.3.60", "v0.2.61", True),
|
||||
], ids=["commits after a release, that release", "commits after a release, a newer one", "commits after a release, an older one",
|
||||
"one commit after a release, that release", "nightly, the first release of its minor", "nightly, a later patch release",
|
||||
"a two-digit minor is newer", "a one-digit minor is older", "a higher patch of a lower minor",
|
||||
"a lower major", "leading zeros", "a higher patch of an older minor"])
|
||||
def test_releases_are_compared_by_their_numbers(described, version, older):
|
||||
comfyui_switch_version, switched = load("strong", True, described)
|
||||
|
||||
answer = call(comfyui_switch_version, {"ver": version})
|
||||
|
||||
assert (answer, switched) == ((REFUSED, []) if older else ((200, None), [version]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [
|
||||
"master", "HEAD~100", "abc1234", "0.3.61", "v0.3", "v0.3.61.1", "v0.3.61-rc1", "V0.3.61", " v0.3.61", "v0.3.61 ",
|
||||
"refs/tags/v0.3.61", "latest", "Nightly", "v0.3.61\n", "v0.3.61\nv0.3.59", "\nv0.3.61", "",
|
||||
], ids=["a branch", "an ancestor", "a commit", "no v", "two numbers", "four numbers", "a suffix", "upper case",
|
||||
"a leading space", "a trailing space", "a full ref", "another name", "nightly in another case", "a trailing newline",
|
||||
"two lines", "a leading newline", "empty"])
|
||||
def test_what_is_not_a_release_tag_is_held_like_an_older_release(version):
|
||||
comfyui_switch_version, switched = load("normal", True)
|
||||
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
|
||||
assert switched == []
|
||||
|
||||
comfyui_switch_version, switched = load("normal-", True)
|
||||
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
|
||||
assert switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described", [None, "", "latest", "latest-3-gabc1234", "0.3.60", "v0.3"],
|
||||
ids=["no tag", "nothing", "another tag", "commits after another tag", "no v", "two numbers"])
|
||||
@pytest.mark.parametrize("version", ["v0.3.61", "v9.9.9"])
|
||||
def test_without_a_release_to_compare_with_every_release_is_held(described, version):
|
||||
comfyui_switch_version, switched = load("normal", True, described)
|
||||
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
|
||||
assert switched == []
|
||||
|
||||
comfyui_switch_version, switched = load("weak", False, described)
|
||||
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
|
||||
assert switched == [version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("described", [None, "latest"], ids=["no tag", "another tag"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_nightly_needs_no_release_to_compare_with(security_level, described):
|
||||
comfyui_switch_version, switched = load(security_level, False, described)
|
||||
|
||||
assert call(comfyui_switch_version, {"ver": "nightly"}) == (200, None)
|
||||
assert switched == ["nightly"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [None, 1, 0.3, ["v0.3.61"], {"v": "0.3.61"}, True],
|
||||
ids=["null", "an integer", "a number", "a list", "an object", "a boolean"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_version_that_is_not_text_switches_nothing(security_level, version):
|
||||
comfyui_switch_version, switched = load(security_level, True)
|
||||
|
||||
status, _ = call(comfyui_switch_version, {"ver": version})
|
||||
|
||||
assert status == 400
|
||||
assert switched == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [{}, {"version": "v0.3.59"}], ids=["no fields", "another field"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_request_without_a_version_does_nothing(security_level, body):
|
||||
comfyui_switch_version, switched = load(security_level, False)
|
||||
|
||||
assert call(comfyui_switch_version, body) == (200, None)
|
||||
assert switched == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("security_level", ["", "STRONG", "middle", "high"])
|
||||
def test_a_security_level_that_is_not_one_of_the_four_allows_no_older_release(security_level):
|
||||
comfyui_switch_version, switched = load(security_level, True)
|
||||
|
||||
assert call(comfyui_switch_version, {"ver": "v0.3.59"}) == REFUSED
|
||||
assert call(comfyui_switch_version, {"ver": "v0.3.61"}) == (200, None)
|
||||
assert switched == ["v0.3.61"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repository(tmp_path, monkeypatch):
|
||||
if shutil.which("git") is None:
|
||||
pytest.skip("git is not installed")
|
||||
# git takes its repository from these when they are set, as they are under a git hook
|
||||
for name in [name for name in os.environ if name.startswith("GIT_")]:
|
||||
monkeypatch.delenv(name)
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(["git", "-C", str(tmp_path), "-c", "user.name=test", "-c", "user.email=test@example.invalid",
|
||||
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True)
|
||||
|
||||
run("init", "-q")
|
||||
for release in ("v0.3.59", "v0.3.60"):
|
||||
run("commit", "-q", "--allow-empty", "-m", release)
|
||||
run("tag", release)
|
||||
return tmp_path, run
|
||||
|
||||
|
||||
def is_downgrade(path, tag):
|
||||
core = {"re": re, "git": pytest.importorskip("git"), "comfy_path": str(path)}
|
||||
exec(functions("manager_core.py", CORE), core)
|
||||
return core["is_comfyui_downgrade"](tag)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", False), ("v0.3.61", False), ("nightly", False),
|
||||
("master", True)])
|
||||
def test_in_a_repository_at_a_release_only_an_older_one_goes_back(repository, tag, older):
|
||||
path, _ = repository
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", True), ("v0.3.61", False), ("nightly", False)])
|
||||
def test_in_a_repository_with_a_commit_after_the_release_that_release_goes_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("commit", "-q", "--allow-empty", "-m", "after the release")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.59", False), ("v0.3.60", False), ("v0.3.58", True)])
|
||||
def test_in_a_repository_checked_out_at_an_earlier_release_the_later_one_does_not_go_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("checkout", "-q", "v0.3.59")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tag, older", [("v0.3.60", True), ("nightly", False)])
|
||||
def test_in_a_repository_without_a_release_tag_every_release_goes_back(repository, tag, older):
|
||||
path, run = repository
|
||||
run("tag", "-d", "v0.3.59", "v0.3.60")
|
||||
|
||||
assert is_downgrade(path, tag) is older
|
||||
@@ -0,0 +1,41 @@
|
||||
"""`comfyui_versions` answers 400 when the versions of ComfyUI cannot be read.
|
||||
|
||||
Each case runs the real handler of `glob/manager_server.py`; `core` is replaced.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
|
||||
def fail():
|
||||
raise RuntimeError("not a git repository")
|
||||
|
||||
|
||||
def answer(get_comfyui_versions):
|
||||
"""The status and text `comfyui_versions` answers."""
|
||||
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
handler = [node for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "comfyui_versions"]
|
||||
assert len(handler) == 1
|
||||
namespace = {"web": web, "logging": logging, "sys": sys,
|
||||
"core": SimpleNamespace(get_comfyui_versions=get_comfyui_versions),
|
||||
"routes": SimpleNamespace(get=lambda path: lambda handler: handler)}
|
||||
exec(compile(ast.Module(body=handler, type_ignores=[]), "<comfyui_versions>", "exec"), namespace)
|
||||
response = asyncio.run(namespace["comfyui_versions"](None))
|
||||
return response.status, response.text
|
||||
|
||||
|
||||
def test_version_list_that_cannot_be_read_is_answered_with_400(caplog):
|
||||
assert answer(fail) == (400, None)
|
||||
assert "ComfyUI update fail: not a git repository" in caplog.text
|
||||
|
||||
|
||||
def test_version_list_is_answered_with_the_versions():
|
||||
assert answer(lambda: (["nightly", "v0.3.1"], "v0.3.1", "v0.3.1")) == (
|
||||
200, '{"versions": ["nightly", "v0.3.1"], "current": "v0.3.1"}')
|
||||
@@ -0,0 +1,62 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import NODE, JsSource, run_node, slice_braced
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
|
||||
COMPONENT = {"packname": "a pack", "category": "", "nodes": [], "links": [], "external": []}
|
||||
|
||||
|
||||
def load(status, body):
|
||||
source = JS.text("components-manager.js")
|
||||
script = """
|
||||
const registered = [];
|
||||
const app = {graph: {}};
|
||||
const api = {fetchApi: async () => ({status: %s, json: async () => JSON.parse(%s)})};
|
||||
const SEPARATOR = '/';
|
||||
const sleep = async () => {};
|
||||
const register_pack_map = () => {};
|
||||
class GroupNodeConfig {
|
||||
constructor(name, data) { this.name = name; }
|
||||
async registerType(category) { registered.push([this.name, category]); }
|
||||
}
|
||||
%s
|
||||
%s
|
||||
let failed = null;
|
||||
try { await load_components(); } catch(e) { failed = String(e); }
|
||||
console.log(JSON.stringify({groupNodes: app.graph.extra?.groupNodes ?? {}, registered, failed}));
|
||||
""" % (
|
||||
json.dumps(status), json.dumps(body),
|
||||
slice_braced(source, "function storeGroupNode(name, data, register=true)"),
|
||||
JS.lift_declaration("components-manager.js", "export async function load_components()"),
|
||||
)
|
||||
return run_node(script)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status, body", [
|
||||
(403, '{"error": "comfyui_outdated"}'), (403, '{"error": "security_level"}'), (403, ""),
|
||||
(400, ""), (404, "404: Not Found"), (500, "<html><body>500 Internal Server Error</body></html>"),
|
||||
(502, "<html><body><h1>502 Bad Gateway</h1></body></html>"), (403, json.dumps({"a component": COMPONENT})),
|
||||
], ids=["an outdated ComfyUI", "a security level", "403 without a body", "400 without a body", "404", "500 with a page",
|
||||
"502 from a proxy", "403 with a list"])
|
||||
def test_an_answer_that_is_not_a_success_has_no_components(status, body):
|
||||
assert load(status, body) == {"groupNodes": {}, "registered": [], "failed": None}
|
||||
|
||||
|
||||
def test_a_success_without_components_adds_nothing():
|
||||
assert load(200, "{}") == {"groupNodes": {}, "registered": [], "failed": None}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("names", [["a component"], ["a component", "error", "another"]], ids=["one", "three, one named error"])
|
||||
def test_the_components_of_a_success_are_registered_as_before(names):
|
||||
loaded = load(200, json.dumps({name: COMPONENT for name in names}))
|
||||
|
||||
assert loaded["failed"] is None
|
||||
assert list(loaded["groupNodes"]) == names
|
||||
assert loaded["registered"] == [[name, "a pack"] for name in names]
|
||||
@@ -0,0 +1,148 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
VALUES = {
|
||||
"security_level": ["normal", "strong", "normal-", "weak"],
|
||||
"network_mode": ["public", "private", "offline"],
|
||||
"db_mode": ["cache", "local", "remote"],
|
||||
"update_policy": ["stable-comfyui", "nightly-comfyui"],
|
||||
"component_policy": ["workflow", "higher", "mine"],
|
||||
}
|
||||
NON_DEFAULT = {key: values[1] for key, values in VALUES.items()}
|
||||
|
||||
CHILD = textwrap.dedent(
|
||||
"""
|
||||
import sys, types, tempfile, os, json, io, contextlib, logging
|
||||
tmp = tempfile.mkdtemp(prefix="cm_config_values_")
|
||||
stub = types.ModuleType("folder_paths")
|
||||
stub.get_user_directory = lambda: tmp
|
||||
stub.get_system_user_directory = lambda *a, **k: os.path.join(tmp, "sysuser")
|
||||
sys.modules["folder_paths"] = stub
|
||||
written, changes, glob_dir = json.loads(sys.argv[1])
|
||||
sys.path.insert(0, glob_dir)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
import manager_core
|
||||
path = os.path.join(tmp, "config.ini")
|
||||
manager_core.manager_config_path = path
|
||||
manager_core.cached_config = None
|
||||
if written is not None:
|
||||
with open(path, "wb") as f:
|
||||
f.write(written.encode("latin-1"))
|
||||
warnings = []
|
||||
handler = logging.Handler(logging.WARNING)
|
||||
handler.emit = lambda record: warnings.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
settings = dict(manager_core.get_config())
|
||||
for key, value in changes:
|
||||
manager_core.get_config()[key] = value
|
||||
if changes:
|
||||
manager_core.write_config()
|
||||
after = open(path, "rb").read().decode("latin-1") if os.path.exists(path) else None
|
||||
print(json.dumps({"settings": settings, "warnings": warnings, "file": after}))
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def read(written, changes=()):
|
||||
done = subprocess.run([sys.executable, "-c", CHILD, json.dumps([written, list(changes), str(GLOB_DIR)])],
|
||||
capture_output=True, text=True, timeout=180)
|
||||
assert done.returncode == 0, done.stderr[-2000:]
|
||||
result = json.loads(done.stdout.strip().splitlines()[-1])
|
||||
return result["settings"], "\n".join(result["warnings"]), result["file"]
|
||||
|
||||
|
||||
def section(settings):
|
||||
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["100%", "%(downgrade_blacklist)s", "%", "bogus", "weak,normal", "<b>weak</b>", "nor mal",
|
||||
"[/x]", "[bold]weak", "cache[/]"])
|
||||
@pytest.mark.parametrize("key", sorted(VALUES))
|
||||
def test_a_value_that_a_setting_cannot_have_gives_its_default_and_changes_no_other_setting(key, value):
|
||||
text = section({**NON_DEFAULT, key: value, "downgrade_blacklist": "kornia"})
|
||||
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == {**NON_DEFAULT, key: VALUES[key][0]}
|
||||
assert settings["downgrade_blacklist"] == "kornia"
|
||||
assert f"{key} = {value!r} in config.ini is not valid; '{VALUES[key][0]}' is used." in printed
|
||||
assert file == text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", sorted(VALUES))
|
||||
def test_a_value_that_a_setting_cannot_have_stays_in_config_ini_when_another_setting_is_saved(key):
|
||||
text = section({**NON_DEFAULT, key: "bogus"})
|
||||
|
||||
_, _, file = read(text, changes=[("share_option", "none")])
|
||||
|
||||
assert f"{key} = bogus\n" in file
|
||||
assert "share_option = none\n" in file
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, value", [(key, value) for key, values in sorted(VALUES.items()) for value in values])
|
||||
@pytest.mark.parametrize("written", [str.lower, str.upper], ids=["lower case", "upper case"])
|
||||
def test_a_value_that_a_setting_can_have_is_read_and_nothing_is_said(key, value, written):
|
||||
settings, printed, _ = read(section({key: written(value)}))
|
||||
|
||||
assert settings[key] == value
|
||||
assert printed == ""
|
||||
|
||||
|
||||
def test_a_config_ini_without_these_settings_has_their_defaults_and_nothing_is_said():
|
||||
settings, printed, _ = read(section({"file_logging": "True"}))
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
|
||||
assert printed == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, value", [
|
||||
("downgrade_blacklist", "100%"), ("downgrade_blacklist", "%(security_level)s"), ("git_exe", "/opt/100%/git"),
|
||||
("channel_url", "https://example.invalid/some%20one/channel"), ("channel_url", "%"), ("git_exe", "/opt/100%%/git"),
|
||||
], ids=["a percent sign", "the form of a reference", "a path", "a percent-encoded url", "only a percent sign",
|
||||
"two percent signs"])
|
||||
def test_a_percent_sign_is_plain_text_and_the_other_settings_are_read(key, value):
|
||||
text = section({**NON_DEFAULT, key: value})
|
||||
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert settings[key] == value
|
||||
assert {name: settings[name] for name in VALUES} == NON_DEFAULT
|
||||
assert printed == ""
|
||||
assert file == text
|
||||
|
||||
|
||||
def test_a_setting_is_written_beside_a_value_with_a_percent_sign_and_one_with_it_is_written():
|
||||
text = section({"security_level": "strong", "downgrade_blacklist": "100%"})
|
||||
|
||||
_, _, file = read(text, changes=[("db_mode", "local"), ("channel_url", "https://example.invalid/some%20one/channel")])
|
||||
|
||||
assert "security_level = strong\n" in file and "downgrade_blacklist = 100%\n" in file
|
||||
assert "db_mode = local\n" in file and "channel_url = https://example.invalid/some%20one/channel\n" in file
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["security_level = strong\n", "\ufeff[default]\nsecurity_level = strong\n".encode("utf-8").decode("latin-1"),
|
||||
"[default\nsecurity_level = strong\n", "[other]\nsecurity_level = strong\n", "",
|
||||
"[default]\nsecurity_level = strong\nnot a setting [/x]\n"],
|
||||
ids=["no section", "a byte order mark", "an unclosed section", "no default section", "empty",
|
||||
"a line that is not a setting"])
|
||||
def test_a_config_ini_that_cannot_be_read_gives_the_defaults_and_says_so(text):
|
||||
settings, printed, file = read(text)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
|
||||
assert "could not be read" in printed and "the default settings are used" in printed
|
||||
assert file == text
|
||||
|
||||
|
||||
def test_without_a_config_ini_the_defaults_are_used_and_nothing_is_said():
|
||||
settings, printed, file = read(None)
|
||||
|
||||
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
|
||||
assert printed == ""
|
||||
assert file is None
|
||||
@@ -0,0 +1,46 @@
|
||||
"""`print` of `manager_core` writes its text as it is.
|
||||
|
||||
The cases take what binds the name `print` out of `glob/manager_core.py`, an
|
||||
import or a function, and call it.
|
||||
"""
|
||||
import ast
|
||||
import io
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
|
||||
def core_print():
|
||||
source = (GLOB_DIR / "manager_core.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, (ast.Import, ast.ImportFrom)) and "rich" in ast.unparse(node)
|
||||
or isinstance(node, ast.FunctionDef) and node.name == "print"]
|
||||
namespace = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<manager_core print>", "exec"), namespace)
|
||||
return namespace["print"]
|
||||
|
||||
|
||||
def printed(*objects, **options):
|
||||
out = io.StringIO()
|
||||
core_print()(*objects, file=out, **options)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"Install(git-clone) error: https://example.com/a[/b] / failed",
|
||||
"## ComfyUI-Manager: EXECUTE => ['python', '-m', 'pip', 'install', 'diffusers[torch]']",
|
||||
"skip black listed pip installation: 'requests[socks]'",
|
||||
"Uninstall: custom_nodes/pack:100:backup",
|
||||
"Download: git clone 'https://github.com/" + "a" * 120 + "'",
|
||||
], ids=["closing tag", "list with an extra", "extra", "emoji code", "longer than 80 columns"])
|
||||
def test_text_is_written_as_it_is(text):
|
||||
assert printed(text) == text + "\n"
|
||||
|
||||
|
||||
def test_objects_are_written_as_their_text():
|
||||
assert printed("Update error:", ValueError("no section [/x]"), 3) == "Update error: no section [/x] 3\n"
|
||||
|
||||
|
||||
def test_end_and_sep_are_kept():
|
||||
assert printed("a", "b", sep="-", end="") == "a-b"
|
||||
@@ -1,121 +0,0 @@
|
||||
"""AC verification for wi-001 (B2): Content-Type rejection helper.
|
||||
|
||||
Validates _reject_simple_form_content_type against the 5-item curl matrix
|
||||
from the WI's acceptance criteria using aiohttp test client. The test
|
||||
builds a minimal aiohttp app that mirrors the helper's wiring into a
|
||||
no-body POST handler, so we exercise the real request.content_type
|
||||
parsing path rather than a mock.
|
||||
|
||||
AC matrix:
|
||||
form-url → 400
|
||||
multipart → 400
|
||||
text/plain → 400
|
||||
no-CT → 200
|
||||
application/json → 200
|
||||
"""
|
||||
import asyncio
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
|
||||
# Parse the helper from manager_server.py without importing it, to avoid
|
||||
# pulling in the full ComfyUI/PromptServer stack. Note: we intentionally do
|
||||
# NOT add the `glob/` directory to sys.path — the dir name would shadow
|
||||
# Python's stdlib `glob` module and break pytest collection.
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _load_helper():
|
||||
"""Parse manager_server.py and execute only the helper definition."""
|
||||
import ast
|
||||
|
||||
source = (REPO_ROOT / "glob" / "manager_server.py").read_text()
|
||||
tree = ast.parse(source)
|
||||
wanted = {"_SIMPLE_FORM_CONTENT_TYPES", "_reject_simple_form_content_type"}
|
||||
nodes = []
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.Assign):
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name) and target.id in wanted:
|
||||
nodes.append(node)
|
||||
elif isinstance(node, ast.FunctionDef) and node.name in wanted:
|
||||
nodes.append(node)
|
||||
module = ast.Module(body=nodes, type_ignores=[])
|
||||
ns = {"web": web, "frozenset": frozenset}
|
||||
exec(compile(module, "manager_server_helpers", "exec"), ns)
|
||||
return ns["_reject_simple_form_content_type"]
|
||||
|
||||
|
||||
_reject_simple_form_content_type = _load_helper()
|
||||
|
||||
|
||||
async def _handler(request):
|
||||
resp = _reject_simple_form_content_type(request)
|
||||
if resp is not None:
|
||||
return resp
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
class ContentTypeRejectionTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(cls.loop)
|
||||
app = web.Application()
|
||||
app.router.add_post("/noop", _handler)
|
||||
cls.server = TestServer(app, loop=cls.loop)
|
||||
cls.client = TestClient(cls.server, loop=cls.loop)
|
||||
cls.loop.run_until_complete(cls.client.start_server())
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.loop.run_until_complete(cls.client.close())
|
||||
cls.loop.close()
|
||||
|
||||
def _post(self, headers):
|
||||
async def go():
|
||||
return await self.client.post("/noop", headers=headers, data=b"")
|
||||
|
||||
return self.loop.run_until_complete(go())
|
||||
|
||||
def test_form_urlencoded_rejected(self):
|
||||
r = self._post({"Content-Type": "application/x-www-form-urlencoded"})
|
||||
self.assertEqual(r.status, 400)
|
||||
|
||||
def test_multipart_form_data_rejected(self):
|
||||
# aiohttp requires a boundary for multipart; helper should still reject
|
||||
# based on the primary mimetype.
|
||||
r = self._post({"Content-Type": "multipart/form-data; boundary=xyz"})
|
||||
self.assertEqual(r.status, 400)
|
||||
|
||||
def test_text_plain_rejected(self):
|
||||
r = self._post({"Content-Type": "text/plain"})
|
||||
self.assertEqual(r.status, 400)
|
||||
|
||||
def test_no_content_type_allowed(self):
|
||||
# Explicitly strip Content-Type: aiohttp client may add a default,
|
||||
# so we use a raw request to ensure absence is tested.
|
||||
async def go():
|
||||
import aiohttp
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
self.client.make_url("/noop"),
|
||||
data=None,
|
||||
skip_auto_headers=["Content-Type"],
|
||||
) as resp:
|
||||
return resp.status
|
||||
|
||||
status = self.loop.run_until_complete(go())
|
||||
self.assertEqual(status, 200)
|
||||
|
||||
def test_application_json_allowed(self):
|
||||
r = self._post({"Content-Type": "application/json"})
|
||||
self.assertEqual(r.status, 200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,156 @@
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import load_manager_util
|
||||
from test_install_flags_config import _run_child
|
||||
|
||||
COMFY_ORG = 'https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main'
|
||||
LTDRDATA = 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main'
|
||||
MIRROR = 'https://example.invalid/mirror'
|
||||
FILES = ['custom-node-list.json', 'extension-node-map.json', 'model-list.json', 'github-stats.json']
|
||||
SPELLINGS = [pytest.param(COMFY_ORG, id='Comfy-Org'), pytest.param(LTDRDATA, id='ltdrdata')]
|
||||
CONFIGS = [pytest.param(None, id='no channel_url')] + SPELLINGS
|
||||
CACHED = [pytest.param((), id='DEFAULT_CHANNEL'), pytest.param(('default_cache_as_channel_url = True',), id='channel_url')]
|
||||
|
||||
PRELUDE = '''
|
||||
import ast, asyncio, logging, pathlib, traceback
|
||||
from types import SimpleNamespace
|
||||
from aiohttp import web
|
||||
import cnr_utils
|
||||
import manager_util
|
||||
core = manager_core
|
||||
user = pathlib.Path(tmp)
|
||||
nodes = user / 'custom_nodes'
|
||||
nodes.mkdir()
|
||||
sys.modules['folder_paths'].get_folder_paths = lambda name: [str(nodes)]
|
||||
core.manager_channel_list_path = str(user / 'channels.list')
|
||||
manager_util.cache_dir = str(user / 'cache')
|
||||
manager_util.comfyui_manager_path = str(user / 'manager')
|
||||
os.makedirs(manager_util.cache_dir)
|
||||
os.makedirs(manager_util.comfyui_manager_path)
|
||||
BAR_URL = 'https://github.com/example/ComfyUI-Bar'
|
||||
SERVED = {
|
||||
'custom-node-list.json': {'custom_nodes': [{'author': 'example', 'title': 'ComfyUI-Bar', 'reference': BAR_URL, 'files': [BAR_URL],
|
||||
'install_type': 'git-clone', 'description': ''}]},
|
||||
'extension-node-map.json': {BAR_URL: [['BarNode'], {'title_aux': 'ComfyUI-Bar'}]},
|
||||
'model-list.json': {'models': [{'name': 'served by the channel'}]},
|
||||
'github-stats.json': {BAR_URL: {'stars': 7, 'last_update': '2026-11-01 00:00:00', 'author_account_age_days': 900}},
|
||||
}
|
||||
BUNDLED = {'custom-node-list.json': {'custom_nodes': []}, 'extension-node-map.json': {}, 'model-list.json': {'models': []},
|
||||
'github-stats.json': {}, 'extras.json': {'favorites': []}}
|
||||
for name, data in BUNDLED.items():
|
||||
(pathlib.Path(manager_util.comfyui_manager_path) / name).write_text(json.dumps(data))
|
||||
REGISTRY = [{'id': 'comfyui-foo', 'name': 'Foo', 'repository': 'https://github.com/example/ComfyUI-Foo',
|
||||
'publisher': {'name': 'example'}, 'description': '', 'latest_version': {'version': '1.0.1'}}]
|
||||
requests = []
|
||||
get_data = manager_util.get_data
|
||||
|
||||
async def from_the_channel(uri, silent=False):
|
||||
if uri.startswith('https://'):
|
||||
requests.append(uri)
|
||||
return json.loads(json.dumps(SERVED[os.path.basename(uri)]))
|
||||
return await get_data(uri, silent)
|
||||
|
||||
async def get_cnr_data(*args, **kwargs):
|
||||
return REGISTRY
|
||||
|
||||
manager_util.get_data = from_the_channel
|
||||
cnr_utils.get_cnr_data = get_cnr_data
|
||||
core.unified_manager = core.UnifiedManager()
|
||||
SERVER = pathlib.Path(core.__file__).with_name('manager_server.py')
|
||||
route = lambda path: lambda handler: handler
|
||||
|
||||
def server(*names):
|
||||
functions = [node for node in ast.parse(SERVER.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
|
||||
scope = {'core': core, 'manager_util': manager_util, 'os': os, 'logging': logging, 'traceback': traceback, 'asyncio': asyncio,
|
||||
'web': web, 'routes': SimpleNamespace(get=route, post=route), 'populate_markdown': lambda node_pack: None}
|
||||
exec(compile(ast.Module(functions, []), str(SERVER), 'exec'), scope)
|
||||
return scope
|
||||
|
||||
def configure(channel_url, default_url, *lines):
|
||||
config = ['[default]'] + ([f'channel_url = {channel_url}'] if channel_url else []) + list(lines)
|
||||
pathlib.Path(CONFIG_PATH).write_text('\\n'.join(config) + '\\n')
|
||||
(user / 'channels.list').write_text(f'default::{default_url}\\nrecent::{default_url}/node_db/new\\nmirror::https://example.invalid/mirror\\n')
|
||||
|
||||
def start():
|
||||
try:
|
||||
asyncio.run(server('default_cache_update')['default_cache_update']())
|
||||
except Exception as e:
|
||||
return repr(e)
|
||||
|
||||
def answer(name, **query):
|
||||
response = asyncio.run(server(name)[name](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
|
||||
return json.loads(response.text)
|
||||
|
||||
def emit(value):
|
||||
print()
|
||||
print(json.dumps(value))
|
||||
'''
|
||||
|
||||
|
||||
def run(body):
|
||||
return _run_child(PRELUDE + body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cached', CACHED)
|
||||
@pytest.mark.parametrize('default_url', SPELLINGS)
|
||||
@pytest.mark.parametrize('channel_url', CONFIGS)
|
||||
def test_start_writes_the_lists_every_reader_reads(channel_url, default_url, cached):
|
||||
data = run(f'''
|
||||
configure({channel_url!r}, {default_url!r}, *{cached!r})
|
||||
failed = start()
|
||||
started = len(os.listdir(manager_util.cache_dir))
|
||||
requests.clear()
|
||||
unread = [[channel, filename] for channel in (None, 'default', {COMFY_ORG!r}, {LTDRDATA!r}) for filename in SERVED
|
||||
if asyncio.run(core.get_data_by_mode('cache', filename, channel)) != SERVED[filename]]
|
||||
level = asyncio.run(server('get_risky_level')['get_risky_level']([BAR_URL], []))
|
||||
emit({{'failed': failed, 'cache': [started, len(os.listdir(manager_util.cache_dir))], 'unread': unread,
|
||||
'fetched': requests, 'level': level}})
|
||||
''')
|
||||
|
||||
assert data == {'failed': None, 'cache': [len(FILES), len(FILES)], 'unread': [], 'fetched': [], 'level': 'middle'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('default_url', SPELLINGS)
|
||||
@pytest.mark.parametrize('channel_url', CONFIGS)
|
||||
def test_custom_nodes_manager_lists_the_registry_nodepacks_on_the_default_channel(channel_url, default_url):
|
||||
data = run(f'''
|
||||
configure({channel_url!r}, {default_url!r})
|
||||
start()
|
||||
listed = answer('fetch_customnode_list', mode='cache')
|
||||
emit({{'channel': listed['channel'], 'node_packs': {{key: row['reference'] for key, row in listed['node_packs'].items()}}}})
|
||||
''')
|
||||
|
||||
assert data == {'channel': 'default', 'node_packs': {
|
||||
'ComfyUI-Bar': 'https://github.com/example/ComfyUI-Bar', 'comfyui-foo': 'https://registry.comfy.org/nodes/comfyui-foo'}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('default_url', SPELLINGS)
|
||||
@pytest.mark.parametrize('channel_url', CONFIGS)
|
||||
def test_channel_menu_selects_the_default_channel(channel_url, default_url):
|
||||
data = run(f'''
|
||||
configure({channel_url!r}, {default_url!r})
|
||||
emit(answer('get_channel_url_list')['selected'])
|
||||
''')
|
||||
|
||||
assert data == 'default'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('default_url', SPELLINGS)
|
||||
def test_another_channel_keeps_its_own_lists(default_url):
|
||||
data = run(f'''
|
||||
configure({MIRROR!r}, {default_url!r}, 'default_cache_as_channel_url = True')
|
||||
failed = start()
|
||||
cache = sorted(os.listdir(manager_util.cache_dir))
|
||||
listed = answer('fetch_customnode_list', mode='cache')
|
||||
requests.clear()
|
||||
emit({{'failed': failed, 'cache': cache,
|
||||
'read': {{filename: asyncio.run(core.get_data_by_mode('cache', filename)) == SERVED[filename] for filename in SERVED}},
|
||||
'fetched': requests, 'selected': answer('get_channel_url_list')['selected'],
|
||||
'listed': [listed['channel'], list(listed['node_packs'])]}})
|
||||
''')
|
||||
|
||||
simple_hash = load_manager_util().simple_hash
|
||||
assert data == {'failed': None, 'cache': sorted(f'{simple_hash(f"{MIRROR}/{filename}")}_{filename}' for filename in FILES),
|
||||
'read': dict.fromkeys(FILES, True), 'fetched': [], 'selected': 'mirror', 'listed': ['mirror', ['ComfyUI-Bar']]}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import pytest
|
||||
|
||||
from test_install_flags_config import _run_child
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def fixes():
|
||||
return _run_child("""
|
||||
import pathlib
|
||||
from types import SimpleNamespace
|
||||
import cm_global, manager_util
|
||||
|
||||
manager_util.make_pip_cmd = lambda cmd: ['python', '-m', 'pip', *cmd]
|
||||
manager_util.get_installed_packages = lambda renew=False: {}
|
||||
manager_util.PIPFixer = lambda *args: SimpleNamespace(fix_broken=lambda: None)
|
||||
cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist, cm_global.pip_overrides = set(), [], {}
|
||||
manager_core.manager_startup_script_path = tmp
|
||||
manager = manager_core.unified_manager
|
||||
pack = pathlib.Path(tmp) / 'pack'
|
||||
pack.mkdir()
|
||||
(pack / 'requirements.txt').write_text('first\\nsecond\\n', encoding='utf-8')
|
||||
(pack / 'install.py').write_text('', encoding='utf-8')
|
||||
manager.unknown_active_nodes = {'pack': ('https://example.invalid/pack', str(pack))}
|
||||
|
||||
def fix(fails=(), node='pack', system='Linux', always_lazy_install=False):
|
||||
manager_core.manager_funcs.run_script = lambda cmd, cwd='.': int(cmd[-1] in fails)
|
||||
manager_core.platform.system = lambda: system
|
||||
manager_core.get_config()['always_lazy_install'] = always_lazy_install
|
||||
manager.processed_install = set()
|
||||
result = manager.unified_fix(node, 'unknown')
|
||||
return [result.result, result.msg]
|
||||
|
||||
print(json.dumps({
|
||||
'every command runs': fix(),
|
||||
'a requirement cannot be installed': fix(fails=['second']),
|
||||
'install.py fails': fix(fails=['install.py']),
|
||||
'reserved by always_lazy_install': fix(fails=['second'], always_lazy_install=True),
|
||||
'reserved on Windows': fix(fails=['second'], system='Windows'),
|
||||
'no such nodepack': fix(node='missing'),
|
||||
}))
|
||||
""")
|
||||
|
||||
|
||||
def test_fix_whose_commands_all_run_succeeds(fixes):
|
||||
assert fixes['every command runs'] == [True, None]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['a requirement cannot be installed', 'install.py fails'])
|
||||
def test_fix_fails_when_a_command_of_its_install_script_fails(fixes, case):
|
||||
assert fixes[case] == [False, 'Failed to execute install script: pack@unknown']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['reserved by always_lazy_install', 'reserved on Windows'])
|
||||
def test_fix_that_is_reserved_succeeds_before_its_commands_run(fixes, case):
|
||||
assert fixes[case] == [True, None]
|
||||
|
||||
|
||||
def test_fix_of_a_nodepack_that_is_not_there_fails(fixes):
|
||||
assert fixes['no such nodepack'] == [False, 'not found: missing@unknown']
|
||||
@@ -251,15 +251,20 @@ print(json.dumps({'ok': result.result, 'old_path': installed.exists(),
|
||||
'queries': 0, 'downloads': 0, 'scripts': 0}
|
||||
|
||||
|
||||
def test_failed_uninstall_stops_reinstall():
|
||||
def test_reinstall_stops_when_the_installed_folder_cannot_be_moved_aside():
|
||||
data = run('''
|
||||
status = 'NodeVersionStatusActive'
|
||||
manager.unified_uninstall = Mock(return_value=core.ManagedResult('uninstall').fail('cannot remove'))
|
||||
installed = nodes / 'fixture'
|
||||
installed.mkdir()
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(installed))
|
||||
rename = os.rename
|
||||
os.rename = Mock(side_effect=PermissionError('cannot move'))
|
||||
result = asyncio.run(manager.reinstall_by_id('fixture', '2.0.0'))
|
||||
print(json.dumps({'ok': result.result, 'message': result.msg, 'queries': get.call_count,
|
||||
'downloads': core.manager_downloader.download_url.call_count}))
|
||||
os.rename = rename
|
||||
print(json.dumps({'ok': result.result, 'moved': 'cannot move' in result.msg, 'kept': installed.is_dir(),
|
||||
'queries': get.call_count, 'downloads': core.manager_downloader.download_url.call_count}))
|
||||
''')
|
||||
assert data == {'ok': False, 'message': 'cannot remove', 'queries': 1, 'downloads': 0}
|
||||
assert data == {'ok': False, 'moved': True, 'kept': True, 'queries': 1, 'downloads': 0}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('version', ['nightly', 'unknown'])
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from test_snapshot_restore_pins import run
|
||||
|
||||
REPOSITORY = '''
|
||||
def repository(path):
|
||||
path.mkdir(parents=True)
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
(path / '__init__.py').write_text('VERSION = %d' % version)
|
||||
for args in (['init', '-q'], ['add', '.'],
|
||||
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
|
||||
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
|
||||
commits.append(head(path))
|
||||
return commits
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
'''
|
||||
|
||||
|
||||
def lines(body):
|
||||
return run(REPOSITORY + body + '\nprint(json.dumps(result))\n')
|
||||
|
||||
|
||||
def test_ref_that_head_names_is_read():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
head_file = nodes / 'fixture/.git/HEAD'
|
||||
branch = head_file.read_text().strip()[5:]
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
|
||||
head_file.write_text('ref:' + branch + '\\n')
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
|
||||
head_file.write_text('ref: \\n')
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
''') == [True, True, 'unknown']
|
||||
|
||||
|
||||
def test_commit_of_a_pack_whose_refs_are_packed_is_read():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
with open(nodes / 'fixture/.git/packed-refs', 'a') as packed:
|
||||
packed.write('\\n')
|
||||
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
|
||||
result = [(nodes / 'fixture/.git' / branch).exists(), git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
|
||||
''') == [False, True]
|
||||
|
||||
|
||||
def test_ref_whose_place_is_a_folder_is_not_read_as_a_file():
|
||||
"""git takes a folder there for no ref: after `git pack-refs`, and after `git checkout --orphan feature` beside a branch `feature/x`."""
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
|
||||
(nodes / 'fixture/.git' / branch).mkdir(parents=True)
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
|
||||
subprocess.run(['git', 'branch', 'feature/x'], cwd=nodes / 'fixture', check=True)
|
||||
subprocess.run(['git', 'checkout', '-q', '--orphan', 'feature'], cwd=nodes / 'fixture', check=True)
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
''') == [True, 'unknown']
|
||||
|
||||
|
||||
def test_commit_that_is_not_ascii_is_read_without_an_error():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
repository(nodes / 'fixture')
|
||||
git_dir = nodes / 'fixture/.git'
|
||||
branch = (git_dir / 'HEAD').read_text().strip()[5:]
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
(git_dir / 'packed-refs').write_bytes(b'0123\\xff ' + branch.encode() + b'\\n')
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
|
||||
(git_dir / branch).write_bytes(b'0123\\xff\\n')
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
(git_dir / 'HEAD').write_bytes(b'0123\\xff\\n')
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
''') == ['0123\ufffd'] * 3
|
||||
|
||||
|
||||
def test_head_that_cannot_be_opened_has_no_commit():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
(nodes / 'fixture/.git/HEAD').mkdir(parents=True)
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
|
||||
''') == ['unknown']
|
||||
|
||||
|
||||
def test_files_that_may_not_be_read_have_no_commit(tmp_path):
|
||||
(tmp_path / 'probe').touch()
|
||||
(tmp_path / 'probe').chmod(0)
|
||||
try:
|
||||
open(tmp_path / 'probe').close()
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
pytest.skip('a file can be read here whatever its mode, as by root or on Windows')
|
||||
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
git_dir = nodes / 'fixture/.git'
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
branch = (git_dir / 'HEAD').read_text().strip()[5:]
|
||||
result = []
|
||||
(git_dir / 'packed-refs').chmod(0)
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
(git_dir / branch).write_text(commits[1])
|
||||
(git_dir / branch).chmod(0)
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
(git_dir / 'HEAD').chmod(0)
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
|
||||
''') == ['unknown', 'unknown', 'unknown']
|
||||
|
||||
|
||||
def test_commit_is_read_beside_refs_that_are_not_utf8():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
packed = nodes / 'fixture/.git/packed-refs'
|
||||
packed.write_bytes(b'0123456789abcdef0123456789abcdef01234567 refs/heads/\\xff\\xfe\\n' + packed.read_bytes())
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
|
||||
''') == [True]
|
||||
|
||||
|
||||
def test_head_that_is_not_utf8_is_read(tmp_path):
|
||||
try:
|
||||
open(os.fsencode(tmp_path) + b'/\xff\xfe', 'wb').close()
|
||||
except (OSError, ValueError):
|
||||
pytest.skip('this file system has no file of such a name, as that of Windows')
|
||||
|
||||
assert lines('''
|
||||
import git_utils
|
||||
heads = nodes / 'fixture/.git/refs/heads'
|
||||
heads.mkdir(parents=True)
|
||||
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/\\xff\\xfe\\n')
|
||||
with open(os.fsencode(heads) + b'/\\xff\\xfe', 'wb') as ref:
|
||||
ref.write(b'0123456789abcdef0123456789abcdef01234567\\n')
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
|
||||
''') == ['0123456789abcdef0123456789abcdef01234567']
|
||||
|
||||
|
||||
# what MinGit 2.56 named the file of a branch that was cloned on Windows
|
||||
NAMES_OF_GIT_FOR_WINDOWS = [
|
||||
(b'rel-\xfe', 'rel-\u00fe'),
|
||||
(b'caf\xe9', 'caf\u00e9'),
|
||||
(b'rel-\x81', 'rel-81'),
|
||||
('\ud55c\uae00'.encode(), '\ud55c\uae00'),
|
||||
('\ud55c'.encode() + b'\xfe\xe9\xc3', '\ud55c\u00fe\u00e9\u00c3'),
|
||||
('a\U0001f600'.encode(), 'a\U0001f600'),
|
||||
(b'\xe0\x80\x80', '\u00e08080'),
|
||||
# a surrogate in UTF-8, which `xutftowcsn` of compat/mingw.c of git takes as one
|
||||
(b'\xed\xa0\x80', '\ud800'),
|
||||
]
|
||||
|
||||
|
||||
def test_file_of_a_ref_is_named_as_git_for_windows_names_it():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
result = [git_utils.file_name_of_git_for_windows(name) for name in %r]
|
||||
''' % [name for name, _ in NAMES_OF_GIT_FOR_WINDOWS]) == [file_name for _, file_name in NAMES_OF_GIT_FOR_WINDOWS]
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='the names that Git for Windows gives its files')
|
||||
def test_ref_that_git_for_windows_made_is_read():
|
||||
"""A name that is not UTF-8 is no name of a file there, and Git for Windows writes the file under another."""
|
||||
assert lines('''
|
||||
import git_utils
|
||||
heads = nodes / 'fixture/.git/refs/heads'
|
||||
heads.mkdir(parents=True)
|
||||
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/rel-\\xfe\\n')
|
||||
(heads / 'rel-\\u00fe').write_text('0123456789abcdef0123456789abcdef01234567\\n')
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
|
||||
''') == ['0123456789abcdef0123456789abcdef01234567']
|
||||
|
||||
|
||||
def test_packed_ref_is_matched_by_its_bytes():
|
||||
assert lines('''
|
||||
import git_utils
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
|
||||
git_dir = nodes / 'fixture/.git'
|
||||
other = b'0123456789abcdef0123456789abcdef01234567 refs/heads/release-\\xff\\n'
|
||||
(git_dir / 'packed-refs').write_bytes(other + (git_dir / 'packed-refs').read_bytes())
|
||||
(git_dir / 'HEAD').write_bytes(b'ref: refs/heads/release-\\xfe\\n')
|
||||
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
|
||||
(git_dir / 'packed-refs').write_bytes(other + commits[1].encode() + b' refs/heads/release-\\xfe\\n')
|
||||
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
|
||||
''') == ['unknown', True]
|
||||
|
||||
|
||||
SUBMODULE = '''
|
||||
os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='protocol.file.allow', GIT_CONFIG_VALUE_0='always')
|
||||
def git(path, *args):
|
||||
subprocess.run(['git', '-c', 'protocol.file.allow=always', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
|
||||
cwd=path, check=True, capture_output=True)
|
||||
library = repository(pathlib.Path(tmp) / 'library')
|
||||
origin = pathlib.Path(tmp) / 'origin'
|
||||
origin.mkdir()
|
||||
git(origin, 'init', '-q')
|
||||
git(origin, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
|
||||
pinned_commits = []
|
||||
for commit in library:
|
||||
git(origin / 'library', 'checkout', '-q', commit)
|
||||
git(origin, 'commit', '-q', '-a', '-m', 'library at ' + commit)
|
||||
pinned_commits.append(head(origin))
|
||||
'''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('clone', [['--recursive'], []], ids=['with its submodules', 'without its submodules'])
|
||||
def test_checkout_brings_the_submodules_to_the_commit(clone):
|
||||
assert lines(SUBMODULE + '''
|
||||
git(nodes, 'clone', '-q', *%r, str(origin), 'fixture')
|
||||
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[0]), head(nodes / 'fixture') == pinned_commits[0],
|
||||
head(nodes / 'fixture/library') == library[0]]
|
||||
''' % clone) == [True, True, True]
|
||||
|
||||
|
||||
def test_submodules_are_brought_to_the_commit_of_a_pack_that_is_at_it_already():
|
||||
assert lines(SUBMODULE + '''
|
||||
git(nodes, 'clone', '-q', '--recursive', str(origin), 'fixture')
|
||||
git(nodes / 'fixture/library', 'checkout', '-q', library[0])
|
||||
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), head(nodes / 'fixture/library') == library[1]]
|
||||
''') == [False, True]
|
||||
|
||||
|
||||
def test_submodule_that_was_never_fetched_is_left_alone_in_a_pack_cloned_without_its_submodules():
|
||||
"""As git does without `--init`: no submodule of such a clone is active."""
|
||||
assert lines(SUBMODULE + '''
|
||||
git(nodes, 'clone', '-q', str(origin), 'fixture')
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
|
||||
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), list((nodes / 'fixture/library').iterdir())]
|
||||
''') == [False, []]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reachable', [True, False], ids=['reachable', 'away'])
|
||||
def test_submodule_that_was_never_fetched_is_fetched_in_a_pack_cloned_as_the_manager_clones(reachable):
|
||||
"""`clone --recursive` makes every submodule active, also one of a later commit: git updates it without `--init`."""
|
||||
result = lines(SUBMODULE + '''
|
||||
import io, logging
|
||||
log = io.StringIO()
|
||||
logging.getLogger().addHandler(logging.StreamHandler(log))
|
||||
plain = pathlib.Path(tmp) / 'plain'
|
||||
plain.mkdir()
|
||||
git(plain, 'init', '-q')
|
||||
git(plain, 'commit', '-q', '--allow-empty', '-m', 'no submodule')
|
||||
git(nodes, 'clone', '-q', '--recursive', str(plain), 'fixture')
|
||||
git(plain, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
|
||||
git(plain, 'commit', '-q', '-m', 'a submodule')
|
||||
git(nodes / 'fixture', 'pull', '-q')
|
||||
if not %r:
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
|
||||
result = [core.repo_switch_commit(str(nodes / 'fixture'), head(plain)), (nodes / 'fixture/library/__init__.py').exists(),
|
||||
"'" + str(nodes / 'fixture') + "'" in log.getvalue(), 'library' in log.getvalue()]
|
||||
''' % reachable)
|
||||
|
||||
assert result == ([False, True, False, False] if reachable else [None, False, True, True])
|
||||
|
||||
|
||||
def test_git_is_not_run_for_the_submodules_of_a_pack_that_has_none():
|
||||
assert lines('''
|
||||
import git
|
||||
commits = repository(nodes / 'fixture')
|
||||
ran = []
|
||||
execute = git.Git.execute
|
||||
def recorded(self, command, *args, **kwargs):
|
||||
ran.append(list(command))
|
||||
return execute(self, command, *args, **kwargs)
|
||||
git.Git.execute = recorded
|
||||
result = [core.repo_switch_commit(str(nodes / 'fixture'), commits[1]), [command for command in ran if 'submodule' in command]]
|
||||
''') == [False, []]
|
||||
@@ -0,0 +1,145 @@
|
||||
import configparser
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
from test_git_exe_setting import take
|
||||
|
||||
URL = "https://github.com/someone/some%20pack"
|
||||
PLAIN = '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
PERCENT = f'[core]\n\tbare = false\n[remote "origin"]\n\turl = {URL}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
|
||||
NO_VALUE = '[core]\n\tbare\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
NO_VALUE_THEN_DEEPER = '[core]\n\tbare\n\t\tfilemode = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
NO_REMOTE = '[core]\n\tbare = false\n'
|
||||
BOM = "\ufeff" + PLAIN
|
||||
NOT_A_CONFIG = "ref: refs/heads/master\n" + PLAIN
|
||||
NOT_ASCII = PLAIN + '[user]\n\tname = 홍길동\n'
|
||||
NOT_UTF8 = PLAIN.encode() + b'[user]\n\tname = \xff\xfe\n'
|
||||
BRANCH_NOT_UTF8 = PLAIN.encode() + b'[branch "release-\xfe"]\n\tremote = origin\n\tmerge = refs/heads/release-\xfe\n'
|
||||
ORIGIN = '[remote "origin"]\n\turl = https://github.com/someone/pack\n'
|
||||
OTHER = '\t[remote "other"]\n\turl = https://github.com/someone/other\n'
|
||||
VALUE_OVER_TWO_LINES = '[core]\n\tdescription = a \\\n' + OTHER + ORIGIN
|
||||
QUOTED_VALUE_OVER_TWO_LINES = '[core]\n\tdescription = "a # b \\\n' + OTHER.replace('\n', '"\n', 1) + ORIGIN
|
||||
COMMENT_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\t# a comment \\\n' + ORIGIN
|
||||
VALUE_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\tdescription = a\\\\\n' + ORIGIN
|
||||
VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS = '[remote "origin"]\n\turl = https://github.com/someone/pack\\'
|
||||
URL_BEFORE_THE_FIRST_SECTION = "url = https://someone:a-token@github.com/someone/pack\n" + PLAIN
|
||||
|
||||
|
||||
def git_utils():
|
||||
spec = importlib.util.spec_from_file_location("_git_utils", GLOB_DIR / "git_utils.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def git_url():
|
||||
return git_utils().git_url
|
||||
|
||||
|
||||
def resolve():
|
||||
return take(GLOB_DIR / "manager_core.py", "resolve_giturl_from_path", {
|
||||
"os": os, "configparser": configparser, "logging": logging, "git_utils": git_utils(),
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture(params=[git_url, resolve], ids=["git_url", "resolve_giturl_from_path"])
|
||||
def read(request, tmp_path):
|
||||
reader = request.param()
|
||||
|
||||
def read(config, mode=None):
|
||||
(tmp_path / ".git").mkdir(exist_ok=True)
|
||||
(tmp_path / ".git" / "config").write_bytes(config if isinstance(config, bytes) else config.encode())
|
||||
if mode is not None:
|
||||
(tmp_path / ".git" / "config").chmod(mode)
|
||||
return reader(str(tmp_path))
|
||||
|
||||
return read
|
||||
|
||||
|
||||
def test_url_is_read(read):
|
||||
assert read(PLAIN) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_with_a_percent_sign_is_read_as_it_is(read):
|
||||
assert read(PERCENT) == URL
|
||||
|
||||
|
||||
def test_url_is_read_beside_a_key_without_a_value(read):
|
||||
assert read(NO_VALUE) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_without_a_remote_has_no_url(read):
|
||||
assert read(NO_REMOTE) is None
|
||||
|
||||
|
||||
def test_url_without_a_value_is_no_url(read):
|
||||
assert read('[remote "origin"]\n\turl\n') is None
|
||||
|
||||
|
||||
def test_url_is_read_after_a_byte_order_mark(read):
|
||||
assert read(BOM) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_text_that_is_not_ascii(read):
|
||||
assert read(NOT_ASCII) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_bytes_that_are_not_utf8(read):
|
||||
assert read(NOT_UTF8) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_url_is_read_beside_a_branch_that_is_not_utf8(read):
|
||||
assert read(BRANCH_NOT_UTF8) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_has_no_url_and_is_reported(read, caplog, tmp_path):
|
||||
assert read(NOT_A_CONFIG) is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
|
||||
|
||||
def test_key_before_a_deeper_line_is_read(read):
|
||||
"""For git a line that is indented more is a key of its own; the parser would take it as more of the value before it."""
|
||||
assert read(NO_VALUE_THEN_DEEPER) == "https://github.com/someone/pack"
|
||||
assert read('[remote "origin"]\n\turl = https://github.com/someone/pack\n\t\tfetch = +refs/heads/*:refs/remotes/origin/*\n') == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_value_that_goes_on_at_the_next_line_is_one_value(read):
|
||||
"""As for git: what looks like a section in the second line of a value is text of that value."""
|
||||
assert read(VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
|
||||
assert read(QUOTED_VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
|
||||
assert read(VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_line_that_does_not_go_on_is_a_line_of_its_own(read):
|
||||
assert read(COMMENT_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
|
||||
assert read(VALUE_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_is_reported_without_its_text(read, caplog, tmp_path):
|
||||
assert read(URL_BEFORE_THE_FIRST_SECTION) is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
assert "a-token" not in caplog.text
|
||||
|
||||
|
||||
def test_config_that_cannot_be_parsed_is_reported_once(read, caplog, tmp_path):
|
||||
for _ in range(3):
|
||||
assert read(NOT_A_CONFIG) is None
|
||||
|
||||
assert caplog.text.count(f"Cannot read '{tmp_path / '.git' / 'config'}'") == 1
|
||||
|
||||
|
||||
def test_config_that_may_not_be_read_has_no_url_and_is_reported(read, caplog, tmp_path):
|
||||
url = read(PLAIN, mode=0)
|
||||
try:
|
||||
open(tmp_path / ".git" / "config").close()
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
pytest.skip("the file can be read here, as by root or on Windows")
|
||||
|
||||
assert url is None
|
||||
assert str(tmp_path / ".git" / "config") in caplog.text
|
||||
@@ -0,0 +1,276 @@
|
||||
import ast
|
||||
import configparser
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import git
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR, load_manager_util
|
||||
from test_install_flags_config import GIT_LOCATION, _run_child
|
||||
|
||||
pytestmark = pytest.mark.skipif(os.name == "nt", reason="the executables of the cases are shell scripts")
|
||||
|
||||
ROOT = GLOB_DIR.parent
|
||||
NOT_A_GIT = {
|
||||
"a path that does not exist": None,
|
||||
"a program that fails": "#!/bin/sh\nexit 3\n",
|
||||
"a program that is not git": "#!/bin/sh\necho hello\n",
|
||||
"a program that waits": "#!/bin/sh\nexec sleep 30\n",
|
||||
"a program that prints bytes that are not text": "#!/bin/sh\nprintf '\\377\\376'\n",
|
||||
"a file that cannot be run": "not a program\n",
|
||||
}
|
||||
|
||||
|
||||
def take(path, name, namespace):
|
||||
function = [node for node in ast.parse(path.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == name]
|
||||
assert len(function) == 1
|
||||
exec(compile(ast.Module(body=function, type_ignores=[]), str(path), "exec"), namespace)
|
||||
return namespace[name]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager_util(monkeypatch):
|
||||
module = load_manager_util()
|
||||
find = module.find_git_executable
|
||||
monkeypatch.setattr(module, "find_git_executable", lambda git_exe, timeout=2: find(git_exe, timeout=timeout))
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def default_git(monkeypatch):
|
||||
for name in (*GIT_LOCATION, 'GIT_PYTHON_GIT_EXECUTABLE'):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
# GitPython keeps the git that the variable of the shell named when it last looked
|
||||
git.refresh()
|
||||
yield
|
||||
# the variables a case set are removed before GitPython looks for its git again
|
||||
monkeypatch.undo()
|
||||
git.refresh()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def recording_git(tmp_path):
|
||||
calls = tmp_path / "calls"
|
||||
executable = tmp_path / "recording-git"
|
||||
executable.write_text(f'#!/bin/sh\necho "$@" >> "{calls}"\nexec "{shutil.which("git")}" "$@"\n')
|
||||
executable.chmod(0o755)
|
||||
return SimpleNamespace(path=str(executable),
|
||||
calls=lambda: calls.read_text().splitlines() if calls.exists() else [],
|
||||
forget=lambda: calls.unlink(missing_ok=True))
|
||||
|
||||
|
||||
@pytest.fixture(params=NOT_A_GIT)
|
||||
def not_a_git(request, tmp_path):
|
||||
path = tmp_path / "not-a-git"
|
||||
if NOT_A_GIT[request.param] is not None:
|
||||
path.write_text(NOT_A_GIT[request.param])
|
||||
path.chmod(0o755)
|
||||
return str(path)
|
||||
|
||||
|
||||
def setup_git_executable(manager_util, git_exe, protected=True):
|
||||
take(GLOB_DIR / "manager_core.py", "setup_git_executable", {
|
||||
"git": git, "logging": logging, "manager_util": manager_util,
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: protected),
|
||||
"get_config": lambda: {"git_exe": git_exe},
|
||||
})()
|
||||
|
||||
|
||||
def test_configured_git_is_run(manager_util, recording_git, tmp_path):
|
||||
setup_git_executable(manager_util, recording_git.path)
|
||||
recording_git.forget()
|
||||
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
|
||||
assert any(line.startswith("init") for line in recording_git.calls())
|
||||
assert (tmp_path / "repo" / ".git").is_dir()
|
||||
|
||||
|
||||
def test_empty_setting_keeps_the_default_git(manager_util, recording_git, tmp_path, caplog):
|
||||
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
setup_git_executable(manager_util, "")
|
||||
|
||||
assert caplog.text == ""
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
|
||||
|
||||
|
||||
def test_setting_that_is_no_git_is_reported_and_the_default_kept(manager_util, not_a_git, tmp_path, caplog):
|
||||
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
|
||||
flags = git.remote.FetchInfo._flag_map.copy()
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
setup_git_executable(manager_util, not_a_git)
|
||||
|
||||
assert not_a_git in caplog.text
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default and git.remote.FetchInfo._flag_map == flags
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
assert (tmp_path / "repo" / ".git").is_dir()
|
||||
|
||||
|
||||
def test_setting_of_an_unprotected_configuration_is_not_used(manager_util, recording_git, tmp_path, caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
setup_git_executable(manager_util, recording_git.path, protected=False)
|
||||
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
|
||||
assert recording_git.calls() == []
|
||||
assert "git_exe" in caplog.text
|
||||
|
||||
|
||||
def set_git_executable(manager_util, monkeypatch, git_exe, protected=True):
|
||||
# set and removed, so that the variable the function sets is removed after the case, also when there was none
|
||||
monkeypatch.setenv("GIT_PYTHON_GIT_EXECUTABLE", "")
|
||||
monkeypatch.delenv("GIT_PYTHON_GIT_EXECUTABLE")
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read_string("[default]\n" + ("" if git_exe is None else f"git_exe = {git_exe}\n"))
|
||||
take(ROOT / "prestartup_script.py", "set_git_executable", {
|
||||
"os": os, "manager_util": manager_util, "_has_system_user_api": protected, "default_conf": config["default"],
|
||||
})()
|
||||
return os.environ.get("GIT_PYTHON_GIT_EXECUTABLE")
|
||||
|
||||
|
||||
def test_git_is_known_before_gitpython_is_imported(manager_util, monkeypatch, recording_git):
|
||||
assert set_git_executable(manager_util, monkeypatch, recording_git.path) == recording_git.path
|
||||
|
||||
|
||||
def test_gitpython_is_imported_without_a_git_on_path(manager_util, monkeypatch, recording_git, tmp_path):
|
||||
"""GitPython looks for its git when it is imported, and the import fails when it finds none."""
|
||||
set_git_executable(manager_util, monkeypatch, recording_git.path)
|
||||
(tmp_path / "empty").mkdir()
|
||||
recording_git.forget()
|
||||
|
||||
imported = subprocess.run([sys.executable, "-c", "import git, sys; git.Repo.init(sys.argv[1])", str(tmp_path / "repository")],
|
||||
env={**os.environ, "PATH": str(tmp_path / "empty")}, capture_output=True, text=True)
|
||||
|
||||
assert imported.returncode == 0, imported.stderr
|
||||
assert any(call.startswith("init") for call in recording_git.calls())
|
||||
|
||||
|
||||
def test_git_in_a_directory_with_a_percent_sign_is_known(manager_util, monkeypatch, recording_git, tmp_path):
|
||||
"""A path of Windows may hold a `%`, which the parser takes as the start of a reference."""
|
||||
(tmp_path / "100%").mkdir()
|
||||
path = shutil.copy(recording_git.path, tmp_path / "100%" / "git")
|
||||
|
||||
assert set_git_executable(manager_util, monkeypatch, str(path)) == str(path)
|
||||
|
||||
|
||||
def test_start_up_without_a_configuration_file_sets_nothing(manager_util, monkeypatch):
|
||||
monkeypatch.setenv("GIT_PYTHON_GIT_EXECUTABLE", "")
|
||||
monkeypatch.delenv("GIT_PYTHON_GIT_EXECUTABLE")
|
||||
take(ROOT / "prestartup_script.py", "set_git_executable", {
|
||||
"os": os, "manager_util": manager_util, "_has_system_user_api": True, "default_conf": {},
|
||||
})()
|
||||
|
||||
assert os.environ.get("GIT_PYTHON_GIT_EXECUTABLE") is None
|
||||
|
||||
|
||||
def test_setting_with_a_percent_sign_is_read_as_written_and_the_others_kept():
|
||||
config = _run_child(r'''
|
||||
write_ini("[default]\ngit_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe\ndb_mode = local\nnetwork_mode = offline\n")
|
||||
cfg = fresh_read()
|
||||
print(json.dumps([cfg["git_exe"], cfg["db_mode"], cfg["network_mode"]]))
|
||||
''')
|
||||
|
||||
assert config == ["%LOCALAPPDATA%\\Git\\bin\\git.exe", "local", "offline"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("git_exe", ["", None])
|
||||
def test_no_setting_leaves_the_environment_alone(manager_util, monkeypatch, git_exe):
|
||||
assert set_git_executable(manager_util, monkeypatch, git_exe) is None
|
||||
|
||||
|
||||
def test_setting_of_an_unprotected_configuration_is_not_put_in_the_environment(manager_util, monkeypatch, recording_git):
|
||||
assert set_git_executable(manager_util, monkeypatch, recording_git.path, protected=False) is None
|
||||
|
||||
|
||||
def test_setting_that_is_no_git_is_not_put_in_the_environment(manager_util, monkeypatch, not_a_git):
|
||||
assert set_git_executable(manager_util, monkeypatch, not_a_git) is None
|
||||
|
||||
|
||||
def test_git_named_by_a_command_on_path_is_run_by_its_full_path(manager_util, tmp_path, monkeypatch):
|
||||
"""GitPython takes a name without a directory as a file of the current directory."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
|
||||
setup_git_executable(manager_util, "git")
|
||||
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == shutil.which("git")
|
||||
git.Repo.init(tmp_path / "repo")
|
||||
assert (tmp_path / "repo" / ".git").is_dir()
|
||||
|
||||
|
||||
def test_git_named_by_a_command_is_not_taken_from_the_current_directory(manager_util, recording_git, tmp_path, monkeypatch):
|
||||
"""Windows looks for a command in the current directory first. Here it is PATH that names that directory."""
|
||||
default = shutil.which("git")
|
||||
shutil.copy(recording_git.path, tmp_path / "git")
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("PATH", os.pathsep.join([".", os.environ["PATH"]]))
|
||||
|
||||
setup_git_executable(manager_util, "git")
|
||||
|
||||
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
|
||||
assert recording_git.calls() == []
|
||||
|
||||
|
||||
def test_check_does_not_wait_for_a_program_that_the_setting_started(manager_util, tmp_path):
|
||||
"""With a pipe for the answer, the check would wait for every program that holds the pipe: on Windows also after its time is up."""
|
||||
executable = tmp_path / "starts-a-program"
|
||||
executable.write_text(f'#!/bin/sh\nsleep 30 &\necho $! > "{tmp_path}/pid"\n')
|
||||
executable.chmod(0o755)
|
||||
started = time.monotonic()
|
||||
|
||||
try:
|
||||
assert manager_util.find_git_executable(str(executable), timeout=20) is None
|
||||
assert time.monotonic() - started < 10
|
||||
finally:
|
||||
os.kill(int((tmp_path / "pid").read_text()), signal.SIGTERM)
|
||||
|
||||
|
||||
def test_setting_saved_beside_a_git_exe_with_a_percent_sign_keeps_it():
|
||||
saved = _run_child(r'''
|
||||
write_ini("[default]\ngit_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe\ndb_mode = local\n")
|
||||
cfg = fresh_read()
|
||||
cfg["db_mode"] = "remote"
|
||||
manager_core.write_config()
|
||||
print(json.dumps(sorted(line for line in open(CONFIG_PATH).read().splitlines() if line.startswith(("git_exe", "db_mode")))))
|
||||
''')
|
||||
|
||||
assert saved == ["db_mode = remote", "git_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe"]
|
||||
|
||||
|
||||
def test_git_helper_runs_the_git_of_the_process_that_starts_it(recording_git, tmp_path):
|
||||
result = _run_child(f'''
|
||||
import pathlib, subprocess
|
||||
write_ini("[default]\\ngit_exe = {recording_git.path}\\n")
|
||||
fresh_read()
|
||||
manager_core.manager_migration.has_system_user_api = lambda: True
|
||||
manager_core.setup_git_executable()
|
||||
work = pathlib.Path({str(tmp_path)!r})
|
||||
(work / "folder_paths.py").touch()
|
||||
|
||||
def git(where, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=test", "-c", "user.email=test@example.invalid", *args],
|
||||
cwd=where, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
(work / "origin").mkdir()
|
||||
git(work / "origin", "init", "-q")
|
||||
git(work / "origin", "commit", "-q", "--allow-empty", "-m", "first")
|
||||
git(work, "clone", "-q", str(work / "origin"), "pack")
|
||||
git(work / "origin", "commit", "-q", "--allow-empty", "-m", "second")
|
||||
(work / "calls").unlink(missing_ok=True)
|
||||
helper = subprocess.run([sys.executable, manager_core.git_script_path, "--pull", str(work / "pack")], cwd=str(work),
|
||||
env={{**manager_core.get_script_env(), "COMFYUI_PATH": str(work)}}, capture_output=True)
|
||||
print(json.dumps([helper.returncode, git(work / "pack", "rev-parse", "HEAD") == git(work / "origin", "rev-parse", "HEAD")]))
|
||||
''')
|
||||
|
||||
assert result == [0, True]
|
||||
assert any(line.startswith("pull") for line in recording_git.calls())
|
||||
@@ -0,0 +1,201 @@
|
||||
import pytest
|
||||
|
||||
from test_install_flags_config import _run_child
|
||||
|
||||
|
||||
PRELUDE = '''
|
||||
import asyncio, os, pathlib, subprocess, time
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
core = manager_core
|
||||
tmp = pathlib.Path(tmp)
|
||||
os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='protocol.file.allow', GIT_CONFIG_VALUE_0='always')
|
||||
(tmp / 'folder_paths.py').touch()
|
||||
os.environ['COMFYUI_PATH'] = str(tmp)
|
||||
nodes = tmp / 'custom_nodes'
|
||||
nodes.mkdir()
|
||||
core.get_default_custom_nodes_path = lambda: str(nodes)
|
||||
core.get_custom_nodes_paths = lambda: [str(nodes)]
|
||||
core.is_valid_url = lambda url: True
|
||||
manager = core.UnifiedManager()
|
||||
manager.reload = AsyncMock()
|
||||
manager.get_custom_nodes = AsyncMock(return_value={})
|
||||
manager.get_cnr_by_repo = Mock(return_value=None)
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
core.unified_manager = manager
|
||||
core.execute_install_script = Mock(return_value=True)
|
||||
|
||||
def git(path, *args):
|
||||
subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args], cwd=path, check=True, capture_output=True)
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
def failed(call, *args, **options):
|
||||
try:
|
||||
call(*args, **options)
|
||||
except Exception:
|
||||
return True
|
||||
return False
|
||||
|
||||
asset, library, origin, pack = tmp / 'asset', tmp / 'library', tmp / 'origin', tmp / 'pack'
|
||||
for repository in (asset, library, origin):
|
||||
repository.mkdir()
|
||||
git(repository, 'init', '-q')
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
for submodule in (asset, library):
|
||||
(submodule / '__init__.py').write_text('VERSION = %d' % version)
|
||||
git(submodule, 'add', '.')
|
||||
git(submodule, 'commit', '-q', '-m', 'version %d' % version)
|
||||
if version == 1:
|
||||
git(origin, 'submodule', 'add', '-q', str(submodule), submodule.name)
|
||||
else:
|
||||
git(origin / submodule.name, 'pull', '-q')
|
||||
git(origin, 'commit', '-q', '-a', '-m', 'library %d' % version)
|
||||
commits.append(head(origin))
|
||||
if version == 1:
|
||||
git(tmp, 'clone', '-q', '--recursive', str(origin), 'pack')
|
||||
away = tmp / 'library.away'
|
||||
library.rename(away)
|
||||
'''
|
||||
|
||||
PULL_TWICE = '''
|
||||
first = failed(core.git_pull, str(pack))
|
||||
after_first = head(pack) == commits[0]
|
||||
asset_after_first = (pack / 'asset/__init__.py').read_text()
|
||||
away.rename(library)
|
||||
second = failed(core.git_pull, str(pack))
|
||||
print(json.dumps({'first failed': first, 'at its commit': after_first, 'asset at its commit': asset_after_first, 'second failed': second,
|
||||
'updated': head(pack) == commits[1], 'library': (pack / 'library/__init__.py').read_text()}))
|
||||
'''
|
||||
PULLED = {'first failed': True, 'at its commit': True, 'asset at its commit': 'VERSION = 1', 'second failed': False, 'updated': True, 'library': 'VERSION = 2'}
|
||||
|
||||
|
||||
def run(body):
|
||||
return _run_child(PRELUDE + body)
|
||||
|
||||
|
||||
def test_pull_that_fails_at_the_submodules_leaves_the_pack_at_its_commit():
|
||||
assert run(PULL_TWICE) == PULLED
|
||||
|
||||
|
||||
def test_pull_of_the_git_helper_that_fails_is_a_failure():
|
||||
assert run("core.platform.system = lambda: 'Windows'\n" + PULL_TWICE) == PULLED
|
||||
|
||||
|
||||
WHERE = pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
|
||||
|
||||
|
||||
@WHERE
|
||||
def test_a_check_of_a_pack_with_an_update_does_not_ask_for_its_install_script(where):
|
||||
assert run(where + '''
|
||||
away.rename(library)
|
||||
os.environ['GIT_COMMITTER_DATE'] = '@%d +0000' % (time.time() + 86400)
|
||||
git(origin, 'commit', '-q', '--allow-empty', '-m', 'a commit dated a day later')
|
||||
del os.environ['GIT_COMMITTER_DATE']
|
||||
state = core.git_repo_update_check_with(str(pack))
|
||||
print()
|
||||
print(json.dumps({'state': list(state), 'install scripts': core.execute_install_script.call_count, 'updated': head(pack) == head(origin)}))
|
||||
''') == {'state': [True, True], 'install scripts': 0, 'updated': False}
|
||||
|
||||
|
||||
LIBRARY_NOT_CLONED = '''
|
||||
git(pack, 'submodule', 'deinit', '-q', '-f', 'library')
|
||||
# moved, as git makes files read-only that Windows does not remove
|
||||
(pack / '.git/modules/library').rename(tmp / 'library.modules')
|
||||
'''
|
||||
|
||||
|
||||
def test_pull_of_the_git_helper_that_fails_at_the_submodules_puts_them_back():
|
||||
data = run('''
|
||||
away.rename(library)
|
||||
nested = tmp / 'nested'
|
||||
nested.mkdir()
|
||||
git(nested, 'init', '-q')
|
||||
git(nested, 'commit', '-q', '--allow-empty', '-m', 'nested')
|
||||
git(asset, 'submodule', 'add', '-q', str(nested), 'nested')
|
||||
git(asset, 'commit', '-q', '-m', 'a submodule')
|
||||
git(origin / 'asset', 'pull', '-q')
|
||||
git(origin, 'commit', '-q', '-a', '-m', 'asset with a submodule')
|
||||
nested.rename(tmp / 'nested.away')
|
||||
core.platform.system = lambda: 'Windows'
|
||||
first = failed(core.git_pull, str(pack))
|
||||
print(json.dumps({'failed': first, 'at its commit': head(pack) == commits[0], 'asset at its commit': not (pack / 'asset/.gitmodules').exists()}))
|
||||
''')
|
||||
assert data == {'failed': True, 'at its commit': True, 'asset at its commit': True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
|
||||
def test_pull_of_a_pack_whose_branch_is_ahead_of_its_remote_is_no_failure(where):
|
||||
data = run(where + '''
|
||||
away.rename(library)
|
||||
git(pack, 'pull', '-q', '--recurse-submodules')
|
||||
git(pack, 'commit', '-q', '--allow-empty', '-m', 'a commit of the pack alone')
|
||||
tip = head(pack)
|
||||
print(json.dumps({'failed': failed(core.git_pull, str(pack)), 'at its commit': head(pack) == tip}))
|
||||
''')
|
||||
assert data == {'failed': False, 'at its commit': True}
|
||||
|
||||
|
||||
LIBRARY_AT_A_COMMIT_AWAY = '''
|
||||
(library / '__init__.py').write_text('VERSION = 3')
|
||||
git(library, 'commit', '-q', '-a', '-m', 'version 3')
|
||||
git(origin / 'library', 'pull', '-q')
|
||||
git(origin, 'commit', '-q', '-a', '-m', 'library 3')
|
||||
version_3 = head(library)
|
||||
library.rename(away)
|
||||
'''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
|
||||
def test_pull_that_fails_puts_back_the_branch_of_a_pack_that_was_not_on_it(where):
|
||||
data = run(where + '''
|
||||
away.rename(library)
|
||||
git(pack, 'pull', '-q', '--recurse-submodules')
|
||||
git(pack, 'checkout', '-q', commits[0])
|
||||
git(pack, 'submodule', 'update', '-q', '--recursive')
|
||||
''' + LIBRARY_NOT_CLONED + LIBRARY_AT_A_COMMIT_AWAY + '''
|
||||
print(json.dumps({'failed': failed(core.git_pull, str(pack)), 'at the commit of its branch': head(pack) == commits[1]}))
|
||||
''')
|
||||
assert data == {'failed': True, 'at the commit of its branch': True}
|
||||
|
||||
|
||||
def test_pull_whose_submodules_cannot_be_put_back_either_fails_with_the_error_of_the_update():
|
||||
data = run('''
|
||||
away.rename(library)
|
||||
git(pack, 'pull', '-q', '--no-recurse-submodules')
|
||||
''' + LIBRARY_AT_A_COMMIT_AWAY + '''
|
||||
error = ''
|
||||
try:
|
||||
core.platform.system = lambda: 'Linux'
|
||||
core.git_pull(str(pack))
|
||||
except Exception as e:
|
||||
error = str(e)
|
||||
helper = subprocess.run([sys.executable, core.git_script_path, '--pull', str(pack)], env=core.get_script_env(), cwd=nodes,
|
||||
capture_output=True, text=True)
|
||||
print(json.dumps({'in the server process': version_3 in error, 'in the git helper': [helper.returncode, version_3 in helper.stdout]}))
|
||||
''')
|
||||
assert data == {'in the server process': True, 'in the git helper': [1, True]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
|
||||
def test_pull_that_fails_leaves_a_submodule_that_was_never_fetched_alone(where):
|
||||
data = run(where + '''
|
||||
away.rename(library)
|
||||
git(tmp, 'clone', '-q', str(origin), 'plain')
|
||||
plain = tmp / 'plain'
|
||||
git(plain, 'submodule', 'update', '-q', '--init', 'asset')
|
||||
extra = tmp / 'extra'
|
||||
extra.mkdir()
|
||||
git(extra, 'init', '-q')
|
||||
(extra / 'x.py').write_text('x')
|
||||
git(extra, 'add', '.')
|
||||
git(extra, 'commit', '-q', '-m', 'x')
|
||||
git(origin, 'rm', '-q', 'library')
|
||||
git(origin, 'submodule', 'add', '-q', str(extra), 'extra')
|
||||
git(origin, 'commit', '-q', '-m', 'library removed, extra added')
|
||||
extra.rename(tmp / 'extra.away')
|
||||
before = head(plain)
|
||||
print(json.dumps({'failed': failed(core.git_pull, str(plain)), 'at its commit': head(plain) == before, 'library': os.listdir(plain / 'library')}))
|
||||
''')
|
||||
assert data == {'failed': True, 'at its commit': True, 'library': []}
|
||||
@@ -169,7 +169,12 @@ def test_manager_search_matches_visible_text(page, filename, column, value, quer
|
||||
escape_cell = "undefined"
|
||||
if filename == "model-manager.js":
|
||||
escape_cell = source.split("const escapeCell = ", 1)[1].split(";", 1)[0]
|
||||
page.evaluate("""({init_body, sanitizer, escape_cell, column, value, query}) => {
|
||||
score = "undefined"
|
||||
if "\tcalculateSortScore(" in source:
|
||||
leven = common.split("const levenArray = [];", 1)[1].split("\n}\n", 1)[0].replace("export ", "")
|
||||
method = source.split("\tcalculateSortScore(", 1)[1].split("\n\t}\n", 1)[0]
|
||||
score = "(() => {const levenArray = [];%s\n}\nreturn {calculateSortScore(%s\n}}.calculateSortScore;})()" % (leven, method)
|
||||
page.evaluate("""({init_body, sanitizer, escape_cell, score, column, value, query}) => {
|
||||
const sanitizeHTML = new Function('str', sanitizer);
|
||||
const escapeCell = new Function('sanitizeHTML', `return (${escape_cell})`)(sanitizeHTML);
|
||||
const initGrid = new Function('ManagerGrid', 'createFlyover', 'gridId', 'sanitizeHTML', 'escapeCell',
|
||||
@@ -177,11 +182,12 @@ def test_manager_search_matches_visible_text(page, filename, column, value, quer
|
||||
const element = document.createElement('div');
|
||||
element.innerHTML = '<div id="tested-grid" class="cn-manager-grid cmm-manager-grid" style="width:800px;height:300px"></div>';
|
||||
document.body.append(element);
|
||||
window.manager = {element, keywords: query, showStatus() {}, handleFlyoverHover() {}, createFlyover: () => ({}), hasAlternatives: () => false};
|
||||
window.manager = {element, keywords: query, showStatus() {}, handleFlyoverHover() {}, createFlyover: () => ({}),
|
||||
calculateSortScore: new Function(`return ${score}`)()};
|
||||
initGrid.call(manager);
|
||||
manager.grid.setData({columns: [{id: column, name: column}], rows: [{[column]: value}]});
|
||||
manager.grid.render();
|
||||
}""", {"init_body": init_body, "sanitizer": sanitizer, "escape_cell": escape_cell,
|
||||
}""", {"init_body": init_body, "sanitizer": sanitizer, "escape_cell": escape_cell, "score": score,
|
||||
"column": column, "value": value, "query": query})
|
||||
page.wait_for_function("manager.grid.viewRows !== undefined")
|
||||
assert page.evaluate("manager.grid.viewRows.length") == 1
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""The two direct install routes answer 400 to a body they cannot use.
|
||||
|
||||
Each case runs the real handler of `glob/manager_server.py` with the install
|
||||
allowed; `core` is replaced and records what it is asked to install.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
GIT_URL, PIP = "install_custom_node_git_url", "install_custom_node_pip"
|
||||
|
||||
|
||||
def post(name, body):
|
||||
"""The status the handler answers for the raw request body, and what it asked `core` to install."""
|
||||
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
handler = [node for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == name]
|
||||
assert len(handler) == 1
|
||||
asked = []
|
||||
|
||||
async def gitclone_install(url):
|
||||
asked.append(url)
|
||||
return SimpleNamespace(action="install-git", result=True, target=url, msg="")
|
||||
|
||||
namespace = {
|
||||
"web": web, "logging": logging, "_reject_non_json_content_type": lambda request: None,
|
||||
"routes": SimpleNamespace(post=lambda path: lambda handler: handler),
|
||||
"is_dedicated_install_allowed": lambda flag, listen: True,
|
||||
"args": SimpleNamespace(listen="127.0.0.1"),
|
||||
"core": SimpleNamespace(get_config=lambda: {"allow_git_url_install": True, "allow_pip_install": True},
|
||||
gitclone_install=gitclone_install, pip_install=asked.append),
|
||||
}
|
||||
exec(compile(ast.Module(body=handler, type_ignores=[]), "<install handler>", "exec"), namespace)
|
||||
|
||||
async def read():
|
||||
return json.loads(body)
|
||||
|
||||
return asyncio.run(namespace[name](SimpleNamespace(json=read))).status, asked
|
||||
|
||||
|
||||
NOT_AN_OBJECT = ["[]", '"text"', "7", "null"]
|
||||
NOT_A_STRING = ["7", "null", '["a"]', '{"a": 1}']
|
||||
|
||||
|
||||
def test_git_url_is_installed():
|
||||
assert post(GIT_URL, '{"url": "https://github.com/a/b"}') == (200, ["https://github.com/a/b"])
|
||||
|
||||
|
||||
def test_packages_are_installed():
|
||||
assert post(PIP, '{"packages": "numpy scipy"}') == (200, [["numpy", "scipy"]])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", [GIT_URL, PIP])
|
||||
@pytest.mark.parametrize("body", NOT_AN_OBJECT + ["{}", "not json"])
|
||||
def test_body_without_the_field_is_answered_with_400(name, body):
|
||||
assert post(name, body) == (400, [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NOT_A_STRING)
|
||||
def test_url_that_is_not_a_string_is_answered_with_400(value):
|
||||
assert post(GIT_URL, '{"url": %s}' % value) == (400, [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", NOT_A_STRING)
|
||||
def test_packages_that_are_not_a_string_are_answered_with_400(value):
|
||||
assert post(PIP, '{"packages": %s}' % value) == (400, [])
|
||||
@@ -10,13 +10,13 @@ quirk the flags rely on stays frozen.
|
||||
|
||||
Harness: the child process injects a stub `folder_paths` (routing
|
||||
import-time side effects into a tmpdir, and making has_system_user_api()
|
||||
True so force_security_level_if_needed does not force 'strong'), prepends
|
||||
`glob/` to ITS OWN sys.path (shadowing of stdlib `glob` confined to the
|
||||
child), points manager_core.manager_config_path at a tmp config.ini,
|
||||
True), prepends `glob/` to ITS OWN sys.path (shadowing of stdlib `glob`
|
||||
confined to the child), points manager_core.manager_config_path at a tmp config.ini,
|
||||
resets cached_config, runs the scenario, and prints one JSON line for the
|
||||
parent to assert.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
@@ -24,6 +24,10 @@ import unittest
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
# what `git rev-parse --local-env-vars` lists: with one of them, git does not work on the repository of its directory
|
||||
GIT_LOCATION = ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY",
|
||||
"GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS",
|
||||
"GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR")
|
||||
|
||||
_CHILD_PREAMBLE = textwrap.dedent(
|
||||
"""
|
||||
@@ -65,6 +69,7 @@ def _run_child(body):
|
||||
text=True,
|
||||
timeout=180,
|
||||
cwd=str(REPO_ROOT),
|
||||
env={name: value for name, value in os.environ.items() if name not in GIT_LOCATION},
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise AssertionError(
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
from test_invalid_installation import run
|
||||
|
||||
|
||||
def test_a_registry_nodepack_is_listed_with_its_id_as_its_pyproject_spells_it():
|
||||
data = run('''
|
||||
pack('ComfyUI_SigmoidOffsetScheduler', 'ComfyUI_SigmoidOffsetScheduler', version='1.1.1', tracking=True)
|
||||
emit(core.get_installed_node_packs())
|
||||
''')
|
||||
|
||||
assert data == {
|
||||
'ComfyUI_SigmoidOffsetScheduler': {'ver': '1.1.1', 'cnr_id': 'ComfyUI_SigmoidOffsetScheduler', 'aux_id': None,
|
||||
'enabled': True}}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,169 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from js_lift import _skip_literal
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
JS_DIR = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
|
||||
FILES = sorted(path.name for path in GLOB_DIR.glob("*.py"))
|
||||
CHECK = "_reject_non_json_content_type"
|
||||
|
||||
NOT_GET = ("routes.post", "routes.put", "routes.patch", "routes.delete")
|
||||
READS_ONLY = {"/manager/component/loads"}
|
||||
|
||||
NOT_JSON = [
|
||||
None, "text/plain", "text/plain;charset=UTF-8", "application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=x", "application/octet-stream", "text/json", "application/jsonp",
|
||||
"application/json-patch+json", "application/ld+json", "",
|
||||
]
|
||||
JSON = ["application/json", "application/json; charset=utf-8", "application/json;charset=UTF-8", "Application/JSON"]
|
||||
|
||||
|
||||
def functions(filename):
|
||||
tree = ast.parse((GLOB_DIR / filename).read_text(encoding="utf-8"))
|
||||
return {node.name: node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
||||
|
||||
|
||||
def routes_that_change_something():
|
||||
found = []
|
||||
for filename in FILES:
|
||||
for node in functions(filename).values():
|
||||
for decorator in node.decorator_list:
|
||||
if isinstance(decorator, ast.Call) and ast.unparse(decorator.func).endswith(NOT_GET) \
|
||||
and decorator.args[0].value not in READS_ONLY:
|
||||
found.append((filename, decorator.args[0].value, node.name))
|
||||
return found
|
||||
|
||||
|
||||
ROUTES = routes_that_change_something()
|
||||
|
||||
|
||||
def load_check():
|
||||
node = functions("manager_server.py").get(CHECK)
|
||||
assert node is not None, "manager_server.py has no " + CHECK
|
||||
namespace = {"web": web}
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), "manager_server.py", "exec"), namespace)
|
||||
return namespace[CHECK]
|
||||
|
||||
|
||||
def load_handler(filename, name):
|
||||
routes = web.RouteTableDef()
|
||||
namespace = {"web": web, "routes": routes, "PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)),
|
||||
CHECK: load_check()}
|
||||
defined = functions(filename)
|
||||
defined.pop(CHECK, None)
|
||||
exec(compile(ast.Module(body=list(defined.values()), type_ignores=[]), filename, "exec"), namespace)
|
||||
return namespace[name]
|
||||
|
||||
|
||||
def test_the_routes_are_found():
|
||||
routes = {route for _, route, _ in ROUTES}
|
||||
|
||||
assert len(ROUTES) >= 28
|
||||
assert {"/manager/queue/install", "/manager/queue/reinstall", "/manager/queue/update_all", "/manager/db_mode",
|
||||
"/comfyui_manager/comfyui_switch_version", "/manager/share", "/manager/share_option"} <= routes
|
||||
assert {"/manager/queue/start", "/manager/queue/reset", "/manager/queue/update_comfyui", "/snapshot/save",
|
||||
"/manager/reboot"} <= routes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/octet-stream"])
|
||||
@pytest.mark.parametrize("filename, route, name", ROUTES, ids=[route for _, route, _ in ROUTES])
|
||||
def test_a_route_refuses_a_request_that_is_not_json_before_anything_else(filename, route, name, content_type):
|
||||
read = []
|
||||
|
||||
async def read_json():
|
||||
read.append(True)
|
||||
return {}
|
||||
|
||||
request = SimpleNamespace(content_type=content_type, json=read_json)
|
||||
try:
|
||||
response = load_handler(filename, name)(request)
|
||||
if asyncio.iscoroutine(response):
|
||||
response = asyncio.run(response)
|
||||
except NameError as error:
|
||||
pytest.fail("the handler went on to use `%s`" % error.name)
|
||||
|
||||
assert response.status == 400
|
||||
assert "application/json" in response.text
|
||||
assert read == []
|
||||
|
||||
|
||||
def answer(content_type):
|
||||
check = load_check()
|
||||
|
||||
async def handler(request):
|
||||
return check(request) or web.Response(status=200)
|
||||
|
||||
async def post():
|
||||
app = web.Application()
|
||||
app.router.add_post("/", handler)
|
||||
async with TestClient(TestServer(app)) as client:
|
||||
headers = {} if content_type is None else {"Content-Type": content_type}
|
||||
async with client.post("/", data=b'{"value": "x"}', headers=headers, skip_auto_headers=["Content-Type"]) as response:
|
||||
return response.status
|
||||
|
||||
return asyncio.run(post())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", NOT_JSON, ids=[repr(c) for c in NOT_JSON])
|
||||
def test_a_content_type_that_is_not_json_is_refused(content_type):
|
||||
assert answer(content_type) == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", JSON)
|
||||
def test_json_is_accepted_with_any_parameters_and_in_any_case(content_type):
|
||||
assert answer(content_type) == 200
|
||||
|
||||
|
||||
def script_calls():
|
||||
found = []
|
||||
for path in sorted(JS_DIR.glob("*.js")):
|
||||
source = path.read_text(encoding="utf-8")
|
||||
for match in re.finditer(r"\bfetch(?:Api|Data)\(", source):
|
||||
pos, depth, commas = match.end(), 1, []
|
||||
while depth:
|
||||
skipped = _skip_literal(source, pos)
|
||||
if skipped != pos:
|
||||
pos = skipped
|
||||
continue
|
||||
depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(source[pos], 0)
|
||||
if source[pos] == "," and depth == 1:
|
||||
commas.append(pos)
|
||||
pos += 1
|
||||
options = source[commas[0] + 1:[*commas, pos - 1][1]].strip() if commas else ""
|
||||
found.append((path.name, source.count("\n", 0, match.start()) + 1, source[match.start():pos], options))
|
||||
return found
|
||||
|
||||
|
||||
PASSES_ITS_OPTIONS_ON = [("common.js", "fetchData(route, options)"), ("common.js", "fetchApi(route, options)")]
|
||||
|
||||
|
||||
def test_the_options_of_a_call_are_written_where_it_is_made():
|
||||
assert [(name, call) for name, _, call, options in script_calls()
|
||||
if options and not options.startswith("{")] == PASSES_ITS_OPTIONS_ON
|
||||
|
||||
|
||||
def calls_that_post():
|
||||
return [(name, line, call) for name, line, call, _ in script_calls()
|
||||
if re.search(r"""['"]?\bbody\b['"]?\s*[:,}]|\bmethod\s*:\s*['"](?!GET)""", call)
|
||||
and not any(route in call for route in READS_ONLY)]
|
||||
|
||||
|
||||
CALLS = calls_that_post()
|
||||
|
||||
|
||||
def test_the_calls_are_found():
|
||||
assert len(CALLS) >= 36
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, line, call", CALLS, ids=["%s:%d" % (name, line) for name, line, _ in CALLS])
|
||||
def test_a_script_that_posts_names_json(name, line, call):
|
||||
assert re.search(r"""['"]Content-Type['"]\s*:\s*['"]application/json['"]""", call), call
|
||||
@@ -0,0 +1,290 @@
|
||||
import configparser
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
PREFERENCES = {
|
||||
"security_level": "strong", "network_mode": "private", "db_mode": "local", "preview_method": "taesd",
|
||||
"share_option": "none", "component_policy": "mine", "update_policy": "nightly-comfyui", "use_uv": "True",
|
||||
"file_logging": "False", "always_lazy_install": "True", "default_cache_as_channel_url": "True",
|
||||
"model_download_by_agent": "True", "downgrade_blacklist": "diffusers, kornia",
|
||||
"windows_selector_event_loop_policy": "True",
|
||||
}
|
||||
LEFT_BEHIND = ["allow_git_url_install", "allow_pip_install", "allow_flagged_nodepack_install",
|
||||
"channel_url", "http_channel_enabled", "bypass_ssl", "git_exe"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def migration(tmp_path):
|
||||
spec = importlib.util.spec_from_file_location("_manager_migration", GLOB_DIR / "manager_migration.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.legacy = tmp_path / "user" / "default" / "ComfyUI-Manager" / "config.ini"
|
||||
module.new = tmp_path / "user" / "__manager" / "config.ini"
|
||||
module.legacy.parent.mkdir(parents=True)
|
||||
return module
|
||||
|
||||
|
||||
def migrated(migration, text):
|
||||
migration.legacy.write_text(text, encoding="utf-8")
|
||||
migration._migrate_config_with_security_check(str(migration.legacy), str(migration.new))
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
config.read(migration.new, encoding="utf-8")
|
||||
assert config.sections() in ([], ["default"])
|
||||
assert not config.defaults()
|
||||
return dict(config["default"]) if "default" in config else {}
|
||||
|
||||
|
||||
def section(settings):
|
||||
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
|
||||
|
||||
|
||||
def test_preferences_are_migrated_as_they_were_written(migration, capsys):
|
||||
assert migrated(migration, section(PREFERENCES)) == PREFERENCES
|
||||
assert "not migrated" not in capsys.readouterr().out
|
||||
assert migration.startup_notices == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["True", "true", "1", "yes", "https://channel.example/list", "/usr/bin/other-git"])
|
||||
@pytest.mark.parametrize("key", LEFT_BEHIND)
|
||||
def test_a_setting_that_permits_an_install_or_changes_the_source_is_left_behind(migration, capsys, key, value):
|
||||
assert migrated(migration, section({**PREFERENCES, key: value})) == PREFERENCES
|
||||
assert key in capsys.readouterr().out
|
||||
assert [level for _, level in migration.startup_notices] == ["warning"]
|
||||
|
||||
|
||||
AS_WRITTEN = {
|
||||
"allow_git_url_install": "False", "allow_pip_install": "False", "allow_flagged_nodepack_install": "False",
|
||||
"http_channel_enabled": "False", "bypass_ssl": "False", "git_exe": "",
|
||||
"channel_url": "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("settings", [AS_WRITTEN, {key: value.upper() for key, value in AS_WRITTEN.items() if value in ("False",)},
|
||||
{key: value.lower() for key, value in AS_WRITTEN.items() if value in ("False",)}],
|
||||
ids=["as written", "upper case", "lower case"])
|
||||
def test_a_setting_that_was_never_changed_is_left_behind_without_a_warning(migration, capsys, settings):
|
||||
assert migrated(migration, section({**PREFERENCES, **settings})) == PREFERENCES
|
||||
assert "not migrated" not in capsys.readouterr().out
|
||||
assert migration.startup_notices == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", LEFT_BEHIND)
|
||||
def test_one_changed_setting_among_those_never_changed_is_the_one_reported(migration, capsys, key):
|
||||
changed = "True" if AS_WRITTEN[key] == "False" else "something-else"
|
||||
|
||||
assert migrated(migration, section({**PREFERENCES, **AS_WRITTEN, key: changed})) == PREFERENCES
|
||||
|
||||
printed = capsys.readouterr().out
|
||||
assert f"['{key}']" in printed
|
||||
assert len(migration.startup_notices) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["ALLOW_GIT_URL_INSTALL", "Allow_Pip_Install", "allow_git_url_install ", "CHANNEL_URL"],
|
||||
ids=["upper case", "mixed case", "trailing space", "upper case channel"])
|
||||
def test_a_setting_is_left_behind_however_its_name_is_written(migration, key):
|
||||
assert migrated(migration, section({**PREFERENCES, key: "True"})) == PREFERENCES
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"[DEFAULT]\nallow_git_url_install = True\n[default]\ndb_mode = local\n",
|
||||
"[DEFAULT]\nallow_git_url_install = True\ndb_mode = local\n[default]\n",
|
||||
"[default]\ndb_mode = local\nallow_git_url_install: True\n",
|
||||
"[default]\ndb_mode = local\n[other]\nallow_git_url_install = True\n",
|
||||
"[default]\ndb_mode = local\n[default2]\nallow_pip_install = True\n",
|
||||
], ids=["in the DEFAULT section", "all in the DEFAULT section", "with a colon", "in another section",
|
||||
"in a section of a similar name"])
|
||||
def test_a_setting_is_left_behind_wherever_the_file_has_it(migration, text):
|
||||
assert migrated(migration, text) == {"db_mode": "local"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["True", "False", ""])
|
||||
@pytest.mark.parametrize("key", ["a_setting_of_a_later_version", "allow_everything", "security_level2", "x"])
|
||||
def test_a_setting_that_is_not_known_is_left_behind(migration, key, value):
|
||||
assert migrated(migration, section({**PREFERENCES, key: value})) == PREFERENCES
|
||||
|
||||
|
||||
def test_all_of_them_at_once_leave_only_the_preferences(migration, capsys):
|
||||
assert migrated(migration, section({**PREFERENCES, **{key: "True" for key in LEFT_BEHIND}})) == PREFERENCES
|
||||
printed = capsys.readouterr().out
|
||||
assert all(key in printed for key in LEFT_BEHIND)
|
||||
assert len(migration.startup_notices) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["<img src=x onerror=alert(1)>", "<b>bold</b>", "a&b", "\x1b[2Jcleared"],
|
||||
ids=["an element", "a tag", "an ampersand", "an escape sequence"])
|
||||
def test_the_text_of_the_file_does_not_reach_the_notice_or_the_terminal_as_written(migration, capsys, name):
|
||||
assert migrated(migration, section({name: "True", "db_mode": "local"})) == {"db_mode": "local"}
|
||||
|
||||
message, _ = migration.startup_notices[0]
|
||||
assert name.lower() not in message.lower()
|
||||
assert "\x1b" not in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("level", ["\x1b[2Jcleared", "strong\x1b[31m", "\x07"], ids=["an escape sequence", "after a level", "a bell"])
|
||||
def test_a_security_level_with_a_control_character_does_not_reach_the_terminal_as_written(migration, capsys, level):
|
||||
migrated(migration, section({"security_level": level}))
|
||||
|
||||
printed = capsys.readouterr().out
|
||||
assert "\x1b" not in printed and "\x07" not in printed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("level, expected", [("weak", "normal"), ("normal-", "normal"), ("WEAK", "normal"),
|
||||
("normal", "normal"), ("strong", "strong")])
|
||||
def test_a_security_level_below_normal_is_raised(migration, level, expected):
|
||||
assert migrated(migration, section({"security_level": level, "allow_git_url_install": "True"})) == {"security_level": expected}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["100%", "%(db_mode)s", "a%%b", "50% off", "%"])
|
||||
@pytest.mark.parametrize("key", sorted(set(PREFERENCES) - {"security_level"}))
|
||||
def test_a_value_with_a_percent_sign_is_migrated_as_it_was_written(migration, key, value):
|
||||
assert migrated(migration, section({**PREFERENCES, key: value})) == {**PREFERENCES, key: value}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("level", ["100%", "%(downgrade_blacklist)s", "%(db_mode)s%(share_option)s", "storng", "high", "normal+", "0",
|
||||
"<b>weak</b>", "wea k", "weak,normal"])
|
||||
def test_a_security_level_that_is_not_one_is_back_at_normal_and_no_other_setting_with_it(migration, capsys, level):
|
||||
settings = {**PREFERENCES, "security_level": level}
|
||||
|
||||
assert migrated(migration, section(settings)) == {**settings, "security_level": "normal"}
|
||||
assert "is not a security level" in capsys.readouterr().out
|
||||
assert [level in message for message, _ in migration.startup_notices] == [False]
|
||||
|
||||
|
||||
def test_a_legacy_file_without_a_security_level_gets_none(migration):
|
||||
assert migrated(migration, section({"db_mode": "local"})) == {"db_mode": "local"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "\n", "[other]\ndb_mode = local\n"], ids=["empty", "a newline", "no default section"])
|
||||
def test_a_file_without_settings_migrates_none(migration, text):
|
||||
assert migrated(migration, text) == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["db_mode = local\n", "[default\ndb_mode = local\n", "[default]\n[default]\n"],
|
||||
ids=["no section", "an unclosed section", "a section twice"])
|
||||
def test_a_file_that_cannot_be_parsed_is_not_migrated(migration, text):
|
||||
assert migrated(migration, text) == {}
|
||||
assert not migration.new.exists()
|
||||
|
||||
|
||||
def test_the_migration_of_the_legacy_directory_leaves_the_install_settings_behind(migration, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
|
||||
migration.legacy.write_text(section({**PREFERENCES, **{key: "True" for key in LEFT_BEHIND}}), encoding="utf-8")
|
||||
|
||||
assert migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent)) is True
|
||||
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
config.read(migration.new, encoding="utf-8")
|
||||
assert dict(config["default"]) == PREFERENCES
|
||||
assert not migration.legacy.exists()
|
||||
|
||||
|
||||
def test_an_earlier_backup_of_the_legacy_directory_is_kept(migration, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
|
||||
backups = [migration.new.parent / ".legacy-manager-backup", migration.new.parent / ".legacy-manager-backup-2",
|
||||
migration.new.parent / ".legacy-manager-backup-3"]
|
||||
|
||||
for number, backup in enumerate(backups):
|
||||
migration.legacy.parent.mkdir(parents=True, exist_ok=True)
|
||||
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
|
||||
(migration.legacy.parent / "kept.txt").write_text(str(number), encoding="utf-8")
|
||||
|
||||
assert migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent)) is True
|
||||
|
||||
assert not migration.legacy.parent.exists()
|
||||
assert [(b / "kept.txt").read_text(encoding="utf-8") for b in backups[:number + 1]] == [str(n) for n in range(number + 1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("backups", [[".legacy-manager-backup"], [".legacy-manager-backup-2"],
|
||||
[".legacy-manager-backup", ".legacy-manager-backup-2", ".legacy-manager-backup-3"]],
|
||||
ids=["the first backup", "only a later backup", "three backups"])
|
||||
def test_a_start_reminds_of_every_backup_that_is_there(migration, capsys, backups):
|
||||
for name in backups:
|
||||
(migration.new.parent / name).mkdir(parents=True)
|
||||
|
||||
migration.check_legacy_backup(str(migration.new.parent))
|
||||
|
||||
printed = capsys.readouterr().out
|
||||
assert [line.strip() for line in printed.splitlines() if ".legacy-manager-backup" in line] == \
|
||||
[str(migration.new.parent / name) for name in backups]
|
||||
assert [level for _, level in migration.startup_notices] == ["info"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("there", [False, True], ids=["no data directory", "a data directory without a backup"])
|
||||
def test_a_start_without_a_backup_reminds_of_nothing(migration, capsys, there):
|
||||
if there:
|
||||
migration.new.parent.mkdir(parents=True)
|
||||
migration.new.write_text(section({"db_mode": "local"}), encoding="utf-8")
|
||||
|
||||
migration.check_legacy_backup(str(migration.new.parent))
|
||||
|
||||
assert capsys.readouterr().out == ""
|
||||
assert migration.startup_notices == []
|
||||
|
||||
|
||||
NAMES = ["kept.txt", "<img src=x>.json", "a&b.json", "\x1b[2Jcleared.json", "a'b\"c.json"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [
|
||||
*[lambda path, name=name: PermissionError(13, "Permission denied", path + name) for name in NAMES],
|
||||
lambda path: OSError("cannot move \x1b[2J" + path),
|
||||
lambda path: shutil.Error([(path + "\x1b[2Ja.json", path + "b.json", "[Errno 13] Permission denied: \x07")]),
|
||||
], ids=["a plain name", "an element", "an ampersand", "an escape sequence", "quotes", "a text with an escape sequence",
|
||||
"the errors of a copy"])
|
||||
def test_a_backup_that_fails_is_reported_without_the_text_of_the_error(migration, monkeypatch, capsys, error):
|
||||
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
|
||||
error = error(str(migration.legacy.parent) + "/")
|
||||
|
||||
def move(source, destination):
|
||||
raise error
|
||||
|
||||
monkeypatch.setattr(shutil, "move", move)
|
||||
|
||||
assert migration._move_legacy_to_backup(str(migration.legacy.parent), str(migration.new.parent)) is None
|
||||
|
||||
assert migration.startup_notices == [("[MIGRATION] Failed to backup legacy directory. See terminal for details.", "warning")]
|
||||
printed = capsys.readouterr().out
|
||||
assert "Failed to backup legacy directory: " + repr(str(error)) in printed
|
||||
assert "\x1b" not in printed and "\x07" not in printed
|
||||
assert migration.legacy.exists()
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), reason="needs a file that cannot be read")
|
||||
def test_a_copy_that_fails_leaves_the_legacy_directory_and_no_part_of_a_backup(migration, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
|
||||
monkeypatch.setattr(os, "rename", lambda source, destination: (_ for _ in ()).throw(OSError(18, "Invalid cross-device link")))
|
||||
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
|
||||
(migration.legacy.parent / "kept.txt").write_text("kept", encoding="utf-8")
|
||||
unreadable = migration.legacy.parent / "unreadable.json"
|
||||
unreadable.write_text("{}", encoding="utf-8")
|
||||
unreadable.chmod(0)
|
||||
|
||||
for _ in range(3):
|
||||
migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent))
|
||||
|
||||
assert sorted(path.name for path in migration.legacy.parent.iterdir()) == ["config.ini", "kept.txt", "unreadable.json"]
|
||||
assert [path.name for path in migration.new.parent.iterdir() if path.name.startswith(".legacy-manager-backup")] == []
|
||||
|
||||
unreadable.chmod(0o600)
|
||||
|
||||
|
||||
def test_a_backup_that_was_copied_is_kept_when_the_legacy_directory_cannot_be_removed(migration, monkeypatch):
|
||||
monkeypatch.setattr(os, "rename", lambda source, destination: (_ for _ in ()).throw(OSError(18, "Invalid cross-device link")))
|
||||
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
|
||||
(migration.legacy.parent / "kept.txt").write_text("kept", encoding="utf-8")
|
||||
migration.new.parent.mkdir(parents=True)
|
||||
|
||||
def rmtree(path, *args, **kwargs):
|
||||
raise PermissionError(13, "Permission denied", str(path))
|
||||
|
||||
monkeypatch.setattr(shutil, "rmtree", rmtree)
|
||||
|
||||
assert migration._move_legacy_to_backup(str(migration.legacy.parent), str(migration.new.parent)) is None
|
||||
|
||||
backup = migration.new.parent / ".legacy-manager-backup"
|
||||
assert sorted(path.name for path in backup.iterdir()) == ["config.ini", "kept.txt"]
|
||||
assert (backup / "kept.txt").read_text(encoding="utf-8") == "kept"
|
||||
@@ -2,10 +2,18 @@
|
||||
|
||||
A logger that always answered "not a terminal" made colorama, and any other library that
|
||||
asks, strip its colors and hide its progress display for the whole session.
|
||||
|
||||
Other cases are about what is written once the log file is closed: the restart under
|
||||
comfy-cli closes it and then exits, and what is logged on the way out must not fail.
|
||||
"""
|
||||
import ast
|
||||
import errno
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import textwrap
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -35,15 +43,143 @@ class StreamThatCannotBeAsked:
|
||||
raise OSError("The handle is invalid")
|
||||
|
||||
|
||||
def loggers(stdout, stderr, log_closed=False):
|
||||
class LogFile:
|
||||
def __init__(self, closed=False):
|
||||
self.closed = closed
|
||||
self.written = []
|
||||
|
||||
def write(self, text):
|
||||
if self.closed:
|
||||
raise ValueError("I/O operation on closed file.")
|
||||
self.written.append(text)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
def loggers(stdout, stderr, log_closed=False, **module_globals):
|
||||
"""Lift ComfyUIManagerLogger; importing prestartup_script would run the startup."""
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
node = next(n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.ClassDef) and n.name == "ComfyUIManagerLogger")
|
||||
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed)}
|
||||
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed),
|
||||
**module_globals}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[node.lineno - 1:node.end_lineno])), scope)
|
||||
return scope["ComfyUIManagerLogger"](True), scope["ComfyUIManagerLogger"](False)
|
||||
|
||||
|
||||
def close_logs(log_file, log_lock):
|
||||
"""The two ways to close the log file: the logger's method, and the function run at exit."""
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
in_class = {id(n) for c in ast.walk(tree) if isinstance(c, ast.ClassDef) for n in ast.walk(c)}
|
||||
function = next(n for n in ast.walk(tree)
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "close_log" and id(n) not in in_class)
|
||||
scope = {"sys": SimpleNamespace(), "original_stdout": None, "original_stderr": None,
|
||||
"log_file": log_file, "log_lock": log_lock}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[function.lineno - 1:function.end_lineno])), scope)
|
||||
out, _ = loggers(None, None, **{name: scope[name] for name in ("sys", "log_file", "log_lock")})
|
||||
return out.close_log, scope["close_log"]
|
||||
|
||||
|
||||
def assigned(name):
|
||||
tree = ast.parse(SOURCE.read_text(encoding="utf-8"))
|
||||
return next(ast.literal_eval(n.value) for n in ast.walk(tree)
|
||||
if isinstance(n, ast.Assign) and [t.id for t in n.targets if isinstance(t, ast.Name)] == [name])
|
||||
|
||||
|
||||
def writing_loggers(stdout, stderr, log_file):
|
||||
return loggers(stdout, stderr, log_file=log_file, log_lock=threading.Lock(), std_log_lock=threading.Lock(),
|
||||
current_timestamp=lambda: "12:00:00", write_stdout=stdout.write, write_stderr=stderr.write,
|
||||
re=re, pat_tqdm=assigned("pat_tqdm"), message_collapses=[], is_start_mode=False)
|
||||
|
||||
|
||||
def recording_stream():
|
||||
written = []
|
||||
return SimpleNamespace(write=written.append, flush=lambda: None), written
|
||||
|
||||
|
||||
def writing_logger(log_file):
|
||||
"""The stderr logger with what its writes need, and the list of what reached the console."""
|
||||
stream, console = recording_stream()
|
||||
_, err = writing_loggers(stream, stream, log_file)
|
||||
return err, console
|
||||
|
||||
|
||||
def logging_handler(console, log_file):
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
node = next(n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.ClassDef) and n.name == "LoggingHandler")
|
||||
_, err = writing_loggers(console, console, log_file)
|
||||
scope = {"logging": logging, "is_start_mode": False, "stderr_wrapper": err, "original_stderr": console}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[node.lineno - 1:node.end_lineno])), scope)
|
||||
return scope["LoggingHandler"]()
|
||||
|
||||
|
||||
def pipe_without_a_reader(unbuffered):
|
||||
read_end, write_end = os.pipe()
|
||||
os.close(read_end)
|
||||
if unbuffered:
|
||||
return io.TextIOWrapper(io.FileIO(write_end, "w"), encoding="utf-8", write_through=True)
|
||||
return open(write_end, "w", encoding="utf-8")
|
||||
|
||||
|
||||
def terminal_that_has_hung_up():
|
||||
if not hasattr(os, "openpty"):
|
||||
pytest.skip("no pseudo-terminal on this platform")
|
||||
master, slave = os.openpty()
|
||||
stream = open(slave, "w", encoding="utf-8")
|
||||
os.close(master)
|
||||
return stream
|
||||
|
||||
|
||||
@pytest.fixture(params=["pipe", "unbuffered pipe", "terminal"])
|
||||
def console_that_is_gone(request):
|
||||
"""A pipe whose reader has exited fails with EPIPE: at the flush, or at the write when the
|
||||
stream is unbuffered, as it is with -u. A terminal that has hung up fails with EIO, at
|
||||
the write of a line, since the stream of a terminal is line-buffered."""
|
||||
if request.param == "terminal":
|
||||
stream = terminal_that_has_hung_up()
|
||||
else:
|
||||
stream = pipe_without_a_reader(unbuffered=request.param == "unbuffered pipe")
|
||||
yield stream
|
||||
try:
|
||||
stream.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class CountingWrites:
|
||||
def __init__(self, stream):
|
||||
self.stream = stream
|
||||
self.writes = 0
|
||||
|
||||
def write(self, text):
|
||||
self.writes += 1
|
||||
return self.stream.write(text)
|
||||
|
||||
def flush(self):
|
||||
return self.stream.flush()
|
||||
|
||||
|
||||
def run_progress_bar(logger):
|
||||
tqdm = pytest.importorskip("tqdm")
|
||||
for _ in tqdm.tqdm(range(3), file=logger, mininterval=0, miniters=1, disable=False):
|
||||
pass
|
||||
|
||||
|
||||
def write_a_line(logger):
|
||||
logger.write("second\n")
|
||||
|
||||
|
||||
class Unprintable:
|
||||
def __str__(self):
|
||||
raise RuntimeError("no text for this")
|
||||
|
||||
|
||||
class UnprintableWithItsError:
|
||||
def __str__(self):
|
||||
raise RuntimeError(self)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ansitowin32(monkeypatch):
|
||||
"""colorama's stream wrapper, with its probe of the Windows console answered.
|
||||
@@ -121,3 +257,159 @@ def test_colorama_keeps_ansi_codes_only_on_a_terminal(ansitowin32, stream, kept)
|
||||
out, _ = loggers(stream, stream)
|
||||
|
||||
assert ansitowin32.AnsiToWin32(out).strip is (not kept)
|
||||
|
||||
|
||||
def test_open_log_file_gets_what_is_written():
|
||||
log_file = LogFile()
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
logger.sync_write("first\n")
|
||||
logger.sync_write("logged only\n", file_only=True)
|
||||
|
||||
assert log_file.written == ["first\n", "[12:00:00] logged only\n"]
|
||||
assert console == ["first\n"]
|
||||
|
||||
|
||||
def test_closed_log_file_is_left_alone():
|
||||
log_file = LogFile(closed=True)
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
# what the logging handler does with a record that arrives after close_log()
|
||||
logger.sync_write("logged only\n", file_only=True)
|
||||
logger.sync_write("still shown\n")
|
||||
|
||||
assert log_file.written == []
|
||||
assert console == ["still shown\n"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", [0, 1])
|
||||
def test_log_file_is_closed_under_the_lock_of_the_writes(which):
|
||||
log_lock = threading.Lock()
|
||||
held = []
|
||||
log_file = SimpleNamespace(close=lambda: held.append(log_lock.locked()))
|
||||
|
||||
close_logs(log_file, log_lock)[which]()
|
||||
|
||||
# a write checks that the file is open and writes to it under this lock
|
||||
assert held == [True]
|
||||
|
||||
|
||||
def test_progress_of_a_bar_is_shown_and_only_the_finished_bar_is_logged():
|
||||
log_file = LogFile()
|
||||
logger, console = writing_logger(log_file)
|
||||
|
||||
run_progress_bar(logger)
|
||||
|
||||
shown, logged = "".join(console), "".join(log_file.written)
|
||||
assert "1/3" in shown and "3/3" in shown
|
||||
assert "3/3" in logged and "1/3" not in logged
|
||||
|
||||
|
||||
def test_each_logger_writes_to_its_own_console_stream():
|
||||
stdout, on_stdout = recording_stream()
|
||||
stderr, on_stderr = recording_stream()
|
||||
out, err = writing_loggers(stdout, stderr, LogFile())
|
||||
|
||||
out.write("to stdout\n")
|
||||
err.write("to stderr\n")
|
||||
run_progress_bar(err)
|
||||
|
||||
assert on_stdout == ["to stdout\n"]
|
||||
assert on_stderr[0] == "to stderr\n" and "3/3" in "".join(on_stderr)
|
||||
|
||||
|
||||
def test_progress_bar_does_not_fail_once_the_console_is_gone(console_that_is_gone):
|
||||
log_file = LogFile()
|
||||
_, logger = writing_loggers(console_that_is_gone, console_that_is_gone, log_file)
|
||||
|
||||
run_progress_bar(logger)
|
||||
|
||||
assert "3/3" in "".join(log_file.written)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("which", [0, 1], ids=["stdout", "stderr"])
|
||||
def test_text_does_not_fail_and_is_logged_once_the_console_is_gone(console_that_is_gone, which):
|
||||
log_file = LogFile()
|
||||
logger = writing_loggers(console_that_is_gone, console_that_is_gone, log_file)[which]
|
||||
|
||||
logger.write("a line of a node\n")
|
||||
|
||||
assert log_file.written == ["a line of a node\n"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("then", [write_a_line, run_progress_bar], ids=["text", "progress bar"])
|
||||
def test_console_that_has_failed_is_not_written_to_again(console_that_is_gone, then):
|
||||
gone = CountingWrites(console_that_is_gone)
|
||||
healthy, shown = recording_stream()
|
||||
out, err = writing_loggers(healthy, gone, LogFile())
|
||||
|
||||
err.write("first\n")
|
||||
then(err)
|
||||
out.write("to stdout\n")
|
||||
|
||||
assert gone.writes == 1
|
||||
assert shown == ["to stdout\n"]
|
||||
|
||||
|
||||
def test_console_that_cannot_take_a_write_now_is_written_to_again():
|
||||
taken = []
|
||||
|
||||
def write(text):
|
||||
if not taken:
|
||||
taken.append(None)
|
||||
raise BlockingIOError(errno.EAGAIN, "write could not complete without blocking")
|
||||
taken.append(text)
|
||||
|
||||
console = SimpleNamespace(write=write, flush=lambda: None)
|
||||
out, _ = writing_loggers(console, console, LogFile())
|
||||
|
||||
out.write("dropped\n")
|
||||
out.write("shown\n")
|
||||
|
||||
assert taken == [None, "shown\n"]
|
||||
|
||||
|
||||
def test_what_is_written_reaches_a_buffered_console_at_once():
|
||||
behind = io.BytesIO()
|
||||
console = io.TextIOWrapper(behind, encoding="utf-8")
|
||||
out, _ = writing_loggers(console, console, LogFile())
|
||||
|
||||
out.write("a line")
|
||||
|
||||
assert behind.getvalue() == b"a line"
|
||||
|
||||
|
||||
def test_text_that_the_console_cannot_encode_fails_as_it_does_without_the_logger():
|
||||
console = io.TextIOWrapper(io.BytesIO(), encoding="utf-8")
|
||||
out, _ = writing_loggers(console, console, LogFile())
|
||||
|
||||
with pytest.raises(UnicodeEncodeError):
|
||||
out.write("half of a surrogate pair \udc80\n")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("message, arguments, error", [
|
||||
("two values %s %s", ("only one",), "TypeError: not enough arguments for format string"),
|
||||
("%(missing)s", ({"other": 1},), "KeyError: 'missing'"),
|
||||
(Unprintable(), (), "RuntimeError: no text for this"),
|
||||
(UnprintableWithItsError(), (), "RuntimeError"),
|
||||
], ids=["too few arguments", "a missing key", "a message that cannot be printed",
|
||||
"a message whose error cannot be printed either"])
|
||||
def test_record_that_cannot_be_formatted_is_logged_and_does_not_fail(message, arguments, error):
|
||||
console, shown = recording_stream()
|
||||
log_file = LogFile()
|
||||
handler = logging_handler(console, log_file)
|
||||
|
||||
handler.emit(logging.LogRecord("root", logging.INFO, "a_node.py", 7, message, arguments, None))
|
||||
|
||||
assert len(log_file.written) == 1
|
||||
assert log_file.written[0].endswith(f"<<logging error>>: a_node.py:7 - {error}\n")
|
||||
assert shown == []
|
||||
|
||||
|
||||
def test_record_that_cannot_be_formatted_is_logged_and_does_not_fail_once_the_console_is_gone(console_that_is_gone):
|
||||
log_file = LogFile()
|
||||
handler = logging_handler(console_that_is_gone, log_file)
|
||||
|
||||
handler.emit(logging.LogRecord("root", logging.INFO, "a_node.py", 7, "two values\n%s %s", ("only one",), None))
|
||||
|
||||
assert len(log_file.written) == 1 and "a_node.py:7" in log_file.written[0]
|
||||
|
||||
@@ -14,7 +14,7 @@ IMPORT DISCIPLINE (load-bearing, see tests/conftest.py):
|
||||
- `glob/manager_server.py` starts a network thread at import and needs the
|
||||
ComfyUI stack, so it is NEVER imported. `convert_markdown_to_html` is
|
||||
AST-extracted and executed in an isolated namespace instead — the same
|
||||
technique tests/test_csrf_content_type_helper.py already uses in this repo.
|
||||
technique tests/test_json_body_content_type.py already uses in this repo.
|
||||
"""
|
||||
import unittest
|
||||
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
MATRIX_ORG = "https://matrix.org"
|
||||
SAVED = ("matrix.org", "user", "the saved password")
|
||||
PASSWORDS_THAT_LOG_IN = {SAVED[2], "a new password"}
|
||||
FUNCTIONS = ("is_matrix_org", "get_matrix_auth", "set_matrix_auth", "api_get_matrix_auth", "share_art")
|
||||
|
||||
|
||||
class LoginResponse:
|
||||
access_token = "token"
|
||||
|
||||
|
||||
class UploadResponse:
|
||||
content_uri = "mxc://test/asset"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(monkeypatch, tmp_path):
|
||||
logins = []
|
||||
|
||||
class AsyncClient:
|
||||
def __init__(self, homeserver, username):
|
||||
self.homeserver, self.username = homeserver, username
|
||||
|
||||
async def login(self, password):
|
||||
logins.append((self.homeserver, self.username, password))
|
||||
return LoginResponse() if password in PASSWORDS_THAT_LOG_IN else None
|
||||
|
||||
async def upload(self, data, content_type=None, filename=None):
|
||||
return UploadResponse(), None
|
||||
|
||||
async def room_send(self, **kwargs):
|
||||
pass
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
nio = ModuleType("nio")
|
||||
nio.AsyncClient, nio.LoginResponse, nio.UploadResponse = AsyncClient, LoginResponse, UploadResponse
|
||||
monkeypatch.setitem(sys.modules, "nio", nio)
|
||||
|
||||
files = tmp_path / "manager"
|
||||
output_dir = tmp_path / "output"
|
||||
files.mkdir()
|
||||
output_dir.mkdir()
|
||||
(output_dir / "a.png").write_bytes(b"output image")
|
||||
|
||||
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in FUNCTIONS]
|
||||
assert len(nodes) == len(FUNCTIONS)
|
||||
namespace = {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
|
||||
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
|
||||
get_temp_directory=lambda: str(tmp_path / "temp")),
|
||||
"core": SimpleNamespace(manager_files_path=str(files)),
|
||||
"os": os, "web": web, "json": json, "mimetypes": mimetypes,
|
||||
"_reject_non_json_content_type": lambda request: None,
|
||||
}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
|
||||
return SimpleNamespace(file=files / "matrix_auth", logins=logins, **{name: namespace[name] for name in FUNCTIONS})
|
||||
|
||||
|
||||
def share(manager, matrix_auth, destinations=("matrix",)):
|
||||
body = {
|
||||
"matrix_auth": matrix_auth, "share_destinations": list(destinations),
|
||||
"credits": "", "title": "", "description": "", "prompt": {"workflow": {}}, "selected_output_index": 0,
|
||||
"potential_outputs": [{"type": "image", "image": {"filename": "a.png", "subfolder": "", "type": "output"}}],
|
||||
}
|
||||
|
||||
async def read_json():
|
||||
return body
|
||||
|
||||
try:
|
||||
return asyncio.run(manager.share_art(SimpleNamespace(json=read_json))).status
|
||||
except Exception:
|
||||
return 500
|
||||
|
||||
|
||||
def account(homeserver=SAVED[0], username=SAVED[1], password=""):
|
||||
return {"homeserver": homeserver, "username": username, "password": password}
|
||||
|
||||
|
||||
MATRIX_ORG_FORMS = ["matrix.org", "https://matrix.org", "http://matrix.org"]
|
||||
|
||||
OTHER_HOMESERVERS = [
|
||||
"matrix.example", "matrix.org.example", "sub.matrix.org", "matrix", "org", "Matrix.org", "MATRIX.ORG",
|
||||
"matrix.org/", "matrix.org.", " matrix.org", "matrix.org ", "matrix.org:8448", "matrix.org:443",
|
||||
"user@matrix.org", "matrix.org@other.example", "other.example/matrix.org", "other.example#matrix.org",
|
||||
"other.example?matrix.org", "https://other.example", "http://other.example", "https://https://matrix.org",
|
||||
"ftp://matrix.org", "//matrix.org", "matrix.org\\other.example", "matrix.org\nother.example", "127.0.0.1", "localhost:8188",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
"matrix.org\nuser\nthe saved password",
|
||||
"matrix.org\nuser\nthe saved password\n",
|
||||
"\n\nmatrix.org\nuser\nthe saved password\n\n",
|
||||
], ids=["three lines", "a final newline", "blank lines around"])
|
||||
def test_the_answer_has_the_homeserver_and_the_username(manager, text):
|
||||
manager.file.write_text(text)
|
||||
|
||||
response = asyncio.run(manager.api_get_matrix_auth(None))
|
||||
|
||||
assert response.status == 200
|
||||
assert json.loads(response.text) == {"homeserver": "matrix.org", "username": "user"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [
|
||||
None, "", "matrix.org\nuser", "matrix.org\nuser\nthe saved password\nmore",
|
||||
"matrix.org\n\nthe saved password", "matrix.org\nuser\n", "\nuser\nthe saved password",
|
||||
], ids=["no file", "an empty file", "two lines", "four lines", "an empty username", "an empty password",
|
||||
"an empty homeserver"])
|
||||
def test_a_file_that_is_not_an_account_is_answered_as_nothing_saved(manager, text):
|
||||
if text is not None:
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
|
||||
assert share(manager, account()) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", "")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", [h for h in OTHER_HOMESERVERS if h == h.strip() and "\n" not in h])
|
||||
def test_an_account_saved_for_another_homeserver_is_not_used(manager, homeserver):
|
||||
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
|
||||
assert share(manager, account()) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", "")]
|
||||
assert manager.file.read_text() == text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS[1:])
|
||||
def test_matrix_org_saved_with_a_scheme_is_the_saved_account(manager, homeserver):
|
||||
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
|
||||
manager.file.write_text(text)
|
||||
|
||||
assert json.loads(asyncio.run(manager.api_get_matrix_auth(None)).text) == {"homeserver": homeserver, "username": "user"}
|
||||
assert share(manager, account()) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["", None], ids=["empty", "null"])
|
||||
def test_no_password_for_the_saved_account_logs_in_with_the_saved_one(manager, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(password=password)) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("matrix_auth", [
|
||||
*(account(homeserver) for homeserver in MATRIX_ORG_FORMS), {"username": "user", "password": ""},
|
||||
], ids=[*MATRIX_ORG_FORMS, "no homeserver field"])
|
||||
def test_matrix_org_is_logged_in_however_the_request_writes_it(manager, matrix_auth):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, matrix_auth) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", OTHER_HOMESERVERS + [""])
|
||||
@pytest.mark.parametrize("password", ["", "a new password"], ids=["no password", "a password that logs in"])
|
||||
def test_another_homeserver_is_refused_before_any_login(manager, homeserver, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver, password=password)) == 400
|
||||
assert manager.logins == []
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", ["User", "user ", " user", "user2", "use", ""],
|
||||
ids=["upper case", "trailing space", "leading space", "longer", "shorter", "empty"])
|
||||
def test_a_username_written_otherwise_is_another_account(manager, username):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(username=username)) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, username, "")]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS)
|
||||
def test_a_password_that_logs_in_replaces_the_saved_account(manager, homeserver):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver, "someone", "a new password")) == 200
|
||||
assert manager.logins == [(MATRIX_ORG, "someone", "a new password")]
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["a wrong password", " "], ids=["wrong", "a space"])
|
||||
def test_a_password_that_does_not_log_in_leaves_the_saved_account(manager, password):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(password=password)) == 400
|
||||
assert manager.logins == [(MATRIX_ORG, "user", password)]
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", ["matrix.org", "other.example"])
|
||||
def test_sharing_without_matrix_leaves_the_saved_account(manager, homeserver):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, account(homeserver), destinations=()) == 200
|
||||
assert manager.logins == []
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("matrix_auth", [
|
||||
None, [], {}, {"homeserver": "matrix.org", "username": "user"},
|
||||
{"homeserver": None, "username": "user", "password": ""},
|
||||
{"homeserver": ["matrix.org"], "username": "user", "password": ""},
|
||||
{"homeserver": 1, "username": "user", "password": ""},
|
||||
{"homeserver": "matrix.org", "username": None, "password": None},
|
||||
{"homeserver": "matrix.org", "username": 1, "password": 0},
|
||||
], ids=["null", "a list", "no fields", "no password field", "null homeserver", "a list as homeserver",
|
||||
"a number as homeserver", "null username", "numbers"])
|
||||
def test_a_malformed_account_leaves_the_saved_account(manager, matrix_auth):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
assert share(manager, matrix_auth) >= 400
|
||||
assert SAVED[2] not in [login[2] for login in manager.logins]
|
||||
assert all(login[0] == MATRIX_ORG for login in manager.logins)
|
||||
assert manager.file.read_text() == "\n".join(SAVED)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
@pytest.mark.parametrize("umask", [0o022, 0o002, 0o000])
|
||||
@pytest.mark.parametrize("before", [None, 0o664, 0o644, 0o600], ids=["no file", "0664", "0644", "0600"])
|
||||
def test_the_saved_account_is_a_file_of_its_user_only(manager, before, umask):
|
||||
if before is not None:
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
manager.file.chmod(before)
|
||||
previous = os.umask(umask)
|
||||
try:
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
finally:
|
||||
os.umask(previous)
|
||||
|
||||
assert manager.file.stat().st_mode & 0o777 == 0o600
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
def test_the_password_is_written_after_the_file_is_of_its_user_only(manager, monkeypatch):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
manager.file.chmod(0o644)
|
||||
seen = []
|
||||
chmod = os.chmod
|
||||
|
||||
def record(path, mode):
|
||||
chmod(path, mode)
|
||||
seen.append((manager.file.stat().st_mode & 0o777, manager.file.read_text()))
|
||||
|
||||
monkeypatch.setattr(os, "chmod", record)
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert seen == [(0o600, "\n".join(SAVED))]
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
def test_a_file_whose_mode_cannot_be_set_is_saved_all_the_same(manager, monkeypatch):
|
||||
manager.file.write_text("\n".join(SAVED))
|
||||
|
||||
def refuse(path, mode):
|
||||
raise PermissionError(1, "Operation not permitted", str(path))
|
||||
|
||||
monkeypatch.setattr(os, "chmod", refuse)
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
|
||||
def test_a_new_file_is_of_its_user_only_from_the_moment_it_is_made(manager, monkeypatch):
|
||||
seen = []
|
||||
monkeypatch.setattr(os, "chmod", lambda path, mode: seen.append(manager.file.stat().st_mode & 0o777))
|
||||
previous = os.umask(0)
|
||||
try:
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
finally:
|
||||
os.umask(previous)
|
||||
|
||||
assert seen == [0o600]
|
||||
assert manager.file.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_a_shorter_account_replaces_a_longer_one_whole(manager):
|
||||
manager.file.write_text("matrix.org\n" + "a" * 200 + "\nthe saved password")
|
||||
|
||||
assert share(manager, account(username="someone", password="a new password")) == 200
|
||||
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
|
||||
@@ -111,15 +111,17 @@ REGISTRY = {
|
||||
("custom-nodes-manager.js", "showStatus",
|
||||
"`Loading missing nodes (${mode}) ...`);"):
|
||||
(NO_DATA, "UI-chosen mode"),
|
||||
("custom-nodes-manager.js", "showStatus",
|
||||
"`Loading alternatives (${mode}) ...`);"):
|
||||
(NO_DATA, "UI-chosen mode"),
|
||||
("custom-nodes-manager.js", "showStatus",
|
||||
"`Loading workflow usage analysis ...`);"):
|
||||
(NO_DATA, "hardcoded"),
|
||||
("custom-nodes-manager.js", "showStatus",
|
||||
"`Loading custom nodes (${mode}) ...`);"):
|
||||
(NO_DATA, "UI-chosen mode"),
|
||||
("custom-nodes-manager.js", "showStatus", "\"Checking updates ...\");"):
|
||||
(NO_DATA, "hardcoded"),
|
||||
("custom-nodes-manager.js", "showStatus",
|
||||
"`Checking updates (${sanitizeHTML(String(done_count))}/${sanitizeHTML(String(total_count))}) ...`);"):
|
||||
(RAW, "the counts come with the cm-check-update event, so this caller escapes them"),
|
||||
("custom-nodes-manager.js", "showMessage",
|
||||
"`To apply the installed/updated/disabled/enabled custom node, please restart "
|
||||
"ComfyUI. And refresh browser.`, \"red\");"):
|
||||
@@ -371,7 +373,6 @@ class HtmlByDesignSinkTest(unittest.TestCase):
|
||||
escaped = {
|
||||
"custom-nodes-manager.js": {
|
||||
'`Failed to get custom node mappings: ${sanitizeHTML(String(res.error))}`);',
|
||||
'`Failed to get alternatives: ${sanitizeHTML(String(res.error))}`);',
|
||||
'`Failed to get workflow data: ${sanitizeHTML(String(result.error))}`);',
|
||||
},
|
||||
"node-usage-analyzer.js": {'sanitizeHTML(String(result.error)));'},
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import pytest
|
||||
|
||||
from test_workflow_nodepack_lookup import EXTENSION, browser, page # noqa: F401 -- fixture
|
||||
|
||||
|
||||
def model(name, model_type, base, save_path, filename, installed):
|
||||
return {"name": name, "type": model_type, "base": base, "save_path": save_path, "description": name,
|
||||
"reference": "https://example.invalid/" + filename, "filename": filename,
|
||||
"url": "https://example.invalid/" + filename, "size": "4.71MB", "installed": installed}
|
||||
|
||||
|
||||
MODELS = [
|
||||
model("FLUX.1 VAE model", "VAE", "FLUX.1", "vae/FLUX1", "ae.safetensors", "False"),
|
||||
model("TAEF1 Decoder", "TAESD", "FLUX.1", "vae_approx", "taef1_decoder.pth", "True"),
|
||||
model("TAESD Decoder", "TAESD", "SD1.x", "vae_approx", "taesd_decoder.pth", "False"),
|
||||
model("RealESRGAN x2", "upscale", "upscale", "default", "RealESRGAN_x2.pth", "False"),
|
||||
model("FLUX.1 dev Q4_0", "unet", "FLUX.1", "diffusion_models/FLUX1", "flux1-dev-Q4_0.gguf", "False"),
|
||||
model("v1-5-pruned-emaonly", "checkpoint", "SD1.5", "checkpoints/SD1.5", "v1-5-pruned-emaonly.safetensors", "True"),
|
||||
]
|
||||
|
||||
|
||||
def node(node_type, *values):
|
||||
return {"type": node_type, "widgets_values": list(values)}
|
||||
|
||||
|
||||
def workflow(*loaders):
|
||||
return [*loaders,
|
||||
node("UNETLoader", "z_image_turbo_bf16.safetensors", "default"),
|
||||
node("KSampler", 42, "fixed", 8, 1, "res_multistep", "simple", 1),
|
||||
node("CLIPTextEncode", "a cute anime girl with gigantic fennec ears and a big fluffy fox tail"),
|
||||
{"type": "VHS_VideoCombine", "widgets_values": {"frame_rate": 8, "filename_prefix": "AnimateDiff"}},
|
||||
{"type": "Reroute"}]
|
||||
|
||||
|
||||
def choose(page, change): # noqa: F811
|
||||
page.evaluate("() => { window.updated = false; manager.grid.onNextUpdated(() => { window.updated = true; }); }")
|
||||
change()
|
||||
page.wait_for_function("window.updated")
|
||||
|
||||
|
||||
def open_models(page, nodes, keywords="", **choices): # noqa: F811
|
||||
page.evaluate("""async ({module, server, nodes}) => {
|
||||
window.server = server;
|
||||
const {app} = await import('/scripts/app.js');
|
||||
app.graph._nodes = nodes;
|
||||
const {setManagerInstance} = await import(new URL('common.js', module).href);
|
||||
setManagerInstance({datasrc_combo: {value: 'cache'}});
|
||||
const {ModelManager} = await import(module);
|
||||
window.manager = new ModelManager(app, null);
|
||||
manager.show();
|
||||
}""", {"module": EXTENSION + "model-manager.js", "server": {"/externalmodel/getlist": {"models": MODELS}},
|
||||
"nodes": nodes})
|
||||
page.wait_for_function("/^[\\d,]+ external models$/.test(document.querySelector('.cmm-manager-status').textContent)")
|
||||
if keywords:
|
||||
choose(page, lambda: page.fill(".cmm-manager-keywords", keywords))
|
||||
for name, value in choices.items():
|
||||
choose(page, lambda: page.select_option(".cmm-manager-" + name, value))
|
||||
return page.evaluate("""() => ({
|
||||
rows: [...document.querySelectorAll('.cmm-manager-grid .tg-body .cmm-node-name')].map(cell => cell.innerText.trim()),
|
||||
status: document.querySelector('.cmm-manager-status').textContent,
|
||||
})""")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value, rows", [
|
||||
("ae.safetensors", ["FLUX.1 VAE model"]),
|
||||
("FLUX1/ae.safetensors", ["FLUX.1 VAE model"]),
|
||||
("FLUX1\\ae.safetensors", ["FLUX.1 VAE model"]),
|
||||
("flux1-dev-Q4_0.gguf", ["FLUX.1 dev Q4_0"]),
|
||||
("qwen_3_4b.safetensors", []),
|
||||
], ids=["file", "file in a folder", "file in a Windows folder", "gguf file", "file not in the list"])
|
||||
def test_in_workflow_lists_the_models_whose_file_the_workflow_loads(page, value, rows): # noqa: F811
|
||||
shown = open_models(page, workflow(node("VAELoader", value)), filter="in_workflow")
|
||||
|
||||
assert shown == {"rows": rows, "status": f"{len(rows)} external models"}
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_in_workflow_keeps_the_marks_of_a_search(page): # noqa: F811
|
||||
shown = open_models(page, workflow(node("VAELoader", "ae.safetensors")), keywords="flux", filter="in_workflow")
|
||||
|
||||
assert shown == {"rows": ["FLUX.1 VAE model"], "status": "1 external models"}
|
||||
page.wait_for_function("document.querySelector('.cmm-manager-grid .tg-body .cmm-node-name mark')")
|
||||
assert page.locator(".cmm-manager-grid .tg-body .cmm-node-name mark").all_text_contents() == ["FLUX"]
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keywords, choices, rows", [
|
||||
("", {"type": "TAESD", "base": "FLUX.1"}, ["TAEF1 Decoder"]),
|
||||
("", {"filter": "installed", "base": "FLUX.1"}, ["TAEF1 Decoder"]),
|
||||
("", {"filter": "not_installed", "type": "TAESD"}, ["TAESD Decoder"]),
|
||||
("", {"filter": "in_workflow", "type": "checkpoint"}, ["v1-5-pruned-emaonly"]),
|
||||
("flux", {"filter": "not_installed", "type": "unet"}, ["FLUX.1 dev Q4_0"]),
|
||||
], ids=["All", "Installed", "Not Installed", "In Workflow", "Not Installed and a search"])
|
||||
def test_a_filter_choice_narrows_the_list_together_with_type_base_and_search(page, keywords, choices, rows): # noqa: F811
|
||||
nodes = workflow(node("VAELoader", "ae.safetensors"), node("CheckpointLoaderSimple", "SD1.5/v1-5-pruned-emaonly.safetensors"))
|
||||
|
||||
shown = open_models(page, nodes, keywords, **choices)
|
||||
|
||||
assert shown == {"rows": rows, "status": f"{len(rows)} external models"}
|
||||
assert page.errors == []
|
||||
@@ -0,0 +1,230 @@
|
||||
import pytest
|
||||
|
||||
from test_install_flags_config import _run_child
|
||||
from test_invalid_installation import PRELUDE
|
||||
|
||||
TAKEN = PRELUDE + '''
|
||||
import io, shutil, traceback, zipfile
|
||||
|
||||
def folders():
|
||||
return sorted(path.relative_to(nodes).as_posix() for path in nodes.rglob('*')
|
||||
if (path.is_dir() or path.is_symlink()) and path.name != '.git')
|
||||
|
||||
def broken_link(folder):
|
||||
(nodes / '.disabled').mkdir(exist_ok=True)
|
||||
os.symlink(nodes / 'gone', nodes / folder)
|
||||
|
||||
def download(url, directory, name):
|
||||
with zipfile.ZipFile(pathlib.Path(directory) / name, 'w') as archive:
|
||||
archive.writestr('__init__.py', '')
|
||||
archive.writestr('pyproject.toml', '[project]\\nname = "comfyui-foo"\\nversion = "1.0.1"\\n')
|
||||
|
||||
cnr_utils.install_node = lambda name, version: SimpleNamespace(version=version, download_url='https://registry.invalid/' + name,
|
||||
status='NodeVersionStatusActive')
|
||||
core.manager_downloader.download_url = core.manager_downloader.basic_download_url = Mock(side_effect=download)
|
||||
|
||||
def clone(url, path, **options):
|
||||
pathlib.Path(path).mkdir()
|
||||
return core.ManagedResult('install-git')
|
||||
|
||||
manager.repo_install = Mock(side_effect=clone)
|
||||
|
||||
def install(version):
|
||||
installed = asyncio.run(manager.install_by_id('comfyui-foo', version, core.DEFAULT_CHANNEL, 'cache', instant_execution=True))
|
||||
return [installed.result, core.manager_downloader.download_url.call_count + manager.repo_install.call_count, folders()]
|
||||
'''
|
||||
|
||||
UNKNOWN, VERSION, NIGHTLY = 'git_url=BAR_URL', "'comfyui-foo', tracking=True", "'comfyui-foo', git_url=FOO_URL"
|
||||
KINDS = pytest.mark.parametrize('name, made_with, disabled, version', [
|
||||
('ComfyUI-Bar', UNKNOWN, '.disabled/ComfyUI-Bar', 'unknown'),
|
||||
('comfyui-foo', VERSION, '.disabled/comfyui-foo@1_0_1', '1.0.1'),
|
||||
('comfyui-foo', NIGHTLY, '.disabled/comfyui-foo@nightly', 'nightly'),
|
||||
], ids=['git_clone_that_no_list_knows', 'registry_version', 'nightly_clone'])
|
||||
|
||||
|
||||
def run(body):
|
||||
return _run_child(TAKEN + body + '\nprint(json.dumps(result))\n')
|
||||
|
||||
|
||||
@KINDS
|
||||
@pytest.mark.parametrize('taken_by', ['pack({disabled!r}, {made_with})', 'broken_link({disabled!r})'], ids=['a_disabled_copy', 'a_broken_link'])
|
||||
def test_disable_fails_when_its_destination_is_taken(taken_by, name, made_with, disabled, version):
|
||||
assert run(f'''
|
||||
pack({name!r}, {made_with})
|
||||
{taken_by.format(disabled=disabled, made_with=made_with)}
|
||||
reload()
|
||||
result = [manager.unified_disable({name!r}, {version == 'unknown'}).result, folders()]
|
||||
''') == [False, ['.disabled', disabled, name]]
|
||||
|
||||
|
||||
@KINDS
|
||||
@pytest.mark.parametrize('taken_by', ['(nodes / {name!r}).mkdir()', 'broken_link({name!r})'],
|
||||
ids=['a_folder_made_since_the_last_scan', 'a_broken_link'])
|
||||
def test_enable_fails_when_its_destination_is_taken(taken_by, name, made_with, disabled, version):
|
||||
assert run(f'''
|
||||
pack({disabled!r}, {made_with})
|
||||
reload()
|
||||
{taken_by.format(name=name)}
|
||||
result = [manager.unified_enable({name!r}, {version!r}).result, folders()]
|
||||
''') == [False, ['.disabled', disabled, name]]
|
||||
|
||||
|
||||
def test_git_clone_that_no_list_knows_is_not_enabled_over_the_enabled_version_of_its_name():
|
||||
assert run(f'''
|
||||
pack('comfyui-foo', {VERSION})
|
||||
pack('.disabled/comfyui-foo', git_url='https://github.com/someone/comfyui-foo')
|
||||
reload()
|
||||
result = [manager.unified_enable('comfyui-foo', 'unknown').result, folders()]
|
||||
''') == [False, ['.disabled', '.disabled/comfyui-foo', 'comfyui-foo']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, taken', [
|
||||
(f"pack('foo', {NIGHTLY})", "(nodes / 'comfyui-foo').mkdir()"),
|
||||
(f"pack('foo', {NIGHTLY})", "os.symlink(nodes / 'foo', nodes / 'comfyui-foo')"),
|
||||
(f"pack('../checkout', {NIGHTLY}); os.symlink(nodes.parent / 'checkout', nodes / 'foo')",
|
||||
"os.symlink(nodes.parent / 'checkout', nodes / 'comfyui-foo')"),
|
||||
], ids=['by_another_folder', 'by_a_link_to_the_enabled_folder', 'by_a_second_link_to_the_folder_of_the_enabled_link'])
|
||||
def test_enable_whose_folder_is_taken_leaves_the_enabled_version_enabled(enabled, taken):
|
||||
assert run(f'''
|
||||
{enabled}
|
||||
pack('.disabled/comfyui-foo@1_0_1', {VERSION})
|
||||
reload()
|
||||
{taken}
|
||||
result = [manager.unified_enable('comfyui-foo', '1.0.1').result, folders()]
|
||||
''') == [False, ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo', 'foo']]
|
||||
|
||||
|
||||
def test_enable_whose_folder_is_taken_fails_when_the_folder_of_the_enabled_version_is_gone():
|
||||
assert run(f'''
|
||||
pack('foo', {NIGHTLY})
|
||||
pack('.disabled/comfyui-foo@1_0_1', {VERSION})
|
||||
reload()
|
||||
shutil.rmtree(nodes / 'foo')
|
||||
(nodes / 'comfyui-foo').mkdir()
|
||||
result = [manager.unified_enable('comfyui-foo', '1.0.1').result, folders()]
|
||||
''') == [False, ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('folder', ['comfyui-foo', 'ComfyUI-Foo'], ids=['in_the_folder_of_its_id', 'in_a_folder_of_another_spelling'])
|
||||
def test_version_takes_the_folder_of_the_enabled_nightly_clone(folder):
|
||||
assert run(f'''
|
||||
pack({folder!r}, {NIGHTLY})
|
||||
pack('.disabled/comfyui-foo@1_0_1', {VERSION})
|
||||
reload()
|
||||
result = [manager.unified_enable('comfyui-foo', '1.0.1').result, folders()]
|
||||
''') == [True, ['.disabled', '.disabled/comfyui-foo@nightly', 'comfyui-foo']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, taken, disabled, act, refused', [
|
||||
(NIGHTLY, '.disabled/comfyui-foo@nightly', f"'.disabled/comfyui-foo@1_0_1', {VERSION}", "manager.unified_enable('comfyui-foo', '1.0.1').result", False),
|
||||
(VERSION, '.disabled/comfyui-foo@1_0_1', f"'.disabled/comfyui-foo@nightly', {NIGHTLY}", "manager.unified_enable('comfyui-foo', 'nightly').result", False),
|
||||
(NIGHTLY, '.disabled/comfyui-foo@nightly', None, "install('1.0.1')[:2]", [False, 0]),
|
||||
(VERSION, '.disabled/comfyui-foo@1_0_1', None, "install('nightly')[:2]", [False, 0]),
|
||||
], ids=['enable_of_a_version', 'enable_of_the_nightly_clone', 'install_of_a_version', 'install_of_the_nightly_clone'])
|
||||
def test_nodepack_does_not_take_the_place_of_an_enabled_one_that_cannot_be_disabled(enabled, taken, disabled, act, refused):
|
||||
done, before, after = run(f'''
|
||||
for folder in ('ComfyUI-Foo', {taken!r}):
|
||||
pack(folder, {enabled})
|
||||
if {disabled is not None}:
|
||||
pack({disabled})
|
||||
reload()
|
||||
before = folders()
|
||||
result = [{act}, before, folders()]
|
||||
''')
|
||||
assert [done, after] == [refused, before]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, disabled, act, done', [
|
||||
(NIGHTLY, f"'.disabled/comfyui-foo@1_0_1', {VERSION}", "manager.unified_enable('comfyui-foo', '1.0.1').result", [True, ['.disabled', 'comfyui-foo']]),
|
||||
(VERSION, f"'.disabled/comfyui-foo@nightly', {NIGHTLY}", "manager.unified_enable('comfyui-foo', 'nightly').result", [True, ['.disabled', 'comfyui-foo']]),
|
||||
(NIGHTLY, None, "install('1.0.1')[:2]", [[True, 1], ['comfyui-foo']]),
|
||||
(VERSION, None, "install('nightly')[:2]", [[True, 1], ['comfyui-foo']]),
|
||||
], ids=['enable_of_a_version', 'enable_of_the_nightly_clone', 'install_of_a_version', 'install_of_the_nightly_clone'])
|
||||
def test_nodepack_takes_the_place_of_an_enabled_one_whose_folder_is_gone(enabled, disabled, act, done):
|
||||
assert run(f'''
|
||||
pack('ComfyUI-Foo', {enabled})
|
||||
if {disabled is not None}:
|
||||
pack({disabled})
|
||||
reload()
|
||||
shutil.rmtree(nodes / 'ComfyUI-Foo')
|
||||
result = [{act}, folders()]
|
||||
''') == done
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, disabled, version', [
|
||||
(NIGHTLY, "pack('.disabled/comfyui-foo@1_0_0', 'comfyui-foo', version='1.0.0', tracking=True)", '1.0.1'),
|
||||
(NIGHTLY, '', '1.0.1'),
|
||||
(VERSION, '', 'nightly'),
|
||||
], ids=['of_a_version_that_enables_a_disabled_one', 'of_a_version_that_is_downloaded', 'of_the_nightly_clone'])
|
||||
def test_install_whose_folder_is_taken_leaves_the_enabled_one_enabled(enabled, disabled, version):
|
||||
done, before = run(f'''
|
||||
pack('foo', {enabled})
|
||||
{disabled}
|
||||
reload()
|
||||
(nodes / 'comfyui-foo').mkdir()
|
||||
before = folders()
|
||||
result = [install({version!r}), before]
|
||||
''')
|
||||
assert done == [False, 0, before]
|
||||
|
||||
|
||||
def test_version_is_not_switched_when_the_disabled_one_cannot_be_enabled():
|
||||
assert run('''
|
||||
pack('comfyui-foo', git_url='https://github.com/someone/comfyui-foo')
|
||||
pack('.disabled/comfyui-foo@1_0_0', 'comfyui-foo', version='1.0.0', tracking=True)
|
||||
reload()
|
||||
result = install('1.0.1')
|
||||
''') == [False, 0, ['.disabled', '.disabled/comfyui-foo@1_0_0', 'comfyui-foo']]
|
||||
|
||||
|
||||
def test_page_is_told_that_a_disable_failed_and_the_terminal_why():
|
||||
assert run(f'''
|
||||
for folder in ('ComfyUI-Bar', '.disabled/ComfyUI-Bar'):
|
||||
pack(folder, {UNKNOWN})
|
||||
reload()
|
||||
logged = []
|
||||
handler = logging.Handler()
|
||||
handler.emit = lambda record: logged.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
disable = server_function('do_disable', core=core, logging=logging, traceback=traceback)
|
||||
result = [asyncio.run(disable(('the row', 'ComfyUI-Bar', True))), any(str(nodes / '.disabled' / 'ComfyUI-Bar') in line for line in logged), folders()]
|
||||
''') == ["Failed to disable: 'ComfyUI-Bar'", True, ['.disabled', '.disabled/ComfyUI-Bar', 'ComfyUI-Bar']]
|
||||
|
||||
|
||||
def test_page_is_told_why_an_enable_failed_and_the_terminal_too():
|
||||
assert run(f'''
|
||||
pack('.disabled/comfyui-foo@1_0_1', {VERSION})
|
||||
reload()
|
||||
(nodes / 'comfyui-foo').mkdir()
|
||||
sent, logged = [], []
|
||||
handler = logging.Handler()
|
||||
handler.emit = lambda record: logged.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
enable = server_function(
|
||||
'_queue_node_install', core=core, logging=logging, _reject_non_json_content_type=lambda request: None,
|
||||
is_allowed_security_level=lambda level: True, web=SimpleNamespace(Response=lambda status=200, text=None: [status, text]),
|
||||
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=lambda name, data: sent.append(data.get('nodepack_result')))))
|
||||
|
||||
async def row():
|
||||
return {{'id': 'comfyui-foo', 'version': '1.0.1', 'selected_version': '1.0.1', 'skip_post_install': True, 'ui_id': 'the row'}}
|
||||
|
||||
reason = 'Destination already exists: ' + str(nodes / 'comfyui-foo')
|
||||
result = [asyncio.run(enable(SimpleNamespace(json=row), 'install')) == [400, reason], any(reason in line for line in logged), sent, folders()]
|
||||
''') == [True, True, [], ['.disabled', '.disabled/comfyui-foo@1_0_1', 'comfyui-foo']]
|
||||
|
||||
|
||||
def test_cm_cli_install_reports_an_enable_that_failed():
|
||||
assert run(f'''
|
||||
pack('.disabled/ComfyUI-Bar', {UNKNOWN})
|
||||
reload()
|
||||
(nodes / 'ComfyUI-Bar').mkdir()
|
||||
out = io.StringIO()
|
||||
install_node = cm_cli_function('install_node', {{
|
||||
'asyncio': asyncio, 'sys': sys, '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)}})
|
||||
try:
|
||||
ended = install_node('ComfyUI-Bar@unknown', cnt_msg='1/1', exit_on_fail=True)
|
||||
except SystemExit as exit:
|
||||
ended = exit.code
|
||||
result = [ended, '[ ENABLED ]' in out.getvalue(), folders()]
|
||||
''') == [1, False, ['.disabled', '.disabled/ComfyUI-Bar', 'ComfyUI-Bar']]
|
||||
@@ -5,6 +5,10 @@ local CONNECT proxy that hands the tunnel for github.com:443 to a local HTTPS se
|
||||
holds a "github.com" certificate from a throwaway CA: a machine in the middle, unless the
|
||||
case trusts that CA through SSL_CERT_FILE. Nothing leaves 127.0.0.1. A child is needed
|
||||
because aiohttp builds its verifying SSL context when it is imported.
|
||||
|
||||
The last cases fetch a list through `get_data`, the same way and from a channel without
|
||||
TLS. Both fetches are also held to raising no deprecation warning from a line of the
|
||||
Manager (#2281).
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
@@ -17,10 +21,12 @@ import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from warnings import catch_warnings, simplefilter
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
|
||||
from manager_test_utils import GLOB_DIR, load_manager_util
|
||||
|
||||
@@ -30,6 +36,9 @@ NOTICE_HTML = ('<div class="markdown-body"><p>Served by <b>the test server</b> '
|
||||
UNAVAILABLE = "Unable to retrieve Notice"
|
||||
TUNNEL = "CONNECT github.com:443 HTTP/1.1"
|
||||
OTHER_HOST = "notice-test.example"
|
||||
LIST_PATH = "/a-channel/model-list.json"
|
||||
LIST = {"models": [{"name": "served by the test server"}]}
|
||||
MANAGER_FILES = ("manager_server.py", "manager_util.py")
|
||||
|
||||
OPENSSL_CONFIG = """
|
||||
[req]
|
||||
@@ -70,6 +79,17 @@ def load_get_notice(bypass_ssl):
|
||||
return namespace["get_notice"]
|
||||
|
||||
|
||||
def load_get_data(bypass_ssl):
|
||||
manager_util = load_manager_util()
|
||||
manager_util.bypass_ssl = bypass_ssl
|
||||
return manager_util.get_data
|
||||
|
||||
|
||||
def manager_deprecations(caught):
|
||||
return [f"{os.path.basename(w.filename)}: {w.message}" for w in caught
|
||||
if issubclass(w.category, DeprecationWarning) and os.path.basename(w.filename) in MANAGER_FILES]
|
||||
|
||||
|
||||
async def _pipe(reader, writer):
|
||||
try:
|
||||
while data := await reader.read(65536):
|
||||
@@ -79,13 +99,18 @@ async def _pipe(reader, writer):
|
||||
writer.close()
|
||||
|
||||
|
||||
async def fetch_notice(certdir, host, bypass_ssl, proxy_mode):
|
||||
"""Child process: what `get_notice` answers and logs, and the tunnels the proxy was asked for."""
|
||||
async def fetch_in_child(certdir, host, bypass_ssl, proxy_mode, what):
|
||||
"""Child process: what `get_notice` answers and logs, or what `get_data` returns, and the tunnels
|
||||
the proxy was asked for."""
|
||||
async def notice_page(request):
|
||||
return web.Response(text=NOTICE_HTML, content_type="text/html")
|
||||
|
||||
async def list_file(request):
|
||||
return web.json_response(LIST)
|
||||
|
||||
upstream = web.Application()
|
||||
upstream.router.add_get(NOTICE_PATH, notice_page)
|
||||
upstream.router.add_get(LIST_PATH, list_file)
|
||||
runner = web.AppRunner(upstream)
|
||||
await runner.setup()
|
||||
server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
|
||||
@@ -126,11 +151,20 @@ async def fetch_notice(certdir, host, bypass_ssl, proxy_mode):
|
||||
handler.emit = lambda record: record.name == "root" and warnings.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
|
||||
response = await load_get_notice(bypass_ssl)(None)
|
||||
with catch_warnings(record=True) as caught:
|
||||
simplefilter("always")
|
||||
if what == "list":
|
||||
try:
|
||||
result = {"list": await load_get_data(bypass_ssl)(f"https://github.com{LIST_PATH}", silent=True)}
|
||||
except aiohttp.ClientError as e:
|
||||
result = {"error": type(e).__name__}
|
||||
else:
|
||||
response = await load_get_notice(bypass_ssl)(None)
|
||||
result = {"status": response.status, "text": response.text}
|
||||
answered.set()
|
||||
proxy.close()
|
||||
await runner.cleanup()
|
||||
return {"status": response.status, "text": response.text, "tunnels": tunnels, "warnings": warnings}
|
||||
return {**result, "tunnels": tunnels, "warnings": warnings, "deprecations": manager_deprecations(caught)}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -156,16 +190,16 @@ def certdir(tmp_path_factory):
|
||||
return path
|
||||
|
||||
|
||||
def fetch(certdir, host="github.com", trust_ca=False, bypass_ssl=False, proxy_mode="tunnel"):
|
||||
def fetch(certdir, host="github.com", trust_ca=False, bypass_ssl=False, proxy_mode="tunnel", what="notice"):
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if not key.lower().endswith("_proxy") and key not in ("SSL_CERT_FILE", "SSL_CERT_DIR")}
|
||||
env["__COMFYUI_DESKTOP_VERSION__"] = "test"
|
||||
if trust_ca:
|
||||
env["SSL_CERT_FILE"] = str(certdir / "ca.pem")
|
||||
child = subprocess.run(
|
||||
[sys.executable, __file__, str(certdir), host, str(int(bypass_ssl)), proxy_mode],
|
||||
[sys.executable, __file__, str(certdir), host, str(int(bypass_ssl)), proxy_mode, what],
|
||||
env=env, capture_output=True, text=True, timeout=60)
|
||||
assert child.returncode == 0, "get_notice raised instead of answering:\n" + child.stderr[-2000:]
|
||||
assert child.returncode == 0, "the fetch raised instead of answering:\n" + child.stderr[-2000:]
|
||||
return json.loads(child.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
@@ -190,6 +224,7 @@ def test_bypass_ssl_accepts_the_untrusted_certificate(certdir):
|
||||
assert result["status"] == 200
|
||||
assert "<b>the test server</b>" in result["text"]
|
||||
assert result["warnings"] == []
|
||||
assert result["deprecations"] == []
|
||||
|
||||
|
||||
def test_trusted_certificate_for_another_host_is_rejected(certdir):
|
||||
@@ -222,5 +257,58 @@ def test_failed_fetch_answers_with_the_unavailable_notice(certdir, proxy_mode, e
|
||||
assert_unavailable(result, error)
|
||||
|
||||
|
||||
def test_list_from_an_untrusted_certificate_is_rejected(certdir):
|
||||
result = fetch(certdir, what="list")
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert result["error"] == "ClientConnectorCertificateError"
|
||||
|
||||
|
||||
def test_list_from_a_trusted_certificate_for_another_host_is_rejected(certdir):
|
||||
result = fetch(certdir, host=OTHER_HOST, trust_ca=True, what="list")
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert result["error"] == "ClientConnectorCertificateError"
|
||||
|
||||
|
||||
def test_list_from_a_ca_trusted_through_ssl_cert_file_is_accepted(certdir):
|
||||
result = fetch(certdir, trust_ca=True, what="list")
|
||||
|
||||
assert result["list"] == LIST
|
||||
assert result["deprecations"] == []
|
||||
|
||||
|
||||
def test_bypass_ssl_accepts_the_list_from_the_untrusted_certificate(certdir):
|
||||
result = fetch(certdir, bypass_ssl=True, what="list")
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert result["list"] == LIST
|
||||
assert result["deprecations"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bypass_ssl", [False, True], ids=["certificates checked", "bypass_ssl"])
|
||||
def test_list_from_a_channel_without_tls_raises_no_deprecation_warning(bypass_ssl, monkeypatch):
|
||||
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
|
||||
async def fetch_list():
|
||||
async def list_file(request):
|
||||
return web.json_response(LIST)
|
||||
|
||||
channel = web.Application()
|
||||
channel.router.add_get(LIST_PATH, list_file)
|
||||
server = TestServer(channel)
|
||||
await server.start_server()
|
||||
try:
|
||||
with catch_warnings(record=True) as caught:
|
||||
simplefilter("always")
|
||||
fetched = await load_get_data(bypass_ssl)(str(server.make_url(LIST_PATH)), silent=True)
|
||||
return fetched, manager_deprecations(caught)
|
||||
finally:
|
||||
await server.close()
|
||||
|
||||
assert asyncio.run(fetch_list()) == (LIST, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(asyncio.run(fetch_notice(sys.argv[1], sys.argv[2], sys.argv[3] == "1", sys.argv[4]))))
|
||||
print(json.dumps(asyncio.run(fetch_in_child(sys.argv[1], sys.argv[2], sys.argv[3] == "1", sys.argv[4], sys.argv[5]))))
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import ast
|
||||
import configparser
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
LEVELS = ["strong", "normal", "normal-", "weak"]
|
||||
SOURCE = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
GATE = next(node for node in ast.parse(SOURCE).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "is_allowed_security_level")
|
||||
|
||||
|
||||
def allowed(needed, security_level, loopback, has_system_user_api):
|
||||
namespace = {
|
||||
"is_local_mode": loopback,
|
||||
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level}),
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
|
||||
}
|
||||
exec(compile(ast.Module(body=[GATE], type_ignores=[]), "manager_server.py", "exec"), namespace)
|
||||
return namespace["is_allowed_security_level"](needed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS + ["", "a level that Manager does not know"])
|
||||
@pytest.mark.parametrize("needed", ["middle", "high", "block", "low", ""])
|
||||
def test_an_old_comfyui_is_refused_at_every_level_of_config_ini(needed, security_level, loopback):
|
||||
assert allowed(needed, security_level, loopback, has_system_user_api=False) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_with_the_system_user_api_the_level_of_config_ini_decides(security_level, loopback):
|
||||
api = dict(security_level=security_level, loopback=loopback, has_system_user_api=True)
|
||||
assert allowed("block", **api) is False
|
||||
assert allowed("middle", **api) is (security_level != "strong")
|
||||
assert allowed("high", **api) is (security_level == "weak" or security_level == "normal-" and loopback)
|
||||
assert allowed("low", **api) is True
|
||||
|
||||
|
||||
CHILD = textwrap.dedent(
|
||||
"""
|
||||
import sys, types, tempfile, os, json
|
||||
tmp = tempfile.mkdtemp(prefix="cm_old_comfyui_")
|
||||
stub = types.ModuleType("folder_paths")
|
||||
stub.get_user_directory = lambda: tmp
|
||||
if {has_system_user_api!r}:
|
||||
stub.get_system_user_directory = lambda *a, **k: os.path.join(tmp, "sysuser")
|
||||
sys.modules["folder_paths"] = stub
|
||||
sys.path.insert(0, {glob_dir!r})
|
||||
import manager_core
|
||||
path = os.path.join(tmp, "config.ini")
|
||||
manager_core.manager_config_path = path
|
||||
manager_core.cached_config = None
|
||||
written = {written!r}
|
||||
if written is not None:
|
||||
with open(path, "w") as f:
|
||||
f.write(written)
|
||||
read = manager_core.get_config()["security_level"]
|
||||
for key, value in {changes!r}:
|
||||
manager_core.get_config()[key] = value
|
||||
manager_core.write_config()
|
||||
with open(path) as f:
|
||||
print(json.dumps({{"read": read, "file": f.read()}}))
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def config_after_a_write(has_system_user_api, written, changes=()):
|
||||
script = CHILD.format(has_system_user_api=has_system_user_api, glob_dir=str(GLOB_DIR), written=written, changes=list(changes))
|
||||
done = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=180)
|
||||
assert done.returncode == 0, done.stderr[-2000:]
|
||||
result = json.loads(done.stdout.strip().splitlines()[-1])
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config.read_string(result["file"])
|
||||
return result["read"], dict(config["default"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
def test_the_first_config_ini_is_written_with_the_default_level(has_system_user_api):
|
||||
read, written = config_after_a_write(has_system_user_api, None)
|
||||
assert read == "normal"
|
||||
assert written["security_level"] == "normal"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_the_level_of_config_ini_is_read_and_kept_as_the_user_wrote_it(security_level, has_system_user_api):
|
||||
text = f"[default]\nsecurity_level = {security_level}\ndb_mode = cache\n"
|
||||
read, written = config_after_a_write(has_system_user_api, text, changes=[("db_mode", "local")])
|
||||
assert read == security_level
|
||||
assert written["security_level"] == security_level
|
||||
assert written["db_mode"] == "local"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
def test_a_config_ini_without_a_level_is_not_given_one_by_another_setting(has_system_user_api):
|
||||
read, written = config_after_a_write(has_system_user_api, "[default]\ndb_mode = cache\n", changes=[("db_mode", "local")])
|
||||
assert read == "normal"
|
||||
assert "security_level" not in written
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
def test_a_config_ini_that_cannot_be_parsed_is_rewritten_with_the_default_level(has_system_user_api):
|
||||
read, written = config_after_a_write(has_system_user_api, "security_level = weak\n")
|
||||
assert read == "normal"
|
||||
assert written["security_level"] == "normal"
|
||||
@@ -0,0 +1,179 @@
|
||||
import ast
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
SERVED = {
|
||||
("POST", "/manager/queue/update_comfyui"), ("POST", "/manager/queue/start"), ("POST", "/manager/queue/reset"),
|
||||
("GET", "/manager/queue/status"), ("GET", "/manager/version"), ("GET", "/manager/notice"),
|
||||
("GET", "/manager/startup_alerts"),
|
||||
}
|
||||
OTHERS = [("GET", "/system_stats", "server"), ("POST", "/prompt", "server"), ("POST", "/a_pack/run", "a_pack.routes"),
|
||||
("GET", "/manager/of_another_pack", "another_manager")]
|
||||
PREFIXES = ["", "/api"]
|
||||
|
||||
|
||||
def routes_of(path):
|
||||
found = []
|
||||
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
|
||||
for decorator in getattr(node, "decorator_list", []):
|
||||
if isinstance(decorator, ast.Call) and ast.unparse(decorator.func).endswith(("routes.get", "routes.post")):
|
||||
found.append((decorator.func.attr.upper(), decorator.args[0].value, path.stem, node.name))
|
||||
return found
|
||||
|
||||
|
||||
ROUTES = [route for path in sorted(GLOB_DIR.glob("*.py")) for route in routes_of(path)]
|
||||
REQUESTS = [(prefix, method, path) for prefix in PREFIXES for method, path, _, _ in ROUTES]
|
||||
|
||||
|
||||
def serve(has_system_user_api):
|
||||
ran = []
|
||||
|
||||
def recording(method, path, module):
|
||||
async def handler(request):
|
||||
ran.append((method, path))
|
||||
return web.Response(text="served")
|
||||
|
||||
handler.__module__ = module
|
||||
return handler
|
||||
|
||||
handlers = {(module, name): recording(method, path, module) for method, path, module, name in ROUTES}
|
||||
|
||||
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if getattr(node, "name", None) in ("security_403_response", "serve_only_comfyui_update")
|
||||
or isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "COMFYUI_UPDATE_HANDLERS"
|
||||
or isinstance(node, ast.If) and "middlewares" in ast.unparse(node)]
|
||||
middlewares = []
|
||||
namespace = {
|
||||
"web": web, "manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(app=SimpleNamespace(middlewares=middlewares))),
|
||||
"threading": SimpleNamespace(Thread=lambda target: SimpleNamespace(start=lambda: None)),
|
||||
**{name: handler for (module, name), handler in handlers.items() if module == "manager_server"},
|
||||
}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "manager_server.py", "exec"), namespace)
|
||||
|
||||
app = web.Application(middlewares=middlewares)
|
||||
for prefix in PREFIXES:
|
||||
for method, path, module, name in ROUTES:
|
||||
app.router.add_route(method, prefix + path, handlers[module, name])
|
||||
for method, path, module in OTHERS:
|
||||
app.router.add_route(method, prefix + path, recording(method, path, module))
|
||||
return app, ran, middlewares == [namespace.get("serve_only_comfyui_update")]
|
||||
|
||||
|
||||
def answers(has_system_user_api, requests):
|
||||
app, ran, added = serve(has_system_user_api)
|
||||
|
||||
async def run():
|
||||
async with TestClient(TestServer(app)) as client:
|
||||
return [(response.status, await response.text())
|
||||
for response in [await client.request(method, url) for method, url in requests]]
|
||||
|
||||
return asyncio.run(run()), ran, added
|
||||
|
||||
|
||||
def url(path):
|
||||
return path.replace("{node_name}", "a-pack")
|
||||
|
||||
|
||||
OUTDATED = (403, '{"error": "comfyui_outdated"}')
|
||||
|
||||
|
||||
def test_the_routes_are_found():
|
||||
found = {(method, path) for method, path, _, _ in ROUTES}
|
||||
|
||||
assert len(ROUTES) >= 50
|
||||
assert SERVED <= found
|
||||
assert {("POST", "/manager/queue/install"), ("POST", "/manager/reboot"), ("GET", "/customnode/getlist"),
|
||||
("POST", "/snapshot/restore"), ("GET", "/snapshot/getlist"), ("POST", "/manager/share"),
|
||||
("GET", "/manager/get_matrix_auth"), ("GET", "/customnode/versions/{node_name}")} <= found
|
||||
|
||||
|
||||
def test_every_route_is_in_a_file_that_the_middleware_knows():
|
||||
assert {module for _, _, module, _ in ROUTES} == {"manager_server", "share_3rdparty"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefix, method, path", REQUESTS, ids=[f"{method} {prefix}{path}" for prefix, method, path in REQUESTS])
|
||||
def test_on_an_older_comfyui_only_the_update_of_comfyui_is_served(prefix, method, path):
|
||||
(answer,), ran, added = answers(False, [(method, prefix + url(path))])
|
||||
|
||||
assert added
|
||||
if (method, path) in SERVED:
|
||||
assert answer == (200, "served")
|
||||
assert ran == [(method, path)]
|
||||
else:
|
||||
assert answer == OUTDATED
|
||||
assert ran == []
|
||||
|
||||
|
||||
def test_with_the_system_user_api_every_route_is_served():
|
||||
requests = [(method, prefix + url(path)) for prefix, method, path in REQUESTS]
|
||||
|
||||
got, ran, added = answers(True, requests)
|
||||
|
||||
assert not added
|
||||
assert got == [(200, "served")] * len(REQUESTS)
|
||||
assert len(ran) == len(REQUESTS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
@pytest.mark.parametrize("prefix", PREFIXES, ids=["without a prefix", "under /api"])
|
||||
def test_routes_that_are_not_of_manager_are_served(prefix, has_system_user_api):
|
||||
got, ran, _ = answers(has_system_user_api, [(method, prefix + path) for method, path, _ in OTHERS])
|
||||
|
||||
assert got == [(200, "served")] * len(OTHERS)
|
||||
assert ran == [(method, path) for method, path, _ in OTHERS]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, path, status", [
|
||||
("GET", "/manager/no_such_route", 404), ("GET", "/no_such_route", 404), ("GET", "/api/api/manager/version", 404),
|
||||
("GET", "/manager/queue/start", 405), ("POST", "/api/manager/version", 405), ("DELETE", "/manager/queue/update_comfyui", 405),
|
||||
], ids=["an unknown route of that prefix", "an unknown route", "the prefix twice", "GET for a served POST",
|
||||
"POST for a served GET", "another method"])
|
||||
def test_on_an_older_comfyui_an_unknown_request_is_answered_as_before(method, path, status):
|
||||
(answer,), ran, _ = answers(False, [(method, path)])
|
||||
|
||||
assert answer[0] == status
|
||||
assert ran == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, served_as", [
|
||||
("/manager/queue/update_comfyui?x=1", "/manager/queue/update_comfyui"), ("/api/manager/queue/start?mode=cache", "/manager/queue/start"),
|
||||
("/manager/queue/./start", "/manager/queue/start"),
|
||||
("/manager/queue/update_comfyui/", None), ("/manager/queue/install?x=/manager/queue/start", None),
|
||||
("/api/manager/queue/install?x=/api/manager/queue/start", None),
|
||||
("/manager/queue//start", None), ("/manager/queue/update_all", None), ("/api/manager/queue/update", None),
|
||||
("/manager/queue/install", None),
|
||||
], ids=["a query", "a query on start", "a dot segment", "a trailing slash", "a served path in the query",
|
||||
"a served path in the query under /api", "a doubled slash", "update_all", "update", "install"])
|
||||
def test_on_an_older_comfyui_a_path_is_served_only_as_a_route_that_updates_comfyui(path, served_as):
|
||||
(answer,), ran, _ = answers(False, [("POST", path)])
|
||||
|
||||
if served_as:
|
||||
assert answer == (200, "served")
|
||||
assert ran == [("POST", served_as)]
|
||||
else:
|
||||
assert answer[0] in (403, 404)
|
||||
assert ran == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
def test_the_lists_are_fetched_at_the_start_only_with_the_system_user_api(has_system_user_api):
|
||||
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
statements = [node for node in ast.parse(source).body if isinstance(node, (ast.If, ast.Expr)) and "default_cache_update" in ast.unparse(node)]
|
||||
assert len(statements) == 1
|
||||
started = []
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), "manager_server.py", "exec"), {
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
|
||||
"threading": SimpleNamespace(Thread=lambda target: SimpleNamespace(start=lambda: started.append(target))),
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(app=SimpleNamespace(middlewares=[]))),
|
||||
"serve_only_comfyui_update": None,
|
||||
})
|
||||
|
||||
assert len(started) == (1 if has_system_user_api else 0)
|
||||
@@ -0,0 +1,98 @@
|
||||
import ast
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from manager_test_utils import GLOB_DIR, load_manager_util
|
||||
|
||||
MANAGER_UTIL = load_manager_util()
|
||||
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
|
||||
LISTED = "a-package==2.0\nanother==1.5 --index-url https://index.example/simple\n"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fix_broken(monkeypatch, tmp_path):
|
||||
def run(manager_files_path, installed):
|
||||
packages = {"torchvision": "0.20.1", "torchaudio": "2.5.1", "comfyui_frontend_package": "1.30.6", **installed}
|
||||
pip_list = "Package Version\n------- -------\n" + "".join(f"{name} {version}\n" for name, version in packages.items())
|
||||
commands = []
|
||||
|
||||
def check_output(cmd, **_):
|
||||
if cmd[-1] == "list":
|
||||
return pip_list
|
||||
commands.append(" ".join(cmd[3:]))
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr(MANAGER_UTIL, "make_pip_cmd", lambda cmd: ["python", "-m", "pip", *cmd])
|
||||
monkeypatch.setattr(MANAGER_UTIL, "subprocess", SimpleNamespace(
|
||||
check_output=check_output, CalledProcessError=subprocess.CalledProcessError))
|
||||
monkeypatch.setattr(MANAGER_UTIL, "pip_map", None)
|
||||
(tmp_path / "pip_auto_fix.list").write_text(LISTED, encoding="utf-8")
|
||||
|
||||
previous = MANAGER_UTIL.get_installed_packages(True)
|
||||
MANAGER_UTIL.PIPFixer(previous, str(tmp_path), manager_files_path and str(tmp_path)).fix_broken()
|
||||
return commands
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def test_with_a_data_directory_the_listed_packages_are_restored(fix_broken):
|
||||
assert fix_broken(True, {"a-package": "1.0"}) == [
|
||||
"install a-package==2.0", "install another==1.5 --index-url https://index.example/simple"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("installed", [{"a-package": "1.0"}, {}, {"a-package": "2.0", "another": "1.5"}],
|
||||
ids=["another version installed", "not installed", "as listed"])
|
||||
def test_without_a_data_directory_nothing_is_restored_from_a_list(fix_broken, installed):
|
||||
assert fix_broken(None, installed) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data_directory", [True, None], ids=["with a data directory", "without one"])
|
||||
def test_a_repair_that_uses_no_list_runs_either_way(fix_broken, data_directory):
|
||||
assert fix_broken(data_directory, {"comfy": "0.0.1", "a-package": "2.0", "another": "1.5"}) == ["uninstall comfy"]
|
||||
|
||||
|
||||
def directory_given_at_start(has_system_user_api):
|
||||
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.Assign) and "PIPFixer(" in ast.unparse(node)]
|
||||
assert len(statements) == 1
|
||||
given = []
|
||||
namespace = {
|
||||
"manager_util": SimpleNamespace(get_installed_packages=dict, PIPFixer=lambda previous, comfy_path, path: given.append(path)),
|
||||
"comfy_path": "comfyui", "manager_files_path": "the data directory", "_has_system_user_api": has_system_user_api,
|
||||
}
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
|
||||
return given
|
||||
|
||||
|
||||
def test_a_start_with_the_system_user_api_gives_the_data_directory():
|
||||
assert directory_given_at_start(True) == ["the data directory"]
|
||||
|
||||
|
||||
def test_a_start_on_an_older_comfyui_gives_no_data_directory():
|
||||
assert directory_given_at_start(False) == [None]
|
||||
|
||||
|
||||
def directories_given_by_the_server(has_system_user_api):
|
||||
path = GLOB_DIR / "manager_core.py"
|
||||
statements = [node for node in ast.walk(ast.parse(path.read_text(encoding="utf-8")))
|
||||
if isinstance(node, ast.Assign) and "PIPFixer(" in ast.unparse(node)]
|
||||
given = []
|
||||
namespace = {
|
||||
"manager_util": SimpleNamespace(get_installed_packages=dict, PIPFixer=lambda previous, comfy_path, path: given.append(path)),
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
|
||||
"comfy_path": "comfyui", "manager_files_path": "the data directory",
|
||||
}
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), str(path), "exec"), namespace)
|
||||
return given
|
||||
|
||||
|
||||
def test_an_install_with_the_system_user_api_gives_the_data_directory():
|
||||
assert directories_given_by_the_server(True) == ["the data directory", "the data directory"]
|
||||
|
||||
|
||||
def test_an_install_on_an_older_comfyui_gives_no_data_directory():
|
||||
assert directories_given_by_the_server(False) == [None, None]
|
||||
@@ -48,7 +48,7 @@ xformers 0.0.30+cu126
|
||||
@pytest.fixture
|
||||
def set_lists(monkeypatch):
|
||||
"""Replace the `pip list` output and return a setter for the two lists."""
|
||||
monkeypatch.setattr(MANAGER_UTIL, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
|
||||
monkeypatch.setattr(MANAGER_UTIL, 'get_pip_cmd', lambda force_uv=False: ['python', '-m', 'pip'])
|
||||
monkeypatch.setattr(MANAGER_UTIL, 'subprocess', SimpleNamespace(
|
||||
check_output=lambda *args, **kwargs: PIP_LIST, CalledProcessError=subprocess.CalledProcessError))
|
||||
monkeypatch.setattr(MANAGER_UTIL, 'pip_map', None)
|
||||
@@ -77,7 +77,7 @@ def load_prestartup(**module_globals):
|
||||
pytest.skip('MANAGER_GLOB_DIR points at a glob directory without prestartup_script.py beside it')
|
||||
return load_functions(
|
||||
PRESTARTUP_SCRIPT,
|
||||
{'is_installed', 'remap_pip_package', 'execute_lazy_install_script', 'execute_startup_script'},
|
||||
{'is_installed', 'execute_lazy_install_script', 'execute_startup_script'},
|
||||
**module_globals)
|
||||
|
||||
|
||||
@@ -392,7 +392,7 @@ from types import SimpleNamespace
|
||||
import cm_global, manager_util
|
||||
|
||||
PIP_LIST = {PIP_LIST!r}
|
||||
manager_util.make_pip_cmd = lambda cmd: ['python', '-m', 'pip', *cmd]
|
||||
manager_util.get_pip_cmd = lambda force_uv=False: ['python', '-m', 'pip']
|
||||
manager_util.subprocess = SimpleNamespace(
|
||||
check_output=lambda *args, **kwargs: PIP_LIST, CalledProcessError=subprocess.CalledProcessError)
|
||||
manager_util.pip_map = None
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
|
||||
OVERRIDES = [{"a-package": "another-package==2.0"}, {"a-package": "a-package==1.0", "torch": "torch==2.5.1"}, {}]
|
||||
|
||||
|
||||
def overrides_after_start(has_system_user_api, path):
|
||||
body = ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
first = next(index for index, node in enumerate(body)
|
||||
if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "cm_global.pip_overrides")
|
||||
statements = body[first:first + 2]
|
||||
assert isinstance(statements[1], ast.If) and "manager_pip_overrides_path" in ast.unparse(statements[1].test)
|
||||
cm_global = SimpleNamespace()
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), {
|
||||
"cm_global": cm_global, "os": os, "json": json,
|
||||
"manager_pip_overrides_path": str(path), "_has_system_user_api": has_system_user_api,
|
||||
})
|
||||
return cm_global.pip_overrides
|
||||
|
||||
|
||||
@pytest.mark.parametrize("overrides", OVERRIDES, ids=["one package", "two packages", "empty"])
|
||||
def test_with_the_system_user_api_the_file_is_read(tmp_path, overrides):
|
||||
path = tmp_path / "pip_overrides.json"
|
||||
path.write_text(json.dumps(overrides), encoding="utf-8")
|
||||
|
||||
assert overrides_after_start(True, path) == overrides
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", [json.dumps(OVERRIDES[0]), json.dumps(OVERRIDES[1]), "{}", "", "not json"],
|
||||
ids=["one package", "two packages", "empty", "an empty file", "not json"])
|
||||
def test_on_an_older_comfyui_the_file_is_not_read(tmp_path, text):
|
||||
path = tmp_path / "pip_overrides.json"
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
assert overrides_after_start(False, path) == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
|
||||
def test_without_a_file_no_package_is_remapped(tmp_path, has_system_user_api):
|
||||
assert overrides_after_start(has_system_user_api, tmp_path / "pip_overrides.json") == {}
|
||||
@@ -0,0 +1,47 @@
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
|
||||
|
||||
|
||||
def start(tmp_path, has_system_user_api, legacy):
|
||||
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.If) and "execute_lazy_install_script(comfy_path" in ast.unparse(node)]
|
||||
assert len(statements) == 1
|
||||
|
||||
directory = tmp_path / "user" / "default" / "ComfyUI-Manager"
|
||||
if legacy is not None:
|
||||
directory.mkdir(parents=True)
|
||||
for name in legacy:
|
||||
(directory / name).write_text("", encoding="utf-8")
|
||||
installed = []
|
||||
|
||||
namespace = {
|
||||
"os": os, "sys": sys, "_has_system_user_api": has_system_user_api, "comfy_path": "comfyui",
|
||||
"folder_paths": types.SimpleNamespace(get_user_directory=lambda: str(tmp_path / "user")),
|
||||
"execute_lazy_install_script": lambda repo_path, executable: installed.append((repo_path, executable)),
|
||||
}
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
|
||||
return installed
|
||||
|
||||
|
||||
def test_the_first_start_after_the_update_installs_the_requirements_of_comfyui(tmp_path, capsys):
|
||||
assert start(tmp_path, True, ["config.ini"]) == [("comfyui", sys.executable)]
|
||||
assert "installing the requirements of ComfyUI" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [None, [], ["channels.list"]],
|
||||
ids=["no legacy directory", "an empty legacy directory", "a legacy directory without config.ini"])
|
||||
def test_a_start_that_is_not_the_first_after_the_update_installs_nothing(tmp_path, legacy, capsys):
|
||||
assert start(tmp_path, True, legacy) == []
|
||||
assert capsys.readouterr().out == ""
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [None, ["config.ini"]], ids=["no data directory yet", "with its config.ini"])
|
||||
def test_an_old_comfyui_installs_nothing_at_the_start(tmp_path, legacy):
|
||||
assert start(tmp_path, False, legacy) == []
|
||||
@@ -0,0 +1,68 @@
|
||||
import ast
|
||||
import locale
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
|
||||
SNAPSHOT = '{"comfyui": null, "git_custom_nodes": {}, "cnr_custom_nodes": {}, "file_custom_nodes": [], "pips": {}}'
|
||||
|
||||
|
||||
def start(monkeypatch, tmp_path, has_system_user_api, scheduled=True, exit_code=0):
|
||||
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.If) and "'restore-snapshot'" in ast.unparse(node)]
|
||||
assert len(statements) == 1
|
||||
|
||||
cli_args = types.ModuleType("comfy.cli_args")
|
||||
cli_args.args = types.SimpleNamespace(listen="127.0.0.1")
|
||||
monkeypatch.setitem(sys.modules, "comfy", types.ModuleType("comfy"))
|
||||
monkeypatch.setitem(sys.modules, "comfy.cli_args", cli_args)
|
||||
|
||||
path = tmp_path / "startup-scripts" / "restore-snapshot.json"
|
||||
if scheduled:
|
||||
path.parent.mkdir()
|
||||
path.write_text(SNAPSHOT, encoding="utf-8")
|
||||
commands = []
|
||||
|
||||
def process_wrap(command, cwd, handler=None, env=None):
|
||||
commands.append(command)
|
||||
return exit_code
|
||||
|
||||
namespace = {
|
||||
"os": os, "sys": sys, "locale": locale, "_has_system_user_api": has_system_user_api,
|
||||
"restore_snapshot_path": str(path), "comfy_path": str(tmp_path), "custom_nodes_base_path": str(tmp_path),
|
||||
"cm_cli_path": "cm-cli.py", "default_conf": {}, "process_wrap": process_wrap,
|
||||
"manager_util": types.SimpleNamespace(is_loopback_listener=lambda listen: True),
|
||||
"folder_paths": types.SimpleNamespace(__file__=str(tmp_path / "folder_paths.py"), get_user_directory=lambda: str(tmp_path / "user")),
|
||||
}
|
||||
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
|
||||
return commands, path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exit_code", [0, 1], ids=["cm-cli succeeds", "cm-cli fails"])
|
||||
def test_with_the_system_user_api_a_scheduled_restore_runs_once(monkeypatch, tmp_path, exit_code):
|
||||
commands, left = start(monkeypatch, tmp_path, has_system_user_api=True, exit_code=exit_code)
|
||||
|
||||
assert [command[:4] for command in commands] == [
|
||||
[sys.executable, "cm-cli.py", "restore-snapshot", str(tmp_path / "startup-scripts" / "restore-snapshot.json")]]
|
||||
assert left is False
|
||||
|
||||
|
||||
def test_on_an_older_comfyui_a_scheduled_restore_does_not_run(monkeypatch, tmp_path, capsys):
|
||||
commands, left = start(monkeypatch, tmp_path, has_system_user_api=False)
|
||||
|
||||
assert commands == []
|
||||
assert left is True
|
||||
assert "blocked on old ComfyUI" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the System User API", "older ComfyUI"])
|
||||
def test_without_a_scheduled_restore_nothing_runs(monkeypatch, tmp_path, has_system_user_api, capsys):
|
||||
commands, left = start(monkeypatch, tmp_path, has_system_user_api, scheduled=False)
|
||||
|
||||
assert commands == []
|
||||
assert left is False
|
||||
assert capsys.readouterr().out == ""
|
||||
@@ -0,0 +1,219 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from test_install_flags_config import _run_child
|
||||
from test_pip_blacklist_matching import CM_GLOBAL, MANAGER_UTIL, load_prestartup, set_lists # noqa: F401 -- fixture
|
||||
|
||||
INDEX = 'https://example.invalid/whl/cu121'
|
||||
MIRROR = 'https://example.invalid/simple'
|
||||
REPO = 'git+https://example.invalid/packs/proto'
|
||||
OVERRIDES = {'opencv-python': 'opencv-contrib-python-headless'}
|
||||
FORCED = ['--force-reinstall', '--no-deps', '--no-cache-dir']
|
||||
|
||||
LINES = {
|
||||
'demo-pkg': [['demo-pkg']],
|
||||
'demo-pkg==1.2': [['demo-pkg==1.2']],
|
||||
'demo-pkg>=1,<2': [['demo-pkg>=1,<2']],
|
||||
'demo-pkg; python_version < "3.12"': [['demo-pkg; python_version < "3.12"']],
|
||||
'opencv-python': [['opencv-contrib-python-headless']],
|
||||
'pygit2>=1.18 # clone_repository(proxy=...) requires 1.18.0+': [['pygit2>=1.18']],
|
||||
'demo-pkg; python_version < "3.12" # older pythons': [['demo-pkg; python_version < "3.12"']],
|
||||
'opencv-python # headless on servers': [['opencv-contrib-python-headless']],
|
||||
f'torch --index-url {INDEX}': [['torch', '--index-url', INDEX]],
|
||||
f'torch==2.1.1 --index-url {INDEX} # the CUDA build': [['torch==2.1.1', '--index-url', INDEX]],
|
||||
f'torch --extra-index-url {INDEX} # the CUDA build': [['torch', '--extra-index-url', INDEX]],
|
||||
f'torch --index-url {MIRROR} --extra-index-url {INDEX}': [['torch', '--index-url', MIRROR, '--extra-index-url', INDEX]],
|
||||
'# a comment': [],
|
||||
' ': [],
|
||||
}
|
||||
URL_LINES = {
|
||||
f'{REPO}#subdirectory=sub': [f'{REPO}#subdirectory=sub'],
|
||||
f'proto-dist @ {REPO}#egg=proto-dist # pinned': [f'proto-dist @ {REPO}#egg=proto-dist'],
|
||||
}
|
||||
BLACKLISTED = ['xformers', 'xformers # attention', f'xformers --index-url {INDEX}', f'XFormers>=0.0.30 --extra-index-url {INDEX} # attention']
|
||||
OPTION_ROWS = {
|
||||
f'--extra-index-url {INDEX}': f'--extra-index-url {INDEX}',
|
||||
f'--index-url {INDEX} # the CUDA build': f'--index-url {INDEX}',
|
||||
'-r other.txt': '-r other.txt',
|
||||
'-c constraints.txt': '-c constraints.txt',
|
||||
'-f https://example.invalid/wheels': '-f https://example.invalid/wheels',
|
||||
'--trusted-host example.invalid': '--trusted-host example.invalid',
|
||||
'--only-binary :all:': '--only-binary :all:',
|
||||
' --hash=sha256:4bc89822243270757f4c272934e2521ad4b41f0cdcdce82672eeacf01ca3d5f1': '--hash=sha256:4bc89822243270757f4c272934e2521ad4b41f0cdcdce82672eeacf01ca3d5f1',
|
||||
}
|
||||
EDITABLE_ROWS = {
|
||||
'-e ./local': ['-e', './local'],
|
||||
'-e .': ['-e', '.'],
|
||||
'--editable ./local': ['-e', './local'],
|
||||
'--editable=./local': ['-e', './local'],
|
||||
'-e./local': ['-e', './local'],
|
||||
f'-e {REPO}#egg=proto-dist # pinned': ['-e', f'{REPO}#egg=proto-dist'],
|
||||
'-e requests': ['-e', 'requests'],
|
||||
f'-e ./local --extra-index-url {INDEX}': ['-e', './local', '--extra-index-url', INDEX],
|
||||
}
|
||||
WITH_A_ROW_AFTER = {row: f'{row}\ndemo-pkg' for row in [*OPTION_ROWS, *EDITABLE_ROWS]}
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def core_runs():
|
||||
return _run_child(f"""
|
||||
import contextlib, io, pathlib, subprocess
|
||||
from types import SimpleNamespace
|
||||
import cm_global, manager_util
|
||||
|
||||
manager_util.get_pip_cmd = lambda force_uv=False: ['python', '-m', 'pip']
|
||||
manager_util.subprocess = SimpleNamespace(
|
||||
check_output=lambda *args, **kwargs: 'Package Version\\n------- -------\\n', CalledProcessError=subprocess.CalledProcessError)
|
||||
manager_util.pip_map = None
|
||||
manager_util.PIPFixer = lambda *args: SimpleNamespace(fix_broken=lambda: None)
|
||||
cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist, cm_global.pip_overrides = {{'xformers'}}, [], {OVERRIDES!r}
|
||||
executed = []
|
||||
manager_core.manager_funcs.run_script = lambda cmd, cwd='.': executed.append(cmd[4:]) or int(cmd[4].startswith('-') and cmd[4] != '-e')
|
||||
manager = manager_core.unified_manager
|
||||
runs = {{}}
|
||||
for number, line in enumerate({[*LINES, *URL_LINES, *BLACKLISTED, *WITH_A_ROW_AFTER.values()]!r}):
|
||||
pack = pathlib.Path(tmp) / f'pack{{number}}'
|
||||
pack.mkdir()
|
||||
(pack / 'requirements.txt').write_text(line + '\\n', encoding='utf-8')
|
||||
manager.unknown_active_nodes = {{'pack': ('https://example.invalid/pack', str(pack))}}
|
||||
runs[line] = {{}}
|
||||
for path, action in [('install', lambda: manager.execute_install_script(None, str(pack), instant_execution=True)),
|
||||
('fix', lambda: manager.unified_fix('pack', 'unknown', instant_execution=True).result),
|
||||
('install from a git url', lambda: manager_core.execute_install_script(None, str(pack), instant_execution=True))]:
|
||||
manager.processed_install = set()
|
||||
del executed[:]
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
ok = action()
|
||||
runs[line][path] = {{'commands': list(executed), 'ok': bool(ok), 'said': [said for said in out.getvalue().splitlines() if 'one row at a time' in said]}}
|
||||
print(json.dumps(runs))
|
||||
""")
|
||||
|
||||
|
||||
@pytest.fixture(params=['install', 'fix', 'install from a git url', 'start'])
|
||||
def installs(request, core_runs, set_lists, monkeypatch, tmp_path, capsys): # noqa: F811
|
||||
monkeypatch.setattr(CM_GLOBAL, 'pip_overrides', OVERRIDES)
|
||||
set_lists(blacklist={'xformers'})
|
||||
|
||||
def start(line):
|
||||
(tmp_path / 'requirements.txt').write_text(line + '\n', encoding='utf-8')
|
||||
executed = []
|
||||
startup = load_prestartup(processed_install=set(), comfy_path=str(tmp_path),
|
||||
process_wrap=lambda cmd, cwd=None, **kwargs: executed.append(cmd[4:]) or int(cmd[4].startswith('-') and cmd[4] != '-e'))
|
||||
capsys.readouterr()
|
||||
startup['execute_lazy_install_script'](str(tmp_path), 'python')
|
||||
said = [said for said in capsys.readouterr().out.splitlines() if 'one row at a time' in said]
|
||||
return SimpleNamespace(commands=executed, ok=True, said=said)
|
||||
|
||||
installs = start if request.param == 'start' else lambda line: SimpleNamespace(**core_runs[line][request.param])
|
||||
installs.path = request.param
|
||||
return installs
|
||||
|
||||
|
||||
@pytest.mark.parametrize('line', LINES)
|
||||
def test_each_path_gives_the_installer_the_line_as_pip_reads_it(installs, line):
|
||||
assert installs(line).commands == LINES[line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('line', URL_LINES)
|
||||
def test_a_url_keeps_its_fragment_on_each_path(installs, line):
|
||||
forced = [[*URL_LINES[line], *FORCED]] if installs.path == 'fix' else []
|
||||
assert installs(line).commands == [URL_LINES[line], *forced]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('line', BLACKLISTED)
|
||||
def test_a_blacklisted_package_is_skipped_however_its_line_is_written(installs, line):
|
||||
assert installs(line).commands == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row', OPTION_ROWS)
|
||||
def test_a_row_with_only_an_option_is_left_out_with_one_line_and_the_rows_after_it_are_installed(installs, row):
|
||||
run = installs(WITH_A_ROW_AFTER[row])
|
||||
|
||||
assert (run.commands, run.ok) == ([['demo-pkg']], True)
|
||||
assert len(run.said) == 1 and f"'{OPTION_ROWS[row]}'" in run.said[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row', EDITABLE_ROWS)
|
||||
def test_an_editable_row_goes_to_the_installer_as_its_option_and_its_target(installs, row):
|
||||
run = installs(WITH_A_ROW_AFTER[row])
|
||||
|
||||
assert (run.commands, run.ok, run.said) == ([EDITABLE_ROWS[row], ['demo-pkg']], True, [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('line', ['# a comment', ' ', 'demo-pkg'])
|
||||
def test_a_row_that_is_not_an_option_row_is_left_out_or_installed_without_that_line(installs, line):
|
||||
assert installs(line).said == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installer, row, installed, said', [
|
||||
(['python', '-m', 'pip'], f'-e {REPO}#egg=proto-dist # pinned', ['-e', f'{REPO}#egg=proto-dist'], False),
|
||||
(['python', '-m', 'uv', 'pip'], f'-e {REPO}#egg=proto-dist # pinned', [f'{REPO}#egg=proto-dist'], True),
|
||||
(['uv', 'pip'], f'--editable={REPO}#egg=proto-dist --extra-index-url {INDEX}', [f'{REPO}#egg=proto-dist', '--extra-index-url', INDEX], True),
|
||||
(['uv', 'pip'], f'-e {REPO}#egg=proto-dist --no-build-isolation', [f'-e {REPO}#egg=proto-dist --no-build-isolation'], False),
|
||||
(['python', '-m', 'pip'], '-e ./local', ['-e', './local'], False),
|
||||
(['uv', 'pip'], '-e ./local', ['-e', './local'], False),
|
||||
(['uv', 'pip'], f'{REPO}#egg=proto-dist', [f'{REPO}#egg=proto-dist'], False),
|
||||
])
|
||||
def test_uv_installs_an_editable_git_requirement_without_e_and_pip_installs_it_as_it_is_written(installer, row, installed, said, monkeypatch, capsys):
|
||||
monkeypatch.setattr(MANAGER_UTIL, 'get_pip_cmd', lambda force_uv=False: installer)
|
||||
|
||||
assert MANAGER_UTIL.pip_install_args(row, {}) == installed
|
||||
assert ('without -e' in capsys.readouterr().out) == said
|
||||
|
||||
|
||||
SAME_ROW_OF_TWO_NODEPACKS = {
|
||||
'-e .': ['pack-a', 'pack-b'],
|
||||
'-e ./local': ['pack-a', 'pack-b'],
|
||||
'./wheels/demo_pkg-1.0-py3-none-any.whl': ['pack-a', 'pack-b'],
|
||||
'-e .[extra]': ['pack-a', 'pack-b'],
|
||||
'./wheels/demo_pkg-1.0-py3-none-any.whl; python_version >= "3"': ['pack-a', 'pack-b'],
|
||||
'demo-pkg': ['pack-a'],
|
||||
'demo-pkg[extra]>=1; python_version >= "3"': ['pack-a'],
|
||||
f'-e {REPO}#egg=proto-dist': ['pack-a'],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def session_runs():
|
||||
return _run_child(f"""
|
||||
import pathlib, subprocess
|
||||
from types import SimpleNamespace
|
||||
import cm_global, manager_util
|
||||
|
||||
manager_util.get_pip_cmd = lambda force_uv=False: ['python', '-m', 'pip']
|
||||
manager_util.subprocess = SimpleNamespace(
|
||||
check_output=lambda *args, **kwargs: 'Package Version\\n------- -------\\n', CalledProcessError=subprocess.CalledProcessError)
|
||||
manager_util.pip_map = None
|
||||
manager_util.PIPFixer = lambda *args: SimpleNamespace(fix_broken=lambda: None)
|
||||
cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist, cm_global.pip_overrides = set(), [], {{}}
|
||||
installed_in = []
|
||||
manager_core.manager_funcs.run_script = lambda cmd, cwd='.': installed_in.append(pathlib.Path(cwd).name) or 0
|
||||
manager = manager_core.unified_manager
|
||||
runs = {{}}
|
||||
for number, row in enumerate({[*SAME_ROW_OF_TWO_NODEPACKS]!r}):
|
||||
packs = [pathlib.Path(tmp) / f'row{{number}}' / name for name in ('pack-a', 'pack-b')]
|
||||
for pack in packs:
|
||||
(pack / 'local').mkdir(parents=True)
|
||||
(pack / 'wheels').mkdir()
|
||||
(pack / 'wheels' / 'demo_pkg-1.0-py3-none-any.whl').write_bytes(b'')
|
||||
(pack / 'requirements.txt').write_text(row + '\\n', encoding='utf-8')
|
||||
manager.unknown_active_nodes = {{pack.name: ('https://example.invalid/' + pack.name, str(pack)) for pack in packs}}
|
||||
runs[row] = {{}}
|
||||
fixed = set()
|
||||
for path, action in [('install', lambda pack: manager.execute_install_script(None, str(pack), instant_execution=True)),
|
||||
('fix', lambda pack: manager.unified_fix(pack.name, 'unknown', instant_execution=True, fixed=fixed))]:
|
||||
manager.processed_install = set()
|
||||
del installed_in[:]
|
||||
for pack in packs:
|
||||
action(pack)
|
||||
runs[row][path] = list(installed_in)
|
||||
print(json.dumps(runs))
|
||||
""")
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path', ['install', 'fix'])
|
||||
@pytest.mark.parametrize('row', SAME_ROW_OF_TWO_NODEPACKS)
|
||||
def test_a_row_that_names_a_path_of_the_nodepack_is_installed_for_each_nodepack_of_a_session(session_runs, row, path):
|
||||
assert session_runs[row][path] == SAME_ROW_OF_TWO_NODEPACKS[row]
|
||||
@@ -0,0 +1,42 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from test_install_flags_config import _CHILD_PREAMBLE, REPO_ROOT
|
||||
|
||||
BODY = '''
|
||||
import ast, pathlib
|
||||
core = manager_core
|
||||
core.manager_startup_script_path = tmp
|
||||
core.get_default_custom_nodes_path = lambda: tmp
|
||||
path = str(pathlib.Path(tmp) / '한글 node pack')
|
||||
|
||||
def reserved():
|
||||
with open(pathlib.Path(tmp) / 'install-scripts.txt', encoding='utf-8') as file:
|
||||
return [ast.literal_eval(line) for line in file]
|
||||
'''
|
||||
|
||||
|
||||
def run(tmp_path, body):
|
||||
# from a file: with this locale a command line cannot hold the name of the node pack
|
||||
(tmp_path / 'reserve.py').write_text(_CHILD_PREAMBLE.format(glob_path=str(REPO_ROOT / 'glob')) + BODY + body, encoding='utf-8')
|
||||
child = subprocess.run([sys.executable, str(tmp_path / 'reserve.py')], capture_output=True, text=True, cwd=str(REPO_ROOT),
|
||||
env={**os.environ, 'LC_ALL': 'C', 'PYTHONUTF8': '0', 'PYTHONCOERCECLOCALE': '0'})
|
||||
assert child.returncode == 0, child.stderr[-600:]
|
||||
return json.loads(child.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def test_install_script_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path):
|
||||
assert run(tmp_path, '''
|
||||
core.reserve_script(path, ['install.py'])
|
||||
print(json.dumps(reserved() == [[path, 'install.py']]))
|
||||
''') is True
|
||||
|
||||
|
||||
def test_switch_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path):
|
||||
assert run(tmp_path, '''
|
||||
core.UnifiedManager().reserve_cnr_switch('fixture', 'https://example.invalid/fixture.zip', path, path, False)
|
||||
entry, = reserved()
|
||||
print(json.dumps(entry[3:5] == [path, path]))
|
||||
''') is True
|
||||
@@ -469,11 +469,12 @@ class ClientAnchorAndStateTest(unittest.TestCase):
|
||||
@unittest.skipIf(NODE is None, "node is required")
|
||||
def test_selection_survives_unrecognised_and_prototype_names(self):
|
||||
sanitize = JS.lift_declaration(COMMON, "export function sanitizeHTML(")
|
||||
guidance = _unique_line(JS.text(MANAGER), "const INVALID_INSTALLATION_GUIDANCE =")
|
||||
buttons = JS.lift_declaration(MANAGER, "\n\tgetActionButtons(")
|
||||
render = JS.lift_declaration(MANAGER, "\n\trenderSelected()")
|
||||
for state in ['not-a-known-install-group', 'constructor', '__proto__', TEXT_PAYLOAD, 'enabled']:
|
||||
with self.subTest(state=state):
|
||||
result = run_node(sanitize + "\nconst manager = {" + buttons + "," + render + """,
|
||||
result = run_node(sanitize + "\n" + guidance + "\nconst manager = {" + buttons + "," + render + """,
|
||||
grid: {hasMask: false, getSelectedRows: () => [{action: STATE, hash: 'fixture'}]},
|
||||
getFilterItem: () => null,
|
||||
showSelection(html) { this.html = html; }
|
||||
|
||||
@@ -25,17 +25,27 @@ PIPS = {
|
||||
'torch==2.5.1': '',
|
||||
}
|
||||
|
||||
GIT_URL = 'git+https://example.com/vcs-pack.git@0123abcd#egg=vcs-pack'
|
||||
EDITABLE = {
|
||||
'alpha==1.0': '',
|
||||
'# Editable install with no version control (local-pack==0.1)': '',
|
||||
'-e /work/local-pack': '',
|
||||
'-e file:///work/uv-pack': '',
|
||||
f'-e {GIT_URL}': '',
|
||||
}
|
||||
UV = ['uv', 'pip']
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def restore(monkeypatch, capsys):
|
||||
"""Run restore_pip_snapshot() with pip replaced; return the pip commands and the reported failures."""
|
||||
manager_util = MANAGER_UTIL
|
||||
|
||||
def run(options, failing=()):
|
||||
def run(options, failing=(), pips=PIPS, installer=('python', '-m', 'pip')):
|
||||
commands = []
|
||||
|
||||
def check_call(cmd, **_):
|
||||
commands.append(cmd[3:])
|
||||
commands.append(cmd[len(installer):])
|
||||
if any(name in arg for arg in cmd for name in failing):
|
||||
raise subprocess.CalledProcessError(1, cmd)
|
||||
return 0
|
||||
@@ -44,13 +54,13 @@ def restore(monkeypatch, capsys):
|
||||
# pip's output, as the real check_output returns it: never an exit status.
|
||||
return check_call(cmd) or b'Successfully installed\n'
|
||||
|
||||
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
|
||||
monkeypatch.setattr(manager_util, 'get_pip_cmd', lambda force_uv=False: list(installer))
|
||||
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
|
||||
check_call=check_call, check_output=check_output,
|
||||
CalledProcessError=subprocess.CalledProcessError))
|
||||
|
||||
manager_util.restore_pip_snapshot(PIPS, options)
|
||||
report = capsys.readouterr().out.strip().splitlines()[-1]
|
||||
run.not_installed = manager_util.restore_pip_snapshot(pips, options)
|
||||
*run.said, report = capsys.readouterr().out.strip().splitlines()
|
||||
return commands, report
|
||||
|
||||
return run
|
||||
@@ -104,8 +114,62 @@ def test_every_failed_package_is_reported(restore):
|
||||
assert report == f"Installation failed for pip packages: {['alpha==1.0', 'beta==2.0', *urls]}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failing, not_installed', [
|
||||
([], []),
|
||||
(['beta', 'delta'], ['beta==2.0', 'file:///wheels/delta.whl']),
|
||||
])
|
||||
def test_packages_that_were_not_installed_are_returned(restore, failing, not_installed):
|
||||
restore(['--pip-non-url', '--pip-non-local-url', '--pip-local-url'], failing=failing)
|
||||
|
||||
assert restore.not_installed == not_installed
|
||||
|
||||
|
||||
def test_group_without_its_option_is_left_alone(restore):
|
||||
commands, report = restore([])
|
||||
|
||||
assert commands == []
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('option, installed', [
|
||||
('--pip-non-url', [['install', 'alpha==1.0']]),
|
||||
('--pip-local-url', [['install', '--no-deps', '-e', '/work/local-pack'],
|
||||
['install', '--no-deps', '-e', 'file:///work/uv-pack']]),
|
||||
('--pip-non-local-url', [['install', '--no-deps', '-e', GIT_URL]]),
|
||||
])
|
||||
def test_editable_install_is_restored_as_editable_with_the_option_of_its_url(restore, option, installed):
|
||||
commands, report = restore([option], pips=EDITABLE)
|
||||
|
||||
assert commands == installed
|
||||
assert restore.said == []
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
|
||||
|
||||
def test_uv_restores_an_editable_install_of_a_git_url_without_e(restore):
|
||||
commands, report = restore(['--pip-non-local-url', '--pip-local-url'], pips=EDITABLE, installer=UV)
|
||||
|
||||
assert commands == [['install', '--no-deps', GIT_URL],
|
||||
['install', '--no-deps', '-e', '/work/local-pack'],
|
||||
['install', '--no-deps', '-e', 'file:///work/uv-pack']]
|
||||
assert restore.said == [f"[ComfyUI-Manager] uv installs an editable from a local folder only: '{GIT_URL}' is installed without -e"]
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
|
||||
|
||||
def test_uv_says_nothing_of_an_editable_install_that_its_option_leaves_alone(restore):
|
||||
commands, _ = restore(['--pip-local-url'], pips=EDITABLE, installer=UV)
|
||||
|
||||
assert commands == [['install', '--no-deps', '-e', '/work/local-pack'], ['install', '--no-deps', '-e', 'file:///work/uv-pack']]
|
||||
assert restore.said == []
|
||||
|
||||
|
||||
def test_an_editable_git_url_that_uv_does_not_install_is_reported_as_the_snapshot_has_it(restore):
|
||||
_, report = restore(['--pip-non-local-url'], failing=['vcs-pack'], pips=EDITABLE, installer=UV)
|
||||
|
||||
assert report == f"Installation failed for pip packages: ['-e {GIT_URL}']"
|
||||
|
||||
|
||||
def test_editable_install_whose_path_is_gone_is_reported(restore):
|
||||
_, report = restore(['--pip-non-url', '--pip-local-url'], failing=['/work/local-pack'], pips=EDITABLE)
|
||||
|
||||
assert report == "Installation failed for pip packages: ['-e /work/local-pack']"
|
||||
assert restore.not_installed == ['-e /work/local-pack']
|
||||
|
||||
@@ -0,0 +1,668 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import os
|
||||
import pathlib
|
||||
import traceback
|
||||
from types import SimpleNamespace
|
||||
from typing import Optional
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from test_snapshot_restore_pins import run
|
||||
|
||||
CM_CLI = pathlib.Path(__file__).resolve().parent.parent / 'cm-cli.py'
|
||||
|
||||
URL = 'https://github.com/owner/fixture'
|
||||
HASH = '0123456789abcdef0123456789abcdef01234567'
|
||||
SUMMARY = '''
|
||||
import contextlib, io, logging, os, shutil
|
||||
from types import SimpleNamespace
|
||||
|
||||
URL = 'https://github.com/owner/fixture'
|
||||
HASH = '0123456789abcdef0123456789abcdef01234567'
|
||||
|
||||
def summary(**snapshot):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
restore(**snapshot)
|
||||
return [line.strip() for line in out.getvalue().splitlines() if line.startswith('[ ')]
|
||||
|
||||
def errors(**snapshot):
|
||||
seen = []
|
||||
handler = logging.Handler(logging.ERROR)
|
||||
handler.emit = lambda record: seen.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
restore(**snapshot)
|
||||
return seen
|
||||
|
||||
def pinned(url):
|
||||
return {'git_custom_nodes': {url: {'hash': HASH, 'disabled': False}}}
|
||||
|
||||
def git_pack(name, url):
|
||||
path = nodes / name
|
||||
(path / '.git').mkdir(parents=True)
|
||||
(path / '.git/config').write_text('[remote "origin"]\\n\\turl = %s\\n' % url)
|
||||
return url, str(path)
|
||||
|
||||
def in_registry():
|
||||
manager.repo_cnr_map[URL] = {'id': 'fixture'}
|
||||
manager.get_custom_nodes.return_value = {'fixture': {'repository': URL}}
|
||||
|
||||
def clones(kind, clone):
|
||||
if kind == 'registry':
|
||||
in_registry()
|
||||
manager.repo_install = lambda url, path, return_postinstall=False, **options: clone(path, return_postinstall)
|
||||
|
||||
def steps():
|
||||
done = []
|
||||
manager.unified_disable = lambda name, is_unknown: done.append('disable ' + name) or core.ManagedResult('disable')
|
||||
manager.unified_enable = lambda name, version: done.append('enable %s@%s' % (name, version)) or core.ManagedResult('enable')
|
||||
manager.repo_install = lambda url, path, **options: done.append('clone %s into %s' % (url, os.path.basename(path))) or core.ManagedResult('install-git')
|
||||
manager._cnr_install = lambda name, version, *args: done.append('install %s@%s' % (name, version.version)) or core.ManagedResult('install-cnr')
|
||||
cnr_utils.install_node = lambda name, version: SimpleNamespace(version=version, download_url='https://registry.invalid/' + name, status='NodeVersionStatusActive')
|
||||
core.repo_switch_commit = Mock(return_value=True)
|
||||
return done
|
||||
|
||||
def answer(action, ok):
|
||||
result = core.ManagedResult(action)
|
||||
return Mock(return_value=result if ok else result.fail('failed'))
|
||||
|
||||
def repository(path):
|
||||
path.mkdir(parents=True)
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
(path / '__init__.py').write_text('VERSION = %d' % version)
|
||||
for args in (['init', '-q'], ['add', '.'],
|
||||
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
|
||||
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
|
||||
commits.append(head(path))
|
||||
return commits
|
||||
|
||||
def head(path):
|
||||
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
'''
|
||||
|
||||
|
||||
def lines(body):
|
||||
return run(SUMMARY + body + '\nprint(json.dumps(result))\n')
|
||||
|
||||
|
||||
CLONES = pytest.mark.parametrize('kind', ['registry', 'url'])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cloned, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_clone_follows_its_result(cloned, line):
|
||||
assert lines(f'''
|
||||
manager.repo_install = answer('install-git', {cloned})
|
||||
core.repo_switch_commit = Mock(return_value=True)
|
||||
result = summary(**pinned('{URL}.git')) + [manager.repo_install.call_args.args[1] == str(nodes / 'fixture')]
|
||||
''') == [line, True]
|
||||
|
||||
|
||||
def test_url_that_is_not_cloned_is_reported_as_failed():
|
||||
assert lines('''
|
||||
result = summary(**pinned('/home/someone/repos/fixture')) + [(nodes / 'fixture').exists()]
|
||||
''') == ['[ FAILED ] fixture', False]
|
||||
|
||||
|
||||
def test_pack_of_the_registry_that_the_node_list_does_not_have_is_cloned():
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map['{URL}'] = {{'id': 'fixture-of-the-registry'}}
|
||||
done = steps()
|
||||
result = summary(**pinned('{URL}.git')) + [done]
|
||||
''') == ['[ INSTALLED ] fixture-of-the-registry', [f'clone {URL} into fixture-of-the-registry']]
|
||||
|
||||
|
||||
def test_pack_of_the_registry_is_cloned_from_the_url_of_the_snapshot_when_the_node_list_has_another_one_under_its_name():
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map['{URL}'] = {{'id': 'fixture'}}
|
||||
manager.get_custom_nodes.return_value = {{'fixture': {{'repository': 'https://github.com/another-owner/fixture'}}}}
|
||||
done = steps()
|
||||
result = summary(**pinned('{URL}')) + [done]
|
||||
''') == ['[ INSTALLED ] fixture', [f'clone {URL} into fixture']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('in_node_list', [True, False])
|
||||
def test_enabled_version_of_the_registry_is_disabled_before_the_clone_of_a_snapshot_that_names_no_version(in_node_list):
|
||||
"""A snapshot from before the registry has no `cnr_custom_nodes`, so nothing else disables that version."""
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map['{URL}'] = {{'id': 'fixture'}}
|
||||
manager.get_custom_nodes.return_value = {{'fixture': {{'repository': '{URL}'}}}} if {in_node_list} else {{}}
|
||||
(nodes / 'fixture').mkdir()
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
|
||||
done = steps()
|
||||
result = summary(cnr_custom_nodes=None, **pinned('{URL}')) + [done]
|
||||
''') == ['[ INSTALLED ] fixture', ['disable fixture', f'clone {URL} into fixture']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('machine, state', [
|
||||
('that saved it', ['[ SKIPPED ] fixture', []]),
|
||||
('with no node pack', ['[ INSTALLED ] fixture@1.0.0', ['install fixture@1.0.0']]),
|
||||
], ids=['that saved it', 'with no node pack'])
|
||||
def test_pack_saved_at_a_version_of_the_registry_with_its_clone_disabled_is_restored_at_that_version(machine, state):
|
||||
"""A switch from the clone to a version of the registry keeps the clone, disabled, and a snapshot saves both."""
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map[URL] = manager.cnr_map['fixture'] = {{'id': 'fixture', 'repository': URL, 'publisher': {{'name': 'owner'}}}}
|
||||
version, clone = nodes / 'fixture', nodes / '.disabled/fixture@nightly'
|
||||
version.mkdir()
|
||||
(version / '.tracking').write_text('')
|
||||
(version / 'pyproject.toml').write_text('[project]\\nname = "fixture"\\nversion = "1.0.0"\\n')
|
||||
repository(clone)
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', URL + '.git'], cwd=clone, check=True)
|
||||
core.get_custom_nodes_paths = lambda: [str(nodes)]
|
||||
saved = asyncio.run(core.get_current_snapshot(custom_nodes_only=True))
|
||||
if '{machine}' == 'that saved it':
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(version))
|
||||
manager.nightly_inactive_nodes['fixture'] = str(clone)
|
||||
else:
|
||||
shutil.rmtree(version)
|
||||
shutil.rmtree(clone)
|
||||
done = steps()
|
||||
result = summary(cnr_custom_nodes=saved['cnr_custom_nodes'], git_custom_nodes=saved['git_custom_nodes']) + [done]
|
||||
''') == state
|
||||
|
||||
|
||||
def test_clone_that_is_enabled_is_left_to_the_install_of_the_version_that_the_snapshot_names():
|
||||
assert lines('''
|
||||
manager.repo_cnr_map[URL] = {'id': 'fixture'}
|
||||
(nodes / 'fixture').mkdir()
|
||||
manager.active_nodes['fixture'] = ('nightly', str(nodes / 'fixture'))
|
||||
done = steps()
|
||||
result = summary(cnr_custom_nodes={'fixture': '1.0.0'}, git_custom_nodes={URL: {'hash': HASH, 'disabled': True}}) + [done]
|
||||
''') == ['[ INSTALLED ] fixture@1.0.0', ['disable fixture', 'install fixture@1.0.0']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure, state', [
|
||||
('cnr_utils.install_node = lambda name, version: None', [f'[ CHECKOUT ] fixture@{HASH}', '[ FAILED ] fixture@1.0.0', []]),
|
||||
("manager._cnr_install = lambda name, version, *args: core.ManagedResult('install-cnr').fail('the download failed')",
|
||||
[f'[ CHECKOUT ] fixture@{HASH}', '[ FAILED ] fixture@1.0.0', ['disable fixture', 'enable fixture@nightly']]),
|
||||
("manager.cnr_inactive_nodes['fixture'] = {'2.0.0': str(nodes / '.disabled/fixture@2_0_0')}; "
|
||||
"manager._cnr_switch_version = lambda name, version, *args: core.ManagedResult('switch-cnr').fail('the download failed')",
|
||||
[f'[ CHECKOUT ] fixture@{HASH}', '[ FAILED ] fixture@1.0.0', ['enable fixture@cnr', 'disable fixture', 'enable fixture@nightly']]),
|
||||
], ids=['the registry does not have it', 'its download fails', 'its download fails after another version was enabled'])
|
||||
def test_clone_of_the_snapshot_is_restored_when_the_version_that_the_snapshot_names_cannot_be_installed(failure, state):
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map[URL] = {{'id': 'fixture'}}
|
||||
(nodes / 'fixture').mkdir()
|
||||
manager.active_nodes['fixture'] = ('nightly', str(nodes / 'fixture'))
|
||||
done = steps()
|
||||
def disable(name, is_unknown):
|
||||
done.append('disable ' + name)
|
||||
manager.nightly_inactive_nodes[name] = manager.active_nodes.pop(name)[1]
|
||||
return core.ManagedResult('disable')
|
||||
def enable(name, version):
|
||||
done.append('enable %s@%s' % (name, version))
|
||||
if version == 'cnr':
|
||||
disable(name, False)
|
||||
manager.active_nodes[name] = ('2.0.0', manager.cnr_inactive_nodes[name].pop('2.0.0'))
|
||||
return core.ManagedResult('enable').with_target(str(nodes / name))
|
||||
manager.unified_disable, manager.unified_enable = disable, enable
|
||||
{failure}
|
||||
result = summary(cnr_custom_nodes={{'fixture': '1.0.0'}}, git_custom_nodes={{URL: {{'hash': HASH, 'disabled': True}}}}) + [done]
|
||||
result += [[x.args for x in core.repo_switch_commit.call_args_list] == [(str(nodes / 'fixture'), HASH)]]
|
||||
''') == state + [True]
|
||||
|
||||
|
||||
def test_pack_of_the_registry_with_the_name_of_the_manager_in_its_id_is_not_cloned():
|
||||
assert lines(f'''
|
||||
manager.repo_cnr_map['{URL}'] = {{'id': 'comfyui-manager-fixture'}}
|
||||
done = steps()
|
||||
result = summary(**pinned('{URL}')) + [done]
|
||||
''') == ['[ SKIPPED ] comfyui-manager-fixture', []]
|
||||
|
||||
|
||||
@CLONES
|
||||
def test_clone_that_is_refused_tells_why(kind):
|
||||
assert lines(f'''
|
||||
clones('{kind}', lambda path, return_postinstall: core.ManagedResult('install-git').fail('the clone was refused'))
|
||||
result = errors(**pinned('{URL}'))
|
||||
''') == ['the clone was refused']
|
||||
|
||||
|
||||
def test_url_that_is_not_cloned_tells_why():
|
||||
assert lines('''
|
||||
result = errors(**pinned('/home/someone/repos/fixture'))
|
||||
''') == ['Invalid git url: /home/someone/repos/fixture']
|
||||
|
||||
|
||||
def test_clone_of_a_pack_of_the_registry_that_raises_is_logged_once():
|
||||
assert lines(f'''
|
||||
in_registry()
|
||||
manager.repo_install = Mock(side_effect=RuntimeError('the disk is full'))
|
||||
result = errors(**pinned('{URL}'))
|
||||
''') == ['[ComfyUI-Manager] the disk is full']
|
||||
|
||||
|
||||
def test_url_that_cannot_be_parsed_is_reported_as_failed_and_the_restore_goes_on():
|
||||
assert lines('''
|
||||
entry = {'hash': HASH, 'disabled': False}
|
||||
result = summary(git_custom_nodes={'https://[not-a-host/first': dict(entry), '/home/someone/repos/second': dict(entry)})
|
||||
''') == ['[ FAILED ] first', '[ FAILED ] second']
|
||||
|
||||
|
||||
def test_cloned_pack_is_checked_out_at_the_pinned_commit():
|
||||
assert lines(f'''
|
||||
commits = repository(pathlib.Path(tmp) / 'origin')
|
||||
def clone(url, path, **options):
|
||||
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), path], check=True, capture_output=True)
|
||||
return core.ManagedResult('install-git')
|
||||
manager.repo_install = clone
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
|
||||
result += [head(nodes / 'fixture') == commits[0], (nodes / 'fixture/__init__.py').read_text()]
|
||||
''') == ['[ INSTALLED ] fixture', True, 'VERSION = 1']
|
||||
|
||||
|
||||
def test_cloned_registry_pack_is_checked_out_at_the_pinned_commit():
|
||||
assert lines(f'''
|
||||
commits = repository(pathlib.Path(tmp) / 'origin')
|
||||
def clone(url, path, **options):
|
||||
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), path], check=True, capture_output=True)
|
||||
return core.ManagedResult('install-git')
|
||||
in_registry()
|
||||
manager.repo_install = clone
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
|
||||
result += [head(nodes / 'fixture') == commits[0]]
|
||||
''') == ['[ INSTALLED ] fixture', True]
|
||||
|
||||
|
||||
def test_cloned_pack_that_cannot_be_checked_out_is_reported_as_failed():
|
||||
assert lines(f'''
|
||||
manager.repo_install = answer('install-git', True)
|
||||
result = summary(**pinned('{URL}'))
|
||||
''') == [f'[ FAILED ] fixture@{HASH}']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_disabling_a_git_pack_that_is_not_in_the_snapshot_follows_its_result(disabled, line):
|
||||
assert lines(f'''
|
||||
manager.unknown_active_nodes['fixture'] = git_pack('fixture', '{URL}')
|
||||
manager.unified_disable = answer('disable', {disabled})
|
||||
result = summary()
|
||||
''') == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_disabling_a_registry_pack_that_is_not_in_the_snapshot_follows_its_result(disabled, line):
|
||||
assert lines(f'''
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
|
||||
manager.unified_disable = answer('disable', {disabled})
|
||||
result = summary()
|
||||
''') == [line]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['ComfyUI-Manager', 'comfyui-manager'])
|
||||
def test_the_manager_itself_is_not_listed(name):
|
||||
assert lines(f'''
|
||||
manager.unknown_active_nodes['{name}'] = git_pack('{name}', 'https://github.com/ltdrdata/ComfyUI-Manager')
|
||||
manager.unified_disable = answer('disable', True)
|
||||
result = summary() + [manager.unified_disable.call_count]
|
||||
''') == [0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled, line', [(True, '[ ENABLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_enabling_a_git_pack_of_the_snapshot_follows_its_result(enabled, line):
|
||||
assert lines(f'''
|
||||
manager.unknown_inactive_nodes['fixture'] = git_pack('.disabled/fixture', '{URL}')
|
||||
manager.unified_enable = answer('enable', {enabled})
|
||||
manager.unified_enable.return_value.target = str(nodes / 'fixture') if {enabled} else None
|
||||
core.repo_switch_commit = Mock(return_value=False)
|
||||
result = summary(**pinned('{URL}')) + [[x.args for x in core.repo_switch_commit.call_args_list] == ([(str(nodes / 'fixture'), HASH)] if {enabled} else [])]
|
||||
''') == [line, True]
|
||||
|
||||
|
||||
LISTED_AS_DISABLED = {
|
||||
'registry_git_pack': ("manager.active_nodes[name] = ('nightly', str(nodes / name)); manager.repo_cnr_map[url] = {'id': name}",
|
||||
['[ DISABLED ] fixture', ['disable fixture']]),
|
||||
'unknown_git_pack': ("manager.unknown_active_nodes[name] = git_pack(name, url)", ['[ DISABLED ] fixture', ['disable fixture']]),
|
||||
'disabled_registry_git_pack': ("manager.nightly_inactive_nodes[name] = git_pack('.disabled/' + name, url)[1]; manager.repo_cnr_map[url] = {'id': name}", [[]]),
|
||||
'disabled_unknown_git_pack': ("manager.unknown_inactive_nodes[name] = git_pack('.disabled/' + name, url)", [[]]),
|
||||
'registry_git_pack_that_is_not_installed': ("manager.repo_cnr_map[url] = {'id': name}", [[]]),
|
||||
'unknown_git_pack_that_is_not_installed': ("", [[]]),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', LISTED_AS_DISABLED)
|
||||
def test_git_pack_that_the_snapshot_lists_as_disabled_is_restored_as_disabled(installed):
|
||||
"""Enabled, it is disabled; disabled, it is left as it is; not installed, it is not cloned."""
|
||||
assert lines(f'''
|
||||
name, url = 'fixture', URL
|
||||
{LISTED_AS_DISABLED[installed][0]}
|
||||
done = steps()
|
||||
result = summary(git_custom_nodes={{URL: {{'hash': HASH, 'disabled': True}}}}) + [done]
|
||||
''') == LISTED_AS_DISABLED[installed][1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('folders', ['nodes, more', 'more, nodes'], ids=['enabled_clone_read_first', 'disabled_clone_read_first'])
|
||||
def test_snapshot_lists_a_repository_as_enabled_when_one_of_its_two_clones_is_enabled(folders):
|
||||
"""Both clones have the URL that names the entry: the enabled one is what a restore brings back."""
|
||||
assert lines(f'''
|
||||
more = nodes.parent / 'more_nodes'
|
||||
enabled, disabled = nodes / 'fixture', more / '.disabled/fixture'
|
||||
repository(enabled)
|
||||
subprocess.run(['git', 'checkout', '-q', repository(disabled)[0]], cwd=disabled, check=True)
|
||||
for clone in (enabled, disabled):
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', URL], cwd=clone, check=True)
|
||||
core.get_custom_nodes_paths = lambda: [str(folder) for folder in ({folders})]
|
||||
saved = asyncio.run(core.get_current_snapshot(custom_nodes_only=True))['git_custom_nodes']
|
||||
result = [list(saved), saved[URL]['disabled'], saved[URL]['hash'] == head(enabled)]
|
||||
''') == [[URL], False, True]
|
||||
|
||||
|
||||
def test_installed_git_pack_the_registry_does_not_know_is_checked_out_at_the_pinned_commit():
|
||||
assert lines(f'''
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', '{URL}'], cwd=nodes / 'fixture', check=True)
|
||||
manager.unknown_active_nodes['fixture'] = ('{URL}', str(nodes / 'fixture'))
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
|
||||
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[0]]
|
||||
''') == ['[ CHECKOUT ] fixture@PINNED', True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', ['unknown_git_pack', 'disabled_unknown_git_pack', 'registry_git_pack', 'disabled_registry_git_pack'])
|
||||
def test_checkout_that_fails_is_reported_as_failed(installed):
|
||||
assert lines(f'''
|
||||
name, url = 'fixture', URL
|
||||
{MOVED[installed][0]}
|
||||
result = summary(**pinned(URL))
|
||||
''') == [f'[ FAILED ] fixture@{HASH}']
|
||||
|
||||
|
||||
NO_COMMIT = pytest.mark.parametrize('entry', [{'hash': 'unknown', 'disabled': False}, {'disabled': False}], ids=['unknown', 'no hash'])
|
||||
|
||||
|
||||
@NO_COMMIT
|
||||
def test_pack_without_a_commit_in_the_snapshot_is_left_where_it_is(entry):
|
||||
assert lines(f'''
|
||||
commits = repository(nodes / 'fixture')
|
||||
subprocess.run(['git', 'remote', 'add', 'origin', '{URL}'], cwd=nodes / 'fixture', check=True)
|
||||
manager.unknown_active_nodes['fixture'] = ('{URL}', str(nodes / 'fixture'))
|
||||
result = summary(git_custom_nodes={{'{URL}': {entry!r}}}) + [head(nodes / 'fixture') == commits[1]]
|
||||
''') == ['[ SKIPPED ] fixture', True]
|
||||
|
||||
|
||||
@CLONES
|
||||
@NO_COMMIT
|
||||
def test_cloned_pack_without_a_commit_in_the_snapshot_is_installed(kind, entry):
|
||||
assert lines(f'''
|
||||
ran = []
|
||||
clones('{kind}', lambda path, return_postinstall: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True))
|
||||
result = summary(git_custom_nodes={{'{URL}': {entry!r}}}) + [ran == [str(nodes / 'fixture')]]
|
||||
''') == ['[ INSTALLED ] fixture', True]
|
||||
|
||||
|
||||
@CLONES
|
||||
@pytest.mark.parametrize('installed, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
|
||||
def test_install_script_of_a_cloned_pack_runs_at_the_pinned_commit(kind, installed, line):
|
||||
assert lines(f'''
|
||||
commits = repository(pathlib.Path(tmp) / 'origin')
|
||||
ran_at = []
|
||||
def clone(path, return_postinstall):
|
||||
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), path], check=True, capture_output=True)
|
||||
def postinstall():
|
||||
ran_at.append(head(path))
|
||||
return {installed}
|
||||
result = core.ManagedResult('install-git')
|
||||
return result.with_postinstall(postinstall) if return_postinstall else (result if postinstall() else result.fail('install script'))
|
||||
clones('{kind}', clone)
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}}) + [ran_at == [commits[0]]]
|
||||
''') == [line, True]
|
||||
|
||||
|
||||
@CLONES
|
||||
def test_install_script_that_raises_is_reported_as_failed_and_the_restore_goes_on(kind):
|
||||
assert lines(f'''
|
||||
def clone(path, return_postinstall):
|
||||
def postinstall():
|
||||
raise subprocess.CalledProcessError(1, ['python', 'install.py'])
|
||||
return core.ManagedResult('install-git').with_postinstall(postinstall)
|
||||
manager.repo_install = lambda url, path, **options: clone(path, True)
|
||||
clones('{kind}', clone)
|
||||
core.repo_switch_commit = Mock(return_value=True)
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': HASH, 'disabled': False}}, '{URL}-other': {{'hash': HASH, 'disabled': False}}}})
|
||||
''') == ['[ FAILED ] fixture', '[ FAILED ] fixture-other']
|
||||
|
||||
|
||||
def test_install_script_of_a_cloned_pack_runs_also_when_the_commit_cannot_be_checked_out():
|
||||
assert lines(f'''
|
||||
ran = []
|
||||
manager.repo_install = lambda url, path, **options: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True)
|
||||
result = summary(**pinned('{URL}')) + [ran == [str(nodes / 'fixture')]]
|
||||
''') == [f'[ FAILED ] fixture@{HASH}', True]
|
||||
|
||||
|
||||
def test_install_script_of_a_cloned_registry_pack_runs_also_when_the_commit_cannot_be_checked_out():
|
||||
assert lines(f'''
|
||||
ran = []
|
||||
in_registry()
|
||||
manager.repo_install = lambda url, path, **options: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(os.path.basename(path)) or True)
|
||||
result = summary(**pinned('{URL}')) + [ran]
|
||||
''') == [f'[ FAILED ] fixture@{HASH}', ['fixture']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('outcome, line', [('return True', '[ INSTALLED ] fixture@1.0.0'), ('return False', '[ FAILED ] fixture@1.0.0'),
|
||||
("raise subprocess.CalledProcessError(1, ['python', 'install.py'])", '[ FAILED ] fixture@1.0.0')])
|
||||
def test_install_script_of_a_registry_pack_is_run(outcome, line):
|
||||
assert lines(f'''
|
||||
ran = []
|
||||
def postinstall():
|
||||
ran.append('fixture')
|
||||
{outcome}
|
||||
async def install(pack_id, **options):
|
||||
ran.append(options['return_postinstall'])
|
||||
return core.ManagedResult('install-cnr').with_postinstall(postinstall)
|
||||
manager.install_by_id = install
|
||||
result = summary(cnr_custom_nodes={{'fixture': '1.0.0'}}) + [ran]
|
||||
''') == [line, [True, 'fixture']]
|
||||
|
||||
|
||||
|
||||
def test_registry_pack_whose_install_raises_is_reported_as_failed_and_the_restore_goes_on():
|
||||
assert lines('''
|
||||
async def install(pack_id, **options):
|
||||
if pack_id == 'fixture':
|
||||
raise ConnectionError('the registry cannot be reached')
|
||||
return core.ManagedResult('install-cnr')
|
||||
manager.install_by_id = install
|
||||
result = summary(cnr_custom_nodes={'fixture': '1.0.0', 'other': '1.0.0'})
|
||||
''') == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@1.0.0']
|
||||
|
||||
|
||||
def test_registry_pack_whose_switch_raises_is_reported_as_failed_and_the_restore_goes_on():
|
||||
assert lines('''
|
||||
async def install(pack_id, **options):
|
||||
return core.ManagedResult('install-cnr')
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
|
||||
manager.cnr_switch_version = Mock(side_effect=ConnectionError('the registry cannot be reached'))
|
||||
manager.install_by_id = install
|
||||
result = summary(cnr_custom_nodes={'fixture': '2.0.0', 'other': '1.0.0'})
|
||||
''') == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@2.0.0']
|
||||
|
||||
|
||||
MOVED = {
|
||||
'registry_pack': ("manager.active_nodes[name] = ('1.0.0', str(nodes / name))", 'unified_disable', False),
|
||||
'registry_git_pack': ("manager.active_nodes[name] = ('nightly', str(nodes / name)); manager.repo_cnr_map[url] = {'id': name}", 'unified_disable', False),
|
||||
'unknown_git_pack': ("manager.unknown_active_nodes[name] = git_pack(name, url)", 'unified_disable', False),
|
||||
'disabled_registry_git_pack': ("manager.nightly_inactive_nodes[name] = git_pack('.disabled/' + name, url)[1]; manager.repo_cnr_map[url] = {'id': name}", 'unified_enable', True),
|
||||
'disabled_unknown_git_pack': ("manager.unknown_inactive_nodes[name] = git_pack('.disabled/' + name, url)", 'unified_enable', True),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', MOVED)
|
||||
def test_pack_whose_directory_cannot_be_moved_is_reported_as_failed_and_the_restore_goes_on(installed):
|
||||
"""The second node pack is the proof that the restore goes on."""
|
||||
arrange, step, in_snapshot = MOVED[installed]
|
||||
assert lines(f'''
|
||||
packs = {{'fixture': URL, 'second': URL + '-2'}}
|
||||
for name, url in packs.items():
|
||||
{arrange}
|
||||
manager.{step} = Mock(side_effect=PermissionError(13, 'Permission denied'))
|
||||
snapshot = {{url: {{'hash': HASH, 'disabled': False}} for url in packs.values()}} if {in_snapshot} else {{}}
|
||||
result = summary(git_custom_nodes=snapshot) + [manager.{step}.call_count]
|
||||
''') == ['[ FAILED ] fixture', '[ FAILED ] second', 2]
|
||||
|
||||
|
||||
def test_pack_that_fails_at_two_steps_is_listed_once():
|
||||
assert lines(f'''
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
|
||||
in_registry()
|
||||
manager.unified_disable = answer('disable', False)
|
||||
manager.repo_install = answer('install-git', False)
|
||||
result = summary(cnr_custom_nodes={{}}, **pinned('{URL}'))
|
||||
''') == ['[ FAILED ] fixture']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@PINNED'), (1, '[ ENABLED ] fixture')])
|
||||
def test_registry_git_pack_that_is_enabled_is_listed_once(pinned_at, line):
|
||||
assert lines(f'''
|
||||
commits = repository(nodes / '.disabled/fixture')
|
||||
manager.nightly_inactive_nodes['fixture'] = str(nodes / '.disabled/fixture')
|
||||
in_registry()
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[{pinned_at}], 'disabled': False}}}})
|
||||
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[{pinned_at}]]
|
||||
''') == [line, True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@PINNED'), (1, '[ SKIPPED ] fixture')])
|
||||
def test_registry_git_pack_that_is_installed_is_listed_once(pinned_at, line):
|
||||
assert lines(f'''
|
||||
commits = repository(nodes / 'fixture')
|
||||
manager.active_nodes['fixture'] = ('nightly', str(nodes / 'fixture'))
|
||||
in_registry()
|
||||
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[{pinned_at}], 'disabled': False}}}})
|
||||
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[{pinned_at}]]
|
||||
''') == [line, True]
|
||||
|
||||
|
||||
INSTALLS = '''
|
||||
import os
|
||||
|
||||
def packs(**files):
|
||||
for name in ('first', 'second'):
|
||||
(nodes / name).mkdir()
|
||||
for file, text in files.items():
|
||||
(nodes / name / file).write_text(text)
|
||||
return str(nodes / 'first'), str(nodes / 'second')
|
||||
|
||||
def installs(*answers):
|
||||
answers, ran = list(answers), []
|
||||
|
||||
def try_install_script(url, repo_path, install_cmd, instant_execution=False):
|
||||
ran.append(os.path.basename(repo_path) + ' ' + install_cmd[-1])
|
||||
return answers.pop(0)
|
||||
|
||||
core.try_install_script = try_install_script
|
||||
core.cm_global.pip_overrides = {}
|
||||
manager_util.PIPFixer = Mock()
|
||||
manager_util.get_installed_packages = Mock(return_value={})
|
||||
return ran
|
||||
'''
|
||||
|
||||
|
||||
def install_steps(body):
|
||||
return lines(INSTALLS + body)
|
||||
|
||||
|
||||
def test_requirement_that_was_not_installed_is_tried_for_the_next_pack():
|
||||
assert install_steps('''
|
||||
first, second = packs(**{'requirements.txt': 'shareddep==1\\n'})
|
||||
ran = installs(False, True)
|
||||
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
|
||||
''') == [False, True, ['first shareddep==1', 'second shareddep==1']]
|
||||
|
||||
|
||||
def test_requirement_after_one_that_failed_is_tried_for_the_next_pack():
|
||||
assert install_steps('''
|
||||
first, second = packs(**{'requirements.txt': 'fails==1\\nshareddep==1\\n'})
|
||||
ran = installs(False, True, True)
|
||||
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
|
||||
''') == [False, True, ['first fails==1', 'second fails==1', 'second shareddep==1']]
|
||||
|
||||
|
||||
def test_requirement_that_was_installed_is_not_installed_twice():
|
||||
assert install_steps('''
|
||||
first, second = packs(**{'requirements.txt': 'shareddep==1\\n'})
|
||||
ran = installs(True)
|
||||
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
|
||||
''') == [True, True, ['first shareddep==1']]
|
||||
|
||||
|
||||
def test_install_script_that_failed_is_run_when_asked_again():
|
||||
assert install_steps('''
|
||||
first, _ = packs(**{'install.py': ''})
|
||||
ran = installs(False, True)
|
||||
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, first), ran]
|
||||
''') == [False, True, ['first install.py', 'first install.py']]
|
||||
|
||||
|
||||
def test_install_script_not_run_after_a_requirement_failed_is_run_when_asked_again():
|
||||
assert install_steps('''
|
||||
first, _ = packs(**{'requirements.txt': 'fails==1\\n', 'install.py': ''})
|
||||
ran = installs(False, True, True)
|
||||
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, first), ran]
|
||||
''') == [False, True, ['first fails==1', 'first fails==1', 'first install.py']]
|
||||
|
||||
|
||||
def test_install_script_of_a_pack_that_is_cloned_where_another_was_installed_is_run():
|
||||
assert install_steps(f'''
|
||||
first, _ = packs(**{{'install.py': ''}})
|
||||
ran = installs(True, True)
|
||||
manager.execute_install_script(None, first)
|
||||
os.rename(first, nodes / '.disabled')
|
||||
|
||||
def clone(url, path, **options):
|
||||
os.mkdir(path)
|
||||
open(os.path.join(path, 'install.py'), 'w').close()
|
||||
return Mock()
|
||||
|
||||
core.git.Repo.clone_from = clone
|
||||
result = [manager.repo_install('{URL}', first, instant_execution=True).result, ran]
|
||||
''') == [True, ['first install.py', 'first install.py']]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cloned', [True, False])
|
||||
def test_restore_tells_whether_every_step_was_done(cloned):
|
||||
assert lines(f'''
|
||||
manager.repo_install = answer('install-git', {cloned})
|
||||
core.repo_switch_commit = Mock(return_value=True)
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
result = restore(**pinned('{URL}'))
|
||||
''') is cloned
|
||||
|
||||
|
||||
@pytest.mark.parametrize('not_installed, restored', [([], True), (['alpha==1.0'], False)])
|
||||
def test_restore_tells_whether_every_pip_package_was_installed(not_installed, restored):
|
||||
assert lines(f'''
|
||||
manager_util.restore_pip_snapshot = Mock(return_value={not_installed})
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
result = restore()
|
||||
''') is restored
|
||||
|
||||
|
||||
class Exit(Exception):
|
||||
def __init__(self, code=0):
|
||||
self.code = code
|
||||
|
||||
|
||||
@pytest.mark.parametrize('restored, code', [(True, None), (False, 1)])
|
||||
def test_cm_cli_ends_with_1_when_a_step_of_the_restore_failed(tmp_path, restored, code):
|
||||
command = next(node for node in ast.parse(CM_CLI.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == 'restore_snapshot')
|
||||
command.decorator_list = []
|
||||
fixer = Mock()
|
||||
scope = {'typer': SimpleNamespace(Option=Mock(), Exit=Exit), 'Optional': Optional, 'os': os, 'asyncio': asyncio, 'traceback': traceback,
|
||||
'cmd_ctx': Mock(), 'comfy_path': '', 'manager_util': SimpleNamespace(PIPFixer=Mock(return_value=fixer), get_installed_packages=Mock()),
|
||||
'core': SimpleNamespace(restore_snapshot=AsyncMock(return_value=restored), manager_files_path='')}
|
||||
exec(compile(ast.Module(body=[command], type_ignores=[]), str(CM_CLI), 'exec'), scope)
|
||||
snapshot = tmp_path / 'snapshot.json'
|
||||
snapshot.touch()
|
||||
|
||||
ended = None
|
||||
try:
|
||||
scope['restore_snapshot'](str(snapshot), None, None, None, None, None)
|
||||
except Exit as e:
|
||||
ended = e.code
|
||||
|
||||
assert ended == code
|
||||
fixer.fix_broken.assert_called_once()
|
||||
@@ -0,0 +1,64 @@
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PRESTARTUP = Path(__file__).resolve().parent.parent / "prestartup_script.py"
|
||||
COMFY = os.path.join(os.sep, "opt", "ComfyUI")
|
||||
LAUNCHER = os.path.join(os.sep, "opt", "launcher")
|
||||
BASE = os.path.join(os.sep, "data", "comfy")
|
||||
|
||||
|
||||
def restore(tmp_path, monkeypatch, environ):
|
||||
scheduled = tmp_path / "restore-snapshot.json"
|
||||
scheduled.write_text("{}")
|
||||
block = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.If) and "'restore-snapshot'" in ast.unparse(node)]
|
||||
assert len(block) == 1
|
||||
|
||||
cli_args = types.ModuleType("comfy.cli_args")
|
||||
cli_args.args = types.SimpleNamespace(listen="127.0.0.1")
|
||||
monkeypatch.setitem(sys.modules, "comfy", types.ModuleType("comfy"))
|
||||
monkeypatch.setitem(sys.modules, "comfy.cli_args", cli_args)
|
||||
for name in ("COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
for name, value in environ.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
|
||||
started = []
|
||||
|
||||
def process_wrap(cmd, cwd=None, handler=None, env=None):
|
||||
started.append((cmd, cwd, env))
|
||||
return 0
|
||||
|
||||
exec(compile(ast.Module(body=block, type_ignores=[]), str(PRESTARTUP), "exec"), {
|
||||
"os": os, "sys": sys, "_has_system_user_api": True, "restore_snapshot_path": str(scheduled), "comfy_path": LAUNCHER,
|
||||
"cm_cli_path": "cm-cli.py", "custom_nodes_base_path": os.path.join(BASE, "custom_nodes"),
|
||||
"folder_paths": types.SimpleNamespace(__file__=os.path.join(COMFY, "folder_paths.py"),
|
||||
get_user_directory=lambda: os.path.join(BASE, "user")),
|
||||
"default_conf": {}, "manager_util": types.SimpleNamespace(is_loopback_listener=lambda listen: True),
|
||||
"process_wrap": process_wrap,
|
||||
})
|
||||
assert len(started) == 1 and not scheduled.exists()
|
||||
return started[0]
|
||||
|
||||
|
||||
def test_cm_cli_is_given_the_comfyui_path(tmp_path, monkeypatch):
|
||||
_, _, env = restore(tmp_path, monkeypatch, {})
|
||||
assert env.get("COMFYUI_PATH") == COMFY
|
||||
|
||||
|
||||
def test_cm_cli_is_given_the_directories_of_the_server(tmp_path, monkeypatch):
|
||||
cmd, _, _ = restore(tmp_path, monkeypatch, {})
|
||||
assert cmd[1:4] == ["cm-cli.py", "restore-snapshot", str(tmp_path / "restore-snapshot.json")]
|
||||
assert cmd[4:] == ["--user-directory", os.path.join(BASE, "user"),
|
||||
"--restore-to", os.path.join(BASE, "custom_nodes")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"])
|
||||
def test_a_path_set_in_the_environment_is_kept(tmp_path, monkeypatch, name):
|
||||
_, _, env = restore(tmp_path, monkeypatch, {name: os.path.join(os.sep, "elsewhere")})
|
||||
assert env[name] == os.path.join(os.sep, "elsewhere")
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Order of the rows the Custom Nodes Manager shows for a search, on the shipped grid in Chromium.
|
||||
|
||||
The search code is lifted from custom-nodes-manager.js and common.js and runs on the shipped
|
||||
ManagerGrid. Browser cases require Playwright and its Chromium install. All requests are
|
||||
intercepted locally; no ComfyUI server or external services are used.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import JsSource, slice_braced, slice_object_entry
|
||||
|
||||
JS_DIR = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
|
||||
JS = JsSource(JS_DIR)
|
||||
MANAGER = "custom-nodes-manager.js"
|
||||
|
||||
OPEN_GRID = """async (rows) => {
|
||||
const {default: ManagerGrid} = await import('/manager-grid.js');
|
||||
%(leven)s
|
||||
%(sanitize_html)s
|
||||
%(get_time_ago)s
|
||||
const manager = {
|
||||
keywords: '',
|
||||
filter: '',
|
||||
grid: new ManagerGrid(document.getElementById('grid')),
|
||||
setDisabled() {},
|
||||
%(show_loading)s,
|
||||
%(hide_loading)s,
|
||||
%(update_grid)s,
|
||||
%(on_keywords_change)s,
|
||||
%(calculate_sort_score)s,
|
||||
setOptions() { const grid = this.grid; %(set_option)s); }
|
||||
};
|
||||
manager.setOptions();
|
||||
rows.forEach((row, index) => { row.id = index + 1; });
|
||||
manager.grid.setData({rows, columns: [
|
||||
{id: 'id', name: 'ID'}, {id: 'title', name: 'Title'}, {id: 'author', name: 'Author'},
|
||||
{id: 'description', name: 'Description'}, {%(nodes_column)s}, {%(stars_column)s}, {%(last_update_column)s}]});
|
||||
manager.grid.render();
|
||||
window.manager = manager;
|
||||
}"""
|
||||
|
||||
|
||||
def _open_grid_script():
|
||||
source = JS.text(MANAGER)
|
||||
return OPEN_GRID % {
|
||||
"leven": JS.lift_span("common.js", "const levenArray = [];", "\treturn result;\n}").replace("export ", ""),
|
||||
"sanitize_html": JS.lift_declaration("common.js", "export function sanitizeHTML("),
|
||||
"get_time_ago": JS.lift_span("common.js", "export function getTimeAgo(dateStr) {", "\n}").replace("export ", ""),
|
||||
"show_loading": slice_braced(source, "\tshowLoading() "),
|
||||
"hide_loading": slice_braced(source, "\thideLoading() "),
|
||||
"update_grid": slice_braced(source, "\tupdateGrid() "),
|
||||
"on_keywords_change": JS.lift_span(MANAGER, "\tonKeywordsChange(e) {", "\t\t}, 300);\n\t}"),
|
||||
"calculate_sort_score": JS.lift_span(
|
||||
MANAGER, "\tcalculateSortScore(rowItem, searchableColumns) {", "\t\treturn 1 / distance;\n\t}"),
|
||||
"set_option": slice_braced(source, "grid.setOption("),
|
||||
"nodes_column": slice_object_entry(source, 'id: "nodes"'),
|
||||
"stars_column": slice_object_entry(source, "id: 'stars'"),
|
||||
"last_update_column": slice_object_entry(source, "id: 'last_update'"),
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def browser():
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
with playwright.sync_playwright() as driver:
|
||||
if not Path(driver.chromium.executable_path).exists():
|
||||
pytest.skip("install Chromium with: playwright install chromium")
|
||||
instance = driver.chromium.launch()
|
||||
yield instance
|
||||
instance.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def open_grid(browser):
|
||||
page = browser.new_page()
|
||||
|
||||
def route(request):
|
||||
name = request.request.url.rsplit("/", 1)[-1]
|
||||
if name in {"manager-grid.js", "turbogrid.esm.js"}:
|
||||
request.fulfill(path=str(JS_DIR / name), content_type="text/javascript")
|
||||
elif request.request.url == "http://manager.test/":
|
||||
request.fulfill(
|
||||
body='<div id="grid" style="width:900px;height:400px"></div>',
|
||||
content_type="text/html",
|
||||
)
|
||||
else:
|
||||
request.abort()
|
||||
|
||||
page.route("**/*", route)
|
||||
page.goto("http://manager.test/")
|
||||
|
||||
def open_with(rows):
|
||||
page.evaluate(_open_grid_script(), rows)
|
||||
page.wait_for_function("window.manager.grid.getViewRows().length === %d" % len(rows))
|
||||
return page
|
||||
|
||||
yield open_with
|
||||
page.close()
|
||||
|
||||
|
||||
def pack(title, stars=500):
|
||||
return {"title": title, "author": "author", "description": "nodes", "stars": stars}
|
||||
|
||||
|
||||
def shown(page):
|
||||
return page.evaluate("() => manager.grid.getViewRows().map(row => row.title)")
|
||||
|
||||
|
||||
def search(page, keywords):
|
||||
page.evaluate("(keywords) => manager.onKeywordsChange({target: {value: keywords}})", keywords)
|
||||
page.wait_for_function("(keywords) => manager.keywords === keywords", arg=keywords)
|
||||
return shown(page)
|
||||
|
||||
|
||||
def click_header(page, name):
|
||||
page.click('.tg-header-item .tg-column-name:text-is("%s")' % name)
|
||||
return shown(page)
|
||||
|
||||
|
||||
def sorted_headers(page):
|
||||
return page.evaluate("() => [...document.querySelectorAll('.tg-column-sorted')].map(x => x.textContent.trim())")
|
||||
|
||||
|
||||
def loading(page):
|
||||
return page.evaluate("() => getComputedStyle(document.querySelector('.tg-loading')).display !== 'none'")
|
||||
|
||||
|
||||
FACE_PACKS = ["Interface Tools", "Unrelated", "FaceTools", "face2video", "Face Detailer", "FACE MASK", "face swap"]
|
||||
BY_TITLE = ["Face Detailer", "FACE MASK", "face swap", "face2video", "FaceTools", "Interface Tools", "Unrelated"]
|
||||
|
||||
|
||||
def test_a_search_orders_the_rows_by_how_the_keyword_matches(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
assert search(page, "face") == [
|
||||
"face swap", "Face Detailer", "FACE MASK", "face2video", "FaceTools", "Interface Tools"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keywords", ["face mask", "face mask tools", "face mask tools set swap"])
|
||||
def test_the_case_of_every_keyword_weighs_less_than_one_match_inside_a_word(open_grid, keywords):
|
||||
# a digit after the keyword is the lightest way of being inside a word
|
||||
page = open_grid([pack(keywords + "2"), pack(keywords.upper())])
|
||||
assert search(page, keywords) == [keywords.upper(), keywords + "2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stars", [9000, 10000, 16860, 150000])
|
||||
def test_more_stars_never_lower_a_row(open_grid, stars):
|
||||
page = open_grid([pack("Alpha Manager", 120), pack("Beta Manager", stars)])
|
||||
assert search(page, "Manager") == ["Beta Manager", "Alpha Manager"]
|
||||
|
||||
|
||||
def test_a_row_without_a_star_count_is_ranked_by_its_text(open_grid):
|
||||
no_stars = pack("Interface Tools")
|
||||
del no_stars["stars"]
|
||||
page = open_grid([no_stars, pack("FaceTools", -1), pack("face swap")])
|
||||
assert search(page, "face") == ["face swap", "FaceTools", "Interface Tools"]
|
||||
|
||||
|
||||
def test_rows_that_match_alike_stay_in_the_listed_order_whatever_was_searched_before(open_grid):
|
||||
page = open_grid([pack("face alpha"), pack("face beta"), pack("Unrelated")])
|
||||
search(page, "beta")
|
||||
assert search(page, "face") == ["face alpha", "face beta"]
|
||||
|
||||
|
||||
def test_a_search_replaces_a_header_sort(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
assert click_header(page, "Title") == BY_TITLE
|
||||
assert search(page, "face")[0] == "face swap"
|
||||
assert sorted_headers(page) == []
|
||||
|
||||
|
||||
def test_clearing_the_search_brings_back_the_listed_order(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
search(page, "face")
|
||||
assert search(page, "") == FACE_PACKS
|
||||
|
||||
|
||||
def test_clearing_the_search_keeps_a_header_sort_made_during_it(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
search(page, "face")
|
||||
click_header(page, "Title")
|
||||
assert search(page, "") == BY_TITLE
|
||||
assert sorted_headers(page) == ["Title"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("header", ["Nodes", "★", "Last Update"])
|
||||
def test_the_first_click_on_a_header_of_counts_lists_the_highest_first(open_grid, header):
|
||||
low = dict(pack("low", 1), nodes=1, last_update="2024-01-01 00:00:00")
|
||||
high = dict(pack("high", 9), nodes=9, last_update="2025-01-01 00:00:00")
|
||||
page = open_grid([low, high])
|
||||
assert click_header(page, header) == ["high", "low"]
|
||||
|
||||
|
||||
def test_the_loading_of_a_search_ends_when_its_rows_are_shown(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
page.evaluate("() => { manager.showLoading(); manager.hideLoading(); }")
|
||||
page.evaluate("() => manager.onKeywordsChange({target: {value: 'face'}})")
|
||||
assert loading(page)
|
||||
page.wait_for_function("manager.keywords === 'face'")
|
||||
assert not loading(page)
|
||||
|
||||
|
||||
def test_a_search_that_is_still_waiting_leaves_the_loading_of_a_reload_on(open_grid):
|
||||
page = open_grid([pack(title) for title in FACE_PACKS])
|
||||
page.evaluate("() => { manager.onKeywordsChange({target: {value: 'face'}}); manager.showLoading(); }")
|
||||
page.wait_for_function("manager.keywords === 'face'")
|
||||
assert loading(page)
|
||||
page.evaluate("() => manager.hideLoading()")
|
||||
assert not loading(page)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""The server stores only a `db_mode`, an `update_policy` or a `component_policy` that the Manager knows.
|
||||
|
||||
Each case runs the real handler of `glob/manager_server.py` with the functions
|
||||
and the lists of values it uses; `core` holds a configuration in memory and
|
||||
counts how often it is written.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
SETTINGS = [
|
||||
("set_db_mode_handler", "db_mode", ["cache", "local", "remote"]),
|
||||
("set_update_policy_handler", "update_policy", ["stable-comfyui", "nightly-comfyui"]),
|
||||
("set_component_policy_handler", "component_policy", ["workflow", "higher", "mine"]),
|
||||
]
|
||||
NAMES = {handler for handler, key, values in SETTINGS} | {"set_db_mode", "set_update_policy", "set_component_policy"}
|
||||
BEFORE = "the value before the request"
|
||||
|
||||
|
||||
def post(handler, key, body):
|
||||
"""The status the handler answers, the stored value and how often the configuration was written."""
|
||||
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if (isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in NAMES)
|
||||
or (isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("ALLOWED_"))]
|
||||
config, written = {key: BEFORE}, []
|
||||
namespace = {
|
||||
"web": web, "routes": SimpleNamespace(post=lambda path: lambda function: function),
|
||||
"_reject_non_json_content_type": lambda request: None,
|
||||
"core": SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config))),
|
||||
}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<setting handlers>", "exec"), namespace)
|
||||
|
||||
async def read():
|
||||
return json.loads(body)
|
||||
|
||||
return asyncio.run(namespace[handler](SimpleNamespace(json=read))).status, config[key], len(written)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, value", [(handler, key, value) for handler, key, values in SETTINGS for value in values])
|
||||
def test_known_value_is_stored(handler, key, value):
|
||||
assert post(handler, key, json.dumps({"value": value})) == (200, value, 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, values", SETTINGS)
|
||||
@pytest.mark.parametrize("value", ['"no-such-value"', '""', '"CACHE"', "7", "null", '["cache"]'])
|
||||
def test_unknown_value_is_refused(handler, key, values, value):
|
||||
assert post(handler, key, '{"value": %s}' % value) == (400, BEFORE, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("handler, key, values", SETTINGS)
|
||||
@pytest.mark.parametrize("body", ["{}", "[]", '"cache"', "7", "null"])
|
||||
def test_request_without_a_value_is_refused(handler, key, values, body):
|
||||
assert post(handler, key, body) == (400, BEFORE, 0)
|
||||
@@ -55,14 +55,15 @@ def load_share_art(monkeypatch, output_dir, temp_dir, os_module: object = os):
|
||||
|
||||
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "share_art"]
|
||||
assert len(nodes) == 1
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in ("share_art", "is_matrix_org")]
|
||||
assert len(nodes) == 2
|
||||
namespace = {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
|
||||
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
|
||||
get_temp_directory=lambda: str(temp_dir)),
|
||||
"os": os_module, "web": web, "json": json, "mimetypes": mimetypes,
|
||||
"set_matrix_auth": lambda matrix_auth: None,
|
||||
"get_matrix_auth": lambda: None, "set_matrix_auth": lambda matrix_auth: None,
|
||||
"_reject_non_json_content_type": lambda request: None,
|
||||
}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
|
||||
return namespace["share_art"], uploads
|
||||
@@ -70,7 +71,7 @@ def load_share_art(monkeypatch, output_dir, temp_dir, os_module: object = os):
|
||||
|
||||
def share(share_art, output):
|
||||
body = {
|
||||
"matrix_auth": {"homeserver": "matrix.example", "username": "user", "password": "password"},
|
||||
"matrix_auth": {"homeserver": "matrix.org", "username": "user", "password": "password"},
|
||||
"share_destinations": ["matrix"], "credits": "", "title": "", "description": "",
|
||||
"prompt": {"workflow": {}}, "potential_outputs": [output], "selected_output_index": 0,
|
||||
}
|
||||
@@ -112,7 +113,7 @@ def test_a_file_in_the_directory_is_shared(monkeypatch, dirs, output, content):
|
||||
response = share(share_art, output)
|
||||
|
||||
assert response.status == 200
|
||||
assert uploads[0] == ("https://matrix.example", content)
|
||||
assert uploads[0] == ("https://matrix.org", content)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output", [
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
|
||||
|
||||
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
|
||||
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
|
||||
|
||||
ANSWERS = {
|
||||
"/manager/db_mode": "cache",
|
||||
"/manager/channel_url_list": {"list": ["default::https://example.invalid/channel"], "selected": "default"},
|
||||
}
|
||||
|
||||
MENUS = {
|
||||
"top bar": '<header id="topbar"></header><div class="comfy-menu" style="display: none"></div>',
|
||||
"old menu": '<div class="comfy-menu"></div>',
|
||||
}
|
||||
|
||||
STAND_INS = {
|
||||
"scripts/api.js": """
|
||||
class Api extends EventTarget {
|
||||
async fetchApi(path, options) {
|
||||
const answer = window.answers[path.split('?')[0]] ?? '';
|
||||
if(options?.method == 'POST' && path == '/manager/share_option') {
|
||||
window.saved = JSON.parse(options.body).value;
|
||||
}
|
||||
return {status: 200, json: async () => answer, text: async () => typeof answer == 'string' ? answer : JSON.stringify(answer)};
|
||||
}
|
||||
}
|
||||
export const api = new Api();
|
||||
""",
|
||||
"scripts/app.js": """
|
||||
import { ComfyDialog } from './ui.js';
|
||||
const settingsGroup = {element: document.createElement('div')};
|
||||
export const app = {
|
||||
ui: {dialog: new ComfyDialog()},
|
||||
graph: new (class { clear() {} })(),
|
||||
menu: {element: document.createElement('div'), settingsGroup},
|
||||
graphToPrompt: async () => ({}),
|
||||
registerExtension(extension) { window.extension = extension; },
|
||||
};
|
||||
app.graph._nodes = [];
|
||||
app.menu.element.append(settingsGroup.element);
|
||||
""",
|
||||
"scripts/ui.js": """
|
||||
const style = document.createElement('style');
|
||||
style.textContent = '.comfy-modal { display: none; position: fixed; z-index: 100; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px; background: #353535; color: #ddd; }';
|
||||
document.head.append(style);
|
||||
|
||||
export function $el(tag, propsOrChildren, children) {
|
||||
const [name, ...classes] = tag.split('.');
|
||||
const element = document.createElement(name);
|
||||
element.classList.add(...classes);
|
||||
if(typeof propsOrChildren == 'string') {
|
||||
propsOrChildren = {textContent: propsOrChildren};
|
||||
}
|
||||
else if(Array.isArray(propsOrChildren) || propsOrChildren instanceof Element) {
|
||||
children = propsOrChildren;
|
||||
propsOrChildren = {};
|
||||
}
|
||||
const {parent, $: callback, dataset, style, ...props} = propsOrChildren ?? {};
|
||||
Object.assign(element.style, style);
|
||||
Object.assign(element.dataset, dataset);
|
||||
Object.assign(element, props);
|
||||
if(children) {
|
||||
element.append(...[children].flat());
|
||||
}
|
||||
parent?.append(element);
|
||||
callback?.(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
export class ComfyDialog {
|
||||
constructor() {
|
||||
this.element = $el('div.comfy-modal', {parent: document.body}, [
|
||||
$el('div.comfy-modal-content', [
|
||||
$el('p', {$: (p) => (this.textElement = p)}),
|
||||
$el('button', {type: 'button', textContent: 'Close', onclick: () => this.close()}),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
close() {
|
||||
this.element.style.display = 'none';
|
||||
}
|
||||
|
||||
show(html) {
|
||||
this.textElement.innerHTML = html;
|
||||
this.element.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
""",
|
||||
"scripts/ui/components/button.js": """
|
||||
const style = document.createElement('style');
|
||||
style.textContent = '.comfyui-button { display: flex; }';
|
||||
document.head.append(style);
|
||||
|
||||
export class ComfyButton {
|
||||
constructor({icon, tooltip, content, action, classList = 'comfyui-button'}) {
|
||||
this.element = document.createElement('button');
|
||||
this.element.className = classList;
|
||||
this.element.title = tooltip;
|
||||
this.element.setAttribute('aria-label', tooltip);
|
||||
this.element.textContent = content ?? icon;
|
||||
this.element.addEventListener('click', (event) => action(event, this));
|
||||
}
|
||||
}
|
||||
""",
|
||||
"scripts/ui/components/buttonGroup.js": """
|
||||
export class ComfyButtonGroup {
|
||||
constructor(...buttons) {
|
||||
this.element = document.createElement('div');
|
||||
this.element.className = 'comfyui-button-group';
|
||||
this.element.append(...buttons);
|
||||
}
|
||||
}
|
||||
""",
|
||||
"extensions/core/groupNode.js": """
|
||||
export class GroupNodeConfig {}
|
||||
export class GroupNodeHandler {}
|
||||
""",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(browser): # noqa: F811
|
||||
page = browser.new_page()
|
||||
|
||||
def route(request):
|
||||
url = request.request.url
|
||||
name = url.rsplit("/", 1)[-1]
|
||||
stand_in = url.removeprefix("http://manager.test/")
|
||||
if url == "http://manager.test/":
|
||||
request.fulfill(body="<body></body>", content_type="text/html")
|
||||
elif url.startswith(EXTENSION) and (JS / name).is_file():
|
||||
request.fulfill(path=str(JS / name), content_type="text/css" if name.endswith(".css") else "text/javascript")
|
||||
elif stand_in in STAND_INS:
|
||||
request.fulfill(body=STAND_INS[stand_in], content_type="text/javascript")
|
||||
else:
|
||||
request.abort()
|
||||
|
||||
page.route("**/*", route)
|
||||
page.add_init_script("""
|
||||
window.errors = [];
|
||||
addEventListener('error', (event) => errors.push(String(event.error ?? event.message)));
|
||||
addEventListener('unhandledrejection', (event) => errors.push(String(event.reason)));
|
||||
""")
|
||||
page.goto("http://manager.test/")
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
def load(page, menu, share_option):
|
||||
page.evaluate("""async ({module, body, answers, share_option}) => {
|
||||
document.body.innerHTML = body;
|
||||
window.answers = {...answers, '/manager/share_option': share_option};
|
||||
await import(module);
|
||||
window.extension.init();
|
||||
await window.extension.setup();
|
||||
const { app } = await import('/scripts/app.js');
|
||||
document.getElementById('topbar')?.append(app.menu.element);
|
||||
}""", {"module": EXTENSION + "comfyui-manager.js", "body": MENUS[menu], "answers": ANSWERS, "share_option": share_option})
|
||||
|
||||
|
||||
def share_buttons(page):
|
||||
return page.get_by_role("button", name="Share", exact=True)
|
||||
|
||||
|
||||
def choose_share(page, value):
|
||||
page.evaluate("window.extension.commands.find((command) => command.id == 'Comfy.Manager.Menu.ToggleVisibility').function()")
|
||||
page.locator(".setting-item", has=page.get_by_text("Share", exact=True)).locator("select").select_option(value)
|
||||
page.wait_for_function("window.saved == '%s'" % value)
|
||||
page.get_by_role("button", name="Close", exact=True).first.click()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("menu", MENUS)
|
||||
@pytest.mark.parametrize("share_option", ["all", "youml", "matrix", "none"])
|
||||
def test_the_share_button_of_the_menu_follows_the_saved_share_setting(page, menu, share_option):
|
||||
load(page, menu, share_option)
|
||||
|
||||
assert share_buttons(page).count() == (0 if share_option == "none" else 1)
|
||||
assert page.evaluate("errors") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("menu", MENUS)
|
||||
def test_choosing_none_in_the_manager_menu_hides_the_share_button_and_all_shows_it(page, menu):
|
||||
load(page, menu, "all")
|
||||
|
||||
choose_share(page, "none")
|
||||
assert share_buttons(page).count() == 0
|
||||
|
||||
choose_share(page, "all")
|
||||
assert share_buttons(page).count() == 1
|
||||
assert page.evaluate("errors") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("menu", MENUS)
|
||||
@pytest.mark.parametrize("share_option, opened", [
|
||||
("all", "Choose a platform to share your workflow"),
|
||||
("youml", "Share your workflow to YouML.com"),
|
||||
("matrix", "No supported output node found"),
|
||||
], ids=["all", "youml", "matrix"])
|
||||
def test_a_click_on_the_share_button_opens_what_the_share_setting_says(page, menu, share_option, opened):
|
||||
page.evaluate("window.alert = (message) => { window.alerted = message; }")
|
||||
load(page, menu, share_option)
|
||||
|
||||
share_buttons(page).click()
|
||||
|
||||
page.wait_for_function("""(opened) => window.alerted?.includes(opened)
|
||||
|| [...document.querySelectorAll('.comfy-modal')].some((box) => box.checkVisibility() && box.innerText.includes(opened))""", arg=opened)
|
||||
assert page.evaluate("errors") == []
|
||||
@@ -0,0 +1,224 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
|
||||
|
||||
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
|
||||
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
|
||||
|
||||
SAVED = {"homeserver": "matrix.org", "username": "user"}
|
||||
ASK_FOR_ACCOUNT = "Please set your Matrix account details."
|
||||
|
||||
SCRIPTS = {
|
||||
"api.js": """
|
||||
export const api = {
|
||||
addEventListener() {},
|
||||
async fetchApi(path, options) {
|
||||
window.requested.push({path, method: options?.method ?? 'GET', body: options?.body ? JSON.parse(options.body) : null});
|
||||
if(path == '/manager/get_matrix_auth') {
|
||||
if(window.offline) throw new TypeError('Failed to fetch');
|
||||
if(window.saved) return {status: 200, json: async () => window.saved};
|
||||
return {status: 404, json: async () => { throw new SyntaxError('Unexpected end of JSON input'); }};
|
||||
}
|
||||
return {status: 200, json: async () => ({matrix: {success: true}})};
|
||||
}
|
||||
};
|
||||
""",
|
||||
"app.js": """
|
||||
const image = {filename: 'a.png', subfolder: '', type: 'output'};
|
||||
export const app = {
|
||||
graph: {_nodes: [{type: 'SaveImage', id: 1, title: 'Save Image', images: [image]}]},
|
||||
graphToPrompt: async () => ({workflow: {}, output: {}}),
|
||||
ui: {dialog: {element: document.body, show() {}}},
|
||||
};
|
||||
""",
|
||||
"ui.js": """
|
||||
export function $el(tag, props, children) {
|
||||
const names = tag.split('.');
|
||||
const element = document.createElement(names.shift());
|
||||
element.classList.add(...names);
|
||||
const {parent, style, ...rest} = props ?? {};
|
||||
Object.assign(element.style, style);
|
||||
Object.assign(element, rest);
|
||||
element.append(...(children ?? []));
|
||||
parent?.append(element);
|
||||
return element;
|
||||
}
|
||||
export class ComfyDialog {
|
||||
close() { this.element.style.display = 'none'; }
|
||||
}
|
||||
""",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(browser): # noqa: F811
|
||||
page = browser.new_page()
|
||||
|
||||
def route(request):
|
||||
url = request.request.url
|
||||
name = url.rsplit("/", 1)[-1]
|
||||
if url == "http://manager.test/":
|
||||
request.fulfill(body="<body></body>", content_type="text/html")
|
||||
elif url.startswith(EXTENSION) and (JS / name).is_file():
|
||||
request.fulfill(path=str(JS / name), content_type="text/javascript")
|
||||
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
|
||||
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
|
||||
else:
|
||||
request.abort()
|
||||
|
||||
page.route("**/*", route)
|
||||
page.errors = []
|
||||
page.alerts = []
|
||||
page.on("pageerror", lambda error: page.errors.append(str(error)))
|
||||
page.on("dialog", lambda dialog: (page.alerts.append(dialog.message), dialog.dismiss()))
|
||||
page.goto("http://manager.test/")
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
def open_dialog(page, saved, offline=False):
|
||||
page.evaluate("""async ({saved, offline, module}) => {
|
||||
window.requested = [];
|
||||
window.saved = saved;
|
||||
window.offline = offline;
|
||||
const { ShareDialog, getPotentialOutputsAndOutputNodes } = await import(module);
|
||||
const { app } = await import('/scripts/app.js');
|
||||
window.dialog = new ShareDialog();
|
||||
window.dialog.show(getPotentialOutputsAndOutputNodes(app.graph._nodes));
|
||||
}""", {"saved": saved, "offline": offline, "module": EXTENSION + "comfyui-share-common.js"})
|
||||
page.wait_for_timeout(200)
|
||||
|
||||
|
||||
def fields(page):
|
||||
return page.evaluate("""() => ({
|
||||
homeserver: dialog.matrix_homeserver_input.value,
|
||||
username: dialog.matrix_username_input.value,
|
||||
password: dialog.matrix_password_input.value,
|
||||
})""")
|
||||
|
||||
|
||||
def share_to_matrix(page, matrix=True, **typed):
|
||||
page.evaluate("""async ({typed, matrix}) => {
|
||||
for(const [name, value] of Object.entries(typed)) {
|
||||
dialog[`matrix_${name}_input`].value = value;
|
||||
}
|
||||
dialog.matrix_destination_checkbox.checked = matrix;
|
||||
await dialog.share_button.onclick();
|
||||
}""", {"typed": typed, "matrix": matrix})
|
||||
page.wait_for_timeout(200)
|
||||
|
||||
|
||||
def shared(page):
|
||||
return [request["body"]["matrix_auth"] for request in page.evaluate("window.requested")
|
||||
if request["path"] == "/manager/share"]
|
||||
|
||||
|
||||
def test_the_saved_account_is_shown_without_its_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
assert fields(page) == {**SAVED, "password": ""}
|
||||
assert "Saved password" in page.evaluate("dialog.matrix_password_input.placeholder")
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_the_saved_account_is_shared_with_an_empty_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page)
|
||||
|
||||
assert shared(page) == [{**SAVED, "password": ""}]
|
||||
assert page.alerts == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_another_account_needs_a_password(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
|
||||
|
||||
def test_the_homeserver_cannot_be_typed(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
assert page.evaluate("dialog.matrix_homeserver_input.readOnly") is True
|
||||
assert fields(page)["homeserver"] == "matrix.org"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("homeserver", ["other.example", "https://matrix.org", "", None],
|
||||
ids=["another homeserver", "matrix.org with a scheme", "empty", "null"])
|
||||
def test_a_saved_homeserver_does_not_reach_the_field_or_the_request(page, homeserver):
|
||||
open_dialog(page, {"homeserver": homeserver, "username": "user"})
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "user", "password": ""}
|
||||
|
||||
share_to_matrix(page)
|
||||
|
||||
assert shared(page) == [{"homeserver": "matrix.org", "username": "user", "password": ""}]
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_typed_password_is_sent(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else", password="a new password")
|
||||
|
||||
assert shared(page) == [{"homeserver": "matrix.org", "username": "someone-else", "password": "a new password"}]
|
||||
assert page.alerts == []
|
||||
|
||||
|
||||
def test_without_a_saved_account_a_password_is_needed(page):
|
||||
open_dialog(page, None)
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
|
||||
assert page.evaluate("dialog.matrix_password_input.placeholder") == "Password"
|
||||
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_the_account_that_was_shared_is_the_saved_one_afterwards(page):
|
||||
open_dialog(page, SAVED)
|
||||
share_to_matrix(page, username="someone-else", password="a new password")
|
||||
|
||||
share_to_matrix(page, username="user", password="")
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
|
||||
share_to_matrix(page, username="someone-else", password="")
|
||||
assert shared(page)[1:] == [{"homeserver": "matrix.org", "username": "someone-else", "password": ""}]
|
||||
|
||||
|
||||
def test_a_field_changed_and_changed_back_is_the_saved_account(page):
|
||||
open_dialog(page, SAVED)
|
||||
|
||||
share_to_matrix(page, username="someone-else")
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == [{**SAVED, "password": ""}]
|
||||
|
||||
|
||||
def test_the_saved_account_that_cannot_be_read_is_no_saved_account(page):
|
||||
open_dialog(page, SAVED, offline=True)
|
||||
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
|
||||
|
||||
share_to_matrix(page, username="user")
|
||||
|
||||
assert page.alerts == [ASK_FOR_ACCOUNT]
|
||||
assert shared(page) == []
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_sharing_without_matrix_needs_no_account(page):
|
||||
open_dialog(page, None)
|
||||
|
||||
share_to_matrix(page, matrix=False)
|
||||
|
||||
assert page.alerts == []
|
||||
assert page.evaluate("window.requested.at(-1).body.share_destinations") == []
|
||||
@@ -0,0 +1,119 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from manager_test_utils import GLOB_DIR
|
||||
|
||||
MENU = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")) / "comfyui-manager.js"
|
||||
CHOICES = ["all", "none", "youml", "matrix"]
|
||||
ROUTE = "/manager/share_option"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def route():
|
||||
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
|
||||
nodes = [node for node in ast.parse(source).body
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name in ("share_option", "set_share_option")
|
||||
or isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "SHARE_OPTIONS"]
|
||||
assert len(nodes) == 3
|
||||
check = next(node for node in ast.parse((GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name == "_reject_non_json_content_type")
|
||||
routes = web.RouteTableDef()
|
||||
config, written, read = {"share_option": "all"}, [], []
|
||||
namespace = {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)), "web": web, "json": json,
|
||||
"core": SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config))),
|
||||
}
|
||||
exec(compile(ast.Module(body=[check, *nodes], type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
|
||||
|
||||
def get(query):
|
||||
response = asyncio.run(namespace["share_option"](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
|
||||
return response.status, response.text
|
||||
|
||||
def post(body, content_type="application/json"):
|
||||
async def read_json():
|
||||
read.append(True)
|
||||
return json.loads(body)
|
||||
|
||||
return asyncio.run(namespace["set_share_option"](SimpleNamespace(content_type=content_type, json=read_json))).status
|
||||
|
||||
return SimpleNamespace(get=get, post=post, config=config, written=written, read=read, choices=namespace["SHARE_OPTIONS"],
|
||||
methods=sorted((entry.method, entry.path) for entry in routes))
|
||||
|
||||
|
||||
def test_the_choices_are_those_of_the_share_menu(route):
|
||||
menu = re.search(r"const share_options = \[(.*?)\];", MENU.read_text(encoding="utf-8"), re.S).group(1)
|
||||
|
||||
assert sorted(route.choices) == sorted(re.findall(r"\['(\w+)',", menu)) == sorted(CHOICES)
|
||||
|
||||
|
||||
def test_the_option_is_read_with_get_and_saved_with_post(route):
|
||||
assert route.methods == [("GET", ROUTE), ("POST", ROUTE)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", CHOICES)
|
||||
@pytest.mark.parametrize("value", CHOICES)
|
||||
def test_a_choice_of_the_menu_is_saved(route, saved, value):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.post(json.dumps({"value": value})) == 200
|
||||
assert route.written == [{"share_option": value}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [
|
||||
"", " ", "ALL", "All", "all ", " all", "all,none", "none\n", "openart", "comfyworkflows", "true", "<b>all</b>", "all\x00",
|
||||
"a" * 5000, None, 0, 1, True, ["all"], {"all": "none"},
|
||||
], ids=repr)
|
||||
@pytest.mark.parametrize("saved", ["all", "none"])
|
||||
def test_any_other_value_is_refused_and_nothing_is_saved(route, saved, value):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.post(json.dumps({"value": value})) == 400
|
||||
assert route.config == {"share_option": saved}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", ['{}', '{"other": "none"}', '[]', '["value"]', '"none"', 'null', '1', '', '{"value": "none"', 'value=none',
|
||||
b'{"value": "\xff"}', b'\xff\xfe'], ids=repr)
|
||||
def test_a_body_without_a_value_is_refused_and_nothing_is_saved(route, body):
|
||||
assert route.post(body) == 400
|
||||
assert route.config == {"share_option": "all"}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data",
|
||||
"application/octet-stream"])
|
||||
def test_a_value_that_is_not_sent_as_json_is_refused_before_the_body_is_read(route, content_type):
|
||||
assert route.post(json.dumps({"value": "none"}), content_type) == 400
|
||||
assert route.read == []
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("saved", [*CHOICES, "openart", ""], ids=lambda saved: saved or "empty")
|
||||
def test_get_answers_the_saved_option_as_it_is(route, saved):
|
||||
route.config["share_option"] = saved
|
||||
|
||||
assert route.get({}) == (200, saved)
|
||||
assert route.written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [*CHOICES, "openart"])
|
||||
def test_get_saves_nothing_whatever_it_is_given(route, value):
|
||||
assert route.get({"value": value}) == (200, "all")
|
||||
assert route.config == {"share_option": "all"}
|
||||
assert route.written == []
|
||||
|
||||
|
||||
def test_the_menu_saves_the_option_with_a_json_post():
|
||||
source = MENU.read_text(encoding="utf-8")
|
||||
|
||||
assert "share_option?value=" not in source
|
||||
assert re.search(r"fetchApi\(\s*'/manager/share_option'\s*,\s*\{[^;]*?\bmethod:\s*'POST'[^;]*?\bbody:\s*JSON\.stringify\(\{\s*value\s*\}\)",
|
||||
source)
|
||||
@@ -0,0 +1,49 @@
|
||||
from test_snapshot_restore_pins import run
|
||||
|
||||
PACKS = '''
|
||||
import ast, io
|
||||
from typing_extensions import Annotated
|
||||
import typer
|
||||
from rich.console import Console
|
||||
|
||||
def show(name, kind):
|
||||
found = [node for node in ast.parse(pathlib.Path('cm-cli.py').read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name in (name, 'show_list')]
|
||||
for node in found:
|
||||
node.decorator_list = []
|
||||
out = io.StringIO()
|
||||
scope = {'typer': typer, 'Annotated': Annotated, 'asyncio': asyncio, 'os': os,
|
||||
'print': Console(file=out, width=1000, color_system=None).print, 'cmd_ctx': Mock(), 'unified_manager': manager}
|
||||
exec(compile(ast.Module(body=found, type_ignores=[]), 'cm-cli.py', 'exec'), scope)
|
||||
scope[name](kind, None, None, None)
|
||||
return [' '.join(line.split()) for line in out.getvalue().splitlines()]
|
||||
|
||||
manager.get_custom_nodes = AsyncMock(return_value={
|
||||
'listed-pack': {'title': 'Listed Pack', 'author': 'someone', 'files': ['https://github.com/someone/listed-pack']},
|
||||
})
|
||||
manager.cnr_map['registry-pack'] = {'id': 'registry-pack', 'name': 'Registry Pack', 'publisher': {'name': 'someone'},
|
||||
'latest_version': {'version': '1.0.0'}}
|
||||
manager.active_nodes['registry-pack'] = ('1.0.0', str(nodes / 'registry-pack'))
|
||||
manager.unknown_active_nodes['listed-pack'] = ('https://github.com/someone/listed-pack', str(nodes / 'listed-pack'))
|
||||
manager.unknown_active_nodes['git-pack'] = ('https://example.invalid/git-pack', str(nodes / 'git-pack'))
|
||||
manager.unknown_inactive_nodes['old-git-pack'] = ('https://example.invalid/old-git-pack', str(nodes / '.disabled/old-git-pack'))
|
||||
'''
|
||||
|
||||
|
||||
def shown(*commands):
|
||||
return run(PACKS + f'print(json.dumps([show(name, kind) for name, kind in {list(commands)!r}]))')
|
||||
|
||||
|
||||
def test_simple_show_lists_every_installed_nodepack():
|
||||
assert shown(('simple_show', 'enabled'), ('simple_show', 'disabled'), ('simple_show', 'installed')) == [
|
||||
['Registry Pack@1.0.0', 'Listed Pack@unknown', 'git-pack@unknown'],
|
||||
['old-git-pack@unknown'],
|
||||
['Registry Pack@1.0.0', 'Listed Pack@unknown', 'git-pack@unknown', 'old-git-pack@unknown'],
|
||||
]
|
||||
|
||||
|
||||
def test_show_names_a_git_nodepack_that_the_lists_do_not_know_by_its_id():
|
||||
assert shown(('show', 'installed'))[0][2:] == [
|
||||
'[ ENABLED ] git-pack git-pack (author: N/A ) [UNKNOWN]',
|
||||
'[ DISABLED ] old-git-pack old-git-pack (author: N/A ) [UNKNOWN]',
|
||||
]
|
||||
@@ -0,0 +1,55 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import json
|
||||
import pathlib
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import typer
|
||||
from rich import print
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from test_core_print import core_print
|
||||
|
||||
CM_CLI = pathlib.Path(__file__).resolve().parent.parent / 'cm-cli.py'
|
||||
|
||||
COMFYUI = 'f0123456789abcdef0123456789abcdef0123456'
|
||||
PACK = 'abcdef0123456789abcdef0123456789abcdef01'
|
||||
URL = 'https://gitlab.com/group/' + 'subgroup/' * 30 + 'pack'
|
||||
SNAPSHOT = {
|
||||
'comfyui': COMFYUI,
|
||||
'git_custom_nodes': {URL: {'hash': PACK, 'disabled': False}},
|
||||
'cnr_custom_nodes': {'registry-pack': '1.0.0'},
|
||||
'file_custom_nodes': [{'filename': 'single.py', 'disabled': False}],
|
||||
'pips': {'torch': '2.0.0'},
|
||||
}
|
||||
|
||||
|
||||
def command(name):
|
||||
async def get_current_snapshot():
|
||||
return SNAPSHOT
|
||||
|
||||
found = [node for node in ast.parse(CM_CLI.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in (name, 'show_snapshot')]
|
||||
for node in found:
|
||||
node.decorator_list = []
|
||||
scope = {'typer': typer, 'Annotated': Annotated, 'asyncio': asyncio, 'json': json, 'print': print,
|
||||
'core': SimpleNamespace(get_current_snapshot=get_current_snapshot, print=core_print()), 'cmd_ctx': Mock()}
|
||||
exec(compile(ast.Module(body=found, type_ignores=[]), str(CM_CLI), 'exec'), scope)
|
||||
return scope[name]
|
||||
|
||||
|
||||
def test_show_snapshot_prints_the_current_snapshot(capsys):
|
||||
command('show')('snapshot', None, None, None)
|
||||
|
||||
assert json.loads(capsys.readouterr().out) == SNAPSHOT
|
||||
|
||||
|
||||
def test_simple_show_snapshot_prints_a_line_per_nodepack(capsys):
|
||||
command('simple_show')('snapshot', None, None, None)
|
||||
|
||||
assert capsys.readouterr().out.splitlines() == [
|
||||
f'[{COMFYUI}] comfyui',
|
||||
f'[{PACK}] {URL}',
|
||||
'[ N/A ] single.py',
|
||||
]
|
||||
@@ -0,0 +1,71 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from test_comfyui_downgrade_level import LEVELS, functions
|
||||
|
||||
SERVER = {"is_allowed_security_level", "security_403_response", "_reject_non_json_content_type", "restore_snapshot"}
|
||||
|
||||
|
||||
def restore_allowed(security_level, loopback):
|
||||
return security_level == "weak" or security_level == "normal-" and loopback
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(tmp_path):
|
||||
snapshot = tmp_path / "snapshots" / "saved.json"
|
||||
snapshot.parent.mkdir()
|
||||
snapshot.write_text("{}", encoding="utf-8")
|
||||
scheduled = tmp_path / "startup-scripts" / "restore-snapshot.json"
|
||||
|
||||
def restore(security_level, loopback, body={"target": "saved"}, content_type="application/json"):
|
||||
namespace = {
|
||||
"routes": web.RouteTableDef(), "web": web, "logging": logging, "os": os, "shutil": shutil,
|
||||
"is_local_mode": loopback,
|
||||
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level},
|
||||
manager_startup_script_path=str(scheduled.parent)),
|
||||
"manager_migration": SimpleNamespace(has_system_user_api=lambda: True),
|
||||
"get_safe_snapshot_path": lambda target: str(snapshot) if target == "saved" else None,
|
||||
}
|
||||
exec(functions("manager_server.py", SERVER), namespace)
|
||||
|
||||
async def read_json():
|
||||
return body
|
||||
|
||||
response = asyncio.run(namespace["restore_snapshot"](SimpleNamespace(json=read_json, content_type=content_type)))
|
||||
return response.status, scheduled.exists()
|
||||
|
||||
return restore
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
def test_a_restore_needs_the_level_of_a_switch_to_an_older_version(server, security_level, loopback):
|
||||
status, scheduled = server(security_level, loopback)
|
||||
|
||||
if restore_allowed(security_level, loopback):
|
||||
assert (status, scheduled) == (200, True)
|
||||
else:
|
||||
assert (status, scheduled) == (403, False)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("body", [{"target": "another"}, {"target": ""}, {"target": None}, {}, {"target": ["saved"]}],
|
||||
ids=["a snapshot that does not exist", "an empty name", "null", "no target", "a list"])
|
||||
def test_a_request_for_no_snapshot_schedules_nothing_at_any_level(server, security_level, loopback, body):
|
||||
status, scheduled = server(security_level, loopback, body)
|
||||
|
||||
assert status == (400 if restore_allowed(security_level, loopback) else 403)
|
||||
assert scheduled is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("security_level", LEVELS)
|
||||
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/octet-stream"])
|
||||
def test_a_body_that_is_not_json_is_refused_before_the_level(server, security_level, content_type):
|
||||
assert server(security_level, True, content_type=content_type) == (400, False)
|
||||
@@ -27,7 +27,7 @@ core = manager_core
|
||||
nodes = pathlib.Path(tmp) / 'custom_nodes'
|
||||
nodes.mkdir()
|
||||
core.get_default_custom_nodes_path = lambda: str(nodes)
|
||||
manager_util.restore_pip_snapshot = Mock()
|
||||
manager_util.restore_pip_snapshot = Mock(return_value=[])
|
||||
manager = core.UnifiedManager()
|
||||
manager.reload = AsyncMock()
|
||||
manager.get_custom_nodes = AsyncMock(return_value={})
|
||||
@@ -36,7 +36,7 @@ core.unified_manager = manager
|
||||
def restore(**snapshot):
|
||||
path = pathlib.Path(tmp) / 'snapshot.json'
|
||||
path.write_text(json.dumps({'cnr_custom_nodes': {}, 'git_custom_nodes': {}, 'file_custom_nodes': [], **snapshot}))
|
||||
asyncio.run(core.restore_snapshot(str(path)))
|
||||
return asyncio.run(core.restore_snapshot(str(path)))
|
||||
|
||||
def git(*args):
|
||||
return subprocess.run(['git', *args], cwd=nodes / 'fixture', check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from js_lift import NODE, JsSource, run_node, slice_braced
|
||||
|
||||
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
|
||||
|
||||
|
||||
def switch(version, status, versions_status=200):
|
||||
script = """
|
||||
const shown = [], requested = [];
|
||||
const api = {fetchApi: async (path, options) => {
|
||||
if(path == '/comfyui_manager/comfyui_versions') {
|
||||
return {status: %s, json: async () => ({versions: ['nightly', 'v0.3.60'], current: 'v0.3.59'})};
|
||||
}
|
||||
requested.push({path, body: JSON.parse(options.body)});
|
||||
return {status: path == '/comfyui_manager/comfyui_switch_version' ? %s : 200};
|
||||
}};
|
||||
const switch_comfyui_button = {style: {}};
|
||||
const update_policy_combo = {value: 'unchanged'};
|
||||
let update_policy_chosen = false;
|
||||
let chosen;
|
||||
const showVersionSelectorDialog = (versions, current, onSelect) => { chosen = onSelect(%s); };
|
||||
const infoToast = (text) => shown.push('toast: ' + text);
|
||||
const customAlert = (text) => shown.push('alert: ' + text);
|
||||
const handle403Response = async () => shown.push('security level message');
|
||||
%s
|
||||
await switchComfyUI();
|
||||
await chosen;
|
||||
console.log(JSON.stringify({shown, requested, update_policy: update_policy_combo.value, update_policy_chosen,
|
||||
button_disabled: switch_comfyui_button.disabled}));
|
||||
""" % (json.dumps(versions_status), json.dumps(status), json.dumps(version),
|
||||
slice_braced(JS.text("comfyui-manager.js"), "async function switchComfyUI()"))
|
||||
return run_node(script)
|
||||
|
||||
|
||||
def switch_request(version):
|
||||
return {"path": "/comfyui_manager/comfyui_switch_version", "body": {"ver": version}}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version, update_policy", [("nightly", "nightly-comfyui"), ("v0.3.60", "stable-comfyui")])
|
||||
def test_a_switch_that_happened_sets_the_update_policy_of_the_version(version, update_policy):
|
||||
did = switch(version, 200)
|
||||
|
||||
assert did["requested"] == [switch_request(version), {"path": "/manager/policy/update", "body": {"value": update_policy}}]
|
||||
assert did["update_policy"] == update_policy
|
||||
assert did["update_policy_chosen"] is True
|
||||
assert did["shown"] == ["toast: ComfyUI version is switched to " + version]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", ["nightly", "v0.3.60"])
|
||||
@pytest.mark.parametrize("status, shown", [
|
||||
(403, "security level message"),
|
||||
(400, "alert: Failed to switch ComfyUI version."),
|
||||
(500, "alert: Failed to switch ComfyUI version."),
|
||||
])
|
||||
def test_a_switch_that_did_not_happen_leaves_the_update_policy(version, status, shown):
|
||||
did = switch(version, status)
|
||||
|
||||
assert did["requested"] == [switch_request(version)]
|
||||
assert did["update_policy"] == "unchanged"
|
||||
assert did["update_policy_chosen"] is False
|
||||
assert did["shown"] == [shown]
|
||||
|
||||
|
||||
def test_without_the_list_of_versions_nothing_is_switched():
|
||||
did = switch("v0.3.60", 200, versions_status=400)
|
||||
|
||||
assert did["requested"] == []
|
||||
assert did["shown"] == ["alert: Failed to fetch ComfyUI versions."]
|
||||
assert did["button_disabled"] is False
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user