Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
f764cc0e54 | ||
|
|
69bc3ef1c6 | ||
|
|
4ad94b2048 | ||
|
|
a0d89e9a56 |
@@ -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
|
||||
|
||||
|
||||
+223
@@ -7,6 +7,227 @@ and this project adheres to [Semantic Versioning 2.0.0](https://semver.org/spec/
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
|
||||
- Prevent HTML and URL injection in the legacy Manager UI while preserving
|
||||
supported formatting and links.
|
||||
- Require loopback-only listeners or `allow_flagged_nodepack_install = true`
|
||||
to install Flagged CNR versions through either Manager API. This requirement
|
||||
is additional to the existing installation security checks.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Preserve administrator settings when saving configuration from the Manager UI.
|
||||
- Clear legacy install progress state when batch submission fails.
|
||||
- Attribute multiline uv dependency conflicts to the affected nodepacks while
|
||||
filtering unrelated stderr output.
|
||||
|
||||
## [4.2.2] - 2026-06-15
|
||||
|
||||
### Security
|
||||
@@ -173,5 +394,7 @@ programmatic clients.
|
||||
perform the change from a trusted entry point. Read access via `GET` is
|
||||
unaffected.
|
||||
|
||||
[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
|
||||
|
||||
@@ -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`
|
||||
@@ -216,6 +218,7 @@ The following settings are applied based on the section marked as `is_default`.
|
||||
security_level = <Set the security level => strong|normal|normal-|weak>
|
||||
allow_git_url_install = <Allow installing custom nodes from arbitrary git URLs. Independent of security_level. Default: False>
|
||||
allow_pip_install = <Allow installing arbitrary pip packages via the Manager. Independent of security_level. Default: False>
|
||||
allow_flagged_nodepack_install = <Allow flagged CNR versions on non-local listeners in trusted private networks. Default: False>
|
||||
always_lazy_install = <Whether to perform dependency installation on restart even in environments other than Windows.>
|
||||
network_mode = <Set the network mode => public|private|offline|personal_cloud>
|
||||
```
|
||||
@@ -251,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.
|
||||
@@ -328,8 +332,8 @@ The security settings are applied based on whether the ComfyUI server's listener
|
||||
|-------------|---------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| high+ | * **Switch ComfyUI version**<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 nodepack registered in the `default channel`.<BR>* Restore/Remove Snapshot<BR>* Install model |
|
||||
| middle | * Restart |
|
||||
| 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) |
|
||||
| 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.
|
||||
@@ -359,6 +363,93 @@ The `Install via git url` and `pip install` features are governed by two dedicat
|
||||
* Changes to these flags require a restart of ComfyUI to take effect.
|
||||
* Migration note: if you previously relied on `security_level = weak` or `normal-` to use these features, you must now opt in explicitly by setting the flags in the `[default]` section of `config.ini`. The flags are not auto-seeded from your `security_level`.
|
||||
|
||||
### Flagged CNR nodepacks
|
||||
|
||||
Before downloading a CNR release, Manager checks the selected version's `status`
|
||||
in the existing `/nodes/{id}/install` response. No additional Registry request is
|
||||
needed. The check applies to both the default and legacy Manager implementations,
|
||||
including CNR version changes, updates, and snapshot restores. Legacy batch
|
||||
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, the pack whitelist,
|
||||
and restart instructions.
|
||||
|
||||
* 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 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:
|
||||
|
||||
```ini
|
||||
[default]
|
||||
allow_flagged_nodepack_install = true
|
||||
```
|
||||
|
||||
* The option defaults to `false`. Only `true` (case-insensitive) enables it;
|
||||
missing or invalid values are treated as `false`. Restart ComfyUI after editing it.
|
||||
* With this option enabled, the flagged-version check allows installation
|
||||
regardless of the listen address. Manager does not automatically detect a
|
||||
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. 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,
|
||||
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, 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, 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.
|
||||
|
||||
|
||||
# Disclaimer
|
||||
|
||||
|
||||
+2
-3
@@ -1541,9 +1541,8 @@ 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:
|
||||
|
||||
@@ -134,6 +134,7 @@ class NodeVersion:
|
||||
id: str
|
||||
version: str
|
||||
download_url: str
|
||||
status: str = ''
|
||||
|
||||
|
||||
def map_node_version(api_node_version):
|
||||
@@ -165,6 +166,7 @@ def map_node_version(api_node_version):
|
||||
download_url=api_node_version.get(
|
||||
"downloadUrl", ""
|
||||
), # Provide a default value if 'downloadUrl' is missing
|
||||
status=api_node_version.get('status', ''),
|
||||
)
|
||||
|
||||
|
||||
@@ -257,4 +259,3 @@ def read_cnr_id(fullpath):
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Shared settings-file writer for glob and legacy."""
|
||||
import configparser
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from rich import print
|
||||
|
||||
|
||||
class DirtyTrackingConfig(dict):
|
||||
"""Track keys assigned after loading the startup configuration."""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.dirty_keys = set()
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self.dirty_keys.add(key)
|
||||
super().__setitem__(key, value)
|
||||
|
||||
def update(self, *args, **kwargs):
|
||||
incoming = dict(*args, **kwargs)
|
||||
self.dirty_keys.update(incoming)
|
||||
super().update(incoming)
|
||||
|
||||
|
||||
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)
|
||||
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)
|
||||
else:
|
||||
# ConfigParser.read silently skips unreadable files; do not overwrite one.
|
||||
if not loaded and os.path.exists(config_path):
|
||||
raise OSError(f"'{config_path}' exists but could not be read; refusing to overwrite it with default settings. Fix the file's permissions, then retry.")
|
||||
|
||||
if config.has_section('default'):
|
||||
keys = [key for key in written_config_keys if key in cached.dirty_keys]
|
||||
else:
|
||||
config['default'] = {}
|
||||
keys = list(written_config_keys)
|
||||
|
||||
section = config['default']
|
||||
for key in keys:
|
||||
section[key] = str(cached[key]).replace('\r', '').replace('\n', '').replace('\x00', '')
|
||||
|
||||
directory = os.path.dirname(config_path)
|
||||
if directory and not os.path.exists(directory):
|
||||
os.makedirs(directory)
|
||||
|
||||
# Replace from the same directory so readers never see a partial write.
|
||||
tmp_path = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
'w', dir=directory or '.', prefix='.config-', suffix='.tmp', delete=False
|
||||
) as configfile:
|
||||
tmp_path = configfile.name
|
||||
config.write(configfile)
|
||||
configfile.flush()
|
||||
os.fsync(configfile.fileno())
|
||||
# Retain the existing mode instead of the temporary file's 0600.
|
||||
if os.path.exists(config_path):
|
||||
os.chmod(tmp_path, os.stat(config_path).st_mode & 0o777)
|
||||
os.replace(tmp_path, config_path)
|
||||
tmp_path = None
|
||||
finally:
|
||||
if tmp_path is not None and os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
|
||||
# Clear only persisted keys, and only after a successful write.
|
||||
cached.dirty_keys.difference_update(keys)
|
||||
@@ -26,7 +26,8 @@ def get_commit_hash(fullpath):
|
||||
else:
|
||||
return "unknown"
|
||||
else:
|
||||
return line
|
||||
# Detached HEAD: the file holds the commit hash and a newline.
|
||||
return line.strip()
|
||||
|
||||
return "unknown"
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ 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).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
@@ -27,6 +28,27 @@ 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.'
|
||||
)
|
||||
FLAGGED_NODEPACK_INSTALL_GUIDANCE = (
|
||||
'Installation of this flagged CNR version is blocked. To satisfy the additional '
|
||||
'flagged-version requirement, choose one of the following:\n'
|
||||
'1. Run ComfyUI with loopback-only listeners, for example --listen 127.0.0.1 '
|
||||
'or --listen ::1. All configured listen addresses must be loopback.\n'
|
||||
' 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'
|
||||
'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
|
||||
@@ -83,6 +105,85 @@ def is_loopback(address):
|
||||
return False
|
||||
|
||||
|
||||
def is_loopback_listener(listen_address: Optional[str]) -> bool:
|
||||
"""All addresses bound by --listen must resolve exclusively to loopback."""
|
||||
import socket
|
||||
|
||||
if not isinstance(listen_address, str) or not listen_address:
|
||||
return False
|
||||
for address in listen_address.split(','):
|
||||
address = address.strip()
|
||||
if not address:
|
||||
return False
|
||||
if is_loopback(address):
|
||||
continue
|
||||
try:
|
||||
resolved = socket.getaddrinfo(address, None, type=socket.SOCK_STREAM)
|
||||
except OSError:
|
||||
return False
|
||||
if not resolved or any(not is_loopback(item[4][0]) for item in resolved):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
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:
|
||||
"""P-direct predicate for the dedicated install flags (goal265-spec.md §1.2).
|
||||
|
||||
|
||||
@@ -17,6 +17,10 @@ import shlex
|
||||
import time
|
||||
from functools import lru_cache
|
||||
|
||||
from packaging.requirements import InvalidRequirement, Requirement
|
||||
from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet
|
||||
from packaging.version import InvalidVersion, Version
|
||||
|
||||
|
||||
cache_lock = threading.Lock()
|
||||
session_lock = threading.Lock()
|
||||
@@ -114,17 +118,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,9 +179,10 @@ 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
|
||||
|
||||
@@ -206,6 +210,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 +237,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 +300,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 +323,269 @@ def extract_package_as_zip(file_path, extract_path):
|
||||
return None
|
||||
|
||||
|
||||
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_MALFORMED_PATTERN = re.compile(r'([A-Za-z0-9][A-Za-z0-9._-]*)\s*(\[[^\]]*\]\s*)?[<>=!~(]')
|
||||
|
||||
|
||||
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.
|
||||
|
||||
Returns (None, False, []) when the line does not name a package: URLs, 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:
|
||||
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 _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 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 +604,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 +649,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
|
||||
@@ -411,6 +710,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)
|
||||
|
||||
@@ -437,33 +745,35 @@ class PIPFixer:
|
||||
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 +816,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 +873,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 = []
|
||||
@@ -597,7 +924,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 +933,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,7 +944,7 @@ 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', x]))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -628,11 +955,11 @@ def restore_pip_snapshot(pips, 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', x]))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if res != 0:
|
||||
failed.append(x)
|
||||
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
print(f"Installation failed for pip packages: {failed}")
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Installation-denial messages shared by the glob and legacy servers."""
|
||||
|
||||
SECURITY_MESSAGE_MIDDLE = "ERROR: To use this action, a security_level of `normal or below` is required. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_MIDDLE_P = "ERROR: To use this action, security_level must be `normal or below`, and network_mode must be set to `personal_cloud`. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_HIGH_P = "ERROR: To use this action, '--listen' must be set to a local IP and security_level must be 'normal-' or lower. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
|
||||
@@ -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
|
||||
@@ -656,10 +644,15 @@ class UnifiedDepResolver:
|
||||
def _parse_conflicts(stderr: str) -> list[str]:
|
||||
"""Extract conflict descriptions from ``uv pip compile`` stderr."""
|
||||
conflicts: list[str] = []
|
||||
for line in stderr.splitlines():
|
||||
line = line.strip()
|
||||
if line and ('conflict' in line.lower() or 'error' in line.lower()):
|
||||
in_diagnostic = False
|
||||
for raw_line in stderr.splitlines():
|
||||
line = raw_line.strip()
|
||||
if line and ('conflict' in line.lower() or 'error' in line.lower()
|
||||
or (in_diagnostic and raw_line[0].isspace())):
|
||||
conflicts.append(line)
|
||||
in_diagnostic = True
|
||||
else:
|
||||
in_diagnostic = False
|
||||
return conflicts or [stderr.strip()] if stderr.strip() else []
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
|
||||
SECURITY_MESSAGE_MIDDLE = "ERROR: To use this action, a security_level of `normal or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_MIDDLE_P = "ERROR: To use this action, security_level must be `normal or below`, and network_mode must be set to `personal_cloud`. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_HIGH_P = "ERROR: To use this action, '--listen' must be set to a local IP and security_level must be 'normal-' or lower. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
|
||||
|
||||
|
||||
def is_loopback(address):
|
||||
import ipaddress
|
||||
|
||||
|
||||
@@ -35,8 +35,10 @@ from packaging import version
|
||||
import uuid
|
||||
|
||||
from ..common import cm_global
|
||||
from ..common.config_writer import DirtyTrackingConfig, write_config_merged
|
||||
from ..common import cnr_utils
|
||||
from ..common import manager_util
|
||||
from ..common import manager_security
|
||||
from ..common import git_utils
|
||||
from ..common import manager_downloader
|
||||
from ..common.node_package import InstalledNodePackage
|
||||
@@ -182,80 +184,7 @@ def remap_pip_package(pkg):
|
||||
|
||||
|
||||
def is_blacklisted(name):
|
||||
name = name.strip()
|
||||
|
||||
pattern = r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
|
||||
match = re.search(pattern, name)
|
||||
|
||||
if match:
|
||||
name = match.group(1)
|
||||
|
||||
if name in cm_global.pip_blacklist:
|
||||
return True
|
||||
|
||||
if name in cm_global.pip_downgrade_blacklist:
|
||||
pips = manager_util.get_installed_packages()
|
||||
|
||||
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)):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def is_installed(name):
|
||||
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:
|
||||
return True
|
||||
|
||||
if name in cm_global.pip_downgrade_blacklist:
|
||||
pips = manager_util.get_installed_packages()
|
||||
|
||||
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
|
||||
|
||||
pkg = manager_util.get_installed_packages().get(name.lower())
|
||||
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
|
||||
|
||||
return name.lower() in manager_util.get_installed_packages()
|
||||
return manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist) is not None
|
||||
|
||||
|
||||
def normalize_channel(channel):
|
||||
@@ -880,10 +809,10 @@ class UnifiedManager:
|
||||
|
||||
return res
|
||||
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps):
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps, status=''):
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable]
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable, status]
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
print(f"Installation reserved: {target}")
|
||||
@@ -909,35 +838,46 @@ class UnifiedManager:
|
||||
|
||||
return result
|
||||
|
||||
def _get_cnr_install_info(self, node_id, version_spec):
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
if (node_info is not None and node_info.status == 'NodeVersionStatusFlagged'
|
||||
and not manager_funcs.is_flagged_install_allowed(node_id)):
|
||||
logging.error(manager_security.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
|
||||
raise PermissionError(manager_security.FLAGGED_NODEPACK_INSTALL_ERROR)
|
||||
return node_info
|
||||
|
||||
def cnr_switch_version(self, node_id, version_spec=None, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
if instant_execution:
|
||||
return self.cnr_switch_version_instant(node_id, version_spec, instant_execution, no_deps, return_postinstall)
|
||||
else:
|
||||
return self.cnr_switch_version_lazy(node_id, version_spec, no_deps, return_postinstall)
|
||||
|
||||
def cnr_switch_version_lazy(self, node_id, version_spec=None, no_deps=False, return_postinstall=False):
|
||||
"""
|
||||
switch between cnr version (lazy mode)
|
||||
"""
|
||||
|
||||
result = ManagedResult('switch-cnr')
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return result.fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
version_spec = node_info.version
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
if self.active_nodes[node_id][0] == version_spec:
|
||||
def _cnr_switch_version(self, node_id, node_info, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
"""Execute a switch using the checked CNR response."""
|
||||
if self.active_nodes[node_id][0] == node_info.version:
|
||||
return ManagedResult('skip').with_msg("Up to date")
|
||||
|
||||
if instant_execution:
|
||||
return self._cnr_switch_version_instant(node_id, node_info, no_deps, return_postinstall)
|
||||
return self._cnr_switch_version_lazy(node_id, node_info, no_deps, return_postinstall)
|
||||
|
||||
def _cnr_switch_version_lazy(self, node_id, node_info, no_deps=False, return_postinstall=False):
|
||||
"""Reserve a switch using the validated install response."""
|
||||
result = ManagedResult('switch-cnr')
|
||||
version_spec = node_info.version
|
||||
zip_url = node_info.download_url
|
||||
from_path = self.active_nodes[node_id][1]
|
||||
target = node_id
|
||||
to_path = os.path.join(get_default_custom_nodes_path(), target)
|
||||
|
||||
def postinstall():
|
||||
return self.reserve_cnr_switch(target, zip_url, from_path, to_path, no_deps)
|
||||
return self.reserve_cnr_switch(target, zip_url, from_path, to_path, no_deps, node_info.status)
|
||||
|
||||
if return_postinstall:
|
||||
return result.with_postinstall(postinstall)
|
||||
@@ -947,23 +887,12 @@ class UnifiedManager:
|
||||
|
||||
return result
|
||||
|
||||
def cnr_switch_version_instant(self, node_id, version_spec=None, instant_execution=True, no_deps=False, return_postinstall=False):
|
||||
"""
|
||||
switch between cnr version
|
||||
"""
|
||||
|
||||
# 1. download
|
||||
def _cnr_switch_version_instant(self, node_id, node_info, no_deps=False, return_postinstall=False):
|
||||
"""Apply a switch using the validated install response."""
|
||||
result = ManagedResult('switch-cnr')
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
version_spec = node_info.version
|
||||
|
||||
if self.active_nodes[node_id][0] == version_spec:
|
||||
return ManagedResult('skip').with_msg("Up to date")
|
||||
|
||||
# 1. download
|
||||
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
@@ -1008,7 +937,7 @@ class UnifiedManager:
|
||||
result.target = version_spec
|
||||
|
||||
def postinstall():
|
||||
res = self.execute_install_script(f"{node_id}@{version_spec}", install_path, instant_execution=instant_execution, no_deps=no_deps)
|
||||
res = self.execute_install_script(f"{node_id}@{version_spec}", install_path, instant_execution=True, no_deps=no_deps)
|
||||
return res
|
||||
|
||||
if return_postinstall:
|
||||
@@ -1289,10 +1218,24 @@ class UnifiedManager:
|
||||
if 'comfyui-manager' in node_id.lower():
|
||||
return result.fail(f"ignored: installing '{node_id}'")
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return result.fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
result = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
# Keep the requested version in the public result.
|
||||
if result.target is not None:
|
||||
result.target = version_spec
|
||||
return result
|
||||
|
||||
def _cnr_install(self, node_id, node_info, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
"""Install using the checked CNR response."""
|
||||
result = ManagedResult('install-cnr')
|
||||
version_spec = node_info.version
|
||||
|
||||
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
|
||||
@@ -1307,12 +1250,28 @@ class UnifiedManager:
|
||||
|
||||
manager_downloader.download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
os.makedirs(install_path, exist_ok=True)
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
except Exception as e:
|
||||
# Left in place, the new directory makes the next install fail with 'Install path already exists'.
|
||||
# A cleanup that fails as well is logged: the extraction error is the one to report.
|
||||
try:
|
||||
try_rmtree(node_id, install_path)
|
||||
except Exception as cleanup_error:
|
||||
logging.warning(f"[ComfyUI-Manager] Failed to clean up '{install_path}': {cleanup_error}")
|
||||
return result.fail(f'Failed to extract archive: {node_id}@{version_spec}: {e}')
|
||||
finally:
|
||||
try:
|
||||
os.remove(download_path)
|
||||
except OSError:
|
||||
pass
|
||||
result.to_path = install_path
|
||||
|
||||
if extracted is None:
|
||||
shutil.rmtree(install_path)
|
||||
try:
|
||||
try_rmtree(node_id, install_path)
|
||||
except Exception as cleanup_error:
|
||||
logging.warning(f"[ComfyUI-Manager] Failed to clean up '{install_path}': {cleanup_error}")
|
||||
return result.fail(f'Empty archive file: {node_id}@{version_spec}')
|
||||
|
||||
# create .tracking file
|
||||
@@ -1538,6 +1497,14 @@ class UnifiedManager:
|
||||
|
||||
return res.with_target(version_spec)
|
||||
|
||||
# Check before changing the existing pack, then reuse this response.
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return ManagedResult('install-cnr').fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return ManagedResult('install-cnr').fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
if self.is_enabled(node_id, 'nightly'):
|
||||
# disable nightly nodes
|
||||
self.unified_disable(node_id, False) # NOTE: don't return from here
|
||||
@@ -1549,12 +1516,12 @@ class UnifiedManager:
|
||||
if self.is_disabled(node_id, "cnr"):
|
||||
# enable and switch version if cnr is disabled (not specified version)
|
||||
self.unified_enable(node_id, "cnr")
|
||||
return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
if self.is_enabled(node_id, "cnr"):
|
||||
return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
res = self.cnr_install(node_id, version_spec, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
res = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
if res.result:
|
||||
self.active_nodes[node_id] = version_spec, res.to_path
|
||||
|
||||
@@ -1673,6 +1640,14 @@ class ManagerFuncs:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def is_flagged_install_allowed(self, node_id):
|
||||
# Restore children use the parent's permission and whitelist directory,
|
||||
# even if the CLI resolves a different user directory.
|
||||
return manager_security.is_cnr_install_allowed(
|
||||
'NodeVersionStatusFlagged', os.environ.get('_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED', 'true') == 'true',
|
||||
listen_address=None, node_id=node_id,
|
||||
manager_files_path=os.environ.get('_COMFYUI_MANAGER_CNR_WHITELIST_DIR'))
|
||||
|
||||
def run_script(self, cmd, cwd='.'):
|
||||
if len(cmd) > 0 and cmd[0].startswith("#"):
|
||||
print(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
|
||||
@@ -1686,41 +1661,33 @@ class ManagerFuncs:
|
||||
manager_funcs = ManagerFuncs()
|
||||
|
||||
|
||||
# Settings owned by this server; other keys and sections are preserved.
|
||||
WRITTEN_CONFIG_KEYS = (
|
||||
'git_exe',
|
||||
'use_uv',
|
||||
'use_unified_resolver',
|
||||
'channel_url',
|
||||
'share_option',
|
||||
'bypass_ssl',
|
||||
'file_logging',
|
||||
'update_policy',
|
||||
'windows_selector_event_loop_policy',
|
||||
'model_download_by_agent',
|
||||
'downgrade_blacklist',
|
||||
'security_level',
|
||||
'always_lazy_install',
|
||||
'network_mode',
|
||||
'db_mode',
|
||||
'verbose',
|
||||
'allow_git_url_install',
|
||||
'allow_pip_install',
|
||||
'allow_flagged_nodepack_install',
|
||||
)
|
||||
|
||||
|
||||
def write_config():
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
|
||||
config['default'] = {
|
||||
'git_exe': get_config()['git_exe'],
|
||||
'use_uv': get_config()['use_uv'],
|
||||
'use_unified_resolver': get_config()['use_unified_resolver'],
|
||||
'channel_url': get_config()['channel_url'],
|
||||
'share_option': get_config()['share_option'],
|
||||
'bypass_ssl': get_config()['bypass_ssl'],
|
||||
"file_logging": get_config()['file_logging'],
|
||||
'update_policy': get_config()['update_policy'],
|
||||
'windows_selector_event_loop_policy': get_config()['windows_selector_event_loop_policy'],
|
||||
'model_download_by_agent': get_config()['model_download_by_agent'],
|
||||
'downgrade_blacklist': get_config()['downgrade_blacklist'],
|
||||
'security_level': get_config()['security_level'],
|
||||
'always_lazy_install': get_config()['always_lazy_install'],
|
||||
'network_mode': get_config()['network_mode'],
|
||||
'db_mode': get_config()['db_mode'],
|
||||
'verbose': get_config()['verbose'],
|
||||
'allow_git_url_install': get_config()['allow_git_url_install'],
|
||||
'allow_pip_install': get_config()['allow_pip_install'],
|
||||
}
|
||||
|
||||
# Sanitize all string values to prevent CRLF injection attacks
|
||||
for key, value in config['default'].items():
|
||||
if isinstance(value, str):
|
||||
config['default'][key] = value.replace('\r', '').replace('\n', '').replace('\x00', '')
|
||||
|
||||
directory = os.path.dirname(context.manager_config_path)
|
||||
if not os.path.exists(directory):
|
||||
os.makedirs(directory)
|
||||
|
||||
with open(context.manager_config_path, 'w') as configfile:
|
||||
config.write(configfile)
|
||||
"""Persist changed settings through the shared writer."""
|
||||
write_config_merged(context.manager_config_path, get_config(), WRITTEN_CONFIG_KEYS)
|
||||
|
||||
|
||||
def read_config():
|
||||
@@ -1759,6 +1726,7 @@ def read_config():
|
||||
'verbose': get_bool('verbose', False),
|
||||
'allow_git_url_install': get_bool('allow_git_url_install', False),
|
||||
'allow_pip_install': get_bool('allow_pip_install', False),
|
||||
'allow_flagged_nodepack_install': get_bool('allow_flagged_nodepack_install', False),
|
||||
}
|
||||
|
||||
except Exception:
|
||||
@@ -1789,6 +1757,7 @@ def read_config():
|
||||
'verbose': False,
|
||||
'allow_git_url_install': False,
|
||||
'allow_pip_install': False,
|
||||
'allow_flagged_nodepack_install': False,
|
||||
}
|
||||
|
||||
|
||||
@@ -1796,7 +1765,8 @@ def get_config():
|
||||
global cached_config
|
||||
|
||||
if cached_config is None:
|
||||
cached_config = read_config()
|
||||
# Start tracking changes after the startup configuration is loaded.
|
||||
cached_config = DirtyTrackingConfig(read_config())
|
||||
if cached_config['http_channel_enabled']:
|
||||
print("[ComfyUI-Manager] Warning: http channel enabled, make sure server in secure env")
|
||||
|
||||
@@ -1907,14 +1877,10 @@ def try_install_script(url, repo_path, install_cmd, instant_execution=False):
|
||||
reserve_script(repo_path, install_cmd)
|
||||
return True
|
||||
else:
|
||||
if len(install_cmd) == 5 and install_cmd[2:4] == ['pip', 'install']:
|
||||
if is_blacklisted(install_cmd[4]):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[4]}'")
|
||||
return True
|
||||
elif len(install_cmd) == 6 and install_cmd[3:5] == ['pip', 'install']: # uv mode
|
||||
if is_blacklisted(install_cmd[5]):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[5]}'")
|
||||
return True
|
||||
requirement = manager_util.pip_install_requirement(install_cmd)
|
||||
if requirement is not None and is_blacklisted(requirement):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{requirement}'")
|
||||
return True
|
||||
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {install_cmd}")
|
||||
code = manager_funcs.run_script(install_cmd, cwd=repo_path)
|
||||
@@ -2357,9 +2323,7 @@ async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
json_obj = await manager_util.get_data(cache_uri)
|
||||
else:
|
||||
json_obj = await manager_util.get_data(uri)
|
||||
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)
|
||||
manager_util.write_cache_file(cache_uri, json_obj)
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] Due to a network error, switching to local mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
|
||||
uri = os.path.join(manager_util.comfyui_manager_path, filename)
|
||||
@@ -3199,7 +3163,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k)
|
||||
else:
|
||||
cnr_ver = cnr_info[k]
|
||||
if v[1] != cnr_ver:
|
||||
if v[0] != cnr_ver:
|
||||
todo_checkout.append((k, cnr_ver))
|
||||
else:
|
||||
skip_node_packs.append(k)
|
||||
@@ -3216,15 +3180,20 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
skip_node_packs.append(f"{x[0]}@{x[1]}")
|
||||
elif not ps.result:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
# install listed cnr nodes
|
||||
# Do not retry processed switches as fresh installs.
|
||||
checked_cnr = {node_id for node_id, _ in todo_checkout}
|
||||
for k, v in cnr_info.items():
|
||||
if 'comfyui-manager' in k:
|
||||
if 'comfyui-manager' in k or k in checked_cnr:
|
||||
continue
|
||||
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
if ps.action == 'install-cnr' and ps.result:
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
elif not ps.result:
|
||||
failed.append(f"{k}@{v}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
if ps is not None and ps.result:
|
||||
if hasattr(ps, 'postinstall'):
|
||||
@@ -3242,6 +3211,10 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k.lower():
|
||||
continue
|
||||
|
||||
# Snapshots saved at a detached HEAD used to keep the newline that follows the hash.
|
||||
if isinstance(v.get('hash'), str):
|
||||
v['hash'] = v['hash'].strip()
|
||||
|
||||
norm_k = git_utils.normalize_url(k)
|
||||
git_info[norm_k] = v
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ from comfyui_manager.glob.utils import (
|
||||
from server import PromptServer
|
||||
|
||||
from . import manager_core as core
|
||||
from ..common import manager_util
|
||||
from ..common import manager_util, manager_security
|
||||
from ..common import cm_global
|
||||
from ..common import manager_downloader
|
||||
from ..common import context
|
||||
@@ -83,11 +83,14 @@ from ..data_models import (
|
||||
ComfyUISwitchVersionParams,
|
||||
)
|
||||
|
||||
from .constants import (
|
||||
model_dir_name_map,
|
||||
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,
|
||||
)
|
||||
|
||||
if not manager_util.is_manager_pip_package():
|
||||
@@ -131,6 +134,11 @@ def error_response(
|
||||
|
||||
|
||||
class ManagerFuncsInComfyUI(core.ManagerFuncs):
|
||||
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("#"):
|
||||
logging.error(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
|
||||
@@ -813,10 +821,6 @@ async def task_worker():
|
||||
await core.unified_manager.reload(ManagerDatabaseSource.cache.value)
|
||||
|
||||
async def do_install(params: InstallPackParams) -> str:
|
||||
if not security_utils.is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return OperationResult.failed.value
|
||||
|
||||
node_id = params.id
|
||||
node_version = params.selected_version
|
||||
channel = params.channel
|
||||
@@ -842,6 +846,11 @@ async def task_worker():
|
||||
return f"Cannot resolve install target: '{node_id}@{node_version}'"
|
||||
|
||||
node_name, version_spec, is_specified = node_spec
|
||||
# CNR versions have their own flagged-status check before download.
|
||||
level = 'middle+' if version_spec in ('nightly', 'unknown') else 'middle'
|
||||
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,
|
||||
@@ -913,7 +922,7 @@ async def task_worker():
|
||||
base_res["msg"] = OperationResult.success.value
|
||||
return base_res
|
||||
|
||||
base_res["msg"] = f"An error occurred while updating '{node_name}'."
|
||||
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})"
|
||||
)
|
||||
@@ -1052,6 +1061,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")
|
||||
|
||||
@@ -2067,17 +2088,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)
|
||||
|
||||
@@ -2130,10 +2143,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}"
|
||||
@@ -2174,4 +2185,3 @@ threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
|
||||
if not os.path.exists(context.manager_config_path):
|
||||
core.get_config()
|
||||
core.write_config()
|
||||
|
||||
|
||||
@@ -4,9 +4,7 @@ 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,49 +20,6 @@ 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()
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/share_option")
|
||||
async def share_option(request):
|
||||
if "value" in request.rel_url.query:
|
||||
@@ -76,17 +31,6 @@ async def share_option(request):
|
||||
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 get_matrix_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
|
||||
return None
|
||||
@@ -105,19 +49,6 @@ 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
|
||||
@@ -134,24 +65,6 @@ def set_youml_settings(settings):
|
||||
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...")
|
||||
@@ -176,32 +89,6 @@ async def api_set_youml_settings(request):
|
||||
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))
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
async def get_matrix_dep_status(request):
|
||||
if matrix_nio_is_available:
|
||||
@@ -218,35 +105,23 @@ def set_matrix_auth(json_data):
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
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 +150,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'
|
||||
@@ -442,9 +258,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
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import locale
|
||||
import sys
|
||||
import re
|
||||
|
||||
|
||||
def handle_stream(stream, prefix):
|
||||
@@ -20,41 +19,3 @@ def handle_stream(stream, prefix):
|
||||
print(prefix, msg, end="", file=sys.stderr)
|
||||
else:
|
||||
print(prefix, msg, end="")
|
||||
|
||||
|
||||
def convert_markdown_to_html(input_text):
|
||||
pattern_a = re.compile(r"\[a/([^]]+)]\(([^)]+)\)")
|
||||
pattern_w = re.compile(r"\[w/([^]]+)]")
|
||||
pattern_i = re.compile(r"\[i/([^]]+)]")
|
||||
pattern_bold = re.compile(r"\*\*([^*]+)\*\*")
|
||||
pattern_white = re.compile(r"%%([^*]+)%%")
|
||||
|
||||
def replace_a(match):
|
||||
return f"<a href='{match.group(2)}' target='blank'>{match.group(1)}</a>"
|
||||
|
||||
def replace_w(match):
|
||||
return f"<p class='cm-warn-note'>{match.group(1)}</p>"
|
||||
|
||||
def replace_i(match):
|
||||
return f"<p class='cm-info-note'>{match.group(1)}</p>"
|
||||
|
||||
def replace_bold(match):
|
||||
return f"<B>{match.group(1)}</B>"
|
||||
|
||||
def replace_white(match):
|
||||
return f"<font color='white'>{match.group(1)}</font>"
|
||||
|
||||
input_text = (
|
||||
input_text.replace("\\[", "[")
|
||||
.replace("\\]", "]")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
)
|
||||
|
||||
result_text = re.sub(pattern_a, replace_a, input_text)
|
||||
result_text = re.sub(pattern_w, replace_w, result_text)
|
||||
result_text = re.sub(pattern_i, replace_i, result_text)
|
||||
result_text = re.sub(pattern_bold, replace_bold, result_text)
|
||||
result_text = re.sub(pattern_white, replace_white, result_text)
|
||||
|
||||
return result_text.replace("\n", "<BR>")
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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' });
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -6,15 +6,13 @@ 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,
|
||||
infoToast, showTerminal, setNeedRestart, generateUUID
|
||||
infoToast, showTerminal, setNeedRestart, generateUUID, sanitizeHTML, sanitizeUrl
|
||||
} from "./common.js";
|
||||
import { CustomNodesManager } from "./custom-nodes-manager.js";
|
||||
import { ModelManager } from "./model-manager.js";
|
||||
@@ -236,6 +234,25 @@ var restart_stop_button = null;
|
||||
var update_policy_combo = null;
|
||||
|
||||
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 +427,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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -659,6 +676,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') {
|
||||
@@ -722,13 +744,14 @@ async function onQueueStatus(event) {
|
||||
msg += "The following custom nodes have been updated:<ul>";
|
||||
for(let x in success_list) {
|
||||
let k = success_list[x];
|
||||
let url = event.detail.nodepack_result[k].url;
|
||||
let title = event.detail.nodepack_result[k].title;
|
||||
// queue results are server-authored and not escaped upstream
|
||||
let url = sanitizeUrl(event.detail.nodepack_result[k].url);
|
||||
let title = sanitizeHTML(String(event.detail.nodepack_result[k].title ?? ''));
|
||||
if(url) {
|
||||
msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
|
||||
msg += `<li><a href='${sanitizeHTML(url)}' target='_blank' rel='noopener noreferrer'>${title}</a></li>`;
|
||||
}
|
||||
else {
|
||||
msg += `<li>${k}</li>`;
|
||||
msg += `<li>${sanitizeHTML(String(k))}</li>`;
|
||||
}
|
||||
}
|
||||
msg += "</ul>";
|
||||
@@ -741,13 +764,13 @@ async function onQueueStatus(event) {
|
||||
msg += '<br>The update for the following custom nodes has failed:<ul>';
|
||||
for(let x in failed_list) {
|
||||
let k = failed_list[x];
|
||||
let url = event.detail.nodepack_result[k].url;
|
||||
let title = event.detail.nodepack_result[k].title;
|
||||
let url = sanitizeUrl(event.detail.nodepack_result[k].url);
|
||||
let title = sanitizeHTML(String(event.detail.nodepack_result[k].title ?? ''));
|
||||
if(url) {
|
||||
msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
|
||||
msg += `<li><a href='${sanitizeHTML(url)}' target='_blank' rel='noopener noreferrer'>${title}</a></li>`;
|
||||
}
|
||||
else {
|
||||
msg += `<li>${k}</li>`;
|
||||
msg += `<li>${sanitizeHTML(String(k))}</li>`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -999,15 +1022,6 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
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'],
|
||||
];
|
||||
for (const option of share_options) {
|
||||
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
|
||||
}
|
||||
@@ -1015,8 +1029,8 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
api.fetchApi('/v2/manager/share_option')
|
||||
.then(response => response.text())
|
||||
.then(data => {
|
||||
share_combo.value = data || 'all';
|
||||
share_option = data || 'all';
|
||||
share_option = to_share_option(data);
|
||||
share_combo.value = share_option;
|
||||
});
|
||||
|
||||
share_combo.addEventListener('change', function (event) {
|
||||
@@ -1148,7 +1162,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
// ...(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 {
|
||||
@@ -1168,7 +1182,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)',
|
||||
@@ -1179,7 +1193,7 @@ class ManagerMenuDialog extends ComfyDialog {
|
||||
})
|
||||
]),
|
||||
$el("div.pysssss-workflow-arrow-2", {
|
||||
id: `comfyworkflows-button-arrow`,
|
||||
id: `workflowgallery-button-arrow`,
|
||||
onclick: this.handleWorkflowGalleryButtonClick
|
||||
})
|
||||
]),
|
||||
@@ -1258,11 +1272,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();
|
||||
@@ -1275,49 +1286,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);
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -1449,11 +1423,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();
|
||||
@@ -1487,11 +1458,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();
|
||||
@@ -1545,13 +1513,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,8 +1,6 @@
|
||||
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 } from "./common.js";
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -519,11 +381,9 @@ export class ShareDialogChooser extends ComfyDialog {
|
||||
export class ShareDialog extends ComfyDialog {
|
||||
static instance = null;
|
||||
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
static cw_sharekey = "";
|
||||
|
||||
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,18 +419,10 @@ 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_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.credits_input = $el("input", {
|
||||
type: "text",
|
||||
placeholder: "This will be used to give credits",
|
||||
@@ -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,7 +634,7 @@ export class ShareDialog extends ComfyDialog {
|
||||
]),
|
||||
]);
|
||||
|
||||
// get the user's existing matrix auth and share key
|
||||
// get the user's existing matrix auth
|
||||
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
|
||||
try {
|
||||
api.fetchApi(`/v2/manager/get_matrix_auth`)
|
||||
@@ -841,23 +652,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
// 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;
|
||||
})
|
||||
.catch(error => {
|
||||
// console.log(error);
|
||||
});
|
||||
} catch (error) {
|
||||
// console.log(error);
|
||||
}
|
||||
|
||||
this.share_button.onclick = async () => {
|
||||
const prompt = await app.graphToPrompt();
|
||||
const nodes = app.graph._nodes;
|
||||
@@ -868,9 +662,6 @@ 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")) {
|
||||
@@ -881,10 +672,6 @@ export class ShareDialog extends ComfyDialog {
|
||||
}
|
||||
}
|
||||
|
||||
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,15 +733,8 @@ export class ShareDialog extends ComfyDialog {
|
||||
|
||||
const response_json = await response.json();
|
||||
|
||||
if (response_json.comfyworkflows.url) {
|
||||
this.final_message.innerHTML = "Your art has been shared: <a href='" + response_json.comfyworkflows.url + "' target='_blank'>" + response_json.comfyworkflows.url + "</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!";
|
||||
}
|
||||
|
||||
this.final_message.style.color = "green";
|
||||
@@ -991,7 +767,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`.
|
||||
@@ -1103,14 +879,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 } 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="${url}" target="_blank">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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import {app} from "../../scripts/app.js";
|
||||
import {api} from "../../scripts/api.js";
|
||||
import {ComfyDialog, $el} from "../../scripts/ui.js";
|
||||
import { customAlert } from "./common.js";
|
||||
import { customAlert, sanitizeHTML, sanitizeUrl } from "./common.js";
|
||||
|
||||
const BASE_URL = "https://youml.com";
|
||||
//const BASE_URL = "http://localhost:3000";
|
||||
@@ -420,7 +420,7 @@ export class YouMLShareDialog extends ComfyDialog {
|
||||
}
|
||||
}
|
||||
this.message.innerHTML = `${messagePrefix} To turn your workflow into an interactive app, ` +
|
||||
`<a href="${recipePageUrl}" target="_blank">visit it on YouML</a>`;
|
||||
`<a href="${sanitizeHTML(sanitizeUrl(recipePageUrl))}" target="_blank" rel="noopener noreferrer">visit it on YouML</a>`;
|
||||
|
||||
this.uploadedImages = [];
|
||||
this.nameInput.value = "";
|
||||
|
||||
@@ -216,7 +216,7 @@ export async function install_pip(packages) {
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
show_message("To use this feature, set <code>allow_pip_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required.");
|
||||
show_message(await install_denial_message(res, 'allow_pip_install'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ export async function install_via_git_url(url, manager_dialog) {
|
||||
});
|
||||
|
||||
if(res.status == 403) {
|
||||
show_message("To use this feature, set <code>allow_git_url_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required.");
|
||||
show_message(await install_denial_message(res, 'allow_git_url_install'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -659,4 +659,54 @@ function initTooltip () {
|
||||
document.body.addEventListener('mouseleave', mouseleaveHandler, true);
|
||||
}
|
||||
|
||||
initTooltip();
|
||||
initTooltip();
|
||||
// Installation flags and network mode take effect after a restart.
|
||||
const INSTALL_DENIAL_RESTART_NOTE = "<BR>Both values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again.";
|
||||
|
||||
export const INSTALL_DENIAL_MESSAGES = {
|
||||
allow_git_url_install: "To use this feature, set <code>allow_git_url_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required." + INSTALL_DENIAL_RESTART_NOTE,
|
||||
allow_pip_install: "To use this feature, set <code>allow_pip_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required." + INSTALL_DENIAL_RESTART_NOTE
|
||||
};
|
||||
|
||||
// Last resort when no entry above applies. Names no flag on purpose.
|
||||
const INSTALL_DENIAL_UNKNOWN_REASON = "This action was refused by the server, and the client could not determine which setting caused it. The server terminal log states the exact condition. Please contact the administrator.";
|
||||
|
||||
// Use the endpoint's flag when the 403 response body is missing or malformed.
|
||||
export async function install_denial_message(res, fallbackReason) {
|
||||
let reason = fallbackReason;
|
||||
try {
|
||||
const data = await res.json();
|
||||
if (typeof data === 'object' && data !== null && typeof data.reason === 'string'
|
||||
&& Object.prototype.hasOwnProperty.call(INSTALL_DENIAL_MESSAGES, data.reason)) {
|
||||
reason = data.reason;
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// absent / non-JSON body: keep the fallback
|
||||
}
|
||||
return INSTALL_DENIAL_MESSAGES[reason] ?? INSTALL_DENIAL_UNKNOWN_REASON;
|
||||
}
|
||||
|
||||
/**
|
||||
* Scheme allow-list for registry-supplied URLs that land in an href.
|
||||
* Returns the URL if it is http(s) or relative, otherwise "". Never throws.
|
||||
*/
|
||||
export function sanitizeUrl(url) {
|
||||
const raw = String(url ?? '').trim();
|
||||
if (!raw) {
|
||||
return '';
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(raw);
|
||||
}
|
||||
catch {
|
||||
// not absolute: keep a scheme-less relative path, drop anything else
|
||||
return /^[a-z][a-z0-9+.\-]*:/i.test(raw) ? '' : raw;
|
||||
}
|
||||
// URL parsing already normalised the scheme (`java\tscript:` collapses).
|
||||
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||||
return raw;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -8,11 +8,13 @@ import {
|
||||
fetchData, md5, icons, show_message, customConfirm, customAlert, customPrompt,
|
||||
sanitizeHTML, infoToast, showTerminal, setNeedRestart,
|
||||
storeColumnWidth, restoreColumnWidth, getTimeAgo, copyText, loadCss,
|
||||
showPopover, hidePopover, generateUUID
|
||||
showPopover, hidePopover, generateUUID, sanitizeUrl
|
||||
} from "./common.js";
|
||||
|
||||
// Registry titles, names and descriptions are server-escaped; other fields are raw.
|
||||
|
||||
// https://cenfun.github.io/turbogrid/api.html
|
||||
import TG from "./turbogrid.esm.js";
|
||||
import ManagerGrid from "./manager-grid.js";
|
||||
|
||||
loadCss("./custom-nodes-manager.css");
|
||||
|
||||
@@ -363,19 +365,20 @@ export class CustomNodesManager {
|
||||
installGroups.enabled = installGroups.enabled.filter(it => it !== "disable" && it !== "uninstall" && it !== "switch");
|
||||
}
|
||||
|
||||
let list = installGroups[action];
|
||||
const list = installGroups[action];
|
||||
|
||||
if(is_selected_button || rowItem?.version === "unknown") {
|
||||
list = list.filter(it => it !== "switch");
|
||||
}
|
||||
|
||||
if (!list) {
|
||||
if (!Array.isArray(list)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return list.map(id => {
|
||||
const shown = (is_selected_button || rowItem?.version === "unknown")
|
||||
? list.filter(it => it !== "switch")
|
||||
: list;
|
||||
|
||||
return shown.map(id => {
|
||||
const bt = buttons[id];
|
||||
return `<button class="cn-btn-${id} p-button p-component" group="${action}" mode="${bt.mode}">${bt.label}</button>`;
|
||||
// `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>`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
@@ -518,7 +521,7 @@ export class CustomNodesManager {
|
||||
|
||||
initGrid() {
|
||||
const container = this.element.querySelector(".cn-manager-grid");
|
||||
const grid = new TG.Grid(container);
|
||||
const grid = new ManagerGrid(container);
|
||||
this.grid = grid;
|
||||
|
||||
this.flyover = this.createFlyover(container);
|
||||
@@ -579,6 +582,9 @@ export class CustomNodesManager {
|
||||
|
||||
|
||||
grid.setOption({
|
||||
highlightKeywords: {
|
||||
textGenerator: (row, column) => column === 'author' ? sanitizeHTML(String(row[column] ?? '')) : row[column]
|
||||
},
|
||||
theme: 'dark',
|
||||
selectVisible: true,
|
||||
selectMultiple: true,
|
||||
@@ -646,7 +652,8 @@ export class CustomNodesManager {
|
||||
|
||||
let res = await response.json();
|
||||
|
||||
let title = `<FONT COLOR=GREEN><B>Error message occurred while importing the '${rowItem.title}' module.</B></FONT><BR><HR><BR>`
|
||||
// `title` is server-escaped; `res['msg']` below is raw and is escaped.
|
||||
let title = `<FONT COLOR=GREEN><B>Error message occurred while importing the '${String(rowItem.title ?? '')}' module.</B></FONT><BR><HR><BR>`
|
||||
|
||||
if(res.code == 400)
|
||||
{
|
||||
@@ -711,11 +718,12 @@ export class CustomNodesManager {
|
||||
|
||||
const link = document.createElement('a');
|
||||
if(rowItem.originalData.repository)
|
||||
link.href = rowItem.originalData.repository;
|
||||
link.href = sanitizeUrl(rowItem.originalData.repository);
|
||||
else
|
||||
link.href = rowItem.reference;
|
||||
link.href = sanitizeUrl(rowItem.reference);
|
||||
link.target = '_blank';
|
||||
link.innerHTML = `<b>${title}</b>`;
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.innerHTML = `<b>${String(title ?? '')}</b>`;
|
||||
link.title = rowItem.originalData.id;
|
||||
container.appendChild(link);
|
||||
|
||||
@@ -734,11 +742,11 @@ export class CustomNodesManager {
|
||||
}
|
||||
if(rowItem.cnr_latest && version != rowItem.cnr_latest) {
|
||||
if(version == 'nightly') {
|
||||
return `<div>${version}</div><div>[${rowItem.cnr_latest}]</div>`;
|
||||
return `<div>${sanitizeHTML(String(version))}</div><div>[${sanitizeHTML(String(rowItem.cnr_latest))}]</div>`;
|
||||
}
|
||||
return `<div>${version}</div><div>[↑${rowItem.cnr_latest}]</div>`;
|
||||
return `<div>${sanitizeHTML(String(version))}</div><div>[↑${sanitizeHTML(String(rowItem.cnr_latest))}]</div>`;
|
||||
}
|
||||
return version;
|
||||
return sanitizeHTML(String(version));
|
||||
}
|
||||
}, {
|
||||
id: 'action',
|
||||
@@ -777,13 +785,13 @@ export class CustomNodesManager {
|
||||
width: 400,
|
||||
maxWidth: 5000,
|
||||
invisible: !this.hasAlternatives(),
|
||||
classMap: 'cn-pack-desc'
|
||||
classMap: 'cn-pack-desc' // composed HTML; tags are escaped in getAlternatives
|
||||
}, {
|
||||
id: 'description',
|
||||
name: 'Description',
|
||||
width: 400,
|
||||
maxWidth: 5000,
|
||||
classMap: 'cn-pack-desc'
|
||||
classMap: 'cn-pack-desc' // composed HTML from the server (convert_markdown_to_html)
|
||||
}, {
|
||||
id: 'author',
|
||||
name: 'Author',
|
||||
@@ -791,9 +799,9 @@ export class CustomNodesManager {
|
||||
classMap: "cn-pack-author",
|
||||
formatter: (author, rowItem, columnItem) => {
|
||||
if (rowItem.trust) {
|
||||
return `<span tooltip="This author has been active for more than six months in GitHub">✅ ${author}</span>`;
|
||||
return `<span tooltip="This author has been active for more than six months in GitHub">✅ ${sanitizeHTML(String(author ?? ''))}</span>`;
|
||||
}
|
||||
return author;
|
||||
return sanitizeHTML(String(author ?? ''));
|
||||
}
|
||||
}, {
|
||||
id: 'stars',
|
||||
@@ -807,7 +815,7 @@ export class CustomNodesManager {
|
||||
if (typeof stars === 'number') {
|
||||
return stars.toLocaleString();
|
||||
}
|
||||
return stars;
|
||||
return sanitizeHTML(String(stars ?? ''));
|
||||
}
|
||||
}, {
|
||||
id: 'last_update',
|
||||
@@ -822,7 +830,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
const ago = getTimeAgo(last_update);
|
||||
const short = `${last_update}`.split(' ')[0];
|
||||
return `<span tooltip="${ago}">${short}</span>`;
|
||||
return `<span tooltip="${ago}">${sanitizeHTML(String(short))}</span>`;
|
||||
}
|
||||
}];
|
||||
|
||||
@@ -902,7 +910,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>`];
|
||||
|
||||
@@ -983,7 +991,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("");
|
||||
|
||||
@@ -991,7 +999,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("");
|
||||
@@ -1023,22 +1031,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("");
|
||||
@@ -1211,7 +1220,7 @@ export class CustomNodesManager {
|
||||
const rowItem = d.rowItem;
|
||||
const isNotInstalled = rowItem.action == "not-installed";
|
||||
|
||||
let titleHtml = `<div class="cn-nodes-pack" hash="${rowItem.hash}">${rowItem.title}</div>`;
|
||||
let titleHtml = `<div class="cn-nodes-pack" hash="${rowItem.hash}">${String(rowItem.title ?? '')}</div>`;
|
||||
if (isNotInstalled) {
|
||||
titleHtml += '<div class="cn-pack-badge">Not Installed</div>'
|
||||
}
|
||||
@@ -1227,11 +1236,12 @@ export class CustomNodesManager {
|
||||
|
||||
list.push(`<div class="${rowClass}">`);
|
||||
list.push(`<div class="cn-nodes-sn">${i+1}</div>`);
|
||||
list.push(`<div class="cn-nodes-name">${it.name}</div>`);
|
||||
// `it.name` is a raw node name from getmappings (not the pack name)
|
||||
list.push(`<div class="cn-nodes-name">${sanitizeHTML(String(it.name ?? ''))}</div>`);
|
||||
|
||||
if (it.conflicts) {
|
||||
list.push(`<div class="cn-conflicts-list"><div class="cn-nodes-conflict cn-icon">${icons.conflicts}</div><b>Conflict with</b>${it.conflicts.map(c => {
|
||||
return `<div class="cn-nodes-pack" hash="${c.hash}">${c.title}</div>`;
|
||||
return `<div class="cn-nodes-pack" hash="${c.hash}">${String(c.title ?? '')}</div>`;
|
||||
}).join("<b>,</b>")}</div>`);
|
||||
}
|
||||
list.push(`</div>`);
|
||||
@@ -1349,7 +1359,7 @@ export class CustomNodesManager {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedMap = {};
|
||||
const selectedMap = Object.create(null);
|
||||
selectedList.forEach(item => {
|
||||
let type = item.action;
|
||||
if (item.restart) {
|
||||
@@ -1367,8 +1377,10 @@ export class CustomNodesManager {
|
||||
const list = [];
|
||||
Object.keys(selectedMap).forEach(v => {
|
||||
const filterItem = this.getFilterItem(v);
|
||||
// `v` is a registry-supplied `state`; escape it when no filter label matches.
|
||||
const typeLabel = filterItem ? filterItem.label : sanitizeHTML(String(v ?? ''));
|
||||
list.push(`<div class="cn-selected-buttons">
|
||||
<span>Selected <b>${selectedMap[v].length}</b> ${filterItem ? filterItem.label : v}</span>
|
||||
<span>Selected <b>${selectedMap[v].length}</b> ${typeLabel}</span>
|
||||
${this.grid.hasMask ? "" : this.getActionButtons(v, null, true)}
|
||||
</div>`);
|
||||
});
|
||||
@@ -1466,7 +1478,6 @@ export class CustomNodesManager {
|
||||
target.classList.add("cn-btn-loading");
|
||||
this.showError("");
|
||||
|
||||
let needRestart = false;
|
||||
let errorMsg = "";
|
||||
|
||||
let target_items = [];
|
||||
@@ -1475,13 +1486,13 @@ export class CustomNodesManager {
|
||||
|
||||
for (const hash of list) {
|
||||
const item = this.grid.getRowItemBy("hash", hash);
|
||||
target_items.push(item);
|
||||
|
||||
if (!item) {
|
||||
errorMsg = `Not found custom node: ${hash}`;
|
||||
errorMsg = `Not found custom node: ${sanitizeHTML(String(hash))}`;
|
||||
break;
|
||||
}
|
||||
|
||||
target_items.push(item);
|
||||
this.grid.scrollRowIntoView(item);
|
||||
|
||||
if (!this.focusInstall(item, mode)) {
|
||||
@@ -1538,23 +1549,48 @@ export class CustomNodesManager {
|
||||
this.batch_id = generateUUID();
|
||||
batch['batch_id'] = this.batch_id;
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
let failed;
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
if (!Array.isArray(data?.failed)) throw new Error('Invalid batch response.');
|
||||
failed = data.failed;
|
||||
} catch (error) {
|
||||
errorMsg = `Failed to submit installation request: ${sanitizeHTML(String(error))}`;
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n" + errorMsg);
|
||||
target.classList.remove("cn-btn-loading");
|
||||
this.element.querySelectorAll(".cn-btn-loading").forEach(button => {
|
||||
button.classList.remove("cn-btn-loading");
|
||||
});
|
||||
this.hideLoading();
|
||||
this.hideStop();
|
||||
this.install_context = undefined;
|
||||
return;
|
||||
}
|
||||
for (const id of failed) {
|
||||
const item = target_items.find(item => item.originalData.id === id);
|
||||
errorMsg += `[FAIL] ${item?.title ?? sanitizeHTML(String(id))}\n`;
|
||||
}
|
||||
if (errorMsg) {
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n" + errorMsg);
|
||||
}
|
||||
|
||||
let failed = await res.json();
|
||||
showTerminal();
|
||||
|
||||
if(failed.length > 0) {
|
||||
for(let k in failed) {
|
||||
let hash = failed[k];
|
||||
const item = this.grid.getRowItemBy("hash", hash);
|
||||
errorMsg = `[FAIL] ${item.title}`;
|
||||
}
|
||||
// No queued work means the server will not send batch-done.
|
||||
if (target_items.every(item => failed.includes(item.originalData.id))) {
|
||||
this.hideLoading();
|
||||
this.hideStop();
|
||||
this.install_context = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
this.showStop();
|
||||
showTerminal();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1580,12 +1616,9 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -1601,7 +1634,7 @@ export class CustomNodesManager {
|
||||
let v = result[hash];
|
||||
|
||||
if(v != 'success' && v != 'skip')
|
||||
errorMsg += v+'\n';
|
||||
errorMsg += sanitizeHTML(String(v))+'\n';
|
||||
}
|
||||
|
||||
for(let k in self.install_context.targets) {
|
||||
@@ -1613,7 +1646,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();
|
||||
@@ -1719,7 +1752,7 @@ export class CustomNodesManager {
|
||||
if(unresolved_cnr_list.length > 0) {
|
||||
let error_msg = "Failed to find the following ComfyRegistry list.\nThe cache may be outdated, or the nodes may have been removed from ComfyRegistry.<HR>";
|
||||
for(let i in unresolved_cnr_list) {
|
||||
error_msg += '<li>'+unresolved_cnr_list[i]+'</li>';
|
||||
error_msg += '<li>'+sanitizeHTML(String(unresolved_cnr_list[i]))+'</li>';
|
||||
}
|
||||
|
||||
show_message(error_msg);
|
||||
@@ -1769,7 +1802,7 @@ export class CustomNodesManager {
|
||||
this.showStatus(`Loading missing nodes (${mode}) ...`);
|
||||
const res = await fetchData(`/v2/customnode/getmappings?mode=${mode}`);
|
||||
if (res.error) {
|
||||
this.showError(`Failed to get custom node mappings: ${res.error}`);
|
||||
this.showError(`Failed to get custom node mappings: ${sanitizeHTML(String(res.error))}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1884,7 +1917,7 @@ export class CustomNodesManager {
|
||||
this.showStatus(`Loading alternatives (${mode}) ...`);
|
||||
const res = await fetchData(`/v2/customnode/alternatives?mode=${mode}`);
|
||||
if (res.error) {
|
||||
this.showError(`Failed to get alternatives: ${res.error}`);
|
||||
this.showError(`Failed to get alternatives: ${sanitizeHTML(String(res.error))}`);
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -1901,7 +1934,7 @@ export class CustomNodesManager {
|
||||
}
|
||||
|
||||
const tags = `${item.tags}`.split(",").map(tag => {
|
||||
return `<div>${tag.trim()}</div>`;
|
||||
return `<div>${sanitizeHTML(tag.trim())}</div>`;
|
||||
}).join("");
|
||||
|
||||
hashMap[custom_node.hash] = {
|
||||
@@ -1948,7 +1981,7 @@ export class CustomNodesManager {
|
||||
this.custom_nodes = node_packs;
|
||||
|
||||
if(this.channel !== 'default') {
|
||||
this.element.querySelector(".cn-manager-channel").innerHTML = `Channel: ${this.channel} (Incomplete list)`;
|
||||
this.element.querySelector(".cn-manager-channel").innerHTML = `Channel: ${sanitizeHTML(String(this.channel))} (Incomplete list)`;
|
||||
}
|
||||
|
||||
for (const k in node_packs) {
|
||||
@@ -2077,6 +2110,7 @@ export class CustomNodesManager {
|
||||
// ===========================================================================================
|
||||
|
||||
showSelection(msg) {
|
||||
// Takes composed HTML (buttons included); ingredients are escaped in renderSelected.
|
||||
this.element.querySelector(".cn-manager-selection").innerHTML = msg;
|
||||
}
|
||||
|
||||
@@ -2084,18 +2118,17 @@ export class CustomNodesManager {
|
||||
this.showMessage(err, "red");
|
||||
}
|
||||
|
||||
// Messages contain HTML: preserve server-escaped names and escape raw values at the caller.
|
||||
showMessage(msg, color) {
|
||||
if (color) {
|
||||
msg = `<font color="${color}">${msg}</font>`;
|
||||
}
|
||||
this.element.querySelector(".cn-manager-message").innerHTML = msg;
|
||||
const element = this.element.querySelector(".cn-manager-message");
|
||||
element.style.color = color || "";
|
||||
element.innerHTML = msg ?? "";
|
||||
}
|
||||
|
||||
showStatus(msg, color) {
|
||||
if (color) {
|
||||
msg = `<font color="${color}">${msg}</font>`;
|
||||
}
|
||||
this.element.querySelector(".cn-manager-status").innerHTML = msg;
|
||||
const element = this.element.querySelector(".cn-manager-status");
|
||||
element.style.color = color || "";
|
||||
element.innerHTML = msg ?? "";
|
||||
}
|
||||
|
||||
showLoading() {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Grid } from "./turbogrid.esm.js";
|
||||
|
||||
// Keep Manager's search hardening outside the vendored TurboGrid bundle.
|
||||
export default class ManagerGrid extends Grid {
|
||||
highlightKeywordsFilter(rowItem, columns, value) {
|
||||
const { textKey, textGenerator, highlightKey } = this.options.highlightKeywords;
|
||||
for (const column of columns) {
|
||||
rowItem[`${highlightKey}${column}`] = null;
|
||||
}
|
||||
const keywords = value ? String(value).trim().toLowerCase().split(/\s+/).filter(Boolean) : [];
|
||||
if (!keywords.length) return true;
|
||||
|
||||
let matched = false;
|
||||
for (const column of columns) {
|
||||
const value = typeof textGenerator === "function" ? textGenerator(rowItem, column) : rowItem[column];
|
||||
if (value === null || value === undefined) continue;
|
||||
let text = String(value).trim();
|
||||
if (!text) continue;
|
||||
const key = `${textKey}${column}`;
|
||||
if (rowItem[key] === null || rowItem[key] === undefined) {
|
||||
// A detached element's innerHTML can still run image handlers.
|
||||
rowItem[key] = new DOMParser().parseFromString(text, "text/html").body.textContent;
|
||||
}
|
||||
text = rowItem[key].toLowerCase();
|
||||
let offset = 0;
|
||||
const found = keywords.every(keyword => {
|
||||
const index = text.indexOf(keyword, offset);
|
||||
if (index === -1) return false;
|
||||
offset = index + keyword.length;
|
||||
return true;
|
||||
});
|
||||
if (found) {
|
||||
rowItem[`${highlightKey}${column}`] = true;
|
||||
this.highlightKeywords = keywords;
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
return matched;
|
||||
}
|
||||
|
||||
highlightTextNodes(nodes, keywords) {
|
||||
if (!keywords.length) return;
|
||||
let keywordIndex = 0;
|
||||
for (const node of nodes) {
|
||||
const text = node.textContent;
|
||||
const lower = text.toLowerCase();
|
||||
const wrapper = document.createElement("span");
|
||||
let offset = 0;
|
||||
while (offset < text.length) {
|
||||
const keyword = keywords[keywordIndex];
|
||||
const index = lower.indexOf(keyword, offset);
|
||||
if (index === -1) break;
|
||||
wrapper.append(text.slice(offset, index));
|
||||
const mark = document.createElement("mark");
|
||||
mark.textContent = text.slice(index, index + keyword.length);
|
||||
wrapper.append(mark);
|
||||
offset = index + keyword.length;
|
||||
keywordIndex = (keywordIndex + 1) % keywords.length;
|
||||
}
|
||||
if (wrapper.childNodes.length) {
|
||||
// Decoded cell text stays in text nodes, including inside <mark>.
|
||||
wrapper.append(text.slice(offset));
|
||||
node.replaceWith(wrapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+172
-117
@@ -3,17 +3,22 @@ import { $el } from "../../scripts/ui.js";
|
||||
import {
|
||||
manager_instance, rebootAPI,
|
||||
fetchData, md5, icons, show_message, customAlert, infoToast, showTerminal,
|
||||
storeColumnWidth, restoreColumnWidth, loadCss, generateUUID
|
||||
storeColumnWidth, restoreColumnWidth, loadCss, generateUUID,
|
||||
sanitizeHTML, sanitizeUrl
|
||||
} from "./common.js";
|
||||
|
||||
// Model names and descriptions are server-escaped; other fields are raw.
|
||||
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
// https://cenfun.github.io/turbogrid/api.html
|
||||
import TG from "./turbogrid.esm.js";
|
||||
import ManagerGrid from "./manager-grid.js";
|
||||
import { buildGuiFrameCustomHeader, createSettingsCombo } from "./comfyui-gui-builder.js";
|
||||
|
||||
loadCss("./model-manager.css");
|
||||
|
||||
const gridId = "model";
|
||||
const escapeCell = (value) => sanitizeHTML(String(value ?? ""));
|
||||
|
||||
const pageHtml = `
|
||||
<div class="cmm-manager cmm-manager-dark">
|
||||
@@ -41,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);
|
||||
@@ -101,22 +109,17 @@ export class ModelManager {
|
||||
|
||||
updateFilter() {
|
||||
const $filter = this.element.querySelector(".cmm-manager-filter");
|
||||
$filter.innerHTML = this.filterList.map(item => {
|
||||
const selected = item.value === this.filter ? " selected" : "";
|
||||
return `<option value="${item.value}"${selected}>${item.label}</option>`
|
||||
}).join("");
|
||||
const option = (item, current) => {
|
||||
const selected = item.value === current ? " selected" : "";
|
||||
return `<option value="${sanitizeHTML(String(item.value ?? ''))}"${selected}>${sanitizeHTML(String(item.label ?? ''))}</option>`;
|
||||
};
|
||||
$filter.innerHTML = this.filterList.map(item => option(item, this.filter)).join("");
|
||||
|
||||
const $type = this.element.querySelector(".cmm-manager-type");
|
||||
$type.innerHTML = this.typeList.map(item => {
|
||||
const selected = item.value === this.type ? " selected" : "";
|
||||
return `<option value="${item.value}"${selected}>${item.label}</option>`
|
||||
}).join("");
|
||||
$type.innerHTML = this.typeList.map(item => option(item, this.type)).join("");
|
||||
|
||||
const $base = this.element.querySelector(".cmm-manager-base");
|
||||
$base.innerHTML = this.baseList.map(item => {
|
||||
const selected = item.value === this.base ? " selected" : "";
|
||||
return `<option value="${item.value}"${selected}>${item.label}</option>`
|
||||
}).join("");
|
||||
$base.innerHTML = this.baseList.map(item => option(item, this.base)).join("");
|
||||
|
||||
}
|
||||
|
||||
@@ -199,7 +202,7 @@ export class ModelManager {
|
||||
|
||||
initGrid() {
|
||||
const container = this.element.querySelector(".cmm-manager-grid");
|
||||
const grid = new TG.Grid(container);
|
||||
const grid = new ManagerGrid(container);
|
||||
this.grid = grid;
|
||||
|
||||
grid.bind('onUpdated', (e, d) => {
|
||||
@@ -227,6 +230,9 @@ export class ModelManager {
|
||||
});
|
||||
|
||||
grid.setOption({
|
||||
highlightKeywords: {
|
||||
textGenerator: (row, column) => ['name', 'description'].includes(column) ? row[column] : escapeCell(row[column])
|
||||
},
|
||||
theme: 'dark',
|
||||
|
||||
selectVisible: true,
|
||||
@@ -325,7 +331,12 @@ export class ModelManager {
|
||||
maxWidth: 500,
|
||||
classMap: 'cmm-node-name',
|
||||
formatter: function(name, rowItem, columnItem, cellNode) {
|
||||
return `<a href=${rowItem.reference} target="_blank"><b>${name}</b></a>`;
|
||||
// Names are server-escaped; raw references need URL and attribute handling.
|
||||
const href = sanitizeUrl(rowItem.reference);
|
||||
if (!href) {
|
||||
return `<b>${String(name ?? '')}</b>`;
|
||||
}
|
||||
return `<a href="${sanitizeHTML(href)}" target="_blank" rel="noopener noreferrer"><b>${String(name ?? '')}</b></a>`;
|
||||
}
|
||||
}, {
|
||||
id: 'installed',
|
||||
@@ -351,7 +362,11 @@ export class ModelManager {
|
||||
sortable: false,
|
||||
align: 'center',
|
||||
formatter: (url, rowItem, columnItem) => {
|
||||
return `<a class="cmm-btn-download" tooltip="Download file" href="${url}" target="_blank">${icons.download}</a>`;
|
||||
const href = sanitizeUrl(url);
|
||||
if (!href) {
|
||||
return '';
|
||||
}
|
||||
return `<a class="cmm-btn-download" tooltip="Download file" href="${sanitizeHTML(href)}" target="_blank" rel="noopener noreferrer">${icons.download}</a>`;
|
||||
}
|
||||
}, {
|
||||
id: 'size',
|
||||
@@ -361,29 +376,33 @@ export class ModelManager {
|
||||
if (typeof size === "number") {
|
||||
return this.formatSize(size);
|
||||
}
|
||||
return size;
|
||||
return sanitizeHTML(String(size ?? ''));
|
||||
}
|
||||
}, {
|
||||
id: 'type',
|
||||
name: 'Type',
|
||||
width: 100
|
||||
width: 100,
|
||||
formatter: escapeCell
|
||||
}, {
|
||||
id: 'base',
|
||||
name: 'Base'
|
||||
name: 'Base',
|
||||
formatter: escapeCell
|
||||
}, {
|
||||
id: 'description',
|
||||
name: 'Description',
|
||||
width: 400,
|
||||
maxWidth: 5000,
|
||||
classMap: 'cmm-node-desc'
|
||||
classMap: 'cmm-node-desc' // composed HTML from the server (convert_markdown_to_html)
|
||||
}, {
|
||||
id: "save_path",
|
||||
name: 'Save Path',
|
||||
width: 200
|
||||
width: 200,
|
||||
formatter: escapeCell
|
||||
}, {
|
||||
id: 'filename',
|
||||
name: 'Filename',
|
||||
width: 200
|
||||
width: 200,
|
||||
formatter: escapeCell
|
||||
}];
|
||||
|
||||
restoreColumnWidth(gridId, columns);
|
||||
@@ -433,7 +452,6 @@ export class ModelManager {
|
||||
btn.classList.add("cmm-btn-loading");
|
||||
this.showError("");
|
||||
|
||||
let needRefresh = false;
|
||||
let errorMsg = "";
|
||||
|
||||
let target_items = [];
|
||||
@@ -454,6 +472,8 @@ export class ModelManager {
|
||||
|
||||
const data = item.originalData;
|
||||
data.ui_id = item.hash;
|
||||
// Batch rejections refer to id; models need a stable request ID.
|
||||
data.id ??= item.hash;
|
||||
|
||||
|
||||
if(batch['install_model']) {
|
||||
@@ -464,49 +484,132 @@ export class ModelManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.install_context = {btn: btn, targets: target_items};
|
||||
const batch_id = generateUUID();
|
||||
batch['batch_id'] = batch_id;
|
||||
this.install_contexts.set(batch_id, {btn: btn, targets: target_items, queued: false});
|
||||
|
||||
if(errorMsg) {
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n"+errorMsg);
|
||||
|
||||
// reset
|
||||
for(let k in target_items) {
|
||||
const item = target_items[k];
|
||||
this.grid.updateCell(item, "installed");
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.batch_id = generateUUID();
|
||||
batch['batch_id'] = this.batch_id;
|
||||
|
||||
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
|
||||
let failed;
|
||||
try {
|
||||
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(batch)
|
||||
});
|
||||
if (error) throw error;
|
||||
if (!Array.isArray(data?.failed)) throw new Error('Invalid batch response.');
|
||||
failed = data.failed;
|
||||
} catch (error) {
|
||||
errorMsg = `Failed to submit installation request: ${sanitizeHTML(String(error))}`;
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n" + errorMsg);
|
||||
this.endInstall(batch_id);
|
||||
return;
|
||||
}
|
||||
for (const id of failed) {
|
||||
const item = target_items.find(item => item.originalData.id === id);
|
||||
errorMsg += `[FAIL] ${item?.name ?? sanitizeHTML(String(id))}\n`;
|
||||
}
|
||||
if (errorMsg) {
|
||||
this.showError(errorMsg);
|
||||
show_message("[Installation Errors]\n" + errorMsg);
|
||||
}
|
||||
|
||||
let failed = await res.json();
|
||||
showTerminal();
|
||||
|
||||
if(failed.length > 0) {
|
||||
for(let k in failed) {
|
||||
let hash = failed[k];
|
||||
const item = self.grid.getRowItemBy("hash", hash);
|
||||
errorMsg = `[FAIL] ${item.title}`;
|
||||
}
|
||||
// No queued work means the server will not send batch-done.
|
||||
if (target_items.every(item => failed.includes(item.originalData.id))) {
|
||||
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);
|
||||
}
|
||||
|
||||
this.showStop();
|
||||
showTerminal();
|
||||
}
|
||||
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);
|
||||
@@ -514,29 +617,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 = "";
|
||||
|
||||
@@ -544,26 +638,22 @@ export class ModelManager {
|
||||
let v = result[hash];
|
||||
|
||||
if(v != 'success')
|
||||
errorMsg += v + '\n';
|
||||
}
|
||||
|
||||
for(let k in self.install_context.targets) {
|
||||
let item = self.install_context.targets[k];
|
||||
self.grid.updateCell(item, "installed");
|
||||
errorMsg += sanitizeHTML(String(v)) + '\n';
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -720,22 +810,20 @@ export class ModelManager {
|
||||
this.showMessage(err, "red");
|
||||
}
|
||||
|
||||
// Messages contain HTML: preserve server-escaped names and escape raw values at the caller.
|
||||
showMessage(msg, color) {
|
||||
if (color) {
|
||||
msg = `<font color="${color}">${msg}</font>`;
|
||||
}
|
||||
this.element.querySelector(".cmm-manager-message").innerHTML = msg;
|
||||
const element = this.element.querySelector(".cmm-manager-message");
|
||||
element.style.color = color || "";
|
||||
element.innerHTML = msg ?? "";
|
||||
}
|
||||
|
||||
showStatus(msg, color) {
|
||||
if (color) {
|
||||
msg = `<font color="${color}">${msg}</font>`;
|
||||
}
|
||||
this.element.querySelector(".cmm-manager-status").innerHTML = msg;
|
||||
const element = this.element.querySelector(".cmm-manager-status");
|
||||
element.style.color = color || "";
|
||||
element.innerHTML = msg ?? "";
|
||||
}
|
||||
|
||||
showLoading() {
|
||||
// this.setDisabled(true);
|
||||
if (this.grid) {
|
||||
this.grid.showLoading();
|
||||
this.grid.showMask({
|
||||
@@ -745,45 +833,12 @@ export class ModelManager {
|
||||
}
|
||||
|
||||
hideLoading() {
|
||||
// this.setDisabled(false);
|
||||
if (this.grid) {
|
||||
this.grid.hideLoading();
|
||||
this.grid.hideMask();
|
||||
}
|
||||
}
|
||||
|
||||
setDisabled(disabled) {
|
||||
const $close = this.element.querySelector(".cmm-manager-close");
|
||||
const $refresh = this.element.querySelector(".cmm-manager-refresh");
|
||||
const $stop = this.element.querySelector(".cmm-manager-stop");
|
||||
|
||||
const list = [
|
||||
".cmm-manager-header input",
|
||||
".cmm-manager-header select",
|
||||
".cmm-manager-footer button",
|
||||
".cmm-manager-selection button"
|
||||
].map(s => {
|
||||
return Array.from(this.element.querySelectorAll(s));
|
||||
})
|
||||
.flat()
|
||||
.filter(it => {
|
||||
return it !== $close && it !== $refresh && it !== $stop;
|
||||
});
|
||||
|
||||
list.forEach($elem => {
|
||||
if (disabled) {
|
||||
$elem.setAttribute("disabled", "disabled");
|
||||
} else {
|
||||
$elem.removeAttribute("disabled");
|
||||
}
|
||||
});
|
||||
|
||||
Array.from(this.element.querySelectorAll(".cmm-btn-loading")).forEach($elem => {
|
||||
$elem.classList.remove("cmm-btn-loading");
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
showRefresh() {
|
||||
this.element.querySelector(".cmm-manager-refresh").style.display = "block";
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js"
|
||||
import { ComfyDialog, $el } from "../../scripts/ui.js";
|
||||
import { manager_instance, rebootAPI, show_message, loadCss } from "./common.js";
|
||||
import { manager_instance, rebootAPI, show_message, loadCss, sanitizeHTML } from "./common.js";
|
||||
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" });
|
||||
|
||||
@@ -16,20 +25,24 @@ async function restore_snapshot(target) {
|
||||
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='p-button p-component'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,15 +57,16 @@ async function remove_snapshot(target) {
|
||||
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 {
|
||||
@@ -133,7 +147,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
startRestore(target) {
|
||||
const self = SnapshotManager.instance;
|
||||
|
||||
self.updateMessage(`<BR><font color="green">Restore snapshot '${target.name}'</font>`);
|
||||
self.updateMessage(`<BR><font color="green">Restore snapshot '${sanitizeHTML(String(target.name ?? ''))}'</font>`);
|
||||
|
||||
for(let i in self.restore_buttons) {
|
||||
self.restore_buttons[i].disabled = true;
|
||||
@@ -214,7 +228,7 @@ export class SnapshotManager extends ComfyDialog {
|
||||
data1.style.textAlign = "center";
|
||||
data1.innerHTML = i+1;
|
||||
var data2 = document.createElement('td');
|
||||
data2.innerHTML = ` ${data}`;
|
||||
data2.textContent = `\u00a0${data}`;
|
||||
var data_button = document.createElement('td');
|
||||
data_button.style.textAlign = "center";
|
||||
data_button.className = "data-btns";
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""HTML rendering helpers used only by the legacy Manager UI."""
|
||||
import re
|
||||
from html import escape, unescape
|
||||
from html.entities import html5
|
||||
|
||||
|
||||
SAFE_URL_SCHEMES = frozenset({'http', 'https'})
|
||||
_URL_SCHEME_NOISE = re.compile(r'[\x00-\x20\x7f]')
|
||||
_URL_HEAD_DELIMITERS = ('/', '?', '#')
|
||||
|
||||
|
||||
def escape_html_attribute(value):
|
||||
"""Escape a value for a quoted HTML attribute."""
|
||||
return escape(str(value), quote=True)
|
||||
|
||||
|
||||
_HTML_ENTITY = re.compile(r'&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);')
|
||||
_HTML_TEXT_TOKEN = re.compile(_HTML_ENTITY.pattern + "|[&<>\"']")
|
||||
|
||||
|
||||
def unescape_html_entities(text):
|
||||
"""Decode complete entities once, leaving query keys such as ¬ebook intact."""
|
||||
def replace(match):
|
||||
entity = match.group(1)
|
||||
if entity.startswith('#'):
|
||||
return unescape(match.group(0))
|
||||
return html5.get(entity + ';', match.group(0))
|
||||
|
||||
return _HTML_ENTITY.sub(replace, text)
|
||||
|
||||
|
||||
def escape_html_text(value):
|
||||
"""Escape HTML text without double-escaping existing entities."""
|
||||
return _HTML_TEXT_TOKEN.sub(
|
||||
lambda m: m.group(0) if m.group(1) else escape_html_attribute(m.group(0)),
|
||||
str(value),
|
||||
)
|
||||
|
||||
|
||||
def sanitize_url(url):
|
||||
"""Allow HTTP(S), relative URLs and anchors.
|
||||
|
||||
HTML callers must also escape the result as an attribute."""
|
||||
raw = '' if url is None else str(url)
|
||||
probe = _URL_SCHEME_NOISE.sub('', raw)
|
||||
if not probe:
|
||||
return '#'
|
||||
|
||||
cut = len(probe)
|
||||
for delimiter in _URL_HEAD_DELIMITERS:
|
||||
found = probe.find(delimiter)
|
||||
if found != -1:
|
||||
cut = min(cut, found)
|
||||
head = probe[:cut]
|
||||
|
||||
if ':' in head:
|
||||
return raw.strip() if head.split(':', 1)[0].lower() in SAFE_URL_SCHEMES else '#'
|
||||
|
||||
return raw.strip()
|
||||
|
||||
|
||||
def sanitize_html_fragment(fragment):
|
||||
"""Sanitize notice HTML, preserving its formatting and opening links safely."""
|
||||
# Keep nh3 loading within the legacy notice path.
|
||||
import nh3
|
||||
|
||||
return nh3.clean(
|
||||
'' if fragment is None else str(fragment),
|
||||
tags=nh3.ALLOWED_TAGS | {'font'},
|
||||
attributes={
|
||||
**nh3.ALLOWED_ATTRIBUTES,
|
||||
'*': {'class', 'title', 'align', 'width', 'height'},
|
||||
'font': {'color'},
|
||||
},
|
||||
# These elements previously hid their contents from the notice.
|
||||
clean_content_tags={
|
||||
'script', 'style', 'iframe', 'object', 'embed', 'svg', 'math',
|
||||
'template', 'noscript', 'textarea', 'title',
|
||||
},
|
||||
url_schemes=SAFE_URL_SCHEMES,
|
||||
set_tag_attribute_values={'a': {'target': '_blank'}},
|
||||
)
|
||||
@@ -33,8 +33,10 @@ from packaging import version
|
||||
import uuid
|
||||
|
||||
from ..common import cm_global
|
||||
from ..common.config_writer import DirtyTrackingConfig, write_config_merged
|
||||
from ..common import cnr_utils
|
||||
from ..common import manager_util
|
||||
from ..common import manager_security
|
||||
from ..common import git_utils
|
||||
from ..common import manager_downloader
|
||||
from ..common.node_package import InstalledNodePackage
|
||||
@@ -183,80 +185,7 @@ def remap_pip_package(pkg):
|
||||
|
||||
|
||||
def is_blacklisted(name):
|
||||
name = name.strip()
|
||||
|
||||
pattern = r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
|
||||
match = re.search(pattern, name)
|
||||
|
||||
if match:
|
||||
name = match.group(1)
|
||||
|
||||
if name in cm_global.pip_blacklist:
|
||||
return True
|
||||
|
||||
if name in cm_global.pip_downgrade_blacklist:
|
||||
pips = manager_util.get_installed_packages()
|
||||
|
||||
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)):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def is_installed(name):
|
||||
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:
|
||||
return True
|
||||
|
||||
if name in cm_global.pip_downgrade_blacklist:
|
||||
pips = manager_util.get_installed_packages()
|
||||
|
||||
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
|
||||
|
||||
pkg = manager_util.get_installed_packages().get(name.lower())
|
||||
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
|
||||
|
||||
return name.lower() in manager_util.get_installed_packages()
|
||||
return manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist) is not None
|
||||
|
||||
|
||||
def normalize_channel(channel):
|
||||
@@ -866,10 +795,10 @@ class UnifiedManager:
|
||||
|
||||
return res
|
||||
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps):
|
||||
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps, status=''):
|
||||
script_path = os.path.join(context.manager_startup_script_path, "install-scripts.txt")
|
||||
with open(script_path, "a") as file:
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable]
|
||||
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable, status]
|
||||
file.write(f"{obj}\n")
|
||||
|
||||
print(f"Installation reserved: {target}")
|
||||
@@ -895,35 +824,46 @@ class UnifiedManager:
|
||||
|
||||
return result
|
||||
|
||||
def _get_cnr_install_info(self, node_id, version_spec):
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
if (node_info is not None and node_info.status == 'NodeVersionStatusFlagged'
|
||||
and not manager_funcs.is_flagged_install_allowed(node_id)):
|
||||
logging.error(manager_security.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
|
||||
raise PermissionError(manager_security.FLAGGED_NODEPACK_INSTALL_ERROR)
|
||||
return node_info
|
||||
|
||||
def cnr_switch_version(self, node_id, version_spec=None, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
if instant_execution:
|
||||
return self.cnr_switch_version_instant(node_id, version_spec, instant_execution, no_deps, return_postinstall)
|
||||
else:
|
||||
return self.cnr_switch_version_lazy(node_id, version_spec, no_deps, return_postinstall)
|
||||
|
||||
def cnr_switch_version_lazy(self, node_id, version_spec=None, no_deps=False, return_postinstall=False):
|
||||
"""
|
||||
switch between cnr version (lazy mode)
|
||||
"""
|
||||
|
||||
result = ManagedResult('switch-cnr')
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return result.fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
version_spec = node_info.version
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
if self.active_nodes[node_id][0] == version_spec:
|
||||
def _cnr_switch_version(self, node_id, node_info, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
"""Execute a switch using the checked CNR response."""
|
||||
if self.active_nodes[node_id][0] == node_info.version:
|
||||
return ManagedResult('skip').with_msg("Up to date")
|
||||
|
||||
if instant_execution:
|
||||
return self._cnr_switch_version_instant(node_id, node_info, no_deps, return_postinstall)
|
||||
return self._cnr_switch_version_lazy(node_id, node_info, no_deps, return_postinstall)
|
||||
|
||||
def _cnr_switch_version_lazy(self, node_id, node_info, no_deps=False, return_postinstall=False):
|
||||
"""Reserve a switch using the validated install response."""
|
||||
result = ManagedResult('switch-cnr')
|
||||
version_spec = node_info.version
|
||||
zip_url = node_info.download_url
|
||||
from_path = self.active_nodes[node_id][1]
|
||||
target = node_id
|
||||
to_path = os.path.join(get_default_custom_nodes_path(), target)
|
||||
|
||||
def postinstall():
|
||||
return self.reserve_cnr_switch(target, zip_url, from_path, to_path, no_deps)
|
||||
return self.reserve_cnr_switch(target, zip_url, from_path, to_path, no_deps, node_info.status)
|
||||
|
||||
if return_postinstall:
|
||||
return result.with_postinstall(postinstall)
|
||||
@@ -933,23 +873,12 @@ class UnifiedManager:
|
||||
|
||||
return result
|
||||
|
||||
def cnr_switch_version_instant(self, node_id, version_spec=None, instant_execution=True, no_deps=False, return_postinstall=False):
|
||||
"""
|
||||
switch between cnr version
|
||||
"""
|
||||
|
||||
# 1. download
|
||||
def _cnr_switch_version_instant(self, node_id, node_info, no_deps=False, return_postinstall=False):
|
||||
"""Apply a switch using the validated install response."""
|
||||
result = ManagedResult('switch-cnr')
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
version_spec = node_info.version
|
||||
|
||||
if self.active_nodes[node_id][0] == version_spec:
|
||||
return ManagedResult('skip').with_msg("Up to date")
|
||||
|
||||
# 1. download
|
||||
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
@@ -994,7 +923,7 @@ class UnifiedManager:
|
||||
result.target = version_spec
|
||||
|
||||
def postinstall():
|
||||
res = self.execute_install_script(f"{node_id}@{version_spec}", install_path, instant_execution=instant_execution, no_deps=no_deps)
|
||||
res = self.execute_install_script(f"{node_id}@{version_spec}", install_path, instant_execution=True, no_deps=no_deps)
|
||||
return res
|
||||
|
||||
if return_postinstall:
|
||||
@@ -1276,10 +1205,24 @@ class UnifiedManager:
|
||||
if 'comfyui-manager' in node_id.lower():
|
||||
return result.fail(f"ignored: installing '{node_id}'")
|
||||
|
||||
node_info = cnr_utils.install_node(node_id, version_spec)
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return result.fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return result.fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
result = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
# Keep the requested version in the public result.
|
||||
if result.target is not None:
|
||||
result.target = version_spec
|
||||
return result
|
||||
|
||||
def _cnr_install(self, node_id, node_info, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
"""Install using the checked CNR response."""
|
||||
result = ManagedResult('install-cnr')
|
||||
version_spec = node_info.version
|
||||
|
||||
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
|
||||
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
|
||||
|
||||
@@ -1294,12 +1237,28 @@ class UnifiedManager:
|
||||
|
||||
manager_downloader.download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
|
||||
os.makedirs(install_path, exist_ok=True)
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
os.remove(download_path)
|
||||
try:
|
||||
extracted = manager_util.extract_package_as_zip(download_path, install_path)
|
||||
except Exception as e:
|
||||
# Left in place, the new directory makes the next install fail with 'Install path already exists'.
|
||||
# A cleanup that fails as well is logged: the extraction error is the one to report.
|
||||
try:
|
||||
try_rmtree(node_id, install_path)
|
||||
except Exception as cleanup_error:
|
||||
logging.warning(f"[ComfyUI-Manager] Failed to clean up '{install_path}': {cleanup_error}")
|
||||
return result.fail(f'Failed to extract archive: {node_id}@{version_spec}: {e}')
|
||||
finally:
|
||||
try:
|
||||
os.remove(download_path)
|
||||
except OSError:
|
||||
pass
|
||||
result.to_path = install_path
|
||||
|
||||
if extracted is None:
|
||||
shutil.rmtree(install_path)
|
||||
try:
|
||||
try_rmtree(node_id, install_path)
|
||||
except Exception as cleanup_error:
|
||||
logging.warning(f"[ComfyUI-Manager] Failed to clean up '{install_path}': {cleanup_error}")
|
||||
return result.fail(f'Empty archive file: {node_id}@{version_spec}')
|
||||
|
||||
# create .tracking file
|
||||
@@ -1468,31 +1427,13 @@ class UnifiedManager:
|
||||
else:
|
||||
version_spec = self.resolve_unspecified_version(node_id)
|
||||
|
||||
if version_spec == 'unknown' or version_spec == 'nightly':
|
||||
if version_spec in ('unknown', 'nightly'):
|
||||
try:
|
||||
custom_nodes = await self.get_custom_nodes(channel, mode)
|
||||
except InvalidChannel as e:
|
||||
return ManagedResult('fail').fail(f'Invalid channel is used: {e.channel}')
|
||||
|
||||
the_node = custom_nodes.get(node_id)
|
||||
if the_node is not None:
|
||||
if version_spec == 'unknown':
|
||||
repo_url = the_node['files'][0]
|
||||
else: # nightly
|
||||
repo_url = the_node['repository']
|
||||
else:
|
||||
# Fallback for nightly only: use repository URL from CNR map
|
||||
# when node is registered in CNR but absent from nightly manifest
|
||||
if version_spec == 'nightly':
|
||||
cnr_fallback = self.cnr_map.get(node_id)
|
||||
if cnr_fallback is not None and cnr_fallback.get('repository'):
|
||||
repo_url = cnr_fallback['repository']
|
||||
else:
|
||||
result = ManagedResult('install')
|
||||
return result.fail(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
|
||||
else:
|
||||
result = ManagedResult('install')
|
||||
return result.fail(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
|
||||
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
|
||||
except InvalidChannel as exc:
|
||||
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
|
||||
except LookupError as exc:
|
||||
return ManagedResult('install').fail(str(exc))
|
||||
|
||||
if self.is_enabled(node_id, version_spec):
|
||||
return ManagedResult('skip').with_target(f"{node_id}@{version_spec}")
|
||||
@@ -1500,32 +1441,16 @@ class UnifiedManager:
|
||||
elif self.is_disabled(node_id, version_spec):
|
||||
return self.unified_enable(node_id, version_spec)
|
||||
|
||||
elif version_spec == 'unknown' or version_spec == 'nightly':
|
||||
to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), node_id))
|
||||
elif version_spec in ('unknown', 'nightly'):
|
||||
return self._install_git(node_id, version_spec, repo_url, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
if version_spec == 'nightly':
|
||||
# disable cnr nodes
|
||||
if self.is_enabled(node_id, 'cnr'):
|
||||
self.unified_disable(node_id, False)
|
||||
|
||||
# use `repo name` as a dir name instead of `cnr id` if system added nodepack (i.e. publisher is null)
|
||||
cnr = self.cnr_map.get(node_id)
|
||||
|
||||
if cnr is not None and cnr.get('publisher') is None:
|
||||
repo_name = os.path.basename(git_utils.normalize_url(repo_url))
|
||||
to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), repo_name))
|
||||
|
||||
res = self.repo_install(repo_url, to_path, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
if res.result:
|
||||
if version_spec == 'unknown':
|
||||
self.unknown_active_nodes[node_id] = repo_url, to_path
|
||||
elif version_spec == 'nightly':
|
||||
cnr_utils.generate_cnr_id(to_path, node_id)
|
||||
self.active_nodes[node_id] = 'nightly', to_path
|
||||
else:
|
||||
return res
|
||||
|
||||
return res.with_target(version_spec)
|
||||
# Check before changing the existing pack, then reuse this response.
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return ManagedResult('install-cnr').fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return ManagedResult('install-cnr').fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
if self.is_enabled(node_id, 'nightly'):
|
||||
# disable nightly nodes
|
||||
@@ -1538,17 +1463,89 @@ class UnifiedManager:
|
||||
if self.is_disabled(node_id, "cnr"):
|
||||
# enable and switch version if cnr is disabled (not specified version)
|
||||
self.unified_enable(node_id, "cnr")
|
||||
return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
if self.is_enabled(node_id, "cnr"):
|
||||
return self.cnr_switch_version(node_id, version_spec, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
return self._cnr_switch_version(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
|
||||
res = self.cnr_install(node_id, version_spec, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
res = self._cnr_install(node_id, node_info, instant_execution, no_deps, return_postinstall)
|
||||
if res.result:
|
||||
self.active_nodes[node_id] = version_spec, res.to_path
|
||||
|
||||
return res
|
||||
|
||||
async def _get_git_install_url(self, node_id, version_spec, channel, mode):
|
||||
custom_nodes = await self.get_custom_nodes(channel, mode)
|
||||
node = custom_nodes.get(node_id)
|
||||
if node is not None:
|
||||
return node['files'][0] if version_spec == 'unknown' else node['repository']
|
||||
if version_spec == 'nightly':
|
||||
cnr = self.cnr_map.get(node_id)
|
||||
if cnr is not None and cnr.get('repository'):
|
||||
return cnr['repository']
|
||||
raise LookupError(f"Node '{node_id}@{version_spec}' not found in [{channel}, {mode}]")
|
||||
|
||||
def _install_git(self, node_id, version_spec, repo_url, instant_execution=False, no_deps=False, return_postinstall=False):
|
||||
to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), node_id))
|
||||
|
||||
if version_spec == 'nightly':
|
||||
# disable cnr nodes
|
||||
if self.is_enabled(node_id, 'cnr'):
|
||||
self.unified_disable(node_id, False)
|
||||
|
||||
# use `repo name` as a dir name instead of `cnr id` if system added nodepack (i.e. publisher is null)
|
||||
cnr = self.cnr_map.get(node_id)
|
||||
|
||||
if cnr is not None and cnr.get('publisher') is None:
|
||||
repo_name = os.path.basename(git_utils.normalize_url(repo_url))
|
||||
to_path = os.path.abspath(os.path.join(get_default_custom_nodes_path(), repo_name))
|
||||
|
||||
res = self.repo_install(repo_url, to_path, instant_execution=instant_execution, no_deps=no_deps, return_postinstall=return_postinstall)
|
||||
if res.result:
|
||||
if version_spec == 'unknown':
|
||||
self.unknown_active_nodes[node_id] = repo_url, to_path
|
||||
elif version_spec == 'nightly':
|
||||
cnr_utils.generate_cnr_id(to_path, node_id)
|
||||
self.active_nodes[node_id] = 'nightly', to_path
|
||||
else:
|
||||
return res
|
||||
|
||||
return res.with_target(version_spec)
|
||||
|
||||
async def reinstall_by_id(self, node_id, version_spec, channel=None, mode=None):
|
||||
if 'comfyui-manager' in node_id.lower():
|
||||
return ManagedResult('skip').fail(f"ignored: installing '{node_id}'")
|
||||
|
||||
if version_spec in ('unknown', 'nightly'):
|
||||
try:
|
||||
repo_url = await self._get_git_install_url(node_id, version_spec, channel, mode)
|
||||
except InvalidChannel as exc:
|
||||
return ManagedResult('fail').fail(f'Invalid channel is used: {exc.channel}')
|
||||
except LookupError as exc:
|
||||
return ManagedResult('install').fail(str(exc))
|
||||
else:
|
||||
try:
|
||||
node_info = self._get_cnr_install_info(node_id, version_spec)
|
||||
except PermissionError as exc:
|
||||
return ManagedResult('install-cnr').fail(str(exc))
|
||||
if node_info is None or not node_info.download_url:
|
||||
return ManagedResult('install-cnr').fail(f'not available node: {node_id}@{version_spec}')
|
||||
|
||||
removed = self.unified_uninstall(node_id, version_spec == 'unknown')
|
||||
if not removed.result:
|
||||
return removed
|
||||
|
||||
for item in removed.items:
|
||||
path = item if version_spec == 'unknown' else item[1]
|
||||
self.processed_install.discard(os.path.join(path, 'install.py'))
|
||||
if version_spec in ('unknown', 'nightly'):
|
||||
return self._install_git(node_id, version_spec, repo_url)
|
||||
|
||||
result = self._cnr_install(node_id, node_info)
|
||||
if result.result:
|
||||
self.active_nodes[node_id] = node_info.version, result.to_path
|
||||
return result
|
||||
|
||||
|
||||
unified_manager = UnifiedManager()
|
||||
|
||||
@@ -1659,6 +1656,14 @@ class ManagerFuncs:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def is_flagged_install_allowed(self, node_id):
|
||||
# Restore children use the parent's permission and whitelist directory,
|
||||
# even if the CLI resolves a different user directory.
|
||||
return manager_security.is_cnr_install_allowed(
|
||||
'NodeVersionStatusFlagged', os.environ.get('_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED', 'true') == 'true',
|
||||
listen_address=None, node_id=node_id,
|
||||
manager_files_path=os.environ.get('_COMFYUI_MANAGER_CNR_WHITELIST_DIR'))
|
||||
|
||||
def run_script(self, cmd, cwd='.'):
|
||||
if len(cmd) > 0 and cmd[0].startswith("#"):
|
||||
print(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
|
||||
@@ -1672,39 +1677,31 @@ class ManagerFuncs:
|
||||
manager_funcs = ManagerFuncs()
|
||||
|
||||
|
||||
# Settings owned by this server; other keys and sections are preserved.
|
||||
WRITTEN_CONFIG_KEYS = (
|
||||
'git_exe',
|
||||
'use_uv',
|
||||
'channel_url',
|
||||
'share_option',
|
||||
'bypass_ssl',
|
||||
'file_logging',
|
||||
'update_policy',
|
||||
'windows_selector_event_loop_policy',
|
||||
'model_download_by_agent',
|
||||
'downgrade_blacklist',
|
||||
'security_level',
|
||||
'always_lazy_install',
|
||||
'network_mode',
|
||||
'db_mode',
|
||||
'allow_git_url_install',
|
||||
'allow_pip_install',
|
||||
'allow_flagged_nodepack_install',
|
||||
)
|
||||
|
||||
|
||||
def write_config():
|
||||
config = configparser.ConfigParser(strict=False)
|
||||
|
||||
config['default'] = {
|
||||
'git_exe': get_config()['git_exe'],
|
||||
'use_uv': get_config()['use_uv'],
|
||||
'channel_url': get_config()['channel_url'],
|
||||
'share_option': get_config()['share_option'],
|
||||
'bypass_ssl': get_config()['bypass_ssl'],
|
||||
"file_logging": get_config()['file_logging'],
|
||||
'update_policy': get_config()['update_policy'],
|
||||
'windows_selector_event_loop_policy': get_config()['windows_selector_event_loop_policy'],
|
||||
'model_download_by_agent': get_config()['model_download_by_agent'],
|
||||
'downgrade_blacklist': get_config()['downgrade_blacklist'],
|
||||
'security_level': get_config()['security_level'],
|
||||
'always_lazy_install': get_config()['always_lazy_install'],
|
||||
'network_mode': get_config()['network_mode'],
|
||||
'db_mode': get_config()['db_mode'],
|
||||
'allow_git_url_install': get_config()['allow_git_url_install'],
|
||||
'allow_pip_install': get_config()['allow_pip_install'],
|
||||
}
|
||||
|
||||
# Sanitize all string values to prevent CRLF injection attacks
|
||||
for key, value in config['default'].items():
|
||||
if isinstance(value, str):
|
||||
config['default'][key] = value.replace('\r', '').replace('\n', '').replace('\x00', '')
|
||||
|
||||
directory = os.path.dirname(context.manager_config_path)
|
||||
if not os.path.exists(directory):
|
||||
os.makedirs(directory)
|
||||
|
||||
with open(context.manager_config_path, 'w') as configfile:
|
||||
config.write(configfile)
|
||||
"""Persist changed settings through the shared writer."""
|
||||
write_config_merged(context.manager_config_path, get_config(), WRITTEN_CONFIG_KEYS)
|
||||
|
||||
|
||||
def read_config():
|
||||
@@ -1738,6 +1735,7 @@ def read_config():
|
||||
'db_mode': default_conf.get('db_mode', DBMode.CACHE.value).lower(),
|
||||
'allow_git_url_install': get_bool('allow_git_url_install', False),
|
||||
'allow_pip_install': get_bool('allow_pip_install', False),
|
||||
'allow_flagged_nodepack_install': get_bool('allow_flagged_nodepack_install', False),
|
||||
}
|
||||
|
||||
except Exception:
|
||||
@@ -1763,6 +1761,7 @@ def read_config():
|
||||
'db_mode': DBMode.CACHE.value,
|
||||
'allow_git_url_install': False,
|
||||
'allow_pip_install': False,
|
||||
'allow_flagged_nodepack_install': False,
|
||||
}
|
||||
|
||||
|
||||
@@ -1770,7 +1769,8 @@ def get_config():
|
||||
global cached_config
|
||||
|
||||
if cached_config is None:
|
||||
cached_config = read_config()
|
||||
# Start tracking changes after the startup configuration is loaded.
|
||||
cached_config = DirtyTrackingConfig(read_config())
|
||||
if cached_config['http_channel_enabled']:
|
||||
print("[ComfyUI-Manager] Warning: http channel enabled, make sure server in secure env")
|
||||
|
||||
@@ -1881,14 +1881,10 @@ def try_install_script(url, repo_path, install_cmd, instant_execution=False):
|
||||
reserve_script(repo_path, install_cmd)
|
||||
return True
|
||||
else:
|
||||
if len(install_cmd) == 5 and install_cmd[2:4] == ['pip', 'install']:
|
||||
if is_blacklisted(install_cmd[4]):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[4]}'")
|
||||
return True
|
||||
elif len(install_cmd) == 6 and install_cmd[3:5] == ['pip', 'install']: # uv mode
|
||||
if is_blacklisted(install_cmd[5]):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{install_cmd[5]}'")
|
||||
return True
|
||||
requirement = manager_util.pip_install_requirement(install_cmd)
|
||||
if requirement is not None and is_blacklisted(requirement):
|
||||
print(f"[ComfyUI-Manager] skip black listed pip installation: '{requirement}'")
|
||||
return True
|
||||
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {install_cmd}")
|
||||
code = manager_funcs.run_script(install_cmd, cwd=repo_path)
|
||||
@@ -2334,9 +2330,7 @@ async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
json_obj = await manager_util.get_data(cache_uri)
|
||||
else:
|
||||
json_obj = await manager_util.get_data(uri)
|
||||
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)
|
||||
manager_util.write_cache_file(cache_uri, json_obj)
|
||||
except Exception as e:
|
||||
print(f"[ComfyUI-Manager] Due to a network error, switching to local mode.\n=> {filename} @ {channel_url}/{mode}\n=> {e}")
|
||||
uri = os.path.join(manager_util.comfyui_manager_path, filename)
|
||||
@@ -3182,7 +3176,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
todo_disable.append(k)
|
||||
else:
|
||||
cnr_ver = cnr_info[k]
|
||||
if v[1] != cnr_ver:
|
||||
if v[0] != cnr_ver:
|
||||
todo_checkout.append((k, cnr_ver))
|
||||
else:
|
||||
skip_node_packs.append(k)
|
||||
@@ -3199,15 +3193,20 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
skip_node_packs.append(f"{x[0]}@{x[1]}")
|
||||
elif not ps.result:
|
||||
failed.append(f"{x[0]}@{x[1]}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
# install listed cnr nodes
|
||||
# Do not retry processed switches as fresh installs.
|
||||
checked_cnr = {node_id for node_id, _ in todo_checkout}
|
||||
for k, v in cnr_info.items():
|
||||
if 'comfyui-manager' in k:
|
||||
if 'comfyui-manager' in k or k in checked_cnr:
|
||||
continue
|
||||
|
||||
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
|
||||
if ps.action == 'install-cnr' and ps.result:
|
||||
installed_node_packs.append(f"{k}@{v}")
|
||||
elif not ps.result:
|
||||
failed.append(f"{k}@{v}")
|
||||
logging.error(ps.msg)
|
||||
|
||||
if ps is not None and ps.result:
|
||||
if hasattr(ps, 'postinstall'):
|
||||
@@ -3225,6 +3224,10 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
|
||||
if 'comfyui-manager' in k.lower():
|
||||
continue
|
||||
|
||||
# Snapshots saved at a detached HEAD used to keep the newline that follows the hash.
|
||||
if isinstance(v.get('hash'), str):
|
||||
v['hash'] = v['hash'].strip()
|
||||
|
||||
norm_k = git_utils.normalize_url(k)
|
||||
git_info[norm_k] = v
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import asyncio
|
||||
from collections import deque
|
||||
|
||||
from . import manager_core as core
|
||||
from . import html_utils
|
||||
from ..common import manager_util
|
||||
from ..common import cm_global
|
||||
from ..common import manager_downloader
|
||||
@@ -37,14 +38,15 @@ logging.info("[ComfyUI-Manager] network_mode: " + network_mode_description)
|
||||
comfy_ui_hash = "-"
|
||||
comfyui_tag = None
|
||||
|
||||
SECURITY_MESSAGE_MIDDLE = "ERROR: To use this action, a security_level of `normal or below` is required. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_MIDDLE_P = "ERROR: To use this action, security_level must be `normal or below`, and network_mode must be set to `personal_cloud`. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_HIGH_P = "ERROR: To use this action, '--listen' must be set to a local IP and security_level must be 'normal-' or lower. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
|
||||
SECURITY_MESSAGE_FLAG_GIT_URL = "ERROR: This action requires 'allow_git_url_install = true' in config.ini ([default] section). This setting is independent of security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_FLAG_PIP = "ERROR: This action requires 'allow_pip_install = true' in config.ini ([default] section). This setting is independent of security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
from ..common.security_messages import (
|
||||
SECURITY_MESSAGE_MIDDLE,
|
||||
SECURITY_MESSAGE_MIDDLE_P,
|
||||
SECURITY_MESSAGE_HIGH_P,
|
||||
SECURITY_MESSAGE_GENERAL,
|
||||
SECURITY_MESSAGE_NORMAL_MINUS_MODEL,
|
||||
)
|
||||
SECURITY_MESSAGE_FLAG_GIT_URL = "ERROR: This action requires BOTH: (1) 'allow_git_url_install = true' in config.ini ([default] section), AND (2) a network position the Manager treats as private - either ComfyUI launched with a loopback '--listen' (any 127.x.x.x address, or ::1), OR 'network_mode = personal_cloud' in config.ini. Currently listening on {listen} with network_mode = {network_mode}. Both values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again. Both are independent of security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
SECURITY_MESSAGE_FLAG_PIP = "ERROR: This action requires BOTH: (1) 'allow_pip_install = true' in config.ini ([default] section), AND (2) a network position the Manager treats as private - either ComfyUI launched with a loopback '--listen' (any 127.x.x.x address, or ::1), OR 'network_mode = personal_cloud' in config.ini. Currently listening on {listen} with network_mode = {network_mode}. Both values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again. Both are independent of security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
|
||||
|
||||
routes = PromptServer.instance.routes
|
||||
|
||||
@@ -160,6 +162,11 @@ async def get_risky_level(files, pip_packages):
|
||||
|
||||
|
||||
class ManagerFuncsInComfyUI(core.ManagerFuncs):
|
||||
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("#"):
|
||||
logging.error(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
|
||||
@@ -259,7 +266,6 @@ print_comfyui_version()
|
||||
core.check_invalid_nodes()
|
||||
|
||||
|
||||
|
||||
def setup_environment():
|
||||
git_exe = core.get_config()['git_exe']
|
||||
|
||||
@@ -467,7 +473,7 @@ async def task_worker():
|
||||
|
||||
await core.unified_manager.reload('cache')
|
||||
|
||||
async def do_install(item) -> str:
|
||||
async def do_install(item, operation) -> str:
|
||||
ui_id, node_spec_str, channel, mode, skip_post_install = item
|
||||
|
||||
try:
|
||||
@@ -477,7 +483,15 @@ async def task_worker():
|
||||
return f"Cannot resolve install target: '{node_spec_str}'"
|
||||
|
||||
node_name, version_spec, is_specified = node_spec
|
||||
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
|
||||
# Check the resolved target, including requests with misleading metadata.
|
||||
level = 'middle+' if version_spec in ('nightly', 'unknown') else 'middle'
|
||||
if not is_allowed_security_level(level):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P if level == 'middle+' else SECURITY_MESSAGE_MIDDLE)
|
||||
return 'Installation blocked by security policy'
|
||||
if operation == 'reinstall':
|
||||
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', 'enable', 'install-git', 'install-cnr', 'switch-cnr']:
|
||||
logging.error(f"[ComfyUI-Manager] Installation failed:\n{res.msg}")
|
||||
@@ -529,7 +543,7 @@ async def task_worker():
|
||||
base_res['msg'] = 'success'
|
||||
return base_res
|
||||
|
||||
base_res['msg'] = f"An error occurred while updating '{node_name}'."
|
||||
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})")
|
||||
return base_res
|
||||
except Exception:
|
||||
@@ -704,8 +718,8 @@ async def task_worker():
|
||||
tasks_in_progress.add((kind, item[0]))
|
||||
|
||||
try:
|
||||
if kind == 'install':
|
||||
msg = await do_install(item)
|
||||
if kind in ('install', 'reinstall'):
|
||||
msg = await do_install(item, kind)
|
||||
elif kind == 'enable':
|
||||
msg = await do_enable(item)
|
||||
elif kind == 'install-model':
|
||||
@@ -769,19 +783,9 @@ async def queue_batch(request):
|
||||
if k == 'update_all':
|
||||
await _update_all({'mode': v})
|
||||
|
||||
elif k == 'reinstall':
|
||||
elif k in ('install', 'reinstall'):
|
||||
for x in v:
|
||||
res = await _uninstall_custom_node(x)
|
||||
if res.status != 200:
|
||||
failed.add(x['id'])
|
||||
else:
|
||||
res = await _install_custom_node(x)
|
||||
if res.status != 200:
|
||||
failed.add(x['id'])
|
||||
|
||||
elif k == 'install':
|
||||
for x in v:
|
||||
res = await _install_custom_node(x)
|
||||
res = await _queue_node_install(x, k)
|
||||
if res.status != 200:
|
||||
failed.add(x['id'])
|
||||
|
||||
@@ -974,14 +978,22 @@ async def _update_all(json_data):
|
||||
|
||||
|
||||
def convert_markdown_to_html(input_text):
|
||||
"""Parse source markdown, escaping text and URLs at their HTML boundaries."""
|
||||
pattern_a = re.compile(r'\[a/([^]]+)]\(([^)]+)\)')
|
||||
pattern_w = re.compile(r'\[w/([^]]+)]')
|
||||
pattern_i = re.compile(r'\[i/([^]]+)]')
|
||||
pattern_bold = re.compile(r'\*\*([^*]+)\*\*')
|
||||
pattern_white = re.compile(r'%%([^*]+)%%')
|
||||
|
||||
# Format link labels separately from URLs; escape URLs when inserted.
|
||||
hrefs = []
|
||||
|
||||
def replace_a(match):
|
||||
return f"<a href='{match.group(2)}' target='blank'>{match.group(1)}</a>"
|
||||
# Entities written in the source URL (e.g. &) retain their meaning.
|
||||
url = html_utils.unescape_html_entities(match.group(2))
|
||||
hrefs.append(html_utils.sanitize_url(url))
|
||||
text = html_utils.escape_html_text(match.group(1))
|
||||
return f"<a href='\x00H{len(hrefs) - 1}\x00' target='_blank' rel='noopener noreferrer'>{text}</a>"
|
||||
|
||||
def replace_w(match):
|
||||
return f"<p class='cm-warn-note'>{match.group(1)}</p>"
|
||||
@@ -995,20 +1007,35 @@ def convert_markdown_to_html(input_text):
|
||||
def replace_white(match):
|
||||
return f"<font color='white'>{match.group(1)}</font>"
|
||||
|
||||
input_text = input_text.replace('\\[', '[').replace('\\]', ']').replace('<', '<').replace('>', '>')
|
||||
# NUL dropped first so the input cannot forge the href placeholders.
|
||||
input_text = input_text.replace('\x00', '')
|
||||
input_text = input_text.replace('\\[', '[').replace('\\]', ']')
|
||||
|
||||
result_text = re.sub(pattern_a, replace_a, input_text)
|
||||
# Parse links before escaping prose, so generated text entities never enter URLs.
|
||||
parts = []
|
||||
start = 0
|
||||
for match in pattern_a.finditer(input_text):
|
||||
parts.append(manager_util.sanitize_tag(input_text[start:match.start()]))
|
||||
parts.append(replace_a(match))
|
||||
start = match.end()
|
||||
parts.append(manager_util.sanitize_tag(input_text[start:]))
|
||||
result_text = ''.join(parts)
|
||||
result_text = re.sub(pattern_w, replace_w, result_text)
|
||||
result_text = re.sub(pattern_i, replace_i, result_text)
|
||||
result_text = re.sub(pattern_bold, replace_bold, result_text)
|
||||
result_text = re.sub(pattern_white, replace_white, result_text)
|
||||
result_text = result_text.replace("\n", "<BR>")
|
||||
|
||||
return result_text.replace("\n", "<BR>")
|
||||
return re.sub(
|
||||
r'\x00H(\d+)\x00',
|
||||
lambda m: html_utils.escape_html_attribute(hrefs[int(m.group(1))]),
|
||||
result_text,
|
||||
)
|
||||
|
||||
|
||||
def populate_markdown(x):
|
||||
if 'description' in x:
|
||||
x['description'] = convert_markdown_to_html(manager_util.sanitize_tag(x['description']))
|
||||
x['description'] = convert_markdown_to_html(x['description'])
|
||||
|
||||
if 'name' in x:
|
||||
x['name'] = manager_util.sanitize_tag(x['name'])
|
||||
@@ -1396,7 +1423,6 @@ async def import_fail_info_bulk(request):
|
||||
return web.Response(status=500, text="Internal server error")
|
||||
|
||||
|
||||
|
||||
@routes.post("/v2/manager/queue/reset")
|
||||
async def reset_queue(request):
|
||||
rejection = manager_security.reject_simple_form_post(request)
|
||||
@@ -1412,7 +1438,6 @@ async def reset_queue(request):
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
|
||||
@routes.get("/v2/manager/queue/status")
|
||||
async def queue_count(request):
|
||||
global task_queue
|
||||
@@ -1437,15 +1462,15 @@ async def queue_count(request):
|
||||
'is_processing': is_processing})
|
||||
|
||||
|
||||
async def _install_custom_node(json_data):
|
||||
if not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
async def _queue_node_install(json_data, operation):
|
||||
if not is_allowed_security_level('middle'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
|
||||
# non-nightly cnr is safe
|
||||
# CNR versions are checked for flagged status by the install worker.
|
||||
risky_level = None
|
||||
cnr_id = json_data.get('id')
|
||||
skip_post_install = json_data.get('skip_post_install')
|
||||
skip_post_install = False if operation == 'reinstall' else json_data.get('skip_post_install')
|
||||
|
||||
git_url = None
|
||||
|
||||
@@ -1487,20 +1512,22 @@ async def _install_custom_node(json_data):
|
||||
else:
|
||||
return web.Response(status=404, text=f"Following node pack doesn't provide `nightly` version: ${git_url}")
|
||||
|
||||
# goal265 S-C (middle+ entry gate above UNCHANGED): unknown git URL ('high+')
|
||||
# -> dedicated-flag full predicate replaces the security_level check (spec §1.2);
|
||||
# unknown pip ('block') -> unconditional deny via is_allowed_security_level (Q1).
|
||||
# Flag-deny PRESERVES today's 404 response shape at this position (R1).
|
||||
if risky_level != 'low' and not is_allowed_security_level('middle+'):
|
||||
logging.error(SECURITY_MESSAGE_MIDDLE_P)
|
||||
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
|
||||
|
||||
# Unknown Git installs also require the dedicated flag; preserve the 404 response.
|
||||
if risky_level == 'high+':
|
||||
if not _dedicated_install_allowed('allow_git_url_install'):
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL)
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(
|
||||
listen=args.listen, network_mode=core.get_config()['network_mode']))
|
||||
return web.Response(status=404, text="A security error has occurred. Please check the terminal logs")
|
||||
elif not is_allowed_security_level(risky_level):
|
||||
logging.error(SECURITY_MESSAGE_GENERAL)
|
||||
return web.Response(status=404, text="A security error has occurred. Please check the terminal logs")
|
||||
|
||||
install_item = json_data.get('ui_id'), node_spec_str, json_data['channel'], json_data['mode'], skip_post_install
|
||||
temp_queue_batch.append(("install", install_item))
|
||||
temp_queue_batch.append((operation, install_item))
|
||||
|
||||
return web.Response(status=200)
|
||||
|
||||
@@ -1551,8 +1578,10 @@ async def _fix_custom_node(json_data):
|
||||
async def install_custom_node_git_url(request):
|
||||
# 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)
|
||||
return web.Response(status=403)
|
||||
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(
|
||||
listen=args.listen, network_mode=core.get_config()['network_mode']))
|
||||
# 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()
|
||||
res = await core.gitclone_install(url)
|
||||
@@ -1572,8 +1601,10 @@ async def install_custom_node_git_url(request):
|
||||
async def install_custom_node_pip(request):
|
||||
# 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)
|
||||
return web.Response(status=403)
|
||||
logging.error(SECURITY_MESSAGE_FLAG_PIP.format(
|
||||
listen=args.listen, network_mode=core.get_config()['network_mode']))
|
||||
# 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()
|
||||
core.pip_install(packages.split(' '))
|
||||
@@ -1682,13 +1713,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
|
||||
@@ -1815,64 +1846,55 @@ async def set_channel_url(request):
|
||||
return web.Response(status=400, text='Invalid request')
|
||||
|
||||
|
||||
def add_target_blank(html_text):
|
||||
pattern = r'(<a\s+href="[^"]*"\s*[^>]*)(>)'
|
||||
|
||||
def add_target(match):
|
||||
if 'target=' not in match.group(1):
|
||||
return match.group(1) + ' target="_blank"' + match.group(2)
|
||||
return match.group(0)
|
||||
|
||||
modified_html = re.sub(pattern, add_target, html_text)
|
||||
|
||||
return modified_html
|
||||
|
||||
|
||||
@routes.get("/v2/manager/notice")
|
||||
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=aiohttp.TCPConnector(verify_ssl=not manager_util.bypass_ssl)) 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:
|
||||
markdown_content = 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}"
|
||||
|
||||
markdown_content = add_target_blank(markdown_content)
|
||||
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
|
||||
@@ -1900,17 +1922,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)
|
||||
|
||||
@@ -1958,10 +1970,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()
|
||||
|
||||
@@ -4,9 +4,7 @@ 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,49 +20,6 @@ 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()
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/share_option")
|
||||
async def share_option(request):
|
||||
if "value" in request.rel_url.query:
|
||||
@@ -76,17 +31,6 @@ async def share_option(request):
|
||||
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 get_matrix_auth():
|
||||
if not os.path.exists(os.path.join(context.manager_files_path, "matrix_auth")):
|
||||
return None
|
||||
@@ -105,19 +49,6 @@ 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
|
||||
@@ -134,24 +65,6 @@ def set_youml_settings(settings):
|
||||
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...")
|
||||
@@ -176,32 +89,6 @@ async def api_set_youml_settings(request):
|
||||
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))
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
|
||||
async def get_matrix_dep_status(request):
|
||||
if matrix_nio_is_available:
|
||||
@@ -218,35 +105,23 @@ def set_matrix_auth(json_data):
|
||||
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)
|
||||
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
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 +150,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'
|
||||
@@ -442,9 +258,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")
|
||||
@@ -280,7 +282,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
|
||||
@@ -492,47 +523,22 @@ def is_installed(name):
|
||||
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 pkg_name is None or extras:
|
||||
return False # not a plain named requirement, or 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
|
||||
|
||||
pkg = manager_util.get_installed_packages().get(name.lower())
|
||||
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
|
||||
|
||||
@@ -570,6 +576,13 @@ if os.path.exists(restore_snapshot_path):
|
||||
if 'COMFYUI_PATH' not in new_env:
|
||||
new_env['COMFYUI_PATH'] = os.path.dirname(folder_paths.__file__)
|
||||
|
||||
from comfy.cli_args import args
|
||||
|
||||
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()
|
||||
new_env['_COMFYUI_MANAGER_CNR_WHITELIST_DIR'] = manager_files_path
|
||||
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path]
|
||||
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
|
||||
|
||||
@@ -619,9 +632,20 @@ def execute_lazy_install_script(repo_path, executable):
|
||||
process_wrap(install_cmd, repo_path, env=new_env)
|
||||
|
||||
|
||||
def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom_nodes_path):
|
||||
def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom_nodes_path, status=''):
|
||||
import uuid
|
||||
import shutil
|
||||
from comfy.cli_args import args
|
||||
|
||||
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
|
||||
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(manager_security.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
|
||||
return False
|
||||
|
||||
# 1. download
|
||||
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
|
||||
@@ -669,6 +693,8 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
|
||||
with open(tracking_info_file, "w", encoding='utf-8') as file:
|
||||
file.write('\n'.join(list(extracted)))
|
||||
|
||||
return True
|
||||
|
||||
|
||||
script_executed = False
|
||||
|
||||
@@ -724,8 +750,9 @@ def execute_startup_script():
|
||||
execute_lazy_install_script(script[0], script[2])
|
||||
|
||||
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
|
||||
execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6])
|
||||
execute_lazy_install_script(script[3], script[7])
|
||||
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])
|
||||
|
||||
elif script[1] == "#LAZY-DELETE-NODEPACK":
|
||||
execute_lazy_delete(script[2])
|
||||
@@ -734,7 +761,8 @@ def execute_startup_script():
|
||||
if script[1] == "#FORCE":
|
||||
del script[1]
|
||||
else:
|
||||
if 'pip' in script[1:] and 'install' in script[1:] and is_installed(script[-1]):
|
||||
requirement = manager_util.pip_install_requirement(script[1:])
|
||||
if requirement is not None and is_installed(requirement):
|
||||
continue
|
||||
|
||||
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
|
||||
@@ -816,15 +844,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")
|
||||
|
||||
@@ -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/,
|
||||
@@ -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,41 +294,28 @@ 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.
|
||||
@@ -621,7 +614,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 +689,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
|
||||
|
||||
@@ -783,20 +776,24 @@ 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)
|
||||
|
||||
|
||||
@@ -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/))
|
||||
|
||||
|
||||
+5
-16
@@ -5,8 +5,8 @@ build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "comfyui-manager"
|
||||
license = { text = "GPL-3.0-only" }
|
||||
version = "4.2.2"
|
||||
requires-python = ">= 3.9"
|
||||
version = "4.4"
|
||||
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"]
|
||||
@@ -35,7 +35,9 @@ dependencies = [
|
||||
"typing-extensions",
|
||||
"toml",
|
||||
"uv",
|
||||
"chardet"
|
||||
"chardet",
|
||||
"packaging",
|
||||
"nh3>=0.3.7"
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -50,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)
|
||||
]
|
||||
|
||||
@@ -10,3 +10,5 @@ typing-extensions
|
||||
toml
|
||||
uv
|
||||
chardet
|
||||
packaging
|
||||
nh3>=0.3.7
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -0,0 +1,666 @@
|
||||
"""Real ComfyUI HTTP/queue/install tests with a local CNR service and harmless ZIPs.
|
||||
|
||||
Run with E2E_ROOT pointing to the existing ComfyUI + venv fixture. Each server
|
||||
uses an isolated base directory; no installed nodes or user config are changed.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import configparser
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import zipfile
|
||||
from contextlib import contextmanager
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
|
||||
E2E_ROOT = Path(os.environ.get('E2E_ROOT', '/nonexistent'))
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not (E2E_ROOT / 'venv/bin/python').is_file(), reason='E2E_ROOT is required',
|
||||
)
|
||||
PACKS = ['fixture-active', 'fixture-flagged', 'fixture-pending', 'fixture-banned',
|
||||
'fixture-latest', 'fixture-switch', 'fixture-update', 'fixture-reinstall', 'fixture-snapshot']
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def registry():
|
||||
calls = []
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
parsed = urlparse(self.path)
|
||||
calls.append(parsed.path + ('?' + parsed.query if parsed.query else ''))
|
||||
parts = parsed.path.strip('/').split('/')
|
||||
version = parse_qs(parsed.query).get('version', ['2.0.0'])[0]
|
||||
node = parts[1] if len(parts) > 1 else ''
|
||||
base = f'http://127.0.0.1:{self.server.server_port}'
|
||||
|
||||
def metadata(node, version):
|
||||
status = {'1.0.0': 'Active', '1.1.0': 'Active', '2.0.0': 'Flagged', '3.0.0': 'Pending'}[version]
|
||||
return {'id': f'{node}-{version}', 'node_id': node, 'version': version,
|
||||
'status': 'NodeVersionStatus' + status, 'dependencies': [],
|
||||
'downloadUrl': f'{base}/zip/{node}/{version}'}
|
||||
|
||||
status = 200
|
||||
if parts[0] == 'zip':
|
||||
node, version = parts[1:]
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, 'w') as z:
|
||||
z.writestr('__init__.py', 'NODE_CLASS_MAPPINGS = {}\n')
|
||||
z.writestr('pyproject.toml', f'[project]\nname = "{node}"\nversion = "{version}"\n')
|
||||
z.writestr('install.py', 'from pathlib import Path\n'
|
||||
f'Path("installed.txt").write_text("{version}")\n')
|
||||
body = archive.getvalue()
|
||||
elif parsed.path == '/nodes':
|
||||
body = json.dumps({'nodes': [
|
||||
{'id': name, 'name': name, 'description': '', 'status': 'NodeStatusActive',
|
||||
'repository': f'https://example.invalid/{name}',
|
||||
'publisher': {'id': 'fixture', 'name': 'Fixture'},
|
||||
'latest_version': metadata(name, '2.0.0')}
|
||||
for name in PACKS], 'totalPages': 1}).encode()
|
||||
elif len(parts) == 3 and parts[0] == 'nodes' and parts[2] == 'install':
|
||||
if node == 'fixture-banned':
|
||||
status, body = 404, b'{"message":"Not found"}'
|
||||
else:
|
||||
body = json.dumps(metadata(node, version)).encode()
|
||||
else:
|
||||
status, body = 404, b'{}'
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
self.send_header('Content-Type', 'application/zip' if parts[0] == 'zip' else 'application/json')
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
yield SimpleNamespace(url=f'http://127.0.0.1:{server.server_port}', calls=calls)
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
|
||||
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(os.environ['CM_E2E_CATALOG_URL']) as response:
|
||||
manager_util.save_to_cache(cnr_utils.base_url + '/nodes', json.load(response))
|
||||
'''
|
||||
BOOTSTRAP = '''
|
||||
import os, runpy, sys
|
||||
sys.argv = [os.environ['CM_E2E_MAIN'], *sys.argv[1:]]
|
||||
import comfy.options
|
||||
comfy.options.enable_args_parsing()
|
||||
''' + REGISTRY_BOOTSTRAP + "\nrunpy.run_path(sys.argv[0], run_name='__main__')\n"
|
||||
RESTORE_BOOTSTRAP = '''
|
||||
import os
|
||||
from comfy.cli_args import args
|
||||
args.base_directory = os.environ['CM_E2E_BASE']
|
||||
''' + REGISTRY_BOOTSTRAP + '''
|
||||
from comfyui_manager.legacy import manager_core as core
|
||||
core.unified_manager.custom_node_map_cache[(core.normalize_channel('default'), 'cache')] = core.NormalizedKeyDict()
|
||||
'''
|
||||
|
||||
|
||||
def prepare_environment(root, override, security, registry):
|
||||
(root / 'custom_nodes').mkdir(exist_ok=True)
|
||||
config_dir = root / 'user/__manager'
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
(config_dir / 'config.ini').write_text(
|
||||
'[default]\nnetwork_mode = offline\nuse_uv = false\n'
|
||||
f'security_level = {security}\nallow_flagged_nodepack_install = {override}\n'
|
||||
)
|
||||
# The real restore subprocess inherits the same isolated Registry and paths.
|
||||
(root / 'sitecustomize.py').write_text(
|
||||
"import sys\nif sys.argv[0] == '-m' and 'cm_cli' in sys.orig_argv:\n"
|
||||
+ '\n'.join(' ' + line for line in RESTORE_BOOTSTRAP.splitlines())
|
||||
)
|
||||
env = dict(os.environ, PYTHONUNBUFFERED='1',
|
||||
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_CATALOG_URL=getattr(registry, 'catalog_url', registry.url + '/nodes'))
|
||||
return env
|
||||
|
||||
|
||||
@contextmanager
|
||||
def running_server(root, tree, listen, override, security, registry):
|
||||
env = prepare_environment(root, override, security, registry)
|
||||
with socket.socket() as sock:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
port = sock.getsockname()[1]
|
||||
base = f'http://127.0.0.1:{port}'
|
||||
command = [str(E2E_ROOT / 'venv/bin/python'), '-c', BOOTSTRAP,
|
||||
'--cpu', '--enable-manager', '--base-directory', str(root),
|
||||
'--listen', listen, '--port', str(port),
|
||||
'--database-url', f'sqlite:///{root / "comfyui.db"}']
|
||||
if tree == 'legacy':
|
||||
command.append('--enable-manager-legacy-ui')
|
||||
log_path = root / 'server.log'
|
||||
with log_path.open('w') as log:
|
||||
process = subprocess.Popen(command, env=env, cwd=E2E_ROOT / 'comfyui', stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, log_path.read_text()
|
||||
try:
|
||||
if requests.get(base + '/system_stats', timeout=1).status_code == 200:
|
||||
break
|
||||
except requests.RequestException:
|
||||
pass
|
||||
time.sleep(.2)
|
||||
else:
|
||||
pytest.fail('ComfyUI did not start:\n' + log_path.read_text())
|
||||
yield SimpleNamespace(root=root, tree=tree, base=base, listen=listen,
|
||||
override=override, security=security, registry=registry,
|
||||
process=process, command=command, env=env)
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
@pytest.fixture(scope='module', params=[
|
||||
(tree, listen, override, security)
|
||||
for tree in ('legacy', 'glob')
|
||||
for listen, override, security in [
|
||||
('127.0.0.1', False, 'normal'),
|
||||
('0.0.0.0', False, 'normal'),
|
||||
('0.0.0.0', True, 'normal'),
|
||||
('0.0.0.0', True, 'strong'),
|
||||
('127.0.0.1', False, 'strong'),
|
||||
]
|
||||
], ids=lambda row: '-'.join(map(str, row)))
|
||||
def comfy_server(request, tmp_path_factory, registry):
|
||||
tree, listen, override, security = request.param
|
||||
root = tmp_path_factory.mktemp('flagged-' + tree)
|
||||
with running_server(root, tree, listen, override, security, registry) as server:
|
||||
yield server
|
||||
|
||||
|
||||
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': repository}
|
||||
if server.tree == 'legacy':
|
||||
response = requests.post(server.base + '/v2/manager/queue/batch',
|
||||
json={'batch_id': ui_id, operation: [params]}, timeout=10)
|
||||
response.raise_for_status()
|
||||
if response.json()['failed']:
|
||||
return response.json()
|
||||
query = {'id': ui_id}
|
||||
else:
|
||||
if operation == 'update':
|
||||
params = {'node_name': node, 'node_ver': '1.0.0'}
|
||||
response = requests.post(server.base + '/v2/manager/queue/task', json={
|
||||
'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()
|
||||
query = {'ui_id': ui_id}
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
response = requests.get(server.base + '/v2/manager/queue/history', params=query, timeout=5)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
if server.tree == 'legacy' or data.get('history'):
|
||||
return data
|
||||
time.sleep(.1)
|
||||
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', 'nodepack-whitelist.list',
|
||||
'trusted private network', 'Restart ComfyUI'):
|
||||
assert detail in log
|
||||
|
||||
|
||||
def assert_flagged_denial(result, log):
|
||||
message = json.dumps(result)
|
||||
assert ('This action is not allowed by the current security configuration. '
|
||||
'See the terminal for details.') in message, result
|
||||
assert 'allow_flagged_nodepack_install' not in message, result
|
||||
assert '--listen' not in message, result
|
||||
assert_terminal_guidance(log)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('node,version', [
|
||||
('fixture-active', '1.0.0'), ('fixture-flagged', '2.0.0'),
|
||||
('fixture-pending', '3.0.0'), ('fixture-banned', '1.0.0'),
|
||||
('fixture-latest', 'latest'),
|
||||
])
|
||||
def test_install_policy(comfy_server, node, version):
|
||||
server = comfy_server
|
||||
log_before = len((server.root / 'server.log').read_text())
|
||||
before = len(server.registry.calls)
|
||||
result = install(server, node, version)
|
||||
calls = server.registry.calls[before:]
|
||||
strong = server.security == 'strong'
|
||||
flagged = version in ('2.0.0', 'latest')
|
||||
allowed = not strong and node != 'fixture-banned' and (
|
||||
not flagged or server.override or server.listen == '127.0.0.1')
|
||||
marker = server.root / 'custom_nodes' / node / 'installed.txt'
|
||||
assert marker.exists() is allowed, (result, (server.root / 'server.log').read_text()[-6000:])
|
||||
assert sum('/install' in call for call in calls) == (0 if strong else 1), calls
|
||||
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
|
||||
if allowed:
|
||||
assert marker.read_text() == ('2.0.0' if version == 'latest' else version)
|
||||
if server.tree == 'legacy':
|
||||
assert list(result['nodepack_result'].values()) == ['success'], result
|
||||
else:
|
||||
assert result['history']['result'] == 'success', result
|
||||
elif flagged and not strong:
|
||||
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
|
||||
if server.security == 'strong':
|
||||
pytest.skip('No installed version in strong mode')
|
||||
# Keep this state separate from test_install_policy, regardless of test order.
|
||||
node = 'fixture-switch' if operation == 'install' else 'fixture-update'
|
||||
marker = server.root / 'custom_nodes' / node / 'installed.txt'
|
||||
install(server, node, '1.0.0')
|
||||
log_before = len((server.root / 'server.log').read_text())
|
||||
before = len(server.registry.calls)
|
||||
result = install(server, node, '2.0.0', operation)
|
||||
calls = server.registry.calls[before:]
|
||||
assert sum('/install' in call for call in calls) == 1
|
||||
assert not any(call.startswith('/zip/') for call in calls)
|
||||
assert marker.read_text() == '1.0.0'
|
||||
reserved = server.root / 'user/__manager/startup-scripts/install-scripts.txt'
|
||||
if server.override or server.listen == '127.0.0.1':
|
||||
assert '#LAZY-CNR-SWITCH-SCRIPT' in reserved.read_text()
|
||||
if server.tree == 'legacy':
|
||||
assert list(result['nodepack_result'].values()) == ['success'], result
|
||||
else:
|
||||
assert result['history']['result'] == 'success', result
|
||||
else:
|
||||
assert not reserved.exists()
|
||||
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('listen,override', [
|
||||
('127.0.0.1', False), ('0.0.0.0', False), ('0.0.0.0', True),
|
||||
])
|
||||
@pytest.mark.parametrize('version', ['1.0.0', '2.0.0'])
|
||||
def test_legacy_reinstall_preserves_denied_pack_and_runs_allowed_script(
|
||||
tmp_path, registry, listen, override, version):
|
||||
with running_server(tmp_path, 'legacy', listen, override, 'normal', registry) as server:
|
||||
node = 'fixture-reinstall'
|
||||
install(server, node, '1.0.0')
|
||||
marker = tmp_path / 'custom_nodes' / node / 'installed.txt'
|
||||
assert marker.read_text() == '1.0.0'
|
||||
original = (marker.read_bytes(), marker.stat().st_mtime_ns)
|
||||
stale = marker.parent / 'stale.txt'
|
||||
stale.write_text('removed only by an allowed reinstall')
|
||||
before = len(registry.calls)
|
||||
log_before = len((server.root / 'server.log').read_text())
|
||||
|
||||
result = install(server, node, version, 'reinstall')
|
||||
|
||||
calls = registry.calls[before:]
|
||||
allowed = version == '1.0.0' or override or listen == '127.0.0.1'
|
||||
assert sum('/install' in call for call in calls) == 1, calls
|
||||
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
|
||||
if allowed:
|
||||
assert list(result['nodepack_result'].values()) == ['success'], result
|
||||
assert marker.read_text() == version, result
|
||||
assert not stale.exists()
|
||||
else:
|
||||
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
|
||||
assert marker.exists(), 'Rejected reinstall removed the existing pack'
|
||||
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
|
||||
assert stale.exists()
|
||||
|
||||
|
||||
def test_nonlocal_override_does_not_allow_nightly(comfy_server):
|
||||
server = comfy_server
|
||||
if server.listen == '127.0.0.1':
|
||||
pytest.skip('This regression checks the non-local Git gate')
|
||||
log_path = server.root / 'server.log'
|
||||
log_before = len(log_path.read_text())
|
||||
before = len(server.registry.calls)
|
||||
result = install(server, 'fixture-nightly', 'nightly')
|
||||
# A missing node or a failed clone must not count as a security rejection.
|
||||
if server.tree == 'legacy':
|
||||
assert result['failed'] == ['fixture-nightly'], result
|
||||
else:
|
||||
assert result['history']['result'] == 'failed', result
|
||||
expected_reason = ('normal or below' if server.security == 'strong' and server.tree == 'legacy'
|
||||
else 'network_mode must be set to `personal_cloud`')
|
||||
assert expected_reason in log_path.read_text()[log_before:], result
|
||||
assert not (server.root / 'custom_nodes/fixture-nightly').exists()
|
||||
assert not any('/install' in call or call.startswith('/zip/')
|
||||
for call in server.registry.calls[before:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
@pytest.mark.parametrize('listen,override,restart_listen,restart_override,allowed', [
|
||||
('127.0.0.1', False, '0.0.0.0', False, False),
|
||||
('0.0.0.0', True, '0.0.0.0', False, False),
|
||||
('127.0.0.1', False, '127.0.0.1', False, True),
|
||||
('0.0.0.0', True, '0.0.0.0', True, True),
|
||||
])
|
||||
@pytest.mark.parametrize('stored_status', [True, False])
|
||||
def test_restart_applies_current_policy_without_registry_query(
|
||||
tree, listen, override, restart_listen, restart_override, allowed, stored_status, tmp_path, registry):
|
||||
with running_server(tmp_path, tree, listen, override, 'normal', registry) as server:
|
||||
marker = server.root / 'custom_nodes/fixture-active/installed.txt'
|
||||
install(server, 'fixture-active', '1.0.0')
|
||||
reserved = server.root / 'user/__manager/startup-scripts/install-scripts.txt'
|
||||
install(server, 'fixture-active', '2.0.0')
|
||||
assert 'NodeVersionStatusFlagged' in reserved.read_text()
|
||||
original_marker = (marker.read_bytes(), marker.stat().st_mtime_ns)
|
||||
server.process.terminate()
|
||||
server.process.wait(timeout=10)
|
||||
if not stored_status:
|
||||
record = ast.literal_eval(reserved.read_text().strip())
|
||||
assert record[1] == '#LAZY-CNR-SWITCH-SCRIPT'
|
||||
assert len(record) == 9
|
||||
reserved.write_text(repr(record[:8]) + '\n')
|
||||
|
||||
config_path = server.root / 'user/__manager/config.ini'
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path)
|
||||
config['default']['allow_flagged_nodepack_install'] = str(restart_override)
|
||||
with config_path.open('w') as config_file:
|
||||
config.write(config_file)
|
||||
command = list(server.command)
|
||||
command[command.index('--listen') + 1] = restart_listen
|
||||
before = len(server.registry.calls)
|
||||
log_path = server.root / 'restart.log'
|
||||
with log_path.open('w') as log:
|
||||
process = subprocess.Popen(command, env=server.env, cwd=E2E_ROOT / 'comfyui',
|
||||
stdout=log, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, log_path.read_text()[-6000:]
|
||||
try:
|
||||
if requests.get(server.base + '/system_stats', timeout=1).status_code == 200:
|
||||
break
|
||||
except requests.RequestException:
|
||||
pass
|
||||
time.sleep(.2)
|
||||
else:
|
||||
pytest.fail(log_path.read_text()[-6000:])
|
||||
calls = server.registry.calls[before:]
|
||||
assert not any('/install' in call for call in calls), calls
|
||||
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
|
||||
if allowed:
|
||||
assert marker.read_text() == '2.0.0', log_path.read_text()[-6000:]
|
||||
else:
|
||||
if stored_status:
|
||||
assert_terminal_guidance(log_path.read_text())
|
||||
else:
|
||||
assert 'stored Registry status is missing' in log_path.read_text()
|
||||
assert 'Request the installation again' in log_path.read_text()
|
||||
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original_marker
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['install', 'restore-snapshot'])
|
||||
def test_direct_cli_installs_flagged_without_server_options(tmp_path, registry, operation):
|
||||
env = prepare_environment(tmp_path, False, 'normal', registry)
|
||||
command = [str(E2E_ROOT / 'venv/bin/python'), '-m', 'cm_cli', operation]
|
||||
if operation == 'install':
|
||||
command += ['fixture-flagged@2.0.0', '--mode', 'cache']
|
||||
else:
|
||||
snapshot = tmp_path / 'direct-snapshot.json'
|
||||
snapshot.write_text(json.dumps({'cnr_custom_nodes': {'fixture-flagged': '2.0.0'},
|
||||
'git_custom_nodes': {}, 'file_custom_nodes': []}))
|
||||
command.append(str(snapshot))
|
||||
command += ['--user-directory', str(tmp_path / 'user')]
|
||||
before = len(registry.calls)
|
||||
|
||||
result = subprocess.run(command, env=env, cwd=E2E_ROOT / 'comfyui',
|
||||
capture_output=True, text=True, timeout=60)
|
||||
|
||||
output = result.stdout + result.stderr
|
||||
assert result.returncode == 0, output
|
||||
installed = tmp_path / 'custom_nodes/fixture-flagged'
|
||||
assert 'version = "2.0.0"' in (installed / 'pyproject.toml').read_text(), output
|
||||
if operation == 'install':
|
||||
assert (installed / 'installed.txt').read_text() == '2.0.0', output
|
||||
assert sum('/install' in call for call in registry.calls[before:]) == 1
|
||||
assert 'Installation of this flagged CNR version is blocked' not in output
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
|
||||
@pytest.mark.parametrize('existing', [False, True])
|
||||
@pytest.mark.parametrize('version,listen,override,allowed', [
|
||||
('1.1.0', '0.0.0.0', False, True),
|
||||
('2.0.0', '0.0.0.0', False, False),
|
||||
('2.0.0', '0.0.0.0', True, True),
|
||||
('2.0.0', '127.0.0.1', False, True),
|
||||
])
|
||||
def test_scheduled_snapshot_restores_through_server_restart(
|
||||
tmp_path, registry, tree, existing, version, listen, override, allowed):
|
||||
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:
|
||||
if existing:
|
||||
install(server, 'fixture-snapshot', '1.0.0')
|
||||
assert marker.read_text() == '1.0.0'
|
||||
original = (marker.read_bytes(), marker.stat().st_mtime_ns)
|
||||
snapshot = tmp_path / 'user/__manager/snapshots/flagged-policy.json'
|
||||
snapshot.write_text(json.dumps({'cnr_custom_nodes': {'fixture-snapshot': version},
|
||||
'git_custom_nodes': {}, 'file_custom_nodes': []}))
|
||||
before = len(registry.calls)
|
||||
response = requests.post(server.base + '/v2/snapshot/restore',
|
||||
params={'target': snapshot.stem}, json={}, timeout=10)
|
||||
assert response.status_code == 200, response.text
|
||||
assert reservation.read_bytes() == snapshot.read_bytes()
|
||||
assert registry.calls[before:] == []
|
||||
if existing:
|
||||
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
|
||||
else:
|
||||
assert not installed.exists()
|
||||
|
||||
before = len(registry.calls)
|
||||
with running_server(tmp_path, tree, listen, override, 'normal', registry):
|
||||
log = (tmp_path / 'server.log').read_text()
|
||||
calls = registry.calls[before:]
|
||||
assert 'Restore snapshot done.' in log, log[-6000:]
|
||||
assert 'Restore snapshot failed.' not in log, log[-6000:]
|
||||
assert 'Error in sitecustomize' not in log, log[-6000:]
|
||||
assert not reservation.exists()
|
||||
assert sum('/install' in call for call in calls) == 1, (calls, log[-6000:])
|
||||
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
|
||||
if allowed:
|
||||
assert f'version = "{version}"' in (installed / 'pyproject.toml').read_text(), log[-6000:]
|
||||
assert 'allow_flagged_nodepack_install' not in log
|
||||
else:
|
||||
assert_terminal_guidance(log)
|
||||
if existing:
|
||||
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
|
||||
assert '1.0.0' in (installed / 'pyproject.toml').read_text()
|
||||
else:
|
||||
assert not installed.exists()
|
||||
@@ -59,6 +59,7 @@ otherwise (harness precedent: tests/e2e/test_e2e_secgate_default.py).
|
||||
from __future__ import annotations
|
||||
|
||||
import configparser
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -506,6 +507,94 @@ class TestFlagsOffWeakLevel:
|
||||
)
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# The 403 denial reason code
|
||||
#
|
||||
# A denied install returns 403 with a JSON body naming the flag that denied it
|
||||
# — `{"reason": "allow_git_url_install"}` or `{"reason": "allow_pip_install"}`
|
||||
# — so the browser can tell the user WHICH setting to change instead of
|
||||
# guessing from the endpoint it happened to call. The full
|
||||
# SECURITY_MESSAGE_FLAG_* text still goes to the terminal via `logging.error`;
|
||||
# only the flag name goes on the wire.
|
||||
#
|
||||
# Every other assertion on these endpoints tests `status_code` alone, so
|
||||
# nothing else in this file can see the body at all — these rows are the only
|
||||
# coverage the wire contract has.
|
||||
#
|
||||
# Reuses CFG-D (git=F, pip=F, sl=weak) — the config that already produces a 403
|
||||
# on both arms, so these rows add no new server boot.
|
||||
# ===========================================================================
|
||||
|
||||
class TestDenialReasonCode:
|
||||
"""The 403 body must name WHICH flag denied — and nothing more."""
|
||||
|
||||
def _denial_body(self, resp):
|
||||
"""Parse the 403 body as the wire contract, with the failure message
|
||||
carrying what was actually received."""
|
||||
assert resp.status_code == 403, (
|
||||
f"precondition: expected 403, got {resp.status_code}"
|
||||
)
|
||||
try:
|
||||
return json.loads(resp.text)
|
||||
except json.JSONDecodeError as exc:
|
||||
pytest.fail(
|
||||
"the 403 body is not JSON. Expected a JSON object carrying "
|
||||
"the denial reason code; "
|
||||
f"observed {resp.text!r} (len={len(resp.text)}). "
|
||||
f"JSONDecodeError: {exc}. A 403 emitted with no `text=` leaves "
|
||||
"the body EMPTY, and the client then has nothing to derive its "
|
||||
"message from."
|
||||
)
|
||||
|
||||
def test_t9_pip_denial_body_names_the_flag(self, comfyui_flags_d):
|
||||
"""The pip 403 body carries the reason code.
|
||||
|
||||
Expected: a JSON OBJECT whose `reason` is the string
|
||||
`allow_pip_install`.
|
||||
"""
|
||||
resp = _post_pip("text-unidecode")
|
||||
body = self._denial_body(resp)
|
||||
|
||||
assert isinstance(body, dict), (
|
||||
"the 403 body must be a JSON OBJECT (the client's guard is "
|
||||
"`typeof data === 'object' && data !== null && typeof data.reason "
|
||||
f"=== 'string'`); observed {type(body).__name__} {body!r}"
|
||||
)
|
||||
assert body.get("reason") == "allow_pip_install", (
|
||||
"expected the pip 403 body to carry "
|
||||
"{'reason': 'allow_pip_install'} so the client can name the "
|
||||
f"condition the SERVER actually failed on; observed {body!r}"
|
||||
)
|
||||
|
||||
def test_t9_git_url_denial_body_names_the_flag(self, comfyui_flags_d):
|
||||
"""The git_url 403 body carries its own code.
|
||||
|
||||
A separate node from the pip arm on purpose: the two emissions are
|
||||
separate `return` statements, so one can be changed while the other is
|
||||
missed.
|
||||
"""
|
||||
resp = _post_git_url(UNKNOWN_GIT_URL)
|
||||
body = self._denial_body(resp)
|
||||
|
||||
assert isinstance(body, dict), (
|
||||
"the 403 body must be a JSON OBJECT; observed "
|
||||
f"{type(body).__name__} {body!r}"
|
||||
)
|
||||
assert body.get("reason") == "allow_git_url_install", (
|
||||
"expected the git_url 403 body to carry "
|
||||
f"{{'reason': 'allow_git_url_install'}}; observed {body!r}"
|
||||
)
|
||||
|
||||
def test_t9b_denial_body_discloses_nothing_further(self, comfyui_flags_d):
|
||||
"""Denied requests expose only the failed flag name."""
|
||||
responses = {
|
||||
"allow_pip_install": _post_pip("text-unidecode"),
|
||||
"allow_git_url_install": _post_git_url(UNKNOWN_GIT_URL),
|
||||
}
|
||||
for reason, response in responses.items():
|
||||
assert self._denial_body(response) == {"reason": reason}
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# CFG-E: git=T, pip=T, sl=weak, nm=public — Q1 guard
|
||||
# ===========================================================================
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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,36 @@
|
||||
"""Execute the legacy renderer without starting ComfyUI or its network threads."""
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
PACKAGE = ROOT / 'comfyui_manager'
|
||||
|
||||
|
||||
def load_functions(path, names, namespace=None):
|
||||
namespace = {} if namespace is None else namespace
|
||||
nodes = [node for node in ast.parse(path.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
|
||||
assert len(nodes) == len(names)
|
||||
exec(compile(ast.Module(nodes, []), str(path), 'exec'), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
def load_renderer():
|
||||
path = PACKAGE / 'legacy/html_utils.py'
|
||||
spec = importlib.util.spec_from_file_location('_legacy_html_utils', path)
|
||||
helpers = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(helpers)
|
||||
util = load_functions(PACKAGE / 'common/manager_util.py', {'sanitize_tag'})
|
||||
return load_functions(PACKAGE / 'legacy/manager_server.py', {'convert_markdown_to_html', 'populate_markdown'},
|
||||
{'re': re, 'html_utils': helpers, 'manager_util': types.SimpleNamespace(**util)})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
item = json.load(sys.stdin)
|
||||
load_renderer()['populate_markdown'](item)
|
||||
print(json.dumps(item))
|
||||
@@ -5,20 +5,25 @@ Browser-based E2E tests for the ComfyUI-Manager legacy UI.
|
||||
## Prerequisites
|
||||
|
||||
1. **E2E environment** built via `python tests/e2e/scripts/setup_e2e_env.py`
|
||||
2. **Playwright installed**: `npx playwright install chromium`
|
||||
2. **Playwright runner and Chromium** (from the repository root):
|
||||
`npm install --no-save --package-lock=false @playwright/test@1.59.1`, then
|
||||
`npx playwright install chromium`.
|
||||
3. **ComfyUI running** with legacy UI enabled:
|
||||
|
||||
```bash
|
||||
E2E_ROOT=/tmp/e2e_full_test
|
||||
PORT=8199
|
||||
$E2E_ROOT/venv/bin/python $E2E_ROOT/comfyui/main.py \
|
||||
PYTHONPATH="$PWD" $E2E_ROOT/venv/bin/python $E2E_ROOT/comfyui/main.py \
|
||||
--listen 127.0.0.1 --port $PORT \
|
||||
--enable-manager-legacy-ui \
|
||||
--enable-manager --enable-manager-legacy-ui \
|
||||
--cpu
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
Run from the repository root. XSS fixtures execute the checkout's Python renderer
|
||||
using `python3`; set `PYTHON=/path/to/python` to select another interpreter.
|
||||
|
||||
```bash
|
||||
# With server already running:
|
||||
PORT=8199 npx playwright test
|
||||
@@ -40,5 +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, 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, 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 |
|
||||
|
||||
@@ -191,7 +191,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
|
||||
|
||||
@@ -0,0 +1,842 @@
|
||||
/**
|
||||
* Browser-level XSS regression suite for the Custom Nodes manager UI.
|
||||
*
|
||||
* Every row feeds hostile node-pack metadata through a stubbed registry
|
||||
* response and asserts the value renders as INERT TEXT: the payload is visible
|
||||
* as literal characters, no element is constructed from it, and its `onerror`
|
||||
* never runs. The three checks are made together because they fail
|
||||
* differently — see `expectInert` in ./helpers.ts.
|
||||
*
|
||||
* NOT EVERY ROW CLOSES A LIVE HOLE, and the distinction matters when reading a
|
||||
* failure. `version`/`cnr_latest`, `author`, `stars` and `last_update` are
|
||||
* served unsanitized and sit in always-visible columns, so opening the manager
|
||||
* is the whole exploit; so are node names from `/v2/customnode/getmappings`,
|
||||
* a route that sanitizes nothing. Those fields are escaped ON THE CLIENT and
|
||||
* their rows target that escape.
|
||||
*
|
||||
* `title` / `name` / `description` are different: `populate_markdown` ->
|
||||
* `sanitize_tag` escapes them SERVER-SIDE, and the client renders them as-is
|
||||
* on purpose. Escaping them again is not free safety — `sanitizeHTML` also maps
|
||||
* `&`, so a second pass turns the server's `<` into `&lt;` and the pack
|
||||
* `ComfyUI-<Impact-Pack>` reaches the user as literal `ComfyUI-<Impact-Pack>`.
|
||||
* The rows targeting those fields assert the SERVER->CLIENT CHAIN, not an
|
||||
* independent client guarantee.
|
||||
*
|
||||
* CAVEAT: `page.route()` REPLACES the HTTP response, so every fixture here
|
||||
* bypasses `populate_markdown`. For the raw fields that is exactly what a live
|
||||
* server delivers. For the server-escaped fields it is NOT, so those rows pass
|
||||
* their payload through `serverSanitizeTag` first — the real transform, read
|
||||
* out of `manager_util.py` — and assert on the wire form the server would
|
||||
* actually have emitted.
|
||||
*
|
||||
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT (see
|
||||
* tests/playwright/README.md).
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import {
|
||||
waitForComfyUI,
|
||||
openManagerMenu,
|
||||
openCustomNodesManager,
|
||||
routeNodeList,
|
||||
routeMappings,
|
||||
routeAlternatives,
|
||||
makePack,
|
||||
expectInert,
|
||||
serverSanitizeTag,
|
||||
serverPopulateMarkdown,
|
||||
serverInstallDenialRestartClause,
|
||||
XSS_PAYLOAD,
|
||||
XSS_PAYLOAD_NOSPACE,
|
||||
} from './helpers';
|
||||
|
||||
const GRID = '.cn-manager-grid';
|
||||
const FLYOVER = '.cn-flyover';
|
||||
|
||||
/** Collect page errors so the rows that assert "did not throw" can see them. */
|
||||
function trackPageErrors(page: import('@playwright/test').Page) {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
return errors;
|
||||
}
|
||||
|
||||
test.describe('grid render sinks', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('hostile title renders inert through the server escape', async ({ page }) => {
|
||||
// NOT defence-in-depth, and the fixture is what says so. `title` is in the
|
||||
// populate_markdown set, so the SERVER escape is the one defence and the
|
||||
// client deliberately renders the value as-is — escaping it a second time
|
||||
// printed `<` to every user (see the double-escape row below).
|
||||
//
|
||||
// The fixture is therefore the server's own sanitize_tag OUTPUT, lifted
|
||||
// from manager_util.py. A raw payload here would assert the opposite of the
|
||||
// design and fail by construction, on a wire form the live server cannot
|
||||
// emit; what this row asserts is that the form it DOES emit stays inert
|
||||
// once the client renders it.
|
||||
await routeNodeList(page, {
|
||||
hostile: makePack('hostile', { title: serverSanitizeTag(XSS_PAYLOAD) }),
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'title');
|
||||
});
|
||||
|
||||
// This row needs a WIDER VIEWPORT THAN THE REST, so it gets its own describe.
|
||||
//
|
||||
// turbogrid virtualises columns horizontally: at the config's default
|
||||
// viewport the `.cn-pack-stars` and `.cn-pack-last-update` BODY CELLS are
|
||||
// not in the DOM at all — a dump returned `stars: []`, `lastUpdate: []`
|
||||
// with `rowCount: 4`, while the HEADER showed both columns. The row's
|
||||
// `last_update` leg then failed leg 1 (presence) with legs 2 and 3 passing,
|
||||
// which is expectInert's own signature for "the payload never rendered",
|
||||
// i.e. the row was reporting the viewport, not the sink. Measured: at
|
||||
// 2600x1000 both cells render and both are inert. Pin the viewport so this
|
||||
// row asserts on the sink it names.
|
||||
test.describe('wide viewport — stars/last_update are column-virtualised', () => {
|
||||
test.use({ viewport: { width: 2600, height: 1000 } });
|
||||
|
||||
test('hostile version/author/stars/last_update render inert (LIVE no-user-action)', async ({ page }) => {
|
||||
// The four fields that carry the no-user-action property: served
|
||||
// unsanitized AND in always-visible columns, so opening the manager is
|
||||
// the whole exploit.
|
||||
await routeNodeList(page, {
|
||||
p1: makePack('p1', { version: XSS_PAYLOAD, cnr_latest: XSS_PAYLOAD }),
|
||||
p2: makePack('p2', { author: XSS_PAYLOAD }),
|
||||
// `stars` must be a NON-number to reach the raw fall-through
|
||||
// (`if (typeof stars === 'number') return stars.toLocaleString()`).
|
||||
p3: makePack('p3', { stars: XSS_PAYLOAD }),
|
||||
// `last_update` is cut at the first space, so the payload must be
|
||||
// space-free or the row would pass for the wrong reason.
|
||||
p4: makePack('p4', { last_update: XSS_PAYLOAD_NOSPACE }),
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
// 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).
|
||||
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.',
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
await expect(
|
||||
page.locator(`${GRID} .cn-pack-last-update`).first(),
|
||||
'precondition: no .cn-pack-last-update body cell rendered — the last_update column is virtualised away at this viewport, so its leg would pass vacuously.',
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'version/cnr_latest');
|
||||
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'author');
|
||||
await expectInert(page, GRID, XSS_PAYLOAD_NOSPACE, 'img', 'last_update');
|
||||
});
|
||||
});
|
||||
|
||||
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.
|
||||
//
|
||||
// The earlier shape of this row fed the RAW authored title straight to the
|
||||
// grid. That is input the live server cannot deliver — getlist runs every
|
||||
// pack through populate_markdown -> sanitize_tag first — and the row passed
|
||||
// either way: escaped once, `<3` comes back as `<3`; not escaped at
|
||||
// all, `<3` is not a tag start so it renders as text too. It asserted
|
||||
// nothing about the chain it was named for.
|
||||
//
|
||||
// Now the fixture is the OUTPUT of the server's own sanitize_tag, read out
|
||||
// of manager_util.py at run time (serverSanitizeTag) rather than re-typed,
|
||||
// so what enters the client is exactly what the server would have emitted:
|
||||
// wire form in, authored text out. A client that escapes the field a second
|
||||
// time prints the entity and BOTH legs below flip.
|
||||
//
|
||||
// page.route still carries it: the escaped fields originate in third-party
|
||||
// registry data (no live pack title contains an angle bracket), so this is
|
||||
// the only deterministic way to place a known value in the grid. What
|
||||
// page.route replaces is the TRANSPORT — the transform is the real one.
|
||||
const AUTHORED = 'Tom & Jerry <3';
|
||||
const ON_THE_WIRE = serverSanitizeTag(AUTHORED);
|
||||
expect(
|
||||
ON_THE_WIRE,
|
||||
'serverSanitizeTag returned its input unchanged, so the fixture is NOT the ' +
|
||||
'wire form and this row is back to proving nothing. Check that sanitize_tag ' +
|
||||
'in comfyui_manager/common/manager_util.py still escapes < and >.',
|
||||
).not.toBe(AUTHORED);
|
||||
|
||||
await routeNodeList(page, { legit: makePack('legit', { title: ON_THE_WIRE }) });
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const text = (await page.locator(GRID).first().textContent()) ?? '';
|
||||
const diagnostic =
|
||||
`authored: ${JSON.stringify(AUTHORED)}\n` +
|
||||
`on the wire (server sanitize_tag output): ${JSON.stringify(ON_THE_WIRE)}\n` +
|
||||
`grid text (first 300 chars): ${JSON.stringify(text.slice(0, 300))}`;
|
||||
|
||||
expect(
|
||||
text,
|
||||
`the server-escaped title did not render as the author wrote it. The client ` +
|
||||
`escaped an ALREADY-escaped value, so sanitizeHTML mapped the server's & to ` +
|
||||
`& and the entity reached the user as literal text.\n${diagnostic}`,
|
||||
).toContain(AUTHORED);
|
||||
expect(
|
||||
text,
|
||||
`the wire form is visible in the grid as literal text — that IS the ` +
|
||||
`double-escape. A field in the populate_markdown set (title/name/description) ` +
|
||||
`must reach innerHTML AS-IS.\n${diagnostic}`,
|
||||
).not.toContain(ON_THE_WIRE);
|
||||
});
|
||||
|
||||
test('missing title/version/author renders without throwing', async ({ page }) => {
|
||||
// Expected to PASS — `sanitizeHTML(undefined)` raises TypeError inside a
|
||||
// render path, so the escape MUST be sanitizeHTML(String(v)).
|
||||
// This row is what turns that mistake into a visible failure.
|
||||
const errors = trackPageErrors(page);
|
||||
const bare = makePack('bare');
|
||||
delete (bare as Record<string, unknown>).title;
|
||||
delete (bare as Record<string, unknown>).version;
|
||||
delete (bare as Record<string, unknown>).author;
|
||||
await routeNodeList(page, { bare });
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
await expect(page.locator(GRID).first()).toBeVisible();
|
||||
expect(
|
||||
errors,
|
||||
`the grid threw while rendering a row with absent title/version/author — sanitizeHTML(undefined) raises TypeError, so the escape must pass String(v). pageerrors: ${errors.join(' | ')}`,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test('composed-HTML description keeps rendering as markup (anti-regression)', async ({ page }) => {
|
||||
// MANDATORY anti-regression. `description` is SERVER-COMPOSED HTML; the
|
||||
// cheapest way to pass every other row here is to blind-escape the grid,
|
||||
// which would print literal <a href=...> / <B> to every user. This row
|
||||
// guards the ESCAPING, not the defect — it is expected to pass both before
|
||||
// and after, and must never be forced to fail.
|
||||
const composed = serverPopulateMarkdown({ description: 'See [a/the docs](https://example.com/x) for **details**' }).description;
|
||||
await routeNodeList(page, { doc: makePack('doc', { description: composed }) });
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const anchors = await page.locator(`${GRID} a[href="https://example.com/x"]`).count();
|
||||
expect(
|
||||
anchors,
|
||||
'the composed-HTML description no longer renders as markup — a working <a href> is gone, so the description column was blind-escaped. That is a regression, not a fix.',
|
||||
).toBeGreaterThan(0);
|
||||
|
||||
const bold = await page.locator(`${GRID} b, ${GRID} B`).count();
|
||||
expect(
|
||||
bold,
|
||||
'the composed-HTML description lost its <B> markup — the column was escaped wholesale.',
|
||||
).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('URL / scheme sink', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('the title link href carries no javascript: scheme (LIVE, click-gated)', async ({ page }) => {
|
||||
// `link.href = <registry URL>` with no scheme allow-list. This is the
|
||||
// client-side twin of the server composer's scheme-trust hole.
|
||||
//
|
||||
// Asserted on the href PROPERTY, not on rendered text: the
|
||||
// rendered label is the pack title and would look perfectly innocent while
|
||||
// the anchor still carries a javascript: target.
|
||||
await routeNodeList(page, {
|
||||
evil: makePack('evil', {
|
||||
repository: 'javascript:window.__xss_fired=1',
|
||||
reference: 'javascript:window.__xss_fired=1',
|
||||
}),
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const hrefs = await page.locator(`${GRID} a`).evaluateAll(
|
||||
(els) => els.map((e) => (e as HTMLAnchorElement).href),
|
||||
);
|
||||
|
||||
// PRECONDITION — the row asserts that no anchor carries a bad scheme, and
|
||||
// a grid with NO anchors satisfies that having tested nothing. Pin that at
|
||||
// least one anchor rendered before reading anything into the result below.
|
||||
expect(
|
||||
hrefs.length,
|
||||
`precondition: the grid rendered no anchors at all, so the href assertion below would pass over an empty list and prove nothing about the URL sink. Observed ${hrefs.length} anchors.`,
|
||||
).toBeGreaterThan(0);
|
||||
|
||||
// ASSERTED AGAINST THE ALLOW-LIST, not against a list of dangerous schemes.
|
||||
const allowed = ['http:', 'https:'];
|
||||
const offending = hrefs.filter((h) => {
|
||||
const scheme = new URL(h).protocol;
|
||||
return scheme !== null && !allowed.includes(scheme);
|
||||
});
|
||||
expect(
|
||||
offending,
|
||||
`the title link's href PROPERTY carries a scheme outside the allow-list — a ` +
|
||||
`registry-controlled URL reached href unfiltered, so one click executes it. ` +
|
||||
`sanitizeUrl admits ${JSON.stringify(allowed)}; observed anchors: ` +
|
||||
`${JSON.stringify(hrefs.slice(0, 10))}`,
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('flyover sinks', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
/** Open the node flyover by clicking the Nodes cell of the first row.
|
||||
*
|
||||
* Targets `.cn-pack-nodes` specifically — that div is emitted ONLY by the
|
||||
* `nodes` column formatter, and only when `rowItem.nodes` is truthy. The
|
||||
* grid's onClick handler routes to `showNodes` on `columnItem.id ===
|
||||
* "nodes"`, so any looser selector (e.g. "a cell containing a digit") lands
|
||||
* on the ID column, silently never opens the flyover, and turns the row
|
||||
* into a timeout that LOOKS like a failed assertion. Waiting for this
|
||||
* element first therefore doubles as a precondition that the getmappings
|
||||
* fixture actually produced a node count. */
|
||||
async function openFlyover(page: import('@playwright/test').Page) {
|
||||
const nodesCell = page.locator(`${GRID} .cn-pack-nodes`).first();
|
||||
await expect(
|
||||
nodesCell,
|
||||
'flyover precondition: no .cn-pack-nodes cell rendered, so the getmappings fixture did not attach a node count to the pack — the flyover cannot open and the row would time out for a fixture reason, not a defect.',
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
await nodesCell.click();
|
||||
await page.waitForSelector(FLYOVER, { state: 'visible', timeout: 10_000 });
|
||||
}
|
||||
|
||||
test('flyover pack title renders inert through the server escape', async ({ page }) => {
|
||||
// Same contract as the grid title row: `title` is server-escaped, the
|
||||
// client renders it as-is, so the fixture must be the WIRE form.
|
||||
await routeNodeList(page, { h: makePack('h', { title: serverSanitizeTag(XSS_PAYLOAD) }) });
|
||||
await routeMappings(page, {
|
||||
'https://github.com/example/h': [['NodeA'], { title_aux: 'h' }],
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await openFlyover(page);
|
||||
|
||||
await expectInert(page, FLYOVER, XSS_PAYLOAD, 'img', 'flyover title');
|
||||
});
|
||||
|
||||
test('flyover node NAME renders inert (LIVE, click-gated)', async ({ page }) => {
|
||||
// `/v2/customnode/getmappings` performs NO sanitization —
|
||||
// `populate_markdown` is never called on that route — so
|
||||
// this node name is genuinely RAW, not defence-in-depth.
|
||||
await routeNodeList(page, { h: makePack('h') });
|
||||
await routeMappings(page, {
|
||||
'https://github.com/example/h': [[XSS_PAYLOAD], { title_aux: 'h' }],
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await openFlyover(page);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
// selection bar
|
||||
// ===========================================================================
|
||||
|
||||
test.describe('selection bar', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
for (const state of ['not-a-known-install-group', 'constructor', '__proto__']) {
|
||||
test(`an unrecognised pack state still renders the selection bar: ${state}`, async ({ page }) => {
|
||||
const errors = trackPageErrors(page);
|
||||
await routeNodeList(page, { odd: makePack('odd', { state }) });
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const checkbox = page.locator(`${GRID} .tg-body .tg-row .tg-checkbox`).first();
|
||||
await expect(checkbox).toBeVisible({ timeout: 15_000 });
|
||||
await checkbox.click();
|
||||
|
||||
const bar = page.locator('.cn-manager-selection').first();
|
||||
await expect(bar).toContainText('Selected');
|
||||
await expect(bar).toContainText(state);
|
||||
await expect(bar.locator('button')).toHaveCount(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
// Install status uses the same server-composed names as the grid.
|
||||
// ===========================================================================
|
||||
|
||||
test.describe('install status sink', () => {
|
||||
for (const [source, visible] of [
|
||||
[XSS_PAYLOAD, XSS_PAYLOAD],
|
||||
['Pack & Friends <Flux>', 'Pack & Friends <Flux>'],
|
||||
['Pack &lt;Flux&gt;', 'Pack <Flux>'],
|
||||
]) {
|
||||
test(`server title remains readable and inert: ${source}`, async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeNodeList(page, { victim: makePack('victim', {
|
||||
title: serverSanitizeTag(source), version: 'unknown',
|
||||
}) });
|
||||
await page.route('**/v2/manager/queue/batch', route => route.fulfill({
|
||||
status: 200, contentType: 'application/json', body: '{"failed": []}',
|
||||
}));
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await page.locator(`${GRID} .cn-btn-install`).first().click();
|
||||
await expectInert(page, '.cn-manager-status', visible, 'img', 'install title');
|
||||
const status = page.locator('.cn-manager-status');
|
||||
await expect(status).toContainText(visible);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
// batch error dialog
|
||||
// ===========================================================================
|
||||
|
||||
test.describe('batch error dialog', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('server-authored batch failure text renders inert (LIVE)', async ({ page }) => {
|
||||
// REAL CONSUMPTION PATH, not a synthetic fixture. The chain exercised here
|
||||
// is the production one end to end on the client side:
|
||||
// real Install click -> real POST /v2/manager/queue/batch
|
||||
// -> real `cm-queue-status` batch-done event on ComfyUI's api
|
||||
// -> real onQueueStatus -> onQueueCompleted -> errorMsg += v (:1604)
|
||||
// -> real showError (:1613) -> showMessage -> .cn-manager-message
|
||||
// .innerHTML (:2091)
|
||||
// Only the SERVER's two responses are stubbed, which is exactly what
|
||||
// Tier A is for — the attacker-controlled value enters at `result[hash]`,
|
||||
// the same slot a real queue result fills.
|
||||
let capturedBatchId = '';
|
||||
await page.route('**/v2/manager/queue/batch', async (route) => {
|
||||
capturedBatchId = route.request().postDataJSON()?.batch_id ?? '';
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: '{"failed": []}' });
|
||||
});
|
||||
// `version: 'unknown'` is load-bearing, not filler. The grid click handler
|
||||
// routes install through a VERSION SELECTOR dialog when
|
||||
// `item.originalData.version != 'unknown'` (:555), and the batch POST only
|
||||
// happens after a version is chosen. The unknown-version shape takes the
|
||||
// direct `installNodes` path (:559), which is the same branch the Python
|
||||
// e2e rows drive, and keeps this test on the error-render path it is about
|
||||
// instead of on version-picker UI.
|
||||
await routeNodeList(page, {
|
||||
victim: makePack('victim', { state: 'not-installed', version: 'unknown' }),
|
||||
});
|
||||
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const installBtn = page.locator(`${GRID} .cn-btn-install`).first();
|
||||
await expect(
|
||||
installBtn,
|
||||
'precondition: no .cn-btn-install rendered, so the batch flow was never entered and install_context/batch_id were never set — the queue event would be dropped by onQueueCompleted and the row would prove nothing.',
|
||||
).toBeVisible({ timeout: 15_000 });
|
||||
await installBtn.click();
|
||||
|
||||
// CAPTURE THE SINK'S WRITES, because the settled element cannot be read.
|
||||
//
|
||||
// onQueueCompleted writes the error into .cn-manager-message via
|
||||
// showError (:1613) and then OVERWRITES the same element with the restart
|
||||
// notice via showMessage (:1620) — inside ONE synchronous handler. So by
|
||||
// the time any assertion runs, the element holds "To apply the
|
||||
// installed/updated... restart ComfyUI", and the value under test is
|
||||
// gone. A MutationObserver does not help: its callback is a microtask and
|
||||
// both writes land before it runs (measured — it reports only the final
|
||||
// state). Wrapping the innerHTML SETTER records each write at the moment
|
||||
// it happens, which is the only way to assert on what the sink actually
|
||||
// received. Installed here rather than via addInitScript because the
|
||||
// writes under test all happen after this point.
|
||||
await page.evaluate(() => {
|
||||
const w = window as unknown as Record<string, any>;
|
||||
w.__cnMessageWrites = [];
|
||||
const desc = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML')!;
|
||||
Object.defineProperty(Element.prototype, 'innerHTML', {
|
||||
configurable: true,
|
||||
get() {
|
||||
return desc.get!.call(this);
|
||||
},
|
||||
set(value) {
|
||||
try {
|
||||
if ((this as Element).classList?.contains('cn-manager-message')) {
|
||||
w.__cnMessageWrites.push(String(value));
|
||||
}
|
||||
} catch {
|
||||
/* never let the probe break the page under test */
|
||||
}
|
||||
desc.set!.call(this, value);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await expect
|
||||
.poll(() => capturedBatchId, {
|
||||
timeout: 15_000,
|
||||
message: 'precondition: the client never POSTed /v2/manager/queue/batch, so no batch_id exists to address the completion event to.',
|
||||
})
|
||||
.not.toBe('');
|
||||
|
||||
// Deliver the completion event exactly as the server does over the socket.
|
||||
await page.evaluate(
|
||||
({ batchId, payload }) => {
|
||||
const api = (window as unknown as Record<string, any>).comfyAPI.api.api;
|
||||
api.dispatchEvent(
|
||||
new CustomEvent('cm-queue-status', {
|
||||
detail: { status: 'batch-done', batch_id: batchId, nodepack_result: [payload] },
|
||||
}),
|
||||
);
|
||||
},
|
||||
{ batchId: capturedBatchId, payload: XSS_PAYLOAD },
|
||||
);
|
||||
|
||||
// The write carrying the payload must arrive, and arrive inert. The three
|
||||
// legs are the same ones expectInert applies, evaluated against the value
|
||||
// the sink RECEIVED rather than against the element's settled content:
|
||||
// leg 1 presence — the payload is there as literal text;
|
||||
// leg 2 structure — parsing that write constructs no <img>;
|
||||
// leg 3 execution — window.__xss_fired never set (document-wide).
|
||||
const sink = await page.evaluate((payload) => {
|
||||
const w = window as unknown as Record<string, any>;
|
||||
const writes: string[] = w.__cnMessageWrites ?? [];
|
||||
// Parse each write the way the browser did, in a detached element.
|
||||
const probe = document.createElement('div');
|
||||
const parsed = writes.map((html) => {
|
||||
probe.innerHTML = html;
|
||||
return { html, text: probe.textContent ?? '', imgs: probe.querySelectorAll('img').length };
|
||||
});
|
||||
return {
|
||||
writes,
|
||||
carrying: parsed.filter((p) => p.text.includes(payload)),
|
||||
imgsAnywhere: parsed.reduce((n, p) => n + p.imgs, 0),
|
||||
firedGlobal: w.__xss_fired,
|
||||
liveImgs: document.querySelectorAll('img[src="x"]').length,
|
||||
};
|
||||
}, XSS_PAYLOAD);
|
||||
|
||||
const diagnostic =
|
||||
`queue failure text — writes observed at .cn-manager-message: ${JSON.stringify(sink.writes)}`;
|
||||
|
||||
expect(
|
||||
sink.carrying.length,
|
||||
`precondition: no write to .cn-manager-message carried the payload at all, so the sink was never exercised and the row proves nothing — check that onQueueCompleted reached showError. ${diagnostic}`,
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
sink.imgsAnywhere,
|
||||
`a write to .cn-manager-message parsed into a live <img> — the server-authored queue text reached innerHTML AS MARKUP. ${diagnostic}`,
|
||||
).toBe(0);
|
||||
expect(
|
||||
sink.liveImgs,
|
||||
`an <img src=x> from the payload is live in the document. ${diagnostic}`,
|
||||
).toBe(0);
|
||||
expect(
|
||||
sink.firedGlobal,
|
||||
`the payload EXECUTED (window.__xss_fired is set). ${diagnostic}`,
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
// client-side 403 denial text
|
||||
// ===========================================================================
|
||||
|
||||
// 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
|
||||
// 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
|
||||
// `.prompt-dialog-content input` hits the prompt on the first attempt.
|
||||
//
|
||||
// The general lesson: a selector that matches SOMETHING makes a broken fixture
|
||||
// look like a product failure, and only checking WHAT it matched tells the two
|
||||
// apart.
|
||||
test.describe('403 denial text', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
await routeNodeList(page, { p: makePack('p') });
|
||||
});
|
||||
|
||||
/** Drive the REAL "Install via Git URL" entry point: footer button ->
|
||||
* customPrompt (ComfyUI's PrimeVue dialog) -> install_via_git_url ->
|
||||
* the 403 arm at common.js:254. */
|
||||
async function installViaGitUrl(page: import('@playwright/test').Page, url: string) {
|
||||
// The REAL entry point, driven exactly as a user does it: footer button ->
|
||||
// customPrompt (common.js:149 -> app.extensionManager.dialog.prompt) ->
|
||||
// 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
|
||||
// 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();
|
||||
const input = page.locator('.prompt-dialog-content input').first();
|
||||
await expect(
|
||||
input,
|
||||
'precondition: the customPrompt dialog never rendered its input, so install_via_git_url was never called and the 403 arm was never reached — the row would prove nothing.',
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
await input.fill(url);
|
||||
await input.press('Enter');
|
||||
}
|
||||
|
||||
/** The denial modal is `app.ui.dialog.element` (`show_message` ->
|
||||
* `app.ui.dialog.show`, common.js:98). Several `.comfy-modal` nodes exist,
|
||||
* so filter by the denial copy rather than taking `.first()`. */
|
||||
function denialDialog(page: import('@playwright/test').Page) {
|
||||
return page.locator('.comfy-modal').filter({ hasText: /config\.ini/ }).first();
|
||||
}
|
||||
|
||||
const MALFORMED = [
|
||||
{ label: 'empty body', body: '' },
|
||||
{ label: 'non-JSON', body: 'not json' },
|
||||
{ label: 'JSON null', body: 'null' },
|
||||
{ label: 'JSON array', body: '[]' },
|
||||
{ label: 'reason is a number', body: '{"reason": 42}' },
|
||||
{ label: 'unknown reason code', body: '{"reason": "unknown_flag"}' },
|
||||
];
|
||||
|
||||
for (const variant of MALFORMED) {
|
||||
test(`403 with ${variant.label} falls back without throwing`, async ({ page }) => {
|
||||
// The client PARSES the 403 body to learn which condition failed, and
|
||||
// `res.json()` resolves for far more than an object: `null`, `[]`,
|
||||
// `"str"` and `3` all parse cleanly. `null.reason` would throw inside the
|
||||
// render path, while `[].reason` and `{"reason":42}` yield `undefined`
|
||||
// and would put the literal string "undefined" in front of the user.
|
||||
// `install_denial_message` guards each of those shapes and falls back to
|
||||
// the calling endpoint's own condition; this row is what holds that
|
||||
// guard in place, one variant per malformed shape.
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
|
||||
await page.route('**/v2/customnode/install/git_url', async (route) => {
|
||||
await route.fulfill({ status: 403, contentType: 'application/json', body: variant.body });
|
||||
});
|
||||
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await installViaGitUrl(page, 'https://github.com/example/pack');
|
||||
|
||||
const dialog = denialDialog(page);
|
||||
await expect(
|
||||
dialog,
|
||||
`${variant.label}: the denial dialog did not render its fallback text. A 403 whose body cannot be interpreted is STILL a denial and must still be explained.`,
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
const text = (await dialog.textContent()) ?? '';
|
||||
expect(
|
||||
text,
|
||||
`${variant.label}: the rendered denial text contains the literal string "undefined" — a malformed body leaked through the reason lookup. text: ${text.slice(0, 300)}`,
|
||||
).not.toContain('undefined');
|
||||
expect(
|
||||
errors,
|
||||
`${variant.label}: the 403 handler threw. pageerrors: ${errors.join(' | ')}`,
|
||||
).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('the denial text is SELECTED BY the server reason code', async ({ page }) => {
|
||||
// CROSS-WIRED ON PURPOSE. Each install arm has its own denial text, so a
|
||||
// per-endpoint check cannot tell a server-DERIVED selection from a
|
||||
// hand-maintained constant that happens to match the endpoint it sits on.
|
||||
// Answering the git_url endpoint with the PIP reason code separates them:
|
||||
// a client that reads the server's reason names allow_pip_install, and a
|
||||
// client that prints a per-call-site literal names the other flag no
|
||||
// matter what the server said. That drift is what this row catches.
|
||||
await page.route('**/v2/customnode/install/git_url', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ reason: 'allow_pip_install' }),
|
||||
});
|
||||
});
|
||||
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await installViaGitUrl(page, 'https://github.com/example/pack');
|
||||
|
||||
const dialog = denialDialog(page);
|
||||
await expect(dialog).toBeVisible({ timeout: 10_000 });
|
||||
const text = (await dialog.textContent()) ?? '';
|
||||
|
||||
expect(
|
||||
text,
|
||||
`the server said reason="allow_pip_install" and the client must name THAT condition. Observed text names the other flag, i.e. the message is a hand-maintained constant per call site rather than being selected from the server's reason code. text: ${text.slice(0, 400)}`,
|
||||
).toContain('allow_pip_install');
|
||||
});
|
||||
|
||||
test('the denial text states the SERVER\'s restart requirement', async ({ page }) => {
|
||||
// THE STANDING GUARD FOR A HAND-MAINTAINED COPY. Only the reason CODE is
|
||||
// derived from the server; the wording lives in js/common.js, and nothing
|
||||
// makes the two move together. They had already come apart: the server
|
||||
// constants say the flag and network_mode are read once at STARTUP, so a
|
||||
// user who edits config.ini and retries is denied identically — and the
|
||||
// client text omitted it, leaving that user with a correct edit and no hint
|
||||
// that a restart is what is missing.
|
||||
//
|
||||
// The expected sentence is READ OUT of the server constants
|
||||
// (serverInstallDenialRestartClause), not typed here, so this row cannot
|
||||
// become a third copy that drifts on its own. Reword the server and the
|
||||
// client must follow; drop it from the server and this row says so.
|
||||
const restartClause = serverInstallDenialRestartClause();
|
||||
|
||||
await page.route('**/v2/customnode/install/git_url', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ reason: 'allow_git_url_install' }),
|
||||
});
|
||||
});
|
||||
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
await installViaGitUrl(page, 'https://github.com/example/pack');
|
||||
|
||||
const dialog = denialDialog(page);
|
||||
await expect(dialog).toBeVisible({ timeout: 10_000 });
|
||||
const text = (await dialog.textContent()) ?? '';
|
||||
|
||||
expect(
|
||||
text,
|
||||
`the client denial text does not state the restart requirement the SERVER states. ` +
|
||||
`A user who edits config.ini and retries is denied identically, with nothing in ` +
|
||||
`the UI saying a restart is what is missing.\n` +
|
||||
`expected (from SECURITY_MESSAGE_FLAG_*): ${JSON.stringify(restartClause)}\n` +
|
||||
`observed dialog text: ${JSON.stringify(text.slice(0, 600))}`,
|
||||
).toContain(restartClause);
|
||||
});
|
||||
});
|
||||
|
||||
// ===========================================================================
|
||||
// search-keyword highlight — the grid re-renders matched cells from
|
||||
// textContent, which would undo the formatter escaping unless the bundle
|
||||
// escapes every slice it splices (see tests/test_grid_highlight_escaping.py)
|
||||
// ===========================================================================
|
||||
|
||||
test.describe('keyword highlight re-render', () => {
|
||||
test.use({ viewport: { width: 2600, height: 1000 } });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('a keyword matching inside an escaped raw field stays inert after highlight', async ({ page }) => {
|
||||
// The keyword must match VISIBLE text: the match cache decodes markup-
|
||||
// shaped values to their text, and a bare <img> has none.
|
||||
const payload = XSS_PAYLOAD + 'PWN_author';
|
||||
await routeNodeList(page, { p: makePack('p', { author: payload }) });
|
||||
await openManagerMenu(page);
|
||||
await openCustomNodesManager(page);
|
||||
|
||||
const search = page.locator('.cn-manager-keywords').first();
|
||||
await expect(search, 'precondition: search box not rendered').toBeVisible();
|
||||
await search.fill('PWN');
|
||||
|
||||
// PRECONDITION: the highlighter actually ran on the payload cell.
|
||||
await expect(
|
||||
page.locator(`${GRID} .cn-pack-author mark`).first(),
|
||||
'precondition: no highlight marker rendered in the author cell, so the re-render path was never exercised',
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await expectInert(page, GRID, payload, 'img', 'author after keyword highlight');
|
||||
});
|
||||
});
|
||||
@@ -6,8 +6,14 @@
|
||||
* Model, Snapshot) are launched.
|
||||
*/
|
||||
|
||||
import * as fs from 'fs';
|
||||
import { execFileSync } from 'child_process';
|
||||
import * as path from 'path';
|
||||
import { type Page, expect } from '@playwright/test';
|
||||
|
||||
/** Repository root, resolved from this file (tests/playwright/helpers.ts). */
|
||||
const REPO_ROOT = path.resolve(__dirname, '..', '..');
|
||||
|
||||
/** Wait for the ComfyUI page to be fully loaded (queue ready). */
|
||||
export async function waitForComfyUI(page: Page) {
|
||||
// ComfyUI shows the canvas once the app is ready. Wait for the
|
||||
@@ -126,3 +132,238 @@ export async function assertManagerMenuVisible(page: Page) {
|
||||
const dialog = page.locator('#cm-manager-dialog').first();
|
||||
await expect(dialog).toBeVisible();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// XSS fixtures. Additive — nothing above is changed.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The payload used by every XSS row. Assertions on it have THREE legs, because
|
||||
* a payload can be neutered in a way that also deletes it:
|
||||
* (1) presence — the container's textContent contains the literal payload
|
||||
* (2) structure — no element the payload would have created exists
|
||||
* (3) execution — window.__xss_fired is undefined after render
|
||||
*/
|
||||
export const XSS_PAYLOAD = '<img src=x onerror="window.__xss_fired=1">';
|
||||
|
||||
/** Space-free variant — the `last_update` formatter cuts its value at the
|
||||
* first space with `.split(' ')[0]`, so a spaced payload would be truncated
|
||||
* and the row would pass for the wrong reason. */
|
||||
export const XSS_PAYLOAD_NOSPACE = '<img/src=x/onerror="window.__xss_fired=1">';
|
||||
|
||||
/** One `/v2/customnode/getlist` pack, shaped exactly like the live response
|
||||
* (verified against the running server: {channel, node_packs: {id: item}}). */
|
||||
export function makePack(id: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
author: 'author-' + id,
|
||||
description: 'description of ' + id,
|
||||
files: [`https://github.com/example/${id}`],
|
||||
install_type: 'git-clone',
|
||||
reference: `https://github.com/example/${id}`,
|
||||
repository: `https://github.com/example/${id}`,
|
||||
title: id,
|
||||
cnr_latest: '1.0.0',
|
||||
id,
|
||||
health: '-',
|
||||
state: 'not-installed',
|
||||
version: '1.0.0',
|
||||
'update-state': 'false',
|
||||
stars: 5,
|
||||
last_update: '2026-01-01 00:00:00',
|
||||
trust: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace the pack list the grid renders from.
|
||||
*
|
||||
* NOTE, because any result read from these fixtures depends on it:
|
||||
* page.route() REPLACES the HTTP response, so the fixture BYPASSES
|
||||
* populate_markdown. For
|
||||
* RAW fields that is what a live server can actually deliver; for
|
||||
* SERVER-ESCAPED fields it delivers input the live server currently cannot,
|
||||
* so such a fixture must be pre-transformed with `serverSanitizeTag` below —
|
||||
* otherwise the row asserts against a wire form that does not exist. */
|
||||
export async function routeNodeList(page: Page, packs: Record<string, unknown>) {
|
||||
await page.route('**/customnode/getlist**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ channel: 'default', node_packs: packs }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Seed `/v2/customnode/getmappings` — that route performs NO server-side
|
||||
* sanitization, so the values it returns are genuinely raw. */
|
||||
export async function routeMappings(page: Page, mappings: Record<string, unknown>) {
|
||||
await page.route('**/customnode/getmappings**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(mappings),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** 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');
|
||||
await page.waitForSelector('#cn-manager-dialog', { timeout: 15_000 });
|
||||
await page.waitForSelector('.cn-manager-grid, .tg-body', { timeout: 15_000 });
|
||||
await page.waitForFunction(
|
||||
() => document.querySelectorAll('.tg-body .tg-row, .cn-manager-grid tr').length > 0,
|
||||
{ timeout: 30_000, polling: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
/** The three legs, applied to one container. `payload` is the literal string
|
||||
* the user must SEE; `createdSelector` is what the payload would have built. */
|
||||
export async function expectInert(
|
||||
page: Page,
|
||||
containerSelector: string,
|
||||
payload: string,
|
||||
createdSelector: string,
|
||||
label: string,
|
||||
) {
|
||||
// ALL THREE LEGS ARE EVALUATED BEFORE ANY ASSERTION FIRES, and that is
|
||||
// load-bearing rather than stylistic. Asserting presence first and
|
||||
// short-circuiting cannot distinguish the two ways leg 1 fails:
|
||||
// - the payload was PARSED AS MARKUP (the defect) — textContent holds the
|
||||
// rendered result, not the literal source, so presence fails; or
|
||||
// - the payload NEVER RENDERED (a broken fixture) — presence fails too.
|
||||
// Those are opposite conclusions from an identical symptom, so a failure whose
|
||||
// message cannot tell them apart is not evidence of anything. The
|
||||
// diagnostic below reports all three observations on every failure.
|
||||
const text = (await page.locator(containerSelector).first().textContent()) ?? '';
|
||||
const created = await page.locator(`${containerSelector} ${createdSelector}`).count();
|
||||
const fired = await page.evaluate(() => (window as unknown as Record<string, unknown>).__xss_fired);
|
||||
|
||||
const present = text.includes(payload);
|
||||
const diagnostic =
|
||||
`${label} — three-leg result in ${containerSelector}:\n` +
|
||||
` leg 1 presence : ${present ? 'PASS (payload visible as literal text)' : 'FAIL (payload not present as literal text)'}\n` +
|
||||
` leg 2 structure : ${created === 0 ? 'PASS (no <' + createdSelector + '> constructed)' : `FAIL (${created} live <${createdSelector}> constructed — the value reached innerHTML AS MARKUP)`}\n` +
|
||||
` leg 3 execution : ${fired === undefined ? 'PASS (window.__xss_fired unset)' : `FAIL (window.__xss_fired=${JSON.stringify(fired)} — the payload EXECUTED)`}\n` +
|
||||
` READ IT THIS WAY: leg 2 or leg 3 failing = the sink is LIVE (this is the failure being demonstrated).\n` +
|
||||
` leg 1 failing while legs 2 and 3 PASS = the payload never rendered at all — a BROKEN FIXTURE, not a defect;\n` +
|
||||
` the row proves nothing in that state and must be fixed rather than reported.\n` +
|
||||
` container text (first 300 chars): ${JSON.stringify(text.slice(0, 300))}`;
|
||||
|
||||
expect(created, diagnostic).toBe(0);
|
||||
expect(fired, diagnostic).toBeUndefined();
|
||||
expect(present, diagnostic).toBe(true);
|
||||
}
|
||||
|
||||
/** Run the shipped Python renderer, including its title/name/description contract. */
|
||||
export function serverPopulateMarkdown(item: Record<string, unknown>): Record<string, any> {
|
||||
return JSON.parse(execFileSync(process.env.PYTHON || 'python3',
|
||||
[path.join(REPO_ROOT, 'tests', 'legacy_html_testutil.py')],
|
||||
{ input: JSON.stringify(item), encoding: 'utf-8' }));
|
||||
}
|
||||
|
||||
export function serverSanitizeTag(value: string): string {
|
||||
return serverPopulateMarkdown({ title: value }).title;
|
||||
}
|
||||
|
||||
/** The RESTART clause both server install-denial constants state.
|
||||
*
|
||||
* `js/common.js: INSTALL_DENIAL_MESSAGES` is a hand-written client copy of a
|
||||
* fact the SERVER owns: the install flag and `network_mode` are read once at
|
||||
* ComfyUI startup, so editing config.ini and retrying is denied identically
|
||||
* until the server is restarted. Nothing makes the two texts move together, so
|
||||
* the client copy is exactly the kind of thing that silently falls behind — it
|
||||
* already had, which is why this helper exists.
|
||||
*
|
||||
* Read from `SECURITY_MESSAGE_FLAG_GIT_URL` / `SECURITY_MESSAGE_FLAG_PIP` and
|
||||
* cross-checked against each other, so the assertion is against the SERVER's
|
||||
* wording rather than a third copy typed into the test. The word "restart" is
|
||||
* only the search key; the whole asserted sentence comes from the source. */
|
||||
export function serverInstallDenialRestartClause(): string {
|
||||
const srcPath = path.join(REPO_ROOT, 'comfyui_manager', 'legacy', 'manager_server.py');
|
||||
const src = fs.readFileSync(srcPath, 'utf-8');
|
||||
const names = ['SECURITY_MESSAGE_FLAG_GIT_URL', 'SECURITY_MESSAGE_FLAG_PIP'];
|
||||
const clauses = names.map((name) => {
|
||||
const m = new RegExp(`^${name}\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"`, 'm').exec(src);
|
||||
if (!m) {
|
||||
throw new Error(
|
||||
`serverInstallDenialRestartClause: ${name} not found as a double-quoted ` +
|
||||
`string literal in ${srcPath} — the server constant moved or changed shape.`,
|
||||
);
|
||||
}
|
||||
const sentence = m[1].split('. ').find((s) => /\brestart\b/i.test(s));
|
||||
if (!sentence) {
|
||||
throw new Error(
|
||||
`serverInstallDenialRestartClause: ${name} states no sentence mentioning a ` +
|
||||
'restart. Either the server dropped the fact (and the client copy should ' +
|
||||
'drop it too) or the wording changed — do not paper over it here.',
|
||||
);
|
||||
}
|
||||
return `${sentence.trim()}.`;
|
||||
});
|
||||
if (clauses[0] !== clauses[1]) {
|
||||
throw new Error(
|
||||
'serverInstallDenialRestartClause: the two server constants state DIFFERENT ' +
|
||||
`restart clauses, so there is no single fact to check the client against:\n` +
|
||||
` ${names[0]}: ${JSON.stringify(clauses[0])}\n` +
|
||||
` ${names[1]}: ${JSON.stringify(clauses[1])}`,
|
||||
);
|
||||
}
|
||||
return clauses[0];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Model Manager fixtures.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** One `/v2/externalmodel/getlist` model, shaped like the live response. */
|
||||
export function makeModel(name: string, overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
name,
|
||||
type: 'checkpoint',
|
||||
base: 'SD1.5',
|
||||
save_path: 'checkpoints',
|
||||
description: 'description of ' + name,
|
||||
reference: 'https://example.com/' + name,
|
||||
filename: name + '.safetensors',
|
||||
url: 'https://example.com/' + name + '.safetensors',
|
||||
size: '1.0MB',
|
||||
installed: 'False',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** Replace the model list the Model Manager grid renders from. */
|
||||
export async function routeModelList(page: Page, models: Record<string, unknown>[]) {
|
||||
await page.route('**/externalmodel/getlist**', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ models }),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Open Manager menu -> Model Manager and wait for the grid to fill. */
|
||||
export async function openModelManager(page: Page) {
|
||||
await clickMenuButton(page, 'Model Manager');
|
||||
await page.waitForSelector('#cmm-manager-dialog', { timeout: 15_000 });
|
||||
await page.waitForSelector('.cmm-manager-grid, .tg-body', { timeout: 15_000 });
|
||||
await page.waitForFunction(
|
||||
() => document.querySelectorAll('.tg-body .tg-row, .cmm-manager-grid tr').length > 0,
|
||||
{ timeout: 30_000, polling: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,576 @@
|
||||
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';
|
||||
const exported = kind === 'nodes' ? 'CustomNodesManager' : 'ModelManager';
|
||||
|
||||
for (const failure of ['network', 'http', 'json', 'shape']) {
|
||||
test(`${kind}: ${failure} batch failure clears pending controls`, async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
if (kind === 'nodes') {
|
||||
await routeNodeList(page, { victim: makePack('victim', { version: 'unknown' }) });
|
||||
} else {
|
||||
await routeModelList(page, [makeModel('victim')]);
|
||||
}
|
||||
await page.route('**/v2/manager/queue/batch', async route => {
|
||||
if (failure === 'network') return route.abort('failed');
|
||||
if (failure === 'http') return route.fulfill({ status: 500, json: { failed: [] } });
|
||||
if (failure === 'json') return route.fulfill({ contentType: 'application/json', body: 'invalid' });
|
||||
return route.fulfill({ json: { failed: {} } });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
|
||||
await page.locator(`.${prefix}-manager-grid .${prefix}-btn-install`).first().click();
|
||||
await expect(page.locator(`.${prefix}-manager-message`)).toContainText('Failed to submit installation request');
|
||||
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
|
||||
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`);
|
||||
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([]);
|
||||
});
|
||||
}
|
||||
|
||||
test(`${kind}: rejected batch names and unknown IDs reach both error displays safely`, async ({ page }) => {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', error => errors.push(String(error)));
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
const title = serverSanitizeTag('Pack & Friends ' + XSS_PAYLOAD);
|
||||
if (kind === 'nodes') {
|
||||
await routeNodeList(page, { victim: makePack('victim', { title, version: 'unknown' }) });
|
||||
} else {
|
||||
await routeModelList(page, [makeModel(title)]);
|
||||
}
|
||||
await page.route('**/v2/manager/queue/batch', async route => {
|
||||
const batch = route.request().postDataJSON();
|
||||
const items = batch[kind === 'nodes' ? 'install' : 'install_model'];
|
||||
expect(items[0].id).toBeTruthy();
|
||||
// The socket event may arrive before the HTTP rejection response.
|
||||
await page.evaluate(async () => {
|
||||
const { api } = await import('/scripts/api.js');
|
||||
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: { status: 'all-done' } }));
|
||||
});
|
||||
await route.fulfill({ json: { failed: [items[0].id, XSS_PAYLOAD] } });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
|
||||
if (kind === 'models') {
|
||||
await page.locator('.cmm-manager-type').evaluate(select => select.setAttribute('disabled', ''));
|
||||
}
|
||||
await page.locator(`.${prefix}-manager-grid .${prefix}-btn-install`).first().click();
|
||||
const message = page.locator(`.${prefix}-manager-message`);
|
||||
await expect(message).toContainText('[FAIL] Pack & Friends ' + XSS_PAYLOAD);
|
||||
await expect(message).toContainText('[FAIL] ' + XSS_PAYLOAD);
|
||||
expect(await message.locator('img').count()).toBe(0);
|
||||
const dialog = await page.evaluate(async () => {
|
||||
const { app } = await import('/scripts/app.js');
|
||||
return { text: app.ui.dialog.element.textContent, images: app.ui.dialog.element.querySelectorAll('img').length };
|
||||
});
|
||||
expect(dialog.text).toContain('[FAIL] Pack & Friends ' + XSS_PAYLOAD);
|
||||
expect(dialog.text).toContain('[FAIL] ' + XSS_PAYLOAD);
|
||||
expect(dialog.images).toBe(0);
|
||||
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
|
||||
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
|
||||
if (kind === 'models') {
|
||||
await expect(page.locator('.cmm-manager-type')).toBeDisabled();
|
||||
}
|
||||
expect(await page.evaluate(async ({ file, exported }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
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([]);
|
||||
});
|
||||
|
||||
for (const rejectedCount of [0, 1]) {
|
||||
test(`${kind}: ${rejectedCount} rejections keep accepted work pending until completion`, async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
if (kind === 'nodes') {
|
||||
await routeNodeList(page, {
|
||||
first: makePack('first', { version: 'unknown' }),
|
||||
second: makePack('second', { version: 'unknown' }),
|
||||
});
|
||||
} else {
|
||||
await routeModelList(page, [makeModel('first'), makeModel('second')]);
|
||||
}
|
||||
let completion: Record<string, unknown>;
|
||||
await page.route('**/v2/manager/queue/batch', async route => {
|
||||
const batch = route.request().postDataJSON();
|
||||
const items = batch[kind === 'nodes' ? 'install' : 'install_model'];
|
||||
const result = Object.fromEntries(items.slice(rejectedCount).map(item => [item.ui_id, 'success']));
|
||||
completion = { status: 'batch-done', batch_id: batch.batch_id,
|
||||
nodepack_result: kind === 'nodes' ? result : {}, model_result: kind === 'models' ? result : {},
|
||||
done_count: items.length - rejectedCount, total_count: items.length - rejectedCount };
|
||||
await route.fulfill({ json: { failed: items.slice(0, rejectedCount).map(item => item.id) } });
|
||||
});
|
||||
await openManagerMenu(page);
|
||||
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
|
||||
await page.evaluate(async ({ file, exported, kind, prefix }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
const manager = module[exported].instance;
|
||||
const button = manager.element.querySelector(`.${prefix}-btn-install`);
|
||||
if (kind === 'nodes') {
|
||||
await manager.installNodes(Object.values(manager.custom_nodes).map((item: any) => item.hash),
|
||||
{ target: button, label: 'Install', mode: 'install' });
|
||||
} else {
|
||||
await manager.installModels(manager.modelList, button);
|
||||
}
|
||||
}, { file, exported, kind, prefix });
|
||||
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`);
|
||||
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`);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
test(`${kind}: HTML messages preserve names and assign color through the DOM`, async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
const wire = serverSanitizeTag('Pack & Friends <Flux>');
|
||||
const result = await page.evaluate(async ({ file, exported, prefix, wire }) => {
|
||||
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
|
||||
const manager = Object.create(module[exported].prototype);
|
||||
manager.element = document.createElement('div');
|
||||
manager.element.innerHTML = `<div class="${prefix}-manager-message"></div><div class="${prefix}-manager-status"></div>`;
|
||||
document.body.append(manager.element);
|
||||
manager.showMessage(wire, 'rgb(1, 2, 3)');
|
||||
manager.showStatus(wire, '"><img src=x onerror="window.__xss_fired=1">');
|
||||
const [message, status] = manager.element.children;
|
||||
const result = { message: message.textContent, status: status.textContent,
|
||||
color: message.style.color, children: status.children.length };
|
||||
manager.showMessage('done');
|
||||
return { ...result, resetColor: message.style.color };
|
||||
}, { file, exported, prefix, wire });
|
||||
expect(result).toEqual({ message: 'Pack & Friends <Flux>', status: 'Pack & Friends <Flux>',
|
||||
color: 'rgb(1, 2, 3)', children: 0, resetColor: '' });
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
const results = await page.evaluate(async payload => {
|
||||
const { CustomNodesManager } = await import('/extensions/comfyui-manager-legacy/custom-nodes-manager.js');
|
||||
const common = await import('/extensions/comfyui-manager-legacy/common.js');
|
||||
const { api } = await import('/scripts/api.js');
|
||||
const manager = Object.create(CustomNodesManager.prototype);
|
||||
manager.element = document.createElement('div');
|
||||
manager.element.innerHTML = '<div class="cn-manager-message"></div><div class="cn-manager-status"></div>';
|
||||
document.body.append(manager.element);
|
||||
manager.grid = { getRowItemBy: () => undefined, updateCell: () => { throw new Error('Missing row updated'); } };
|
||||
const saved = api.fetchApi;
|
||||
const previousManager = common.manager_instance;
|
||||
common.setManagerInstance({ datasrc_combo: { value: 'cache' } });
|
||||
api.fetchApi = async () => ({ status: 500, statusText: payload });
|
||||
const results = [];
|
||||
try {
|
||||
for (const invoke of [
|
||||
() => manager.getMissingNodesLegacy({}, new Set()),
|
||||
() => manager.getAlternatives(),
|
||||
() => manager.installNodes([payload], { target: document.createElement('button'), mode: 'install' }),
|
||||
]) {
|
||||
await invoke();
|
||||
const message = manager.element.querySelector('.cn-manager-message');
|
||||
results.push({ text: message.textContent, images: message.querySelectorAll('img').length });
|
||||
}
|
||||
} finally {
|
||||
api.fetchApi = saved;
|
||||
common.setManagerInstance(previousManager);
|
||||
}
|
||||
return results;
|
||||
}, XSS_PAYLOAD);
|
||||
expect(results).toHaveLength(3);
|
||||
for (const result of results) {
|
||||
expect(result.text).toContain(XSS_PAYLOAD);
|
||||
expect(result.images).toBe(0);
|
||||
}
|
||||
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
|
||||
});
|
||||
|
||||
test('nodes: workflow registry IDs remain inert in the Missing Nodes dialog', async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
const result = await page.evaluate(async payload => {
|
||||
const { app } = await import('/scripts/app.js');
|
||||
const { CustomNodesManager } = await import('/extensions/comfyui-manager-legacy/custom-nodes-manager.js');
|
||||
const manager = Object.create(CustomNodesManager.prototype);
|
||||
manager.custom_nodes = {};
|
||||
manager.getMissingNodesLegacy = async () => {};
|
||||
const nodes = app.graph._nodes;
|
||||
try {
|
||||
app.graph._nodes = [{ type: 'MissingTestNode', properties: { cnr_id: payload } }];
|
||||
await manager.getMissingNodes();
|
||||
} finally {
|
||||
app.graph._nodes = nodes;
|
||||
}
|
||||
const dialog = app.ui.dialog.element;
|
||||
return { text: dialog.textContent, images: dialog.querySelectorAll('img').length };
|
||||
}, XSS_PAYLOAD + ' & Registry');
|
||||
expect(result.images).toBe(0);
|
||||
expect(result.text).toContain(XSS_PAYLOAD + ' & Registry');
|
||||
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -121,4 +121,81 @@ 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 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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* Browser-level XSS regression suite for the Model Manager UI.
|
||||
*
|
||||
* Same contract as custom-nodes-xss.spec.ts: `name` / `description` are
|
||||
* escaped by the server (populate_markdown) and rendered as-is; every other
|
||||
* model-list field is raw and must be escaped on the client. Rows assert the
|
||||
* payload is visible as literal text, constructs no element, and never runs.
|
||||
*
|
||||
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT.
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
import {
|
||||
waitForComfyUI,
|
||||
openManagerMenu,
|
||||
openModelManager,
|
||||
routeModelList,
|
||||
makeModel,
|
||||
expectInert,
|
||||
serverSanitizeTag,
|
||||
XSS_PAYLOAD,
|
||||
} from './helpers';
|
||||
|
||||
const DIALOG = '#cmm-manager-dialog';
|
||||
const GRID = '.cmm-manager-grid';
|
||||
|
||||
function trackPageErrors(page: import('@playwright/test').Page) {
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (e) => errors.push(String(e)));
|
||||
return errors;
|
||||
}
|
||||
|
||||
/** Records every innerHTML write to elements carrying `className`. */
|
||||
async function captureInnerHTMLWrites(page: import('@playwright/test').Page, className: string, slot: string) {
|
||||
await page.evaluate(({ className, slot }) => {
|
||||
const w = window as unknown as Record<string, any>;
|
||||
w[slot] = [];
|
||||
const desc = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML')!;
|
||||
Object.defineProperty(Element.prototype, 'innerHTML', {
|
||||
configurable: true,
|
||||
get() { return desc.get!.call(this); },
|
||||
set(value) {
|
||||
try {
|
||||
if ((this as Element).classList?.contains(className)) w[slot].push(String(value));
|
||||
} catch { /* never break the page under test */ }
|
||||
desc.set!.call(this, value);
|
||||
},
|
||||
});
|
||||
}, { className, slot });
|
||||
}
|
||||
|
||||
async function analyseWrites(page: import('@playwright/test').Page, slot: string, payload: string) {
|
||||
return page.evaluate(({ slot, payload }) => {
|
||||
const w = window as unknown as Record<string, any>;
|
||||
const writes: string[] = w[slot] ?? [];
|
||||
const probe = document.createElement('div');
|
||||
const parsed = writes.map((html) => {
|
||||
probe.innerHTML = html;
|
||||
return { text: probe.textContent ?? '', imgs: probe.querySelectorAll('img').length };
|
||||
});
|
||||
return {
|
||||
writes,
|
||||
carrying: parsed.filter((p) => p.text.includes(payload)).length,
|
||||
imgs: parsed.reduce((n, p) => n + p.imgs, 0),
|
||||
fired: w.__xss_fired,
|
||||
liveImgs: document.querySelectorAll('img[src="x"]').length,
|
||||
};
|
||||
}, { slot, payload });
|
||||
}
|
||||
|
||||
test.describe('model grid render sinks', () => {
|
||||
// Columns are virtualised horizontally; pin a wide viewport so every body
|
||||
// cell this suite asserts on is actually in the DOM.
|
||||
test.use({ viewport: { width: 2600, height: 1000 } });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('hostile raw fields render inert (LIVE no-user-action)', async ({ page }) => {
|
||||
await routeModelList(page, [
|
||||
makeModel('m1', { type: XSS_PAYLOAD, base: XSS_PAYLOAD }),
|
||||
makeModel('m2', { save_path: XSS_PAYLOAD, filename: XSS_PAYLOAD }),
|
||||
// a non-parsable size falls through to the raw branch of the formatter
|
||||
makeModel('m3', { size: XSS_PAYLOAD }),
|
||||
]);
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
|
||||
// The dialog covers the grid AND the type/base filter dropdowns, which are
|
||||
// built from the same raw values.
|
||||
await expectInert(page, DIALOG, XSS_PAYLOAD, 'img', 'type/base/save_path/filename/size');
|
||||
});
|
||||
|
||||
test('a server-escaped name renders decoded (no double-escape)', async ({ page }) => {
|
||||
const AUTHORED = 'Tom & Jerry <3';
|
||||
const ON_THE_WIRE = serverSanitizeTag(AUTHORED);
|
||||
expect(ON_THE_WIRE).not.toBe(AUTHORED);
|
||||
// makeModel derives filename/reference/url/description from the name;
|
||||
// those are RAW columns and would carry the wire form literally, so give
|
||||
// them values that do not contain the name.
|
||||
await routeModelList(page, [makeModel(ON_THE_WIRE, {
|
||||
filename: 'legit.safetensors', reference: 'https://example.com/legit',
|
||||
url: 'https://example.com/legit.safetensors', description: 'a legit model',
|
||||
})]);
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
|
||||
const text = (await page.locator(GRID).first().textContent()) ?? '';
|
||||
expect(text, 'the server-escaped name was escaped a second time').toContain(AUTHORED);
|
||||
expect(text, 'the wire form is visible as literal text').not.toContain(ON_THE_WIRE);
|
||||
});
|
||||
|
||||
test('missing raw fields render without throwing', async ({ page }) => {
|
||||
const errors = trackPageErrors(page);
|
||||
const bare = makeModel('bare') as Record<string, unknown>;
|
||||
delete bare.type; delete bare.base; delete bare.save_path; delete bare.filename; delete bare.size; delete bare.reference;
|
||||
await routeModelList(page, [bare]);
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
await expect(page.locator(GRID).first()).toBeVisible();
|
||||
expect(errors, `pageerrors: ${errors.join(' | ')}`).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('model URL sinks', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('name and download links carry no scheme outside the allow-list', async ({ page }) => {
|
||||
await routeModelList(page, [
|
||||
makeModel('evil', {
|
||||
reference: 'javascript:window.__xss_fired=1',
|
||||
url: 'javascript:window.__xss_fired=1',
|
||||
}),
|
||||
// an unquoted href used to let a space inject attributes
|
||||
makeModel('inject', { reference: 'https://example.com/x onmouseover=window.__xss_fired=1' }),
|
||||
// a quoted href must not be closed early by a quote inside a URL that
|
||||
// still parses as https (sanitizeUrl keeps the raw string)
|
||||
makeModel('quote', { reference: 'https://example.com/x" onmouseover="window.__xss_fired=1' }),
|
||||
makeModel('quote2', { url: 'https://example.com/y" onmouseover="window.__xss_fired=1' }),
|
||||
]);
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
|
||||
const anchors = await page.locator(`${GRID} a`).evaluateAll((els) =>
|
||||
els.map((e) => ({ href: (e as HTMLAnchorElement).href, attrs: e.getAttributeNames() })),
|
||||
);
|
||||
expect(anchors.length, 'precondition: no anchors rendered').toBeGreaterThan(0);
|
||||
|
||||
const allowed = ['http:', 'https:'];
|
||||
const offending = anchors.filter((a) => {
|
||||
const s = new URL(a.href).protocol;
|
||||
return s !== null && !allowed.includes(s);
|
||||
});
|
||||
expect(offending, `anchor href carries a scheme outside ${JSON.stringify(allowed)}`).toEqual([]);
|
||||
|
||||
const injected = anchors.filter((a) => a.attrs.some((n) => n.startsWith('on')));
|
||||
expect(injected, 'an anchor gained an event-handler attribute from the URL').toEqual([]);
|
||||
// hover the rows so an injected onmouseover would fire if present
|
||||
for (const row of await page.locator(`${GRID} .tg-body .tg-row`).all()) {
|
||||
await row.hover();
|
||||
}
|
||||
const fired = await page.evaluate(() => (window as unknown as Record<string, unknown>).__xss_fired);
|
||||
expect(fired, 'a handler injected through a URL EXECUTED').toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('model status and error sinks', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('install status and batch failure text render inert', async ({ page }) => {
|
||||
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);
|
||||
await openModelManager(page);
|
||||
|
||||
await captureInnerHTMLWrites(page, 'cmm-manager-status', '__cmmStatusWrites');
|
||||
await captureInnerHTMLWrites(page, 'cmm-manager-message', '__cmmMessageWrites');
|
||||
|
||||
const installBtn = page.locator(`${GRID} .cmm-btn-install`).first();
|
||||
await expect(installBtn, 'precondition: no install button rendered').toBeVisible({ timeout: 15_000 });
|
||||
await installBtn.click();
|
||||
|
||||
// Status line preserves the server-composed name.
|
||||
const status = await analyseWrites(page, '__cmmStatusWrites', XSS_PAYLOAD);
|
||||
expect(status.writes.length, 'precondition: nothing written to the status line').toBeGreaterThan(0);
|
||||
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. 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', batch_id, model_result: { x: payload }, done_count: 1, total_count: 1 },
|
||||
}));
|
||||
}, { 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);
|
||||
expect(message.imgs, `message write parsed into <img>: ${JSON.stringify(message.writes)}`).toBe(0);
|
||||
expect(message.liveImgs, 'an <img src=x> from the payload is live').toBe(0);
|
||||
expect(message.fired, 'the payload EXECUTED').toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test.describe('model keyword highlight re-render', () => {
|
||||
test.use({ viewport: { width: 2600, height: 1000 } });
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.goto('/');
|
||||
await waitForComfyUI(page);
|
||||
});
|
||||
|
||||
test('a keyword matching inside an escaped raw field stays inert after highlight', async ({ page }) => {
|
||||
// The keyword must match VISIBLE text (see the custom-nodes row).
|
||||
const payload = XSS_PAYLOAD + 'PWN_type';
|
||||
await routeModelList(page, [makeModel('m', { type: payload })]);
|
||||
await openManagerMenu(page);
|
||||
await openModelManager(page);
|
||||
|
||||
const search = page.locator('.cmm-manager-keywords').first();
|
||||
await expect(search, 'precondition: search box not rendered').toBeVisible();
|
||||
await search.fill('PWN');
|
||||
|
||||
// The type column has no classMap, so narrow to the cell carrying the payload text.
|
||||
await expect(
|
||||
page.locator(`${GRID} .tg-cell`).filter({ hasText: 'PWN_type' }).locator('mark').first(),
|
||||
'precondition: no highlight marker rendered in the type cell, so the re-render path was never exercised',
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await expectInert(page, DIALOG, payload, 'img', 'type after keyword highlight');
|
||||
});
|
||||
});
|
||||
@@ -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 = 5
|
||||
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,
|
||||
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, "get_channel_dict": lambda: {}})
|
||||
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,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,95 @@
|
||||
"""A Registry install whose archive cannot be extracted leaves nothing behind.
|
||||
|
||||
The install reports the failure, and removes both the downloaded archive and the
|
||||
directory it created for the nodepack, so that installing the nodepack again starts
|
||||
from a clean state instead of stopping at 'Install path already exists'. When the
|
||||
cleanup fails as well, the install still reports the extraction failure.
|
||||
"""
|
||||
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_reader
|
||||
|
||||
|
||||
def write_good(path):
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
archive.writestr('__init__.py', 'VERSION = "2.0.0"')
|
||||
|
||||
|
||||
def write_failing_midway(path):
|
||||
"""'nodes' is extracted as a file, so the entry below it cannot be created."""
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
archive.writestr('__init__.py', 'VERSION = "2.0.0"')
|
||||
archive.writestr('nodes', 'a file')
|
||||
archive.writestr('nodes/loader.py', 'a file inside a file')
|
||||
|
||||
|
||||
def write_not_a_zip(path):
|
||||
Path(path).write_bytes(b'<html>502 Bad Gateway</html>')
|
||||
|
||||
|
||||
@pytest.fixture(params=['glob', 'legacy'])
|
||||
def core(request):
|
||||
return import_reader(request.param)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def install(core, monkeypatch, tmp_path):
|
||||
"""Install 'fixture' from an archive written by the given function; return the result."""
|
||||
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(tmp_path))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', Mock(return_value=SimpleNamespace(
|
||||
status_code=200, json=lambda: {
|
||||
'id': 'version-id', 'node_id': 'fixture', 'version': '2.0.0',
|
||||
'status': 'NodeVersionStatusActive', 'downloadUrl': 'https://example.invalid/fixture.zip',
|
||||
})))
|
||||
manager = core.UnifiedManager()
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
|
||||
def run(write_archive):
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url',
|
||||
lambda url, directory, name: write_archive(Path(directory) / name))
|
||||
return manager.cnr_install('fixture', '2.0.0', instant_execution=True, no_deps=True)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
@pytest.mark.parametrize('write_archive, message', [
|
||||
(write_failing_midway, 'Failed to extract archive: fixture@2.0.0: '),
|
||||
(write_not_a_zip, 'Empty archive file: fixture@2.0.0'),
|
||||
])
|
||||
def test_failed_extraction_leaves_nothing_behind(install, tmp_path, write_archive, message):
|
||||
result = install(write_archive)
|
||||
|
||||
assert result.result is False
|
||||
assert result.msg.startswith(message)
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
|
||||
|
||||
def test_install_succeeds_after_a_failed_extraction(install, tmp_path):
|
||||
install(write_failing_midway)
|
||||
|
||||
result = install(write_good)
|
||||
|
||||
assert result.result is True, result.msg
|
||||
assert sorted(path.name for path in tmp_path.iterdir()) == ['fixture']
|
||||
assert (tmp_path / 'fixture/__init__.py').read_text() == 'VERSION = "2.0.0"'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('write_archive, message', [
|
||||
(write_failing_midway, 'Failed to extract archive: fixture@2.0.0: '),
|
||||
(write_not_a_zip, 'Empty archive file: fixture@2.0.0'),
|
||||
])
|
||||
def test_cleanup_that_fails_does_not_hide_the_extraction_failure(core, install, monkeypatch, write_archive, message):
|
||||
cleanup = Mock(side_effect=OSError('the directory cannot be removed'))
|
||||
monkeypatch.setattr(core, 'try_rmtree', cleanup)
|
||||
|
||||
result = install(write_archive)
|
||||
|
||||
assert result.result is False
|
||||
assert result.msg.startswith(message)
|
||||
assert cleanup.call_count == 1
|
||||
@@ -0,0 +1,800 @@
|
||||
"""Regression suite for the settings writer and the install-denial messages.
|
||||
|
||||
Two behaviours are pinned here, both of which used to be wrong in ways a user
|
||||
only notices after losing data or acting on misleading advice:
|
||||
|
||||
* ``write_config()`` MERGES onto what is on disk. It used to rebuild the
|
||||
``[default]`` section from the process-lifetime cache, so a hand edit made
|
||||
while the server was up, a key that ``read_config`` reads but the writer
|
||||
never writes, and any non-``[default]`` section were all silently destroyed
|
||||
by the next settings write. Those are the four merge rows below.
|
||||
* the install-denial MESSAGES name the condition that actually failed. A
|
||||
denial can be caused by the dedicated flag OR by the network mode, and a
|
||||
message that names only one of them sends the user to change a setting that
|
||||
will not help.
|
||||
|
||||
A later group covers a silent read failure: an existing but
|
||||
UNREADABLE ``config.ini`` used to fall through the same else-branch as "no
|
||||
config yet", so the writer treated it as a fresh bootstrap and overwrote the
|
||||
file it could not read.
|
||||
|
||||
RUN IT PINNED. A non-editable ``comfyui_manager`` can live in site-packages,
|
||||
and the console-script ``pytest`` does not put cwd on ``sys.path``, so an
|
||||
unpinned run silently exercises the stale installed copy:
|
||||
|
||||
PYTHONPATH=<repo abs path> pytest tests/test_config_write_and_install_denial.py
|
||||
|
||||
``test_import_origin_is_this_tree`` fails loudly when the run is unpinned,
|
||||
so a misleading pass or failure cannot go unnoticed.
|
||||
|
||||
Harness: the in-repo ``tests/_install_flags_testutil.py``, parameterized over
|
||||
BOTH config readers. ``manager_server`` is NEVER imported — importing that
|
||||
module starts a network thread — so the message rows assert against parsed
|
||||
SOURCE rather than against an imported constant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import configparser
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _install_flags_testutil import import_context, import_reader # noqa: E402
|
||||
|
||||
REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
READERS = ("glob", "legacy")
|
||||
|
||||
LEGACY_SERVER = os.path.join(REPO_ROOT, "comfyui_manager", "legacy", "manager_server.py")
|
||||
SHARED_MESSAGES = os.path.join(REPO_ROOT, "comfyui_manager", "common", "security_messages.py")
|
||||
|
||||
#: the keys ``write_config()`` owns, per tree. Deliberately spelled
|
||||
#: out rather than read back from the implementation: this is the CONTRACT the
|
||||
#: code must satisfy, not a mirror of whatever the code currently does.
|
||||
OWNED_KEYS = {
|
||||
"legacy": (
|
||||
"git_exe", "use_uv", "channel_url", "share_option", "bypass_ssl",
|
||||
"file_logging", "update_policy", "windows_selector_event_loop_policy",
|
||||
"model_download_by_agent", "downgrade_blacklist", "security_level",
|
||||
"always_lazy_install", "network_mode", "db_mode",
|
||||
"allow_git_url_install", "allow_pip_install",
|
||||
),
|
||||
"glob": (
|
||||
"git_exe", "use_uv", "use_unified_resolver", "channel_url",
|
||||
"share_option", "bypass_ssl", "file_logging", "update_policy",
|
||||
"windows_selector_event_loop_policy", "model_download_by_agent",
|
||||
"downgrade_blacklist", "security_level", "always_lazy_install",
|
||||
"network_mode", "db_mode", "verbose",
|
||||
"allow_git_url_install", "allow_pip_install",
|
||||
),
|
||||
}
|
||||
|
||||
#: read by both readers, written by neither — a settings write must leave
|
||||
#: them alone.
|
||||
UNWRITTEN_KEYS = ("http_channel_enabled", "default_cache_as_channel_url")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture(params=READERS)
|
||||
def reader_core(request):
|
||||
"""(reader_name, manager_core) for BOTH readers, cache isolated per test."""
|
||||
core = import_reader(request.param)
|
||||
saved = getattr(core, "cached_config", None)
|
||||
setattr(core, "cached_config", None)
|
||||
yield request.param, core
|
||||
setattr(core, "cached_config", saved)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def point_config(monkeypatch):
|
||||
"""Point ``context.manager_config_path`` at a path (resolved at call time
|
||||
by read_config AND write_config, so this redirects both readers)."""
|
||||
ctx = import_context()
|
||||
|
||||
def _point(path):
|
||||
monkeypatch.setattr(ctx, "manager_config_path", str(path))
|
||||
|
||||
return _point
|
||||
|
||||
|
||||
def _write_ini(path, body: str):
|
||||
with open(path, "w", encoding="utf-8") as fh:
|
||||
fh.write(body)
|
||||
return path
|
||||
|
||||
|
||||
def _read_raw(path) -> str:
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
return fh.read()
|
||||
|
||||
|
||||
def _parse_disk(path) -> configparser.ConfigParser:
|
||||
cp = configparser.ConfigParser(strict=False)
|
||||
cp.read(str(path))
|
||||
return cp
|
||||
|
||||
|
||||
def _boot(core):
|
||||
"""Simulate process start: populate the module-level config cache once."""
|
||||
setattr(core, "cached_config", None)
|
||||
return core.get_config()
|
||||
|
||||
|
||||
def _settings_change(core, key, value):
|
||||
"""The real caller shape: mutate the cache, then write."""
|
||||
core.get_config()[key] = value
|
||||
core.write_config()
|
||||
|
||||
|
||||
def _message_constants(source_path):
|
||||
"""Module-level ``SECURITY_MESSAGE_* = "..."`` assignments -> {name: text}.
|
||||
|
||||
Parsed from source: importing ``manager_server`` starts a network thread.
|
||||
"""
|
||||
tree = ast.parse(_read_raw(source_path), filename=source_path)
|
||||
out = {}
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.Assign):
|
||||
continue
|
||||
if not isinstance(node.value, ast.Constant) or not isinstance(node.value.value, str):
|
||||
continue
|
||||
for target in node.targets:
|
||||
if isinstance(target, ast.Name) and target.id.startswith("SECURITY_MESSAGE_"):
|
||||
out[target.id] = node.value.value
|
||||
return out
|
||||
|
||||
|
||||
def _flag_message_emissions(source_path):
|
||||
"""Every ``logging.error(SECURITY_MESSAGE_FLAG_*...)`` site.
|
||||
|
||||
Returns [(lineno, const_name, formatted: bool)]. ``formatted`` is True only
|
||||
when the argument is ``SECURITY_MESSAGE_FLAG_*.format(listen=args.listen)``.
|
||||
"""
|
||||
tree = ast.parse(_read_raw(source_path), filename=source_path)
|
||||
found = []
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
func = node.func
|
||||
if not (isinstance(func, ast.Attribute) and func.attr == "error"):
|
||||
continue
|
||||
if not node.args:
|
||||
continue
|
||||
arg = node.args[0]
|
||||
# bare constant: logging.error(SECURITY_MESSAGE_FLAG_GIT_URL)
|
||||
if isinstance(arg, ast.Name) and arg.id.startswith("SECURITY_MESSAGE_FLAG_"):
|
||||
found.append((node.lineno, arg.id, False))
|
||||
continue
|
||||
# formatted: logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(listen=...))
|
||||
if (isinstance(arg, ast.Call)
|
||||
and isinstance(arg.func, ast.Attribute)
|
||||
and arg.func.attr == "format"
|
||||
and isinstance(arg.func.value, ast.Name)
|
||||
and arg.func.value.id.startswith("SECURITY_MESSAGE_FLAG_")):
|
||||
kwargs = {kw.arg for kw in arg.keywords}
|
||||
listen_kw = "listen" in kwargs
|
||||
found.append((node.lineno, arg.func.value.id, listen_kw))
|
||||
return sorted(found)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# import-origin guard
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_import_origin_is_this_tree():
|
||||
"""The suite must exercise THIS checkout, not the site-packages copy.
|
||||
|
||||
Unpinned, the console-script ``pytest`` resolves ``comfyui_manager`` to the
|
||||
non-editable 4.2.2 install and every other verdict in this file becomes
|
||||
meaningless. Measured once on the pre-existing suites: an unpinned run
|
||||
reported 18 failed / 73 passed where a pinned run reported 91 passed.
|
||||
"""
|
||||
core = import_reader("legacy")
|
||||
origin = getattr(core, "__file__", None)
|
||||
assert origin, "comfyui_manager.legacy.manager_core has no __file__ to check"
|
||||
resolved = os.path.abspath(origin)
|
||||
assert resolved.startswith(REPO_ROOT + os.sep), (
|
||||
"IMPORT-ORIGIN GUARD: comfyui_manager resolved to %r, which is OUTSIDE this "
|
||||
"checkout (%r). The run is UNPINNED and is testing a different copy of "
|
||||
"the package. Re-run as: PYTHONPATH=%s pytest tests/test_config_write_and_install_denial.py"
|
||||
% (resolved, REPO_ROOT, REPO_ROOT)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# write_config merges onto disk
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_hand_edit_survives(reader_core, point_config, tmp_path):
|
||||
"""A hand edit made while the server is UP survives an
|
||||
unrelated settings change.
|
||||
|
||||
``write_config()`` rebuilds ``[default]`` from the process-lifetime
|
||||
startup snapshot, so the edit is overwritten with the stale cached value —
|
||||
the user follows the denial message, edits config.ini, touches any Manager
|
||||
setting, and is denied again after restart.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\nallow_git_url_install = false\n")
|
||||
point_config(ini)
|
||||
|
||||
_boot(core) # startup snapshot: flag False
|
||||
# user hand-edits config.ini while ComfyUI is running
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\nallow_git_url_install = true\n")
|
||||
_settings_change(core, "db_mode", "local")
|
||||
|
||||
on_disk = _parse_disk(ini)["default"].get("allow_git_url_install", "<ABSENT>")
|
||||
assert str(on_disk).lower() == "true", (
|
||||
"expected the hand-edited allow_git_url_install=true to SURVIVE "
|
||||
"an unrelated settings change; observed %r on disk (%s reader). "
|
||||
"write_config() re-wrote the key from the startup snapshot.\nfile:\n%s"
|
||||
% (on_disk, reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_unwritten_keys_survive(reader_core, point_config, tmp_path):
|
||||
"""Keys read_config reads but write_config never writes.
|
||||
|
||||
``http_channel_enabled`` gates the insecure-channel warning and
|
||||
``default_cache_as_channel_url`` steers channel resolution; every settings
|
||||
write deletes both from the file.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(
|
||||
ini,
|
||||
"[default]\nsecurity_level = normal\n"
|
||||
"http_channel_enabled = true\ndefault_cache_as_channel_url = true\n",
|
||||
)
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
_settings_change(core, "db_mode", "local")
|
||||
|
||||
section = _parse_disk(ini)["default"]
|
||||
missing = [k for k in UNWRITTEN_KEYS if k not in section]
|
||||
assert not missing, (
|
||||
"expected the read-but-never-written keys %s to SURVIVE a "
|
||||
"settings write; observed %s DELETED from the file (%s reader). "
|
||||
"write_config() rebuilds [default] from its own key list.\nfile:\n%s"
|
||||
% (list(UNWRITTEN_KEYS), missing, reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_foreign_section_survives(reader_core, point_config, tmp_path):
|
||||
"""A non-[default] section survives a settings write.
|
||||
|
||||
``write_config()`` builds a FRESH parser, assigns only
|
||||
``config['default']`` and opens the file ``'w'``, erasing every other section.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(
|
||||
ini,
|
||||
"[default]\nsecurity_level = normal\n\n"
|
||||
"[my_custom_section]\nfoo = bar\nbaz = 1\n",
|
||||
)
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
_settings_change(core, "db_mode", "local")
|
||||
|
||||
disk = _parse_disk(ini)
|
||||
assert disk.has_section("my_custom_section"), (
|
||||
"expected the foreign section [my_custom_section] to SURVIVE a "
|
||||
"settings write; observed it ERASED (%s reader).\nfile:\n%s"
|
||||
% (reader, _read_raw(ini))
|
||||
)
|
||||
assert disk["my_custom_section"].get("foo") == "bar", (
|
||||
"[my_custom_section] survived but lost its content (%s reader).\nfile:\n%s"
|
||||
% (reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_no_reclobber_after_persist(reader_core, point_config, tmp_path):
|
||||
"""A key changed once through the API, then hand-edited,
|
||||
is NOT re-clobbered by the next unrelated write.
|
||||
|
||||
This is the residual clobber that upstream's first attempt at the merge
|
||||
left behind, later fixed with ``dirty_keys.difference_update(keys)``:
|
||||
without the post-write reset the key stays dirty for the life of the
|
||||
process and every later write overlays the stale cached value again.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\ndb_mode = cache\n")
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
_settings_change(core, "db_mode", "local") # persisted through the API
|
||||
assert _parse_disk(ini)["default"].get("db_mode") == "local", (
|
||||
"precondition failed: the API change did not reach disk (%s reader)" % reader
|
||||
)
|
||||
|
||||
# user now hand-edits that SAME key while the server is up
|
||||
raw = _read_raw(ini).replace("db_mode = local", "db_mode = remote")
|
||||
_write_ini(ini, raw)
|
||||
|
||||
_settings_change(core, "share_option", "none") # UNRELATED settings change
|
||||
|
||||
on_disk = _parse_disk(ini)["default"].get("db_mode", "<ABSENT>")
|
||||
assert on_disk == "remote", (
|
||||
"expected the later hand-edit db_mode=remote to SURVIVE an "
|
||||
"unrelated settings change; observed %r (%s reader) — the previously "
|
||||
"API-changed key was written again from the stale cache.\nfile:\n%s"
|
||||
% (on_disk, reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_bootstrap_seeds_owned_keys(reader_core, point_config, tmp_path):
|
||||
"""No config.ini at all: the bootstrap path seeds the full
|
||||
owned key set.
|
||||
|
||||
A guard: the merge rework must not break first-launch bootstrap.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
point_config(ini)
|
||||
assert not os.path.exists(ini), "precondition: config.ini must be absent"
|
||||
|
||||
_boot(core)
|
||||
core.write_config()
|
||||
|
||||
assert os.path.exists(ini), (
|
||||
"bootstrap did not create config.ini (%s reader)" % reader
|
||||
)
|
||||
section = _parse_disk(ini)["default"]
|
||||
missing = [k for k in OWNED_KEYS[reader] if k not in section]
|
||||
assert not missing, (
|
||||
"bootstrap seeded an incomplete [default] for the %s reader — "
|
||||
"missing %s.\nfile:\n%s"
|
||||
% (reader, missing, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_malformed_ini_does_not_raise(reader_core, point_config, tmp_path):
|
||||
"""An unparsable config.ini must not make a settings change
|
||||
raise; the file is rewritten from the current settings.
|
||||
|
||||
A guard. Deliberately does NOT assert survival of unwritten keys or
|
||||
foreign sections: an unparsable file is exactly where the merge narrows,
|
||||
and asserting survival here would pin a behavior the design does not
|
||||
promise.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "this is not an ini file\n[[[unclosed\n= = =\n")
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
try:
|
||||
_settings_change(core, "db_mode", "local")
|
||||
except Exception as exc: # noqa: BLE001 — the point of the row
|
||||
pytest.fail(
|
||||
"a settings change raised %s on an unparsable config.ini "
|
||||
"(%s reader): %s" % (type(exc).__name__, reader, exc)
|
||||
)
|
||||
|
||||
disk = _parse_disk(ini)
|
||||
assert disk.has_section("default"), (
|
||||
"after the fallback rewrite the file has no [default] section "
|
||||
"(%s reader).\nfile:\n%s" % (reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_unowned_key_not_persisted(reader_core, point_config, tmp_path):
|
||||
"""Dirtying a key write_config does NOT own must not
|
||||
persist it (unchanged from today's behavior).
|
||||
|
||||
A guard: ownership alone decides what a write persists.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\n")
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
core.get_config()["http_channel_enabled"] = True # unowned
|
||||
_settings_change(core, "db_mode", "local") # owned
|
||||
|
||||
section = _parse_disk(ini)["default"]
|
||||
assert "http_channel_enabled" not in section, (
|
||||
"the unowned key http_channel_enabled was persisted (%s reader); "
|
||||
"write_config() must persist only keys it owns.\nfile:\n%s"
|
||||
% (reader, _read_raw(ini))
|
||||
)
|
||||
|
||||
|
||||
def test_unowned_dirty_marker_survives(reader_core, point_config, tmp_path):
|
||||
"""A dirty marker for a key this write did NOT persist
|
||||
must SURVIVE the write.
|
||||
|
||||
Rests on the ``DirtyTrackingConfig`` cache, and pins
|
||||
``difference_update(keys)`` over ``clear()``: a blanket clear would drop the
|
||||
marker for a key the write never persisted, so the change the user made to
|
||||
it would never reach disk.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\n")
|
||||
point_config(ini)
|
||||
|
||||
cached = _boot(core)
|
||||
cached["http_channel_enabled"] = True # unowned -> never persisted
|
||||
_settings_change(core, "db_mode", "local") # owned -> persisted
|
||||
|
||||
dirty = getattr(core.get_config(), "dirty_keys", None)
|
||||
assert dirty is not None, (
|
||||
"the cached config exposes no dirty_keys (%s reader) — the cache is no "
|
||||
"longer a DirtyTrackingConfig, so write_config() cannot know what "
|
||||
"actually changed and falls back to rewriting every owned key from the "
|
||||
"startup snapshot."
|
||||
% reader
|
||||
)
|
||||
assert "http_channel_enabled" in dirty, (
|
||||
"the dirty marker for the UNPERSISTED key http_channel_enabled "
|
||||
"was dropped by the write (%s reader); the post-write reset must "
|
||||
"difference_update() exactly the persisted keys, never clear() "
|
||||
". dirty_keys=%r" % (reader, dirty)
|
||||
)
|
||||
assert "db_mode" not in dirty, (
|
||||
"db_mode was persisted by this write but is still marked dirty "
|
||||
"(%s reader) — without the reset it stays dirty for the life of the "
|
||||
"process and re-clobbers a later hand-edit. dirty_keys=%r"
|
||||
% (reader, dirty)
|
||||
)
|
||||
|
||||
|
||||
def test_partial_write_leaves_file_intact(reader_core, point_config, tmp_path, monkeypatch):
|
||||
"""A settings write that fails PART-WAY must leave config.ini byte-intact.
|
||||
|
||||
The merge is what makes this matter. Foreign keys and foreign sections are
|
||||
carried across by reading them off the disk, so the file on disk is their
|
||||
ONLY home — nothing in the process holds a copy. A writer that truncates
|
||||
that file and then streams into it opens a window in which the content
|
||||
exists nowhere at all, and a crash, a kill, or a full disk inside the window
|
||||
leaves a half-written file and nothing to recover from. That is the same
|
||||
loss the merge exists to prevent, arriving through the writer instead.
|
||||
|
||||
The failure has to be INJECTED because the window is invisible from
|
||||
outside: a write that completes closes it either way, so only interrupting
|
||||
one distinguishes "wrote elsewhere and renamed" from "truncated in place".
|
||||
The injection point is ``ConfigParser.write`` mid-output, which is where a
|
||||
real ENOSPC or SIGKILL would land.
|
||||
|
||||
Two legs. The file is unchanged — the previous settings survive the failed
|
||||
attempt in full. And nothing is left behind: writing to a temporary file is
|
||||
only an improvement if the failed attempt cleans up after itself, otherwise
|
||||
the directory accumulates partial files that a later reader could mistake
|
||||
for the real one.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\ndb_mode = cache\n"
|
||||
"http_channel_enabled = true\n\n[my_section]\nfoo = bar\n")
|
||||
point_config(ini)
|
||||
|
||||
_boot(core)
|
||||
before = ini.read_bytes()
|
||||
|
||||
def _partial_then_fail(self, fp, *args, **kwargs):
|
||||
fp.write("[default]\nsecurity_level = nor")
|
||||
raise OSError(28, "No space left on device")
|
||||
|
||||
monkeypatch.setattr(configparser.ConfigParser, "write", _partial_then_fail)
|
||||
|
||||
with pytest.raises(OSError):
|
||||
_settings_change(core, "db_mode", "local")
|
||||
|
||||
after = ini.read_bytes()
|
||||
assert after == before, (
|
||||
"a settings write that failed mid-output changed config.ini (%s reader). "
|
||||
"The failed attempt must not touch the target at all — write a temporary "
|
||||
"file beside it and os.replace() it into place, so the file is either the "
|
||||
"old one or the complete new one.\nbefore:\n%s\nafter:\n%s"
|
||||
% (reader, before.decode("utf-8", "replace"), after.decode("utf-8", "replace"))
|
||||
)
|
||||
|
||||
strays = sorted(p.name for p in tmp_path.iterdir() if p.name != "config.ini")
|
||||
assert not strays, (
|
||||
"the failed write left %s behind next to config.ini (%s reader). A "
|
||||
"partial file in the settings directory outlives the failure and can be "
|
||||
"picked up later; the writer must remove its temporary file when the "
|
||||
"write does not complete." % (strays, reader)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# install-denial messages
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("const_name,flag_key", [
|
||||
("SECURITY_MESSAGE_FLAG_GIT_URL", "allow_git_url_install"),
|
||||
("SECURITY_MESSAGE_FLAG_PIP", "allow_pip_install"),
|
||||
])
|
||||
def test_flag_messages_state_both_conds(const_name, flag_key):
|
||||
"""The denial message states BOTH gate conditions and
|
||||
carries a ``{listen}`` placeholder for the live value.
|
||||
|
||||
Naming only the config flag would send a user to enable a flag that is
|
||||
often already enabled, while the real blocker is the network-position half
|
||||
of the predicate. The gate is
|
||||
``flag AND (loopback OR network_mode == 'personal_cloud')`` — WIDER than
|
||||
upstream's loopback-only, so BOTH alternatives must appear.
|
||||
"""
|
||||
consts = _message_constants(LEGACY_SERVER)
|
||||
assert const_name in consts, "%s not found in %s" % (const_name, LEGACY_SERVER)
|
||||
text = consts[const_name]
|
||||
lowered = text.lower()
|
||||
|
||||
assert flag_key in text, (
|
||||
"%s no longer names its flag %r — the e2e denial-log assertions "
|
||||
"depend on it. text=%r" % (const_name, flag_key, text)
|
||||
)
|
||||
assert "{listen}" in text, (
|
||||
"expected %s to carry a {listen} placeholder so every emission "
|
||||
"can print the LIVE --listen value; observed none. text=%r"
|
||||
% (const_name, text)
|
||||
)
|
||||
assert ("loopback" in lowered or "127.0.0.1" in text), (
|
||||
"expected %s to state the loopback half of the gate "
|
||||
"(flag AND (loopback OR personal_cloud)); observed a flag-only message. "
|
||||
"text=%r" % (const_name, text)
|
||||
)
|
||||
assert "personal_cloud" in lowered, (
|
||||
"expected %s to state the network_mode = personal_cloud "
|
||||
"alternative — our predicate is WIDER than upstream's loopback-only "
|
||||
", so omitting it makes the message contradict the gate. "
|
||||
"text=%r" % (const_name, text)
|
||||
)
|
||||
|
||||
|
||||
def test_flag_message_emissions_format():
|
||||
"""EVERY flag-message emission renders the live listen value.
|
||||
|
||||
There are 3 emission sites in legacy/manager_server.py
|
||||
(the 404 arm of install_custom_node, plus the git_url and pip endpoints);
|
||||
each must emit ``.format(listen=args.listen)``.
|
||||
"""
|
||||
emissions = _flag_message_emissions(LEGACY_SERVER)
|
||||
assert len(emissions) == 3, (
|
||||
"expected 3 flag-message emission sites in %s; found %d: %r"
|
||||
% (LEGACY_SERVER, len(emissions), emissions)
|
||||
)
|
||||
unformatted = [(line, name) for line, name, formatted in emissions if not formatted]
|
||||
assert not unformatted, (
|
||||
"these flag-denial emissions do not render the live listen value "
|
||||
"— expected SECURITY_MESSAGE_FLAG_*.format(listen=args.listen) at every "
|
||||
"site, observed a bare constant at %r. A user reading the log cannot tell "
|
||||
"which half of the gate denied them." % (unformatted,)
|
||||
)
|
||||
|
||||
|
||||
def test_flag_messages_drop_seclevel_copy():
|
||||
"""The flag messages must NOT carry the security-level copy.
|
||||
|
||||
A guard. Two existing e2e tests assert this
|
||||
substring is ABSENT from flag-denial logs
|
||||
(tests/e2e/test_e2e_secgate_legacy_flags.py:471,
|
||||
tests/e2e/test_e2e_pip_url_form.py:286); the rewrite must not trip them.
|
||||
"""
|
||||
consts = _message_constants(LEGACY_SERVER)
|
||||
offenders = {
|
||||
name: text
|
||||
for name, text in consts.items()
|
||||
if name.startswith("SECURITY_MESSAGE_FLAG_") and "security level to 'normal-'" in text
|
||||
}
|
||||
assert not offenders, (
|
||||
"flag-denial message(s) %s carry the substring "
|
||||
"\"security level to 'normal-'\", which the existing e2e suites assert is "
|
||||
"ABSENT from the denial log. The dedicated flags are decoupled from "
|
||||
"security_level, so the copy is also wrong." % sorted(offenders)
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# stale 'middle' security_level
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("source_path", [
|
||||
# ids are repo-RELATIVE on purpose: the absolute path differs per checkout,
|
||||
# so an absolute id would give the same test a different node-id in every
|
||||
# checkout and defeat node-id comparison across test runs.
|
||||
pytest.param(LEGACY_SERVER, id=os.path.relpath(LEGACY_SERVER, REPO_ROOT)),
|
||||
pytest.param(SHARED_MESSAGES, id=os.path.relpath(SHARED_MESSAGES, REPO_ROOT)),
|
||||
])
|
||||
def test_no_middle_security_level_value(source_path):
|
||||
"""No message may quote ``'middle'`` as a security_level.
|
||||
|
||||
The message that motivated this row told the user to "set the security
|
||||
level to 'middle' or 'weak'", but no such value exists (valid: strong /
|
||||
normal / normal- / weak) — a user following that copy sets an unrecognised
|
||||
value and stays denied. Both remaining definition sites are covered: the
|
||||
shared module, and the per-flag messages that are still declared next to
|
||||
the legacy gate. The internal gate-LEVEL tokens ``is_allowed_security_level
|
||||
('middle')`` are NOT security_level values and are deliberately out of
|
||||
scope — this row only inspects message CONSTANTS.
|
||||
"""
|
||||
consts = _message_constants(source_path)
|
||||
assert consts, "no SECURITY_MESSAGE_* constants found in %s" % source_path
|
||||
offenders = {name: text for name, text in consts.items() if "'middle'" in text}
|
||||
assert not offenders, (
|
||||
"message constant(s) %s in %s quote 'middle' as a security_level "
|
||||
"value, which does not exist (valid: strong / normal / normal- / weak). "
|
||||
"A user following this copy sets an unrecognised value and stays denied."
|
||||
% (sorted(offenders), os.path.relpath(source_path, REPO_ROOT))
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Silent read failure — an existing config.ini that cannot be READ must not
|
||||
# be mistaken for "no config yet"
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# MECHANISM:
|
||||
# configparser.ConfigParser.read() SWALLOWS OSError — "if a file named in
|
||||
# filenames cannot be opened, that file will be ignored". On a chmod-0o000
|
||||
# config.ini it returns [] and raises nothing, so write_config()'s narrow
|
||||
# `except (configparser.Error, UnicodeDecodeError)` never fires, the parser
|
||||
# is empty, has_section('default') is False, and the BOOTSTRAP branch runs:
|
||||
# the file is rewritten from the startup snapshot and the settings call
|
||||
# returns success. The user's config.ini is destroyed and nothing says so.
|
||||
#
|
||||
# The distinction these rows pin: an ABSENT file may legitimately be seeded
|
||||
# (the absent-file row below is allowed to seed), an UNREADABLE file may NOT —
|
||||
# because "unreadable" means
|
||||
# the content is unknown, not that there is no content.
|
||||
|
||||
#: chmod cannot make a file unreadable to root, so the scenario is unbuildable
|
||||
#: there. Skip rather than assert a false pass.
|
||||
_IS_ROOT = getattr(os, "geteuid", lambda: -1)() == 0
|
||||
_root_skip = pytest.mark.skipif(
|
||||
_IS_ROOT or os.name != "posix",
|
||||
reason="Making a config unreadable with chmod requires POSIX and a non-root user.",
|
||||
)
|
||||
|
||||
#: WRITE-ONLY (0o200), deliberately NOT 0o000.
|
||||
#:
|
||||
#: MEASURED against the unguarded writer, and this is the whole reason these
|
||||
#: rows are worth having: under 0o000 the scenario did NOT reproduce the defect.
|
||||
#: read() still swallowed the error and the bootstrap branch still ran, but a
|
||||
#: writer that truncates the target in place ALSO hit PermissionError, so the
|
||||
#: settings change raised and the file survived — for a reason that had nothing
|
||||
#: to do with a guard. Both assertions below would have passed against the
|
||||
#: unguarded writer, so a change could have "fixed" nothing and still passed.
|
||||
#:
|
||||
#: 0o200 removes that confound: the read fails silently, the write is fully
|
||||
#: permitted, and the file is destroyed with the call reporting success. Any
|
||||
#: raise observed under 0o200 therefore comes from a DELIBERATE check, never
|
||||
#: from the OS.
|
||||
_UNREADABLE_MODE = 0o200
|
||||
|
||||
|
||||
def _run_settings_change_on_unreadable(core, ini):
|
||||
"""Boot readable -> make unreadable-but-writable -> settings change.
|
||||
|
||||
Returns ``(raised, before_bytes, after_bytes)``. Permissions are ALWAYS
|
||||
restored, including on failure, so tmp_path teardown can clean up.
|
||||
"""
|
||||
_boot(core) # startup snapshot, taken while readable
|
||||
before = ini.read_bytes()
|
||||
os.chmod(ini, _UNREADABLE_MODE) # perms tightened while the server is up
|
||||
raised = None
|
||||
try:
|
||||
_settings_change(core, "db_mode", "local")
|
||||
except Exception as exc: # noqa: BLE001 — capturing IS the assertion
|
||||
raised = exc
|
||||
finally:
|
||||
os.chmod(ini, 0o600) # restore before asserting, always
|
||||
return raised, before, ini.read_bytes()
|
||||
|
||||
|
||||
@_root_skip
|
||||
def test_unreadable_config_is_loud(reader_core, point_config, tmp_path):
|
||||
"""A settings write against an UNREADABLE config.ini must
|
||||
fail LOUDLY rather than silently rewriting it.
|
||||
|
||||
Without the guard the call returns success: read() ignores the
|
||||
PermissionError, the empty parser routes into the bootstrap branch, and the
|
||||
user is told nothing while their file is replaced by defaults. This row
|
||||
asserts the raise that closes that path.
|
||||
|
||||
The file is write-only (0o200), not 0o000 — see ``_UNREADABLE_MODE``. Under
|
||||
0o000 this row passes against the UNFIXED code, because the OS blocks the
|
||||
destroying write for reasons unrelated to any guard.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\ndb_mode = cache\n"
|
||||
"http_channel_enabled = true\n\n[my_section]\nfoo = bar\n")
|
||||
point_config(ini)
|
||||
|
||||
raised, before, after = _run_settings_change_on_unreadable(core, ini)
|
||||
|
||||
assert raised is not None, (
|
||||
"expected the settings change to RAISE on an unreadable "
|
||||
"config.ini; it returned success (%s reader). The file was %s. "
|
||||
"config.read() swallows the PermissionError, so the empty parser falls "
|
||||
"into the bootstrap branch and rewrites the file from the startup "
|
||||
"snapshot — silent data loss.\nbefore:\n%s\nafter:\n%s"
|
||||
% (reader,
|
||||
"DESTROYED" if after != before else "left intact",
|
||||
before.decode("utf-8", "replace"),
|
||||
after.decode("utf-8", "replace"))
|
||||
)
|
||||
|
||||
|
||||
@_root_skip
|
||||
def test_unreadable_config_file_intact(reader_core, point_config, tmp_path):
|
||||
"""The unreadable config.ini must be left BYTE-UNTOUCHED.
|
||||
|
||||
Separate node from the loudness row on purpose: "was it loud" and "was
|
||||
the file preserved" are independent failures, and a fix that only logs a
|
||||
warning satisfies loudness while still destroying the file. Keeping them
|
||||
apart means neither can be satisfied by sacrificing the other.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
_write_ini(ini, "[default]\nsecurity_level = normal\ndb_mode = cache\n"
|
||||
"http_channel_enabled = true\n\n[my_section]\nfoo = bar\n")
|
||||
point_config(ini)
|
||||
|
||||
_raised, before, after = _run_settings_change_on_unreadable(core, ini)
|
||||
|
||||
assert after == before, (
|
||||
"the unreadable config.ini was MODIFIED by a settings change "
|
||||
"(%s reader) — an unreadable file's content is UNKNOWN, so rewriting it "
|
||||
"destroys data the process never saw. Hand-maintained keys and foreign "
|
||||
"sections are gone.\nbefore:\n%s\nafter:\n%s"
|
||||
% (reader,
|
||||
before.decode("utf-8", "replace"),
|
||||
after.decode("utf-8", "replace"))
|
||||
)
|
||||
|
||||
|
||||
def test_genuine_bootstrap_still_seeds(reader_core, point_config, tmp_path):
|
||||
"""A genuinely ABSENT config.ini must still be seeded.
|
||||
|
||||
The guard that keeps the read-failure check honest: it must distinguish
|
||||
"no file, so there is nothing to lose" from "unreadable file, so the
|
||||
content is unknown". A check that refuses BOTH breaks first-launch
|
||||
bootstrap; this row fails if it does.
|
||||
|
||||
test_bootstrap_seeds_owned_keys already covers the seeding itself; what
|
||||
this row adds is the CONTRAST — it is the absent-file half of the same
|
||||
decision the two unreadable-file rows pin the other half of, so a future
|
||||
reader sees why one branch may write and the other may not.
|
||||
"""
|
||||
reader, core = reader_core
|
||||
ini = tmp_path / "config.ini"
|
||||
point_config(ini)
|
||||
assert not os.path.exists(ini), "precondition: config.ini must be absent"
|
||||
|
||||
_boot(core)
|
||||
try:
|
||||
core.write_config()
|
||||
except Exception as exc: # noqa: BLE001 — the point of the row
|
||||
pytest.fail(
|
||||
"genuine bootstrap (absent config.ini) raised %s on the "
|
||||
"%s reader: %s. The read-failure guard must refuse UNREADABLE files "
|
||||
"without refusing ABSENT ones."
|
||||
% (type(exc).__name__, reader, exc)
|
||||
)
|
||||
|
||||
assert os.path.exists(ini), (
|
||||
"bootstrap did not create config.ini (%s reader)" % reader
|
||||
)
|
||||
section = _parse_disk(ini)["default"]
|
||||
missing = [k for k in OWNED_KEYS[reader] if k not in section]
|
||||
assert not missing, (
|
||||
"bootstrap seeded an incomplete [default] for the %s reader "
|
||||
"— missing %s.\nfile:\n%s"
|
||||
% (reader, missing, _read_raw(ini))
|
||||
)
|
||||
@@ -0,0 +1,581 @@
|
||||
"""Exercise the real CNR client and both install implementations."""
|
||||
|
||||
import asyncio
|
||||
import ast
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def security():
|
||||
import_context()
|
||||
from comfyui_manager.common import manager_security
|
||||
|
||||
return manager_security
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cnr_client(monkeypatch):
|
||||
import_context()
|
||||
from comfy.cli_args import args
|
||||
from comfyui_manager.common import cnr_utils
|
||||
|
||||
monkeypatch.setattr(args, 'listen', '0.0.0.0')
|
||||
return cnr_utils
|
||||
|
||||
|
||||
@pytest.fixture(params=['glob', 'legacy'])
|
||||
def core(request, cnr_client, monkeypatch, tmp_path):
|
||||
core = import_reader(request.param)
|
||||
monkeypatch.setattr(core.manager_funcs, 'is_flagged_install_allowed', lambda node_id: False)
|
||||
monkeypatch.setattr(core, 'get_config', lambda: {'allow_flagged_nodepack_install': False})
|
||||
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(tmp_path))
|
||||
return core
|
||||
|
||||
|
||||
def api_response(status='NodeVersionStatusFlagged', http=200):
|
||||
return SimpleNamespace(status_code=http, json=lambda: {
|
||||
'id': 'version-id', 'node_id': 'fixture', 'version': '2.0.0',
|
||||
'status': status, 'downloadUrl': 'https://example.invalid/fixture.zip',
|
||||
})
|
||||
|
||||
|
||||
@pytest.mark.parametrize('permission,listed_id,allowed,whitelist_logged', [
|
||||
(None, None, True, False), ('true', 'FiXtUrE', True, False), ('false', None, False, False),
|
||||
('false', 'FiXtUrE', True, True), ('false', 'other', False, False),
|
||||
])
|
||||
def test_cli_install_uses_parent_policy(
|
||||
core, monkeypatch, caplog, permission, listed_id, allowed, whitelist_logged, tmp_path,
|
||||
):
|
||||
from comfy.cli_args import args
|
||||
|
||||
# Restore children use Python's default WARNING threshold.
|
||||
caplog.set_level(logging.WARNING)
|
||||
monkeypatch.delenv('_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED', raising=False)
|
||||
if permission is not None:
|
||||
monkeypatch.setenv('_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED', permission)
|
||||
monkeypatch.delenv('_COMFYUI_MANAGER_CNR_WHITELIST_DIR', raising=False)
|
||||
if listed_id is not None:
|
||||
parent_dir = tmp_path / 'parent-manager'
|
||||
parent_dir.mkdir()
|
||||
(parent_dir / 'nodepack-whitelist.list').write_text(listed_id + '\n')
|
||||
monkeypatch.setenv('_COMFYUI_MANAGER_CNR_WHITELIST_DIR', str(parent_dir))
|
||||
# The child's local config cannot expand the server's permission.
|
||||
monkeypatch.setattr(core.context, 'manager_files_path', str(tmp_path))
|
||||
(tmp_path / 'nodepack-whitelist.list').write_text('fixture\n')
|
||||
monkeypatch.setattr(core, 'manager_funcs', core.ManagerFuncs())
|
||||
monkeypatch.setattr(args, 'listen', '127.0.0.1' if permission == 'false' else '0.0.0.0')
|
||||
monkeypatch.setattr(core, 'get_config', lambda: {'allow_flagged_nodepack_install': permission == 'false'})
|
||||
get = Mock(return_value=api_response())
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
download = Mock(side_effect=lambda url, directory, name: (tmp_path / name).write_bytes(b'fixture'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_util, 'extract_package_as_zip', lambda *a: ['__init__.py'])
|
||||
manager = core.UnifiedManager()
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
|
||||
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
|
||||
|
||||
assert result.result is allowed, result.msg
|
||||
assert get.call_count == 1
|
||||
assert download.call_count == int(allowed)
|
||||
records = [record for record in caplog.records if 'permitted by nodepack whitelist' in record.getMessage()]
|
||||
assert len(records) == int(whitelist_logged)
|
||||
if whitelist_logged:
|
||||
assert records[0].levelno == logging.WARNING
|
||||
assert "'fixture'" in records[0].getMessage()
|
||||
assert str(parent_dir / 'nodepack-whitelist.list') in records[0].getMessage()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('listen,allowed', [
|
||||
('127.0.0.1', True), ('127.2.3.4', True), ('::1', True),
|
||||
('127.0.0.1,::1', True), ('0.0.0.0', False), ('::', False),
|
||||
('192.168.1.2', False), ('127.0.0.1,0.0.0.0', False),
|
||||
('0.0.0.0,::', False), ('', False), ('127.0.0.1,', False),
|
||||
])
|
||||
def test_listener_policy(security, listen, allowed):
|
||||
assert security.is_cnr_install_allowed('NodeVersionStatusFlagged', False, listen) is allowed
|
||||
assert security.is_cnr_install_allowed('NodeVersionStatusFlagged', True, listen) is True
|
||||
|
||||
|
||||
def test_hostname_requires_all_resolved_addresses_to_be_loopback(security, monkeypatch):
|
||||
def addresses(*hosts):
|
||||
return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (host, 0)) for host in hosts]
|
||||
|
||||
monkeypatch.setattr(socket, 'getaddrinfo', lambda *a, **k: addresses('127.0.0.1', '::1'))
|
||||
assert security.is_loopback_listener('localhost')
|
||||
monkeypatch.setattr(socket, 'getaddrinfo', lambda *a, **k: addresses('127.0.0.1', '192.168.1.2'))
|
||||
assert not security.is_loopback_listener('localhost')
|
||||
monkeypatch.setattr(socket, 'getaddrinfo', Mock(side_effect=socket.gaierror))
|
||||
assert not security.is_loopback_listener('invalid.invalid')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('contents,node_id,allowed', [
|
||||
(None, 'fixture', False), ('', 'fixture', False), ('# fixture\n', 'fixture', False),
|
||||
('fixture\n', 'fixture', True), ('\ufefffixture\n', 'fixture', True),
|
||||
(' \tfixture \r\n', 'fixture', True), ('fixture # approved\n', 'fixture', True),
|
||||
('Fixture\n', 'fixture', True), ('fixture\n', 'FIXTURE', True),
|
||||
('FiXtUrE\n', 'fIxTuRe', True), ('fixture-other\n', 'fixture', False),
|
||||
('fixture@2.0.0\n', 'fixture', False), ('*\nfixture-*\n', 'fixture', False),
|
||||
('https://example.invalid/fixture\n', 'fixture', False),
|
||||
])
|
||||
def test_whitelist_matches_pack_ids(security, tmp_path, contents, node_id, allowed):
|
||||
path = tmp_path / 'nodepack-whitelist.list'
|
||||
if contents is not None:
|
||||
path.write_text(contents, encoding='utf-8')
|
||||
assert security.is_flagged_nodepack_whitelisted(node_id, tmp_path) is allowed
|
||||
|
||||
|
||||
def test_whitelist_template_grants_no_exceptions(security, tmp_path):
|
||||
manager_dir = tmp_path / 'user/__manager'
|
||||
security.ensure_nodepack_whitelist(manager_dir)
|
||||
contents = (manager_dir / 'nodepack-whitelist.list').read_text()
|
||||
assert contents.strip() and all(line.lstrip().startswith('#') for line in contents.splitlines() if line.strip())
|
||||
assert not security.is_flagged_nodepack_whitelisted('comfyui-impact-pack', manager_dir)
|
||||
assert not security.is_flagged_nodepack_whitelisted('comfyui-inspire-pack', manager_dir)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('contents', [b'', b'# Keep this comment\nFiXtUrE\n'])
|
||||
def test_whitelist_template_preserves_existing_file(security, tmp_path, caplog, contents):
|
||||
path = tmp_path / 'nodepack-whitelist.list'
|
||||
path.write_bytes(contents)
|
||||
security.ensure_nodepack_whitelist(tmp_path)
|
||||
assert path.read_bytes() == contents
|
||||
assert 'Cannot create nodepack whitelist' not in caplog.text
|
||||
|
||||
|
||||
def test_whitelist_template_write_failure_is_logged(security, tmp_path, monkeypatch, caplog):
|
||||
monkeypatch.setattr(security, 'open', Mock(side_effect=PermissionError('read-only')), raising=False)
|
||||
security.ensure_nodepack_whitelist(tmp_path)
|
||||
assert not (tmp_path / 'nodepack-whitelist.list').exists()
|
||||
assert 'Cannot create nodepack whitelist' in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['manager-file', 'dangling-symlink', 'whitelist-directory'])
|
||||
def test_whitelist_template_path_failure_is_logged(security, tmp_path, caplog, failure):
|
||||
manager_dir = tmp_path / 'manager'
|
||||
path = manager_dir / 'nodepack-whitelist.list'
|
||||
if failure == 'manager-file':
|
||||
manager_dir.write_text('existing file')
|
||||
else:
|
||||
manager_dir.mkdir()
|
||||
if failure == 'dangling-symlink':
|
||||
try:
|
||||
path.symlink_to(manager_dir / 'missing-target')
|
||||
except (OSError, NotImplementedError) as exc:
|
||||
pytest.skip(f'Symlinks unavailable: {exc}')
|
||||
else:
|
||||
path.mkdir()
|
||||
|
||||
security.ensure_nodepack_whitelist(manager_dir)
|
||||
|
||||
assert 'Cannot create nodepack whitelist' in caplog.text
|
||||
assert str(path) in caplog.text
|
||||
if failure == 'manager-file':
|
||||
assert manager_dir.read_text() == 'existing file'
|
||||
elif failure == 'dangling-symlink':
|
||||
assert path.is_symlink() and not path.exists()
|
||||
else:
|
||||
assert path.is_dir()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prefix,suffix', [
|
||||
(b'', b''),
|
||||
(b'', b'comfyui-impact-pack\n'),
|
||||
(b'comfyui-impact-pack\n' + b'# comment\n' * 2048, b''),
|
||||
], ids=['utf16-appended', 'utf8-after-utf16', 'match-before-invalid-encoding'])
|
||||
def test_mixed_encoding_whitelist_is_rejected(security, tmp_path, caplog, prefix, suffix):
|
||||
security.ensure_nodepack_whitelist(tmp_path)
|
||||
path = tmp_path / 'nodepack-whitelist.list'
|
||||
with path.open('ab') as file:
|
||||
file.write(prefix + 'comfyui-impact-pack\r\n'.encode('utf-16-le') + suffix)
|
||||
|
||||
assert not security.is_flagged_nodepack_whitelisted('comfyui-impact-pack', tmp_path)
|
||||
assert 'NUL' in caplog.text and 'UTF-8' in caplog.text
|
||||
assert str(path) in caplog.text
|
||||
assert 'permitted by nodepack whitelist' not in caplog.text
|
||||
|
||||
|
||||
def test_whitelist_reloads_edits_and_removal(security, tmp_path):
|
||||
path = tmp_path / 'nodepack-whitelist.list'
|
||||
path.write_text('fixture\n', encoding='utf-8')
|
||||
assert security.is_flagged_nodepack_whitelisted('fixture', tmp_path)
|
||||
path.write_text('other\n', encoding='utf-8')
|
||||
assert not security.is_flagged_nodepack_whitelisted('fixture', tmp_path)
|
||||
assert security.is_flagged_nodepack_whitelisted('other', tmp_path)
|
||||
path.unlink()
|
||||
assert not security.is_flagged_nodepack_whitelisted('other', tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['encoding', 'directory'])
|
||||
def test_unreadable_whitelist_grants_no_exceptions(security, tmp_path, caplog, failure):
|
||||
path = tmp_path / 'nodepack-whitelist.list'
|
||||
if failure == 'encoding':
|
||||
# The invalid byte is beyond the first read buffer. A matching first
|
||||
# line must not hide a decoding failure later in the file.
|
||||
path.write_bytes(b'fixture\n' + b'# comment\n' * 2048 + b'\xff')
|
||||
else:
|
||||
path.mkdir()
|
||||
assert not security.is_flagged_nodepack_whitelisted('fixture', tmp_path)
|
||||
assert 'Cannot read flagged nodepack whitelist' in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,permission,allowed', [
|
||||
('NodeVersionStatusActive', False, True), ('NodeVersionStatusPending', False, True),
|
||||
('NodeVersionStatusFlagged', False, False), ('NodeVersionStatusFlagged', True, True),
|
||||
])
|
||||
def test_install_uses_status_from_one_response(core, monkeypatch, tmp_path, caplog, status, permission, allowed):
|
||||
get = Mock(return_value=api_response(status))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
monkeypatch.setattr(core.manager_funcs, 'is_flagged_install_allowed', lambda node_id: permission)
|
||||
download = Mock(side_effect=lambda url, directory, name: (tmp_path / name).write_bytes(b'fixture'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_util, 'extract_package_as_zip', lambda *a: ['__init__.py'])
|
||||
manager = core.UnifiedManager()
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
|
||||
result = manager.cnr_install('fixture', '2.0.0')
|
||||
|
||||
assert result.result is allowed, result.msg
|
||||
if not allowed:
|
||||
assert result.msg == ('This action is not allowed by the current security configuration. '
|
||||
'See the terminal for details.')
|
||||
for detail in ('--listen 127.0.0.1', '--listen ::1', '0.0.0.0', '[default]',
|
||||
'allow_flagged_nodepack_install = true', 'config.ini',
|
||||
'trusted private network', 'Restart ComfyUI'):
|
||||
assert detail in caplog.text
|
||||
else:
|
||||
assert 'allow_flagged_nodepack_install' not in caplog.text
|
||||
assert get.call_count == 1
|
||||
assert download.call_count == int(allowed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('http', [403, 404, 500])
|
||||
def test_override_does_not_bypass_registry_refusal(core, monkeypatch, tmp_path, http):
|
||||
monkeypatch.setattr(core.manager_funcs, 'is_flagged_install_allowed', lambda node_id: True)
|
||||
get = Mock(return_value=api_response(http=http))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
download = Mock(side_effect=AssertionError('Registry refusal must prevent downloading'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
manager = core.UnifiedManager()
|
||||
|
||||
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
|
||||
|
||||
assert result.result is False
|
||||
assert result.msg == 'not available node: fixture@2.0.0'
|
||||
assert get.call_count == 1
|
||||
assert download.call_count == 0
|
||||
assert not (tmp_path / 'fixture').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['install', 'lazy', 'instant'])
|
||||
def test_direct_install_and_switch_reject_before_side_effects(core, monkeypatch, operation):
|
||||
get = Mock(return_value=api_response())
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
download = Mock(side_effect=AssertionError('download must not happen'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', download)
|
||||
manager = core.UnifiedManager()
|
||||
manager.reserve_cnr_switch = Mock(side_effect=AssertionError('reservation must not happen'))
|
||||
if operation == 'install':
|
||||
result = manager.cnr_install('fixture', '2.0.0')
|
||||
else:
|
||||
result = manager.cnr_switch_version('fixture', '2.0.0', instant_execution=operation == 'instant')
|
||||
assert result.result is False
|
||||
assert result.msg == ('This action is not allowed by the current security configuration. '
|
||||
'See the terminal for details.')
|
||||
assert get.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['install', 'lazy', 'instant'])
|
||||
@pytest.mark.parametrize('return_postinstall', [False, True])
|
||||
def test_direct_cnr_execution_and_postinstall(core, monkeypatch, tmp_path, operation, return_postinstall):
|
||||
get = Mock(return_value=api_response('NodeVersionStatusActive'))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
|
||||
def download(url, directory, name):
|
||||
with zipfile.ZipFile(Path(directory) / name, 'w') as archive:
|
||||
archive.writestr('__init__.py', 'VERSION = "2.0.0"')
|
||||
|
||||
downloader = Mock(side_effect=download)
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', downloader)
|
||||
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', downloader)
|
||||
manager = core.UnifiedManager()
|
||||
installed = tmp_path / 'fixture'
|
||||
if operation != 'install':
|
||||
installed.mkdir()
|
||||
(installed / '__init__.py').write_text('original')
|
||||
(installed / '.tracking').write_text('__init__.py')
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(installed))
|
||||
manager.reserve_cnr_switch = Mock(return_value=True)
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
|
||||
if operation == 'install':
|
||||
result = manager.cnr_install('fixture', instant_execution=True,
|
||||
no_deps=True, return_postinstall=return_postinstall)
|
||||
else:
|
||||
result = manager.cnr_switch_version('fixture', instant_execution=operation == 'instant',
|
||||
no_deps=True, return_postinstall=return_postinstall)
|
||||
|
||||
assert result.result is True, result.msg
|
||||
assert result.target == ('2.0.0' if operation == 'instant' else None)
|
||||
effect = manager.reserve_cnr_switch if operation == 'lazy' else manager.execute_install_script
|
||||
assert effect.call_count == int(not return_postinstall)
|
||||
if return_postinstall:
|
||||
assert result.postinstall()
|
||||
assert effect.call_count == 1
|
||||
assert get.call_count == 1
|
||||
assert downloader.call_count == int(operation != 'lazy')
|
||||
assert (installed / '__init__.py').read_text() == (
|
||||
'original' if operation == 'lazy' else 'VERSION = "2.0.0"')
|
||||
if operation == 'lazy':
|
||||
assert effect.call_args.args[1] == 'https://example.invalid/fixture.zip'
|
||||
assert effect.call_args.args[-2:] == (True, 'NodeVersionStatusActive')
|
||||
else:
|
||||
assert effect.call_args.kwargs == {'instant_execution': True, 'no_deps': True}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', ['nightly', 'disabled-cnr', 'new'])
|
||||
def test_rejection_preserves_existing_install_state(core, monkeypatch, installed):
|
||||
get = Mock(return_value=api_response())
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
manager = core.UnifiedManager()
|
||||
manager.is_enabled = lambda node, version=None: installed == 'nightly' and version == 'nightly'
|
||||
manager.is_disabled = lambda node, version=None: installed == 'disabled-cnr' and version == 'cnr'
|
||||
manager.unified_disable = Mock(side_effect=AssertionError('must not disable'))
|
||||
manager.unified_enable = Mock(side_effect=AssertionError('must not enable'))
|
||||
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
|
||||
assert result.result is False
|
||||
assert result.msg == ('This action is not allowed by the current security configuration. '
|
||||
'See the terminal for details.')
|
||||
assert get.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', ['new', 'cnr', 'disabled-cnr'])
|
||||
@pytest.mark.parametrize('instant', [False, True])
|
||||
def test_preflight_response_is_reused(core, monkeypatch, installed, instant, tmp_path):
|
||||
get = Mock(return_value=api_response('NodeVersionStatusActive'))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
manager = core.UnifiedManager()
|
||||
manager.is_enabled = lambda node, version=None: installed == 'cnr' and version == 'cnr'
|
||||
manager.is_disabled = lambda node, version=None: installed == 'disabled-cnr' and version == 'cnr'
|
||||
manager.unified_enable = Mock()
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
|
||||
manager.reserve_cnr_switch = Mock(return_value=True)
|
||||
manager.execute_install_script = Mock(return_value=True)
|
||||
marker = tmp_path / 'fixture/__init__.py'
|
||||
if installed != 'new':
|
||||
marker.parent.mkdir()
|
||||
marker.write_text('original')
|
||||
(marker.parent / '.tracking').write_text('__init__.py')
|
||||
|
||||
def download(url, directory, name):
|
||||
(tmp_path / name).write_bytes(b'fixture')
|
||||
|
||||
def extract(archive, directory):
|
||||
(Path(directory) / '__init__.py').write_text('replacement')
|
||||
return ['__init__.py']
|
||||
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', download)
|
||||
monkeypatch.setattr(core.manager_util, 'extract_package_as_zip', extract)
|
||||
result = asyncio.run(manager.install_by_id('fixture', '2.0.0', instant_execution=instant))
|
||||
assert result.result is True
|
||||
assert get.call_count == 1
|
||||
if installed == 'new' or instant:
|
||||
assert marker.read_text() == 'replacement'
|
||||
manager.reserve_cnr_switch.assert_not_called()
|
||||
manager.execute_install_script.assert_called_once()
|
||||
assert manager.execute_install_script.call_args.kwargs['instant_execution'] is instant
|
||||
else:
|
||||
assert marker.read_text() == 'original'
|
||||
manager.reserve_cnr_switch.assert_called_once()
|
||||
manager.execute_install_script.assert_not_called()
|
||||
|
||||
|
||||
def test_exact_installed_version_enables_without_registry_lookup(core, monkeypatch, tmp_path):
|
||||
manager = core.UnifiedManager()
|
||||
installed = tmp_path / '.disabled/fixture@2_0_0'
|
||||
installed.mkdir(parents=True)
|
||||
(installed / '__init__.py').write_text('already installed')
|
||||
manager.cnr_inactive_nodes['fixture'] = {'2.0.0': str(installed)}
|
||||
query = Mock(side_effect=AssertionError('activation must not query the Registry'))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', query)
|
||||
manager.execute_install_script = Mock(side_effect=AssertionError('activation must not install'))
|
||||
|
||||
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
|
||||
|
||||
assert result.result is True
|
||||
assert (tmp_path / 'fixture/__init__.py').read_text() == 'already installed'
|
||||
assert not installed.exists()
|
||||
assert manager.active_nodes['fixture'] == ('2.0.0', str(tmp_path / 'fixture'))
|
||||
assert asyncio.run(manager.install_by_id('fixture', '2.0.0')).action == 'skip'
|
||||
query.assert_not_called()
|
||||
manager.execute_install_script.assert_not_called()
|
||||
|
||||
|
||||
def test_snapshot_denial_preserves_existing_pack_without_retry(core, monkeypatch, tmp_path):
|
||||
manager = core.UnifiedManager()
|
||||
monkeypatch.setattr(core, 'unified_manager', manager)
|
||||
installed = tmp_path / 'fixture'
|
||||
installed.mkdir()
|
||||
marker = installed / '__init__.py'
|
||||
marker.write_text('original')
|
||||
(installed / '.tracking').write_text('__init__.py')
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(installed))
|
||||
manager.reload = AsyncMock()
|
||||
manager.get_custom_nodes = AsyncMock(return_value={})
|
||||
monkeypatch.setattr(core.manager_util, 'restore_pip_snapshot', Mock())
|
||||
get = Mock(return_value=api_response())
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
download = Mock(side_effect=AssertionError('denied target must not download'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
monkeypatch.setattr(core.manager_downloader, 'basic_download_url', download)
|
||||
snapshot = tmp_path / 'snapshot.json'
|
||||
snapshot.write_text(json.dumps({'cnr_custom_nodes': {'fixture': '2.0.0'},
|
||||
'git_custom_nodes': {}, 'file_custom_nodes': []}))
|
||||
|
||||
asyncio.run(core.restore_snapshot(str(snapshot)))
|
||||
|
||||
assert marker.read_text() == 'original'
|
||||
assert manager.active_nodes['fixture'] == ('1.0.0', str(installed))
|
||||
assert download.call_count == 0
|
||||
assert get.call_count == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
|
||||
def test_reinstall_stops_when_removal_fails(core, monkeypatch):
|
||||
get = Mock(return_value=api_response('NodeVersionStatusActive'))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', get)
|
||||
download = Mock(side_effect=AssertionError('failed removal must prevent downloading'))
|
||||
monkeypatch.setattr(core.manager_downloader, 'download_url', download)
|
||||
manager = core.UnifiedManager()
|
||||
manager.unified_uninstall = Mock(return_value=core.ManagedResult('uninstall').fail('cannot remove'))
|
||||
|
||||
result = asyncio.run(manager.reinstall_by_id('fixture', '2.0.0'))
|
||||
|
||||
assert result.result is False
|
||||
assert result.msg == 'cannot remove'
|
||||
assert get.call_count == 1
|
||||
assert download.call_count == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('core', ['legacy'], indirect=True)
|
||||
@pytest.mark.parametrize('version,source', [
|
||||
('nightly', 'manifest'), ('unknown', 'manifest'),
|
||||
('nightly', 'cnr'), ('nightly', 'system-repository'),
|
||||
])
|
||||
def test_git_reinstall_replaces_existing_pack(core, monkeypatch, tmp_path, version, source):
|
||||
manager = core.UnifiedManager()
|
||||
directory = 'repository-name' if source == 'system-repository' else 'fixture'
|
||||
installed = tmp_path / directory
|
||||
installed.mkdir()
|
||||
marker = installed / 'original.txt'
|
||||
marker.write_text('original')
|
||||
repo_url = f'https://example.invalid/{directory}'
|
||||
if version == 'nightly':
|
||||
manager.active_nodes['fixture'] = ('nightly', str(installed))
|
||||
else:
|
||||
manager.unknown_active_nodes['fixture'] = (repo_url, str(installed))
|
||||
manager.get_custom_nodes = AsyncMock(return_value={
|
||||
'fixture': {'repository': repo_url, 'files': [repo_url]},
|
||||
} if source == 'manifest' else {})
|
||||
if source != 'manifest':
|
||||
manager.cnr_map['fixture'] = {
|
||||
'repository': repo_url, 'publisher': None if source == 'system-repository' else {'id': 'fixture'},
|
||||
}
|
||||
manager.processed_install.add(str(installed / 'install.py'))
|
||||
execute = Mock(return_value=True)
|
||||
monkeypatch.setattr(core, 'try_install_script', execute)
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', Mock(side_effect=AssertionError('Git needs no CNR install query')))
|
||||
|
||||
def clone(url, path, **kwargs):
|
||||
assert url == repo_url
|
||||
assert not Path(path).exists()
|
||||
Path(path).mkdir()
|
||||
(Path(path) / 'replacement.txt').write_text('installed')
|
||||
(Path(path) / 'install.py').write_text('')
|
||||
assert manager.execute_install_script(url, path)
|
||||
return core.ManagedResult('install-git')
|
||||
|
||||
manager.repo_install = Mock(side_effect=clone)
|
||||
result = asyncio.run(manager.reinstall_by_id('fixture', version))
|
||||
|
||||
assert result.result is True
|
||||
assert not marker.exists()
|
||||
assert (installed / 'replacement.txt').read_text() == 'installed'
|
||||
assert manager.repo_install.call_count == 1
|
||||
assert execute.call_count == 1
|
||||
assert execute.call_args.args[1] == str(installed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,override,listen,whitelist,allowed', [
|
||||
('NodeVersionStatusActive', False, '0.0.0.0', '', True),
|
||||
('NodeVersionStatusFlagged', False, '127.0.0.1', '', True),
|
||||
('NodeVersionStatusFlagged', True, '0.0.0.0', '', True),
|
||||
('NodeVersionStatusFlagged', False, '0.0.0.0', '', False),
|
||||
('NodeVersionStatusFlagged', False, '0.0.0.0', 'FiXtUrE\n', True),
|
||||
('NodeVersionStatusFlagged', False, '0.0.0.0', 'fixture-other\n', False),
|
||||
('', False, '127.0.0.1', '', True),
|
||||
('', True, '0.0.0.0', '', True),
|
||||
('', False, '0.0.0.0', '', False),
|
||||
('', False, '0.0.0.0', 'FiXtUrE\n', True),
|
||||
('', False, '0.0.0.0', 'fixture-other\n', False),
|
||||
])
|
||||
def test_deferred_switch_reuses_status_with_current_policy(
|
||||
cnr_client, monkeypatch, tmp_path, caplog, status, override, listen, whitelist, allowed,
|
||||
):
|
||||
from comfy.cli_args import args as server_args
|
||||
from comfyui_manager.common import manager_downloader, manager_security, manager_util
|
||||
|
||||
monkeypatch.setattr(server_args, 'listen', listen)
|
||||
(tmp_path / 'nodepack-whitelist.list').write_text(whitelist)
|
||||
# Execute the real function without running prestartup's module-level startup.
|
||||
source = Path(cnr_client.__file__).parents[1] / 'prestartup_script.py'
|
||||
tree = ast.parse(source.read_text())
|
||||
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef)
|
||||
and node.name == 'execute_lazy_cnr_switch')
|
||||
scope = {'__package__': 'comfyui_manager', 'os': os, 'logging': logging,
|
||||
'manager_downloader': manager_downloader, 'manager_util': manager_util,
|
||||
'manager_security': manager_security,
|
||||
'manager_files_path': str(tmp_path),
|
||||
'default_conf': {'allow_flagged_nodepack_install': str(override)}}
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), str(source), 'exec'), scope)
|
||||
from_path, to_path = tmp_path / 'fixture@1.0.0', tmp_path / 'fixture'
|
||||
from_path.mkdir()
|
||||
(from_path / '.tracking').write_text('__init__.py')
|
||||
(from_path / '__init__.py').write_text('')
|
||||
|
||||
def download(url, directory, name):
|
||||
(Path(directory) / name).write_bytes(b'fixture')
|
||||
|
||||
downloader = Mock(side_effect=download)
|
||||
monkeypatch.setattr(manager_downloader, 'download_url', downloader)
|
||||
monkeypatch.setattr(manager_util, 'extract_package_as_zip', lambda *a: {'__init__.py'})
|
||||
monkeypatch.setattr(cnr_client.requests, 'get', Mock(side_effect=AssertionError('no CNR query')))
|
||||
args = ('fixture', 'https://example.invalid/archive.zip', str(from_path), str(to_path), False, str(tmp_path))
|
||||
# Omit the added argument for the old on-disk reservation format.
|
||||
result = scope['execute_lazy_cnr_switch'](*args, *([status] if status else []))
|
||||
assert result is allowed
|
||||
assert downloader.call_count == int(allowed)
|
||||
assert to_path.exists() is allowed
|
||||
assert from_path.exists() is not allowed
|
||||
if not allowed and not status:
|
||||
assert 'stored Registry status is missing' in caplog.text
|
||||
assert 'Request the installation again' in caplog.text
|
||||
elif not allowed:
|
||||
for detail in ('--listen 127.0.0.1', '--listen ::1', '[default]',
|
||||
'allow_flagged_nodepack_install = true', 'Restart ComfyUI'):
|
||||
assert detail in caplog.text
|
||||
else:
|
||||
assert 'allow_flagged_nodepack_install' not in caplog.text
|
||||
@@ -0,0 +1,110 @@
|
||||
"""The glob server installs only models that are in the model list.
|
||||
|
||||
Each case hands a model to the real `do_install_model`, the worker step that
|
||||
queue/install_model and queue/task both reach, with the real
|
||||
`check_whitelist_for_model`. The downloaders are replaced by a recorder, so
|
||||
nothing is fetched.
|
||||
"""
|
||||
import ast
|
||||
import asyncio
|
||||
import importlib.util
|
||||
import logging
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
SAFETENSORS = {"name": "a", "type": "checkpoint", "base": "SDXL", "save_path": "checkpoints",
|
||||
"filename": "a.safetensors", "url": "https://huggingface.co/a/resolve/main/a.safetensors"}
|
||||
PICKLE = {"name": "b", "type": "upscale", "base": "upscale", "save_path": "upscale_models",
|
||||
"filename": "b.pth", "url": "https://huggingface.co/b/resolve/main/b.pth"}
|
||||
OTHER_URL = "http://other.example/x.bin"
|
||||
|
||||
|
||||
def load_data_models(monkeypatch):
|
||||
spec = importlib.util.spec_from_file_location("_generated_models", PACKAGE / "data_models/generated_models.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
monkeypatch.setitem(sys.modules, spec.name, module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def install(monkeypatch, item, channel_models, default_models, local_models=(), high_plus=False):
|
||||
"""What the worker answers for `item`, and the downloads it started.
|
||||
|
||||
The three arguments are the model lists of the configured channel, of the default
|
||||
channel, and of the local file; None stands for a list file without `models`.
|
||||
"""
|
||||
models = load_data_models(monkeypatch)
|
||||
monkeypatch.setitem(sys.modules, "comfyui_manager.data_models", models)
|
||||
|
||||
async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
listed = {"cache": default_models if channel_url == "default" else channel_models, "local": local_models}[mode]
|
||||
return {} if listed is None else {"models": list(listed)}
|
||||
|
||||
downloads = []
|
||||
core = SimpleNamespace(get_data_by_mode=get_data_by_mode, get_config=lambda: {"model_download_by_agent": True})
|
||||
whitelist = load_functions(PACKAGE / "glob/utils/model_utils.py", {"check_whitelist_for_model"}, {"core": core})
|
||||
namespace = {
|
||||
"logging": logging, "core": core,
|
||||
"ModelMetadata": models.ModelMetadata, "OperationResult": models.OperationResult,
|
||||
"ManagerDatabaseSource": models.ManagerDatabaseSource,
|
||||
"SECURITY_MESSAGE_NORMAL_MINUS_MODEL": "",
|
||||
"security_utils": SimpleNamespace(is_allowed_security_level=lambda level: level != "high+" or high_plus),
|
||||
"model_utils": SimpleNamespace(check_whitelist_for_model=whitelist["check_whitelist_for_model"],
|
||||
get_model_path=lambda data: f"{data['save_path']}/{data['filename']}"),
|
||||
"download_url_with_agent": lambda url, path: downloads.append((url, path)) or True,
|
||||
}
|
||||
path = PACKAGE / "glob/manager_server.py"
|
||||
nodes = [node for node in ast.walk(ast.parse(path.read_text(encoding="utf-8")))
|
||||
if isinstance(node, ast.AsyncFunctionDef) and node.name == "do_install_model"]
|
||||
assert len(nodes) == 1
|
||||
exec(compile(ast.Module(nodes, []), str(path), "exec"), namespace)
|
||||
|
||||
result = asyncio.run(namespace["do_install_model"](models.ModelMetadata.model_validate(item)))
|
||||
return result, downloads
|
||||
|
||||
|
||||
def test_listed_model_is_downloaded_from_its_listed_url(monkeypatch):
|
||||
result, downloads = install(monkeypatch, PICKLE, [SAFETENSORS, PICKLE], [SAFETENSORS, PICKLE])
|
||||
assert result == "success"
|
||||
assert downloads == [(PICKLE["url"], "upscale_models/b.pth")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("change", [
|
||||
{"url": OTHER_URL},
|
||||
{"save_path": "custom_nodes/SomePack"},
|
||||
{"filename": "__init__.py"},
|
||||
], ids=["other url", "other folder", "other filename"])
|
||||
def test_unlisted_model_is_not_downloaded(monkeypatch, change):
|
||||
result, downloads = install(monkeypatch, {**SAFETENSORS, **change}, [SAFETENSORS, PICKLE], [SAFETENSORS, PICKLE])
|
||||
assert result != "success"
|
||||
assert downloads == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("high_plus, expected", [(False, []), (True, [(PICKLE["url"], "upscale_models/b.pth")])],
|
||||
ids=["high+ not allowed", "high+ allowed"])
|
||||
def test_pickle_model_outside_the_default_channel_needs_high_plus(monkeypatch, high_plus, expected):
|
||||
result, downloads = install(monkeypatch, PICKLE, [SAFETENSORS, PICKLE], [SAFETENSORS], high_plus=high_plus)
|
||||
assert (result == "success") == bool(expected)
|
||||
assert downloads == expected
|
||||
|
||||
|
||||
def test_pickle_model_is_refused_when_the_default_list_has_no_models(monkeypatch):
|
||||
result, downloads = install(monkeypatch, PICKLE, [SAFETENSORS, PICKLE], None)
|
||||
assert isinstance(result, str) and result != "success"
|
||||
assert downloads == []
|
||||
|
||||
|
||||
def test_model_listed_only_in_the_local_file_is_downloaded(monkeypatch):
|
||||
result, downloads = install(monkeypatch, SAFETENSORS, [], [], local_models=[SAFETENSORS])
|
||||
assert result == "success"
|
||||
assert downloads == [(SAFETENSORS["url"], "checkpoints/a.safetensors")]
|
||||
|
||||
|
||||
def test_safetensors_model_outside_the_default_channel_is_downloaded(monkeypatch):
|
||||
result, downloads = install(monkeypatch, SAFETENSORS, [SAFETENSORS], [])
|
||||
assert result == "success"
|
||||
assert downloads == [(SAFETENSORS["url"], "checkpoints/a.safetensors")]
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Exercise Manager's search overrides with the shipped TurboGrid in Chromium.
|
||||
|
||||
Browser cases require Playwright and its Chromium install. All requests are
|
||||
intercepted locally; no ComfyUI server or external services are used.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "comfyui_manager" / "js"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename", ["custom-nodes-manager.js", "model-manager.js"])
|
||||
def test_searching_managers_use_the_safe_grid(filename):
|
||||
source = (JS / filename).read_text()
|
||||
assert 'import ManagerGrid from "./manager-grid.js"' in source
|
||||
assert "new ManagerGrid(container)" in source
|
||||
assert 'from "./turbogrid.esm.js"' not in source
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def browser():
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
with playwright.sync_playwright() as driver:
|
||||
if not Path(driver.chromium.executable_path).exists():
|
||||
pytest.skip("install Chromium with: playwright install chromium")
|
||||
instance = driver.chromium.launch()
|
||||
yield instance
|
||||
instance.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def page(browser):
|
||||
page = browser.new_page()
|
||||
|
||||
def route(request):
|
||||
name = request.request.url.rsplit("/", 1)[-1]
|
||||
if name in {"manager-grid.js", "turbogrid.esm.js"}:
|
||||
request.fulfill(path=str(JS / name), content_type="text/javascript")
|
||||
elif request.request.url == "http://manager.test/":
|
||||
request.fulfill(
|
||||
body='<div id="grid" style="width:800px;height:300px"></div>',
|
||||
content_type="text/html",
|
||||
)
|
||||
else:
|
||||
request.abort()
|
||||
|
||||
page.route("**/*", route)
|
||||
page.goto("http://manager.test/")
|
||||
page.evaluate("""async () => {
|
||||
const {default: ManagerGrid} = await import('/manager-grid.js');
|
||||
window.grid = new ManagerGrid(document.getElementById('grid'));
|
||||
grid.setData({columns: [{id: 'name', name: 'Name'}], rows: []});
|
||||
grid.render();
|
||||
}""")
|
||||
page.wait_for_function("window.grid.options !== undefined")
|
||||
yield page
|
||||
page.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("keyword", ["before", "img", "after"])
|
||||
def test_highlighting_keeps_all_text_inert(page, keyword):
|
||||
text = 'before <img src="/bad.png" onerror="window.__probe=1"> & after'
|
||||
result = page.evaluate("""({text, keyword}) => {
|
||||
const cell = document.createElement('div');
|
||||
cell.id = 'cell';
|
||||
cell.textContent = text;
|
||||
document.body.append(cell);
|
||||
grid.highlightKeywordsSync([cell], [keyword]);
|
||||
return {text: cell.textContent, marks: [...cell.querySelectorAll('mark')].map(x => x.textContent),
|
||||
images: cell.querySelectorAll('img').length};
|
||||
}""", {"text": text, "keyword": keyword})
|
||||
assert result == {"text": text, "marks": [keyword], "images": 0}
|
||||
assert page.evaluate("window.__probe === undefined")
|
||||
|
||||
|
||||
def test_keyword_order_continues_across_text_nodes(page):
|
||||
result = page.evaluate("""() => {
|
||||
const cell = document.createElement('div');
|
||||
cell.innerHTML = '<b>Alpha</b> beta Alpha beta <svg><text>Alpha</text></svg><textarea>beta</textarea>';
|
||||
grid.highlightKeywordsSync([cell], ['alpha', 'beta']);
|
||||
return [...cell.querySelectorAll('mark')].map(x => x.textContent);
|
||||
}""")
|
||||
assert result == ["Alpha", "beta", "Alpha", "beta"]
|
||||
|
||||
|
||||
def test_search_cache_does_not_execute_html(page):
|
||||
result = page.evaluate("""() => {
|
||||
const row = {description: '<img src="/bad.png" onerror="window.__probe=1"><b>Alpha</b> & Beta'};
|
||||
const matched = grid.highlightKeywordsFilter(row, ['description'], 'alpha & beta');
|
||||
return {matched, text: row.tg_text_description, highlight: row.tg_highlight_description};
|
||||
}""")
|
||||
assert result == {"matched": True, "text": "Alpha & Beta", "highlight": True}
|
||||
page.wait_for_timeout(50)
|
||||
assert page.evaluate("window.__probe === undefined")
|
||||
|
||||
|
||||
def test_search_preserves_order_columns_and_empty_query(page):
|
||||
result = page.evaluate("""() => {
|
||||
const row = {name: 'Alpha Beta', description: 'Gamma', missing: null, count: 0};
|
||||
const columns = ['name', 'description', 'missing', 'count'];
|
||||
const ordered = grid.highlightKeywordsFilter(row, columns, ' ALPHA beta ');
|
||||
const reversed = grid.highlightKeywordsFilter(row, columns, 'beta alpha');
|
||||
const acrossColumns = grid.highlightKeywordsFilter(row, columns, 'alpha gamma');
|
||||
const zero = grid.highlightKeywordsFilter(row, columns, '0');
|
||||
const empty = grid.highlightKeywordsFilter(row, columns, '');
|
||||
return {ordered, reversed, acrossColumns, zero, empty,
|
||||
flags: columns.map(column => row['tg_highlight_' + column])};
|
||||
}""")
|
||||
assert result == {"ordered": True, "reversed": False, "acrossColumns": False,
|
||||
"zero": True, "empty": True, "flags": [None] * 4}
|
||||
|
||||
|
||||
def test_custom_text_generator_and_cache_keys(page):
|
||||
result = page.evaluate("""() => {
|
||||
Object.assign(grid.options.highlightKeywords, {
|
||||
textKey: 'text_', highlightKey: 'mark_',
|
||||
textGenerator: (row, column) => row[column].label
|
||||
});
|
||||
const row = {name: {label: '<b>Model</b> <Flux>'}};
|
||||
const matched = grid.highlightKeywordsFilter(row, ['name'], 'model <flux>');
|
||||
return {matched, text: row.text_name, highlight: row.mark_name};
|
||||
}""")
|
||||
assert result == {"matched": True, "text": "Model <Flux>", "highlight": True}
|
||||
|
||||
|
||||
def test_grid_render_search_and_clear_keep_names_readable(page):
|
||||
page.evaluate("""() => {
|
||||
window.query = 'flux';
|
||||
grid.setOption({rowFilter: row => grid.highlightKeywordsFilter(row, ['name'], window.query)});
|
||||
grid.setData({columns: [{id: 'name', name: 'Name'}], rows: [
|
||||
{name: 'Model <Flux> <img src=x onerror=window.__probe=1>'},
|
||||
{name: 'Other Model'}
|
||||
]});
|
||||
grid.render();
|
||||
}""")
|
||||
page.wait_for_function("document.querySelectorAll('#grid mark').length === 1")
|
||||
assert page.locator("#grid mark").all_text_contents() == ["Flux"]
|
||||
assert page.evaluate("grid.viewRows.length") == 1
|
||||
assert page.locator("#grid img").count() == 0
|
||||
assert 'Model <Flux> <img src=x onerror=window.__probe=1>' in page.locator("#grid").inner_text()
|
||||
|
||||
page.evaluate("window.query = 'other'; grid.update()")
|
||||
page.wait_for_function("document.querySelector('#grid mark')?.textContent === 'Other'")
|
||||
assert page.evaluate("grid.viewRows.length") == 1
|
||||
|
||||
page.evaluate("window.query = ''; grid.update()")
|
||||
page.wait_for_function("grid.viewRows.length === 2 && !document.querySelector('#grid mark')")
|
||||
assert page.locator("#grid img").count() == 0
|
||||
assert page.evaluate("window.__probe === undefined")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("filename,column,value,query,nonmatching", [
|
||||
("custom-nodes-manager.js", "title", "Pack <Flux>", "<flux>", "<flux>"),
|
||||
("custom-nodes-manager.js", "description", "Notes <Flux>", "<flux>", "<flux>"),
|
||||
("custom-nodes-manager.js", "author", "Writer <Alias>", "<alias>", "<alias>"),
|
||||
("custom-nodes-manager.js", "author", "Writer <Alias>", "<alias>", "<alias>"),
|
||||
("model-manager.js", "name", "Model <Flux>", "<flux>", "<flux>"),
|
||||
("model-manager.js", "description", "<b>Notes</b> <Flux>", "<flux>", "<flux>"),
|
||||
("model-manager.js", "filename", "model <Flux>", "<flux>", "<flux>"),
|
||||
("model-manager.js", "type", "Type <Flux>", "<flux>", "<flux>"),
|
||||
])
|
||||
def test_manager_search_matches_visible_text(page, filename, column, value, query, nonmatching):
|
||||
source = (JS / filename).read_text()
|
||||
init_body = source.split("\tinitGrid() {", 1)[1].split("\n\t}\n", 1)[0]
|
||||
common = (JS / "common.js").read_text()
|
||||
sanitizer = common.split("export function sanitizeHTML(str) {", 1)[1].split("\n}", 1)[0]
|
||||
escape_cell = "undefined"
|
||||
if filename == "model-manager.js":
|
||||
escape_cell = source.split("const escapeCell = ", 1)[1].split(";", 1)[0]
|
||||
page.evaluate("""({init_body, sanitizer, escape_cell, column, value, query}) => {
|
||||
const sanitizeHTML = new Function('str', sanitizer);
|
||||
const escapeCell = new Function('sanitizeHTML', `return (${escape_cell})`)(sanitizeHTML);
|
||||
const initGrid = new Function('ManagerGrid', 'createFlyover', 'gridId', 'sanitizeHTML', 'escapeCell',
|
||||
`return function initGrid() {${init_body}}`)(grid.constructor, () => ({}), 'review', sanitizeHTML, escapeCell);
|
||||
const element = document.createElement('div');
|
||||
element.innerHTML = '<div id="tested-grid" class="cn-manager-grid cmm-manager-grid" style="width:800px;height:300px"></div>';
|
||||
document.body.append(element);
|
||||
window.manager = {element, keywords: query, showStatus() {}, handleFlyoverHover() {}, createFlyover: () => ({}), hasAlternatives: () => false};
|
||||
initGrid.call(manager);
|
||||
manager.grid.setData({columns: [{id: column, name: column}], rows: [{[column]: value}]});
|
||||
manager.grid.render();
|
||||
}""", {"init_body": init_body, "sanitizer": sanitizer, "escape_cell": escape_cell,
|
||||
"column": column, "value": value, "query": query})
|
||||
page.wait_for_function("manager.grid.viewRows !== undefined")
|
||||
assert page.evaluate("manager.grid.viewRows.length") == 1
|
||||
page.evaluate("query => {manager.keywords=query;}", nonmatching)
|
||||
assert not page.evaluate("manager.grid.options.rowFilter(manager.grid.data.rows[0])")
|
||||
@@ -43,7 +43,7 @@ import pytest
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _install_flags_testutil import import_context, import_reader # noqa: E402
|
||||
|
||||
FLAG_KEYS = ("allow_git_url_install", "allow_pip_install")
|
||||
FLAG_KEYS = ("allow_git_url_install", "allow_pip_install", "allow_flagged_nodepack_install")
|
||||
READERS = ("glob", "legacy")
|
||||
|
||||
|
||||
@@ -169,7 +169,8 @@ def test_sc21_write_config_round_trips_both_flags(
|
||||
ini = _write_ini(
|
||||
tmp_path,
|
||||
"[default]\nsecurity_level = normal\n"
|
||||
"allow_git_url_install = true\nallow_pip_install = true\n",
|
||||
"allow_git_url_install = true\nallow_pip_install = true\n"
|
||||
"allow_flagged_nodepack_install = true\n",
|
||||
)
|
||||
point_config(ini)
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""The legacy server installs a listed model only from its listed url (#3428).
|
||||
|
||||
Each case hands a request to the real `_install_model` with the real
|
||||
`check_whitelist_for_model`; the route only queues, so nothing is fetched.
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
LISTED = {"name": "a", "type": "checkpoint", "base": "SDXL", "save_path": "checkpoints",
|
||||
"filename": "a.safetensors", "url": "https://huggingface.co/a/resolve/main/a.safetensors"}
|
||||
OTHER = {**LISTED, "name": "b", "filename": "b.safetensors", "url": "https://huggingface.co/b/resolve/main/b.safetensors"}
|
||||
|
||||
|
||||
def install(item):
|
||||
"""The status `_install_model` answers for `item`, and what it queued."""
|
||||
async def get_data_by_mode(mode, filename, channel_url=None):
|
||||
return {"models": [LISTED, OTHER]}
|
||||
|
||||
queued = []
|
||||
functions = load_functions(PACKAGE / "legacy/manager_server.py", {"check_whitelist_for_model", "_install_model"}, {
|
||||
"web": web, "logging": logging, "core": SimpleNamespace(get_data_by_mode=get_data_by_mode),
|
||||
"is_allowed_security_level": lambda level: level == "middle+", "temp_queue_batch": queued,
|
||||
})
|
||||
return asyncio.run(functions["_install_model"](item)).status, queued
|
||||
|
||||
|
||||
def test_listed_model_is_queued_with_its_listed_url():
|
||||
status, queued = install({**LISTED, "ui_id": "u"})
|
||||
assert status == 200
|
||||
assert [(kind, item["url"]) for kind, (_, item) in queued] == [("install-model", LISTED["url"])]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [{"url": OTHER["url"]}, {}], ids=["url of another entry", "no url"])
|
||||
def test_listed_name_with_another_url_is_refused(url):
|
||||
status, queued = install({**{k: v for k, v in LISTED.items() if k != "url"}, **url, "ui_id": "u"})
|
||||
assert status == 400
|
||||
assert queued == []
|
||||
@@ -240,7 +240,7 @@ def test_p1_install_custom_node_denies_at_strong_403(ms, gate):
|
||||
"""P1 deny: at sl=strong the middle+ entry gate (first statement of
|
||||
_install_custom_node) returns 403 before any further processing."""
|
||||
gate("strong", is_local_mode=True)
|
||||
resp = _run(ms._install_custom_node({}))
|
||||
resp = _run(ms._queue_node_install({}, "install"))
|
||||
assert resp.status == 403
|
||||
|
||||
|
||||
@@ -263,7 +263,7 @@ def test_p1_install_custom_node_passes_entry_gate_at_normal(ms, gate, monkeypatc
|
||||
"channel": "default",
|
||||
"mode": "cache",
|
||||
}
|
||||
resp = _run(ms._install_custom_node(dict(json_data)))
|
||||
resp = _run(ms._queue_node_install(dict(json_data), "install"))
|
||||
assert resp.status == 200
|
||||
|
||||
|
||||
@@ -286,7 +286,7 @@ def test_p2_unknown_pip_block_denies_404_even_at_weak(ms, gate, monkeypatch):
|
||||
"channel": "default",
|
||||
"mode": "cache",
|
||||
}
|
||||
resp = _run(ms._install_custom_node(dict(json_data)))
|
||||
resp = _run(ms._queue_node_install(dict(json_data), "install"))
|
||||
assert resp.status == 404
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""The startup logger reports the terminal state of the stream it wraps (#3259).
|
||||
|
||||
A logger that always answered "not a terminal" made colorama, and any other library that
|
||||
asks, strip its colors and hide its progress display for the whole session.
|
||||
"""
|
||||
import ast
|
||||
import io
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
SOURCE = Path(__file__).resolve().parent.parent / "comfyui_manager" / "prestartup_script.py"
|
||||
|
||||
|
||||
class Stream:
|
||||
def __init__(self, tty, closed=False):
|
||||
self._tty = tty
|
||||
self.closed = closed
|
||||
|
||||
def isatty(self):
|
||||
return self._tty
|
||||
|
||||
|
||||
class StreamWithoutClosed:
|
||||
def isatty(self):
|
||||
return True
|
||||
|
||||
|
||||
class StreamThatCannotBeAsked:
|
||||
closed = False
|
||||
|
||||
def isatty(self):
|
||||
raise OSError("The handle is invalid")
|
||||
|
||||
|
||||
def loggers(stdout, stderr, log_closed=False):
|
||||
"""Lift ComfyUIManagerLogger; importing prestartup_script would run the startup."""
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
node = next(n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.ClassDef) and n.name == "ComfyUIManagerLogger")
|
||||
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed)}
|
||||
exec(textwrap.dedent("\n".join(source.splitlines()[node.lineno - 1:node.end_lineno])), scope)
|
||||
return scope["ComfyUIManagerLogger"](True), scope["ComfyUIManagerLogger"](False)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ansitowin32(monkeypatch):
|
||||
"""colorama's stream wrapper, with its probe of the Windows console answered.
|
||||
|
||||
On a console that takes the Win32 calls colorama converts the codes itself and strips
|
||||
them from the text, whatever the stream answers, so the cases would depend on where
|
||||
they are run."""
|
||||
module = pytest.importorskip("colorama.ansitowin32")
|
||||
monkeypatch.setattr(module, "winapi_test", lambda *_: False)
|
||||
return module
|
||||
|
||||
|
||||
def detached_stream():
|
||||
stream = io.TextIOWrapper(io.BytesIO())
|
||||
stream.detach()
|
||||
return stream
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stdout_tty, stderr_tty", [(True, True), (True, False), (False, True), (False, False)])
|
||||
def test_isatty_follows_each_wrapped_stream(stdout_tty, stderr_tty):
|
||||
out, err = loggers(Stream(stdout_tty), Stream(stderr_tty))
|
||||
|
||||
assert (out.isatty(), err.isatty()) == (stdout_tty, stderr_tty)
|
||||
|
||||
|
||||
def test_closed_follows_each_wrapped_stream():
|
||||
out, err = loggers(Stream(True, closed=False), Stream(True, closed=True))
|
||||
|
||||
assert (out.closed, err.closed) == (False, True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream", [object(), StreamThatCannotBeAsked(), detached_stream()])
|
||||
def test_stream_that_cannot_answer_is_not_a_terminal(stream):
|
||||
out, _ = loggers(stream, stream)
|
||||
|
||||
assert out.isatty() is False
|
||||
|
||||
|
||||
def test_stream_without_closed_is_open():
|
||||
out, _ = loggers(StreamWithoutClosed(), StreamWithoutClosed())
|
||||
|
||||
assert out.closed is False
|
||||
|
||||
|
||||
def test_detached_stream_is_closed():
|
||||
out, _ = loggers(detached_stream(), detached_stream())
|
||||
|
||||
assert out.closed is True
|
||||
|
||||
|
||||
def test_logger_is_closed_once_its_log_file_is_closed():
|
||||
out, err = loggers(Stream(True), Stream(True), log_closed=True)
|
||||
|
||||
assert (out.closed, err.closed) == (True, True)
|
||||
|
||||
|
||||
def test_colorama_writes_no_reset_at_exit_after_the_log_file_is_closed(ansitowin32):
|
||||
out, _ = loggers(Stream(True), Stream(True), log_closed=True)
|
||||
written = []
|
||||
out.write = written.append
|
||||
|
||||
# what colorama's exit handler does with the stream it was given at init()
|
||||
ansitowin32.AnsiToWin32(out).reset_all()
|
||||
|
||||
assert written == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stream, kept", [
|
||||
(Stream(True), True),
|
||||
(Stream(False), False),
|
||||
(StreamWithoutClosed(), True),
|
||||
(StreamThatCannotBeAsked(), False),
|
||||
])
|
||||
def test_colorama_keeps_ansi_codes_only_on_a_terminal(ansitowin32, stream, kept):
|
||||
out, _ = loggers(stream, stream)
|
||||
|
||||
assert ansitowin32.AnsiToWin32(out).strip is (not kept)
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Exercise the full legacy populate_markdown path, including readable URLs."""
|
||||
from html.parser import HTMLParser
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import load_renderer
|
||||
|
||||
RENDERER = load_renderer()
|
||||
|
||||
|
||||
def compose(text):
|
||||
item = {'description': text}
|
||||
RENDERER['populate_markdown'](item)
|
||||
return item['description']
|
||||
|
||||
|
||||
class Elements(HTMLParser):
|
||||
def __init__(self, markup):
|
||||
super().__init__()
|
||||
self.elements = []
|
||||
self.text = ''
|
||||
self.feed(markup)
|
||||
self.close()
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
self.elements.append((tag, dict(attrs)))
|
||||
|
||||
def handle_data(self, text):
|
||||
self.text += text
|
||||
|
||||
|
||||
def anchor(markup):
|
||||
parsed = Elements(markup)
|
||||
assert [tag for tag, _ in parsed.elements] == ['a']
|
||||
attrs = parsed.elements[0][1]
|
||||
assert set(attrs) == {'href', 'target', 'rel'}
|
||||
assert attrs['target'] == '_blank'
|
||||
assert set(attrs['rel'].split()) == {'noopener', 'noreferrer'}
|
||||
return attrs
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
"' onmouseover='alert`1`", '" onclick="alert`1`',
|
||||
'https://example.com/a\"><img src=x onerror=alert`1`>',
|
||||
])
|
||||
def test_attribute_breakout_is_inert(url):
|
||||
assert anchor(compose(f'[a/link]({url})'))['href'] == url
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
'javascript:alert`1`', 'JaVaScRiPt:alert`1`', 'data:text/html,evil',
|
||||
'vbscript:msgbox`1`', 'ftp://host/file', 'mailto:user@example.com',
|
||||
'java\tscript:alert`1`', 'java\nscript:alert`1`', '\x01javascript:alert`1`',
|
||||
])
|
||||
def test_disallowed_schemes_are_rejected(url):
|
||||
assert anchor(compose(f'[a/link]({url})'))['href'] == '#'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url,expected', [
|
||||
('https://example.com/?q=<Flux>', 'https://example.com/?q=<Flux>'),
|
||||
('https://example.com/?a=1&b=2', 'https://example.com/?a=1&b=2'),
|
||||
('https://example.com/?a=1¬ebook=2©=3', 'https://example.com/?a=1¬ebook=2©=3'),
|
||||
('https://example.com/?q=¬it;', 'https://example.com/?q=¬it;'),
|
||||
('https://example.com/?q=<Flux>', 'https://example.com/?q=<Flux>'),
|
||||
('https://example.com/?q=&lt;', 'https://example.com/?q=<'),
|
||||
('https://example.com/a**b**c', 'https://example.com/a**b**c'),
|
||||
('https://example.com/%%white%%', 'https://example.com/%%white%%'),
|
||||
('https://example.com/[w/note]', 'https://example.com/[w/note]'),
|
||||
('https://example.com/a\nb', 'https://example.com/a\nb'),
|
||||
('http://example.com/x', 'http://example.com/x'),
|
||||
('./docs/readme.md', './docs/readme.md'), ('#section', '#section'), ('//host/path', '//host/path'),
|
||||
('&#106;avascript:alert`1`', 'javascript:alert`1`'),
|
||||
('javascript:alert`1`', 'javascript:alert`1`'),
|
||||
])
|
||||
def test_href_survives_entity_decoding_and_formatting(url, expected):
|
||||
assert anchor(compose(f'[a/link]({url})'))['href'] == expected
|
||||
|
||||
|
||||
def test_labels_prose_and_notes_keep_their_formatting():
|
||||
out = compose('<img src=x> [w/Read [a/**<Flux>**](https://example.com)]\n%%white%% [i/info]')
|
||||
parsed = Elements(out)
|
||||
assert [tag for tag, _ in parsed.elements] == ['p', 'a', 'b', 'br', 'font', 'p']
|
||||
assert parsed.text == '<img src=x> Read <Flux>white info'
|
||||
assert "class='cm-warn-note'" in out and "class='cm-info-note'" in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize('label', ['a <b> tag', 'a <b> tag', 'a\x00 <b> tag'])
|
||||
def test_link_label_is_escaped_once(label):
|
||||
out = compose(f'[a/{label}](https://example.com)')
|
||||
anchor(out)
|
||||
assert Elements(out).text == 'a <b> tag'
|
||||
|
||||
|
||||
def test_source_cannot_forge_a_href_placeholder():
|
||||
out = compose('\x00H0\x00 [a/link](https://example.com)')
|
||||
assert out.count('https://example.com') == 1
|
||||
assert anchor(out)['href'] == 'https://example.com'
|
||||
|
||||
|
||||
def test_name_and_title_preserve_existing_server_contract():
|
||||
item = {'name': 'Name <Flux>', 'title': 'Pack <Flux>'}
|
||||
RENDERER['populate_markdown'](item)
|
||||
assert item == {'name': 'Name <Flux>', 'title': 'Pack <Flux>'}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', [
|
||||
'javascript:alert`1`', 'javascript:alert`1`',
|
||||
'javascript:alert`1`', 'javascript:alert`1`',
|
||||
'javascript:alert`1`', 'javascript:alert`1`',
|
||||
'data:text/html;base64,PHNjcmlwdD4=', 'java	script:alert`1`',
|
||||
'vbscript:msgbox`1`',
|
||||
])
|
||||
def test_entity_obfuscated_schemes_are_rejected(url):
|
||||
assert anchor(compose(f'[a/link]({url})'))['href'] == '#'
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Exercise the legacy notice sanitizer and its endpoint without network access."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
from html.parser import HTMLParser
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
import pytest
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions, load_renderer
|
||||
|
||||
sanitize = load_renderer()['html_utils'].sanitize_html_fragment
|
||||
|
||||
|
||||
class _Tags(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.tags = []
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
self.tags.append((tag, dict(attrs)))
|
||||
|
||||
|
||||
def _tags(html):
|
||||
p = _Tags()
|
||||
p.feed(html)
|
||||
p.close()
|
||||
return p.tags
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
'<script>alert(1)</script>',
|
||||
'<img src=x onerror=alert(1)>',
|
||||
'<a href="javascript:alert(1)">x</a>',
|
||||
'<a href="javascript:alert(1)">x</a>',
|
||||
'<a href="java	script:alert(1)">x</a>',
|
||||
'<svg onload=alert(1)></svg>',
|
||||
'<iframe src="//evil"></iframe>',
|
||||
'<p onclick="alert(1)">x</p>',
|
||||
'<details open ontoggle=alert(1)>x</details>',
|
||||
'<style>*{background:url(//evil)}</style>',
|
||||
])
|
||||
def test_script_bearing_markup_is_removed(payload):
|
||||
out = sanitize(payload)
|
||||
for tag, attrs in _tags(out):
|
||||
assert tag not in ("script", "svg", "iframe", "style"), out
|
||||
assert not any(k.startswith("on") for k in attrs), out
|
||||
for k in ("href", "src"):
|
||||
v = attrs.get(k)
|
||||
assert v is None or not v.lower().lstrip().startswith(("javascript", "data", "vbscript")), out
|
||||
# Script-bearing markup must be gone entirely, as tags AND as raw text.
|
||||
assert "<script" not in out.lower()
|
||||
assert "onerror" not in out.lower() and "onload" not in out.lower() and "onclick" not in out.lower()
|
||||
|
||||
|
||||
def test_script_content_is_dropped_not_escaped():
|
||||
assert "alert" not in sanitize('<p>a<script>alert(1)</script>b</p>')
|
||||
assert sanitize('<p>a<script>alert(1)</script>b</p>') == "<p>ab</p>"
|
||||
|
||||
|
||||
def test_formatting_markup_survives():
|
||||
src = '<h2>News</h2><p>See <a href="https://example.com/x?a=1&b=2" title="t">docs</a> and <b>bold</b><br>line</p><ul><li>one</li></ul>'
|
||||
out = sanitize(src)
|
||||
parsed = _tags(out)
|
||||
assert [tag for tag, _ in parsed] == ['h2', 'p', 'a', 'b', 'br', 'ul', 'li']
|
||||
link = next(attrs for tag, attrs in parsed if tag == 'a')
|
||||
assert link == {'href': 'https://example.com/x?a=1&b=2', 'title': 't',
|
||||
'target': '_blank', 'rel': 'noopener noreferrer'}
|
||||
|
||||
|
||||
def test_text_nodes_are_escaped():
|
||||
assert sanitize('a <b> c') == 'a <b> c'
|
||||
assert sanitize('<p>1 < 2</p>') == '<p>1 < 2</p>'
|
||||
|
||||
|
||||
def test_unknown_harmless_tag_keeps_content():
|
||||
assert sanitize('<custom-tag><em>x</em></custom-tag>') == '<em>x</em>'
|
||||
|
||||
|
||||
def test_relative_and_https_urls_kept():
|
||||
out = sanitize('<a href="/wiki/x">r</a><a href="https://a.b/c">s</a>')
|
||||
hrefs = [attrs["href"] for tag, attrs in _tags(out) if tag == "a"]
|
||||
assert hrefs == ["/wiki/x", "https://a.b/c"]
|
||||
|
||||
|
||||
def test_script_body_ends_at_first_close_tag_like_a_browser():
|
||||
# Script content is raw text up to the FIRST </script>, exactly as the
|
||||
# browser parses it; what follows is ordinary text and stays visible.
|
||||
assert sanitize('<script><script>x</script>y</script><i>z</i>') == 'y<i>z</i>'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prefix', ['<embed>', '<svg/>', '<svg><script></svg>'])
|
||||
def test_hidden_element_does_not_swallow_following_notice(prefix):
|
||||
assert sanitize(prefix + '<p>after</p>') == '<p>after</p>'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('url', ['ftp://host/file', 'mailto:user@example.com', 'data:text/html,evil'])
|
||||
def test_other_url_schemes_are_removed(url):
|
||||
out = sanitize(f'<a href="{url}">link</a><img src="{url}">')
|
||||
assert all('href' not in attrs and 'src' not in attrs for _, attrs in _tags(out))
|
||||
|
||||
|
||||
def test_notice_layout_attributes_survive_without_inline_scripts_or_css():
|
||||
out = sanitize('<font color="red">alert</font><p class="note" align="center" style="color:red">'
|
||||
'<img src="https://example.com/a.png" width="40" height="20" onerror="boom()"></p>')
|
||||
assert _tags(out) == [('font', {'color': 'red'}), ('p', {'class': 'note', 'align': 'center'}),
|
||||
('img', {'src': 'https://example.com/a.png', 'width': '40', 'height': '20'})]
|
||||
|
||||
|
||||
def test_notice_endpoint_sanitizes_remote_content_and_retains_local_version_footer():
|
||||
response = MagicMock(status=200)
|
||||
response.text = AsyncMock(return_value='<div class="markdown-body"><embed><p>News '
|
||||
'<a href="https://example.com" onclick="boom()">link</a><script>boom()</script></p></div>')
|
||||
session = MagicMock()
|
||||
session.get.return_value.__aenter__ = AsyncMock(return_value=response)
|
||||
client = MagicMock()
|
||||
client.__aenter__ = AsyncMock(return_value=session)
|
||||
namespace = load_functions(PACKAGE / 'legacy/manager_server.py', {'get_notice'}, {
|
||||
'routes': web.RouteTableDef(), 're': re, 'web': web,
|
||||
'html_utils': load_renderer()['html_utils'],
|
||||
'aiohttp': SimpleNamespace(ClientSession=lambda **kwargs: client, TCPConnector=lambda **kwargs: None),
|
||||
'manager_util': SimpleNamespace(bypass_ssl=False),
|
||||
'os': SimpleNamespace(environ={'__COMFYUI_DESKTOP_VERSION__': '1.0'}),
|
||||
'core': SimpleNamespace(version_str='4.2.1'),
|
||||
})
|
||||
result = asyncio.run(namespace['get_notice'](None))
|
||||
assert result.status == 200
|
||||
assert 'News' in result.text and 'ComfyUI: 1.0 [Desktop]' in result.text and 'Manager: 4.2.1' in result.text
|
||||
assert 'boom' not in result.text and '<embed' not in result.text
|
||||
link = next(attrs for tag, attrs in _tags(result.text) if tag == 'a')
|
||||
assert link == {'href': 'https://example.com', 'target': '_blank', 'rel': 'noopener noreferrer'}
|
||||
@@ -0,0 +1,218 @@
|
||||
"""The legacy notice route verifies the upstream certificate and survives a failed fetch (#3302).
|
||||
|
||||
Each case runs the real `get_notice` in a child process. The child points HTTPS_PROXY at a
|
||||
local CONNECT proxy that hands the tunnel for github.com:443 to a local HTTPS server, which
|
||||
holds a "github.com" certificate from a throwaway CA: a machine in the middle, unless the
|
||||
case trusts that CA through SSL_CERT_FILE. Nothing leaves 127.0.0.1. A child is needed
|
||||
because aiohttp builds its verifying SSL context when it is imported.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions, load_renderer
|
||||
|
||||
NOTICE_PATH = "/ltdrdata/ltdrdata.github.io/wiki/News"
|
||||
NOTICE_HTML = ('<div class="markdown-body"><p>Served by <b>the test server</b> '
|
||||
'<a href="https://example.com/notes">notes</a><script>x()</script></p></div>')
|
||||
UNAVAILABLE = "Unable to retrieve Notice"
|
||||
TUNNEL = "CONNECT github.com:443 HTTP/1.1"
|
||||
OTHER_HOST = "notice-test.example"
|
||||
|
||||
OPENSSL_CONFIG = """
|
||||
[req]
|
||||
distinguished_name = dn
|
||||
prompt = no
|
||||
[dn]
|
||||
CN = ComfyUI-Manager notice test CA
|
||||
[ca]
|
||||
basicConstraints = critical, CA:TRUE
|
||||
keyUsage = critical, keyCertSign, cRLSign
|
||||
subjectKeyIdentifier = hash
|
||||
"""
|
||||
LEAF_EXTENSIONS = """
|
||||
[leaf]
|
||||
basicConstraints = critical, CA:FALSE
|
||||
keyUsage = critical, digitalSignature, keyEncipherment
|
||||
extendedKeyUsage = serverAuth
|
||||
subjectAltName = DNS:{host}
|
||||
subjectKeyIdentifier = hash
|
||||
authorityKeyIdentifier = keyid, issuer
|
||||
"""
|
||||
|
||||
|
||||
def load_get_notice(bypass_ssl):
|
||||
return load_functions(PACKAGE / "legacy/manager_server.py", {"get_notice"}, {
|
||||
"routes": web.RouteTableDef(), "aiohttp": aiohttp, "asyncio": asyncio, "logging": logging,
|
||||
"re": re, "web": web, "os": os,
|
||||
"html_utils": load_renderer()["html_utils"],
|
||||
"manager_util": SimpleNamespace(bypass_ssl=bypass_ssl),
|
||||
"core": SimpleNamespace(version_str="4.test"),
|
||||
})["get_notice"]
|
||||
|
||||
|
||||
async def _pipe(reader, writer):
|
||||
try:
|
||||
while data := await reader.read(65536):
|
||||
writer.write(data)
|
||||
await writer.drain()
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
|
||||
async def fetch_notice(certdir, host, bypass_ssl, proxy_mode):
|
||||
"""Child process: what `get_notice` answers and logs, and the tunnels the proxy was asked for."""
|
||||
async def notice_page(request):
|
||||
return web.Response(text=NOTICE_HTML, content_type="text/html")
|
||||
|
||||
upstream = web.Application()
|
||||
upstream.router.add_get(NOTICE_PATH, notice_page)
|
||||
runner = web.AppRunner(upstream)
|
||||
await runner.setup()
|
||||
server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
|
||||
server_context.load_cert_chain(os.path.join(certdir, host + ".pem"), os.path.join(certdir, host + ".key"))
|
||||
await web.TCPSite(runner, "127.0.0.1", 0, ssl_context=server_context).start()
|
||||
upstream_port = runner.addresses[0][1]
|
||||
|
||||
tunnels = []
|
||||
answered = asyncio.Event()
|
||||
|
||||
async def connect_proxy(reader, writer):
|
||||
tunnels.append((await reader.readuntil(b"\r\n\r\n")).split(b"\r\n", 1)[0].decode())
|
||||
if proxy_mode == "bad_gateway":
|
||||
writer.write(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n")
|
||||
await writer.drain()
|
||||
if proxy_mode == "silent":
|
||||
await answered.wait()
|
||||
if proxy_mode != "tunnel":
|
||||
writer.close()
|
||||
return
|
||||
upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", upstream_port)
|
||||
writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
|
||||
await writer.drain()
|
||||
await asyncio.gather(_pipe(reader, upstream_writer), _pipe(upstream_reader, writer), return_exceptions=True)
|
||||
|
||||
proxy = await asyncio.start_server(connect_proxy, "127.0.0.1", 0)
|
||||
proxy_port = proxy.sockets[0].getsockname()[1]
|
||||
if proxy_mode == "closed":
|
||||
proxy.close()
|
||||
await proxy.wait_closed()
|
||||
if proxy_mode == "silent":
|
||||
aiohttp.client.DEFAULT_TIMEOUT = aiohttp.ClientTimeout(total=0.5)
|
||||
os.environ["HTTPS_PROXY"] = f"http://127.0.0.1:{proxy_port}"
|
||||
|
||||
# Only what get_notice logs: aiohttp warns through its own loggers, for example about .netrc.
|
||||
warnings = []
|
||||
handler = logging.Handler(logging.WARNING)
|
||||
handler.emit = lambda record: record.name == "root" and warnings.append(record.getMessage())
|
||||
logging.getLogger().addHandler(handler)
|
||||
|
||||
response = await load_get_notice(bypass_ssl)(None)
|
||||
answered.set()
|
||||
proxy.close()
|
||||
await runner.cleanup()
|
||||
return {"status": response.status, "text": response.text, "tunnels": tunnels, "warnings": warnings}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def certdir(tmp_path_factory):
|
||||
if shutil.which("openssl") is None:
|
||||
pytest.skip("the openssl command is needed to create the test certificates")
|
||||
path = tmp_path_factory.mktemp("notice-tls")
|
||||
config = path / "openssl.cnf"
|
||||
config.write_text(OPENSSL_CONFIG, encoding="utf-8")
|
||||
|
||||
def openssl(*args):
|
||||
subprocess.run(["openssl", *args], cwd=path, check=True, capture_output=True)
|
||||
|
||||
openssl("req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "2", "-config", str(config),
|
||||
"-extensions", "ca", "-keyout", "ca.key", "-out", "ca.pem")
|
||||
for serial, host in enumerate(("github.com", OTHER_HOST), start=1):
|
||||
(path / f"{host}.ext").write_text(LEAF_EXTENSIONS.format(host=host), encoding="utf-8")
|
||||
openssl("req", "-newkey", "rsa:2048", "-nodes", "-subj", f"/CN={host}", "-config", str(config),
|
||||
"-keyout", f"{host}.key", "-out", f"{host}.csr")
|
||||
openssl("x509", "-req", "-in", f"{host}.csr", "-CA", "ca.pem", "-CAkey", "ca.key",
|
||||
"-set_serial", str(serial), "-days", "2", "-extfile", f"{host}.ext", "-extensions", "leaf",
|
||||
"-out", f"{host}.pem")
|
||||
return path
|
||||
|
||||
|
||||
def fetch(certdir, host="github.com", trust_ca=False, bypass_ssl=False, proxy_mode="tunnel"):
|
||||
env = {key: value for key, value in os.environ.items()
|
||||
if not key.lower().endswith("_proxy") and key not in ("SSL_CERT_FILE", "SSL_CERT_DIR")}
|
||||
env["__COMFYUI_DESKTOP_VERSION__"] = "test"
|
||||
if trust_ca:
|
||||
env["SSL_CERT_FILE"] = str(certdir / "ca.pem")
|
||||
child = subprocess.run(
|
||||
[sys.executable, __file__, str(certdir), host, str(int(bypass_ssl)), proxy_mode],
|
||||
env=env, capture_output=True, text=True, timeout=60)
|
||||
assert child.returncode == 0, "get_notice raised instead of answering:\n" + child.stderr[-2000:]
|
||||
return json.loads(child.stdout.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def assert_unavailable(result, *cause):
|
||||
assert (result["status"], result["text"]) == (200, UNAVAILABLE)
|
||||
assert len(result["warnings"]) == 1
|
||||
for text in cause:
|
||||
assert text in result["warnings"][0]
|
||||
|
||||
|
||||
def test_untrusted_certificate_is_rejected_before_its_content_is_used(certdir):
|
||||
result = fetch(certdir)
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert_unavailable(result, "ClientConnectorCertificateError", "CERTIFICATE_VERIFY_FAILED")
|
||||
|
||||
|
||||
def test_bypass_ssl_accepts_the_untrusted_certificate(certdir):
|
||||
result = fetch(certdir, bypass_ssl=True)
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert result["status"] == 200
|
||||
assert "<b>the test server</b>" in result["text"]
|
||||
assert result["warnings"] == []
|
||||
|
||||
|
||||
def test_trusted_certificate_for_another_host_is_rejected(certdir):
|
||||
result = fetch(certdir, host=OTHER_HOST, trust_ca=True)
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert_unavailable(result, "ClientConnectorCertificateError", "not valid for 'github.com'")
|
||||
|
||||
|
||||
def test_ca_trusted_through_ssl_cert_file_is_accepted(certdir):
|
||||
result = fetch(certdir, trust_ca=True)
|
||||
|
||||
assert result["tunnels"] == [TUNNEL]
|
||||
assert result["status"] == 200
|
||||
assert "<b>the test server</b>" in result["text"]
|
||||
assert 'href="https://example.com/notes"' in result["text"]
|
||||
assert "<script" not in result["text"]
|
||||
assert result["warnings"] == []
|
||||
assert "Manager: 4.test" in result["text"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy_mode, error", [
|
||||
("closed", "ClientProxyConnectionError"),
|
||||
("bad_gateway", "ClientHttpProxyError"),
|
||||
("silent", "TimeoutError"),
|
||||
], ids=["proxy_closed", "proxy_answers_502", "proxy_silent"])
|
||||
def test_failed_fetch_answers_with_the_unavailable_notice(certdir, proxy_mode, error):
|
||||
result = fetch(certdir, trust_ca=True, proxy_mode=proxy_mode)
|
||||
|
||||
assert_unavailable(result, error)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(asyncio.run(fetch_notice(sys.argv[1], sys.argv[2], sys.argv[3] == "1", sys.argv[4]))))
|
||||
@@ -0,0 +1,425 @@
|
||||
"""pip_blacklist and downgrade_blacklist apply however a requirement is written.
|
||||
|
||||
tests/test_pip_package_names.py covers the '-', '_' and letter-case spellings of a name
|
||||
(issue #3458). This file covers the other forms of a requirement, the version rules,
|
||||
and the paths that install one.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from packaging.specifiers import Specifier
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
|
||||
|
||||
# What `pip list` prints. The installed-package lookup is built from this output.
|
||||
PIP_LIST = '''\
|
||||
Package Version
|
||||
--------------- ------------
|
||||
einops 0.8.0.post1
|
||||
numpy 2.2.0
|
||||
opencv-python 5.0.0.93
|
||||
ruamel.yaml 0.18.6
|
||||
safetensors 0.5.0.dev1
|
||||
tokenizers 0.21.0rc1
|
||||
transformers 4.57.0
|
||||
triton-windows 3.5.0
|
||||
xformers 0.0.30+cu126
|
||||
'''
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def set_lists(monkeypatch):
|
||||
"""Replace the `pip list` output and return a setter for the two lists."""
|
||||
import_context()
|
||||
from comfyui_manager.common import cm_global, manager_util
|
||||
|
||||
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
|
||||
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
|
||||
check_output=lambda *args, **kwargs: PIP_LIST, CalledProcessError=subprocess.CalledProcessError))
|
||||
monkeypatch.setattr(manager_util, 'pip_map', None)
|
||||
monkeypatch.setattr(cm_global, 'pip_overrides', {}, raising=False)
|
||||
|
||||
def set_lists(blacklist=(), downgrade_blacklist=()):
|
||||
monkeypatch.setattr(cm_global, 'pip_blacklist', set(blacklist), raising=False)
|
||||
monkeypatch.setattr(cm_global, 'pip_downgrade_blacklist', list(downgrade_blacklist), raising=False)
|
||||
|
||||
set_lists()
|
||||
return set_lists
|
||||
|
||||
|
||||
def load_prestartup(**module_globals):
|
||||
"""Load the startup install functions; importing prestartup_script would run the startup."""
|
||||
from comfyui_manager.common import cm_global, manager_util
|
||||
|
||||
source = Path(manager_util.__file__).parents[1] / 'prestartup_script.py'
|
||||
wanted = {'is_installed', 'remap_pip_package', 'execute_lazy_install_script'}
|
||||
functions = [node for node in ast.parse(source.read_text(encoding='utf-8')).body
|
||||
if isinstance(node, ast.FunctionDef) and node.name in wanted]
|
||||
scope = {'os': os, 're': re, 'manager_util': manager_util, 'cm_global': cm_global, **module_globals}
|
||||
exec(compile(ast.Module(body=functions, type_ignores=[]), str(source), 'exec'), scope)
|
||||
return scope
|
||||
|
||||
|
||||
def load_check(implementation):
|
||||
"""Return the implementation's check. True means the requirement is not installed."""
|
||||
if implementation == 'prestartup':
|
||||
return load_prestartup()['is_installed']
|
||||
return import_reader(implementation).is_blacklisted
|
||||
|
||||
|
||||
@pytest.fixture(params=['glob', 'legacy', 'prestartup'])
|
||||
def is_blocked(request, set_lists):
|
||||
"""Every check that skips a listed requirement."""
|
||||
return load_check(request.param)
|
||||
|
||||
|
||||
@pytest.fixture(params=['glob', 'legacy'])
|
||||
def is_blacklisted(request, set_lists):
|
||||
"""The checks whose False means exactly 'not blocked by the lists'."""
|
||||
return load_check(request.param)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('entry', ['ruamel.yaml', 'ruamel-yaml', 'Ruamel_Yaml'])
|
||||
@pytest.mark.parametrize('requirement', ['ruamel.yaml<0.18', 'ruamel-yaml<0.18', 'ruamel_yaml<0.18'])
|
||||
def test_dots_are_name_separators(set_lists, is_blocked, entry, requirement):
|
||||
set_lists(downgrade_blacklist=[entry])
|
||||
assert is_blocked(requirement) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement', [
|
||||
'triton-windows<3.5',
|
||||
'transformers',
|
||||
'transformers<4.50',
|
||||
'transformers~=4.57.0',
|
||||
'transformers===4.0.0',
|
||||
'transformers == 4.0.0',
|
||||
'transformers[torch]==4.0.0',
|
||||
'transformers<=4.57.0,>=4.0',
|
||||
'transformers>=4.0,<4.50', # the lower bound comes first
|
||||
'transformers (>=4.0,<4.50)',
|
||||
'transformers==4.*',
|
||||
'transformers==4.0.0; python_version > "3.8"',
|
||||
'transformers ; python_version > "3.8"',
|
||||
'transformers==4.0.0 --index-url https://example.invalid/simple',
|
||||
'opencv-python<5', # 5.0.0.93 is newer than 5
|
||||
'xformers==0.0.20', # installed with a local version label
|
||||
# The installed version is excluded and nothing newer is allowed, so pip has only older versions.
|
||||
'transformers<=4.57.0,!=4.57.0',
|
||||
'transformers[torch]<=4.57.0,!=4.57.0',
|
||||
'transformers[torch]!=4.57.*,<=4.57.0',
|
||||
'transformers[torch]>=4.50,<=4.57.0,!=4.57.0',
|
||||
'transformers<4.58,!=4.57.*', # the excluded range reaches the upper bound
|
||||
'transformers[torch]<4.58,!=4.57.*',
|
||||
'transformers[torch]~=4.57.0,!=4.57.*',
|
||||
])
|
||||
def test_downgrade_blacklist_blocks_possible_downgrades(set_lists, is_blocked, caplog, requirement):
|
||||
set_lists(downgrade_blacklist=['transformers', 'triton-windows', 'opencv-python', 'xformers'])
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert is_blocked(requirement) is True
|
||||
# These versions can be compared, so nothing is reported as uncomparable.
|
||||
assert caplog.text == ''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement', [
|
||||
'transformers>=4.60',
|
||||
'transformers>=4.0', # a lower bound below the installed version
|
||||
'transformers>4.0',
|
||||
'transformers!=4.0.0',
|
||||
'transformers==4.58.0', # newer than installed
|
||||
'transformers<5', # the installed version already satisfies it
|
||||
'transformers == 5.0',
|
||||
'transformers[torch]==5.0',
|
||||
'transformers<=5.0,>=4.0',
|
||||
'transformers>=4.0,<5',
|
||||
'transformers==5.*',
|
||||
'transformers==5.0; python_version > "3.8"',
|
||||
'transformers==5.0 --index-url https://example.invalid/simple',
|
||||
'transformers-stream==0.1', # a different package
|
||||
# With extras pip keeps the installed version and adds the extras' dependencies.
|
||||
'transformers[sentencepiece]',
|
||||
'transformers[sentencepiece]==4.57.0',
|
||||
'transformers[sentencepiece]~=4.57.0',
|
||||
'transformers[sentencepiece]>=4.0,<5',
|
||||
# A clause allows the installed version, but another sets a minimum above it: an upgrade.
|
||||
'transformers==4.*,>=4.58.0',
|
||||
'transformers~=4.57.0,>4.57.0',
|
||||
# The installed version is excluded, but newer versions are allowed: which version is left to pip.
|
||||
'transformers!=4.57.0',
|
||||
'transformers~=4.57.0,!=4.57.0',
|
||||
'transformers==4.*,!=4.57.0',
|
||||
'transformers[torch]==4.*,!=4.57.0',
|
||||
'transformers[torch]<5,!=4.57.0',
|
||||
'transformers[torch]~=4.57.0,!=4.57.0',
|
||||
'transformers<4.57.1,!=4.57.0', # a post-release of 4.57.0 is left
|
||||
'transformers<4.57.0.1,!=4.57', # 4.57.0.0.1 is left: versions are written at one length
|
||||
'transformers<4.59,!=4.57.*', # 4.58 is left
|
||||
'transformers!=4.57.*,!=4.58.*,<5', # 4.59 is left
|
||||
])
|
||||
def test_downgrade_blacklist_allows_other_requirements(set_lists, is_blacklisted, caplog, requirement):
|
||||
set_lists(downgrade_blacklist=['transformers'])
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert is_blacklisted(requirement) is False
|
||||
# A misread version would be reported as uncomparable.
|
||||
assert caplog.text == ''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement', [
|
||||
'torch==2.0.0', 'torch == 2.0.0', 'Torch', 'torch[opt]>=2.0',
|
||||
'torch==', 'torch=2.0', 'torch=>2.0', # malformed version clauses
|
||||
'torch @ https://example.invalid/torch-2.0.0-py3-none-any.whl',
|
||||
'torch (>=2.0)', 'torch(>=2.0)',
|
||||
])
|
||||
def test_blacklist_matches_every_requirement_form(set_lists, is_blocked, requirement):
|
||||
set_lists(blacklist={'torch'})
|
||||
assert is_blocked(requirement) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement', ['torchvision', 'torch-audio==2.0', 'opencv-python-headless'])
|
||||
def test_blacklist_does_not_match_other_packages(set_lists, is_blacklisted, requirement):
|
||||
set_lists(blacklist={'torch', 'opencv-python'})
|
||||
assert is_blacklisted(requirement) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement', [
|
||||
'git+https://example.invalid/torch.git',
|
||||
'https://example.invalid/torch-2.0.0-py3-none-any.whl',
|
||||
'./wheels/torch-2.0.0-py3-none-any.whl',
|
||||
'--extra-index-url https://example.invalid/simple',
|
||||
])
|
||||
def test_lines_that_do_not_name_a_package_have_no_name_to_match(set_lists, is_blacklisted, requirement):
|
||||
"""A known limit: a bare URL, path or option states no package name."""
|
||||
set_lists(blacklist={'torch'})
|
||||
assert is_blacklisted(requirement) is False
|
||||
|
||||
|
||||
def test_identical_blacklist_entry_applies_to_such_lines(set_lists, is_blacklisted):
|
||||
set_lists(blacklist={'git+https://example.invalid/pack.git'})
|
||||
assert is_blacklisted('git+https://example.invalid/pack.git') is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement,installed', [
|
||||
('transformers=>4.0', '4.57.0'),
|
||||
('transformers==', '4.57.0'),
|
||||
('transformers @ https://example.invalid/transformers.whl', '4.57.0'), # no version to compare
|
||||
])
|
||||
def test_uncomparable_version_is_blocked_with_an_explanation(set_lists, is_blocked, caplog, requirement, installed):
|
||||
set_lists(downgrade_blacklist=['transformers'])
|
||||
with caplog.at_level(logging.ERROR):
|
||||
assert is_blocked(requirement) is True
|
||||
errors = [record.getMessage() for record in caplog.records if record.levelno == logging.ERROR]
|
||||
assert len(errors) == 1
|
||||
# What was skipped, why, and how to proceed.
|
||||
assert f"Skipped '{requirement}'" in errors[0]
|
||||
assert f"installed version ({installed}) cannot be compared with the requested version" in errors[0]
|
||||
assert 'Install it manually' in errors[0] and 'downgrade_blacklist in config.ini' in errors[0]
|
||||
|
||||
|
||||
def test_startup_check_reports_downgrade_protection(set_lists, capsys):
|
||||
is_installed = load_check('prestartup')
|
||||
set_lists(blacklist={'torch'}, downgrade_blacklist=['opencv-python'])
|
||||
|
||||
assert is_installed('torch==2.0.0') is True
|
||||
assert 'skip black listed' not in capsys.readouterr().out
|
||||
|
||||
assert is_installed('opencv-python~=4.8.1.78') is True
|
||||
assert "skip black listed pip installation: 'opencv-python~=4.8.1.78'" in capsys.readouterr().out
|
||||
|
||||
|
||||
@pytest.mark.parametrize('requirement,skipped', [
|
||||
('scipy', False), # not installed
|
||||
('numpy', True), # installed, no version requested
|
||||
('numpy>=3.0', False), # needs an upgrade
|
||||
('numpy==1.26.4', True), # would be a downgrade
|
||||
('numpy >= 1.20', True), # spaces around the operator
|
||||
('OpenCV_Python==4.8.1.78', True), # a hyphenated name is found and not downgraded
|
||||
('opencv-python>=6', False),
|
||||
('opencv-python~=5.1', False), # older than the compatible release
|
||||
('opencv-python~=5.0.0', True),
|
||||
('numpy>2.2.0', False), # `>` excludes the installed version
|
||||
('numpy>2.1', True),
|
||||
('numpy>2.2.0,<2.2.1', False), # 2.2.0.1 is left; `>` leaves out the post-releases of 2.2.0
|
||||
('numpy>2.2,<2.2.0.1', False), # 2.2.0.0.1 is left: versions are written at one length
|
||||
('numpy>2.2.0,<=2.2.0', True), # nothing newer is left
|
||||
('ruamel-yaml>=0.17', True), # listed by pip as ruamel.yaml
|
||||
('xformers>=0.0.20', True), # installed with a local version label
|
||||
('xformers>=0.0.30', True),
|
||||
('xformers>0.0.30', True), # an installed local build is left alone
|
||||
('xformers!=0.0.30', True),
|
||||
('xformers~=0.0.30,!=0.0.30+cu126', True),
|
||||
('xformers>=0.0.31', False), # a minimum above it is still installed
|
||||
('einops>=0.8.0', True), # installed as a post-release
|
||||
('einops>0.8.0', False), # `>` also excludes a post-release of that version
|
||||
('einops>0.7', True),
|
||||
('tokenizers==0.21.*', True), # installed as a pre-release, which the wildcard includes
|
||||
('tokenizers>=0.21.0rc1', True),
|
||||
('tokenizers>=0.21.0', False), # a pre-release is older than its release
|
||||
('tokenizers==0.21.0', False),
|
||||
# `!=` excludes the installed version: pip installs another one, unless only older ones are left.
|
||||
('numpy!=2.2.0', False),
|
||||
('numpy>=2.2.0,!=2.2.0', False),
|
||||
('numpy~=2.2.0,!=2.2.0', False),
|
||||
('numpy==2.*,!=2.2.*', False),
|
||||
('numpy<3,!=2.2.0', False),
|
||||
('numpy!=2.1.0', True), # another version is excluded
|
||||
('numpy<=2.2.0,!=2.2.0', True), # nothing newer is allowed
|
||||
('numpy==2.2.0,!=2.2.0', True),
|
||||
('numpy<2.2.0,!=2.2.0', True), # the upper bound is below the installed version
|
||||
('numpy<2.3,!=2.2.*', True), # the excluded range reaches the upper bound
|
||||
('numpy<2.4,!=2.2.*', False),
|
||||
('einops<0.8.0.post3,!=0.8.0.post1', False), # the next post-release is left
|
||||
('numpy<2.2.0.post2,!=2.2.0', False), # a post-release of 2.2.0 is left
|
||||
('tokenizers<=0.21.0rc2,!=0.21.0rc1', False), # the next pre-release is left, and `<=` names one
|
||||
('tokenizers<0.21.0rc3,!=0.21.0rc1', True), # only `<` names one: pip before 25.0 would install an older release
|
||||
('safetensors>=0.5.0.dev1,!=0.5.0.dev1,<0.5.0.dev3', False), # the next development release is left
|
||||
('tokenizers<=0.21.0,!=0.21.0,!=0.21.0rc1', True), # only a pre-release is left, which pip would not take
|
||||
('einops>0.8.0rc1,<=0.8.0.post1', True), # `>` leaves out 0.8.0.post1, and only 0.8.0 is left
|
||||
('opencv-python[extra]', False), # extras to add: pip decides
|
||||
('opencv-python @ https://example.invalid/opencv.whl', False), # no version: pip decides
|
||||
])
|
||||
def test_startup_check_for_packages_on_neither_list(set_lists, requirement, skipped):
|
||||
"""The general rule: install what is missing or too old, and never downgrade."""
|
||||
assert load_check('prestartup')(requirement) is skipped
|
||||
|
||||
|
||||
def test_an_installed_local_build_is_not_replaced_on_the_new_grounds(set_lists, is_blocked):
|
||||
"""A local build, such as a CUDA build, is given up only for a minimum above it or a build that the requirement names."""
|
||||
set_lists(downgrade_blacklist=['xformers'])
|
||||
|
||||
# pip would most often find the build without a label, which is older than the installed one
|
||||
assert is_blocked('xformers==0.0.30,!=0.0.30+cu126') is True
|
||||
assert is_blocked('xformers[extra]<=0.0.30,!=0.0.30+cu126') is True
|
||||
assert is_blocked('xformers~=0.0.30,!=0.0.30') is True
|
||||
assert is_blocked('xformers[extra]~=0.0.30,!=0.0.30') is True
|
||||
assert is_blocked('xformers==0.*,>=0.0.31') is True
|
||||
# `!=` alone leaves the choice to pip, which may replace the build with any other
|
||||
assert is_blocked('xformers!=0.0.30') is True
|
||||
assert is_blocked('xformers<1,!=0.0.30+cu126') is True
|
||||
|
||||
assert is_blocked('xformers>=0.0.31') is False
|
||||
assert is_blocked('xformers>=0.0.31,!=0.0.30') is False
|
||||
assert is_blocked('xformers==0.0.30+cu128,!=0.0.30+cu126') is False
|
||||
|
||||
|
||||
def test_a_requirement_that_leaves_only_an_older_version_to_pip_is_blocked(set_lists, is_blocked):
|
||||
"""What counts is the version pip would install, read as pip reads the requirement."""
|
||||
set_lists(downgrade_blacklist=['tokenizers', 'einops', 'safetensors'])
|
||||
|
||||
# pip takes a pre-release only when the requirement names one; here it would take an older release
|
||||
assert is_blocked('tokenizers<=0.21.0,!=0.21.0,!=0.21.0rc1') is True
|
||||
assert is_blocked('tokenizers<=0.21.0rc2,!=0.21.0rc1') is False
|
||||
assert is_blocked('tokenizers>=0.21.0rc1,!=0.21.0rc1,<0.21.0rc3') is False # 0.21.0rc2 is left
|
||||
assert is_blocked('safetensors>=0.5.0.dev1,!=0.5.0.dev1,<0.5.0.dev3') is False # 0.5.0.dev2 is left
|
||||
# pip before 25.0 does not take one that only `<` or `>` names
|
||||
assert is_blocked('tokenizers<0.21.0rc3,!=0.21.0rc1') is True
|
||||
assert is_blocked('safetensors!=0.5.0.dev1,<0.5.0.dev3') is True
|
||||
|
||||
# `>0.8.0` leaves out the installed 0.8.0.post1, and no version is left
|
||||
assert is_blocked('einops>0.8.0,<=0.8.0.post1') is True
|
||||
assert is_blocked('einops[extra]>0.8.0,<=0.8.0.post1') is True
|
||||
assert is_blocked('einops>0.8.0,<=0.8.1') is False
|
||||
|
||||
|
||||
def test_a_post_release_that_greater_than_leaves_out_is_not_replaced_by_its_release(set_lists, is_blocked, is_blacklisted):
|
||||
"""packaging before 26.1 reads `>0.8.0rc1` as leaving out 0.8.0.post1 while allowing 0.8.0, which is older."""
|
||||
set_lists(downgrade_blacklist=['einops'])
|
||||
left_out = not Specifier('>0.8.0rc1').contains('0.8.0.post1', prereleases=True)
|
||||
|
||||
assert is_blocked('einops>0.8.0rc1,<=0.8.0.post1') is True # left out or not, nothing newer is allowed
|
||||
# Where it is not left out, the requirement is met: pip keeps the version and adds the extras.
|
||||
assert is_blocked('einops[extra]>0.8.0rc1,<=0.8.0.post1') is left_out
|
||||
assert is_blocked('einops[extra]>0.8.0rc1,<=0.8.0.post2') is left_out # the upper bound is above the installed version
|
||||
assert is_blacklisted('einops>0.8.0rc1,<=0.8.0.post2') is left_out
|
||||
assert is_blacklisted('einops>0.8.0rc1,<0.9') is False # 0.8.1 is allowed
|
||||
|
||||
|
||||
def test_startup_check_agrees_with_downgrade_protection_on_an_excluded_version(set_lists):
|
||||
"""A protected package whose installed version is excluded is installed at startup as it is immediately."""
|
||||
set_lists(downgrade_blacklist=['transformers'])
|
||||
is_installed = load_check('prestartup')
|
||||
|
||||
assert is_installed('transformers~=4.57.0,!=4.57.0') is False
|
||||
assert is_installed('transformers!=4.57.0') is False
|
||||
assert is_installed('transformers<=4.57.0,!=4.57.0') is True # only older versions are left: skipped
|
||||
|
||||
|
||||
REQUIREMENTS_TXT = '''\
|
||||
torch --index-url https://example.invalid/simple
|
||||
opencv-python~=4.8.1.78 # pinned by the pack
|
||||
scipy --index-url https://example.invalid/simple
|
||||
pyyaml>=6
|
||||
'''
|
||||
|
||||
|
||||
@pytest.mark.parametrize('entry_point', [
|
||||
'glob function', 'glob manager', 'legacy function', 'legacy manager', 'startup',
|
||||
])
|
||||
def test_requirements_file_lines_are_checked_before_install(set_lists, monkeypatch, tmp_path, entry_point):
|
||||
"""From a pack's requirements.txt to the pip commands that are run."""
|
||||
set_lists(blacklist={'torch'}, downgrade_blacklist=['opencv-python'])
|
||||
(tmp_path / 'requirements.txt').write_text(REQUIREMENTS_TXT, encoding='utf-8')
|
||||
executed = []
|
||||
|
||||
if entry_point == 'startup':
|
||||
# Reserved installs, which is every server-requested install on Windows, run here.
|
||||
startup = load_prestartup(
|
||||
process_wrap=lambda cmd, cwd=None, **kwargs: executed.append(cmd) or 0,
|
||||
processed_install=set(), _unified_resolver_succeeded=False)
|
||||
startup['execute_lazy_install_script'](str(tmp_path), 'python')
|
||||
else:
|
||||
tree, caller = entry_point.split()
|
||||
core = import_reader(tree)
|
||||
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': executed.append(cmd) or 0)
|
||||
monkeypatch.setattr(core.manager_util, 'PIPFixer', lambda *args: SimpleNamespace(fix_broken=lambda: None))
|
||||
monkeypatch.setattr(core.manager_util, 'use_unified_resolver', False)
|
||||
monkeypatch.setattr(core.unified_manager, 'processed_install', set())
|
||||
target = core if caller == 'function' else core.unified_manager
|
||||
target.execute_install_script(None, str(tmp_path), instant_execution=True)
|
||||
|
||||
requirements = [' '.join(cmd[cmd.index('install') + 1:]) for cmd in executed]
|
||||
assert requirements == ['scipy --index-url https://example.invalid/simple', 'pyyaml>=6']
|
||||
|
||||
|
||||
# Every base command make_pip_cmd() can produce.
|
||||
PIP_COMMANDS = [
|
||||
['python', '-m', 'pip'], ['python', '-s', '-m', 'pip'],
|
||||
['python', '-m', 'uv', 'pip'], ['python', '-s', '-m', 'uv', 'pip'], ['uv', 'pip'],
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('tree', ['glob', 'legacy'])
|
||||
@pytest.mark.parametrize('pip', PIP_COMMANDS, ids=' '.join)
|
||||
@pytest.mark.parametrize('arguments,blocked', [
|
||||
(['torch'], True),
|
||||
(['torch', '--index-url', 'https://example.invalid/simple'], True),
|
||||
(['numpy', '--index-url', 'https://example.invalid/simple'], False),
|
||||
(['-r', 'requirements.txt'], False),
|
||||
])
|
||||
def test_immediate_install_checks_the_requirement(set_lists, monkeypatch, tree, pip, arguments, blocked):
|
||||
core = import_reader(tree)
|
||||
set_lists(blacklist={'torch'})
|
||||
executed = []
|
||||
monkeypatch.setattr(core.manager_funcs, 'run_script', lambda cmd, cwd='.': executed.append(cmd) or 0)
|
||||
|
||||
install_cmd = [*pip, 'install', *arguments]
|
||||
assert core.try_install_script(None, '.', install_cmd, instant_execution=True) is True
|
||||
assert executed == ([] if blocked else [install_cmd])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pip', PIP_COMMANDS, ids=' '.join)
|
||||
def test_reserved_pip_command_requirement(set_lists, pip):
|
||||
"""The startup loop passes this value to is_installed() instead of the last argument."""
|
||||
from comfyui_manager.common import manager_util
|
||||
|
||||
url = 'https://example.invalid/simple'
|
||||
assert manager_util.pip_install_requirement([*pip, 'install', 'torch', '--index-url', url]) == 'torch'
|
||||
assert manager_util.pip_install_requirement([*pip, 'install', 'torch==2.0.0']) == 'torch==2.0.0'
|
||||
assert manager_util.pip_install_requirement(['python', 'install.py']) is None
|
||||
assert manager_util.pip_install_requirement([*pip, 'install']) is None
|
||||
@@ -0,0 +1,135 @@
|
||||
"""PIPFixer brings the installed OpenCV packages to one version.
|
||||
|
||||
The four OpenCV packages all install the `cv2` module, and the one installed last
|
||||
provides it. When they are installed at different versions, PIPFixer reinstalls the
|
||||
older ones at the newest installed version, without their dependencies, and leaves
|
||||
`cv2` to the preferred one: a headless package rather than one with the GUI, and within
|
||||
each kind the one with the contrib modules. Which package was the older one makes no
|
||||
difference. OpenCV packages listed in pip_auto_fix.list are left to that list.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
|
||||
|
||||
# Packages PIPFixer looks at besides OpenCV; listed so that only the OpenCV step acts.
|
||||
OTHER_PACKAGES = {
|
||||
'torch': '2.5.1',
|
||||
'torchvision': '0.20.1',
|
||||
'torchaudio': '2.5.1',
|
||||
'comfyui_frontend_package': '1.30.6',
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fix_broken(monkeypatch, tmp_path):
|
||||
"""Run PIPFixer.fix_broken() against a given `pip list` and return the pip commands it ran, in order."""
|
||||
import_context()
|
||||
from comfyui_manager.common import manager_util
|
||||
|
||||
def run(installed, pip_auto_fix=None):
|
||||
pip_list = 'Package Version\n------- -------\n' + ''.join(
|
||||
f'{name} {version}\n' for name, version in {**OTHER_PACKAGES, **installed}.items())
|
||||
commands = []
|
||||
|
||||
def check_output(cmd, **_):
|
||||
if cmd[-1] == 'list':
|
||||
return pip_list
|
||||
commands.append(' '.join(cmd[3:]))
|
||||
return ''
|
||||
|
||||
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
|
||||
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
|
||||
check_output=check_output, CalledProcessError=subprocess.CalledProcessError))
|
||||
monkeypatch.setattr(manager_util, 'pip_map', None)
|
||||
if pip_auto_fix is not None:
|
||||
(tmp_path / 'pip_auto_fix.list').write_text(pip_auto_fix, encoding='utf-8')
|
||||
|
||||
previous = manager_util.get_installed_packages(True)
|
||||
manager_util.PIPFixer(previous, str(tmp_path), str(tmp_path)).fix_broken()
|
||||
return commands
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def test_older_packages_are_raised_to_the_newest_installed_version(fix_broken):
|
||||
"""The preferred package, opencv-contrib-python-headless, is installed last."""
|
||||
assert fix_broken({
|
||||
'opencv-python': '4.11.0.86',
|
||||
'opencv-python-headless': '4.10.0.84',
|
||||
'opencv-contrib-python': '4.10.0.84',
|
||||
'opencv-contrib-python-headless': '4.9.0.80',
|
||||
}) == [
|
||||
'install --no-deps opencv-contrib-python==4.11.0.86',
|
||||
'install --no-deps opencv-python-headless==4.11.0.86',
|
||||
'install --no-deps opencv-contrib-python-headless==4.11.0.86',
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('gui, headless', [
|
||||
('opencv-python', 'opencv-python-headless'),
|
||||
('opencv-contrib-python', 'opencv-python-headless'),
|
||||
('opencv-contrib-python', 'opencv-contrib-python-headless'),
|
||||
])
|
||||
def test_headless_package_provides_cv2_beside_a_gui_package(fix_broken, gui, headless):
|
||||
"""A package with the GUI needs system libraries that Linux may lack, so it must not replace a headless `cv2`.
|
||||
|
||||
The result is the same whichever of the two was the older one.
|
||||
"""
|
||||
assert fix_broken({gui: '4.13.0.92', headless: '4.10.0.84'}) == [f'install --no-deps {headless}==4.13.0.92']
|
||||
assert fix_broken({gui: '4.10.0.84', headless: '4.13.0.92'}) == [
|
||||
f'install --no-deps {gui}==4.13.0.92',
|
||||
f'install --no-deps --force-reinstall {headless}==4.13.0.92',
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('plain, contrib', [
|
||||
('opencv-python', 'opencv-contrib-python'),
|
||||
('opencv-python-headless', 'opencv-contrib-python-headless'),
|
||||
])
|
||||
def test_contrib_package_provides_cv2_beside_the_plain_one_of_its_kind(fix_broken, plain, contrib):
|
||||
"""Raising the plain package replaces the `cv2` of the contrib one, which must be put back."""
|
||||
assert fix_broken({plain: '4.11.0.86', contrib: '4.10.0.84'}) == [f'install --no-deps {contrib}==4.11.0.86']
|
||||
assert fix_broken({plain: '4.10.0.84', contrib: '4.11.0.86'}) == [
|
||||
f'install --no-deps {plain}==4.11.0.86',
|
||||
f'install --no-deps --force-reinstall {contrib}==4.11.0.86',
|
||||
]
|
||||
|
||||
|
||||
def test_fourth_version_component_is_compared_as_a_number(fix_broken):
|
||||
"""4.11.0.100 is newer than 4.11.0.86; compared as text it would be older."""
|
||||
assert fix_broken({
|
||||
'opencv-python': '4.11.0.100',
|
||||
'opencv-contrib-python': '4.11.0.86',
|
||||
}) == ['install --no-deps opencv-contrib-python==4.11.0.100']
|
||||
|
||||
|
||||
def test_opencv_packages_listed_in_pip_auto_fix_are_left_to_that_list(fix_broken):
|
||||
"""Raising a package pinned there would be undone by the pip_auto_fix.list step, at every startup."""
|
||||
assert fix_broken({
|
||||
'opencv-python': '4.10.0.84',
|
||||
'opencv-contrib-python': '4.11.0.86',
|
||||
}, pip_auto_fix='opencv-python==4.10.0.84\n') == []
|
||||
|
||||
|
||||
def test_other_packages_in_pip_auto_fix_do_not_stop_the_repair(fix_broken):
|
||||
assert fix_broken({
|
||||
'opencv-python': '4.10.0.84',
|
||||
'opencv-python-headless': '4.11.0.86',
|
||||
}, pip_auto_fix='torch>=2.5.0\n') == [
|
||||
'install --no-deps opencv-python==4.11.0.86',
|
||||
'install --no-deps --force-reinstall opencv-python-headless==4.11.0.86',
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('installed', [
|
||||
{'opencv-python': '4.11.0.86', 'opencv-python-headless': '4.11.0.86'},
|
||||
{'opencv-python-rolling': '5.0.0.20221015', 'opencv-python': '4.11.0.86', 'opencv-python-headless': '4.11.0.86'},
|
||||
], ids=['same version', 'package with a longer name'])
|
||||
def test_nothing_is_installed_when_the_versions_already_agree(fix_broken, installed):
|
||||
"""The order of preference is applied only when a package has to be raised."""
|
||||
assert fix_broken(installed) == []
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Exercise the real pip guards without running Manager's startup side effects."""
|
||||
|
||||
import ast
|
||||
import importlib.util
|
||||
import re
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "comfyui_manager"
|
||||
GUARDS = [
|
||||
("glob/manager_core.py", "is_blacklisted"),
|
||||
("legacy/manager_core.py", "is_blacklisted"),
|
||||
("prestartup_script.py", "is_installed"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager_util(monkeypatch):
|
||||
"""Feed pip's display names through the production inventory parser."""
|
||||
spec = importlib.util.spec_from_file_location("manager_util_under_test", ROOT / "common/manager_util.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
inventory = "Package Version\n------- -------\nOpenCV-Python 5.0.0.93\nnumpy 2.0.0\n"
|
||||
monkeypatch.setattr(module.subprocess, "check_output", lambda *args, **kwargs: inventory)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture(params=GUARDS, ids=[f"{path}:{name}" for path, name in GUARDS])
|
||||
def guard(request, manager_util):
|
||||
"""Compile unchanged function bodies; do not import startup/install hooks."""
|
||||
path, name = request.param
|
||||
tree = ast.parse((ROOT / path).read_text(encoding="utf-8"))
|
||||
function = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == name)
|
||||
config = SimpleNamespace(pip_blacklist=set(), pip_downgrade_blacklist=["opencv-python", "numpy"])
|
||||
namespace = {"re": re, "cm_global": config, "manager_util": manager_util}
|
||||
exec(compile(ast.Module(body=[function], type_ignores=[]), str(ROOT / path), "exec"), namespace)
|
||||
return namespace[name], config, name
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"requirement",
|
||||
["opencv-python~=4.8.1.78", "OpenCV_Python==4.8.1.78", "OPENCV-PYTHON<4.9.0", "opencv-python"],
|
||||
)
|
||||
def test_protected_package_is_recognized(guard, requirement):
|
||||
"""A display-name alias must not bypass downgrade protection."""
|
||||
check, _, _ = guard
|
||||
assert check(requirement) is True
|
||||
|
||||
|
||||
def test_blacklist_entry_uses_the_same_name_format(guard):
|
||||
"""Configuration aliases must match the inventory and requirement names."""
|
||||
check, config, _ = guard
|
||||
config.pip_downgrade_blacklist = ["OpenCV_Python"]
|
||||
assert check("opencv-python~=4.8.1.78") is True
|
||||
config.pip_downgrade_blacklist = []
|
||||
config.pip_blacklist = {"OpenCV-Python"}
|
||||
assert check("opencv_python>=6.0.0") is True
|
||||
|
||||
|
||||
def test_upgrade_is_still_allowed(guard):
|
||||
"""Protection must not suppress an upgrade to a newer required version."""
|
||||
check, _, _ = guard
|
||||
assert check("opencv-python>=6.0.0") is False
|
||||
|
||||
|
||||
def test_missing_package_is_not_reported_installed(guard):
|
||||
"""A protected name alone does not mean the package is installed."""
|
||||
check, config, _ = guard
|
||||
config.pip_downgrade_blacklist.append("missing-package")
|
||||
assert check("missing-package==1.0.0") is False
|
||||
|
||||
|
||||
def test_existing_simple_package_protection(guard):
|
||||
"""The existing NumPy downgrade guard must continue to work."""
|
||||
check, _, _ = guard
|
||||
assert check("numpy==1.26.4") is True
|
||||
|
||||
|
||||
def test_unprotected_installed_package(guard):
|
||||
"""Installed status remains distinct from blacklist membership."""
|
||||
check, config, name = guard
|
||||
config.pip_downgrade_blacklist = []
|
||||
assert check("opencv-python") is (name == "is_installed")
|
||||
@@ -0,0 +1,195 @@
|
||||
"""The command line ComfyUI is restarted with keeps every argument as it was (#3339).
|
||||
|
||||
The reboot endpoints and the prestartup restart after an install re-exec ComfyUI with
|
||||
os.execv. On Windows os.execv joins its arguments with spaces and quotes nothing, so
|
||||
`--output-directory "D:\\My Outputs"` used to reach the new process as two arguments.
|
||||
manager_util.build_restart_command quotes each argument there; other platforms get
|
||||
the list unchanged. A ComfyUI started as a module is restarted with `python -m`.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
PACKAGE_DIR = Path(__file__).resolve().parent.parent / "comfyui_manager"
|
||||
MANAGER_UTIL_PATH = PACKAGE_DIR / "common" / "manager_util.py"
|
||||
|
||||
TRICKY_ARGS = [
|
||||
"--browser-profile", "Profile 1",
|
||||
"--output-directory", "C:\\my dir\\",
|
||||
"--note", 'say "hi"',
|
||||
"--empty", "",
|
||||
"--port", "8188",
|
||||
]
|
||||
|
||||
|
||||
def load_manager_util():
|
||||
# By path: importing the package needs a running ComfyUI
|
||||
spec = importlib.util.spec_from_file_location("_manager_util_under_test", MANAGER_UTIL_PATH)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
MANAGER_UTIL = load_manager_util()
|
||||
|
||||
|
||||
def test_windows_quotes_only_what_needs_quoting(monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setattr(sys, "executable", "C:\\Program Files\\python.exe")
|
||||
|
||||
cmds = MANAGER_UTIL.build_restart_command(["C:\\Comfy UI\\main.py"] + TRICKY_ARGS)
|
||||
|
||||
assert cmds == [
|
||||
'"C:\\Program Files\\python.exe"',
|
||||
'"C:\\Comfy UI\\main.py"',
|
||||
"--browser-profile", '"Profile 1"',
|
||||
"--output-directory", '"C:\\my dir\\\\"',
|
||||
"--note", '"say \\"hi\\""',
|
||||
"--empty", '""',
|
||||
"--port", "8188",
|
||||
]
|
||||
|
||||
|
||||
def test_posix_passes_arguments_through(monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "linux")
|
||||
monkeypatch.setattr(sys, "executable", "/usr/bin/python3")
|
||||
|
||||
argv = ["/opt/Comfy UI/main.py"] + TRICKY_ARGS
|
||||
|
||||
assert MANAGER_UTIL.build_restart_command(argv) == ["/usr/bin/python3"] + argv
|
||||
|
||||
|
||||
def test_module_entry_point_uses_dash_m(monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "linux")
|
||||
monkeypatch.setattr(sys, "executable", "/usr/bin/python3")
|
||||
|
||||
cmds = MANAGER_UTIL.build_restart_command(["/opt/site-packages/comfy/__main__.py", "--port", "8188"])
|
||||
|
||||
assert cmds == ["/usr/bin/python3", "-m", "comfy", "--port", "8188"]
|
||||
|
||||
|
||||
def test_module_entry_point_is_quoted_on_windows(monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "win32")
|
||||
monkeypatch.setattr(sys, "executable", "C:\\Program Files\\python.exe")
|
||||
|
||||
# Forward slashes: the module name is then found by both the POSIX and the Windows os.path
|
||||
cmds = MANAGER_UTIL.build_restart_command(
|
||||
["C:/site packages/comfy/__main__.py", "--browser-profile", "Profile 1"])
|
||||
|
||||
assert cmds == ['"C:\\Program Files\\python.exe"', "-m", "comfy", "--browser-profile", '"Profile 1"']
|
||||
|
||||
|
||||
def test_drop_args_removes_only_listed_arguments(monkeypatch):
|
||||
monkeypatch.setattr(sys, "platform", "linux")
|
||||
monkeypatch.setattr(sys, "executable", "/usr/bin/python3")
|
||||
argv = ["main.py", "--windows-standalone-build", "--cpu"]
|
||||
|
||||
assert MANAGER_UTIL.build_restart_command(argv) == ["/usr/bin/python3"] + argv
|
||||
assert MANAGER_UTIL.build_restart_command(argv, drop_args=("--windows-standalone-build",)) == \
|
||||
["/usr/bin/python3", "main.py", "--cpu"]
|
||||
assert argv == ["main.py", "--windows-standalone-build", "--cpu"] # caller's list is untouched
|
||||
assert MANAGER_UTIL.build_restart_command(argv + ["--windows-standalone-build"], drop_args=("--windows-standalone-build",)) == \
|
||||
["/usr/bin/python3", "main.py", "--cpu"] # every occurrence
|
||||
assert MANAGER_UTIL.build_restart_command(["main.py", "--cpu"], drop_args=("--windows-standalone-build",)) == \
|
||||
["/usr/bin/python3", "main.py", "--cpu"] # nothing to drop
|
||||
|
||||
|
||||
def run_restart_site(path, execv):
|
||||
"""Run the restart code of `path` as it is written, up to `os.execv`, which is replaced by `execv`."""
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
if path.name == "prestartup_script.py":
|
||||
nodes = [node for node in tree.body if isinstance(node, ast.If) and ast.unparse(node.test) == "script_executed"]
|
||||
else:
|
||||
nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "restart"]
|
||||
assert len(nodes) == 1, f"restart code not found in {path}"
|
||||
|
||||
allow = SimpleNamespace(reject_simple_form_post=lambda request: None, is_allowed_security_level=lambda level: True)
|
||||
namespace = {
|
||||
"os": SimpleNamespace(environ={}, path=os.path, execv=execv), # not a comfy-cli session
|
||||
"sys": sys,
|
||||
"manager_util": MANAGER_UTIL,
|
||||
"script_executed": True,
|
||||
"security_utils": allow, "manager_security": allow, "is_allowed_security_level": allow.is_allowed_security_level,
|
||||
}
|
||||
for node in nodes:
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
node.decorator_list = []
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), namespace)
|
||||
if "restart" in namespace:
|
||||
namespace["restart"](None)
|
||||
|
||||
|
||||
# ComfyUI opens a browser when it starts with --windows-standalone-build. A reboot endpoint
|
||||
# restarts a ComfyUI whose page is already open, so it drops the flag (#1160). The prestartup
|
||||
# restart happens before ComfyUI has opened anything, so the flag must stay there.
|
||||
@pytest.mark.parametrize("site, drops_the_flag", [
|
||||
("glob/manager_server.py", True),
|
||||
("legacy/manager_server.py", True),
|
||||
("prestartup_script.py", False),
|
||||
])
|
||||
def test_restart_site_runs_the_built_command(monkeypatch, site, drops_the_flag):
|
||||
flag = "--windows-standalone-build"
|
||||
for platform, executable, quoted_executable, directory, quoted_directory in [
|
||||
("win32", "C:\\Program Files\\python.exe", '"C:\\Program Files\\python.exe"', "D:\\My Outputs", '"D:\\My Outputs"'),
|
||||
("linux", "/usr/bin/python3", "/usr/bin/python3", "/data/My Outputs", "/data/My Outputs"),
|
||||
]:
|
||||
for started_with_flag in (True, False): # most installs do not start with the flag
|
||||
monkeypatch.setattr(sys, "platform", platform)
|
||||
monkeypatch.setattr(sys, "executable", executable)
|
||||
monkeypatch.setattr(sys, "argv", ["main.py"] + [flag] * started_with_flag + ["--output-directory", directory])
|
||||
calls = []
|
||||
|
||||
run_restart_site(PACKAGE_DIR / site, lambda *args: calls.append(args))
|
||||
|
||||
kept = [flag] * (started_with_flag and not drops_the_flag)
|
||||
assert calls == [(executable, [quoted_executable, "main.py"] + kept + ["--output-directory", quoted_directory])]
|
||||
|
||||
|
||||
LAUNCHER = """
|
||||
import importlib.util, os, sys
|
||||
spec = importlib.util.spec_from_file_location("_manager_util_under_test", sys.argv[1])
|
||||
manager_util = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(manager_util)
|
||||
os.execv(sys.executable, manager_util.build_restart_command(sys.argv[2:]))
|
||||
"""
|
||||
|
||||
CHILD = """
|
||||
import json, os, sys
|
||||
with open(sys.argv[1] + ".tmp", "w", encoding="utf-8") as f:
|
||||
json.dump(sys.argv[2:], f)
|
||||
os.replace(sys.argv[1] + ".tmp", sys.argv[1])
|
||||
"""
|
||||
|
||||
|
||||
def test_arguments_survive_a_real_execv(tmp_path):
|
||||
"""End to end on the running platform: what the re-exec'ed process sees must equal what was sent."""
|
||||
work_dir = tmp_path / "dir with spaces"
|
||||
work_dir.mkdir()
|
||||
child = work_dir / "main entry.py"
|
||||
child.write_text(CHILD, encoding="utf-8")
|
||||
result_file = work_dir / "argv seen.json"
|
||||
|
||||
subprocess.run(
|
||||
[sys.executable, "-c", LAUNCHER, str(MANAGER_UTIL_PATH), str(child), str(result_file)] + TRICKY_ARGS,
|
||||
check=True, timeout=60,
|
||||
)
|
||||
|
||||
# On Windows os.execv returns control to the caller before the new process is done.
|
||||
deadline = time.time() + 30
|
||||
while not result_file.exists():
|
||||
if time.time() > deadline:
|
||||
pytest.fail("re-exec'ed process never reported its arguments")
|
||||
time.sleep(0.1)
|
||||
|
||||
assert json.loads(result_file.read_text(encoding="utf-8")) == TRICKY_ARGS
|
||||
@@ -0,0 +1,110 @@
|
||||
"""restore_pip_snapshot decides success from pip's exit status.
|
||||
|
||||
The pip packages of a snapshot are restored in three groups, each chosen by its own
|
||||
option: packages named by version, packages given by a remote URL, and packages given
|
||||
by a local `file:` URL. The first group is installed in one pip run, and only when that
|
||||
run fails is each package installed by itself without dependencies. A package is
|
||||
reported as failed only when pip exits with an error for it.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context
|
||||
|
||||
|
||||
PIPS = {
|
||||
'alpha==1.0': '',
|
||||
'beta==2.0': '',
|
||||
'gamma @ https://example.com/gamma.whl': 'https://example.com/gamma.whl',
|
||||
'delta @ file:///wheels/delta.whl': 'file:///wheels/delta.whl',
|
||||
'torch==2.5.1': '',
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def restore(monkeypatch, capsys):
|
||||
"""Run restore_pip_snapshot() with pip replaced; return the pip commands and the reported failures."""
|
||||
import_context()
|
||||
from comfyui_manager.common import manager_util
|
||||
|
||||
def run(options, failing=()):
|
||||
commands = []
|
||||
|
||||
def check_call(cmd, **_):
|
||||
commands.append(cmd[3:])
|
||||
if any(name in arg for arg in cmd for name in failing):
|
||||
raise subprocess.CalledProcessError(1, cmd)
|
||||
return 0
|
||||
|
||||
def check_output(cmd, **_):
|
||||
# pip's output, as the real check_output returns it: never an exit status.
|
||||
return check_call(cmd) or b'Successfully installed\n'
|
||||
|
||||
monkeypatch.setattr(manager_util, 'make_pip_cmd', lambda cmd: ['python', '-m', 'pip', *cmd])
|
||||
monkeypatch.setattr(manager_util, 'subprocess', SimpleNamespace(
|
||||
check_call=check_call, check_output=check_output,
|
||||
CalledProcessError=subprocess.CalledProcessError))
|
||||
|
||||
manager_util.restore_pip_snapshot(PIPS, options)
|
||||
report = capsys.readouterr().out.strip().splitlines()[-1]
|
||||
return commands, report
|
||||
|
||||
return run
|
||||
|
||||
|
||||
def test_packages_installed_in_one_run_get_no_second_run(restore):
|
||||
commands, report = restore(['--pip-non-url'])
|
||||
|
||||
assert commands == [['install', 'alpha==1.0', 'beta==2.0']]
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
|
||||
|
||||
def test_failed_run_falls_back_to_one_package_at_a_time(restore):
|
||||
commands, report = restore(['--pip-non-url'], failing=['beta'])
|
||||
|
||||
assert commands == [
|
||||
['install', 'alpha==1.0', 'beta==2.0'],
|
||||
['install', '--no-deps', 'alpha==1.0'],
|
||||
['install', '--no-deps', 'beta==2.0'],
|
||||
]
|
||||
assert report == "Installation failed for pip packages: ['beta==2.0']"
|
||||
|
||||
|
||||
@pytest.mark.parametrize('option, url', [
|
||||
('--pip-non-local-url', 'https://example.com/gamma.whl'),
|
||||
('--pip-local-url', 'file:///wheels/delta.whl'),
|
||||
])
|
||||
def test_url_package_is_reported_only_when_pip_fails(restore, option, url):
|
||||
commands, report = restore([option])
|
||||
assert commands == [['install', '--no-deps', url]]
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
|
||||
commands, report = restore([option], failing=[url])
|
||||
assert commands == [['install', '--no-deps', url]]
|
||||
assert report == f"Installation failed for pip packages: ['{url}']"
|
||||
|
||||
|
||||
def test_every_failed_package_is_reported(restore):
|
||||
urls = ['https://example.com/gamma.whl', 'file:///wheels/delta.whl']
|
||||
|
||||
commands, report = restore(['--pip-non-url', '--pip-non-local-url', '--pip-local-url'],
|
||||
failing=['alpha', 'beta', *urls])
|
||||
|
||||
assert commands == [
|
||||
['install', 'alpha==1.0', 'beta==2.0'],
|
||||
['install', '--no-deps', 'alpha==1.0'],
|
||||
['install', '--no-deps', 'beta==2.0'],
|
||||
['install', '--no-deps', urls[0]],
|
||||
['install', '--no-deps', urls[1]],
|
||||
]
|
||||
assert report == f"Installation failed for pip packages: {['alpha==1.0', 'beta==2.0', *urls]}"
|
||||
|
||||
|
||||
def test_group_without_its_option_is_left_alone(restore):
|
||||
commands, report = restore([])
|
||||
|
||||
assert commands == []
|
||||
assert report == 'Installation failed for pip packages: []'
|
||||
@@ -0,0 +1,185 @@
|
||||
"""The share route uploads only a file inside the output or temp directory (#3427).
|
||||
|
||||
Each case runs the real `share_art` of the glob and the legacy package against a recording
|
||||
Matrix client. The filename and the subfolder of the selected output come from the request.
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
|
||||
from legacy_html_testutil import PACKAGE, load_functions
|
||||
|
||||
SECRET = b"not an output"
|
||||
|
||||
|
||||
class LoginResponse:
|
||||
access_token = "token"
|
||||
|
||||
|
||||
class UploadResponse:
|
||||
content_uri = "mxc://test/asset"
|
||||
|
||||
|
||||
def load_share_art(package, output_dir, temp_dir, os_module: object = os):
|
||||
"""Returns `share_art` and the list that receives (homeserver, uploaded bytes)."""
|
||||
uploads = []
|
||||
|
||||
class AsyncClient:
|
||||
def __init__(self, homeserver, username):
|
||||
self.homeserver = homeserver
|
||||
|
||||
async def login(self, password):
|
||||
return LoginResponse()
|
||||
|
||||
async def upload(self, data, content_type=None, filename=None):
|
||||
uploads.append((self.homeserver, data.read()))
|
||||
return UploadResponse(), None
|
||||
|
||||
async def room_send(self, **kwargs):
|
||||
pass
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
namespace = load_functions(PACKAGE / package / "share_3rdparty.py", {"share_art"}, {
|
||||
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
|
||||
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
|
||||
get_temp_directory=lambda: str(temp_dir)),
|
||||
"os": os_module, "web": web, "json": json, "mimetypes": mimetypes,
|
||||
"matrix_nio_is_available": True, "set_matrix_auth": lambda matrix_auth: None,
|
||||
"AsyncClient": AsyncClient, "LoginResponse": LoginResponse, "UploadResponse": UploadResponse,
|
||||
})
|
||||
return namespace["share_art"], uploads
|
||||
|
||||
|
||||
def share(share_art, output):
|
||||
body = {
|
||||
"matrix_auth": {"homeserver": "matrix.example", "username": "user", "password": "password"},
|
||||
"share_destinations": ["matrix"], "credits": "", "title": "", "description": "",
|
||||
"prompt": {"workflow": {}}, "potential_outputs": [output], "selected_output_index": 0,
|
||||
}
|
||||
|
||||
async def read_json():
|
||||
return body
|
||||
|
||||
return asyncio.run(share_art(SimpleNamespace(json=read_json)))
|
||||
|
||||
|
||||
def image(filename, subfolder="", type="output"):
|
||||
return {"type": "image", "image": {"filename": filename, "subfolder": subfolder, "type": type}}
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def package(request):
|
||||
return request.param
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dirs(tmp_path):
|
||||
output_dir = tmp_path / "output"
|
||||
temp_dir = tmp_path / "temp"
|
||||
(output_dir / "sub").mkdir(parents=True)
|
||||
temp_dir.mkdir()
|
||||
(output_dir / "a.png").write_bytes(b"output image")
|
||||
(output_dir / "sub" / "b.png").write_bytes(b"image in a subfolder")
|
||||
(temp_dir / "c.png").write_bytes(b"preview image")
|
||||
(tmp_path / "secret.txt").write_bytes(SECRET)
|
||||
(tmp_path / "output-other").mkdir()
|
||||
(tmp_path / "output-other" / "d.png").write_bytes(SECRET)
|
||||
return output_dir, temp_dir
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output, content", [
|
||||
(image("a.png"), b"output image"),
|
||||
(image("b.png", "sub"), b"image in a subfolder"),
|
||||
(image("c.png", type="temp"), b"preview image"),
|
||||
({"type": "output", "output": {"filename": "b.png", "subfolder": "sub"}}, b"image in a subfolder"),
|
||||
])
|
||||
def test_a_file_in_the_directory_is_shared(package, dirs, output, content):
|
||||
share_art, uploads = load_share_art(package, *dirs)
|
||||
|
||||
response = share(share_art, output)
|
||||
|
||||
assert response.status == 200
|
||||
assert uploads[0] == ("https://matrix.example", content)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output", [
|
||||
image("../secret.txt"),
|
||||
image("secret.txt", ".."),
|
||||
image("secret.txt", "sub/../.."),
|
||||
image("d.png", "../output-other"), # a sibling whose name starts with the directory's name
|
||||
image("a.png", "../output", type="temp"), # the output directory is not inside the temp directory
|
||||
{"type": "output", "output": {"filename": "../secret.txt", "subfolder": ""}},
|
||||
])
|
||||
def test_a_path_that_leaves_the_directory_is_refused(package, dirs, output):
|
||||
share_art, uploads = load_share_art(package, *dirs)
|
||||
|
||||
response = share(share_art, output)
|
||||
|
||||
assert response.status == 400
|
||||
assert "output directory" in json.loads(response.body)["error"]
|
||||
assert uploads == []
|
||||
|
||||
|
||||
def test_an_absolute_path_is_refused(package, dirs, tmp_path):
|
||||
share_art, uploads = load_share_art(package, *dirs)
|
||||
|
||||
response = share(share_art, image(str(tmp_path / "secret.txt"), "sub"))
|
||||
|
||||
assert response.status == 400
|
||||
assert uploads == []
|
||||
|
||||
|
||||
def test_a_symlink_that_the_user_placed_in_the_directory_is_followed(package, dirs, tmp_path):
|
||||
"""ComfyUI's /view shows such a file, so the image that the dialog previews can be shared."""
|
||||
output_dir, _ = dirs
|
||||
elsewhere = tmp_path / "another-disk"
|
||||
elsewhere.mkdir()
|
||||
(elsewhere / "e.png").write_bytes(b"image on another disk")
|
||||
try:
|
||||
(output_dir / "link").symlink_to(elsewhere, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip("cannot create a symlink here")
|
||||
share_art, uploads = load_share_art(package, *dirs)
|
||||
|
||||
response = share(share_art, image("e.png", "link"))
|
||||
|
||||
assert response.status == 200
|
||||
assert uploads[0][1] == b"image on another disk"
|
||||
|
||||
|
||||
def test_the_path_that_was_checked_is_the_path_that_is_read(package, dirs, tmp_path):
|
||||
"""`link/..` is the output directory once normalized, and the parent of the link's target on disk."""
|
||||
output_dir, _ = dirs
|
||||
elsewhere = tmp_path / "another-disk"
|
||||
elsewhere.mkdir()
|
||||
(tmp_path / "a.png").write_bytes(SECRET)
|
||||
try:
|
||||
(output_dir / "link").symlink_to(elsewhere, target_is_directory=True)
|
||||
except OSError:
|
||||
pytest.skip("cannot create a symlink here")
|
||||
share_art, uploads = load_share_art(package, *dirs)
|
||||
|
||||
response = share(share_art, image("a.png", "link/.."))
|
||||
|
||||
assert response.status == 200
|
||||
assert uploads[0][1] == b"output image"
|
||||
|
||||
|
||||
def test_a_path_on_another_windows_drive_is_refused(package):
|
||||
"""`os.path.commonpath` raises ValueError for paths on different drives."""
|
||||
windows = SimpleNamespace(path=ntpath)
|
||||
share_art, uploads = load_share_art(package, r"C:\ComfyUI\output", r"C:\ComfyUI\temp", os_module=windows)
|
||||
|
||||
for output in (image(r"D:\secret.txt"), image("secret.txt", "D:\\"), image(r"\\server\share\secret.txt")):
|
||||
response = share(share_art, output)
|
||||
|
||||
assert response.status == 400
|
||||
assert uploads == []
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Restoring a snapshot compares each nodepack with the version or commit the snapshot pins.
|
||||
|
||||
A Registry nodepack already at the pinned version is left as it is, without asking the
|
||||
Registry about it. A git nodepack is checked out at the pinned commit hash; the hash is
|
||||
the bare 40 characters both when it is read from a repository whose HEAD is detached and
|
||||
when it comes from a snapshot that an older version saved with the newline still attached.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import subprocess
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
|
||||
|
||||
COMMIT = '0123456789abcdef0123456789abcdef01234567'
|
||||
REPO_URL = 'https://github.com/owner/fixture'
|
||||
|
||||
|
||||
def git(path, *args):
|
||||
return subprocess.run(['git', *args], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
@pytest.fixture(params=['glob', 'legacy'])
|
||||
def core(request, monkeypatch, tmp_path):
|
||||
core = import_reader(request.param)
|
||||
monkeypatch.setattr(core, 'get_default_custom_nodes_path', lambda: str(tmp_path))
|
||||
monkeypatch.setattr(core.manager_util, 'restore_pip_snapshot', Mock())
|
||||
return core
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manager(core, monkeypatch):
|
||||
manager = core.UnifiedManager()
|
||||
manager.reload = AsyncMock()
|
||||
manager.get_custom_nodes = AsyncMock(return_value={})
|
||||
monkeypatch.setattr(core, 'unified_manager', manager)
|
||||
return manager
|
||||
|
||||
|
||||
def restore(core, tmp_path, **snapshot):
|
||||
path = tmp_path / 'snapshot.json'
|
||||
path.write_text(json.dumps({'cnr_custom_nodes': {}, 'git_custom_nodes': {}, 'file_custom_nodes': [], **snapshot}))
|
||||
asyncio.run(core.restore_snapshot(str(path)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('head, expected', [
|
||||
(COMMIT + '\n', COMMIT),
|
||||
('ref: refs/heads/main\n', COMMIT),
|
||||
])
|
||||
def test_commit_hash_has_no_trailing_newline(tmp_path, head, expected):
|
||||
import_context()
|
||||
from comfyui_manager.common import git_utils
|
||||
|
||||
(tmp_path / '.git/refs/heads').mkdir(parents=True)
|
||||
(tmp_path / '.git/HEAD').write_text(head)
|
||||
(tmp_path / '.git/refs/heads/main').write_text(COMMIT + '\n')
|
||||
|
||||
assert git_utils.get_commit_hash(str(tmp_path)) == expected
|
||||
|
||||
|
||||
def test_registry_pack_at_the_pinned_version_is_left_alone(core, manager, monkeypatch, tmp_path):
|
||||
installed = tmp_path / 'fixture'
|
||||
installed.mkdir()
|
||||
manager.active_nodes['fixture'] = ('2.0.0', str(installed))
|
||||
query = Mock(side_effect=AssertionError('a pack at the pinned version must not query the Registry'))
|
||||
monkeypatch.setattr(core.cnr_utils.requests, 'get', query)
|
||||
|
||||
restore(core, tmp_path, cnr_custom_nodes={'fixture': '2.0.0'})
|
||||
|
||||
query.assert_not_called()
|
||||
assert manager.active_nodes['fixture'] == ('2.0.0', str(installed))
|
||||
|
||||
|
||||
def test_registry_pack_at_another_version_is_switched(core, manager, tmp_path):
|
||||
manager.active_nodes['fixture'] = ('1.0.0', str(tmp_path / 'fixture'))
|
||||
manager.cnr_switch_version = Mock(return_value=core.ManagedResult('switch-cnr'))
|
||||
|
||||
restore(core, tmp_path, cnr_custom_nodes={'fixture': '2.0.0'})
|
||||
|
||||
assert manager.cnr_switch_version.call_args.args == ('fixture', '2.0.0')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pack(tmp_path):
|
||||
"""A git nodepack with two commits, checked out at the second; returns its path and the two hashes."""
|
||||
path = tmp_path / 'fixture'
|
||||
path.mkdir()
|
||||
git(path, 'init', '-q')
|
||||
commits = []
|
||||
for version in (1, 2):
|
||||
(path / '__init__.py').write_text(f'VERSION = {version}\n')
|
||||
git(path, 'add', '.')
|
||||
git(path, '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', f'version {version}')
|
||||
commits.append(git(path, 'rev-parse', 'HEAD'))
|
||||
return path, commits
|
||||
|
||||
|
||||
@pytest.mark.parametrize('newline', ['', '\n'])
|
||||
def test_git_pack_is_checked_out_at_the_pinned_commit(core, manager, pack, tmp_path, newline):
|
||||
path, (first, second) = pack
|
||||
manager.active_nodes['fixture'] = ('nightly', str(path))
|
||||
manager.repo_cnr_map[REPO_URL] = {'id': 'fixture'}
|
||||
manager.install_by_id = AsyncMock(return_value=core.ManagedResult('skip'))
|
||||
assert git(path, 'rev-parse', 'HEAD') == second
|
||||
|
||||
restore(core, tmp_path, git_custom_nodes={REPO_URL: {'hash': first + newline, 'disabled': False}})
|
||||
|
||||
assert git(path, 'rev-parse', 'HEAD') == first
|
||||
assert (path / '__init__.py').read_text() == 'VERSION = 1\n'
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -24,27 +25,6 @@ import pytest
|
||||
_MOCK_INSTALLED_PACKAGES: dict[str, str] = {}
|
||||
|
||||
|
||||
class _FakeStrictVersion:
|
||||
"""Minimal replica of manager_util.StrictVersion for testing."""
|
||||
|
||||
def __init__(self, version_string: str) -> None:
|
||||
parts = version_string.split('.')
|
||||
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
|
||||
|
||||
def __ge__(self, other: _FakeStrictVersion) -> bool:
|
||||
return (self.major, self.minor, self.patch) >= (other.major, other.minor, other.patch)
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
if not isinstance(other, _FakeStrictVersion):
|
||||
return NotImplemented
|
||||
return (self.major, self.minor, self.patch) == (other.major, other.minor, other.patch)
|
||||
|
||||
def __lt__(self, other: _FakeStrictVersion) -> bool:
|
||||
return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch)
|
||||
|
||||
|
||||
def _fake_get_installed_packages(renew: bool = False) -> dict[str, str]:
|
||||
return _MOCK_INSTALLED_PACKAGES
|
||||
|
||||
@@ -54,9 +34,21 @@ def _fake_robust_readlines(path: str) -> list[str]:
|
||||
return f.readlines()
|
||||
|
||||
|
||||
# Build a fake manager_util module
|
||||
# Build a fake manager_util module: the production code, with only the functions
|
||||
# that run pip or read files replaced. It stays a bare module without ``__file__``
|
||||
# so that tests importing the real package afterwards discard it.
|
||||
_real_manager_util_spec = importlib.util.spec_from_file_location(
|
||||
"_cm_real_manager_util",
|
||||
os.path.join(os.path.dirname(__file__), os.pardir, "comfyui_manager", "common", "manager_util.py"),
|
||||
)
|
||||
assert _real_manager_util_spec is not None and _real_manager_util_spec.loader is not None
|
||||
_real_manager_util = importlib.util.module_from_spec(_real_manager_util_spec)
|
||||
_real_manager_util_spec.loader.exec_module(_real_manager_util)
|
||||
|
||||
_manager_util_fake = types.ModuleType("comfyui_manager.common.manager_util")
|
||||
_manager_util_fake.StrictVersion = _FakeStrictVersion
|
||||
_manager_util_fake.__dict__.update(
|
||||
{name: value for name, value in vars(_real_manager_util).items() if not name.startswith("__")}
|
||||
)
|
||||
_manager_util_fake.get_installed_packages = _fake_get_installed_packages
|
||||
_manager_util_fake.robust_readlines = _fake_robust_readlines
|
||||
|
||||
@@ -85,6 +77,7 @@ assert _spec is not None and _spec.loader is not None
|
||||
_udr_module = importlib.util.module_from_spec(_spec)
|
||||
sys.modules[_spec.name] = _udr_module
|
||||
_spec.loader.exec_module(_udr_module)
|
||||
sys.modules["comfyui_manager.common"].unified_dep_resolver = _udr_module
|
||||
|
||||
# Pull symbols into the test namespace
|
||||
CollectedDeps = _udr_module.CollectedDeps
|
||||
@@ -100,7 +93,6 @@ _CREDENTIAL_PATTERN = _udr_module._CREDENTIAL_PATTERN
|
||||
_DANGEROUS_PATTERNS = _udr_module._DANGEROUS_PATTERNS
|
||||
_INLINE_DANGEROUS_OPTIONS = _udr_module._INLINE_DANGEROUS_OPTIONS
|
||||
_TMP_PREFIX = _udr_module._TMP_PREFIX
|
||||
_VERSION_SPEC_PATTERN = _udr_module._VERSION_SPEC_PATTERN
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -202,6 +194,26 @@ class TestCollectRequirements:
|
||||
deps = r.collect_requirements()
|
||||
assert deps.requirements[0].spec == "numpy>=1.0"
|
||||
|
||||
@pytest.mark.parametrize("entry", ["opencv-python", "opencv_python", "OpenCV-Python"])
|
||||
def test_blacklist_name_spelling_does_not_matter(self, entry, tmp_path):
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", "opencv-python>=4.8\nnumpy\n")
|
||||
r = _resolver([p], blacklist={entry})
|
||||
deps = r.collect_requirements()
|
||||
assert [req.name for req in deps.requirements] == ["numpy"]
|
||||
assert deps.skipped == [("opencv-python>=4.8", "blacklisted")]
|
||||
|
||||
@pytest.mark.parametrize("requirement", [
|
||||
"Torch == 2.0.0", "torch[opt]>=2.0", "torch>=1.0,<3",
|
||||
"torch (>=2.0)", "torch(>=2.0)",
|
||||
"torch==", "torch=>2.0", # malformed version clauses
|
||||
])
|
||||
def test_blacklist_matches_every_requirement_form(self, requirement, tmp_path):
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\nnumpy\n")
|
||||
r = _resolver([p], blacklist={"torch"})
|
||||
deps = r.collect_requirements()
|
||||
assert [req.name for req in deps.requirements] == ["numpy"]
|
||||
assert deps.skipped == [(requirement, "blacklisted")]
|
||||
|
||||
def test_blacklist_filtering(self, tmp_path):
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", "torch\nnumpy\ntorchaudio\n")
|
||||
r = _resolver([p], blacklist={"torch", "torchaudio"})
|
||||
@@ -534,6 +546,91 @@ class TestDowngradeBlacklist:
|
||||
deps = r.collect_requirements()
|
||||
assert len(deps.requirements) == 1 # installed < requested → allowed
|
||||
|
||||
@pytest.mark.parametrize("entry", ["opencv-python", "opencv_python", "OpenCV-Python"])
|
||||
@pytest.mark.parametrize("requirement", ["opencv-python~=4.8.1.78", "opencv_python", "OpenCV-Python<4.9"])
|
||||
def test_name_spelling_does_not_matter(self, entry, requirement, tmp_path):
|
||||
# get_installed_packages() keys are normalised: lowercase with '_'.
|
||||
_MOCK_INSTALLED_PACKAGES["opencv_python"] = "5.0.0.93"
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\n")
|
||||
r = _resolver([p], downgrade_blacklist=[entry])
|
||||
deps = r.collect_requirements()
|
||||
assert deps.requirements == []
|
||||
assert "downgrade blacklisted" in deps.skipped[0][1]
|
||||
|
||||
@pytest.mark.parametrize("installed,requirement", [
|
||||
("0.0.30+cu126", "torch==0.0.20"), # a local version label
|
||||
("5.0.0.93", "torch<5"), # a fourth release component
|
||||
])
|
||||
def test_installed_version_forms_are_compared(self, installed, requirement, tmp_path, caplog):
|
||||
_MOCK_INSTALLED_PACKAGES["torch"] = installed
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\n")
|
||||
r = _resolver([p], downgrade_blacklist=["torch"])
|
||||
with caplog.at_level(logging.ERROR, logger="ComfyUI-Manager"):
|
||||
deps = r.collect_requirements()
|
||||
assert deps.skipped == [(requirement, "downgrade blacklisted")]
|
||||
assert caplog.text == ""
|
||||
|
||||
@pytest.mark.parametrize("entry", ["ruamel.yaml", "ruamel-yaml"])
|
||||
@pytest.mark.parametrize("requirement", ["ruamel.yaml<0.18", "ruamel-yaml<0.18"])
|
||||
def test_dots_are_name_separators(self, entry, requirement, tmp_path):
|
||||
_MOCK_INSTALLED_PACKAGES["ruamel_yaml"] = "0.18.6"
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\n")
|
||||
r = _resolver([p], downgrade_blacklist=[entry])
|
||||
deps = r.collect_requirements()
|
||||
assert deps.skipped == [(requirement, "downgrade blacklisted")]
|
||||
|
||||
@pytest.mark.parametrize("installed,requirement", [
|
||||
("2.1.0", "torch=>1.0"),
|
||||
("2.1.0", "torch=="),
|
||||
])
|
||||
def test_uncomparable_version_is_blocked_with_an_explanation(
|
||||
self, installed, requirement, tmp_path, caplog,
|
||||
):
|
||||
_MOCK_INSTALLED_PACKAGES["torch"] = installed
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\n")
|
||||
r = _resolver([p], downgrade_blacklist=["torch"])
|
||||
with caplog.at_level(logging.ERROR, logger="ComfyUI-Manager"):
|
||||
deps = r.collect_requirements()
|
||||
assert deps.requirements == []
|
||||
assert deps.skipped == [(requirement, "downgrade blacklisted")]
|
||||
errors = [record.getMessage() for record in caplog.records if record.levelno == logging.ERROR]
|
||||
assert len(errors) == 1
|
||||
assert f"Skipped '{requirement}'" in errors[0]
|
||||
assert f"installed version ({installed}) cannot be compared with the requested version" in errors[0]
|
||||
assert "Install it manually" in errors[0] and "downgrade_blacklist in config.ini" in errors[0]
|
||||
|
||||
@pytest.mark.parametrize("requirement,blocked", [
|
||||
("torch == 1.20", True),
|
||||
('torch==1.20; python_version > "3.8"', True),
|
||||
('torch ; python_version > "3.8"', True), # no version: the marker is not a version clause
|
||||
("torch<=1.20,>=1.0", True),
|
||||
("torch>=1.0,<2.0", True), # the lower bound comes first
|
||||
("torch (>=1.0,<2.0)", True),
|
||||
("torch(<2.0)", True),
|
||||
("torch===1.20", True),
|
||||
("torch==2.*", True),
|
||||
("torch[opt]==1.20", True),
|
||||
("torch == 3.0", False),
|
||||
('torch==3.0; python_version > "3.8"', False),
|
||||
("torch<=3.0,>=1.0", False),
|
||||
("torch>=1.0", False), # a lower bound below the installed version
|
||||
("torch>=1.0,<3.0", False),
|
||||
("torch(>=1.0,<3.0)", False),
|
||||
("torch==3.*", False),
|
||||
# With extras the installed version is kept and the extras' dependencies are added.
|
||||
("torch[opt]", False),
|
||||
("torch[opt]==2.1.0", False),
|
||||
])
|
||||
def test_version_clause_is_read_from_the_requirement(self, requirement, blocked, tmp_path, caplog):
|
||||
_MOCK_INSTALLED_PACKAGES["torch"] = "2.1.0"
|
||||
p = _make_node_pack(str(tmp_path), "pack_a", requirement + "\n")
|
||||
r = _resolver([p], downgrade_blacklist=["torch"])
|
||||
with caplog.at_level(logging.ERROR, logger="ComfyUI-Manager"):
|
||||
deps = r.collect_requirements()
|
||||
assert (deps.requirements == []) is blocked
|
||||
# A misread version would be reported as uncomparable.
|
||||
assert caplog.text == ""
|
||||
|
||||
def teardown_method(self):
|
||||
_MOCK_INSTALLED_PACKAGES.clear()
|
||||
|
||||
@@ -942,6 +1039,36 @@ class TestResolveAndInstall:
|
||||
specs = {spec for _, spec in attributed["torch"]}
|
||||
assert specs == {"torch>=2.1", "torch<2.0"}
|
||||
|
||||
def test_multiline_conflict_attribution(self, tmp_path):
|
||||
from comfyui_manager.common.unified_dep_resolver import attribute_conflicts
|
||||
|
||||
p1 = _make_node_pack(str(tmp_path), "pack_a", "python-slugify==8.0.4\n")
|
||||
p2 = _make_node_pack(str(tmp_path), "pack_b", "text-unidecode==1.2\n")
|
||||
p3 = _make_node_pack(str(tmp_path), "unrelated", "numpy>=1.20\n")
|
||||
resolver = _resolver([p1, p2, p3])
|
||||
stderr = (
|
||||
"debug: checking numpy>=1.20\n"
|
||||
"error: No solution found when resolving dependencies\n"
|
||||
" cause: Because python-slugify==8.0.4 depends on text-unidecode>=1.3 "
|
||||
"and you require python-slugify==8.0.4, we can conclude that you require text-unidecode>=1.3.\n"
|
||||
" And because you require text-unidecode==1.2, "
|
||||
"we can conclude that your requirements are unsatisfiable.\n"
|
||||
"debug: finished checking numpy>=1.20\n"
|
||||
)
|
||||
|
||||
with mock.patch.object(resolver, "_get_uv_cmd", return_value=["uv"]):
|
||||
with mock.patch("subprocess.run", return_value=subprocess.CompletedProcess(
|
||||
[], 1, stdout="", stderr=stderr,
|
||||
)) as run:
|
||||
result = resolver.resolve_and_install()
|
||||
|
||||
assert not result.success
|
||||
run.assert_called_once()
|
||||
assert attribute_conflicts(result.collected.sources, result.lockfile.conflicts) == {
|
||||
"python_slugify": [(p1, "python-slugify==8.0.4")],
|
||||
"text_unidecode": [(p2, "text-unidecode==1.2")],
|
||||
}
|
||||
|
||||
def test_conflict_attribution_no_false_positive_on_underscore_prefix(self, tmp_path):
|
||||
"""'torch' must NOT match 'torch_audio' in conflict text (underscore boundary)."""
|
||||
from comfyui_manager.common.unified_dep_resolver import attribute_conflicts
|
||||
@@ -1101,17 +1228,6 @@ class TestPatterns:
|
||||
assert _DANGEROUS_PATTERNS.match("requests") is None
|
||||
assert _DANGEROUS_PATTERNS.match("torch --index-url https://x.com") is None
|
||||
|
||||
def test_version_spec_pattern(self):
|
||||
m = _VERSION_SPEC_PATTERN.search("torch>=2.0")
|
||||
assert m is not None
|
||||
assert m.group(1) == "torch"
|
||||
assert m.group(2) == ">="
|
||||
assert m.group(3) == "2.0"
|
||||
|
||||
def test_version_spec_no_version(self):
|
||||
m = _VERSION_SPEC_PATTERN.search("torch")
|
||||
assert m is None
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# _extract_package_name
|
||||
@@ -1133,6 +1249,15 @@ class TestExtractPackageName:
|
||||
def test_at_url(self):
|
||||
assert UnifiedDepResolver._extract_package_name("pkg @ https://example.com/pkg.tar.gz") == "pkg"
|
||||
|
||||
def test_parentheses(self):
|
||||
assert UnifiedDepResolver._extract_package_name("numpy(<2)") == "numpy"
|
||||
|
||||
def test_dots(self):
|
||||
assert UnifiedDepResolver._extract_package_name("ruamel.yaml<0.18") == "ruamel_yaml"
|
||||
|
||||
def test_line_without_a_package_name(self):
|
||||
assert UnifiedDepResolver._extract_package_name("(Broken") == "(broken"
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# _is_disabled_path
|
||||
@@ -1232,6 +1357,27 @@ class TestParseConflicts:
|
||||
assert "conflicting" in result[0]
|
||||
assert "conflict" in result[1]
|
||||
|
||||
def test_preserves_indented_diagnostic_continuations(self):
|
||||
stderr = (
|
||||
"info: checking packages\n"
|
||||
"error: No solution found when resolving dependencies\n"
|
||||
" cause: package-a requires package-b>=2\n"
|
||||
" but package-b==1 is required\n"
|
||||
"\n"
|
||||
" debug: unrelated trace\n"
|
||||
"error: second diagnostic\n"
|
||||
" its continuation\n"
|
||||
"info: finished\n"
|
||||
" debug: unrelated detail\n"
|
||||
)
|
||||
assert UnifiedDepResolver._parse_conflicts(stderr) == [
|
||||
"error: No solution found when resolving dependencies",
|
||||
"cause: package-a requires package-b>=2",
|
||||
"but package-b==1 is required",
|
||||
"error: second diagnostic",
|
||||
"its continuation",
|
||||
]
|
||||
|
||||
def test_extracts_error_lines(self):
|
||||
stderr = "ERROR: No matching distribution found for nonexistent-pkg\n"
|
||||
result = UnifiedDepResolver._parse_conflicts(stderr)
|
||||
@@ -1259,8 +1405,7 @@ class TestParseConflicts:
|
||||
"debug: trace output\n"
|
||||
)
|
||||
result = UnifiedDepResolver._parse_conflicts(stderr)
|
||||
assert len(result) == 1
|
||||
assert "failed to resolve" in result[0]
|
||||
assert result == ["error: failed to resolve"]
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Versions with a suffix are read: node pack versions, and pip versions in pip_auto_fix.list (#3431).
|
||||
|
||||
A node pack installed from the registry has its version in pyproject.toml. The registry holds
|
||||
versions such as `1.8.0-beta.1`, and a pack may write `0.1.3.post1`. pip reports versions such
|
||||
as `2.5.1+cu124` and `4.41.0rc1`.
|
||||
"""
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from _install_flags_testutil import import_context, import_reader
|
||||
from test_pip_fixer_opencv import fix_broken # noqa: F401 -- fixture
|
||||
|
||||
|
||||
@pytest.fixture(params=["glob", "legacy"])
|
||||
def resolve(request, tmp_path):
|
||||
"""Returns what the installed-pack scan of each core reads for a registry pack of a given version."""
|
||||
import_context()
|
||||
manager = import_reader(request.param).UnifiedManager()
|
||||
manager.cnr_map["some-pack"] = {"id": "some-pack"}
|
||||
|
||||
def run(version):
|
||||
path = tmp_path / "some-pack"
|
||||
path.mkdir(exist_ok=True)
|
||||
(path / ".tracking").write_text("", encoding="utf-8")
|
||||
(path / "pyproject.toml").write_text(
|
||||
f'[project]\nname = "some-pack"\nversion = "{version}"\n', encoding="utf-8")
|
||||
return manager.resolve_from_path(str(path))
|
||||
|
||||
return run
|
||||
|
||||
|
||||
@pytest.mark.parametrize("written, read", [
|
||||
("1.2.3", "1.2.3"),
|
||||
("2.5", "2.5.0"),
|
||||
("3", "3.0.0"),
|
||||
("0.7.2-b2", "0.7.2-b2"),
|
||||
("1.8.0-beta.1", "1.8.0-beta.1"),
|
||||
("2.0.0-inprogress", "2.0.0-inprogress"),
|
||||
("0.1.3.post1", "0.1.3-post1"),
|
||||
("0.1.3-post1", "0.1.3-post1"), # what the scan itself writes for 0.1.3.post1
|
||||
])
|
||||
def test_a_registry_pack_is_read_with_its_version(resolve, written, read):
|
||||
info = resolve(written)
|
||||
|
||||
assert info["id"] == "some-pack"
|
||||
assert info["ver"] == read
|
||||
|
||||
|
||||
@pytest.mark.parametrize("written", ["", "abc", "1.x", "1.2.x", "1.2.3-", "2.5-beta", "1.0.0rc1", "1.0.3+local"])
|
||||
def test_a_pack_without_a_readable_version_is_not_a_registry_pack(resolve, written):
|
||||
assert resolve(written) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("installed, listed", [
|
||||
("2.5.1+cu124", "torch==2.5.1"),
|
||||
("2.5.1+cu124", "torch>=2.5.0"),
|
||||
("2.5.1+cu124", "torch<=2.5.1"),
|
||||
("2.5.1+cu124", "torch~=2.5.0"),
|
||||
("2.5.1", "torch~=2.5.1"),
|
||||
("2.6.0.dev20241112", "torch>2.5.1"),
|
||||
("2.5.1rc1", "torch!=2.5.1"),
|
||||
])
|
||||
def test_a_listed_requirement_that_the_installed_version_meets_is_left_alone(fix_broken, caplog, installed, listed): # noqa: F811
|
||||
with caplog.at_level(logging.ERROR):
|
||||
commands = fix_broken({"torch": installed, "torchvision": "0.20.1", "torchaudio": "2.5.1"}, pip_auto_fix=listed + "\n")
|
||||
|
||||
assert commands == []
|
||||
assert "Failed to restore" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("installed, listed", [
|
||||
("2.5.0+cu124", "torch==2.5.1"),
|
||||
("2.5.1rc1", "torch>=2.5.1"),
|
||||
("2.5.1rc1", "torch<2.5.1"), # as pip reads it: `<` leaves out the pre-releases of that version
|
||||
("2.5.1+cu124", "torch<2.5.1"),
|
||||
("2.5.1+cu124", "torch!=2.5.1"),
|
||||
("2.6.0", "torch~=2.5.1"),
|
||||
("2.5.0", "torch~=2.5.1"),
|
||||
])
|
||||
def test_a_listed_requirement_that_the_installed_version_misses_is_installed(fix_broken, installed, listed): # noqa: F811
|
||||
assert fix_broken({"torch": installed, "torchvision": "0.20.1", "torchaudio": "2.5.1"},
|
||||
pip_auto_fix=listed + "\n") == ["install " + listed]
|
||||
|
||||
|
||||
def test_the_index_url_of_a_listed_requirement_is_passed_to_pip(fix_broken): # noqa: F811
|
||||
index = "https://download.pytorch.org/whl/cu124"
|
||||
|
||||
assert fix_broken({"torch": "2.5.0+cu124", "torchvision": "0.20.1", "torchaudio": "2.5.1"},
|
||||
pip_auto_fix=f"torch==2.5.1 --index-url {index}\n") == [f"install torch==2.5.1 --index-url {index}"]
|
||||
Reference in New Issue
Block a user