Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7494883c93 | ||
|
|
347473e689 | ||
|
|
4bbdb2e95f | ||
|
|
455ad3acd0 | ||
|
|
e32d3a4a71 | ||
|
|
899819d230 | ||
|
|
a1b0264744 | ||
|
|
9f1faeb0f5 | ||
|
|
fef6b412fc | ||
|
|
780c199dc7 | ||
|
|
25ca413586 | ||
|
|
7f28788cd5 | ||
|
|
a930773408 | ||
|
|
aa1620c608 | ||
|
|
b73b9ea0d9 | ||
|
|
9107e8fa3a | ||
|
|
4367158b50 | ||
|
|
b08783e963 | ||
|
|
d8867456d1 | ||
|
|
6e1ee9529d | ||
|
|
3a72e71f91 | ||
|
|
13a10217e7 | ||
|
|
9f967363e2 | ||
|
|
d157bb9b32 | ||
|
|
1c9e57f72a | ||
|
|
3badbaaebc | ||
|
|
685618664d | ||
|
|
a48433cc9a | ||
|
|
14626f8602 | ||
|
|
cd9114a933 | ||
|
|
2479e8c26e | ||
|
|
8c2a67a7b3 | ||
|
|
1c3a47b6ce | ||
|
|
3726fbcfb1 | ||
|
|
9d5f65827c | ||
|
|
89079387cf | ||
|
|
5ab11da187 | ||
|
|
ba3fd681e1 | ||
|
|
b76eb11207 | ||
|
|
b4528eedb7 | ||
|
|
7a6a72d7e9 | ||
|
|
a4cb6f5b3f | ||
|
|
8dd1967fde | ||
|
|
5986d2237c | ||
|
|
175e085fcf | ||
|
|
2bb25594b8 | ||
|
|
72f05493e5 | ||
|
|
857e2ca5a5 | ||
|
|
9e72648931 | ||
|
|
ad3a2b862b | ||
|
|
c53ee36f30 | ||
|
|
573742e800 | ||
|
|
e519c56057 | ||
|
|
50131e3bb7 | ||
|
|
dbdb642ed2 | ||
|
|
215d7d4cb0 |
@@ -37,7 +37,8 @@ jobs:
|
||||
|
||||
code-quality:
|
||||
name: Code Quality Checks
|
||||
runs-on: ubuntu-latest
|
||||
# Use a fixed image for syntax checks; E2E separately tests the latest runners.
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -52,11 +53,13 @@ jobs:
|
||||
files_ignore: |
|
||||
comfyui_manager/legacy/**
|
||||
|
||||
- name: Setup Python
|
||||
if: steps.changed-py-files.outputs.any_changed == 'true'
|
||||
- name: Setup minimum supported Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: '3.9'
|
||||
python-version: '3.10'
|
||||
|
||||
- name: Check syntax on minimum supported Python
|
||||
run: python -m compileall -q comfyui_manager cm_cli
|
||||
|
||||
- name: Install dependencies
|
||||
if: steps.changed-py-files.outputs.any_changed == 'true'
|
||||
@@ -67,4 +70,4 @@ jobs:
|
||||
if: steps.changed-py-files.outputs.any_changed == 'true'
|
||||
run: |
|
||||
echo "Changed files: ${{ steps.changed-py-files.outputs.all_changed_files }}"
|
||||
echo "${{ steps.changed-py-files.outputs.all_changed_files }}" | xargs -r ruff check
|
||||
echo "${{ steps.changed-py-files.outputs.all_changed_files }}" | xargs -r ruff check
|
||||
|
||||
@@ -58,6 +58,7 @@ jobs:
|
||||
shell: bash
|
||||
env:
|
||||
MANAGER_ROOT: ${{ github.workspace }}
|
||||
UV_PYTHON: ${{ matrix.python-version }}
|
||||
run: |
|
||||
python tests/e2e/scripts/setup_e2e_env.py
|
||||
|
||||
|
||||
+962
@@ -7,6 +7,963 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.5] - 2026-11-30
|
||||
|
||||
### Removed
|
||||
|
||||
- Remove the "Alternatives of A1111" choice from the Filter of the legacy
|
||||
Custom Nodes Manager, with its Alternatives column and the legacy route
|
||||
`GET /customnode/alternatives`. The page asked `/v2/customnode/alternatives`,
|
||||
which no server registers, so the choice showed no rows and an error. Manager
|
||||
no longer fetches `alter-list.json` at start or in `cm-cli update-cache`, and
|
||||
no longer ships it.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The legacy Manager checks the install of a nightly by the repository that
|
||||
the install clones. It looks that repository up by the id of the nodepack
|
||||
before the install is queued, with the lookup the install itself uses. A
|
||||
nightly of a nodepack that no list has is refused at once, where it failed
|
||||
in the queue.
|
||||
|
||||
- `cm-cli reinstall` keeps the version that is installed. `cm-cli reinstall
|
||||
<nodepack>` without a version removed the nodepack and installed the latest
|
||||
version of the registry, whatever was installed: 1.0.1 became 1.0.2, and a
|
||||
nightly clone became a registry version. It now installs the version that is
|
||||
installed, enabled or disabled, and a nightly clone is cloned again. A
|
||||
nodepack that is not installed gets the latest version, and
|
||||
`<nodepack>@latest`, `<nodepack>@<version>` or a URL installs what it names,
|
||||
as before. When the registry no longer has the version that is installed,
|
||||
the reinstall fails with `not available node: <nodepack>@<version>` and the
|
||||
nodepack stays as it is; `<nodepack>@latest` installs the latest one.
|
||||
|
||||
- cm-cli prints a value in square brackets, and a line for each nodepack it
|
||||
counts. cm-cli printed every line through rich, which reads a lowercase word
|
||||
in square brackets as markup and drops it, and typer shows a help text the
|
||||
same way. `cm-cli fix` named no version for a git nodepack (`[unknown]`,
|
||||
`[nightly]`), and an install of an id that no list has ended with `not found
|
||||
in` and nothing after it. The name of a nodepack, a reason, a title or an
|
||||
author of the node list, a changelog line, a path or the name of a snapshot
|
||||
lost a part in square brackets that starts with a lowercase letter, and with
|
||||
`--uv-compile` the report of a failed resolution dropped the extra of a
|
||||
requirement, such as `[ffmpeg]` of `opencv-python-headless[ffmpeg]`. A path
|
||||
lost a backslash before a bracket. cm-cli now writes every line as it is, as
|
||||
the Manager writes its own, a coloured line in its colour. A line longer than
|
||||
the console is wide is no longer broken in two, which was at 80 columns where
|
||||
no terminal is attached, as in a script, and a code such as `:bug:` in a
|
||||
value is no longer turned into an emoji. `--help` showed no text for `--mode`
|
||||
and for the argument of `show`, `simple-show`, `update`, `enable`, `disable`
|
||||
and `fix`. These texts are now written without their brackets, as
|
||||
`remote|local|cache`, and read the same with and without rich. `cm-cli
|
||||
simple-show` refused a word that is no list with the tags of a colour around
|
||||
the line: `[bold red]Invalid command: ...[/bold red]`. The reason of a failed
|
||||
`cm-cli fix` had an `f` before it. `cm-cli disable all` printed no line for
|
||||
the Manager and `cm-cli fix all` none for a disabled nodepack, so each
|
||||
skipped a number; both print a line now, as `update all` does. `cm-cli
|
||||
restore-dependencies` counted `__pycache__` as a nodepack. The `cm-cli`
|
||||
command printed an empty line before the output of each command, also before
|
||||
the script of `--show-completion`.
|
||||
|
||||
- A git nodepack that a snapshot lists as disabled is restored as disabled. A
|
||||
snapshot lists each git nodepack with whether it was disabled when the
|
||||
snapshot was saved, and a restore did not read that, with `cm-cli
|
||||
restore-snapshot` and from the Snapshot Manager alike. A nodepack saved as
|
||||
disabled was enabled when it was disabled, left enabled when it was enabled,
|
||||
and cloned when it was not installed. It is now left disabled, disabled, and
|
||||
not cloned. A nodepack saved at a version of the registry keeps its git clone
|
||||
disabled: that clone is restored when the version could not be, as before,
|
||||
where the node list of the machine that restores knows the URL of the clone.
|
||||
Where a URL has an enabled and a disabled clone installed, a snapshot lists
|
||||
it as enabled, with the commit of the enabled clone; it listed the clone it
|
||||
read last.
|
||||
|
||||
- A disable or an enable does not move a nodepack into a folder that exists.
|
||||
Disabling a nodepack moves its folder into `custom_nodes/.disabled`, and
|
||||
enabling moves it back. Where the folder it moves to was already there, as
|
||||
with an enabled nodepack and a disabled copy of it, the nodepack was moved
|
||||
inside that folder (`.disabled/<name>/<name>`) and reported as disabled.
|
||||
`cm-cli disable`, the Disable button of both UIs, a restore that disables a
|
||||
nodepack, and an enable or an install that first disables the enabled version
|
||||
all did so. The disable or enable now fails with
|
||||
`Destination already exists: <folder>` and the nodepack stays in its folder.
|
||||
An enable or an install that first disables the enabled version now looks at
|
||||
its own folder before it does so, and stops when that version cannot be
|
||||
disabled, so one that is refused changes nothing. The Disable and Enable
|
||||
buttons reported success for a disable or an enable that the Manager refused;
|
||||
they now report the failure, and the terminal says why. `cm-cli install`
|
||||
printed its `ENABLED` line for an enable that failed; it now prints the error.
|
||||
An install that first enables a disabled version stops when that enable fails;
|
||||
it went on to switch the version of whatever was in the folder.
|
||||
|
||||
- Both URLs of the default channel,
|
||||
`https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main` and
|
||||
`https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main`, are one
|
||||
channel. The server of the new UI cached the lists under the ltdrdata URL,
|
||||
while the legacy server and cm-cli used the Comfy-Org URL, so
|
||||
`cm-cli update-cache` refreshed lists that the new UI never read. A first
|
||||
start with the new UI writes the ltdrdata URL into `config.ini`. With that
|
||||
`config.ini` the legacy Custom Nodes Manager left out every nodepack that is
|
||||
only in the registry, and the channel menu of the legacy Manager showed no
|
||||
channel. Both servers and cm-cli now write and read one set of cache files
|
||||
under the Comfy-Org URL, whichever URL `config.ini` or `channels.list`
|
||||
names, and `default` is selected. Neither file is rewritten. Lists cached
|
||||
under the ltdrdata URL are no longer read: the next start fetches them
|
||||
again under the Comfy-Org URL. With `network_mode = offline`, or `private`
|
||||
when the start cannot reach the channel, a user who only used the new UI
|
||||
reads the lists that come with the installed version until a start fetches
|
||||
the lists or `cm-cli update-cache` is run.
|
||||
- Every place that installs the `requirements.txt` of a nodepack line by line
|
||||
reads a line the same way. In an install, an update and a fix, the legacy
|
||||
core, which `cm-cli` uses, gave a requirement with a comment, such as
|
||||
`pygit2>=1.18 # clone_repository(proxy=...) requires 1.18.0+` in the
|
||||
Manager's own `requirements.txt`, to pip or uv as one argument, which both
|
||||
refuse, so `cm-cli fix all` and `cm-cli restore-dependencies` ended with a
|
||||
traceback and exit 1. Every other place cut a URL at its `#`, so
|
||||
`git+https://host/repo#subdirectory=sub` installed the root of the
|
||||
repository, which pip and uv refuse as no Python project. A requirement
|
||||
followed by `--index-url URL` went to the installer as one argument in an
|
||||
install from the registry, an update and a fix of a nodepack, `cm-cli`
|
||||
included. An entry of `pip_overrides.json` did not apply to a line with a
|
||||
comment there either, nor in a reserved install that runs at the next
|
||||
start. Now a comment starts at a `#` at the start of the line or after
|
||||
whitespace, as pip reads it, and a requirement followed by
|
||||
`--index-url URL` is installed from that index in every place. A
|
||||
requirement followed by another option, such as
|
||||
`flash-attn --no-build-isolation`, still goes to the installer as one
|
||||
argument and fails as before.
|
||||
- An option in `requirements.txt` applies to its own row only. A row of the
|
||||
`requirements.txt` of a nodepack that has only an option, such as
|
||||
`--extra-index-url URL`, `--trusted-host host` or `-r other.txt`, went to
|
||||
pip or uv as one argument, which both refuse. In an install from the
|
||||
registry, an update and a fix of a nodepack, `cm-cli` included, that
|
||||
failure stopped every row after it: none of them was installed, and the
|
||||
nodepack was reported as failed. The Manager installs requirements one row
|
||||
at a time. A row with only an option has nothing to install: it is now
|
||||
left out with the line `skip '<row>': the Manager installs requirements one
|
||||
row at a time and does not apply this row`, and the rows after it are
|
||||
installed. `-r` and `-c` install nothing. A row `-e path` or
|
||||
`--editable path` is an editable requirement and goes to the installer as
|
||||
`-e` and its target, which pip and uv install as editable; before, uv
|
||||
installed `-e path` and pip refused it. With a git URL, pip installs `-e`
|
||||
as it is written. uv installs an editable from a local folder only, so with
|
||||
uv a row `-e git+URL`, with or without index options after it, is installed
|
||||
without `-e`, and a line says so; before, uv refused the row.
|
||||
`--extra-index-url URL` after a requirement now goes to the installer with
|
||||
that requirement, as `--index-url URL` does.
|
||||
- A row of `requirements.txt` that names a path, such as `-e .`,
|
||||
`-e ./local` or `./wheels/demo-1.0-py3-none-any.whl`, is installed for each
|
||||
nodepack. In one session the Manager installs a row once: a row that an
|
||||
earlier nodepack has installed is not installed again, and such a row
|
||||
counted as the same row in every nodepack, although the installer reads the
|
||||
path from the folder of each nodepack. In an install, an update and a fix
|
||||
without the unified resolver, the second nodepack with such a row was
|
||||
reported as done without its row being installed. A row counts as one that
|
||||
names a path when an argument of it, without extras and marker, exists as a
|
||||
path seen from that folder. Any other row is installed once in a session,
|
||||
as before.
|
||||
- `cm-cli show snapshot` and `cm-cli simple-show snapshot` print the snapshot
|
||||
of the current state: as JSON with `show`, and with `simple-show` a line
|
||||
with the commit hash of ComfyUI and of each git nodepack. They printed only
|
||||
a `RuntimeWarning` that a coroutine was never awaited, and ended with exit
|
||||
code 0. The hashes, the URLs and the JSON are written as they are, so a hash
|
||||
that starts with a letter is no longer left out and a long line is not
|
||||
broken.
|
||||
- `cm-cli enable all` enables the disabled nodepacks. It enabled nothing and
|
||||
said `Already enabled` for every nodepack, the disabled ones too: `all`
|
||||
names each nodepack with its version, and a nodepack named with a version
|
||||
counted as enabled and as disabled at once. `enable`, `disable`, `update`
|
||||
and `fix` now look at the state of the version that is named, also in
|
||||
`<id>@<version>` on the command line, so `disable all` says
|
||||
`Already disabled` for a disabled registry nodepack instead of
|
||||
`Not installed`, and `fix all` leaves the disabled nodepacks out instead of
|
||||
printing an error for each. `<id>@latest` names no installed version, so
|
||||
with it these four commands act on the installed nodepack, as with the id
|
||||
alone. A disabled version with a pre-release part, such as `1.0.0-rc1`, is
|
||||
enabled as well: it was named `1.0.0rc1`, which no installed version is
|
||||
called, so `cm-cli enable` did not find it. The legacy Custom Nodes Manager
|
||||
shows the version of a disabled nodepack under that name too. For a
|
||||
registry nodepack that is not installed, `update` and `fix` say
|
||||
`Not installed` and `enable` and `disable` say `Not found`, instead of
|
||||
`Disabled` and `Already disabled`.
|
||||
- `cm-cli install --exit-on-fail` ends with exit code 1 when an id that
|
||||
neither the registry nor the node list knows, or a git URL, could not be
|
||||
installed. It goes on with the other nodepacks of the command, then lists
|
||||
the ones that failed. The option did not reach the install, and the command
|
||||
ended with exit code 0.
|
||||
- `cm-cli show installed`, `show enabled` and `show disabled`, and the same
|
||||
lists of `simple-show`, list a git nodepack that neither the node list of the
|
||||
channel nor the registry knows, with its id and `author: N/A`. They left it
|
||||
out, enabled or disabled, where the documentation says that `installed`
|
||||
shows all nodes that have been installed.
|
||||
- `cm-cli` no longer writes the line `[ComfyUI-Manager] Using GitPython
|
||||
backend`, or its pygit2 form. The line was written whenever the Manager was
|
||||
loaded, so it came first in the output of every `cm-cli` command:
|
||||
`cm-cli --show-completion` did not print the completion script alone, a
|
||||
shell that evaluated it said `[ComfyUI-Manager]: command not found`, and
|
||||
with the completion installed a Tab offered the line among its candidates.
|
||||
The server writes the line at its start, on stderr as the other messages
|
||||
about git.
|
||||
- `cm-cli deps-in-workflow` tells whether a nodepack installed from the
|
||||
registry is installed. It wrote `"state": "not-installed"` for such a
|
||||
nodepack, enabled or disabled, and for a git nodepack disabled into
|
||||
`custom_nodes/.disabled`: it looked for a folder named after the
|
||||
repository, but a registry install has a folder named by its id, and a
|
||||
disable moves the folder into `.disabled`. The state now comes from the
|
||||
nodepacks the Manager knows to be installed, as in the Custom Nodes
|
||||
Manager. `cm-cli install-deps`, which reads the same state, enables a
|
||||
disabled nodepack as `cm-cli enable` does. For a disabled registry
|
||||
nodepack it cloned the repository as a nightly beside it, and a git
|
||||
nodepack in `.disabled` stayed disabled. It no longer runs an `enable.py`
|
||||
of the nodepack, which `cm-cli enable` and the Custom Nodes Manager do not
|
||||
run either.
|
||||
- `cm-cli restore-snapshot` with `--pip-non-url`, `--pip-non-local-url` or
|
||||
`--pip-local-url` restores a package installed in editable mode, as
|
||||
`pip install -e` makes it. It ended with exit code 1: the pip list of the
|
||||
snapshot has it as `-e <path or url>` (pip adds a comment line before it),
|
||||
and the restore gave those lines to pip as packages of PyPI, which pip
|
||||
refused; every package was then installed again one at a time. An editable
|
||||
install is now restored as editable with the option of where it is:
|
||||
`--pip-local-url` for a path, `--pip-non-local-url` for a repository URL.
|
||||
With uv, a git URL is installed without `-e`, as such a row of
|
||||
`requirements.txt` is, and a line says so. A path that the machine does not
|
||||
have is listed under `Installation failed for pip packages`, as a `file:`
|
||||
URL is. The comment line is skipped.
|
||||
- The Filter "In Workflow" of the legacy Model Manager lists only the models
|
||||
whose file a widget of the workflow names, also in a subfolder. It took the
|
||||
name of each model file of the workflow without its extension and showed
|
||||
every row that had that text anywhere in its name, type, base, description,
|
||||
file name or save path. The default workflow loads `ae.safetensors`, and the
|
||||
filter showed 29 rows, every TAESD model among them, where only FLUX.1 VAE
|
||||
model is that file. It also cleared the marks of a search, and did not list
|
||||
a model whose file has none of eight extensions, such as a `.gguf` file.
|
||||
- The Filter of the legacy Model Manager works together with Type and Base.
|
||||
With a choice other than All it ignored them: Type TAESD with the Filter at
|
||||
Not Installed showed all 569 models that are not installed, instead of the
|
||||
8 TAESD models. The list now shows the rows that match the Filter, Type,
|
||||
Base and the search together.
|
||||
- After Stop, the legacy Custom Nodes Manager shows Install again on the rows
|
||||
whose install did not start, hides the Stop button, and offers Restart when
|
||||
a nodepack of the batch was installed. Those rows stayed shown as being
|
||||
installed and the Stop button stayed: the page waited for the report of the
|
||||
end of its batch, and the server sends none for a batch that Stop drops. When
|
||||
the queue reports its own end and is no longer running, the page now ends the
|
||||
install, as the Model Manager already does.
|
||||
- Try fix in the legacy Custom Nodes Manager is refused when it is pressed at
|
||||
a `security_level` that does not allow it, as the other actions of the list
|
||||
are. At the default `security_level = normal` the server took the request
|
||||
and then did not run it: the box said only `failed`, the row said
|
||||
`Restart Required` with a Restart button, and after the restart the
|
||||
nodepack still failed to import. Try fix needs `security_level = normal-` or
|
||||
`weak` with a loopback `--listen`, or `weak` with
|
||||
`network_mode = personal_cloud`. At any other level the box now says
|
||||
`[FAIL]` with the name of the nodepack, the terminal log says which setting
|
||||
is needed, nothing is queued, and no restart is asked for.
|
||||
- An update of ComfyUI by the legacy Manager skips ComfyUI's
|
||||
`manager_requirements.txt` when `COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS`
|
||||
is set, as one by the new Manager does. It installed the file anyway, and
|
||||
with it the Manager version that ComfyUI pins in place of the installed one.
|
||||
Without the variable an update installs that pin, as before.
|
||||
- An install without torchaudio is no longer reported as one without
|
||||
PyTorch, and gets the PyTorch restore after a nodepack. ComfyUI no longer
|
||||
needs torchaudio (Comfy-Org/ComfyUI#16457). On an install without it,
|
||||
Manager logged `[ComfyUI-Manager] PyTorch is not installed` at every start
|
||||
and after an install, an update or a fix of a nodepack that has
|
||||
requirements, and did not restore PyTorch when a nodepack changed torch or
|
||||
torchvision (#3388). That line is no longer logged, and after such a
|
||||
nodepack Manager runs the PyTorch restore that an install with torchaudio
|
||||
gets. The restore installs torchaudio only when the install had it or the
|
||||
nodepack added it. A nodepack that changes only torchaudio no longer starts
|
||||
that restore.
|
||||
|
||||
- The legacy server lists a nodepack installed from the registry with its id
|
||||
as the registry writes it, as `ComfyUI_SigmoidOffsetScheduler`, as the
|
||||
server of the new UI already does. It gave the id in lowercase, a node
|
||||
added to a workflow took that id, and the legacy Custom Nodes Manager,
|
||||
which names the nodepack as the registry writes it, did not find it from
|
||||
that node. Custom Nodes In Workflow and Used In Workflow showed
|
||||
`0 custom nodes` for such a workflow, and Check Missing and Install Missing
|
||||
Custom Nodes said `Failed to find the following ComfyRegistry list` for the
|
||||
id and then listed the same nodepack.
|
||||
- The legacy Custom Nodes Manager also finds the nodepack of a workflow node
|
||||
whose id differs from the registry's only in case, as the lowercased id in
|
||||
a workflow saved with an earlier install. When that nodepack was not
|
||||
installed, Check Missing and Install Missing Custom Nodes said `Failed to
|
||||
find the following ComfyRegistry list` for the id, and did not list the
|
||||
nodepack at all when the node map did not know the node. The id of a node
|
||||
is now matched without regard to case when the list has no exact match.
|
||||
- Update All in the legacy Manager menu shows its result again when its tasks
|
||||
are done: a box that lists the nodepacks that were updated and those whose
|
||||
update failed, with a RESTART button, or says that everything is up to
|
||||
date. The menu sent the batch without the id by which it recognizes the
|
||||
report of the batch's end, so it ignored that report and showed nothing.
|
||||
Update All Custom Nodes of the desktop app, which does not update ComfyUI,
|
||||
shows its result as well.
|
||||
|
||||
## [4.4.3] - 2026-11-24
|
||||
|
||||
### Changed
|
||||
|
||||
- A search in the legacy Custom Nodes Manager lists the best matches first.
|
||||
It only filtered the list, so the rows stayed in the listed order and 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
|
||||
sorts from the highest value down.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Check Update in the legacy Custom Nodes Manager no longer stops the server,
|
||||
and shows how far it is. It 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 /v2/customnode/getlist` no longer fetches, with or without
|
||||
`skip_update`, and `GET /v2/customnode/fetch_updates` of the legacy server
|
||||
answers 410, as that of the new one does. A check is asked for with
|
||||
`POST /v2/customnode/check_update` of the legacy server and reports by the
|
||||
`cm-check-update` event.
|
||||
|
||||
- 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 that the
|
||||
server is asked for (**Try fix** of the legacy page, a `fix` task of the
|
||||
queue) 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. 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. With `use_unified_resolver` the requirements of a
|
||||
nodepack wait for the next start as well, and the fix answers for
|
||||
`install.py` alone; the legacy core runs them at the fix.
|
||||
- No deprecation warning of aiohttp with `bypass_ssl`. With
|
||||
`bypass_ssl = true`, the fetch of the legacy 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 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. A log record that cannot be
|
||||
formatted is no longer written to the console by the Manager, where it
|
||||
could fail the node the same way: for a record that the console shows,
|
||||
Python's logging reports it there already. The line that the Manager puts
|
||||
into the log file for such a record names the file and the line of the
|
||||
call; it named the record itself, which failed the node when the message
|
||||
of the call could not be turned into text. 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 snapshot restore clones a git node pack from the url of the snapshot.
|
||||
For a url that the registry knows, it asked for a nightly install by the id
|
||||
of the registry, which takes its url from the node list first: when the
|
||||
node list had another repository under the same name, that one was cloned.
|
||||
The restore no longer reads the node list.
|
||||
- A snapshot restore leaves a node pack at the version of the registry that
|
||||
the snapshot names. A node pack that was switched from its clone to a
|
||||
version keeps the clone, disabled, and a snapshot saves both: the restore
|
||||
enabled or cloned the clone and disabled that version. When that version
|
||||
cannot be installed, the clone is restored as before.
|
||||
- A clone of a snapshot restore that is refused says why in the log, as
|
||||
`Invalid git url: ...`. The summary said `[ FAILED ]` with no word of
|
||||
why.
|
||||
- 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, `/v2/customnode/installed`
|
||||
lists it with `invalid_installation: true`, the legacy node list marks its row
|
||||
`INVALID INSTALLATION ↗` and offers Reinstall, and the startup notice names
|
||||
it. `kind: "reinstall"` in `/v2/manager/queue/task` installs the nodepack
|
||||
again in its place. 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
|
||||
legacy server failed there with `Install path already exists`, and
|
||||
`cm-cli reinstall` deleted it.
|
||||
- The console line of a failed update says why the update failed.
|
||||
|
||||
## [4.4.2] - 2026-11-19
|
||||
|
||||
### Security
|
||||
|
||||
- Keep the saved Matrix password on the server.
|
||||
`GET /v2/manager/get_matrix_auth` answered with the saved homeserver, username
|
||||
and password, to any client that could reach the server. It now answers
|
||||
without the password. With the legacy UI, 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.
|
||||
- Share to Matrix through matrix.org only, where the share room is. The server
|
||||
logged in to any homeserver that a share request named, with the password of
|
||||
the request. The homeserver of the legacy UI's 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.
|
||||
- Keep the YouML API token in the browser that shares, which is what sends it to
|
||||
YouML. The server stored it, and `GET /v2/manager/youml/settings` answered
|
||||
with it to any client that could reach the server. Both
|
||||
`/v2/manager/youml/settings` routes are removed. With the legacy UI, the token
|
||||
has to be entered once more in the YouML share dialog. Delete `.youml` in
|
||||
`<USER_DIRECTORY>/__manager/`, and if others could reach the server while a
|
||||
token was saved, issue a new token.
|
||||
- Hold a switch of ComfyUI to an older version to the security level when it is
|
||||
asked for through `POST /v2/manager/queue/task`. The switch route has needed
|
||||
`normal-` or lower on a loopback listener, or `weak` in `personal_cloud` mode,
|
||||
since 4.2.1; an `update-comfyui` task with a version was not checked. Such a
|
||||
task now needs the same when the version is an older release or is not a
|
||||
release tag. A task for `nightly` or for a newer release is an update and runs
|
||||
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. `Switch ComfyUI` in the legacy UI's menu changed
|
||||
the update policy before it asked for the switch, so a switch that was refused
|
||||
still changed it; it now changes it after the switch is accepted, and says so
|
||||
when the security level does not allow the switch.
|
||||
- Hold an enable that puts a nightly in the place of a registry version to the
|
||||
security level of a nightly install (`middle+`). An `enable` names a node pack
|
||||
and no version; with a registry version of the pack enabled and its nightly
|
||||
disabled, it enabled the nightly instead, at any security level through
|
||||
`queue/task` and at `middle` through the legacy UI's install route.
|
||||
- Hold a snapshot restore to the security level of the switch route (`high+`).
|
||||
A restore takes the node packs back to the versions that the
|
||||
snapshot recorded. `POST /v2/snapshot/restore` needed `middle+`, which the
|
||||
default `security_level = normal` gives on a loopback listener. It now needs
|
||||
`normal-` or lower on a loopback listener, or `weak` in `personal_cloud`
|
||||
mode, and is refused otherwise. `cm-cli restore-snapshot` is not changed.
|
||||
- Read a value of `config.ini` as plain text, and use the default of a setting
|
||||
for a value that it cannot have. Manager read `%(name)s` in a value 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` and `update_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.
|
||||
- Take a JSON body only as `application/json`. A POST route that reads a JSON
|
||||
body parsed it whatever the Content-Type of the request. These routes, among
|
||||
them `POST /v2/manager/queue/task` and `POST /v2/manager/queue/batch`, now
|
||||
answer 400 unless the Content-Type is `application/json`. The legacy routes
|
||||
`POST /v2/customnode/install/git_url` and `POST /v2/customnode/install/pip`
|
||||
now take `{"url": ...}` and `{"packages": ...}` as JSON in place of plain
|
||||
text. A script or tool that posts to these routes without
|
||||
`Content-Type: application/json` has to add it.
|
||||
- Save only a choice of the share menu as the share option.
|
||||
`/v2/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.
|
||||
- Write the saved Matrix account as a file of its user only. The share dialog
|
||||
saves the 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.
|
||||
- Take every POST that changes something only as `application/json`, and save
|
||||
the share option 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 routes that take no body
|
||||
(`/v2/manager/queue/start`, `/v2/manager/queue/reset`,
|
||||
`/v2/manager/queue/update_all`, `/v2/manager/queue/update_comfyui`,
|
||||
`/v2/snapshot/save`, `/v2/snapshot/remove`, `/v2/snapshot/restore`,
|
||||
`/v2/manager/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 /v2/manager/share_option` and a JSON body
|
||||
`{"value": ...}`; `GET /v2/manager/share_option` only answers with the saved
|
||||
option, and a `value` given to it is ignored. The legacy UI sends 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.
|
||||
|
||||
## [4.4.1] - 2026-11-19
|
||||
|
||||
### Fixed
|
||||
|
||||
- Restarting ComfyUI from the Manager under comfy-cli no longer prints
|
||||
`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.
|
||||
- In the legacy UI, Update ComfyUI and Update All with ComfyUI no longer end
|
||||
with status 500 and nothing queued. The batch route called the handler of
|
||||
the update route without a request.
|
||||
- With `update_policy = nightly`, the legacy server updates ComfyUI to the
|
||||
nightly version. Only `nightly-comfyui` was taken as nightly, and `nightly`
|
||||
as stable.
|
||||
- The legacy server answers 400 again when the list of ComfyUI versions cannot
|
||||
be read or a switch to another version fails. The call that logs the cause
|
||||
was given an argument it does not take, so the answer was 500 with a
|
||||
`TypeError` in the log.
|
||||
|
||||
- Update ComfyUI to the latest stable version again when Manager runs git
|
||||
through GitPython, which it does whenever the `git` command is available.
|
||||
The update ended with `Failed to checkout 'master' branch` and ComfyUI
|
||||
stayed at its version: the branch to check out was passed to git as an
|
||||
object instead of by its name. An update to the nightly version failed the
|
||||
same way when the checkout was detached and the remote's default branch was
|
||||
not known locally.
|
||||
|
||||
- On the default server, `POST /v2/manager/queue/update_comfyui` follows
|
||||
`update_policy` when the request names no version line. Its `stable`
|
||||
parameter defaulted to true, so the policy was never read and such a request
|
||||
updated ComfyUI to the stable version also under `nightly-comfyui`.
|
||||
`nightly` is taken as nightly too.
|
||||
- On the default server, the same route reads `is_stable`, the name the
|
||||
ComfyUI frontend sends, when `stable` is not given. It was ignored.
|
||||
- `openapi.yaml` lists the values the two setting routes accept: `cache` for
|
||||
`db_mode` and `stable-comfyui` for the update policy were missing.
|
||||
|
||||
- Print console messages with 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. Numbers and quoted strings keep
|
||||
their colors.
|
||||
|
||||
- Start with a node pack whose `.git/config` Manager could not read. 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 on Windows text that
|
||||
the code page of the system cannot decode, such as a Korean user name
|
||||
written in UTF-8, raised an error while Manager was loading: ComfyUI did not
|
||||
start, or with `--enable-manager-legacy-ui` started without Manager. These
|
||||
files are read now, and for a file that cannot be read the url of that pack
|
||||
is unknown and a warning names the file once.
|
||||
|
||||
- Run the git executable set as `git_exe` in `config.ini`. The path was read
|
||||
but not used: with the GitPython backend, git commands kept running the
|
||||
`git` found on `PATH`, and without a `git` on `PATH` the pygit2 backend was
|
||||
selected, or with the legacy UI Manager did not load. Both servers, the git
|
||||
helper and `cm-cli` now run the configured executable. For the servers and
|
||||
what they start it no longer has to be on `PATH`; `cm-cli` run by hand still
|
||||
needs a git on `PATH`. A value that is not a working git is reported, and
|
||||
the default git is used. The value is read as it is written: with a `%` in
|
||||
it, as in a path of Windows, Manager read every setting of `config.ini` as
|
||||
its default. The configured executable is also run when pygit2
|
||||
is asked for with `CM_USE_PYGIT2=1` but is not installed.
|
||||
- Start without a git. With neither a `git` on `PATH` nor pygit2, ComfyUI did
|
||||
not start, or with the legacy UI started without Manager; Manager now loads
|
||||
and reports that git is missing, and what needs git fails when it is used.
|
||||
With pygit2 and no `git`, the legacy UI started without Manager; it now
|
||||
loads on the pygit2 backend, but what the legacy server does with GitPython
|
||||
itself still needs a git.
|
||||
|
||||
- Update the submodules of a submodule with the pygit2 backend, and fail when
|
||||
the submodules could not be updated. pygit2 updated the submodules of the
|
||||
nodepack and not those below them, which git does. When it could not update
|
||||
them and there was no `git` to do it in its place, or that `git` did not
|
||||
answer in time, a message was printed and the install or the update went on
|
||||
as if they were updated.
|
||||
- Fetch the submodules of a nodepack through the proxy with the pygit2
|
||||
backend. The nodepack was cloned through the `http.proxy` of the global git
|
||||
configuration and its submodules were not, so behind a proxy they could not
|
||||
be fetched. As for the nodepack, the proxy is used for an `https` url.
|
||||
- Fetch a submodule with an ssh url over https with the pygit2 backend, as the
|
||||
nodepack itself is. It was asked for credentials, which pygit2 does not
|
||||
have, and with a public repository does not need.
|
||||
- Fetch a submodule again with the pygit2 backend after its clone failed, and
|
||||
check one out again after its checkout was removed, as by an update that
|
||||
was undone. What was left of it in `.git/modules` kept every later update
|
||||
from it.
|
||||
- Update a nodepack whose submodule is at another commit than the nodepack
|
||||
names, with the pygit2 backend. The update ended before the pull, at a
|
||||
stash with nothing to stash, as it did after a submodule could not be
|
||||
fetched once.
|
||||
- Do not end a clone or a fetch of the pygit2 backend at a progress message
|
||||
of the server. pygit2 decodes each piece of such a message as UTF-8, and a
|
||||
piece can end in the middle of a character: with a server that writes its
|
||||
messages in a language other than English, a clone, a fetch or the update
|
||||
of a submodule failed now and then with `UnicodeDecodeError`.
|
||||
- Bring the submodules of a git nodepack to the commits that its commit names
|
||||
when a snapshot restore checks it out, and also when it is at the commit of
|
||||
the snapshot already. A submodule that was never fetched is then fetched
|
||||
too in a nodepack that Manager installed, as Manager clones a nodepack with
|
||||
its submodules; with the pygit2 backend, or in a nodepack cloned without
|
||||
them, it is fetched only when the nodepack itself is checked out.
|
||||
- Record the commit of a git nodepack whose refs are packed, as after
|
||||
`git gc`, in a snapshot. It was recorded as `unknown`. A `HEAD` that is not
|
||||
UTF-8, as one that names a branch in another encoding, raised an error where
|
||||
the commit of a nodepack 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.
|
||||
- Start with a git nodepack whose commit cannot be read. The commit is read
|
||||
while Manager is loading, and an error there kept ComfyUI from starting, or
|
||||
with `--enable-manager-legacy-ui` Manager from loading: 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 nodepack is unknown now.
|
||||
- Fail an update whose pull failed in the git helper. On Windows the pull 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.
|
||||
- Undo the pull of an update when the update of its submodules fails. The
|
||||
nodepack stayed at the new commit: the next update found nothing to do, and
|
||||
the install script of the update never ran. The submodules that were updated
|
||||
before the one that failed go back with it. A nodepack with a submodule
|
||||
that cannot be fetched at all is not updated until it can.
|
||||
|
||||
- Carry out a scheduled snapshot restore in the directories of the server.
|
||||
With `--base-directory`, the restore that runs at the next start worked on
|
||||
the Manager's files and the `custom_nodes` directory inside the ComfyUI
|
||||
directory instead of those of the base directory: it did not see the node
|
||||
packs of the server.
|
||||
|
||||
- Report the steps of a snapshot restore that failed. The summary listed a
|
||||
nodepack 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 listed as `FAILED`, and Manager itself is no longer listed as
|
||||
`DISABLED`. A Registry that cannot be reached ended the restore at the first
|
||||
nodepack to install from it, and so did a nodepack whose directory could not
|
||||
be moved to disable or enable it; such a nodepack 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
|
||||
nodepack is listed as `FAILED`. A git nodepack 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.
|
||||
- Restore the commit of the snapshot for every git nodepack. A git nodepack
|
||||
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 nodepack is listed as `FAILED`. An installed
|
||||
git nodepack 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.
|
||||
- Install the requirements and run the install script of a Registry nodepack
|
||||
that a snapshot restore installs. The nodepack was unpacked and nothing
|
||||
more. It is listed as `FAILED` when they fail.
|
||||
- Try a requirement or an install script that failed again. It was taken as
|
||||
done until the next start: the next nodepack that names the requirement
|
||||
skipped it, and installing or fixing the nodepack again did not run the
|
||||
script. The install script of a git nodepack was skipped in the same way
|
||||
when it was cloned where another version of the nodepack had been installed
|
||||
since the start, as a restore does for a snapshot that has both; it runs.
|
||||
- Write what is reserved for the next start as UTF-8, which is how the
|
||||
start-up script reads it. The install script of an update, the removal of a
|
||||
nodepack whose files are in use and a switch of version are reserved in a
|
||||
file 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.
|
||||
- Remove the files of the old version from the nodepack when a switch of
|
||||
version is carried out at the next start. The files that the new version no
|
||||
longer has were looked for in `custom_nodes` in place of the directory of the
|
||||
nodepack: they stayed in the nodepack, and a file of the same name in
|
||||
`custom_nodes` was removed. 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 nodepack, 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 nodepack 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 nodepack to another directory, the install script
|
||||
of the new version runs there; it was looked for in the directory that the
|
||||
nodepack was moved from, and did not run.
|
||||
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.
|
||||
- Read the list of the files of a Registry nodepack as UTF-8, which is how it
|
||||
is written. It was read in the encoding of the system: on Windows a switch of
|
||||
version of a nodepack with a file name that the code page of the system
|
||||
cannot decode ended in the middle, with the files of the new version
|
||||
unpacked, its install script not run and the files of the old version left. 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.
|
||||
|
||||
- Refuse a `db_mode` or an `update_policy` that Manager does not know in the
|
||||
legacy server. With `--enable-manager-legacy-ui`, the two setting routes
|
||||
stored whatever value a request carried and wrote it to `config.ini`. They
|
||||
answer 400 for a value that is not one of the known ones, as the default
|
||||
server does.
|
||||
- Answer 400 from the two setting routes of both servers for a JSON body that
|
||||
is not an object. It ended with status 500.
|
||||
- Name the security level `normal-` and the database mode `channel` as the
|
||||
servers do in `common/enums.py`, which had `normal-minus` and no `channel`.
|
||||
Nothing read these two members.
|
||||
|
||||
- Keep a database mode, update policy or share option that is chosen in the
|
||||
legacy Manager menu while the menu is still loading the stored value. The
|
||||
value was saved, but the menu went back to showing the old one when it
|
||||
arrived.
|
||||
|
||||
- Draw the dialogs of the legacy UI with styles of Manager's own. The Manager
|
||||
menu, the Custom Nodes Manager, the Model Manager and the Snapshot Manager
|
||||
were built with the classes of PrimeVue dialogs and buttons, and a ComfyUI
|
||||
frontend that no longer ships those styles drew them without a background:
|
||||
the buttons lay over the canvas and the nodes behind them. `main` has had
|
||||
this change since #3392.
|
||||
|
||||
## [4.4] - 2026-11-16
|
||||
|
||||
### Changed
|
||||
|
||||
- Require Python 3.10 or newer to match ComfyUI's minimum supported version.
|
||||
Python 3.9 is no longer supported.
|
||||
|
||||
### Removed
|
||||
|
||||
- Remove four share destinations of the legacy UI that no longer take workflows
|
||||
from Manager: ComfyWorkflows (its domain registration has expired), Copus (its
|
||||
API answers that publishing from ComfyUI is no longer supported), OpenArt (its
|
||||
workflow API and pages are gone), and eSheep (its site no longer resolves).
|
||||
Sharing to YouML and to the Matrix server is unchanged. A saved `Share`
|
||||
setting that names a removed site now acts as `All`, and the Workflow Gallery
|
||||
button no longer opens a removed site that was visited last. The files saved
|
||||
for the removed sites are no longer read; `comfyworkflows_sharekey`,
|
||||
`.openart_key`, and `esheep_share_message.json` under
|
||||
`<USER_DIRECTORY>/__manager/` can be deleted.
|
||||
|
||||
### Security
|
||||
|
||||
- Allow administrators to exempt selected Registry IDs from the flagged CNR
|
||||
install restriction using `nodepack-whitelist.list` beside Manager's `config.ini`.
|
||||
Entries are case-insensitive, apply to all versions, and take effect without a
|
||||
restart. Server startup creates a commented template with no default exceptions;
|
||||
other installation security checks still apply.
|
||||
- Verify the TLS certificate when the legacy UI fetches its notice from GitHub;
|
||||
verification was off for every user. A response whose certificate is not
|
||||
trusted is discarded and the notice area shows `Unable to retrieve Notice`. It
|
||||
shows the same when the connection fails, where it used to show a server
|
||||
error. Behind a proxy that re-signs TLS traffic, point the `SSL_CERT_FILE`
|
||||
environment variable at a CA bundle that includes the proxy's CA, or set
|
||||
`bypass_ssl = True` in `config.ini`, which turns verification off for this
|
||||
fetch too (#3302).
|
||||
- Check every model install against the model list, including the download URL:
|
||||
the folder, base, file name, and URL must match an entry. With the legacy UI,
|
||||
a request with a listed name and another URL was accepted. Without it, the
|
||||
list was not checked, and neither was the rule that a model in a format other
|
||||
than `.safetensors` must be in the default channel's list unless the security
|
||||
level is `normal-` or lower on a loopback listener, or `weak` in
|
||||
`personal_cloud` mode (#3428).
|
||||
- Share to the Matrix server only a file inside ComfyUI's output or temp
|
||||
directory. The file name and subfolder of the output to share come from the
|
||||
request and were not checked, so a request could have any file that ComfyUI
|
||||
can read uploaded to the Matrix homeserver named in the same request. Only
|
||||
installations with `matrix-nio`, which Manager does not install, were
|
||||
affected (#3427).
|
||||
|
||||
### Fixed
|
||||
|
||||
- Apply `downgrade_blacklist` to packages whose names contain a hyphen, such as
|
||||
`opencv-python`; they were never protected. Names in `downgrade_blacklist`,
|
||||
`pip_blacklist.list`, and requirements are now compared without regard to case
|
||||
or to `-`, `_`, and `.` (#3458).
|
||||
- Read every version clause of a requirement, so `numpy>=1.24,<2` no longer
|
||||
passes because its lower bound comes first, and read requirements written with
|
||||
spaces, parentheses, an environment marker, or as a direct reference
|
||||
(`name @ url`). Versions with a local label such as `0.0.30+cu126` or a fourth
|
||||
component such as `5.0.0.93` are compared correctly.
|
||||
- Install a requirement with extras for a `downgrade_blacklist` package unless it
|
||||
would downgrade the package, so the extras' dependencies are still installed.
|
||||
- Skip a `downgrade_blacklist` package when the requirement cannot be compared
|
||||
with the installed version, such as a malformed version or a direct reference,
|
||||
and log the reason with how to install it. The list check previously raised an
|
||||
error or let the install proceed.
|
||||
- Apply `downgrade_blacklist` and `pip_blacklist.list` to requirements that carry
|
||||
pip options such as `--index-url`, and to installs run through uv in embedded
|
||||
Python or as a standalone tool. These installs were not checked.
|
||||
- At startup, recognize an installed package however its requirement spells the
|
||||
name. Pending installs no longer downgrade or reinstall packages whose names
|
||||
contain `-` or `.`, and a requirement older than its `~=` version is upgraded.
|
||||
- Restore the OpenCV repair that runs at startup and after installs. When
|
||||
`opencv-python`, `opencv-python-headless`, `opencv-contrib-python`, and
|
||||
`opencv-contrib-python-headless` are installed at different versions, the older
|
||||
ones are reinstalled at the newest installed version, without their
|
||||
dependencies, so numpy is left as it is. A headless package is installed
|
||||
after one with the GUI, so `cv2` stays importable on a Linux without the
|
||||
graphics libraries; within each kind, the package with the contrib modules is
|
||||
installed last. OpenCV packages listed in `pip_auto_fix.list` are left to
|
||||
that list. The repair found no installed OpenCV package and did nothing; it
|
||||
now also compares four-part versions such as `4.11.0.100` numerically.
|
||||
- In the legacy core, except on Windows, give the backup branch the next free
|
||||
name when an update cannot fast-forward and a backup branch of the same second
|
||||
already exists. The existing name was reused, so creating the branch failed
|
||||
and the update was not applied.
|
||||
- On Windows, keep command-line arguments intact when ComfyUI restarts, from the
|
||||
Restart button or after an install that runs at startup. An argument with a
|
||||
space, such as `--output-directory "D:\My Outputs"`, was split in two, so
|
||||
ComfyUI failed to start with `unrecognized arguments`; quotation marks and
|
||||
empty arguments were lost as well. A ComfyUI started as a module (`python -m`)
|
||||
from a Python path with a space now restarts too (#3339).
|
||||
- In the legacy UI, make `Fix node (recreate)` work on a node with a connected
|
||||
input on frontends whose node ids are strings. It stopped with
|
||||
`findInputSlot is not a function` and left two copies of the node on the
|
||||
canvas: the original, still wired, and an unwired replacement (#3126).
|
||||
- In the legacy UI, make `Fix node (recreate)` work on a node inside a
|
||||
subgraph. It read the node's links from the root graph, so it stopped with an
|
||||
error and left the same two copies of the node. Links to the inputs and
|
||||
outputs of the subgraph are kept as well.
|
||||
- Read the version of a node pack installed from the registry when it has a
|
||||
pre-release, such as `1.8.0-beta.1` or `0.7.2-b2`; such a pack was not
|
||||
recognized as a registry pack. A version with a fourth part, such as
|
||||
`0.1.3.post1`, stopped the scan of installed node packs with
|
||||
`invalid literal for int()`, in the server and in `cm-cli` (#3431).
|
||||
- Compare the versions in `pip_auto_fix.list` as pip does. An entry for a
|
||||
package installed with a local label or as a pre-release, such as
|
||||
`torch==2.5.1` beside an installed `2.5.1+cu124`, was skipped with
|
||||
`Failed to restore`. Such an entry is now applied: that installed version
|
||||
meets it, and one that does not, such as `2.6.0+cu124`, is replaced with
|
||||
`pip install`. `~=` is a compatible-release clause: it was taken as met by
|
||||
any other version, and as not met by the same version.
|
||||
- Keep the custom node list and the model list loading when the channel answers
|
||||
with something other than JSON, such as a block page or `404: Not Found`. The
|
||||
startup cache update stored an empty result in the cache, in place of a list
|
||||
cached earlier, and the lists then failed to load from it until a later start
|
||||
got the lists from the channel; with the legacy UI the Model Manager showed
|
||||
`Failed to get external model list.`. Such a response is now handled like a
|
||||
failed connection: the cache is left as it is, and without a cached list the
|
||||
one bundled with the Manager is used. An empty result that an earlier version
|
||||
cached is replaced at the next start that reaches the channel, or goes away
|
||||
when the files in `<USER_DIRECTORY>/__manager/cache` are deleted (#3480).
|
||||
- Judge a requirement for a `downgrade_blacklist` package by all of its clauses.
|
||||
One that allows the installed version is installed when another clause sets a
|
||||
minimum above it, as in `transformers==4.*,>=4.58.0` beside an installed
|
||||
`4.57.0`, or excludes it with `!=` while a newer version is allowed, as in
|
||||
`transformers~=4.57.0,!=4.57.0`; without extras both were skipped, so the
|
||||
upgrade did not happen. One that the installed version does not meet and
|
||||
that allows no newer version, as in `transformers[torch]<=4.57.0,!=4.57.0` or
|
||||
`transformers<4.58,!=4.57.*`, is skipped; it was installed, and pip replaced
|
||||
the package with an older version. A pre-release counts as a newer version
|
||||
only when `==`, `>=`, `<=`, `~=` or `===` names one: pip before 25.0 takes no
|
||||
other.
|
||||
- At startup, read `>` as pip reads it: a post-release of the version, such as
|
||||
`1.0.post1` for `>1.0`, does not meet it, and the requirement is installed. A
|
||||
wildcard such as `==0.21.*` is met by an installed pre-release `0.21.0rc1`,
|
||||
and the requirement is no longer passed to pip.
|
||||
- At startup, install a requirement that excludes the installed version with
|
||||
`!=` and allows a newer one, as in `numpy>=2.2.0,!=2.2.0` beside an installed
|
||||
`2.2.0`, as an immediate install does; it was taken as installed already. pip
|
||||
chooses the version, and that is an older one when no newer release exists.
|
||||
- Leave an installed local build, such as the CUDA build `2.5.1+cu124`, alone
|
||||
on all of these grounds. For a `downgrade_blacklist` package, keep it as well
|
||||
when a requirement excludes it with `!=`, as in `xformers!=0.0.30` beside
|
||||
`0.0.30+cu126`, unless the requirement sets a minimum above it; pip replaced
|
||||
the build with whatever it found. For such a build, these changes only add
|
||||
requirements that are skipped.
|
||||
- In the legacy UI, enable a disabled node pack that another extension
|
||||
requires before restarting. After the user agreed to enable it and restart,
|
||||
ComfyUI restarted with the pack still disabled, because the request went to
|
||||
a route that no longer exists. The pack is now enabled through the queue, as
|
||||
the Custom Nodes Manager does, and ComfyUI restarts only when that
|
||||
succeeded; otherwise the reason is shown. While other tasks are queued
|
||||
behind the pack, ComfyUI is not restarted, and the user is asked to restart
|
||||
after them. `Rebooting...` is shown as well: the restart request is never
|
||||
answered, which ended the handler before it.
|
||||
- In the legacy UI, say so when that restart is refused at the current
|
||||
security level. Nothing was shown; the browser console had
|
||||
`show_message is not defined`.
|
||||
- With `cm-cli restore-snapshot` and its `--pip-non-url`, `--pip-non-local-url`
|
||||
or `--pip-local-url` options, report a pip package as failed only when pip
|
||||
fails for it. Every package was listed under `Installation failed for pip
|
||||
packages`, and pip was run a second time for each package named by version
|
||||
(#3425).
|
||||
- When restoring a snapshot, check a git node pack out at the commit the
|
||||
snapshot names when the snapshot was saved while that pack's HEAD was
|
||||
detached. The hash was saved with the newline that follows it in `.git/HEAD`,
|
||||
so the checkout failed and the pack was reported as skipped at the commit it
|
||||
had. New snapshots hold the bare hash, and the newline in an existing
|
||||
snapshot is ignored. A registry node pack already at the snapshot's version
|
||||
is left alone without asking the registry; when the registry could not be
|
||||
reached, that lookup stopped the restore (#3426).
|
||||
- Replace a cache file in one step when it is updated, so a write that stops
|
||||
part-way leaves the previous list. It left a truncated file, which Manager
|
||||
reads as an empty list. The age of a cached list is counted from its last
|
||||
write; it was read from the file's creation time, which Windows keeps when a
|
||||
file is rewritten (#3432).
|
||||
- When the archive of a registry node pack cannot be extracted, report the
|
||||
failure and remove the directory created for the pack and the downloaded
|
||||
archive. Both were left behind, and installing the pack again stopped with
|
||||
`Install path already exists` until the directory was removed by hand (#3433).
|
||||
- In the legacy UI, show a node's name, inputs, default values, outputs and
|
||||
description as text in the preview that appears over a node name in a pack's
|
||||
node list. They were inserted as HTML, so a default such as
|
||||
`<lora:name:0.8>` was missing from the preview and markup in a node
|
||||
definition was rendered (#3434).
|
||||
- In the legacy UI, keep the Model Manager waiting for its downloads when
|
||||
another batch finishes, such as a node pack install queued before them or a
|
||||
model install started earlier. It showed the downloads as done while they
|
||||
were still running, hid the Stop button, and ignored their real completion.
|
||||
After Stop, the dialog returns to idle; it stayed waiting, with its Stop
|
||||
button. A failed download is no longer followed by the request to click
|
||||
Refresh (#3303, #3437).
|
||||
- In the legacy UI, say why restoring or removing a snapshot failed. For a
|
||||
request the server refused, the message was `Restore snapshot failed:
|
||||
undefined / ReferenceError: exception is not defined`, also for a removal,
|
||||
and a refused restore still asked for a restart. An answer with another
|
||||
error status was taken as success (#3436).
|
||||
- With file logging on, tell libraries that ask whether the console is a
|
||||
terminal the state of the real console. The logger that captures the output
|
||||
always answered that it was not one, so after `colorama.init()` the colors of
|
||||
every `print()` were removed, and tqdm and rich took a terminal for a pipe
|
||||
(#3259, #3423).
|
||||
|
||||
## [4.3] - 2026-09-19
|
||||
|
||||
### Security
|
||||
@@ -190,6 +1147,11 @@ programmatic clients.
|
||||
perform the change from a trusted entry point. Read access via `GET` is
|
||||
unaffected.
|
||||
|
||||
[4.5]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.3...v4.5
|
||||
[4.4.3]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.2...v4.4.3
|
||||
[4.4.2]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4.1...v4.4.2
|
||||
[4.4.1]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.4...v4.4.1
|
||||
[4.4]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.3...v4.4
|
||||
[4.3]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.2.2...v4.3
|
||||
[4.2.2]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.2.1...v4.2.2
|
||||
[4.2.1]: https://github.com/Comfy-Org/ComfyUI-Manager/compare/v4.1b6...v4.2.1
|
||||
|
||||
+2
-2
@@ -10,5 +10,5 @@ include extension-node-list.json
|
||||
include extras.json
|
||||
include github-stats.json
|
||||
include model-list.json
|
||||
include alter-list.json
|
||||
include comfyui_manager/channels.list.template
|
||||
include comfyui_manager/channels.list.template
|
||||
prune tests
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
|
||||
## Installation
|
||||
|
||||
Requires Python 3.10 or newer, matching ComfyUI's minimum Python version.
|
||||
|
||||
* When installing the latest ComfyUI, it will be automatically installed as a dependency, so manual installation is no longer necessary.
|
||||
|
||||
* Manual installation of the nightly version:
|
||||
@@ -77,8 +79,7 @@
|
||||
 
|
||||
|
||||
* You can share the workflow by clicking the Share button at the bottom of the main menu or selecting Share Output from the Context Menu of the Image node.
|
||||
* Currently, it supports sharing via [https://comfyworkflows.com/](https://comfyworkflows.com/),
|
||||
[https://openart.ai](https://openart.ai/workflows/dev), [https://youml.com](https://youml.com)
|
||||
* Currently, it supports sharing via [https://youml.com](https://youml.com)
|
||||
as well as through the Matrix channel.
|
||||
|
||||

|
||||
@@ -100,6 +101,7 @@ In `ComfyUI-Manager` V4.0.3b4 and later, configuration files and dynamically gen
|
||||
* Configurable pip overrides: `<USER_DIRECTORY>/__manager/pip_overrides.json`
|
||||
* Configurable pip blacklist: `<USER_DIRECTORY>/__manager/pip_blacklist.list`
|
||||
* Configurable pip auto fix: `<USER_DIRECTORY>/__manager/pip_auto_fix.list`
|
||||
* Configurable flagged nodepack whitelist: `<USER_DIRECTORY>/__manager/nodepack-whitelist.list`
|
||||
* Saved snapshot files: `<USER_DIRECTORY>/__manager/snapshots`
|
||||
* Startup script files: `<USER_DIRECTORY>/__manager/startup-scripts`
|
||||
* Component files: `<USER_DIRECTORY>/__manager/components`
|
||||
@@ -252,6 +254,7 @@ The following settings are applied based on the section marked as `is_default`.
|
||||
```
|
||||
downgrade_blacklist = diffusers, kornia
|
||||
```
|
||||
* Names are matched without regard to case or to `-`, `_`, and `.`, so `opencv-python` and `opencv_python` are the same package.
|
||||
|
||||
* Custom pip mapping
|
||||
* When you create the `pip_overrides.json` file, it changes the installation of specific pip packages to installations defined by the user.
|
||||
@@ -327,10 +330,10 @@ The security settings are applied based on whether the ComfyUI server's listener
|
||||
|
||||
| Risky Level | features |
|
||||
|-------------|---------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| high+ | * **Switch ComfyUI version**<BR>* **Fix nodepack** |
|
||||
| high+ | * **Switch ComfyUI version**<BR>* **Restore Snapshot**<BR>* **Fix nodepack** |
|
||||
| high | _(no features at this tier — `Fix nodepack` promoted to `high+` to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text)_ |
|
||||
| middle+ | * Uninstall/Update<BR>* Installation of Git/nightly nodepacks registered in the `default channel`.<BR>* Restore/Remove Snapshot<BR>* Install model |
|
||||
| middle | * Restart<BR>* Installation of CNR release versions (subject to the flagged-version policy below) |
|
||||
| middle+ | * Uninstall/Update<BR>* Installation of Git/nightly nodepacks registered in the `default channel`.<BR>* Enabling a disabled nightly in the place of an enabled Registry version.<BR>* Install model |
|
||||
| middle | * Restart<BR>* Remove Snapshot<BR>* Installation of CNR release versions (subject to the flagged-version policy below) |
|
||||
| low | * Update ComfyUI |
|
||||
|
||||
* **Note**: `Install via git url` and `pip install` are no longer gated by `security_level` — they moved to the dedicated flags `allow_git_url_install` / `allow_pip_install`. Installation of a nodepack registered not in the `default channel` likewise requires `allow_git_url_install` (in addition to the `middle+` level preconditions) instead of a `high+` security level. See the [Dedicated install flags](#dedicated-install-flags-allow_git_url_install--allow_pip_install) subsection below.
|
||||
@@ -370,16 +373,44 @@ reinstallation checks the target before removing the existing nodepack, and a
|
||||
policy refusal preserves the current installation. For flagged-policy denials,
|
||||
the UI reports that the current security configuration does not allow the action
|
||||
and directs users to the terminal. Only the terminal provides loopback-only
|
||||
`--listen` examples, the private network override setting, and restart instructions.
|
||||
`--listen` examples, the private network override setting, the pack whitelist,
|
||||
and restart instructions.
|
||||
|
||||
* Active versions continue through the normal install flow. CNR release installs
|
||||
use the `middle` security level, so they are available on non-local listeners
|
||||
with `security_level = normal`, `normal-`, or `weak`. `strong` still denies
|
||||
these install requests.
|
||||
* Active versions continue through the normal install flow. New HTTP requests
|
||||
to install CNR releases use the `middle` security level, so they are available
|
||||
on non-local listeners with `security_level = normal`, `normal-`, or `weak`.
|
||||
`strong` denies these new requests, including requests for whitelisted packs.
|
||||
* Flagged versions (`NodeVersionStatusFlagged`) must satisfy the same installation
|
||||
conditions as Active versions. In addition, **all** addresses in `--listen`
|
||||
must resolve to loopback, such as `127.0.0.1` and `::1`, unless the explicit
|
||||
override below is enabled.
|
||||
override below is enabled or the pack ID is whitelisted.
|
||||
* To allow specific packs on any listener without enabling all flagged installs,
|
||||
edit `nodepack-whitelist.list` beside Manager's `config.ini`
|
||||
(normally `<USER_DIRECTORY>/__manager/nodepack-whitelist.list`).
|
||||
At server startup, Manager creates a commented template if the file is missing;
|
||||
existing files are preserved. The template grants no exceptions by default.
|
||||
Enter one Registry pack ID per line:
|
||||
|
||||
```text
|
||||
# Nodepack whitelist
|
||||
# Add one Registry ID per line; each entry applies to all CNR versions.
|
||||
# Registry IDs are case-insensitive.
|
||||
|
||||
comfyui-impact-pack
|
||||
comfyui-inspire-pack # Inline comments are supported.
|
||||
```
|
||||
|
||||
Entries are case-insensitive and apply to all CNR versions of that pack. Use
|
||||
Registry IDs, not display names, Git URLs, or `id@version`; wildcards are not
|
||||
expanded. Blank lines and `#` comments are ignored. Delete an entry or comment
|
||||
out its line with `#` to revoke that exception. Manager reads the file
|
||||
for each installation check, so edits and removals apply without restarting.
|
||||
A missing, unreadable, or NUL-containing file grants no whitelist exceptions.
|
||||
If mixed encodings introduce NUL characters, Manager logs a warning to save
|
||||
the file as UTF-8. Whitelist-based permission is logged at WARNING level with
|
||||
the Registry ID, including in snapshot restore children. This records the policy
|
||||
decision, not successful installation. Packs absent from the list continue to
|
||||
use the listener and global option rules.
|
||||
* To allow flagged versions on a non-local listener in a **trusted private
|
||||
network**, an administrator can explicitly opt in:
|
||||
|
||||
@@ -395,17 +426,27 @@ and directs users to the terminal. Only the terminal provides loopback-only
|
||||
private network. This option does not require `network_mode = private`, and
|
||||
`network_mode = personal_cloud` alone does not allow flagged versions.
|
||||
* CNR API refusals, including banned or unavailable packages, still prevent
|
||||
installation. This option does not override `security_level = strong` or
|
||||
the separate Git/nightly and pip installation policies.
|
||||
installation. Neither the option nor the whitelist bypasses the `strong`
|
||||
restriction on new HTTP install requests or the separate Git/nightly and pip
|
||||
installation policies.
|
||||
* Enabling an already installed version does not query the Registry or reinstall it.
|
||||
* Older deferred switches without a stored status require loopback-only listeners
|
||||
or the override. Otherwise they are rejected without changing the installed pack;
|
||||
request the installation again so Manager can check its current Registry status.
|
||||
* Older deferred switches without a stored status require loopback-only listeners,
|
||||
the override, or a whitelisted pack ID. Otherwise they are rejected without
|
||||
changing the installed pack; request the installation again so Manager can
|
||||
check its current Registry status.
|
||||
* Newly scheduled deferred version switches retain the returned version status
|
||||
and check it against the current listen address and option again at restart.
|
||||
and check it against the current listen address, option, and whitelist again
|
||||
at restart.
|
||||
This uses the saved status; it does not query CNR again for later status changes.
|
||||
Server-scheduled snapshot restores inherit the permission computed from the
|
||||
server's current listener and setting.
|
||||
server's current listener and setting, and read the whitelist from the server's
|
||||
Manager configuration directory.
|
||||
* Startup execution of deferred CNR switches and server-scheduled snapshot
|
||||
restores does not recheck `security_level`. Changing it to `strong` does not
|
||||
cancel previously scheduled work. For example, a flagged version switch
|
||||
scheduled under `normal` can still run after restarting with `strong` if the
|
||||
pack remains whitelisted. The startup flagged-version checks described above
|
||||
still apply. This is existing behavior of scheduled execution.
|
||||
* Standalone `cm-cli` commands remain local administrator operations and do not
|
||||
use the server listener policy.
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
python json-checker.py "custom-node-list.json"
|
||||
python json-checker.py "model-list.json"
|
||||
python json-checker.py "alter-list.json"
|
||||
python json-checker.py "extension-node-map.json"
|
||||
python json-checker.py "node_db\new\custom-node-list.json"
|
||||
python json-checker.py "node_db\new\model-list.json"
|
||||
|
||||
@@ -6,7 +6,6 @@ echo CHECK1
|
||||
files=(
|
||||
"custom-node-list.json"
|
||||
"model-list.json"
|
||||
"alter-list.json"
|
||||
"extension-node-map.json"
|
||||
"github-stats.json"
|
||||
"extras.json"
|
||||
|
||||
+123
-121
@@ -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 importlib
|
||||
@@ -21,17 +21,18 @@ import importlib
|
||||
comfy_path = os.environ.get('COMFYUI_PATH')
|
||||
|
||||
if comfy_path is None:
|
||||
print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
|
||||
rich.print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
|
||||
exit(-1)
|
||||
|
||||
sys.path.append(comfy_path)
|
||||
|
||||
if not os.path.exists(os.path.join(comfy_path, 'folder_paths.py')):
|
||||
print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
|
||||
rich.print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
|
||||
exit(-1)
|
||||
|
||||
|
||||
import utils.extra_config
|
||||
from comfyui_manager.common.git_compat import setup_git_environment
|
||||
from comfyui_manager.common import manager_util
|
||||
from comfyui_manager.common import cm_global
|
||||
from comfyui_manager.legacy import manager_core as core
|
||||
@@ -39,6 +40,8 @@ from comfyui_manager.common import context
|
||||
from comfyui_manager.legacy.manager_core import unified_manager
|
||||
from comfyui_manager.common import cnr_utils
|
||||
|
||||
print = core.print
|
||||
|
||||
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
|
||||
@@ -66,7 +69,7 @@ def check_comfyui_hash():
|
||||
core.comfy_ui_revision = repo.iter_commits_count()
|
||||
core.comfy_ui_commit_datetime = repo.head_commit_datetime
|
||||
except Exception:
|
||||
print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
|
||||
print('INFO: Frozen ComfyUI mode.', style='bold yellow')
|
||||
core.comfy_ui_revision = 0
|
||||
core.comfy_ui_commit_datetime = 0
|
||||
|
||||
@@ -74,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(context.manager_config_path)
|
||||
default_conf = config['default']
|
||||
|
||||
@@ -135,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)
|
||||
context.update_user_directory(user_directory)
|
||||
|
||||
context.update_user_directory(user_directory)
|
||||
if os.path.exists(context.manager_pip_overrides_path):
|
||||
with open(context.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(context.manager_pip_overrides_path):
|
||||
with open(context.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(context.manager_pip_blacklist_path):
|
||||
with open(context.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(context.manager_pip_blacklist_path):
|
||||
with open(context.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)
|
||||
setup_git_environment(core.get_config()['git_exe'])
|
||||
|
||||
def update_custom_nodes_dir(self, target_dir):
|
||||
import folder_paths
|
||||
@@ -196,7 +198,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
|
||||
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
|
||||
if not res.result:
|
||||
print(res.msg)
|
||||
print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
|
||||
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
|
||||
if raise_on_fail:
|
||||
raise NodeInstallError(node_spec_str)
|
||||
else:
|
||||
@@ -217,7 +219,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
|
||||
|
||||
if res.action == 'skip':
|
||||
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
|
||||
elif res.action == 'enable':
|
||||
elif res.action == 'enable' and res.result:
|
||||
print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
|
||||
elif res.action == 'install-git' and res.target == 'nightly':
|
||||
print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
|
||||
@@ -232,56 +234,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 raise_on_fail:
|
||||
raise NodeInstallError(node_name)
|
||||
|
||||
|
||||
def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
|
||||
repo_url = None
|
||||
if core.is_valid_url(node_spec_str):
|
||||
# URL-based: resolve_node_spec returns the full URL as node_name,
|
||||
# but internal dicts are keyed by repo basename or cnr_id.
|
||||
url = node_spec_str.rstrip('/')
|
||||
cnr = unified_manager.get_cnr_by_repo(url)
|
||||
if cnr:
|
||||
node_id = cnr['id']
|
||||
unified_manager.unified_uninstall(node_id, False)
|
||||
unified_manager.purge_node_state(node_id)
|
||||
node_name, version_spec = cnr['id'], 'nightly'
|
||||
else:
|
||||
repo_name = os.path.splitext(os.path.basename(url))[0]
|
||||
unified_manager.unified_uninstall(repo_name, True)
|
||||
unified_manager.purge_node_state(repo_name)
|
||||
|
||||
install_node(node_spec_str, is_all=is_all, cnt_msg=cnt_msg, raise_on_fail=True)
|
||||
node_name, version_spec, repo_url = core.unknown_node_id(url), 'unknown', url
|
||||
else:
|
||||
node_spec = unified_manager.resolve_node_spec(node_spec_str)
|
||||
node_name, version_spec, _ = node_spec
|
||||
node_name, version_spec, is_specified = unified_manager.resolve_node_spec(node_spec_str)
|
||||
if not is_specified:
|
||||
for guess_mode in ('active', 'inactive'):
|
||||
installed = unified_manager.resolve_unspecified_version(node_name, guess_mode=guess_mode)
|
||||
if installed not in (None, 'unknown'):
|
||||
version_spec = installed
|
||||
break
|
||||
|
||||
unified_manager.unified_uninstall(node_name, version_spec == 'unknown')
|
||||
unified_manager.purge_node_state(node_name)
|
||||
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")
|
||||
raise NodeInstallError(node_name)
|
||||
|
||||
install_node(node_name, is_all=is_all, cnt_msg=cnt_msg, raise_on_fail=True)
|
||||
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 = ''):
|
||||
@@ -337,8 +345,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']]
|
||||
|
||||
@@ -412,6 +421,7 @@ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
|
||||
|
||||
def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
|
||||
if 'comfyui-manager' in node_spec_str.lower():
|
||||
print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not disabled: its name has 'comfyui-manager'")
|
||||
return
|
||||
|
||||
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
|
||||
@@ -468,11 +478,7 @@ def show_list(kind, simple=False):
|
||||
|
||||
if flag and kind != 'cnr':
|
||||
for k, v in unified_manager.unknown_active_nodes.items():
|
||||
item = repo_unknown.get(k)
|
||||
|
||||
if item is None:
|
||||
continue
|
||||
|
||||
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
|
||||
log_item = "[ ENABLED ] ", item['title'], k, item['author']
|
||||
unknown_processed.append(log_item)
|
||||
|
||||
@@ -505,11 +511,7 @@ def show_list(kind, simple=False):
|
||||
|
||||
if flag and kind != 'cnr':
|
||||
for k, v in unified_manager.unknown_inactive_nodes.items():
|
||||
item = repo_unknown.get(k)
|
||||
|
||||
if item is None:
|
||||
continue
|
||||
|
||||
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
|
||||
log_item = "[ DISABLED ] ", item['title'], k, item['author']
|
||||
unknown_processed.append(log_item)
|
||||
|
||||
@@ -543,7 +545,7 @@ def show_list(kind, simple=False):
|
||||
if simple:
|
||||
print(title+'@'+ver_spec)
|
||||
else:
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [{ver_spec}]")
|
||||
|
||||
for x in unknown_processed:
|
||||
prefix, title, short_id, author = x
|
||||
@@ -553,19 +555,19 @@ def show_list(kind, simple=False):
|
||||
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
|
||||
|
||||
|
||||
async def show_snapshot(simple_mode=False):
|
||||
json_obj = await core.get_current_snapshot()
|
||||
def show_snapshot(simple_mode=False):
|
||||
json_obj = asyncio.run(core.get_current_snapshot())
|
||||
|
||||
if simple_mode:
|
||||
print(f"[{json_obj['comfyui']}] comfyui")
|
||||
core.print(f"[{json_obj['comfyui']}] comfyui")
|
||||
for k, v in json_obj['git_custom_nodes'].items():
|
||||
print(f"[{v['hash']}] {k}")
|
||||
core.print(f"[{v['hash']}] {k}")
|
||||
for v in json_obj['file_custom_nodes']:
|
||||
print(f"[ N/A ] {v['filename']}")
|
||||
core.print(f"[ N/A ] {v['filename']}")
|
||||
|
||||
else:
|
||||
formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
|
||||
print(formatted_json)
|
||||
core.print(formatted_json)
|
||||
|
||||
|
||||
def show_snapshot_list(simple_mode=False):
|
||||
@@ -646,7 +648,7 @@ def for_each_nodes(nodes, act, allow_all=True, **kwargs):
|
||||
failed.append(x)
|
||||
|
||||
if failed:
|
||||
print(f"\n[bold red]Failed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}[/bold red]")
|
||||
print(f"\nFailed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}", style="bold red")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -673,7 +675,7 @@ def install(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
no_deps: Annotated[
|
||||
Optional[bool],
|
||||
@@ -704,7 +706,7 @@ def install(
|
||||
cmd_ctx.set_channel_mode(channel, mode)
|
||||
|
||||
if uv_compile and no_deps:
|
||||
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
|
||||
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if uv_compile:
|
||||
@@ -713,7 +715,7 @@ def install(
|
||||
cmd_ctx.set_no_deps(no_deps)
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
|
||||
for_each_nodes(nodes, act=install_node, exit_on_fail=exit_on_fail)
|
||||
for_each_nodes(nodes, act=install_node, raise_on_fail=exit_on_fail)
|
||||
|
||||
_finalize_resolve(pip_fixer, uv_compile)
|
||||
|
||||
@@ -732,7 +734,7 @@ def reinstall(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
no_deps: Annotated[
|
||||
Optional[bool],
|
||||
@@ -759,7 +761,7 @@ def reinstall(
|
||||
cmd_ctx.set_channel_mode(channel, mode)
|
||||
|
||||
if uv_compile and no_deps:
|
||||
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
|
||||
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if uv_compile:
|
||||
@@ -787,7 +789,7 @@ def uninstall(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
):
|
||||
cmd_ctx.set_channel_mode(channel, mode)
|
||||
@@ -798,7 +800,7 @@ def uninstall(
|
||||
def update(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to update]"
|
||||
help="all|List of custom nodes to update"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -809,7 +811,7 @@ def update(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -849,7 +851,7 @@ def update(
|
||||
def disable(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to disable]"
|
||||
help="all|List of custom nodes to disable"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -860,7 +862,7 @@ def disable(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -880,7 +882,7 @@ def disable(
|
||||
def enable(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to enable]"
|
||||
help="all|List of custom nodes to enable"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -891,7 +893,7 @@ def enable(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -911,7 +913,7 @@ def enable(
|
||||
def fix(
|
||||
nodes: List[str] = typer.Argument(
|
||||
...,
|
||||
help="[all|List of custom nodes to fix]"
|
||||
help="all|List of custom nodes to fix"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -922,7 +924,7 @@ def fix(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -947,7 +949,7 @@ def fix(
|
||||
asyncio.run(auto_save_snapshot())
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
|
||||
for_each_nodes(nodes, fix_node, allow_all=True)
|
||||
for_each_nodes(nodes, fix_node, allow_all=True, fixed=set())
|
||||
|
||||
_finalize_resolve(pip_fixer, uv_compile)
|
||||
|
||||
@@ -965,7 +967,7 @@ def show_versions(node_name: str):
|
||||
@app.command("show", help="Show node list")
|
||||
def show(
|
||||
arg: str = typer.Argument(
|
||||
help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
|
||||
help="installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -976,7 +978,7 @@ def show(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1010,7 +1012,7 @@ def show(
|
||||
@app.command("simple-show", help="Show node list (simple mode)")
|
||||
def simple_show(
|
||||
arg: str = typer.Argument(
|
||||
help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
|
||||
help="installed|enabled|not-installed|disabled|all|snapshot|snapshot-list"
|
||||
),
|
||||
channel: Annotated[
|
||||
str,
|
||||
@@ -1021,7 +1023,7 @@ def simple_show(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1038,7 +1040,7 @@ def simple_show(
|
||||
"snapshot-list",
|
||||
]
|
||||
if arg not in valid_commands:
|
||||
typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
|
||||
typer.echo(f"Invalid command: `show {arg}`", err=True)
|
||||
exit(1)
|
||||
|
||||
cmd_ctx.set_user_directory(user_directory)
|
||||
@@ -1072,7 +1074,7 @@ def deps_in_workflow(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1086,7 +1088,7 @@ def deps_in_workflow(
|
||||
output_path = output
|
||||
|
||||
if not os.path.exists(input_path):
|
||||
print(f"[bold red]File not found: {input_path}[/bold red]")
|
||||
print(f"File not found: {input_path}", style="bold red")
|
||||
exit(1)
|
||||
|
||||
used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
|
||||
@@ -1131,13 +1133,13 @@ def save_snapshot(
|
||||
|
||||
if output is not None:
|
||||
if(not output.endswith('.json') and not output.endswith('.yaml')):
|
||||
print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
|
||||
print("ERROR: output path should be either '.json' or '.yaml' file.", style="bold red")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
dir_path = os.path.dirname(output)
|
||||
|
||||
if(dir_path != '' and not os.path.exists(dir_path)):
|
||||
print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
|
||||
print(f"ERROR: {output} path not exists.", style="bold red")
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
|
||||
@@ -1207,14 +1209,14 @@ def restore_snapshot(
|
||||
else:
|
||||
snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
|
||||
if not os.path.exists(snapshot_path):
|
||||
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
|
||||
print(f"ERROR: `{snapshot_path}` is not exists.", style="bold red")
|
||||
exit(1)
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
|
||||
try:
|
||||
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()
|
||||
if uv_compile:
|
||||
pip_fixer.fix_broken()
|
||||
@@ -1222,6 +1224,9 @@ def restore_snapshot(
|
||||
|
||||
_finalize_resolve(pip_fixer, uv_compile)
|
||||
|
||||
if not is_restored:
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
|
||||
@app.command(
|
||||
"restore-dependencies", help="Restore dependencies from whole installed custom nodes."
|
||||
@@ -1250,7 +1255,7 @@ def restore_dependencies(
|
||||
for base_path in cmd_ctx.get_custom_nodes_paths():
|
||||
for name in os.listdir(base_path):
|
||||
target = os.path.join(base_path, name)
|
||||
if os.path.isdir(target) and not name.endswith('.disabled'):
|
||||
if os.path.isdir(target) and not name.endswith('.disabled') and name != '__pycache__':
|
||||
node_paths.append(target)
|
||||
|
||||
total = len(node_paths)
|
||||
@@ -1298,7 +1303,7 @@ def install_deps(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1322,14 +1327,14 @@ def install_deps(
|
||||
asyncio.run(auto_save_snapshot())
|
||||
|
||||
if not os.path.exists(deps):
|
||||
print(f"[bold red]File not found: {deps}[/bold red]")
|
||||
print(f"File not found: {deps}", style="bold red")
|
||||
exit(1)
|
||||
else:
|
||||
with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
|
||||
try:
|
||||
json_obj = json.load(json_file)
|
||||
except Exception:
|
||||
print(f"[bold red]Invalid json file: {deps}[/bold red]")
|
||||
print(f"Invalid json file: {deps}", style="bold red")
|
||||
exit(1)
|
||||
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
|
||||
@@ -1340,7 +1345,8 @@ def install_deps(
|
||||
elif state == 'not-installed':
|
||||
asyncio.run(core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
|
||||
else: # disabled
|
||||
core.gitclone_set_active([k], False)
|
||||
cnr = unified_manager.get_cnr_by_repo(k)
|
||||
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
|
||||
|
||||
_finalize_resolve(pip_fixer, uv_compile)
|
||||
|
||||
@@ -1353,12 +1359,12 @@ def _finalize_resolve(pip_fixer, uv_compile) -> None:
|
||||
try:
|
||||
_run_unified_resolve()
|
||||
except ImportError as e:
|
||||
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
|
||||
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
except typer.Exit:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"[bold red]Batch resolution failed: {e}[/bold red]")
|
||||
print(f"Batch resolution failed: {e}", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
finally:
|
||||
pip_fixer.fix_broken()
|
||||
@@ -1378,7 +1384,7 @@ def _run_unified_resolve():
|
||||
|
||||
node_pack_paths = collect_node_pack_paths(cmd_ctx.get_custom_nodes_paths())
|
||||
if not node_pack_paths:
|
||||
print("[bold yellow]No custom node packs found.[/bold yellow]")
|
||||
print("No custom node packs found.", style="bold yellow")
|
||||
return
|
||||
|
||||
print(f"Resolving dependencies for {len(node_pack_paths)} node pack(s)...")
|
||||
@@ -1393,27 +1399,28 @@ def _run_unified_resolve():
|
||||
try:
|
||||
result = resolver.resolve_and_install()
|
||||
except UvNotAvailableError:
|
||||
print("[bold red]uv is not available. Install uv to use this feature.[/bold red]")
|
||||
print("uv is not available. Install uv to use this feature.", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
|
||||
if result.success:
|
||||
collected = result.collected
|
||||
if collected:
|
||||
print(
|
||||
f"[bold green]Resolved {len(collected.requirements)} deps "
|
||||
f"Resolved {len(collected.requirements)} deps "
|
||||
f"from {len(collected.sources)} source(s) "
|
||||
f"(skipped {len(collected.skipped)}).[/bold green]"
|
||||
f"(skipped {len(collected.skipped)}).",
|
||||
style="bold green",
|
||||
)
|
||||
else:
|
||||
print("[bold green]Resolution complete (no deps needed).[/bold green]")
|
||||
print("Resolution complete (no deps needed).", style="bold green")
|
||||
else:
|
||||
print(f"[bold red]Resolution failed: {result.error}[/bold red]")
|
||||
print(f"Resolution failed: {result.error}", style="bold red")
|
||||
if result.lockfile and result.lockfile.conflicts and result.collected:
|
||||
attributed = attribute_conflicts(result.collected.sources, result.lockfile.conflicts)
|
||||
if attributed:
|
||||
print("[bold yellow]Conflicting packages (by node pack):[/bold yellow]")
|
||||
print("Conflicting packages (by node pack):", style="bold yellow")
|
||||
for pkg_name, requesters in sorted(attributed.items()):
|
||||
print(f" [yellow]{pkg_name}[/yellow]:")
|
||||
print(f" {pkg_name}:", style="yellow")
|
||||
for pack_path, pkg_spec in requesters:
|
||||
print(f" {os.path.basename(pack_path)} → {pkg_spec}")
|
||||
raise typer.Exit(1)
|
||||
@@ -1435,12 +1442,12 @@ def unified_uv_compile(
|
||||
try:
|
||||
_run_unified_resolve()
|
||||
except ImportError as e:
|
||||
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
|
||||
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
except typer.Exit:
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"[bold red]Unexpected error: {e}[/bold red]")
|
||||
print(f"Unexpected error: {e}", style="bold red")
|
||||
raise typer.Exit(1)
|
||||
finally:
|
||||
pip_fixer.fix_broken()
|
||||
@@ -1463,7 +1470,7 @@ def export_custom_node_ids(
|
||||
] = None,
|
||||
mode: str = typer.Option(
|
||||
None,
|
||||
help="[remote|local|cache]"
|
||||
help="remote|local|cache"
|
||||
),
|
||||
user_directory: str = typer.Option(
|
||||
None,
|
||||
@@ -1525,7 +1532,6 @@ async def _force_update_cache(channel):
|
||||
"custom-node-list.json",
|
||||
"extension-node-map.json",
|
||||
"model-list.json",
|
||||
"alter-list.json",
|
||||
"github-stats.json",
|
||||
]
|
||||
|
||||
@@ -1541,13 +1547,12 @@ async def _force_update_cache(channel):
|
||||
|
||||
json_obj = await manager_util.get_data(uri, silent=True)
|
||||
|
||||
with manager_util.cache_lock:
|
||||
with open(cache_uri, "w", encoding='utf-8') as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
if not manager_util.write_cache_file(cache_uri, json_obj):
|
||||
raise OSError("the cache file is in use")
|
||||
|
||||
print(f" [CACHED] {filename}")
|
||||
except Exception as e:
|
||||
print(f" [bold red][FAILED] {filename}: {e}[/bold red]")
|
||||
print(f" [FAILED] {filename}: {e}", style="bold red")
|
||||
failed.append(filename)
|
||||
|
||||
print("Fetching channel data...")
|
||||
@@ -1560,7 +1565,7 @@ async def _force_update_cache(channel):
|
||||
try:
|
||||
await unified_manager.reload('remote', dont_wait=False)
|
||||
except Exception as e:
|
||||
print(f" [bold red][FAILED] CNR registry: {e}[/bold red]")
|
||||
print(f" [FAILED] CNR registry: {e}", style="bold red")
|
||||
failed.append("CNR registry")
|
||||
|
||||
# Step 3: Load nightly data (cache files now exist from Step 1)
|
||||
@@ -1568,10 +1573,10 @@ async def _force_update_cache(channel):
|
||||
await unified_manager.load_nightly(channel or 'default', 'cache')
|
||||
|
||||
if failed:
|
||||
print(f"\n[bold red]Cache update incomplete. Failed: {', '.join(failed)}[/bold red]")
|
||||
print(f"\nCache update incomplete. Failed: {', '.join(failed)}", style="bold red")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("[bold green]Cache update complete.[/bold green]")
|
||||
print("Cache update complete.", style="bold green")
|
||||
|
||||
|
||||
def main():
|
||||
@@ -1581,6 +1586,3 @@ def main():
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
|
||||
sys.exit(app())
|
||||
|
||||
|
||||
print("")
|
||||
|
||||
@@ -1,224 +0,0 @@
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id":"https://github.com/Fannovel16/comfyui_controlnet_aux",
|
||||
"tags":"controlnet",
|
||||
"description": "This extension provides preprocessor nodes for using controlnet."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/comfyanonymous/ComfyUI_experiments",
|
||||
"tags":"Dynamic Thresholding, DT, CFG, controlnet, reference only",
|
||||
"description": "This experimental nodes contains a 'Reference Only' node and a 'ModelSamplerTonemapNoiseTest' node corresponding to the 'Dynamic Threshold'."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ltdrdata/ComfyUI-Impact-Pack",
|
||||
"tags":"ddetailer, adetailer, ddsd, DD, loopback scaler, prompt, wildcard, dynamic prompt",
|
||||
"description": "To implement the feature of automatically detecting faces and enhancing details, various detection nodes and detailers provided by the Impact Pack can be applied. Similarly to Loopback Scaler, it also provides various custom workflows that can apply Ksampler while gradually scaling up."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ltdrdata/ComfyUI-Inspire-Pack",
|
||||
"tags":"lora block weight, effective block analyzer, lbw, variation seed",
|
||||
"description": "The Inspire Pack provides the functionality of Lora Block Weight, Variation Seed."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/biegert/ComfyUI-CLIPSeg/raw/main/custom_nodes/clipseg.py",
|
||||
"tags":"ddsd",
|
||||
"description": "This extension provides a feature that generates segment masks on an image using a text prompt. When used in conjunction with Impact Pack, it enables applications such as DDSD."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/BadCafeCode/masquerade-nodes-comfyui",
|
||||
"tags":"ddetailer",
|
||||
"description": "This extension is a less feature-rich and well-maintained alternative to Impact Pack, but it has fewer dependencies and may be easier to install on abnormal configurations. The author recommends trying Impact Pack first."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/BlenderNeko/ComfyUI_Cutoff",
|
||||
"tags":"cutoff",
|
||||
"description": "By using this extension, prompts like 'blue hair' can be prevented from interfering with other prompts by blocking the attribute 'blue' from being used in prompts other than 'hair'."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb",
|
||||
"tags":"prompt, weight",
|
||||
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. With this extension, various settings can be used to implement prompt processing methods similar to A1111. As this feature is also integrated into ComfyUI Cutoff, please download the Cutoff extension if you plan to use it in conjunction with Cutoff."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/shiimizu/ComfyUI_smZNodes",
|
||||
"tags":"prompt, weight",
|
||||
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. This extension helps to reproduce the same embedding as A1111."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/BlenderNeko/ComfyUI_Noise",
|
||||
"tags":"img2img alt, random",
|
||||
"description": "The extension provides an unsampler that reverses the sampling process, allowing for a function similar to img2img alt to be implemented. Furthermore, ComfyUI uses CPU's Random instead of GPU's Random for better reproducibility compared to A1111. This extension provides the ability to use GPU's Random for Latent Noise. However, since GPU's Random may vary depending on the GPU model, reproducibility on different devices cannot be guaranteed."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/BlenderNeko/ComfyUI_SeeCoder",
|
||||
"tags":"seecoder, prompt-free-diffusion",
|
||||
"description": "The extension provides seecoder feature."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/lilly1987/ComfyUI_node_Lilly",
|
||||
"tags":"prompt, wildcard",
|
||||
"description": "This extension provides features such as a wildcard function that randomly selects prompts belonging to a category and the ability to directly load lora from prompts."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/Davemane42/ComfyUI_Dave_CustomNode",
|
||||
"tags":"latent couple",
|
||||
"description": "ComfyUI already provides the ability to composite latents by default. However, this extension makes it more convenient to use by visualizing the composite area."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/LEv145/images-grid-comfy-plugin",
|
||||
"tags":"X/Y Plot",
|
||||
"description": "This tool provides a viewer node that allows for checking multiple outputs in a grid, similar to the X/Y Plot extension."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/pythongosssss/ComfyUI-WD14-Tagger",
|
||||
"tags":"deepbooru, clip interrogation",
|
||||
"description": "This extension generates clip text by taking an image as input and using the Deepbooru model."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/szhublox/ambw_comfyui",
|
||||
"tags":"supermerger",
|
||||
"description": "This node takes two models, merges individual blocks together at various ratios, and automatically rates each merge, keeping the ratio with the highest score. "
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ssitu/ComfyUI_UltimateSDUpscale",
|
||||
"tags":"upscaler, Ultimate SD Upscale",
|
||||
"description": "ComfyUI nodes for the Ultimate Stable Diffusion Upscale script by Coyote-A. Uses the same script used in the A1111 extension to hopefully replicate images generated using the A1111 webui."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/dawangraoming/ComfyUI_ksampler_gpu/raw/main/ksampler_gpu.py",
|
||||
"tags":"random, noise",
|
||||
"description": "A1111 provides KSampler that uses GPU-based random noise. This extension offers KSampler utilizing GPU-based random noise."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/space-nuko/nui-suite",
|
||||
"tags":"prompt, dynamic prompt",
|
||||
"description": "This extension provides nodes with the functionality of dynamic prompts."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/melMass/comfy_mtb",
|
||||
"tags":"roop",
|
||||
"description": "This extension provides bunch of nodes including roop"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ssitu/ComfyUI_roop",
|
||||
"tags":"roop",
|
||||
"description": "This extension provides nodes for the roop A1111 webui script."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/asagi4/comfyui-prompt-control",
|
||||
"tags":"prompt, prompt editing",
|
||||
"description": "This extension provides the ability to use prompts like \n\n**a [large::0.1] [cat|dog:0.05] [<lora:somelora:0.5:0.6>::0.5] [in a park:in space:0.4]**\n\n"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/adieyal/comfyui-dynamicprompts",
|
||||
"tags":"prompt, dynamic prompt",
|
||||
"description": "This extension is a port of sd-dynamic-prompt to ComfyUI."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/kwaroran/abg-comfyui",
|
||||
"tags":"abg, background remover",
|
||||
"description": "A Anime Background Remover node for comfyui, based on this hf space, works same as AGB extention in automatic1111."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/Gourieff/comfyui-reactor-node",
|
||||
"tags":"reactor, sd-webui-roop-nsfw",
|
||||
"description": "This is a ported version of ComfyUI for the sd-webui-roop-nsfw extension."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/laksjdjf/cgem156-ComfyUI",
|
||||
"tags":"regional prompt, latent couple, prompt",
|
||||
"description": "This custom nodes provide a functionality similar to regional prompts, offering couple features at the attention level."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/FizzleDorf/ComfyUI_FizzNodes",
|
||||
"tags":"deforum",
|
||||
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/seanlynch/comfyui-optical-flow",
|
||||
"tags":"deforum, vid2vid",
|
||||
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ssitu/ComfyUI_fabric",
|
||||
"tags":"fabric",
|
||||
"description": "Similar to sd-webui-fabric, this custom nodes provide the functionality of [a/FABRIC](https://github.com/sd-fabric/fabric)."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/Zuellni/ComfyUI-ExLlama",
|
||||
"tags":"ExLlama, prompt, language model",
|
||||
"description": "Similar to text-generation-webui, this custom nodes provide the functionality of [a/exllama](https://github.com/turboderp/exllama)."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/spinagon/ComfyUI-seamless-tiling",
|
||||
"tags":"tiling",
|
||||
"description": "ComfyUI node for generating seamless textures Replicates 'Tiling' option from A1111"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI",
|
||||
"tags":"cd-tuner, negpip",
|
||||
"description": "This extension is a port of the [a/sd-webui-cd-tuner](https://github.com/hako-mikan/sd-webui-cd-tuner)(a.k.a. CD(color/Detail) Tuner )and [a/sd-webui-negpip](https://github.com/hako-mikan/sd-webui-negpip)(a.k.a. NegPiP) extensions of A1111 to ComfyUI."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding",
|
||||
"tags":"DT, dynamic thresholding",
|
||||
"description": "This custom node is a port of the Dynamic Thresholding extension from A1111 to make it available for use in ComfyUI."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/hhhzzyang/Comfyui_Lama",
|
||||
"tags":"lama, inpainting anything",
|
||||
"description": "This extension provides custom nodes developed based on [a/LaMa](https://github.com/advimman/lama) and [a/Inpainting anything](https://github.com/geekyutao/Inpaint-Anything)."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/mlinmg/ComfyUI-LaMA-Preprocessor",
|
||||
"tags":"lama",
|
||||
"description": "This extension provides custom nodes for [a/LaMa](https://github.com/advimman/lama) functionality."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/Haoming02/comfyui-diffusion-cg",
|
||||
"tags":"diffusion-cg",
|
||||
"description": "This extension provides custom nodes for [a/SD Webui Diffusion Color Grading](https://github.com/Haoming02/sd-webui-diffusion-cg) functionality."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/asagi4/ComfyUI-CADS",
|
||||
"tags":"diffusion-cg",
|
||||
"description": "This extension provides custom nodes for [a/sd-webui-cads](https://github.com/v0xie/sd-webui-cads) functionality."
|
||||
},
|
||||
{
|
||||
"id":"https://git.mmaker.moe/mmaker/sd-webui-color-enhance",
|
||||
"tags":"color-enhance",
|
||||
"description": "This extension supports both A1111 and ComfyUI simultaneously."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/shiimizu/ComfyUI-TiledDiffusion",
|
||||
"tags":"multidiffusion",
|
||||
"description": "This extension provides custom nodes for [a/Mixture of Diffusers](https://github.com/albarji/mixture-of-diffusers) and [a/MultiDiffusion](https://github.com/omerbt/MultiDiffusion)"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/abyz22/image_control",
|
||||
"tags":"BMAB",
|
||||
"description": "This extension provides some alternative functionalities of the [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab) extension."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/blepping/ComfyUI-sonar",
|
||||
"tags":"sonar",
|
||||
"description": "This extension provides some alternative functionalities of the [a/stable-diffusion-webui-sonar](https://github.com/Kahsolt/stable-diffusion-webui-sonar) extension."
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/AIFSH/ComfyUI-RVC",
|
||||
"tags":"sonar",
|
||||
"description": "a comfyui custom node for [a/Retrieval-based-Voice-Conversion-WebUI](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git), you can Voice-Conversion in comfyui now!"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/portu-sim/comfyui-bmab",
|
||||
"tags":"bmab",
|
||||
"description": "a comfyui custom node for [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab)"
|
||||
},
|
||||
{
|
||||
"id":"https://github.com/ThereforeGames/ComfyUI-Unprompted",
|
||||
"tags":"unprompted",
|
||||
"description": "This extension is a port of [a/unprompted](https://github.com/ThereforeGames/unprompted)"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -239,6 +239,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:
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""Shared settings-file writer for glob and legacy."""
|
||||
import configparser
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from rich import print
|
||||
|
||||
|
||||
class DirtyTrackingConfig(dict):
|
||||
"""Track keys assigned after loading the startup configuration."""
|
||||
@@ -23,17 +22,35 @@ class DirtyTrackingConfig(dict):
|
||||
super().update(incoming)
|
||||
|
||||
|
||||
SETTING_VALUES = {
|
||||
'security_level': ('normal', 'strong', 'normal-', 'weak'),
|
||||
'network_mode': ('public', 'private', 'offline', 'personal_cloud'),
|
||||
'db_mode': ('cache', 'channel', 'local', 'remote'),
|
||||
'update_policy': ('stable-comfyui', 'nightly-comfyui', 'stable', 'nightly'),
|
||||
}
|
||||
|
||||
|
||||
def with_valid_values(settings):
|
||||
for key, values in SETTING_VALUES.items():
|
||||
default = values[0]
|
||||
if settings[key] not in values:
|
||||
logging.warning(f"[ComfyUI-Manager] {key} = {settings[key]!r} in config.ini is not valid; '{default}' is used.")
|
||||
settings[key] = default
|
||||
|
||||
return settings
|
||||
|
||||
|
||||
def write_config_merged(config_path, cached, written_config_keys):
|
||||
"""Merge changed owned keys onto the latest settings on disk.
|
||||
|
||||
Preserve parsed keys and values, not INI comments or formatting."""
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
try:
|
||||
loaded = config.read(config_path)
|
||||
except (configparser.Error, UnicodeDecodeError) as e:
|
||||
# Preserve the existing fallback for malformed files.
|
||||
print(f"[ComfyUI-Manager] Warning: '{config_path}' could not be parsed ({e}); rewriting it from the current settings.")
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
logging.warning(f"[ComfyUI-Manager] '{config_path}' could not be parsed ({e}); rewriting it from the current settings.")
|
||||
config = configparser.ConfigParser(strict=False, interpolation=None)
|
||||
else:
|
||||
# ConfigParser.read silently skips unreadable files; do not overwrite one.
|
||||
if not loaded and os.path.exists(config_path):
|
||||
|
||||
@@ -9,10 +9,11 @@ class NetworkMode(enum.Enum):
|
||||
class SecurityLevel(enum.Enum):
|
||||
STRONG = "strong"
|
||||
NORMAL = "normal"
|
||||
NORMAL_MINUS = "normal-minus"
|
||||
NORMAL_MINUS = "normal-"
|
||||
WEAK = "weak"
|
||||
|
||||
class DBMode(enum.Enum):
|
||||
LOCAL = "local"
|
||||
CACHE = "cache"
|
||||
CHANNEL = "channel"
|
||||
REMOTE = "remote"
|
||||
@@ -15,7 +15,10 @@ Exports:
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone, timedelta
|
||||
@@ -52,25 +55,91 @@ def _to_https_url(url):
|
||||
# Backend selection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def which_on_path(name):
|
||||
"""Return the file that the directories of PATH give for a command name.
|
||||
|
||||
`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
|
||||
|
||||
|
||||
_PYGIT2_REQUESTED = os.environ.get('CM_USE_PYGIT2', '').strip() == '1'
|
||||
USE_PYGIT2 = _PYGIT2_REQUESTED
|
||||
|
||||
_GIT_EXE = os.environ.get('GIT_EXE_PATH')
|
||||
_GIT_EXE_FOUND = None
|
||||
|
||||
|
||||
def _find_configured_git():
|
||||
found = find_git_executable(_GIT_EXE)
|
||||
if found is not None:
|
||||
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = found
|
||||
else:
|
||||
print(f"[ComfyUI-Manager] `git_exe = {_GIT_EXE}` is not a working git executable. The default git is used.", file=sys.stderr)
|
||||
return found
|
||||
|
||||
|
||||
if not USE_PYGIT2 and _GIT_EXE:
|
||||
_GIT_EXE_FOUND = _find_configured_git()
|
||||
|
||||
if not USE_PYGIT2:
|
||||
try:
|
||||
import git as _git
|
||||
_git.Git().execute(['git', '--version'])
|
||||
_git.Git().execute([_git.Git.GIT_PYTHON_GIT_EXECUTABLE, '--version'])
|
||||
except Exception:
|
||||
USE_PYGIT2 = True
|
||||
|
||||
if USE_PYGIT2:
|
||||
# Without a git, GitPython raises already when it is imported, unless it
|
||||
# is told to keep quiet. The legacy modules import it themselves.
|
||||
os.environ.setdefault('GIT_PYTHON_REFRESH', 'quiet')
|
||||
|
||||
try:
|
||||
import pygit2 as _pygit2
|
||||
except ImportError:
|
||||
# pygit2 not available either — fall back to GitPython and let it
|
||||
# fail at the point of use, preserving pre-existing behavior.
|
||||
# fail at the point of use.
|
||||
USE_PYGIT2 = False
|
||||
if _PYGIT2_REQUESTED and _GIT_EXE:
|
||||
_GIT_EXE_FOUND = _find_configured_git()
|
||||
_PYGIT2_REQUESTED = False
|
||||
import git as _git
|
||||
if not _git.GIT_OK:
|
||||
print("[ComfyUI-Manager] No git executable was found and pygit2 is not installed. What needs git will fail.", file=sys.stderr)
|
||||
else:
|
||||
# Disable owner validation once at import time.
|
||||
# Required for Desktop 2.0 standalone installs where repo directories
|
||||
@@ -133,11 +202,11 @@ else:
|
||||
|
||||
if USE_PYGIT2:
|
||||
if _PYGIT2_REQUESTED:
|
||||
print("[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)")
|
||||
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)"
|
||||
else:
|
||||
print("[ComfyUI-Manager] Using pygit2 backend (system git not available)")
|
||||
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (system git not available)"
|
||||
else:
|
||||
print("[ComfyUI-Manager] Using GitPython backend")
|
||||
BACKEND_LINE = "[ComfyUI-Manager] Using GitPython backend"
|
||||
|
||||
|
||||
# ===================================================================
|
||||
@@ -237,7 +306,14 @@ class GitRepo(ABC):
|
||||
def checkout_new_branch(self, branch_name: str, start_point: str): ...
|
||||
|
||||
@abstractmethod
|
||||
def submodule_update(self): ...
|
||||
def submodule_update(self, init=True): ...
|
||||
|
||||
def undo_pull(self, commit):
|
||||
self.reset_hard(commit)
|
||||
try:
|
||||
self.submodule_update(init=False)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def clear_cache(self): ...
|
||||
@@ -415,13 +491,17 @@ class _GitPythonRepo(GitRepo):
|
||||
self._repo.create_head(name)
|
||||
|
||||
def checkout(self, ref):
|
||||
# ref can be a _HeadProxy from get_head_by_name
|
||||
if isinstance(ref, _HeadProxy):
|
||||
ref = ref.name
|
||||
|
||||
self._repo.git.checkout(ref)
|
||||
|
||||
def checkout_new_branch(self, branch_name, start_point):
|
||||
self._repo.git.checkout('-b', branch_name, start_point)
|
||||
|
||||
def submodule_update(self):
|
||||
self._repo.git.submodule('update', '--init', '--recursive')
|
||||
def submodule_update(self, init=True):
|
||||
self._repo.git.submodule('update', *(['--init'] if init else []), '--recursive')
|
||||
|
||||
def clear_cache(self):
|
||||
self._repo.git.clear_cache()
|
||||
@@ -440,6 +520,17 @@ class _GitPythonRepo(GitRepo):
|
||||
# Pygit2 wrapper
|
||||
# ===================================================================
|
||||
|
||||
def _remote_callbacks():
|
||||
"""The callbacks of a clone or a fetch, without the one for the progress messages of the server.
|
||||
|
||||
pygit2 decodes each piece of such a message as UTF-8 before it calls that one, and a piece can end
|
||||
in the middle of a character: the clone or the fetch then ended with UnicodeDecodeError.
|
||||
"""
|
||||
callbacks = _pygit2.RemoteCallbacks()
|
||||
callbacks.sideband_progress = None
|
||||
return callbacks
|
||||
|
||||
|
||||
class _Pygit2Repo(GitRepo):
|
||||
def __init__(self, path):
|
||||
repo_path = os.path.abspath(path)
|
||||
@@ -467,12 +558,12 @@ class _Pygit2Repo(GitRepo):
|
||||
anon.fetch(
|
||||
list(refspecs) if refspecs is not None
|
||||
else list(remote.fetch_refspecs),
|
||||
proxy=_HTTP_PROXY,
|
||||
proxy=_HTTP_PROXY, callbacks=_remote_callbacks(),
|
||||
)
|
||||
elif refspecs is not None:
|
||||
remote.fetch(list(refspecs), proxy=_HTTP_PROXY)
|
||||
remote.fetch(list(refspecs), proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
remote.fetch(proxy=_HTTP_PROXY)
|
||||
remote.fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
|
||||
@property
|
||||
def working_dir(self):
|
||||
@@ -732,7 +823,11 @@ class _Pygit2Repo(GitRepo):
|
||||
|
||||
def stash(self):
|
||||
sig = _pygit2.Signature('comfyui-manager', 'manager@comfy')
|
||||
self._repo.stash(sig)
|
||||
try:
|
||||
self._repo.stash(sig)
|
||||
except KeyError:
|
||||
# nothing to stash, which is no error for git: a submodule that is at another commit makes the repository dirty
|
||||
pass
|
||||
|
||||
def pull_ff_only(self):
|
||||
branch_name = self.active_branch_name
|
||||
@@ -841,28 +936,96 @@ class _Pygit2Repo(GitRepo):
|
||||
self._repo.checkout(branch)
|
||||
self._repo.set_head(branch.name)
|
||||
|
||||
def submodule_update(self):
|
||||
@staticmethod
|
||||
def _check_out_from(git_dir, path):
|
||||
# set before the repository is opened: pygit2 does not open one whose `core.worktree` names a folder that is not there
|
||||
_pygit2.Config(os.path.join(git_dir, 'config'))['core.worktree'] = os.path.relpath(path, git_dir).replace(os.sep, '/')
|
||||
repo = _pygit2.Repository(git_dir)
|
||||
with open(os.path.join(path, '.git'), 'w', encoding='utf-8') as f:
|
||||
f.write('gitdir: ' + os.path.relpath(git_dir, path).replace(os.sep, '/') + '\n')
|
||||
if not repo.head_is_unborn:
|
||||
repo.reset(repo.head.target, _pygit2.GIT_RESET_HARD)
|
||||
|
||||
@staticmethod
|
||||
def _is_left_without_a_checkout(git_dir):
|
||||
if not os.path.exists(os.path.join(git_dir, 'HEAD')):
|
||||
return False
|
||||
# git keeps the repository of a submodule under its name, which can be the path of another one
|
||||
config = _pygit2.Config(os.path.join(git_dir, 'config'))
|
||||
return 'core.worktree' not in config or not os.path.exists(os.path.join(git_dir, config['core.worktree'], '.git'))
|
||||
|
||||
@staticmethod
|
||||
def _fetchable_submodules(repo):
|
||||
# pygit2 lists the submodules by path, and one that is looked up by its path has no url when its name is another
|
||||
names = {}
|
||||
gitmodules = os.path.join(repo.workdir, '.gitmodules')
|
||||
if os.path.exists(gitmodules):
|
||||
names = {entry.value: entry.name[len('submodule.'):-len('.path')] for entry in _pygit2.Config(gitmodules)
|
||||
if entry.name.startswith('submodule.') and entry.name.endswith('.path')}
|
||||
top = os.path.normcase(os.path.realpath(repo.workdir))
|
||||
named = [repo.submodules.get(names[path]) for path in repo.listall_submodules()
|
||||
if path in names and os.path.normcase(os.path.realpath(os.path.join(top, path))).startswith(top + os.sep)]
|
||||
return [submodule.name for submodule in named
|
||||
if submodule is not None and submodule.head_id is not None and submodule.url is not None]
|
||||
|
||||
def _update_submodules(self, repo, init):
|
||||
def checkout_of(name):
|
||||
return os.path.join(repo.workdir, repo.submodules[name].path)
|
||||
|
||||
fetchable = self._fetchable_submodules(repo)
|
||||
if init:
|
||||
for name in fetchable:
|
||||
# pygit2 does not clone into a folder that is not there
|
||||
os.makedirs(checkout_of(name), exist_ok=True)
|
||||
# a repository in `.git/modules` without a checkout: pygit2 refuses to clone into it
|
||||
leftover = os.path.join(repo.path, 'modules', repo.submodules[name].path)
|
||||
if not os.path.exists(os.path.join(checkout_of(name), '.git')) and self._is_left_without_a_checkout(leftover):
|
||||
self._check_out_from(leftover, checkout_of(name))
|
||||
checked_out = [name for name in fetchable if os.path.exists(os.path.join(checkout_of(name), '.git'))]
|
||||
names = fetchable if init else checked_out
|
||||
|
||||
if init and names:
|
||||
repo.submodules.init(names)
|
||||
for name in names:
|
||||
url = repo.config[f'submodule.{name}.url']
|
||||
if _to_https_url(url) != url:
|
||||
repo.config[f'submodule.{name}.url'] = _to_https_url(url)
|
||||
|
||||
if _HTTP_PROXY is not None:
|
||||
# `update` cannot be given the proxy: what it would fetch is fetched here, and it is left the checkout
|
||||
for name in names:
|
||||
submodule = repo.submodules[name]
|
||||
if name not in checked_out:
|
||||
# the url that `init` resolved: the one of `.gitmodules` may be relative
|
||||
_pygit2.clone_repository(repo.config[f'submodule.{name}.url'], os.path.join(repo.workdir, submodule.path),
|
||||
proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
cloned = submodule.open()
|
||||
if submodule.head_id not in cloned:
|
||||
cloned.remotes['origin'].fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
if names:
|
||||
repo.submodules.update(names, callbacks=_remote_callbacks())
|
||||
|
||||
for name in names:
|
||||
self._update_submodules(repo.submodules[name].open(), init)
|
||||
|
||||
def submodule_update(self, init=True):
|
||||
try:
|
||||
self._repo.submodules.init()
|
||||
self._repo.submodules.update()
|
||||
except Exception:
|
||||
import subprocess
|
||||
self._update_submodules(self._repo, init)
|
||||
except Exception as e:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['git', 'submodule', 'update', '--init', '--recursive'],
|
||||
['git', 'submodule', 'update', *(['--init'] if init else []), '--recursive'],
|
||||
cwd=self._working_dir,
|
||||
capture_output=True, timeout=120,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise GitCommandError(
|
||||
f"submodule update failed (exit {result.returncode}): "
|
||||
f"{result.stderr.decode(errors='replace')}")
|
||||
except FileNotFoundError:
|
||||
print("[ComfyUI-Manager] pygit2: submodule update requires system git (not installed)", file=sys.stderr)
|
||||
except GitCommandError:
|
||||
raise
|
||||
except Exception as sub_e:
|
||||
print(f"[ComfyUI-Manager] pygit2: submodule update failed: {sub_e}", file=sys.stderr)
|
||||
raise GitCommandError(f"submodule update failed: {e}") from e
|
||||
|
||||
if result.returncode != 0:
|
||||
raise GitCommandError(
|
||||
f"submodule update failed (exit {result.returncode}): "
|
||||
f"{result.stderr.decode(errors='replace')}")
|
||||
|
||||
def clear_cache(self):
|
||||
pass
|
||||
@@ -918,9 +1081,9 @@ def clone_repo(url, dest, progress=None):
|
||||
# configured so proxy-less installs keep working on older pygit2.
|
||||
# (A configured proxy still needs >=1.18 — see requirements.txt.)
|
||||
if _HTTP_PROXY is not None:
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY)
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
|
||||
else:
|
||||
_pygit2.clone_repository(_to_https_url(url), dest)
|
||||
_pygit2.clone_repository(_to_https_url(url), dest, callbacks=_remote_callbacks())
|
||||
repo = _Pygit2Repo(dest)
|
||||
repo.submodule_update()
|
||||
return repo
|
||||
@@ -934,7 +1097,15 @@ def clone_repo(url, dest, progress=None):
|
||||
|
||||
def setup_git_environment(git_exe):
|
||||
"""Configure the git executable path (GitPython only)."""
|
||||
if USE_PYGIT2:
|
||||
if USE_PYGIT2 or not git_exe:
|
||||
return
|
||||
if git_exe:
|
||||
_git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
|
||||
|
||||
if git_exe == _GIT_EXE:
|
||||
found = _GIT_EXE_FOUND
|
||||
else:
|
||||
found = find_git_executable(git_exe)
|
||||
if found is None:
|
||||
print(f"[ComfyUI-Manager] `git_exe = {git_exe}` is not a working git executable. The default git is used.", file=sys.stderr)
|
||||
|
||||
if found is not None and _git.Git.GIT_PYTHON_GIT_EXECUTABLE != found:
|
||||
_git.refresh(found)
|
||||
|
||||
@@ -6,7 +6,7 @@ import traceback
|
||||
# Make git_compat importable as a standalone subprocess script
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
|
||||
from git_compat import open_repo, clone_repo, GitCommandError, setup_git_environment
|
||||
from git_compat import open_repo, clone_repo, GitCommandError
|
||||
import json
|
||||
import yaml
|
||||
import requests
|
||||
@@ -18,7 +18,6 @@ except ImportError:
|
||||
|
||||
|
||||
comfy_path = os.environ.get('COMFYUI_PATH')
|
||||
git_exe_path = os.environ.get('GIT_EXE_PATH')
|
||||
|
||||
if comfy_path is None:
|
||||
print("git_helper: environment variable 'COMFYUI_PATH' is not specified.")
|
||||
@@ -267,6 +266,7 @@ def gitpull(path):
|
||||
print("CUSTOM NODE PULL: None") # there is no update
|
||||
return
|
||||
|
||||
tip_before_pull = repo.head_commit_hexsha
|
||||
try:
|
||||
repo.pull_ff_only()
|
||||
except GitCommandError:
|
||||
@@ -276,7 +276,12 @@ def gitpull(path):
|
||||
repo.reset_hard(f'{remote_name}/{branch_name}')
|
||||
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
|
||||
|
||||
repo.submodule_update()
|
||||
try:
|
||||
repo.submodule_update()
|
||||
except Exception:
|
||||
repo.undo_pull(tip_before_pull)
|
||||
raise
|
||||
|
||||
new_commit_hash = repo.head_commit_hexsha
|
||||
|
||||
if commit_hash != new_commit_hash:
|
||||
@@ -286,6 +291,7 @@ def gitpull(path):
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print("CUSTOM NODE PULL: Fail") # unknown git error
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def checkout_comfyui_hash(target_hash):
|
||||
@@ -537,14 +543,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:
|
||||
setup_git_environment(git_exe_path)
|
||||
|
||||
|
||||
setup_environment()
|
||||
|
||||
|
||||
try:
|
||||
if sys.argv[1] == "--clone":
|
||||
repo_path = None
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import configparser
|
||||
import logging
|
||||
|
||||
|
||||
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
|
||||
@@ -12,25 +13,110 @@ 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:
|
||||
return line
|
||||
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:"):
|
||||
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
|
||||
@@ -40,12 +126,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']
|
||||
|
||||
@@ -1,23 +1,13 @@
|
||||
"""Security helpers for CSRF protection and Content-Type gating.
|
||||
|
||||
reject_simple_form_post() is applied ONLY to POST handlers that do not consume
|
||||
a request body (e.g., snapshot/save, queue/reset, queue/start, reboot). These
|
||||
are vulnerable to cross-origin <form method=POST> attacks because the server
|
||||
accepts the request 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 DO read a body via ``await request.json()`` (install/git_url,
|
||||
install/pip, queue/install_model, db_mode POST, policy/update POST,
|
||||
channel_url_list POST, queue/batch, queue/task, import_fail_info, etc.) are
|
||||
NOT gated here — a cross-origin <form method=POST> cannot forge a valid JSON
|
||||
body because the browser refuses to send ``application/json`` without a CORS
|
||||
preflight, which this server rejects by not responding with an appropriate
|
||||
Access-Control-Allow-Origin.
|
||||
|
||||
DO NOT add the gate to body-reading handlers (redundant + UX-breaking).
|
||||
DO NOT remove the gate from no-body handlers (this is the bypass vector).
|
||||
reject_non_json_post() is applied to every POST handler that changes something.
|
||||
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.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
@@ -27,6 +17,8 @@ from aiohttp import web
|
||||
is_personal_cloud_mode = False
|
||||
handler_policy = {}
|
||||
|
||||
FLAGGED_NODEPACK_WHITELIST_FILE = 'nodepack-whitelist.list'
|
||||
|
||||
FLAGGED_NODEPACK_INSTALL_ERROR = (
|
||||
'This action is not allowed by the current security configuration. '
|
||||
'See the terminal for details.'
|
||||
@@ -39,49 +31,19 @@ FLAGGED_NODEPACK_INSTALL_GUIDANCE = (
|
||||
' Do not use bare --listen or any non-loopback address, such as 0.0.0.0 or ::.\n'
|
||||
'2. For a trusted private network, set allow_flagged_nodepack_install = true '
|
||||
'in the [default] section of ComfyUI-Manager\'s config.ini.\n'
|
||||
'Restart ComfyUI after changing the listener or configuration. '
|
||||
'3. To allow specific packs, add their Registry pack IDs (case-insensitive), one per line, '
|
||||
f'to {FLAGGED_NODEPACK_WHITELIST_FILE} beside ComfyUI-Manager\'s config.ini. '
|
||||
'Whitelist changes apply to subsequent installations without a restart.\n'
|
||||
'Restart ComfyUI after changing the listener or config.ini. '
|
||||
'All other installation security checks still apply.'
|
||||
)
|
||||
|
||||
|
||||
# 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 our 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 (no Access-Control-Allow-Origin response).
|
||||
_SIMPLE_FORM_CONTENT_TYPES = frozenset({
|
||||
'application/x-www-form-urlencoded',
|
||||
'multipart/form-data',
|
||||
'text/plain',
|
||||
})
|
||||
|
||||
|
||||
def reject_simple_form_post(request) -> Optional[web.Response]:
|
||||
"""Reject Content-Types that enable preflight-less <form method=POST> CSRF.
|
||||
|
||||
These 3 MIME types are the complete CORS "simple request" Content-Type set
|
||||
(Fetch spec §3.2.3 "CORS-safelisted request-header"). Blocking them
|
||||
eliminates the <form method=POST> cross-origin CSRF vector, because any
|
||||
other Content-Type triggers a browser-enforced CORS preflight — and this
|
||||
server does not answer preflights with ``Access-Control-Allow-Origin``,
|
||||
effectively blocking cross-origin requests that use non-simple types.
|
||||
|
||||
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 body, application/json, or any non-simple Content-Type).
|
||||
|
||||
Note:
|
||||
aiohttp's ``request.content_type`` normalizes the header (lower-cases,
|
||||
strips parameters), so a ``multipart/form-data; boundary=----X`` header
|
||||
is compared as ``multipart/form-data``.
|
||||
"""
|
||||
if request.content_type in _SIMPLE_FORM_CONTENT_TYPES:
|
||||
def reject_non_json_post(request) -> Optional[web.Response]:
|
||||
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
|
||||
|
||||
@@ -99,7 +61,7 @@ def is_loopback(address):
|
||||
return False
|
||||
|
||||
|
||||
def is_loopback_listener(listen_address: str) -> bool:
|
||||
def is_loopback_listener(listen_address: Optional[str]) -> bool:
|
||||
"""All addresses bound by --listen must resolve exclusively to loopback."""
|
||||
import socket
|
||||
|
||||
@@ -120,9 +82,62 @@ def is_loopback_listener(listen_address: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def is_cnr_install_allowed(status: str, allow_flagged: bool, listen_address: str) -> bool:
|
||||
"""Only flagged versions require loopback or the private-network opt-in."""
|
||||
return status != 'NodeVersionStatusFlagged' or bool(allow_flagged) or is_loopback_listener(listen_address)
|
||||
def ensure_nodepack_whitelist(manager_files_path):
|
||||
"""Create a commented template without replacing an existing whitelist."""
|
||||
path = os.path.join(manager_files_path, FLAGGED_NODEPACK_WHITELIST_FILE)
|
||||
try:
|
||||
os.makedirs(manager_files_path, exist_ok=True)
|
||||
with open(path, 'x', encoding='utf-8') as file:
|
||||
file.write(
|
||||
'# Allow selected flagged CNR nodepacks on non-local listeners.\n'
|
||||
'# One Registry ID per line; IDs are case-insensitive and apply to all versions.\n'
|
||||
'# Blank lines and # comments are ignored. Changes apply without restarting.\n'
|
||||
'# Other installation security checks still apply.\n'
|
||||
'#\n'
|
||||
'# Example entries (commented out; uncomment to allow):\n'
|
||||
'# comfyui-impact-pack\n'
|
||||
'# comfyui-inspire-pack # Optional inline comment\n'
|
||||
)
|
||||
except OSError as exc:
|
||||
if isinstance(exc, FileExistsError) and os.path.isfile(path):
|
||||
return
|
||||
logging.warning('[ComfyUI-Manager] Cannot create nodepack whitelist %s: %s', path, exc)
|
||||
|
||||
|
||||
def is_flagged_nodepack_whitelisted(node_id: str, manager_files_path) -> bool:
|
||||
"""Match a whole Registry ID, ignoring case, in the current Manager whitelist."""
|
||||
if not manager_files_path:
|
||||
return False
|
||||
path = os.path.join(manager_files_path, FLAGGED_NODEPACK_WHITELIST_FILE)
|
||||
try:
|
||||
with open(path, encoding='utf-8-sig') as file:
|
||||
contents = file.read()
|
||||
if '\x00' in contents:
|
||||
raise UnicodeError('NUL characters found; save the file as UTF-8')
|
||||
entries = (line.split('#', 1)[0].strip() for line in contents.split('\n'))
|
||||
if node_id.lower() in {entry.lower() for entry in entries if entry}:
|
||||
logging.warning('[ComfyUI-Manager] CNR installation of %r permitted by nodepack whitelist (%s).', node_id, path)
|
||||
return True
|
||||
return False
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
except (OSError, UnicodeError) as exc:
|
||||
logging.warning('[ComfyUI-Manager] Cannot read flagged nodepack whitelist %s: %s', path, exc)
|
||||
return False
|
||||
|
||||
|
||||
def is_cnr_install_allowed(
|
||||
status: str, allow_flagged: bool, listen_address: Optional[str], *,
|
||||
node_id: Optional[str] = None, manager_files_path=None,
|
||||
) -> bool:
|
||||
"""Flagged versions require loopback, explicit permission, or a whitelisted ID.
|
||||
|
||||
Restore children pass their parent's resolved permission and no listener.
|
||||
"""
|
||||
return (status != 'NodeVersionStatusFlagged'
|
||||
or bool(allow_flagged)
|
||||
or is_loopback_listener(listen_address)
|
||||
or (node_id is not None and is_flagged_nodepack_whitelisted(node_id, manager_files_path)))
|
||||
|
||||
|
||||
def is_dedicated_install_allowed(flag_value: bool, listen_address: str, network_mode: str) -> bool:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
description:
|
||||
`manager_util` is the lightest module shared across the prestartup_script, main code, and cm-cli of ComfyUI-Manager.
|
||||
"""
|
||||
import importlib.metadata
|
||||
import traceback
|
||||
|
||||
import aiohttp
|
||||
@@ -16,6 +17,11 @@ import platform
|
||||
import shlex
|
||||
import time
|
||||
from functools import lru_cache
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
|
||||
cache_lock = threading.Lock()
|
||||
@@ -114,17 +120,16 @@ class StrictVersion:
|
||||
self.parse_version_string()
|
||||
|
||||
def parse_version_string(self):
|
||||
parts = self.version_string.split('.')
|
||||
if not parts:
|
||||
raise ValueError("Version string must not be empty")
|
||||
# A pre-release follows the third number after '.' or '-': '0.1.3.post1', '1.8.0-beta.1'.
|
||||
# __str__ writes it with '-', so a version that was already normalized is read as well.
|
||||
m = re.fullmatch(r'(\d+)(?:\.(\d+)(?:\.(\d+)(?:[.-](.+))?)?)?', self.version_string)
|
||||
if m is None:
|
||||
raise ValueError(f"Invalid version: {self.version_string!r}")
|
||||
|
||||
self.major = int(parts[0])
|
||||
self.minor = int(parts[1]) if len(parts) > 1 else 0
|
||||
self.patch = int(parts[2]) if len(parts) > 2 else 0
|
||||
|
||||
# Handling pre-release versions if present
|
||||
if len(parts) > 3:
|
||||
self.pre_release = parts[3]
|
||||
self.major = int(m.group(1))
|
||||
self.minor = int(m.group(2) or 0)
|
||||
self.patch = int(m.group(3) or 0)
|
||||
self.pre_release = m.group(4)
|
||||
|
||||
def __str__(self):
|
||||
version = f"{self.major}.{self.minor}.{self.patch}"
|
||||
@@ -176,19 +181,25 @@ def is_file_created_within_one_day(file_path):
|
||||
if not os.path.exists(file_path):
|
||||
return False
|
||||
|
||||
file_creation_time = os.path.getctime(file_path)
|
||||
# The modification time: on Windows the creation time stays the same when a file is rewritten.
|
||||
file_modified_time = os.path.getmtime(file_path)
|
||||
current_time = time.time()
|
||||
time_difference = current_time - file_creation_time
|
||||
time_difference = current_time - file_modified_time
|
||||
|
||||
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',
|
||||
@@ -206,6 +217,9 @@ async def get_data(uri, silent=False):
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] An error occurred while fetching '{uri}': {e}")
|
||||
|
||||
if uri.startswith("http"):
|
||||
raise
|
||||
|
||||
return {}
|
||||
|
||||
if not silent:
|
||||
@@ -230,14 +244,47 @@ def get_cache_state(uri):
|
||||
return "expired"
|
||||
|
||||
|
||||
def save_to_cache(uri, json_obj, silent=False):
|
||||
cache_uri = get_cache_path(uri)
|
||||
def write_cache_file(cache_uri, json_obj):
|
||||
"""Write a cache file by replacing it, so that a write that stops part-way leaves the previous content.
|
||||
|
||||
Returns whether the cache was replaced. A cache that stays open elsewhere is left as it is,
|
||||
with a warning: writing over it in place could be cut short, and the caller has its data anyway.
|
||||
Takes `cache_lock`; do not call it while holding the lock."""
|
||||
tmp_uri = f"{cache_uri}.{os.getpid()}.tmp"
|
||||
|
||||
with cache_lock:
|
||||
with open(cache_uri, "w", encoding='utf-8') as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
if not silent:
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
try:
|
||||
with open(tmp_uri, "w", encoding='utf-8') as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
try:
|
||||
if os.path.exists(cache_uri):
|
||||
os.chmod(tmp_uri, os.stat(cache_uri).st_mode & 0o777)
|
||||
except OSError:
|
||||
# A file system that refuses chmod sets the mode itself.
|
||||
pass
|
||||
for attempt in range(3):
|
||||
try:
|
||||
os.replace(tmp_uri, cache_uri)
|
||||
return True
|
||||
except OSError as e:
|
||||
# Windows does not replace a file that is open elsewhere. A reader has it open
|
||||
# for a moment only, so try again shortly.
|
||||
refusal = e
|
||||
if attempt < 2:
|
||||
time.sleep(0.1)
|
||||
logging.warning(f"[ComfyUI-Manager] The cache could not be replaced and is left as it is: {cache_uri}\n=> {refusal}")
|
||||
return False
|
||||
finally:
|
||||
# Gone after a replace; otherwise remove it if nothing holds it open.
|
||||
try:
|
||||
os.remove(tmp_uri)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def save_to_cache(uri, json_obj, silent=False):
|
||||
if write_cache_file(get_cache_path(uri), json_obj) and not silent:
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
|
||||
|
||||
async def get_data_with_cache(uri, silent=False, cache_mode=True, dont_wait=False, dont_cache=False):
|
||||
@@ -260,11 +307,8 @@ async def get_data_with_cache(uri, silent=False, cache_mode=True, dont_wait=Fals
|
||||
else:
|
||||
json_obj = await get_data(uri, silent=silent)
|
||||
if not dont_cache:
|
||||
with cache_lock:
|
||||
with open(cache_uri, "w", encoding='utf-8') as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
if not silent:
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
if write_cache_file(cache_uri, json_obj) and not silent:
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
|
||||
return json_obj
|
||||
|
||||
@@ -286,6 +330,538 @@ 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)
|
||||
|
||||
|
||||
def normalize_pip_name(name):
|
||||
"""Return the key used to compare pip package names.
|
||||
|
||||
Case is ignored and runs of '-', '_' and '.' are one separator (PEP 503), written
|
||||
as '_'. `get_installed_packages()` returns its keys in this form.
|
||||
"""
|
||||
return re.sub(r'[-_.]+', '_', name.strip()).lower()
|
||||
|
||||
|
||||
_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):
|
||||
"""Read a requirement line into (normalized name, has extras, version clauses).
|
||||
|
||||
Clauses are (operator, version) pairs, one per clause of the requirement. A direct
|
||||
reference ('name @ url') has the single clause ('@', url), and a version that cannot
|
||||
be parsed has ('?', text); neither can be compared with an installed version. A
|
||||
trailing comment, an environment marker and pip options are ignored.
|
||||
|
||||
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.
|
||||
"""
|
||||
text = spec.strip()
|
||||
tail = _PIP_LINE_TAIL_PATTERN.search(text)
|
||||
if tail is not None:
|
||||
text = text[:tail.start()]
|
||||
|
||||
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, []
|
||||
return normalize_pip_name(match.group(1)), match.group(2) is not None, [('?', text[match.end(1):].strip())]
|
||||
|
||||
name = normalize_pip_name(requirement.name)
|
||||
extras = bool(requirement.extras)
|
||||
if requirement.url:
|
||||
return name, extras, [('@', requirement.url)]
|
||||
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.
|
||||
|
||||
'above': pip would have to install an older version. 'at': the clause allows the
|
||||
installed version and nothing newer in its range needs installing. 'below': the
|
||||
clause does not constrain the installed version from above.
|
||||
"""
|
||||
satisfied = Specifier(operator + version).contains(installed, prereleases=True)
|
||||
if operator == '<':
|
||||
return 'below' if satisfied else 'above'
|
||||
if satisfied:
|
||||
if operator == '<=' and not Specifier('==' + version).contains(installed, prereleases=True):
|
||||
return 'below'
|
||||
return 'at'
|
||||
bound = Version(version[:-2] if version.endswith('.*') else version)
|
||||
return 'above' if installed > bound else 'below'
|
||||
|
||||
|
||||
def _is_met(clauses, installed):
|
||||
"""Whether the installed version meets every clause."""
|
||||
return all(Specifier(operator + version).contains(installed, prereleases=True) for operator, version in clauses)
|
||||
|
||||
|
||||
def _is_excluded(clauses, installed):
|
||||
"""Whether a '!=' clause rejects the installed version."""
|
||||
return any(operator == '!=' and not Specifier('!=' + version).contains(installed, prereleases=True)
|
||||
for operator, version in clauses)
|
||||
|
||||
|
||||
def _newer_version_allowed(clauses, installed):
|
||||
"""Whether some version newer than the installed one meets every clause.
|
||||
|
||||
Which versions exist is not known here. The clauses are asked about the versions
|
||||
next to the installed one and next to the version of each clause, where a range
|
||||
that a clause closes or excludes ends: the version itself, the one right after it,
|
||||
and the next one at each level, which for '4.57.0' are '4.57.0.1', '4.57.1', '4.58'
|
||||
and '5'; for a pre-release, a post-release or a development release, the next one
|
||||
of its kind as well. Versions are written as long as the longest of them, so that
|
||||
'1.0' beside '<1.0.1' is followed by '1.0.0.1'. The first post-release of a version
|
||||
is asked about too.
|
||||
|
||||
A pre-release is asked about only when '==', '>=', '<=', '~=' or '===' names one:
|
||||
every pip takes a pre-release then. Otherwise pip may install an older release
|
||||
instead; pip before 25.0 does so even when '<' or '>' names a pre-release.
|
||||
|
||||
Another local build of the installed version is not asked about unless a clause
|
||||
names it: a label says nothing about being newer, and pip would most often find
|
||||
the build without a label.
|
||||
"""
|
||||
requirement = SpecifierSet(','.join(operator + version for operator, version in clauses))
|
||||
anchors = [installed]
|
||||
pre_release_named = False
|
||||
for operator, version in clauses:
|
||||
try:
|
||||
anchor = Version(version[:-2] if version.endswith('.*') else version)
|
||||
except InvalidVersion:
|
||||
continue # '===' may name anything
|
||||
anchors.append(anchor)
|
||||
if operator in ('==', '>=', '<=', '~=', '===') and anchor.is_prerelease:
|
||||
pre_release_named = True
|
||||
|
||||
width = max(len(anchor.release) for anchor in anchors)
|
||||
candidates = []
|
||||
for anchor in anchors:
|
||||
epoch = f'{anchor.epoch}!' if anchor.epoch else ''
|
||||
padded = anchor.release + (0,) * (width - len(anchor.release))
|
||||
releases = [padded, padded + (1,)]
|
||||
releases += [padded[:level] + (padded[level] + 1,) for level in range(width)]
|
||||
candidates += [epoch + '.'.join(map(str, release)) for release in releases]
|
||||
candidates.append(str(anchor))
|
||||
if anchor.pre is not None:
|
||||
candidates.append(f'{anchor.base_version}{anchor.pre[0]}{anchor.pre[1] + 1}')
|
||||
candidates.append(f'{anchor.base_version}.post{0 if anchor.post is None else anchor.post + 1}')
|
||||
if anchor.dev is not None:
|
||||
candidates.append(f"{anchor.public.rsplit('.dev', 1)[0]}.dev{anchor.dev + 1}")
|
||||
|
||||
for candidate in map(Version, candidates):
|
||||
if candidate.is_prerelease and not pre_release_named:
|
||||
continue
|
||||
if candidate > installed and requirement.contains(candidate, prereleases=True):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def downgrade_protection(spec, clauses, extras, installed):
|
||||
"""Decide whether a requirement may replace a downgrade-protected installed package.
|
||||
|
||||
`clauses` and `extras` come from `parse_pip_spec()`; `installed` is the installed
|
||||
version. Returns (blocked, error).
|
||||
|
||||
The requirement is blocked when any clause would make pip install an older version.
|
||||
Without extras it is also blocked when it has no version or allows exactly the
|
||||
installed version, where pip would change nothing. With extras pip would still add
|
||||
the extras' dependencies, so those two cases are allowed.
|
||||
|
||||
The clauses are weighed together. A clause that allows the installed version does
|
||||
not block the requirement when another clause sets a minimum above that version or
|
||||
excludes it with '!=': pip then installs another version, and which one is left to
|
||||
pip. When the installed version does not meet the clauses and no newer version meets
|
||||
them either, the requirement is blocked, with or without extras, because pip has
|
||||
only older versions to install.
|
||||
|
||||
An installed local build, such as a CUDA build, is given up only for a minimum above
|
||||
it. A requirement that allows it is blocked without extras, whatever its other
|
||||
clauses, and one that excludes it with '!=' is blocked unless it sets such a minimum:
|
||||
pip would replace the build with whatever it finds.
|
||||
|
||||
It is blocked as well when a clause cannot be compared with the installed version;
|
||||
`error` then says what was skipped, why, and how to proceed.
|
||||
"""
|
||||
if not clauses:
|
||||
return not extras, None
|
||||
|
||||
try:
|
||||
current = Version(installed)
|
||||
states = set()
|
||||
for operator, version in clauses:
|
||||
if operator in ('>=', '>', '!='):
|
||||
continue
|
||||
if operator not in ('<', '<=', '==', '===', '~='):
|
||||
raise InvalidSpecifier(operator)
|
||||
states.add(_upper_bound_state(operator, version, current))
|
||||
only_older = not _is_met(clauses, current) and not _newer_version_allowed(clauses, current)
|
||||
local_kept = (_is_excluded(clauses, current) and current.local is not None
|
||||
and not requires_newer_version(clauses, installed))
|
||||
except (InvalidSpecifier, InvalidVersion):
|
||||
return True, (
|
||||
f"Skipped '{spec.strip()}': this package is protected by downgrade_blacklist, and its installed "
|
||||
f"version ({installed}) cannot be compared with the requested version. Install it manually if it is "
|
||||
"needed, or remove the package from downgrade_blacklist in config.ini if it was added there.")
|
||||
|
||||
if 'above' in states or only_older or local_kept:
|
||||
return True, None
|
||||
if 'at' in states and not extras:
|
||||
# requires_newer_version() is also true when '!=' excludes the installed version
|
||||
return current.local is not None or not requires_newer_version(clauses, installed), None
|
||||
return False, None
|
||||
|
||||
|
||||
def requires_newer_version(clauses, installed):
|
||||
"""Whether the installed version fails the requirement where a newer version can meet it.
|
||||
|
||||
That is so when a clause sets a minimum above the installed version. It is also so
|
||||
when '!=' or '>' leaves out the installed version itself and a newer version meets
|
||||
every clause.
|
||||
|
||||
An installed local build, such as a CUDA build, is replaced only for a minimum above
|
||||
it. '!=' is no ground for it, nor is '>' of its own version.
|
||||
|
||||
A clause is read as pip reads it. '>' also leaves out a post-release and a local
|
||||
build of its version, and '==4.*' is met by a pre-release of 4.0. Clauses that
|
||||
cannot be compared count as requiring a newer version, so that pip decides.
|
||||
"""
|
||||
try:
|
||||
current = Version(installed)
|
||||
left_out = False # by '>', although the installed version is not below its version
|
||||
for operator, version in clauses:
|
||||
if operator in ('>', '>=', '==', '===', '~='):
|
||||
if Specifier(operator + version).contains(current, prereleases=True):
|
||||
continue
|
||||
bound = Version(version[:-2] if version.endswith('.*') else version)
|
||||
if current < bound:
|
||||
return True
|
||||
left_out = left_out or operator == '>'
|
||||
elif operator in ('@', '?'):
|
||||
return True
|
||||
if current.local is not None:
|
||||
return False
|
||||
return (left_out or _is_excluded(clauses, current)) and _newer_version_allowed(clauses, current)
|
||||
except InvalidVersion:
|
||||
return True
|
||||
|
||||
|
||||
def pip_block_reason(spec, blacklist, downgrade_blacklist):
|
||||
"""Return why a requirement must not be installed, or None if it may be.
|
||||
|
||||
'blacklisted': the package is in `blacklist`.
|
||||
'downgrade blacklisted': the package is in `downgrade_blacklist`, is installed, and
|
||||
`downgrade_protection()` blocks the requirement.
|
||||
|
||||
Names are compared in normalized form, so 'opencv-python', 'opencv_python' and
|
||||
'OpenCV-Python' are the same package in both lists and in the requirement.
|
||||
"""
|
||||
name, extras, clauses = parse_pip_spec(spec)
|
||||
if name is None:
|
||||
# The line does not name a package: only an identical blacklist entry applies.
|
||||
return 'blacklisted' if spec.strip() in blacklist else None
|
||||
|
||||
if name in {normalize_pip_name(x) for x in blacklist}:
|
||||
return 'blacklisted'
|
||||
|
||||
if name not in {normalize_pip_name(x) for x in downgrade_blacklist}:
|
||||
return None
|
||||
|
||||
installed = get_installed_packages().get(name)
|
||||
if installed is None:
|
||||
return None
|
||||
|
||||
blocked, error = downgrade_protection(spec, clauses, extras, installed)
|
||||
if error is not None:
|
||||
logging.error("[ComfyUI-Manager] %s", error)
|
||||
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.
|
||||
|
||||
The base command varies (python -m pip, python -s -m pip, python -m uv pip, uv pip),
|
||||
and options such as --index-url may follow the requirement.
|
||||
|
||||
The command must install one requirement, placed right after `install`. Only
|
||||
`pip_install()` builds a command with an option first and several packages; it is
|
||||
marked #FORCE and is not checked against the lists.
|
||||
"""
|
||||
for i in range(len(cmd) - 2):
|
||||
if cmd[i] == 'pip' and cmd[i + 1] == 'install':
|
||||
return cmd[i + 2]
|
||||
return None
|
||||
|
||||
|
||||
pip_map = None
|
||||
|
||||
|
||||
@@ -304,8 +880,7 @@ def get_installed_packages(renew=False):
|
||||
if y[0] == 'Package' or y[0].startswith('-'):
|
||||
continue
|
||||
|
||||
normalized_name = y[0].lower().replace('-', '_')
|
||||
pip_map[normalized_name] = y[1]
|
||||
pip_map[normalize_pip_name(y[0])] = y[1]
|
||||
except subprocess.CalledProcessError:
|
||||
logging.error("[ComfyUI-Manager] Failed to retrieve the information of installed pip packages.")
|
||||
return {}
|
||||
@@ -350,7 +925,7 @@ def parse_requirement_line(line):
|
||||
res['operator'] = operator
|
||||
|
||||
if version is not None:
|
||||
res['version'] = StrictVersion(version)
|
||||
res['version'] = version
|
||||
|
||||
if index_url is not None:
|
||||
res['index_url'] = index_url
|
||||
@@ -378,12 +953,12 @@ torch_torchvision_torchaudio_version_map = {
|
||||
}
|
||||
|
||||
|
||||
def torch_rollback(prev):
|
||||
def torch_rollback(prev, packages):
|
||||
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])
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
logging.error(cmd)
|
||||
return
|
||||
@@ -393,12 +968,13 @@ 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',
|
||||
cmd = make_pip_cmd(['install', '--pre', *packages,
|
||||
'--index-url', f"https://download.pytorch.org/whl/nightly/{platform}"])
|
||||
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}",
|
||||
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}"])
|
||||
logging.info(f"[ComfyUI-Manager] restore PyTorch to {torch_ver}+{platform}")
|
||||
|
||||
@@ -411,6 +987,15 @@ class PIPFixer:
|
||||
self.comfyui_path = comfyui_path
|
||||
self.manager_files_path = manager_files_path
|
||||
|
||||
def pip_auto_fix_names(self):
|
||||
"""Return the normalized names of the packages listed in pip_auto_fix.list."""
|
||||
pip_auto_fix_path = os.path.join(self.manager_files_path, "pip_auto_fix.list")
|
||||
if not os.path.exists(pip_auto_fix_path):
|
||||
return set()
|
||||
|
||||
with open(pip_auto_fix_path, 'r', encoding="UTF-8", errors="ignore") as f:
|
||||
return {parse_pip_spec(x)[0] for x in f.readlines()}
|
||||
|
||||
def fix_broken(self):
|
||||
new_pip_versions = get_installed_packages(True)
|
||||
|
||||
@@ -427,43 +1012,46 @@ 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'])
|
||||
or self.prev_pip_versions['torchvision'] != new_pip_versions['torchvision']:
|
||||
packages = [name for name in ('torch', 'torchvision', 'torchaudio')
|
||||
if name in self.prev_pip_versions or name in new_pip_versions]
|
||||
torch_rollback(self.prev_pip_versions['torch'], packages)
|
||||
except Exception as e:
|
||||
logging.error("[ComfyUI-Manager] Failed to restore PyTorch")
|
||||
logging.error(e)
|
||||
|
||||
# fix opencv
|
||||
# fix opencv - the OpenCV packages all install the `cv2` module; keep them at one version
|
||||
try:
|
||||
ocp = new_pip_versions.get('opencv-contrib-python')
|
||||
ocph = new_pip_versions.get('opencv-contrib-python-headless')
|
||||
op = new_pip_versions.get('opencv-python')
|
||||
oph = new_pip_versions.get('opencv-python-headless')
|
||||
# From least to most preferred: the package installed last provides `cv2`.
|
||||
# A headless package comes after one with the GUI, which needs system libraries that
|
||||
# Linux may lack; within each kind, the one with the contrib modules comes last.
|
||||
installed = {}
|
||||
for x in ['opencv-python', 'opencv-contrib-python', 'opencv-python-headless', 'opencv-contrib-python-headless']:
|
||||
version = new_pip_versions.get(normalize_pip_name(x))
|
||||
if version is not None:
|
||||
installed[x] = version
|
||||
|
||||
versions = [ocp, ocph, op, oph]
|
||||
versions = [StrictVersion(x) for x in versions if x is not None]
|
||||
versions.sort(reverse=True)
|
||||
|
||||
if len(versions) > 0:
|
||||
# pip_auto_fix.list decides the version of a package it lists; leave OpenCV to it then
|
||||
listed = self.pip_auto_fix_names()
|
||||
if len(installed) > 0 and not any(normalize_pip_name(x) in listed for x in installed):
|
||||
# upgrade to maximum version
|
||||
targets = []
|
||||
cur = versions[0]
|
||||
if ocp is not None and StrictVersion(ocp) != cur:
|
||||
targets.append('opencv-contrib-python')
|
||||
if ocph is not None and StrictVersion(ocph) != cur:
|
||||
targets.append('opencv-contrib-python-headless')
|
||||
if op is not None and StrictVersion(op) != cur:
|
||||
targets.append('opencv-python')
|
||||
if oph is not None and StrictVersion(oph) != cur:
|
||||
targets.append('opencv-python-headless')
|
||||
newest = max(installed.values(), key=Version)
|
||||
targets = [x for x, version in installed.items() if Version(version) != Version(newest)]
|
||||
|
||||
if len(targets) > 0:
|
||||
# --no-deps: the newest version is already installed for another package;
|
||||
# its dependencies, such as numpy, must stay as they are
|
||||
for x in targets:
|
||||
cmd = make_pip_cmd(['install', f"{x}=={versions[0].version_string}"])
|
||||
cmd = make_pip_cmd(['install', '--no-deps', f"{x}=={newest}"])
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
|
||||
preferred = list(installed)[-1]
|
||||
if preferred not in targets:
|
||||
# it was already at the newest version, and the installs above replaced its `cv2`
|
||||
cmd = make_pip_cmd(['install', '--no-deps', '--force-reinstall', f"{preferred}=={newest}"])
|
||||
subprocess.check_output(cmd, universal_newlines=True)
|
||||
|
||||
logging.info(f"[ComfyUI-Manager] 'opencv' dependencies were fixed: {targets}")
|
||||
@@ -506,26 +1094,17 @@ class PIPFixer:
|
||||
parsed = parse_requirement_line(x)
|
||||
need_to_reinstall = True
|
||||
|
||||
normalized_name = parsed['package'].lower().replace('-', '_')
|
||||
normalized_name = normalize_pip_name(parsed['package'])
|
||||
if normalized_name in new_pip_versions:
|
||||
if 'version' in parsed and 'operator' in parsed:
|
||||
cur = StrictVersion(new_pip_versions[normalized_name])
|
||||
dest = parsed['version']
|
||||
op = parsed['operator']
|
||||
if cur == dest:
|
||||
if op in ['==', '>=', '<=']:
|
||||
need_to_reinstall = False
|
||||
elif cur < dest:
|
||||
if op in ['<=', '<', '~=', '!=']:
|
||||
need_to_reinstall = False
|
||||
elif cur > dest:
|
||||
if op in ['>=', '>', '~=', '!=']:
|
||||
need_to_reinstall = False
|
||||
specifier = Specifier(parsed['operator'] + parsed['version'])
|
||||
if specifier.contains(new_pip_versions[normalized_name], prereleases=True):
|
||||
need_to_reinstall = False
|
||||
|
||||
if need_to_reinstall:
|
||||
cmd_args = ['install']
|
||||
if 'version' in parsed and 'operator' in parsed:
|
||||
cmd_args.append(parsed['package']+parsed['operator']+parsed['version'].version_string)
|
||||
cmd_args.append(parsed['package']+parsed['operator']+parsed['version'])
|
||||
|
||||
if 'index_url' in parsed:
|
||||
cmd_args.append('--index-url')
|
||||
@@ -572,6 +1151,32 @@ def robust_readlines(fullpath):
|
||||
return []
|
||||
|
||||
|
||||
def build_restart_command(argv, drop_args=()):
|
||||
"""
|
||||
Rebuild the command line used to re-exec the current ComfyUI process.
|
||||
|
||||
`argv` is `sys.argv` of the running process; entries listed in `drop_args` are left out.
|
||||
The result is meant to be passed to `os.execv(sys.executable, ...)`.
|
||||
|
||||
On Windows, `os.execv` does not quote anything: it joins the list with spaces into one
|
||||
command line and the new process splits it again. Every entry is therefore quoted with
|
||||
the MSVC rules (`subprocess.list2cmdline`), otherwise an argument such as `Profile 1`
|
||||
comes back as two arguments. Other platforms pass the list through untouched.
|
||||
"""
|
||||
argv = [x for x in argv if x not in drop_args]
|
||||
|
||||
if argv[0].endswith("__main__.py"): # this is a python module
|
||||
module_name = os.path.basename(os.path.dirname(argv[0]))
|
||||
cmds = [sys.executable, '-m', module_name] + argv[1:]
|
||||
else:
|
||||
cmds = [sys.executable] + argv
|
||||
|
||||
if sys.platform.startswith('win32'):
|
||||
cmds = [subprocess.list2cmdline([x]) for x in cmds]
|
||||
|
||||
return cmds
|
||||
|
||||
|
||||
def restore_pip_snapshot(pips, options):
|
||||
non_url = []
|
||||
local_url = []
|
||||
@@ -582,13 +1187,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
|
||||
@@ -597,7 +1211,7 @@ def restore_pip_snapshot(pips, options):
|
||||
# try all at once
|
||||
res = 1
|
||||
try:
|
||||
res = subprocess.check_output(make_pip_cmd(['install'] + non_url))
|
||||
res = subprocess.check_call(make_pip_cmd(['install'] + non_url))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -606,7 +1220,7 @@ def restore_pip_snapshot(pips, options):
|
||||
for x in non_url:
|
||||
res = 1
|
||||
try:
|
||||
res = subprocess.check_output(make_pip_cmd(['install', '--no-deps', x]))
|
||||
res = subprocess.check_call(make_pip_cmd(['install', '--no-deps', x]))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -617,22 +1231,23 @@ def restore_pip_snapshot(pips, options):
|
||||
for x in non_local_url:
|
||||
res = 1
|
||||
try:
|
||||
res = subprocess.check_output(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_output(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}")
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
return failed
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -72,8 +72,9 @@ def get_backup_branch_name(repo=None) -> str:
|
||||
Format: backup_YYYYMMDD_HHMMSS (or backup_YYYYMMDD_HHMMSS_N if exists)
|
||||
|
||||
Args:
|
||||
repo: Optional git.Repo object. If provided, checks for name collisions
|
||||
and adds sequential suffix if needed.
|
||||
repo: Optional repository: a git_compat repository (glob core) or
|
||||
GitPython's git.Repo (legacy core). If provided, checks for name
|
||||
collisions and adds sequential suffix if needed.
|
||||
|
||||
Returns:
|
||||
Unique backup branch name.
|
||||
@@ -85,7 +86,9 @@ def get_backup_branch_name(repo=None) -> str:
|
||||
|
||||
# Check if branch exists
|
||||
try:
|
||||
existing_branches = {b.name for b in repo.list_heads()}
|
||||
# a git_compat repository lists its branches with list_heads(); git.Repo has heads
|
||||
heads = repo.list_heads() if hasattr(repo, 'list_heads') else repo.heads
|
||||
existing_branches = {b.name for b in heads}
|
||||
except Exception:
|
||||
return base_name
|
||||
|
||||
|
||||
@@ -122,10 +122,6 @@ _INLINE_DANGEROUS_OPTIONS = re.compile(
|
||||
# Credential redaction in index URLs.
|
||||
_CREDENTIAL_PATTERN = re.compile(r'://([^@]+)@')
|
||||
|
||||
# Version-spec parsing (same regex as existing ``is_blacklisted()``).
|
||||
_VERSION_SPEC_PATTERN = re.compile(r'([^<>!~=]+)([<>!~=]=?)([^ ]*)')
|
||||
|
||||
|
||||
|
||||
def collect_node_pack_paths(custom_nodes_dirs: list[str]) -> list[str]:
|
||||
"""Collect all installed node-pack directory paths.
|
||||
@@ -209,11 +205,12 @@ class UnifiedDepResolver:
|
||||
) -> None:
|
||||
self.node_pack_paths = node_pack_paths
|
||||
self.base_requirements = base_requirements or []
|
||||
self.blacklist: set[str] = blacklist if blacklist is not None else set()
|
||||
# Requirement names are compared in normalised form, so the lists are too.
|
||||
self.blacklist: set[str] = {manager_util.normalize_pip_name(x) for x in blacklist or ()}
|
||||
self.overrides: dict[str, str] = overrides if overrides is not None else {}
|
||||
self.downgrade_blacklist: list[str] = (
|
||||
downgrade_blacklist if downgrade_blacklist is not None else []
|
||||
)
|
||||
self.downgrade_blacklist: list[str] = [
|
||||
manager_util.normalize_pip_name(x) for x in downgrade_blacklist or ()
|
||||
]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
@@ -610,43 +607,34 @@ class UnifiedDepResolver:
|
||||
|
||||
@staticmethod
|
||||
def _extract_package_name(spec: str) -> str:
|
||||
"""Extract normalised package name from a requirement spec."""
|
||||
name = re.split(r'[><=!~;\[@ ]', spec)[0].strip()
|
||||
return name.lower().replace('-', '_')
|
||||
"""Extract normalised package name from a requirement spec.
|
||||
|
||||
The name is read by ``manager_util.parse_pip_spec()``, as in ``is_blacklisted()``.
|
||||
A line that names no package is compared as a whole.
|
||||
"""
|
||||
name = manager_util.parse_pip_spec(spec)[0]
|
||||
return name if name is not None else manager_util.normalize_pip_name(spec)
|
||||
|
||||
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str,
|
||||
installed: dict) -> bool:
|
||||
"""Reproduce the downgrade logic from ``is_blacklisted()``.
|
||||
"""Apply the downgrade rule shared with ``is_blacklisted()``.
|
||||
|
||||
Uses ``manager_util.StrictVersion`` — **not** ``packaging.version``.
|
||||
Parsing and the decision come from ``manager_util.parse_pip_spec()`` and
|
||||
``manager_util.downgrade_protection()``, so both paths give the same result.
|
||||
|
||||
Args:
|
||||
installed: Pre-fetched snapshot from
|
||||
``manager_util.get_installed_packages()``.
|
||||
"""
|
||||
if pkg_name not in self.downgrade_blacklist:
|
||||
if pkg_name not in self.downgrade_blacklist or pkg_name not in installed:
|
||||
return False
|
||||
|
||||
match = _VERSION_SPEC_PATTERN.search(pkg_spec)
|
||||
|
||||
if match is None:
|
||||
# No version spec: prevent reinstall if already installed
|
||||
if pkg_name in installed:
|
||||
return True
|
||||
elif match.group(2) in ('<=', '==', '<', '~='):
|
||||
if pkg_name in installed:
|
||||
try:
|
||||
installed_ver = manager_util.StrictVersion(installed[pkg_name])
|
||||
requested_ver = manager_util.StrictVersion(match.group(3))
|
||||
if installed_ver >= requested_ver:
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
logger.warning(
|
||||
"[UnifiedDepResolver] version parse failed: %s", pkg_spec,
|
||||
)
|
||||
return False
|
||||
|
||||
return False
|
||||
_, extras, clauses = manager_util.parse_pip_spec(pkg_spec)
|
||||
blocked, error = manager_util.downgrade_protection(
|
||||
pkg_spec, clauses, extras, installed[pkg_name])
|
||||
if error is not None:
|
||||
logger.error("[UnifiedDepResolver] %s", error)
|
||||
return blocked
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers — parsing & output
|
||||
|
||||
@@ -13,6 +13,7 @@ from pydantic import BaseModel, Field, RootModel
|
||||
|
||||
class OperationType(str, Enum):
|
||||
install = "install"
|
||||
reinstall = "reinstall"
|
||||
uninstall = "uninstall"
|
||||
update = "update"
|
||||
update_comfyui = "update-comfyui"
|
||||
@@ -64,6 +65,10 @@ class ManagerPackInstalled(BaseModel):
|
||||
description="The name of the pack if installed from github (author/repo-name format)",
|
||||
)
|
||||
enabled: bool = Field(..., description="Whether the pack is enabled")
|
||||
invalid_installation: Optional[bool] = Field(
|
||||
None,
|
||||
description='True when the folder has neither .git nor .tracking, so the Manager can neither update it nor tell its version; absent or null otherwise. Its ver is then "unknown" and its cnr_id is the registry id of its pack when the registry list has it, otherwise [project].name of its pyproject.toml in lower case (also while the registry list is still loading), otherwise "". A reinstall task fixes it.',
|
||||
)
|
||||
|
||||
|
||||
class SelectedVersion(str, Enum):
|
||||
@@ -224,8 +229,12 @@ class UpdateComfyUIQueryParams(BaseModel):
|
||||
)
|
||||
ui_id: str = Field(..., description="UI identifier for task tracking")
|
||||
stable: Optional[bool] = Field(
|
||||
True,
|
||||
description="Whether to update to stable version (true) or nightly (false)",
|
||||
None,
|
||||
description="Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.",
|
||||
)
|
||||
is_stable: Optional[bool] = Field(
|
||||
None,
|
||||
description="Another name for `stable`, the one the task parameters use. Read when `stable` is not given.",
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -87,6 +87,7 @@ from ..common.security_messages import (
|
||||
SECURITY_MESSAGE_MIDDLE,
|
||||
SECURITY_MESSAGE_MIDDLE_P,
|
||||
SECURITY_MESSAGE_HIGH_P,
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL,
|
||||
)
|
||||
from .constants import (
|
||||
model_dir_name_map,
|
||||
@@ -133,8 +134,10 @@ def error_response(
|
||||
|
||||
|
||||
class ManagerFuncsInComfyUI(core.ManagerFuncs):
|
||||
def is_flagged_install_allowed(self):
|
||||
return core.get_config()['allow_flagged_nodepack_install'] or manager_security.is_loopback_listener(args.listen)
|
||||
def is_flagged_install_allowed(self, node_id):
|
||||
return manager_security.is_cnr_install_allowed(
|
||||
'NodeVersionStatusFlagged', core.get_config()['allow_flagged_nodepack_install'], args.listen,
|
||||
node_id=node_id, manager_files_path=context.manager_files_path)
|
||||
|
||||
def run_script(self, cmd, cwd="."):
|
||||
if len(cmd) > 0 and cmd[0].startswith("#"):
|
||||
@@ -347,6 +350,7 @@ class TaskQueue:
|
||||
# Force cache refresh for successful pack-modifying operations
|
||||
pack_modifying_tasks = {
|
||||
OperationType.install.value,
|
||||
OperationType.reinstall.value,
|
||||
OperationType.uninstall.value,
|
||||
OperationType.enable.value,
|
||||
OperationType.disable.value,
|
||||
@@ -813,11 +817,16 @@ class TaskQueue:
|
||||
task_queue = TaskQueue()
|
||||
|
||||
|
||||
def replaces_cnr_with_nightly(node_id):
|
||||
unified = core.unified_manager
|
||||
return unified.is_enabled(node_id, 'cnr') and unified.resolve_unspecified_version(node_id, guess_mode='inactive') == 'nightly'
|
||||
|
||||
|
||||
async def task_worker():
|
||||
logging.debug("[ComfyUI-Manager] Task worker started")
|
||||
await core.unified_manager.reload(ManagerDatabaseSource.cache.value)
|
||||
|
||||
async def do_install(params: InstallPackParams) -> str:
|
||||
async def do_install(params: InstallPackParams, operation: str) -> str:
|
||||
node_id = params.id
|
||||
node_version = params.selected_version
|
||||
channel = params.channel
|
||||
@@ -848,13 +857,18 @@ async def task_worker():
|
||||
if not security_utils.is_allowed_security_level(level):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P if level == 'middle+' else SECURITY_MESSAGE_MIDDLE)
|
||||
return OperationResult.failed.value
|
||||
res = await core.unified_manager.install_by_id(
|
||||
node_name,
|
||||
version_spec,
|
||||
channel,
|
||||
mode,
|
||||
return_postinstall=skip_post_install,
|
||||
) # discard post install if skip_post_install mode
|
||||
if operation == OperationType.reinstall.value:
|
||||
res = await core.unified_manager.reinstall_by_id(
|
||||
node_name, version_spec, channel, mode
|
||||
)
|
||||
else:
|
||||
res = await core.unified_manager.install_by_id(
|
||||
node_name,
|
||||
version_spec,
|
||||
channel,
|
||||
mode,
|
||||
return_postinstall=skip_post_install,
|
||||
)
|
||||
|
||||
if res.action not in [
|
||||
"skip",
|
||||
@@ -878,8 +892,15 @@ async def task_worker():
|
||||
async def do_enable(params: EnablePackParams) -> str:
|
||||
cnr_id = params.cnr_id
|
||||
logging.debug("[ComfyUI-Manager] Enabling node: cnr_id=%s", cnr_id)
|
||||
core.unified_manager.unified_enable(cnr_id)
|
||||
return OperationResult.success.value
|
||||
if replaces_cnr_with_nightly(cnr_id) and not security_utils.is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return OperationResult.failed.value
|
||||
res = core.unified_manager.unified_enable(cnr_id)
|
||||
if res.result:
|
||||
return OperationResult.success.value
|
||||
|
||||
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
|
||||
return f"Failed to enable: '{cnr_id}'"
|
||||
|
||||
async def do_update(params: UpdatePackParams) -> dict[str, str]:
|
||||
node_name = params.node_name
|
||||
@@ -898,7 +919,7 @@ async def task_worker():
|
||||
# the remote URL. Downstream branches at L901/904 already
|
||||
# handle url is None, so we just need a None-safe title.
|
||||
# Harmonized with legacy/manager_server.py equivalent (WI #252).
|
||||
url = core.unified_manager.unknown_active_nodes[node_name][0]
|
||||
url = core.unified_manager.unknown_active_nodes.get(node_name, (None,))[0]
|
||||
title = os.path.basename(url) if url else node_name
|
||||
else:
|
||||
url = core.unified_manager.cnr_map[node_name].get("repository")
|
||||
@@ -921,7 +942,7 @@ async def task_worker():
|
||||
|
||||
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})"
|
||||
f"\nERROR: An error occurred while updating '{node_name}': {res.msg} (res.result={res.result}, res.action={res.action})"
|
||||
)
|
||||
return base_res
|
||||
except Exception:
|
||||
@@ -935,6 +956,10 @@ async def task_worker():
|
||||
|
||||
# Check if this is a version switch operation
|
||||
if params.target_version:
|
||||
if core.is_comfyui_downgrade(params.target_version) and not security_utils.is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return OperationResult.failed.value
|
||||
|
||||
# Switch to specific version
|
||||
logging.info(f"Switching ComfyUI to version: {params.target_version}")
|
||||
core.switch_comfyui(params.target_version)
|
||||
@@ -1043,9 +1068,10 @@ async def task_worker():
|
||||
try:
|
||||
res = core.unified_manager.unified_disable(node_name, is_unknown)
|
||||
|
||||
if res:
|
||||
if res.result:
|
||||
return OperationResult.success.value
|
||||
|
||||
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
@@ -1058,6 +1084,18 @@ async def task_worker():
|
||||
|
||||
json_data = params.model_dump()
|
||||
|
||||
# Checked here, not in a route: queue/install_model and queue/task both end up here.
|
||||
if not await model_utils.check_whitelist_for_model(json_data):
|
||||
logging.error(f"[ComfyUI-Manager] Invalid model install request is detected: {json_data}")
|
||||
return "Invalid model install request is detected"
|
||||
|
||||
if not json_data["filename"].endswith(".safetensors") and not security_utils.is_allowed_security_level("high+"):
|
||||
models_json = await core.get_data_by_mode(ManagerDatabaseSource.cache.value, "model-list.json", "default")
|
||||
|
||||
if not any(x.get("url") == json_data["url"] for x in models_json.get("models", [])):
|
||||
logging.error(SECURITY_MESSAGE_NORMAL_MINUS_MODEL)
|
||||
return "A security error has occurred. Please check the terminal logs"
|
||||
|
||||
model_path = model_utils.get_model_path(json_data)
|
||||
model_url = json_data.get("url")
|
||||
|
||||
@@ -1160,8 +1198,8 @@ async def task_worker():
|
||||
)
|
||||
|
||||
try:
|
||||
if kind == OperationType.install.value:
|
||||
msg = await do_install(item.params)
|
||||
if kind in (OperationType.install.value, OperationType.reinstall.value):
|
||||
msg = await do_install(item.params, kind)
|
||||
elif kind == OperationType.enable.value:
|
||||
msg = await do_enable(item.params)
|
||||
elif kind == OperationType.install_model.value:
|
||||
@@ -1241,6 +1279,10 @@ async def queue_task(request) -> web.Response:
|
||||
Returns:
|
||||
web.Response: HTTP 200 on successful queueing, HTTP 400 on validation error
|
||||
"""
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
# Validate input using Pydantic model
|
||||
@@ -1436,7 +1478,7 @@ async def fetch_updates(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/update_all")
|
||||
async def update_all(request: web.Request) -> web.Response:
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1496,6 +1538,9 @@ async def _update_all(params: UpdateAllQueryParams) -> web.Response:
|
||||
if os.environ.get("__COMFYUI_DESKTOP_VERSION__"):
|
||||
continue
|
||||
|
||||
if v[1] in core.unified_manager.invalid_installations:
|
||||
continue
|
||||
|
||||
update_task = QueueTaskItem(
|
||||
kind=OperationType.update.value,
|
||||
ui_id=f"{base_ui_id}_{k}", # Use client's base ui_id + node name
|
||||
@@ -1549,7 +1594,7 @@ async def get_snapshot_list(request):
|
||||
|
||||
@routes.post("/v2/snapshot/remove")
|
||||
async def remove_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
@@ -1574,11 +1619,11 @@ async def remove_snapshot(request):
|
||||
|
||||
@routes.post("/v2/snapshot/restore")
|
||||
async def restore_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle+"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
if not security_utils.is_allowed_security_level("high+"):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
|
||||
try:
|
||||
@@ -1619,7 +1664,7 @@ async def get_current_snapshot_api(request):
|
||||
|
||||
@routes.post("/v2/snapshot/save")
|
||||
async def save_snapshot(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1660,6 +1705,10 @@ def unzip_install(files):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info")
|
||||
async def import_fail_info(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1694,6 +1743,10 @@ async def import_fail_info(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info_bulk")
|
||||
async def import_fail_info_bulk(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1755,7 +1808,7 @@ async def import_fail_info_bulk(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
logging.debug("[ComfyUI-Manager] Queue reset requested")
|
||||
@@ -1818,7 +1871,7 @@ async def queue_count(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/start")
|
||||
async def queue_start(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
logging.debug("[ComfyUI-Manager] Queue start requested")
|
||||
@@ -1835,7 +1888,7 @@ async def queue_start(request):
|
||||
@routes.post("/v2/manager/queue/update_comfyui")
|
||||
async def update_comfyui(request):
|
||||
"""Queue a ComfyUI update based on the configured update policy."""
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1845,10 +1898,12 @@ async def update_comfyui(request):
|
||||
)
|
||||
|
||||
# Check if stable parameter was provided, otherwise use config
|
||||
if query_params.stable is None:
|
||||
is_stable = core.get_config()["update_policy"] != "nightly-comfyui"
|
||||
else:
|
||||
if query_params.stable is not None:
|
||||
is_stable = query_params.stable
|
||||
elif query_params.is_stable is not None:
|
||||
is_stable = query_params.is_stable
|
||||
else:
|
||||
is_stable = core.get_config()["update_policy"] not in ("nightly", "nightly-comfyui")
|
||||
|
||||
client_id = query_params.client_id
|
||||
ui_id = query_params.ui_id
|
||||
@@ -1886,10 +1941,10 @@ async def comfyui_versions(request):
|
||||
|
||||
@routes.post("/v2/comfyui_manager/comfyui_switch_version")
|
||||
async def comfyui_switch_version(request):
|
||||
# Body-reading handler — Content-Type gate omitted per
|
||||
# comfyui_manager/common/manager_security.py module policy: a cross-origin
|
||||
# <form method=POST> cannot forge a valid application/json body because
|
||||
# the browser would trigger a CORS preflight that this server refuses.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("high+"):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
@@ -1928,6 +1983,10 @@ async def comfyui_switch_version(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/install_model")
|
||||
async def install_model(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1965,11 +2024,12 @@ async def db_mode(request):
|
||||
|
||||
@routes.post("/v2/manager/db_mode")
|
||||
async def set_db_mode_api(request):
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# Config writes are at the same risk tier as uninstall/update — apply the
|
||||
# 'middle' gate consistent with snapshot/remove, etc. Content-Type gate is
|
||||
# NOT applied here: this handler consumes application/json and a
|
||||
# cross-origin <form method=POST> cannot forge that without triggering
|
||||
# CORS preflight (see module docstring in common/manager_security.py).
|
||||
# 'middle' gate consistent with snapshot/remove, etc.
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1978,7 +2038,7 @@ async def set_db_mode_api(request):
|
||||
environment_utils.set_db_mode(data["value"])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text="Invalid request")
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
@@ -1991,7 +2051,10 @@ async def update_policy(request):
|
||||
|
||||
@routes.post("/v2/manager/policy/update")
|
||||
async def set_update_policy_api(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -2000,7 +2063,7 @@ async def set_update_policy_api(request):
|
||||
environment_utils.set_update_policy(data["value"])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text="Invalid request")
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
@@ -2023,7 +2086,10 @@ async def channel_url_list(request):
|
||||
|
||||
@routes.post("/v2/manager/channel_url_list")
|
||||
async def set_channel_url(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -2048,7 +2114,7 @@ async def set_channel_url(request):
|
||||
|
||||
@routes.post("/v2/manager/reboot")
|
||||
def restart(request):
|
||||
rejection = security_utils.reject_simple_form_post(request)
|
||||
rejection = security_utils.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not security_utils.is_allowed_security_level("middle"):
|
||||
@@ -2073,17 +2139,9 @@ def restart(request):
|
||||
"\nRestarting... [Legacy Mode]\n\n"
|
||||
) # This printing should not be logging - that will be ugly
|
||||
|
||||
sys_argv = sys.argv.copy()
|
||||
if "--windows-standalone-build" in sys_argv:
|
||||
sys_argv.remove("--windows-standalone-build")
|
||||
|
||||
if sys_argv[0].endswith("__main__.py"): # this is a python module
|
||||
module_name = os.path.basename(os.path.dirname(sys_argv[0]))
|
||||
cmds = [sys.executable, "-m", module_name] + sys_argv[1:]
|
||||
elif sys.platform.startswith("win32"):
|
||||
cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
|
||||
else:
|
||||
cmds = [sys.executable] + sys_argv
|
||||
cmds = manager_util.build_restart_command(
|
||||
sys.argv, drop_args=("--windows-standalone-build",)
|
||||
)
|
||||
|
||||
print(f"Command: {cmds}", flush=True)
|
||||
|
||||
@@ -2136,10 +2194,8 @@ async def default_cache_update():
|
||||
|
||||
json_obj = await manager_util.get_data(uri, True)
|
||||
|
||||
with manager_util.cache_lock:
|
||||
with open(cache_uri, "w", encoding="utf-8") as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
logging.debug(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
if manager_util.write_cache_file(cache_uri, json_obj):
|
||||
logging.debug(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
except Exception as e:
|
||||
logging.error(
|
||||
f"[ComfyUI-Manager] Failed to perform initial fetching '{filename}': {e}"
|
||||
@@ -2150,15 +2206,17 @@ 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(
|
||||
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
|
||||
)
|
||||
else:
|
||||
# load at least once
|
||||
await core.unified_manager.reload(
|
||||
@@ -2172,6 +2230,7 @@ async def default_cache_update():
|
||||
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
|
||||
)
|
||||
|
||||
core.check_invalid_nodes()
|
||||
logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import mimetypes
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from . import manager_core as core
|
||||
|
||||
import os
|
||||
from aiohttp import web
|
||||
import aiohttp
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
import folder_paths
|
||||
from server import PromptServer
|
||||
@@ -22,69 +21,33 @@ except Exception:
|
||||
matrix_nio_is_available = False
|
||||
|
||||
|
||||
def extract_model_file_names(json_data):
|
||||
"""Extract unique file names from the input JSON data."""
|
||||
file_names = set()
|
||||
model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
|
||||
|
||||
# Recursively search for file names in the JSON data
|
||||
def recursive_search(data):
|
||||
if isinstance(data, dict):
|
||||
for value in data.values():
|
||||
recursive_search(value)
|
||||
elif isinstance(data, list):
|
||||
for item in data:
|
||||
recursive_search(item)
|
||||
elif isinstance(data, str) and '.' in data:
|
||||
file_names.add(os.path.basename(data)) # file_names.add(data)
|
||||
|
||||
recursive_search(json_data)
|
||||
return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
|
||||
|
||||
|
||||
def find_file_paths(base_dir, file_names):
|
||||
"""Find the paths of the files in the base directory."""
|
||||
file_paths = {}
|
||||
|
||||
for root, dirs, files in os.walk(base_dir):
|
||||
# Exclude certain directories
|
||||
dirs[:] = [d for d in dirs if d not in ['.git']]
|
||||
|
||||
for file in files:
|
||||
if file in file_names:
|
||||
file_paths[file] = os.path.join(root, file)
|
||||
return file_paths
|
||||
|
||||
|
||||
def compute_sha256_checksum(filepath):
|
||||
"""Compute the SHA256 checksum of a file, in chunks"""
|
||||
sha256 = hashlib.sha256()
|
||||
with open(filepath, 'rb') as f:
|
||||
for chunk in iter(lambda: f.read(4096), b''):
|
||||
sha256.update(chunk)
|
||||
return sha256.hexdigest()
|
||||
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/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("/v2/manager/share_option")
|
||||
async def set_share_option(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
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 get_openart_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
|
||||
openart_key = f.read().strip()
|
||||
return openart_key if openart_key else None
|
||||
except Exception:
|
||||
return None
|
||||
def is_matrix_org(homeserver):
|
||||
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
|
||||
|
||||
|
||||
def get_matrix_auth():
|
||||
@@ -94,7 +57,7 @@ def get_matrix_auth():
|
||||
with open(os.path.join(context.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,
|
||||
@@ -105,101 +68,12 @@ def get_matrix_auth():
|
||||
return None
|
||||
|
||||
|
||||
def get_comfyworkflows_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
|
||||
share_key = f.read()
|
||||
if not share_key.strip():
|
||||
return None
|
||||
return share_key
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def get_youml_settings():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
|
||||
youml_settings = f.read().strip()
|
||||
return youml_settings if youml_settings else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def set_youml_settings(settings):
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
|
||||
f.write(settings)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_openart_auth")
|
||||
async def api_get_openart_auth(request):
|
||||
# print("Getting stored Matrix credentials...")
|
||||
openart_key = get_openart_auth()
|
||||
if not openart_key:
|
||||
return web.Response(status=404)
|
||||
return web.json_response({"openart_key": openart_key})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/set_openart_auth")
|
||||
async def api_set_openart_auth(request):
|
||||
json_data = await request.json()
|
||||
openart_key = json_data['openart_key']
|
||||
with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
|
||||
f.write(openart_key)
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/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("/v2/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("/v2/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)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_comfyworkflows_auth")
|
||||
async def api_get_comfyworkflows_auth(request):
|
||||
# Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
|
||||
# in the same directory as the ComfyUI base folder
|
||||
# print("Getting stored Comfyworkflows.com auth...")
|
||||
comfyworkflows_auth = get_comfyworkflows_auth()
|
||||
if not comfyworkflows_auth:
|
||||
return web.Response(status=404)
|
||||
return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
|
||||
async def set_esheep_workflow_and_images(request):
|
||||
json_data = await request.json()
|
||||
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
|
||||
json.dump(json_data, file, indent=4)
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
|
||||
async def get_esheep_workflow_and_images(request):
|
||||
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
|
||||
data = json.load(file)
|
||||
return web.Response(status=200, text=json.dumps(data))
|
||||
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
@@ -211,42 +85,42 @@ async def get_matrix_dep_status(request):
|
||||
|
||||
|
||||
def set_matrix_auth(json_data):
|
||||
homeserver = json_data['homeserver']
|
||||
username = json_data['username']
|
||||
password = json_data['password']
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
|
||||
f.write("\n".join([homeserver, username, password]))
|
||||
|
||||
|
||||
def set_comfyworkflows_auth(comfyworkflows_sharekey):
|
||||
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
|
||||
f.write(comfyworkflows_sharekey)
|
||||
path = os.path.join(context.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):
|
||||
return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
|
||||
|
||||
|
||||
def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
|
||||
return comfyworkflows_sharekey.strip()
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/share")
|
||||
async def share_art(request):
|
||||
# get json data
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
matrix_auth = json_data['matrix_auth']
|
||||
comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
set_comfyworkflows_auth(comfyworkflows_sharekey)
|
||||
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']
|
||||
title = json_data['title']
|
||||
description = json_data['description']
|
||||
is_nsfw = json_data['is_nsfw']
|
||||
prompt = json_data['prompt']
|
||||
potential_outputs = json_data['potential_outputs']
|
||||
selected_output_index = json_data['selected_output_index']
|
||||
@@ -275,79 +149,20 @@ async def share_art(request):
|
||||
else:
|
||||
asset_filepath = os.path.join(output_dir, asset_filename)
|
||||
|
||||
# The filename and the subfolder come from the request: share only a file in that directory.
|
||||
# Like ComfyUI's /view, this follows a symlink that the user placed in the directory.
|
||||
output_dir = os.path.abspath(output_dir)
|
||||
asset_filepath = os.path.abspath(asset_filepath)
|
||||
try:
|
||||
is_inside = os.path.commonpath((output_dir, asset_filepath)) == output_dir
|
||||
except ValueError: # on Windows, a path on another drive
|
||||
is_inside = False
|
||||
if not is_inside:
|
||||
return web.json_response({"error": "The selected output is not in the output directory."}, content_type='application/json', status=400)
|
||||
|
||||
# get the mime type of the asset
|
||||
assetFileType = mimetypes.guess_type(asset_filepath)[0]
|
||||
|
||||
share_website_host = "UNKNOWN"
|
||||
if "comfyworkflows" in share_destinations:
|
||||
share_website_host = "https://comfyworkflows.com"
|
||||
share_endpoint = f"{share_website_host}/api"
|
||||
|
||||
# get presigned urls
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.post(
|
||||
f"{share_endpoint}/get_presigned_urls",
|
||||
json={
|
||||
"assetFileName": asset_filename,
|
||||
"assetFileType": assetFileType,
|
||||
"workflowJsonFileName": 'workflow.json',
|
||||
"workflowJsonFileType": 'application/json',
|
||||
},
|
||||
) as resp:
|
||||
assert resp.status == 200
|
||||
presigned_urls_json = await resp.json()
|
||||
assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
|
||||
assetFileKey = presigned_urls_json["assetFileKey"]
|
||||
workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
|
||||
workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
|
||||
|
||||
# upload asset
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
|
||||
assert resp.status == 200
|
||||
|
||||
# upload workflow json
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
|
||||
assert resp.status == 200
|
||||
|
||||
model_filenames = extract_model_file_names(prompt['workflow'])
|
||||
model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
|
||||
|
||||
models_info = {}
|
||||
for filename, filepath in model_file_paths.items():
|
||||
models_info[filename] = {
|
||||
"filename": filename,
|
||||
"sha256_checksum": compute_sha256_checksum(filepath),
|
||||
"relative_path": os.path.relpath(filepath, folder_paths.base_path),
|
||||
}
|
||||
|
||||
# make a POST request to /api/upload_workflow with form data key values
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
form = aiohttp.FormData()
|
||||
if comfyworkflows_sharekey:
|
||||
form.add_field("shareKey", comfyworkflows_sharekey)
|
||||
form.add_field("source", "comfyui_manager")
|
||||
form.add_field("assetFileKey", assetFileKey)
|
||||
form.add_field("assetFileType", assetFileType)
|
||||
form.add_field("workflowJsonFileKey", workflowJsonFileKey)
|
||||
form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
|
||||
form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
|
||||
form.add_field("shareWorkflowCredits", credits)
|
||||
form.add_field("shareWorkflowTitle", title)
|
||||
form.add_field("shareWorkflowDescription", description)
|
||||
form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
|
||||
form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
|
||||
form.add_field("modelsInfo", json.dumps(models_info))
|
||||
|
||||
async with session.post(
|
||||
f"{share_endpoint}/upload_workflow",
|
||||
data=form,
|
||||
) as resp:
|
||||
assert resp.status == 200
|
||||
upload_workflow_json = await resp.json()
|
||||
workflowId = upload_workflow_json["workflowId"]
|
||||
|
||||
# check if the user has provided Matrix credentials
|
||||
if matrix_nio_is_available and "matrix" in share_destinations:
|
||||
comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
|
||||
@@ -355,14 +170,10 @@ async def share_art(request):
|
||||
content_type = assetFileType
|
||||
|
||||
try:
|
||||
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'])
|
||||
@@ -370,6 +181,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)
|
||||
@@ -442,9 +255,6 @@ async def share_art(request):
|
||||
return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
|
||||
|
||||
return web.json_response({
|
||||
"comfyworkflows": {
|
||||
"url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
|
||||
},
|
||||
"matrix": {
|
||||
"success": None if "matrix" not in share_destinations else True
|
||||
}
|
||||
|
||||
@@ -124,7 +124,6 @@ def initialize_environment():
|
||||
|
||||
# Legacy database paths - kept for potential future use
|
||||
# local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
|
||||
# local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
|
||||
# local_db_custom_node_list = os.path.join(
|
||||
# manager_util.comfyui_manager_path, "custom-node-list.json"
|
||||
# )
|
||||
@@ -134,5 +133,3 @@ def initialize_environment():
|
||||
|
||||
print_comfyui_version()
|
||||
setup_environment()
|
||||
|
||||
core.check_invalid_nodes()
|
||||
|
||||
@@ -145,6 +145,7 @@ async def check_whitelist_for_model(item):
|
||||
x["save_path"] == item["save_path"]
|
||||
and x["base"] == item["base"]
|
||||
and x["filename"] == item["filename"]
|
||||
and x.get("url") == item.get("url")
|
||||
):
|
||||
return True
|
||||
|
||||
@@ -155,6 +156,7 @@ async def check_whitelist_for_model(item):
|
||||
x["save_path"] == item["save_path"]
|
||||
and x["base"] == item["base"]
|
||||
and x["filename"] == item["filename"]
|
||||
and x.get("url") == item.get("url")
|
||||
):
|
||||
return True
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from comfyui_manager.common.manager_security import (
|
||||
is_loopback,
|
||||
is_safe_path_target,
|
||||
get_safe_file_path,
|
||||
reject_simple_form_post,
|
||||
reject_non_json_post,
|
||||
)
|
||||
|
||||
# Re-export for backward compatibility
|
||||
@@ -13,7 +13,7 @@ __all__ = [
|
||||
'is_loopback',
|
||||
'is_safe_path_target',
|
||||
'get_safe_file_path',
|
||||
'reject_simple_form_post',
|
||||
'reject_non_json_post',
|
||||
'is_allowed_security_level',
|
||||
'get_risky_level',
|
||||
]
|
||||
@@ -53,7 +53,7 @@ async def get_risky_level(files, pip_packages):
|
||||
json_data2 = await core.get_data_by_mode(
|
||||
ManagerDatabaseSource.cache.value,
|
||||
"custom-node-list.json",
|
||||
channel_url="https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main",
|
||||
channel_url=core.DEFAULT_CHANNEL,
|
||||
)
|
||||
|
||||
all_urls = set()
|
||||
|
||||
@@ -13,8 +13,6 @@ This directory contains the JavaScript frontend implementation for ComfyUI-Manag
|
||||
## Sharing Components
|
||||
|
||||
- **comfyui-share-common.js**: Base functionality for workflow sharing features.
|
||||
- **comfyui-share-copus.js**: Integration with the ComfyUI Copus sharing platform.
|
||||
- **comfyui-share-openart.js**: Integration with the OpenArt sharing platform.
|
||||
- **comfyui-share-youml.js**: Integration with the YouML sharing platform.
|
||||
|
||||
## Utility Components
|
||||
|
||||
+122
-35
@@ -1,59 +1,146 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { sleep, customConfirm, customAlert } from "./common.js";
|
||||
import { sleep, customConfirm, customAlert, show_message, sanitizeHTML, generateUUID, md5 } from "./common.js";
|
||||
|
||||
// Enable a disabled node pack as the Enable button of the Custom Nodes Manager does: find the pack
|
||||
// in the node list, put it in the queue, and wait until the queue has finished it.
|
||||
// Returns { failure }, the reason, when the pack was not enabled, and otherwise { busy }: whether
|
||||
// the queue still holds other work.
|
||||
async function enableNodePack(target) {
|
||||
const list = await api.fetchApi(`/v2/customnode/getlist?mode=cache&skip_update=true`);
|
||||
if(list.status != 200) {
|
||||
return { failure: `Failed to get the custom node list (${list.status}).` };
|
||||
}
|
||||
|
||||
const { channel, node_packs } = await list.json();
|
||||
const key = Object.keys(node_packs).find((k) => {
|
||||
const pack = node_packs[k];
|
||||
return pack.state == 'disabled' && pack.files?.some((url) => target.files.includes(url));
|
||||
});
|
||||
if(key == undefined) {
|
||||
return { failure: 'It is not in the custom node list as a disabled node pack. Please enable it in the Custom Nodes Manager.' };
|
||||
}
|
||||
|
||||
// Behind other work the pack would be enabled at some later time, after the wait below has ended.
|
||||
const status = await api.fetchApi('/v2/manager/queue/status');
|
||||
if((await status.json()).is_processing) {
|
||||
return { failure: 'There are already tasks in progress. Please try again after it is completed.' };
|
||||
}
|
||||
|
||||
const batch_id = generateUUID();
|
||||
const ui_id = md5(key); // the id of this pack's row in the Custom Nodes Manager
|
||||
|
||||
// Once the batch is in the queue, 'all-done' without its report ends the wait: something else,
|
||||
// such as another tab, has emptied the queue.
|
||||
let listener, queued = false;
|
||||
const result = new Promise((resolve) => {
|
||||
listener = (event) => {
|
||||
const report = event.detail;
|
||||
if(report.status == 'batch-done' && report.batch_id == batch_id) {
|
||||
resolve(report);
|
||||
}
|
||||
else if(report.status == 'all-done' && queued) {
|
||||
resolve({ nodepack_result: {} });
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
// The queue may report the batch before the request below is answered.
|
||||
api.addEventListener("cm-queue-status", listener);
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
batch_id,
|
||||
install: [{
|
||||
...node_packs[key],
|
||||
channel,
|
||||
mode: 'cache',
|
||||
ui_id,
|
||||
skip_post_install: true
|
||||
}]
|
||||
})
|
||||
});
|
||||
|
||||
if(response.status != 200) {
|
||||
return { failure: `The request was refused (${response.status}). Please check the terminal log.` };
|
||||
}
|
||||
|
||||
const { failed } = await response.json();
|
||||
if(failed.length > 0) {
|
||||
return { failure: 'The request was refused. Please check the terminal log.' };
|
||||
}
|
||||
|
||||
// A report that does not reach the page would leave the listener in place, and the batch,
|
||||
// run at some later time, would then restart ComfyUI unasked.
|
||||
queued = true;
|
||||
const report = await Promise.race([result, sleep(60000)]);
|
||||
if(report == undefined) {
|
||||
return { failure: 'The queue did not report the result. Please check the node pack in the Custom Nodes Manager.' };
|
||||
}
|
||||
|
||||
const message = report.nodepack_result[ui_id] ?? 'The queue finished without a result for this node pack. Please check the node pack in the Custom Nodes Manager.';
|
||||
if(message != 'success') {
|
||||
return { failure: String(message) };
|
||||
}
|
||||
|
||||
return { busy: report.remaining_batch_count > 1 }; // the count includes this batch
|
||||
}
|
||||
finally {
|
||||
api.removeEventListener("cm-queue-status", listener);
|
||||
}
|
||||
}
|
||||
|
||||
async function tryInstallCustomNode(event) {
|
||||
let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
|
||||
msg += `The '${event.detail.sender}' extension requires the installation of the '${event.detail.target.title}' extension. `;
|
||||
const target = event.detail.target;
|
||||
|
||||
if(event.detail.target.installed == 'Disabled') {
|
||||
let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
|
||||
msg += `The '${event.detail.sender}' extension requires the installation of the '${target.title}' extension. `;
|
||||
|
||||
if(target.installed == 'Disabled') {
|
||||
msg += 'However, the extension is currently disabled. Would you like to enable it and reboot?'
|
||||
}
|
||||
else if(event.detail.target.installed == 'True') {
|
||||
msg += 'However, it seems that the extension is in an import-fail state or is not compatible with the current version. Please address this issue.';
|
||||
}
|
||||
else {
|
||||
msg += `Would you like to install it and reboot?`;
|
||||
msg += 'However, it seems that the extension is in an import-fail state or is not compatible with the current version. Please address this issue.';
|
||||
}
|
||||
|
||||
msg += `\n\nRequest message:\n${event.detail.msg}`;
|
||||
|
||||
if(event.detail.target.installed == 'True') {
|
||||
// The server sends this request only for a node pack that is installed: it is disabled, or it failed to load.
|
||||
if(target.installed != 'Disabled') {
|
||||
customAlert(msg);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await customConfirm(msg);
|
||||
if(res) {
|
||||
if(event.detail.target.installed == 'Disabled') {
|
||||
const response = await api.fetchApi(`/v2/customnode/toggle_active`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(event.detail.target)
|
||||
});
|
||||
}
|
||||
else {
|
||||
await sleep(300);
|
||||
app.ui.dialog.show(`Installing... '${event.detail.target.title}'`);
|
||||
const title = sanitizeHTML(String(target.title));
|
||||
|
||||
const response = await api.fetchApi(`/v2/customnode/install`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(event.detail.target)
|
||||
});
|
||||
await sleep(300);
|
||||
app.ui.dialog.show(`Enabling... '${title}'`);
|
||||
|
||||
if(response.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
return false;
|
||||
}
|
||||
else if(response.status == 400) {
|
||||
let msg = await res.text();
|
||||
show_message(msg);
|
||||
return false;
|
||||
}
|
||||
const { failure, busy } = await enableNodePack(target).catch((exception) => ({ failure: String(exception) }));
|
||||
if(failure != undefined) {
|
||||
show_message(`Failed to enable '${title}'.<BR><BR>${sanitizeHTML(failure)}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
let response = await api.fetchApi("/v2/manager/reboot", { method: 'POST' });
|
||||
if(response.status == 403) {
|
||||
// A restart would cut off the work that was queued behind the pack.
|
||||
if(busy) {
|
||||
show_message(`'${title}' is enabled.<BR><BR>Other tasks are still in progress. Please restart ComfyUI after they are completed.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
catch(exception) {
|
||||
// The server restarts without answering.
|
||||
}
|
||||
|
||||
if(response?.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
.cm-ui-overlay {
|
||||
z-index: 1000;
|
||||
background: rgb(0 0 0 / 50%);
|
||||
}
|
||||
|
||||
.cm-ui-dialog {
|
||||
max-width: calc(100vw - 2rem);
|
||||
max-height: calc(100vh - 2rem);
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 12px;
|
||||
background: var(--background, var(--comfy-menu-bg));
|
||||
color: var(--foreground, var(--fg-color));
|
||||
box-shadow: var(--shadow-lg, 0 8px 24px rgb(0 0 0 / 30%));
|
||||
}
|
||||
|
||||
.cm-ui-header {
|
||||
flex-shrink: 0;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.cm-ui-content {
|
||||
padding: 0 1rem 1rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.cm-ui-muted {
|
||||
color: var(--muted-foreground, var(--fg-color));
|
||||
}
|
||||
|
||||
:where(.cm-ui-button) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 6px;
|
||||
background: var(--secondary, var(--comfy-input-bg));
|
||||
color: var(--foreground, var(--input-text));
|
||||
font: inherit;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
:where(.cm-ui-input) {
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--border, var(--border-color));
|
||||
border-radius: 6px;
|
||||
background: var(--secondary, var(--comfy-input-bg));
|
||||
color: var(--foreground, var(--input-text));
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.cm-ui-button:not(:disabled):hover {
|
||||
filter: brightness(115%);
|
||||
}
|
||||
|
||||
.cm-ui-button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.cm-ui-button:focus-visible,
|
||||
.cm-ui-input:focus-visible {
|
||||
outline: 2px solid var(--ring, var(--input-text));
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.cm-ui-close {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.cm-ui-close:not(:disabled):hover {
|
||||
background: var(--accent, var(--comfy-input-bg));
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
import { $el } from "../../scripts/ui.js";
|
||||
import { loadCss } from "./common.js";
|
||||
|
||||
loadCss("./comfyui-gui-builder.css");
|
||||
|
||||
function normalizeContent(content) {
|
||||
const tmp = document.createElement('div');
|
||||
@@ -16,7 +19,7 @@ export function createSettingsCombo(label, content) {
|
||||
const settingItem = $el("div.setting-item", {}, [
|
||||
$el("div.flex.flex-row.items-center.gap-2",[
|
||||
$el("div.form-label.flex.grow.items-center", [
|
||||
$el("span.text-muted", { textContent: label },)
|
||||
$el("span.cm-ui-muted", { textContent: label },)
|
||||
]),
|
||||
$el("div.form-input.flex.justify-end",
|
||||
[content]
|
||||
@@ -28,51 +31,27 @@ export function createSettingsCombo(label, content) {
|
||||
}
|
||||
|
||||
export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
|
||||
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
|
||||
parent: document.body,
|
||||
style: {
|
||||
position: "fixed",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
left: "0px",
|
||||
top: "0px",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
pointerEvents: "auto",
|
||||
zIndex: "1000"
|
||||
},
|
||||
onclick: (e) => {
|
||||
if (e.target === dialog_mask) {
|
||||
owner.close();
|
||||
}
|
||||
}
|
||||
// data-pc-section="mask"
|
||||
});
|
||||
|
||||
const header_actions = $el("div.p-dialog-header-actions", {
|
||||
// [TODO]
|
||||
// data-pc-section="headeractions"
|
||||
}
|
||||
);
|
||||
const header_actions = $el("div.flex.items-center");
|
||||
|
||||
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
|
||||
$el("button.cm-ui-button.cm-ui-close", {
|
||||
parent: header_actions,
|
||||
type: "button",
|
||||
ariaLabel: "Close",
|
||||
onclick: () => owner.close(),
|
||||
// "data-pc-name": "pcclosebutton",
|
||||
// "data-p-disabled": "false",
|
||||
// "data-p-severity": "secondary",
|
||||
// "data-pc-group-section": "headericon",
|
||||
// "data-pc-extend": "button",
|
||||
// "data-pc-section": "root",
|
||||
// [FIXME] Not sure how to do most of the SVG using $el
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label"> </span><!---->'
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
|
||||
}
|
||||
);
|
||||
|
||||
const dialog_header = $el("div.p-dialog-header",
|
||||
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
|
||||
[
|
||||
$el("div", [
|
||||
$el("div",
|
||||
@@ -96,8 +75,8 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
]
|
||||
);
|
||||
|
||||
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
|
||||
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
|
||||
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
|
||||
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
|
||||
id: dialogId,
|
||||
parent: dialog_mask,
|
||||
style: {
|
||||
@@ -108,76 +87,35 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
|
||||
},
|
||||
role: 'dialog',
|
||||
ariaModal: 'true',
|
||||
// [TODO]
|
||||
// ariaLabbelledby: 'cm-title',
|
||||
// maximized: 'false',
|
||||
// data-pc-name: 'dialog',
|
||||
// data-pc-section: 'root',
|
||||
// data-pd-focustrap: 'true'
|
||||
},
|
||||
[ dialog_header, contentFrame ]
|
||||
);
|
||||
|
||||
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
|
||||
parent: manager_dialog,
|
||||
tabindex: "0",
|
||||
role: "presentation",
|
||||
ariaHidden: "true",
|
||||
"data-p-hidden-accessible": "true",
|
||||
"data-p-hidden-focusable": "true",
|
||||
"data-pc-section": "firstfocusableelement"
|
||||
});
|
||||
|
||||
return dialog_mask;
|
||||
}
|
||||
|
||||
export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner) {
|
||||
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
|
||||
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
|
||||
parent: document.body,
|
||||
style: {
|
||||
position: "fixed",
|
||||
height: "100%",
|
||||
width: "100%",
|
||||
left: "0px",
|
||||
top: "0px",
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
pointerEvents: "auto",
|
||||
zIndex: "1000"
|
||||
},
|
||||
onclick: (e) => {
|
||||
if (e.target === dialog_mask) {
|
||||
owner.close();
|
||||
}
|
||||
}
|
||||
// data-pc-section="mask"
|
||||
});
|
||||
|
||||
const header_actions = $el("div.p-dialog-header-actions", {
|
||||
// [TODO]
|
||||
// data-pc-section="headeractions"
|
||||
}
|
||||
);
|
||||
const header_actions = $el("div.flex.items-center");
|
||||
|
||||
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
|
||||
$el("button.cm-ui-button.cm-ui-close", {
|
||||
parent: header_actions,
|
||||
type: "button",
|
||||
ariaLabel: "Close",
|
||||
onclick: () => owner.close(),
|
||||
// "data-pc-name": "pcclosebutton",
|
||||
// "data-p-disabled": "false",
|
||||
// "data-p-severity": "secondary",
|
||||
// "data-pc-group-section": "headericon",
|
||||
// "data-pc-extend": "button",
|
||||
// "data-pc-section": "root",
|
||||
// [FIXME] Not sure how to do most of the SVG using $el
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label"> </span><!---->'
|
||||
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
|
||||
}
|
||||
);
|
||||
|
||||
const _customHeader = normalizeContent(customHeader);
|
||||
const dialog_header = $el("div.p-dialog-header",
|
||||
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
|
||||
[
|
||||
$el("div", [
|
||||
$el("div",
|
||||
@@ -191,8 +129,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
|
||||
]
|
||||
);
|
||||
|
||||
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
|
||||
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
|
||||
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
|
||||
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
|
||||
id: dialogId,
|
||||
parent: dialog_mask,
|
||||
style: {
|
||||
@@ -203,25 +141,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
|
||||
},
|
||||
role: 'dialog',
|
||||
ariaModal: 'true',
|
||||
// [TODO]
|
||||
// ariaLabbelledby: 'cm-title',
|
||||
// maximized: 'false',
|
||||
// data-pc-name: 'dialog',
|
||||
// data-pc-section: 'root',
|
||||
// data-pd-focustrap: 'true'
|
||||
},
|
||||
[ dialog_header, contentFrame ]
|
||||
);
|
||||
|
||||
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
|
||||
parent: manager_dialog,
|
||||
tabindex: "0",
|
||||
role: "presentation",
|
||||
ariaHidden: "true",
|
||||
"data-p-hidden-accessible": "true",
|
||||
"data-p-hidden-focusable": "true",
|
||||
"data-pc-section": "firstfocusableelement"
|
||||
});
|
||||
|
||||
return dialog_mask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,11 +6,9 @@ import {
|
||||
ShareDialog,
|
||||
ShareDialogChooser,
|
||||
getPotentialOutputsAndOutputNodes,
|
||||
showOpenArtShareDialog,
|
||||
showShareDialog,
|
||||
showYouMLShareDialog
|
||||
} from "./comfyui-share-common.js";
|
||||
import { OpenArtShareDialog } from "./comfyui-share-openart.js";
|
||||
import {
|
||||
free_models, install_pip, install_via_git_url, manager_instance,
|
||||
rebootAPI, setManagerInstance, show_message, customAlert, customPrompt,
|
||||
@@ -133,17 +131,6 @@ docStyle.innerHTML = `
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#alternatives-grid a {
|
||||
color: #5555FF;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#alternatives-grid a:hover {
|
||||
color: #7777FF;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.cm-notice-board {
|
||||
width: auto;
|
||||
height: 280px;
|
||||
@@ -234,8 +221,28 @@ 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 = [
|
||||
['none', 'None'],
|
||||
['youml', 'YouML'],
|
||||
['matrix', 'Matrix Server'],
|
||||
['all', 'All'],
|
||||
];
|
||||
|
||||
// The saved choice may be a share site that Manager no longer has
|
||||
function to_share_option(value) {
|
||||
return share_options.some(option => option[0] === value) ? value : 'all';
|
||||
}
|
||||
|
||||
const youml_gallery_url = "https://youml.com/?from=comfyui-share";
|
||||
|
||||
// The gallery opened last, unless Manager no longer has it
|
||||
function last_visited_gallery() {
|
||||
const url = localStorage.getItem("wg_last_visited");
|
||||
return url === youml_gallery_url ? url : null;
|
||||
}
|
||||
var batch_id = null;
|
||||
|
||||
|
||||
@@ -410,7 +417,7 @@ async function init_share_option() {
|
||||
api.fetchApi('/v2/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_option = data || 'all';
|
||||
share_option = to_share_option(data);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -477,6 +484,7 @@ async function updateComfyUI() {
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
}
|
||||
@@ -626,15 +634,6 @@ async function switchComfyUI() {
|
||||
}
|
||||
|
||||
showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
|
||||
if(selected_version == 'nightly') {
|
||||
update_policy_combo.value = 'nightly-comfyui';
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'nightly-comfyui'}) });
|
||||
}
|
||||
else {
|
||||
update_policy_combo.value = 'stable-comfyui';
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'stable-comfyui'}) });
|
||||
}
|
||||
|
||||
let response = await api.fetchApi('/v2/comfyui_manager/comfyui_switch_version', {
|
||||
method: 'POST',
|
||||
cache: "no-store",
|
||||
@@ -646,8 +645,16 @@ async function switchComfyUI() {
|
||||
}),
|
||||
});
|
||||
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('/v2/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) {
|
||||
customAlert('This action is not allowed with this security level configuration.');
|
||||
}
|
||||
else {
|
||||
customAlert('Failed to switch ComfyUI version.');
|
||||
}
|
||||
@@ -659,6 +666,11 @@ async function switchComfyUI() {
|
||||
}
|
||||
|
||||
async function onQueueStatus(event) {
|
||||
// The buttons exist once the Manager menu has been created; the queue can run before that.
|
||||
if(update_all_button == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isElectron = 'electronAPI' in window;
|
||||
|
||||
if(event.detail.status == 'in_progress') {
|
||||
@@ -694,7 +706,7 @@ async function onQueueStatus(event) {
|
||||
|
||||
let msg = "";
|
||||
|
||||
if(success_list.length == 0 && comfyui_state.startsWith('skip')) {
|
||||
if(success_list.length == 0 && (comfyui_state == null || comfyui_state.startsWith('skip'))) {
|
||||
if(failed_list.length == 0) {
|
||||
msg += "You are already up to date.";
|
||||
}
|
||||
@@ -706,7 +718,7 @@ async function onQueueStatus(event) {
|
||||
msg += "ComfyUI has been updated to latest nightly version.<BR><BR>";
|
||||
infoToast("ComfyUI has been updated to the latest nightly version.");
|
||||
}
|
||||
else if(comfyui_state.startsWith('success-stable')) {
|
||||
else if(comfyui_state?.startsWith('success-stable')) {
|
||||
const ver = comfyui_state.split("-").pop();
|
||||
msg += `ComfyUI has been updated to ${ver}.<BR><BR>`;
|
||||
infoToast(`ComfyUI has been updated to ${ver}`);
|
||||
@@ -782,6 +794,7 @@ async function updateAll(update_comfyui) {
|
||||
batch_id = generateUUID();
|
||||
|
||||
let batch = {};
|
||||
batch['batch_id'] = batch_id;
|
||||
if(update_comfyui) {
|
||||
update_all_button.innerText = "Updating ComfyUI...";
|
||||
batch['update_comfyui'] = true;
|
||||
@@ -791,6 +804,7 @@ async function updateAll(update_comfyui) {
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
}
|
||||
@@ -807,7 +821,7 @@ function restartOrStop() {
|
||||
rebootAPI();
|
||||
}
|
||||
else {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
}
|
||||
@@ -819,7 +833,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
const isElectron = 'electronAPI' in window;
|
||||
|
||||
update_comfyui_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update ComfyUI",
|
||||
style: {
|
||||
@@ -830,7 +844,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
});
|
||||
|
||||
switch_comfyui_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Switch ComfyUI",
|
||||
style: {
|
||||
@@ -841,7 +855,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
});
|
||||
|
||||
restart_stop_button =
|
||||
$el("button.p-button.p-component.cm-button-red", {
|
||||
$el("button.cm-ui-button.cm-button-red", {
|
||||
type: "button",
|
||||
textContent: "Restart",
|
||||
onclick: () => restartOrStop()
|
||||
@@ -849,7 +863,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
if(isElectron) {
|
||||
update_all_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update All Custom Nodes",
|
||||
onclick:
|
||||
@@ -858,7 +872,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
else {
|
||||
update_all_button =
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Update All",
|
||||
onclick:
|
||||
@@ -868,7 +882,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
const res =
|
||||
[
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Custom Nodes Manager",
|
||||
onclick:
|
||||
@@ -880,7 +894,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Install Missing Custom Nodes",
|
||||
onclick:
|
||||
@@ -892,7 +906,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Custom Nodes In Workflow",
|
||||
onclick:
|
||||
@@ -905,7 +919,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}),
|
||||
|
||||
$el("div", {}, []),
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Model Manager",
|
||||
onclick:
|
||||
@@ -917,7 +931,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
}),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
type: "button",
|
||||
textContent: "Install via Git URL",
|
||||
onclick: async () => {
|
||||
@@ -951,17 +965,20 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
this.datasrc_combo = document.createElement("select");
|
||||
this.datasrc_combo.setAttribute("title", "Configure where to retrieve node/model information. If set to 'local,' the channel is ignored, and if set to 'channel (remote),' it fetches the latest information each time the list is opened.");
|
||||
this.datasrc_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled ";
|
||||
this.datasrc_combo.className = "cm-menu-combo cm-ui-input ";
|
||||
this.datasrc_combo.appendChild($el('option', { value: 'cache', text: 'Channel (1day cache)' }, []));
|
||||
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('/v2/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) {
|
||||
api.fetchApi('/v2/manager/db_mode', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
db_mode_chosen = true;
|
||||
api.fetchApi('/v2/manager/db_mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
const dbRetrievalSetttingItem = createSettingsCombo("DB", this.datasrc_combo);
|
||||
@@ -969,7 +986,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
// channel
|
||||
let channel_combo = document.createElement("select");
|
||||
channel_combo.setAttribute("title", "Configure the channel for retrieving data from the Custom Node list (including missing nodes) or the Model list.");
|
||||
channel_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
channel_combo.className = "cm-menu-combo cm-ui-input";
|
||||
api.fetchApi('/v2/manager/channel_url_list')
|
||||
.then(response => response.json())
|
||||
.then(async data => {
|
||||
@@ -983,7 +1000,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}
|
||||
|
||||
channel_combo.addEventListener('change', function (event) {
|
||||
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
channel_combo.value = data.selected;
|
||||
@@ -999,31 +1016,26 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
// share
|
||||
let share_combo = document.createElement("select");
|
||||
share_combo.setAttribute("title", "Hide the share button in the main menu or set the default action upon clicking it. Additionally, configure the default share site when sharing via the context menu's share button.");
|
||||
share_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
const share_options = [
|
||||
['none', 'None'],
|
||||
['openart', 'OpenArt AI'],
|
||||
['youml', 'YouML'],
|
||||
['matrix', 'Matrix Server'],
|
||||
['comfyworkflows', 'ComfyWorkflows'],
|
||||
['copus', 'Copus'],
|
||||
['all', 'All'],
|
||||
];
|
||||
share_combo.className = "cm-menu-combo cm-ui-input";
|
||||
for (const option of share_options) {
|
||||
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
|
||||
}
|
||||
|
||||
let share_option_chosen = false;
|
||||
api.fetchApi('/v2/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_combo.value = data || 'all';
|
||||
share_option = data || 'all';
|
||||
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(`/v2/manager/share_option?value=${value}`);
|
||||
api.fetchApi('/v2/manager/share_option', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
const shareButton = document.getElementById("shareButton");
|
||||
if (value === 'none') {
|
||||
shareButton.style.display = "none";
|
||||
@@ -1037,17 +1049,19 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
update_policy_combo = document.createElement("select");
|
||||
|
||||
update_policy_combo.setAttribute("title", "Sets the policy to be applied when performing an update.");
|
||||
update_policy_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
|
||||
update_policy_combo.className = "cm-menu-combo cm-ui-input";
|
||||
update_policy_combo.appendChild($el('option', { value: 'stable-comfyui', text: 'ComfyUI Stable Version' }, []));
|
||||
update_policy_combo.appendChild($el('option', { value: 'nightly-comfyui', text: 'ComfyUI Nightly Version' }, []));
|
||||
api.fetchApi('/v2/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) {
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
|
||||
update_policy_chosen = true;
|
||||
api.fetchApi('/v2/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
|
||||
});
|
||||
|
||||
const updateSetttingItem = createSettingsCombo("Update", update_policy_combo);
|
||||
@@ -1063,7 +1077,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
//[TODO] replace mt-2 with wrapper div with flex column gap
|
||||
$el("filedset.cm-experimental.mt-auto", {}, [
|
||||
$el("legend.cm-experimental-legend", {}, ["EXPERIMENTAL"]),
|
||||
$el("button.p-button.p-component.cm-button.cm-experimental-button", {
|
||||
$el("button.cm-ui-button.cm-button.cm-experimental-button", {
|
||||
type: "button",
|
||||
textContent: "Snapshot Manager",
|
||||
onclick:
|
||||
@@ -1073,7 +1087,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
SnapshotManager.instance.show();
|
||||
}
|
||||
}),
|
||||
$el("button.p-button.p-component.cm-button.cm-experimental-button.mt-2", {
|
||||
$el("button.cm-ui-button.cm-button.cm-experimental-button.mt-2", {
|
||||
type: "button",
|
||||
textContent: "Install PIP packages",
|
||||
onclick:
|
||||
@@ -1091,7 +1105,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
|
||||
createControlsRight() {
|
||||
const elts = [
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'cm-manual-button',
|
||||
type: "button",
|
||||
textContent: "Community Manual",
|
||||
@@ -1142,14 +1156,14 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
})
|
||||
]),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'workflowgallery-button',
|
||||
type: "button",
|
||||
style: {
|
||||
// ...(localStorage.getItem("wg_last_visited") ? {height: '50px'} : {})
|
||||
},
|
||||
onclick: (e) => {
|
||||
const last_visited_site = localStorage.getItem("wg_last_visited")
|
||||
const last_visited_site = last_visited_gallery();
|
||||
if (!!last_visited_site) {
|
||||
window.open(last_visited_site, last_visited_site);
|
||||
} else {
|
||||
@@ -1169,7 +1183,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
}, [
|
||||
$el("p", {
|
||||
id: 'workflowgallery-button-last-visited-label',
|
||||
textContent: `(${localStorage.getItem("wg_last_visited") ? localStorage.getItem("wg_last_visited").split('/')[2] : 'none selected'})`,
|
||||
textContent: `(${last_visited_gallery()?.split('/')[2] ?? 'none selected'})`,
|
||||
style: {
|
||||
'text-align': 'center',
|
||||
'color': 'var(--input-text)',
|
||||
@@ -1180,12 +1194,12 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
})
|
||||
]),
|
||||
$el("div.pysssss-workflow-arrow-2", {
|
||||
id: `comfyworkflows-button-arrow`,
|
||||
id: `workflowgallery-button-arrow`,
|
||||
onclick: this.handleWorkflowGalleryButtonClick
|
||||
})
|
||||
]),
|
||||
|
||||
$el("button.p-button.p-component.cm-button", {
|
||||
$el("button.cm-ui-button.cm-button", {
|
||||
id: 'cm-nodeinfo-button',
|
||||
type: "button",
|
||||
textContent: "Nodes Info",
|
||||
@@ -1259,11 +1273,8 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
{
|
||||
title: "Share your art",
|
||||
callback: () => {
|
||||
if (share_option === 'openart') {
|
||||
showOpenArtShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
|
||||
showShareDialog(share_option);
|
||||
if (share_option === 'matrix') {
|
||||
showShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'youml') {
|
||||
showYouMLShareDialog();
|
||||
@@ -1276,49 +1287,12 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
ShareDialogChooser.instance.show();
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Open 'openart.ai'",
|
||||
callback: () => {
|
||||
const url = "https://openart.ai/workflows/dev";
|
||||
localStorage.setItem("wg_last_visited", url);
|
||||
window.open(url, url);
|
||||
modifyButtonStyle(url);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Open 'youml.com'",
|
||||
callback: () => {
|
||||
const url = "https://youml.com/?from=comfyui-share";
|
||||
localStorage.setItem("wg_last_visited", url);
|
||||
window.open(url, url);
|
||||
modifyButtonStyle(url);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Open 'comfyworkflows.com'",
|
||||
callback: () => {
|
||||
const url = "https://comfyworkflows.com/";
|
||||
localStorage.setItem("wg_last_visited", url);
|
||||
window.open(url, url);
|
||||
modifyButtonStyle(url);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Open 'esheep'",
|
||||
callback: () => {
|
||||
const url = "https://www.esheep.com";
|
||||
localStorage.setItem("wg_last_visited", url);
|
||||
window.open(url, url);
|
||||
modifyButtonStyle(url);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "Open 'Copus.io'",
|
||||
callback: () => {
|
||||
const url = "https://www.copus.io";
|
||||
localStorage.setItem("wg_last_visited", url);
|
||||
window.open(url, url);
|
||||
modifyButtonStyle(url);
|
||||
localStorage.setItem("wg_last_visited", youml_gallery_url);
|
||||
window.open(youml_gallery_url, youml_gallery_url);
|
||||
modifyButtonStyle(youml_gallery_url);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1450,11 +1424,8 @@ app.registerExtension({
|
||||
new(await import("../../scripts/ui/components/button.js")).ComfyButton({
|
||||
icon: "share",
|
||||
action: () => {
|
||||
if (share_option === 'openart') {
|
||||
showOpenArtShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
|
||||
showShareDialog(share_option);
|
||||
if (share_option === 'matrix') {
|
||||
showShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'youml') {
|
||||
showYouMLShareDialog();
|
||||
@@ -1488,11 +1459,8 @@ app.registerExtension({
|
||||
shareButton.id = "shareButton";
|
||||
shareButton.textContent = "Share";
|
||||
shareButton.onclick = () => {
|
||||
if (share_option === 'openart') {
|
||||
showOpenArtShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
|
||||
showShareDialog(share_option);
|
||||
if (share_option === 'matrix') {
|
||||
showShareDialog();
|
||||
return;
|
||||
} else if (share_option === 'youml') {
|
||||
showYouMLShareDialog();
|
||||
@@ -1546,13 +1514,6 @@ app.registerExtension({
|
||||
const shareButton = document.getElementById("shareButton");
|
||||
if (shareButton) {
|
||||
const currentNode = this;
|
||||
if (!OpenArtShareDialog.instance) {
|
||||
OpenArtShareDialog.instance = new OpenArtShareDialog();
|
||||
}
|
||||
OpenArtShareDialog.instance.selectedNodeId = currentNode.id;
|
||||
if (!ShareDialog.instance) {
|
||||
ShareDialog.instance = new ShareDialog(share_option);
|
||||
}
|
||||
ShareDialog.instance.selectedNodeId = currentNode.id;
|
||||
shareButton.click();
|
||||
}
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { $el, ComfyDialog } from "../../scripts/ui.js";
|
||||
import { CopusShareDialog } from "./comfyui-share-copus.js";
|
||||
import { OpenArtShareDialog } from "./comfyui-share-openart.js";
|
||||
import { YouMLShareDialog } from "./comfyui-share-youml.js";
|
||||
import { customAlert, sanitizeHTML, sanitizeUrl } from "./common.js";
|
||||
import { customAlert } from "./common.js";
|
||||
|
||||
export const SUPPORTED_OUTPUT_NODE_TYPES = [
|
||||
"PreviewImage",
|
||||
@@ -166,61 +164,6 @@ export function parseURLPath(urlPath) {
|
||||
}
|
||||
|
||||
|
||||
export const shareToEsheep= () => {
|
||||
app.graphToPrompt()
|
||||
.then(prompt => {
|
||||
const nodes = app.graph._nodes
|
||||
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
|
||||
const workflow = prompt['workflow']
|
||||
api.fetchApi(`/v2/manager/set_esheep_workflow_and_images`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
workflow: workflow,
|
||||
images: potential_outputs
|
||||
})
|
||||
}).then(response => {
|
||||
var domain = window.location.hostname;
|
||||
var port = window.location.port;
|
||||
port = port || (window.location.protocol === 'http:' ? '80' : window.location.protocol === 'https:' ? '443' : '');
|
||||
var full_domin = domain + ':' + port
|
||||
window.open('https://www.esheep.com/app/workflow_upload?from_local='+ full_domin, '_blank');
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
export const showCopusShareDialog = () => {
|
||||
if (!CopusShareDialog.instance) {
|
||||
CopusShareDialog.instance = new CopusShareDialog();
|
||||
}
|
||||
|
||||
return app.graphToPrompt()
|
||||
.then(prompt => {
|
||||
return app.graph._nodes;
|
||||
})
|
||||
.then(nodes => {
|
||||
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
|
||||
CopusShareDialog.instance.show({ potential_outputs, potential_output_nodes});
|
||||
})
|
||||
}
|
||||
|
||||
export const showOpenArtShareDialog = () => {
|
||||
if (!OpenArtShareDialog.instance) {
|
||||
OpenArtShareDialog.instance = new OpenArtShareDialog();
|
||||
}
|
||||
|
||||
return app.graphToPrompt()
|
||||
.then(prompt => {
|
||||
// console.log({ prompt })
|
||||
return app.graph._nodes;
|
||||
})
|
||||
.then(nodes => {
|
||||
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
|
||||
OpenArtShareDialog.instance.show({ potential_outputs, potential_output_nodes});
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export const showYouMLShareDialog = () => {
|
||||
if (!YouMLShareDialog.instance) {
|
||||
YouMLShareDialog.instance = new YouMLShareDialog();
|
||||
@@ -237,9 +180,9 @@ export const showYouMLShareDialog = () => {
|
||||
}
|
||||
|
||||
|
||||
export const showShareDialog = async (share_option) => {
|
||||
export const showShareDialog = async () => {
|
||||
if (!ShareDialog.instance) {
|
||||
ShareDialog.instance = new ShareDialog(share_option);
|
||||
ShareDialog.instance = new ShareDialog();
|
||||
}
|
||||
return app.graphToPrompt()
|
||||
.then(prompt => {
|
||||
@@ -259,7 +202,7 @@ export const showShareDialog = async (share_option) => {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
ShareDialog.instance.show({ potential_outputs, potential_output_nodes, share_option });
|
||||
ShareDialog.instance.show({ potential_outputs, potential_output_nodes });
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -282,17 +225,6 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
createButtons() {
|
||||
const buttons = [
|
||||
{
|
||||
key: "openart",
|
||||
textContent: "OpenArt AI",
|
||||
website: "https://openart.ai/workflows/",
|
||||
description: "Share ComfyUI workflows and art on OpenArt.ai",
|
||||
onclick: () => {
|
||||
showOpenArtShareDialog();
|
||||
this.close();
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "youml",
|
||||
textContent: "YouML",
|
||||
website: "https://youml.com",
|
||||
description: "Share your workflow or transform it into an interactive app on YouML.com",
|
||||
@@ -302,47 +234,15 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "matrix",
|
||||
textContent: "Matrix Server",
|
||||
website: "https://app.element.io/#/room/%23comfyui_space%3Amatrix.org",
|
||||
description: "Share your art on the official ComfyUI matrix server",
|
||||
onclick: async () => {
|
||||
showShareDialog('matrix').then((suc) => {
|
||||
showShareDialog().then((suc) => {
|
||||
suc && this.close();
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "comfyworkflows",
|
||||
textContent: "ComfyWorkflows",
|
||||
website: "https://comfyworkflows.com",
|
||||
description: "Share & browse thousands of ComfyUI workflows and art 🎨<br/><br/><a style='color:var(--input-text);' href='https://comfyworkflows.com' target='_blank'>ComfyWorkflows.com</a>",
|
||||
onclick: () => {
|
||||
showShareDialog('comfyworkflows').then((suc) => {
|
||||
suc && this.close();
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "esheep",
|
||||
textContent: "eSheep",
|
||||
website: "https://www.esheep.com",
|
||||
description: "Share & download thousands of ComfyUI workflows on <a style='color:var(--input-text);' href='https://www.esheep.com' target='_blank'>esheep.com</a>",
|
||||
onclick: () => {
|
||||
shareToEsheep();
|
||||
this.close();
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "Copus",
|
||||
textContent: "Copus",
|
||||
website: "https://www.copus.io",
|
||||
description: "🔴 Earn simple. Get paid from your ComfyUI workflows—no revenue sharing. Ever.",
|
||||
onclick: () => {
|
||||
showCopusShareDialog();
|
||||
this.close();
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
function createShareButtonsWithDescriptions() {
|
||||
@@ -357,8 +257,7 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
});
|
||||
|
||||
buttons.forEach(b => {
|
||||
const button = $el("button",
|
||||
{
|
||||
const button = $el("button", {
|
||||
type: "button",
|
||||
textContent: b.textContent,
|
||||
onclick: b.onclick,
|
||||
@@ -371,14 +270,8 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
'padding': '5px 5px',
|
||||
'margin-bottom': '5px',
|
||||
'transition': 'background-color 0.3s',
|
||||
'position':'relative'
|
||||
}
|
||||
},
|
||||
[
|
||||
$el("span", { style: {
|
||||
} }),
|
||||
]
|
||||
);
|
||||
});
|
||||
button.addEventListener('mouseover', () => {
|
||||
button.style.backgroundColor = '#007BFF'; // Change color on hover
|
||||
});
|
||||
@@ -387,7 +280,7 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
});
|
||||
|
||||
const description = $el("p", {
|
||||
innerHTML: b.description,
|
||||
textContent: b.description,
|
||||
style: {
|
||||
'text-align': 'left',
|
||||
color: 'var(--input-text)',
|
||||
@@ -396,28 +289,6 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
},
|
||||
});
|
||||
|
||||
const copus_ui =$el("div", { style: {
|
||||
'position': 'absolute',
|
||||
'height': '100%',
|
||||
'left': '-25px',
|
||||
'top': '-26px',
|
||||
'width': '100%',
|
||||
'z-index':'-1',
|
||||
'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
|
||||
'background-repeat': 'no-repeat',
|
||||
} });
|
||||
const copus_ui_bottom =$el("div", { style: {
|
||||
'position': 'absolute',
|
||||
'height': '100%',
|
||||
'left': '25px',
|
||||
'bottom': '-26px',
|
||||
'width': '100%',
|
||||
'transform':'scale(-1, -1)',
|
||||
'z-index':'-1',
|
||||
'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
|
||||
'background-repeat': 'no-repeat',
|
||||
} });
|
||||
|
||||
const websiteLink = $el("a", {
|
||||
textContent: "🌐 Website",
|
||||
href: b.website,
|
||||
@@ -455,17 +326,8 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
'border': '1px solid #ddd',
|
||||
'border-radius': '5px',
|
||||
'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
|
||||
'position':'relative'
|
||||
}
|
||||
}, [buttonLinkContainer, description
|
||||
,
|
||||
b.key ==='Copus' ?
|
||||
copus_ui
|
||||
:'',
|
||||
b.key ==='Copus' ?
|
||||
copus_ui_bottom
|
||||
:'',
|
||||
]);
|
||||
}, [buttonLinkContainer, description]);
|
||||
|
||||
container.appendChild(column);
|
||||
});
|
||||
@@ -518,12 +380,10 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
}
|
||||
export class ShareDialog extends ComfyDialog {
|
||||
static instance = null;
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
static cw_sharekey = "";
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
|
||||
constructor(share_option) {
|
||||
constructor() {
|
||||
super();
|
||||
this.share_option = share_option;
|
||||
this.element = $el("div.comfy-modal", {
|
||||
parent: document.body, style: {
|
||||
'overflow-y': "auto",
|
||||
@@ -541,16 +401,9 @@ export class ShareDialog extends ComfyDialog {
|
||||
id: "selectOutputImages",
|
||||
}, []);
|
||||
|
||||
this.is_nsfw_checkbox = $el("input", { type: 'checkbox', id: "is_nsfw" }, [])
|
||||
const is_nsfw_checkbox_text = $el("label", {
|
||||
}, [" Is this NSFW?"])
|
||||
this.is_nsfw_checkbox.style.color = "var(--fg-color)";
|
||||
this.is_nsfw_checkbox.checked = false;
|
||||
|
||||
this.matrix_destination_checkbox = $el("input", { type: 'checkbox', id: "matrix_destination" }, [])
|
||||
const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
|
||||
this.matrix_destination_checkbox.style.color = "var(--fg-color)";
|
||||
this.matrix_destination_checkbox.checked = this.share_option === 'matrix'; //true;
|
||||
|
||||
try {
|
||||
api.fetchApi(`/v2/manager/get_matrix_dep_status`)
|
||||
@@ -566,17 +419,9 @@ export class ShareDialog extends ComfyDialog {
|
||||
.catch(error => {});
|
||||
} catch (error) {}
|
||||
|
||||
this.comfyworkflows_destination_checkbox = $el("input", { type: 'checkbox', id: "comfyworkflows_destination" }, [])
|
||||
const comfyworkflows_destination_checkbox_text = $el("label", {}, [" ComfyWorkflows.com"])
|
||||
this.comfyworkflows_destination_checkbox.style.color = "var(--fg-color)";
|
||||
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
|
||||
|
||||
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.cw_sharekey_input = $el("input", { type: 'text', placeholder: "Share key (found on your profile page)", value: ShareDialog.cw_sharekey || '' }, []);
|
||||
this.cw_sharekey_input.style.width = "100%";
|
||||
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password" }, []);
|
||||
|
||||
this.credits_input = $el("input", {
|
||||
type: "text",
|
||||
@@ -626,8 +471,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
textContent: "Close",
|
||||
onclick: () => {
|
||||
// Reset state
|
||||
this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
|
||||
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
|
||||
this.share_button.textContent = "Share";
|
||||
this.share_button.style.display = "inline-block";
|
||||
this.final_message.innerHTML = "";
|
||||
@@ -635,7 +478,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
this.credits_input.value = "";
|
||||
this.title_input.value = "";
|
||||
this.description_input.value = "";
|
||||
this.is_nsfw_checkbox.checked = false;
|
||||
this.selectedOutputIndex = 0;
|
||||
|
||||
// hide the final message
|
||||
@@ -713,28 +555,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
]),
|
||||
|
||||
]),
|
||||
$el("details", {
|
||||
style: {
|
||||
border: "1px solid #999",
|
||||
marginTop: "10px",
|
||||
padding: "5px",
|
||||
borderRadius: "5px",
|
||||
backgroundColor: "#222"
|
||||
},
|
||||
}, [
|
||||
$el("summary", {
|
||||
style: {
|
||||
color: "white",
|
||||
cursor: "pointer",
|
||||
}
|
||||
}, [`Comfyworkflows.com account`]),
|
||||
$el("h4", {
|
||||
textContent: "Share key (found on your profile page)",
|
||||
}, []),
|
||||
$el("p", { size: 3, color: "white" }, ["If provided, your art will be saved to your account. Otherwise, it will be shared anonymously."]),
|
||||
this.cw_sharekey_input,
|
||||
]),
|
||||
|
||||
$el("div", {}, [
|
||||
$el("p", {
|
||||
size: 3, color: "white", style: {
|
||||
@@ -743,9 +563,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
}, [`Select where to share your art:`]),
|
||||
this.matrix_destination_checkbox,
|
||||
matrix_destination_checkbox_text,
|
||||
$el("br", {}, []),
|
||||
this.comfyworkflows_destination_checkbox,
|
||||
comfyworkflows_destination_checkbox_text,
|
||||
]),
|
||||
|
||||
$el("h4", {
|
||||
@@ -779,9 +596,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
}
|
||||
}, []),
|
||||
this.description_input,
|
||||
$el("br", {}, []),
|
||||
|
||||
$el("div", {}, [this.is_nsfw_checkbox, is_nsfw_checkbox_text]),
|
||||
// $el("br", {}, []),
|
||||
|
||||
// this.final_message,
|
||||
@@ -798,8 +612,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
textContent: "Close",
|
||||
onclick: () => {
|
||||
// Reset state
|
||||
this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
|
||||
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
|
||||
this.share_button.textContent = "Share";
|
||||
this.share_button.style.display = "inline-block";
|
||||
this.final_message.innerHTML = "";
|
||||
@@ -807,7 +619,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
this.credits_input.value = "";
|
||||
this.title_input.value = "";
|
||||
this.description_input.value = "";
|
||||
this.is_nsfw_checkbox.checked = false;
|
||||
this.selectedOutputIndex = 0;
|
||||
|
||||
// hide the final message
|
||||
@@ -823,33 +634,15 @@ export class ShareDialog extends ComfyDialog {
|
||||
]),
|
||||
]);
|
||||
|
||||
// get the user's existing matrix auth and share key
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
// get the user's existing matrix auth
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
|
||||
try {
|
||||
api.fetchApi(`/v2/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;
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
});
|
||||
} catch (error) {
|
||||
// console.log(error);
|
||||
}
|
||||
|
||||
// get the user's existing comfyworkflows share key
|
||||
ShareDialog.cw_sharekey = "";
|
||||
try {
|
||||
// console.log("Fetching comfyworkflows share key")
|
||||
api.fetchApi(`/v2/manager/get_comfyworkflows_auth`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
ShareDialog.cw_sharekey = data.comfyworkflows_sharekey;
|
||||
this.cw_sharekey_input.value = ShareDialog.cw_sharekey;
|
||||
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
@@ -868,23 +661,17 @@ export class ShareDialog extends ComfyDialog {
|
||||
if (this.matrix_destination_checkbox.checked) {
|
||||
destinations.push("matrix");
|
||||
}
|
||||
if (this.comfyworkflows_destination_checkbox.checked) {
|
||||
destinations.push("comfyworkflows");
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
if (destinations.includes("comfyworkflows") && !this.cw_sharekey_input.value && false) { //!confirm("You have NOT set your ComfyWorkflows.com share key. Your art will NOT be connected to your account (it will be shared anonymously). Continue?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
|
||||
|
||||
// console.log({ potential_outputs, potential_output_nodes })
|
||||
@@ -914,14 +701,10 @@ export class ShareDialog extends ComfyDialog {
|
||||
username: this.matrix_username_input.value,
|
||||
password: this.matrix_password_input.value,
|
||||
},
|
||||
cw_auth: {
|
||||
cw_sharekey: this.cw_sharekey_input.value,
|
||||
},
|
||||
share_destinations: destinations,
|
||||
credits: this.credits_input.value,
|
||||
title: this.title_input.value,
|
||||
description: this.description_input.value,
|
||||
is_nsfw: this.is_nsfw_checkbox.checked,
|
||||
prompt,
|
||||
potential_outputs,
|
||||
selected_output_index: this.selectedOutputIndex,
|
||||
@@ -950,16 +733,9 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
const response_json = await response.json();
|
||||
|
||||
if (response_json.comfyworkflows.url) {
|
||||
const sharedUrl = sanitizeHTML(sanitizeUrl(response_json.comfyworkflows.url));
|
||||
this.final_message.innerHTML = "Your art has been shared: <a href='" + sharedUrl + "' target='_blank' rel='noopener noreferrer'>" + sharedUrl + "</a>";
|
||||
if (response_json.matrix.success) {
|
||||
this.final_message.innerHTML += "<br>Your art has been shared in the ComfyUI Matrix server's #share channel!";
|
||||
}
|
||||
} else {
|
||||
if (response_json.matrix.success) {
|
||||
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
|
||||
}
|
||||
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";
|
||||
@@ -992,7 +768,7 @@ export class ShareDialog extends ComfyDialog {
|
||||
return res;
|
||||
}
|
||||
|
||||
show({potential_outputs, potential_output_nodes, share_option}) {
|
||||
show({potential_outputs, potential_output_nodes}) {
|
||||
// Sort `potential_output_nodes` by node ID to make the order always
|
||||
// consistent, but we should also keep `potential_outputs` in the same
|
||||
// order as `potential_output_nodes`.
|
||||
@@ -1104,14 +880,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
// this.radio_buttons.appendChild(subheader);
|
||||
this.radio_buttons.appendChild(new_radio_buttons);
|
||||
this.element.style.display = "block";
|
||||
|
||||
share_option = share_option || this.share_option;
|
||||
if (share_option === 'comfyworkflows') {
|
||||
this.matrix_destination_checkbox.checked = false;
|
||||
this.comfyworkflows_destination_checkbox.checked = true;
|
||||
} else {
|
||||
this.matrix_destination_checkbox.checked = true;
|
||||
this.comfyworkflows_destination_checkbox.checked = false;
|
||||
}
|
||||
this.matrix_destination_checkbox.checked = true;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,746 +0,0 @@
|
||||
import {app} from "../../scripts/app.js";
|
||||
import {api} from "../../scripts/api.js";
|
||||
import {ComfyDialog, $el} from "../../scripts/ui.js";
|
||||
import { customAlert, sanitizeHTML, sanitizeUrl } from "./common.js";
|
||||
|
||||
const LOCAL_STORAGE_KEY = "openart_comfy_workflow_key";
|
||||
const DEFAULT_HOMEPAGE_URL = "https://openart.ai/workflows/dev?developer=true";
|
||||
//const DEFAULT_HOMEPAGE_URL = "http://localhost:8080/workflows/dev?developer=true";
|
||||
|
||||
const API_ENDPOINT = "https://openart.ai/api";
|
||||
//const API_ENDPOINT = "http://localhost:8080/api";
|
||||
|
||||
const style = `
|
||||
.openart-share-dialog a {
|
||||
color: #f8f8f8;
|
||||
}
|
||||
.openart-share-dialog a:hover {
|
||||
color: #007bff;
|
||||
}
|
||||
.output_label {
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
.output_label:hover {
|
||||
border: 5px solid #59E8C6;
|
||||
}
|
||||
.output_label.checked {
|
||||
border: 5px solid #59E8C6;
|
||||
}
|
||||
`;
|
||||
|
||||
// Shared component styles
|
||||
const sectionStyle = {
|
||||
marginBottom: 0,
|
||||
padding: 0,
|
||||
borderRadius: "8px",
|
||||
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
justifyContent: "center",
|
||||
};
|
||||
|
||||
export class OpenArtShareDialog extends ComfyDialog {
|
||||
static instance = null;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
$el("style", {
|
||||
textContent: style,
|
||||
parent: document.head,
|
||||
});
|
||||
this.element = $el(
|
||||
"div.comfy-modal.openart-share-dialog",
|
||||
{
|
||||
parent: document.body,
|
||||
style: {
|
||||
"overflow-y": "auto",
|
||||
},
|
||||
},
|
||||
[$el("div.comfy-modal-content", {}, [...this.createButtons()])]
|
||||
);
|
||||
this.selectedOutputIndex = 0;
|
||||
this.selectedNodeId = null;
|
||||
this.uploadedImages = [];
|
||||
this.selectedFile = null;
|
||||
}
|
||||
|
||||
async readKey() {
|
||||
let key = ""
|
||||
try {
|
||||
key = await api.fetchApi(`/v2/manager/get_openart_auth`)
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
return data.openart_key;
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
});
|
||||
} catch (error) {
|
||||
// console.log(error);
|
||||
}
|
||||
return key || "";
|
||||
}
|
||||
|
||||
async saveKey(value) {
|
||||
await api.fetchApi(`/v2/manager/set_openart_auth`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
openart_key: value
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
createButtons() {
|
||||
const inputStyle = {
|
||||
display: "block",
|
||||
minWidth: "500px",
|
||||
width: "100%",
|
||||
padding: "10px",
|
||||
margin: "10px 0",
|
||||
borderRadius: "4px",
|
||||
border: "1px solid #ddd",
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
|
||||
const hyperLinkStyle = {
|
||||
display: "block",
|
||||
marginBottom: "15px",
|
||||
fontWeight: "bold",
|
||||
fontSize: "14px",
|
||||
};
|
||||
|
||||
const labelStyle = {
|
||||
color: "#f8f8f8",
|
||||
display: "block",
|
||||
margin: "10px 0 0 0",
|
||||
fontWeight: "bold",
|
||||
textDecoration: "none",
|
||||
};
|
||||
|
||||
const buttonStyle = {
|
||||
padding: "10px 80px",
|
||||
margin: "10px 5px",
|
||||
borderRadius: "4px",
|
||||
border: "none",
|
||||
cursor: "pointer",
|
||||
color: "#fff",
|
||||
backgroundColor: "#007bff",
|
||||
};
|
||||
|
||||
// upload images input
|
||||
this.uploadImagesInput = $el("input", {
|
||||
type: "file",
|
||||
multiple: false,
|
||||
style: inputStyle,
|
||||
accept: "image/*",
|
||||
});
|
||||
|
||||
this.uploadImagesInput.addEventListener("change", async (e) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) {
|
||||
this.previewImage.src = "";
|
||||
this.previewImage.style.display = "none";
|
||||
return;
|
||||
}
|
||||
const reader = new FileReader();
|
||||
reader.onload = async (e) => {
|
||||
const imgData = e.target.result;
|
||||
this.previewImage.src = imgData;
|
||||
this.previewImage.style.display = "block";
|
||||
this.selectedFile = null
|
||||
// Once user uploads an image, we uncheck all radio buttons
|
||||
this.radioButtons.forEach((ele) => {
|
||||
ele.checked = false;
|
||||
ele.parentElement.classList.remove("checked");
|
||||
});
|
||||
|
||||
// Add the opacity style toggle here to indicate that they only need
|
||||
// to upload one image or choose one from the outputs.
|
||||
this.outputsSection.style.opacity = 0.35;
|
||||
this.uploadImagesInput.style.opacity = 1;
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
// preview image
|
||||
this.previewImage = $el("img", {
|
||||
src: "",
|
||||
style: {
|
||||
width: "100%",
|
||||
maxHeight: "100px",
|
||||
objectFit: "contain",
|
||||
display: "none",
|
||||
marginTop: '10px',
|
||||
},
|
||||
});
|
||||
|
||||
this.keyInput = $el("input", {
|
||||
type: "password",
|
||||
placeholder: "Copy & paste your API key",
|
||||
style: inputStyle,
|
||||
});
|
||||
this.NameInput = $el("input", {
|
||||
type: "text",
|
||||
placeholder: "Title (required)",
|
||||
style: inputStyle,
|
||||
});
|
||||
this.descriptionInput = $el("textarea", {
|
||||
placeholder: "Description (optional)",
|
||||
style: {
|
||||
...inputStyle,
|
||||
minHeight: "100px",
|
||||
},
|
||||
});
|
||||
|
||||
// Header Section
|
||||
const headerSection = $el("h3", {
|
||||
textContent: "Share your workflow to OpenArt",
|
||||
size: 3,
|
||||
color: "white",
|
||||
style: {
|
||||
'text-align': 'center',
|
||||
color: 'var(--input-text)',
|
||||
margin: '0 0 10px 0',
|
||||
}
|
||||
});
|
||||
|
||||
// LinkSection
|
||||
this.communityLink = $el("a", {
|
||||
style: hyperLinkStyle,
|
||||
href: DEFAULT_HOMEPAGE_URL,
|
||||
target: "_blank"
|
||||
}, ["👉 Check out thousands of workflows shared from the community"])
|
||||
this.getAPIKeyLink = $el("a", {
|
||||
style: {
|
||||
...hyperLinkStyle,
|
||||
color: "#59E8C6"
|
||||
},
|
||||
href: DEFAULT_HOMEPAGE_URL,
|
||||
target: "_blank"
|
||||
}, ["👉 Get your API key here"])
|
||||
const linkSection = $el(
|
||||
"div",
|
||||
{
|
||||
style: {
|
||||
marginTop: "10px",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
},
|
||||
},
|
||||
[
|
||||
this.communityLink,
|
||||
this.getAPIKeyLink,
|
||||
]
|
||||
);
|
||||
|
||||
// Account Section
|
||||
const accountSection = $el("div", {style: sectionStyle}, [
|
||||
$el("label", {style: labelStyle}, ["1️⃣ OpenArt API Key"]),
|
||||
this.keyInput,
|
||||
]);
|
||||
|
||||
// Output Upload Section
|
||||
const outputUploadSection = $el("div", {style: sectionStyle}, [
|
||||
$el("label", {
|
||||
style: {
|
||||
...labelStyle,
|
||||
margin: "10px 0 0 0"
|
||||
}
|
||||
}, ["2️⃣ Image/Thumbnail (Required)"]),
|
||||
this.previewImage,
|
||||
this.uploadImagesInput,
|
||||
]);
|
||||
|
||||
// Outputs Section
|
||||
this.outputsSection = $el("div", {
|
||||
id: "selectOutputs",
|
||||
}, []);
|
||||
|
||||
// Additional Inputs Section
|
||||
const additionalInputsSection = $el("div", {style: sectionStyle}, [
|
||||
$el("label", {style: labelStyle}, ["3️⃣ Workflow Information"]),
|
||||
this.NameInput,
|
||||
this.descriptionInput,
|
||||
]);
|
||||
|
||||
// OpenArt Contest Section
|
||||
/*
|
||||
this.joinContestCheckbox = $el("input", {
|
||||
type: 'checkbox',
|
||||
id: "join_contest"s
|
||||
}, [])
|
||||
this.joinContestDescription = $el("a", {
|
||||
style: {
|
||||
...hyperLinkStyle,
|
||||
display: 'inline-block',
|
||||
color: "#59E8C6",
|
||||
fontSize: '12px',
|
||||
marginLeft: '10px',
|
||||
marginBottom: 0,
|
||||
},
|
||||
href: "https://contest.openart.ai/",
|
||||
target: "_blank"
|
||||
}, ["🏆 I'm participating in the OpenArt workflow contest"])
|
||||
this.joinContestLabel = $el("label", {
|
||||
style: {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
cursor: 'pointer',
|
||||
}
|
||||
}, [this.joinContestCheckbox, this.joinContestDescription])
|
||||
const contestSection = $el("div", {style: sectionStyle}, [
|
||||
this.joinContestLabel,
|
||||
]);
|
||||
*/
|
||||
|
||||
// Message Section
|
||||
this.message = $el(
|
||||
"div",
|
||||
{
|
||||
style: {
|
||||
color: "#ff3d00",
|
||||
textAlign: "center",
|
||||
padding: "10px",
|
||||
fontSize: "20px",
|
||||
},
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
this.shareButton = $el("button", {
|
||||
type: "submit",
|
||||
textContent: "Share",
|
||||
style: buttonStyle,
|
||||
onclick: () => {
|
||||
this.handleShareButtonClick();
|
||||
},
|
||||
});
|
||||
|
||||
// Share and Close Buttons
|
||||
const buttonsSection = $el(
|
||||
"div",
|
||||
{
|
||||
style: {
|
||||
textAlign: "right",
|
||||
marginTop: "20px",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
},
|
||||
},
|
||||
[
|
||||
$el("button", {
|
||||
type: "button",
|
||||
textContent: "Close",
|
||||
style: {
|
||||
...buttonStyle,
|
||||
backgroundColor: undefined,
|
||||
},
|
||||
onclick: () => {
|
||||
this.close();
|
||||
},
|
||||
}),
|
||||
this.shareButton,
|
||||
]
|
||||
);
|
||||
|
||||
// Composing the full layout
|
||||
const layout = [
|
||||
headerSection,
|
||||
linkSection,
|
||||
accountSection,
|
||||
outputUploadSection,
|
||||
this.outputsSection,
|
||||
additionalInputsSection,
|
||||
// contestSection,
|
||||
this.message,
|
||||
buttonsSection,
|
||||
];
|
||||
|
||||
return layout;
|
||||
}
|
||||
|
||||
async fetchApi(path, options, statusText) {
|
||||
if (statusText) {
|
||||
this.message.textContent = statusText;
|
||||
}
|
||||
const addSearchParams = (url, params = {}) =>
|
||||
new URL(
|
||||
`${url.origin}${url.pathname}?${new URLSearchParams([
|
||||
...Array.from(url.searchParams.entries()),
|
||||
...Object.entries(params),
|
||||
])}`
|
||||
);
|
||||
|
||||
const fullPath = addSearchParams(new URL(API_ENDPOINT + path), {
|
||||
workflow_api_key: this.keyInput.value,
|
||||
});
|
||||
|
||||
const response = await fetch(fullPath, options);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
if (statusText) {
|
||||
this.message.textContent = "";
|
||||
}
|
||||
const data = await response.json();
|
||||
return {
|
||||
ok: response.ok,
|
||||
statusText: response.statusText,
|
||||
status: response.status,
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
async uploadThumbnail(uploadFile) {
|
||||
const form = new FormData();
|
||||
form.append("file", uploadFile);
|
||||
try {
|
||||
const res = await this.fetchApi(
|
||||
`/v2/workflows/upload_thumbnail`,
|
||||
{
|
||||
method: "POST",
|
||||
body: form,
|
||||
},
|
||||
"Uploading thumbnail..."
|
||||
);
|
||||
|
||||
if (res.ok && res.data) {
|
||||
const {image_url, width, height} = res.data;
|
||||
this.uploadedImages.push({
|
||||
url: image_url,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if (e?.response?.status === 413) {
|
||||
throw new Error("File size is too large (max 20MB)");
|
||||
} else {
|
||||
throw new Error("Error uploading thumbnail: " + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleShareButtonClick() {
|
||||
this.message.textContent = "";
|
||||
await this.saveKey(this.keyInput.value);
|
||||
try {
|
||||
this.shareButton.disabled = true;
|
||||
this.shareButton.textContent = "Sharing...";
|
||||
await this.share();
|
||||
} catch (e) {
|
||||
customAlert(e.message);
|
||||
}
|
||||
this.shareButton.disabled = false;
|
||||
this.shareButton.textContent = "Share";
|
||||
}
|
||||
|
||||
async share() {
|
||||
const prompt = await app.graphToPrompt();
|
||||
const workflowJSON = prompt["workflow"];
|
||||
const workflowAPIJSON = prompt["output"];
|
||||
const form_values = {
|
||||
name: this.NameInput.value,
|
||||
description: this.descriptionInput.value,
|
||||
};
|
||||
|
||||
if (!this.keyInput.value) {
|
||||
throw new Error("API key is required");
|
||||
}
|
||||
|
||||
if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
|
||||
throw new Error("Thumbnail is required");
|
||||
}
|
||||
|
||||
if (!form_values.name) {
|
||||
throw new Error("Title is required");
|
||||
}
|
||||
|
||||
const current_snapshot = await api.fetchApi(`/v2/snapshot/get_current`)
|
||||
.then(response => response.json())
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
});
|
||||
|
||||
|
||||
if (!this.uploadedImages.length) {
|
||||
if (this.selectedFile) {
|
||||
await this.uploadThumbnail(this.selectedFile);
|
||||
} else {
|
||||
for (const file of this.uploadImagesInput.files) {
|
||||
try {
|
||||
await this.uploadThumbnail(file);
|
||||
} catch (e) {
|
||||
this.uploadedImages = [];
|
||||
throw new Error(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.uploadImagesInput.files.length === 0) {
|
||||
throw new Error("No thumbnail uploaded");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// const join_contest = this.joinContestCheckbox.checked;
|
||||
|
||||
try {
|
||||
const response = await this.fetchApi(
|
||||
"/v2/workflows/publish",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({
|
||||
workflow_json: workflowJSON,
|
||||
upload_images: this.uploadedImages,
|
||||
form_values,
|
||||
advanced_config: {
|
||||
workflow_api_json: workflowAPIJSON,
|
||||
snapshot: current_snapshot,
|
||||
},
|
||||
// join_contest,
|
||||
}),
|
||||
},
|
||||
"Uploading workflow..."
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const {workflow_id} = response.data;
|
||||
if (workflow_id) {
|
||||
const url = `https://openart.ai/workflows/-/-/${workflow_id}`;
|
||||
this.message.innerHTML = `Workflow has been shared successfully. <a href="${sanitizeHTML(sanitizeUrl(url))}" target="_blank" rel="noopener noreferrer">Click here to view it.</a>`;
|
||||
this.previewImage.src = "";
|
||||
this.previewImage.style.display = "none";
|
||||
this.uploadedImages = [];
|
||||
this.NameInput.value = "";
|
||||
this.descriptionInput.value = "";
|
||||
this.radioButtons.forEach((ele) => {
|
||||
ele.checked = false;
|
||||
ele.parentElement.classList.remove("checked");
|
||||
});
|
||||
this.selectedOutputIndex = 0;
|
||||
this.selectedNodeId = null;
|
||||
this.selectedFile = null;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error("Error sharing workflow: " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async fetchImageBlob(url) {
|
||||
const response = await fetch(url);
|
||||
const blob = await response.blob();
|
||||
return blob;
|
||||
}
|
||||
|
||||
async show({potential_outputs, potential_output_nodes} = {}) {
|
||||
// Sort `potential_output_nodes` by node ID to make the order always
|
||||
// consistent, but we should also keep `potential_outputs` in the same
|
||||
// order as `potential_output_nodes`.
|
||||
const potential_output_to_order = {};
|
||||
potential_output_nodes.forEach((node, index) => {
|
||||
if (node.id in potential_output_to_order) {
|
||||
potential_output_to_order[node.id][1].push(potential_outputs[index]);
|
||||
} else {
|
||||
potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
|
||||
}
|
||||
})
|
||||
// Sort the object `potential_output_to_order` by key (node ID)
|
||||
const sorted_potential_output_to_order = Object.fromEntries(
|
||||
Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
|
||||
);
|
||||
const sorted_potential_outputs = []
|
||||
const sorted_potential_output_nodes = []
|
||||
for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
|
||||
sorted_potential_output_nodes.push(value[0]);
|
||||
sorted_potential_outputs.push(...value[1]);
|
||||
}
|
||||
potential_output_nodes = sorted_potential_output_nodes;
|
||||
potential_outputs = sorted_potential_outputs;
|
||||
|
||||
this.message.innerHTML = "";
|
||||
this.message.textContent = "";
|
||||
this.element.style.display = "block";
|
||||
this.previewImage.src = "";
|
||||
this.previewImage.style.display = "none";
|
||||
const key = await this.readKey();
|
||||
this.keyInput.value = key;
|
||||
this.uploadedImages = [];
|
||||
|
||||
// If `selectedNodeId` is provided, we will select the corresponding radio
|
||||
// button for the node. In addition, we move the selected radio button to
|
||||
// the top of the list.
|
||||
if (this.selectedNodeId) {
|
||||
const index = potential_output_nodes.findIndex(node => node.id === this.selectedNodeId);
|
||||
if (index >= 0) {
|
||||
this.selectedOutputIndex = index;
|
||||
}
|
||||
}
|
||||
|
||||
this.radioButtons = [];
|
||||
const new_radio_buttons = $el("div",
|
||||
{
|
||||
id: "selectOutput-Options",
|
||||
style: {
|
||||
'overflow-y': 'scroll',
|
||||
'max-height': '200px',
|
||||
|
||||
'display': 'grid',
|
||||
'grid-template-columns': 'repeat(auto-fit, minmax(100px, 1fr))',
|
||||
'grid-template-rows': 'auto',
|
||||
'grid-column-gap': '10px',
|
||||
'grid-row-gap': '10px',
|
||||
'margin-bottom': '10px',
|
||||
'padding': '10px',
|
||||
'border-radius': '8px',
|
||||
'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.05)',
|
||||
'background-color': 'var(--bg-color)',
|
||||
}
|
||||
},
|
||||
potential_outputs.map((output, index) => {
|
||||
const {node_id} = output;
|
||||
const radio_button = $el("input", {
|
||||
type: 'radio',
|
||||
name: "selectOutputImages",
|
||||
value: index,
|
||||
required: index === 0
|
||||
}, [])
|
||||
let radio_button_img;
|
||||
let filename;
|
||||
if (output.type === "image" || output.type === "temp") {
|
||||
radio_button_img = $el("img", {
|
||||
src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
|
||||
style: {
|
||||
width: "100px",
|
||||
height: "100px",
|
||||
objectFit: "cover",
|
||||
borderRadius: "5px"
|
||||
}
|
||||
}, []);
|
||||
filename = output.image.filename
|
||||
} else if (output.type === "output") {
|
||||
radio_button_img = $el("img", {
|
||||
src: output.output.value,
|
||||
style: {
|
||||
width: "auto",
|
||||
height: "100px",
|
||||
objectFit: "cover",
|
||||
borderRadius: "5px"
|
||||
}
|
||||
}, []);
|
||||
filename = output.filename
|
||||
} else {
|
||||
// unsupported output type
|
||||
// this should never happen
|
||||
// TODO
|
||||
radio_button_img = $el("img", {
|
||||
src: "",
|
||||
style: {width: "auto", height: "100px"}
|
||||
}, []);
|
||||
}
|
||||
const radio_button_text = $el("span", {
|
||||
style: {
|
||||
color: 'gray',
|
||||
display: 'block',
|
||||
fontSize: '12px',
|
||||
overflowX: 'hidden',
|
||||
textOverflow: 'ellipsis',
|
||||
textWrap: 'nowrap',
|
||||
maxWidth: '100px',
|
||||
}
|
||||
}, [output.title])
|
||||
const node_id_chip = $el("span", {
|
||||
style: {
|
||||
color: '#FBFBFD',
|
||||
display: 'block',
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.5)',
|
||||
fontSize: '12px',
|
||||
overflowX: 'hidden',
|
||||
padding: '2px 3px',
|
||||
textOverflow: 'ellipsis',
|
||||
textWrap: 'nowrap',
|
||||
maxWidth: '100px',
|
||||
position: 'absolute',
|
||||
top: '3px',
|
||||
left: '3px',
|
||||
borderRadius: '3px',
|
||||
}
|
||||
}, [`Node: ${node_id}`])
|
||||
radio_button.style.color = "var(--fg-color)";
|
||||
radio_button.checked = this.selectedOutputIndex === index;
|
||||
|
||||
radio_button.onchange = async () => {
|
||||
this.selectedOutputIndex = parseInt(radio_button.value);
|
||||
|
||||
// Remove the "checked" class from all radio buttons
|
||||
this.radioButtons.forEach((ele) => {
|
||||
ele.parentElement.classList.remove("checked");
|
||||
});
|
||||
radio_button.parentElement.classList.add("checked");
|
||||
|
||||
this.fetchImageBlob(radio_button_img.src).then((blob) => {
|
||||
const file = new File([blob], filename, {
|
||||
type: blob.type,
|
||||
});
|
||||
this.previewImage.src = radio_button_img.src;
|
||||
this.previewImage.style.display = "block";
|
||||
this.selectedFile = file;
|
||||
})
|
||||
|
||||
// Add the opacity style toggle here to indicate that they only need
|
||||
// to upload one image or choose one from the outputs.
|
||||
this.outputsSection.style.opacity = 1;
|
||||
this.uploadImagesInput.style.opacity = 0.35;
|
||||
};
|
||||
|
||||
if (radio_button.checked) {
|
||||
this.fetchImageBlob(radio_button_img.src).then((blob) => {
|
||||
const file = new File([blob], filename, {
|
||||
type: blob.type,
|
||||
});
|
||||
this.previewImage.src = radio_button_img.src;
|
||||
this.previewImage.style.display = "block";
|
||||
this.selectedFile = file;
|
||||
})
|
||||
// Add the opacity style toggle here to indicate that they only need
|
||||
// to upload one image or choose one from the outputs.
|
||||
this.outputsSection.style.opacity = 1;
|
||||
this.uploadImagesInput.style.opacity = 0.35;
|
||||
}
|
||||
|
||||
this.radioButtons.push(radio_button);
|
||||
|
||||
return $el(`label.output_label${radio_button.checked ? '.checked' : ''}`, {
|
||||
style: {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
marginBottom: "10px",
|
||||
cursor: "pointer",
|
||||
position: 'relative',
|
||||
}
|
||||
}, [radio_button_img, radio_button_text, radio_button, node_id_chip]);
|
||||
})
|
||||
);
|
||||
|
||||
const header =
|
||||
$el("p", {
|
||||
textContent: this.radioButtons.length === 0 ? "Queue Prompt to see the outputs" : "Or choose one from the outputs (scroll to see all)",
|
||||
size: 2,
|
||||
color: "white",
|
||||
style: {
|
||||
color: 'var(--input-text)',
|
||||
margin: '0 0 5px 0',
|
||||
fontSize: '12px',
|
||||
},
|
||||
}, [])
|
||||
this.outputsSection.innerHTML = "";
|
||||
this.outputsSection.appendChild(header);
|
||||
this.outputsSection.appendChild(new_radio_buttons);
|
||||
}
|
||||
}
|
||||
@@ -176,25 +176,12 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
this.selectedFile = null;
|
||||
}
|
||||
|
||||
async loadToken() {
|
||||
let key = ""
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/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(`/v2/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";
|
||||
|
||||
@@ -172,7 +172,7 @@ export function rebootAPI() {
|
||||
customConfirm("Are you sure you'd like to reboot the server?").then((isConfirmed) => {
|
||||
if (isConfirmed) {
|
||||
try {
|
||||
api.fetchApi("/v2/manager/reboot", { method: 'POST' });
|
||||
api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
catch(exception) {}
|
||||
}
|
||||
@@ -212,7 +212,8 @@ export async function install_pip(packages) {
|
||||
|
||||
const res = await api.fetchApi("/v2/customnode/install/pip", {
|
||||
method: "POST",
|
||||
body: packages,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ packages: packages }),
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
@@ -247,7 +248,8 @@ export async function install_via_git_url(url, manager_dialog) {
|
||||
|
||||
const res = await api.fetchApi("/v2/customnode/install/git_url", {
|
||||
method: "POST",
|
||||
body: url,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: url }),
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
@@ -347,6 +349,55 @@ 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 async function fetchData(route, options) {
|
||||
let err;
|
||||
const res = await api.fetchApi(route, options).catch(e => {
|
||||
|
||||
@@ -103,7 +103,7 @@
|
||||
line-height: 28px;
|
||||
|
||||
cursor: pointer;
|
||||
padding: 0.5em 0.5em;
|
||||
padding: 0 0.5em;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
background: var(--comfy-input-bg);
|
||||
@@ -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;
|
||||
@@ -726,4 +719,4 @@
|
||||
|
||||
.cn-manager-light .cn-btn-install {
|
||||
background-color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
fetchData, md5, icons, show_message, customConfirm, customAlert, customPrompt,
|
||||
sanitizeHTML, infoToast, showTerminal, setNeedRestart,
|
||||
storeColumnWidth, restoreColumnWidth, getTimeAgo, copyText, loadCss,
|
||||
showPopover, hidePopover, generateUUID, sanitizeUrl
|
||||
showPopover, hidePopover, generateUUID, sanitizeUrl, leven
|
||||
} from "./common.js";
|
||||
|
||||
// Registry titles, names and descriptions are server-escaped; other fields are raw.
|
||||
@@ -20,19 +20,21 @@ 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>
|
||||
<div class="cn-manager-selection"></div>
|
||||
<div class="cn-manager-message"></div>
|
||||
<div class="cn-manager-footer">
|
||||
<button class="cn-manager-restart p-button p-component">Restart</button>
|
||||
<button class="cn-manager-stop p-button p-component">Stop</button>
|
||||
<button class="cn-manager-restart cm-ui-button">Restart</button>
|
||||
<button class="cn-manager-stop cm-ui-button">Stop</button>
|
||||
<div class="cn-flex-auto"></div>
|
||||
<button class="cn-manager-used-in-workflow p-button p-component">Used In Workflow</button>
|
||||
<button class="cn-manager-check-update p-button p-component">Check Update</button>
|
||||
<button class="cn-manager-check-missing p-button p-component">Check Missing</button>
|
||||
<button class="cn-manager-install-url p-button p-component">Install via Git URL</button>
|
||||
<button class="cn-manager-used-in-workflow cm-ui-button">Used In Workflow</button>
|
||||
<button class="cn-manager-check-update cm-ui-button">Check Update</button>
|
||||
<button class="cn-manager-check-missing cm-ui-button">Check Missing</button>
|
||||
<button class="cn-manager-install-url cm-ui-button">Install via Git URL</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -42,7 +44,6 @@ const ShowMode = {
|
||||
UPDATE: "Update",
|
||||
MISSING: "Missing",
|
||||
FAVORITES: "Favorites",
|
||||
ALTERNATIVES: "Alternatives",
|
||||
IN_WORKFLOW: "In Workflow",
|
||||
};
|
||||
|
||||
@@ -73,6 +74,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;
|
||||
})
|
||||
@@ -85,7 +88,7 @@ export class CustomNodesManager {
|
||||
// $el("select.cn-manager-filter")
|
||||
// ]),
|
||||
createSettingsCombo("Filter", $el("select.cn-manager-filter")),
|
||||
$el("input.cn-manager-keywords.p-inputtext.p-component", { type: "search", placeholder: "Search" }),
|
||||
$el("input.cn-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
|
||||
$el("div.cn-manager-status"),
|
||||
$el("div.cn-flex-auto"),
|
||||
$el("div.cn-manager-channel")
|
||||
@@ -253,6 +256,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",
|
||||
@@ -281,10 +288,6 @@ export class CustomNodesManager {
|
||||
label: "Favorites",
|
||||
value: ShowMode.FAVORITES,
|
||||
hasData: false
|
||||
}, {
|
||||
label: "Alternatives of A1111",
|
||||
value: ShowMode.ALTERNATIVES,
|
||||
hasData: false
|
||||
}];
|
||||
this.filterList = filterList;
|
||||
$filter.innerHTML = filterList.map(item => {
|
||||
@@ -323,7 +326,8 @@ export class CustomNodesManager {
|
||||
|
||||
"reinstall": {
|
||||
label: "Reinstall",
|
||||
mode: "reinstall"
|
||||
mode: "reinstall",
|
||||
title: INVALID_INSTALLATION_GUIDANCE
|
||||
},
|
||||
|
||||
"install": {
|
||||
@@ -377,8 +381,9 @@ export class CustomNodesManager {
|
||||
|
||||
return shown.map(id => {
|
||||
const bt = buttons[id];
|
||||
const tooltip = bt.title ? ` title="${sanitizeHTML(bt.title)}"` : "";
|
||||
// `action` is registry-derived and lands in an attribute.
|
||||
return `<button class="cn-btn-${id} p-button p-component" group="${sanitizeHTML(String(action ?? ''))}" mode="${bt.mode}">${bt.label}</button>`;
|
||||
return `<button class="cn-btn-${id} cm-ui-button" group="${sanitizeHTML(String(action ?? ''))}" mode="${bt.mode}"${tooltip}>${bt.label}</button>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
@@ -424,11 +429,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()
|
||||
},
|
||||
@@ -465,7 +466,7 @@ export class CustomNodesManager {
|
||||
|
||||
".cn-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -545,7 +546,7 @@ export class CustomNodesManager {
|
||||
|
||||
this.addHighlight(d.rowItem);
|
||||
|
||||
if (d.columnItem.id === "nodes") {
|
||||
if (d.columnItem && d.columnItem.id === "nodes") {
|
||||
this.showNodes(d);
|
||||
return;
|
||||
}
|
||||
@@ -601,17 +602,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);
|
||||
|
||||
@@ -621,14 +629,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) {
|
||||
@@ -703,10 +806,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 '${String(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';
|
||||
@@ -767,6 +873,7 @@ export class CustomNodesManager {
|
||||
id: "nodes",
|
||||
name: "Nodes",
|
||||
width: 100,
|
||||
sortAsc: false,
|
||||
formatter: (v, rowItem, columnItem) => {
|
||||
if (!rowItem.nodes) {
|
||||
return '';
|
||||
@@ -779,13 +886,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' // composed HTML; tags are escaped in getAlternatives
|
||||
}, {
|
||||
id: 'description',
|
||||
name: 'Description',
|
||||
@@ -807,6 +907,7 @@ export class CustomNodesManager {
|
||||
id: 'stars',
|
||||
name: '★',
|
||||
align: 'center',
|
||||
sortAsc: false,
|
||||
classMap: "cn-pack-stars",
|
||||
formatter: (stars) => {
|
||||
if (stars < 0) {
|
||||
@@ -822,6 +923,7 @@ export class CustomNodesManager {
|
||||
name: 'Last Update',
|
||||
align: 'center',
|
||||
type: 'date',
|
||||
sortAsc: false,
|
||||
width: 100,
|
||||
classMap: "cn-pack-last-update",
|
||||
formatter: (last_update) => {
|
||||
@@ -868,11 +970,6 @@ export class CustomNodesManager {
|
||||
updateGrid() {
|
||||
if (this.grid) {
|
||||
this.grid.update();
|
||||
if (this.hasAlternatives()) {
|
||||
this.grid.showColumn("alternatives");
|
||||
} else {
|
||||
this.grid.hideColumn("alternatives");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -910,7 +1007,7 @@ export class CustomNodesManager {
|
||||
// console.log(nodeItem);
|
||||
const list = [`<div class="cn-preview-header">
|
||||
<div class="cn-preview-dot"></div>
|
||||
<div class="cn-preview-name">${nodeItem.name}</div>
|
||||
<div class="cn-preview-name">${sanitizeHTML(String(nodeItem.name ?? ""))}</div>
|
||||
<div class="cn-pack-badge">Preview</div>
|
||||
</div>`];
|
||||
|
||||
@@ -991,7 +1088,7 @@ export class CustomNodesManager {
|
||||
const optional = it.optional ? " cn-preview-optional" : ""
|
||||
return `<div class="cn-preview-input">
|
||||
<div class="cn-preview-dot${optional}" style="background-color:${color}"></div>
|
||||
${it.name}
|
||||
${sanitizeHTML(String(it.name ?? ""))}
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
@@ -999,7 +1096,7 @@ export class CustomNodesManager {
|
||||
const color = colorMap[it.type] || "gray";
|
||||
const grid = it.list ? " cn-preview-grid" : "";
|
||||
return `<div class="cn-preview-output">
|
||||
${it.name}
|
||||
${sanitizeHTML(String(it.name ?? ""))}
|
||||
<div class="cn-preview-dot${grid}" style="background-color:${color}"></div>
|
||||
</div>`;
|
||||
}).join("");
|
||||
@@ -1031,22 +1128,23 @@ export class CustomNodesManager {
|
||||
|| it.type === "MARKDOWN"
|
||||
) {
|
||||
if (value) {
|
||||
value = value.replace(/\r?\n/g, "<br>")
|
||||
// escape first, then allow the <br> this branch adds
|
||||
value = sanitizeHTML(String(value)).replace(/\r?\n/g, "<br>")
|
||||
}
|
||||
list.push(`<div class="cn-preview-string">${value || it.name}</div>`);
|
||||
list.push(`<div class="cn-preview-string">${value || sanitizeHTML(String(it.name ?? ""))}</div>`);
|
||||
return;
|
||||
}
|
||||
|
||||
list.push(`<div class="cn-preview-switch">
|
||||
<div>${it.name}</div>
|
||||
<div class="cn-preview-value">${value}</div>
|
||||
<div>${sanitizeHTML(String(it.name ?? ""))}</div>
|
||||
<div class="cn-preview-value">${sanitizeHTML(String(value))}</div>
|
||||
</div>`);
|
||||
});
|
||||
list.push(`</div>`);
|
||||
}
|
||||
|
||||
if (nodeItem.description) {
|
||||
list.push(`<div class="cn-preview-description">${nodeItem.description}</div>`)
|
||||
list.push(`<div class="cn-preview-description">${sanitizeHTML(String(nodeItem.description))}</div>`)
|
||||
}
|
||||
|
||||
return list.join("");
|
||||
@@ -1468,7 +1566,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;
|
||||
}
|
||||
@@ -1532,7 +1631,8 @@ export class CustomNodesManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.install_context = {btn: btn, targets: target_items};
|
||||
const context = {btn: btn, targets: target_items};
|
||||
this.install_context = context;
|
||||
|
||||
if(errorMsg) {
|
||||
this.showError(errorMsg);
|
||||
@@ -1552,6 +1652,7 @@ export class CustomNodesManager {
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
@@ -1589,10 +1690,67 @@ export class CustomNodesManager {
|
||||
return;
|
||||
}
|
||||
|
||||
context.queued = true;
|
||||
this.showStop();
|
||||
}
|
||||
}
|
||||
|
||||
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('/v2/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 legacy manager front is not open, return early (using new manager front)
|
||||
@@ -1612,15 +1770,43 @@ export class CustomNodesManager {
|
||||
self.hideStop();
|
||||
self.onQueueCompleted(event.detail);
|
||||
}
|
||||
else if(event.detail.status == 'all-done') {
|
||||
self.endDroppedInstall();
|
||||
}
|
||||
}
|
||||
|
||||
// The end of the queue was reported and the install did not get the end of its batch: Stop dropped
|
||||
// the batch. The report can also be that of a queue that ran before the batch was added, so the
|
||||
// install is ended only if the queue is not running now.
|
||||
async endDroppedInstall() {
|
||||
const context = this.install_context;
|
||||
if(!context?.queued) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Without an answer the queue may still be running.
|
||||
const { data } = await fetchData('/v2/manager/queue/status');
|
||||
if(!data || data.is_processing) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.btn.target.classList.remove("cn-btn-loading");
|
||||
for(const item of context.targets) {
|
||||
this.grid.updateCell(item, "action");
|
||||
}
|
||||
this.hideStop();
|
||||
this.install_context = undefined;
|
||||
|
||||
if(context.targets.some(item => item.restart)) {
|
||||
this.showRestart();
|
||||
this.showMessage(`To apply the installed/updated/disabled/enabled custom node, please restart ComfyUI. And refresh browser.`, "red");
|
||||
}
|
||||
}
|
||||
|
||||
async onQueueCompleted(info) {
|
||||
// nodepack_result is an object keyed by the id of each task, not an array
|
||||
let result = info.nodepack_result;
|
||||
|
||||
if(result.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let self = CustomNodesManager.instance;
|
||||
|
||||
if(!self.install_context) {
|
||||
@@ -1648,7 +1834,7 @@ export class CustomNodesManager {
|
||||
self.showError(errorMsg);
|
||||
show_message("Installation Error:\n"+errorMsg);
|
||||
} else {
|
||||
self.showStatus(`${label} ${result.length} custom node(s) successfully`);
|
||||
self.showStatus(`${label} ${Object.keys(result).length} custom node(s) successfully`);
|
||||
}
|
||||
|
||||
self.showRestart();
|
||||
@@ -1707,6 +1893,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 = {};
|
||||
@@ -1731,7 +1932,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;
|
||||
}
|
||||
@@ -1901,7 +2102,7 @@ export class CustomNodesManager {
|
||||
for(let k in allUsedNodes) {
|
||||
var item;
|
||||
if(allUsedNodes[k].properties.cnr_id) {
|
||||
item = this.custom_nodes[allUsedNodes[k].properties.cnr_id];
|
||||
item = this.getNodepackByCnrId(allUsedNodes[k].properties.cnr_id);
|
||||
}
|
||||
else if(allUsedNodes[k].properties.aux_id) {
|
||||
item = aux_id_to_pack[allUsedNodes[k].properties.aux_id];
|
||||
@@ -1914,58 +2115,31 @@ export class CustomNodesManager {
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
async getAlternatives() {
|
||||
const mode = manager_instance.datasrc_combo.value;
|
||||
this.showStatus(`Loading alternatives (${mode}) ...`);
|
||||
const res = await fetchData(`/v2/customnode/alternatives?mode=${mode}`);
|
||||
if (res.error) {
|
||||
this.showError(`Failed to get alternatives: ${sanitizeHTML(String(res.error))}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const hashMap = {};
|
||||
const items = res.data;
|
||||
|
||||
for(let i in items) {
|
||||
let item = items[i];
|
||||
let custom_node = this.custom_nodes[i];
|
||||
|
||||
if (!custom_node) {
|
||||
console.log(`Not found custom node: ${item.id}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const tags = `${item.tags}`.split(",").map(tag => {
|
||||
return `<div>${sanitizeHTML(tag.trim())}</div>`;
|
||||
}).join("");
|
||||
|
||||
hashMap[custom_node.hash] = {
|
||||
alternatives: `<div class="cn-tag-list">${tags}</div> ${item.description}`
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return hashMap;
|
||||
}
|
||||
|
||||
async loadData(show_mode = ShowMode.NORMAL) {
|
||||
const isElectron = 'electronAPI' in window;
|
||||
|
||||
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(`/v2/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(`/v2/customnode/getlist?mode=${mode}&skip_update=true`);
|
||||
if (res.error) {
|
||||
this.showError("Failed to get custom node list.");
|
||||
this.hideLoading();
|
||||
@@ -1974,6 +2148,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'];
|
||||
}
|
||||
@@ -2011,8 +2191,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) {
|
||||
@@ -2059,9 +2237,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) {
|
||||
@@ -2134,6 +2309,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
showLoading() {
|
||||
this.loading = true;
|
||||
this.setDisabled(true);
|
||||
if (this.grid) {
|
||||
this.grid.showLoading();
|
||||
@@ -2144,6 +2320,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
hideLoading() {
|
||||
this.loading = false;
|
||||
this.setDisabled(false);
|
||||
if (this.grid) {
|
||||
this.grid.hideLoading();
|
||||
|
||||
@@ -71,7 +71,7 @@
|
||||
line-height: 28px;
|
||||
|
||||
cursor: pointer;
|
||||
padding: 0.5em 0.5em;
|
||||
padding: 0 0.5em;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
background: var(--comfy-input-bg);
|
||||
@@ -234,4 +234,4 @@
|
||||
|
||||
.cmm-manager-light .cmm-btn-install {
|
||||
background-color: #333;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@ const pageHtml = `
|
||||
<div class="cmm-manager-selection"></div>
|
||||
<div class="cmm-manager-message"></div>
|
||||
<div class="cmm-manager-footer">
|
||||
<button class="cmm-manager-refresh p-button p-component">Refresh</button>
|
||||
<button class="cmm-manager-stop p-button p-component">Stop</button>
|
||||
<button class="cmm-manager-refresh cm-ui-button">Refresh</button>
|
||||
<button class="cmm-manager-stop cm-ui-button">Stop</button>
|
||||
<div class="cmm-flex-auto"></div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -46,6 +46,9 @@ export class ModelManager {
|
||||
this.base = '';
|
||||
this.keywords = '';
|
||||
|
||||
// Installs that are waiting for the end of their batch, by batch id
|
||||
this.install_contexts = new Map();
|
||||
|
||||
this.init();
|
||||
|
||||
api.addEventListener("cm-queue-status", this.onQueueStatus);
|
||||
@@ -56,7 +59,7 @@ export class ModelManager {
|
||||
createSettingsCombo("Filter", $el("select.cmm-manager-filter")),
|
||||
createSettingsCombo("Type", $el("select.cmm-manager-type")),
|
||||
createSettingsCombo("Base", $el("select.cmm-manager-base")),
|
||||
$el("input.cmm-manager-keywords.p-inputtext.p-component", { type: "search", placeholder: "Search" }),
|
||||
$el("input.cmm-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
|
||||
$el("div.cmm-manager-status"),
|
||||
$el("div.cmm-flex-auto")
|
||||
]);
|
||||
@@ -170,7 +173,7 @@ export class ModelManager {
|
||||
|
||||
".cmm-manager-stop": {
|
||||
click: () => {
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
|
||||
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
|
||||
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
|
||||
}
|
||||
},
|
||||
@@ -255,31 +258,20 @@ export class ModelManager {
|
||||
rowFilter: (rowItem) => {
|
||||
|
||||
const searchableColumns = ["name", "type", "base", "description", "filename", "save_path"];
|
||||
const models_extensions = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'];
|
||||
|
||||
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
|
||||
|
||||
if (shouldShown) {
|
||||
if(this.filter) {
|
||||
if (this.filter == "in_workflow") {
|
||||
rowItem.in_workflow = null;
|
||||
if (Array.isArray(app.graph._nodes)) {
|
||||
app.graph._nodes.forEach((item, i) => {
|
||||
if (Array.isArray(item.widgets_values)) {
|
||||
item.widgets_values.forEach((_item, i) => {
|
||||
if (rowItem.in_workflow === null && _item !== null && models_extensions.includes("." + _item.toString().split('.').pop())) {
|
||||
let filename = _item.match(/([^\/]+)(?=\.\w+$)/)[0];
|
||||
if (grid.highlightKeywordsFilter(rowItem, searchableColumns, filename)) {
|
||||
rowItem.in_workflow = "True";
|
||||
grid.highlightKeywordsFilter(rowItem, searchableColumns, "");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
return ((this.filter == "installed" && rowItem.installed == "True") || (this.filter == "not_installed" && rowItem.installed == "False") || (this.filter == "in_workflow" && rowItem.in_workflow == "True"));
|
||||
if(this.filter == "installed" && rowItem.installed !== "True") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.filter == "not_installed" && rowItem.installed !== "False") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.filter == "in_workflow" && !app.graph._nodes.some(node => Array.isArray(node.widgets_values) && node.widgets_values.some(value => String(value).split(/[\\/]/).pop() === rowItem.filename))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if(this.type && rowItem.type !== this.type) {
|
||||
@@ -350,7 +342,7 @@ export class ModelManager {
|
||||
if (installed === "True") {
|
||||
return `<div class="cmm-icon-passed">${icons.passed}</div>`;
|
||||
}
|
||||
return `<button class="cmm-btn-install p-button p-component" mode="install">Install</button>`;
|
||||
return `<button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`;
|
||||
}
|
||||
}, {
|
||||
id: 'url',
|
||||
@@ -431,7 +423,7 @@ export class ModelManager {
|
||||
}
|
||||
|
||||
this.selectedModels = selectedList;
|
||||
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install p-button p-component" mode="install">Install</button>`);
|
||||
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`);
|
||||
}
|
||||
|
||||
focusInstall(item) {
|
||||
@@ -481,15 +473,15 @@ export class ModelManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.install_context = {btn: btn, targets: target_items};
|
||||
|
||||
this.batch_id = generateUUID();
|
||||
batch['batch_id'] = this.batch_id;
|
||||
const batch_id = generateUUID();
|
||||
batch['batch_id'] = batch_id;
|
||||
this.install_contexts.set(batch_id, {btn: btn, targets: target_items, queued: false});
|
||||
|
||||
let failed;
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
@@ -499,13 +491,7 @@ export class ModelManager {
|
||||
errorMsg = `Failed to submit installation request: ${sanitizeHTML(String(error))}`;
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n" + errorMsg);
|
||||
btn.classList.remove("cmm-btn-loading");
|
||||
this.element.querySelectorAll(".cmm-btn-loading").forEach(button => {
|
||||
button.classList.remove("cmm-btn-loading");
|
||||
});
|
||||
this.hideLoading();
|
||||
this.hideStop();
|
||||
this.install_context = undefined;
|
||||
this.endInstall(batch_id);
|
||||
return;
|
||||
}
|
||||
for (const id of failed) {
|
||||
@@ -521,25 +507,99 @@ export class ModelManager {
|
||||
|
||||
// No queued work means the server will not send batch-done.
|
||||
if (target_items.every(item => failed.includes(item.originalData.id))) {
|
||||
this.element.querySelectorAll(".cmm-btn-loading").forEach(button => {
|
||||
button.classList.remove("cmm-btn-loading");
|
||||
});
|
||||
this.hideLoading();
|
||||
this.hideStop();
|
||||
this.install_context = undefined;
|
||||
this.endInstall(batch_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// The batch can end before its request is answered.
|
||||
const context = this.install_contexts.get(batch_id);
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.queued = true;
|
||||
this.showStop();
|
||||
|
||||
if (context.queue_ended) {
|
||||
this.endDroppedInstalls();
|
||||
}
|
||||
}
|
||||
|
||||
// Forget a pending install and return its button and rows to idle.
|
||||
// The Stop button goes with the last pending install.
|
||||
endInstall(batch_id) {
|
||||
const context = this.install_contexts.get(batch_id);
|
||||
if (!context) {
|
||||
return;
|
||||
}
|
||||
this.install_contexts.delete(batch_id);
|
||||
|
||||
context.btn.classList.remove("cmm-btn-loading");
|
||||
for (const item of context.targets) {
|
||||
this.grid.updateCell(item, "installed");
|
||||
}
|
||||
|
||||
if (this.install_contexts.size == 0) {
|
||||
this.hideLoading();
|
||||
this.hideStop();
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
// The end of the queue was reported: a batch that was queued and has not ended was dropped
|
||||
// by Stop. The report can also be that of a queue that ran before the batch was added, so
|
||||
// the installs are ended only if the queue is not running now.
|
||||
async endDroppedInstalls() {
|
||||
const queued = [...this.install_contexts].filter(([, context]) => context.queued);
|
||||
if (queued.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Without an answer the queue may still be running.
|
||||
const { data } = await fetchData('/v2/manager/queue/status');
|
||||
if (!data || data.is_processing) {
|
||||
return;
|
||||
}
|
||||
|
||||
let downloaded = false;
|
||||
for (const [batch_id, context] of queued) {
|
||||
if (this.endInstall(batch_id)) {
|
||||
downloaded ||= context.targets.some(item => item.refresh);
|
||||
}
|
||||
}
|
||||
if (downloaded) {
|
||||
this.showRefresh();
|
||||
this.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
|
||||
}
|
||||
}
|
||||
|
||||
async onQueueStatus(event) {
|
||||
let self = ModelManager.instance;
|
||||
const detail = event.detail;
|
||||
|
||||
if(event.detail.status == 'in_progress' && event.detail.ui_target == 'model_manager') {
|
||||
const hash = event.detail.target;
|
||||
if (!self) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (detail.status == 'all-done') {
|
||||
// An install whose request is not answered yet is looked at when it is.
|
||||
for (const context of self.install_contexts.values()) {
|
||||
context.queue_ended = !context.queued;
|
||||
}
|
||||
self.endDroppedInstalls();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!self.install_contexts.has(detail.batch_id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(detail.status == 'in_progress' && detail.ui_target == 'model_manager') {
|
||||
const hash = detail.target;
|
||||
|
||||
const item = self.grid.getRowItemBy("hash", hash);
|
||||
if (!item) return;
|
||||
|
||||
item.refresh = true;
|
||||
self.grid.setRowSelected(item, false);
|
||||
@@ -547,29 +607,20 @@ export class ModelManager {
|
||||
// self.grid.updateCell(item, "tg-column-select");
|
||||
self.grid.updateRow(item);
|
||||
}
|
||||
else if(event.detail.status == 'batch-done') {
|
||||
self.hideStop();
|
||||
self.onQueueCompleted(event.detail);
|
||||
else if(detail.status == 'batch-done') {
|
||||
self.onQueueCompleted(detail);
|
||||
}
|
||||
}
|
||||
|
||||
async onQueueCompleted(info) {
|
||||
let result = info.model_result;
|
||||
|
||||
if(result.length == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let self = ModelManager.instance;
|
||||
|
||||
if(!self.install_context) {
|
||||
if(!self?.install_contexts.has(info.batch_id)) {
|
||||
return;
|
||||
}
|
||||
self.endInstall(info.batch_id);
|
||||
|
||||
let btn = self.install_context.btn;
|
||||
|
||||
self.hideLoading();
|
||||
btn.classList.remove("cmm-btn-loading");
|
||||
const result = info.model_result ?? {};
|
||||
|
||||
let errorMsg = "";
|
||||
|
||||
@@ -580,23 +631,19 @@ export class ModelManager {
|
||||
errorMsg += sanitizeHTML(String(v)) + '\n';
|
||||
}
|
||||
|
||||
for(let k in self.install_context.targets) {
|
||||
let item = self.install_context.targets[k];
|
||||
self.grid.updateCell(item, "installed");
|
||||
}
|
||||
|
||||
if (errorMsg) {
|
||||
self.showError(errorMsg);
|
||||
show_message("Installation Error:\n"+errorMsg);
|
||||
} else {
|
||||
self.showStatus(`Install ${result.length} models successfully`);
|
||||
self.showStatus(`Install ${Object.keys(result).length} models successfully`);
|
||||
}
|
||||
|
||||
self.showRefresh();
|
||||
self.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
|
||||
if (!errorMsg) {
|
||||
self.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
|
||||
}
|
||||
|
||||
infoToast('Tasks done', `[ComfyUI-Manager] All model downloading tasks in the queue have been completed.\n${info.done_count}/${info.total_count}`);
|
||||
self.install_context = undefined;
|
||||
}
|
||||
|
||||
getModelList(models) {
|
||||
|
||||
@@ -92,6 +92,9 @@ function connect_inputs(nearest_inputs, node) {
|
||||
}
|
||||
|
||||
function node_info_copy(src, dest, connect_both, copy_shape) {
|
||||
// The graph the node is in. A subgraph keeps its own links and nodes.
|
||||
const graph = src.graph;
|
||||
|
||||
// copy input connections
|
||||
for(let i in src.inputs) {
|
||||
let input = src.inputs[i];
|
||||
@@ -100,9 +103,19 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
|
||||
dest.convertWidgetToInput(destWidget);
|
||||
}
|
||||
if(input.link) {
|
||||
let link = app.graph.links[input.link];
|
||||
let src_node = app.graph.getNodeById(link.origin_id);
|
||||
src_node.connect(link.origin_slot, dest.id, input.name);
|
||||
let link = graph.links[input.link];
|
||||
if(link.origin_id === graph.inputNode?.id) {
|
||||
// The link starts at an input of the subgraph, which is not a node of the graph.
|
||||
// Unlike a node's connect(), it takes any input, so the checks are made here.
|
||||
let subgraph_input = graph.inputNode.slots[link.origin_slot];
|
||||
let dest_input = dest.inputs[dest.findInputSlot(input.name)];
|
||||
if(dest_input && LiteGraph.isValidConnection(subgraph_input.type, dest_input.type))
|
||||
subgraph_input.connect(dest_input, dest);
|
||||
}
|
||||
else {
|
||||
let src_node = graph.getNodeById(link.origin_id);
|
||||
src_node.connect(link.origin_slot, dest, input.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,7 +127,7 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
|
||||
if(output.links) {
|
||||
let links = [];
|
||||
for(let j in output.links) {
|
||||
links.push(app.graph.links[output.links[j]]);
|
||||
links.push(graph.links[output.links[j]]);
|
||||
}
|
||||
output_links[output.name] = links;
|
||||
}
|
||||
@@ -125,8 +138,14 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
|
||||
if(links) {
|
||||
for(let j in links) {
|
||||
let link = links[j];
|
||||
let target_node = app.graph.getNodeById(link.target_id);
|
||||
dest.connect(parseInt(i), target_node, link.target_slot);
|
||||
if(link.target_id === graph.outputNode?.id) {
|
||||
// The link ends at an output of the subgraph, whose connect() checks the type itself.
|
||||
graph.outputNode.slots[link.target_slot].connect(dest.outputs[i], dest);
|
||||
}
|
||||
else {
|
||||
let target_node = graph.getNodeById(link.target_id);
|
||||
dest.connect(parseInt(i), target_node, link.target_slot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,30 +6,43 @@ import { buildGuiFrame } from "./comfyui-gui-builder.js";
|
||||
|
||||
loadCss("./snapshot.css");
|
||||
|
||||
// The server gives its reason as plain text, and most refusals carry none.
|
||||
// For those, and for the error page of a proxy, show the status line.
|
||||
async function failureReason(response) {
|
||||
const plain = (response.headers.get('Content-Type') || '').startsWith('text/plain');
|
||||
const text = plain ? await response.text() : '';
|
||||
return sanitizeHTML(text || `HTTP ${response.status} ${response.statusText}`.trim());
|
||||
}
|
||||
|
||||
async function restore_snapshot(target) {
|
||||
if(SnapshotManager.instance) {
|
||||
let scheduled = false;
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
|
||||
if(response.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if(response.status == 400) {
|
||||
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
|
||||
if(!response.ok) {
|
||||
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
app.ui.dialog.close();
|
||||
scheduled = true;
|
||||
return true;
|
||||
}
|
||||
catch(exception) {
|
||||
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
|
||||
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
|
||||
return false;
|
||||
}
|
||||
finally {
|
||||
await SnapshotManager.instance.invalidateControl();
|
||||
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='p-button p-component'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
|
||||
if(scheduled) {
|
||||
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-ui-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,22 +50,23 @@ async function restore_snapshot(target) {
|
||||
async function remove_snapshot(target) {
|
||||
if(SnapshotManager.instance) {
|
||||
try {
|
||||
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
|
||||
if(response.status == 403) {
|
||||
show_message('This action is not allowed with this security level configuration.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if(response.status == 400) {
|
||||
show_message(`Remove snapshot failed: ${target.title} / ${exception}`);
|
||||
if(!response.ok) {
|
||||
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
app.ui.dialog.close();
|
||||
return true;
|
||||
}
|
||||
catch(exception) {
|
||||
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
|
||||
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
|
||||
return false;
|
||||
}
|
||||
finally {
|
||||
@@ -63,7 +77,7 @@ async function remove_snapshot(target) {
|
||||
|
||||
async function save_current_snapshot() {
|
||||
try {
|
||||
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', cache: "no-store" });
|
||||
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
|
||||
app.ui.dialog.close();
|
||||
return true;
|
||||
}
|
||||
@@ -122,7 +136,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
|
||||
createControls() {
|
||||
return [
|
||||
$el("button.p-button.p-component", {
|
||||
$el("button.cm-ui-button", {
|
||||
type: "button",
|
||||
textContent: "Close",
|
||||
onclick: () => { this.close(); }
|
||||
@@ -220,7 +234,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
data_button.className = "data-btns";
|
||||
|
||||
var restoreBtn = document.createElement('button');
|
||||
restoreBtn.className = "snapshot-restore-btn p-button p-component";
|
||||
restoreBtn.className = "snapshot-restore-btn cm-ui-button";
|
||||
restoreBtn.innerHTML = 'Restore';
|
||||
restoreBtn.style.width = "100px";
|
||||
|
||||
@@ -229,7 +243,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
});
|
||||
|
||||
var removeBtn = document.createElement('button');
|
||||
removeBtn.className = "snapshot-remove-btn p-button p-component";
|
||||
removeBtn.className = "snapshot-remove-btn cm-ui-button";
|
||||
removeBtn.innerHTML = 'Remove';
|
||||
removeBtn.style.width = "100px";
|
||||
|
||||
@@ -279,7 +293,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
|
||||
async createBottomControls() {
|
||||
var save_button = document.createElement("button");
|
||||
save_button.className = "p-button p-component";
|
||||
save_button.className = "cm-ui-button";
|
||||
save_button.innerHTML = "Save snapshot";
|
||||
save_button.onclick = () => { save_current_snapshot(); }
|
||||
save_button.style.horizontalAlign = "right";
|
||||
|
||||
@@ -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();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,7 @@ from ..common import cm_global
|
||||
from ..common import manager_downloader
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from ..common.git_compat import setup_git_environment
|
||||
|
||||
|
||||
logging.info(f"### Loading: ComfyUI-Manager ({core.version_str})")
|
||||
@@ -140,7 +141,7 @@ def _dedicated_install_allowed(flag_key: str) -> bool:
|
||||
|
||||
async def get_risky_level(files, pip_packages):
|
||||
json_data1 = await core.get_data_by_mode('local', 'custom-node-list.json')
|
||||
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url='https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main')
|
||||
json_data2 = await core.get_data_by_mode('cache', 'custom-node-list.json', channel_url=core.DEFAULT_CHANNEL)
|
||||
|
||||
all_urls = set()
|
||||
for x in json_data1['custom_nodes'] + json_data2['custom_nodes']:
|
||||
@@ -162,8 +163,10 @@ async def get_risky_level(files, pip_packages):
|
||||
|
||||
|
||||
class ManagerFuncsInComfyUI(core.ManagerFuncs):
|
||||
def is_flagged_install_allowed(self):
|
||||
return core.get_config()['allow_flagged_nodepack_install'] or manager_security.is_loopback_listener(args.listen)
|
||||
def is_flagged_install_allowed(self, node_id):
|
||||
return manager_security.is_cnr_install_allowed(
|
||||
'NodeVersionStatusFlagged', core.get_config()['allow_flagged_nodepack_install'], args.listen,
|
||||
node_id=node_id, manager_files_path=context.manager_files_path)
|
||||
|
||||
def run_script(self, cmd, cwd='.'):
|
||||
if len(cmd) > 0 and cmd[0].startswith("#"):
|
||||
@@ -192,15 +195,22 @@ context.comfy_path = os.path.dirname(folder_paths.__file__)
|
||||
core.js_path = os.path.join(context.comfy_path, "web", "extensions")
|
||||
|
||||
local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
|
||||
local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
|
||||
local_db_custom_node_list = os.path.join(manager_util.comfyui_manager_path, "custom-node-list.json")
|
||||
local_db_extension_node_mappings = os.path.join(manager_util.comfyui_manager_path, "extension-node-map.json")
|
||||
|
||||
|
||||
ALLOWED_UPDATE_POLICIES = ('stable', 'stable-comfyui', 'nightly', 'nightly-comfyui')
|
||||
ALLOWED_DB_MODES = ('cache', 'channel', 'local', 'remote')
|
||||
|
||||
|
||||
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():
|
||||
@@ -261,14 +271,13 @@ def print_comfyui_version():
|
||||
|
||||
|
||||
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_git_environment(git_exe)
|
||||
|
||||
|
||||
setup_environment()
|
||||
@@ -344,34 +353,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 = {}
|
||||
|
||||
@@ -449,6 +430,11 @@ temp_queue_batch = []
|
||||
task_batch_queue = deque()
|
||||
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()
|
||||
aborted_batch = None
|
||||
|
||||
|
||||
@@ -465,6 +451,11 @@ def finalize_temp_queue_batch(batch_json=None, failed=None):
|
||||
temp_queue_batch = []
|
||||
|
||||
|
||||
def replaces_cnr_with_nightly(node_id):
|
||||
unified = core.unified_manager
|
||||
return unified.is_enabled(node_id, 'cnr') and unified.resolve_unspecified_version(node_id, guess_mode='inactive') == 'nightly'
|
||||
|
||||
|
||||
async def task_worker():
|
||||
global task_queue
|
||||
global tasks_in_progress
|
||||
@@ -506,8 +497,15 @@ async def task_worker():
|
||||
|
||||
async def do_enable(item) -> str:
|
||||
ui_id, cnr_id = item
|
||||
core.unified_manager.unified_enable(cnr_id)
|
||||
return 'success'
|
||||
if replaces_cnr_with_nightly(cnr_id) and not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return 'failed'
|
||||
res = core.unified_manager.unified_enable(cnr_id)
|
||||
if res.result:
|
||||
return 'success'
|
||||
|
||||
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
|
||||
return f"Failed to enable: '{cnr_id}'"
|
||||
|
||||
async def do_update(item):
|
||||
ui_id, node_name, node_ver = item
|
||||
@@ -520,7 +518,7 @@ async def task_worker():
|
||||
# None when git_utils.git_url() in manager_core can't determine
|
||||
# the remote URL. Downstream branches at L504/507 already
|
||||
# handle url is None, so we just need a None-safe title.
|
||||
url = core.unified_manager.unknown_active_nodes[node_name][0]
|
||||
url = core.unified_manager.unknown_active_nodes.get(node_name, (None,))[0]
|
||||
title = os.path.basename(url) if url else node_name
|
||||
else:
|
||||
url = core.unified_manager.cnr_map[node_name].get('repository')
|
||||
@@ -542,7 +540,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()
|
||||
@@ -625,9 +623,10 @@ async def task_worker():
|
||||
try:
|
||||
res = core.unified_manager.unified_disable(node_name, is_unknown)
|
||||
|
||||
if res:
|
||||
if res.result:
|
||||
return 'success'
|
||||
|
||||
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
|
||||
@@ -715,6 +714,10 @@ async def task_worker():
|
||||
kind, item = cur_batch.get_next()
|
||||
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)
|
||||
@@ -773,6 +776,10 @@ async def task_worker():
|
||||
|
||||
@routes.post("/v2/manager/queue/batch")
|
||||
async def queue_batch(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
failed = set()
|
||||
@@ -800,7 +807,8 @@ async def queue_batch(request):
|
||||
failed.add(x['id'])
|
||||
|
||||
elif k == 'update_comfyui':
|
||||
await update_comfyui(None)
|
||||
if v:
|
||||
_update_comfyui()
|
||||
|
||||
elif k == 'disable':
|
||||
for x in v:
|
||||
@@ -900,34 +908,19 @@ async def fetch_customnode_mappings(request):
|
||||
|
||||
@routes.get("/v2/customnode/fetch_updates")
|
||||
async def fetch_updates(request):
|
||||
try:
|
||||
if request.rel_url.query["mode"] == "local":
|
||||
channel = 'local'
|
||||
else:
|
||||
channel = core.get_config()['channel_url']
|
||||
|
||||
await core.unified_manager.reload(request.rel_url.query["mode"])
|
||||
await core.unified_manager.get_custom_nodes(channel, request.rel_url.query["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 Exception:
|
||||
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 /v2/customnode/check_update.",
|
||||
"deprecated": True,
|
||||
},
|
||||
status=410,
|
||||
)
|
||||
|
||||
|
||||
@routes.post("/v2/manager/queue/update_all")
|
||||
async def update_all(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
json_data = dict(request.rel_url.query)
|
||||
@@ -969,6 +962,9 @@ async def _update_all(json_data):
|
||||
if os.environ.get('__COMFYUI_DESKTOP_VERSION__'):
|
||||
continue
|
||||
|
||||
if v[1] in core.unified_manager.invalid_installations:
|
||||
continue
|
||||
|
||||
update_item = k, k, 'unknown'
|
||||
temp_queue_batch.append(("update-main", update_item))
|
||||
|
||||
@@ -1065,16 +1061,79 @@ async def installed_list(request):
|
||||
return web.json_response(res, content_type='application/json')
|
||||
|
||||
|
||||
@routes.post("/v2/customnode/check_update")
|
||||
async def check_update(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
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("/v2/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:
|
||||
@@ -1087,8 +1146,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)
|
||||
|
||||
@@ -1104,7 +1161,7 @@ async def fetch_customnode_list(request):
|
||||
if channel != 'local':
|
||||
found = 'custom'
|
||||
|
||||
if channel == core.DEFAULT_CHANNEL or channel == core.DEFAULT_CHANNEL_LEGACY:
|
||||
if channel == core.DEFAULT_CHANNEL:
|
||||
channel = 'default'
|
||||
else:
|
||||
for name, url in core.get_channel_dict().items():
|
||||
@@ -1119,21 +1176,6 @@ async def fetch_customnode_list(request):
|
||||
return web.json_response(result, content_type='application/json')
|
||||
|
||||
|
||||
@routes.get("/customnode/alternatives")
|
||||
async def fetch_customnode_alternatives(request):
|
||||
alter_json = await core.get_data_by_mode(request.rel_url.query["mode"], 'alter-list.json')
|
||||
|
||||
res = {}
|
||||
|
||||
for item in alter_json['items']:
|
||||
populate_markdown(item)
|
||||
res[item['id']] = item
|
||||
|
||||
res = core.map_to_unified_keys(res)
|
||||
|
||||
return web.json_response(res, content_type='application/json')
|
||||
|
||||
|
||||
def check_model_installed(json_obj):
|
||||
def is_exists(model_dir_name, filename, url):
|
||||
if filename == '<huggingface>':
|
||||
@@ -1212,7 +1254,7 @@ async def get_snapshot_list(request):
|
||||
|
||||
@routes.post("/v2/snapshot/remove")
|
||||
async def remove_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -1238,11 +1280,11 @@ async def remove_snapshot(request):
|
||||
|
||||
@routes.post("/v2/snapshot/restore")
|
||||
async def restore_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
if not is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
|
||||
try:
|
||||
@@ -1280,7 +1322,7 @@ async def get_current_snapshot_api(request):
|
||||
|
||||
@routes.post("/v2/snapshot/save")
|
||||
async def save_snapshot(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
try:
|
||||
@@ -1311,7 +1353,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.")
|
||||
@@ -1347,6 +1389,10 @@ async def get_disabled_versions(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info")
|
||||
async def import_fail_info(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
if 'cnr_id' in json_data:
|
||||
@@ -1364,6 +1410,10 @@ async def import_fail_info(request):
|
||||
|
||||
@routes.post("/v2/customnode/import_fail_info_bulk")
|
||||
async def import_fail_info_bulk(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
try:
|
||||
json_data = await request.json()
|
||||
|
||||
@@ -1423,7 +1473,7 @@ async def import_fail_info_bulk(request):
|
||||
|
||||
@routes.post("/v2/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
global task_batch_queue
|
||||
@@ -1488,10 +1538,11 @@ async def _queue_node_install(json_data, operation):
|
||||
node_spec_str = f"{cnr_id}@{selected_version}"
|
||||
else:
|
||||
node_spec_str = f"{cnr_id}@nightly"
|
||||
git_url = [json_data.get('repository')]
|
||||
if git_url is None:
|
||||
logging.error(f"[ComfyUI-Manager] Following node pack doesn't provide `nightly` version: ${git_url}")
|
||||
return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
|
||||
try:
|
||||
git_url = [await core.unified_manager.get_git_install_url(cnr_id, 'nightly', json_data['channel'], json_data['mode'])]
|
||||
except (LookupError, core.InvalidChannel):
|
||||
logging.error(f"[ComfyUI-Manager] Following nodepack doesn't provide `nightly` version: {cnr_id}")
|
||||
return web.Response(status=404, text=f"Following nodepack doesn't provide `nightly` version: {cnr_id}")
|
||||
|
||||
elif json_data['version'] != 'unknown' and selected_version == 'unknown':
|
||||
logging.error(f"[ComfyUI-Manager] Invalid installation request: {json_data}")
|
||||
@@ -1534,7 +1585,7 @@ task_worker_thread:threading.Thread = None
|
||||
|
||||
@routes.post("/v2/manager/queue/start")
|
||||
async def queue_start(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
with task_worker_lock:
|
||||
@@ -1554,8 +1605,8 @@ def _queue_start():
|
||||
|
||||
|
||||
async def _fix_custom_node(json_data):
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_GENERAL)
|
||||
if not is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
|
||||
node_id = json_data.get('id')
|
||||
@@ -1574,6 +1625,10 @@ async def _fix_custom_node(json_data):
|
||||
|
||||
@routes.post("/v2/customnode/install/git_url")
|
||||
async def install_custom_node_git_url(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# goal265 S-A: dedicated-flag gate, decoupled from security_level (spec §1.2).
|
||||
if not _dedicated_install_allowed('allow_git_url_install'):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(
|
||||
@@ -1581,7 +1636,13 @@ async def install_custom_node_git_url(request):
|
||||
# Only the flag name goes on the wire; the full message is logged above.
|
||||
return web.json_response({'reason': 'allow_git_url_install'}, status=403)
|
||||
|
||||
url = await request.text()
|
||||
try:
|
||||
json_data = await request.json()
|
||||
url = json_data['url']
|
||||
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)
|
||||
|
||||
if res.action == 'skip':
|
||||
@@ -1597,6 +1658,10 @@ async def install_custom_node_git_url(request):
|
||||
|
||||
@routes.post("/v2/customnode/install/pip")
|
||||
async def install_custom_node_pip(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# goal265 S-B: dedicated-flag gate, decoupled from security_level (spec §1.2).
|
||||
if not _dedicated_install_allowed('allow_pip_install'):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_PIP.format(
|
||||
@@ -1604,7 +1669,13 @@ async def install_custom_node_pip(request):
|
||||
# Only the flag name goes on the wire; the full message is logged above.
|
||||
return web.json_response({'reason': 'allow_pip_install'}, status=403)
|
||||
|
||||
packages = await request.text()
|
||||
try:
|
||||
json_data = await request.json()
|
||||
packages = json_data['packages']
|
||||
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(' '))
|
||||
|
||||
return web.Response(status=200)
|
||||
@@ -1650,31 +1721,35 @@ async def _update_custom_node(json_data):
|
||||
|
||||
@routes.post("/v2/manager/queue/update_comfyui")
|
||||
async def update_comfyui(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
|
||||
temp_queue_batch.append(("update-comfyui", ('comfyui', is_stable)))
|
||||
_update_comfyui()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
def _update_comfyui():
|
||||
is_stable = core.get_config()['update_policy'] not in ('nightly', 'nightly-comfyui')
|
||||
temp_queue_batch.append(("update-comfyui", ('comfyui', is_stable)))
|
||||
|
||||
|
||||
@routes.get("/v2/comfyui_manager/comfyui_versions")
|
||||
async def comfyui_versions(request):
|
||||
try:
|
||||
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("/v2/comfyui_manager/comfyui_switch_version")
|
||||
async def comfyui_switch_version(request):
|
||||
# Body-reading handler — Content-Type gate omitted per
|
||||
# comfyui_manager/common/manager_security.py module policy: a cross-origin
|
||||
# <form method=POST> cannot forge a valid application/json body because
|
||||
# the browser would trigger a CORS preflight that this server refuses.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('high+'):
|
||||
logging.error(SECURITY_MESSAGE_HIGH_P)
|
||||
return web.Response(status=403)
|
||||
@@ -1689,7 +1764,7 @@ async def comfyui_switch_version(request):
|
||||
except json.JSONDecodeError:
|
||||
return web.Response(status=400, text="Invalid JSON body")
|
||||
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)
|
||||
|
||||
|
||||
@@ -1711,13 +1786,13 @@ async def check_whitelist_for_model(item):
|
||||
json_obj = await core.get_data_by_mode('cache', 'model-list.json')
|
||||
|
||||
for x in json_obj.get('models', []):
|
||||
if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
|
||||
if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename'] and x.get('url') == item.get('url'):
|
||||
return True
|
||||
|
||||
json_obj = await core.get_data_by_mode('local', 'model-list.json')
|
||||
|
||||
for x in json_obj.get('models', []):
|
||||
if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename']:
|
||||
if x['save_path'] == item['save_path'] and x['base'] == item['base'] and x['filename'] == item['filename'] and x.get('url') == item.get('url'):
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -1725,6 +1800,10 @@ async def check_whitelist_for_model(item):
|
||||
|
||||
@routes.post("/v2/manager/queue/install_model")
|
||||
async def install_model(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
return await _install_model(json_data)
|
||||
|
||||
@@ -1765,11 +1844,12 @@ async def db_mode(request):
|
||||
|
||||
@routes.post("/v2/manager/db_mode")
|
||||
async def set_db_mode_api(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
# Config writes are at the same risk tier as uninstall/update — apply the
|
||||
# 'middle' gate consistent with snapshot/remove, etc. Content-Type gate is
|
||||
# NOT applied here: this handler consumes application/json and a
|
||||
# cross-origin <form method=POST> cannot forge that without triggering
|
||||
# CORS preflight (see module docstring in common/manager_security.py).
|
||||
# 'middle' gate consistent with snapshot/remove, etc.
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1778,8 +1858,10 @@ async def set_db_mode_api(request):
|
||||
set_db_mode(data['value'])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
|
||||
|
||||
@routes.get("/v2/manager/policy/update")
|
||||
@@ -1789,7 +1871,10 @@ async def update_policy(request):
|
||||
|
||||
@routes.post("/v2/manager/policy/update")
|
||||
async def set_update_policy_api(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1798,8 +1883,10 @@ async def set_update_policy_api(request):
|
||||
set_update_policy(data['value'])
|
||||
core.write_config()
|
||||
return web.Response(status=200)
|
||||
except (json.JSONDecodeError, KeyError):
|
||||
except (json.JSONDecodeError, KeyError, TypeError):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
except ValueError as e:
|
||||
return web.Response(status=400, text=str(e))
|
||||
|
||||
|
||||
@routes.get("/v2/manager/channel_url_list")
|
||||
@@ -1820,7 +1907,10 @@ async def channel_url_list(request):
|
||||
|
||||
@routes.post("/v2/manager/channel_url_list")
|
||||
async def set_channel_url(request):
|
||||
# See set_db_mode_api above for gate rationale.
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403)
|
||||
@@ -1849,53 +1939,57 @@ async def get_notice(request):
|
||||
url = "github.com"
|
||||
path = "/ltdrdata/ltdrdata.github.io/wiki/News"
|
||||
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.get(f"https://{url}{path}") as response:
|
||||
if response.status == 200:
|
||||
# html_content = response.read().decode('utf-8')
|
||||
html_content = await response.text()
|
||||
try:
|
||||
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')
|
||||
html_content = await response.text()
|
||||
|
||||
pattern = re.compile(r'<div class="markdown-body">([\s\S]*?)</div>')
|
||||
match = pattern.search(html_content)
|
||||
pattern = re.compile(r'<div class="markdown-body">([\s\S]*?)</div>')
|
||||
match = pattern.search(html_content)
|
||||
|
||||
if match:
|
||||
# Remote page content lands in innerHTML on the client:
|
||||
# keep formatting markup only.
|
||||
markdown_content = html_utils.sanitize_html_fragment(match.group(1))
|
||||
version_tag = os.environ.get('__COMFYUI_DESKTOP_VERSION__')
|
||||
if version_tag is not None:
|
||||
markdown_content += f"<HR>ComfyUI: {version_tag} [Desktop]"
|
||||
else:
|
||||
version_tag = context.get_comfyui_tag()
|
||||
if version_tag is None:
|
||||
markdown_content += f"<HR>ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
|
||||
if match:
|
||||
# Remote page content lands in innerHTML on the client:
|
||||
# keep formatting markup only.
|
||||
markdown_content = html_utils.sanitize_html_fragment(match.group(1))
|
||||
version_tag = os.environ.get('__COMFYUI_DESKTOP_VERSION__')
|
||||
if version_tag is not None:
|
||||
markdown_content += f"<HR>ComfyUI: {version_tag} [Desktop]"
|
||||
else:
|
||||
markdown_content += (f"<HR>ComfyUI: {version_tag}<BR>"
|
||||
f" ({core.comfy_ui_commit_datetime.date()})")
|
||||
# markdown_content += f"<BR> ()"
|
||||
markdown_content += f"<BR>Manager: {core.version_str}"
|
||||
version_tag = context.get_comfyui_tag()
|
||||
if version_tag is None:
|
||||
markdown_content += f"<HR>ComfyUI: {core.comfy_ui_revision}[{comfy_ui_hash[:6]}]({core.comfy_ui_commit_datetime.date()})"
|
||||
else:
|
||||
markdown_content += (f"<HR>ComfyUI: {version_tag}<BR>"
|
||||
f" ({core.comfy_ui_commit_datetime.date()})")
|
||||
# markdown_content += f"<BR> ()"
|
||||
markdown_content += f"<BR>Manager: {core.version_str}"
|
||||
|
||||
try:
|
||||
if '__COMFYUI_DESKTOP_VERSION__' not in os.environ:
|
||||
if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
|
||||
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
|
||||
elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
|
||||
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if '__COMFYUI_DESKTOP_VERSION__' not in os.environ:
|
||||
if core.comfy_ui_commit_datetime == datetime(1900, 1, 1, 0, 0, 0):
|
||||
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI isn\'t git repo.</P>' + markdown_content
|
||||
elif core.comfy_ui_required_commit_datetime.date() > core.comfy_ui_commit_datetime.date():
|
||||
markdown_content = '<P style="text-align: center; color:red; background-color:white; font-weight:bold">Your ComfyUI is too OUTDATED!!!</P>' + markdown_content
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return web.Response(text=markdown_content, status=200)
|
||||
return web.Response(text=markdown_content, status=200)
|
||||
else:
|
||||
return web.Response(text="Unable to retrieve Notice", status=200)
|
||||
else:
|
||||
return web.Response(text="Unable to retrieve Notice", status=200)
|
||||
else:
|
||||
return web.Response(text="Unable to retrieve Notice", status=200)
|
||||
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
|
||||
logging.warning(f"[ComfyUI-Manager] Unable to retrieve Notice: {type(e).__name__}: {e}")
|
||||
return web.Response(text="Unable to retrieve Notice", status=200)
|
||||
|
||||
|
||||
# legacy /manager/notice
|
||||
|
||||
@routes.post("/v2/manager/reboot")
|
||||
def restart(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
if not is_allowed_security_level('middle'):
|
||||
@@ -1916,17 +2010,7 @@ def restart(request):
|
||||
|
||||
print("\nRestarting... [Legacy Mode]\n\n") # This printing should not be logging - that will be ugly
|
||||
|
||||
sys_argv = sys.argv.copy()
|
||||
if '--windows-standalone-build' in sys_argv:
|
||||
sys_argv.remove('--windows-standalone-build')
|
||||
|
||||
if sys_argv[0].endswith("__main__.py"): # this is a python module
|
||||
module_name = os.path.basename(os.path.dirname(sys_argv[0]))
|
||||
cmds = [sys.executable, '-m', module_name] + sys_argv[1:]
|
||||
elif sys.platform.startswith('win32'):
|
||||
cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
|
||||
else:
|
||||
cmds = [sys.executable] + sys_argv
|
||||
cmds = manager_util.build_restart_command(sys.argv, drop_args=('--windows-standalone-build',))
|
||||
|
||||
print(f"Command: {cmds}", flush=True)
|
||||
|
||||
@@ -1974,10 +2058,8 @@ async def default_cache_update():
|
||||
|
||||
json_obj = await manager_util.get_data(uri, True)
|
||||
|
||||
with manager_util.cache_lock:
|
||||
with open(cache_uri, "w", encoding='utf-8') as file:
|
||||
json.dump(json_obj, file, indent=4, sort_keys=True)
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
if manager_util.write_cache_file(cache_uri, json_obj):
|
||||
logging.info(f"[ComfyUI-Manager] default cache updated: {uri}")
|
||||
except Exception as e:
|
||||
logging.error(f"[ComfyUI-Manager] Failed to perform initial fetching '{filename}': {e}")
|
||||
traceback.print_exc()
|
||||
@@ -1986,13 +2068,13 @@ 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)
|
||||
@@ -2000,6 +2082,7 @@ async def default_cache_update():
|
||||
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.")
|
||||
|
||||
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import mimetypes
|
||||
from ..common import context
|
||||
from ..common import manager_security
|
||||
from . import manager_core as core
|
||||
|
||||
import os
|
||||
from aiohttp import web
|
||||
import aiohttp
|
||||
import json
|
||||
import hashlib
|
||||
|
||||
import folder_paths
|
||||
from server import PromptServer
|
||||
@@ -22,69 +21,33 @@ except Exception:
|
||||
matrix_nio_is_available = False
|
||||
|
||||
|
||||
def extract_model_file_names(json_data):
|
||||
"""Extract unique file names from the input JSON data."""
|
||||
file_names = set()
|
||||
model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
|
||||
|
||||
# Recursively search for file names in the JSON data
|
||||
def recursive_search(data):
|
||||
if isinstance(data, dict):
|
||||
for value in data.values():
|
||||
recursive_search(value)
|
||||
elif isinstance(data, list):
|
||||
for item in data:
|
||||
recursive_search(item)
|
||||
elif isinstance(data, str) and '.' in data:
|
||||
file_names.add(os.path.basename(data)) # file_names.add(data)
|
||||
|
||||
recursive_search(json_data)
|
||||
return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
|
||||
|
||||
|
||||
def find_file_paths(base_dir, file_names):
|
||||
"""Find the paths of the files in the base directory."""
|
||||
file_paths = {}
|
||||
|
||||
for root, dirs, files in os.walk(base_dir):
|
||||
# Exclude certain directories
|
||||
dirs[:] = [d for d in dirs if d not in ['.git']]
|
||||
|
||||
for file in files:
|
||||
if file in file_names:
|
||||
file_paths[file] = os.path.join(root, file)
|
||||
return file_paths
|
||||
|
||||
|
||||
def compute_sha256_checksum(filepath):
|
||||
"""Compute the SHA256 checksum of a file, in chunks"""
|
||||
sha256 = hashlib.sha256()
|
||||
with open(filepath, 'rb') as f:
|
||||
for chunk in iter(lambda: f.read(4096), b''):
|
||||
sha256.update(chunk)
|
||||
return sha256.hexdigest()
|
||||
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/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("/v2/manager/share_option")
|
||||
async def set_share_option(request):
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
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 get_openart_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
|
||||
openart_key = f.read().strip()
|
||||
return openart_key if openart_key else None
|
||||
except Exception:
|
||||
return None
|
||||
def is_matrix_org(homeserver):
|
||||
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
|
||||
|
||||
|
||||
def get_matrix_auth():
|
||||
@@ -94,7 +57,7 @@ def get_matrix_auth():
|
||||
with open(os.path.join(context.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,
|
||||
@@ -105,101 +68,12 @@ def get_matrix_auth():
|
||||
return None
|
||||
|
||||
|
||||
def get_comfyworkflows_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
|
||||
share_key = f.read()
|
||||
if not share_key.strip():
|
||||
return None
|
||||
return share_key
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def get_youml_settings():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
|
||||
return None
|
||||
try:
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
|
||||
youml_settings = f.read().strip()
|
||||
return youml_settings if youml_settings else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def set_youml_settings(settings):
|
||||
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
|
||||
f.write(settings)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_openart_auth")
|
||||
async def api_get_openart_auth(request):
|
||||
# print("Getting stored Matrix credentials...")
|
||||
openart_key = get_openart_auth()
|
||||
if not openart_key:
|
||||
return web.Response(status=404)
|
||||
return web.json_response({"openart_key": openart_key})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/set_openart_auth")
|
||||
async def api_set_openart_auth(request):
|
||||
json_data = await request.json()
|
||||
openart_key = json_data['openart_key']
|
||||
with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
|
||||
f.write(openart_key)
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/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("/v2/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("/v2/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)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_comfyworkflows_auth")
|
||||
async def api_get_comfyworkflows_auth(request):
|
||||
# Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
|
||||
# in the same directory as the ComfyUI base folder
|
||||
# print("Getting stored Comfyworkflows.com auth...")
|
||||
comfyworkflows_auth = get_comfyworkflows_auth()
|
||||
if not comfyworkflows_auth:
|
||||
return web.Response(status=404)
|
||||
return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
|
||||
async def set_esheep_workflow_and_images(request):
|
||||
json_data = await request.json()
|
||||
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
|
||||
json.dump(json_data, file, indent=4)
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
|
||||
async def get_esheep_workflow_and_images(request):
|
||||
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
|
||||
data = json.load(file)
|
||||
return web.Response(status=200, text=json.dumps(data))
|
||||
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
@@ -211,42 +85,42 @@ async def get_matrix_dep_status(request):
|
||||
|
||||
|
||||
def set_matrix_auth(json_data):
|
||||
homeserver = json_data['homeserver']
|
||||
username = json_data['username']
|
||||
password = json_data['password']
|
||||
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
|
||||
f.write("\n".join([homeserver, username, password]))
|
||||
|
||||
|
||||
def set_comfyworkflows_auth(comfyworkflows_sharekey):
|
||||
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
|
||||
f.write(comfyworkflows_sharekey)
|
||||
path = os.path.join(context.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):
|
||||
return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
|
||||
|
||||
|
||||
def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
|
||||
return comfyworkflows_sharekey.strip()
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/v2/manager/share")
|
||||
async def share_art(request):
|
||||
# get json data
|
||||
rejection = manager_security.reject_non_json_post(request)
|
||||
if rejection is not None:
|
||||
return rejection
|
||||
|
||||
json_data = await request.json()
|
||||
|
||||
matrix_auth = json_data['matrix_auth']
|
||||
comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
|
||||
|
||||
set_matrix_auth(matrix_auth)
|
||||
set_comfyworkflows_auth(comfyworkflows_sharekey)
|
||||
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']
|
||||
title = json_data['title']
|
||||
description = json_data['description']
|
||||
is_nsfw = json_data['is_nsfw']
|
||||
prompt = json_data['prompt']
|
||||
potential_outputs = json_data['potential_outputs']
|
||||
selected_output_index = json_data['selected_output_index']
|
||||
@@ -275,79 +149,20 @@ async def share_art(request):
|
||||
else:
|
||||
asset_filepath = os.path.join(output_dir, asset_filename)
|
||||
|
||||
# The filename and the subfolder come from the request: share only a file in that directory.
|
||||
# Like ComfyUI's /view, this follows a symlink that the user placed in the directory.
|
||||
output_dir = os.path.abspath(output_dir)
|
||||
asset_filepath = os.path.abspath(asset_filepath)
|
||||
try:
|
||||
is_inside = os.path.commonpath((output_dir, asset_filepath)) == output_dir
|
||||
except ValueError: # on Windows, a path on another drive
|
||||
is_inside = False
|
||||
if not is_inside:
|
||||
return web.json_response({"error": "The selected output is not in the output directory."}, content_type='application/json', status=400)
|
||||
|
||||
# get the mime type of the asset
|
||||
assetFileType = mimetypes.guess_type(asset_filepath)[0]
|
||||
|
||||
share_website_host = "UNKNOWN"
|
||||
if "comfyworkflows" in share_destinations:
|
||||
share_website_host = "https://comfyworkflows.com"
|
||||
share_endpoint = f"{share_website_host}/api"
|
||||
|
||||
# get presigned urls
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.post(
|
||||
f"{share_endpoint}/get_presigned_urls",
|
||||
json={
|
||||
"assetFileName": asset_filename,
|
||||
"assetFileType": assetFileType,
|
||||
"workflowJsonFileName": 'workflow.json',
|
||||
"workflowJsonFileType": 'application/json',
|
||||
},
|
||||
) as resp:
|
||||
assert resp.status == 200
|
||||
presigned_urls_json = await resp.json()
|
||||
assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
|
||||
assetFileKey = presigned_urls_json["assetFileKey"]
|
||||
workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
|
||||
workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
|
||||
|
||||
# upload asset
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
|
||||
assert resp.status == 200
|
||||
|
||||
# upload workflow json
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
|
||||
assert resp.status == 200
|
||||
|
||||
model_filenames = extract_model_file_names(prompt['workflow'])
|
||||
model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
|
||||
|
||||
models_info = {}
|
||||
for filename, filepath in model_file_paths.items():
|
||||
models_info[filename] = {
|
||||
"filename": filename,
|
||||
"sha256_checksum": compute_sha256_checksum(filepath),
|
||||
"relative_path": os.path.relpath(filepath, folder_paths.base_path),
|
||||
}
|
||||
|
||||
# make a POST request to /api/upload_workflow with form data key values
|
||||
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
|
||||
form = aiohttp.FormData()
|
||||
if comfyworkflows_sharekey:
|
||||
form.add_field("shareKey", comfyworkflows_sharekey)
|
||||
form.add_field("source", "comfyui_manager")
|
||||
form.add_field("assetFileKey", assetFileKey)
|
||||
form.add_field("assetFileType", assetFileType)
|
||||
form.add_field("workflowJsonFileKey", workflowJsonFileKey)
|
||||
form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
|
||||
form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
|
||||
form.add_field("shareWorkflowCredits", credits)
|
||||
form.add_field("shareWorkflowTitle", title)
|
||||
form.add_field("shareWorkflowDescription", description)
|
||||
form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
|
||||
form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
|
||||
form.add_field("modelsInfo", json.dumps(models_info))
|
||||
|
||||
async with session.post(
|
||||
f"{share_endpoint}/upload_workflow",
|
||||
data=form,
|
||||
) as resp:
|
||||
assert resp.status == 200
|
||||
upload_workflow_json = await resp.json()
|
||||
workflowId = upload_workflow_json["workflowId"]
|
||||
|
||||
# check if the user has provided Matrix credentials
|
||||
if matrix_nio_is_available and "matrix" in share_destinations:
|
||||
comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
|
||||
@@ -355,14 +170,10 @@ async def share_art(request):
|
||||
content_type = assetFileType
|
||||
|
||||
try:
|
||||
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'])
|
||||
@@ -370,6 +181,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)
|
||||
@@ -442,9 +255,6 @@ async def share_art(request):
|
||||
return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
|
||||
|
||||
return web.json_response({
|
||||
"comfyworkflows": {
|
||||
"url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
|
||||
},
|
||||
"matrix": {
|
||||
"success": None if "matrix" not in share_destinations else True
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ from .common import security_check
|
||||
from .common import manager_util
|
||||
from .common import cm_global
|
||||
from .common import manager_downloader
|
||||
from .common import manager_security
|
||||
from .common.timestamp_utils import current_timestamp
|
||||
import folder_paths
|
||||
|
||||
@@ -67,6 +68,7 @@ comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
|
||||
|
||||
custom_nodes_base_path = folder_paths.get_folder_paths('custom_nodes')[0]
|
||||
manager_files_path = folder_paths.get_system_user_directory("manager")
|
||||
manager_security.ensure_nodepack_whitelist(manager_files_path)
|
||||
manager_pip_overrides_path = os.path.join(manager_files_path, "pip_overrides.json")
|
||||
manager_pip_blacklist_path = os.path.join(manager_files_path, "pip_blacklist.list")
|
||||
restore_snapshot_path = os.path.join(manager_files_path, "startup-scripts", "restore-snapshot.json")
|
||||
@@ -78,7 +80,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:
|
||||
@@ -99,7 +101,17 @@ def check_file_logging():
|
||||
enable_file_logging = False
|
||||
|
||||
|
||||
def set_git_executable():
|
||||
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
|
||||
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
|
||||
if git_exe != '':
|
||||
os.environ['GIT_EXE_PATH'] = git_exe
|
||||
|
||||
|
||||
read_config()
|
||||
set_git_executable()
|
||||
from .common import git_compat # noqa: E402
|
||||
print(git_compat.BACKEND_LINE, file=sys.stderr)
|
||||
read_uv_mode()
|
||||
read_unified_resolver_mode()
|
||||
security_check.security_check()
|
||||
@@ -124,15 +136,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()
|
||||
|
||||
|
||||
@@ -268,6 +271,7 @@ try:
|
||||
self.is_stdout = is_stdout
|
||||
self.encoding = "utf-8"
|
||||
self.last_char = ''
|
||||
self.console_is_gone = False
|
||||
|
||||
def fileno(self):
|
||||
try:
|
||||
@@ -280,7 +284,36 @@ try:
|
||||
raise ValueError("The object does not have a fileno method")
|
||||
|
||||
def isatty(self):
|
||||
return False
|
||||
# Delegate to the real console we wrap, not a hardcoded False.
|
||||
# Returning False here made colorama (and any ANSI-aware lib) believe
|
||||
# the stream is a pipe and strip every ANSI code from the print() path
|
||||
# in both the console and the file log. The console still receives the
|
||||
# text unchanged -- this only tells colorama the truth about the target.
|
||||
stream = original_stdout if self.is_stdout else original_stderr
|
||||
try:
|
||||
return stream.isatty()
|
||||
except (AttributeError, ValueError, OSError):
|
||||
return False
|
||||
|
||||
@property
|
||||
def closed(self):
|
||||
# Same reasoning as isatty(): without this attribute, colorama's
|
||||
# StreamWrapper.closed falls back to True (AttributeError -> closed),
|
||||
# which again forces strip=True. Report the real underlying state.
|
||||
if log_file.closed:
|
||||
# after close_log() nothing can be written through this logger;
|
||||
# colorama, which keeps it, would write its reset at exit
|
||||
return True
|
||||
|
||||
stream = original_stdout if self.is_stdout else original_stderr
|
||||
try:
|
||||
return stream.closed
|
||||
except AttributeError:
|
||||
# the output still goes to a stream that cannot say whether it is closed
|
||||
return False
|
||||
except ValueError:
|
||||
# a detached stream
|
||||
return True
|
||||
|
||||
def write(self, message):
|
||||
global is_start_mode
|
||||
@@ -312,36 +345,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:
|
||||
@@ -368,12 +415,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:
|
||||
@@ -394,8 +444,12 @@ try:
|
||||
try:
|
||||
message = record.getMessage()
|
||||
except Exception as e:
|
||||
message = f"<<logging error>>: {record} - {e}"
|
||||
original_stderr.write(message)
|
||||
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)
|
||||
@@ -486,53 +540,34 @@ script_list_path = os.path.join(manager_files_path, "startup-scripts", "install-
|
||||
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
|
||||
|
||||
|
||||
def is_installed(name):
|
||||
def is_installed(name, reinstall=False):
|
||||
name = name.strip()
|
||||
|
||||
if name.startswith('#'):
|
||||
return True
|
||||
|
||||
pattern = r'([^<>!~=]+)([<>!~=]=?)([0-9.a-zA-Z]*)'
|
||||
match = re.search(pattern, name)
|
||||
|
||||
if match:
|
||||
name = match.group(1)
|
||||
|
||||
if name in cm_global.pip_blacklist:
|
||||
reason = manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist)
|
||||
if reason is not None:
|
||||
if reason == 'downgrade blacklisted':
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
|
||||
return True
|
||||
|
||||
if name in cm_global.pip_downgrade_blacklist:
|
||||
pips = manager_util.get_installed_packages()
|
||||
pkg_name, extras, clauses = manager_util.parse_pip_spec(name)
|
||||
if extras:
|
||||
return False # extras to add: let pip decide
|
||||
|
||||
if match is None:
|
||||
if name in pips:
|
||||
return True
|
||||
elif match.group(2) in ['<=', '==', '<', '~=']:
|
||||
if name in pips:
|
||||
if manager_util.StrictVersion(pips[name]) >= manager_util.StrictVersion(match.group(3)):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
|
||||
return True
|
||||
if clauses and clauses[0][0] == '@':
|
||||
return not reinstall and manager_util.installed_from(clauses[0][1], pkg_name) is not None
|
||||
|
||||
pkg = manager_util.get_installed_packages().get(name.lower())
|
||||
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:
|
||||
return False # update if not installed
|
||||
|
||||
if match is None:
|
||||
return True # don't update if version is not specified
|
||||
|
||||
if match.group(2) in ['>', '>=']:
|
||||
if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
|
||||
return False
|
||||
elif manager_util.StrictVersion(pkg) > manager_util.StrictVersion(match.group(3)):
|
||||
print(f"[SKIP] Downgrading pip package isn't allowed: {name.lower()} (cur={pkg})")
|
||||
|
||||
if match.group(2) == '==':
|
||||
if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
|
||||
return False
|
||||
|
||||
if match.group(2) == '~=':
|
||||
if manager_util.StrictVersion(pkg) == manager_util.StrictVersion(match.group(3)):
|
||||
return False
|
||||
if manager_util.requires_newer_version(clauses, pkg):
|
||||
return False
|
||||
|
||||
return True # prevent downgrade
|
||||
|
||||
@@ -571,13 +606,14 @@ if os.path.exists(restore_snapshot_path):
|
||||
new_env['COMFYUI_PATH'] = os.path.dirname(folder_paths.__file__)
|
||||
|
||||
from comfy.cli_args import args
|
||||
from .common import manager_security
|
||||
|
||||
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
|
||||
new_env['_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED'] = str(
|
||||
allow_flagged or manager_security.is_loopback_listener(args.listen)
|
||||
).lower()
|
||||
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path]
|
||||
new_env['_COMFYUI_MANAGER_CNR_WHITELIST_DIR'] = manager_files_path
|
||||
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path,
|
||||
'--user-directory', manager_files_path, '--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:
|
||||
@@ -604,16 +640,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')
|
||||
@@ -630,14 +659,15 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
import uuid
|
||||
import shutil
|
||||
from comfy.cli_args import args
|
||||
from .common.manager_security import FLAGGED_NODEPACK_INSTALL_GUIDANCE, is_cnr_install_allowed
|
||||
|
||||
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
|
||||
if not is_cnr_install_allowed(status or 'NodeVersionStatusFlagged', allow_flagged, args.listen):
|
||||
if not manager_security.is_cnr_install_allowed(
|
||||
status or 'NodeVersionStatusFlagged', allow_flagged, args.listen,
|
||||
node_id=target, manager_files_path=manager_files_path):
|
||||
if not status:
|
||||
logging.error("Cannot execute reserved CNR switch for '%s': stored Registry status is missing. Request the installation again so its current status can be checked.", target)
|
||||
else:
|
||||
logging.error(FLAGGED_NODEPACK_INSTALL_GUIDANCE)
|
||||
logging.error(manager_security.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
|
||||
return False
|
||||
|
||||
# 1. download
|
||||
@@ -645,9 +675,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:
|
||||
@@ -656,32 +687,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)))
|
||||
@@ -744,26 +753,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:
|
||||
if 'pip' in script[1:] and 'install' in script[1:] and is_installed(script[-1]):
|
||||
reinstall = manager_util.is_reinstall(script[1:])
|
||||
requirement = manager_util.pip_install_requirement(script[1:])
|
||||
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]}")
|
||||
@@ -836,15 +853,7 @@ if script_executed:
|
||||
print("--------------------------------------------------------------------------\n")
|
||||
exit(0)
|
||||
else:
|
||||
sys_argv = sys.argv.copy()
|
||||
|
||||
if sys_argv[0].endswith("__main__.py"): # this is a python module
|
||||
module_name = os.path.basename(os.path.dirname(sys_argv[0]))
|
||||
cmds = [sys.executable, '-m', module_name] + sys_argv[1:]
|
||||
elif sys.platform.startswith('win32'):
|
||||
cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
|
||||
else:
|
||||
cmds = [sys.executable] + sys_argv
|
||||
cmds = manager_util.build_restart_command(sys.argv)
|
||||
|
||||
print(f"Command: {cmds}", flush=True)
|
||||
print("--------------------------------------------------------------------------\n")
|
||||
@@ -855,7 +864,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']
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ comfyui_manager/
|
||||
│ ├── manager_util.py # Existing: get_pip_cmd(), PIPFixer, use_uv flag
|
||||
│ ├── cm_global.py # Existing: pip_overrides, pip_blacklist (runtime dynamic assignment)
|
||||
│ └── unified_dep_resolver.py # New: Unified dependency resolution module
|
||||
├── prestartup_script.py # Existing: config reading, remap_pip_package, cm_global initialization
|
||||
├── prestartup_script.py # Existing: config reading, cm_global initialization
|
||||
└── legacy/
|
||||
└── manager_core.py # Legacy (not a modification target)
|
||||
cm_cli/
|
||||
@@ -199,6 +199,12 @@ def collect_requirements(self) -> CollectedDeps:
|
||||
sources = defaultdict(list)
|
||||
extra_index_urls = []
|
||||
|
||||
# Snapshot installed packages once; skipped when downgrade_blacklist is empty
|
||||
installed_snapshot = (
|
||||
manager_util.get_installed_packages()
|
||||
if self.downgrade_blacklist else {}
|
||||
)
|
||||
|
||||
for path in self.node_pack_paths:
|
||||
# Exclude disabled node packs (directory-based mechanism)
|
||||
# Disabled node packs are actually moved to custom_nodes/.disabled/,
|
||||
@@ -242,7 +248,7 @@ def collect_requirements(self) -> CollectedDeps:
|
||||
skipped.append((line, f"rejected: path separator in package name"))
|
||||
continue
|
||||
|
||||
# 2. Apply remap_pip_package (using cm_global.pip_overrides)
|
||||
# 2. Apply cm_global.pip_overrides
|
||||
pkg_spec = self._remap_package(line)
|
||||
|
||||
# 3. Blacklist check (cm_global.pip_blacklist)
|
||||
@@ -252,7 +258,7 @@ def collect_requirements(self) -> CollectedDeps:
|
||||
continue
|
||||
|
||||
# 4. Downgrade blacklist check (includes version comparison)
|
||||
if self._is_downgrade_blacklisted(pkg_name, pkg_spec):
|
||||
if self._is_downgrade_blacklisted(pkg_name, pkg_spec, installed_snapshot):
|
||||
skipped.append((pkg_spec, "downgrade blacklisted"))
|
||||
continue
|
||||
|
||||
@@ -288,45 +294,31 @@ def _split_index_url(self, line: str) -> tuple[str, str | None]:
|
||||
return pkg_spec, url
|
||||
return line, None
|
||||
|
||||
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str) -> bool:
|
||||
"""Reproduce the downgrade version comparison from existing is_blacklisted() logic.
|
||||
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str, installed: dict) -> bool:
|
||||
"""Apply the downgrade rule shared with is_blacklisted().
|
||||
|
||||
Same logic as manager_core.py's is_blacklisted():
|
||||
- No version spec and already installed → block (prevent reinstall)
|
||||
- Operator is one of ['<=', '==', '<', '~='] and
|
||||
installed version >= requested version → block (prevent downgrade)
|
||||
- Version comparison uses manager_util.StrictVersion (NOT packaging.version)
|
||||
Parsing and the decision come from manager_util.parse_pip_spec() and
|
||||
manager_util.downgrade_protection(), so both paths give the same result:
|
||||
- Any clause with operator ['<', '<=', '==', '===', '~='] that would make pip
|
||||
install an older version → block (prevent downgrade)
|
||||
- No version spec, or a clause that allows exactly the installed version,
|
||||
and no extras → block (pip would change nothing)
|
||||
- The same two cases with extras → allow (the extras' dependencies are added)
|
||||
- A clause that cannot be compared → block, and log why and how to proceed
|
||||
- Requirements and versions are parsed with `packaging` (PEP 508 / PEP 440)
|
||||
"""
|
||||
if pkg_name not in self.downgrade_blacklist:
|
||||
if pkg_name not in self.downgrade_blacklist or pkg_name not in installed:
|
||||
return False
|
||||
|
||||
installed_packages = manager_util.get_installed_packages()
|
||||
|
||||
# Version spec parsing (same pattern as existing is_blacklisted())
|
||||
pattern = r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
|
||||
match = re.search(pattern, pkg_spec)
|
||||
|
||||
if match is None:
|
||||
# No version spec: prevent reinstall if already installed
|
||||
if pkg_name in installed_packages:
|
||||
return True
|
||||
elif match.group(2) in ['<=', '==', '<', '~=']:
|
||||
# Downgrade operator: block if installed version >= requested version
|
||||
if pkg_name in installed_packages:
|
||||
try:
|
||||
installed_ver = manager_util.StrictVersion(installed_packages[pkg_name])
|
||||
requested_ver = manager_util.StrictVersion(match.group(3))
|
||||
if installed_ver >= requested_ver:
|
||||
return True
|
||||
except (ValueError, TypeError):
|
||||
logging.warning(f"[UnifiedDepResolver] version parse failed: {pkg_spec}")
|
||||
return False
|
||||
|
||||
return False
|
||||
_, extras, clauses = manager_util.parse_pip_spec(pkg_spec)
|
||||
blocked, error = manager_util.downgrade_protection(
|
||||
pkg_spec, clauses, extras, installed[pkg_name])
|
||||
if error is not None:
|
||||
logger.error("[UnifiedDepResolver] %s", error)
|
||||
return blocked
|
||||
|
||||
def _remap_package(self, pkg: str) -> str:
|
||||
"""Package name remapping based on cm_global.pip_overrides.
|
||||
Reuses existing remap_pip_package() logic."""
|
||||
"""Package name remapping based on cm_global.pip_overrides."""
|
||||
if pkg in self.overrides:
|
||||
remapped = self.overrides[pkg]
|
||||
logging.info(f"[UnifiedDepResolver] '{pkg}' remapped to '{remapped}'")
|
||||
@@ -621,7 +613,7 @@ comfyui_manager/prestartup_script.py # Config reading + startup batch reso
|
||||
|-----------|---------|-------|
|
||||
| `uv` | Dependency resolution and installation | Already included in project dependencies |
|
||||
| `cm_global` | pip_overrides, pip_blacklist, pip_downgrade_blacklist | Reuse existing global state (runtime dynamic assignment) |
|
||||
| `manager_util` | StrictVersion, get_installed_packages, use_unified_resolver flag | Reuse existing utilities |
|
||||
| `manager_util` | parse_pip_spec, downgrade_protection, normalize_pip_name, get_installed_packages, use_unified_resolver flag | Reuse existing utilities |
|
||||
| `tempfile` | Temporary requirements files, mkdtemp | Standard library |
|
||||
| `subprocess` | uv process execution | Standard library |
|
||||
| `dataclasses` | Result data structures | Standard library |
|
||||
@@ -696,8 +688,8 @@ sequenceDiagram
|
||||
| Credential redaction | `user:pass@host` URL masked in log output |
|
||||
| `_redact_url` | `://user:pass@host` → `://****@host` conversion, no-credential URL passthrough |
|
||||
| `cleanup_stale_tmp` | Delete stale dirs >1 hour, preserve recent dirs, ignore permission errors |
|
||||
| Downgrade operators | `<=`, `==`, `<`, `~=` blocked; `>=`, `>`, `!=` pass; no spec + installed → blocked |
|
||||
| `StrictVersion` comparison | Verify `manager_util.StrictVersion` is used (not `packaging.version`) |
|
||||
| Downgrade operators | `<`, `<=`, `==`, `===`, `~=` that require an older version blocked; `>=`, `>`, `!=` pass; no spec or the installed version + installed → blocked, unless the requirement has extras |
|
||||
| Shared downgrade decision | Verify `manager_util.parse_pip_spec` and `manager_util.downgrade_protection` are used, as in `is_blacklisted()` |
|
||||
|
||||
### 9.2 Integration Tests
|
||||
|
||||
@@ -742,15 +734,11 @@ sequenceDiagram
|
||||
> **Note**: Line numbers may shift as code changes, so references use symbol names (function/class names).
|
||||
> Use `grep -n` or IDE symbol search for exact locations.
|
||||
|
||||
### remap_pip_package Location (Code Duplication Exists)
|
||||
### pip_overrides Outside the Resolver
|
||||
|
||||
```
|
||||
comfyui_manager/glob/manager_core.py — def remap_pip_package(pkg)
|
||||
comfyui_manager/prestartup_script.py — def remap_pip_package(pkg)
|
||||
```
|
||||
|
||||
Both reference `cm_global.pip_overrides` with identical logic.
|
||||
The unified resolver uses `cm_global.pip_overrides` directly to avoid adding more duplication.
|
||||
The paths that install one line at a time read each line with
|
||||
`manager_util.pip_install_args(line, cm_global.pip_overrides)`, which applies the override.
|
||||
The unified resolver applies `cm_global.pip_overrides` itself in `_remap_package()`.
|
||||
|
||||
### cm_global Global State
|
||||
|
||||
@@ -783,30 +771,28 @@ pip_fixer.fix_broken()
|
||||
The unified resolver does not call PIPFixer directly.
|
||||
The caller (execute_install_script) calls PIPFixer as part of the existing flow.
|
||||
|
||||
### is_blacklisted() Logic (Must Be Reproduced in Unified Resolver)
|
||||
### is_blacklisted() Logic (Shared with the Unified Resolver)
|
||||
|
||||
```python
|
||||
# manager_core.py — def is_blacklisted(name)
|
||||
# 1. Simple pip_blacklist membership check
|
||||
# manager_core.py — def is_blacklisted(name) → manager_util.pip_block_reason()
|
||||
# 1. pip_blacklist membership check, names compared in normalized form
|
||||
# (manager_util.normalize_pip_name: lowercase; '-', '_' and '.' are one separator)
|
||||
# 2. pip_downgrade_blacklist version comparison:
|
||||
# - Parse spec with regex r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
|
||||
# - match is None (no version spec) + installed → block
|
||||
# - Operator in ['<=', '==', '<', '~='] + installed version >= requested version → block
|
||||
# - Version comparison uses manager_util.StrictVersion (NOT packaging.version)
|
||||
# - Parse the requirement with manager_util.parse_pip_spec() (packaging, PEP 508)
|
||||
# - Any clause in ['<', '<=', '==', '===', '~='] that requires an older version → block
|
||||
# - No version spec, or a clause that allows exactly the installed version → block,
|
||||
# unless the requirement has extras
|
||||
# - A clause that cannot be compared → block, with an error that explains how to proceed
|
||||
# - Versions are compared with packaging.version (PEP 440)
|
||||
```
|
||||
|
||||
The unified resolver's `_is_downgrade_blacklisted()` method faithfully reproduces this logic.
|
||||
It uses `manager_util.StrictVersion` instead of `packaging.version.parse()` to ensure consistency with existing behavior.
|
||||
The unified resolver's `_is_downgrade_blacklisted()` method calls the same
|
||||
`manager_util.parse_pip_spec()` and `manager_util.downgrade_protection()`, so the two
|
||||
paths cannot diverge.
|
||||
|
||||
### Existing Code --index-url Handling (Asymmetric)
|
||||
### Existing Code --index-url Handling
|
||||
|
||||
```python
|
||||
# Only exists in standalone function execute_install_script():
|
||||
if '--index-url' in package_name:
|
||||
s = package_name.split('--index-url')
|
||||
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
|
||||
|
||||
# UnifiedManager.execute_install_script() method does NOT have this handling
|
||||
```
|
||||
|
||||
The unified resolver unifies both paths for consistent handling via `_split_index_url()`.
|
||||
On every path that installs one line at a time, `manager_util.pip_install_args()` gives a
|
||||
requirement followed by `--index-url URL` or `--extra-index-url URL` to the installer with that
|
||||
requirement only, and leaves out a line that has only an option.
|
||||
The unified resolver collects index URLs for the whole batch via `_split_index_url()`.
|
||||
|
||||
@@ -25,11 +25,13 @@ rm -rf /tmp/e2e_test
|
||||
|
||||
| Script | Purpose | Input | Output |
|
||||
|--------|---------|-------|--------|
|
||||
| `setup_e2e_env.sh` | Full environment setup (8 steps) | `E2E_ROOT`, `MANAGER_ROOT`, `COMFYUI_BRANCH` (default: master), `PYTHON` (default: python3) | `E2E_ROOT=<path>` on last line |
|
||||
| `setup_e2e_env.sh` | Full environment setup (8 steps) | `E2E_ROOT`, `MANAGER_ROOT`, `COMFYUI_BRANCH` (default: master), `UV_PYTHON` (optional uv request) | `E2E_ROOT=<path>` on last line |
|
||||
| `start_comfyui.sh` | Foreground-blocking launcher | `E2E_ROOT`, `PORT` (default: 8199), `TIMEOUT` (default: 120s) | `COMFYUI_PID=<pid> PORT=<port>` |
|
||||
| `stop_comfyui.sh` | Graceful shutdown | `E2E_ROOT`, `PORT` (default: 8199) | — |
|
||||
|
||||
**Idempotent**: `setup_e2e_env.sh` checks for a `.e2e_setup_complete` marker file and skips setup if the environment already exists.
|
||||
**Interpreter selection**: both setup scripts use `uv venv --project "$MANAGER_ROOT"`, so uv reads Manager's `pyproject.toml` and honors its `.python-version` file and `UV_PYTHON`. To select a specific interpreter, set `UV_PYTHON` to a request such as `3.10` or an absolute executable path. The scripts do not read the old `PYTHON` variable. Explicit uv selections can override the project requirement, so the resulting venv is still checked for Python 3.10+. Selection applies only to new venvs.
|
||||
|
||||
**Idempotent**: both setup scripts reuse a completed environment only after checking that its venv runs Python 3.10+. If an existing venv is too old or its interpreter cannot run, recreate it with a supported interpreter in a fresh `E2E_ROOT`.
|
||||
|
||||
**Blocking mechanism**: `start_comfyui.sh` uses `tail -n +1 -f | grep -q -m1 'To see the GUI'` to block until ComfyUI is ready. No polling loop needed.
|
||||
|
||||
@@ -37,7 +39,7 @@ rm -rf /tmp/e2e_test
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.9+
|
||||
- Python 3.10+ in the E2E venv (selected automatically by uv during automated setup)
|
||||
- Git
|
||||
- `uv` (install via `pip install uv` or [standalone](https://docs.astral.sh/uv/getting-started/installation/))
|
||||
|
||||
|
||||
+1
-1
@@ -104,7 +104,7 @@ ComfyUI-Loopchain
|
||||
|
||||
* Detailed Operations
|
||||
* `install`: Installs the specified custom nodes.
|
||||
* `reinstall`: Removes and then reinstalls the specified custom nodes.
|
||||
* `reinstall`: Removes and then reinstalls the specified custom nodes. A nodepack named by its id without a version is reinstalled at the version that is installed.
|
||||
* `uninstall`: Uninstalls the specified custom nodes.
|
||||
* `update`: Updates the specified custom nodes.
|
||||
* `disable`: Disables the specified custom nodes.
|
||||
|
||||
+1
-1
@@ -105,7 +105,7 @@ ComfyUI-Loopchain
|
||||
|
||||
* 세부 동작
|
||||
* `install`: 지정된 커스텀 노드들을 설치합니다
|
||||
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
|
||||
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다. 버전 없이 이름만 지정하면 설치되어 있는 버전으로 재설치합니다.
|
||||
* `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
|
||||
* `update`: 지정된 커스텀 노드들을 업데이트합니다.
|
||||
* `disable`: 지정된 커스텀 노드들을 비활성화합니다.
|
||||
|
||||
@@ -19,7 +19,6 @@ Each subdirectory contains a standard set of JSON files:
|
||||
- **custom-node-list.json**: Primary database of custom nodes with metadata
|
||||
- **extension-node-map.json**: Maps between extensions and individual nodes they provide
|
||||
- **model-list.json**: Catalog of models that can be downloaded through the manager
|
||||
- **alter-list.json**: Alternative implementations of nodes for compatibility or functionality
|
||||
- **github-stats.json**: GitHub repository statistics for node popularity metrics
|
||||
|
||||
## Database Schema
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
{}
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"items": [
|
||||
]
|
||||
}
|
||||
+43
-20
@@ -20,7 +20,7 @@ components:
|
||||
schemas:
|
||||
OperationType:
|
||||
type: string
|
||||
enum: [install, uninstall, update, update-comfyui, fix, disable, enable, install-model]
|
||||
enum: [install, reinstall, uninstall, update, update-comfyui, fix, disable, enable, install-model]
|
||||
description: Type of operation or task being performed
|
||||
OperationResult:
|
||||
type: string
|
||||
@@ -226,6 +226,9 @@ components:
|
||||
enabled:
|
||||
type: boolean
|
||||
description: Whether the pack is enabled
|
||||
invalid_installation:
|
||||
type: [boolean, 'null']
|
||||
description: True when the folder has neither .git nor .tracking, so the Manager can neither update it nor tell its version; absent or null otherwise. Its ver is then "unknown" and its cnr_id is the registry id of its pack when the registry list has it, otherwise [project].name of its pyproject.toml in lower case (also while the registry list is still loading), otherwise "". A reinstall task fixes it.
|
||||
required: [ver, enabled]
|
||||
SelectedVersion:
|
||||
type: string
|
||||
@@ -422,8 +425,10 @@ components:
|
||||
description: UI identifier for task tracking
|
||||
stable:
|
||||
type: boolean
|
||||
default: true
|
||||
description: Whether to update to stable version (true) or nightly (false)
|
||||
description: Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.
|
||||
is_stable:
|
||||
type: boolean
|
||||
description: Another name for `stable`, the one the task parameters use. Read when `stable` is not given.
|
||||
required: [client_id, ui_id]
|
||||
ComfyUISwitchVersionParams:
|
||||
type: object
|
||||
@@ -923,6 +928,18 @@ paths:
|
||||
selected_version: "latest"
|
||||
mode: "remote"
|
||||
channel: "default"
|
||||
reinstall:
|
||||
summary: Reinstall a custom node in place of its folders, which are kept if the install fails
|
||||
value:
|
||||
ui_id: "task_132"
|
||||
client_id: "client_abc"
|
||||
kind: "reinstall"
|
||||
params:
|
||||
id: "comfyui-impact-pack"
|
||||
version: "latest"
|
||||
selected_version: "latest"
|
||||
mode: "remote"
|
||||
channel: "default"
|
||||
update:
|
||||
summary: Update a custom node
|
||||
value:
|
||||
@@ -1057,12 +1074,14 @@ paths:
|
||||
/v2/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
|
||||
|
||||
/v2/customnode/import_fail_info_bulk:
|
||||
post:
|
||||
@@ -1092,14 +1111,16 @@ paths:
|
||||
/v2/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
|
||||
/v2/manager/queue/update_all:
|
||||
post:
|
||||
summary: Update all custom nodes
|
||||
description: Queues update operations for all installed custom nodes. Parameters are read from the query string.
|
||||
description: Queues update operations for all installed custom nodes. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1110,7 +1131,7 @@ paths:
|
||||
'200':
|
||||
description: Update queued successfully
|
||||
'400':
|
||||
description: Missing required parameters
|
||||
description: Content-Type is not application/json, or missing required parameters
|
||||
'401':
|
||||
description: Processing already in progress
|
||||
'403':
|
||||
@@ -1118,7 +1139,7 @@ paths:
|
||||
/v2/manager/queue/update_comfyui:
|
||||
post:
|
||||
summary: Update ComfyUI
|
||||
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string.
|
||||
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/clientIdRequiredParam'
|
||||
- $ref: '#/components/parameters/uiIdRequiredParam'
|
||||
@@ -1126,7 +1147,7 @@ paths:
|
||||
'200':
|
||||
description: Update queued successfully
|
||||
'400':
|
||||
description: Missing required parameters
|
||||
description: Content-Type is not application/json, or missing required parameters
|
||||
/v2/manager/queue/install_model:
|
||||
post:
|
||||
summary: Install model
|
||||
@@ -1232,7 +1253,7 @@ paths:
|
||||
/v2/snapshot/remove:
|
||||
post:
|
||||
summary: Remove snapshot
|
||||
description: Removes a specified snapshot. The `target` parameter is read from the query string.
|
||||
description: Removes a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1241,13 +1262,13 @@ paths:
|
||||
'200':
|
||||
description: Snapshot removed successfully
|
||||
'400':
|
||||
description: Error removing snapshot
|
||||
description: Content-Type is not application/json, or error removing snapshot
|
||||
'403':
|
||||
description: Security policy violation
|
||||
/v2/snapshot/restore:
|
||||
post:
|
||||
summary: Restore snapshot
|
||||
description: Restores a specified snapshot. The `target` parameter is read from the query string.
|
||||
description: Restores a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
|
||||
security:
|
||||
- securityLevel: []
|
||||
parameters:
|
||||
@@ -1256,7 +1277,7 @@ paths:
|
||||
'200':
|
||||
description: Snapshot restoration scheduled
|
||||
'400':
|
||||
description: Error restoring snapshot
|
||||
description: Content-Type is not application/json, or error restoring snapshot
|
||||
'403':
|
||||
description: Security policy violation
|
||||
/v2/snapshot/get_current:
|
||||
@@ -1275,12 +1296,12 @@ paths:
|
||||
/v2/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 (v2)
|
||||
/v2/comfyui_manager/comfyui_versions:
|
||||
get:
|
||||
@@ -1333,7 +1354,7 @@ paths:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
enum: [channel, local, remote]
|
||||
enum: [cache, channel, local, remote]
|
||||
post:
|
||||
summary: Set database mode
|
||||
description: Sets the database mode. Payload is a JSON object with a `value` field.
|
||||
@@ -1347,7 +1368,7 @@ paths:
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
enum: [channel, local, remote]
|
||||
enum: [cache, channel, local, remote]
|
||||
description: New database mode
|
||||
responses:
|
||||
'200':
|
||||
@@ -1365,7 +1386,7 @@ paths:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
enum: [stable, nightly, nightly-comfyui]
|
||||
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
|
||||
post:
|
||||
summary: Set update policy
|
||||
description: Sets the update policy. Payload is a JSON object with a `value` field.
|
||||
@@ -1379,7 +1400,7 @@ paths:
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
enum: [stable, nightly, nightly-comfyui]
|
||||
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
|
||||
description: New update policy
|
||||
responses:
|
||||
'200':
|
||||
@@ -1431,12 +1452,14 @@ paths:
|
||||
/v2/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
|
||||
/v2/manager/version:
|
||||
|
||||
+2
-15
@@ -5,8 +5,8 @@ build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "comfyui-manager"
|
||||
license = { text = "GPL-3.0-only" }
|
||||
version = "4.3"
|
||||
requires-python = ">= 3.9"
|
||||
version = "4.5"
|
||||
requires-python = ">=3.10"
|
||||
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
|
||||
readme = "README.md"
|
||||
keywords = ["comfyui", "comfyui-manager"]
|
||||
@@ -52,16 +52,3 @@ include = ["comfyui_manager*", "cm_cli*"]
|
||||
|
||||
[project.scripts]
|
||||
cm-cli = "cm_cli:main"
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
target-version = "py39"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = [
|
||||
"E4", # default
|
||||
"E7", # default
|
||||
"E9", # default
|
||||
"F", # default
|
||||
"I", # isort-like behavior (import statement sorting)
|
||||
]
|
||||
|
||||
@@ -397,12 +397,11 @@
|
||||
|
||||
## 22. tests/e2e/test_e2e_legacy_endpoints.py — Legacy-only endpoint positive-path suite (WI-TT + WI-UU deliverable)
|
||||
|
||||
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All seven routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
|
||||
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All six routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
|
||||
**Scope**: Positive-path assertions — status 200 + response-shape verification for each legacy-only endpoint. `disabled_versions` additionally accepts 400 as a valid branch because the handler returns 400 when the target node has no disabled versions (empty-result convention, not a validation error). `queue/batch` uses an empty-payload strategy to exercise the full handler path (parse → action-loop no-op → finalize-with-empty-guard → `_queue_start()` → JSON 200) with zero state mutation, plus a queue/status liveness check to verify the worker lock was released cleanly.
|
||||
|
||||
| Test | Design Goal | Verdict | Evidence |
|
||||
|---|---|---|---|
|
||||
| `TestLegacyCustomNodeAlternatives::test_returns_dict_of_alternatives` | Endpoint contract (alternatives — wi-031) | ✅ PASS | GET `/customnode/alternatives?mode=local` → 200 + dict body. Exercises unified-key mapping path (handler L1072-1084). |
|
||||
| `TestLegacyCustomNodeDisabledVersions::test_endpoint_reachable_and_parses_param` | Endpoint contract (disabled_versions — wi-032) | ✅ PASS | GET `/v2/customnode/disabled_versions/ComfyUI_SigmoidOffsetScheduler` → status ∈ {200, 400}; 200 body asserted as list of `{version}` entries. Seed pack has no disabled versions → 400 is the live branch, 200 is guarded for when state is mutated. |
|
||||
| `TestLegacyCustomNodeGetList::test_returns_channel_and_node_packs` | Endpoint contract (getlist — wi-033) | ✅ PASS | GET `/v2/customnode/getlist?mode=local&skip_update=true` → 200 + `{channel, node_packs}` dict with node_packs as dict. Exercises the unified `get_unified_total_nodes + populate_*` pipeline. |
|
||||
| `TestLegacyCustomNodeVersions::test_returns_versions_list_for_seed_pack` | Endpoint contract (versions — wi-034) | ✅ PASS | GET `/v2/customnode/versions/ComfyUI_SigmoidOffsetScheduler` → 200 + non-empty list. Verifies CNR version lookup for the seed pack (handler L1262-1270). |
|
||||
@@ -410,7 +409,7 @@
|
||||
| `TestLegacyManagerNotice::test_returns_text_body` | Endpoint contract (notice — wi-036) | ✅ PASS | GET `/v2/manager/notice` → 200 + non-empty text body. Handler returns text/html (not JSON); both the markdown-fetch branch and the 'Unable to retrieve Notice' fallback return 200 with body. |
|
||||
| `TestLegacyQueueBatch::test_accepts_empty_payload_returns_failed_list` | Endpoint contract (queue/batch — wi-039) | ✅ PASS | POST `/v2/manager/queue/batch` with `{}` → 200 + `{"failed": []}`. Safe-payload choice (empty body) exercises full handler path with zero state mutation; `finalize_temp_queue_batch` no-ops via its `if len(temp_queue_batch):` guard (handler L444), and `_queue_start()` releases the task-worker lock cleanly. Post-POST `/v2/manager/queue/status` returns 200 — lock-release liveness check. Closes the wi-039 pytest-I gap (was CSRF-only direct + indirect-via-callers). |
|
||||
|
||||
**File verdict**: 7/7 ✅ PASS.
|
||||
**File verdict**: 6/6 ✅ PASS.
|
||||
|
||||
---
|
||||
|
||||
@@ -431,32 +430,32 @@
|
||||
| test_e2e_csrf_legacy.py | 29 | 0 | 0 | 0 | 29 |
|
||||
| test_e2e_secgate_strict.py | 1 | 0 | 0 | 0 | 1 |
|
||||
| test_e2e_secgate_default.py | 1 | 0 | 0 | 0 | 1 |
|
||||
| test_e2e_legacy_endpoints.py | 7 | 0 | 0 | 0 | 7 |
|
||||
| test_e2e_legacy_endpoints.py | 6 | 0 | 0 | 0 | 6 |
|
||||
| legacy-ui-manager-menu.spec.ts | 5 | 0 | 0 | 0 | 5 |
|
||||
| legacy-ui-custom-nodes.spec.ts | 5 | 0 | 0 | 0 | 5 |
|
||||
| legacy-ui-model-manager.spec.ts | 4 | 0 | 0 | 0 | 4 |
|
||||
| legacy-ui-snapshot.spec.ts | 3 | 0 | 0 | 0 | 3 |
|
||||
| legacy-ui-navigation.spec.ts | 2 | 0 | 0 | 0 | 2 |
|
||||
| legacy-ui-install.spec.ts | 2 | 0 | 0 | 0 | 2 |
|
||||
| **TOTAL** | **122** | **0** | **0** | **1** | **123** |
|
||||
| **TOTAL** | **121** | **0** | **0** | **1** | **122** |
|
||||
|
||||
(Count adjusted to 109 after Wave1 WI-L/M/N: 10 WEAK→PASS upgrades across 5 files (endpoint, git_clone, customnode_info, queue_lifecycle, version_mgmt) + 1 WEAK-row retired via WI-M dedup (test_get_current_returns_dict folded into strengthened test_get_current_snapshot — the folded row is treated as a deletion rather than a separate upgrade). Stage2 WI-F earlier established the 110 baseline from 112 by retiring 4 INADEQUATE legacy-ui tests with net +2 PASS. Wave2 WI-P/Q added 7 more WEAK→PASS upgrades (WI-P: task_operations 6 upgrades for update/fix effect + params; WI-Q: snapshot_lifecycle 1 upgrade for save_snapshot disk + content verification). Wave3 WI-T/U/W completed the reconciliation with 10 further WEAK→PASS upgrades: WI-T Cluster C+G strengthened queue_lifecycle (3), customnode_info (1), system_info (1) for field-level effect checks; WI-U Cluster H rewrote 3 Playwright legacy-ui specs (manager-menu 2, custom-nodes 1, model-manager 2) to verify UI state via dialog reopen / `<select>.value` assertions instead of direct API; WI-W fixed the TaskHistoryItem schema-drop regression enabling queue_lifecycle un-skip. Cumulative **upgrade** count across the three waves = 10 + 7 + 10 = **27** (unchanged). WI-Z reconciled the audit with the actual test-file surface (no upgrades, only inventory): Y1 recorded the pre-existing `test_remove_path_traversal_rejected` in snapshot_lifecycle (§7, 6→7), and Y3 recorded 5 pre-existing config_api rows (junk_value rejections ×3 + persists_to_config_ini ×2 from WI-E/WI-I, §4, 10→15). WI-AA recorded the pre-existing `legacy-ui-install.spec.ts` (LB1 + LB2) as new §16 — these UI-driven install/uninstall tests (from WI-U Cluster) close the LB1/LB2 gap formerly flagged in `coverage_gaps.md`. WI-GG added new §19 for `test_e2e_csrf_legacy.py` (from WI-FF): 4 new test functions / 26 parametrized invocations closing the legacy-side CSRF regression-guard gap — counted per-invocation (+26 PASS rows) for parity with the CSRF endpoint-fixture accounting in `endpoint_scenarios.md`; this is an accounting-granularity choice, not a contract addition (CSRF-M1/M2/M3 Goals were already referenced in §18). Total test count progression: **109 → 115 (WI-Z) → 117 (WI-AA) → 143 (WI-GG) → 146 (WI-JJ) → 148 (WI-LL)**; all 39 added rows were **pre-existing** tests or newly-added tests from their source WIs, not new engineering work performed by the audit reconciliation itself.)
|
||||
|
||||
> **Note**: The matrix above counts *tests* (148), not *design Goals* (92).
|
||||
> See `reports/verification_design.md` for the 92 Goals and the RV-B trace
|
||||
> **Note**: The matrix above counts *tests* (147), not *design Goals* (91).
|
||||
> See `reports/verification_design.md` for the 91 Goals and the RV-B trace
|
||||
> (adhoc-rv-b-trace session evidence) for the Goal↔test cross-reference.
|
||||
> **Design-Goal coverage: 70/92 Goals referenced (76.1%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **73/95** (76.8%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
|
||||
> **Design-Goal coverage: 69/91 Goals referenced (75.8%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **72/94** (76.6%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
|
||||
|
||||
Percentages (excluding N/A, denominator = 122+0+0 = 122):
|
||||
- ✅ PASS: 122 / 122 = 100%
|
||||
- ⚠️ WEAK: 0 / 122 = 0%
|
||||
- ❌ INADEQUATE: 0 / 122 = 0%
|
||||
Percentages (excluding N/A, denominator = 121+0+0 = 121):
|
||||
- ✅ PASS: 121 / 121 = 100%
|
||||
- ⚠️ WEAK: 0 / 121 = 0%
|
||||
- ❌ INADEQUATE: 0 / 121 = 0%
|
||||
|
||||
---
|
||||
|
||||
# Design-Goal Coverage Gap
|
||||
|
||||
24 of 92 design Goals (`reports/verification_design.md`) have no corresponding row in
|
||||
24 of 91 design Goals (`reports/verification_design.md`) have no corresponding row in
|
||||
the test audit above. Full list:
|
||||
|
||||
| Section | Goal | Intent | Recommended |
|
||||
@@ -481,12 +480,12 @@ the test audit above. Full list:
|
||||
| 5.4 | CV2 | Non-git error branch | NORMAL add |
|
||||
| 6.1 | LB4 | UI update-all | NORMAL add |
|
||||
| 6.1 | LB5 | Batch partial failure | NORMAL add |
|
||||
| 6.2 | LG2 | skip_update perf | NORMAL add |
|
||||
| 6.4 | LM2 | Install flag seed | NORMAL add |
|
||||
| 6.5 | LV1 | Version dropdown | NORMAL add |
|
||||
| 6.5 | LV2 | Unknown pack 400 | NORMAL add |
|
||||
| 6.2 | LG2 | List without fetch | NORMAL add |
|
||||
| 6.3 | LM2 | Install flag seed | NORMAL add |
|
||||
| 6.4 | LV1 | Version dropdown | NORMAL add |
|
||||
| 6.4 | LV2 | Unknown pack 400 | NORMAL add |
|
||||
|
||||
Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 95 Goals: KEEP 25 / rest unchanged.
|
||||
Final Goal-class tally (91 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 94 Goals: KEEP 25 / rest unchanged.
|
||||
|
||||
---
|
||||
|
||||
@@ -539,7 +538,6 @@ Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL
|
||||
- LN1-LN4 manager/notice tests (4 variants)
|
||||
- LPP1/LPP2 pip install tests
|
||||
- LGU1/LGU2 git_url install tests
|
||||
- LA1 alternatives display test
|
||||
- LDV1 disabled_versions test
|
||||
|
||||
## Classification policy (tier rule)
|
||||
@@ -599,9 +597,9 @@ should land as one cross-cutting item" collapses into a 4-sub-tier structure:
|
||||
| T2-TASKLEVEL | IM4 | Queue-observation pattern (not HTTP 403) — pattern TBD | Open design question; not a simple mechanical add |
|
||||
|
||||
Propagation plan (post-PR):
|
||||
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 136/151 TOTAL.
|
||||
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 138/153.
|
||||
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 139/154. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
|
||||
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 135/150 TOTAL.
|
||||
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 137/152.
|
||||
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 138/153. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
|
||||
|
||||
---
|
||||
|
||||
@@ -617,11 +615,11 @@ Cumulative Wave1+Wave2+Wave3 upgrade count: **27 WEAK → PASS** (10 + 7 + 10).
|
||||
|
||||
- Check status code without verifying the actual effect (WEAK — 0%) ✅
|
||||
- Use direct API in UI tests (INADEQUATE — 0%) ✅
|
||||
- Are outside endpoint-effect scope (N/A — 15/148 ≈ 10.1% of total)
|
||||
- Are outside endpoint-effect scope (N/A — 15/147 ≈ 10.2% of total)
|
||||
|
||||
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/92 absent, 70/92 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
|
||||
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/91 absent, 69/91 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
|
||||
|
||||
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (133/133 PASS, excluding 15 N/A). Audit is in a terminal state for the current 148 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
|
||||
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (132/132 PASS, excluding 15 N/A). Audit is in a terminal state for the current 147 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
|
||||
|
||||
> **WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL note**: Total test count 109 → 115 (WI-Z Y1 +1 snapshot, Y3 +5 config_api) → 117 (WI-AA +2 LB1/LB2) → 143 (WI-GG +26 legacy CSRF per-invocation rows) → 146 (WI-JJ +3 legacy-side install/parity rows) → 148 (WI-LL +2 SECGATE PoC rows) reflects inventory reconciliation plus WI-KK's newly-landed secgate coverage. Cumulative **upgrade** count remains 27 (unchanged since Wave3). WI-LL is the first audit-reflect WI to also introduce a Classification-policy reshape (T2 SECGATE-PENDING 8 → 4 sub-tiers), not just row additions.
|
||||
|
||||
|
||||
@@ -10,14 +10,14 @@
|
||||
| Category | Endpoints | Unique Scenarios |
|
||||
|---|---:|---:|
|
||||
| Glob v2 | 30 | 120 |
|
||||
| Legacy-only (not in glob) | 9 | 34 |
|
||||
| Legacy-only (not in glob) | 8 | 33 |
|
||||
| Legacy-shared (same path as glob) | 29 | — (see glob) |
|
||||
| **TOTAL unique HTTP handlers** | **39** | **154** |
|
||||
| **TOTAL unique HTTP handlers** | **38** | **153** |
|
||||
|
||||
Security-gated endpoints:
|
||||
- `middle`: reboot, snapshot/remove, _uninstall_custom_node, _update_custom_node
|
||||
- `middle+`: update_all, snapshot/restore, _install_custom_node, _install_model
|
||||
- `high+`: comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
|
||||
- `middle+`: update_all, _install_custom_node, _install_model
|
||||
- `high+`: comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version` (glob worker step), install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
|
||||
|
||||
---
|
||||
|
||||
@@ -188,7 +188,7 @@ Security-gated endpoints:
|
||||
|
||||
### POST /v2/snapshot/restore
|
||||
- **Handler**: `restore_snapshot` (L1543)
|
||||
- **Security gate**: `middle+` → 403
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Query**: `target`
|
||||
- **Scenarios**:
|
||||
1. Success — copies snapshot to startup script path (applied on next reboot) → 200
|
||||
@@ -291,21 +291,24 @@ Endpoints in this section exist **only in the legacy server** (not registered in
|
||||
7. `install` with security gate fail → failed set entry
|
||||
8. Empty body `{}` → 200 `{failed: []}`
|
||||
|
||||
### POST /v2/customnode/check_update
|
||||
- **Handler**: `check_update`
|
||||
- **Body**: `{mode, ui_id}` (required; `ui_id` is chosen by the client)
|
||||
- **Scenarios**:
|
||||
1. Success — starts a background check that fetches the enabled git packs of the list and answers `{}` at once → 200. The check reports by the `cm-check-update` event (`in_progress` with `done_count`/`total_count`, then `done` with `updatable` and the `ui_ids` of the requests it answers)
|
||||
2. A check already runs — no second check is started; the nodepacks of this request that the running check does not have are added to it (`total_count` grows), and its `done` names this request too → 200
|
||||
3. A task on nodepacks that the queue takes while a check runs waits for the check to end; a model download and an update of ComfyUI do not wait
|
||||
4. The check fails — `done` with `updatable: null` names the requests that waited, and the page shows `Failed to check updates.`
|
||||
|
||||
### GET /v2/customnode/getlist
|
||||
- **Handler**: `fetch_customnode_list` (L1018)
|
||||
- **Query**: `mode` (required), `skip_update?` (bool string)
|
||||
- **Query**: `mode` (required), `skip_update?` (not used)
|
||||
- **Scenarios**:
|
||||
1. Success — returns `{channel, node_packs}` with installed/update state populated → 200
|
||||
2. `skip_update=true` — skips git update check (faster)
|
||||
1. Success — returns `{channel, node_packs}` with installed state and the update state of versioned packs populated → 200
|
||||
2. With or without `skip_update` — no git fetch; the page marks the git packs that have an update from the result of `POST /v2/customnode/check_update`
|
||||
3. Removes comfyui-manager self-entry from results
|
||||
4. Channel lookup resolves to 'default'/'custom'/known name
|
||||
|
||||
### GET /customnode/alternatives
|
||||
- **Handler**: `fetch_customnode_alternatives` (L1072)
|
||||
- **Query**: `mode` (required)
|
||||
- **Scenarios**:
|
||||
1. Success — alter-list.json items keyed by id → 200
|
||||
|
||||
### GET /v2/externalmodel/getlist
|
||||
- **Handler**: `fetch_externalmodel_list` (L1143)
|
||||
- **Query**: `mode` (required)
|
||||
@@ -331,7 +334,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
|
||||
### POST /v2/customnode/install/git_url
|
||||
- **Handler**: `install_custom_node_git_url` (L1502)
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Body**: plain text URL
|
||||
- **Body**: JSON `{"url": ...}`, sent as `application/json`
|
||||
- **Scenarios**:
|
||||
1. Success install → 200
|
||||
2. Already installed (skip action) → 200
|
||||
@@ -341,7 +344,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
|
||||
### POST /v2/customnode/install/pip
|
||||
- **Handler**: `install_custom_node_pip` (L1522)
|
||||
- **Security gate**: `high+` → 403
|
||||
- **Body**: plain text space-separated packages
|
||||
- **Body**: JSON `{"packages": ...}` (space-separated), sent as `application/json`
|
||||
- **Scenarios**:
|
||||
1. Success — pip install completes → 200
|
||||
2. Security blocked → 403
|
||||
@@ -378,14 +381,14 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
|
||||
| Level | Glob endpoints | Legacy endpoints |
|
||||
|---|---|---|
|
||||
| **middle** | snapshot/remove, reboot | snapshot/remove, reboot, _uninstall, _update |
|
||||
| **middle+** | update_all, snapshot/restore, install_model | update_all, snapshot/restore, _install_custom_node, _install_model |
|
||||
| **high+** | comfyui_switch_version, _fix_custom_node | comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix |
|
||||
| **middle+** | update_all, install_model | update_all, _install_custom_node, _install_model |
|
||||
| **high+** | comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version`, _fix_custom_node | comfyui_switch_version, snapshot/restore, install/git_url, install/pip, non-safetensors model install, _fix |
|
||||
|
||||
> Note: `_fix` / `_fix_custom_node` security-level history: `middle` → `high` in commit `c8992e5d` (2026-04-04, which also added a previously-missing gate to the legacy handler); subsequent `high` → `high+` in WI-#235 to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text (and tighten the gate for a state-mutating fix path). README 'Risky Level Table' has been updated in lockstep.
|
||||
|
||||
# Deprecated / Removed
|
||||
|
||||
- **GET /v2/customnode/fetch_updates** — glob returns 410; legacy still attempts fetch (may succeed but deprecated in concept)
|
||||
- **GET /v2/customnode/fetch_updates** — glob and legacy return 410
|
||||
- **Individual queue/{install,uninstall,update,fix,disable,reinstall,abort_current}** — removed from legacy in recent work (replaced by queue/batch aggregator)
|
||||
- **GET /manager/notice** (v1, no /v2 prefix) — removed from legacy
|
||||
|
||||
@@ -407,7 +410,7 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
|
||||
| 6 | `/v2/manager/queue/task` | POST | POST (pre-existing) | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/queue/task]` |
|
||||
| 7 | `/v2/snapshot/save` | GET | POST | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/save]` |
|
||||
| 8 | `/v2/snapshot/remove` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/remove]` |
|
||||
| 9 | `/v2/snapshot/restore` | GET | POST | middle+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
|
||||
| 9 | `/v2/snapshot/restore` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
|
||||
| 10 | `/v2/manager/reboot` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/reboot]` |
|
||||
| 11 | `/v2/comfyui_manager/comfyui_switch_version` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/comfyui_manager/comfyui_switch_version]` |
|
||||
| 12 | `/v2/manager/db_mode` | GET (dual) | POST (write); GET preserved for read | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/db_mode]` |
|
||||
|
||||
@@ -384,18 +384,10 @@ Purpose: **feed the Custom Nodes Manager dialog with the list of available + ins
|
||||
|
||||
| Scenario | Effect to verify |
|
||||
|---|---|
|
||||
| Success | Response has `channel` + `node_packs`; each pack includes install state (installed/disabled), stars (github-stats), update availability (if skip_update=false) |
|
||||
| skip_update=true | No git fetch performed (check timing / no remote calls) |
|
||||
| Success | Response has `channel` + `node_packs`; each pack includes install state (installed/disabled), stars (github-stats), update availability of versioned packs |
|
||||
| With or without skip_update | No git fetch performed (check timing / no remote calls) |
|
||||
| Channel resolution | Maps URL back to name (default/custom/etc.) |
|
||||
|
||||
### GET /customnode/alternatives (legacy)
|
||||
|
||||
Purpose: **show alternative pack recommendations for a given pack**.
|
||||
|
||||
| Scenario | Effect to verify |
|
||||
|---|---|
|
||||
| Success | Response dict keyed by unified pack id; values from `alter-list.json` with markdown processed |
|
||||
|
||||
### GET /v2/externalmodel/getlist (legacy)
|
||||
|
||||
Purpose: **list available external models with install state for Model Manager dialog**.
|
||||
@@ -473,7 +465,6 @@ For Playwright tests, the "UI→effect" contract requires:
|
||||
| Click "Disable" on row | POST queue/batch (disable) | Pack in `.disabled/` + row state "Disabled" |
|
||||
| Click "Update" on outdated row | POST queue/batch (update) | Pack version changes + row state update |
|
||||
| Click "Fix" on row | POST queue/batch (fix) | Dependencies restored |
|
||||
| Click "Try alternatives" | GET /customnode/alternatives | Alternatives list rendered |
|
||||
| Open "Versions" dropdown on row | GET customnode/versions/{id} | Version list rendered in UI |
|
||||
| Open "Disabled Versions" on row | GET customnode/disabled_versions/{id} | Disabled versions rendered |
|
||||
| Click "Install via Git URL" button + enter URL + confirm | POST customnode/install/git_url | Pack cloned; dir visible in UI |
|
||||
|
||||
@@ -219,7 +219,7 @@ Intent categories used:
|
||||
| Success | Recovery: rollback to a known-good state after bad update |
|
||||
| Nonexistent | Input resilience |
|
||||
| Path traversal | Security boundary |
|
||||
| Security denied | Security boundary: middle+ required (restore is destructive) |
|
||||
| Security denied | Security boundary: high+ required (restore is destructive) |
|
||||
|
||||
## 1.4 Configuration
|
||||
|
||||
@@ -313,15 +313,9 @@ Same as db_mode: observability of current policy + user choice to change update
|
||||
| Scenario | Intent |
|
||||
|---|---|
|
||||
| Success | User capability: populate Custom Nodes Manager dialog with full available pack catalog |
|
||||
| skip_update=true | Performance: fast load when user doesn't need remote fetch |
|
||||
| With or without skip_update | Performance: the list loads without a remote fetch; a check for updates runs in the background |
|
||||
| Channel resolution | Observability: user sees which channel data came from |
|
||||
|
||||
### GET /customnode/alternatives
|
||||
|
||||
| Scenario | Intent |
|
||||
|---|---|
|
||||
| Success | User capability: recommend alternative packs when one is discontinued/unavailable |
|
||||
|
||||
### GET /v2/externalmodel/getlist
|
||||
|
||||
| Scenario | Intent |
|
||||
@@ -385,7 +379,7 @@ Some scenarios recur across many endpoints with consistent intent:
|
||||
| Security level denial (middle/middle+/high+) | destructive endpoints | Security boundary — tier privileged ops per deployment risk profile |
|
||||
| Idempotent re-call on empty state | queue/reset, history_list, snapshot/getlist, installed | Idempotency — safe to poll or retry |
|
||||
| Repeated read returns same value | version, db_mode, policy/update | Data integrity — config/runtime state is stable |
|
||||
| Empty collection returned cleanly | history, getlist, installed, alternatives | Input resilience — empty is valid, not an error |
|
||||
| Empty collection returned cleanly | history, getlist, installed | Input resilience — empty is valid, not an error |
|
||||
|
||||
---
|
||||
|
||||
@@ -393,7 +387,7 @@ Some scenarios recur across many endpoints with consistent intent:
|
||||
|
||||
| Intent category | # scenarios | Notes |
|
||||
|---|---:|---|
|
||||
| User capability (positive user need) | 62 | The "happy paths" |
|
||||
| User capability (positive user need) | 61 | The "happy paths" |
|
||||
| Input resilience | 32 | Mostly 400s for bad input |
|
||||
| Security boundary | 15 | Security levels + path traversal |
|
||||
| Idempotency | 14 | No-op / retry safety |
|
||||
@@ -402,7 +396,7 @@ Some scenarios recur across many endpoints with consistent intent:
|
||||
| Recovery | 5 | Fix, restore, reset |
|
||||
| Concurrency safety | 2 | Worker dedup |
|
||||
|
||||
Total unique scenarios mapped: ~154 (matches Report A).
|
||||
Total unique scenarios mapped: ~153 (matches Report A).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -359,7 +359,7 @@ Negative check: <what must NOT happen>
|
||||
- **Observable**: manager_startup_script_path for `restore-snapshot.json`
|
||||
- **Assertion**: restore-snapshot.json exists; content == target snapshot; (downstream: reboot → state reverts)
|
||||
|
||||
### Goal SR6 — Security gate (<middle+)
|
||||
### Goal SR6 — Security gate (<high+)
|
||||
- **Assertion**: 403; no marker file
|
||||
|
||||
---
|
||||
@@ -513,19 +513,12 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
- **Observable**: UI grid rows
|
||||
- **Assertion**: rows > 0; each row has Title + Installed/Not-Installed state + Install/Uninstall button
|
||||
|
||||
### Goal LG2 — skip_update=true optimizes loading
|
||||
- **Action (UI)**: open dialog with flag set (URL param or setting)
|
||||
### Goal LG2 — the list loads without a git fetch
|
||||
- **Action (UI)**: open dialog (with or without `skip_update`)
|
||||
- **Observable**: loading time; network log
|
||||
- **Assertion**: no git fetch calls; load time < N seconds
|
||||
|
||||
## 6.3 GET /customnode/alternatives
|
||||
|
||||
### Goal LA1 — Show alternatives on dedicated UI flow
|
||||
- **Action (UI)**: trigger alternatives display (specific button or context)
|
||||
- **Observable**: alternatives panel/dialog
|
||||
- **Assertion**: populated with alter-list.json entries (at least one if data exists)
|
||||
|
||||
## 6.4 GET /v2/externalmodel/getlist
|
||||
## 6.3 GET /v2/externalmodel/getlist
|
||||
|
||||
### Goal LM1 — Populate Model Manager dialog
|
||||
- **Action (UI)**: open Model Manager
|
||||
@@ -537,7 +530,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
- **Action (UI)**: open Model Manager
|
||||
- **Assertion**: that model row shows "Installed"
|
||||
|
||||
## 6.5 GET /v2/customnode/versions/{node_name}
|
||||
## 6.4 GET /v2/customnode/versions/{node_name}
|
||||
|
||||
### Goal LV1 — Version dropdown on Install click
|
||||
- **Action (UI)**: click Install on a CNR pack row
|
||||
@@ -548,7 +541,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
- **Action**: direct API call with bogus node_name
|
||||
- **Assertion**: 400; UI shows error or skips
|
||||
|
||||
## 6.6 GET /v2/customnode/disabled_versions/{node_name}
|
||||
## 6.5 GET /v2/customnode/disabled_versions/{node_name}
|
||||
|
||||
### Goal LDV1 — Show disabled versions for re-enable
|
||||
- **Precondition**: pack has disabled versions
|
||||
@@ -556,7 +549,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
- **Observable**: dropdown options
|
||||
- **Assertion**: options match backend disabled_versions response
|
||||
|
||||
## 6.7 POST /v2/customnode/install/git_url
|
||||
## 6.6 POST /v2/customnode/install/git_url
|
||||
|
||||
### Goal LGU1 — Install via "Install via Git URL" button
|
||||
- **Precondition**: security_level ≥ high+; pack absent
|
||||
@@ -568,7 +561,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
- **Precondition**: security_level < high+
|
||||
- **Assertion**: 403 from API; UI shows error; no clone occurs
|
||||
|
||||
## 6.8 POST /v2/customnode/install/pip
|
||||
## 6.7 POST /v2/customnode/install/pip
|
||||
|
||||
### Goal LPP1 — Install pip packages via UI
|
||||
- **Action (UI)**: trigger pip install flow with known package
|
||||
@@ -578,7 +571,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
|
||||
### Goal LPP2 — Security gate
|
||||
- **Assertion**: 403 at lower security; no pip invocation
|
||||
|
||||
## 6.9 GET /v2/manager/notice
|
||||
## 6.8 GET /v2/manager/notice
|
||||
|
||||
### Goal LN1 — Fetch and display News
|
||||
- **Precondition**: GitHub reachable
|
||||
@@ -666,7 +659,7 @@ Reusable verification templates organized by intent category. Apply the template
|
||||
|
||||
**Security tiers to cover**:
|
||||
- `middle` — reboot, snapshot/remove, _uninstall, _update
|
||||
- `middle+` — update_all, snapshot/restore, _install_custom_node, _install_model
|
||||
- `middle+` — update_all, _install_custom_node, _install_model
|
||||
- `high+` — comfyui_switch_version, install/git_url, install/pip, non-safetensors model, _fix (`middle` → `high` in commit `c8992e5d`; subsequent `high` → `high+` in WI-#235 to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text)
|
||||
|
||||
**Path-traversal sub-template** (within security boundary):
|
||||
@@ -752,7 +745,7 @@ Reusable verification templates organized by intent category. Apply the template
|
||||
|
||||
| Intent category | Template | Scenarios using | Test type needed |
|
||||
|---|---|---:|---|
|
||||
| User capability | 7.1 | 62 | E2E effect verification (real install/remove/save etc.) |
|
||||
| User capability | 7.1 | 61 | E2E effect verification (real install/remove/save etc.) |
|
||||
| Input resilience | 7.2 | 32 | Negative tests with negative-check assertions |
|
||||
| Security boundary | 7.3 | 15 | Permission tests at each security level |
|
||||
| Observability | 7.4 | 16 | GET correctness + traceability tests |
|
||||
|
||||
@@ -175,3 +175,9 @@ def import_glob_security_utils():
|
||||
(the glob copy of the security_level gate matrix — guard rows
|
||||
SC-25C / SC-28)."""
|
||||
return _import_real("comfyui_manager.glob.utils.security_utils")
|
||||
|
||||
|
||||
# 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')
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
git_helper.py runs as a subprocess on Windows and must NOT import comfyui_manager.
|
||||
Tests validate: (1) no forbidden imports via AST, (2) subprocess-level standalone
|
||||
execution, (3) get_backup_branch_name behavioural correctness.
|
||||
execution, (3) get_backup_branch_name behavioural correctness, for the copy in
|
||||
git_helper.py and the copy in timestamp_utils.py that both cores call, (4) the name
|
||||
each core gets for a real repository.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -16,6 +19,14 @@ import pytest
|
||||
_GIT_HELPER_PATH = pathlib.Path(__file__).resolve().parents[2] / "comfyui_manager" / "common" / "git_helper.py"
|
||||
|
||||
|
||||
def _load_common_module(name):
|
||||
"""Load a standalone module of comfyui_manager/common without importing the package."""
|
||||
spec = importlib.util.spec_from_file_location(name, _GIT_HELPER_PATH.with_name(f"{name}.py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. No comfyui_manager imports (AST check — no execution)
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -81,12 +92,25 @@ def test_standalone_subprocess_can_load(tmp_path):
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. get_backup_branch_name behavioural tests (function extracted via AST)
|
||||
# 3. get_backup_branch_name behavioural tests, for both copies of the function
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def _get_backup_branch_name():
|
||||
"""Extract and compile get_backup_branch_name from git_helper.py source."""
|
||||
@pytest.fixture(params=["git_helper", "timestamp_utils"])
|
||||
def _get_backup_branch_name(request, monkeypatch):
|
||||
"""Return get_backup_branch_name from git_helper.py or from timestamp_utils.py."""
|
||||
import time
|
||||
|
||||
# Branch setup and the function call must use the same second.
|
||||
strftime = time.strftime
|
||||
fixed_time = time.struct_time((2026, 9, 17, 12, 0, 0, 3, 260, -1))
|
||||
monkeypatch.setattr(time, "strftime", lambda fmt, *args: strftime(fmt, args[0] if args else fixed_time))
|
||||
|
||||
if request.param == "timestamp_utils":
|
||||
timestamp_utils = _load_common_module("timestamp_utils")
|
||||
monkeypatch.setattr(timestamp_utils, "get_timestamp_for_filename", lambda: time.strftime("%Y%m%d_%H%M%S"))
|
||||
return timestamp_utils.get_backup_branch_name
|
||||
|
||||
# git_helper.py runs its command line on import, so the function is compiled from its source.
|
||||
source = _GIT_HELPER_PATH.read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
|
||||
@@ -108,21 +132,21 @@ class _FakeHead:
|
||||
|
||||
class _FakeRepo:
|
||||
def __init__(self, branch_names):
|
||||
self.heads = [_FakeHead(n) for n in branch_names]
|
||||
self._heads = [_FakeHead(n) for n in branch_names]
|
||||
|
||||
def list_heads(self):
|
||||
return self._heads
|
||||
|
||||
|
||||
def test_basic_name_format(_get_backup_branch_name):
|
||||
import time
|
||||
name = _get_backup_branch_name()
|
||||
assert name.startswith("backup_")
|
||||
expected = f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
|
||||
assert name == expected
|
||||
assert _get_backup_branch_name() == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
|
||||
def test_no_collision(_get_backup_branch_name):
|
||||
import time
|
||||
repo = _FakeRepo(["main", "dev"])
|
||||
name = _get_backup_branch_name(repo)
|
||||
assert name.startswith("backup_")
|
||||
assert _get_backup_branch_name(repo) == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
|
||||
def test_single_collision(_get_backup_branch_name):
|
||||
@@ -141,22 +165,16 @@ def test_multi_collision(_get_backup_branch_name):
|
||||
assert name == f"backup_{ts}_3"
|
||||
|
||||
|
||||
def test_repo_none_returns_base(_get_backup_branch_name):
|
||||
name = _get_backup_branch_name(None)
|
||||
assert name.startswith("backup_")
|
||||
|
||||
|
||||
def test_repo_heads_exception_returns_base(_get_backup_branch_name):
|
||||
"""When repo.heads raises, fall back to base name without suffix."""
|
||||
def test_repo_list_heads_exception_returns_base(_get_backup_branch_name):
|
||||
"""When listing branches fails, return the timestamp without a suffix."""
|
||||
import time
|
||||
|
||||
class _BrokenRepo:
|
||||
@property
|
||||
def heads(self):
|
||||
def list_heads(self):
|
||||
raise RuntimeError("simulated git error")
|
||||
|
||||
name = _get_backup_branch_name(_BrokenRepo())
|
||||
assert name.startswith("backup_")
|
||||
assert "_1" not in name # no suffix — exception path returns base
|
||||
assert name == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
|
||||
|
||||
|
||||
def test_uuid_fallback_on_full_collision(_get_backup_branch_name):
|
||||
@@ -171,3 +189,33 @@ def test_uuid_fallback_on_full_collision(_get_backup_branch_name):
|
||||
# UUID suffix is 6 hex chars
|
||||
suffix = name[len(f"backup_{ts}_"):]
|
||||
assert len(suffix) == 6, f"Expected 6-char UUID suffix, got: {suffix}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. The name each core gets for a real repository
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _open_as_legacy_core(path):
|
||||
"""The legacy core opens GitPython's git.Repo, which has `heads` and no `list_heads()`."""
|
||||
import git
|
||||
return git.Repo(path)
|
||||
|
||||
|
||||
def _open_as_glob_core(path):
|
||||
"""The glob core opens the repository through git_compat."""
|
||||
return _load_common_module("git_compat").open_repo(str(path))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("open_repo", [_open_as_legacy_core, _open_as_glob_core], ids=["legacy core", "glob core"])
|
||||
def test_real_repository_with_a_backup_from_the_same_second(open_repo, tmp_path, monkeypatch):
|
||||
"""A backup branch of the same second exists, so the next free name is returned."""
|
||||
git = pytest.importorskip("git")
|
||||
timestamp_utils = _load_common_module("timestamp_utils")
|
||||
monkeypatch.setattr(timestamp_utils, "get_timestamp_for_filename", lambda: "20260917_120000")
|
||||
|
||||
with git.Repo.init(tmp_path) as repo:
|
||||
repo.index.commit("initial")
|
||||
repo.create_head("backup_20260917_120000")
|
||||
|
||||
with open_repo(tmp_path) as repo:
|
||||
assert timestamp_utils.get_backup_branch_name(repo) == "backup_20260917_120000_1"
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Cross-platform E2E environment setup for ComfyUI + Manager.
|
||||
|
||||
Creates an isolated ComfyUI installation with ComfyUI-Manager for E2E testing.
|
||||
Idempotent: skips setup if marker file and key artifacts already exist.
|
||||
Idempotent: skips setup if marker, key artifacts, and a supported venv already exist.
|
||||
uv reads the Manager project's Python requirement when creating a venv.
|
||||
|
||||
Input env vars:
|
||||
E2E_ROOT — target directory (required)
|
||||
MANAGER_ROOT — manager repo root (default: auto-detected)
|
||||
COMFYUI_BRANCH — ComfyUI branch to clone (default: master)
|
||||
UV_PYTHON — optional uv Python request for a new venv
|
||||
|
||||
Output (last line of stdout):
|
||||
E2E_ROOT=/path/to/environment
|
||||
@@ -46,6 +48,18 @@ def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(cmd, check=True, **kwargs)
|
||||
|
||||
|
||||
def check_python_version(python: str) -> None:
|
||||
try:
|
||||
version = subprocess.check_output(
|
||||
[python, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"],
|
||||
text=True,
|
||||
).strip()
|
||||
except (OSError, subprocess.CalledProcessError) as exc:
|
||||
die(f"Cannot run venv Python: {python}: {exc}. Recreate the E2E environment with Python 3.10+.")
|
||||
if tuple(map(int, version.split("."))) < (3, 10):
|
||||
die(f"Python 3.10+ required, found {version} ({python}). Recreate the E2E environment.")
|
||||
|
||||
|
||||
def detect_manager_root() -> Path:
|
||||
"""Walk up from this script to find pyproject.toml."""
|
||||
d = Path(__file__).resolve().parent
|
||||
@@ -69,7 +83,7 @@ def venv_bin(root: Path, name: str) -> str:
|
||||
return str(root / "venv" / "bin" / name)
|
||||
|
||||
|
||||
def is_already_setup(root: Path, manager_root: Path) -> bool:
|
||||
def is_already_setup(root: Path) -> bool:
|
||||
marker = root / ".e2e_setup_complete"
|
||||
comfyui = root / "comfyui"
|
||||
venv = root / "venv"
|
||||
@@ -119,7 +133,9 @@ def main() -> None:
|
||||
branch = os.environ.get("COMFYUI_BRANCH", "master")
|
||||
|
||||
# Idempotency
|
||||
if is_already_setup(root, manager_root):
|
||||
if (root / "venv").is_dir():
|
||||
check_python_version(venv_python(root))
|
||||
if is_already_setup(root):
|
||||
log("Environment already set up (marker file exists). Skipping.")
|
||||
print(f"E2E_ROOT={root}")
|
||||
return
|
||||
@@ -138,7 +154,8 @@ def main() -> None:
|
||||
log("Step 2/7: venv already exists, skipping")
|
||||
else:
|
||||
log("Step 2/7: Creating virtual environment...")
|
||||
run(["uv", "venv", str(venv_dir)])
|
||||
run(["uv", "venv", "--project", str(manager_root), str(venv_dir)])
|
||||
check_python_version(venv_python(root))
|
||||
|
||||
py = venv_python(root)
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
# setup_e2e_env.sh — Automated E2E environment setup for ComfyUI + Manager
|
||||
#
|
||||
# Creates an isolated ComfyUI installation with ComfyUI-Manager for E2E testing.
|
||||
# Idempotent: skips setup if marker file and key artifacts already exist.
|
||||
# Idempotent: skips setup if marker, key artifacts, and a supported venv already exist.
|
||||
#
|
||||
# Input env vars:
|
||||
# E2E_ROOT — target directory (default: auto-generated via mktemp)
|
||||
# MANAGER_ROOT — manager repo root (default: auto-detected from script location)
|
||||
# COMFYUI_BRANCH — ComfyUI branch to clone (default: master)
|
||||
# PYTHON — Python executable (default: python3)
|
||||
# UV_PYTHON — optional uv Python request for a new venv
|
||||
#
|
||||
# Output (last line of stdout):
|
||||
# E2E_ROOT=/path/to/environment
|
||||
@@ -44,29 +44,25 @@ detect_manager_root() {
|
||||
return 1
|
||||
}
|
||||
|
||||
check_python_version() {
|
||||
"$1" -c 'import sys
|
||||
if sys.version_info < (3, 10):
|
||||
sys.exit(f"Python 3.10+ required, found {sys.version_info.major}.{sys.version_info.minor}")' \
|
||||
|| die "Cannot use venv Python: $1. Recreate the E2E environment with Python 3.10+."
|
||||
}
|
||||
|
||||
# --- Validate prerequisites ---
|
||||
validate_prerequisites() {
|
||||
local py="${PYTHON:-python3}"
|
||||
local missing=()
|
||||
|
||||
command -v git >/dev/null 2>&1 || missing+=("git")
|
||||
command -v uv >/dev/null 2>&1 || missing+=("uv")
|
||||
command -v "$py" >/dev/null 2>&1 || missing+=("$py")
|
||||
|
||||
if [[ ${#missing[@]} -gt 0 ]]; then
|
||||
die "Missing prerequisites: ${missing[*]}"
|
||||
fi
|
||||
|
||||
# Verify Python version >= 3.9
|
||||
local py_version
|
||||
py_version=$("$py" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
|
||||
local major minor
|
||||
major="${py_version%%.*}"
|
||||
minor="${py_version##*.}"
|
||||
if [[ "$major" -lt 3 ]] || { [[ "$major" -eq 3 ]] && [[ "$minor" -lt 9 ]]; }; then
|
||||
die "Python 3.9+ required, found $py_version"
|
||||
fi
|
||||
log "Prerequisites OK (python=$py_version, git=$(git --version | awk '{print $3}'), uv=$(uv --version 2>&1 | awk '{print $2}'))"
|
||||
log "Prerequisites OK (git=$(git --version | awk '{print $3}'), uv=$(uv --version 2>&1 | awk '{print $2}'))"
|
||||
}
|
||||
|
||||
# --- Check idempotency: skip if already set up ---
|
||||
@@ -151,7 +147,6 @@ log "MANAGER_ROOT=$MANAGER_ROOT"
|
||||
# Validate prerequisites
|
||||
validate_prerequisites
|
||||
|
||||
PYTHON="${PYTHON:-python3}"
|
||||
COMFYUI_BRANCH="${COMFYUI_BRANCH:-master}"
|
||||
|
||||
# Create or use E2E_ROOT
|
||||
@@ -166,6 +161,9 @@ else
|
||||
fi
|
||||
|
||||
# Idempotency check
|
||||
if [[ -d "$E2E_ROOT/venv" ]]; then
|
||||
check_python_version "$E2E_ROOT/venv/bin/python"
|
||||
fi
|
||||
check_already_setup "$E2E_ROOT"
|
||||
|
||||
# Cleanup trap: remove E2E_ROOT on failure only if we created it
|
||||
@@ -191,7 +189,8 @@ log "Step 2/8: Creating virtual environment..."
|
||||
if [[ -d "$E2E_ROOT/venv" ]]; then
|
||||
log " venv already exists, skipping"
|
||||
else
|
||||
uv venv "$E2E_ROOT/venv"
|
||||
uv venv --project "$MANAGER_ROOT" "$E2E_ROOT/venv"
|
||||
check_python_version "$E2E_ROOT/venv/bin/python"
|
||||
fi
|
||||
VENV_PY="$E2E_ROOT/venv/bin/python"
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ def _assert_config_ini_persists_across_reboot(
|
||||
to work.
|
||||
"""
|
||||
try:
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
if resp.status_code == 403:
|
||||
pytest.skip(
|
||||
"reboot denied by security policy "
|
||||
|
||||
+23
-51
@@ -149,14 +149,14 @@ class TestCsrfPostWorks:
|
||||
|
||||
def test_queue_reset_post_works(self, comfyui):
|
||||
"""POST queue/reset should succeed (the same path rejects GET)."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
|
||||
def test_snapshot_save_post_works(self, comfyui):
|
||||
"""POST snapshot/save should succeed."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
@@ -168,6 +168,7 @@ class TestCsrfPostWorks:
|
||||
requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": items[0]},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
@@ -207,18 +208,10 @@ class TestCsrfReadEndpointsStillAllowGet:
|
||||
# Content-Type gate — second CSRF mitigation layer
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# GET→POST conversion alone does NOT block <form method=POST> from a malicious
|
||||
# cross-origin page, because browsers mark form submissions with one of three
|
||||
# CORS "simple request" Content-Types (Fetch spec §3.2.3) and do NOT preflight
|
||||
# them. These 9 high-risk state mutation endpoints therefore additionally
|
||||
# reject those three MIME types at the handler entry. Bare POST (no body) and
|
||||
# application/json remain accepted — same-origin fetch() and existing
|
||||
# manager-core JS callers are unaffected.
|
||||
#
|
||||
# Source of truth for the gated handler list:
|
||||
# comfyui_manager/common/manager_security.py :: reject_simple_form_post
|
||||
# comfyui_manager/glob/manager_server.py :: 9 handlers call it
|
||||
FORM_REJECTED_POST_ENDPOINTS = [
|
||||
# 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.
|
||||
# It cannot send application/json without a preflight.
|
||||
BODYLESS_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_all",
|
||||
"/v2/snapshot/remove",
|
||||
"/v2/snapshot/restore",
|
||||
@@ -228,65 +221,47 @@ FORM_REJECTED_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_comfyui",
|
||||
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
|
||||
# migrated from query-string to JSON body, now a body-reading handler.
|
||||
# Per the module policy in common/manager_security.py, body-reading
|
||||
# handlers are NOT gated (CORS preflight on application/json already
|
||||
# blocks cross-origin form POST forgery).
|
||||
"/v2/manager/reboot",
|
||||
]
|
||||
|
||||
SIMPLE_FORM_CONTENT_TYPES = [
|
||||
NOT_JSON_CONTENT_TYPES = [
|
||||
None,
|
||||
"application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
|
||||
"text/plain",
|
||||
]
|
||||
|
||||
|
||||
class TestFormContentTypeRejected:
|
||||
"""Every gated state-changing endpoint MUST reject CORS simple-request
|
||||
Content-Types to block preflight-less <form method=POST> CSRF.
|
||||
|
||||
Matrix: 9 endpoints × 3 Content-Types = 27 assertions.
|
||||
"""
|
||||
|
||||
class TestContentTypeThatIsNotJsonRejected:
|
||||
@pytest.mark.parametrize(
|
||||
"content_type",
|
||||
SIMPLE_FORM_CONTENT_TYPES,
|
||||
ids=["urlencoded", "multipart", "textplain"],
|
||||
NOT_JSON_CONTENT_TYPES,
|
||||
ids=["none", "urlencoded", "multipart", "textplain"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
FORM_REJECTED_POST_ENDPOINTS,
|
||||
ids=FORM_REJECTED_POST_ENDPOINTS,
|
||||
BODYLESS_POST_ENDPOINTS,
|
||||
ids=BODYLESS_POST_ENDPOINTS,
|
||||
)
|
||||
def test_form_content_type_rejected(self, comfyui, path, content_type):
|
||||
"""POST with a simple-form Content-Type must be rejected with 400.
|
||||
|
||||
The handler's Content-Type gate runs BEFORE the security_level check,
|
||||
def test_content_type_that_is_not_json_rejected(self, comfyui, path, content_type):
|
||||
"""The handler's Content-Type gate runs BEFORE the security_level check,
|
||||
so the expected status is 400 even under security levels that would
|
||||
otherwise return 403.
|
||||
"""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}{path}",
|
||||
headers={"Content-Type": content_type},
|
||||
data="", # empty body still counts: browsers would not preflight
|
||||
headers={} if content_type is None else {"Content-Type": content_type},
|
||||
data="",
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
f"CSRF FORM-POST GATE BYPASS: POST {path} with "
|
||||
f"CSRF GATE BYPASS: POST {path} with "
|
||||
f"Content-Type={content_type!r} returned {resp.status_code} "
|
||||
f"(expected 400): {resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
class TestNoBodyPostStillAccepted:
|
||||
"""Positive control: bare POST (no body, no Content-Type) must still pass
|
||||
the form-content-type gate.
|
||||
|
||||
The existing frontend (snapshot.js, comfyui-manager.js, etc.) issues
|
||||
fetch()/XHR POSTs without an explicit body for these idempotent-ish
|
||||
operations; a regression here would break those callers.
|
||||
"""
|
||||
|
||||
class TestJsonPostWithoutBodyAccepted:
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
# Subset — pick endpoints whose happy path is deterministic under the
|
||||
@@ -300,16 +275,13 @@ class TestNoBodyPostStillAccepted:
|
||||
],
|
||||
ids=["queue-reset", "queue-start", "snapshot-save"],
|
||||
)
|
||||
def test_no_body_post_still_accepted(self, comfyui, path):
|
||||
"""Bare POST (no Content-Type, no body) must NOT be rejected by the
|
||||
form-content-type gate. Any response other than 400-with-form-text
|
||||
proves the gate did not fire."""
|
||||
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
|
||||
def test_json_post_without_body_accepted(self, comfyui, path):
|
||||
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
# The gate returns 400 with a very specific text. Non-gate 400s
|
||||
# (validation errors, etc.) are allowed — we only assert the gate
|
||||
# itself didn't trigger.
|
||||
if resp.status_code == 400:
|
||||
assert "Invalid Content-Type for this endpoint" not in resp.text, (
|
||||
f"POST {path} (bare) hit the form-content-type gate: "
|
||||
f"POST {path} (application/json) hit the content-type gate: "
|
||||
f"{resp.text[:200]}"
|
||||
)
|
||||
|
||||
@@ -182,14 +182,14 @@ class TestLegacyCsrfPostWorks:
|
||||
|
||||
def test_queue_reset_post_works(self, comfyui_legacy):
|
||||
"""POST queue/reset should succeed (the same path rejects GET)."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
|
||||
def test_snapshot_save_post_works(self, comfyui_legacy):
|
||||
"""POST snapshot/save should succeed on legacy."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
@@ -201,6 +201,7 @@ class TestLegacyCsrfPostWorks:
|
||||
requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": items[0]},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
@@ -280,11 +281,10 @@ class TestLegacyIsLegacyManagerUIReturnsTrue:
|
||||
# Content-Type gate — legacy-side parity with test_e2e_csrf.py
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# The 9 legacy handlers mirrored from glob each call
|
||||
# manager_security.reject_simple_form_post() before their security-level
|
||||
# check. This suite verifies the legacy route table enforces the same
|
||||
# CORS-simple-request Content-Type rejection contract.
|
||||
LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
|
||||
# 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.
|
||||
# It cannot send application/json without a preflight.
|
||||
LEGACY_BODYLESS_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/update_all",
|
||||
"/v2/snapshot/remove",
|
||||
"/v2/snapshot/restore",
|
||||
@@ -293,57 +293,46 @@ LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
|
||||
"/v2/manager/queue/start",
|
||||
"/v2/manager/queue/update_comfyui",
|
||||
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
|
||||
# migrated from query-string to JSON body on legacy + glob in parallel,
|
||||
# body-reading handler is not Content-Type-gated (see module policy in
|
||||
# common/manager_security.py).
|
||||
# migrated from query-string to JSON body on legacy + glob in parallel.
|
||||
"/v2/manager/reboot",
|
||||
]
|
||||
|
||||
LEGACY_SIMPLE_FORM_CONTENT_TYPES = [
|
||||
LEGACY_NOT_JSON_CONTENT_TYPES = [
|
||||
None,
|
||||
"application/x-www-form-urlencoded",
|
||||
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
|
||||
"text/plain",
|
||||
]
|
||||
|
||||
|
||||
class TestLegacyFormContentTypeRejected:
|
||||
"""Legacy counterpart to TestFormContentTypeRejected in test_e2e_csrf.py.
|
||||
|
||||
Matrix: 9 endpoints × 3 Content-Types = 27 assertions against the legacy
|
||||
route table.
|
||||
"""
|
||||
|
||||
class TestLegacyContentTypeThatIsNotJsonRejected:
|
||||
@pytest.mark.parametrize(
|
||||
"content_type",
|
||||
LEGACY_SIMPLE_FORM_CONTENT_TYPES,
|
||||
ids=["urlencoded", "multipart", "textplain"],
|
||||
LEGACY_NOT_JSON_CONTENT_TYPES,
|
||||
ids=["none", "urlencoded", "multipart", "textplain"],
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
LEGACY_FORM_REJECTED_POST_ENDPOINTS,
|
||||
ids=LEGACY_FORM_REJECTED_POST_ENDPOINTS,
|
||||
LEGACY_BODYLESS_POST_ENDPOINTS,
|
||||
ids=LEGACY_BODYLESS_POST_ENDPOINTS,
|
||||
)
|
||||
def test_form_content_type_rejected(
|
||||
def test_content_type_that_is_not_json_rejected(
|
||||
self, comfyui_legacy, path, content_type
|
||||
):
|
||||
"""POST with a simple-form Content-Type must be rejected with 400
|
||||
on the legacy route table as well."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}{path}",
|
||||
headers={"Content-Type": content_type},
|
||||
headers={} if content_type is None else {"Content-Type": content_type},
|
||||
data="",
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
f"CSRF FORM-POST GATE BYPASS (legacy): POST {path} with "
|
||||
f"CSRF GATE BYPASS (legacy): POST {path} with "
|
||||
f"Content-Type={content_type!r} returned {resp.status_code} "
|
||||
f"(expected 400): {resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
class TestLegacyNoBodyPostStillAccepted:
|
||||
"""Positive control for the legacy route table: bare POST still works."""
|
||||
|
||||
class TestLegacyJsonPostWithoutBodyAccepted:
|
||||
@pytest.mark.parametrize(
|
||||
"path",
|
||||
[
|
||||
@@ -353,13 +342,11 @@ class TestLegacyNoBodyPostStillAccepted:
|
||||
],
|
||||
ids=["queue-reset", "queue-start", "snapshot-save"],
|
||||
)
|
||||
def test_no_body_post_still_accepted(self, comfyui_legacy, path):
|
||||
"""Bare POST (no Content-Type, no body) must not hit the gate on
|
||||
legacy either."""
|
||||
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
|
||||
def test_json_post_without_body_accepted(self, comfyui_legacy, path):
|
||||
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
if resp.status_code == 400:
|
||||
assert "Invalid Content-Type for this endpoint" not in resp.text, (
|
||||
f"POST {path} (bare, legacy) hit the form-content-type gate: "
|
||||
f"POST {path} (application/json, legacy) hit the content-type gate: "
|
||||
f"{resp.text[:200]}"
|
||||
)
|
||||
|
||||
|
||||
@@ -49,6 +49,10 @@ PACK_VERSION = "1.0.1"
|
||||
POLL_TIMEOUT = 30 # max seconds to wait for an operation
|
||||
POLL_INTERVAL = 0.5 # seconds between polls
|
||||
|
||||
# A fresh environment has no cache of the Registry list. Manager fetches the
|
||||
# list when the server starts, and an install is refused until it is cached.
|
||||
REGISTRY_TIMEOUT = 300
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not E2E_ROOT
|
||||
or not os.path.isfile(os.path.join(E2E_ROOT, ".e2e_setup_complete")),
|
||||
@@ -98,7 +102,7 @@ def _queue_task(task: dict) -> None:
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
@@ -143,6 +147,11 @@ def _wait_for(predicate, timeout=POLL_TIMEOUT, interval=POLL_INTERVAL):
|
||||
return False
|
||||
|
||||
|
||||
def _registry_list_is_cached() -> bool:
|
||||
cache = os.path.join(COMFYUI_PATH, "user", "__manager", "cache")
|
||||
return os.path.isdir(cache) and any(name.endswith("_nodes.json") for name in os.listdir(cache))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -152,9 +161,14 @@ def comfyui():
|
||||
"""Start ComfyUI once for the module, stop after all tests."""
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
pid = _start_comfyui()
|
||||
yield pid
|
||||
_stop_comfyui()
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
try:
|
||||
assert _wait_for(_registry_list_is_cached, timeout=REGISTRY_TIMEOUT), (
|
||||
f"Manager did not cache the Registry list within {REGISTRY_TIMEOUT}s; an install fails without it"
|
||||
)
|
||||
yield pid
|
||||
finally:
|
||||
_stop_comfyui()
|
||||
_remove_pack(PACK_DIR_NAME)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -99,7 +99,7 @@ REGISTRY_BOOTSTRAP = '''
|
||||
import json, os, urllib.request
|
||||
from comfyui_manager.common import cnr_utils, manager_util
|
||||
cnr_utils.base_url = os.environ['CM_E2E_REGISTRY']
|
||||
with urllib.request.urlopen(cnr_utils.base_url + '/nodes') as response:
|
||||
with urllib.request.urlopen(os.environ['CM_E2E_CATALOG_URL']) as response:
|
||||
manager_util.save_to_cache(cnr_utils.base_url + '/nodes', json.load(response))
|
||||
'''
|
||||
BOOTSTRAP = '''
|
||||
@@ -135,7 +135,8 @@ def prepare_environment(root, override, security, registry):
|
||||
PYTHONPATH=os.pathsep.join([str(root), str(REPO_ROOT), str(E2E_ROOT / 'comfyui')]),
|
||||
COMFYUI_PATH=str(E2E_ROOT / 'comfyui'), COMFYUI_FOLDERS_BASE_PATH=str(root),
|
||||
CM_E2E_BASE=str(root),
|
||||
CM_E2E_MAIN=str(E2E_ROOT / 'comfyui/main.py'), CM_E2E_REGISTRY=registry.url)
|
||||
CM_E2E_MAIN=str(E2E_ROOT / 'comfyui/main.py'), CM_E2E_REGISTRY=registry.url,
|
||||
CM_E2E_CATALOG_URL=getattr(registry, 'catalog_url', registry.url + '/nodes'))
|
||||
return env
|
||||
|
||||
|
||||
@@ -197,11 +198,11 @@ def comfy_server(request, tmp_path_factory, registry):
|
||||
yield server
|
||||
|
||||
|
||||
def install(server, node, version, operation='install'):
|
||||
def install(server, node, version, operation='install', *, repository='https://example.invalid/fixture'):
|
||||
ui_id = uuid.uuid4().hex
|
||||
params = {'id': node, 'version': '1.0.0', 'selected_version': version,
|
||||
'mode': 'cache', 'channel': 'default', 'ui_id': ui_id,
|
||||
'repository': 'https://example.invalid/fixture'}
|
||||
'repository': repository}
|
||||
if server.tree == 'legacy':
|
||||
response = requests.post(server.base + '/v2/manager/queue/batch',
|
||||
json={'batch_id': ui_id, operation: [params]}, timeout=10)
|
||||
@@ -216,7 +217,7 @@ def install(server, node, version, operation='install'):
|
||||
'ui_id': ui_id, 'client_id': 'flagged-e2e', 'kind': operation, 'params': params,
|
||||
}, timeout=10)
|
||||
response.raise_for_status()
|
||||
requests.post(server.base + '/v2/manager/queue/start', timeout=10).raise_for_status()
|
||||
requests.post(server.base + '/v2/manager/queue/start', headers={'Content-Type': 'application/json'}, timeout=10).raise_for_status()
|
||||
query = {'ui_id': ui_id}
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
@@ -229,9 +230,47 @@ def install(server, node, version, operation='install'):
|
||||
pytest.fail('Install did not complete:\n' + (server.root / 'server.log').read_text()[-6000:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('command', ['save-snapshot', 'restore-snapshot'])
|
||||
def test_cli_does_not_create_server_whitelist(tmp_path, command):
|
||||
base = tmp_path / 'cli-base'
|
||||
(base / 'custom_nodes').mkdir(parents=True)
|
||||
server_manager = tmp_path / 'server-user/__manager'
|
||||
server_manager.mkdir(parents=True)
|
||||
whitelist = server_manager / 'nodepack-whitelist.list'
|
||||
whitelist.write_text('comfyui-impact-pack\n')
|
||||
requested_user = tmp_path / 'requested-user'
|
||||
# Stop after CLI initialization, before any snapshot work or network access.
|
||||
if command == 'save-snapshot':
|
||||
arguments = [command, '--user-directory', str(requested_user),
|
||||
'--output', str(tmp_path / 'invalid-extension.txt')]
|
||||
expected_error = 'output path should be either'
|
||||
else:
|
||||
arguments = [command, str(tmp_path / 'missing-snapshot.json')]
|
||||
expected_error = 'is not exists.'
|
||||
bootstrap = '''
|
||||
import runpy, sys
|
||||
from comfy.cli_args import args
|
||||
args.base_directory = sys.argv[1]
|
||||
sys.argv = ['cm-cli', *sys.argv[2:]]
|
||||
runpy.run_module('cm_cli', run_name='__main__')
|
||||
'''
|
||||
env = dict(os.environ,
|
||||
PYTHONPATH=os.pathsep.join([str(REPO_ROOT), str(E2E_ROOT / 'comfyui')]),
|
||||
COMFYUI_PATH=str(E2E_ROOT / 'comfyui'), COMFYUI_FOLDERS_BASE_PATH=str(base),
|
||||
_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED='false',
|
||||
_COMFYUI_MANAGER_CNR_WHITELIST_DIR=str(server_manager))
|
||||
result = subprocess.run([str(E2E_ROOT / 'venv/bin/python'), '-c', bootstrap,
|
||||
str(base), *arguments], env=env, cwd=tmp_path,
|
||||
capture_output=True, text=True, timeout=30)
|
||||
output = result.stdout + result.stderr
|
||||
assert result.returncode == 1 and expected_error in output, output
|
||||
assert whitelist.read_text() == 'comfyui-impact-pack\n'
|
||||
assert sorted(tmp_path.rglob('nodepack-whitelist.list')) == [whitelist]
|
||||
|
||||
|
||||
def assert_terminal_guidance(log):
|
||||
for detail in ('--listen 127.0.0.1', '--listen ::1', '0.0.0.0', '[default]',
|
||||
'allow_flagged_nodepack_install = true', 'config.ini',
|
||||
'allow_flagged_nodepack_install = true', 'config.ini', 'nodepack-whitelist.list',
|
||||
'trusted private network', 'Restart ComfyUI'):
|
||||
assert detail in log
|
||||
|
||||
@@ -274,6 +313,124 @@ def test_install_policy(comfy_server, node, version):
|
||||
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
def test_whitelist_install_policy(tmp_path, registry, tree):
|
||||
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry) as server:
|
||||
log_path = tmp_path / 'server.log'
|
||||
whitelist = tmp_path / 'user/__manager/nodepack-whitelist.list'
|
||||
template = whitelist.read_text()
|
||||
assert template.strip() and all(line.lstrip().startswith('#') for line in template.splitlines() if line.strip())
|
||||
# Edited after startup: no restart is required to pick up this policy.
|
||||
whitelist.write_text('Fixture-Flagged\nfixture-banned\nfixture-switch\n')
|
||||
for node, version, expected_error in [
|
||||
('fixture-flagged', '2.0.0', None),
|
||||
('fixture-latest', 'latest', 'This action is not allowed by the current security configuration.'),
|
||||
('fixture-banned', '1.0.0', 'not available node: fixture-banned@1.0.0'),
|
||||
]:
|
||||
log_before = len(log_path.read_text())
|
||||
before = len(registry.calls)
|
||||
result = install(server, node, version)
|
||||
allowed = expected_error is None
|
||||
marker = tmp_path / 'custom_nodes' / node / 'installed.txt'
|
||||
assert marker.exists() is allowed, (result, log_path.read_text()[log_before:])
|
||||
calls = registry.calls[before:]
|
||||
assert any(call.startswith('/zip/') for call in calls) is allowed
|
||||
assert sum('/install' in call for call in calls) == 1, calls
|
||||
assert ('permitted by nodepack whitelist' in log_path.read_text()[log_before:]) is allowed
|
||||
assert 'permitted by nodepack whitelist' not in json.dumps(result)
|
||||
if allowed:
|
||||
assert marker.read_text() == version
|
||||
if tree == 'legacy':
|
||||
assert list(result['nodepack_result'].values()) == ['success'], result
|
||||
else:
|
||||
assert result['history']['result'] == 'success', result
|
||||
else:
|
||||
assert expected_error in json.dumps(result), result
|
||||
if node == 'fixture-latest':
|
||||
assert_flagged_denial(result, log_path.read_text()[log_before:])
|
||||
|
||||
# Removing the file revokes the exception for another listed pack.
|
||||
whitelist.unlink()
|
||||
log_before = len(log_path.read_text())
|
||||
before = len(registry.calls)
|
||||
result = install(server, 'fixture-switch', '2.0.0')
|
||||
assert not (tmp_path / 'custom_nodes/fixture-switch').exists(), result
|
||||
calls = registry.calls[before:]
|
||||
assert sum('/install' in call for call in calls) == 1, calls
|
||||
assert not any(call.startswith('/zip/') for call in calls), calls
|
||||
assert_flagged_denial(result, log_path.read_text()[log_before:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
def test_whitelist_does_not_override_strong_security(tmp_path, registry, tree):
|
||||
with running_server(tmp_path, tree, '0.0.0.0', False, 'strong', registry) as server:
|
||||
(tmp_path / 'user/__manager/nodepack-whitelist.list').write_text('Fixture-Flagged\n')
|
||||
log_path = tmp_path / 'server.log'
|
||||
log_before = len(log_path.read_text())
|
||||
before = len(registry.calls)
|
||||
result = install(server, 'fixture-flagged', '2.0.0')
|
||||
if tree == 'legacy':
|
||||
assert result['failed'] == ['fixture-flagged'], result
|
||||
else:
|
||||
assert result['history']['result'] == 'failed', result
|
||||
assert 'normal or below' in log_path.read_text()[log_before:]
|
||||
assert not (tmp_path / 'custom_nodes/fixture-flagged').exists()
|
||||
assert not any('/install' in call or call.startswith('/zip/') for call in registry.calls[before:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
@pytest.mark.parametrize('keep_listed', [False, True])
|
||||
def test_restart_rechecks_whitelist(tmp_path, registry, tree, keep_listed):
|
||||
whitelist = tmp_path / 'user/__manager/nodepack-whitelist.list'
|
||||
marker = tmp_path / 'custom_nodes/fixture-switch/installed.txt'
|
||||
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry) as server:
|
||||
whitelist.write_text('Fixture-Switch\n')
|
||||
install(server, 'fixture-switch', '1.0.0')
|
||||
install(server, 'fixture-switch', '2.0.0')
|
||||
reserved = tmp_path / 'user/__manager/startup-scripts/install-scripts.txt'
|
||||
assert 'NodeVersionStatusFlagged' in reserved.read_text()
|
||||
assert marker.read_text() == '1.0.0'
|
||||
|
||||
if not keep_listed:
|
||||
whitelist.write_text('fixture-other\n')
|
||||
before = len(registry.calls)
|
||||
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry):
|
||||
assert whitelist.read_text() == ('Fixture-Switch\n' if keep_listed else 'fixture-other\n')
|
||||
calls = registry.calls[before:]
|
||||
assert not any('/install' in call for call in calls), calls
|
||||
assert any(call.startswith('/zip/') for call in calls) is keep_listed, calls
|
||||
assert marker.read_text() == ('2.0.0' if keep_listed else '1.0.0')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
def test_scheduled_snapshot_uses_whitelist(tmp_path, registry, tree):
|
||||
config_dir = tmp_path / 'user/__manager'
|
||||
startup_dir = config_dir / 'startup-scripts'
|
||||
startup_dir.mkdir(parents=True)
|
||||
(config_dir / 'nodepack-whitelist.list').write_text('Fixture-Flagged\n')
|
||||
reservation = startup_dir / 'restore-snapshot.json'
|
||||
reservation.write_text(json.dumps({
|
||||
'cnr_custom_nodes': {'fixture-flagged': '2.0.0', 'fixture-latest': '2.0.0'},
|
||||
'git_custom_nodes': {}, 'file_custom_nodes': [],
|
||||
}))
|
||||
|
||||
before = len(registry.calls)
|
||||
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry):
|
||||
log = (tmp_path / 'server.log').read_text()
|
||||
assert 'Restore snapshot done.' in log, log[-6000:]
|
||||
assert 'Restore snapshot failed.' not in log, log[-6000:]
|
||||
assert not reservation.exists()
|
||||
installed = tmp_path / 'custom_nodes/fixture-flagged'
|
||||
assert 'version = "2.0.0"' in (installed / 'pyproject.toml').read_text()
|
||||
assert not (tmp_path / 'custom_nodes/fixture-latest').exists()
|
||||
assert "CNR installation of 'fixture-flagged' permitted by nodepack whitelist" in log, log[-6000:]
|
||||
assert "CNR installation of 'fixture-latest' permitted by nodepack whitelist" not in log
|
||||
calls = registry.calls[before:]
|
||||
assert sum('/install' in call for call in calls) == 2, calls
|
||||
# torchvision may probe redirects before downloading the same archive.
|
||||
assert {call for call in calls if call.startswith('/zip/')} == {'/zip/fixture-flagged/2.0.0'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['install', 'update'])
|
||||
def test_flagged_transition_preserves_active_version(comfy_server, operation):
|
||||
server = comfy_server
|
||||
@@ -468,7 +625,7 @@ def test_scheduled_snapshot_restores_through_server_restart(
|
||||
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, tree, '127.0.0.1', False, 'normal', registry) as server:
|
||||
with running_server(tmp_path, tree, '127.0.0.1', False, 'normal-', registry) as server:
|
||||
if existing:
|
||||
install(server, 'fixture-snapshot', '1.0.0')
|
||||
assert marker.read_text() == '1.0.0'
|
||||
|
||||
@@ -153,7 +153,7 @@ def _queue_task(task: dict) -> None:
|
||||
"""Queue a Manager task and start the worker."""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=task, timeout=10)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
@@ -348,3 +348,26 @@ class TestNightlyInstallCycle:
|
||||
f"Installed entry {pkg_key!r} still references {PACK_TEST1!r} "
|
||||
f"via cnr_id/aux_id: {pkg!r}"
|
||||
)
|
||||
|
||||
|
||||
class TestGitBackendLine:
|
||||
def test_server_log_has_the_line(self, comfyui):
|
||||
with open(os.path.join(E2E_ROOT, "logs", "comfyui.log")) as f:
|
||||
log = f.read()
|
||||
|
||||
assert "Using GitPython backend" in log or "Using pygit2 backend" in log
|
||||
|
||||
def test_cm_cli_does_not_write_the_line(self, comfyui):
|
||||
r = subprocess.run([_cm_cli_path(), "--help"], capture_output=True, text=True, timeout=120,
|
||||
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
|
||||
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert "Using GitPython backend" not in r.stdout + r.stderr
|
||||
assert "Using pygit2 backend" not in r.stdout + r.stderr
|
||||
|
||||
def test_cm_cli_writes_no_empty_line_before_the_output_of_its_command(self, comfyui):
|
||||
r = subprocess.run([_cm_cli_path(), "simple-show", "snapshot-list"], capture_output=True, text=True, timeout=120,
|
||||
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
|
||||
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert not r.stdout.startswith("\n")
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""E2E positive-path tests for legacy-only GET endpoints.
|
||||
|
||||
SCOPE — closes the 6 pytest-N gaps from reports/api-coverage-matrix.md
|
||||
SCOPE — closes the pytest-N gaps from reports/api-coverage-matrix.md
|
||||
(WI-TT). Each target endpoint is registered ONLY in
|
||||
`comfyui_manager/legacy/manager_server.py` and thus reachable only when
|
||||
ComfyUI runs with `--enable-manager-legacy-ui`.
|
||||
|
||||
Endpoints covered:
|
||||
- GET /customnode/alternatives (legacy L1072)
|
||||
- GET /v2/customnode/disabled_versions/{node_name} (legacy L1273)
|
||||
- GET /v2/customnode/getlist (legacy L1018)
|
||||
- GET /v2/customnode/versions/{node_name} (legacy L1262)
|
||||
@@ -96,25 +95,6 @@ def comfyui_legacy():
|
||||
_stop_comfyui()
|
||||
|
||||
|
||||
class TestLegacyCustomNodeAlternatives:
|
||||
"""GET /customnode/alternatives?mode=local (wi-031)."""
|
||||
|
||||
def test_returns_dict_of_alternatives(self, comfyui_legacy):
|
||||
resp = requests.get(
|
||||
f"{BASE_URL}/customnode/alternatives",
|
||||
params={"mode": "local"},
|
||||
timeout=30,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
f"Expected 200, got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
data = resp.json()
|
||||
assert isinstance(data, dict), (
|
||||
f"alternatives response should be a dict keyed by unified id, "
|
||||
f"got {type(data).__name__}"
|
||||
)
|
||||
|
||||
|
||||
class TestLegacyCustomNodeDisabledVersions:
|
||||
"""GET /v2/customnode/disabled_versions/{node_name} (wi-032).
|
||||
|
||||
|
||||
@@ -320,12 +320,13 @@ class TestUpdateComfyuiQueued:
|
||||
|
||||
def test_direct_endpoint_returns_200(self, comfyui_legacy):
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui", timeout=15
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui", headers={"Content-Type": "application/json"}, timeout=15
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
f"update_comfyui should return 200 at default security_level, "
|
||||
f"got {resp.status_code}: {resp.text[:200]}"
|
||||
)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10).raise_for_status()
|
||||
|
||||
|
||||
class TestInstallModelRealDownload:
|
||||
@@ -468,7 +469,7 @@ class TestSwitchComfyuiSelfSwitch:
|
||||
class TestInstallViaGitUrlRealClone:
|
||||
"""Real E2E for wi-037 POST /v2/customnode/install/git_url.
|
||||
|
||||
Strategy: POST with body=TRUSTED_GIT_URL (plain text). Handler
|
||||
Handler
|
||||
(legacy/manager_server.py:1502-1519) runs core.gitclone_install(url)
|
||||
synchronously; 200 on success + 'After restarting ComfyUI' log;
|
||||
'skip' action on already-installed → also 200.
|
||||
@@ -492,8 +493,7 @@ class TestInstallViaGitUrlRealClone:
|
||||
try:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/git_url",
|
||||
data=TRUSTED_GIT_URL,
|
||||
headers={"Content-Type": "text/plain"},
|
||||
json={"url": TRUSTED_GIT_URL},
|
||||
timeout=180,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -558,8 +558,7 @@ class TestInstallPipRealExecute:
|
||||
try:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/pip",
|
||||
data=TRUSTED_PIP_PKG,
|
||||
headers={"Content-Type": "text/plain"},
|
||||
json={"packages": TRUSTED_PIP_PKG},
|
||||
timeout=30,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
|
||||
@@ -127,7 +127,7 @@ class TestQueueLifecycle:
|
||||
must be 0/False. Any non-zero count here would indicate a leak from an
|
||||
earlier test module or a reset-handler regression.
|
||||
"""
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code == 200, (
|
||||
f"Queue reset failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -179,13 +179,13 @@ class TestQueueLifecycle:
|
||||
`start_worker()` accidentally spawns a hot-loop that never exits.
|
||||
"""
|
||||
# Ensure idle baseline (pending empty before start).
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
pre = requests.get(f"{BASE_URL}/v2/manager/queue/status", timeout=10).json()
|
||||
assert pre["pending_count"] == 0, (
|
||||
f"Pre-condition: pending_count must be 0 before idle-start test, got {pre['pending_count']}"
|
||||
)
|
||||
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code in (200, 201), (
|
||||
f"Queue start returned unexpected status {resp.status_code}"
|
||||
)
|
||||
@@ -223,7 +223,7 @@ class TestQueueLifecycle:
|
||||
# Reset to clean slate. Note: reset wipes pending/running but not
|
||||
# file-based batch history, so we track completion by our OWN ui_id
|
||||
# rather than a global done_count which can reflect unrelated tasks.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
UI_ID = "e2e-queue-lifecycle"
|
||||
# Queue a lightweight task (install a small CNR package)
|
||||
@@ -249,7 +249,7 @@ class TestQueueLifecycle:
|
||||
)
|
||||
|
||||
# Start processing
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert resp.status_code in (200, 201), (
|
||||
f"Queue start failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -342,7 +342,7 @@ class TestQueueLifecycle:
|
||||
}
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=seed_payload, timeout=10)
|
||||
assert r.status_code == 200, f"seed queue/task failed: {r.status_code} {r.text[:200]}"
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
assert r.status_code in (200, 201), f"seed queue/start failed: {r.status_code}"
|
||||
|
||||
def _seed_done():
|
||||
|
||||
@@ -204,13 +204,13 @@ comfyui_flags_h = _make_flags_server_fixture(
|
||||
|
||||
def _post_git_url(url: str) -> requests.Response:
|
||||
return requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/git_url", data=url, timeout=120,
|
||||
f"{BASE_URL}/v2/customnode/install/git_url", json={"url": url}, timeout=120,
|
||||
)
|
||||
|
||||
|
||||
def _post_pip(packages: str) -> requests.Response:
|
||||
return requests.post(
|
||||
f"{BASE_URL}/v2/customnode/install/pip", data=packages, timeout=60,
|
||||
f"{BASE_URL}/v2/customnode/install/pip", json={"packages": packages}, timeout=60,
|
||||
)
|
||||
|
||||
|
||||
@@ -626,7 +626,7 @@ class TestUnknownPipStaysBlocked:
|
||||
# ===========================================================================
|
||||
|
||||
def _batch_op_item(ui_id: str) -> dict:
|
||||
"""Item for middle-gated batch ops (fix/uninstall/update). The GATE
|
||||
"""Item for middle-gated batch ops (uninstall/update). The GATE
|
||||
check precedes node resolution, so a placeholder spec is sufficient:
|
||||
the queue worker's later failure on the nonexistent node is irrelevant
|
||||
to the synchronous gate observable (the response's failed list)."""
|
||||
@@ -646,10 +646,9 @@ class _LegacyGuardRows:
|
||||
flags_label = ""
|
||||
|
||||
def _assert_sc25a(self):
|
||||
"""SC-25A: legacy middle-gated ops (fix/uninstall/update) stay
|
||||
"""SC-25A: legacy middle-gated ops (uninstall/update) stay
|
||||
allowed at sl=normal local for this flag combination."""
|
||||
payload = {
|
||||
"fix": [_batch_op_item(f"sc25a-fix-{self.flags_label}")],
|
||||
"uninstall": [_batch_op_item(f"sc25a-unin-{self.flags_label}")],
|
||||
"update": [_batch_op_item(f"sc25a-upd-{self.flags_label}")],
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ without elevating the security_level to STRONG.
|
||||
|
||||
The 4 T2 SECGATE-PENDING Goals at middle/middle+ that depend on this harness:
|
||||
- SR4 (snapshot/remove, gate=middle) ← THIS PoC
|
||||
- SR6 (snapshot/restore, gate=middle+) ← follow-up
|
||||
- SR6 (snapshot/restore, gate=high+) ← follow-up
|
||||
- V5 (manager/reboot, gate=middle) ← follow-up
|
||||
- UA2 (manager/queue/update_all, gate=middle+) ← follow-up
|
||||
|
||||
@@ -156,6 +156,7 @@ class TestSecurityGate403_SR4:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": seed_name},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
|
||||
|
||||
@@ -181,7 +181,7 @@ class TestSnapshotLifecycle:
|
||||
if os.path.isdir(SNAPSHOT_DIR):
|
||||
files_before = {f for f in os.listdir(SNAPSHOT_DIR) if f.endswith(".json")}
|
||||
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert resp.status_code == 200, (
|
||||
f"Snapshot save failed with status {resp.status_code}"
|
||||
)
|
||||
@@ -251,7 +251,7 @@ class TestSnapshotLifecycle:
|
||||
asserts. Does not depend on prior tests in this module.
|
||||
"""
|
||||
# SETUP: create a snapshot so we have a deterministic target
|
||||
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
|
||||
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
|
||||
assert save_resp.status_code == 200, "setup save failed"
|
||||
|
||||
# Find the newly created snapshot by diffing against pre-save list
|
||||
@@ -267,6 +267,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": target},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -290,6 +291,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": "nonexistent_snapshot_99999"},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
# Server returns 200 even when file doesn't exist (no-op behavior)
|
||||
@@ -317,6 +319,7 @@ class TestSnapshotLifecycle:
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/snapshot/remove",
|
||||
params={"target": target},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
|
||||
@@ -204,7 +204,7 @@ class TestReboot:
|
||||
|
||||
# Trigger reboot — server may drop connection mid-response
|
||||
try:
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
|
||||
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
if resp.status_code == 403:
|
||||
pytest.skip(
|
||||
"Reboot denied by security policy "
|
||||
|
||||
@@ -93,7 +93,7 @@ def _queue_task(task: dict) -> None:
|
||||
timeout=10,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _remove_pack(name: str) -> None:
|
||||
@@ -241,7 +241,7 @@ def _ensure_pack_installed_with_tracking():
|
||||
|
||||
def _reset_queue():
|
||||
"""Reset the queue to clean state."""
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
|
||||
def _wait_queue_idle(timeout=POLL_TIMEOUT):
|
||||
@@ -643,10 +643,10 @@ class TestInstallModel:
|
||||
advances beyond baseline within a bounded timeout)
|
||||
(c) optionally, queue/history records a row matching this ui_id
|
||||
Download completion to a real model file is NOT an E2E responsibility —
|
||||
it depends on external network + the target URL. The test URL points
|
||||
to example.com, which will not yield a valid safetensors file; the
|
||||
task will still transition through running → history (as failed /
|
||||
trivial-success), which is the E2E-observable we need.
|
||||
it depends on external network + the target URL. The test model is
|
||||
not in the model list, so the worker refuses it without a download;
|
||||
the task still transitions through running → history (as failed),
|
||||
which is the E2E-observable we need.
|
||||
"""
|
||||
_reset_queue()
|
||||
|
||||
@@ -696,7 +696,7 @@ class TestInstallModel:
|
||||
# - done_count advanced → task already ran to history
|
||||
# Either proves the enqueued task left the pending state under
|
||||
# worker control. This does NOT assert download success.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
|
||||
def _worker_observed_task() -> bool:
|
||||
try:
|
||||
@@ -827,10 +827,10 @@ class TestUpdateAll:
|
||||
if isinstance(pkg, dict) and pkg.get("enabled", True):
|
||||
active_packs += 1
|
||||
|
||||
# The handler runs reload + get_custom_nodes synchronously, which can
|
||||
# be slow (up to ~2 min on cache-cold runs). Use an explicit long
|
||||
# timeout; a timeout here is a real server-perf regression, NOT
|
||||
# something to hide as a pass.
|
||||
# The handler fetches the whole Registry list before it answers. The
|
||||
# list is fetched 30 nodepacks per page with a pause after each page,
|
||||
# to keep the load on the Registry low: about three minutes for 6,500
|
||||
# nodepacks, and longer as the list grows.
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_all",
|
||||
params={
|
||||
@@ -838,7 +838,8 @@ class TestUpdateAll:
|
||||
"client_id": "e2e-update-all",
|
||||
"ui_id": "e2e-update-all",
|
||||
},
|
||||
timeout=180,
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=600,
|
||||
)
|
||||
|
||||
# Detect expected outcome based on server security configuration.
|
||||
@@ -875,6 +876,7 @@ class TestUpdateAll:
|
||||
"""POST /v2/manager/queue/update_all without required params -> 400."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_all",
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
@@ -903,6 +905,7 @@ class TestUpdateComfyUI:
|
||||
"client_id": "e2e-update-comfyui",
|
||||
"ui_id": "e2e-update-comfyui",
|
||||
},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -927,6 +930,7 @@ class TestUpdateComfyUI:
|
||||
"""POST /v2/manager/queue/update_comfyui without required params -> 400."""
|
||||
resp = requests.post(
|
||||
f"{BASE_URL}/v2/manager/queue/update_comfyui",
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 400, (
|
||||
@@ -944,6 +948,7 @@ class TestUpdateComfyUI:
|
||||
"ui_id": "e2e-update-comfyui-stable",
|
||||
"stable": "true",
|
||||
},
|
||||
headers={"Content-Type": "application/json"},
|
||||
timeout=10,
|
||||
)
|
||||
assert resp.status_code == 200, (
|
||||
@@ -961,7 +966,7 @@ class TestUpdateComfyUI:
|
||||
# never reaches history (silent empty-history regression). The
|
||||
# actual update work will fail fast in E2E (no real git remote),
|
||||
# but the task completes and moves to history regardless.
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
|
||||
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
|
||||
_wait_queue_idle(timeout=POLL_TIMEOUT)
|
||||
|
||||
# Try to inspect queued task params via JSON path.
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Opt-in production Registry/CDN verification; never collected by pytest.
|
||||
|
||||
Requires E2E_ROOT with comfyui/ and venv/bin/python, as for the local E2E suite.
|
||||
Pass two explicitly chosen ID@version values via --listed and --unlisted, and a
|
||||
new --output directory. Both versions must currently be Flagged. The listed
|
||||
archive must have no install.py or requirements.txt. Servers use isolated data
|
||||
directories, the normal installation path, and do not reload installed nodes.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
import test_e2e_flagged_nodepacks as harness
|
||||
|
||||
REGISTRY = 'https://api.comfy.org'
|
||||
|
||||
|
||||
def get_json(path, **params):
|
||||
response = requests.get(REGISTRY + path, params=params, timeout=30)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--listed', required=True, metavar='ID@VERSION')
|
||||
parser.add_argument('--unlisted', required=True, metavar='ID@VERSION')
|
||||
parser.add_argument('--output', required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
if not (harness.E2E_ROOT / 'venv/bin/python').is_file():
|
||||
parser.error('E2E_ROOT must point to the ComfyUI + venv fixture')
|
||||
packs = []
|
||||
for value in (args.listed, args.unlisted):
|
||||
node, separator, version = value.rpartition('@')
|
||||
if not node or not separator or not version:
|
||||
parser.error('Specify each pack as ID@VERSION')
|
||||
catalog = get_json('/nodes/' + quote(node, safe=''))
|
||||
assert catalog['id'] == node, catalog
|
||||
packs.append((catalog, version))
|
||||
assert packs[0][0]['id'].lower() != packs[1][0]['id'].lower(), 'Choose two different packs'
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True)
|
||||
catalog = {'nodes': [pack for pack, _ in packs], 'totalPages': 1}
|
||||
catalog_path = output / 'catalog.json'
|
||||
catalog_path.write_text(json.dumps(catalog, indent=2), encoding='utf-8')
|
||||
# Seed only the catalog cache from live /nodes/{id} responses. Installation
|
||||
# metadata and ZIP downloads still go directly to the production services.
|
||||
registry = SimpleNamespace(url=REGISTRY, catalog_url=catalog_path.as_uri())
|
||||
results = []
|
||||
|
||||
def check(server, label, pack, version, allowed):
|
||||
node = pack['id']
|
||||
metadata = get_json('/nodes/' + quote(node, safe='') + '/install', version=version)
|
||||
assert metadata['status'] == 'NodeVersionStatusFlagged', metadata
|
||||
assert metadata['node_id'] == node and metadata['version'] == version, metadata
|
||||
expected = {}
|
||||
if allowed:
|
||||
response = requests.get(metadata['downloadUrl'], timeout=60)
|
||||
response.raise_for_status()
|
||||
archive_path = server.root / 'cdn.zip'
|
||||
archive_path.write_bytes(response.content)
|
||||
with zipfile.ZipFile(archive_path) as archive:
|
||||
assert 'install.py' not in archive.namelist(), 'Choose a pack without an install script'
|
||||
assert 'requirements.txt' not in archive.namelist(), 'Choose a pack without pip requirements'
|
||||
for member in archive.infolist():
|
||||
if not member.is_dir():
|
||||
expected[member.filename] = hashlib.sha256(archive.read(member)).hexdigest()
|
||||
assert expected, 'CDN archive is empty'
|
||||
log_path = server.root / 'server.log'
|
||||
offset = len(log_path.read_text())
|
||||
queue = harness.install(server, node, version, repository=pack['repository'])
|
||||
installed = server.root / 'custom_nodes' / node
|
||||
assert installed.exists() is allowed, queue
|
||||
if allowed:
|
||||
if server.tree == 'legacy':
|
||||
assert list(queue['nodepack_result'].values()) == ['success'], queue
|
||||
else:
|
||||
assert queue['history']['result'] == 'success', queue
|
||||
for name, digest in expected.items():
|
||||
assert hashlib.sha256((installed / name).read_bytes()).hexdigest() == digest, name
|
||||
assert (installed / '.tracking').is_file()
|
||||
else:
|
||||
harness.assert_flagged_denial(queue, log_path.read_text()[offset:])
|
||||
assert not any(installed.parent.glob('CNR_temp_*'))
|
||||
results.append({'tree': server.tree, 'label': label,
|
||||
'observed_at': datetime.now(timezone.utc).isoformat(),
|
||||
'registry_response': metadata, 'queue_response': queue,
|
||||
'installed': installed.exists(), 'matched_archive_files': expected})
|
||||
(output / 'results.json').write_text(json.dumps(results, indent=2), encoding='utf-8')
|
||||
print(f'{server.tree} {label}: installed={installed.exists()}, verified_files={len(expected)}', flush=True)
|
||||
|
||||
for tree in ('glob', 'legacy'):
|
||||
root = output / tree
|
||||
root.mkdir()
|
||||
with harness.running_server(root, tree, '0.0.0.0', False, 'normal', registry) as server:
|
||||
whitelist = root / 'user/__manager/nodepack-whitelist.list'
|
||||
template = whitelist.read_text()
|
||||
assert template.strip() and all(line.lstrip().startswith('#') for line in template.splitlines() if line.strip())
|
||||
listed, version = packs[0]
|
||||
check(server, 'default-template', listed, version, False)
|
||||
whitelist.write_text(listed['id'].swapcase() + '\n', encoding='utf-8')
|
||||
check(server, 'listed-different-case', listed, version, True)
|
||||
check(server, 'unlisted-control', *packs[1], False)
|
||||
|
||||
manifest = {
|
||||
'tested_commit': subprocess.check_output(
|
||||
['git', 'rev-parse', 'HEAD'], cwd=harness.REPO_ROOT, text=True).strip(),
|
||||
'completed_cases': len(results), 'registry': REGISTRY,
|
||||
'archive_sha256': {str(path.relative_to(output)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for path in output.glob('*/cdn.zip')},
|
||||
}
|
||||
(output / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
|
||||
print(f'PASS: {len(results)} live Registry cases; evidence: {output}', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Lift real production JS out of the shipped files and execute it in node.
|
||||
|
||||
WHY LIFT RATHER THAN IMPORT: the manager's front-end modules pull in
|
||||
``../../scripts/app.js`` and touch ``document`` at module scope, so node cannot
|
||||
import them. WHY LIFT RATHER THAN RETYPE: a retyped copy of a formatter stops
|
||||
tracking the formatter the moment someone edits it, and then the guard passes
|
||||
while the shipped code regresses. Lifting keeps the executed bytes the shipped
|
||||
bytes — if the production function changes, so does the text under test.
|
||||
|
||||
This mirrors tests/test_manager_markdown_escaping.py, which AST-extracts
|
||||
``convert_markdown_to_html`` rather than importing manager_server.
|
||||
|
||||
Consumers point ``JsSource`` at a directory of .js files; an override directory
|
||||
(e.g. one populated with ``git show <base>:js/foo.js``) makes the RED half of a
|
||||
fix reproducible in one command.
|
||||
"""
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
|
||||
NODE = shutil.which("node")
|
||||
|
||||
|
||||
def _skip_literal(source: str, pos: int) -> int:
|
||||
"""If a literal or comment starts at pos, return the index just past it.
|
||||
|
||||
Returns pos unchanged when nothing starts there. Template literals are
|
||||
consumed whole, which is safe for brace counting because a `${...}`
|
||||
substitution is itself balanced. A lone `/` is read as a regex literal —
|
||||
sanitizeHTML's own `.replace(/'/g, ...)` hides an apostrophe inside one, and
|
||||
no scanned range uses `/` as division. Were that to change, the assertion
|
||||
below fails loudly rather than returning a wrong slice.
|
||||
"""
|
||||
ch = source[pos]
|
||||
nxt = source[pos + 1] if pos + 1 < len(source) else ""
|
||||
if ch == "/" and nxt == "/":
|
||||
return source.index("\n", pos)
|
||||
if ch == "/" and nxt == "*":
|
||||
return source.index("*/", pos) + 2
|
||||
if ch not in "\"'`/":
|
||||
return pos
|
||||
cursor = pos + 1
|
||||
while cursor < len(source):
|
||||
if source[cursor] == "\\":
|
||||
cursor += 2
|
||||
continue
|
||||
if source[cursor] == ch:
|
||||
return cursor + 1
|
||||
cursor += 1
|
||||
raise AssertionError("unterminated literal at offset %d" % (pos,))
|
||||
|
||||
|
||||
def slice_braced(source: str, start_marker: str) -> str:
|
||||
"""Return start_marker plus the balanced {...} block that follows it."""
|
||||
start = source.index(start_marker)
|
||||
pos = source.index("{", start + len(start_marker))
|
||||
depth = 0
|
||||
while pos < len(source):
|
||||
skipped = _skip_literal(source, pos)
|
||||
if skipped != pos:
|
||||
pos = skipped
|
||||
continue
|
||||
if source[pos] == "{":
|
||||
depth += 1
|
||||
elif source[pos] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start:pos + 1]
|
||||
pos += 1
|
||||
raise AssertionError("unbalanced braces after %r" % (start_marker,))
|
||||
|
||||
|
||||
def slice_object_entry(source: str, marker: str, indent: str = "\t\t") -> str:
|
||||
"""Return one object literal out of a `}, {`-chained array, by id marker.
|
||||
|
||||
These objects are literals inside an array, so the first `{` after the
|
||||
marker belongs to the NEXT entry — brace matching cannot be used. The entry
|
||||
instead ends at the first `}` sitting at the array's own indent.
|
||||
"""
|
||||
start = source.index(marker)
|
||||
end = source.index("\n%s}" % indent, start)
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def line_containing(source: str, marker: str) -> str:
|
||||
"""Return the single source line that holds `marker` (fails if absent)."""
|
||||
start = source.index(marker)
|
||||
line_start = source.rfind("\n", 0, start) + 1
|
||||
return source[line_start:source.index("\n", start)]
|
||||
|
||||
|
||||
class JsSource:
|
||||
"""The shipped .js files under test, read from `js_dir`."""
|
||||
|
||||
def __init__(self, js_dir):
|
||||
self.js_dir = Path(js_dir)
|
||||
self._cache = {}
|
||||
|
||||
def text(self, filename: str) -> str:
|
||||
if filename not in self._cache:
|
||||
self._cache[filename] = (self.js_dir / filename).read_text(encoding="utf-8")
|
||||
return self._cache[filename]
|
||||
|
||||
def lift_declaration(self, filename: str, marker: str) -> str:
|
||||
"""Lift an `export function`/`export const` declaration, minus `export`."""
|
||||
return slice_braced(self.text(filename), marker).replace("export ", "", 1)
|
||||
|
||||
def lift_formatter(self, filename: str, anchor: str) -> str:
|
||||
"""Lift the `formatter: ...` at `anchor` as a bare function expression."""
|
||||
block = slice_braced(self.text(filename), anchor)
|
||||
marker = "formatter:"
|
||||
return block[block.index(marker) + len(marker):].strip()
|
||||
|
||||
def lift_span(self, filename: str, start_marker: str, end_marker: str) -> str:
|
||||
"""Lift the source between two markers, end_marker included."""
|
||||
source = self.text(filename)
|
||||
start = source.index(start_marker)
|
||||
end = source.index(end_marker, start) + len(end_marker)
|
||||
return source[start:end]
|
||||
|
||||
|
||||
def run_node(script: str) -> dict:
|
||||
"""Execute an ES-module script and parse the single JSON object it prints."""
|
||||
assert NODE is not None, "node is required to execute the lifted production JS"
|
||||
result = subprocess.run(
|
||||
[NODE, "--input-type=module", "-e", script],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
assert result.returncode == 0, "node failed:\n%s" % (result.stderr,)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
class Collector(HTMLParser):
|
||||
"""Collects the tags and attributes a browser would actually build."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.tags = []
|
||||
self.attrs = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
self.tags.append(tag)
|
||||
self.attrs.extend(attrs)
|
||||
|
||||
handle_startendtag = handle_starttag
|
||||
|
||||
|
||||
def parse(markup: str) -> Collector:
|
||||
collector = Collector()
|
||||
collector.feed(markup)
|
||||
collector.close()
|
||||
return collector
|
||||
|
||||
|
||||
def event_handlers(markup: str):
|
||||
"""Every on* attribute a browser would attach for this markup."""
|
||||
return [name for name, _ in parse(markup).attrs if name.lower().startswith("on")]
|
||||
@@ -45,8 +45,9 @@ PORT=8199 npx playwright test --debug
|
||||
| `legacy-ui-manager-menu.spec.ts` | Menu dialog rendering, settings dropdowns, API round-trip |
|
||||
| `legacy-ui-custom-nodes.spec.ts` | Node list grid, filter, search, footer buttons |
|
||||
| `legacy-ui-model-manager.spec.ts` | Model list grid, filter, search |
|
||||
| `legacy-ui-snapshot.spec.ts` | Snapshot list, save, remove |
|
||||
| `legacy-ui-snapshot.spec.ts` | Snapshot list, save, remove, failed restore and remove |
|
||||
| `legacy-ui-navigation.spec.ts` | Dialog open/close, nested navigation, no duplicates |
|
||||
| `custom-nodes-xss.spec.ts` | Node metadata, Markdown, links, errors, search highlighting |
|
||||
| `custom-nodes-xss.spec.ts` | Node metadata, node preview, Markdown, links, errors, search highlighting |
|
||||
| `model-manager-xss.spec.ts` | Model metadata, links, errors, search highlighting |
|
||||
| `legacy-message-errors.spec.ts` | Batch rejection IDs, name readability, DOM colors, lookup errors |
|
||||
| `legacy-message-errors.spec.ts` | Batch rejection IDs, batch completion, name readability, DOM colors, lookup errors |
|
||||
| `legacy-ui-node-fixer.spec.ts` | "Fix node (recreate)" context-menu entry: one node left, links rewired, numeric and string node ids, inside a subgraph |
|
||||
|
||||
@@ -54,9 +54,8 @@ ComfyUI's `api.fetchApi()` automatically prepends the `/api` prefix to every pat
|
||||
| 2-3 | Installed filter | Filter → "Installed" | rows ≤ All | Client-side filter |
|
||||
| 2-4 | Not Installed filter | Filter → "Not Installed" | rows > 0 | Client-side filter |
|
||||
| 2-5 | Import Failed filter | Filter → "Import Failed" | Filter works | Client-side filter |
|
||||
| 2-6 | Check Update | "Check Update" button | Filter flips to "Update", API re-called | `GET /api/v2/customnode/getlist?mode=cache` (no `skip_update`) |
|
||||
| 2-6 | Check Update | "Check Update" button | Filter flips to "Update", the check runs in the background, the list is loaded when the `cm-check-update` event tells its end | `POST /api/v2/customnode/check_update`, then `GET /api/v2/customnode/getlist?mode=cache&skip_update=true` |
|
||||
| 2-7 | Check Missing | "Check Missing" button | Filter flips to "Missing" | `GET /api/v2/customnode/getmappings?mode=cache` |
|
||||
| 2-8 | Alternatives filter | Filter → "Alternatives of A1111" | Data loads | `GET /api/customnode/alternatives?mode=cache` |
|
||||
|
||||
## 3. Full node install lifecycle
|
||||
|
||||
@@ -156,7 +155,7 @@ Note: skipped when no import-failed nodes are present.
|
||||
| File | New/Enhanced | Scenarios | Target Endpoints |
|
||||
|------|----------|:-------:|---------------|
|
||||
| `legacy-ui-manager-menu.spec.ts` | enhanced | 7 | db_mode, channel_url_list, policy/update, notice |
|
||||
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 9 | getlist, getmappings, alternatives, import_fail_info |
|
||||
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 8 | getlist, getmappings, import_fail_info |
|
||||
| `legacy-ui-node-lifecycle.spec.ts` | **new** | 8 | versions/{id}, disabled_versions/{id}, queue/batch (install/uninstall/update/fix/disable/enable) |
|
||||
| `legacy-ui-node-versions.spec.ts` | **new** | 2 | versions/{id}, disabled_versions/{id} |
|
||||
| `legacy-ui-batch-operations.spec.ts` | **new** | 4 | queue/batch (update_all, update_comfyui), queue/reset |
|
||||
@@ -165,7 +164,7 @@ Note: skipped when no import-failed nodes are present.
|
||||
| `legacy-ui-snapshot.spec.ts` | enhanced | 4 | snapshot/getlist, save, restore, remove |
|
||||
| `legacy-ui-navigation.spec.ts` | existing | 4 | is_legacy_manager_ui, version |
|
||||
|
||||
**Total: 44 scenarios**
|
||||
**Total: 43 scenarios**
|
||||
|
||||
## Legacy-only endpoint coverage
|
||||
|
||||
@@ -173,7 +172,6 @@ Note: skipped when no import-failed nodes are present.
|
||||
|----------|---------|
|
||||
| `GET /api/v2/customnode/getlist` | 2-1, 2-6 |
|
||||
| `GET /api/v2/customnode/getmappings` | 2-2, 2-7 |
|
||||
| `GET /api/customnode/alternatives` | 2-8 |
|
||||
| `GET /api/v2/customnode/versions/{id}` | 3-1, 4-1 |
|
||||
| `GET /api/v2/customnode/disabled_versions/{id}` | 3-6, 4-2 |
|
||||
| `POST /api/v2/customnode/import_fail_info` | 7-1 |
|
||||
@@ -191,7 +189,7 @@ Note: skipped when no import-failed nodes are present.
|
||||
## Exclusions
|
||||
|
||||
- `share_option` — per user instruction
|
||||
- **External-service auth/integration** (9 endpoints) — external services are unreachable from E2E
|
||||
- **External-service auth/integration** (4 endpoints) — external services are unreachable from E2E
|
||||
- **Individual queue endpoints** (6) — unused by JS; delegated internally through `queue/batch`
|
||||
- `queue/abort_current` — unused by JS (Stop uses `queue/reset`)
|
||||
- `/manager/notice` (v1) — superseded by v2
|
||||
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
openCustomNodesManager,
|
||||
routeNodeList,
|
||||
routeMappings,
|
||||
routeAlternatives,
|
||||
makePack,
|
||||
expectInert,
|
||||
serverSanitizeTag,
|
||||
@@ -120,7 +119,7 @@ test.describe('grid render sinks', () => {
|
||||
// PRECONDITION — the two virtualised columns must actually have body
|
||||
// cells before their legs mean anything. Without this the row can go
|
||||
// pass again the moment a layout change hides them, on a fixture that
|
||||
// proved nothing (the same vacuous-pass shape the tags row guards against).
|
||||
// proved nothing.
|
||||
await expect(
|
||||
page.locator(`${GRID} .cn-pack-stars`).first(),
|
||||
'precondition: no .cn-pack-stars body cell rendered — the stars column is virtualised away at this viewport, so its leg would pass vacuously.',
|
||||
@@ -136,46 +135,6 @@ test.describe('grid render sinks', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('hostile tags render inert once the alternatives column is shown (LIVE, gated)', async ({ page }) => {
|
||||
// The alternatives column is `invisible: !this.hasAlternatives()`, so this
|
||||
// row MUST establish the gate. Without the precondition assertion below it
|
||||
// passes vacuously against a grid that never rendered the column at all.
|
||||
await routeNodeList(page, { alt1: makePack('alt1') });
|
||||
await routeAlternatives(page, {
|
||||
alt1: {
|
||||
id: 'alt1',
|
||||
title: 'alt1',
|
||||
description: 'alternative description',
|
||||
tags: XSS_PAYLOAD,
|
||||
},
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
// ESTABLISH THE GATE. `hasAlternatives()` is `this.filter ===
|
||||
// ShowMode.ALTERNATIVES`, so the column exists ONLY while the filter
|
||||
// dropdown is on "Alternatives of A1111" — selecting it is also what
|
||||
// triggers getAlternatives() and therefore the `:1903` tag loop. Without
|
||||
// this step the fixture is never fetched, nothing renders, and the row
|
||||
// would report a failure that has nothing to do with the sink.
|
||||
const filterSelect = page.locator('select.cn-manager-filter').first();
|
||||
await expect(filterSelect).toBeVisible({ timeout: 10_000 });
|
||||
await filterSelect.selectOption({ label: 'Alternatives of A1111' });
|
||||
|
||||
// PRECONDITION — assert on `.cn-tag-list` SPECIFICALLY, the div the tag
|
||||
// loop emits. An earlier draft accepted `.cn-pack-desc` too, which the
|
||||
// description column also carries: it matched, the row failed on a
|
||||
// different leg, and it looked like a reproduction. That is the vacuous
|
||||
// vacuous pass this row has to guard against, arriving as a vacuous
|
||||
// FAILURE instead.
|
||||
await expect(
|
||||
page.locator(`${GRID} .cn-tag-list`).first(),
|
||||
'precondition: no .cn-tag-list rendered, so the alternatives tag sink was never exercised — the row proves nothing about the sink.',
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'tags');
|
||||
});
|
||||
|
||||
test('a server-escaped title renders decoded (no double-escape)', async ({ page }) => {
|
||||
// THE REGRESSION GUARD FOR THE DOUBLE-ESCAPE FIX, and it only guards
|
||||
// anything because the fixture is the WIRE form.
|
||||
@@ -379,6 +338,52 @@ test.describe('flyover sinks', () => {
|
||||
|
||||
await expectInert(page, FLYOVER, XSS_PAYLOAD, 'img', 'flyover node name');
|
||||
});
|
||||
|
||||
test('node preview renders the node definition inert (LIVE, hover-gated)', async ({ page }) => {
|
||||
// The preview is built from ComfyUI's node definitions (/object_info),
|
||||
// which Manager's server never touches, so every field is RAW.
|
||||
await routeNodeList(page, { h: makePack('h') });
|
||||
await routeMappings(page, {
|
||||
'https://github.com/example/h': [['NodeA'], { title_aux: 'h' }],
|
||||
});
|
||||
const fields = ['name', 'slot', 'text', 'blank', 'count', 'default', 'output', 'description'];
|
||||
const hostile = Object.fromEntries(fields.map((field) => [field, `${field} ${XSS_PAYLOAD}`]));
|
||||
// The frontend has loaded its own node definitions by now, so this answers
|
||||
// only the request the manager makes when its dialog is created.
|
||||
await page.route('**/object_info', (route) => route.fulfill({ json: {
|
||||
NodeA: {
|
||||
name: hostile.name,
|
||||
description: hostile.description,
|
||||
input: { required: {
|
||||
[hostile.slot]: ['IMAGE'],
|
||||
[hostile.text]: ['STRING', { default: `first line\n${hostile.default}` }],
|
||||
[hostile.blank]: ['STRING', { multiline: true }],
|
||||
[hostile.count]: ['INT', { default: hostile.default }],
|
||||
} },
|
||||
input_order: { required: [hostile.slot, hostile.text, hostile.blank, hostile.count] },
|
||||
output: ['IMAGE'],
|
||||
output_name: [hostile.output],
|
||||
output_is_list: [false],
|
||||
},
|
||||
} }));
|
||||
const definitions = page.waitForResponse('**/object_info');
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await definitions;
|
||||
await openFlyover(page);
|
||||
|
||||
await page.locator(`${FLYOVER} .cn-nodes-name`).first().hover();
|
||||
await page.waitForSelector('.cn-preview', { state: 'visible', timeout: 10_000 });
|
||||
|
||||
await expectInert(page, '.cn-preview', XSS_PAYLOAD, 'img', 'node preview');
|
||||
const preview = page.locator('.cn-preview');
|
||||
// A text input shows its default value, and its name only when it has none.
|
||||
for (const field of fields.filter((field) => field !== 'text')) {
|
||||
await expect(preview, `node preview: ${field}`).toContainText(hostile[field]);
|
||||
}
|
||||
// The line break of a multi-line default is the one piece of markup kept.
|
||||
await expect(preview.locator('.cn-preview-string br')).toHaveCount(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
@@ -593,8 +598,8 @@ test.describe('batch error dialog', () => {
|
||||
// ===========================================================================
|
||||
|
||||
// The selectors below are load-bearing and were arrived at the hard way.
|
||||
// `.p-dialog input` matches the Custom Nodes SEARCH box
|
||||
// (`.cn-manager-keywords`, in `.p-dialog-header`) before it matches the prompt
|
||||
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box
|
||||
// (`.cn-manager-keywords`, in `.cm-ui-header`) before it matches the prompt
|
||||
// field, so a `.first()` on it silently types the URL into the search box:
|
||||
// install_via_git_url is never called, the denial modal never renders, and the
|
||||
// row fails as though the client produced nothing. Targeting
|
||||
@@ -619,7 +624,7 @@ test.describe('403 denial text', () => {
|
||||
// install_via_git_url -> the 403 arm at common.js:254.
|
||||
//
|
||||
// `.prompt-dialog-content input` is the load-bearing selector. A broader
|
||||
// `.p-dialog input` matches the Custom Nodes SEARCH box first, which is
|
||||
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box first, which is
|
||||
// silent: the URL lands in the search field, no request is made, and the
|
||||
// row fails at the denial assertion as though the client rendered nothing.
|
||||
await page.locator('.cn-manager-install-url').first().click();
|
||||
|
||||
+24
-23
@@ -101,19 +101,33 @@ export async function clickMenuButton(page: Page, text: string) {
|
||||
await dialog.locator(`button:has-text("${text}")`).click();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the toasts of the ComfyUI frontend. One of them, such as the error
|
||||
* `getCanvas: canvas is null` that the frontend can raise while several pages
|
||||
* load at once, can lie over a button of a Manager dialog, and a click on
|
||||
* that button then never arrives.
|
||||
*/
|
||||
export async function closeToasts(page: Page) {
|
||||
const closeButtons = page.locator('[data-testid="toast"]').getByRole('button', { name: 'Close' });
|
||||
// A closed toast leaves the page and the others move up, so each click is
|
||||
// on the one that is first by then.
|
||||
for (let left = await closeButtons.count(); left > 0; left--) {
|
||||
await closeButtons.first().click({ timeout: 2_000 }).catch(() => {});
|
||||
await expect(closeButtons).toHaveCount(left - 1, { timeout: 2_000 }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/** Close the topmost dialog via its X (close) button or Escape. */
|
||||
export async function closeDialog(page: Page) {
|
||||
// Try clicking close buttons on visible dialogs. The manager-menu dialog
|
||||
// (`#cm-manager-dialog`) is a ComfyDialog with `.p-dialog-close-button` (X),
|
||||
// while sub-dialogs use `.cm-close-btn`. Try both.
|
||||
// Every Manager dialog has a `.cm-ui-close` (X). A sub-dialog lies
|
||||
// over the manager-menu dialog (`#cm-manager-dialog`), whose X stays visible
|
||||
// but cannot be clicked then, so the sub-dialogs are tried first.
|
||||
for (const sel of [
|
||||
'#cn-manager-dialog button.cm-close-btn',
|
||||
'#cmm-manager-dialog button.cm-close-btn',
|
||||
'#snapshot-manager-dialog button.cm-close-btn',
|
||||
'#cm-manager-dialog button.cm-close-btn',
|
||||
'#cm-manager-dialog .p-dialog-close-button',
|
||||
'.cm-close-btn',
|
||||
'.p-dialog-close-button',
|
||||
'#cn-manager-dialog .cm-ui-close',
|
||||
'#cmm-manager-dialog .cm-ui-close',
|
||||
'#snapshot-manager-dialog .cm-ui-close',
|
||||
'#cm-manager-dialog .cm-ui-close',
|
||||
'.cm-ui-close',
|
||||
]) {
|
||||
const btn = page.locator(sel).last();
|
||||
if (await btn.isVisible({ timeout: 500 }).catch(() => false)) {
|
||||
@@ -206,19 +220,6 @@ export async function routeMappings(page: Page, mappings: Record<string, unknown
|
||||
});
|
||||
}
|
||||
|
||||
/** Seed `/customnode/alternatives` — required to OPEN the alternatives column,
|
||||
* which is `invisible: !this.hasAlternatives()`. Without this the alternatives
|
||||
* column stays hidden and any test asserting on it passes vacuously. */
|
||||
export async function routeAlternatives(page: Page, alts: Record<string, unknown>) {
|
||||
await page.route('**/customnode/alternatives**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(alts),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Open Manager menu -> Custom Nodes Manager and wait for the grid to fill. */
|
||||
export async function openCustomNodesManager(page: Page) {
|
||||
await clickMenuButton(page, 'Custom Nodes Manager');
|
||||
|
||||
@@ -1,9 +1,24 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import {
|
||||
waitForComfyUI, openManagerMenu, openCustomNodesManager, openModelManager,
|
||||
routeNodeList, routeModelList, makePack, makeModel, serverSanitizeTag, XSS_PAYLOAD,
|
||||
} from './helpers';
|
||||
|
||||
/** The grid replaces the status line with its row count as soon as it redraws, so record the
|
||||
* texts that the manager passes to it; read them from `window.__statuses`. */
|
||||
async function recordStatuses(page: Page, file: string, exported: string) {
|
||||
await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
const manager = module[exported].instance;
|
||||
const showStatus = manager.showStatus.bind(manager);
|
||||
(window as any).__statuses = [];
|
||||
manager.showStatus = (msg: string, color?: string) => {
|
||||
(window as any).__statuses.push(msg);
|
||||
showStatus(msg, color);
|
||||
};
|
||||
}, { file, exported });
|
||||
}
|
||||
|
||||
for (const kind of ['nodes', 'models']) {
|
||||
const prefix = kind === 'nodes' ? 'cn' : 'cmm';
|
||||
const file = kind === 'nodes' ? 'custom-nodes-manager' : 'model-manager';
|
||||
@@ -34,7 +49,9 @@ for (const kind of ['nodes', 'models']) {
|
||||
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
return !!module[exported].instance.install_context;
|
||||
const manager = module[exported].instance;
|
||||
// The Model Manager keeps one pending install for each batch.
|
||||
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
}, { file, exported })).toBe(false);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
@@ -86,7 +103,8 @@ for (const kind of ['nodes', 'models']) {
|
||||
}
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
return !!module[exported].instance.install_context;
|
||||
const manager = module[exported].instance;
|
||||
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
}, { file, exported })).toBe(false);
|
||||
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
|
||||
expect(errors).toEqual([]);
|
||||
@@ -130,18 +148,38 @@ for (const kind of ['nodes', 'models']) {
|
||||
await expect(page.locator(`.${prefix}-manager-stop`)).toBeVisible();
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
return !!module[exported].instance.install_context;
|
||||
const manager = module[exported].instance;
|
||||
// The Model Manager keeps one pending install for each batch.
|
||||
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
}, { file, exported })).toBe(true);
|
||||
|
||||
// A batch that carries no result for this manager is another manager's batch.
|
||||
await page.evaluate(async detail => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail }));
|
||||
}, { status: 'batch-done', batch_id: 'another-batch', nodepack_result: kind === 'nodes' ? {} : { other: 'success' },
|
||||
model_result: kind === 'models' ? {} : { other: 'success' }, done_count: 1, total_count: 1 });
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
const manager = module[exported].instance;
|
||||
// The Model Manager keeps one pending install for each batch.
|
||||
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
}, { file, exported })).toBe(true);
|
||||
|
||||
await recordStatuses(page, file, exported);
|
||||
await page.evaluate(async detail => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail }));
|
||||
}, completion!);
|
||||
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
|
||||
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
|
||||
expect(await page.evaluate(() => (window as any).__statuses)).toContain(
|
||||
`Install ${2 - rejectedCount} ${kind === 'nodes' ? 'custom node(s)' : 'models'} successfully`);
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
return !!module[exported].instance.install_context;
|
||||
const manager = module[exported].instance;
|
||||
// The Model Manager keeps one pending install for each batch.
|
||||
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
}, { file, exported })).toBe(false);
|
||||
});
|
||||
}
|
||||
@@ -169,6 +207,309 @@ for (const kind of ['nodes', 'models']) {
|
||||
});
|
||||
}
|
||||
|
||||
for (const outcome of ['success', 'failure']) {
|
||||
test(`models: only the active batch can update progress and complete (${outcome})`, async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
|
||||
let batch: { batch_id: string; install_model: { ui_id: string }[] };
|
||||
await page.route('**/v2/manager/queue/batch', async route => {
|
||||
batch = route.request().postDataJSON();
|
||||
await route.fulfill({ json: { failed: [] } });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
await page.evaluate(async () => {
|
||||
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
|
||||
const manager = ModelManager.instance;
|
||||
const button = manager.element.querySelector('.cmm-btn-install');
|
||||
await manager.installModels(manager.modelList, button);
|
||||
});
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
|
||||
const target = batch!.install_model[0].ui_id;
|
||||
const status = (batchId: string, state: string, modelResult: Record<string, string>) => ({
|
||||
status: state, batch_id: batchId, ui_target: 'model_manager', target,
|
||||
model_result: modelResult, done_count: 1, total_count: 1,
|
||||
});
|
||||
const dispatch = async (detail: ReturnType<typeof status>) => {
|
||||
await page.evaluate(async value => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: value }));
|
||||
}, detail);
|
||||
};
|
||||
const state = () => page.evaluate(async hash => {
|
||||
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
|
||||
const manager = ModelManager.instance;
|
||||
const pending = manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
|
||||
return { pending, refresh: !!manager.grid.getRowItemBy('hash', hash)?.refresh };
|
||||
}, target);
|
||||
|
||||
await dispatch(status('other-batch', 'in_progress', {}));
|
||||
expect(await state()).toEqual({ pending: true, refresh: false });
|
||||
await dispatch(status('other-batch', 'batch-done', { [target]: 'success' }));
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
expect(await state()).toEqual({ pending: true, refresh: false });
|
||||
|
||||
await dispatch(status(batch!.batch_id, 'in_progress', {}));
|
||||
expect(await state()).toEqual({ pending: true, refresh: true });
|
||||
const result = { [target]: outcome === 'success' ? 'success' : 'download failed' };
|
||||
await recordStatuses(page, 'model-manager', 'ModelManager');
|
||||
await dispatch(status(batch!.batch_id, 'batch-done', result));
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
expect((await state()).pending).toBe(false);
|
||||
const statuses = await page.evaluate(() => (window as any).__statuses);
|
||||
const refresh = "To apply the installed model, please click the 'Refresh' button.";
|
||||
if (outcome === 'success') {
|
||||
expect(statuses).toContain('Install 1 models successfully');
|
||||
await expect(page.locator('.cmm-manager-message')).toContainText(refresh);
|
||||
} else {
|
||||
await expect(page.locator('.cmm-manager-message')).toContainText('download failed');
|
||||
await expect(page.locator('.cmm-manager-message')).not.toContainText(refresh);
|
||||
}
|
||||
|
||||
await dispatch(status(batch!.batch_id, 'batch-done', { [target]: 'success' }));
|
||||
expect((await state()).pending).toBe(false);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
type PostedBatch = { batch_id: string; install_model: { ui_id: string }[] };
|
||||
|
||||
/** Answer the Model Manager's question whether the queue is running. The batch request is replaced
|
||||
* in these cases, so the real server never has the batch in its queue. */
|
||||
async function routeQueueStatus(page: Page, isProcessing: boolean) {
|
||||
await page.route('**/v2/manager/queue/status', route => route.fulfill({
|
||||
json: { total_count: 0, done_count: 0, in_progress_count: 0, is_processing: isProcessing },
|
||||
}));
|
||||
}
|
||||
|
||||
/** Keep the Model Manager's checks of the queue, so that a case can wait until they have finished. */
|
||||
async function recordQueueChecks(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
|
||||
const manager = ModelManager.instance;
|
||||
const check = manager.endDroppedInstalls.bind(manager);
|
||||
(window as any).__queueChecks = [];
|
||||
manager.endDroppedInstalls = () => {
|
||||
const finished = check();
|
||||
(window as any).__queueChecks.push(finished);
|
||||
return finished;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve once every check of the queue that was started has handled its answer. */
|
||||
async function queueChecked(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
const checks = (window as any).__queueChecks;
|
||||
if (checks.length === 0) throw new Error('The queue was not checked');
|
||||
await Promise.all(checks);
|
||||
});
|
||||
}
|
||||
|
||||
/** Start one install for each of the listed models, as clicking Install in their rows does one after
|
||||
* the other; resolve with the id and the target of each batch that was posted. */
|
||||
async function installEachModel(page: Page, onBatchPosted?: (batch: PostedBatch) => Promise<void>) {
|
||||
const batches: PostedBatch[] = [];
|
||||
await page.route('**/v2/manager/queue/batch', async route => {
|
||||
batches.push(route.request().postDataJSON());
|
||||
await onBatchPosted?.(batches.at(-1)!);
|
||||
await route.fulfill({ json: { failed: [] } });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
await page.evaluate(async () => {
|
||||
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
|
||||
const manager = ModelManager.instance;
|
||||
for (const item of manager.modelList) {
|
||||
const button = manager.grid.getCellNode(item, 'installed').querySelector('button[mode="install"]');
|
||||
await manager.installModels([item], button);
|
||||
}
|
||||
});
|
||||
return batches.map(batch => ({ id: batch.batch_id, target: batch.install_model[0].ui_id }));
|
||||
}
|
||||
|
||||
async function dispatchQueueStatus(page: Page, detail: Record<string, unknown>) {
|
||||
await page.evaluate(async value => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: value }));
|
||||
}, detail);
|
||||
}
|
||||
|
||||
/** How many installs are pending, and which of the given rows are marked as downloaded. */
|
||||
async function modelInstallState(page: Page, targets: string[]) {
|
||||
return page.evaluate(async hashes => {
|
||||
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
|
||||
const manager = ModelManager.instance;
|
||||
return {
|
||||
// A manager that keeps one install only has one pending at most.
|
||||
pending: manager.install_contexts ? manager.install_contexts.size : (manager.install_context ? 1 : 0),
|
||||
downloaded: hashes.map(hash => !!manager.grid.getRowItemBy('hash', hash)?.refresh),
|
||||
};
|
||||
}, targets);
|
||||
}
|
||||
|
||||
test('models: each of two installs started in a row ends with its own batch', async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('first'), makeModel('second')]);
|
||||
const [first, second] = await installEachModel(page);
|
||||
const targets = [first.target, second.target];
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(2);
|
||||
expect(await modelInstallState(page, targets)).toEqual({ pending: 2, downloaded: [false, false] });
|
||||
|
||||
const report = (batch: { id: string; target: string }, status: string) => dispatchQueueStatus(page, {
|
||||
status, batch_id: batch.id, ui_target: 'model_manager', target: batch.target,
|
||||
model_result: { [batch.target]: 'success' }, done_count: 1, total_count: 1,
|
||||
});
|
||||
await report(first, 'in_progress');
|
||||
await report(first, 'batch-done');
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(1);
|
||||
expect(await modelInstallState(page, targets)).toEqual({ pending: 1, downloaded: [true, false] });
|
||||
|
||||
await report(second, 'in_progress');
|
||||
await report(second, 'batch-done');
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
|
||||
expect(await modelInstallState(page, targets)).toEqual({ pending: 0, downloaded: [true, true] });
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('models: a queue that ends without the batch returns the install to idle', async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('first'), makeModel('second')]);
|
||||
// Stop empties the queue: the task that is running ends, and then only the end of the queue is reported.
|
||||
await routeQueueStatus(page, false);
|
||||
const [first, second] = await installEachModel(page);
|
||||
const targets = [first.target, second.target];
|
||||
await dispatchQueueStatus(page, { status: 'in_progress', batch_id: first.id, ui_target: 'model_manager', target: first.target });
|
||||
expect(await modelInstallState(page, targets)).toEqual({ pending: 2, downloaded: [true, false] });
|
||||
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
|
||||
expect(await modelInstallState(page, targets)).toEqual({ pending: 0, downloaded: [true, false] });
|
||||
await expect(page.locator('.cmm-manager-message')).toContainText("To apply the installed model, please click the 'Refresh' button.");
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('models: a stopped queue that downloaded nothing asks for no refresh', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
await routeQueueStatus(page, false);
|
||||
const [batch] = await installEachModel(page);
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
|
||||
await expect(page.locator('.cmm-manager-message')).toHaveText('');
|
||||
await expect(page.locator('.cmm-manager-refresh')).toBeHidden();
|
||||
});
|
||||
|
||||
test('models: the end of an earlier queue does not end an install that is being queued', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
// The report of the queue that ran before reaches the page while the batch is still being posted.
|
||||
// The batch is then added to the queue and runs.
|
||||
await routeQueueStatus(page, true);
|
||||
let asked = 0;
|
||||
page.on('request', request => { if (request.url().endsWith('/v2/manager/queue/status')) asked++; });
|
||||
const [batch] = await installEachModel(page, async () => {
|
||||
await recordQueueChecks(page);
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
});
|
||||
await queueChecked(page);
|
||||
expect(asked).toBe(1);
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
|
||||
});
|
||||
|
||||
test('models: an install that was dropped while it was being queued returns to idle', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
// Stop emptied the queue after the batch was added to it, and the end of the queue is reported
|
||||
// before the answer to the batch request arrives.
|
||||
await routeQueueStatus(page, false);
|
||||
const [batch] = await installEachModel(page, () => dispatchQueueStatus(page, { status: 'all-done' }));
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
|
||||
});
|
||||
|
||||
test('models: the end of an earlier queue does not end an install that is running', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
// The report of the queue that ran before reaches the page after the answer to the batch request.
|
||||
await routeQueueStatus(page, true);
|
||||
const [batch] = await installEachModel(page);
|
||||
await recordQueueChecks(page);
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
await queueChecked(page);
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(1);
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
|
||||
|
||||
await dispatchQueueStatus(page, { status: 'batch-done', batch_id: batch.id,
|
||||
model_result: { [batch.target]: 'success' }, done_count: 1, total_count: 1 });
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
|
||||
});
|
||||
|
||||
test('models: an install stays pending when the queue cannot be asked', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
// Without an answer the queue may still be running the batch.
|
||||
await page.route('**/v2/manager/queue/status', route => route.fulfill({ status: 500, body: 'error' }));
|
||||
const [batch] = await installEachModel(page);
|
||||
await recordQueueChecks(page);
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
await queueChecked(page);
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
|
||||
|
||||
// The next report of the end of the queue that can be checked ends it.
|
||||
await page.unroute('**/v2/manager/queue/status');
|
||||
await routeQueueStatus(page, false);
|
||||
await dispatchQueueStatus(page, { status: 'all-done' });
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
|
||||
});
|
||||
|
||||
test('models: a batch that ends before its request is answered completes the install', async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
const [batch] = await installEachModel(page, posted => dispatchQueueStatus(page, {
|
||||
status: 'batch-done', batch_id: posted.batch_id,
|
||||
model_result: { [posted.install_model[0].ui_id]: 'download failed' }, done_count: 1, total_count: 1,
|
||||
}));
|
||||
await expect(page.locator('.cmm-manager-message')).toContainText('download failed');
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
|
||||
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
|
||||
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
test('nodes: lookup errors and missing row IDs remain literal text', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
@@ -189,7 +530,6 @@ test('nodes: lookup errors and missing row IDs remain literal text', async ({ pa
|
||||
try {
|
||||
for (const invoke of [
|
||||
() => manager.getMissingNodesLegacy({}, new Set()),
|
||||
() => manager.getAlternatives(),
|
||||
() => manager.installNodes([payload], { target: document.createElement('button'), mode: 'install' }),
|
||||
]) {
|
||||
await invoke();
|
||||
@@ -202,7 +542,7 @@ test('nodes: lookup errors and missing row IDs remain literal text', async ({ pa
|
||||
}
|
||||
return results;
|
||||
}, XSS_PAYLOAD);
|
||||
expect(results).toHaveLength(3);
|
||||
expect(results).toHaveLength(2);
|
||||
for (const result of results) {
|
||||
expect(result.text).toContain(XSS_PAYLOAD);
|
||||
expect(result.images).toBe(0);
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* E2E tests: the Manager dialogs bring their own styles.
|
||||
*
|
||||
* The ComfyUI frontend no longer ships the PrimeVue dialog styles. A dialog
|
||||
* that relies on them has no background, and its buttons lie over the canvas.
|
||||
*
|
||||
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT.
|
||||
*/
|
||||
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton } from './helpers';
|
||||
|
||||
const TRANSPARENT = 'rgba(0, 0, 0, 0)';
|
||||
const DIALOGS: [string, string | null, string][] = [
|
||||
['Manager menu', null, '#cm-manager-dialog'],
|
||||
['Custom Nodes Manager', 'Custom Nodes Manager', '#cn-manager-dialog'],
|
||||
['Model Manager', 'Model Manager', '#cmm-manager-dialog'],
|
||||
['Snapshot Manager', 'Snapshot Manager', '#snapshot-manager-dialog'],
|
||||
];
|
||||
|
||||
async function open(page: Page, button: string | null, selector: string) {
|
||||
await openManagerMenu(page);
|
||||
if (button) await clickMenuButton(page, button);
|
||||
await page.waitForSelector(selector, { timeout: 15_000 });
|
||||
return page.locator(selector).last();
|
||||
}
|
||||
|
||||
function background(locator: ReturnType<Page['locator']>) {
|
||||
return locator.evaluate((element) => getComputedStyle(element).backgroundColor);
|
||||
}
|
||||
|
||||
test.describe('Dialog styles', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
for (const [name, button, selector] of DIALOGS) {
|
||||
test(`${name} has a background and dims the page behind it`, async ({ page }) => {
|
||||
const dialog = await open(page, button, selector);
|
||||
|
||||
expect(await background(dialog)).not.toBe(TRANSPARENT);
|
||||
expect(await background(dialog.locator('xpath=..'))).not.toBe(TRANSPARENT);
|
||||
});
|
||||
|
||||
test(`${name} is closed by its close button`, async ({ page }) => {
|
||||
const dialog = await open(page, button, selector);
|
||||
|
||||
await dialog.getByRole('button', { name: 'Close' }).click();
|
||||
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -100,7 +100,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
test('LB1 Install button triggers install effect', async ({ page }) => {
|
||||
// Reset queue at start for deterministic done_count baseline in waitForAllDone
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// Precondition: pack must NOT be installed. If the seed pack is already
|
||||
// installed (prior pytest runs, pre-seeded E2E environment), the
|
||||
@@ -128,7 +128,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
expect(queueResp.ok()).toBe(true);
|
||||
await page.request.post('/v2/manager/queue/start');
|
||||
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
|
||||
await waitForAllDone(page, 60_000);
|
||||
// Hard fail if setup itself couldn't uninstall the pack
|
||||
expect(await isPackInstalled(page)).toBe(false);
|
||||
@@ -141,16 +141,13 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
// Wait for grid to populate before applying filter (avoids race on empty grid)
|
||||
await expect(page.locator('.tg-body .tg-row').first()).toBeVisible({ timeout: 30_000 });
|
||||
const initialRowCount = await page.locator('.tg-body .tg-row').count();
|
||||
|
||||
// Filter to Not Installed to make install buttons visible. Wait for
|
||||
// filtered row count to actually change (DOM state, not wall-clock).
|
||||
// Filter to Not Installed to make install buttons visible. The grid
|
||||
// renders only the rows in view, so their number does not tell whether
|
||||
// the filter was applied; the search below waits for its own result.
|
||||
const filterSelect = page.locator('select.cn-manager-filter').first();
|
||||
if (await filterSelect.isVisible().catch(() => false)) {
|
||||
await filterSelect.selectOption({ value: 'not-installed' });
|
||||
await expect
|
||||
.poll(async () => page.locator('.tg-body .tg-row').count(), { timeout: 10_000 })
|
||||
.not.toBe(initialRowCount);
|
||||
}
|
||||
|
||||
// Search for the specific test pack. Wait for search to narrow results.
|
||||
@@ -198,7 +195,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
|
||||
test('LB2 Uninstall button triggers uninstall effect', async ({ page }) => {
|
||||
// Reset queue at start for deterministic done_count baseline in waitForAllDone
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
|
||||
// Precondition: pack must be installed. Install via API as test SETUP
|
||||
// (not verification). This makes LB2 independent of LB1 — hard-failing
|
||||
@@ -207,7 +204,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
// is async, so waitForAllDone is still required after queue/start.
|
||||
const preinstalled = await isPackInstalled(page);
|
||||
if (!preinstalled) {
|
||||
await page.request.post('/v2/manager/queue/reset');
|
||||
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
const queueResp = await page.request.post('/v2/manager/queue/batch', {
|
||||
data: JSON.stringify({
|
||||
batch_id: 'lb2-setup-install',
|
||||
@@ -225,7 +222,7 @@ test.describe('UI-driven install/uninstall', () => {
|
||||
expect(queueResp.ok()).toBe(true);
|
||||
const queueBody = await queueResp.json();
|
||||
expect(queueBody.failed ?? []).toEqual([]);
|
||||
await page.request.post('/v2/manager/queue/start');
|
||||
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
|
||||
// Poll the terminal state directly: isPackInstalled returning true is
|
||||
// the unambiguous success signal. Using waitForAllDone here is racy —
|
||||
// fast-path installs (pack already on disk / cached CNR artifacts) can
|
||||
|
||||
@@ -56,7 +56,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
// No page.request / page.waitForResponse — pure UI interaction + dialog
|
||||
// close-reopen as the persistence proof. networkidle is used only as a
|
||||
// settle barrier (wait), never as assertion input. Close via the dialog's
|
||||
// own `.p-dialog-close-button` (X button) because Escape doesn't close
|
||||
// own `.cm-ui-close` (X button) because Escape doesn't close
|
||||
// ComfyDialog reliably.
|
||||
await openManagerMenu(page);
|
||||
const dialog = page.locator('#cm-manager-dialog').first();
|
||||
@@ -72,7 +72,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Close + reopen (UI-only persistence proof)
|
||||
await dialog.locator('.p-dialog-close-button').first().click();
|
||||
await dialog.locator('.cm-ui-close').first().click();
|
||||
// ComfyDialog.close() sets display:none but keeps the element in DOM,
|
||||
// so check visibility (toBeHidden), not presence (toHaveCount 0).
|
||||
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
|
||||
@@ -106,6 +106,63 @@ test.describe('Manager Menu Dialog', () => {
|
||||
}
|
||||
});
|
||||
|
||||
for (const setting of [
|
||||
{ name: 'DB mode', route: '/v2/manager/db_mode', options: /Cache|Local|Channel/, values: ['local', 'remote'] },
|
||||
{ name: 'Update Policy', route: '/v2/manager/policy/update', options: /Stable|Nightly/, values: ['nightly-comfyui', 'stable-comfyui'] },
|
||||
{ name: 'Share', route: '/v2/manager/share_option', options: /YouML|Matrix/, values: ['youml', 'matrix'] },
|
||||
]) {
|
||||
test(`${setting.name}: a choice made while the setting is still loading is kept`, async ({ page }) => {
|
||||
// The dialog asks the server for the setting when it is first opened.
|
||||
// Hold the answer back after the server has given it, choose another
|
||||
// value, then let the answer through. The value that is chosen is not
|
||||
// the first option, which the select shows before the answer and which
|
||||
// a user therefore cannot choose.
|
||||
const reads = (request: { method(): string; url(): string }) =>
|
||||
request.method() === 'GET' && request.url().includes(setting.route);
|
||||
const saves = (request: { method(): string; url(): string }) => request.url().includes(setting.route) && !reads(request);
|
||||
const save = (value: string) =>
|
||||
page.request.post(setting.route, { data: JSON.stringify({ value }), headers: { 'Content-Type': 'application/json' } });
|
||||
const stored = await (await page.request.get(setting.route)).text();
|
||||
const chosen = setting.values.find((value) => value !== stored)!;
|
||||
let release!: () => void;
|
||||
const held = new Promise<void>((resolve) => { release = resolve; });
|
||||
let answered!: () => void;
|
||||
const answer = new Promise<void>((resolve) => { answered = resolve; });
|
||||
await page.route(`**${setting.route}*`, async (route) => {
|
||||
if (!reads(route.request())) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
const response = await route.fetch();
|
||||
answered();
|
||||
await held;
|
||||
await route.fulfill({ response });
|
||||
});
|
||||
|
||||
try {
|
||||
await openManagerMenu(page);
|
||||
const combo = page.locator('#cm-manager-dialog').first().locator('select').filter({ hasText: setting.options }).first();
|
||||
// The answer that is held back is one the server gave before the choice.
|
||||
await answer;
|
||||
const saved = page.waitForResponse((response) => saves(response.request()));
|
||||
await combo.selectOption(chosen);
|
||||
await saved;
|
||||
|
||||
const loaded = page.waitForResponse((response) => reads(response.request()));
|
||||
release();
|
||||
await loaded;
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
await expect(combo).toHaveValue(chosen);
|
||||
expect(await (await page.request.get(setting.route)).text()).toBe(chosen);
|
||||
} finally {
|
||||
release();
|
||||
await page.unroute(`**${setting.route}*`);
|
||||
await save(stored);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('Update Policy dropdown persists via UI (close-reopen verification)', async ({ page }) => {
|
||||
// Wave3 WI-U Cluster H target 2: same UI-only pattern as the DB mode test.
|
||||
await openManagerMenu(page);
|
||||
@@ -119,7 +176,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
await policyCombo.selectOption(newValue);
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
await dialog.locator('.p-dialog-close-button').first().click();
|
||||
await dialog.locator('.cm-ui-close').first().click();
|
||||
// ComfyDialog.close() sets display:none but keeps the element in DOM,
|
||||
// so check visibility (toBeHidden), not presence (toHaveCount 0).
|
||||
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
|
||||
@@ -316,7 +373,7 @@ test.describe('Manager Menu Dialog', () => {
|
||||
expect(statusBefore.status()).toBe(200);
|
||||
const statusJson = await statusBefore.json();
|
||||
|
||||
const resetResp = await request.post('/v2/manager/queue/reset');
|
||||
const resetResp = await request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
|
||||
expect(resetResp.status()).toBe(200);
|
||||
|
||||
// Post-check: queue/status still callable (handler released locks
|
||||
|
||||
@@ -42,9 +42,9 @@ test.describe('Dialog Navigation', () => {
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
// Close the Model Manager dialog via its close button (p-dialog-close-button)
|
||||
const mmMask = page.locator('.p-dialog-mask:has(#cmm-manager-dialog)');
|
||||
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .p-dialog-close-button').first();
|
||||
// Close the Model Manager dialog via its close button
|
||||
const mmMask = page.locator('.cm-ui-overlay:has(#cmm-manager-dialog)');
|
||||
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .cm-ui-close').first();
|
||||
if (await mmCloseBtn.isVisible({ timeout: 2_000 }).catch(() => false)) {
|
||||
await mmCloseBtn.click();
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* E2E test: "Fix node (recreate)" in the node context menu (js/node_fixer.js).
|
||||
*
|
||||
* Recreating a node must leave one copy of it, wired as the original was.
|
||||
*
|
||||
* String node ids: the entry passed the new node's id to
|
||||
* `LGraphNode.connect()`, which looks a target up by id only when the id is a
|
||||
* number. Where node ids are strings it threw `findInputSlot is not a
|
||||
* function` and left the wired original plus an unwired replacement.
|
||||
*
|
||||
* Subgraphs: the entry read links and nodes from the root graph. A subgraph
|
||||
* keeps its own, and its inputs and outputs are not nodes of it, so inside a
|
||||
* subgraph the entry threw and left the same two nodes.
|
||||
*
|
||||
* The entry exists for nodes whose definition changed, so two rows give the
|
||||
* original an input the new node cannot take over, one it does not have and
|
||||
* one it has with another type: that link is dropped, the rest is kept.
|
||||
*
|
||||
* Honesty boundary: where the frontend issues numeric ids (1.45.15, which the
|
||||
* E2E environment pins), the "string node ids" row rewrites the ids to strings
|
||||
* itself. That reproduces the failing call but is a simulation, and it reaches
|
||||
* into `graph._nodes_by_id`. Where ids are already strings (1.57.6) the
|
||||
* rewrite changes nothing and that row runs the real thing.
|
||||
*
|
||||
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT.
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { waitForComfyUI } from './helpers';
|
||||
|
||||
// Each case builds CheckpointLoaderSimple + CLIPTextEncode -> KSampler ->
|
||||
// VAEDecode in the root graph and recreates the KSampler. `subgraph` lists the
|
||||
// nodes that are moved into a subgraph first; the test then works inside that
|
||||
// subgraph. `links` is what the KSampler must be wired to before the click, at
|
||||
// the least. `dropped` names an input of the KSampler that is typed MODEL and
|
||||
// fed by the subgraph's `model` input before the click; a new KSampler either
|
||||
// has no input of that name or has it with another type.
|
||||
const toNodes = {
|
||||
inputs: { model: 'CheckpointLoaderSimple.MODEL', positive: 'CLIPTextEncode.CONDITIONING' },
|
||||
outputs: ['VAEDecode.samples'],
|
||||
};
|
||||
const toSubgraph = {
|
||||
inputs: { model: 'subgraph input.model', positive: 'subgraph input.positive' },
|
||||
outputs: ['subgraph output.LATENT'],
|
||||
};
|
||||
const cases = [
|
||||
{ name: 'frontend-issued node ids', links: toNodes },
|
||||
{ name: 'string node ids', stringIds: true, links: toNodes },
|
||||
{
|
||||
name: 'inside a subgraph',
|
||||
subgraph: ['CheckpointLoaderSimple', 'CLIPTextEncode', 'KSampler', 'VAEDecode'],
|
||||
links: toNodes,
|
||||
},
|
||||
{ name: 'linked to the inputs and outputs of a subgraph', subgraph: ['KSampler'], links: toSubgraph },
|
||||
{
|
||||
name: 'an input the new node lacks, linked to an input of a subgraph',
|
||||
subgraph: ['KSampler'],
|
||||
dropped: 'legacy_model',
|
||||
links: { ...toSubgraph, inputs: { ...toSubgraph.inputs, legacy_model: 'subgraph input.model' } },
|
||||
},
|
||||
{
|
||||
name: 'an input whose type changed, linked to an input of a subgraph',
|
||||
subgraph: ['KSampler'],
|
||||
dropped: 'negative',
|
||||
links: { ...toSubgraph, inputs: { ...toSubgraph.inputs, negative: 'subgraph input.model' } },
|
||||
},
|
||||
];
|
||||
|
||||
for (const { name, stringIds = false, subgraph = [], dropped = '', links } of cases) {
|
||||
test(`Fix node (recreate) leaves one wired node — ${name}`, async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error) => errors.push(error.message));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await page.waitForFunction(() => !!(window as any).LiteGraph?.registered_node_types?.KSampler);
|
||||
|
||||
await page.evaluate(({ stringIds, subgraph, dropped }) => {
|
||||
const { app, LiteGraph } = window as any;
|
||||
const graph = app.canvas.graph;
|
||||
graph.clear();
|
||||
const add = (type: string, x: number, y: number) => {
|
||||
const node = LiteGraph.createNode(type);
|
||||
node.pos = [x, y];
|
||||
graph.add(node);
|
||||
return node;
|
||||
};
|
||||
const loader = add('CheckpointLoaderSimple', 50, 150);
|
||||
const prompt = add('CLIPTextEncode', 50, 350);
|
||||
const sampler = add('KSampler', 500, 150);
|
||||
const decoder = add('VAEDecode', 900, 150);
|
||||
loader.connect(0, sampler, 'model');
|
||||
prompt.connect(0, sampler, 'positive');
|
||||
sampler.connect(0, decoder, 'samples');
|
||||
|
||||
if (stringIds) {
|
||||
const toStringId = (node: any) => {
|
||||
delete graph._nodes_by_id[node.id];
|
||||
node.id = String(node.id);
|
||||
graph._nodes_by_id[node.id] = node;
|
||||
};
|
||||
graph.nodes.forEach(toStringId);
|
||||
for (const link of graph.links.values()) {
|
||||
link.origin_id = String(link.origin_id);
|
||||
link.target_id = String(link.target_id);
|
||||
}
|
||||
// The menu entry adds the replacement; it needs a string id as well.
|
||||
const graphAdd = graph.add.bind(graph);
|
||||
graph.add = (node: any, ...rest: unknown[]) => {
|
||||
const result = graphAdd(node, ...rest);
|
||||
toStringId(node);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
if (subgraph.length) {
|
||||
const moved = new Set(graph.nodes.filter((node: any) => subgraph.includes(node.type)));
|
||||
const converted = graph.convertToSubgraph(moved);
|
||||
app.canvas.openSubgraph(converted.subgraph, converted.node);
|
||||
if (dropped) {
|
||||
const inner = converted.subgraph.nodes.find((node: any) => node.type === 'KSampler');
|
||||
const input = inner.inputs.find((slot: any) => slot.name === dropped) ?? inner.addInput(dropped, 'MODEL');
|
||||
input.type = 'MODEL';
|
||||
const model = converted.subgraph.inputNode.slots.find((slot: any) => slot.name === 'model');
|
||||
model.connect(input, inner);
|
||||
}
|
||||
}
|
||||
}, { stringIds, subgraph, dropped });
|
||||
// Opening a subgraph re-fits the view a moment later.
|
||||
if (subgraph.length) await page.waitForTimeout(1_500);
|
||||
|
||||
// Every KSampler of the graph on screen, with the slots it is wired to. A
|
||||
// link to an input or output of the subgraph must be recorded on that slot
|
||||
// too: that record is what running and saving the workflow read.
|
||||
const readSamplers = () => page.evaluate(() => {
|
||||
const graph = (window as any).app.canvas.graph;
|
||||
const onSlot = (slot: any, link: any) =>
|
||||
`${slot.name}${slot.linkIds.includes(link.id) ? '' : ' (link not recorded on the slot)'}`;
|
||||
const origin = (link: any) => {
|
||||
if (link.origin_id === graph.inputNode?.id) {
|
||||
return `subgraph input.${onSlot(graph.inputNode.slots[link.origin_slot], link)}`;
|
||||
}
|
||||
const node = graph.getNodeById(link.origin_id);
|
||||
return `${node.type}.${node.outputs[link.origin_slot].name}`;
|
||||
};
|
||||
const target = (link: any) => {
|
||||
if (link.target_id === graph.outputNode?.id) {
|
||||
return `subgraph output.${onSlot(graph.outputNode.slots[link.target_slot], link)}`;
|
||||
}
|
||||
const node = graph.getNodeById(link.target_id);
|
||||
return `${node.type}.${node.inputs[link.target_slot].name}`;
|
||||
};
|
||||
return graph.nodes.filter((node: any) => node.type === 'KSampler').map((node: any) => ({
|
||||
id: node.id,
|
||||
inputs: Object.fromEntries(node.inputs.filter((input: any) => input.link != null)
|
||||
.map((input: any) => [input.name, origin(graph.links.get(input.link))])),
|
||||
outputs: (node.outputs[0].links ?? []).map((id: number) => target(graph.links.get(id))),
|
||||
}));
|
||||
});
|
||||
|
||||
const [original] = await readSamplers();
|
||||
expect(original).toMatchObject(links);
|
||||
|
||||
const title = await page.evaluate(() => {
|
||||
const { app, LiteGraph } = window as any;
|
||||
const sampler = app.canvas.graph.nodes.find((node: any) => node.type === 'KSampler');
|
||||
app.canvas.ds.scale = 1;
|
||||
app.canvas.ds.offset = [500 - sampler.pos[0], 150 - sampler.pos[1]];
|
||||
// The canvas finds the node under the pointer among the nodes it last drew.
|
||||
app.canvas.draw(true, true);
|
||||
return { x: 500 + 60, y: 150 - LiteGraph.NODE_TITLE_HEIGHT / 2 };
|
||||
});
|
||||
await page.mouse.click(title.x, title.y, { button: 'right' });
|
||||
await page.locator('.litecontextmenu .litemenu-entry', { hasText: 'Fix node (recreate)' }).click();
|
||||
|
||||
const samplers = await readSamplers();
|
||||
const expected = { ...original, id: expect.anything(), inputs: { ...original.inputs } };
|
||||
delete expected.inputs[dropped];
|
||||
// One comparison, so a failure shows the thrown error and the leftover node together.
|
||||
expect({ errors, samplers }).toEqual({ errors: [], samplers: [expected] });
|
||||
expect(samplers[0].id).not.toBe(original.id);
|
||||
});
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton } from './helpers';
|
||||
import { waitForComfyUI, openManagerMenu, clickMenuButton, closeToasts } from './helpers';
|
||||
|
||||
const SNAPSHOT_ROW_SELECTOR = '#snapshot-manager-dialog tr, #snapshot-manager-dialog li';
|
||||
|
||||
@@ -32,7 +32,7 @@ test.describe('Snapshot Manager', () => {
|
||||
test.afterEach(async ({ page }) => {
|
||||
// Cleanup snapshots newly created during the test to avoid state leak.
|
||||
for (const name of createdDuringTest) {
|
||||
await page.request.post(`/v2/snapshot/remove?target=${encodeURIComponent(name)}`);
|
||||
await page.request.post(`/v2/snapshot/remove?target=${encodeURIComponent(name)}`, { headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -78,7 +78,7 @@ test.describe('Snapshot Manager', () => {
|
||||
|
||||
test('UI Remove button deletes a snapshot row', async ({ page }) => {
|
||||
// SETUP: create a snapshot via API so we have a deterministic target
|
||||
const saveResp = await page.request.post('/v2/snapshot/save');
|
||||
const saveResp = await page.request.post('/v2/snapshot/save', { headers: { 'Content-Type': 'application/json' } });
|
||||
expect(saveResp.ok()).toBe(true);
|
||||
const namesAfterSave = await getSnapshotNames(page);
|
||||
expect(namesAfterSave.length).toBeGreaterThan(0);
|
||||
@@ -113,6 +113,7 @@ test.describe('Snapshot Manager', () => {
|
||||
page.once('dialog', async (d) => {
|
||||
await d.accept();
|
||||
});
|
||||
await closeToasts(page);
|
||||
await removeBtn.first().click();
|
||||
|
||||
// Effect verification: snapshot disappears from backend AND from UI
|
||||
@@ -121,4 +122,82 @@ test.describe('Snapshot Manager', () => {
|
||||
.toBe(false);
|
||||
await expect(page.locator(SNAPSHOT_ROW_SELECTOR, { hasText: targetName })).toHaveCount(0);
|
||||
});
|
||||
|
||||
/** List one snapshot, answer the given action with `status` and `body` without touching the disk, and
|
||||
* return once the dialog has finished handling the answer: it refreshes its list, and only then
|
||||
* decides about the restart notice. */
|
||||
async function clickAction(page: import('@playwright/test').Page, action: string, status: number, body: string,
|
||||
contentType = 'text/plain') {
|
||||
const name = '2026-01-01_00-00-00_<b>snapshot</b>';
|
||||
await page.route('**/v2/snapshot/getlist**', (route) => route.fulfill({ json: { items: [name] } }));
|
||||
await page.route(`**/v2/snapshot/${action.toLowerCase()}**`, (route) => route.fulfill({ status, body, contentType }));
|
||||
await clickMenuButton(page, 'Snapshot Manager');
|
||||
await page.waitForSelector('#snapshot-manager-dialog', { timeout: 10_000 });
|
||||
page.once('dialog', async (d) => {
|
||||
await d.accept();
|
||||
});
|
||||
await page.evaluate(async () => {
|
||||
const { SnapshotManager } = await import('/extensions/comfyui-manager-legacy/snapshot.js');
|
||||
const manager = SnapshotManager.instance;
|
||||
const refresh = manager.invalidateControl.bind(manager);
|
||||
(window as any).__handled = new Promise<void>((resolve) => {
|
||||
manager.invalidateControl = async () => {
|
||||
await refresh();
|
||||
setTimeout(resolve, 0);
|
||||
};
|
||||
});
|
||||
});
|
||||
await closeToasts(page);
|
||||
await page.locator(SNAPSHOT_ROW_SELECTOR, { hasText: name }).first()
|
||||
.locator(`button:has-text("${action}")`).click();
|
||||
await page.evaluate(() => (window as any).__handled);
|
||||
return name;
|
||||
}
|
||||
|
||||
async function messageDialog(page: import('@playwright/test').Page) {
|
||||
return page.evaluate(async () => {
|
||||
const { app } = await import('/scripts/app.js');
|
||||
const element = app.ui.dialog.element;
|
||||
return { text: element.textContent, markup: element.querySelectorAll('b, i').length };
|
||||
});
|
||||
}
|
||||
|
||||
const PROXY_PAGE = '<html><body><center><h1>502 Bad Gateway</h1></center><hr><i>proxy</i></body></html>';
|
||||
const failures: [string, number, string, string, string][] = [
|
||||
['400', 400, 'text/plain', '', 'HTTP 400 Bad Request'],
|
||||
['400, with a reason', 400, 'text/plain', 'Invalid <i>target</i>', 'Invalid <i>target</i>'],
|
||||
['502, with the page of a proxy', 502, 'text/html', PROXY_PAGE, 'HTTP 502 Bad Gateway'],
|
||||
];
|
||||
for (const action of ['Restore', 'Remove']) {
|
||||
for (const [label, status, contentType, body, reason] of failures) {
|
||||
test(`a failed ${action} (${label}) is reported as literal text`, async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (error) => errors.push(String(error)));
|
||||
|
||||
const name = await clickAction(page, action, status, body, contentType);
|
||||
|
||||
await expect.poll(async () => (await messageDialog(page)).text)
|
||||
.toContain(`${action} snapshot failed: ${name} / ${reason}`);
|
||||
expect((await messageDialog(page)).text).not.toContain('Bad Gateway<');
|
||||
expect((await messageDialog(page)).markup).toBe(0);
|
||||
// Nothing was scheduled, so there is nothing to restart for.
|
||||
await expect(page.locator('#cm-reboot-button2')).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('a Restore refused by the security level asks for no restart', async ({ page }) => {
|
||||
await clickAction(page, 'Restore', 403, '');
|
||||
|
||||
await expect.poll(async () => (await messageDialog(page)).text)
|
||||
.toContain('This action is not allowed with this security level configuration.');
|
||||
await expect(page.locator('#cm-reboot-button2')).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('an accepted Restore asks for a restart', async ({ page }) => {
|
||||
await clickAction(page, 'Restore', 200, '');
|
||||
|
||||
await expect(page.locator('#cm-reboot-button2')).toBeVisible();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -179,7 +179,9 @@ test.describe('model status and error sinks', () => {
|
||||
const onTheWire = serverSanitizeTag(XSS_PAYLOAD);
|
||||
expect(onTheWire).not.toBe(XSS_PAYLOAD);
|
||||
await routeModelList(page, [makeModel(onTheWire)]);
|
||||
let batchId: string | undefined;
|
||||
await page.route('**/v2/manager/queue/batch', async (route) => {
|
||||
batchId = route.request().postDataJSON().batch_id;
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: '{"failed": []}' });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
@@ -198,13 +200,16 @@ test.describe('model status and error sinks', () => {
|
||||
expect(status.imgs, `status write parsed into <img>: ${JSON.stringify(status.writes)}`).toBe(0);
|
||||
expect(status.carrying, 'status line does not carry the name as literal text').toBeGreaterThan(0);
|
||||
|
||||
// Batch completion: server-authored failure text reaches the message sink.
|
||||
await page.evaluate((payload) => {
|
||||
// Batch completion: server-authored failure text reaches the message sink. The Model Manager
|
||||
// takes the end of a batch only for a batch it queued, so the report carries that batch's id.
|
||||
await expect.poll(() => batchId, 'precondition: no batch was posted').toBeTruthy();
|
||||
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
|
||||
await page.evaluate(({ payload, batch_id }) => {
|
||||
const api = (window as unknown as Record<string, any>).comfyAPI.api.api;
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', {
|
||||
detail: { status: 'batch-done', model_result: { x: payload }, done_count: 1, total_count: 1 },
|
||||
detail: { status: 'batch-done', batch_id, model_result: { x: payload }, done_count: 1, total_count: 1 },
|
||||
}));
|
||||
}, XSS_PAYLOAD);
|
||||
}, { payload: XSS_PAYLOAD, batch_id: batchId });
|
||||
|
||||
const message = await analyseWrites(page, '__cmmMessageWrites', XSS_PAYLOAD);
|
||||
expect(message.carrying, `precondition: no message write carried the payload: ${JSON.stringify(message.writes)}`).toBeGreaterThan(0);
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Cache files stay fresh for a day after they are written, and are written whole.
|
||||
|
||||
A cache file is fresh for one day counted from its last write. A write puts the new
|
||||
content in place in one step, so the file holds the previous content or the new content
|
||||
and never a part of either, and it keeps the permissions it had. A file that stays open
|
||||
elsewhere, which cannot be replaced, is left as it is.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import errno
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
|
||||
|
||||
URI = 'https://example.invalid/custom-node-list.json'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def util(monkeypatch, tmp_path):
|
||||
import_context()
|
||||
from comfyui_manager.common import manager_util
|
||||
|
||||
monkeypatch.setattr(manager_util, 'cache_dir', str(tmp_path))
|
||||
return manager_util
|
||||
|
||||
|
||||
def cache_files(tmp_path):
|
||||
return sorted(path.name for path in tmp_path.iterdir())
|
||||
|
||||
|
||||
def test_rewritten_cache_is_fresh_whatever_its_creation_time(util, monkeypatch):
|
||||
"""On Windows a rewritten file keeps the creation time of the first write."""
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
monkeypatch.setattr(util.os.path, 'getctime', lambda path: time.time() - 10 * 86400)
|
||||
|
||||
assert util.get_cache_state(URI) == 'cached'
|
||||
|
||||
|
||||
def test_cache_expires_a_day_after_its_last_write(util):
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
|
||||
almost_a_day_ago = time.time() - 86400 + 60
|
||||
os.utime(cache, (almost_a_day_ago, almost_a_day_ago))
|
||||
assert util.get_cache_state(URI) == 'cached'
|
||||
|
||||
over_a_day_ago = time.time() - 86400 - 60
|
||||
os.utime(cache, (over_a_day_ago, over_a_day_ago))
|
||||
assert util.get_cache_state(URI) == 'expired'
|
||||
|
||||
|
||||
def test_failed_write_keeps_the_previous_content(util, tmp_path):
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
util.save_to_cache(URI, {'b': 2, 'c': object()}, silent=True)
|
||||
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'a': 1}
|
||||
assert cache_files(tmp_path) == [os.path.basename(cache)]
|
||||
|
||||
|
||||
def test_write_that_runs_out_of_space_keeps_the_previous_content(util, monkeypatch, tmp_path):
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
|
||||
def disk_full(obj, file, **_):
|
||||
file.write('{"b": ')
|
||||
raise OSError(errno.ENOSPC, 'No space left on device')
|
||||
|
||||
monkeypatch.setattr(util.json, 'dump', disk_full)
|
||||
with pytest.raises(OSError):
|
||||
util.save_to_cache(URI, {'b': 2}, silent=True)
|
||||
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'a': 1}
|
||||
assert cache_files(tmp_path) == [os.path.basename(cache)]
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == 'win32', reason='POSIX permission bits')
|
||||
def test_write_keeps_the_permissions_of_the_file(util, tmp_path):
|
||||
plain = tmp_path / 'plain'
|
||||
plain.write_text('')
|
||||
default_mode = plain.stat().st_mode & 0o777
|
||||
plain.unlink()
|
||||
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
assert os.stat(cache).st_mode & 0o777 == default_mode
|
||||
|
||||
other_mode = default_mode ^ 0o040 # never what a new file gets
|
||||
os.chmod(cache, other_mode)
|
||||
util.save_to_cache(URI, {'b': 2}, silent=True)
|
||||
assert os.stat(cache).st_mode & 0o777 == other_mode
|
||||
|
||||
|
||||
def test_cache_is_replaced_where_its_mode_cannot_be_set(util, monkeypatch, tmp_path):
|
||||
"""A file system may refuse chmod; the cache is still replaced in one step."""
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
replace = util.os.replace
|
||||
replaced = []
|
||||
|
||||
def refuse(path, mode):
|
||||
raise PermissionError(errno.EPERM, 'Operation not permitted', path)
|
||||
|
||||
def record(src, dst):
|
||||
replaced.append(dst)
|
||||
replace(src, dst)
|
||||
|
||||
monkeypatch.setattr(util.os, 'chmod', refuse)
|
||||
monkeypatch.setattr(util.os, 'replace', record)
|
||||
util.save_to_cache(URI, {'b': 2}, silent=True)
|
||||
|
||||
assert replaced == [cache]
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'b': 2}
|
||||
assert cache_files(tmp_path) == [os.path.basename(cache)]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def refusing_replace(util, monkeypatch):
|
||||
"""Make os.replace refuse the given number of times, as Windows does while another reader has
|
||||
the file open, and then replace; returns the list of attempts."""
|
||||
def install(refusals):
|
||||
replace = util.os.replace
|
||||
attempts = []
|
||||
|
||||
def attempt(src, dst):
|
||||
attempts.append(dst)
|
||||
if len(attempts) <= refusals:
|
||||
raise PermissionError(13, 'The process cannot access the file', dst)
|
||||
replace(src, dst)
|
||||
|
||||
monkeypatch.setattr(util.os, 'replace', attempt)
|
||||
monkeypatch.setattr(util.time, 'sleep', lambda seconds: None)
|
||||
return attempts
|
||||
|
||||
return install
|
||||
|
||||
|
||||
def test_file_is_replaced_once_the_reader_has_closed_it(util, refusing_replace, monkeypatch, tmp_path):
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
attempts = refusing_replace(2)
|
||||
dump = Mock(wraps=util.json.dump)
|
||||
monkeypatch.setattr(util.json, 'dump', dump)
|
||||
|
||||
util.save_to_cache(URI, {'b': 2}, silent=True)
|
||||
|
||||
assert len(attempts) == 3
|
||||
assert dump.call_count == 1, 'the cache must not be written in place'
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'b': 2}
|
||||
assert cache_files(tmp_path) == [os.path.basename(cache)]
|
||||
|
||||
|
||||
def test_file_that_stays_open_elsewhere_is_left_as_it_is(util, refusing_replace, tmp_path, caplog):
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
attempts = refusing_replace(100)
|
||||
|
||||
with caplog.at_level('INFO'):
|
||||
# The caller sees no error: it goes on with the data it fetched.
|
||||
util.save_to_cache(URI, {'b': 2})
|
||||
|
||||
assert len(attempts) == 3
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'a': 1}
|
||||
assert cache_files(tmp_path) == [os.path.basename(cache)]
|
||||
assert 'The cache could not be replaced' in caplog.text
|
||||
assert 'default cache updated' not in caplog.text
|
||||
|
||||
|
||||
def test_temporary_file_that_is_open_elsewhere_does_not_fail_the_write(util, refusing_replace, monkeypatch):
|
||||
"""A scanner that opens the new file keeps Windows from replacing with it and from removing it."""
|
||||
util.save_to_cache(URI, {'a': 1}, silent=True)
|
||||
cache = util.get_cache_path(URI)
|
||||
attempts = refusing_replace(100)
|
||||
|
||||
def refuse(path):
|
||||
raise PermissionError(13, 'The process cannot access the file', path)
|
||||
|
||||
monkeypatch.setattr(util.os, 'remove', refuse)
|
||||
|
||||
assert util.write_cache_file(cache, {'b': 2}) is False
|
||||
assert len(attempts) == 3
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'a': 1}
|
||||
|
||||
|
||||
def test_fetched_data_is_cached_whole(util, tmp_path):
|
||||
source = tmp_path / 'source.json'
|
||||
source.write_text(json.dumps({'a': 1}))
|
||||
cache = util.get_cache_path(str(source))
|
||||
|
||||
assert asyncio.run(util.get_data_with_cache(str(source), silent=True, cache_mode=False)) == {'a': 1}
|
||||
|
||||
assert json.loads(open(cache, encoding='utf-8').read()) == {'a': 1}
|
||||
assert cache_files(tmp_path) == sorted([os.path.basename(cache), 'source.json'])
|
||||
@@ -0,0 +1,172 @@
|
||||
"""A channel response that is not JSON does not empty a list (#3480).
|
||||
|
||||
The channel is a local HTTP server. The startup cache update and `get_data_by_mode`
|
||||
are the real functions of each server, run against a temporary cache directory and a
|
||||
temporary bundled list. The Manager is laid out as an installed package, so the lists
|
||||
are read from the cache that the startup cache update writes.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import traceback
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
FILENAME = "model-list.json"
|
||||
STARTUP_FILES = 4
|
||||
BUNDLED = {"models": [{"name": "bundled with the Manager"}]}
|
||||
SERVED = {"models": [{"name": "served by the channel"}]}
|
||||
NOT_JSON = [
|
||||
pytest.param(200, "<html><body>Access blocked</body></html>", id="block page"),
|
||||
pytest.param(404, "404: Not Found", id="missing file"),
|
||||
]
|
||||
SERVERS = ["glob", "legacy"]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reach_the_channel_directly(monkeypatch):
|
||||
# get_data() honors the proxy variables of the environment.
|
||||
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
|
||||
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager_util(tmp_path, monkeypatch):
|
||||
import_context()
|
||||
from comfyui_manager.common import manager_util
|
||||
|
||||
monkeypatch.setattr(manager_util, "comfyui_manager_path", str(tmp_path / "manager"))
|
||||
monkeypatch.setattr(manager_util, "cache_dir", str(tmp_path / "cache"))
|
||||
os.makedirs(manager_util.comfyui_manager_path)
|
||||
os.makedirs(manager_util.cache_dir)
|
||||
with open(os.path.join(manager_util.comfyui_manager_path, FILENAME), "w", encoding="utf-8") as f:
|
||||
json.dump(BUNDLED, f)
|
||||
return manager_util
|
||||
|
||||
|
||||
def load_server(server, manager_util, channel_url):
|
||||
"""The startup cache update and `get_data_by_mode` of `server`, set to read `channel_url`."""
|
||||
async def loaded(*args, **kwargs):
|
||||
pass
|
||||
|
||||
config = {"channel_url": channel_url, "network_mode": "public", "default_cache_as_channel_url": True}
|
||||
core = SimpleNamespace(get_config=lambda: config, refresh_channel_dict=lambda: None, check_invalid_nodes=lambda: None,
|
||||
unified_manager=SimpleNamespace(reload=loaded, get_custom_nodes=loaded))
|
||||
remote = SimpleNamespace(remote=SimpleNamespace(value="remote"))
|
||||
startup = load_functions(PACKAGE / server / "manager_server.py", {"default_cache_update"}, {
|
||||
"os": os, "json": json, "logging": logging, "traceback": traceback, "asyncio": asyncio,
|
||||
"manager_util": manager_util, "core": core, "ManagerDatabaseSource": remote})
|
||||
reader = load_functions(PACKAGE / server / "manager_core.py", {"get_data_by_mode"}, {
|
||||
"os": os, "json": json, "manager_util": manager_util,
|
||||
"get_config": lambda: config, "normalize_channel": lambda channel: channel})
|
||||
return startup["default_cache_update"], reader["get_data_by_mode"]
|
||||
|
||||
|
||||
class Channel:
|
||||
def __init__(self):
|
||||
self.requests = 0
|
||||
self.serve(200, json.dumps(SERVED))
|
||||
|
||||
def serve(self, status, text):
|
||||
self.status, self.text = status, text
|
||||
|
||||
async def handle(self, request):
|
||||
self.requests += 1
|
||||
return web.Response(status=self.status, text=self.text)
|
||||
|
||||
|
||||
def run(scenario):
|
||||
async def main():
|
||||
channel = Channel()
|
||||
app = web.Application()
|
||||
app.router.add_get("/main/{name}", channel.handle)
|
||||
server = TestServer(app)
|
||||
await server.start_server()
|
||||
try:
|
||||
return await scenario(channel, str(server.make_url("/main")))
|
||||
finally:
|
||||
await server.close()
|
||||
|
||||
return asyncio.run(main())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_response_that_is_not_json_is_an_error(manager_util, status, text):
|
||||
async def scenario(channel, channel_url):
|
||||
channel.serve(status, text)
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
await manager_util.get_data(f"{channel_url}/{FILENAME}")
|
||||
|
||||
run(scenario)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_bundled_list_is_used_and_nothing_is_cached(manager_util, server, status, text):
|
||||
async def scenario(channel, channel_url):
|
||||
start, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
channel.serve(status, text)
|
||||
await start()
|
||||
return await get_data_by_mode("cache", FILENAME), os.listdir(manager_util.cache_dir), channel.requests
|
||||
|
||||
result, cached, requests = run(scenario)
|
||||
|
||||
assert requests == STARTUP_FILES
|
||||
assert result == BUNDLED
|
||||
assert cached == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_list_cached_by_an_earlier_start_is_kept(manager_util, server, status, text):
|
||||
async def scenario(channel, channel_url):
|
||||
start, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
await start()
|
||||
channel.serve(status, text)
|
||||
await start()
|
||||
return await get_data_by_mode("cache", FILENAME)
|
||||
|
||||
assert run(scenario) == SERVED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
@pytest.mark.parametrize("status, text", NOT_JSON)
|
||||
def test_next_start_reads_the_list_from_the_channel(manager_util, server, status, text):
|
||||
async def scenario(channel, channel_url):
|
||||
start, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
channel.serve(status, text)
|
||||
await start()
|
||||
channel.serve(200, json.dumps(SERVED))
|
||||
await start()
|
||||
return await get_data_by_mode("cache", FILENAME)
|
||||
|
||||
assert run(scenario) == SERVED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", SERVERS)
|
||||
def test_list_from_the_channel_is_read_from_the_cache(manager_util, server):
|
||||
async def scenario(channel, channel_url):
|
||||
start, get_data_by_mode = load_server(server, manager_util, channel_url)
|
||||
await start()
|
||||
first = await get_data_by_mode("cache", FILENAME)
|
||||
second = await get_data_by_mode("cache", FILENAME)
|
||||
return first, second, channel.requests
|
||||
|
||||
assert run(scenario) == (SERVED, SERVED, STARTUP_FILES)
|
||||
|
||||
|
||||
def test_unreadable_local_file_still_reads_as_empty(manager_util):
|
||||
async def scenario(channel, channel_url):
|
||||
path = os.path.join(manager_util.comfyui_manager_path, "broken.json")
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write("{")
|
||||
return await manager_util.get_data(path)
|
||||
|
||||
assert run(scenario) == {}
|
||||
@@ -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 / "comfyui_manager" / "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 /v2/customnode/check_update {"mode":"cache","ui_id":"check-1"}'
|
||||
LIST = "GET /v2/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,398 @@
|
||||
import ast
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import traceback
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE
|
||||
from test_invalid_installation import BAR_URL, FOO_URL, NODE_LIST, core, custom_nodes, pack # noqa: F401 -- fixtures
|
||||
|
||||
pytestmark = pytest.mark.parametrize('core', ['legacy'], indirect=True)
|
||||
|
||||
|
||||
def server(names, **namespace):
|
||||
path = PACKAGE / 'legacy/manager_server.py'
|
||||
nodes = [node for node in ast.parse(path.read_text(encoding='utf-8')).body if getattr(node, 'name', None) in names]
|
||||
assert {node.name for node in nodes} == set(names)
|
||||
for node in nodes:
|
||||
node.decorator_list = []
|
||||
exec(compile(ast.Module(nodes, []), str(path), 'exec'), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
def request(query=None, body=None):
|
||||
async def json_body():
|
||||
return body
|
||||
return SimpleNamespace(rel_url=SimpleNamespace(query=query), json=json_body)
|
||||
|
||||
|
||||
class Fetched(list):
|
||||
answers: dict
|
||||
during_a_fetch: list
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fetched(core, custom_nodes, monkeypatch): # noqa: F811
|
||||
names = Fetched()
|
||||
names.answers = answers = {}
|
||||
names.during_a_fetch = during_a_fetch = []
|
||||
|
||||
def fetch(path):
|
||||
name = Path(path).name
|
||||
names.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))
|
||||
|
||||
monkeypatch.setattr(core, 'git_repo_update_check_with', fetch)
|
||||
return names
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def listed(core, custom_nodes, monkeypatch): # noqa: F811
|
||||
node_list = [dict(item) for item in NODE_LIST]
|
||||
|
||||
async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
shown = add.others.get('the local mode' if mode == 'local' else channel_url, node_list)
|
||||
return {'custom-node-list.json': {'custom_nodes': [dict(item) for item in shown]},
|
||||
'extras.json': {'favorites': []}}.get(filename, {})
|
||||
|
||||
monkeypatch.setattr(core, 'get_data_by_mode', get_data_by_mode)
|
||||
|
||||
def add(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
|
||||
|
||||
add.others = {}
|
||||
return add
|
||||
|
||||
|
||||
class Lock:
|
||||
def __init__(self, update_check_done):
|
||||
self.held = threading.Lock()
|
||||
self.update_check_done = update_check_done
|
||||
self.after_the_end = []
|
||||
|
||||
def __enter__(self):
|
||||
self.held.acquire()
|
||||
|
||||
def __exit__(self, *error):
|
||||
self.held.release()
|
||||
if self.after_the_end and self.update_check_done.is_set():
|
||||
self.after_the_end.pop()()
|
||||
|
||||
|
||||
class Checks:
|
||||
def __init__(self, core): # noqa: F811
|
||||
self.events = []
|
||||
self.started = []
|
||||
self.update_check_done = threading.Event()
|
||||
self.update_check_done.set()
|
||||
self.update_check_lock = Lock(self.update_check_done)
|
||||
self.thread = lambda target: SimpleNamespace(start=lambda: self.started.append(target))
|
||||
self.ask = server(
|
||||
{'check_update'}, core=core, update_check_done=self.update_check_done, update_check_lock=self.update_check_lock,
|
||||
update_check_paths={}, update_check_ui_ids=set(), traceback=traceback,
|
||||
threading=SimpleNamespace(Thread=lambda target: self.thread(target)),
|
||||
manager_security=SimpleNamespace(reject_non_json_post=lambda request: None),
|
||||
web=SimpleNamespace(json_response=lambda data: data),
|
||||
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=self.sent)))['check_update']
|
||||
|
||||
def sent(self, name, data):
|
||||
self.events.append((name, {key: sorted(value) if isinstance(value, list) else value for key, value in data.items()}))
|
||||
|
||||
def ask_for_a_check(self, mode='cache', ui_id='the page'):
|
||||
return asyncio.run(self.ask(request(body={'mode': mode, 'ui_id': ui_id})))
|
||||
|
||||
def ended(self):
|
||||
return [event for name, event in self.events if event['status'] == 'done']
|
||||
|
||||
|
||||
def check_for_updates(core, fetched, mode='cache'): # noqa: F811
|
||||
checks = Checks(core)
|
||||
answer = checks.ask_for_a_check(mode)
|
||||
fetched_by_the_request = list(fetched)
|
||||
checks.started.pop()()
|
||||
return {'answer': answer, 'fetched by the request': fetched_by_the_request, 'fetched': sorted(fetched),
|
||||
'check': [event for name, event in checks.events if name == 'cm-check-update']}
|
||||
|
||||
|
||||
class EndMark(threading.Event):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.queue_waits = threading.Event()
|
||||
|
||||
def wait(self):
|
||||
self.queue_waits.set()
|
||||
super().wait()
|
||||
|
||||
|
||||
DISABLE = ('disable', ('a-row', 'ComfyUI-Foo', False))
|
||||
|
||||
|
||||
def run_the_queue(core, monkeypatch, update_check_done, *tasks): # noqa: F811
|
||||
order = []
|
||||
scratch = Path(core.get_default_custom_nodes_path()).parent
|
||||
core.get_config()['model_download_by_agent'] = True
|
||||
monkeypatch.setattr(core, 'update_path', lambda path: order.append('ComfyUI is updated') or 'skipped')
|
||||
monkeypatch.setattr(core.unified_manager, 'unified_disable', lambda node_name, is_unknown: order.append('the task') or core.ManagedResult('disable'))
|
||||
monkeypatch.setattr(core.unified_manager, 'unified_enable', lambda cnr_id: order.append('the task') or core.ManagedResult('enable'))
|
||||
monkeypatch.setattr(core.unified_manager, 'unified_update', lambda node_name, node_ver: order.append('the task') or SimpleNamespace(
|
||||
ver='unknown', result=True, action='skip'))
|
||||
namespace = server({'task_worker', 'TaskBatch'}, core=core, logging=logging, traceback=traceback, os=os,
|
||||
folder_paths=SimpleNamespace(__file__=str(scratch / 'folder_paths.py')),
|
||||
get_model_path=lambda data: str(scratch / 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), replaces_cnr_with_nightly=lambda node_id: False,
|
||||
update_check_done=update_check_done, tasks_in_progress=set(), task_worker_lock=threading.Lock(),
|
||||
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=lambda name, data: None)))
|
||||
namespace['task_batch_queue'] = deque([namespace['TaskBatch'](None, list(tasks), None)])
|
||||
queue_run = threading.Thread(target=lambda: asyncio.run(namespace['task_worker']()), daemon=True)
|
||||
queue_run.start()
|
||||
return order, queue_run
|
||||
|
||||
|
||||
def run_the_queue_during_a_check(core, monkeypatch, *tasks): # noqa: F811
|
||||
update_check_done = EndMark()
|
||||
order, queue_run = run_the_queue(core, monkeypatch, update_check_done, *tasks)
|
||||
update_check_done.queue_waits.wait(5)
|
||||
order.append('the check ends')
|
||||
update_check_done.set()
|
||||
queue_run.join()
|
||||
return order
|
||||
|
||||
|
||||
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(core, custom_nodes, listed, fetched, query): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
handler = server({'fetch_customnode_list'}, core=core, populate_markdown=lambda row: None,
|
||||
web=SimpleNamespace(json_response=lambda result, content_type: result))['fetch_customnode_list']
|
||||
|
||||
rows = asyncio.run(handler(request(query=query)))['node_packs']
|
||||
|
||||
assert {key: row['active_version'] for key, row in rows.items() if row['state'] == 'enabled'} == {
|
||||
'comfyui-foo': 'nightly', 'ComfyUI-Bar': 'unknown'}
|
||||
assert fetched == []
|
||||
|
||||
|
||||
def test_a_check_fetches_the_enabled_git_nodepacks_of_the_list_once_its_request_is_answered(
|
||||
core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'bar-clone', git_url=BAR_URL)
|
||||
pack(custom_nodes / '.disabled/ComfyUI-Bar')
|
||||
pack(custom_nodes / 'comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
|
||||
pack(custom_nodes / '.disabled/ComfyUI-Disabled', git_url=listed('ComfyUI-Disabled'))
|
||||
listed('ComfyUI-Invalid')
|
||||
pack(custom_nodes / 'ComfyUI-Invalid')
|
||||
pack(custom_nodes / 'ComfyUI-NotListed', git_url='https://github.com/example/ComfyUI-NotListed')
|
||||
fetched.answers.update({'ComfyUI-Foo': (True, True), 'bar-clone': (True, True)})
|
||||
|
||||
data = check_for_updates(core, fetched)
|
||||
|
||||
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', ['the local mode', 'https://example.invalid/a-channel'],
|
||||
ids=['the-local-list', 'the-list-of-another-channel'])
|
||||
def test_a_check_is_of_the_list_that_the_page_shows(core, custom_nodes, listed, fetched, monkeypatch, shown): # noqa: F811
|
||||
mode = 'cache'
|
||||
if shown == 'the local mode':
|
||||
mode = 'local'
|
||||
else:
|
||||
core.get_config()['channel_url'] = shown
|
||||
monkeypatch.setattr(core, 'valid_channels', core.valid_channels | {shown})
|
||||
listed.others[shown] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
|
||||
assert check_for_updates(core, fetched, mode=mode)['fetched'] == ['ComfyUI-Foo']
|
||||
|
||||
|
||||
def test_a_nodepack_that_cannot_be_fetched_does_not_end_the_check(core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Qux', git_url=listed('ComfyUI-Qux'))
|
||||
fetched.answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': OSError('no route to the remote')})
|
||||
|
||||
data = check_for_updates(core, fetched)
|
||||
|
||||
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(core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
|
||||
|
||||
data = check_for_updates(core, fetched)
|
||||
|
||||
assert data['answer'] == {}
|
||||
assert data['check'] == [done([])]
|
||||
|
||||
|
||||
def test_a_check_that_is_asked_for_while_one_runs_starts_no_second_one(core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
fetched.answers['ComfyUI-Foo'] = (True, True)
|
||||
checks = Checks(core)
|
||||
|
||||
assert [checks.ask_for_a_check(ui_id='a page'), checks.ask_for_a_check(ui_id='another page')] == [{}, {}]
|
||||
assert len(checks.started) == 1
|
||||
checks.started.pop()()
|
||||
assert checks.ended() == [done(['comfyui-foo'], 'a page', 'another page')]
|
||||
checks.ask_for_a_check()
|
||||
assert len(checks.started) == 1
|
||||
|
||||
|
||||
def test_a_check_that_is_asked_for_while_one_runs_adds_the_nodepacks_that_one_does_not_have(
|
||||
core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
listed.others['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
fetched.answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
|
||||
checks = Checks(core)
|
||||
|
||||
checks.ask_for_a_check('local', ui_id='a page')
|
||||
fetched.during_a_fetch.append(lambda: checks.ask_for_a_check(ui_id='another page'))
|
||||
checks.started.pop()()
|
||||
|
||||
assert fetched == ['ComfyUI-Foo', 'ComfyUI-Bar']
|
||||
assert checks.started == []
|
||||
assert [event for name, event in checks.events] == [
|
||||
{'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(
|
||||
core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
listed.others['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
fetched.answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
|
||||
checks = Checks(core)
|
||||
|
||||
checks.ask_for_a_check('local', ui_id='a page')
|
||||
checks.update_check_lock.after_the_end.append(lambda: checks.ask_for_a_check(ui_id='another page'))
|
||||
checks.started.pop()()
|
||||
|
||||
first = [event for name, event in checks.events]
|
||||
assert first == progress(1) + [done(['comfyui-foo'], 'a page')]
|
||||
assert len(checks.started) == 1
|
||||
assert not checks.update_check_done.is_set()
|
||||
|
||||
del fetched[:]
|
||||
checks.started.pop()()
|
||||
|
||||
assert [event for name, event in checks.events[len(first):]] == progress(2) + [
|
||||
done(['comfyui-foo', 'ComfyUI-Bar'], 'another page')]
|
||||
assert sorted(fetched) == ['ComfyUI-Bar', 'ComfyUI-Foo']
|
||||
|
||||
|
||||
def test_a_check_is_not_of_the_requests_of_the_check_before(core, custom_nodes, listed, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
pack(custom_nodes / 'ComfyUI-Bar', git_url=BAR_URL)
|
||||
listed.others['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
|
||||
checks = Checks(core)
|
||||
|
||||
checks.ask_for_a_check(ui_id='a page')
|
||||
checks.started.pop()()
|
||||
del fetched[:]
|
||||
checks.ask_for_a_check('local', ui_id='another page')
|
||||
checks.started.pop()()
|
||||
|
||||
assert fetched == ['ComfyUI-Foo']
|
||||
assert checks.ended()[-1] == done([], 'another page')
|
||||
|
||||
|
||||
def test_a_check_whose_thread_cannot_start_does_not_stand_in_the_way_of_the_next(core, custom_nodes, listed): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
checks = Checks(core)
|
||||
started_later = checks.thread
|
||||
|
||||
def no_thread(target):
|
||||
raise RuntimeError("can't start new thread")
|
||||
|
||||
checks.thread = no_thread
|
||||
with pytest.raises(RuntimeError):
|
||||
checks.ask_for_a_check()
|
||||
checks.thread = started_later
|
||||
checks.ask_for_a_check()
|
||||
|
||||
assert len(checks.started) == 1
|
||||
|
||||
|
||||
def test_a_check_that_fails_tells_the_pages_that_wait_for_it_and_does_not_hold_the_tasks_of_the_queue(
|
||||
core, custom_nodes, listed, monkeypatch): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
|
||||
checks = Checks(core)
|
||||
during_the_check = [lambda: checks.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")
|
||||
|
||||
monkeypatch.setattr(core, 'fetch_git_node_packs', fails)
|
||||
|
||||
checks.ask_for_a_check()
|
||||
checks.update_check_lock.after_the_end.append(lambda: checks.ask_for_a_check(ui_id='a page that asks after it'))
|
||||
checks.started.pop()()
|
||||
|
||||
failed = [event for name, event in checks.events]
|
||||
assert failed == [{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks during the check', 'the page']}]
|
||||
assert len(checks.started) == 1
|
||||
|
||||
checks.started.pop()()
|
||||
order, queue_run = run_the_queue(core, monkeypatch, checks.update_check_done, DISABLE)
|
||||
queue_run.join(5)
|
||||
|
||||
assert [event for name, event in checks.events[len(failed):]] == [
|
||||
{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks after it']}]
|
||||
assert order == ['the task']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('task', [DISABLE, ('enable', ('a-row', 'comfyui-foo')), ('update-main', ('ComfyUI-Foo', 'ComfyUI-Foo', 'unknown'))],
|
||||
ids=['disable', 'enable', 'Update-All'])
|
||||
def test_a_task_of_the_queue_waits_for_the_check_that_runs(core, custom_nodes, monkeypatch, task): # noqa: F811
|
||||
assert run_the_queue_during_a_check(core, monkeypatch, task) == ['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(core, custom_nodes, monkeypatch, task, work): # noqa: F811
|
||||
assert run_the_queue_during_a_check(core, monkeypatch, task, DISABLE) == [work, 'the check ends', 'the task']
|
||||
|
||||
|
||||
def test_the_request_that_fetched_inside_itself_is_gone(core, custom_nodes, fetched): # noqa: F811
|
||||
pack(custom_nodes / 'ComfyUI-Foo', git_url=FOO_URL)
|
||||
handler = server({'fetch_updates'}, web=SimpleNamespace(
|
||||
json_response=lambda data, status: (status, data['deprecated'])))['fetch_updates']
|
||||
|
||||
assert asyncio.run(handler(request(query={'mode': 'cache'}))) == (410, True)
|
||||
assert fetched == []
|
||||
@@ -0,0 +1,381 @@
|
||||
"""The legacy UI enables a disabled node pack that another extension asks for, and then restarts.
|
||||
|
||||
An extension asks through `cm.try-install-custom-node` for a node pack it needs. When the pack is
|
||||
disabled, the legacy UI asks the user whether to enable it and restart. It enables the pack as
|
||||
the Enable button of the Custom Nodes Manager does: it finds the pack in the node list, puts it
|
||||
in the queue, and waits for the queue. It restarts only after the queue reports success, and
|
||||
the wait has an end.
|
||||
|
||||
The cases run the shipped cm-api.js and common.js in Chromium against stand-ins for ComfyUI's
|
||||
scripts; no ComfyUI server is used. The stand-in for the API answers each route as the case
|
||||
says and records the requests.
|
||||
|
||||
Browser cases require Playwright and its Chromium install.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
|
||||
|
||||
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
|
||||
EXTENSION = "http://manager.test/extensions/comfyui-manager-legacy/"
|
||||
|
||||
GETLIST = "/v2/customnode/getlist"
|
||||
STATUS = "/v2/manager/queue/status"
|
||||
BATCH = "/v2/manager/queue/batch"
|
||||
REBOOT = "/v2/manager/reboot"
|
||||
# the requests that enable the pack
|
||||
ENABLE = [("GET", GETLIST), ("GET", STATUS), ("POST", BATCH)]
|
||||
|
||||
URL = "https://github.com/someone/Other-Pack"
|
||||
# The entry of custom-node-list.json that the server sends with the request
|
||||
TARGET = {"title": "Other Pack", "installed": "Disabled", "files": [URL], "id": "listed-id"}
|
||||
# The node list as /v2/customnode/getlist answers it: rows by key
|
||||
PACKS = {
|
||||
"another-pack": {"id": "another-pack", "title": "Another Pack", "version": "1.0.0", "state": "disabled",
|
||||
"files": ["https://github.com/someone/Another-Pack"]},
|
||||
"from-the-registry": {"id": "from-the-registry", "title": "No Files", "version": "1.0.0", "state": "disabled"},
|
||||
"other-pack": {"id": "other-pack", "title": "Other Pack", "version": "nightly", "state": "disabled",
|
||||
"files": [URL], "repository": URL},
|
||||
}
|
||||
UI_ID = hashlib.md5(b"other-pack").hexdigest()
|
||||
|
||||
SCRIPTS = {
|
||||
# `window.answers[route]` says how a route answers: `status`, `json`, `fails` for a request that
|
||||
# gets no answer, and for the batch route `result`, which the queue reports for the pack either
|
||||
# `before` the request is answered or after it; `remaining` is the number of batches the queue
|
||||
# then holds, this one included. With `emptied` the queue only reports that it has finished, and
|
||||
# with `silent` no report reaches the page. The end of an earlier run is reported while the
|
||||
# batch request is handled.
|
||||
"api.js": """
|
||||
class Api extends EventTarget {
|
||||
report(detail) {
|
||||
this.dispatchEvent(new CustomEvent('cm-queue-status', {detail}));
|
||||
}
|
||||
|
||||
async fetchApi(path, options) {
|
||||
const route = path.split('?')[0];
|
||||
const answer = window.answers[route] ?? {};
|
||||
const body = options?.body ? JSON.parse(options.body) : null;
|
||||
window.requested.push({path, method: options?.method ?? 'GET', body});
|
||||
if(answer.fails) {
|
||||
throw new TypeError('Failed to fetch');
|
||||
}
|
||||
if(route == '/v2/manager/queue/batch') {
|
||||
this.report({status: 'all-done'});
|
||||
}
|
||||
if(answer.emptied) {
|
||||
setTimeout(() => this.report({status: 'all-done'}), 50);
|
||||
}
|
||||
else if(answer.result !== undefined && !answer.silent) {
|
||||
const report = () => {
|
||||
this.report({status: 'in_progress', target: body.install[0].ui_id, batch_id: body.batch_id});
|
||||
this.report({status: 'batch-done', batch_id: 'another-batch', nodepack_result: {}});
|
||||
this.report({status: 'batch-done', batch_id: body.batch_id,
|
||||
remaining_batch_count: answer.remaining ?? 1,
|
||||
nodepack_result: answer.result === null ? {} : {[body.install[0].ui_id]: answer.result}});
|
||||
this.report({status: 'all-done'});
|
||||
};
|
||||
if(answer.before) report(); else setTimeout(report, 50);
|
||||
}
|
||||
return {status: answer.status ?? 200, json: async () => answer.json, text: async () => ''};
|
||||
}
|
||||
}
|
||||
export const api = new Api();
|
||||
""",
|
||||
# `show_message` in common.js and the handler show their text in this dialog.
|
||||
"app.js": """
|
||||
const element = document.createElement('div');
|
||||
element.id = 'comfy-dialog';
|
||||
document.body.append(element);
|
||||
export const app = {ui: {dialog: {element, show(html) { element.innerHTML = html; }}}};
|
||||
""",
|
||||
"ui.js": "export const $el = () => null; export class ComfyDialog {}",
|
||||
}
|
||||
|
||||
|
||||
@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.on("pageerror", lambda error: page.errors.append(str(error)))
|
||||
page.goto("http://manager.test/")
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
# The batch is accepted, and the queue reports the pack as enabled.
|
||||
ENABLED = {"json": {"failed": []}, "result": "success"}
|
||||
|
||||
|
||||
def answers(batch=ENABLED, reboot=None, packs=PACKS, getlist=None, status=None):
|
||||
"""How the routes answer; by default the pack is listed as disabled, the queue is idle, the pack is enabled, and the restart is accepted."""
|
||||
return {
|
||||
GETLIST: {"json": {"channel": "default", "node_packs": packs}} if getlist is None else getlist,
|
||||
STATUS: {"json": {"is_processing": False}} if status is None else status,
|
||||
BATCH: batch,
|
||||
REBOOT: {} if reboot is None else reboot,
|
||||
}
|
||||
|
||||
|
||||
def ask(page, answers, target=TARGET):
|
||||
"""Deliver the request an extension makes for `target`."""
|
||||
page.evaluate("""async ({answers, target, module}) => {
|
||||
window.requested = [];
|
||||
window.answers = answers;
|
||||
await import(module);
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-api-try-install-customnode', {detail: {
|
||||
sender: 'Some Pack', msg: 'needed for the detector nodes', target,
|
||||
}}));
|
||||
}""", {"answers": answers, "target": target, "module": EXTENSION + "cm-api.js"})
|
||||
|
||||
|
||||
def confirm(page):
|
||||
"""Confirm the dialog that asks whether to enable the pack and restart."""
|
||||
question = page.get_by_text("Would you like to enable it and reboot?")
|
||||
question.wait_for()
|
||||
assert "'Some Pack' extension requires the installation of the 'Other Pack' extension" in question.inner_text()
|
||||
page.get_by_role("button", name="Confirm").click()
|
||||
|
||||
|
||||
def shown(page, text):
|
||||
page.locator("#comfy-dialog").get_by_text(text).wait_for(timeout=5000)
|
||||
|
||||
|
||||
def requested(page):
|
||||
return [(request["method"], request["path"].split("?")[0]) for request in page.evaluate("window.requested")]
|
||||
|
||||
|
||||
def test_the_pack_is_enabled_through_the_queue_and_then_comfyui_restarts(page):
|
||||
ask(page, answers())
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Rebooting...")
|
||||
assert requested(page) == ENABLE + [("POST", REBOOT)]
|
||||
assert page.evaluate("window.requested[0].path") == GETLIST + "?mode=cache&skip_update=true"
|
||||
batch = page.evaluate("window.requested[2].body")
|
||||
# what the Enable button of the Custom Nodes Manager sends for this row
|
||||
assert batch["install"] == [{**PACKS["other-pack"], "channel": "default", "mode": "cache",
|
||||
"ui_id": UI_ID, "skip_post_install": True}]
|
||||
assert set(batch) == {"batch_id", "install"}
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_report_that_arrives_before_the_request_is_answered_is_not_missed(page):
|
||||
ask(page, answers(batch={**ENABLED, "before": True}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Rebooting...")
|
||||
assert requested(page)[-1] == ("POST", REBOOT)
|
||||
|
||||
|
||||
def test_the_restart_is_announced_when_the_server_restarts_without_answering(page):
|
||||
ask(page, answers(reboot={"fails": True}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Rebooting...")
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_refused_restart_is_reported(page):
|
||||
ask(page, answers(reboot={"status": 403}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "This action is not allowed with this security level configuration.")
|
||||
assert requested(page)[-1] == ("POST", REBOOT)
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch, reason", [
|
||||
({"json": {"failed": ["other-pack"]}}, "The request was refused. Please check the terminal log."),
|
||||
({"status": 500}, "The request was refused (500). Please check the terminal log."),
|
||||
({"json": {"failed": []}, "result": "Cannot resolve install target: 'other-pack@nightly'"},
|
||||
"Cannot resolve install target: 'other-pack@nightly'"),
|
||||
], ids=["refused by the queue", "an error answer", "failed in the queue"])
|
||||
def test_comfyui_does_not_restart_when_the_pack_was_not_enabled(page, batch, reason):
|
||||
ask(page, answers(batch=batch))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, reason)
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch", [{"json": {"failed": []}, "emptied": True}, {**ENABLED, "result": None}],
|
||||
ids=["the queue was emptied", "the batch is reported without the pack"])
|
||||
def test_a_queue_that_finishes_without_the_pack_ends_the_wait(page, batch):
|
||||
ask(page, answers(batch=batch))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, "The queue finished without a result for this node pack.")
|
||||
shown(page, "Please check the node pack in the Custom Nodes Manager.")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_the_wait_ends_when_no_report_reaches_the_page(page):
|
||||
page.clock.install()
|
||||
ask(page, answers(batch={**ENABLED, "silent": True}))
|
||||
confirm(page)
|
||||
shown(page, "Enabling... 'Other Pack'")
|
||||
|
||||
page.clock.fast_forward(59000)
|
||||
assert "Failed to enable" not in page.locator("#comfy-dialog").inner_text()
|
||||
page.clock.fast_forward(2000)
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, "The queue did not report the result.")
|
||||
|
||||
# the batch is run at some later time, as when another tab wakes the queue
|
||||
page.evaluate("""async (ui_id) => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.report({status: 'batch-done', batch_id: window.requested[2].body.batch_id, remaining_batch_count: 1,
|
||||
nodepack_result: {[ui_id]: 'success'}});
|
||||
}""", UI_ID)
|
||||
page.clock.fast_forward(1000)
|
||||
assert requested(page) == ENABLE
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_queue_that_is_running_is_left_alone(page):
|
||||
ask(page, answers(status={"json": {"is_processing": True}}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, "There are already tasks in progress. Please try again after it is completed.")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE[:2]
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_comfyui_does_not_restart_while_other_work_is_queued_behind_the_pack(page):
|
||||
ask(page, answers(batch={**ENABLED, "remaining": 2}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "'Other Pack' is enabled.")
|
||||
shown(page, "Other tasks are still in progress. Please restart ComfyUI after they are completed.")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("packs", [
|
||||
{**PACKS, "other-pack": {**PACKS["other-pack"], "state": "enabled"}},
|
||||
{**PACKS, "other-pack": {**PACKS["other-pack"], "state": "not-installed"}},
|
||||
{key: pack for key, pack in PACKS.items() if key != "other-pack"},
|
||||
], ids=["listed as enabled", "listed as not installed", "not listed"])
|
||||
def test_a_pack_that_the_node_list_does_not_have_as_disabled_is_not_queued(page, packs):
|
||||
ask(page, answers(packs=packs))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, "Please enable it in the Custom Nodes Manager.")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE[:1]
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_a_node_list_that_cannot_be_read_is_reported(page):
|
||||
ask(page, answers(getlist={"status": 500}))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to get the custom node list (500).")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == ENABLE[:1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failing, requests", [
|
||||
({"getlist": {"fails": True}}, ENABLE[:1]),
|
||||
({"status": {"fails": True}}, ENABLE[:2]),
|
||||
({"batch": {"fails": True}}, ENABLE),
|
||||
], ids=["the node list", "the queue status", "the batch request"])
|
||||
def test_a_request_that_gets_no_answer_is_reported(page, failing, requests):
|
||||
ask(page, answers(**failing))
|
||||
confirm(page)
|
||||
|
||||
shown(page, "Failed to enable 'Other Pack'.")
|
||||
shown(page, "Failed to fetch")
|
||||
page.wait_for_timeout(300)
|
||||
assert requested(page) == requests
|
||||
assert page.errors == []
|
||||
|
||||
|
||||
def test_text_from_the_node_list_and_the_queue_is_shown_as_text(page):
|
||||
markup = '<img src="/bad.png" onerror="window.__probe=1">'
|
||||
target = {**TARGET, "title": "Other " + markup}
|
||||
ask(page, answers(batch={"json": {"failed": []}, "result": "failed " + markup}), target)
|
||||
page.get_by_text("Would you like to enable it and reboot?").wait_for()
|
||||
page.get_by_role("button", name="Confirm").click()
|
||||
|
||||
shown(page, "failed " + markup)
|
||||
assert "Failed to enable 'Other " + markup + "'." in page.locator("#comfy-dialog").inner_text()
|
||||
assert page.locator("#comfy-dialog img").count() == 0
|
||||
assert page.evaluate("window.__probe === undefined")
|
||||
|
||||
|
||||
def test_nothing_is_requested_when_the_user_declines(page):
|
||||
ask(page, answers())
|
||||
page.get_by_text("Would you like to enable it and reboot?").wait_for()
|
||||
page.get_by_role("button", name="Cancel").click()
|
||||
|
||||
page.wait_for_timeout(500)
|
||||
assert requested(page) == []
|
||||
assert page.locator("#comfy-dialog").inner_text() == ""
|
||||
|
||||
|
||||
def test_a_pack_that_is_installed_but_did_not_load_is_only_reported(page):
|
||||
alerts = []
|
||||
page.on("dialog", lambda dialog: (alerts.append(dialog.message), dialog.dismiss()))
|
||||
|
||||
ask(page, answers(), {**TARGET, "installed": "True"})
|
||||
|
||||
page.wait_for_timeout(500)
|
||||
assert len(alerts) == 1
|
||||
assert "it seems that the extension is in an import-fail state" in alerts[0]
|
||||
assert requested(page) == []
|
||||
|
||||
|
||||
def lift(name):
|
||||
"""A function of comfyui-manager.js, as it is written there."""
|
||||
source = (JS / "comfyui-manager.js").read_text(encoding="utf-8")
|
||||
start = source.index(f"async function {name}(")
|
||||
return source[start:source.index("\n}\n", start) + 3]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["in_progress", "all-done"])
|
||||
def test_a_queue_report_before_the_manager_menu_exists_is_ignored(browser, status): # noqa: F811
|
||||
"""A queue started from this handler reports to the menu's listener, whose buttons the menu creates."""
|
||||
page = browser.new_page()
|
||||
errors = []
|
||||
page.on("pageerror", lambda error: errors.append(str(error)))
|
||||
page.add_script_tag(content="""
|
||||
var update_all_button = null, update_comfyui_button = null, switch_comfyui_button = null;
|
||||
var restart_stop_button = null, batch_id = null;
|
||||
""" + lift("reset_action_buttons") + lift("onQueueStatus"))
|
||||
|
||||
page.evaluate("event => onQueueStatus(event)", {"detail": {"status": status, "done_count": 0, "total_count": 1}})
|
||||
page.wait_for_timeout(100)
|
||||
|
||||
assert errors == []
|
||||
page.close()
|
||||
@@ -0,0 +1,85 @@
|
||||
import asyncio
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
import typer
|
||||
from rich.console import Console
|
||||
from typing_extensions import Annotated, List
|
||||
|
||||
from legacy_html_testutil import ROOT, load_functions
|
||||
from test_snapshot_restore_pins import core, manager # noqa: F401
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cm_cli(manager, tmp_path): # noqa: F811
|
||||
for name in ('enabled-pack', '.disabled/registry-pack@1_0_0', '.disabled/rc-pack@1_0_0-rc1', '.disabled/git-pack'):
|
||||
(tmp_path / name).mkdir(parents=True)
|
||||
manager.active_nodes['enabled-pack'] = ('2.0.0', str(tmp_path / 'enabled-pack'))
|
||||
manager.cnr_inactive_nodes['registry-pack'] = {'1.0.0': str(tmp_path / '.disabled/registry-pack@1_0_0')}
|
||||
manager.cnr_inactive_nodes['rc-pack'] = {'1.0.0-rc1': str(tmp_path / '.disabled/rc-pack@1_0_0-rc1')}
|
||||
manager.unknown_inactive_nodes['git-pack'] = ('https://github.com/owner/git-pack', str(tmp_path / '.disabled/git-pack'))
|
||||
out = io.StringIO()
|
||||
|
||||
def cm_cli(*names):
|
||||
return load_functions(ROOT / 'cm_cli/__main__.py', set(names), {
|
||||
'app': SimpleNamespace(command=lambda *args, **kwargs: lambda function: function),
|
||||
'typer': typer, 'Annotated': Annotated, 'List': List, 'asyncio': asyncio, 'sys': sys, 'traceback': traceback,
|
||||
'print': Console(file=out, width=1000, color_system=None).print, 'NodeInstallError': type('NodeInstallError', (Exception,), {}),
|
||||
'cmd_ctx': Mock(no_deps=False), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock(),
|
||||
})
|
||||
|
||||
cm_cli.said = lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if 'pack' in line]
|
||||
cm_cli.folders = lambda: (sorted(os.listdir(tmp_path)), sorted(os.listdir(tmp_path / '.disabled')))
|
||||
return cm_cli
|
||||
|
||||
|
||||
def all_of(cm_cli, name):
|
||||
cm_cli(name, 'for_each_nodes', 'get_all_installed_node_specs', 'enable_node', 'disable_node')[name](['all'], None, None, None)
|
||||
return [line.split('=>')[-1].strip() for line in cm_cli.said()], *cm_cli.folders()
|
||||
|
||||
|
||||
def test_enable_all_enables_every_disabled_nodepack(cm_cli):
|
||||
said, enabled, disabled = all_of(cm_cli, 'enable')
|
||||
|
||||
assert enabled == ['.disabled', 'enabled-pack', 'git-pack', 'rc-pack', 'registry-pack']
|
||||
assert disabled == []
|
||||
assert said[0] == 'Already enabled'
|
||||
|
||||
|
||||
def test_disable_all_disables_every_enabled_nodepack_and_leaves_the_disabled_ones(cm_cli):
|
||||
said, enabled, disabled = all_of(cm_cli, 'disable')
|
||||
|
||||
assert enabled == ['.disabled']
|
||||
assert disabled == ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1', 'registry-pack@1_0_0']
|
||||
assert said[1:] == ['Already disabled', 'Already disabled', 'Already disabled']
|
||||
|
||||
|
||||
def test_latest_names_the_installed_nodepack_as_a_bare_id_does(cm_cli, manager, core, monkeypatch): # noqa: F811
|
||||
for name, latest in (('enabled-pack', '3.0.0'), ('registry-pack', '1.5.0')):
|
||||
manager.cnr_map[name] = {'id': name, 'latest_version': {'version': latest}}
|
||||
monkeypatch.setattr(manager, 'unified_update', lambda node_id, version_spec=None, **kwargs: core.ManagedResult('update').with_target('3.0.0'))
|
||||
monkeypatch.setattr(manager, 'unified_fix', lambda node_id, version_spec, **kwargs: core.ManagedResult('fix'))
|
||||
acts = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
|
||||
|
||||
for act, name in (('update_node', 'enabled-pack'), ('fix_node', 'enabled-pack'), ('disable_node', 'enabled-pack'), ('enable_node', 'registry-pack')):
|
||||
acts[act](name + '@latest')
|
||||
|
||||
assert cm_cli.said() == ['[ UPDATED ]: enabled-pack => (2.0.0 -> 3.0.0)', '[ FIXING ]: enabled-pack [2.0.0]', '[DISABLED] enabled-pack',
|
||||
'[ENABLED] registry-pack']
|
||||
assert cm_cli.folders() == (['.disabled', 'registry-pack'], ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1'])
|
||||
|
||||
|
||||
def test_a_registry_nodepack_that_is_not_installed_is_not_called_disabled(cm_cli, manager): # noqa: F811
|
||||
manager.cnr_map['absent-pack'] = {'id': 'absent-pack', 'latest_version': {'version': '1.0.0'}}
|
||||
acts = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
|
||||
|
||||
for name in ('absent-pack', 'absent-pack@latest'):
|
||||
for act in ('update_node', 'fix_node', 'disable_node', 'enable_node'):
|
||||
acts[act](name)
|
||||
|
||||
assert [line.split('=>')[-1].strip() for line in cm_cli.said()] == ['Not installed', 'Not installed', 'Not found', 'Not found'] * 2
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user