Compare commits

..
1 Commits
Author SHA1 Message Date
Robin Huang 14b82d97ae Print form factor. 2025-03-12 15:01:43 -07:00
163 changed files with 21971 additions and 258622 deletions
View File
-58
View File
@@ -1,58 +0,0 @@
name: Publish to PyPI
on:
workflow_dispatch:
push:
branches:
- draft-v4
paths:
- "pyproject.toml"
jobs:
build-and-publish:
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'ltdrdata' || github.repository_owner == 'Comfy-Org' }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install build twine
- name: Get current version
id: current_version
run: |
CURRENT_VERSION=$(grep -oP 'version = "\K[^"]+' pyproject.toml)
echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
echo "Current version: $CURRENT_VERSION"
- name: Build package
run: python -m build
- name: Create GitHub Release
id: create_release
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
files: dist/*
tag_name: v${{ steps.current_version.outputs.version }}
draft: false
prerelease: false
generate_release_notes: true
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
password: ${{ secrets.PYPI_TOKEN }}
skip-existing: true
verbose: true
+2 -6
View File
@@ -7,19 +7,15 @@ on:
paths:
- "pyproject.toml"
permissions:
issues: write
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'ltdrdata' }}
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Publish Custom Node
uses: Comfy-Org/publish-node-action@v1
uses: Comfy-Org/publish-node-action@main
with:
## Add your own personal access token to your Github Repository secrets and reference it here.
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
+1 -3
View File
@@ -16,7 +16,5 @@ comfyworkflows_sharekey
github-stats-cache.json
pip_overrides.json
*.json
# Track JSON test fixtures.
!tests/cases/*.json
check2.sh
/venv/
/venv/
-1064
View File
File diff suppressed because it is too large Load Diff
+37 -149
View File
@@ -5,11 +5,10 @@
![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/refs/heads/Main/ComfyUI-Manager/images/dialog.jpg)
## NOTICE
* V3.38: **Security patch** - Manager data migrated to protected path. See [Migration Guide](docs/en/v3.38-userdata-security-migration.md).
* V3.16: Support for `uv` has been added. Set `use_uv` in `config.ini`.
* V3.10: `double-click feature` is removed
* This feature has been moved to https://github.com/ltdrdata/comfyui-connection-helper
* V3.3.2: Overhauled. Officially supports [https://registry.comfy.org/](https://registry.comfy.org/).
* V3.3.2: Overhauled. Officially supports [https://comfyregistry.org/](https://comfyregistry.org/).
* You can see whole nodes info on [ComfyUI Nodes Info](https://ltdrdata.github.io/) page.
## Installation
@@ -18,7 +17,7 @@
To install ComfyUI-Manager in addition to an existing installation of ComfyUI, you can follow the following steps:
1. Go to `ComfyUI/custom_nodes` dir in terminal (cmd)
1. goto `ComfyUI/custom_nodes` dir in terminal(cmd)
2. `git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager`
3. Restart ComfyUI
@@ -29,8 +28,8 @@ To install ComfyUI-Manager in addition to an existing installation of ComfyUI, y
- standalone version
- select option: use windows default console window
2. Download [scripts/install-manager-for-portable-version.bat](https://github.com/ltdrdata/ComfyUI-Manager/raw/main/scripts/install-manager-for-portable-version.bat) into installed `"ComfyUI_windows_portable"` directory
- Don't click. Right-click the link and choose 'Save As...'
3. Double-click `install-manager-for-portable-version.bat` batch file
- Don't click. Right click the link and use save as...
3. double click `install-manager-for-portable-version.bat` batch file
![portable-install](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/portable-install.jpg)
@@ -48,7 +47,7 @@ pip install comfy-cli
comfy install
```
Linux/macOS:
Linux/OSX:
```commandline
python -m venv venv
. venv/bin/activate
@@ -58,13 +57,13 @@ comfy install
* See also: https://github.com/Comfy-Org/comfy-cli
### Installation[method4] (Installation for Linux+venv: ComfyUI + ComfyUI-Manager)
### Installation[method4] (Installation for linux+venv: ComfyUI + ComfyUI-Manager)
To install ComfyUI with ComfyUI-Manager on Linux using a venv environment, you can follow these steps:
* **prerequisite: python-is-python3, python3-venv, git**
1. Download [scripts/install-comfyui-venv-linux.sh](https://github.com/ltdrdata/ComfyUI-Manager/raw/main/scripts/install-comfyui-venv-linux.sh) into empty install directory
- Don't click. Right-click the link and choose 'Save As...'
- Don't click. Right click the link and use save as...
- ComfyUI will be installed in the subdirectory of the specified directory, and the directory will contain the generated executable script.
2. `chmod +x install-comfyui-venv-linux.sh`
3. `./install-comfyui-venv-linux.sh`
@@ -129,7 +128,8 @@ This repository provides Colab notebooks that allow you to install and use Comfy
![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/topbar.jpg) ![share](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share.jpg)
* 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://youml.com](https://youml.com)
* 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)
as well as through the Matrix channel.
![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share-setting.jpg)
@@ -140,27 +140,20 @@ This repository provides Colab notebooks that allow you to install and use Comfy
## Paths
Starting from V3.38, Manager uses a protected system path for enhanced security.
In `ComfyUI-Manager` V3.0 and later, configuration files and dynamically generated files are located under `<USER_DIRECTORY>/default/ComfyUI-Manager/`.
* <USER_DIRECTORY>
* If executed without any options, the path defaults to ComfyUI/user.
* It can be set using --user-directory <USER_DIRECTORY>.
* <USER_DIRECTORY>
* If executed without any options, the path defaults to ComfyUI/user.
* It can be set using --user-directory <USER_DIRECTORY>.
| ComfyUI Version | Manager Path |
|-----------------|--------------|
| v0.3.76+ (with System User API) | `<USER_DIRECTORY>/__manager/` |
| Older versions | `<USER_DIRECTORY>/default/ComfyUI-Manager/` |
* Basic config files: `config.ini`
* Configurable channel lists: `channels.list`
* Configurable pip overrides: `pip_overrides.json`
* Configurable pip blacklist: `pip_blacklist.list`
* Configurable pip auto fix: `pip_auto_fix.list`
* Saved snapshot files: `snapshots/`
* Startup script files: `startup-scripts/`
* Component files: `components/`
> **Note**: See [Migration Guide](docs/en/v3.38-userdata-security-migration.md) for upgrade details.
* Basic config files: `<USER_DIRECTORY>/default/ComfyUI-Manager/config.ini`
* Configurable channel lists: `<USER_DIRECTORY>/default/ComfyUI-Manager/channels.ini`
* Configurable pip overrides: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_overrides.json`
* Configurable pip blacklist: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_blacklist.list`
* Configurable pip auto fix: `<USER_DIRECTORY>/default/ComfyUI-Manager/pip_auto_fix.list`
* Saved snapshot files: `<USER_DIRECTORY>/default/ComfyUI-Manager/snapshots`
* Startup script files: `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts`
* Component files: `<USER_DIRECTORY>/default/ComfyUI-Manager/components`
## `extra_model_paths.yaml` Configuration
@@ -178,12 +171,12 @@ The following settings are applied based on the section marked as `is_default`.
* Press the "Restore" button to revert to the installation status of the respective snapshot.
* However, for custom nodes not managed by Git, snapshot support is incomplete.
* When you press `Restore`, it will take effect on the next ComfyUI startup.
* The selected snapshot file is saved in `<USER_DIRECTORY>/__manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
* The selected snapshot file is saved in `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
![model-install-dialog](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/snapshot.jpg)
## cm-cli: command line tools for power users
## cm-cli: command line tools for power user
* A tool is provided that allows you to use the features of ComfyUI-Manager without running ComfyUI.
* For more details, please refer to the [cm-cli documentation](docs/en/cm-cli.md).
@@ -229,7 +222,7 @@ The following settings are applied based on the section marked as `is_default`.
* `<current timestamp>` Ensure that the timestamp is always unique.
* "components" should have the same structure as the content of the file stored in `<USER_DIRECTORY>/default/ComfyUI-Manager/components`.
* `<component name>`: The name should be in the format `<prefix>::<node name>`.
* `<component node data>`: In the node data of the group node.
* `<compnent nodeata>`: In the nodedata of the group node.
* `<version>`: Only two formats are allowed: `major.minor.patch` or `major.minor`. (e.g. `1.0`, `2.2.1`)
* `<datetime>`: Saved time
* `<packname>`: If the packname is not empty, the category becomes packname/workflow, and it is saved in the <packname>.pack file in `<USER_DIRECTORY>/default/ComfyUI-Manager/components`.
@@ -247,7 +240,7 @@ The following settings are applied based on the section marked as `is_default`.
* Dragging and dropping or pasting a single component will add a node. However, when adding multiple components, nodes will not be added.
## Support for installing missing nodes
## Support of missing nodes installation
![missing-menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/missing-menu.jpg)
@@ -286,10 +279,10 @@ The following settings are applied based on the section marked as `is_default`.
* Logging to file feature
* This feature is enabled by default and can be disabled by setting `file_logging = False` in the `config.ini`.
* Fix node (recreate): When right-clicking on a node and selecting `Fix node (recreate)`, you can recreate the node. The widget's values are reset, while the connections maintain those with the same names.
* Fix node(recreate): When right-clicking on a node and selecting `Fix node (recreate)`, you can recreate the node. The widget's values are reset, while the connections maintain those with the same names.
* It is used to correct errors in nodes of old workflows created before, which are incompatible with the version changes of custom nodes.
* Double-Click Node Title: You can set the double-click behavior of nodes in the ComfyUI-Manager menu.
* Double-Click Node Title: You can set the double click behavior of nodes in the ComfyUI-Manager menu.
* `Copy All Connections`, `Copy Input Connections`: Double-clicking a node copies the connections of the nearest node.
* This action targets the nearest node within a straight-line distance of 1000 pixels from the center of the node.
* In the case of `Copy All Connections`, it duplicates existing outputs, but since it does not allow duplicate connections, the existing output connections of the original node are disconnected.
@@ -306,7 +299,6 @@ 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.
@@ -322,6 +314,9 @@ The following settings are applied based on the section marked as `is_default`.
* Use `aria2` as downloader
* [howto](docs/en/use_aria2.md)
* If you add the item `skip_migration_check = True` to `config.ini`, it will not check whether there are nodes that can be migrated at startup.
* This option can be used if performance issues occur in a Colab+GDrive environment.
## Environment Variables
@@ -356,7 +351,7 @@ When you run the `scan.sh` script:
* It updates the `github-stats.json`.
* This uses the GitHub API, so set your token with `export GITHUB_TOKEN=your_token_here` to avoid quickly reaching the rate limit and malfunctioning.
* To skip this step, add the `--skip-stat-update` option.
* To skip this step, add the `--skip-update-stat` option.
* The `--skip-all` option applies both `--skip-update` and `--skip-stat-update`.
@@ -364,9 +359,9 @@ When you run the `scan.sh` script:
## Troubleshooting
* If your `git.exe` is installed in a specific location other than system git, please install ComfyUI-Manager and run ComfyUI. Then, specify the path including the file name in `git_exe = ` in the `<USER_DIRECTORY>/default/ComfyUI-Manager/config.ini` file that is generated.
* If updating ComfyUI-Manager itself fails, please go to the **ComfyUI-Manager** directory and execute the command `git update-ref refs/remotes/origin/main a361cc1 && git fetch --all && git pull`.
* If you encounter the error message `Overlapped Object has pending operation at deallocation on ComfyUI Manager load` under Windows
* If you encounter the error message `Overlapped Object has pending operation at deallocation on Comfyui Manager load` under Windows
* Edit `config.ini` file: add `windows_selector_event_loop_policy = True`
* If the `SSL: CERTIFICATE_VERIFY_FAILED` error occurs.
* if `SSL: CERTIFICATE_VERIFY_FAILED` error is occured.
* Edit `config.ini` file: add `bypass_ssl = True`
@@ -384,126 +379,19 @@ When you run the `scan.sh` script:
* all feature is available
* `high` level risky features
* Downloading models that are not in `.safetensors` format and not
registered in the `default channel` model list
* Switch ComfyUI to an older version
* Restore Snapshot
* NOTE: `Install via git url`, `pip install`, and installation of custom nodes
not registered in the `default channel` are **no longer governed by
`security_level`** — they are governed by the dedicated install flags
described below.
* `Install via git url`, `pip install`
* Installation of custom nodes registered not in the `default channel`.
* Fix custom nodes
* `middle` level risky features
* Uninstall/Update
* Installation of custom nodes registered in the `default channel`.
* Fix custom nodes
* Remove Snapshot
* Restore/Remove Snapshot
* Restart
* `low` level risky features
* Update ComfyUI
### Dedicated install flags: `allow_git_url_install` / `allow_pip_install`
The two arbitrary-install surfaces are governed by dedicated boolean keys in
`config.ini` (`[default]` section), fully **decoupled** from `security_level`:
* `allow_git_url_install`
* governs `Install via Git URL` (`POST /customnode/install/git_url`) **and**
the unknown-git-URL arm of the batch install queue
(`POST /manager/queue/install`, including reinstall delegation) — i.e.
installing any custom node from a git URL that is not registered in the
`default channel` catalog
* on the **batch queue path**, the flag is **necessary but not
sufficient**: the queue's normal `security_level` entry gate (`middle`)
must ALSO pass — at `security_level = strong`, batch unknown-URL
installs stay denied even with the flag set to `true` (only the direct
`Install via Git URL` endpoint is fully independent of `security_level`)
* covers the **entire install transaction** it starts, including the
pack's transitive dependency pip installs
* `allow_pip_install`
* governs **only** the standalone `pip install` feature
(`POST /customnode/install/pip`)
Key properties:
* **Decoupled from `security_level` (replace, not and)** — on the two
**direct endpoints** (`Install via Git URL` and `pip install`),
`security_level` no longer has any effect in either direction: a strict
level cannot deny them when the flag is `true`, and a weak level cannot
allow them when the flag is `false`. (The batch queue path keeps its
`security_level` entry gate in ADDITION to the flag — see the scope bullet
above.) Every other gated feature remains governed by `security_level` as
described above.
* **Loopback only** — the flags take effect **only** when the server listens
on a loopback address (e.g. `--listen 127.0.0.1`). On a non-loopback
listener these surfaces stay denied regardless of the flags; the flags
never widen the exposure of a public deployment.
* **Default deny / explicit opt-in** — both flags default to `false`. Only
the case-insensitive string `true` enables a flag; a missing or malformed
key reads as `false`.
To opt in, edit `config.ini`:
```ini
[default]
allow_git_url_install = true
allow_pip_install = true
```
Changes take effect after a **restart** (no hot reload).
> **Migration note**: there is no automatic migration from `security_level`.
> If you previously relied on `security_level = weak` (or `normal-`) to use
> install-via-git-URL / pip install, you must opt in explicitly with the flags
> above. See `CHANGELOG.md` for details, including a behavior note for
> outdated ComfyUI deployments.
### Flagged CNR versions: `allow_flagged_nodepack_install`
Manager checks the version status in the existing CNR install response; no
additional Registry request is needed. Active versions continue to install
normally, subject to the existing security policy. Registry refusals (including
HTTP 404) still prevent installation.
Flagged versions must also satisfy the existing security policy and Registry
checks. In addition, they require either **all** `--listen` addresses to be
loopback, such as `127.0.0.1` or `::1`, or the explicit override below.
A mixed loopback/non-loopback listener is non-local.
For a **trusted private network**, administrators can explicitly allow flagged
versions on non-loopback listeners:
```ini
[default]
allow_flagged_nodepack_install = true
```
The default is `false`; only the case-insensitive value `true` enables it.
Restart ComfyUI after editing the setting. This option does not detect private
networks and is independent of `network_mode`. It does not bypass
`security_level`, `allow_git_url_install`, or `allow_pip_install`.
When the flagged-version check denies an action, the UI reports that the current
security configuration does not allow it and directs users to the terminal.
Only the terminal provides the loopback-only `--listen` examples, the private
network override setting, and the instruction to restart ComfyUI after changes.
Enabling an already installed version does not query the Registry or reinstall it.
Older deferred switches without a stored status require loopback-only listeners
or the override. Otherwise they are rejected without changing the installed pack;
request the installation again so Manager can check its current Registry status.
The check applies to server-initiated installation, reinstallation, version switches, updates,
and snapshot restores. A policy refusal preserves the existing nodepack.
Scheduled version switches save the returned status and check the current
listener and setting again at startup, before downloading or running scripts.
Server-scheduled snapshot restores inherit the permission computed from the
server's current listener and setting. Standalone `cm-cli` commands remain local
administrator operations and do not use the server listener policy.
Saved statuses are not refreshed from the Registry.
# Disclaimer
-4
View File
@@ -1,7 +1,3 @@
"""
This file is the entry point for the ComfyUI-Manager package, handling CLI-only mode and initial setup.
"""
import os
import sys
+2 -2
View File
@@ -37,7 +37,7 @@ find ~/.tmp/default -name "*.py" -print0 | xargs -0 grep -E "crypto|^_A="
echo
echo CHECK3
find ~/.tmp/default -name "requirements.txt" | xargs grep "^\s*[^#]*https\?:"
find ~/.tmp/default -name "requirements.txt" | xargs grep "^\s*[^#].*\.whl"
find ~/.tmp/default -name "requirements.txt" | xargs grep "^\s*https\\?:"
find ~/.tmp/default -name "requirements.txt" | xargs grep "\.whl"
echo
+121 -134
View File
@@ -8,7 +8,7 @@ import threading
from typing import Optional
import typer
import rich
from rich import print
from typing_extensions import List, Annotated
import re
import git
@@ -29,7 +29,7 @@ if comfy_path is None:
import folder_paths
comfy_path = os.path.join(os.path.dirname(folder_paths.__file__))
except:
rich.print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
print("\n[bold yellow]WARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.[/bold yellow]", file=sys.stderr)
comfy_path = os.path.abspath(os.path.join(manager_util.comfyui_manager_path, '..', '..'))
# This should be placed here
@@ -41,14 +41,11 @@ import manager_core as core
from manager_core import unified_manager
import cnr_utils
print = core.print
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
cm_global.pip_downgrade_blacklist = ['torch', 'torchaudio', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
cm_global.pip_overrides = {}
cm_global.pip_blacklist = {'torch', 'torchsde', 'torchvision'}
cm_global.pip_downgrade_blacklist = ['torch', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
cm_global.pip_overrides = {'numpy': 'numpy<2'}
if os.path.exists(os.path.join(manager_util.comfyui_manager_path, "pip_overrides.json")):
with open(os.path.join(manager_util.comfyui_manager_path, "pip_overrides.json"), 'r', encoding="UTF-8", errors="ignore") as json_file:
@@ -69,7 +66,7 @@ def check_comfyui_hash():
core.comfy_ui_revision = len(list(repo.iter_commits('HEAD')))
core.comfy_ui_commit_datetime = repo.head.commit.committed_datetime
except:
print('INFO: Frozen ComfyUI mode.', style='bold yellow')
print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
core.comfy_ui_revision = 0
core.comfy_ui_commit_datetime = 0
@@ -77,13 +74,14 @@ def check_comfyui_hash():
check_comfyui_hash() # This is a preparation step for manager_core
core.check_invalid_nodes()
def read_downgrade_blacklist():
try:
import configparser
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(core.manager_config_path)
config = configparser.ConfigParser(strict=False)
config.read(core.manager_config.path)
default_conf = config['default']
if 'downgrade_blacklist' in default_conf:
@@ -137,25 +135,26 @@ class Ctx:
self.no_deps = no_deps
def set_user_directory(self, user_directory):
if user_directory is not None:
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
if user_directory is None:
return
core.update_user_directory(user_directory)
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
if os.path.exists(core.manager_pip_overrides_path):
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
core.update_user_directory(user_directory)
if os.path.exists(core.manager_pip_blacklist_path):
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
if os.path.exists(core.manager_pip_overrides_path):
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
cm_global.pip_overrides = {'numpy': 'numpy<2'}
core.setup_git_executable()
if os.path.exists(core.manager_pip_blacklist_path):
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
def update_custom_nodes_dir(self, target_dir):
import folder_paths
@@ -185,17 +184,13 @@ class Ctx:
cmd_ctx = Ctx()
def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
exit_on_fail = kwargs.get('exit_on_fail', False)
def install_node(node_spec_str, is_all=False, cnt_msg=''):
if core.is_valid_url(node_spec_str):
# install via urls
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
if not res.result:
print(res.msg)
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
if exit_on_fail:
sys.exit(1)
print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
else:
print(f"{cnt_msg} [INSTALLED] {node_spec_str:50}")
else:
@@ -214,7 +209,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
if res.action == 'skip':
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
elif res.action == 'enable' and res.result:
elif res.action == 'enable':
print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
elif res.action == 'install-git' and res.target == 'nightly':
print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
@@ -229,62 +224,37 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
show_versions(node_name)
print("")
else:
print(f"ERROR: An error occurred while installing '{node_name}'.\n{res.msg}", style="bold red")
if exit_on_fail:
sys.exit(1)
print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.\n{res.msg}[/bold red]")
def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
node_name, version_spec, is_specified = unified_manager.resolve_node_spec(node_spec_str)
repo_url = None
if core.is_valid_url(node_name):
url = node_name.rstrip('/')
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
node_name = cnr['id']
if not is_specified:
version_spec = unified_manager.resolve_unspecified_version(node_name)
else:
node_name, version_spec, repo_url = core.unknown_node_id(url), 'unknown', url
node_spec = unified_manager.resolve_node_spec(node_spec_str)
if not is_specified and repo_url is None:
for guess_mode in ('active', 'inactive'):
installed = unified_manager.resolve_unspecified_version(node_name, guess_mode=guess_mode)
if installed not in (None, 'unknown'):
version_spec = installed
break
node_name, version_spec, _ = node_spec
res = asyncio.run(unified_manager.reinstall_by_id(node_name, version_spec, cmd_ctx.channel, cmd_ctx.mode, instant_execution=True,
no_deps=cmd_ctx.no_deps, repo_url=repo_url))
if res.action == 'skip':
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
return
if not res.result:
print(f"ERROR: An error occurred while reinstalling '{node_name}'.\n{res.msg}", style="bold red")
return
target = res.target.upper() if res.target in ('nightly', 'unknown') else res.target
print(f"{cnt_msg} [REINSTALLED] {node_name:50}[{target}]")
unified_manager.unified_uninstall(node_name, version_spec == 'unknown')
install_node(node_name, is_all=is_all, cnt_msg=cnt_msg)
def fix_node(node_spec_str, is_all=False, cnt_msg='', fixed=None):
def fix_node(node_spec_str, is_all=False, cnt_msg=''):
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
if node_spec is None:
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
if not is_all:
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
return
node_name, version_spec, _ = node_spec
print(f"{cnt_msg} [ FIXING ]: {node_name:50}[{version_spec}]")
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps, fixed=fixed)
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps)
if not res.result:
print(f"ERROR: {res.msg}", style="bold red")
print(f"[bold red]ERROR: f{res.msg}[/bold red]")
def uninstall_node(node_spec_str: str, is_all: bool = False, cnt_msg: str = ''):
@@ -340,9 +310,8 @@ def update_parallel(nodes):
nodes = []
for x in unified_manager.active_nodes.keys():
nodes.append(x)
for k, v in unified_manager.unknown_active_nodes.items():
if v[1] not in unified_manager.invalid_installations:
nodes.append(k+"@unknown")
for x in unified_manager.unknown_active_nodes.keys():
nodes.append(x+"@unknown")
else:
nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui']]
@@ -416,7 +385,6 @@ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
if 'comfyui-manager' in node_spec_str.lower():
print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not disabled: its name has 'comfyui-manager'")
return
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
@@ -470,7 +438,11 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_active_nodes.items():
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
item = repo_unknown.get(k)
if item is None:
continue
log_item = "[ ENABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -497,7 +469,11 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_inactive_nodes.items():
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
item = repo_unknown.get(k)
if item is None:
continue
log_item = "[ DISABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -528,7 +504,7 @@ def show_list(kind, simple=False):
if simple:
print(title+'@'+ver_spec)
else:
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [{ver_spec}]")
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
for x in unknown_processed:
prefix, title, short_id, author = x
@@ -538,19 +514,19 @@ def show_list(kind, simple=False):
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
def show_snapshot(simple_mode=False):
json_obj = asyncio.run(core.get_current_snapshot())
async def show_snapshot(simple_mode=False):
json_obj = await core.get_current_snapshot()
if simple_mode:
core.print(f"[{json_obj['comfyui']}] comfyui")
print(f"[{json_obj['comfyui']}] comfyui")
for k, v in json_obj['git_custom_nodes'].items():
core.print(f"[{v['hash']}] {k}")
print(f"[{v['hash']}] {k}")
for v in json_obj['file_custom_nodes']:
core.print(f"[ N/A ] {v['filename']}")
print(f"[ N/A ] {v['filename']}")
else:
formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
core.print(formatted_json)
print(formatted_json)
def show_snapshot_list(simple_mode=False):
@@ -610,7 +586,7 @@ def get_all_installed_node_specs():
return res
def for_each_nodes(nodes, act, allow_all=True, **kwargs):
def for_each_nodes(nodes, act, allow_all=True):
is_all = False
if allow_all and 'all' in nodes:
is_all = True
@@ -622,7 +598,7 @@ def for_each_nodes(nodes, act, allow_all=True, **kwargs):
i = 1
for x in nodes:
try:
act(x, is_all=is_all, cnt_msg=f'{i}/{total}', **kwargs)
act(x, is_all=is_all, cnt_msg=f'{i}/{total}')
except Exception as e:
print(f"ERROR: {e}")
traceback.print_exc()
@@ -652,7 +628,7 @@ def install(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
no_deps: Annotated[
Optional[bool],
@@ -666,17 +642,13 @@ def install(
None,
help="user directory"
),
exit_on_fail: bool = typer.Option(
False,
help="Exit on failure"
)
):
cmd_ctx.set_user_directory(user_directory)
cmd_ctx.set_channel_mode(channel, mode)
cmd_ctx.set_no_deps(no_deps)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
for_each_nodes(nodes, act=install_node, exit_on_fail=exit_on_fail)
for_each_nodes(nodes, act=install_node)
pip_fixer.fix_broken()
@@ -694,7 +666,7 @@ def reinstall(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
no_deps: Annotated[
Optional[bool],
@@ -732,7 +704,7 @@ def uninstall(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
):
cmd_ctx.set_channel_mode(channel, mode)
@@ -743,7 +715,7 @@ def uninstall(
def update(
nodes: List[str] = typer.Argument(
...,
help="all|List of custom nodes to update"
help="[all|List of custom nodes to update]"
),
channel: Annotated[
str,
@@ -754,7 +726,7 @@ def update(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -782,7 +754,7 @@ def update(
def disable(
nodes: List[str] = typer.Argument(
...,
help="all|List of custom nodes to disable"
help="[all|List of custom nodes to disable]"
),
channel: Annotated[
str,
@@ -793,7 +765,7 @@ def disable(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -813,7 +785,7 @@ def disable(
def enable(
nodes: List[str] = typer.Argument(
...,
help="all|List of custom nodes to enable"
help="[all|List of custom nodes to enable]"
),
channel: Annotated[
str,
@@ -824,7 +796,7 @@ def enable(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -844,7 +816,7 @@ def enable(
def fix(
nodes: List[str] = typer.Argument(
...,
help="all|List of custom nodes to fix"
help="[all|List of custom nodes to fix]"
),
channel: Annotated[
str,
@@ -855,7 +827,7 @@ def fix(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -869,7 +841,7 @@ def fix(
asyncio.run(auto_save_snapshot())
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
for_each_nodes(nodes, fix_node, allow_all=True, fixed=set())
for_each_nodes(nodes, fix_node, allow_all=True)
pip_fixer.fix_broken()
@@ -886,7 +858,7 @@ def show_versions(node_name: str):
@app.command("show", help="Show node list")
def show(
arg: str = typer.Argument(
help="installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list"
help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
),
channel: Annotated[
str,
@@ -897,7 +869,7 @@ def show(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -931,7 +903,7 @@ def show(
@app.command("simple-show", help="Show node list (simple mode)")
def simple_show(
arg: str = typer.Argument(
help="installed|enabled|not-installed|disabled|all|snapshot|snapshot-list"
help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
),
channel: Annotated[
str,
@@ -942,7 +914,7 @@ def simple_show(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -959,7 +931,7 @@ def simple_show(
"snapshot-list",
]
if arg not in valid_commands:
typer.echo(f"Invalid command: `show {arg}`", err=True)
typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
exit(1)
cmd_ctx.set_user_directory(user_directory)
@@ -976,7 +948,7 @@ def simple_show(
@app.command('cli-only-mode', help="Set whether to use ComfyUI-Manager in CLI-only mode.")
def cli_only_mode(
mode: str = typer.Argument(
..., help="enable|disable"
..., help="[enable|disable]"
),
user_directory: str = typer.Option(
None,
@@ -995,7 +967,7 @@ def cli_only_mode(
os.remove(cli_mode_flag)
print("\nINFO: `cli-only-mode` is disabled\n")
else:
print(f"\nInvalid value for cli-only-mode: {mode}\n", style="bold red")
print(f"\n[bold red]Invalid value for cli-only-mode: {mode}[/bold red]\n")
exit(1)
@@ -1018,7 +990,7 @@ def deps_in_workflow(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -1032,7 +1004,7 @@ def deps_in_workflow(
output_path = output
if not os.path.exists(input_path):
print(f"File not found: {input_path}", style="bold red")
print(f"[bold red]File not found: {input_path}[/bold red]")
exit(1)
used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
@@ -1075,16 +1047,18 @@ def save_snapshot(
):
cmd_ctx.set_user_directory(user_directory)
if output is not None:
if(not output.endswith('.json') and not output.endswith('.yaml')):
print("ERROR: output path should be either '.json' or '.yaml' file.", style="bold red")
raise typer.Exit(code=1)
dir_path = os.path.dirname(output)
if output is None:
print("[bold red]ERROR: missing output path[/bold red]")
raise typer.Exit(code=1)
if(dir_path != '' and not os.path.exists(dir_path)):
print(f"ERROR: {output} path not exists.", style="bold red")
raise typer.Exit(code=1)
if(not output.endswith('.json') and not output.endswith('.yaml')):
print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
raise typer.Exit(code=1)
dir_path = os.path.dirname(output)
if(dir_path != '' and not os.path.exists(dir_path)):
print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
raise typer.Exit(code=1)
path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
print(f"Current snapshot is saved as `{path}`")
@@ -1142,21 +1116,18 @@ def restore_snapshot(
else:
snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
if not os.path.exists(snapshot_path):
print(f"ERROR: `{snapshot_path}` is not exists.", style="bold red")
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
try:
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
asyncio.run(core.restore_snapshot(snapshot_path, extras))
except Exception:
print("ERROR: Failed to restore snapshot.", style="bold red")
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
traceback.print_exc()
raise typer.Exit(code=1)
pip_fixer.fix_broken()
if not is_restored:
raise typer.Exit(code=1)
@app.command(
"restore-dependencies", help="Restore dependencies from whole installed custom nodes."
@@ -1174,7 +1145,7 @@ def restore_dependencies(
for base_path in cmd_ctx.get_custom_nodes_paths():
for name in os.listdir(base_path):
target = os.path.join(base_path, name)
if os.path.isdir(target) and not name.endswith('.disabled') and name != '__pycache__':
if os.path.isdir(target) and not name.endswith('.disabled'):
node_paths.append(target)
total = len(node_paths)
@@ -1221,7 +1192,7 @@ def install_deps(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -1233,14 +1204,14 @@ def install_deps(
asyncio.run(auto_save_snapshot())
if not os.path.exists(deps):
print(f"File not found: {deps}", style="bold red")
print(f"[bold red]File not found: {deps}[/bold red]")
exit(1)
else:
with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
try:
json_obj = json.load(json_file)
except:
print(f"Invalid json file: {deps}", style="bold red")
print(f"[bold red]Invalid json file: {deps}[/bold red]")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
@@ -1251,8 +1222,7 @@ def install_deps(
elif state == 'not-installed':
asyncio.run(core.gitclone_install(k, instant_execution=True))
else: # disabled
cnr = unified_manager.get_cnr_by_repo(k)
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
core.gitclone_set_active([k], False)
pip_fixer.fix_broken()
print("Dependency installation and activation complete.")
@@ -1275,7 +1245,7 @@ def export_custom_node_ids(
] = None,
mode: str = typer.Option(
None,
help="remote|local|cache"
help="[remote|local|cache]"
),
user_directory: str = typer.Option(
None,
@@ -1301,6 +1271,23 @@ def export_custom_node_ids(
print(f"{x['id']}@unknown", file=output_file)
@app.command(
"migrate",
help="Migrate legacy node system to new node system",
)
def migrate(
user_directory: str = typer.Option(
None,
help="user directory"
)
):
cmd_ctx.set_user_directory(user_directory)
asyncio.run(unified_manager.migrate_unmanaged_nodes())
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(app())
print("")
Regular → Executable
+1963 -42541
View File
File diff suppressed because it is too large Load Diff
-41
View File
@@ -1,41 +0,0 @@
# ComfyUI-Manager: Documentation
This directory contains documentation for the ComfyUI-Manager, providing guides and tutorials for users in multiple languages.
## Directory Structure
The documentation is organized into language-specific directories:
- **en/**: English documentation
- **ko/**: Korean documentation
## Core Documentation Files
### Command-Line Interface
- **cm-cli.md**: Documentation for the ComfyUI-Manager Command Line Interface (CLI), which allows using manager functionality without the UI.
### Advanced Features
- **use_aria2.md**: Guide for using the aria2 download accelerator with ComfyUI-Manager for faster model downloads.
## Documentation Standards
The documentation follows these standards:
1. **Markdown Format**: All documentation is written in Markdown for easy rendering on GitHub and other platforms
2. **Language-specific Directories**: Content is separated by language to facilitate localization
3. **Feature-focused Documentation**: Each major feature has its own documentation file
4. **Updated with Releases**: Documentation is kept in sync with software releases
## Contributing to Documentation
When contributing new documentation:
1. Place files in the appropriate language directory
2. Use clear, concise language appropriate for the target audience
3. Include examples where helpful
4. Consider adding screenshots or diagrams for complex features
5. Maintain consistent formatting with existing documentation
This documentation directory will continue to grow to support the expanding feature set of ComfyUI-Manager.
+3 -3
View File
@@ -105,7 +105,7 @@ ComfyUI-Loopchain
* Detailed Operations
* `install`: Installs the specified custom nodes.
* `reinstall`: Removes and then reinstalls the specified custom nodes. A nodepack named without a version is reinstalled at the version that is installed.
* `reinstall`: Removes and then reinstalls the specified custom nodes.
* `uninstall`: Uninstalls the specified custom nodes.
* `update`: Updates the specified custom nodes.
* `disable`: Disables the specified custom nodes.
@@ -139,9 +139,9 @@ You can set whether to use ComfyUI-Manager solely via CLI.
`restore-dependencies`
* This command can be used if custom nodes are installed under the `ComfyUI/custom_nodes` path but their dependencies are not installed.
* It is useful when starting a new cloud instance, like Colab, where dependencies need to be reinstalled and installation scripts re-executed.
* It is useful when starting a new cloud instance, like colab, where dependencies need to be reinstalled and installation scripts re-executed.
* It can also be utilized if ComfyUI is reinstalled and only the custom_nodes path has been backed up and restored.
### 7. Clear
In the GUI, installations, updates, or snapshot restorations are scheduled to execute the next time ComfyUI is launched. The `clear` command clears this scheduled state, ensuring no pre-execution actions are applied.
In the GUI, installations, updates, or snapshot restorations are scheduled to execute the next time ComfyUI is launched. The `clear` command clears this scheduled state, ensuring no pre-execution actions are applied.
@@ -1,251 +0,0 @@
# ComfyUI-Manager V3.38: Userdata Security Migration Guide
## Introduction
ComfyUI-Manager V3.38 introduces a **security patch** that migrates Manager's configuration and data to a protected system path. This change leverages ComfyUI's new System User Protection API (PR #10966) to provide enhanced security isolation.
This guide explains what happens during the migration and how to handle various situations.
---
## What Changed
### Finding Your Paths
When ComfyUI starts, it displays the full paths in the terminal:
```
** User directory: /path/to/ComfyUI/user
** ComfyUI-Manager config path: /path/to/ComfyUI/user/__manager/config.ini
```
Look for these lines in your startup log to find the exact location on your system. In this guide, paths are shown relative to the `user` directory.
### Path Migration
| Data | Legacy Path | New Path |
|------|-------------|----------|
| Configuration | `user/default/ComfyUI-Manager/` | `user/__manager/` |
| Snapshots | `user/default/ComfyUI-Manager/snapshots/` | `user/__manager/snapshots/` |
### Why This Change
In older ComfyUI versions, the `default/` directory was **unprotected** and accessible via web APIs. If you ran ComfyUI with `--listen 0.0.0.0` or similar options to allow external connections, this data **may have been tampered with** by malicious actors.
**Note:** If you only used ComfyUI locally (without `--listen` or with `--listen 127.0.0.1`), your data was not exposed to this vulnerability.
The new `__manager` path uses ComfyUI's protected system directory, which:
- **Cannot be accessed** from outside (protected by ComfyUI)
- Isolates system settings from user data
- Enables stricter security for remote access
**This is why only `config.ini` is automatically migrated** - other files (snapshots) may have been compromised and should be manually verified before copying.
---
## Automatic Migration
When you start ComfyUI with the new System User Protection API, Manager automatically handles the migration:
### Step 1: Configuration Migration
Only `config.ini` is migrated automatically, and of it only the settings that are preferences.
Settings that permit an install (`allow_git_url_install`, `allow_pip_install`, `allow_flagged_nodepack_install`) or change where Manager fetches from (`channel_url`, `http_channel_enabled`, `bypass_ssl`, `git_exe`), and settings that Manager does not know, are **not** migrated: the old `config.ini` was not protected, so they may have been changed without your knowledge. They are back at their defaults after the migration, and the terminal lists those that had another value than the default:
```
======================================================================
[ComfyUI-Manager] WARNING: Settings not migrated
- ['allow_git_url_install', 'channel_url']
- The legacy config.ini was not protected, so these are back at their defaults.
- Set them again in /path/to/ComfyUI/user/__manager/config.ini if you need them.
======================================================================
```
**Important**: Snapshots are **NOT** automatically migrated. You must copy them manually if needed.
### Step 2: Security Level Check
During migration, if your security level is below `normal` (i.e., `weak` or `normal-`), it will be automatically raised to `normal`. This is a safety measure because the security level setting itself may have been tampered with in the old version.
```
======================================================================
[ComfyUI-Manager] WARNING: Security level adjusted
- Previous: 'weak' → New: 'normal'
- Raised to prevent unauthorized remote access.
======================================================================
```
If you need a lower security level, you can manually edit the config after migration.
A security level that is not one of `strong`, `normal`, `normal-` and `weak` is set to `normal` as well. Only that setting changes.
### Step 3: Legacy Backup
Your entire legacy directory is moved to a backup location:
```
user/__manager/.legacy-manager-backup/
```
This backup is preserved until you manually delete it. If a backup is already there, it is kept, and the new one is named `.legacy-manager-backup-2`, `-3`, and so on.
### Requirements of ComfyUI
Before these steps, the start that finds the legacy `config.ini` installs the requirements of ComfyUI, before the node packs are loaded. On an old ComfyUI the update of ComfyUI could only reserve that install on Windows or with `always_lazy_install`, in the legacy directory, which is not read anymore.
If the updated ComfyUI does not start because one of its requirements is missing, it does not get as far as Manager. Install them yourself, with the Python that runs ComfyUI: `python -m pip install -r requirements.txt` in the ComfyUI directory.
---
## Persistent Backup Notification
As long as the backup exists, Manager will remind you on **every startup**:
```
----------------------------------------------------------------------
[ComfyUI-Manager] NOTICE: Legacy backup exists
- Your old Manager data was backed up to:
/path/to/ComfyUI/user/__manager/.legacy-manager-backup
- Please verify and remove it when no longer needed.
----------------------------------------------------------------------
```
**To stop this notification**: Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it. If there are numbered ones (`.legacy-manager-backup-2`, ...), the notification lists them as well and stops when all are deleted.
---
## Recovering Old Data
### Snapshots
If you need your old snapshots, copy the contents of `.legacy-manager-backup/snapshots/` to `user/__manager/snapshots/`.
---
## Outdated ComfyUI Warning
If you're running an older version of ComfyUI without the System User Protection API, Manager will:
1. **Block all installations** - They are refused at every `security_level`. The `security_level` of `config.ini` is not changed
2. **Serve only the update of ComfyUI** - Every other request to Manager is answered with `comfyui_outdated` (HTTP 403), and files in Manager's data directory that schedule a restore or direct pip (`restore-snapshot.json`, `pip_auto_fix.list`, `pip_overrides.json`) are not acted on
3. **Display warning message**:
```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
[ComfyUI-Manager] ERROR: ComfyUI version is outdated!
- Every operation but the update of ComfyUI is blocked for security.
- ComfyUI update is still allowed.
- Please update ComfyUI to use Manager normally.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
```
**Solution**: Update ComfyUI to v0.3.76 or later.
---
## Security Levels
| Level | What's Allowed |
|-------|----------------|
| `strong` | ComfyUI update only. All other installations blocked. |
| `normal` | Install/update/remove registered custom nodes and models. |
| `normal-` | Above + Install via Git URL or pip (localhost only). |
| `weak` | All operations allowed, including from remote connections. |
**Notes:**
- On outdated ComfyUI versions all installations are blocked at every level.
- `normal` is the default and recommended for most users.
- `normal-` is for developers who need to install unregistered nodes locally.
- `weak` should only be used in isolated development environments.
### Changing Security Level
Edit `user/__manager/config.ini`:
```ini
[default]
security_level = normal
```
---
## Error Messages
### "comfyui_outdated" (HTTP 403)
This error appears when:
- Your ComfyUI doesn't have the System User Protection API
- Everything but the update of ComfyUI is blocked until you update ComfyUI
**Solution**: Update ComfyUI to the latest version.
### "security_level" (HTTP 403)
This error appears when:
- Your security level blocks the requested operation
- For example, `strong` level blocks all installations
**Solution**: Lower your security level in config.ini if appropriate for your use case.
---
## Security Warning: Suspicious Path
If you see this error on an **older** ComfyUI:
```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
[ComfyUI-Manager] ERROR: Suspicious path detected!
- '__manager' exists with low security level: 'weak'
- Please verify manually:
/path/to/ComfyUI/user/__manager/config.ini
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
```
On older ComfyUI versions, the `__manager` directory is not normally created. If this directory exists, it may have been created externally. For safety, manually verify the contents of this directory before updating ComfyUI.
---
## Troubleshooting
### All my installations are blocked
**Check 1**: Is your ComfyUI updated?
- Old ComfyUI blocks all installations at every `security_level`
- Update ComfyUI to resolve
**Check 2**: What's your security level?
- Check `user/__manager/config.ini`
- `security_level = strong` blocks all installations
- Manager 3.43 and earlier wrote `security_level = strong` into a `config.ini` that it created on an old ComfyUI. If you did not choose it, set it to `normal`
### My snapshots are missing
Snapshots are not automatically migrated. You need to manually copy the `snapshots` folder from inside `.legacy-manager-backup` to the `user/__manager/` directory.
### I keep seeing the backup notification
Delete the `.legacy-manager-backup` folder inside `user/__manager/`, and any numbered one (`.legacy-manager-backup-2`, ...), after confirming you don't need any data from it.
### Snapshot restore is blocked
On old ComfyUI (without System User API), snapshot restore is blocked, as is everything but the update of ComfyUI. A restore that is already scheduled is not run at the start either. Update ComfyUI to enable snapshot restore.
---
## File Structure Reference
```
user/
└── __manager/
├── config.ini # Manager configuration
├── channels.list # Custom node channels
├── snapshots/ # Environment snapshots
└── .legacy-manager-backup/ # Backup of old Manager data (temporary)
```
---
## Requirements
- **ComfyUI**: v0.3.76 or later (with System User Protection API)
- **ComfyUI-Manager**: V3.38 or later
+14 -14
View File
@@ -23,13 +23,13 @@ OPTIONS:
## How To Use?
* `python cm-cli.py` 를 통해서 실행 시킬 수 있습니다.
* 예를 들어 custom node를 모두 업데이트 하고 싶다면
* ComfyUI-Manager 경로에서 `python cm-cli.py update all` 명령을 실행할 수 있습니다.
* ComfyUI-Manager경로 에서 `python cm-cli.py update all` 를 command를 실행할 수 있습니다.
* ComfyUI 경로에서 실행한다면, `python custom_nodes/ComfyUI-Manager/cm-cli.py update all` 와 같이 cm-cli.py 의 경로를 지정할 수도 있습니다.
## Prerequisite
* ComfyUI 를 실행하는 python과 동일한 python 환경에서 실행해야 합니다.
* venv를 사용할 경우 해당 venv를 activate 한 상태에서 실행해야 합니다.
* portable 버전을 사용할 경우 run_nvidia_gpu.bat 파일이 있는 경로인 경우, 다음과 같은 방식으로 명령을 실행해야 합니다.
* portable 버전을 사용할 경우 run_nvidia_gpu.bat 파일이 있는 경로인 경우, 다음과 같은 방식으로 코맨드를 실행해야 합니다.
`.\python_embeded\python.exe ComfyUI\custom_nodes\ComfyUI-Manager\cm-cli.py update all`
* ComfyUI 의 경로는 COMFYUI_PATH 환경 변수로 설정할 수 있습니다. 만약 생략할 경우 다음과 같은 경고 메시지가 나타나며, ComfyUI-Manager가 설치된 경로를 기준으로 상대 경로로 설정됩니다.
```
@@ -40,8 +40,8 @@ OPTIONS:
### 1. --channel, --mode
* 정보 보기 기능과 커스텀 노드 관리 기능의 경우는 --channel과 --mode를 통해 정보 DB를 설정할 수 있습니다.
* 예를 들어 `python cm-cli.py update all --channel recent --mode remote`와 같은 명령을 실행할 경우, 현재 ComfyUI-Manager repo에 내장된 로컬의 정보가 아닌 remote의 최신 정보를 기준으로 동작하며, recent channel에 있는 목록을 대상으로만 동작합니다.
* --channel, --mode 는 `simple-show, show, install, uninstall, update, disable, enable, fix` 명령에서만 사용 가능합니다.
* 예들 들어 `python cm-cli.py update all --channel recent --mode remote`와 같은 command를 실행할 경우, 현재 ComfyUI-Manager repo에 내장된 로컬의 정보가 아닌 remote의 최신 정보를 기준으로 동작하며, recent channel에 있는 목록을 대상으로만 동작합니다.
* --channel, --mode 는 `simple-show, show, install, uninstall, update, disable, enable, fix` command에서만 사용 가능합니다.
### 2. 관리 정보 보기
@@ -51,7 +51,7 @@ OPTIONS:
* `[show|simple-show]` - `show`는 상세하게 정보를 보여주며, `simple-show`는 간단하게 정보를 보여줍니다.
`python cm-cli.py show installed` 와 같은 명령을 실행하면 설치된 커스텀 노드의 정보를 상세하게 보여줍니다.
`python cm-cli.py show installed` 와 같은 코맨드를 실행하면 설치된 커스텀 노드의 정보를 상세하게 보여줍니다.
```
-= ComfyUI-Manager CLI (V2.24) =-
@@ -67,7 +67,7 @@ FETCH DATA from: https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main
[ DISABLED ] ComfyUI-Loopchain (author: Fannovel16)
```
`python cm-cli.py simple-show installed` 와 같은 명령을 이용해서 설치된 커스텀 노드의 정보를 간단하게 보여줍니다.
`python cm-cli.py simple-show installed` 와 같은 코맨드를 이용해서 설치된 커스텀 노드의 정보를 간단하게 보여줍니다.
```
-= ComfyUI-Manager CLI (V2.24) =-
@@ -89,7 +89,7 @@ ComfyUI-Loopchain
* `installed`: enable, disable 여부와 상관없이 설치된 모든 노드를 보여줍니다
* `not-installed`: 설치되지 않은 커스텀 노드의 목록을 보여줍니다.
* `all`: 모든 커스텀 노드의 목록을 보여줍니다.
* `snapshot`: 현재 설치된 커스텀 노드의 snapshot 정보를 보여줍니다. `show`를 통해서 볼 경우는 json 출력 형태로 보여주며, `simple-show`를 통해서 볼 경우는 간단하게, 커밋 해시와 함께 보여줍니다.
* `snapshot`: 현재 설치된 커스텀 노드의 snapshot 정보를 보여줍니다. `show`롤 통해서 볼 경우는 json 출력 형태로 보여주며, `simple-show`를 통해서 볼 경우는 간단하게, 커밋 해시와 함께 보여줍니다.
* `snapshot-list`: ComfyUI-Manager/snapshots 에 저장된 snapshot 파일의 목록을 보여줍니다.
### 3. 커스텀 노드 관리 하기
@@ -98,7 +98,7 @@ ComfyUI-Loopchain
* `python cm-cli.py install ComfyUI-Impact-Pack ComfyUI-Inspire-Pack ComfyUI_experiments` 와 같이 커스텀 노드의 이름을 나열해서 관리 기능을 적용할 수 있습니다.
* 커스텀 노드의 이름은 `show`를 했을 때 보여주는 이름이며, git repository의 이름입니다.
(추후 nickname을 사용 가능하도록 업데이트할 예정입니다.)
(추후 nickname 을 사용가능하돌고 업데이트 할 예정입니다.)
`[update|disable|enable|fix] all ?[--channel <channel name>] ?[--mode [remote|local|cache]]`
@@ -106,7 +106,7 @@ ComfyUI-Loopchain
* 세부 동작
* `install`: 지정된 커스텀 노드들을 설치합니다
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다. 버전 없이 이름만 지정하면 설치되어 있는 버전으로 재설치합니다.
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
* `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
* `update`: 지정된 커스텀 노드들을 업데이트합니다.
* `disable`: 지정된 커스텀 노드들을 비활성화합니다.
@@ -124,7 +124,7 @@ ComfyUI-Loopchain
* `--pip-non-local-url`: web URL에 등록된 pip 패키지들에 대해서 복구를 수행
* `--pip-local-url`: local 경로를 지정하고 있는 pip 패키지들에 대해서 복구를 수행
* `--user-directory`: 사용자 디렉토리 설정
* `--restore-to`: 복구될 커스텀 노드가 설치될 경로. (이 옵션을 적용할 경우 오직 대상 경로에 설치된 custom nodes만 설치된 것으로 인식함.)
* `--restore-to`: 복구될 커스텀 노드가 설치될 경로. (이 옵션을 적용할 경우 오직 대상 경로에 설치된 custom nodes 만 설치된 것으로 인식함.)
### 5. CLI only mode
@@ -133,7 +133,7 @@ ComfyUI-Manager를 CLI로만 사용할 것인지를 설정할 수 있습니다.
`cli-only-mode [enable|disable]`
* security 혹은 policy 의 이유로 GUI 를 통한 ComfyUI-Manager 사용을 제한하고 싶은 경우 이 모드를 사용할 수 있습니다.
* CLI only mode를 적용할 경우 ComfyUI-Manager 가 매우 제한된 상태로 로드되어, 내부적으로 제공하는 web API가 비활성화되며, 메인 메뉴에서도 Manager 버튼이 표시되지 않습니다.
* CLI only mode를 적용할 경우 ComfyUI-Manager 가 매우 제한된 상태로 로드되어, 내부적으로 제공하는 web API가 비활성화 되며, 메인 메뉴에서도 Manager 버튼이 표시되지 않습니다.
### 6. 의존성 설치
@@ -141,10 +141,10 @@ ComfyUI-Manager를 CLI로만 사용할 것인지를 설정할 수 있습니다.
`restore-dependencies`
* `ComfyUI/custom_nodes` 하위 경로에 커스텀 노드들이 설치되어 있긴 하지만, 의존성이 설치되지 않은 경우 사용할 수 있습니다.
* Colab과 같이 cloud instance를 새로 시작하는 경우 의존성 재설치 및 설치 스크립트가 재실행되어야 하는 경우 사용합니다.
* ComfyUI를 재설치할 경우, custom_nodes 경로만 백업했다가 재설치할 경우 활용 가능합니다.
* colab 과 같이 cloud instance를 새로 시작하는 경우 의존성 재설치 및 설치 스크립트가 재실행 되어야 하는 경우 사용합니다.
* ComfyUI을 재설치할 경우, custom_nodes 경로만 백업했다가 재설치 할 경우 활용 가능합니다.
### 7. clear
GUI에서 install, update를 하거나 snapshot을 restore하는 경우 예약을 통해서 다음번 ComfyUI를 실행할 경우 실행되는 구조입니다. `clear` 는 이런 예약 상태를 clear해서, 아무런 사전 실행이 적용되지 않도록 합니다.
GUI에서 install, update를 하거나 snapshot 을 restore하는 경우 예약을 통해서 다음번 ComfyUI를 실행할 경우 실행되는 구조입니다. `clear` 는 이런 예약 상태를 clear해서, 아무런 사전 실행이 적용되지 않도록 합니다.
+2953 -59792
View File
File diff suppressed because it is too large Load Diff
+11 -25
View File
@@ -2,7 +2,6 @@ import subprocess
import sys
import os
import traceback
import time
import git
import json
@@ -13,6 +12,7 @@ from git.remote import RemoteProgress
comfy_path = os.environ.get('COMFYUI_PATH')
git_exe_path = os.environ.get('GIT_EXE_PATH')
if comfy_path is None:
print("\nWARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.", file=sys.stderr)
@@ -180,14 +180,6 @@ def switch_to_default_branch(repo):
return False
def undo_pull(repo, commit):
repo.git.reset('--hard', commit)
try:
repo.git.submodule('update', '--recursive')
except Exception:
pass
def gitpull(path):
# Check if the path is a git repository
if not os.path.exists(os.path.join(path, '.git')):
@@ -227,22 +219,9 @@ def gitpull(path):
repo.close()
return
tip_before_pull = repo.head.commit.hexsha
try:
repo.git.pull('--ff-only')
except git.GitCommandError:
backup_name = f'backup_{time.strftime("%Y%m%d_%H%M%S")}'
repo.create_head(backup_name)
print(f"[ComfyUI-Manager] Cannot fast-forward. Backup created: {backup_name}")
repo.git.reset('--hard', f'{remote_name}/{branch_name}')
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
try:
repo.git.submodule('update', '--init', '--recursive')
except Exception:
undo_pull(repo, tip_before_pull)
raise
remote.pull()
repo.git.submodule('update', '--init', '--recursive')
new_commit_hash = repo.head.commit.hexsha
if commit_hash != new_commit_hash:
@@ -252,7 +231,6 @@ def gitpull(path):
except Exception as e:
print(e)
print("CUSTOM NODE PULL: Fail") # unknown git error
sys.exit(1)
repo.close()
@@ -506,6 +484,14 @@ def restore_pip_snapshot(pips, options):
print(f"Installation failed for pip packages: {failed}")
def setup_environment():
if git_exe_path is not None:
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe_path)
setup_environment()
try:
if sys.argv[1] == "--clone":
repo_path = None
+4917 -24667
View File
File diff suppressed because it is too large Load Diff
-53
View File
@@ -1,53 +0,0 @@
# ComfyUI-Manager: Core Backend (glob)
This directory contains the Python backend modules that power ComfyUI-Manager, handling the core functionality of node management, downloading, security, and server operations.
## Core Modules
- **manager_core.py**: The central implementation of management functions, handling configuration, installation, updates, and node management.
- **manager_server.py**: Implements server functionality and API endpoints for the web interface to interact with the backend.
- **manager_downloader.py**: Handles downloading operations for models, extensions, and other resources.
- **manager_util.py**: Provides utility functions used throughout the system.
## Specialized Modules
- **cm_global.py**: Maintains global variables and state management across the system.
- **cnr_utils.py**: Helper utilities for interacting with the custom node registry (CNR).
- **git_utils.py**: Git-specific utilities for repository operations.
- **node_package.py**: Handles the packaging and installation of node extensions.
- **security_check.py**: Implements the multi-level security system for installation safety.
- **share_3rdparty.py**: Manages integration with third-party sharing platforms.
## Architecture
The backend follows a modular design pattern with clear separation of concerns:
1. **Core Layer**: Manager modules provide the primary API and business logic
2. **Utility Layer**: Helper modules provide specialized functionality
3. **Integration Layer**: Modules that connect to external systems
## Security Model
The system implements a comprehensive security framework with multiple levels:
- **Block**: Highest security - blocks most remote operations
- **High**: Allows only specific trusted operations
- **Middle**: Standard security for most users
- **Normal-**: More permissive for advanced users
- **Weak**: Lowest security for development environments
## Implementation Details
- The backend is designed to work seamlessly with ComfyUI
- Asynchronous task queuing is implemented for background operations
- The system supports multiple installation modes
- Error handling and risk assessment are integrated throughout the codebase
## API Integration
The backend exposes a REST API via `manager_server.py` that enables:
- Custom node management (install, update, disable, remove)
- Model downloading and organization
- System configuration
- Snapshot management
- Workflow component handling
+6 -16
View File
@@ -68,6 +68,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
else:
form_factor = 'other'
print(f"form_factor: {form_factor}")
while remained:
# Add comfyui_version and form_factor to the API request
sub_uri = f'{base_url}/nodes?page={page}&limit=30&comfyui_version={comfyui_ver}&form_factor={form_factor}'
@@ -77,8 +78,8 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
for x in sub_json_obj['nodes']:
full_nodes[x['id']] = x
# if page % 5 == 0:
# print(f"FETCH ComfyRegistry Data: {page}/{sub_json_obj['totalPages']}")
if page % 5 == 0:
print(f"FETCH ComfyRegistry Data: {page}/{sub_json_obj['totalPages']}")
page += 1
time.sleep(0.5)
@@ -129,7 +130,6 @@ class NodeVersion:
id: str
version: str
download_url: str
status: str = ''
def map_node_version(api_node_version):
@@ -161,7 +161,6 @@ 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', ''),
)
@@ -181,8 +180,9 @@ def install_node(node_id, version=None):
else:
url = f"{base_url}/nodes/{node_id}/install?version={version}"
response = requests.get(url, verify=not manager_util.bypass_ssl)
response = requests.get(url)
if response.status_code == 200:
# Convert the API response to a NodeVersion object
return map_node_version(response.json())
else:
return None
@@ -191,7 +191,7 @@ def install_node(node_id, version=None):
def all_versions_of_node(node_id):
url = f"{base_url}/nodes/{node_id}/versions?statuses=NodeVersionStatusActive&statuses=NodeVersionStatusPending"
response = requests.get(url, verify=not manager_util.bypass_ssl)
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
@@ -211,7 +211,6 @@ def read_cnr_info(fullpath):
project = data.get('project', {})
name = project.get('name').strip().lower()
original_name = project.get('name')
# normalize version
# for example: 2.5 -> 2.5.0
@@ -223,7 +222,6 @@ def read_cnr_info(fullpath):
if name and version: # repository is optional
return {
"id": name,
"original_name": original_name,
"version": version,
"url": repository
}
@@ -233,14 +231,6 @@ def read_cnr_info(fullpath):
return None # not valid CNR node pack
def read_project_name(fullpath):
try:
with open(os.path.join(fullpath, 'pyproject.toml'), "r", encoding="utf-8") as f:
return toml.load(f)['project']['name'].strip()
except Exception:
return None
def generate_cnr_id(fullpath, cnr_id):
cnr_id_path = os.path.join(fullpath, '.git', '.cnr-id')
try:
+17 -108
View File
@@ -1,6 +1,5 @@
import os
import configparser
import logging
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
@@ -13,113 +12,25 @@ def is_git_repo(path: str) -> bool:
return os.path.exists(os.path.join(path, '.git'))
def file_name_of_git_for_windows(name):
"""The name that Git for Windows gives the file of a ref, whose name is `name` in bytes.
A name that is not UTF-8 is no name of a file there: a byte that is not of a character becomes
the character of its number, or below 0xa0 its two hex digits, as in `xutftowcsn` of compat/mingw.c of git."""
file_name = ''
at = 0
while at < len(name):
size = 1 if name[at] < 0xc2 else 2 if name[at] < 0xe0 else 3 if name[at] < 0xf0 else 4
try:
file_name += name[at:at + size].decode('utf-8', 'surrogatepass')
at += size
except UnicodeDecodeError:
file_name += chr(name[at]) if name[at] >= 0xa0 else '%02x' % name[at]
at += 1
return file_name
def get_commit_hash(fullpath):
git_dir = os.path.join(fullpath, '.git')
try:
with open(os.path.join(git_dir, 'HEAD'), 'rb') as f:
line = f.readline().strip()
git_head = os.path.join(fullpath, '.git', 'HEAD')
if os.path.exists(git_head):
with open(git_head) as f:
line = f.readline()
if not line.startswith(b"ref:"):
# detached HEAD: the file holds the sha followed by a newline;
# without the strip the pinned hash carries that newline into
# snapshots, and the next restore's checkout of that hash fails
return line.decode('ascii', errors='replace')
ref_name = line[4:].strip()
# put together as git does it, and not with `os.path.join`, for which a name can lead elsewhere
if os.name == 'nt':
ref = git_dir + '/' + file_name_of_git_for_windows(ref_name)
else:
ref = os.fsencode(git_dir) + b'/' + ref_name
# a folder there is no ref, as for git: a branch `feature/x` beside the unborn branch `feature`
if os.path.isfile(ref):
with open(ref, 'rb') as f:
return f.readline().strip().decode('ascii', errors='replace')
# after `git pack-refs` or `git gc` the ref is a line of packed-refs
with open(os.path.join(git_dir, 'packed-refs'), 'rb') as f:
for packed in f:
fields = packed.split()
if len(fields) == 2 and fields[1] == ref_name:
return fields[0].decode('ascii', errors='replace')
except OSError:
pass
if line.startswith("ref: "):
ref = os.path.join(fullpath, '.git', line[5:].strip())
if os.path.exists(ref):
with open(ref) as f2:
return f2.readline().strip()
else:
return "unknown"
else:
return line
return "unknown"
warned_git_configs = set()
def lines_of_git_config(lines):
"""
the lines as git takes them: a `\\` at the end of a line makes the next line more of the same value,
and a line may be indented by any amount
"""
whole, quoted = '', False
for line in lines:
line = line.rstrip('\n')
goes_on = False
i = 0
while i < len(line):
if line[i] == '\\':
goes_on = i == len(line) - 1
i += 1
elif line[i] == '"':
quoted = not quoted
elif line[i] in '#;' and not quoted:
break
i += 1
if goes_on:
whole += line[:-1]
else:
yield (whole + line).lstrip() + '\n'
whole, quoted = '', False
if whole:
yield whole.lstrip() + '\n'
def read_git_config(git_config_path) -> 'configparser.ConfigParser | None':
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
# a url may hold a `%`, git accepts a key without a value, the file may start with a BOM,
# and a value that is not UTF-8 does not make the others unreadable
config = configparser.ConfigParser(strict=False, interpolation=None, allow_no_value=True)
try:
with open(git_config_path, encoding='utf-8-sig', errors='replace') as f:
# the parser would take a line that is indented more as more of the value before it
config.read_file(lines_of_git_config(f))
except (configparser.Error, OSError) as e:
if git_config_path not in warned_git_configs:
warned_git_configs.add(git_config_path)
# the message of a parsing error holds lines of the file, and a url in them can hold a token
reason = e.strerror if isinstance(e, OSError) else type(e).__name__
logging.warning(f"[ComfyUI-Manager] Cannot read '{git_config_path}': {reason}")
return None
return config
def git_url(fullpath):
"""
resolve version of unclassified custom node based on remote url in .git/config
@@ -129,14 +40,12 @@ def git_url(fullpath):
if not os.path.exists(git_config_path):
return None
config = read_git_config(git_config_path)
if config is None:
return None
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
config = configparser.ConfigParser(strict=False)
config.read(git_config_path)
for k, v in config.items():
if k.startswith('remote ') and v.get('url'):
if 'Comfy-Org/ComfyUI-Manager' in v['url']:
return "https://github.com/ltdrdata/ComfyUI-Manager"
if k.startswith('remote ') and 'url' in v:
return v['url']
return None
+805 -1294
View File
File diff suppressed because it is too large Load Diff
+1 -5
View File
@@ -55,11 +55,7 @@ def download_url(model_url: str, model_dir: str, filename: str):
return aria2_download_url(model_url, model_dir, filename)
else:
from torchvision.datasets.utils import download_url as torchvision_download_url
try:
return torchvision_download_url(model_url, model_dir, filename)
except Exception as e:
logging.error(f"[ComfyUI-Manager] Failed to download: {model_url} / {repr(e)}")
raise
return torchvision_download_url(model_url, model_dir, filename)
def aria2_find_task(dir: str, filename: str):
-381
View File
@@ -1,381 +0,0 @@
"""
ComfyUI-Manager migration module.
Handles migration from legacy paths to new __manager path structure.
"""
import os
import configparser
# Startup notices for notice board
startup_notices = [] # List of (message, level) tuples
def add_startup_notice(message, level='warning'):
"""Add a notice to be displayed on Manager notice board.
Args:
message: HTML-formatted message string
level: 'warning', 'error', 'info'
"""
global startup_notices
startup_notices.append((message, level))
# Cache for API check (computed once per session)
_cached_has_system_user_api = None
def has_system_user_api():
"""Check if ComfyUI has the System User Protection API (PR #10966).
Result is cached for performance.
"""
global _cached_has_system_user_api
if _cached_has_system_user_api is None:
try:
import folder_paths
_cached_has_system_user_api = hasattr(folder_paths, 'get_system_user_directory')
except Exception:
_cached_has_system_user_api = False
return _cached_has_system_user_api
def get_manager_path(user_dir):
"""Get the appropriate manager files path based on ComfyUI version.
Returns:
str: manager_files_path
"""
if has_system_user_api():
return os.path.abspath(os.path.join(user_dir, '__manager'))
else:
return os.path.abspath(os.path.join(user_dir, 'default', 'ComfyUI-Manager'))
def run_migration_checks(user_dir, manager_files_path):
"""Run all migration and security checks.
Call this after get_manager_path() to handle:
- Legacy config migration (new ComfyUI)
- Legacy backup notification (every startup)
- Suspicious directory detection (old ComfyUI)
- Outdated ComfyUI warning (old ComfyUI)
"""
if has_system_user_api():
migrated = migrate_legacy_config(user_dir, manager_files_path)
# Only check for legacy backup if migration didn't just happen
# (migration already shows backup location in its message)
if not migrated:
check_legacy_backup(manager_files_path)
else:
check_suspicious_manager(user_dir)
warn_outdated_comfyui()
LEGACY_BACKUP_NAME = '.legacy-manager-backup'
def check_legacy_backup(manager_files_path):
"""Check for legacy backup and notify user to verify and remove it.
This runs on every startup to remind users about pending legacy backup.
"""
if not os.path.isdir(manager_files_path):
return
backup_dirs = [os.path.join(manager_files_path, name) for name in sorted(os.listdir(manager_files_path))
if name.startswith(LEGACY_BACKUP_NAME)]
if not backup_dirs:
return
# Terminal output
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: Legacy backup exists")
print(" - Your old Manager data was backed up to:")
for backup_dir in backup_dirs:
print(f" {backup_dir}")
print(" - Please verify and remove it when no longer needed.")
print("-"*70 + "\n")
# Notice board output
add_startup_notice(
"Legacy ComfyUI-Manager data backup exists. Please verify and remove when no longer needed. See terminal for details.",
level='info'
)
def check_suspicious_manager(user_dir):
"""Check for suspicious __manager directory on old ComfyUI.
On old ComfyUI without System User API, if __manager exists with low security,
warn the user to verify manually.
Returns:
bool: True if suspicious setup detected
"""
if has_system_user_api():
return False # Not suspicious on new ComfyUI
suspicious_path = os.path.abspath(os.path.join(user_dir, '__manager'))
if not os.path.exists(suspicious_path):
return False
config_path = os.path.join(suspicious_path, 'config.ini')
if not os.path.exists(config_path):
return False
config = configparser.ConfigParser(interpolation=None)
config.read(config_path)
sec_level = config.get('default', 'security_level', fallback='normal').lower()
if sec_level in ['weak', 'normal-']:
# Terminal output
print("\n" + "!"*70)
print("[ComfyUI-Manager] ERROR: Suspicious path detected!")
print(f" - '__manager' exists with low security level: '{sec_level}'")
print(" - Please verify manually:")
print(f" {config_path}")
print("!"*70 + "\n")
# Notice board output
add_startup_notice(
"[Security Alert] Suspicious path detected. See terminal log for details.",
level='error'
)
return True
return False
def warn_outdated_comfyui():
"""Warn user about outdated ComfyUI without System User API."""
if has_system_user_api():
return
# Terminal output
print("\n" + "!"*70)
print("[ComfyUI-Manager] ERROR: ComfyUI version is outdated!")
print(" - Every operation but the update of ComfyUI is blocked for security.")
print(" - ComfyUI update is still allowed.")
print(" - Please update ComfyUI to use Manager normally.")
print("!"*70 + "\n")
# Notice board output
add_startup_notice(
"[Security Alert] ComfyUI outdated. Everything but its update is blocked.<BR>"
"Update ComfyUI for normal operation.",
level='error'
)
def migrate_legacy_config(user_dir, manager_files_path):
"""Migrate ONLY config.ini to new __manager path if needed.
IMPORTANT: Only config.ini is migrated. Other files (snapshots, cache, etc.)
are NOT migrated - users must recreate them.
Scenarios:
1. Legacy exists, New doesn't exist → Migrate config.ini
2. Legacy exists, New exists → First update after upgrade
- Rename legacy to .backup
3. Legacy doesn't exist → No migration needed
Returns:
bool: True if migration was performed
"""
if not has_system_user_api():
return False
legacy_dir = os.path.join(user_dir, 'default', 'ComfyUI-Manager')
legacy_config = os.path.join(legacy_dir, 'config.ini')
new_config = os.path.join(manager_files_path, 'config.ini')
if not os.path.exists(legacy_dir):
return False # No legacy directory, nothing to migrate
# IMPORTANT: Check for config.ini existence, not just directory
# (because makedirs() creates __manager before this function is called)
# Case: Both configs exist (first update after ComfyUI upgrade)
# This means user ran new ComfyUI at least once, creating __manager/config.ini
if os.path.exists(legacy_config) and os.path.exists(new_config):
_handle_first_update_migration(user_dir, legacy_dir, manager_files_path)
return True
# Case: Legacy config exists but new config doesn't (normal migration)
# This is the first run after ComfyUI upgrade
if os.path.exists(legacy_config) and not os.path.exists(new_config):
pass # Continue with normal migration below
else:
return False
# Terminal output
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: Legacy config.ini detected")
print(f" - Old: {legacy_config}")
print(f" - New: {new_config}")
print(" - Migrating config.ini only (other files are NOT migrated).")
print(" - Security level below 'normal' will be raised.")
print(" - Settings that permit installs or change the channel are not migrated.")
print("-"*70 + "\n")
_migrate_config_with_security_check(legacy_config, new_config)
# Move legacy directory to backup
_move_legacy_to_backup(legacy_dir, manager_files_path)
return True
def _handle_first_update_migration(user_dir, legacy_dir, manager_files_path):
"""Handle first ComfyUI update when both legacy and new directories exist.
This scenario happens when:
- User was on old ComfyUI (using default/ComfyUI-Manager)
- ComfyUI was updated (now has System User API)
- Manager already created __manager on first new run
- But legacy directory still exists
"""
# Terminal output
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: First update after ComfyUI upgrade detected")
print(" - Both legacy and new directories exist.")
print("-"*70 + "\n")
# Move legacy to backup inside __manager
_move_legacy_to_backup(legacy_dir, manager_files_path)
def _move_legacy_to_backup(legacy_dir, manager_files_path):
"""Move legacy directory to backup inside __manager.
Returns:
str: Path to backup directory if successful, None if failed
"""
import shutil
backup_dir = os.path.join(manager_files_path, LEGACY_BACKUP_NAME)
count = 1
while os.path.exists(backup_dir):
count += 1
backup_dir = os.path.join(manager_files_path, f'{LEGACY_BACKUP_NAME}-{count}')
try:
shutil.move(legacy_dir, backup_dir)
# Terminal output (full paths shown here only)
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: Legacy settings migrated")
print(f" - Old location: {legacy_dir}")
print(f" - Backed up to: {backup_dir}")
print(" - Please verify and remove the backup when no longer needed.")
print("-"*70 + "\n")
# Notice board output (no full paths for security)
add_startup_notice(
"Legacy ComfyUI-Manager data migrated. See terminal for details.",
level='info'
)
return backup_dir
except Exception as e:
copy_failed = isinstance(e, shutil.Error)
if copy_failed:
shutil.rmtree(backup_dir, ignore_errors=True)
print(f"[ComfyUI-Manager] WARNING: Failed to backup legacy directory: {str(e)!r}")
add_startup_notice(
"[MIGRATION] Failed to backup legacy directory. See terminal for details.",
level='warning'
)
return None
# The settings that are carried over from config.ini of the legacy path. That file could be written
# through ComfyUI's /userdata, so a setting that permits an install or changes where Manager
# fetches from, and one that is not known here, is left behind.
MIGRATED_SETTINGS = {
'security_level', 'network_mode', 'db_mode', 'preview_method', 'share_option', 'component_policy',
'update_policy', 'use_uv', 'file_logging', 'always_lazy_install', 'default_cache_as_channel_url',
'model_download_by_agent', 'downgrade_blacklist', 'windows_selector_event_loop_policy',
}
VALUES_WRITTEN_BY_DEFAULT = {'false', '', 'https://raw.githubusercontent.com/ltdrdata/comfyui-manager/main'}
def _migrate_config_with_security_check(legacy_path, new_path):
legacy = configparser.ConfigParser(interpolation=None)
try:
legacy.read(legacy_path)
except Exception as e:
print(f"[ComfyUI-Manager] WARNING: Failed to parse config.ini: {e}")
print(" - Creating fresh config with default settings.")
add_startup_notice(
"[MIGRATION] Failed to parse legacy config. Using defaults.",
level='warning'
)
return # Skip migration, let Manager create fresh config
config = configparser.ConfigParser(interpolation=None)
if 'default' in legacy:
settings = dict(legacy.items('default'))
config['default'] = {key: value for key, value in settings.items() if key in MIGRATED_SETTINGS}
not_migrated = sorted(key for key, value in settings.items()
if key not in MIGRATED_SETTINGS and value.lower() not in VALUES_WRITTEN_BY_DEFAULT)
if not_migrated:
print("\n" + "="*70)
print("[ComfyUI-Manager] WARNING: Settings not migrated")
print(f" - {not_migrated!r}")
print(" - The legacy config.ini was not protected, so these are back at their defaults.")
print(f" - Set them again in {new_path} if you need them.")
print("="*70 + "\n")
add_startup_notice(
f"[MIGRATION] Settings of the legacy config.ini that were not migrated: {len(not_migrated)}.<BR>"
"That file was not protected, so they are back at their defaults. See terminal for details.",
level='warning'
)
# Security level hierarchy: strong > normal > normal- > weak
# Default is 'normal', only raise if below default
if 'default' in config:
current_level = config['default'].get('security_level', 'normal').lower()
below_default_levels = ['weak', 'normal-']
if current_level in below_default_levels:
config['default']['security_level'] = 'normal'
# Terminal output
print("\n" + "="*70)
print("[ComfyUI-Manager] WARNING: Security level adjusted")
print(f" - Previous: '{current_level}' → New: 'normal'")
print(" - Raised to prevent unauthorized remote access.")
print("="*70 + "\n")
# Notice board output
add_startup_notice(
f"[MIGRATION] Security level raised: '{current_level}' → 'normal'.<BR>"
"To prevent unauthorized remote access.",
level='warning'
)
elif current_level not in ('strong', 'normal'):
config['default']['security_level'] = 'normal'
print("\n" + "="*70)
print("[ComfyUI-Manager] WARNING: Security level adjusted")
print(f" - Previous: {current_level!r} is not a security level → New: 'normal'")
print("="*70 + "\n")
add_startup_notice(
"[MIGRATION] The security level of the legacy config.ini was not a security level.<BR>"
"It is back at 'normal'. See terminal for details.",
level='warning'
)
else:
print(f" - Security level: {current_level!r} (no change needed)")
# Ensure directory exists
os.makedirs(os.path.dirname(new_path), exist_ok=True)
with open(new_path, 'w') as f:
config.write(f)
+262 -702
View File
File diff suppressed because it is too large Load Diff
+94 -1355
View File
File diff suppressed because it is too large Load Diff
+3 -29
View File
@@ -6,27 +6,6 @@ import os
from git_utils import get_commit_hash
IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
def is_link(path: str) -> bool:
"""
A junction is told by the reparse tag that os.lstat reads on every Python; os.path.isjunction is new in 3.12.
"""
try:
return os.path.islink(path) or getattr(os.lstat(path), 'st_reparse_tag', 0) == IO_REPARSE_TAG_MOUNT_POINT
except OSError:
return False
@dataclass(frozen=True)
class InvalidInstallation:
fullpath: str
unknown_key: str
project_name: str | None
enabled: bool
@dataclass
class InstalledNodePackage:
"""Information about an installed node package."""
@@ -59,16 +38,11 @@ class InstalledNodePackage:
def get_commit_hash(self) -> str:
return get_commit_hash(self.fullpath)
def is_exempt_from_installation_check(self) -> bool:
name = os.path.basename(self.fullpath)
return ('comfyui-manager' in self.id.lower() or is_link(self.fullpath)
or name.startswith('.') or name in ('__MACOSX', '__pycache__'))
def isValid(self) -> bool:
if self.is_exempt_from_installation_check():
return True
if self.is_from_cnr:
return os.path.exists(os.path.join(self.fullpath, '.tracking'))
return os.path.exists(os.path.join(self.fullpath, '.git')) or os.path.exists(os.path.join(self.fullpath, '.tracking'))
return True
@staticmethod
def from_fullpath(fullpath: str, resolve_from_path) -> InstalledNodePackage:
+16 -69
View File
@@ -2,8 +2,6 @@ import sys
import subprocess
import os
import manager_util
def security_check():
print("[START] Security scan")
@@ -53,40 +51,6 @@ And kill and remove /tmp/ultralytics_runner
The version 8.3.41 to 8.3.42 of the Ultralytics package you installed is compromised. Please uninstall that version and reinstall the latest version.
https://blog.comfy.org/comfyui-statement-on-the-ultralytics-crypto-miner-situation/
""",
"litellm==1.82.7": f"""
Execute following commands:
{sys.executable} -m pip uninstall litellm
The litellm PyPI package versions 1.82.7 and 1.82.8 were compromised via a supply chain attack.
Malicious code harvests SSH keys, environment variables, API keys, cloud credentials, and exfiltrates them to an attacker-controlled server.
Version 1.82.8 also installs a .pth file that executes malware on ANY Python startup, even without importing litellm.
1. Uninstall litellm immediately.
2. Assume all credentials accessible to the litellm environment are compromised.
3. Rotate all API keys, cloud credentials, SSH keys, and database passwords.
4. Check site-packages for unexpected .pth files (e.g. litellm_init.pth) and remove them.
5. Run a full malware scan.
Details: https://github.com/BerriAI/litellm/issues/24518
Advisory: PYSEC-2026-2
""",
"litellm==1.82.8": f"""
Execute following commands:
{sys.executable} -m pip uninstall litellm
The litellm PyPI package versions 1.82.7 and 1.82.8 were compromised via a supply chain attack.
Malicious code harvests SSH keys, environment variables, API keys, cloud credentials, and exfiltrates them to an attacker-controlled server.
Version 1.82.8 also installs a .pth file that executes malware on ANY Python startup, even without importing litellm.
1. Uninstall litellm immediately.
2. Assume all credentials accessible to the litellm environment are compromised.
3. Rotate all API keys, cloud credentials, SSH keys, and database passwords.
4. Check site-packages for unexpected .pth files (e.g. litellm_init.pth) and remove them.
5. Run a full malware scan.
Details: https://github.com/BerriAI/litellm/issues/24518
Advisory: PYSEC-2026-2
"""
}
@@ -94,10 +58,7 @@ Advisory: PYSEC-2026-2
pip_blacklist = {
"AppleBotzz": "ComfyUI_LLMVISION",
"ultralytics==8.3.41": "ultralytics==8.3.41",
"ultralytics==8.3.42": "ultralytics==8.3.42",
"litellm==1.82.7": "litellm==1.82.7",
"litellm==1.82.8": "litellm==1.82.8",
"ultralytics==8.3.41": "ultralytics==8.3.41"
}
file_blacklist = {
@@ -105,23 +66,18 @@ Advisory: PYSEC-2026-2
"lolMiner": [os.path.join(comfyui_path, 'lolMiner')]
}
installed_pips = subprocess.check_output(manager_util.make_pip_cmd(["freeze"]), text=True)
installed_pips = subprocess.check_output([sys.executable, '-m', "pip", "freeze"], text=True)
detected = set()
try:
anthropic_info = subprocess.check_output(manager_util.make_pip_cmd(["show", "anthropic"]), text=True, stderr=subprocess.DEVNULL)
requires_lines = [x for x in anthropic_info.split('\n') if x.startswith("Requires")]
if requires_lines:
anthropic_reqs = requires_lines[0].split(": ", 1)[1]
if "pycrypto" in anthropic_reqs:
location_lines = [x for x in anthropic_info.split('\n') if x.startswith("Location")]
if location_lines:
location = location_lines[0].split(": ", 1)[1]
for fi in os.listdir(location):
if fi.startswith("anthropic"):
guide["ComfyUI_LLMVISION"] = (f"\n0.Remove {os.path.join(location, fi)}" + guide["ComfyUI_LLMVISION"])
detected.add("ComfyUI_LLMVISION")
anthropic_info = subprocess.check_output([sys.executable, '-m', "pip", "show", "anthropic"], text=True, stderr=subprocess.DEVNULL)
anthropic_reqs = [x for x in anthropic_info.split('\n') if x.startswith("Requires")][0].split(': ')[1]
if "pycrypto" in anthropic_reqs:
location = [x for x in anthropic_info.split('\n') if x.startswith("Location")][0].split(': ')[1]
for fi in os.listdir(location):
if fi.startswith("anthropic"):
guide["ComfyUI_LLMVISION"] = f"\n0.Remove {os.path.join(location, fi)}" + guide["ComfyUI_LLMVISION"]
detected.add("ComfyUI_LLMVISION")
except subprocess.CalledProcessError:
pass
@@ -130,15 +86,10 @@ Advisory: PYSEC-2026-2
print(f"[SECURITY ALERT] custom node '{k}' is dangerous.")
detected.add(v)
installed_pip_set = set(installed_pips.strip().split('\n'))
for k, v in pip_blacklist.items():
if '==' in k:
if k in installed_pip_set:
detected.add(v)
else:
if any(line.split('==')[0] == k for line in installed_pip_set):
detected.add(v)
if k in installed_pips:
detected.add(v)
break
for k, v in file_blacklist.items():
for x in v:
@@ -147,14 +98,10 @@ Advisory: PYSEC-2026-2
break
if len(detected) > 0:
for line in installed_pip_set:
for line in installed_pips.split('\n'):
for k, v in pip_blacklist.items():
if '==' in k:
if line == k:
print(f"[SECURITY ALERT] '{line}' is dangerous.")
else:
if line.split('==')[0] == k:
print(f"[SECURITY ALERT] '{line}' is dangerous.")
if k in line:
print(f"[SECURITY ALERT] '{line}' is dangerous.")
print("\n########################################################################")
print(" Malware has been detected, forcibly terminating ComfyUI execution.")
+257 -116
View File
@@ -2,40 +2,77 @@ import mimetypes
import manager_core as core
import os
from aiohttp import web
import aiohttp
import json
import hashlib
import folder_paths
from server import PromptServer
from manager_server import _reject_non_json_content_type
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
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("/manager/share_option")
async def share_option(request):
return web.Response(text=core.get_config()['share_option'], status=200)
if "value" in request.rel_url.query:
core.get_config()['share_option'] = request.rel_url.query['value']
core.write_config()
else:
return web.Response(text=core.get_config()['share_option'], status=200)
@PromptServer.instance.routes.post("/manager/share_option")
async def set_share_option(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
value = (await request.json())['value']
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
if value not in SHARE_OPTIONS:
return web.Response(status=400, text='Invalid request')
core.get_config()['share_option'] = value
core.write_config()
return web.Response(status=200)
def is_matrix_org(homeserver):
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
def get_openart_auth():
if not os.path.exists(os.path.join(core.manager_files_path, ".openart_key")):
return None
try:
with open(os.path.join(core.manager_files_path, ".openart_key"), "r") as f:
openart_key = f.read().strip()
return openart_key if openart_key else None
except:
return None
def get_matrix_auth():
@@ -45,7 +82,7 @@ def get_matrix_auth():
with open(os.path.join(core.manager_files_path, "matrix_auth"), "r") as f:
matrix_auth = f.read()
homeserver, username, password = matrix_auth.strip().split("\n")
if not is_matrix_org(homeserver) or not username or not password:
if not homeserver or not username or not password:
return None
return {
"homeserver": homeserver,
@@ -56,51 +93,140 @@ def get_matrix_auth():
return None
def get_comfyworkflows_auth():
if not os.path.exists(os.path.join(core.manager_files_path, "comfyworkflows_sharekey")):
return None
try:
with open(os.path.join(core.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
share_key = f.read()
if not share_key.strip():
return None
return share_key
except:
return None
def get_youml_settings():
if not os.path.exists(os.path.join(core.manager_files_path, ".youml")):
return None
try:
with open(os.path.join(core.manager_files_path, ".youml"), "r") as f:
youml_settings = f.read().strip()
return youml_settings if youml_settings else None
except:
return None
def set_youml_settings(settings):
with open(os.path.join(core.manager_files_path, ".youml"), "w") as f:
f.write(settings)
@PromptServer.instance.routes.get("/manager/get_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("/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(core.manager_files_path, ".openart_key"), "w") as f:
f.write(openart_key)
return web.Response(status=200)
@PromptServer.instance.routes.get("/manager/get_matrix_auth")
async def api_get_matrix_auth(request):
# print("Getting stored Matrix credentials...")
matrix_auth = get_matrix_auth()
if not matrix_auth:
return web.Response(status=404)
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
return web.json_response(matrix_auth)
@PromptServer.instance.routes.get("/manager/youml/settings")
async def api_get_youml_settings(request):
youml_settings = get_youml_settings()
if not youml_settings:
return web.Response(status=404)
return web.json_response(json.loads(youml_settings))
@PromptServer.instance.routes.post("/manager/youml/settings")
async def api_set_youml_settings(request):
json_data = await request.json()
set_youml_settings(json.dumps(json_data))
return web.Response(status=200)
@PromptServer.instance.routes.get("/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("/manager/set_esheep_workflow_and_images")
async def set_esheep_workflow_and_images(request):
json_data = await request.json()
with open(os.path.join(core.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("/manager/get_esheep_workflow_and_images")
async def get_esheep_workflow_and_images(request):
with open(os.path.join(core.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))
def set_matrix_auth(json_data):
homeserver = json_data['homeserver']
username = json_data['username']
password = json_data['password']
path = os.path.join(core.manager_files_path, "matrix_auth")
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
try:
os.chmod(path, 0o600)
except OSError:
pass # a file of another owner keeps its mode
f.truncate()
f.write("\n".join(["matrix.org", username, password]))
with open(os.path.join(core.manager_files_path, "matrix_auth"), "w") as f:
f.write("\n".join([homeserver, username, password]))
def set_comfyworkflows_auth(comfyworkflows_sharekey):
with open(os.path.join(core.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("/manager/share")
async def share_art(request):
# get json data
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
matrix_auth = json_data['matrix_auth']
comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
saved = get_matrix_auth()
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
matrix_auth['password'] = saved['password']
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']
@@ -129,20 +255,79 @@ 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" in share_destinations:
comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
@@ -150,42 +335,30 @@ async def share_art(request):
content_type = assetFileType
try:
from nio import AsyncClient, LoginResponse, UploadResponse
from matrix_client.api import MatrixHttpApi
from matrix_client.client import MatrixClient
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
homeserver = 'matrix.org'
if matrix_auth:
homeserver = matrix_auth.get('homeserver', 'matrix.org')
homeserver = homeserver.replace("http://", "https://")
if not homeserver.startswith("https://"):
homeserver = "https://" + homeserver
client = AsyncClient("https://matrix.org", matrix_auth['username'])
# Login
login_resp = await client.login(matrix_auth['password'])
if not isinstance(login_resp, LoginResponse) or not login_resp.access_token:
await client.close()
client = MatrixClient(homeserver)
try:
token = client.login(username=matrix_auth['username'], password=matrix_auth['password'])
if not token:
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
except:
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
set_matrix_auth(matrix_auth)
# Upload asset
matrix = MatrixHttpApi(homeserver, token=token)
with open(asset_filepath, 'rb') as f:
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
asset_data = f.seek(0) or f.read() # get size for info below
if not isinstance(upload_resp, UploadResponse) or not upload_resp.content_uri:
await client.close()
return web.json_response({"error": "Failed to upload asset to Matrix."}, content_type='application/json', status=500)
mxc_url = upload_resp.content_uri
mxc_url = matrix.media_upload(f.read(), content_type, filename=filename)['content_uri']
# Upload workflow JSON
import io
workflow_json_bytes = json.dumps(prompt['workflow']).encode('utf-8')
workflow_io = io.BytesIO(workflow_json_bytes)
upload_workflow_resp, _maybe_keys = await client.upload(workflow_io, content_type='application/json', filename='workflow.json')
workflow_io.seek(0)
if not isinstance(upload_workflow_resp, UploadResponse) or not upload_workflow_resp.content_uri:
await client.close()
return web.json_response({"error": "Failed to upload workflow to Matrix."}, content_type='application/json', status=500)
workflow_json_mxc_url = upload_workflow_resp.content_uri
workflow_json_mxc_url = matrix.media_upload(prompt['workflow'], 'application/json', filename='workflow.json')['content_uri']
# Send text message
text_content = ""
if title:
text_content += f"{title}\n"
@@ -193,50 +366,18 @@ async def share_art(request):
text_content += f"{description}\n"
if credits:
text_content += f"\ncredits: {credits}\n"
await client.room_send(
room_id=comfyui_share_room_id,
message_type="m.room.message",
content={"msgtype": "m.text", "body": text_content}
)
# Send image
await client.room_send(
room_id=comfyui_share_room_id,
message_type="m.room.message",
content={
"msgtype": "m.image",
"body": filename,
"url": mxc_url,
"info": {
"mimetype": content_type,
"size": len(asset_data)
}
}
)
# Send workflow JSON file
await client.room_send(
room_id=comfyui_share_room_id,
message_type="m.room.message",
content={
"msgtype": "m.file",
"body": "workflow.json",
"url": workflow_json_mxc_url,
"info": {
"mimetype": "application/json",
"size": len(workflow_json_bytes)
}
}
)
await client.close()
matrix.send_message(comfyui_share_room_id, text_content)
matrix.send_content(comfyui_share_room_id, mxc_url, filename, 'm.image')
matrix.send_content(comfyui_share_room_id, workflow_json_mxc_url, 'workflow.json', 'm.file')
except:
import traceback
traceback.print_exc()
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
}
-50
View File
@@ -1,50 +0,0 @@
# ComfyUI-Manager: Frontend (js)
This directory contains the JavaScript frontend implementation for ComfyUI-Manager, providing the user interface components that interact with the backend API.
## Core Components
- **comfyui-manager.js**: Main entry point that initializes the manager UI and integrates with ComfyUI.
- **custom-nodes-manager.js**: Implements the UI for browsing, installing, and managing custom nodes.
- **model-manager.js**: Handles the model management interface for downloading and organizing AI models.
- **components-manager.js**: Manages reusable workflow components system.
- **snapshot.js**: Implements the snapshot system for backing up and restoring installations.
- **node-usage-analyzer.js**: Implements the UI for analyzing node usage in workflows.
## Sharing Components
- **comfyui-share-common.js**: Base functionality for workflow sharing features.
- **comfyui-share-youml.js**: Integration with the YouML sharing platform.
## Utility Components
- **cm-api.js**: Client-side API wrapper for communication with the backend.
- **common.js**: Shared utilities and helper functions used across the frontend.
- **node_fixer.js**: Utilities for fixing disconnected links and repairing malformed nodes by recreating them while preserving connections.
- **popover-helper.js**: UI component for popup tooltips and contextual information.
- **turbogrid.esm.js**: Grid component library - https://github.com/cenfun/turbogrid
- **workflow-metadata.js**: Handles workflow metadata parsing, validation and cross-repository compatibility including versioning, dependencies tracking, and resource management.
## Architecture
The frontend follows a modular component-based architecture:
1. **Integration Layer**: Connects with ComfyUI's existing UI system
2. **Manager Components**: Individual functional UI components (node manager, model manager, etc.)
3. **Sharing Components**: Platform-specific sharing implementations
4. **Utility Layer**: Reusable UI components and helpers
## Implementation Details
- The frontend integrates directly with ComfyUI's UI system through `app.js`
- Dialog-based UI for most manager functions to avoid cluttering the main interface
- Asynchronous API calls to handle backend operations without blocking the UI
## Styling
CSS files are included for specific components:
- **custom-nodes-manager.css**: Styling for the node management UI
- **model-manager.css**: Styling for the model management UI
- **node-usage-analyzer.css**: Styling for the node usage analyzer UI
This frontend implementation provides a comprehensive yet user-friendly interface for managing the ComfyUI ecosystem.
+35 -109
View File
@@ -1,134 +1,60 @@
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { sleep, customConfirm, customAlert, handle403Response, show_message, sanitizeHTML, 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 undefined when the pack was enabled, or the reason when it was not.
async function enableNodePack(target) {
const list = await api.fetchApi(`/customnode/getlist?mode=cache&skip_update=true`);
if(list.status != 200) {
return `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 'It is not in the custom node list as a disabled node pack. Please enable it in the Custom Nodes Manager.';
}
const ui_id = md5(key); // the id of this pack's row in the Custom Nodes Manager
const status = await api.fetchApi('/manager/queue/status');
if((await status.json()).is_processing) {
return 'There are already tasks in progress. Please try again after it is completed.';
}
// Once the queue is started its next report ends the wait; it is without the pack when
// something else has emptied the queue.
let listener, started = false;
const result = new Promise((resolve) => {
listener = (event) => {
if(event.detail.status != 'done') {
return;
}
if(ui_id in event.detail.nodepack_result) {
resolve(event.detail.nodepack_result[ui_id]);
}
else if(started) {
resolve('The queue finished without this node pack. Please try again.');
}
};
});
// A node pack from the registry is enabled while the install request is handled, and reported then.
api.addEventListener("cm-queue-status", listener);
try {
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
const response = await api.fetchApi(`/manager/queue/install`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
...node_packs[key],
channel,
mode: 'cache',
ui_id,
skip_post_install: true
})
});
if(response.status == 403) {
return 'This action is not allowed with this security level configuration.';
}
if(response.status != 200) {
return `The request was refused (${response.status}). Please check the terminal log.`;
}
started = true;
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// A report that does not reach the page would leave the listener in place, and a later report
// for the same row, such as its Disable, would then restart ComfyUI unasked.
const message = await Promise.race([result, sleep(60000).then(() =>
'The queue did not report the result. Please check the node pack in the Custom Nodes Manager.')]);
if(message != 'success') {
return String(message);
}
}
finally {
api.removeEventListener("cm-queue-status", listener);
}
}
import { sleep, customConfirm, customAlert } from "./common.js";
async function tryInstallCustomNode(event) {
const target = event.detail.target;
let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
msg += `The '${event.detail.sender}' extension requires the installation of the '${target.title}' extension. `;
msg += `The '${event.detail.sender}' extension requires the installation of the '${event.detail.target.title}' extension. `;
if(target.installed == 'Disabled') {
if(event.detail.target.installed == 'Disabled') {
msg += 'However, the extension is currently disabled. Would you like to enable it and reboot?'
}
else {
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 += `\n\nRequest message:\n${event.detail.msg}`;
// 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') {
if(event.detail.target.installed == 'True') {
customAlert(msg);
return;
}
const res = await customConfirm(msg);
if(res) {
const title = sanitizeHTML(String(target.title));
if(event.detail.target.installed == 'Disabled') {
const response = await api.fetchApi(`/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}'`);
await sleep(300);
app.ui.dialog.show(`Enabling... '${title}'`);
const response = await api.fetchApi(`/customnode/install`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.detail.target)
});
const failure = await enableNodePack(target).catch((exception) => String(exception));
if(failure != undefined) {
show_message(`Failed to enable '${title}'.<BR><BR>${sanitizeHTML(failure)}`);
return false;
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;
}
}
let response;
try {
response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
catch(exception) {
// The server restarts without answering.
}
if(response?.status == 403) {
await handle403Response(response);
let response = await api.fetchApi("/manager/reboot");
if(response.status == 403) {
show_message('This action is not allowed with this security level configuration.');
return false;
}
-82
View File
@@ -1,82 +0,0 @@
.cm-ui-overlay {
z-index: 1000;
background: rgb(0 0 0 / 50%);
}
.cm-ui-dialog {
max-width: calc(100vw - 2rem);
max-height: calc(100vh - 2rem);
border: 1px solid var(--border, var(--border-color));
border-radius: 12px;
background: var(--background, var(--comfy-menu-bg));
color: var(--foreground, var(--fg-color));
box-shadow: var(--shadow-lg, 0 8px 24px rgb(0 0 0 / 30%));
}
.cm-ui-header {
flex-shrink: 0;
padding: 1rem;
}
.cm-ui-content {
padding: 0 1rem 1rem;
overflow: auto;
}
.cm-ui-muted {
color: var(--muted-foreground, var(--fg-color));
}
:where(.cm-ui-button) {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--border, var(--border-color));
border-radius: 6px;
background: var(--secondary, var(--comfy-input-bg));
color: var(--foreground, var(--input-text));
font: inherit;
line-height: 1.25;
cursor: pointer;
}
:where(.cm-ui-input) {
padding: 0.5rem;
border: 1px solid var(--border, var(--border-color));
border-radius: 6px;
background: var(--secondary, var(--comfy-input-bg));
color: var(--foreground, var(--input-text));
font: inherit;
}
.cm-ui-button:not(:disabled):hover {
filter: brightness(115%);
}
.cm-ui-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cm-ui-button:focus-visible,
.cm-ui-input:focus-visible {
outline: 2px solid var(--ring, var(--input-text));
outline-offset: 2px;
}
.cm-ui-close {
width: 2rem;
height: 2rem;
flex-shrink: 0;
padding: 0;
border: 0;
border-radius: 50%;
background: transparent;
color: inherit;
}
.cm-ui-close:not(:disabled):hover {
background: var(--accent, var(--comfy-input-bg));
}
-148
View File
@@ -1,148 +0,0 @@
import { $el } from "../../scripts/ui.js";
import { loadCss } from "./common.js";
loadCss("./comfyui-gui-builder.css");
function normalizeContent(content) {
const tmp = document.createElement('div');
if (typeof content === 'string') {
tmp.innerHTML = content;
return Array.from(tmp.childNodes);
}
if (content instanceof Node) {
return content;
}
return content;
}
export function createSettingsCombo(label, content) {
const settingItem = $el("div.setting-item", {}, [
$el("div.flex.flex-row.items-center.gap-2",[
$el("div.form-label.flex.grow.items-center", [
$el("span.cm-ui-muted", { textContent: label },)
]),
$el("div.form-input.flex.justify-end",
[content]
)
]
)
]);
return settingItem;
}
export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
parent: document.body,
onclick: (e) => {
if (e.target === dialog_mask) {
owner.close();
}
}
});
const header_actions = $el("div.flex.items-center");
$el("button.cm-ui-button.cm-ui-close", {
parent: header_actions,
type: "button",
ariaLabel: "Close",
onclick: () => owner.close(),
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
}
);
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
[
$el("div", [
$el("div",
{
id: "frame-title-container",
},
[
$el("h2.px-4", [
$el(iconClass, {
style: {
"font-size": "1.25rem",
"margin-right": ".5rem"
}
}),
$el("span", { textContent: title })
])
]
)
]),
header_actions
]
);
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
id: dialogId,
parent: dialog_mask,
style: {
'display': 'flex',
'flex-direction': 'column',
'pointer-events': 'auto',
'margin': '0px',
},
role: 'dialog',
ariaModal: 'true',
},
[ dialog_header, contentFrame ]
);
return dialog_mask;
}
export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner) {
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
parent: document.body,
onclick: (e) => {
if (e.target === dialog_mask) {
owner.close();
}
}
});
const header_actions = $el("div.flex.items-center");
$el("button.cm-ui-button.cm-ui-close", {
parent: header_actions,
type: "button",
ariaLabel: "Close",
onclick: () => owner.close(),
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
}
);
const _customHeader = normalizeContent(customHeader);
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
[
$el("div", [
$el("div",
{
id: "frame-title-container",
},
Array.isArray(_customHeader) ? _customHeader : [_customHeader]
)
]),
header_actions
]
);
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
id: dialogId,
parent: dialog_mask,
style: {
'display': 'flex',
'flex-direction': 'column',
'pointer-events': 'auto',
'margin': '0px',
},
role: 'dialog',
ariaModal: 'true',
},
[ dialog_header, contentFrame ]
);
return dialog_mask;
}
+287 -345
View File
File diff suppressed because it is too large Load Diff
+253 -22
View File
@@ -1,6 +1,8 @@
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { $el, ComfyDialog } from "../../scripts/ui.js";
import { CopusShareDialog } from "./comfyui-share-copus.js";
import { OpenArtShareDialog } from "./comfyui-share-openart.js";
import { YouMLShareDialog } from "./comfyui-share-youml.js";
import { customAlert } from "./common.js";
@@ -164,6 +166,61 @@ 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(`/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();
@@ -180,9 +237,9 @@ export const showYouMLShareDialog = () => {
}
export const showShareDialog = async () => {
export const showShareDialog = async (share_option) => {
if (!ShareDialog.instance) {
ShareDialog.instance = new ShareDialog();
ShareDialog.instance = new ShareDialog(share_option);
}
return app.graphToPrompt()
.then(prompt => {
@@ -202,7 +259,7 @@ export const showShareDialog = async () => {
}
return false;
}
ShareDialog.instance.show({ potential_outputs, potential_output_nodes });
ShareDialog.instance.show({ potential_outputs, potential_output_nodes, share_option });
return true;
});
}
@@ -225,6 +282,17 @@ 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",
@@ -234,15 +302,47 @@ 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().then((suc) => {
showShareDialog('matrix').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() {
@@ -257,7 +357,8 @@ export class ShareDialogChooser extends ComfyDialog {
});
buttons.forEach(b => {
const button = $el("button", {
const button = $el("button",
{
type: "button",
textContent: b.textContent,
onclick: b.onclick,
@@ -270,8 +371,14 @@ 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
});
@@ -280,7 +387,7 @@ export class ShareDialogChooser extends ComfyDialog {
});
const description = $el("p", {
textContent: b.description,
innerHTML: b.description,
style: {
'text-align': 'left',
color: 'var(--input-text)',
@@ -289,6 +396,28 @@ 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,
@@ -326,8 +455,17 @@ 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]);
}, [buttonLinkContainer, description
,
b.key ==='Copus' ?
copus_ui
:'',
b.key ==='Copus' ?
copus_ui_bottom
:'',
]);
container.appendChild(column);
});
@@ -380,10 +518,12 @@ export class ShareDialogChooser extends ComfyDialog {
}
export class ShareDialog extends ComfyDialog {
static instance = null;
static matrix_auth = { homeserver: "matrix.org", username: "" };
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
static cw_sharekey = "";
constructor() {
constructor(share_option) {
super();
this.share_option = share_option;
this.element = $el("div.comfy-modal", {
parent: document.body, style: {
'overflow-y': "auto",
@@ -401,13 +541,28 @@ 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;
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", value: "matrix.org", readOnly: true, title: "The share room is on matrix.org; only an account of matrix.org can share." }, []);
this.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" }, []);
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",
@@ -457,6 +612,8 @@ 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 = "";
@@ -464,6 +621,7 @@ 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
@@ -541,6 +699,28 @@ 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: {
@@ -549,6 +729,9 @@ 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", {
@@ -582,6 +765,9 @@ 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,
@@ -598,6 +784,8 @@ 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 = "";
@@ -605,6 +793,7 @@ 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
@@ -620,15 +809,33 @@ export class ShareDialog extends ComfyDialog {
]),
]);
// get the user's existing matrix auth
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
// get the user's existing matrix auth and share key
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
try {
api.fetchApi(`/manager/get_matrix_auth`)
.then(response => response.json())
.then(data => {
ShareDialog.matrix_auth = data;
this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
this.matrix_username_input.value = ShareDialog.matrix_auth.username;
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
this.matrix_password_input.value = ShareDialog.matrix_auth.password;
})
.catch(error => {
// console.log(error);
});
} catch (error) {
// console.log(error);
}
// get the user's existing comfyworkflows share key
ShareDialog.cw_sharekey = "";
try {
// console.log("Fetching comfyworkflows share key")
api.fetchApi(`/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);
@@ -647,17 +854,23 @@ 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")) {
const usesSavedPassword = this.matrix_username_input.value == ShareDialog.matrix_auth.username;
let definedMatrixAuth = !!this.matrix_username_input.value && (!!this.matrix_password_input.value || usesSavedPassword);
let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
if (!definedMatrixAuth) {
customAlert("Please set your Matrix account details.");
return;
}
}
if (destinations.includes("comfyworkflows") && !this.cw_sharekey_input.value && false) { //!confirm("You have NOT set your ComfyWorkflows.com share key. Your art will NOT be connected to your account (it will be shared anonymously). Continue?")) {
return;
}
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
// console.log({ potential_outputs, potential_output_nodes })
@@ -687,10 +900,14 @@ 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,
@@ -719,9 +936,15 @@ export class ShareDialog extends ComfyDialog {
const response_json = await response.json();
if (response_json.matrix.success) {
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
ShareDialog.matrix_auth = { homeserver: this.matrix_homeserver_input.value, username: this.matrix_username_input.value };
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!";
}
}
this.final_message.style.color = "green";
@@ -754,7 +977,7 @@ export class ShareDialog extends ComfyDialog {
return res;
}
show({potential_outputs, potential_output_nodes}) {
show({potential_outputs, potential_output_nodes, share_option}) {
// 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`.
@@ -866,6 +1089,14 @@ export class ShareDialog extends ComfyDialog {
// this.radio_buttons.appendChild(subheader);
this.radio_buttons.appendChild(new_radio_buttons);
this.element.style.display = "block";
this.matrix_destination_checkbox.checked = true;
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;
}
}
}
+985
View File
@@ -0,0 +1,985 @@
import { app } from "../../scripts/app.js";
import { $el, ComfyDialog } from "../../scripts/ui.js";
import { customAlert } from "./common.js";
const env = "prod";
let DEFAULT_HOMEPAGE_URL = "https://copus.io";
let API_ENDPOINT = "https://api.client.prod.copus.io";
if (env !== "prod") {
API_ENDPOINT = "https://api.test.copus.io";
DEFAULT_HOMEPAGE_URL = "https://test.copus.io";
}
const style = `
.copus-share-dialog a {
color: #f8f8f8;
}
.copus-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",
position: "relative",
};
export class CopusShareDialog extends ComfyDialog {
static instance = null;
constructor() {
super();
$el("style", {
textContent: style,
parent: document.head,
});
this.element = $el(
"div.comfy-modal.copus-share-dialog",
{
parent: document.body,
style: {
"overflow-y": "auto",
},
},
[$el("div.comfy-modal-content", {}, [...this.createButtons()])]
);
this.selectedOutputIndex = 0;
this.selectedOutput_lock = 0;
this.selectedNodeId = null;
this.uploadedImages = [];
this.allFilesImages = [];
this.selectedFile = null;
this.allFiles = [];
this.titleNum = 0;
}
createButtons() {
const inputStyle = {
display: "block",
minWidth: "500px",
width: "100%",
padding: "10px",
margin: "10px 0",
borderRadius: "4px",
border: "1px solid #ddd",
boxSizing: "border-box",
};
const textAreaStyle = {
display: "block",
minWidth: "500px",
width: "100%",
padding: "10px",
margin: "10px 0",
borderRadius: "4px",
border: "1px solid #ddd",
boxSizing: "border-box",
minHeight: "100px",
background: "#222",
resize: "vertical",
color: "#f2f2f2",
fontFamily: "Arial",
fontWeight: "400",
fontSize: "15px",
};
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.TitleInput = $el("input", {
type: "text",
placeholder: "Title (Required)",
style: inputStyle,
maxLength: "70",
oninput: () => {
const titleNum = this.TitleInput.value.length;
titleNumDom.textContent = `${titleNum}/70`;
},
});
this.SubTitleInput = $el("input", {
type: "text",
placeholder: "Subtitle (Optional)",
style: inputStyle,
maxLength: "350",
oninput: () => {
const titleNum = this.SubTitleInput.value.length;
subTitleNumDom.textContent = `${titleNum}/350`;
},
});
this.LockInput = $el("input", {
type: "text",
placeholder: "",
style: {
width: "100px",
padding: "7px",
borderRadius: "4px",
border: "1px solid #ddd",
boxSizing: "border-box",
},
oninput: (event) => {
let input = event.target.value;
// Use a regular expression to match a number with up to two decimal places
const regex = /^\d*\.?\d{0,2}$/;
if (!regex.test(input)) {
// If the input doesn't match, remove the last entered character
event.target.value = input.slice(0, -1);
}
const numericValue = parseFloat(input);
if (numericValue > 9999) {
input = "9999";
}
// Update the input field with the valid value
event.target.value = input;
},
});
this.descriptionInput = $el("textarea", {
placeholder: "Content (Optional)",
style: {
...textAreaStyle,
minHeight: "100px",
},
});
// Header Section
const headerSection = $el("h3", {
textContent: "Share your workflow to Copus",
size: 3,
color: "white",
style: {
"text-align": "center",
color: "white",
margin: "0 0 10px 0",
},
});
this.getAPIKeyLink = $el(
"a",
{
style: {
...hyperLinkStyle,
color: "#59E8C6",
},
href: `${DEFAULT_HOMEPAGE_URL}?fromPage=comfyUI`,
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️⃣ Copus 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",
},
[]
);
const titleNumDom = $el(
"label",
{
style: {
fontSize: "12px",
position: "absolute",
right: "10px",
bottom: "-10px",
color: "#999",
},
},
["0/70"]
);
const subTitleNumDom = $el(
"label",
{
style: {
fontSize: "12px",
position: "absolute",
right: "10px",
bottom: "-10px",
color: "#999",
},
},
["0/350"]
);
const descriptionNumDom = $el(
"label",
{
style: {
fontSize: "12px",
position: "absolute",
right: "10px",
bottom: "-10px",
color: "#999",
},
},
["0/70"]
);
// Additional Inputs Section
const additionalInputsSection = $el(
"div",
{ style: { ...sectionStyle, } },
[
$el("label", { style: labelStyle }, ["3️⃣ Title "]),
this.TitleInput,
titleNumDom,
]
);
const SubtitleSection = $el("div", { style: sectionStyle }, [
$el("label", { style: labelStyle }, ["4️⃣ Subtitle "]),
this.SubTitleInput,
subTitleNumDom,
]);
const DescriptionSection = $el("div", { style: sectionStyle }, [
$el("label", { style: labelStyle }, ["5️⃣ Description "]),
this.descriptionInput,
// descriptionNumDom,
]);
// switch between outputs section and additional inputs section
this.radioButtons_lock = [];
this.radioButtonsCheck_lock = $el("input", {
type: "radio",
name: "output_type_lock",
value: "0",
id: "blockchain1_lock",
checked: true,
});
this.radioButtonsCheckOff_lock = $el("input", {
type: "radio",
name: "output_type_lock",
value: "1",
id: "blockchain_lock",
});
const blockChainSection_lock = $el("div", { style: sectionStyle }, [
$el("label", { style: labelStyle }, ["6️⃣ Pay to download"]),
$el(
"label",
{
style: {
marginTop: "10px",
display: "flex",
alignItems: "center",
cursor: "pointer",
},
},
[
this.radioButtonsCheck_lock,
$el("div", { style: { marginLeft: "5px" ,display:'flex',alignItems:'center'} }, [
$el("span", { style: { marginLeft: "5px" } }, ["ON"]),
$el("span", { style: { marginLeft: "20px",marginRight:'10px' ,color:'#fff'} }, ["Price US$"]),
this.LockInput
]),
]
),
$el(
"label",
{ style: { display: "flex", alignItems: "center", cursor: "pointer" } },
[
this.radioButtonsCheckOff_lock,
$el("span", { style: { marginLeft: "5px" } }, ["OFF"]),
]
),
$el(
"p",
{ style: { fontSize: "16px", color: "#fff", margin: "10px 0 0 0" } },
["Get paid from your workflow. You can change the price and withdraw your earnings on Copus."]
),
]);
this.radioButtons = [];
this.radioButtonsCheck = $el("input", {
type: "radio",
name: "output_type",
value: "0",
id: "blockchain1",
checked: true,
});
this.radioButtonsCheckOff = $el("input", {
type: "radio",
name: "output_type",
value: "1",
id: "blockchain",
});
const blockChainSection = $el("div", { style: sectionStyle }, [
$el("label", { style: labelStyle }, ["7️⃣ Store on blockchain "]),
$el(
"label",
{
style: {
marginTop: "10px",
display: "flex",
alignItems: "center",
cursor: "pointer",
},
},
[
this.radioButtonsCheck,
$el("span", { style: { marginLeft: "5px" } }, ["ON"]),
]
),
$el(
"label",
{ style: { display: "flex", alignItems: "center", cursor: "pointer" } },
[
this.radioButtonsCheckOff,
$el("span", { style: { marginLeft: "5px" } }, ["OFF"]),
]
),
$el(
"p",
{ style: { fontSize: "16px", color: "#fff", margin: "10px 0 0 0" } },
["Secure ownership with a permanent & decentralized storage"]
),
]);
// 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,
SubtitleSection,
DescriptionSection,
// contestSection,
blockChainSection_lock,
blockChainSection,
this.message,
buttonsSection,
];
return layout;
}
/**
* api
* @param {url} path
* @param {params} options
* @param {statusText} statusText
* @returns
*/
async fetchApi(path, options, statusText) {
if (statusText) {
this.message.textContent = statusText;
}
const fullPath = new URL(API_ENDPOINT + path);
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,
};
}
/**
* @param {file} uploadFile
*/
async uploadThumbnail(uploadFile, type) {
const form = new FormData();
form.append("file", uploadFile);
form.append("apiToken", this.keyInput.value);
try {
const res = await this.fetchApi(
`/client/common/opus/uploadImage`,
{
method: "POST",
body: form,
},
"Uploading thumbnail..."
);
if (res.status && res.data.status && res.data) {
const { data } = res.data;
if (type) {
this.allFilesImages.push({
url: data,
});
}
this.uploadedImages.push({
url: data,
});
} else {
throw new Error("make sure your API key is correct and try again later");
}
} 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 = "";
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";
}
/**
* share
* @param {string} title
* @param {string} subtitle
* @param {string} content
* @param {boolean} storeOnChain
* @param {string} coverUrl
* @param {string[]} imageUrls
* @param {string} apiToken
*/
async share() {
const prompt = await app.graphToPrompt();
const workflowJSON = prompt["workflow"];
const form_values = {
title: this.TitleInput.value,
subTitle: this.SubTitleInput.value,
content: this.descriptionInput.value,
storeOnChain: this.radioButtonsCheck.checked ? true : false,
lockState:this.radioButtonsCheck_lock.checked ? 2 : 0,
unlockPrice:this.LockInput.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.title) {
throw new Error("Title is required");
}
if(this.radioButtonsCheck_lock.checked){
if (!this.LockInput.value){
throw new Error("Price is required");
}
}
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");
}
}
}
if (this.allFiles.length > 0) {
for (const file of this.allFiles) {
try {
await this.uploadThumbnail(file, true);
} catch (e) {
this.allFilesImages = [];
throw new Error(e.message);
}
}
}
try {
const res = await this.fetchApi(
"/client/common/opus/shareFromComfyUI",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
workflowJson: workflowJSON,
apiToken: this.keyInput.value,
coverUrl: this.uploadedImages[0].url,
imageUrls: this.allFilesImages.map((image) => image.url),
...form_values,
}),
},
"Uploading workflow..."
);
if (res.status && res.data.status && res.data) {
localStorage.setItem("copus_token",this.keyInput.value);
const { data } = res.data;
if (data) {
const url = `${DEFAULT_HOMEPAGE_URL}/work/${data}`;
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.allFilesImages = [];
this.allFiles = [];
this.TitleInput.value = "";
this.SubTitleInput.value = "";
this.descriptionInput.value = "";
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;
const apiToken = localStorage.getItem("copus_token");
this.message.innerHTML = "";
this.message.textContent = "";
this.element.style.display = "block";
this.previewImage.src = "";
this.previewImage.style.display = "none";
this.keyInput.value = apiToken!=null?apiToken:"";
this.uploadedImages = [];
this.allFilesImages = [];
this.allFiles = [];
// 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
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);
let src = "";
if (output.type === "image" || output.type === "temp") {
filename = output.image.filename;
src = `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`;
} else if (output.type === "output") {
src = output.output.value;
filename = output.filename;
}
if (src) {
this.fetchImageBlob(src).then((blob) => {
const file = new File([blob], filename, {
type: blob.type,
});
this.allFiles.push(file);
});
}
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: "white",
margin: "0 0 5px 0",
fontSize: "12px",
},
},
[]
);
this.outputsSection.innerHTML = "";
this.outputsSection.appendChild(header);
this.outputsSection.appendChild(new_radio_buttons);
}
}
+746
View File
@@ -0,0 +1,746 @@
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(`/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(`/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(
`/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(`/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(
"/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);
}
}
+22 -8
View File
@@ -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, safeHref } from "./common.js";
import { customAlert } from "./common.js";
const BASE_URL = "https://youml.com";
//const BASE_URL = "http://localhost:3000";
@@ -176,12 +176,25 @@ export class YouMLShareDialog extends ComfyDialog {
this.selectedFile = null;
}
loadToken() {
return localStorage.getItem("youml_token") || "";
async loadToken() {
let key = ""
try {
const response = await api.fetchApi(`/manager/youml/settings`)
const settings = await response.json()
return settings.token
} catch (error) {
}
return key || "";
}
saveToken(value) {
localStorage.setItem("youml_token", value);
async saveToken(value) {
await api.fetchApi(`/manager/youml/settings`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
token: value
})
});
}
createLayout() {
@@ -329,7 +342,7 @@ export class YouMLShareDialog extends ComfyDialog {
async handleShareButtonClick() {
this.message.textContent = "";
this.saveToken(this.apiTokenInput.value);
await this.saveToken(this.apiTokenInput.value);
try {
this.shareButton.disabled = true;
this.shareButton.textContent = "Sharing...";
@@ -407,7 +420,7 @@ export class YouMLShareDialog extends ComfyDialog {
}
}
this.message.innerHTML = `${messagePrefix} To turn your workflow into an interactive app, ` +
`<a href="${safeHref(recipePageUrl)}" target="_blank" rel="noopener noreferrer">visit it on YouML</a>`;
`<a href="${recipePageUrl}" target="_blank">visit it on YouML</a>`;
this.uploadedImages = [];
this.nameInput.value = "";
@@ -547,7 +560,8 @@ export class YouMLShareDialog extends ComfyDialog {
this.message.innerHTML = "";
this.message.textContent = "";
this.apiTokenInput.value = this.loadToken();
const token = await this.loadToken();
this.apiTokenInput.value = token;
this.uploadedImages = [];
this.element.style.display = "block";
+39 -686
View File
@@ -1,7 +1,6 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { $el, ComfyDialog } from "../../scripts/ui.js";
import { getBestPosition, getPositionStyle, getRect } from './popover-helper.js';
function internalCustomConfirm(message, confirmMessage, cancelMessage) {
@@ -100,19 +99,6 @@ export function show_message(msg) {
app.ui.dialog.element.style.zIndex = 1100;
}
export async function handle403Response(res, defaultMessage) {
try {
const data = await res.json();
if(data.error === 'comfyui_outdated') {
show_message('ComfyUI version is outdated.<BR>Please update ComfyUI to use Manager normally.');
} else {
show_message(defaultMessage || 'This action is not allowed with this security level configuration.');
}
} catch {
show_message(defaultMessage || 'This action is not allowed with this security level configuration.');
}
}
export async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
@@ -122,9 +108,9 @@ export async function customConfirm(message) {
let res = await
window['app'].extensionManager.dialog
.confirm({
title: 'Confirm',
message: message
});
title: 'Confirm',
message: message
});
return res;
}
@@ -164,9 +150,9 @@ export async function customPrompt(title, message) {
let res = await
window['app'].extensionManager.dialog
.prompt({
title: title,
message: message
});
title: title,
message: message
});
return res;
}
@@ -176,22 +162,36 @@ export async function customPrompt(title, message) {
}
export async function rebootAPI() {
export function rebootAPI() {
if ('electronAPI' in window) {
window.electronAPI.restartApp();
return true;
}
const isConfirmed = await customConfirm("Are you sure you'd like to reboot the server?");
if (isConfirmed) {
try {
const response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
if (response.status == 403) {
await handle403Response(response);
return false;
customConfirm("Are you sure you'd like to reboot the server?").then((isConfirmed) => {
if (isConfirmed) {
try {
api.fetchApi("/manager/reboot");
}
catch(exception) {}
}
catch(exception) {}
});
return false;
}
export async function migrateAPI() {
let confirmed = await customConfirm("When performing a migration, existing installed custom nodes will be renamed and the server will be restarted. Are you sure you want to apply this?\n\n(If you don't perform the migration, ComfyUI-Manager's start-up time will be longer each time due to re-checking during startup.)")
if (confirmed) {
try {
await api.fetchApi("/manager/migrate_unmanaged_nodes");
api.fetchApi("/manager/reboot");
}
catch(exception) {
}
return true;
}
return false;
@@ -223,19 +223,16 @@ function isValidURL(url) {
}
export async function install_pip(packages) {
if(packages.includes('&')) {
if(packages.includes('&'))
app.ui.dialog.show(`Invalid PIP package enumeration: '${packages}'`);
return;
}
const res = await api.fetchApi("/customnode/install/pip", {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ packages: packages }),
body: packages,
});
if(res.status == 403) {
await handle403Response(res, "To use this feature you need BOTH: (1) 'allow_pip_install = true' in config.ini ([default] section), AND (2) ComfyUI launched with a loopback --listen (127.0.0.1 or ::1). 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.");
show_message('This action is not allowed with this security level configuration.');
return;
}
@@ -266,12 +263,11 @@ export async function install_via_git_url(url, manager_dialog) {
const res = await api.fetchApi("/customnode/install/git_url", {
method: "POST",
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url }),
body: url,
});
if(res.status == 403) {
await handle403Response(res, "To use this feature you need BOTH: (1) 'allow_git_url_install = true' in config.ini ([default] section), AND (2) ComfyUI launched with a loopback --listen (127.0.0.1 or ::1). 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.");
show_message('This action is not allowed with this security level configuration.');
return;
}
@@ -282,9 +278,9 @@ export async function install_via_git_url(url, manager_dialog) {
const self = this;
rebootButton.addEventListener("click",
async function() {
if(await rebootAPI()) {
manager_instance.close();
function() {
if(rebootAPI()) {
manager_dialog.close();
}
});
}
@@ -367,63 +363,6 @@ export function md5(inputString) {
return rh(a)+rh(b)+rh(c)+rh(d);
}
const levenArray = [];
const levenCodeCache = [];
export const leven = (first, second) => {
if (first === second) {
return 0;
}
const swap = first;
if (first.length > second.length) {
first = second;
second = swap;
}
let firstLength = first.length;
let secondLength = second.length;
while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) {
firstLength--;
secondLength--;
}
let start = 0;
while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) {
start++;
}
firstLength -= start;
secondLength -= start;
if (firstLength === 0) {
return secondLength;
}
let bCharacterCode;
let result;
let temporary;
let temporary2;
let index = 0;
let index2 = 0;
while (index < firstLength) {
levenCodeCache[index] = first.charCodeAt(start + index);
levenArray[index] = ++index;
}
while (index2 < secondLength) {
bCharacterCode = second.charCodeAt(start + index2);
temporary = index2++;
result = index2;
for (index = 0; index < firstLength; index++) {
temporary2 = bCharacterCode === levenCodeCache[index] ? temporary : temporary + 1;
temporary = levenArray[index];
result = levenArray[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2);
}
}
return result;
}
export function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
export async function fetchData(route, options) {
let err;
const res = await api.fetchApi(route, options).catch(e => {
@@ -465,14 +404,12 @@ export async function fetchData(route, options) {
}
}
// https://cenfun.github.io/open-icons/
export const icons = {
search: '<svg viewBox="0 0 24 24" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m21 21-4.486-4.494M19 10.5a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0"/></svg>',
extensions: '<svg viewBox="64 64 896 896" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M843.5 737.4c-12.4-75.2-79.2-129.1-155.3-125.4S550.9 676 546 752c-153.5-4.8-208-40.7-199.1-113.7 3.3-27.3 19.8-41.9 50.1-49 18.4-4.3 38.8-4.9 57.3-3.2 1.7.2 3.5.3 5.2.5 11.3 2.7 22.8 5 34.3 6.8 34.1 5.6 68.8 8.4 101.8 6.6 92.8-5 156-45.9 159.2-132.7 3.1-84.1-54.7-143.7-147.9-183.6-29.9-12.8-61.6-22.7-93.3-30.2-14.3-3.4-26.3-5.7-35.2-7.2-7.9-75.9-71.5-133.8-147.8-134.4S189.7 168 180.5 243.8s40 146.3 114.2 163.9 149.9-23.3 175.7-95.1c9.4 1.7 18.7 3.6 28 5.8 28.2 6.6 56.4 15.4 82.4 26.6 70.7 30.2 109.3 70.1 107.5 119.9-1.6 44.6-33.6 65.2-96.2 68.6-27.5 1.5-57.6-.9-87.3-5.8-8.3-1.4-15.9-2.8-22.6-4.3-3.9-.8-6.6-1.5-7.8-1.8l-3.1-.6c-2.2-.3-5.9-.8-10.7-1.3-25-2.3-52.1-1.5-78.5 4.6-55.2 12.9-93.9 47.2-101.1 105.8-15.7 126.2 78.6 184.7 276 188.9 29.1 70.4 106.4 107.9 179.6 87 73.3-20.9 119.3-93.4 106.9-168.6M329.1 345.2a83.3 83.3 0 1 1 .01-166.61 83.3 83.3 0 0 1-.01 166.61M695.6 845a83.3 83.3 0 1 1 .01-166.61A83.3 83.3 0 0 1 695.6 845"/></svg>',
conflicts: '<svg viewBox="0 0 400 400" width="100%" height="100%" pointer-events="none" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="m397.2 350.4.2-.2-180-320-.2.2C213.8 24.2 207.4 20 200 20s-13.8 4.2-17.2 10.4l-.2-.2-180 320 .2.2c-1.6 2.8-2.8 6-2.8 9.6 0 11 9 20 20 20h360c11 0 20-9 20-20 0-3.6-1.2-6.8-2.8-9.6M220 340h-40v-40h40zm0-60h-40V120h40z"/></svg>',
passed: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 426.667 426.667"><path fill="#6AC259" d="M213.333,0C95.518,0,0,95.514,0,213.333s95.518,213.333,213.333,213.333c117.828,0,213.333-95.514,213.333-213.333S331.157,0,213.333,0z M174.199,322.918l-93.935-93.931l31.309-31.309l62.626,62.622l140.894-140.898l31.309,31.309L174.199,322.918z"/></svg>',
download: '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" width="100%" height="100%" viewBox="0 0 32 32"><path fill="currentColor" d="M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4zm0-10l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10l10-10z"></path></svg>',
close: '<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="100%" height="100%" viewBox="0 0 16 16"><g fill="currentColor"><path fill-rule="evenodd" clip-rule="evenodd" d="m7.116 8-4.558 4.558.884.884L8 8.884l4.558 4.558.884-.884L8.884 8l4.558-4.558-.884-.884L8 7.116 3.442 2.558l-.884.884L7.116 8z"/></g></svg>',
arrowRight: '<svg xmlns="http://www.w3.org/2000/svg" pointer-events="none" width="100%" height="100%" viewBox="0 0 20 20"><path fill="currentColor" fill-rule="evenodd" d="m2.542 2.154 7.254 7.26c.136.14.204.302.204.483a.73.73 0 0 1-.204.5l-7.575 7.398c-.383.317-.724.317-1.022 0-.299-.317-.299-.643 0-.98l7.08-6.918-6.754-6.763c-.237-.343-.215-.654.066-.935.281-.28.598-.295.951-.045Zm9 0 7.254 7.26c.136.14.204.302.204.483a.73.73 0 0 1-.204.5l-7.575 7.398c-.383.317-.724.317-1.022 0-.299-.317-.299-.643 0-.98l7.08-6.918-6.754-6.763c-.237-.343-.215-.654.066-.935.281-.28.598-.295.951-.045Z"/></svg>'
download: '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" width="100%" height="100%" viewBox="0 0 32 32"><path fill="currentColor" d="M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4zm0-10l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10l10-10z"></path></svg>'
}
export function sanitizeHTML(str) {
@@ -484,40 +421,6 @@ export function sanitizeHTML(str) {
.replace(/'/g, "&#039;");
}
// Keep URL handling aligned with glob/manager_util.py; covered by shared cases.
export const SAFE_URL_SCHEMES = ['http', 'https'];
const URL_SCHEME_NOISE = /[\x00-\x20\x7f]/g;
const URL_HEAD_DELIMITERS = ['/', '?', '#'];
// Match Python str.strip(); JavaScript trim() uses different Unicode whitespace.
const URL_TRIM = /^[\t-\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+|[\t-\r\x1c-\x20\x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/g;
const trimUrl = (value) => value.replace(URL_TRIM, '');
export function sanitizeUrl(url) {
const raw = (url === null || url === undefined) ? '' : String(url);
const probe = raw.replace(URL_SCHEME_NOISE, '');
if (!probe) {
return '#';
}
let cut = probe.length;
for (const delimiter of URL_HEAD_DELIMITERS) {
const found = probe.indexOf(delimiter);
if (found !== -1) {
cut = Math.min(cut, found);
}
}
const head = probe.slice(0, cut);
if (head.includes(':')) {
return SAFE_URL_SCHEMES.includes(head.split(':', 1)[0].toLowerCase()) ? trimUrl(raw) : '#';
}
return trimUrl(raw);
}
// Validate the URL, then escape it for a quoted href attribute.
export const safeHref = (url) => sanitizeHTML(sanitizeUrl(url));
export function showTerminal() {
try {
const panel = app.extensionManager.bottomPanel;
@@ -600,553 +503,3 @@ export function restoreColumnWidth(gridId, columns) {
});
}
export function getTimeAgo(dateStr) {
const date = new Date(dateStr);
if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
return "";
}
const units = [
{ max: 2760000, value: 60000, name: 'minute', past: 'a minute ago', future: 'in a minute' },
{ max: 72000000, value: 3600000, name: 'hour', past: 'an hour ago', future: 'in an hour' },
{ max: 518400000, value: 86400000, name: 'day', past: 'yesterday', future: 'tomorrow' },
{ max: 2419200000, value: 604800000, name: 'week', past: 'last week', future: 'in a week' },
{ max: 28512000000, value: 2592000000, name: 'month', past: 'last month', future: 'in a month' }
];
const diff = Date.now() - date.getTime();
// less than a minute
if (Math.abs(diff) < 60000)
return 'just now';
for (let i = 0; i < units.length; i++) {
if (Math.abs(diff) < units[i].max) {
return format(diff, units[i].value, units[i].name, units[i].past, units[i].future, diff < 0);
}
}
function format(diff, divisor, unit, past, future, isInTheFuture) {
const val = Math.round(Math.abs(diff) / divisor);
if (isInTheFuture)
return val <= 1 ? future : 'in ' + val + ' ' + unit + 's';
return val <= 1 ? past : val + ' ' + unit + 's ago';
}
return format(diff, 31536000000, 'year', 'last year', 'in a year', diff < 0);
};
export const loadCss = (cssFile) => {
const cssPath = import.meta.resolve(cssFile);
//console.log(cssPath);
const $link = document.createElement("link");
$link.setAttribute("rel", 'stylesheet');
$link.setAttribute("href", cssPath);
document.head.appendChild($link);
};
export const copyText = (text) => {
return new Promise((resolve) => {
let err;
try {
navigator.clipboard.writeText(text);
} catch (e) {
err = e;
}
if (err) {
resolve(false);
} else {
resolve(true);
}
});
};
function renderPopover($elem, target, options = {}) {
// async microtask
queueMicrotask(() => {
const containerRect = getRect(window);
const targetRect = getRect(target);
const elemRect = getRect($elem);
const positionInfo = getBestPosition(
containerRect,
targetRect,
elemRect,
options.positions
);
const style = getPositionStyle(positionInfo, {
bgColor: options.bgColor,
borderColor: options.borderColor,
borderRadius: options.borderRadius
});
$elem.style.top = positionInfo.top + "px";
$elem.style.left = positionInfo.left + "px";
$elem.style.background = style.background;
});
}
let $popover;
export function hidePopover() {
if ($popover) {
$popover.remove();
$popover = null;
}
}
export function showPopover(target, text, className, options) {
hidePopover();
$popover = document.createElement("div");
$popover.className = ['cn-popover', className].filter(it => it).join(" ");
document.body.appendChild($popover);
$popover.innerHTML = text;
$popover.style.display = "block";
renderPopover($popover, target, {
borderRadius: 10,
... options
});
}
export async function uninstallNodes(nodeList, options = {}) {
const {
title = `${nodeList.length} custom nodes`,
onProgress = () => {},
onError = () => {},
onSuccess = () => {},
channel = 'default',
mode = 'default'
} = options;
// Check if queue is busy
let stats = await api.fetchApi('/manager/queue/status');
stats = await stats.json();
if (stats.is_processing) {
customAlert(`[ComfyUI-Manager] There are already tasks in progress. Please try again after it is completed. (${stats.done_count}/${stats.total_count})`);
return { success: false, error: 'Queue is busy' };
}
// Confirmation dialog for uninstall
const confirmed = await customConfirm(`Are you sure uninstall ${title}?`);
if (!confirmed) {
return { success: false, error: 'User cancelled' };
}
let errorMsg = "";
let target_items = [];
await api.fetchApi('/manager/queue/reset');
for (const nodeItem of nodeList) {
target_items.push(nodeItem);
// Titles are escaped by the caller; the name fallback is a raw pack key.
const displayTitle = nodeItem.title || sanitizeHTML(String(nodeItem.name));
onProgress(`Uninstall ${displayTitle} ...`);
const data = nodeItem.originalData || nodeItem;
data.channel = channel;
data.mode = mode;
data.ui_id = nodeItem.hash || md5(nodeItem.name || nodeItem.title);
const res = await api.fetchApi(`/manager/queue/uninstall`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (res.status != 200) {
errorMsg = `'${displayTitle}': `;
if (res.status == 403) {
errorMsg += `This action is not allowed with this security level configuration.\n`;
} else {
errorMsg += sanitizeHTML(await res.text()) + '\n';
}
break;
}
}
if (errorMsg) {
onError(errorMsg);
show_message("[Uninstall Errors]\n" + errorMsg);
return { success: false, error: errorMsg, targets: target_items };
} else {
await api.fetchApi('/manager/queue/start');
onSuccess(target_items);
showTerminal();
return { success: true, targets: target_items };
}
}
// ===========================================================================================
// Workflow Utilities Consolidation
export async function getWorkflowNodeTypes() {
try {
const res = await fetchData('/customnode/get_node_types_in_workflows');
if (res.status === 200) {
return { success: true, data: res.data };
} else if (res.status === 204) {
// No workflows found - return empty list
return { success: true, data: [] };
} else {
return { success: false, error: res.error };
}
} catch (error) {
return { success: false, error: error };
}
}
export function findPackageByCnrId(cnrId, nodePackages, installedOnly = true) {
if (!cnrId || !nodePackages) {
return null;
}
// Tier 1: Direct key match
if (nodePackages[cnrId]) {
const pack = nodePackages[cnrId];
if (!installedOnly || pack.state !== "not-installed") {
return { key: cnrId, pack: pack };
}
}
// Tier 2: Case-insensitive match
const cnrIdLower = cnrId.toLowerCase();
for (const packKey of Object.keys(nodePackages)) {
if (packKey.toLowerCase() === cnrIdLower) {
const pack = nodePackages[packKey];
if (!installedOnly || pack.state !== "not-installed") {
return { key: packKey, pack: pack };
}
}
}
// Tier 3: URL/reference contains match
for (const packKey of Object.keys(nodePackages)) {
const pack = nodePackages[packKey];
// Skip non-installed packages if installedOnly is true
if (installedOnly && pack.state === "not-installed") {
continue;
}
// Check if reference URL contains cnr_id
if (pack.reference && pack.reference.includes(cnrId)) {
return { key: packKey, pack: pack };
}
// Check if any file URL contains cnr_id
if (pack.files && Array.isArray(pack.files)) {
for (const fileUrl of pack.files) {
if (fileUrl.includes(cnrId)) {
return { key: packKey, pack: pack };
}
}
}
}
return null;
}
export async function analyzeWorkflowUsage(nodePackages) {
const result = await getWorkflowNodeTypes();
if (!result.success) {
return { success: false, error: result.error };
}
const workflowNodeList = result.data;
const usageMap = new Map();
const workflowDetailsMap = new Map();
if (workflowNodeList && Array.isArray(workflowNodeList)) {
const cnrIdCounts = new Map();
const cnrIdToWorkflows = new Map();
// Process each workflow
workflowNodeList.forEach((workflowObj, workflowIndex) => {
if (workflowObj.node_types && Array.isArray(workflowObj.node_types)) {
const workflowCnrIds = new Set();
// Get workflow filename
const workflowFilename = workflowObj.workflow_file_name ||
workflowObj.filename ||
workflowObj.file ||
workflowObj.name ||
workflowObj.path ||
`Workflow ${workflowIndex + 1}`;
// Count nodes per cnr_id in this workflow
const workflowCnrIdCounts = new Map();
workflowObj.node_types.forEach(nodeTypeObj => {
const cnrId = nodeTypeObj.cnr_id;
if (cnrId && cnrId !== "comfy-core") {
// Track unique cnr_ids per workflow
workflowCnrIds.add(cnrId);
// Count nodes per cnr_id in this specific workflow
const workflowNodeCount = workflowCnrIdCounts.get(cnrId) || 0;
workflowCnrIdCounts.set(cnrId, workflowNodeCount + 1);
}
});
// Record workflow details for each unique cnr_id found in this workflow
workflowCnrIds.forEach(cnrId => {
// Count occurrences of this cnr_id across all workflows
const currentCount = cnrIdCounts.get(cnrId) || 0;
cnrIdCounts.set(cnrId, currentCount + 1);
// Track workflow details
if (!cnrIdToWorkflows.has(cnrId)) {
cnrIdToWorkflows.set(cnrId, []);
}
cnrIdToWorkflows.get(cnrId).push({
filename: workflowFilename,
nodeCount: workflowCnrIdCounts.get(cnrId) || 0
});
});
}
});
// Map cnr_id to installed packages with workflow details
cnrIdCounts.forEach((count, cnrId) => {
const workflowDetails = cnrIdToWorkflows.get(cnrId) || [];
const foundPackage = findPackageByCnrId(cnrId, nodePackages, true);
if (foundPackage) {
usageMap.set(foundPackage.key, count);
workflowDetailsMap.set(foundPackage.key, workflowDetails);
}
});
}
return {
success: true,
usageMap: usageMap,
workflowDetailsMap: workflowDetailsMap
};
}
// Size formatting utilities - consolidated from model-manager.js and node-usage-analyzer.js
export function formatSize(v) {
const base = 1000;
const units = ['', 'K', 'M', 'G', 'T', 'P'];
const space = '';
const postfix = 'B';
if (v <= 0) {
return `0${space}${postfix}`;
}
for (let i = 0, l = units.length; i < l; i++) {
const min = Math.pow(base, i);
const max = Math.pow(base, i + 1);
if (v > min && v <= max) {
const unit = units[i];
if (unit) {
const n = v / min;
const nl = n.toString().split('.')[0].length;
const fl = Math.max(3 - nl, 1);
v = n.toFixed(fl);
}
v = v + space + unit + postfix;
break;
}
}
return v;
}
// for size sort
export function sizeToBytes(v) {
if (typeof v === "number") {
return v;
}
if (typeof v === "string") {
const n = parseFloat(v);
const unit = v.replace(/[0-9.B]+/g, "").trim().toUpperCase();
if (unit === "K") {
return n * 1000;
}
if (unit === "M") {
return n * 1000 * 1000;
}
if (unit === "G") {
return n * 1000 * 1000 * 1000;
}
if (unit === "T") {
return n * 1000 * 1000 * 1000 * 1000;
}
}
return v;
}
// Flyover component - consolidated from custom-nodes-manager.js and node-usage-analyzer.js
export function createFlyover(container, options = {}) {
const {
enableHover = false,
hoverHandler = null,
context = null
} = options;
const $flyover = document.createElement("div");
$flyover.className = "cn-flyover";
$flyover.innerHTML = `<div class="cn-flyover-header">
<div class="cn-flyover-close">${icons.arrowRight}</div>
<div class="cn-flyover-title"></div>
<div class="cn-flyover-close">${icons.close}</div>
</div>
<div class="cn-flyover-body"></div>`
container.appendChild($flyover);
const $flyoverTitle = $flyover.querySelector(".cn-flyover-title");
const $flyoverBody = $flyover.querySelector(".cn-flyover-body");
let width = '50%';
let visible = false;
let timeHide;
const closeHandler = (e) => {
if ($flyover === e.target || $flyover.contains(e.target)) {
return;
}
clearTimeout(timeHide);
timeHide = setTimeout(() => {
flyover.hide();
}, 100);
}
const displayHandler = () => {
if (visible) {
$flyover.classList.remove("cn-slide-in-right");
} else {
$flyover.classList.remove("cn-slide-out-right");
$flyover.style.width = '0px';
$flyover.style.display = "none";
}
}
const flyover = {
show: (titleHtml, bodyHtml) => {
clearTimeout(timeHide);
if (context && context.element) {
context.element.removeEventListener("click", closeHandler);
}
$flyoverTitle.innerHTML = titleHtml;
$flyoverBody.innerHTML = bodyHtml;
$flyover.style.display = "block";
$flyover.style.width = width;
if(!visible) {
$flyover.classList.add("cn-slide-in-right");
}
visible = true;
setTimeout(() => {
if (context && context.element) {
context.element.addEventListener("click", closeHandler);
}
}, 100);
},
hide: (now) => {
visible = false;
if (context && context.element) {
context.element.removeEventListener("click", closeHandler);
}
if(now) {
displayHandler();
return;
}
$flyover.classList.add("cn-slide-out-right");
}
}
$flyover.addEventListener("animationend", (e) => {
displayHandler();
});
// Add hover handlers if enabled
if (enableHover && hoverHandler) {
$flyover.addEventListener("mouseenter", hoverHandler, true);
$flyover.addEventListener("mouseleave", hoverHandler, true);
}
$flyover.addEventListener("click", (e) => {
if(e.target.classList.contains("cn-flyover-close")) {
flyover.hide();
return;
}
// Forward other click events to the provided handler or context
if (context && context.handleFlyoverClick) {
context.handleFlyoverClick(e);
}
});
return flyover;
}
// Message methods accept HTML; callers escape raw data and preserve formatted content.
export function createUIStateManager(element, selectors) {
return {
showSelection: (msg) => {
const el = element.querySelector(selectors.selection);
if (el) el.innerHTML = msg;
},
showError: (err) => {
const el = element.querySelector(selectors.message);
if (el) {
const msg = err ? `<font color="red">${err}</font>` : "";
el.innerHTML = msg;
}
},
showMessage: (msg, color) => {
const el = element.querySelector(selectors.message);
if (el) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
el.innerHTML = msg;
}
},
showStatus: (msg, color) => {
const el = element.querySelector(selectors.status);
if (el) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
el.innerHTML = msg;
}
},
showLoading: (grid) => {
if (grid) {
grid.showLoading();
grid.showMask({
opacity: 0.05
});
}
},
hideLoading: (grid) => {
if (grid) {
grid.hideLoading();
grid.hideMask();
}
},
showRefresh: () => {
const el = element.querySelector(selectors.refresh);
if (el) el.style.display = "block";
},
showStop: () => {
const el = element.querySelector(selectors.stop);
if (el) el.style.display = "block";
},
hideStop: () => {
const el = element.querySelector(selectors.stop);
if (el) el.style.display = "none";
}
};
}
+4 -8
View File
@@ -65,10 +65,6 @@ function storeGroupNode(name, data, register=true) {
export async function load_components() {
let data = await api.fetchApi('/manager/component/loads', {method: "POST"});
if(data.status != 200) {
return;
}
let components = await data.json();
let start_time = Date.now();
@@ -682,7 +678,7 @@ export class ComponentBuilderDialog extends ComfyDialog {
let orig_handleFile = app.handleFile;
async function handleFile(file, ...args) {
async function handleFile(file) {
if (file.name?.endsWith(".json") || file.name?.endsWith(".pack")) {
const reader = new FileReader();
reader.onload = async () => {
@@ -698,7 +694,7 @@ async function handleFile(file, ...args) {
await handle_import_components(jsonContent);
}
else {
orig_handleFile.call(app, file, ...args);
orig_handleFile.call(app, file);
}
};
reader.readAsText(file);
@@ -706,7 +702,7 @@ async function handleFile(file, ...args) {
return;
}
orig_handleFile.call(app, file, ...args);
orig_handleFile.call(app, file);
}
app.handleFile = handleFile;
@@ -784,7 +780,7 @@ export function set_component_policy(v) {
let graphToPrompt = app.graphToPrompt;
app.graphToPrompt = async function () {
let p = await graphToPrompt.apply(app, arguments);
let p = await graphToPrompt.call(app);
try {
let groupNodes = p.workflow.extra?.groupNodes;
if(groupNodes) {
-722
View File
@@ -1,722 +0,0 @@
.cn-manager {
--grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
z-index: 1099;
width: 80vw;
height: 75vh;
min-height: 30em;
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg-color);
font-family: arial, sans-serif;
text-underline-offset: 3px;
outline: none;
margin: calc(var(--spacing)*2);
}
.cn-manager .cn-flex-auto {
flex: auto;
}
.cn-manager button {
width: auto;
position: relative;
overflow: hidden;
font-size: 16px;
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-color: var(--border-color);
margin: 0;
min-width: 100px;
}
.cn-manager button:hover {
filter: brightness(125%);
}
.cn-manager button:disabled,
.cn-manager input:disabled,
.cn-manager select:disabled {
color: gray;
}
.cn-manager button:disabled {
background-color: var(--comfy-input-bg);
}
.cn-manager .cn-manager-restart {
display: none;
background-color: #500000 !important;
border-color: #88181b !important;
color: white !important;
}
.cn-manager .cn-manager-restart:hover {
background-color: #88181b !important;
}
.cn-manager .cn-manager-stop {
display: none;
background-color: #500000;
color: white;
}
.cn-manager .cn-manager-back {
align-items: center;
justify-content: center;
}
.arrow-icon {
height: 1em;
width: 1em;
margin-right: 5px;
transform: translateY(2px);
}
.cn-icon {
display: block;
width: 16px;
height: 16px;
}
.cn-icon svg {
display: block;
margin: 0;
pointer-events: none;
}
.cn-manager-header {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
}
.cn-manager-header label {
display: flex;
gap: 5px;
align-items: center;
}
.cn-manager-filter {
height: 28px;
line-height: 28px;
cursor: pointer;
padding: 0 0.5em;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--comfy-input-bg);
}
.cn-manager-filter:hover {
filter: brightness(125%);
}
.cn-manager-keywords {
height: 28px;
line-height: 28px;
padding: 0 5px 0 26px;
background: var(--comfy-input-bg);
background-size: 16px;
background-position: 5px center;
background-repeat: no-repeat;
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%220%200%2024%2024%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20pointer-events%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23888%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%222%22%20d%3D%22m21%2021-4.486-4.494M19%2010.5a8.5%208.5%200%201%201-17%200%208.5%208.5%200%200%201%2017%200%22%2F%3E%3C%2Fsvg%3E");
border: 1px solid var(--border-color);
border-radius: 6px;
outline-color: transparent;
}
.cn-manager-status {
padding-left: 10px;
}
.cn-manager-grid {
flex: auto;
border: 1px solid var(--border-color);
overflow: hidden;
position: relative;
}
.cn-manager-selection {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cn-manager-message {
position: relative;
}
.cn-manager-footer {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cn-manager-grid .tg-turbogrid {
font-family: var(--grid-font);
font-size: 15px;
background: var(--bg-color);
}
.cn-manager-grid .tg-turbogrid .tg-highlight::after {
position: absolute;
top: 0;
left: 0;
content: "";
display: block;
width: 100%;
height: 100%;
box-sizing: border-box;
background-color: #80bdff11;
pointer-events: none;
}
.cn-manager-grid .cn-pack-name a {
color: skyblue;
text-decoration: none;
word-break: break-word;
}
.cn-manager-grid .cn-pack-desc a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
.cn-manager-grid .tg-cell a:hover {
text-decoration: underline;
}
.cn-manager-grid .cn-pack-version {
line-height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
gap: 5px;
}
.cn-manager-grid .cn-pack-nodes {
line-height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
gap: 5px;
cursor: pointer;
height: 100%;
}
.cn-manager-grid .cn-pack-nodes:hover {
text-decoration: underline;
}
.cn-manager-grid .cn-pack-conflicts {
color: orange;
}
.cn-popover {
position: fixed;
z-index: 10000;
padding: 20px;
color: #1e1e1e;
filter: drop-shadow(1px 5px 5px rgb(0 0 0 / 30%));
overflow: hidden;
}
.cn-flyover {
position: absolute;
top: 0;
right: 0;
z-index: 1000;
display: none;
width: 50%;
height: 100%;
background-color: var(--comfy-menu-bg);
animation-duration: 0.2s;
animation-fill-mode: both;
flex-direction: column;
}
.cn-flyover::before {
position: absolute;
top: 0;
content: "";
z-index: 10;
display: block;
width: 10px;
height: 100%;
pointer-events: none;
left: -10px;
background-image: linear-gradient(to left, rgb(0 0 0 / 20%), rgb(0 0 0 / 0%));
}
.cn-flyover-header {
height: 45px;
display: flex;
align-items: center;
gap: 5px;
border-bottom: 1px solid var(--border-color);
}
.cn-flyover-close {
display: flex;
align-items: center;
padding: 0 10px;
justify-content: center;
cursor: pointer;
opacity: 0.8;
height: 100%;
}
.cn-flyover-close:hover {
opacity: 1;
}
.cn-flyover-close svg {
display: block;
margin: 0;
pointer-events: none;
width: 20px;
height: 20px;
}
.cn-flyover-title {
display: flex;
align-items: center;
font-weight: bold;
gap: 10px;
flex: auto;
}
.cn-flyover-body {
height: calc(100% - 45px);
overflow-y: auto;
position: relative;
background-color: var(--comfy-menu-secondary-bg);
}
@keyframes cn-slide-in-right {
from {
visibility: visible;
transform: translate3d(100%, 0, 0);
}
to {
transform: translate3d(0, 0, 0);
}
}
.cn-slide-in-right {
animation-name: cn-slide-in-right;
}
@keyframes cn-slide-out-right {
from {
transform: translate3d(0, 0, 0);
}
to {
visibility: hidden;
transform: translate3d(100%, 0, 0);
}
}
.cn-slide-out-right {
animation-name: cn-slide-out-right;
}
.cn-nodes-list {
width: 100%;
}
.cn-nodes-row {
display: flex;
align-items: center;
gap: 10px;
}
.cn-nodes-row:nth-child(odd) {
background-color: rgb(0 0 0 / 5%);
}
.cn-nodes-row:hover {
background-color: rgb(0 0 0 / 10%);
}
.cn-nodes-sn {
text-align: right;
min-width: 35px;
color: var(--drag-text);
flex-shrink: 0;
font-size: 12px;
padding: 8px 5px;
}
.cn-nodes-name {
cursor: pointer;
white-space: nowrap;
flex-shrink: 0;
position: relative;
padding: 8px 5px;
}
.cn-nodes-name::after {
content: attr(action);
position: absolute;
pointer-events: none;
top: 50%;
left: 100%;
transform: translate(5px, -50%);
font-size: 12px;
color: var(--drag-text);
background-color: var(--comfy-input-bg);
border-radius: 10px;
border: 1px solid var(--border-color);
padding: 3px 8px;
display: none;
}
.cn-nodes-name.action::after {
display: block;
}
.cn-nodes-name:hover {
text-decoration: underline;
}
.cn-nodes-conflict .cn-nodes-name,
.cn-nodes-conflict .cn-icon {
color: orange;
}
.cn-conflicts-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
padding: 5px 0;
}
.cn-conflicts-list b {
font-weight: normal;
color: var(--descrip-text);
}
.cn-nodes-pack {
cursor: pointer;
color: skyblue;
}
.cn-nodes-pack:hover {
text-decoration: underline;
}
.cn-pack-badge {
font-size: 12px;
font-weight: normal;
background-color: var(--comfy-input-bg);
border-radius: 10px;
border: 1px solid var(--border-color);
padding: 3px 8px;
color: var(--error-text);
}
.cn-preview {
min-width: 300px;
max-width: 500px;
min-height: 120px;
overflow: hidden;
font-size: 12px;
pointer-events: none;
padding: 12px;
color: var(--fg-color);
}
.cn-preview-header {
display: flex;
gap: 8px;
align-items: center;
border-bottom: 1px solid var(--comfy-input-bg);
padding: 5px 10px;
}
.cn-preview-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: grey;
position: relative;
filter: drop-shadow(1px 2px 3px rgb(0 0 0 / 30%));
}
.cn-preview-dot.cn-preview-optional::after {
content: "";
position: absolute;
pointer-events: none;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: var(--comfy-input-bg);
border-radius: 50%;
width: 3px;
height: 3px;
}
.cn-preview-dot.cn-preview-grid {
border-radius: 0;
}
.cn-preview-dot.cn-preview-grid::before {
content: '';
position: absolute;
border-left: 1px solid var(--comfy-input-bg);
border-right: 1px solid var(--comfy-input-bg);
width: 4px;
height: 100%;
left: 2px;
top: 0;
z-index: 1;
}
.cn-preview-dot.cn-preview-grid::after {
content: '';
position: absolute;
border-top: 1px solid var(--comfy-input-bg);
border-bottom: 1px solid var(--comfy-input-bg);
width: 100%;
height: 4px;
left: 0;
top: 2px;
z-index: 1;
}
.cn-preview-name {
flex: auto;
font-size: 14px;
}
.cn-preview-io {
display: flex;
justify-content: space-between;
padding: 10px 10px;
}
.cn-preview-column > div {
display: flex;
gap: 10px;
align-items: center;
height: 18px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.cn-preview-input {
justify-content: flex-start;
}
.cn-preview-output {
justify-content: flex-end;
}
.cn-preview-list {
display: flex;
flex-direction: column;
gap: 3px;
padding: 0 10px 10px 10px;
}
.cn-preview-switch {
position: relative;
display: flex;
justify-content: space-between;
align-items: center;
background: var(--bg-color);
border: 2px solid var(--border-color);
border-radius: 10px;
text-wrap: nowrap;
padding: 2px 20px;
gap: 10px;
}
.cn-preview-switch::before,
.cn-preview-switch::after {
position: absolute;
pointer-events: none;
top: 50%;
transform: translate(0, -50%);
color: var(--fg-color);
opacity: 0.8;
}
.cn-preview-switch::before {
content: "◀";
left: 5px;
}
.cn-preview-switch::after {
content: "▶";
right: 5px;
}
.cn-preview-value {
color: var(--descrip-text);
}
.cn-preview-string {
min-height: 30px;
max-height: 300px;
background: var(--bg-color);
color: var(--descrip-text);
border-radius: 3px;
padding: 3px 5px;
overflow-y: auto;
overflow-x: hidden;
}
.cn-preview-description {
margin: 0px 10px 10px 10px;
padding: 6px;
background: var(--border-color);
color: var(--descrip-text);
border-radius: 5px;
font-style: italic;
word-break: break-word;
}
.cn-install-buttons {
display: flex;
flex-direction: column;
gap: 3px;
padding: 3px;
align-items: center;
justify-content: center;
height: 100%;
}
.cn-install-buttons button {
padding: 4px 8px;
}
.cn-selected-buttons {
display: flex;
gap: 5px;
align-items: center;
padding-right: 20px;
}
.cn-manager .cn-btn-enable {
background-color: #333399;
color: white;
}
.cn-manager .cn-btn-disable {
background-color: #442277;
color: white;
}
.cn-manager .cn-btn-update {
background-color: #1155AA;
color: white;
}
.cn-manager .cn-btn-try-update {
background-color: Gray;
color: white;
}
.cn-manager .cn-btn-try-fix {
background-color: #6495ED;
color: white;
}
.cn-manager .cn-btn-import-failed {
background-color: #AA1111;
font-size: 10px;
font-weight: bold;
color: white;
}
.cn-manager .cn-btn-invalid-installation {
background-color: #A65E00;
font-size: 10px;
font-weight: bold;
color: white;
}
.cn-manager .cn-btn-install {
background-color: black;
color: white;
}
.cn-manager .cn-btn-try-install {
background-color: Gray;
color: white;
}
.cn-manager .cn-btn-uninstall {
background-color: #993333;
color: white;
}
.cn-manager .cn-btn-reinstall {
background-color: #993333;
color: white;
}
.cn-manager .cn-btn-switch {
background-color: #448833;
color: white;
}
@keyframes cn-btn-loading-bg {
0% {
left: 0;
}
100% {
left: -105px;
}
}
.cn-manager button.cn-btn-loading {
position: relative;
overflow: hidden;
border-color: rgb(0 119 207 / 80%);
background-color: var(--comfy-input-bg);
}
.cn-manager button.cn-btn-loading::after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 500px;
height: 100%;
background-image: repeating-linear-gradient(
-45deg,
rgb(0 119 207 / 30%),
rgb(0 119 207 / 30%) 10px,
transparent 10px,
transparent 15px
);
animation: cn-btn-loading-bg 2s linear infinite;
}
.cn-manager-light .cn-pack-name a {
color: blue;
}
.cn-manager-light .cm-warn-note {
background-color: #ccc !important;
}
.cn-manager-light .cn-btn-install {
background-color: #333;
}
+659 -957
View File
File diff suppressed because it is too large Load Diff
-67
View File
@@ -1,67 +0,0 @@
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);
}
}
}
}
-237
View File
@@ -1,237 +0,0 @@
.cmm-manager {
--grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
z-index: 1099;
width: 80vw;
height: 75vh;
min-height: 30em;
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg-color);
font-family: arial, sans-serif;
margin: calc(var(--spacing)*2);
}
.cmm-manager .cmm-flex-auto {
flex: auto;
}
.cmm-manager button {
font-size: 16px;
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-color: var(--border-color);
margin: 0;
min-width: 100px;
}
.cmm-manager button:hover {
filter: brightness(125%);
}
.cmm-manager button:disabled,
.cmm-manager input:disabled,
.cmm-manager select:disabled {
color: gray;
}
.cmm-manager button:disabled {
background-color: var(--comfy-input-bg);
}
.cmm-manager .cmm-manager-refresh {
display: none;
background-color: #000080 !important;
color: white;
}
.cmm-manager .cmm-manager-stop {
display: none;
background-color: #500000;
color: white;
}
.cmm-manager-header {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
}
.cmm-manager-header label {
display: flex;
gap: 5px;
align-items: center;
}
.cmm-manager-type,
.cmm-manager-base,
.cmm-manager-filter {
height: 28px;
line-height: 28px;
cursor: pointer;
padding: 0 0.5em;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--comfy-input-bg);
}
.cmm-manager-type:hover,
.cmm-manager-base:hover,
.cmm-manager-filter:hover {
filter: brightness(125%);
}
.cmm-manager-keywords {
height: 28px;
line-height: 28px;
padding: 0 5px 0 26px;
background: var(--comfy-input-bg);
background-size: 16px;
background-position: 5px center;
background-repeat: no-repeat;
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%220%200%2024%2024%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20pointer-events%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23888%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%222%22%20d%3D%22m21%2021-4.486-4.494M19%2010.5a8.5%208.5%200%201%201-17%200%208.5%208.5%200%200%201%2017%200%22%2F%3E%3C%2Fsvg%3E");
border: 1px solid var(--border-color);
border-radius: 6px;
outline-color: transparent;
}
.cmm-manager-status {
padding-left: 10px;
}
.cmm-manager-grid {
flex: auto;
border: 1px solid var(--border-color);
overflow: hidden;
}
.cmm-manager-selection {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cmm-manager-footer {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cmm-manager-grid .tg-turbogrid {
font-family: var(--grid-font);
font-size: 15px;
background: var(--bg-color);
}
.cmm-manager-grid .cmm-node-name a {
color: skyblue;
text-decoration: none;
word-break: break-word;
}
.cmm-manager-grid .cmm-node-desc a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
.cmm-manager-grid .tg-cell a:hover {
text-decoration: underline;
}
.cmm-icon-passed {
width: 20px;
height: 20px;
position: absolute;
left: calc(50% - 10px);
top: calc(50% - 10px);
}
.cmm-manager .cmm-btn-enable {
background-color: blue;
color: white;
}
.cmm-manager .cmm-btn-disable {
background-color: MediumSlateBlue;
color: white;
}
.cmm-manager .cmm-btn-install {
background-color: black;
color: white;
}
.cmm-btn-install {
padding: 4px 8px;
}
.cmm-btn-download {
width: 18px;
height: 18px;
position: absolute;
left: calc(50% - 10px);
top: calc(50% - 10px);
cursor: pointer;
opacity: 0.8;
color: #fff;
}
.cmm-btn-download:hover {
opacity: 1;
}
.cmm-manager-light .cmm-btn-download {
color: #000;
}
@keyframes cmm-btn-loading-bg {
0% {
left: 0;
}
100% {
left: -105px;
}
}
.cmm-manager button.cmm-btn-loading {
position: relative;
overflow: hidden;
border-color: rgb(0 119 207 / 80%);
background-color: var(--comfy-input-bg);
}
.cmm-manager button.cmm-btn-loading::after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 500px;
height: 100%;
background-image: repeating-linear-gradient(
-45deg,
rgb(0 119 207 / 30%),
rgb(0 119 207 / 30%) 10px,
transparent 10px,
transparent 15px
);
animation: cmm-btn-loading-bg 2s linear infinite;
}
.cmm-manager-light .cmm-node-name a {
color: blue;
}
.cmm-manager-light .cm-warn-note {
background-color: #ccc !important;
}
.cmm-manager-light .cmm-btn-install {
background-color: #333;
}
+354 -126
View File
@@ -1,40 +1,266 @@
import { app } from "../../scripts/app.js";
import { $el } from "../../scripts/ui.js";
import {
manager_instance, rebootAPI,
import {
manager_instance, rebootAPI,
fetchData, md5, icons, show_message, customAlert, infoToast, showTerminal,
storeColumnWidth, restoreColumnWidth, loadCss, formatSize, sizeToBytes,
sanitizeHTML, safeHref
storeColumnWidth, restoreColumnWidth
} from "./common.js";
import { api } from "../../scripts/api.js";
// https://cenfun.github.io/turbogrid/api.html
import ManagerGrid from "./manager-grid.js";
import { buildGuiFrameCustomHeader, createSettingsCombo } from "./comfyui-gui-builder.js";
loadCss("./model-manager.css");
import TG from "./turbogrid.esm.js";
const gridId = "model";
// Escape raw cells while preserving empty values.
const escapeCell = (value) => (value === null || value === undefined) ? value : sanitizeHTML(String(value));
const pageCss = `
.cmm-manager {
--grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
z-index: 1099;
width: 80%;
height: 80%;
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg-color);
font-family: arial, sans-serif;
}
// Escape option markup while comparing the original values.
const renderOptions = (list, current) => list.map(item => {
const selected = item.value === current ? " selected" : "";
return `<option value="${sanitizeHTML(String(item.value))}"${selected}>${sanitizeHTML(String(item.label))}</option>`;
}).join("");
.cmm-manager .cmm-flex-auto {
flex: auto;
}
.cmm-manager button {
font-size: 16px;
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-radius: 8px;
border-color: var(--border-color);
border-style: solid;
margin: 0;
padding: 4px 8px;
min-width: 100px;
}
.cmm-manager button:disabled,
.cmm-manager input:disabled,
.cmm-manager select:disabled {
color: gray;
}
.cmm-manager button:disabled {
background-color: var(--comfy-input-bg);
}
.cmm-manager .cmm-manager-refresh {
display: none;
background-color: #000080;
color: white;
}
.cmm-manager .cmm-manager-stop {
display: none;
background-color: #500000;
color: white;
}
.cmm-manager-header {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
padding: 0 5px;
}
.cmm-manager-header label {
display: flex;
gap: 5px;
align-items: center;
}
.cmm-manager-type,
.cmm-manager-base,
.cmm-manager-filter {
height: 28px;
line-height: 28px;
}
.cmm-manager-keywords {
height: 28px;
line-height: 28px;
padding: 0 5px 0 26px;
background-size: 16px;
background-position: 5px center;
background-repeat: no-repeat;
background-image: url("data:image/svg+xml;charset=utf8,${encodeURIComponent(icons.search.replace("currentColor", "#888"))}");
}
.cmm-manager-status {
padding-left: 10px;
}
.cmm-manager-grid {
flex: auto;
border: 1px solid var(--border-color);
overflow: hidden;
}
.cmm-manager-selection {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cmm-manager-message {
}
.cmm-manager-footer {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.cmm-manager-grid .tg-turbogrid {
font-family: var(--grid-font);
font-size: 15px;
background: var(--bg-color);
}
.cmm-manager-grid .cmm-node-name a {
color: skyblue;
text-decoration: none;
word-break: break-word;
}
.cmm-manager-grid .cmm-node-desc a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
.cmm-manager-grid .tg-cell a:hover {
text-decoration: underline;
}
.cmm-icon-passed {
width: 20px;
height: 20px;
position: absolute;
left: calc(50% - 10px);
top: calc(50% - 10px);
}
.cmm-manager .cmm-btn-enable {
background-color: blue;
color: white;
}
.cmm-manager .cmm-btn-disable {
background-color: MediumSlateBlue;
color: white;
}
.cmm-manager .cmm-btn-install {
background-color: black;
color: white;
}
.cmm-btn-download {
width: 18px;
height: 18px;
position: absolute;
left: calc(50% - 10px);
top: calc(50% - 10px);
cursor: pointer;
opacity: 0.8;
color: #fff;
}
.cmm-btn-download:hover {
opacity: 1;
}
.cmm-manager-light .cmm-btn-download {
color: #000;
}
@keyframes cmm-btn-loading-bg {
0% {
left: 0;
}
100% {
left: -105px;
}
}
.cmm-manager button.cmm-btn-loading {
position: relative;
overflow: hidden;
border-color: rgb(0 119 207 / 80%);
background-color: var(--comfy-input-bg);
}
.cmm-manager button.cmm-btn-loading::after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 500px;
height: 100%;
background-image: repeating-linear-gradient(
-45deg,
rgb(0 119 207 / 30%),
rgb(0 119 207 / 30%) 10px,
transparent 10px,
transparent 15px
);
animation: cmm-btn-loading-bg 2s linear infinite;
}
.cmm-manager-light .cmm-node-name a {
color: blue;
}
.cmm-manager-light .cm-warn-note {
background-color: #ccc !important;
}
.cmm-manager-light .cmm-btn-install {
background-color: #333;
}
`;
const pageHtml = `
<div class="cmm-manager cmm-manager-dark">
<div class="cmm-manager-grid"></div>
<div class="cmm-manager-selection"></div>
<div class="cmm-manager-message"></div>
<div class="cmm-manager-footer">
<button class="cmm-manager-refresh cm-ui-button">Refresh</button>
<button class="cmm-manager-stop cm-ui-button">Stop</button>
<div class="cmm-flex-auto"></div>
</div>
<div class="cmm-manager-header">
<label>Filter
<select class="cmm-manager-filter"></select>
</label>
<label>Type
<select class="cmm-manager-type"></select>
</label>
<label>Base
<select class="cmm-manager-base"></select>
</label>
<input class="cmm-manager-keywords" type="search" placeholder="Search" />
<div class="cmm-manager-status"></div>
<div class="cmm-flex-auto"></div>
</div>
<div class="cmm-manager-grid"></div>
<div class="cmm-manager-selection"></div>
<div class="cmm-manager-message"></div>
<div class="cmm-manager-footer">
<button class="cmm-manager-back">
<svg class="arrow-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 8H18M2 8L8 2M2 8L8 14" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
Back
</button>
<button class="cmm-manager-refresh">Refresh</button>
<button class="cmm-manager-stop">Stop</button>
<div class="cmm-flex-auto"></div>
</div>
`;
@@ -57,23 +283,19 @@ export class ModelManager {
}
init() {
const header = $el("div.cmm-manager-header", {}, [
createSettingsCombo("Filter", $el("select.cmm-manager-filter")),
createSettingsCombo("Type", $el("select.cmm-manager-type")),
createSettingsCombo("Base", $el("select.cmm-manager-base")),
$el("input.cmm-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
$el("div.cmm-manager-status"),
$el("div.cmm-flex-auto")
]);
const frame = buildGuiFrameCustomHeader(
'cmm-manager-dialog', // dialog id
header, // custom header element
pageHtml, // dialog content element
this
); // send this so we can attach close functions
if (!document.querySelector(`style[context="${this.id}"]`)) {
const $style = document.createElement("style");
$style.setAttribute("context", this.id);
$style.innerHTML = pageCss;
document.head.appendChild($style);
}
this.element = frame;
this.element = $el("div", {
parent: document.body,
className: "comfy-modal cmm-manager"
});
this.element.innerHTML = pageHtml;
this.initFilter();
this.bindEvents();
this.initGrid();
@@ -86,13 +308,10 @@ export class ModelManager {
value: ""
}, {
label: "Installed",
value: "installed"
value: "True"
}, {
label: "Not Installed",
value: "not_installed"
}, {
label: "In Workflow",
value: "in_workflow"
value: "False"
}];
this.typeList = [{
@@ -111,13 +330,22 @@ export class ModelManager {
updateFilter() {
const $filter = this.element.querySelector(".cmm-manager-filter");
$filter.innerHTML = renderOptions(this.filterList, this.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 $type = this.element.querySelector(".cmm-manager-type");
$type.innerHTML = renderOptions(this.typeList, this.type);
$type.innerHTML = this.typeList.map(item => {
const selected = item.value === this.type ? " selected" : "";
return `<option value="${item.value}"${selected}>${item.label}</option>`
}).join("");
const $base = this.element.querySelector(".cmm-manager-base");
$base.innerHTML = renderOptions(this.baseList, this.base);
$base.innerHTML = this.baseList.map(item => {
const selected = item.value === this.base ? " selected" : "";
return `<option value="${item.value}"${selected}>${item.label}</option>`
}).join("");
}
@@ -171,7 +399,7 @@ export class ModelManager {
".cmm-manager-stop": {
click: () => {
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
api.fetchApi('/manager/queue/reset');
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
@@ -200,7 +428,7 @@ export class ModelManager {
initGrid() {
const container = this.element.querySelector(".cmm-manager-grid");
const grid = new ManagerGrid(container);
const grid = new TG.Grid(container);
this.grid = grid;
grid.bind('onUpdated', (e, d) => {
@@ -228,9 +456,6 @@ export class ModelManager {
});
grid.setOption({
highlightKeywords: {
textGenerator: (row, column) => ['name', 'description'].includes(column) ? row[column] : escapeCell(row[column])
},
theme: 'dark',
selectVisible: true,
@@ -260,15 +485,7 @@ export class ModelManager {
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
if (shouldShown) {
if(this.filter == "installed" && rowItem.installed !== "True") {
return false;
}
if(this.filter == "not_installed" && rowItem.installed !== "False") {
return false;
}
if(this.filter == "in_workflow" && !app.graph._nodes.some(node => Array.isArray(node.widgets_values) && node.widgets_values.some(value => String(value).split(/[\\/]/).pop() === rowItem.filename))) {
if(this.filter && rowItem.installed !== this.filter) {
return false;
}
@@ -318,8 +535,7 @@ export class ModelManager {
maxWidth: 500,
classMap: 'cmm-node-name',
formatter: function(name, rowItem, columnItem, cellNode) {
// Names are server-escaped; raw references need URL and attribute handling.
return `<a href="${safeHref(rowItem.reference)}" target="_blank" rel="noopener noreferrer"><b>${name}</b></a>`;
return `<a href=${rowItem.reference} target="_blank"><b>${name}</b></a>`;
}
}, {
id: 'installed',
@@ -336,7 +552,7 @@ export class ModelManager {
if (installed === "True") {
return `<div class="cmm-icon-passed">${icons.passed}</div>`;
}
return `<button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`;
return `<button class="cmm-btn-install" mode="install">Install</button>`;
}
}, {
id: 'url',
@@ -345,7 +561,7 @@ export class ModelManager {
sortable: false,
align: 'center',
formatter: (url, rowItem, columnItem) => {
return `<a class="cmm-btn-download" title="Download file" href="${safeHref(url)}" target="_blank" rel="noopener noreferrer">${icons.download}</a>`;
return `<a class="cmm-btn-download" title="Download file" href="${url}" target="_blank">${icons.download}</a>`;
}
}, {
id: 'size',
@@ -353,21 +569,18 @@ export class ModelManager {
width: 100,
formatter: (size) => {
if (typeof size === "number") {
return formatSize(size);
return this.formatSize(size);
}
return size;
}
}, {
id: 'type',
name: 'Type',
width: 100,
formatter: escapeCell
width: 100
}, {
id: 'base',
name: 'Base',
formatter: escapeCell
name: 'Base'
}, {
// Descriptions are formatted HTML from the server.
id: 'description',
name: 'Description',
width: 400,
@@ -376,13 +589,11 @@ export class ModelManager {
}, {
id: "save_path",
name: 'Save Path',
width: 200,
formatter: escapeCell
width: 200
}, {
id: 'filename',
name: 'Filename',
width: 200,
formatter: escapeCell
width: 200
}];
restoreColumnWidth(gridId, columns);
@@ -414,7 +625,7 @@ export class ModelManager {
}
this.selectedModels = selectedList;
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`);
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install" mode="install">Install</button>`);
}
focusInstall(item) {
@@ -443,7 +654,7 @@ export class ModelManager {
let needRefresh = false;
let errorMsg = "";
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
await api.fetchApi('/manager/queue/reset');
let target_items = [];
@@ -457,7 +668,6 @@ export class ModelManager {
});
}
// Model names are already escaped by the server.
this.showStatus(`Install ${item.name} ...`);
const data = item.originalData;
@@ -465,7 +675,6 @@ export class ModelManager {
const res = await api.fetchApi(`/manager/queue/install_model`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
@@ -473,26 +682,16 @@ export class ModelManager {
errorMsg = `'${item.name}': `;
if(res.status == 403) {
try {
const data = await res.json();
if(data.error === 'comfyui_outdated') {
errorMsg += `ComfyUI version is outdated. Please update ComfyUI to use Manager normally.\n`;
} else {
errorMsg += `This action is not allowed with this security level configuration.\n`;
}
} catch {
errorMsg += `This action is not allowed with this security level configuration.\n`;
}
errorMsg += `This action is not allowed with this security level configuration.\n`;
} else {
errorMsg += sanitizeHTML(await res.text()) + '\n';
errorMsg += await res.text() + '\n';
}
break;
}
}
const context = {btn: btn, targets: target_items};
this.install_context = context;
this.install_context = {btn: btn, targets: target_items};
if(errorMsg) {
this.showError(errorMsg);
@@ -505,11 +704,8 @@ export class ModelManager {
}
}
else {
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// The queue can end before this request is answered.
if(this.install_context === context) {
this.showStop();
}
await api.fetchApi('/manager/queue/start');
this.showStop();
showTerminal();
}
}
@@ -529,36 +725,24 @@ export class ModelManager {
self.grid.updateRow(item);
}
else if(event.detail.status == 'done') {
self.hideStop();
self.onQueueCompleted(event.detail);
}
}
async onQueueCompleted(info) {
let result = info.model_result;
if(result.length == 0) {
return;
}
let self = ModelManager.instance;
if(!self.install_context) {
return;
}
// model_result is a dict (model hash -> outcome). A queue that ends
// without one, such as a node pack install, is not this install's
// while tasks are left. With none left, this install is over without
// a result, as after a refused request or a queue that was reset.
const ended_without_result = !result || Object.keys(result).length === 0;
if(ended_without_result) {
// Another install can start while the server is asked.
const context = self.install_context;
const stats = await (await api.fetchApi('/manager/queue/status')).json();
if(stats.total_count > stats.done_count || self.install_context !== context) {
return;
}
}
self.hideStop();
let btn = self.install_context.btn;
self.hideLoading();
@@ -569,9 +753,8 @@ export class ModelManager {
for(let hash in result){
let v = result[hash];
// Escape raw task errors for both HTML message destinations.
if(v != 'success')
errorMsg += sanitizeHTML(String(v)) + '\n';
errorMsg += v + '\n';
}
for(let k in self.install_context.targets) {
@@ -579,16 +762,11 @@ export class ModelManager {
self.grid.updateCell(item, "installed");
}
if(ended_without_result) {
self.install_context = undefined;
return;
}
if (errorMsg) {
self.showError(errorMsg);
show_message("Installation Error:\n"+errorMsg);
} else {
self.showStatus(`Install ${Object.keys(result).length} models successfully`);
self.showStatus(`Install ${result.length} models successfully`);
}
self.showRefresh();
@@ -605,7 +783,7 @@ export class ModelManager {
models.forEach((item, i) => {
const { type, base, name, reference, installed } = item;
item.originalData = JSON.parse(JSON.stringify(item));
item.size = sizeToBytes(item.size);
item.size = this.sizeToBytes(item.size);
item.hash = md5(name + reference);
item.id = i + 1;
@@ -682,6 +860,7 @@ export class ModelManager {
const { models } = res.data;
this.modelList = this.getModelList(models);
// console.log("models", this.modelList);
this.updateFilter();
@@ -693,7 +872,56 @@ export class ModelManager {
// ===========================================================================================
// Messages accept HTML; see createUIStateManager in common.js.
formatSize(v) {
const base = 1000;
const units = ['', 'K', 'M', 'G', 'T', 'P'];
const space = '';
const postfix = 'B';
if (v <= 0) {
return `0${space}${postfix}`;
}
for (let i = 0, l = units.length; i < l; i++) {
const min = Math.pow(base, i);
const max = Math.pow(base, i + 1);
if (v > min && v <= max) {
const unit = units[i];
if (unit) {
const n = v / min;
const nl = n.toString().split('.')[0].length;
const fl = Math.max(3 - nl, 1);
v = n.toFixed(fl);
}
v = v + space + unit + postfix;
break;
}
}
return v;
}
// for size sort
sizeToBytes(v) {
if (typeof v === "number") {
return v;
}
if (typeof v === "string") {
const n = parseFloat(v);
const unit = v.replace(/[0-9.B]+/g, "").trim().toUpperCase();
if (unit === "K") {
return n * 1000;
}
if (unit === "M") {
return n * 1000 * 1000;
}
if (unit === "G") {
return n * 1000 * 1000 * 1000;
}
if (unit === "T") {
return n * 1000 * 1000 * 1000 * 1000;
}
}
return v;
}
showSelection(msg) {
this.element.querySelector(".cmm-manager-selection").innerHTML = msg;
}
@@ -794,4 +1022,4 @@ export class ModelManager {
close() {
this.element.style.display = "none";
}
}
}
-699
View File
@@ -1,699 +0,0 @@
.nu-manager {
--grid-font: -apple-system, BlinkMacSystemFont, "Segue UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
z-index: 1099;
width: 80%;
height: 80%;
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg-color);
font-family: arial, sans-serif;
text-underline-offset: 3px;
outline: none;
}
.nu-manager .nu-flex-auto {
flex: auto;
}
.nu-manager button {
font-size: 16px;
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-radius: 8px;
border-color: var(--border-color);
border-style: solid;
margin: 0;
padding: 4px 8px;
min-width: 100px;
}
.nu-manager button:disabled,
.nu-manager input:disabled,
.nu-manager select:disabled {
color: gray;
}
.nu-manager button:disabled {
background-color: var(--comfy-input-bg);
}
.nu-manager .nu-manager-restart {
display: none;
background-color: #500000;
color: white;
}
.nu-manager .nu-manager-stop {
display: none;
background-color: #500000;
color: white;
}
.nu-manager .nu-manager-back {
align-items: center;
justify-content: center;
}
.arrow-icon {
height: 1em;
width: 1em;
margin-right: 5px;
transform: translateY(2px);
}
.cn-icon {
display: block;
width: 16px;
height: 16px;
}
.cn-icon svg {
display: block;
margin: 0;
pointer-events: none;
}
.nu-manager-header {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
padding: 0 5px;
}
.nu-manager-header label {
display: flex;
gap: 5px;
align-items: center;
}
.nu-manager-filter {
height: 28px;
line-height: 28px;
}
.nu-manager-keywords {
height: 28px;
line-height: 28px;
padding: 0 5px 0 26px;
background-size: 16px;
background-position: 5px center;
background-repeat: no-repeat;
background-image: url("data:image/svg+xml;charset=utf8,%3Csvg%20viewBox%3D%220%200%2024%2024%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20pointer-events%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20fill%3D%22none%22%20stroke%3D%22%23888%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%222%22%20d%3D%22m21%2021-4.486-4.494M19%2010.5a8.5%208.5%200%201%201-17%200%208.5%208.5%200%200%201%2017%200%22%2F%3E%3C%2Fsvg%3E");
}
.nu-manager-status {
padding-left: 10px;
}
.nu-manager-grid {
flex: auto;
border: 1px solid var(--border-color);
overflow: hidden;
position: relative;
}
.nu-manager-selection {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.nu-manager-message {
position: relative;
}
.nu-manager-footer {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.nu-manager-grid .tg-turbogrid {
font-family: var(--grid-font);
font-size: 15px;
background: var(--bg-color);
}
.nu-manager-grid .tg-turbogrid .tg-highlight::after {
position: absolute;
top: 0;
left: 0;
content: "";
display: block;
width: 100%;
height: 100%;
box-sizing: border-box;
background-color: #80bdff11;
pointer-events: none;
}
.nu-manager-grid .nu-pack-name a {
color: skyblue;
text-decoration: none;
word-break: break-word;
}
.nu-manager-grid .cn-pack-desc a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
.nu-manager-grid .tg-cell a:hover {
text-decoration: underline;
}
.nu-manager-grid .cn-pack-version {
line-height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
height: 100%;
gap: 5px;
}
.nu-manager-grid .cn-pack-nodes {
line-height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
gap: 5px;
cursor: pointer;
height: 100%;
}
.nu-manager-grid .cn-pack-nodes:hover {
text-decoration: underline;
}
.nu-manager-grid .cn-pack-conflicts {
color: orange;
}
.cn-popover {
position: fixed;
z-index: 10000;
padding: 20px;
color: #1e1e1e;
filter: drop-shadow(1px 5px 5px rgb(0 0 0 / 30%));
overflow: hidden;
}
.cn-flyover {
position: absolute;
top: 0;
right: 0;
z-index: 1000;
display: none;
width: 50%;
height: 100%;
background-color: var(--comfy-menu-bg);
animation-duration: 0.2s;
animation-fill-mode: both;
flex-direction: column;
}
.cn-flyover::before {
position: absolute;
top: 0;
content: "";
z-index: 10;
display: block;
width: 10px;
height: 100%;
pointer-events: none;
left: -10px;
background-image: linear-gradient(to left, rgb(0 0 0 / 20%), rgb(0 0 0 / 0%));
}
.cn-flyover-header {
height: 45px;
display: flex;
align-items: center;
gap: 5px;
border-bottom: 1px solid var(--border-color);
}
.cn-flyover-close {
display: flex;
align-items: center;
padding: 0 10px;
justify-content: center;
cursor: pointer;
opacity: 0.8;
height: 100%;
}
.cn-flyover-close:hover {
opacity: 1;
}
.cn-flyover-close svg {
display: block;
margin: 0;
pointer-events: none;
width: 20px;
height: 20px;
}
.cn-flyover-title {
display: flex;
align-items: center;
font-weight: bold;
gap: 10px;
flex: auto;
}
.cn-flyover-body {
height: calc(100% - 45px);
overflow-y: auto;
position: relative;
background-color: var(--comfy-menu-secondary-bg);
}
@keyframes cn-slide-in-right {
from {
visibility: visible;
transform: translate3d(100%, 0, 0);
}
to {
transform: translate3d(0, 0, 0);
}
}
.cn-slide-in-right {
animation-name: cn-slide-in-right;
}
@keyframes cn-slide-out-right {
from {
transform: translate3d(0, 0, 0);
}
to {
visibility: hidden;
transform: translate3d(100%, 0, 0);
}
}
.cn-slide-out-right {
animation-name: cn-slide-out-right;
}
.cn-nodes-list {
width: 100%;
}
.cn-nodes-row {
display: flex;
align-items: center;
gap: 10px;
}
.cn-nodes-row:nth-child(odd) {
background-color: rgb(0 0 0 / 5%);
}
.cn-nodes-row:hover {
background-color: rgb(0 0 0 / 10%);
}
.cn-nodes-sn {
text-align: right;
min-width: 35px;
color: var(--drag-text);
flex-shrink: 0;
font-size: 12px;
padding: 8px 5px;
}
.cn-nodes-name {
cursor: pointer;
white-space: nowrap;
flex-shrink: 0;
position: relative;
padding: 8px 5px;
}
.cn-nodes-name::after {
content: attr(action);
position: absolute;
pointer-events: none;
top: 50%;
left: 100%;
transform: translate(5px, -50%);
font-size: 12px;
color: var(--drag-text);
background-color: var(--comfy-input-bg);
border-radius: 10px;
border: 1px solid var(--border-color);
padding: 3px 8px;
display: none;
}
.cn-nodes-name.action::after {
display: block;
}
.cn-nodes-name:hover {
text-decoration: underline;
}
.cn-nodes-conflict .cn-nodes-name,
.cn-nodes-conflict .cn-icon {
color: orange;
}
.cn-conflicts-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
padding: 5px 0;
}
.cn-conflicts-list b {
font-weight: normal;
color: var(--descrip-text);
}
.cn-nodes-pack {
cursor: pointer;
color: skyblue;
}
.cn-nodes-pack:hover {
text-decoration: underline;
}
.cn-pack-badge {
font-size: 12px;
font-weight: normal;
background-color: var(--comfy-input-bg);
border-radius: 10px;
border: 1px solid var(--border-color);
padding: 3px 8px;
color: var(--error-text);
}
.cn-preview {
min-width: 300px;
max-width: 500px;
min-height: 120px;
overflow: hidden;
font-size: 12px;
pointer-events: none;
padding: 12px;
color: var(--fg-color);
}
.cn-preview-header {
display: flex;
gap: 8px;
align-items: center;
border-bottom: 1px solid var(--comfy-input-bg);
padding: 5px 10px;
}
.cn-preview-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: grey;
position: relative;
filter: drop-shadow(1px 2px 3px rgb(0 0 0 / 30%));
}
.cn-preview-dot.cn-preview-optional::after {
content: "";
position: absolute;
pointer-events: none;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: var(--comfy-input-bg);
border-radius: 50%;
width: 3px;
height: 3px;
}
.cn-preview-dot.cn-preview-grid {
border-radius: 0;
}
.cn-preview-dot.cn-preview-grid::before {
content: '';
position: absolute;
border-left: 1px solid var(--comfy-input-bg);
border-right: 1px solid var(--comfy-input-bg);
width: 4px;
height: 100%;
left: 2px;
top: 0;
z-index: 1;
}
.cn-preview-dot.cn-preview-grid::after {
content: '';
position: absolute;
border-top: 1px solid var(--comfy-input-bg);
border-bottom: 1px solid var(--comfy-input-bg);
width: 100%;
height: 4px;
left: 0;
top: 2px;
z-index: 1;
}
.cn-preview-name {
flex: auto;
font-size: 14px;
}
.cn-preview-io {
display: flex;
justify-content: space-between;
padding: 10px 10px;
}
.cn-preview-column > div {
display: flex;
gap: 10px;
align-items: center;
height: 18px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.cn-preview-input {
justify-content: flex-start;
}
.cn-preview-output {
justify-content: flex-end;
}
.cn-preview-list {
display: flex;
flex-direction: column;
gap: 3px;
padding: 0 10px 10px 10px;
}
.cn-preview-switch {
position: relative;
display: flex;
justify-content: space-between;
align-items: center;
background: var(--bg-color);
border: 2px solid var(--border-color);
border-radius: 10px;
text-wrap: nowrap;
padding: 2px 20px;
gap: 10px;
}
.cn-preview-switch::before,
.cn-preview-switch::after {
position: absolute;
pointer-events: none;
top: 50%;
transform: translate(0, -50%);
color: var(--fg-color);
opacity: 0.8;
}
.cn-preview-switch::before {
content: "◀";
left: 5px;
}
.cn-preview-switch::after {
content: "▶";
right: 5px;
}
.cn-preview-value {
color: var(--descrip-text);
}
.cn-preview-string {
min-height: 30px;
max-height: 300px;
background: var(--bg-color);
color: var(--descrip-text);
border-radius: 3px;
padding: 3px 5px;
overflow-y: auto;
overflow-x: hidden;
}
.cn-preview-description {
margin: 0px 10px 10px 10px;
padding: 6px;
background: var(--border-color);
color: var(--descrip-text);
border-radius: 5px;
font-style: italic;
word-break: break-word;
}
.cn-tag-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
margin-bottom: 5px;
}
.cn-tag-list > div {
background-color: var(--border-color);
border-radius: 5px;
padding: 0 5px;
}
.cn-install-buttons {
display: flex;
flex-direction: column;
gap: 3px;
padding: 3px;
align-items: center;
justify-content: center;
height: 100%;
}
.cn-selected-buttons {
display: flex;
gap: 5px;
align-items: center;
padding-right: 20px;
}
.nu-manager .cn-btn-enable {
background-color: #333399;
color: white;
}
.nu-manager .cn-btn-disable {
background-color: #442277;
color: white;
}
.nu-manager .cn-btn-update {
background-color: #1155AA;
color: white;
}
.nu-manager .cn-btn-try-update {
background-color: Gray;
color: white;
}
.nu-manager .cn-btn-try-fix {
background-color: #6495ED;
color: white;
}
.nu-manager .cn-btn-import-failed {
background-color: #AA1111;
font-size: 10px;
font-weight: bold;
color: white;
}
.nu-manager .cn-btn-install {
background-color: black;
color: white;
}
.nu-manager .cn-btn-try-install {
background-color: Gray;
color: white;
}
.nu-manager .cn-btn-uninstall {
background-color: #993333;
color: white;
}
.nu-manager .cn-btn-reinstall {
background-color: #993333;
color: white;
}
.nu-manager .cn-btn-switch {
background-color: #448833;
color: white;
}
@keyframes nu-btn-loading-bg {
0% {
left: 0;
}
100% {
left: -105px;
}
}
.nu-manager button.nu-btn-loading {
position: relative;
overflow: hidden;
border-color: rgb(0 119 207 / 80%);
background-color: var(--comfy-input-bg);
}
.nu-manager button.nu-btn-loading::after {
position: absolute;
top: 0;
left: 0;
content: "";
width: 500px;
height: 100%;
background-image: repeating-linear-gradient(
-45deg,
rgb(0 119 207 / 30%),
rgb(0 119 207 / 30%) 10px,
transparent 10px,
transparent 15px
);
animation: nu-btn-loading-bg 2s linear infinite;
}
.nu-manager-light .nu-pack-name a {
color: blue;
}
.nu-manager-light .cm-warn-note {
background-color: #ccc !important;
}
.nu-manager-light .cn-btn-install {
background-color: #333;
}
-751
View File
@@ -1,751 +0,0 @@
import { app } from "../../scripts/app.js";
import { $el } from "../../scripts/ui.js";
import {
manager_instance,
fetchData, md5, show_message, customAlert, infoToast, showTerminal,
storeColumnWidth, restoreColumnWidth, loadCss, uninstallNodes,
analyzeWorkflowUsage, sizeToBytes, createFlyover, createUIStateManager,
sanitizeHTML, safeHref
} from "./common.js";
import { api } from "../../scripts/api.js";
// https://cenfun.github.io/turbogrid/api.html
import TG from "./turbogrid.esm.js";
loadCss("./node-usage-analyzer.css");
const gridId = "model";
const pageHtml = `
<div class="nu-manager-header">
<div class="nu-manager-status"></div>
<input type="text" class="nu-manager-keywords" placeholder="Filter keywords..." />
<div class="nu-flex-auto"></div>
</div>
<div class="nu-manager-grid"></div>
<div class="nu-manager-selection"></div>
<div class="nu-manager-message"></div>
<div class="nu-manager-footer">
<button class="nu-manager-back">
<svg class="arrow-icon" width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2 8H18M2 8L8 2M2 8L8 14" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
Back
</button>
<button class="nu-manager-refresh">Refresh</button>
<button class="nu-manager-stop">Stop</button>
<div class="nu-flex-auto"></div>
</div>
`;
export class NodeUsageAnalyzer {
static instance = null;
static SortMode = {
BY_PACKAGE: 'by_package'
};
constructor(app, manager_dialog) {
this.app = app;
this.manager_dialog = manager_dialog;
this.id = "nu-manager";
this.filter = '';
this.type = '';
this.base = '';
this.keywords = '';
this.init();
// Initialize shared UI state manager
this.ui = createUIStateManager(this.element, {
selection: ".nu-manager-selection",
message: ".nu-manager-message",
status: ".nu-manager-status",
refresh: ".nu-manager-refresh",
stop: ".nu-manager-stop"
});
api.addEventListener("cm-queue-status", this.onQueueStatus);
}
init() {
this.element = $el("div", {
parent: document.body,
className: "comfy-modal nu-manager"
});
this.element.innerHTML = pageHtml;
this.bindEvents();
this.initGrid();
}
bindEvents() {
const eventsMap = {
".nu-manager-selection": {
click: (e) => {
const target = e.target;
const mode = target.getAttribute("mode");
if (mode === "install") {
this.installModels(this.selectedModels, target);
} else if (mode === "uninstall") {
this.uninstallModels(this.selectedModels, target);
}
}
},
".nu-manager-refresh": {
click: () => {
app.refreshComboInNodes();
}
},
".nu-manager-stop": {
click: () => {
api.fetchApi('/manager/queue/reset');
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
".nu-manager-back": {
click: (e) => {
this.close()
manager_instance.show();
}
}
};
Object.keys(eventsMap).forEach(selector => {
const target = this.element.querySelector(selector);
if (target) {
const events = eventsMap[selector];
if (events) {
Object.keys(events).forEach(type => {
target.addEventListener(type, events[type]);
});
}
}
});
}
// ===========================================================================================
initGrid() {
const container = this.element.querySelector(".nu-manager-grid");
const grid = new TG.Grid(container);
this.grid = grid;
this.flyover = createFlyover(container, { context: this });
grid.bind('onUpdated', (e, d) => {
this.ui.showStatus(`${grid.viewRows.length.toLocaleString()} installed packages`);
});
grid.bind('onSelectChanged', (e, changes) => {
this.renderSelected();
});
grid.bind("onColumnWidthChanged", (e, columnItem) => {
storeColumnWidth(gridId, columnItem)
});
grid.bind('onClick', (e, d) => {
const { rowItem } = d;
const target = d.e.target;
const mode = target.getAttribute("mode");
if (mode === "install") {
this.installModels([rowItem], target);
return;
}
if (mode === "uninstall") {
this.uninstallModels([rowItem], target);
return;
}
// Handle click on usage count
if (d.columnItem.id === "used_in_count" && rowItem.used_in_count > 0) {
this.showUsageDetails(rowItem);
return;
}
});
grid.setOption({
theme: 'dark',
selectVisible: true,
selectMultiple: true,
selectAllVisible: true,
textSelectable: true,
scrollbarRound: true,
frozenColumn: 1,
rowNotFound: "No Results",
rowHeight: 40,
bindWindowResize: true,
bindContainerResize: true,
cellResizeObserver: (rowItem, columnItem) => {
const autoHeightColumns = ['name', 'description'];
return autoHeightColumns.includes(columnItem.id)
}
});
}
renderGrid() {
// update theme
const colorPalette = this.app.ui.settings.settingsValues['Comfy.ColorPalette'];
Array.from(this.element.classList).forEach(cn => {
if (cn.startsWith("nu-manager-")) {
this.element.classList.remove(cn);
}
});
this.element.classList.add(`nu-manager-${colorPalette}`);
const options = {
theme: colorPalette === "light" ? "" : "dark"
};
const rows = this.modelList || [];
const columns = [{
id: 'title',
name: 'Title',
width: 200,
minWidth: 100,
maxWidth: 500,
classMap: 'nu-pack-name',
formatter: function (name, rowItem, columnItem, cellNode) {
// Names are escaped during loadData; references need URL and attribute handling.
return `<a href="${safeHref(rowItem.reference)}" target="_blank" rel="noopener noreferrer"><b>${name}</b></a>`;
}
}, {
id: 'used_in_count',
name: 'Used in',
width: 100,
formatter: function (usedCount, rowItem, columnItem) {
if (!usedCount || usedCount === 0) {
return '0';
}
const plural = usedCount > 1 ? 's' : '';
return `<div class="cn-pack-nodes" style="cursor: pointer;">${usedCount} workflow${plural}</div>`;
}
}, {
id: 'action',
name: 'Action',
width: 160,
minWidth: 140,
maxWidth: 200,
sortable: false,
align: 'center',
formatter: function (action, rowItem, columnItem) {
// Only show uninstall button for installed packages
if (rowItem.originalData && rowItem.originalData.state && rowItem.originalData.state !== "not-installed") {
return `<div class="cn-install-buttons"><button class="nu-btn-uninstall" mode="uninstall">Uninstall</button></div>`;
}
return '';
}
}];
restoreColumnWidth(gridId, columns);
this.grid.setData({
options,
rows,
columns
});
this.grid.render();
}
updateGrid() {
if (this.grid) {
this.grid.update();
}
}
showUsageDetails(rowItem) {
const workflowList = rowItem.workflowDetails;
if (!workflowList || workflowList.length === 0) {
return;
}
let titleHtml = `<div class="cn-nodes-pack">${rowItem.title}</div>`;
const list = [];
list.push(`<div class="cn-nodes-list">`);
workflowList.forEach((workflow, i) => {
list.push(`<div class="cn-nodes-row">`);
list.push(`<div class="cn-nodes-sn">${i + 1}</div>`);
// Workflow filenames are raw server data.
list.push(`<div class="cn-nodes-name">${sanitizeHTML(String(workflow.filename))}</div>`);
list.push(`<div class="cn-nodes-details">${workflow.nodeCount} node${workflow.nodeCount > 1 ? 's' : ''}</div>`);
list.push(`</div>`);
});
list.push("</div>");
const bodyHtml = list.join("");
this.flyover.show(titleHtml, bodyHtml);
}
renderSelected() {
const selectedList = this.grid.getSelectedRows();
if (!selectedList.length) {
this.ui.showSelection("");
return;
}
const installedSelected = selectedList.filter(item =>
item.originalData && item.originalData.state && item.originalData.state !== "not-installed"
);
if (installedSelected.length === 0) {
this.ui.showSelection(`<span>Selected <b>${selectedList.length}</b> packages (none can be uninstalled)</span>`);
return;
}
this.selectedModels = installedSelected;
this.ui.showSelection(`
<div class="nu-selected-buttons">
<span>Selected <b>${installedSelected.length}</b> installed packages</span>
<button class="nu-btn-uninstall" mode="uninstall">Uninstall Selected</button>
</div>
`);
}
// ===========================================================================================
async installModels(list, btn) {
let stats = await api.fetchApi('/manager/queue/status');
stats = await stats.json();
if (stats.is_processing) {
customAlert(`[ComfyUI-Manager] There are already tasks in progress. Please try again after it is completed. (${stats.done_count}/${stats.total_count})`);
return;
}
btn.classList.add("nu-btn-loading");
this.ui.showError("");
let needRefresh = false;
let errorMsg = "";
await api.fetchApi('/manager/queue/reset');
let target_items = [];
for (const item of list) {
this.grid.scrollRowIntoView(item);
target_items.push(item);
// Here item.name is a raw pack key, not a server-escaped title.
this.ui.showStatus(`Install ${sanitizeHTML(String(item.name))} ...`);
const data = item.originalData;
data.ui_id = item.hash;
const res = await api.fetchApi(`/manager/queue/install_model`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (res.status != 200) {
// Escape raw task errors for both HTML message destinations.
errorMsg = `'${sanitizeHTML(String(item.name))}': `;
if (res.status == 403) {
errorMsg += `This action is not allowed with this security level configuration.\n`;
} else {
errorMsg += sanitizeHTML(await res.text()) + '\n';
}
break;
}
}
this.install_context = { btn: btn, targets: target_items };
if (errorMsg) {
this.ui.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 {
await api.fetchApi('/manager/queue/start');
this.ui.showStop();
showTerminal();
}
}
async uninstallModels(list, btn) {
btn.classList.add("nu-btn-loading");
this.ui.showError("");
const result = await uninstallNodes(list, {
title: list.length === 1 ? list[0].title || list[0].name : `${list.length} custom nodes`,
channel: 'default',
mode: 'default',
onProgress: (msg) => {
this.showStatus(msg);
},
onError: (errorMsg) => {
this.showError(errorMsg);
},
onSuccess: (targets) => {
this.showStatus(`Uninstalled ${targets.length} custom node(s) successfully`);
this.showMessage(`To apply the uninstalled custom nodes, please restart ComfyUI and refresh browser.`, "red");
// Update the grid to reflect changes
for (let item of targets) {
if (item.originalData) {
item.originalData.state = "not-installed";
}
this.grid.updateRow(item);
}
}
});
if (result.success) {
this.showStop();
}
btn.classList.remove("nu-btn-loading");
}
async onQueueStatus(event) {
let self = NodeUsageAnalyzer.instance;
if (event.detail.status == 'in_progress' && (event.detail.ui_target == 'model_manager' || event.detail.ui_target == 'nodepack_manager')) {
const hash = event.detail.target;
const item = self.grid.getRowItemBy("hash", hash);
if (item) {
item.refresh = true;
self.grid.setRowSelected(item, false);
item.selectable = false;
self.grid.updateRow(item);
}
}
else if (event.detail.status == 'done') {
self.hideStop();
self.onQueueCompleted(event.detail);
}
}
async onQueueCompleted(info) {
let result = info.model_result || info.nodepack_result;
if (!result || result.length == 0) {
return;
}
let self = NodeUsageAnalyzer.instance;
if (!self.install_context) {
return;
}
let btn = self.install_context.btn;
self.hideLoading();
btn.classList.remove("nu-btn-loading");
let errorMsg = "";
for (let hash in result) {
let v = result[hash];
// Escape raw task errors for both HTML message destinations.
if (v != 'success' && v != 'skip')
errorMsg += sanitizeHTML(String(v)) + '\n';
}
for (let k in self.install_context.targets) {
let item = self.install_context.targets[k];
if (info.model_result) {
self.grid.updateCell(item, "installed");
} else if (info.nodepack_result) {
// Handle uninstall completion
if (item.originalData) {
item.originalData.state = "not-installed";
}
self.grid.updateRow(item);
}
}
if (errorMsg) {
self.showError(errorMsg);
show_message("Operation Error:\n" + errorMsg);
} else {
if (info.model_result) {
self.showStatus(`Install ${Object.keys(result).length} models successfully`);
self.showRefresh();
self.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red");
} else if (info.nodepack_result) {
self.showStatus(`Uninstall ${Object.keys(result).length} custom node(s) successfully`);
self.showMessage(`To apply the uninstalled custom nodes, please restart ComfyUI and refresh browser.`, "red");
}
}
infoToast('Tasks done', `[ComfyUI-Manager] All tasks in the queue have been completed.\n${info.done_count}/${info.total_count}`);
self.install_context = undefined;
}
getModelList(models) {
const typeMap = new Map();
const baseMap = new Map();
models.forEach((item, i) => {
const { type, base, name, reference, installed } = item;
// CRITICAL FIX: Do NOT overwrite originalData - it contains the needed state field!
item.size = sizeToBytes(item.size);
item.hash = md5(name + reference);
if (installed === "True") {
item.selectable = false;
}
typeMap.set(type, type);
baseMap.set(base, base);
});
const typeList = [];
typeMap.forEach(type => {
typeList.push({
label: type,
value: type
});
});
typeList.sort((a, b) => {
const au = a.label.toUpperCase();
const bu = b.label.toUpperCase();
if (au !== bu) {
return au > bu ? 1 : -1;
}
return 0;
});
this.typeList = [{
label: "All",
value: ""
}].concat(typeList);
const baseList = [];
baseMap.forEach(base => {
baseList.push({
label: base,
value: base
});
});
baseList.sort((a, b) => {
const au = a.label.toUpperCase();
const bu = b.label.toUpperCase();
if (au !== bu) {
return au > bu ? 1 : -1;
}
return 0;
});
this.baseList = [{
label: "All",
value: ""
}].concat(baseList);
return models;
}
// ===========================================================================================
async loadData() {
this.showLoading();
this.showStatus(`Analyzing node usage ...`);
const mode = manager_instance.datasrc_combo.value;
const nodeListRes = await fetchData(`/customnode/getlist?mode=${mode}&skip_update=true`);
if (nodeListRes.error) {
this.showError("Failed to get custom node list.");
this.hideLoading();
return;
}
const { channel, node_packs } = nodeListRes.data;
delete node_packs['comfyui-manager'];
this.installed_custom_node_packs = node_packs;
// Use the consolidated workflow analysis utility
const result = await analyzeWorkflowUsage(node_packs);
if (!result.success) {
if (result.error.toString().includes('204')) {
this.showMessage("No workflows were found for analysis.");
} else {
this.showError(sanitizeHTML(String(result.error)));
this.hideLoading();
return;
}
}
// Transform node_packs into models format - ONLY INSTALLED PACKAGES
const models = [];
Object.keys(node_packs).forEach((packKey, index) => {
const pack = node_packs[packKey];
// Only include installed packages (filter out "not-installed" packages)
if (pack.state === "not-installed") {
return; // Skip non-installed packages
}
const usedCount = result.usageMap?.get(packKey) || 0;
const workflowDetails = result.workflowDetailsMap?.get(packKey) || [];
models.push({
// Preserve server-escaped titles; escape only the raw pack-key fallback.
title: pack.title || sanitizeHTML(String(packKey)),
reference: pack.reference || pack.files?.[0] || '#',
used_in_count: usedCount,
workflowDetails: workflowDetails,
name: packKey,
originalData: pack
});
});
// Sort by usage count (descending) then by title
models.sort((a, b) => {
if (b.used_in_count !== a.used_in_count) {
return b.used_in_count - a.used_in_count;
}
return a.title.localeCompare(b.title);
});
this.modelList = this.getModelList(models);
this.renderGrid();
this.hideLoading();
}
// ===========================================================================================
// Messages accept HTML; see createUIStateManager in common.js.
showSelection(msg) {
this.element.querySelector(".nu-manager-selection").innerHTML = msg;
}
showError(err) {
this.showMessage(err, "red");
}
showMessage(msg, color) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
this.element.querySelector(".nu-manager-message").innerHTML = msg;
}
showStatus(msg, color) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
this.element.querySelector(".nu-manager-status").innerHTML = msg;
}
showLoading() {
// this.setDisabled(true);
if (this.grid) {
this.grid.showLoading();
this.grid.showMask({
opacity: 0.05
});
}
}
hideLoading() {
// this.setDisabled(false);
if (this.grid) {
this.grid.hideLoading();
this.grid.hideMask();
}
}
setDisabled(disabled) {
const $close = this.element.querySelector(".nu-manager-close");
const $refresh = this.element.querySelector(".nu-manager-refresh");
const $stop = this.element.querySelector(".nu-manager-stop");
const list = [
".nu-manager-header input",
".nu-manager-header select",
".nu-manager-footer button",
".nu-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(".nu-btn-loading")).forEach($elem => {
$elem.classList.remove("nu-btn-loading");
});
}
showRefresh() {
this.element.querySelector(".nu-manager-refresh").style.display = "block";
}
showStop() {
this.element.querySelector(".nu-manager-stop").style.display = "block";
}
hideStop() {
this.element.querySelector(".nu-manager-stop").style.display = "none";
}
setKeywords(keywords = "") {
this.keywords = keywords;
this.element.querySelector(".nu-manager-keywords").value = keywords;
}
show(sortMode) {
this.element.style.display = "flex";
this.setKeywords("");
this.showSelection("");
this.showMessage("");
this.loadData();
}
close() {
this.element.style.display = "none";
}
}
+6 -26
View File
@@ -92,9 +92,6 @@ 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];
@@ -103,19 +100,9 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
dest.convertWidgetToInput(destWidget);
}
if(input.link) {
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);
}
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);
}
}
@@ -127,7 +114,7 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
if(output.links) {
let links = [];
for(let j in output.links) {
links.push(graph.links[output.links[j]]);
links.push(app.graph.links[output.links[j]]);
}
output_links[output.name] = links;
}
@@ -138,14 +125,8 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
if(links) {
for(let j in links) {
let link = links[j];
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);
}
let target_node = app.graph.getNodeById(link.target_id);
dest.connect(parseInt(i), target_node, link.target_slot);
}
}
}
@@ -172,7 +153,6 @@ app.registerExtension({
app.canvas.graph.add(new_node, false);
node_info_copy(this, new_node, true);
app.canvas.graph.remove(this);
requestAnimationFrame(() => app.canvas.setDirty(true, true))
},
});
});
-619
View File
@@ -1,619 +0,0 @@
const hasOwn = function(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
};
const isNum = function(num) {
if (typeof num !== 'number' || isNaN(num)) {
return false;
}
const isInvalid = function(n) {
if (n === Number.MAX_VALUE || n === Number.MIN_VALUE || n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY) {
return true;
}
return false;
};
if (isInvalid(num)) {
return false;
}
return true;
};
const toNum = (num) => {
if (typeof (num) !== 'number') {
num = parseFloat(num);
}
if (isNaN(num)) {
num = 0;
}
num = Math.round(num);
return num;
};
const clamp = function(value, min, max) {
return Math.max(min, Math.min(max, value));
};
const isWindow = (obj) => {
return Boolean(obj && obj === obj.window);
};
const isDocument = (obj) => {
return Boolean(obj && obj.nodeType === 9);
};
const isElement = (obj) => {
return Boolean(obj && obj.nodeType === 1);
};
// ===========================================================================================
export const toRect = (obj) => {
if (obj) {
return {
left: toNum(obj.left || obj.x),
top: toNum(obj.top || obj.y),
width: toNum(obj.width),
height: toNum(obj.height)
};
}
return {
left: 0,
top: 0,
width: 0,
height: 0
};
};
export const getElement = (selector) => {
if (typeof selector === 'string' && selector) {
if (selector.startsWith('#')) {
return document.getElementById(selector.slice(1));
}
return document.querySelector(selector);
}
if (isDocument(selector)) {
return selector.body;
}
if (isElement(selector)) {
return selector;
}
};
export const getRect = (target, fixed) => {
if (!target) {
return toRect();
}
if (isWindow(target)) {
return {
left: 0,
top: 0,
width: window.innerWidth,
height: window.innerHeight
};
}
const elem = getElement(target);
if (!elem) {
return toRect(target);
}
const br = elem.getBoundingClientRect();
const rect = toRect(br);
// fix offset
if (!fixed) {
rect.left += window.scrollX;
rect.top += window.scrollY;
}
rect.width = elem.offsetWidth;
rect.height = elem.offsetHeight;
return rect;
};
// ===========================================================================================
const calculators = {
bottom: (info, containerRect, targetRect) => {
info.space = containerRect.top + containerRect.height - targetRect.top - targetRect.height - info.height;
info.top = targetRect.top + targetRect.height;
info.left = Math.round(targetRect.left + targetRect.width * 0.5 - info.width * 0.5);
},
top: (info, containerRect, targetRect) => {
info.space = targetRect.top - info.height - containerRect.top;
info.top = targetRect.top - info.height;
info.left = Math.round(targetRect.left + targetRect.width * 0.5 - info.width * 0.5);
},
right: (info, containerRect, targetRect) => {
info.space = containerRect.left + containerRect.width - targetRect.left - targetRect.width - info.width;
info.top = Math.round(targetRect.top + targetRect.height * 0.5 - info.height * 0.5);
info.left = targetRect.left + targetRect.width;
},
left: (info, containerRect, targetRect) => {
info.space = targetRect.left - info.width - containerRect.left;
info.top = Math.round(targetRect.top + targetRect.height * 0.5 - info.height * 0.5);
info.left = targetRect.left - info.width;
}
};
// with order
export const getDefaultPositions = () => {
return Object.keys(calculators);
};
const calculateSpace = (info, containerRect, targetRect) => {
const calculator = calculators[info.position];
calculator(info, containerRect, targetRect);
if (info.space >= 0) {
info.passed += 1;
}
};
// ===========================================================================================
const calculateAlignOffset = (info, containerRect, targetRect, alignType, sizeType) => {
const popoverStart = info[alignType];
const popoverSize = info[sizeType];
const containerStart = containerRect[alignType];
const containerSize = containerRect[sizeType];
const targetStart = targetRect[alignType];
const targetSize = targetRect[sizeType];
const targetCenter = targetStart + targetSize * 0.5;
// size overflow
if (popoverSize > containerSize) {
const overflow = (popoverSize - containerSize) * 0.5;
info[alignType] = containerStart - overflow;
info.offset = targetCenter - containerStart + overflow;
return;
}
const space1 = popoverStart - containerStart;
const space2 = (containerStart + containerSize) - (popoverStart + popoverSize);
// both side passed, default to center
if (space1 >= 0 && space2 >= 0) {
if (info.passed) {
info.passed += 2;
}
info.offset = popoverSize * 0.5;
return;
}
// one side passed
if (info.passed) {
info.passed += 1;
}
if (space1 < 0) {
const min = containerStart;
info[alignType] = min;
info.offset = targetCenter - min;
return;
}
// space2 < 0
const max = containerStart + containerSize - popoverSize;
info[alignType] = max;
info.offset = targetCenter - max;
};
const calculateHV = (info, containerRect) => {
if (['top', 'bottom'].includes(info.position)) {
info.top = clamp(info.top, containerRect.top, containerRect.top + containerRect.height - info.height);
return ['left', 'width'];
}
info.left = clamp(info.left, containerRect.left, containerRect.left + containerRect.width - info.width);
return ['top', 'height'];
};
const calculateOffset = (info, containerRect, targetRect) => {
const [alignType, sizeType] = calculateHV(info, containerRect);
calculateAlignOffset(info, containerRect, targetRect, alignType, sizeType);
info.offset = clamp(info.offset, 0, info[sizeType]);
};
// ===========================================================================================
const calculateDistance = (info, previousPositionInfo) => {
if (!previousPositionInfo) {
return;
}
// no change if position no change with previous
if (info.position === previousPositionInfo.position) {
return;
}
const ax = info.left + info.width * 0.5;
const ay = info.top + info.height * 0.5;
const bx = previousPositionInfo.left + previousPositionInfo.width * 0.5;
const by = previousPositionInfo.top + previousPositionInfo.height * 0.5;
const dx = Math.abs(ax - bx);
const dy = Math.abs(ay - by);
info.distance = Math.round(Math.sqrt(dx * dx + dy * dy));
};
// ===========================================================================================
const calculatePositionInfo = (info, containerRect, targetRect, previousPositionInfo) => {
calculateSpace(info, containerRect, targetRect);
calculateOffset(info, containerRect, targetRect);
calculateDistance(info, previousPositionInfo);
};
// ===========================================================================================
const calculateBestPosition = (containerRect, targetRect, infoMap, withOrder, previousPositionInfo) => {
// position space: +1
// align space:
// two side passed: +2
// one side passed: +1
const safePassed = 3;
if (previousPositionInfo) {
const prevInfo = infoMap[previousPositionInfo.position];
if (prevInfo) {
calculatePositionInfo(prevInfo, containerRect, targetRect);
if (prevInfo.passed >= safePassed) {
return prevInfo;
}
prevInfo.calculated = true;
}
}
const positionList = [];
Object.values(infoMap).forEach((info) => {
if (!info.calculated) {
calculatePositionInfo(info, containerRect, targetRect, previousPositionInfo);
}
positionList.push(info);
});
positionList.sort((a, b) => {
if (a.passed !== b.passed) {
return b.passed - a.passed;
}
if (withOrder && a.passed >= safePassed && b.passed >= safePassed) {
return a.index - b.index;
}
if (a.space !== b.space) {
return b.space - a.space;
}
return a.index - b.index;
});
// logTable(positionList);
return positionList[0];
};
// const logTable = (() => {
// let time_id;
// return (info) => {
// clearTimeout(time_id);
// time_id = setTimeout(() => {
// console.table(info);
// }, 10);
// };
// })();
// ===========================================================================================
const getAllowPositions = (positions, defaultAllowPositions) => {
if (!positions) {
return;
}
if (Array.isArray(positions)) {
positions = positions.join(',');
}
positions = String(positions).split(',').map((it) => it.trim().toLowerCase()).filter((it) => it);
positions = positions.filter((it) => defaultAllowPositions.includes(it));
if (!positions.length) {
return;
}
return positions;
};
const isPositionChanged = (info, previousPositionInfo) => {
if (!previousPositionInfo) {
return true;
}
if (info.left !== previousPositionInfo.left) {
return true;
}
if (info.top !== previousPositionInfo.top) {
return true;
}
return false;
};
// ===========================================================================================
// const log = (name, time) => {
// if (time > 0.1) {
// console.log(name, time);
// }
// };
export const getBestPosition = (containerRect, targetRect, popoverRect, positions, previousPositionInfo) => {
const defaultAllowPositions = getDefaultPositions();
let withOrder = true;
let allowPositions = getAllowPositions(positions, defaultAllowPositions);
if (!allowPositions) {
allowPositions = defaultAllowPositions;
withOrder = false;
}
// console.log('withOrder', withOrder);
// const start_time = performance.now();
const infoMap = {};
allowPositions.forEach((k, i) => {
infoMap[k] = {
position: k,
index: i,
top: 0,
left: 0,
width: popoverRect.width,
height: popoverRect.height,
space: 0,
offset: 0,
passed: 0,
distance: 0
};
});
// log('infoMap', performance.now() - start_time);
const bestPosition = calculateBestPosition(containerRect, targetRect, infoMap, withOrder, previousPositionInfo);
// check left/top
bestPosition.changed = isPositionChanged(bestPosition, previousPositionInfo);
return bestPosition;
};
// ===========================================================================================
const getTemplatePath = (width, height, arrowOffset, arrowSize, borderRadius) => {
const p = (px, py) => {
return [px, py].join(',');
};
const px = function(num, alignEnd) {
const floor = Math.floor(num);
let n = num < floor + 0.5 ? floor + 0.5 : floor + 1.5;
if (alignEnd) {
n -= 1;
}
return n;
};
const pxe = function(num) {
return px(num, true);
};
const ls = [];
const innerLeft = px(arrowSize);
const innerRight = pxe(width - arrowSize);
arrowOffset = clamp(arrowOffset, innerLeft, innerRight);
const innerTop = px(arrowSize);
const innerBottom = pxe(height - arrowSize);
const startPoint = p(innerLeft, innerTop + borderRadius);
const arrowPoint = p(arrowOffset, 1);
const LT = p(innerLeft, innerTop);
const RT = p(innerRight, innerTop);
const AOT = p(arrowOffset - arrowSize, innerTop);
const RRT = p(innerRight - borderRadius, innerTop);
ls.push(`M${startPoint}`);
ls.push(`V${innerBottom - borderRadius}`);
ls.push(`Q${p(innerLeft, innerBottom)} ${p(innerLeft + borderRadius, innerBottom)}`);
ls.push(`H${innerRight - borderRadius}`);
ls.push(`Q${p(innerRight, innerBottom)} ${p(innerRight, innerBottom - borderRadius)}`);
ls.push(`V${innerTop + borderRadius}`);
if (arrowOffset < innerLeft + arrowSize + borderRadius) {
ls.push(`Q${RT} ${RRT}`);
ls.push(`H${arrowOffset + arrowSize}`);
ls.push(`L${arrowPoint}`);
if (arrowOffset < innerLeft + arrowSize) {
ls.push(`L${LT}`);
ls.push(`L${startPoint}`);
} else {
ls.push(`L${AOT}`);
ls.push(`Q${LT} ${startPoint}`);
}
} else if (arrowOffset > innerRight - arrowSize - borderRadius) {
if (arrowOffset > innerRight - arrowSize) {
ls.push(`L${RT}`);
} else {
ls.push(`Q${RT} ${p(arrowOffset + arrowSize, innerTop)}`);
}
ls.push(`L${arrowPoint}`);
ls.push(`L${AOT}`);
ls.push(`H${innerLeft + borderRadius}`);
ls.push(`Q${LT} ${startPoint}`);
} else {
ls.push(`Q${RT} ${RRT}`);
ls.push(`H${arrowOffset + arrowSize}`);
ls.push(`L${arrowPoint}`);
ls.push(`L${AOT}`);
ls.push(`H${innerLeft + borderRadius}`);
ls.push(`Q${LT} ${startPoint}`);
}
return ls.join('');
};
const getPathData = function(position, width, height, arrowOffset, arrowSize, borderRadius) {
const handlers = {
bottom: () => {
const d = getTemplatePath(width, height, arrowOffset, arrowSize, borderRadius);
return {
d,
transform: ''
};
},
top: () => {
const d = getTemplatePath(width, height, width - arrowOffset, arrowSize, borderRadius);
return {
d,
transform: `rotate(180,${width * 0.5},${height * 0.5})`
};
},
left: () => {
const d = getTemplatePath(height, width, arrowOffset, arrowSize, borderRadius);
const x = (width - height) * 0.5;
const y = (height - width) * 0.5;
return {
d,
transform: `translate(${x} ${y}) rotate(90,${height * 0.5},${width * 0.5})`
};
},
right: () => {
const d = getTemplatePath(height, width, height - arrowOffset, arrowSize, borderRadius);
const x = (width - height) * 0.5;
const y = (height - width) * 0.5;
return {
d,
transform: `translate(${x} ${y}) rotate(-90,${height * 0.5},${width * 0.5})`
};
}
};
return handlers[position]();
};
// ===========================================================================================
// position style cache
const styleCache = {
// position: '',
// top: {},
// bottom: {},
// left: {},
// right: {}
};
export const getPositionStyle = (info, options = {}) => {
const o = {
bgColor: '#fff',
borderColor: '#ccc',
borderRadius: 5,
arrowSize: 10
};
Object.keys(o).forEach((k) => {
if (hasOwn(options, k)) {
const d = o[k];
const v = options[k];
if (typeof d === 'string') {
// string
if (typeof v === 'string' && v) {
o[k] = v;
}
} else {
// number
if (isNum(v) && v >= 0) {
o[k] = v;
}
}
}
});
const key = [
info.width,
info.height,
info.offset,
o.arrowSize,
o.borderRadius,
o.bgColor,
o.borderColor
].join('-');
const positionCache = styleCache[info.position];
if (positionCache && key === positionCache.key) {
const st = positionCache.style;
st.changed = styleCache.position !== info.position;
styleCache.position = info.position;
return st;
}
// console.log(options);
const data = getPathData(info.position, info.width, info.height, info.offset, o.arrowSize, o.borderRadius);
// console.log(data);
const viewBox = [0, 0, info.width, info.height].join(' ');
const svg = [
`<svg viewBox="${viewBox}" xmlns="http://www.w3.org/2000/svg">`,
`<path d="${data.d}" fill="${o.bgColor}" stroke="${o.borderColor}" transform="${data.transform}" />`,
'</svg>'
].join('');
// console.log(svg);
const backgroundImage = `url("data:image/svg+xml;charset=utf8,${encodeURIComponent(svg)}")`;
const background = `${backgroundImage} center no-repeat`;
const padding = `${o.arrowSize + o.borderRadius}px`;
const style = {
background,
backgroundImage,
padding,
changed: true
};
styleCache.position = info.position;
styleCache[info.position] = {
key,
style
};
return style;
};
-65
View File
@@ -1,65 +0,0 @@
.snapshot-manager {
--grid-font: -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
z-index: 1099;
width: 80vw;
height: 75vh;
min-height: 30em;
display: flex;
flex-direction: column;
gap: 10px;
color: var(--fg-color);
font-family: arial, sans-serif;
text-underline-offset: 3px;
outline: none;
margin: calc(var(--spacing)*2);
}
.snapshot-manager button {
width: auto;
position: relative;
overflow: hidden;
font-size: 16px;
color: var(--input-text);
background-color: var(--comfy-input-bg);
border-color: var(--border-color);
margin: 0;
min-width: 100px;
padding: 4px 8px;
}
.snapshot-manager .snapshot-restore-btn {
background-color: #00158f !important;
border-color: #2025b9 !important;
color: white !important;
}
.snapshot-manager .snapshot-remove-btn {
background-color: #970000 !important;
border-color: #be2127 !important;
color: white !important;
}
.snapshot-manager button:hover {
filter: brightness(125%);
}
.snapshot-manager .data-btns {
display: flex;
flex-direction: column;
gap: calc(var(--spacing)*2);
padding: calc(var(--spacing)*2);
align-items: center;
justify-content: center;
height: 100%;
}
.snapshot-footer {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
.snapshot-manager .cn-flex-auto {
flex: auto;
}
+40 -65
View File
@@ -1,48 +1,33 @@
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, handle403Response, loadCss, sanitizeHTML } from "./common.js";
import { buildGuiFrame } from "./comfyui-gui-builder.js";
import { manager_instance, rebootAPI, show_message } from "./common.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 success = false;
try {
const response = await api.fetchApi('/snapshot/restore', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target: target }), cache: "no-store" });
const response = await api.fetchApi(`/snapshot/restore?target=${target}`, { cache: "no-store" });
if(response.status == 403) {
await handle403Response(response);
show_message('This action is not allowed with this security level configuration.');
return false;
}
if(!response.ok) {
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
return false;
if(response.status == 400) {
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
}
app.ui.dialog.close();
success = true;
return true;
}
catch(exception) {
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
return false;
}
finally {
await SnapshotManager.instance.invalidateControl();
if(success) {
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-ui-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
}
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-small-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
}
}
}
@@ -50,23 +35,22 @@ async function restore_snapshot(target) {
async function remove_snapshot(target) {
if(SnapshotManager.instance) {
try {
const response = await api.fetchApi('/snapshot/remove', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ target: target }), cache: "no-store" });
const response = await api.fetchApi(`/snapshot/remove?target=${target}`, { cache: "no-store" });
if(response.status == 403) {
await handle403Response(response);
show_message('This action is not allowed with this security level configuration.');
return false;
}
if(!response.ok) {
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
return false;
if(response.status == 400) {
show_message(`Remove snapshot failed: ${target.title} / ${exception}`);
}
app.ui.dialog.close();
return true;
}
catch(exception) {
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
return false;
}
finally {
@@ -77,7 +61,7 @@ async function remove_snapshot(target) {
async function save_current_snapshot() {
try {
const response = await api.fetchApi('/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
const response = await api.fetchApi('/snapshot/save', { cache: "no-store" });
app.ui.dialog.close();
return true;
}
@@ -104,8 +88,6 @@ export class SnapshotManager extends ComfyDialog {
message_box = null;
data = null;
content = $el("div.snapshot-manager");
clear() {
this.restore_buttons = [];
this.message_box = null;
@@ -114,18 +96,9 @@ export class SnapshotManager extends ComfyDialog {
constructor(app, manager_dialog) {
super();
// this.manager_dialog = manager_dialog;
this.manager_dialog = manager_dialog;
this.search_keyword = '';
const frame = buildGuiFrame(
'snapshot-manager-dialog', // dialog id
'Snapshot Manager', // title
'i.mdi.mdi-puzzle', // icon class
this.content, // dialog content element
this
); // send this so we can attach close functions
this.element = frame;
this.element = $el("div.comfy-modal", { parent: document.body }, []);
}
async remove_item() {
@@ -136,7 +109,7 @@ export class SnapshotManager extends ComfyDialog {
createControls() {
return [
$el("button.cm-ui-button", {
$el("button.cm-small-button", {
type: "button",
textContent: "Close",
onclick: () => { this.close(); }
@@ -147,7 +120,7 @@ export class SnapshotManager extends ComfyDialog {
startRestore(target) {
const self = SnapshotManager.instance;
self.updateMessage(`<BR><font color="green">Restore snapshot '${sanitizeHTML(target.name)}'</font>`);
self.updateMessage(`<BR><font color="green">Restore snapshot '${target.name}'</font>`);
for(let i in self.restore_buttons) {
self.restore_buttons[i].disabled = true;
@@ -159,8 +132,8 @@ export class SnapshotManager extends ComfyDialog {
this.clear();
this.data = (await getSnapshotList()).items;
while (this.content.children.length) {
this.content.removeChild(this.content.children[0]);
while (this.element.children.length) {
this.element.removeChild(this.element.children[0]);
}
await this.createGrid();
@@ -172,8 +145,8 @@ export class SnapshotManager extends ComfyDialog {
if(btn_id) {
const rebootButton = document.getElementById(btn_id);
const self = this;
rebootButton.onclick = async function() {
if(await rebootAPI()) {
rebootButton.onclick = function() {
if(rebootAPI()) {
self.close();
self.manager_dialog.close();
}
@@ -228,24 +201,23 @@ export class SnapshotManager extends ComfyDialog {
data1.style.textAlign = "center";
data1.innerHTML = i+1;
var data2 = document.createElement('td');
data2.innerHTML = `&nbsp;${sanitizeHTML(data)}`;
data2.innerHTML = `&nbsp;${data}`;
var data_button = document.createElement('td');
data_button.style.textAlign = "center";
data_button.className = "data-btns";
var restoreBtn = document.createElement('button');
restoreBtn.className = "snapshot-restore-btn cm-ui-button";
restoreBtn.innerHTML = 'Restore';
restoreBtn.style.width = "100px";
restoreBtn.style.backgroundColor = 'blue';
restoreBtn.addEventListener('click', function() {
restore_snapshot(data);
});
var removeBtn = document.createElement('button');
removeBtn.className = "snapshot-remove-btn cm-ui-button";
removeBtn.innerHTML = 'Remove';
removeBtn.style.width = "100px";
removeBtn.style.backgroundColor = 'red';
removeBtn.addEventListener('click', function() {
remove_snapshot(data);
@@ -269,14 +241,13 @@ export class SnapshotManager extends ComfyDialog {
let self = this;
const panel = document.createElement('div');
panel.style.width = "100%";
panel.style.height = "100%";
panel.appendChild(grid);
function handleResize() {
const parentHeight = self.element.clientHeight;
const gridHeight = parentHeight - 200;
// grid.style.height = gridHeight + "px";
grid.style.height = gridHeight + "px";
}
window.addEventListener("resize", handleResize);
@@ -285,17 +256,25 @@ export class SnapshotManager extends ComfyDialog {
grid.style.width = "100%";
grid.style.height = "100%";
grid.style.overflowY = "scroll";
this.content.appendChild(panel);
this.element.style.height = "85%";
this.element.style.width = "80%";
this.element.appendChild(panel);
handleResize();
}
async createBottomControls() {
var close_button = document.createElement("button");
close_button.className = "cm-small-button";
close_button.innerHTML = "Close";
close_button.onclick = () => { this.close(); }
close_button.style.display = "inline-block";
var save_button = document.createElement("button");
save_button.className = "cm-ui-button";
save_button.className = "cm-small-button";
save_button.innerHTML = "Save snapshot";
save_button.onclick = () => { save_current_snapshot(); }
save_button.style.display = "inline-block";
save_button.style.horizontalAlign = "right";
save_button.style.width = "170px";
@@ -303,19 +282,15 @@ export class SnapshotManager extends ComfyDialog {
this.message_box.style.height = '60px';
this.message_box.style.verticalAlign = 'middle';
const footer = $el("div.snapshot-footer");
const spacer = $el("div.cn-flex-auto");
footer.appendChild(spacer);
footer.appendChild(save_button);
this.content.appendChild(this.message_box);
this.content.appendChild(footer);
this.element.appendChild(this.message_box);
this.element.appendChild(close_button);
this.element.appendChild(save_button);
}
async show() {
try {
this.invalidateControl();
this.element.style.display = "flex";
this.element.style.display = "block";
this.element.style.zIndex = 1099;
}
catch(exception) {
+3 -3
View File
@@ -67,11 +67,11 @@ class WorkflowMetadataExtension {
this.installedNodes[nodePackageName.toLowerCase()] ??
{};
if (cnr_id?.toLowerCase() === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id) nodeProperties.cnr_id = cnr_id;
else nodeProperties.aux_id = aux_id;
if (ver) nodeProperties.ver = ver.trim();
} else if (["nodes", "comfy_extras", "comfy_api_nodes"].includes(moduleType)) {
if (ver) nodeProperties.ver = ver;
} else if (["nodes", "comfy_extras"].includes(moduleType)) {
nodeProperties.cnr_id = "comfy-core";
nodeProperties.ver = this.comfyCoreVersion;
}
+16 -255
View File
@@ -1,264 +1,25 @@
#!/usr/bin/env python3
"""JSON Entry Validator
Validates JSON entries based on content structure.
Validation rules based on JSON content:
- {"custom_nodes": [...]}: Validates required fields (author, title, reference, files, install_type, description)
- {"models": [...]}: Validates JSON syntax only (no required fields)
- Other JSON structures: Validates JSON syntax only
Git repository URL validation (for custom_nodes):
1. URLs must NOT end with .git
2. URLs must follow format: https://github.com/{author}/{reponame}
3. .py and .js files are exempt from this check
Supported formats:
- Array format: [{...}, {...}]
- Object format: {"custom_nodes": [...]} or {"models": [...]}
"""
import json
import re
import sys
from pathlib import Path
from typing import Dict, List, Tuple
import argparse
# Required fields for each entry type
REQUIRED_FIELDS_CUSTOM_NODE = ['author', 'title', 'reference', 'files', 'install_type', 'description']
REQUIRED_FIELDS_MODEL = [] # model-list.json doesn't require field validation
# Pattern for valid GitHub repository URL (without .git suffix)
GITHUB_REPO_PATTERN = re.compile(r'^https://github\.com/[^/]+/[^/]+$')
def get_entry_context(entry: Dict) -> str:
"""Get identifying information from entry for error messages
Args:
entry: JSON entry
Returns:
String with author and reference info
"""
parts = []
if 'author' in entry:
parts.append(f"author={entry['author']}")
if 'reference' in entry:
parts.append(f"ref={entry['reference']}")
if 'title' in entry:
parts.append(f"title={entry['title']}")
if parts:
return " | ".join(parts)
else:
# No identifying info - show actual entry content (truncated)
import json
entry_str = json.dumps(entry, ensure_ascii=False)
if len(entry_str) > 100:
entry_str = entry_str[:100] + "..."
return f"content={entry_str}"
def validate_required_fields(entry: Dict, entry_index: int, required_fields: List[str]) -> List[str]:
"""Validate that all required fields are present
Args:
entry: JSON entry to validate
entry_index: Index of entry in array (for error reporting)
required_fields: List of required field names
Returns:
List of error descriptions (without entry prefix/context)
"""
errors = []
for field in required_fields:
if field not in entry:
errors.append(f"Missing required field '{field}'")
elif entry[field] is None:
errors.append(f"Field '{field}' is null")
elif isinstance(entry[field], str) and not entry[field].strip():
errors.append(f"Field '{field}' is empty")
elif field == 'files' and not entry[field]: # Empty array
errors.append("Field 'files' is empty array")
return errors
def validate_git_repo_urls(entry: Dict, entry_index: int) -> List[str]:
"""Validate git repository URLs in 'files' array
Requirements:
- Git repo URLs must NOT end with .git
- Must follow format: https://github.com/{author}/{reponame}
- .py and .js files are exempt
Args:
entry: JSON entry to validate
entry_index: Index of entry in array (for error reporting)
Returns:
List of error descriptions (without entry prefix/context)
"""
errors = []
if 'files' not in entry or not isinstance(entry['files'], list):
return errors
for file_url in entry['files']:
if not isinstance(file_url, str):
continue
# Skip .py and .js files - they're exempt from git repo validation
if file_url.endswith('.py') or file_url.endswith('.js'):
continue
# Check if it's a GitHub URL (likely a git repo)
if 'github.com' in file_url:
# Error if URL ends with .git
if file_url.endswith('.git'):
errors.append(f"Git repo URL must NOT end with .git: {file_url}")
continue
# Validate format: https://github.com/{author}/{reponame}
if not GITHUB_REPO_PATTERN.match(file_url):
errors.append(f"Invalid git repo URL format (expected https://github.com/author/reponame): {file_url}")
return errors
def validate_entry(entry: Dict, entry_index: int, required_fields: List[str]) -> List[str]:
"""Validate a single JSON entry
Args:
entry: JSON entry to validate
entry_index: Index of entry in array (for error reporting)
required_fields: List of required field names
Returns:
List of error messages (empty if valid)
"""
errors = []
# Check required fields
errors.extend(validate_required_fields(entry, entry_index, required_fields))
# Check git repository URLs
errors.extend(validate_git_repo_urls(entry, entry_index))
return errors
def validate_json_file(file_path: str) -> Tuple[bool, List[str]]:
"""Validate JSON file containing entries
Args:
file_path: Path to JSON file
Returns:
Tuple of (is_valid, error_messages)
"""
errors = []
# Check file exists
path = Path(file_path)
if not path.exists():
return False, [f"File not found: {file_path}"]
# Load JSON
def check_json_syntax(file_path):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
with open(file_path, 'r', encoding='utf-8') as file:
json_str = file.read()
json.loads(json_str)
print(f"[ OK ] {file_path}")
except UnicodeDecodeError as e:
print(f"Unicode decode error: {e}")
except json.JSONDecodeError as e:
return False, [f"Invalid JSON: {e}"]
except Exception as e:
return False, [f"Error reading file: {e}"]
# Determine required fields based on JSON content
required_fields = []
# Validate structure - support both array and object formats
entries_to_validate = []
if isinstance(data, list):
# Direct array format: [{...}, {...}]
entries_to_validate = data
elif isinstance(data, dict):
# Object format: {"custom_nodes": [...]} or {"models": [...]}
# Determine validation based on keys
if 'custom_nodes' in data and isinstance(data['custom_nodes'], list):
required_fields = REQUIRED_FIELDS_CUSTOM_NODE
entries_to_validate = data['custom_nodes']
elif 'models' in data and isinstance(data['models'], list):
required_fields = REQUIRED_FIELDS_MODEL
entries_to_validate = data['models']
else:
# Other JSON structures (extension-node-map.json, etc.) - just validate JSON syntax
return True, []
else:
return False, ["JSON root must be either an array or an object containing arrays"]
# Validate each entry
for idx, entry in enumerate(entries_to_validate, start=1):
if not isinstance(entry, dict):
# Show actual value for type errors
entry_str = json.dumps(entry, ensure_ascii=False) if not isinstance(entry, str) else repr(entry)
if len(entry_str) > 150:
entry_str = entry_str[:150] + "..."
errors.append(f"\n❌ Entry #{idx}: Must be an object, got {type(entry).__name__}")
errors.append(f" Actual value: {entry_str}")
continue
entry_errors = validate_entry(entry, idx, required_fields)
if entry_errors:
# Group errors by entry with context
context = get_entry_context(entry)
errors.append(f"\n❌ Entry #{idx} ({context}):")
for error in entry_errors:
errors.append(f" - {error}")
is_valid = len(errors) == 0
return is_valid, errors
print(f"[FAIL] {file_path}\n\n {e}\n")
except FileNotFoundError:
print(f"[FAIL] {file_path}\n\n File not found\n")
def main():
"""Main entry point"""
if len(sys.argv) < 2:
print("Usage: python json-checker.py <json-file>")
print("\nValidates JSON entries based on content:")
print(" - {\"custom_nodes\": [...]}: Validates required fields (author, title, reference, files, install_type, description)")
print(" - {\"models\": [...]}: Validates JSON syntax only (no required fields)")
print(" - Other JSON structures: Validates JSON syntax only")
print("\nGit repo URL validation (for custom_nodes):")
print(" - URLs must NOT end with .git")
print(" - URLs must follow: https://github.com/{author}/{reponame}")
sys.exit(1)
parser = argparse.ArgumentParser(description="JSON File Syntax Checker")
parser.add_argument("file_path", type=str, help="Path to the JSON file for syntax checking")
file_path = sys.argv[1]
args = parser.parse_args()
check_json_syntax(args.file_path)
is_valid, errors = validate_json_file(file_path)
if is_valid:
print(f"✅ {file_path}: Validation passed")
sys.exit(0)
else:
print(f"Validating: {file_path}")
print("=" * 60)
print("❌ Validation failed!\n")
print("Errors:")
# Count actual errors (lines starting with " -")
error_count = sum(1 for e in errors if e.strip().startswith('-'))
for error in errors:
# Don't add ❌ prefix to grouped entries (they already have it)
if error.strip().startswith('❌'):
print(error)
else:
print(error)
print(f"\nTotal errors: {error_count}")
sys.exit(1)
if __name__ == '__main__':
if __name__ == "__main__":
main()
+3 -1580
View File
File diff suppressed because it is too large Load Diff
-95
View File
@@ -1,95 +0,0 @@
# ComfyUI-Manager: Node Database (node_db)
This directory contains the JSON database files that power ComfyUI-Manager's legacy node registry system. While the manager is gradually transitioning to the online Custom Node Registry (CNR), these local JSON files continue to provide important metadata about custom nodes, models, and their integrations.
## Directory Structure
The node_db directory is organized into several subdirectories, each serving a specific purpose:
- **dev/**: Development channel files with latest additions and experimental nodes
- **legacy/**: Historical/legacy nodes that may require special handling
- **new/**: New nodes that have passed initial verification but are still being evaluated
- **forked/**: Forks of existing nodes with modifications
- **tutorial/**: Example and tutorial nodes designed for learning purposes
## Core Database Files
Each subdirectory contains a standard set of JSON files:
- **custom-node-list.json**: Primary database of custom nodes with metadata
- **extension-node-map.json**: Maps between extensions and individual nodes they provide
- **model-list.json**: Catalog of models that can be downloaded through the manager
- **alter-list.json**: Alternative implementations of nodes for compatibility or functionality
- **github-stats.json**: GitHub repository statistics for node popularity metrics
## Database Schema
### custom-node-list.json
```json
{
"custom_nodes": [
{
"title": "Node display name",
"name": "Repository name",
"reference": "Original repository if forked",
"files": ["GitHub URL or other source location"],
"install_type": "git",
"description": "Description of the node's functionality",
"pip": ["optional pip dependencies"],
"js": ["optional JavaScript files"],
"tags": ["categorization tags"]
}
]
}
```
### extension-node-map.json
```json
{
"extension-id": [
["list", "of", "node", "classes"],
{
"author": "Author name",
"description": "Extension description",
"nodename_pattern": "Optional regex pattern for node name matching"
}
]
}
```
## Transition to Custom Node Registry (CNR)
This local database system is being progressively replaced by the online Custom Node Registry (CNR), which provides:
- Real-time updates without manual JSON maintenance
- Improved versioning support
- Better security validation
- Enhanced metadata
The Manager supports both systems simultaneously during the transition period.
## Implementation Details
- The database follows a channel-based architecture for different sources
- Multiple database modes are supported: Channel, Local, and Remote
- The system supports differential updates to minimize bandwidth usage
- Security levels are enforced for different node installations based on source
## Usage in the Application
The Manager's backend uses these database files to:
1. Provide browsable lists of available nodes and models
2. Resolve dependencies for installation
3. Track updates and new versions
4. Map node classes to their source repositories
5. Assess risk levels for installation security
## Maintenance Scripts
Each subdirectory contains a `scan.sh` script that assists with:
- Scanning repositories for new nodes
- Updating metadata
- Validating database integrity
- Generating proper JSON structures
This database system enables a flexible, secure, and comprehensive management system for the ComfyUI ecosystem while the transition to CNR continues.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,3 +1,3 @@
#!/bin/bash
rm ~/.tmp/dev/*.py > /dev/null 2>&1
python ../../scanner.py ~/.tmp/dev $*
python ../../scanner.py ~/.tmp/dev
-50
View File
@@ -1,45 +1,5 @@
{
"custom_nodes": [
{
"author": "Fossiel",
"title": "ComfyUI-MultiGPU-Patched",
"reference": "https://github.com/Fossiel/ComfyUI-MultiGPU-Patched",
"files": [
"https://github.com/Fossiel/ComfyUI-MultiGPU-Patched"
],
"install_type": "git-clone",
"description": "Patched fork of ComfyUI-MultiGPU providing universal .safetensors and GGUF multi-GPU distribution with DisTorch 2.0 engine, model-driven allocation options (bytes/ratio modes), WanVideoWrapper integration, and up to 10% faster GGUF inference. (Description by CC)"
},
{
"author": "synchronicity-labs",
"title": "ComfyUI Sync Lipsync Node",
"reference": "https://github.com/synchronicity-labs/sync-comfyui",
"files": [
"https://github.com/synchronicity-labs/sync-comfyui"
],
"install_type": "git-clone",
"description": "This custom node allows you to perform audio-video lip synchronization inside ComfyUI using a simple interface."
},
{
"author": "joaomede",
"title": "ComfyUI-Unload-Model-Fork",
"reference": "https://github.com/joaomede/ComfyUI-Unload-Model-Fork",
"files": [
"https://github.com/joaomede/ComfyUI-Unload-Model-Fork"
],
"install_type": "git-clone",
"description": "For unloading a model or all models, using the memory management that is already present in ComfyUI. Copied from [a/https://github.com/willblaschko/ComfyUI-Unload-Models](https://github.com/willblaschko/ComfyUI-Unload-Models) but without the unnecessary extra stuff."
},
{
"author": "SanDiegoDude",
"title": "ComfyUI-HiDream-Sampler [WIP]",
"reference": "https://github.com/SanDiegoDude/ComfyUI-HiDream-Sampler",
"files": [
"https://github.com/SanDiegoDude/ComfyUI-HiDream-Sampler"
],
"install_type": "git-clone",
"description": "A collection of enhanced nodes for ComfyUI that provide powerful additional functionality to your workflows.\nNOTE: The files in the repo are not organized."
},
{
"author": "PramaLLC",
"title": "ComfyUI BEN - Background Erase Network",
@@ -179,16 +139,6 @@
],
"install_type": "git-clone",
"description": "A fork of KJNodes for ComfyUI.\nVarious quality of life -nodes for ComfyUI, mostly just visual stuff to improve usability"
},
{
"author": "huixingyun",
"title": "ComfyUI-SoundFlow",
"reference": "https://github.com/huixingyun/ComfyUI-SoundFlow",
"files": [
"https://github.com/huixingyun/ComfyUI-SoundFlow"
],
"install_type": "git-clone",
"description": "forked from https://github.com/fredconex/ComfyUI-SoundFlow (removed)"
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -71
View File
@@ -1,25 +1,5 @@
{
"custom_nodes": [
{
"author": "Comfy-Org",
"title": "ComfyUI React Extension Template",
"reference": "https://github.com/Comfy-Org/ComfyUI-React-Extension-Template",
"files": [
"https://github.com/Comfy-Org/ComfyUI-React-Extension-Template"
],
"install_type": "git-clone",
"description": "A minimal template for creating React/TypeScript frontend extensions for ComfyUI, with complete boilerplate setup including internationalization and unit testing."
},
{
"author": "comfyui-wiki",
"title": "ComfyUI-i18n-demo",
"reference": "https://github.com/comfyui-wiki/ComfyUI-i18n-demo",
"files": [
"https://github.com/comfyui-wiki/ComfyUI-i18n-demo"
],
"install_type": "git-clone",
"description": "ComfyUI custom node develop i18n support demo "
},
{
"author": "Suzie1",
"title": "Guide To Making Custom Nodes in ComfyUI",
@@ -331,56 +311,6 @@
],
"description": "ComfyUI node for creating some Turtle Graphic demos.",
"install_type": "git-clone"
},
{
"author": "cozy-comfyui",
"title": "cozy_ex_dynamic",
"reference": "https://github.com/cozy-comfyui/cozy_ex_dynamic",
"files": [
"https://github.com/cozy-comfyui/cozy_ex_dynamic"
],
"description": "Dynamic Node examples for ComfyUI",
"install_type": "git-clone"
},
{
"author": "Jonathon-Doran",
"title": "remote-combo-demo",
"reference": "https://github.com/Jonathon-Doran/remote-combo-demo",
"files": [
"https://github.com/Jonathon-Doran/remote-combo-demo"
],
"install_type": "git-clone",
"description": "A minimal test suite demonstrating how remote COMBO inputs behave in ComfyUI, with and without force_input"
},
{
"author": "J1mB091",
"title": "ComfyUI-J1mB091 Custom Nodes",
"reference": "https://github.com/J1mB091/ComfyUI-J1mB091",
"files": [
"https://github.com/J1mB091/ComfyUI-J1mB091"
],
"install_type": "git-clone",
"description": "Vibe Coded ComfyUI Custom Nodes"
},
{
"author": "aiforhumans",
"title": "XDev Nodes - Complete Toolkit",
"reference": "https://github.com/aiforhumans/comfyui-xdev-nodes",
"files": [
"https://github.com/aiforhumans/comfyui-xdev-nodes"
],
"install_type": "git-clone",
"description": "Complete ComfyUI development toolkit with 8 professional nodes including VAE tools, universal type testing, and comprehensive debugging infrastructure."
},
{
"author": "ganlvtech",
"title": "ComfyUI-CustomModelPatcher",
"reference": "https://github.com/ganlvtech/ComfyUI-CustomModelPatcher",
"files": [
"https://github.com/ganlvtech/ComfyUI-CustomModelPatcher"
],
"install_type": "git-clone",
"description": "Demonstrates GPU memory management techniques for external models like onnxruntime and InsightFace in ComfyUI by pre-allocating VRAM. (Description by CC)"
}
}
]
}
+1 -1
View File
@@ -67,7 +67,7 @@
"!echo -= Install dependencies =-\n",
"!pip3 install accelerate\n",
"!pip3 install einops transformers>=4.28.1 safetensors>=0.4.2 aiohttp pyyaml Pillow scipy tqdm psutil tokenizers>=0.13.3\n",
"!pip3 install torch torchvision --index-url https://download.pytorch.org/whl/cu121\n",
"!pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121\n",
"!pip3 install torchsde\n",
"!pip3 install kornia>=0.7.1 spandrel soundfile sentencepiece\n",
"\n",
-1113
View File
File diff suppressed because it is too large Load Diff
+156 -225
View File
@@ -21,26 +21,24 @@ import cm_global
import manager_downloader
import folder_paths
manager_util.add_python_path_to_env()
import datetime as dt
if hasattr(dt, 'datetime'):
from datetime import datetime as dt_datetime
import datetime
if hasattr(datetime, 'datetime'):
from datetime import datetime
def current_timestamp():
return dt_datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
return datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
else:
# NOTE: Occurs in some Mac environments.
import time
logging.error(f"[ComfyUI-Manager] fallback timestamp mode\n datetime module is invalid: '{dt.__file__}'")
logging.error(f"[ComfyUI-Manager] fallback timestamp mode\n datetime module is invalid: '{datetime.__file__}'")
def current_timestamp():
return str(time.time()).split('.')[0]
security_check.security_check()
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
cm_global.pip_downgrade_blacklist = ['torch', 'torchaudio', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
manager_util.add_python_path_to_env()
cm_global.pip_blacklist = {'torch', 'torchsde', 'torchvision'}
cm_global.pip_downgrade_blacklist = ['torch', 'torchsde', 'torchvision', 'transformers', 'safetensors', 'kornia']
def skip_pip_spam(x):
@@ -85,15 +83,7 @@ cm_global.register_api('cm.is_import_failed_extension', is_import_failed_extensi
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
custom_nodes_base_path = folder_paths.get_folder_paths('custom_nodes')[0]
# Check for System User API availability (PR #10966)
_has_system_user_api = hasattr(folder_paths, 'get_system_user_directory')
if _has_system_user_api:
manager_files_path = os.path.abspath(os.path.join(folder_paths.get_user_directory(), '__manager'))
else:
manager_files_path = os.path.abspath(os.path.join(folder_paths.get_user_directory(), 'default', 'ComfyUI-Manager'))
manager_files_path = os.path.abspath(os.path.join(folder_paths.get_user_directory(), 'default', 'ComfyUI-Manager'))
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")
@@ -108,7 +98,7 @@ def read_config():
global default_conf
try:
import configparser
config = configparser.ConfigParser(strict=False, interpolation=None)
config = configparser.ConfigParser(strict=False)
config.read(manager_config_path)
default_conf = config['default']
except Exception:
@@ -123,27 +113,17 @@ def check_file_logging():
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
enable_file_logging = False
def set_git_executable():
# GitPython reads this when it is imported, so that a git that is not on PATH can be named
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
if git_exe != '' and _has_system_user_api:
git_exe = manager_util.find_git_executable(git_exe)
if git_exe is not None:
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = git_exe
read_config()
set_git_executable()
read_uv_mode()
security_check.security_check()
check_file_logging()
cm_global.pip_overrides = {}
if _has_system_user_api and os.path.exists(manager_pip_overrides_path):
cm_global.pip_overrides = {'numpy': 'numpy<2', 'ultralytics': 'ultralytics==8.3.40'}
if os.path.exists(manager_pip_overrides_path):
with open(manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
cm_global.pip_overrides['numpy'] = 'numpy<2'
cm_global.pip_overrides['ultralytics'] = 'ultralytics==8.3.40' # for security
if os.path.exists(manager_pip_blacklist_path):
@@ -154,6 +134,15 @@ if os.path.exists(manager_pip_blacklist_path):
cm_global.pip_blacklist.add(y)
def remap_pip_package(pkg):
if pkg in cm_global.pip_overrides:
res = cm_global.pip_overrides[pkg]
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
return res
else:
return pkg
std_log_lock = threading.Lock()
@@ -289,7 +278,6 @@ try:
self.is_stdout = is_stdout
self.encoding = "utf-8"
self.last_char = ''
self.console_is_gone = False
def fileno(self):
try:
@@ -302,36 +290,7 @@ try:
raise ValueError("The object does not have a fileno method")
def isatty(self):
# 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
return False
def write(self, message):
global is_start_mode
@@ -363,65 +322,40 @@ try:
if '100%' in message:
self.sync_write(message)
else:
self.write_console(message)
write_stderr(message)
original_stderr.flush()
else:
self.sync_write(message)
else:
self.sync_write(message)
def write_console(self, message):
# A console that is gone does not come back, and ComfyUI's stream keeps every write
# it could not flush, so it is not written to again.
if self.console_is_gone:
return
try:
if self.is_stdout:
write_stdout(message)
original_stdout.flush()
else:
write_stderr(message)
original_stderr.flush()
except BlockingIOError:
pass
except OSError:
self.console_is_gone = True
def sync_write(self, message, file_only=False):
with log_lock:
# after close_log() the output goes to the console only
if not log_file.closed:
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(message)
else:
log_file.write(f"[{timestamp}] {message}")
try:
log_file.flush()
except Exception:
pass
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(message)
else:
log_file.write(f"[{timestamp}] {message}")
log_file.flush()
self.last_char = message if message == '' else message[-1]
if not file_only:
with std_log_lock:
self.write_console(message)
def flush(self):
try:
log_file.flush()
except Exception:
pass
with std_log_lock:
try:
if self.is_stdout:
write_stdout(message)
original_stdout.flush()
else:
write_stderr(message)
original_stderr.flush()
except (OSError, ValueError):
pass
def flush(self):
log_file.flush()
with std_log_lock:
if self.is_stdout:
original_stdout.flush()
else:
original_stderr.flush()
def close(self):
self.flush()
@@ -433,15 +367,12 @@ try:
def close_log(self):
sys.stderr = original_stderr
sys.stdout = original_stdout
with log_lock:
log_file.close()
log_file.close()
def close_log():
sys.stderr = original_stderr
sys.stdout = original_stdout
# a write that has found the file open finishes first
with log_lock:
log_file.close()
log_file.close()
if enable_file_logging:
@@ -459,15 +390,7 @@ try:
def emit(self, record):
global is_start_mode
try:
message = record.getMessage()
except Exception as e:
try:
error = f"{type(e).__name__}: {e}"
except Exception:
# an error can carry the message that cannot be turned into text
error = type(e).__name__
message = f"<<logging error>>: {record.pathname}:{record.lineno} - {error}"
message = record.getMessage()
if is_start_mode:
match = re.search(pat_import_fail, message)
@@ -511,32 +434,16 @@ except Exception as e:
def ensure_dependencies():
requirements_path = os.path.join(os.path.dirname(__file__), "requirements.txt")
try:
import git # noqa: F401
import toml # noqa: F401
import rich # noqa: F401
import chardet # noqa: F401
from importlib.metadata import version
from packaging.requirements import Requirement
# Check the declared version before loading the native extension, so an
# older nh3 can be upgraded without loading its binary into this process.
with open(requirements_path) as requirements:
for line in requirements:
line = re.split(r'\s+#', line.strip(), maxsplit=1)[0]
if not line or line.startswith(('#', '-')):
continue
nh3_requirement = Requirement(line)
if nh3_requirement.name.lower() == 'nh3':
break
else:
raise ValueError('requirements.txt does not declare nh3')
if version('nh3') not in nh3_requirement.specifier:
raise ModuleNotFoundError(str(nh3_requirement))
import nh3 # noqa: F401
except ModuleNotFoundError:
print("## ComfyUI-Manager: installing dependencies.")
my_path = os.path.dirname(__file__)
requirements_path = os.path.join(my_path, "requirements.txt")
print("## ComfyUI-Manager: installing dependencies. (GitPython)")
try:
subprocess.check_output(manager_util.make_pip_cmd(['install', '-r', requirements_path]))
except subprocess.CalledProcessError:
@@ -544,7 +451,7 @@ def ensure_dependencies():
try:
subprocess.check_output(manager_util.make_pip_cmd(['install', '--user', '-r', requirements_path]))
except subprocess.CalledProcessError:
print("## [ERROR] ComfyUI-Manager: Failed to install required packages in the correct Python environment. Please install requirements.txt manually in the appropriate environment. (You can seek help at https://app.element.io/#/room/%23comfyui_space%3Amatrix.org)")
print("## [ERROR] ComfyUI-Manager: Failed to install the GitPython package in the correct Python environment. Please install it manually in the appropriate environment. (You can seek help at https://app.element.io/#/room/%23comfyui_space%3Amatrix.org)")
try:
print("## ComfyUI-Manager: installing dependencies done.")
@@ -599,47 +506,62 @@ check_bypass_ssl()
# Perform install
processed_install = set()
# Use manager_files_path for consistency (fixes path inconsistency bug)
script_list_path = os.path.join(manager_files_path, "startup-scripts", "install-scripts.txt")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if _has_system_user_api else None)
script_list_path = os.path.join(folder_paths.user_directory, "default", "ComfyUI-Manager", "startup-scripts", "install-scripts.txt")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
def is_installed(name, reinstall=False):
def is_installed(name):
name = name.strip()
if name.startswith('#'):
return True
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}'")
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
pkg_name, extras, clauses = manager_util.parse_pip_spec(name)
if extras:
return False # extras to add: let pip decide
if name in cm_global.pip_downgrade_blacklist:
pips = manager_util.get_installed_packages()
if clauses and clauses[0][0] == '@':
return not reinstall and manager_util.installed_from(clauses[0][1], pkg_name) is not None
if match is None:
if name in pips:
return True
elif match.group(2) in ['<=', '==', '<', '~=']:
if name in pips:
if manager_util.StrictVersion(pips[name]) >= manager_util.StrictVersion(match.group(3)):
print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
return True
if pkg_name is None:
return False # a path or an option: let pip decide
pkg = manager_util.get_installed_packages().get(pkg_name)
pkg = manager_util.get_installed_packages().get(name.lower())
if pkg is None:
return False # update if not installed
if manager_util.requires_newer_version(clauses, pkg):
return False
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 True # prevent downgrade
if not _has_system_user_api:
if os.path.exists(restore_snapshot_path):
print("[ComfyUI-Manager] Snapshot restore blocked on old ComfyUI version.")
elif os.path.exists(restore_snapshot_path):
if os.path.exists(restore_snapshot_path):
try:
cloned_repos = []
@@ -666,19 +588,10 @@ elif os.path.exists(restore_snapshot_path):
print("[ComfyUI-Manager] Restore snapshot.")
new_env = os.environ.copy()
if 'COMFYUI_PATH' not in new_env:
new_env["COMFYUI_PATH"] = os.path.dirname(folder_paths.__file__)
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
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_util.is_loopback_listener(args.listen)
).lower()
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path,
'--user-directory', folder_paths.get_user_directory(), '--restore-to', custom_nodes_base_path]
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path]
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
if exit_code != 0:
@@ -704,9 +617,15 @@ def execute_lazy_install_script(repo_path, executable):
lines = manager_util.robust_readlines(requirements_path)
for line in lines:
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args and not is_installed(install_args[0]):
process_wrap(manager_util.make_pip_cmd(["install", *install_args]), repo_path)
package_name = remap_pip_package(line.strip())
if package_name and not is_installed(package_name):
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
else:
install_cmd = manager_util.make_pip_cmd(["install", package_name])
process_wrap(install_cmd, repo_path)
if os.path.exists(install_script_path) and f'{repo_path}/install.py' not in processed_install:
processed_install.add(f'{repo_path}/install.py')
@@ -719,28 +638,18 @@ 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, status=''):
def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom_nodes_path):
import uuid
import shutil
from comfy.cli_args import args
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
if not manager_util.is_cnr_install_allowed(status or 'NodeVersionStatusFlagged', allow_flagged, args.listen):
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_util.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
return False
# 1. download
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
download_path = os.path.join(custom_nodes_path, archive_name)
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
try:
extracted = manager_util.switch_package_files(download_path, from_path)
finally:
os.remove(download_path)
# 2. extract files into <node_id>@<cur_ver>
extracted = manager_util.extract_package_as_zip(download_path, from_path)
os.remove(download_path)
if extracted is None:
if len(os.listdir(from_path)) == 0:
@@ -749,15 +658,43 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
print(f'Empty archive file: {target}')
return False
if from_path != to_path:
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 3. calculate garbage files (.tracking - extracted)
tracking_info_file = os.path.join(from_path, '.tracking')
prev_files = set()
with open(tracking_info_file, 'r') as f:
for line in f:
prev_files.add(line.strip())
garbage = prev_files.difference(extracted)
garbage = [os.path.join(custom_nodes_path, x) for x in garbage]
# 4-1. remove garbage files
for x in garbage:
if os.path.isfile(x):
os.remove(x)
# 4-2. remove garbage dir if empty
for x in garbage:
if os.path.isdir(x):
if not os.listdir(x):
os.rmdir(x)
# 5. rename dir name <node_id>@<prev_ver> ==> <node_id>@<cur_ver>
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 6. create .tracking file
tracking_info_file = os.path.join(to_path, '.tracking')
with open(tracking_info_file, "w", encoding='utf-8') as file:
file.write('\n'.join(list(extracted)))
return True
def execute_migration(moves):
import shutil
for x in moves:
if os.path.exists(x[0]) and not os.path.exists(x[1]):
shutil.move(x[0], x[1])
print(f"[ComfyUI-Manager] MIGRATION: '{x[0]}' -> '{x[1]}'")
script_executed = False
@@ -814,35 +751,29 @@ def execute_startup_script():
execute_lazy_install_script(script[0], script[2])
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
status = script[8] if len(script) > 8 else ''
to_path = script[4]
if execute_lazy_cnr_switch(script[0], script[2], script[3], to_path, script[5], script[6], status):
execute_lazy_install_script(to_path, script[7])
execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6])
execute_lazy_install_script(script[3], script[7])
elif script[1] == "#LAZY-MIGRATION":
execute_migration(script[2])
elif script[1] == "#LAZY-DELETE-NODEPACK":
execute_lazy_delete(script[2])
elif os.path.exists(script[0]):
reinstall = False
if script[1] == "#FORCE":
del script[1]
else:
reinstall = manager_util.is_reinstall(script[1:])
requirement = manager_util.pip_install_requirement(script[1:])
if requirement is not None and is_installed(requirement, reinstall):
if 'pip' in script[1:] and 'install' in script[1:] and is_installed(script[-1]):
continue
if not reinstall:
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
print(f"\n## Execute management script for '{script[0]}'")
new_env = os.environ.copy()
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
if reinstall:
exit_code = manager_util.reinstall(script[1:], lambda cmd: process_wrap(cmd, script[0], env=new_env))
else:
exit_code = process_wrap(script[1:], script[0], env=new_env)
exit_code = process_wrap(script[1:], script[0], env=new_env)
if exit_code != 0:
print(f"management script failed: {script[0]}")
@@ -862,17 +793,9 @@ def execute_startup_script():
# Check if script_list_path exists
# Block startup-scripts on old ComfyUI (security measure)
if not _has_system_user_api:
if os.path.exists(script_list_path):
print("[ComfyUI-Manager] Startup scripts blocked on old ComfyUI version.")
elif os.path.exists(script_list_path):
if os.path.exists(script_list_path):
execute_startup_script()
if _has_system_user_api and os.path.exists(os.path.join(folder_paths.get_user_directory(), 'default', 'ComfyUI-Manager', 'config.ini')):
print("[ComfyUI-Manager] The legacy config.ini is still there: installing the requirements of ComfyUI.")
execute_lazy_install_script(comfy_path, sys.executable)
pip_fixer.fix_broken()
@@ -891,7 +814,15 @@ if script_executed:
print("--------------------------------------------------------------------------\n")
exit(0)
else:
cmds = manager_util.build_restart_command(sys.argv)
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
print(f"Command: {cmds}", flush=True)
print("--------------------------------------------------------------------------\n")
@@ -902,7 +833,7 @@ if script_executed:
def check_windows_event_loop_policy():
try:
import configparser
config = configparser.ConfigParser(strict=False, interpolation=None)
config = configparser.ConfigParser(strict=False)
config.read(manager_config_path)
default_conf = config['default']
+3 -4
View File
@@ -1,14 +1,13 @@
[project]
name = "comfyui-manager"
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
version = "3.44"
version = "3.30.9"
license = { file = "LICENSE.txt" }
requires-python = ">=3.9"
dependencies = ["GitPython", "PyGithub", "matrix-nio", "transformers", "huggingface-hub>0.20", "typer", "rich", "typing-extensions", "toml", "uv", "chardet", "packaging", "nh3>=0.3.7"]
dependencies = ["GitPython", "PyGithub", "matrix-client==0.4.0", "transformers", "huggingface-hub>0.20", "typer", "rich", "typing-extensions", "toml", "uv", "chardet"]
[project.urls]
Repository = "https://github.com/ltdrdata/ComfyUI-Manager"
# Used by Comfy Registry https://registry.comfy.org
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "drltdata"
+2 -4
View File
@@ -1,13 +1,11 @@
GitPython
PyGithub
matrix-nio
matrix-client==0.4.0
transformers
huggingface-hub
huggingface-hub>0.20
typer
rich
typing-extensions
toml
uv
chardet
packaging
nh3>=0.3.7
+85 -1211
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager
cd ..
python -m venv venv
source venv/bin/activate
python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu130
python -m pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121
python -m pip install -r requirements.txt
python -m pip install -r custom_nodes/comfyui-manager/requirements.txt
cd ..
+1 -1
View File
@@ -4,7 +4,7 @@ git clone https://github.com/ltdrdata/ComfyUI-Manager comfyui-manager
cd ..
python -m venv venv
call venv/Scripts/activate
python -m pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu130
python -m pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121
python -m pip install -r requirements.txt
python -m pip install -r custom_nodes/comfyui-manager/requirements.txt
cd ..
-153
View File
@@ -1,153 +0,0 @@
{
"note": "JS<->Python sanitize_url differential case matrix. STRING inputs only: Python str() and JS String() disagree for non-strings, so feeding them would report divergence for something that is not a defect. See the docstring of tests/test_url_sanitize_parity.py.",
"provenance": "Handed over by gm3-review: 35 cases built to clear the WI-112 model-manager port, plus 22 built for the WI-120 review (scheme grammar, protocol-relative with userinfo, colons after a delimiter, unicode spaces and RTL override, degenerate schemes, a 500-char path). All 57 agreed on both implementations when handed over -- they are coverage, not known failures.",
"type_coercion_warning": {
"why": "Python str() and JS String() are NOT equivalent for non-strings. Feeding non-strings into the differential matrix produces FALSE divergence - a guard RED for a non-bug.",
"measured": {
"1.0": {
"py": "1.0",
"js": "1"
},
"True": {
"py": "True",
"js": "true"
},
"False": {
"py": "False",
"js": "false"
},
"[1,2]": {
"py": "[1, 2]",
"js": "1,2"
},
"{}": {
"py": "{}",
"js": "[object Object]"
}
},
"aligned": {
"0": "both '0'",
"None/null": "both '#' - explicit null handling in both impls"
},
"recommendation": "Scope the matrix to STRING inputs and say so in the guard docstring; url is always a string off the JSON payload in practice."
},
"shared_matrix": [
"javascript:a",
"JaVaScRiPt:a",
"java\tscript:a",
"java\nscript:a",
"\u0001javascript:a",
" javascript:a",
"data:text/html,x",
"vbscript:a",
"file:///etc/passwd",
"about:blank",
"blob:http://x",
"javascript&#58;a",
"javascript&colon;a",
"&#x6a;avascript:a",
"&#106;avascript:a",
"http://e.com",
"https://e.com/a?b=1&c=2",
"HTTPS://E.COM",
"/rel/path",
"rel",
"#anchor",
"//proto/x",
"a&b/c",
"x&y?z=1",
"e.com:8080/p",
"foo:bar",
":alert(1)",
"",
" ",
"https://e.com/x\" onmouseover=\"y",
"https://evil.example/a onmouseover=alert(1) x",
"\\\\evil.com/x",
"/\\evil.com",
"\u0000javascript:a",
"j\u0000avascript:a",
"coap+tcp://h/x",
"x-scheme://h",
"a.b://h",
"a-b://h",
"HTTP+S://h",
"//user:pass@evil.example/x",
"#a:b",
"?a=b:c",
"/p:q",
"http://h/#f:g",
"http ://h",
"javascript :a",
"ja​vascript:a",
"http://h",
"http://h/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"http://h/‮evil",
"http:",
"https:",
"http:/h",
":",
"::",
"a::b",
" /rel/path ",
" rel ",
"\t#anchor\n",
" http://h/x ",
"\thttps://h/x\t",
"http://h/x",
"/rel/path",
"https://h/x",
"",
" /rel ",
"http://h/x…",
"…http://h/x",
"http://h/x\u001c",
"http://h/x\u001d",
"http://h/x\u001e",
"http://h/x\u001f",
"/rel/path…",
"/rel/path\u001c",
"https://h/x…",
"http://h/x ",
" http://h/x",
"http://h/x ",
"http://h/x ",
"http://h/x ",
"http://h/x
",
"http://h/x
",
"http://h/x ",
"http://h/x ",
"http://h/x ",
" /rel",
"  /rel  "
],
"gap_cases_found_by_enforcement": {
"why": "Found by tests/test_url_sanitize_parity.py's own perturbation test, not by review: perturbing the JS scheme-less branch from `return raw.trim()` to `return raw` produced ZERO divergences against the handed-over 57, because every scheme-less case in that set is already trim-clean. The two trim call sites in sanitize_url were therefore unpinned on both sides.",
"cases": [
" /rel/path ",
" rel ",
"\t#anchor\n",
" http://h/x ",
"\thttps://h/x\t"
]
},
"unicode_whitespace_divergence": {
"why": "The 62-case matrix had no BOM or unicode-whitespace input, so the two trim call sites in sanitize_url were compared only over inputs whose edges are ASCII. They are NOT equivalent: String.prototype.trim() and str.strip() disagree on six codepoints.",
"measured": {
"js_strips_python_keeps": [
"U+FEFF"
],
"python_strips_js_keeps": [
"U+001C",
"U+001D",
"U+001E",
"U+001F",
"U+0085"
],
"method": "enumerated every codepoint below U+110000 on both sides: chr(c).isspace() in Python vs /\\s/-equivalent String.trim() in node; 24 shared, 6 divergent"
},
"example": "'http://h/x<U+FEFF>' -> python 'http://h/x<U+FEFF>', js 'http://h/x'",
"resolution": "ALIGNED, not accepted. glob/manager_util.py is the declared source of truth for this pair (see test_the_guard_goes_red_when_either_allow_list_gains_a_scheme, which names it), so js/common.js stopped delegating to trim() and spells Python's str.strip() set out as URL_TRIM. The divergence is therefore a REGRESSION SHAPE this matrix now catches, not a gap_case.",
"scope": "The trim only shapes the RETURNED string for an already-accepted URL. Scheme acceptance is decided on `probe`, which both sides build identically, so no case here changes what is allowed."
}
}
-40
View File
@@ -1,40 +0,0 @@
"""Test-runner guard for the GOAL #32 tests/ modules.
WHY THIS FILE EXISTS (collection hazard, not test logic):
The repo root contains ``__init__.py`` — the ComfyUI plugin entrypoint —
which at import time appends ``glob/`` to sys.path and imports
``manager_server`` (which needs ``folder_paths`` / ``comfy.cli_args`` /
a constructed ``PromptServer``). pytest 8 collects any ancestor
directory that carries an ``__init__.py`` as a ``Package`` node and
IMPORTS that ``__init__.py`` during test setup (observed module name:
``__init__``). Outside a live ComfyUI process that import can never
succeed, so EVERY test under tests/ errors at setup whenever pytest's
rootdir ends up at or above the repo root (e.g. running inside a git
worktree nested under the parent checkout).
The guard below pre-seeds ``sys.modules`` with an inert stub whose
``__file__`` matches the real path, so pytest's
``import_path(<repo-root>/__init__.py)`` resolves to the stub without
executing the plugin entrypoint. Conftest files load before the setup
phase, so the stub is always in place in time. This does NOT touch
production code and does NOT alter what the tests import themselves
(they use AST-extraction / subprocess isolation per the
tests/test_json_body_content_type.py precedent — ``glob/`` is never
added to the runner's sys.path).
"""
import sys
import types
from pathlib import Path
_REPO_ROOT = Path(__file__).resolve().parent.parent
_ROOT_INIT = _REPO_ROOT / "__init__.py"
if _ROOT_INIT.exists() and "__init__" not in sys.modules:
_stub = types.ModuleType("__init__")
_stub.__file__ = str(_ROOT_INIT)
_stub.__doc__ = (
"Inert stand-in for the ComfyUI-Manager plugin entrypoint; "
"see tests/conftest.py for rationale."
)
sys.modules["__init__"] = _stub
-169
View File
@@ -1,169 +0,0 @@
#!/usr/bin/env bash
# setup_e2e_env.sh — E2E environment builder for GOAL #60 (T1, spec §2).
#
# Builds the DISPOSABLE test ComfyUI root used by
# tests/e2e/test_e2e_install_flags.py. ENV BUILD ONLY: donor steps 4-5
# (editable pip install of the Manager + custom_nodes symlink) are
# deliberately DROPPED — the Manager is mounted via `git worktree add`
# by the `mount_worktree` session fixture in the test module, which is
# the SOLE owner of mount create/reuse/teardown (spec §2 T1
# single-ownership rule). This script never touches the Manager repo.
#
# Idempotent: re-run is a no-op when the marker + key artifacts exist
# (E2E-SC-01).
#
# Input env vars:
# E2E_COMFYUI_ROOT — target directory (default: mktemp -d)
# COMFYUI_BRANCH — ComfyUI clone ref (default: master; Q-2)
# PYTHON — python executable for version probe (default: python3)
#
# Output (last line of stdout):
# E2E_COMFYUI_ROOT=/path/to/environment
#
# Exit: 0=success, 1=failure
set -euo pipefail
COMFYUI_REPO="https://github.com/comfyanonymous/ComfyUI.git"
PYTORCH_CPU_INDEX="https://download.pytorch.org/whl/cpu"
# Minimal seed config. use_uv=false: the venv is seeded with pip
# (`uv venv --seed`), so the Manager's make_pip_cmd resolves to
# `<venv-python> -m pip` and the suite's pip-uninstall hygiene helpers
# work without uv on PATH at server runtime. The install flags are NOT
# seeded here — stage_flags.sh stages them per launch identity (SC-06).
CONFIG_INI_CONTENT="[default]
file_logging = false
use_uv = false"
log() { echo "[setup_e2e] $*"; }
err() { echo "[setup_e2e] ERROR: $*" >&2; }
die() { err "$@"; exit 1; }
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
local py_version major minor
py_version=$("$py" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.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)"
}
check_already_setup() {
local root="$1"
if [[ -f "$root/.e2e_setup_complete" ]] \
&& [[ -d "$root/comfyui" ]] \
&& [[ -d "$root/venv" ]] \
&& [[ -f "$root/comfyui/user/__manager/config.ini" ]]; then
log "Environment already set up at $root (marker exists). Skipping. (E2E-SC-01 idempotence)"
echo "E2E_COMFYUI_ROOT=$root"
exit 0
fi
}
verify_setup() {
local root="$1"
local venv_py="$root/venv/bin/python"
local errors=0
log "Running verification checks..."
[[ -f "$root/comfyui/main.py" ]] || { err "Verification FAIL: comfyui/main.py not found"; ((errors+=1)); }
[[ -x "$venv_py" ]] || { err "Verification FAIL: venv python not executable"; ((errors+=1)); }
[[ -f "$root/comfyui/user/__manager/config.ini" ]] || { err "Verification FAIL: config.ini not found"; ((errors+=1)); }
# venv must carry pip (uv venv --seed) — the suite's hygiene helpers
# and the Manager's reservation-consuming boot both call `-m pip`.
if ! "$venv_py" -m pip --version >/dev/null 2>&1; then
err "Verification FAIL: venv pip not available"
((errors+=1))
fi
# comfy is a local package inside the ComfyUI checkout
if ! PYTHONPATH="$root/comfyui" "$venv_py" -c "import comfy" 2>/dev/null; then
err "Verification FAIL: 'import comfy' failed"
((errors+=1))
fi
# [D2] half-check at setup time: the Manager must NOT be pip-installed
# into this venv (the worktree mount is the only delivery mechanism).
if "$venv_py" -m pip show comfyui-manager >/dev/null 2>&1 \
|| "$venv_py" -m pip show ComfyUI-Manager >/dev/null 2>&1; then
err "Verification FAIL: a pip-installed Manager exists in the venv (wrong layout for [D2])"
((errors+=1))
fi
if [[ "$errors" -gt 0 ]]; then
die "Verification failed with $errors error(s)"
fi
log "Verification OK: all checks passed"
}
# ===== Main =====
validate_prerequisites
PYTHON="${PYTHON:-python3}"
COMFYUI_BRANCH="${COMFYUI_BRANCH:-master}"
CREATED_BY_US=false
if [[ -z "${E2E_COMFYUI_ROOT:-}" ]]; then
E2E_COMFYUI_ROOT="$(mktemp -d -t e2e_comfyui_XXXXXX)"
CREATED_BY_US=true
log "Created E2E_COMFYUI_ROOT=$E2E_COMFYUI_ROOT"
else
mkdir -p "$E2E_COMFYUI_ROOT"
log "Using E2E_COMFYUI_ROOT=$E2E_COMFYUI_ROOT"
fi
check_already_setup "$E2E_COMFYUI_ROOT"
cleanup_on_failure() {
local exit_code=$?
if [[ "$exit_code" -ne 0 ]] && [[ "$CREATED_BY_US" == "true" ]]; then
err "Setup failed. Cleaning up $E2E_COMFYUI_ROOT"
rm -rf "$E2E_COMFYUI_ROOT"
fi
}
trap cleanup_on_failure EXIT
log "Step 1/5: Cloning ComfyUI (branch=$COMFYUI_BRANCH)..."
if [[ -d "$E2E_COMFYUI_ROOT/comfyui/.git" ]]; then
log " ComfyUI already cloned, skipping"
else
git clone --depth=1 --branch "$COMFYUI_BRANCH" "$COMFYUI_REPO" "$E2E_COMFYUI_ROOT/comfyui"
fi
log "Step 2/5: Creating virtual environment (seeded with pip)..."
if [[ -d "$E2E_COMFYUI_ROOT/venv" ]]; then
log " venv already exists, skipping"
else
uv venv --seed "$E2E_COMFYUI_ROOT/venv"
fi
VENV_PY="$E2E_COMFYUI_ROOT/venv/bin/python"
log "Step 3/5: Installing ComfyUI dependencies (CPU-only torch index)..."
uv pip install \
--python "$VENV_PY" \
-r "$E2E_COMFYUI_ROOT/comfyui/requirements.txt" \
--extra-index-url "$PYTORCH_CPU_INDEX"
log "Step 4/5: Writing seed config.ini + HOME isolation dirs..."
mkdir -p "$E2E_COMFYUI_ROOT/comfyui/user/__manager"
echo "$CONFIG_INI_CONTENT" > "$E2E_COMFYUI_ROOT/comfyui/user/__manager/config.ini"
mkdir -p "$E2E_COMFYUI_ROOT/home/.config"
mkdir -p "$E2E_COMFYUI_ROOT/home/.local/share"
mkdir -p "$E2E_COMFYUI_ROOT/logs"
mkdir -p "$E2E_COMFYUI_ROOT/comfyui/custom_nodes"
log "Step 5/5: Verifying setup..."
verify_setup "$E2E_COMFYUI_ROOT"
# Marker written ONLY after verification passes (E2E-SC-01)
date -Iseconds > "$E2E_COMFYUI_ROOT/.e2e_setup_complete"
trap - EXIT
log "Setup complete."
echo "E2E_COMFYUI_ROOT=$E2E_COMFYUI_ROOT"
-82
View File
@@ -1,82 +0,0 @@
#!/usr/bin/env bash
# stage_flags.sh — Per-launch-identity config staging (T4, spec §1.4).
#
# Analog of the donor's start_comfyui_strict.sh config patching, split
# out as a pure staging script (launch is a separate step; the pytest
# fixture owns restore+delete of the backup at teardown — donor
# symmetry, spec §1.4).
#
# Modes (arg $1):
# deny — REMOVE both flag keys (L-D: flags ABSENT also live-proves
# "missing key reads false")
# allow — set allow_git_url_install = true AND allow_pip_install = true
# (L-A / L-P)
#
# Backup: config.ini.before-flags, created ONLY if not already present
# (crashed-run-safe — preserves the true baseline across crashed runs).
# Restore + DELETE of the backup happens in the pytest fixture teardown,
# NOT here (E2E-SC-06/07).
#
# Input env vars:
# E2E_COMFYUI_ROOT — (required)
#
# Exit: 0=staged, 1=failure
set -euo pipefail
MODE="${1:-}"
log() { echo "[stage_flags] $*"; }
err() { echo "[stage_flags] ERROR: $*" >&2; }
die() { err "$@"; exit 1; }
[[ -n "${E2E_COMFYUI_ROOT:-}" ]] || die "E2E_COMFYUI_ROOT is not set"
[[ "$MODE" == "deny" || "$MODE" == "allow" ]] || die "usage: stage_flags.sh deny|allow"
CONFIG="$E2E_COMFYUI_ROOT/comfyui/user/__manager/config.ini"
BACKUP="$CONFIG.before-flags"
[[ -f "$CONFIG" ]] || die "config not found at $CONFIG (run setup_e2e_env.sh first)"
# Backup ONLY if absent (crashed-run-safe; SC-06)
if [[ ! -f "$BACKUP" ]]; then
cp "$CONFIG" "$BACKUP"
log "Backed up original config to $BACKUP"
else
log "Backup already present at $BACKUP (preserving original baseline)"
fi
stage_key() {
local key="$1" value="$2"
if grep -qE "^${key}\s*=" "$CONFIG"; then
sed -i -E "s|^${key}\s*=.*|${key} = ${value}|" "$CONFIG"
else
# The append-after target MUST exist, otherwise the sed below is a
# silent no-op and the flag never lands (false-PASS for the allow arm).
grep -qE "^\[default\]" "$CONFIG" \
|| die "no [default] section in $CONFIG — cannot stage '${key}' (would silently no-op)"
sed -i -E "/^\[default\]/a ${key} = ${value}" "$CONFIG"
fi
}
remove_key() {
local key="$1"
sed -i -E "/^${key}\s*=/d" "$CONFIG"
}
case "$MODE" in
deny)
remove_key "allow_git_url_install"
remove_key "allow_pip_install"
log "Staged DENY config (both flags ABSENT — missing key reads false)"
;;
allow)
stage_key "allow_git_url_install" "true"
stage_key "allow_pip_install" "true"
log "Staged ALLOW config (both flags = true)"
;;
esac
# The staged value takes effect ONLY on the NEXT launch (restart-only
# cached_config — by construction, no hot-reload assumption; SC-06).
log "Staged config at $CONFIG (effective on next launch)"
-142
View File
@@ -1,142 +0,0 @@
#!/usr/bin/env bash
# start_comfyui.sh — Foreground-blocking ComfyUI launcher (T2, spec §1.3).
#
# Starts ComfyUI in the background and blocks until the server answers
# GET /system_stats (or timeout). Deltas vs the donor script (binding,
# spec §1.3):
# - NO --enable-manager: the Manager is a custom-node-style plugin
# activated by ComfyUI's custom_nodes scan of the worktree mount.
# - NO COMFYUI_MANAGER_SKIP_MANAGER_REQUIREMENTS: that belt does not
# exist in this repo (Q-6 verified); watchdog row E2E-SC-42 covers
# the residual.
# - --listen is ALWAYS passed explicitly (LISTEN env): the predicate
# under test is request-time `flag AND is_loopback(args.listen)` —
# the listener value is LOAD-BEARING.
# - Per-launch log isolation (E2E-SC-04, MANDATORY): each launch
# identity writes a FRESH log file comfyui.<port>.<launch-id>.log,
# so a deny-copy substring from L-D is unfindable by L-A/R-A log
# assertions (stale-substring false-PASS class).
# - Readiness = poll GET /system_stats == 200; child exit code 0
# during the wait = Manager-triggered restart -> KEEP polling;
# non-zero exit -> fail fast with log tail.
#
# Input env vars:
# E2E_COMFYUI_ROOT — (required) root from setup_e2e_env.sh
# PORT — listen port (default: 8189)
# TIMEOUT — max seconds to readiness (default: 120)
# LISTEN — listener address (default: 127.0.0.1)
# LAUNCH_ID — launch identity tag for the log file (default: default)
#
# Output (last line on success):
# COMFYUI_PID=<pid> PORT=<port> LOG_FILE=<path>
#
# Exit: 0=ready, 1=timeout/failure
set -euo pipefail
PORT="${PORT:-8189}"
TIMEOUT="${TIMEOUT:-120}"
LISTEN="${LISTEN:-127.0.0.1}"
LAUNCH_ID="${LAUNCH_ID:-default}"
log() { echo "[start_comfyui] $*"; }
err() { echo "[start_comfyui] ERROR: $*" >&2; }
die() { err "$@"; exit 1; }
[[ -n "${E2E_COMFYUI_ROOT:-}" ]] || die "E2E_COMFYUI_ROOT is not set"
[[ -d "$E2E_COMFYUI_ROOT/comfyui" ]] || die "ComfyUI not found at $E2E_COMFYUI_ROOT/comfyui"
[[ -x "$E2E_COMFYUI_ROOT/venv/bin/python" ]] || die "venv python not found"
[[ -f "$E2E_COMFYUI_ROOT/.e2e_setup_complete" ]] || die "Setup marker not found. Run setup_e2e_env.sh first."
PY="$E2E_COMFYUI_ROOT/venv/bin/python"
COMFY_DIR="$E2E_COMFYUI_ROOT/comfyui"
LOG_DIR="$E2E_COMFYUI_ROOT/logs"
LOG_FILE="$LOG_DIR/comfyui.${PORT}.${LAUNCH_ID}.log"
# Port-namespaced PID file (donor WI-CC incident: shared PID file caused
# a cross-port kill).
PID_FILE="$LOG_DIR/comfyui.${PORT}.pid"
mkdir -p "$LOG_DIR"
# --- Pre-launch port clear ---
if ss -tlnp 2>/dev/null | grep -q ":${PORT}\b"; then
log "Port $PORT is in use. Attempting to stop existing process..."
if [[ -f "$PID_FILE" ]]; then
OLD_PID="$(cat "$PID_FILE")"
if kill -0 "$OLD_PID" 2>/dev/null; then
kill "$OLD_PID" 2>/dev/null || true
sleep 2
fi
fi
if ss -tlnp 2>/dev/null | grep -q ":${PORT}\b"; then
pkill -f "main\\.py.*--port $PORT" 2>/dev/null || true
sleep 2
fi
if ss -tlnp 2>/dev/null | grep -q ":${PORT}\b"; then
die "Port $PORT is still in use after cleanup attempt"
fi
log "Port $PORT cleared."
fi
# --- Launch (FRESH per-launch log file) ---
log "Starting ComfyUI on port $PORT (listen=$LISTEN, launch_id=$LAUNCH_ID)..."
: > "$LOG_FILE"
PYTHONUNBUFFERED=1 \
HOME="$E2E_COMFYUI_ROOT/home" \
nohup "$PY" -u "$COMFY_DIR/main.py" \
--cpu \
--port "$PORT" \
--listen "$LISTEN" \
> "$LOG_FILE" 2>&1 &
COMFYUI_PID=$!
echo "$COMFYUI_PID" > "$PID_FILE"
log "ComfyUI PID=$COMFYUI_PID, log=$LOG_FILE"
# --- Block until ready: poll /system_stats (restart-tolerant) ---
log "Waiting up to ${TIMEOUT}s for ComfyUI readiness (GET /system_stats)..."
DEADLINE=$(( $(date +%s) + TIMEOUT ))
READY=0
while [[ "$(date +%s)" -lt "$DEADLINE" ]]; do
if curl -sf --max-time 2 "http://127.0.0.1:${PORT}/system_stats" >/dev/null 2>&1; then
READY=1
break
fi
# Child exit handling: exit 0 = Manager-triggered restart -> keep
# polling (a restarted process will bind the port); non-zero -> fail fast.
if ! kill -0 "$COMFYUI_PID" 2>/dev/null; then
if wait "$COMFYUI_PID" 2>/dev/null; then
: # exit 0 — restart class, keep polling
else
RC=$?
err "ComfyUI exited with code $RC. Last 30 lines of log:"
tail -n 30 "$LOG_FILE" >&2
rm -f "$PID_FILE"
exit 1
fi
fi
sleep 1
done
if [[ "$READY" -ne 1 ]]; then
err "Timeout (${TIMEOUT}s) waiting for ComfyUI. Last 30 lines of log:"
tail -n 30 "$LOG_FILE" >&2
kill "$COMFYUI_PID" 2>/dev/null || true
rm -f "$PID_FILE"
exit 1
fi
# A Manager-triggered restart (child exit 0 above) leaves COMFYUI_PID pointing
# at the dead original child while a FRESH process now owns the port. Re-resolve
# the live listener PID so PID_FILE (consumed by stop_comfyui.sh) targets the
# process that must actually be killed at teardown.
LISTENER_PID="$(ss -tlnp 2>/dev/null | grep ":${PORT}\b" | grep -oE 'pid=[0-9]+' | head -n1 | cut -d= -f2)"
if [[ -n "$LISTENER_PID" && "$LISTENER_PID" != "$COMFYUI_PID" ]]; then
log "Listener PID $LISTENER_PID differs from launched PID $COMFYUI_PID (restart). Updating PID file."
COMFYUI_PID="$LISTENER_PID"
echo "$COMFYUI_PID" > "$PID_FILE"
fi
log "ComfyUI is ready."
echo "COMFYUI_PID=$COMFYUI_PID PORT=$PORT LOG_FILE=$LOG_FILE"
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env bash
# stop_comfyui.sh — Graceful ComfyUI shutdown (T3, spec §1.3 stop contract).
#
# Donor mirror: SIGTERM -> 10s grace -> SIGKILL -> port-pattern pkill
# fallback -> port-free verify (incl. the legacy-PID-file warning from
# the donor WI-CC cross-port-kill incident).
#
# Input env vars:
# E2E_COMFYUI_ROOT — (required) path to the E2E environment
# PORT — ComfyUI port (default: 8189)
#
# Exit: 0=stopped, 1=failed
set -euo pipefail
PORT="${PORT:-8189}"
GRACE_PERIOD=10
log() { echo "[stop_comfyui] $*"; }
err() { echo "[stop_comfyui] ERROR: $*" >&2; }
die() { err "$@"; exit 1; }
[[ -n "${E2E_COMFYUI_ROOT:-}" ]] || die "E2E_COMFYUI_ROOT is not set"
# Ownership guard: only signal a PID whose cmdline references THIS E2E root.
# On shared runners a bare "main.py --port N" pattern (or a reused PID) could
# otherwise match an unrelated process; the launcher invokes
# "$E2E_COMFYUI_ROOT/venv/bin/python $E2E_COMFYUI_ROOT/comfyui/main.py", so the
# root path is always present in our process's cmdline.
belongs_to_root() {
local pid="$1"
[[ -n "$pid" && -r "/proc/$pid/cmdline" ]] || return 1
tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -qF "$E2E_COMFYUI_ROOT"
}
# PIDs currently listening on PORT (deduped).
listener_pids() {
ss -tlnp 2>/dev/null | grep ":${PORT}\b" | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u
}
PID_FILE="$E2E_COMFYUI_ROOT/logs/comfyui.${PORT}.pid"
LEGACY_PID_FILE="$E2E_COMFYUI_ROOT/logs/comfyui.pid"
if [[ -f "$LEGACY_PID_FILE" ]] && [[ ! -f "$PID_FILE" ]]; then
log "WARN: found legacy unported PID file $LEGACY_PID_FILE but no ${PID_FILE}. Cross-port risk — ignoring legacy file."
fi
COMFYUI_PID=""
if [[ -f "$PID_FILE" ]]; then
COMFYUI_PID="$(cat "$PID_FILE")"
log "Read PID=$COMFYUI_PID from $PID_FILE"
fi
if [[ -n "$COMFYUI_PID" ]] && kill -0 "$COMFYUI_PID" 2>/dev/null; then
if belongs_to_root "$COMFYUI_PID"; then
log "Sending SIGTERM to PID $COMFYUI_PID..."
kill "$COMFYUI_PID" 2>/dev/null || true
elapsed=0
while kill -0 "$COMFYUI_PID" 2>/dev/null && [[ "$elapsed" -lt "$GRACE_PERIOD" ]]; do
sleep 1
elapsed=$((elapsed + 1))
done
if kill -0 "$COMFYUI_PID" 2>/dev/null; then
log "Process still alive after ${GRACE_PERIOD}s. Sending SIGKILL..."
kill -9 "$COMFYUI_PID" 2>/dev/null || true
sleep 1
fi
else
log "WARN: PID $COMFYUI_PID does NOT belong to $E2E_COMFYUI_ROOT (reused/stale PID). Refusing to kill it."
fi
fi
# Fallback: kill the port listener(s) (covers Manager-restarted processes whose
# PID differs from the recorded one) — but ONLY those verified to belong to this
# E2E root, never a broad pattern pkill that could hit unrelated CI processes.
if ss -tlnp 2>/dev/null | grep -q ":${PORT}\b"; then
log "Port $PORT still in use. Killing verified-own listener(s)..."
for pid in $(listener_pids); do
if belongs_to_root "$pid"; then
log "Sending SIGTERM to listener PID $pid..."
kill "$pid" 2>/dev/null || true
else
log "WARN: PID $pid on port $PORT is not part of $E2E_COMFYUI_ROOT — leaving it alone."
fi
done
sleep 2
for pid in $(listener_pids); do
if belongs_to_root "$pid"; then
log "Listener PID $pid still alive. Sending SIGKILL..."
kill -9 "$pid" 2>/dev/null || true
fi
done
sleep 1
fi
rm -f "$PID_FILE"
if ss -tlnp 2>/dev/null | grep -q ":${PORT}\b"; then
die "Port $PORT is still in use after shutdown"
fi
log "ComfyUI stopped."
-400
View File
@@ -1,400 +0,0 @@
"""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 asyncio
import ast
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 aiohttp
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-reinstall', 'fixture-update', '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()
# Redirect only the external Registry in both ComfyUI and its restore subprocess.
REGISTRY_BOOTSTRAP = '''
import asyncio, json, os, sys, urllib.request
sys.path.insert(0, os.environ['CM_E2E_MANAGER_GLOB'])
import manager_core, cnr_utils, manager_util
cnr_utils.base_url = os.environ['CM_E2E_REGISTRY']
with urllib.request.urlopen(cnr_utils.base_url + '/nodes') as response:
manager_util.save_to_cache(cnr_utils.base_url + '/nodes', json.load(response))
asyncio.run(manager_core.unified_manager.reload('cache', dont_wait=False))
manager_core.unified_manager.custom_node_map_cache[(manager_core.normalize_channel('default'), 'cache')] = manager_core.NormalizedKeyDict()
'''
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"
@contextmanager
def running_server(root, listen, override, registry, security='normal'):
custom_nodes = root / 'custom_nodes'
custom_nodes.mkdir(exist_ok=True)
mount = custom_nodes / 'comfyui-manager'
if not mount.exists():
mount.symlink_to(REPO_ROOT, target_is_directory=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'
)
# cm-cli.py inherits this test-only IO redirection from its real parent.
hook = root / 'sitecustomize.py'
hook.write_text("import os, sys\nif os.path.basename(sys.argv[0]) == 'cm-cli.py':\n"
" from comfy.cli_args import args\n"
" args.base_directory = os.environ['CM_E2E_BASE']\n"
+ '\n'.join(' ' + line for line in REGISTRY_BOOTSTRAP.splitlines()))
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
base = f'http://127.0.0.1:{port}'
env = dict(os.environ, PYTHONUNBUFFERED='1',
PYTHONPATH=os.pathsep.join([str(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_MANAGER_GLOB=str(REPO_ROOT / 'glob'), CM_E2E_REGISTRY=registry.url)
command = [str(E2E_ROOT / 'venv/bin/python'), '-c', BOOTSTRAP, '--cpu',
'--base-directory', str(root), '--listen', listen, '--port', str(port),
'--database-url', f'sqlite:///{root / "comfyui.db"}']
log_path = root / ('server-' + uuid.uuid4().hex + '.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()[-6000:]
try:
if requests.get(base + '/system_stats', timeout=1).status_code == 200:
break
except requests.RequestException:
pass
time.sleep(.2)
else:
pytest.fail(log_path.read_text()[-6000:])
assert requests.get(base + '/manager/version', timeout=5).status_code == 200, log_path.read_text()[-6000:]
assert 'PRESTARTUP FAILED' not in log_path.read_text(), log_path.read_text()
yield SimpleNamespace(root=root, base=base, listen=listen, override=override,
security=security, registry=registry, log=log_path, env=env)
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):
with running_server(tmp_path, '0.0.0.0', False, registry) as server:
env = server.env
command = [str(E2E_ROOT / 'venv/bin/python'), str(REPO_ROOT / 'cm-cli.py'), 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.fixture(scope='module', params=[
('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):
listen, override, security = request.param
root = tmp_path_factory.mktemp('flagged-v3')
with running_server(root, listen, override, registry, security) as server:
yield server
def install(server, node, version, operation='install'):
async def request_and_wait():
ui_id = uuid.uuid4().hex
params = {'id': node, 'version': '1.0.0', 'selected_version': version,
'mode': 'cache', 'channel': 'default', 'ui_id': ui_id,
'repository': 'https://example.invalid/fixture'}
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=40)) as session:
# Subscribe first: a fast worker can emit completion before POST returns.
async with session.ws_connect(server.base + '/ws?clientId=' + ui_id) as ws:
async with session.post(server.base + '/manager/queue/' + operation, json=params) as response:
if response.status != 200:
return {'http': response.status, 'message': await response.text()}
async with session.post(server.base + '/manager/queue/start', headers={'Content-Type': 'application/json'}) as response:
response.raise_for_status()
while True:
event = await ws.receive_json(timeout=30)
data = event.get('data', {})
if event.get('type') == 'cm-queue-status' and data.get('status') == 'done':
if ui_id in data.get('nodepack_result', {}):
return {'http': 200, 'message': data['nodepack_result'][ui_id]}
return asyncio.run(request_and_wait())
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',
'trusted private network', 'Restart ComfyUI'):
assert detail in log
def assert_flagged_denial(result, log):
assert result['message'] == ('This action is not allowed by the current security configuration. '
'See the terminal for details.'), result
assert_terminal_guidance(log)
@pytest.mark.parametrize('node,version,flagged', [
('fixture-active', '1.0.0', False), ('fixture-flagged', '2.0.0', True),
('fixture-pending', '3.0.0', False), ('fixture-banned', '1.0.0', False),
('fixture-latest', 'latest', True),
])
def test_install_policy(comfy_server, node, version, flagged):
server = comfy_server
log_before = len(server.log.read_text())
before = len(server.registry.calls)
result = install(server, node, version)
calls = server.registry.calls[before:]
strong = server.security == 'strong'
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.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
if allowed:
assert result['message'] == 'success', result
assert marker.read_text() == ('2.0.0' if version == 'latest' else version)
elif strong:
assert result['http'] == 403, result
elif flagged:
assert_flagged_denial(result, server.log.read_text()[log_before:])
@pytest.mark.parametrize('operation', ['install', 'reinstall', 'update'])
def test_existing_pack_policy(comfy_server, operation):
server = comfy_server
if server.security == 'strong':
pytest.skip('Existing-pack transitions require an installed pack')
node = {'install': 'fixture-switch', 'reinstall': 'fixture-reinstall', 'update': 'fixture-update'}[operation]
assert install(server, node, '1.0.0')['message'] == 'success'
marker = server.root / 'custom_nodes' / node / 'installed.txt'
log_before = len(server.log.read_text())
before = len(server.registry.calls)
result = install(server, node, '2.0.0', operation)
calls = server.registry.calls[before:]
allowed = server.override or server.listen == '127.0.0.1'
assert sum('/install' in call for call in calls) == 1, calls
if allowed:
assert result['message'] == 'success', result
if operation == 'reinstall':
assert marker.read_text() == '2.0.0', server.log.read_text()[-6000:]
else:
assert marker.read_text() == '1.0.0'
assert 'NodeVersionStatusFlagged' in (server.root / 'user/__manager/startup-scripts/install-scripts.txt').read_text()
else:
assert_flagged_denial(result, server.log.read_text()[log_before:])
assert marker.read_text() == '1.0.0'
assert any(call.startswith('/zip/') for call in calls) is (allowed and operation == 'reinstall')
@pytest.mark.parametrize('restart_listen,restart_override,allowed', [
('0.0.0.0', False, False), ('0.0.0.0', True, True), ('127.0.0.1', False, True),
])
@pytest.mark.parametrize('stored_status', [True, False])
def test_restart_uses_current_policy(tmp_path, registry, restart_listen, restart_override, allowed, stored_status):
with running_server(tmp_path, '127.0.0.1', False, registry) as server:
assert install(server, 'fixture-switch', '1.0.0')['message'] == 'success'
assert install(server, 'fixture-switch', '2.0.0')['message'] == 'success'
if not stored_status:
reservation = tmp_path / 'user/__manager/startup-scripts/install-scripts.txt'
record = ast.literal_eval(reservation.read_text().strip())
assert record[1] == '#LAZY-CNR-SWITCH-SCRIPT'
assert len(record) == 9
reservation.write_text(repr(record[:8]) + '\n')
marker = tmp_path / 'custom_nodes/fixture-switch/installed.txt'
original = (marker.read_bytes(), marker.stat().st_mtime_ns)
before = len(registry.calls)
with running_server(tmp_path, restart_listen, restart_override, registry) as server:
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 allowed
if allowed:
assert marker.read_text() == '2.0.0', server.log.read_text()[-6000:]
else:
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
if stored_status:
assert_terminal_guidance(server.log.read_text())
else:
assert 'stored Registry status is missing' in server.log.read_text()
assert 'Request the installation again' in server.log.read_text()
@pytest.mark.parametrize('surface,payload,flag', [
('git_url', {'url': 'https://example.invalid/fixture'}, 'allow_git_url_install'),
('pip', {'packages': 'fixture-do-not-install'}, 'allow_pip_install'),
])
def test_other_install_flags_remain_required(comfy_server, surface, payload, flag):
server = comfy_server
before = len(server.registry.calls)
response = requests.post(server.base + '/customnode/install/' + surface, json=payload, timeout=10)
assert response.status_code == 403, response.text
assert response.json() == {'error': flag}
assert server.registry.calls[before:] == []
@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_inherits_parent_policy(tmp_path, registry, 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, '127.0.0.1', False, registry, security='normal-') as server:
if existing:
assert install(server, 'fixture-snapshot', '1.0.0')['message'] == 'success'
assert marker.read_text() == '1.0.0'
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 + '/snapshot/restore',
json={'target': snapshot.stem}, 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, listen, override, registry) as server:
log = 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
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()
-752
View File
@@ -1,752 +0,0 @@
"""GOAL #60 — Real-server E2E for the dedicated install flags (worktree-mounted Manager).
Boots a REAL ComfyUI server from a disposable test root
(`E2E_COMFYUI_ROOT`, built by tests/e2e/scripts/setup_e2e_env.sh) with
the Manager mounted via `git worktree add --detach` (NEVER pip-installed
— [D2]) and exercises both dedicated-flag surfaces over live HTTP.
Usage:
bash tests/e2e/scripts/setup_e2e_env.sh # once (E2E-SC-01)
E2E_COMFYUI_ROOT=/path/to/root pytest tests/e2e/test_e2e_install_flags.py -v
Per-row map (goal60-scenarios.md, 24 rows — spec §3 BINDING):
SC-01 setup_e2e_env.sh (pre-suite script; idempotent build + marker — not a pytest test)
SC-02 mount_worktree fixture create path (SHA pin, .git-file, no-pip, printed SHA)
SC-03 mount_worktree fixture reuse path + path-prefix scoping invariant
SC-04 _start_server via start_comfyui.sh (readiness poll, restart tolerance,
per-launch log comfyui.<port>.<launch-id>.log)
SC-05 test_00_smoke_manager_version in EVERY server-up class (+abort guard)
SC-06 _stage via stage_flags.sh (backup-if-absent; restart-only by construction)
SC-07 class fixture finalizers (stop + port-free + config restore + backup DELETE)
+ mount_worktree finalizer (unmount + prune + absence assert)
SC-10 TestDenyArms.test_01_sa_deny SC-11 TestDenyArms.test_02_sb_deny
SC-12 TestAllowArms.test_01_git_url_allow
SC-13 TestAllowArms.test_02_pip_allow_reserved (anti-false-PASS — VERBATIM)
SC-14 TestAllowArms.test_03_restart_consumes_reservation (R-A through the holder)
SC-20 _pre_guards in both class fixtures (before any request)
SC-21 TestAllowArms.test_04_clone_residual_cleanup (+ installed-index cross-check)
SC-22 TestAllowArms.test_05_pip_residual_uninstall
SC-23 _reservation_guard — UNCONDITIONAL fixture-teardown guard (failure path)
SC-24 TestZeroResidual.test_99_zero_residual_sweep (unmount half lives in the
mount_worktree finalizer — it cannot be asserted from inside the session)
SC-30 module-level pytestmark (env unset -> all SKIP; unit suite unaffected)
SC-31 module-level pytestmark (marker absent -> all SKIP)
SC-32 needs_network marker on fixture-dependent (allow-arm / public) rows
SC-33 collection safety by construction: stdlib + pytest + requests
(via pytest.importorskip) ONLY — no glob/ imports, no server imports,
HTTP only at test time
SC-40 TestPublicListener (opt-in E2E_PUBLIC_LISTEN=1; L-P @ 0.0.0.0)
SC-41 batch S-C/S-C' E2E — DEFERRED (Q-5; spec FREEZE item 3; recorded here)
SC-42 TestAllowArms.test_06_requirements_watchdog (L-A launch log)
Fixture-lifecycle ownership (spec §3 BINDING block):
- every class server fixture DECLARES mount_worktree (mount-before-launch);
- process handle lives in a MUTABLE ServerHolder owned by the fixture;
teardown stops the CURRENT holder content (whatever launch identity is live);
- SC-14 restarts THROUGH the holder (stop L-A -> launch R-A -> replace handle);
- stop-before-next-class is structural (pytest class-fixture scoping);
- `requests` is imported via pytest.importorskip (absence degrades to SKIP).
T6 note: no tests/e2e/conftest.py — all fixtures are single-module, so the
optional T6 file is not demanded (spec §2 T6 condition not met).
"""
from __future__ import annotations
import configparser
import os
import shutil
import socket
import subprocess
import sys
import time
import uuid
from pathlib import Path
import pytest
# ---------------------------------------------------------------------------
# Skip gates (E2E-SC-30/31) — BEFORE anything env-dependent
# ---------------------------------------------------------------------------
E2E_ROOT = os.environ.get("E2E_COMFYUI_ROOT", "")
_MARKER_OK = bool(E2E_ROOT) and os.path.isfile(os.path.join(E2E_ROOT, ".e2e_setup_complete"))
pytestmark = pytest.mark.skipif(
not _MARKER_OK,
reason="E2E_COMFYUI_ROOT not set or E2E environment not ready (.e2e_setup_complete missing)",
)
# requests: test-extra — absence degrades to SKIP, never a collection error
# (spec §3 binding block item 5; [D4]).
requests = pytest.importorskip("requests")
# ---------------------------------------------------------------------------
# Constants / paths
# ---------------------------------------------------------------------------
PORT = int(os.environ.get("PORT", "8189"))
TIMEOUT = int(os.environ.get("TIMEOUT", "120"))
BASE_URL = f"http://127.0.0.1:{PORT}"
THIS_DIR = Path(__file__).resolve().parent
SCRIPTS_DIR = THIS_DIR / "scripts"
MANAGER_REPO = THIS_DIR.parents[1] # repo root of the checkout running the suite
ROOT = Path(E2E_ROOT) if E2E_ROOT else Path(".")
COMFY_DIR = ROOT / "comfyui"
CN_DIR = COMFY_DIR / "custom_nodes"
MOUNT = CN_DIR / "comfyui-manager"
CFG = COMFY_DIR / "user" / "__manager" / "config.ini"
CFG_BACKUP = Path(str(CFG) + ".before-flags")
SCRIPTS_FILE = COMFY_DIR / "user" / "__manager" / "startup-scripts" / "install-scripts.txt"
LOGS_DIR = ROOT / "logs"
VENV_PY = ROOT / "venv" / "bin" / "python"
# Owned fixtures ONLY (goal60-scenarios.md Conventions; [D3])
NODEPACK_URL = "https://github.com/ltdrdata/nodepack-test1-do-not-install"
PACK_NAME = "nodepack-test1-do-not-install"
# pip stimulus uses the git+ scheme: pip/uv require it for VCS URLs — a
# plain GitHub repo URL serves HTML and cannot install (verified by probe;
# spec amendment requested via leader pushback 2026-06-08; the SC-13/14
# oracle itself is encoded VERBATIM).
PIP_URL = "git+https://github.com/ltdrdata/pip-test1-do-not-install"
PIP_PKG = "pip-test1-do-not-install"
PIP_IMPORT = "pip_test1_do_not_install"
PIP_MARKER = "pip-test1-do-not-install:ok"
# Amendment A2 (live-run finding, leader-approved): the S-A nodepack fixture
# is deliberately NOT zero-dep — it pins python-slugify==8.0.4 in its
# requirements as the invariant-4 ride-along proof vehicle. The SC-42
# watchdog therefore allowlists exactly that requirement, and the
# transitive-dep residual class is swept at allow-class teardown + SC-24.
# (The S-B pip fixture IS zero-dep as documented.)
NODEPACK_PINNED_REQ = "python-slugify==8.0.4"
TRANSITIVE_DEPS = ("python-slugify", "text-unidecode")
POLL_TIMEOUT = 60
POLL_INTERVAL = 1.0
# Distinctive substrings of the flag-naming denial constants @ d45c8e6b
DENY_COPY_GIT = "'allow_git_url_install = true' in config.ini"
DENY_COPY_PIP = "'allow_pip_install = true' in config.ini"
# Old security_level-attributing copy (must NOT appear on flag denials)
OLD_COPY_GENERAL = "is not allowed in this security_level"
OLD_COPY_NORMAL_MINUS = "set the security level to"
# ---------------------------------------------------------------------------
# Network probe (E2E-SC-32) — evaluated ONLY when the env gate is open, so
# collection without the env performs no network IO (SC-33).
# ---------------------------------------------------------------------------
def _network_available() -> bool:
try:
with socket.create_connection(("github.com", 443), timeout=5):
return True
except OSError:
return False
_NETWORK = _network_available() if _MARKER_OK else False
needs_network = pytest.mark.skipif(
not _NETWORK,
reason="github.com unreachable — network-dependent fixture row skipped (E2E-SC-32)",
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _run(cmd, check=False, timeout=180, env=None, cwd=None):
return subprocess.run(
cmd, capture_output=True, text=True, timeout=timeout, check=check,
env=env, cwd=cwd,
)
def _script(name: str) -> str:
return str(SCRIPTS_DIR / name)
def _script_env(**extra) -> dict:
env = {**os.environ, "E2E_COMFYUI_ROOT": str(ROOT), "PORT": str(PORT),
"TIMEOUT": str(TIMEOUT)}
env.update({k: str(v) for k, v in extra.items()})
return env
def _pack_dir(name: str = PACK_NAME) -> Path:
return CN_DIR / name
def _pack_exists(name: str = PACK_NAME) -> bool:
return _pack_dir(name).is_dir()
def _remove_pack(name: str = PACK_NAME) -> None:
"""Donor _remove_pack pattern: rmtree 3-retry + rename-to-.trash_ fallback."""
path = _pack_dir(name)
if path.is_symlink():
path.unlink()
return
if not path.is_dir():
return
for attempt in range(3):
try:
shutil.rmtree(path)
return
except OSError:
if attempt < 2:
time.sleep(1)
trash = CN_DIR / f".trash_{uuid.uuid4().hex[:8]}"
try:
os.rename(path, trash)
shutil.rmtree(trash, ignore_errors=True)
except OSError:
shutil.rmtree(path, ignore_errors=True)
def _wait_for(predicate, timeout=POLL_TIMEOUT, interval=POLL_INTERVAL) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
time.sleep(interval)
return False
def _pip_import_rc() -> int:
return _run([str(VENV_PY), "-c", f"import {PIP_IMPORT}"]).returncode
def _pip_marker_rc() -> "subprocess.CompletedProcess":
return _run([
str(VENV_PY), "-c",
f"import {PIP_IMPORT} as m; assert m.MARKER == '{PIP_MARKER}'",
])
def _pip_uninstall() -> "subprocess.CompletedProcess":
return _run([str(VENV_PY), "-m", "pip", "uninstall", "-y", PIP_PKG])
def _scripts_clean() -> bool:
"""True when the reservation file is absent OR carries no pip-test1 line."""
if not SCRIPTS_FILE.exists():
return True
return "pip-test1" not in SCRIPTS_FILE.read_text(errors="ignore")
def _reservation_guard() -> None:
"""E2E-SC-23 — UNCONDITIONAL teardown guard for the unconsumed-reservation
leak class: a leaked line would pip-install on ANY next boot of this root."""
if SCRIPTS_FILE.exists() and "pip-test1" in SCRIPTS_FILE.read_text(errors="ignore"):
SCRIPTS_FILE.unlink()
assert _scripts_clean(), "reservation guard failed to clear pip-test1 line (SC-23)"
def _restore_config() -> None:
"""E2E-SC-07: restore from backup, then DELETE the backup and assert absence
(a surviving stale backup would silently restore an outdated config at a
FUTURE run's teardown via the create-only-if-absent rule)."""
if CFG_BACKUP.exists():
shutil.copyfile(CFG_BACKUP, CFG)
CFG_BACKUP.unlink()
assert not CFG_BACKUP.exists(), "config backup must be DELETED after restore (SC-07/24)"
def _port_free() -> bool:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(1)
return s.connect_ex(("127.0.0.1", PORT)) != 0
finally:
s.close()
def _pre_guards() -> None:
"""E2E-SC-20 — before EACH arm's matrix rows; assert all three."""
_remove_pack(PACK_NAME)
assert not _pack_exists(PACK_NAME), (
f"pre-guard: failed to clean {PACK_NAME} (file locks?)"
)
_pip_uninstall() # ignore rc: not-installed is fine
assert _pip_import_rc() != 0, "pre-guard: pip fixture importable before test"
_reservation_guard()
assert _scripts_clean(), "pre-guard: stale pip-test1 reservation present"
# ---------------------------------------------------------------------------
# Server lifecycle (E2E-SC-04 + spec §3 binding holder contract)
# ---------------------------------------------------------------------------
class ServerHolder:
"""Mutable process-handle holder owned by the class server fixture.
The holder always points at the CURRENT launch identity; SC-14 replaces
its content when it restarts through it, so class teardown stops
whatever is live — no orphan."""
def __init__(self):
self.launch_id: str | None = None
self.log_path: Path | None = None
self.live = False
self.smoke_ok = False
def _stage(mode: str) -> None:
r = _run(["bash", _script("stage_flags.sh"), mode], env=_script_env(), check=False)
assert r.returncode == 0, f"stage_flags.sh {mode} failed:\n{r.stdout}\n{r.stderr}"
assert CFG_BACKUP.exists(), "backup must exist after staging (SC-06)"
def _start_server(holder: ServerHolder, launch_id: str, listen: str = "127.0.0.1") -> None:
r = _run(
["bash", _script("start_comfyui.sh")],
env=_script_env(LISTEN=listen, LAUNCH_ID=launch_id),
timeout=TIMEOUT + 90,
)
assert r.returncode == 0, (
f"start_comfyui.sh failed for launch {launch_id}:\n{r.stdout}\n{r.stderr}"
)
holder.launch_id = launch_id
holder.log_path = LOGS_DIR / f"comfyui.{PORT}.{launch_id}.log"
holder.live = True
assert holder.log_path.is_file(), "per-launch log file missing (SC-04)"
def _stop_server(holder: ServerHolder) -> None:
if not holder.live:
return
r = _run(["bash", _script("stop_comfyui.sh")], env=_script_env(), timeout=120)
assert r.returncode == 0, f"stop_comfyui.sh failed:\n{r.stdout}\n{r.stderr}"
holder.live = False
assert _port_free(), "port still bound after stop (SC-07)"
def _launch_log(holder: ServerHolder) -> str:
assert holder.log_path is not None and holder.log_path.is_file()
return holder.log_path.read_text(errors="ignore")
def _named_log(launch_id: str) -> str:
p = LOGS_DIR / f"comfyui.{PORT}.{launch_id}.log"
assert p.is_file(), f"launch log for {launch_id} missing"
return p.read_text(errors="ignore")
def _require_smoke(holder: ServerHolder) -> None:
"""SC-05 abort semantics: matrix rows refuse to run after a smoke failure
so a mount/activation problem cannot produce misleading 404 results."""
if not holder.smoke_ok:
pytest.fail(
"aborting matrix row: smoke (GET /manager/version) has not passed "
"for this launch — mount/activation problem or Q-2 bundled-manager "
"collision (E2E-SC-05)"
)
def _smoke(holder: ServerHolder) -> None:
r = requests.get(f"{BASE_URL}/manager/version", timeout=10)
assert r.status_code == 200, (
f"smoke FAILED: GET /manager/version -> {r.status_code}; the "
f"worktree-mounted plugin did not register its routes (E2E-SC-05). "
f"Log tail:\n{_launch_log(holder)[-2000:]}"
)
assert r.text.strip(), "smoke: /manager/version body empty"
holder.smoke_ok = True
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(scope="session")
def mount_worktree():
"""E2E-SC-02/03 — SOLE owner of mount create / reuse-verify / teardown."""
ref = os.environ.get("E2E_MANAGER_REF", "HEAD")
r = _run(["git", "-C", str(MANAGER_REPO), "rev-parse", f"{ref}^{{commit}}"], check=True)
sha = r.stdout.strip()
# Scoping invariant (SC-03): the mount path is {ROOT}-prefixed and is
# NEVER under the members' .claude/worktrees tree. Every mount/teardown
# command below references ONLY this path.
mount = MOUNT.resolve()
assert ".claude/worktrees" not in str(mount).replace(os.sep, "/"), (
"mount path must never live under member worktrees (SC-03 scoping)"
)
assert str(mount).startswith(str(ROOT.resolve())), (
"mount path must be {ROOT}-prefixed (SC-03 scoping)"
)
porcelain = _run(["git", "-C", str(MANAGER_REPO), "worktree", "list", "--porcelain"]).stdout
if f"worktree {mount}" in porcelain:
# Reuse path (SC-03)
head = _run(["git", "-C", str(mount), "rev-parse", "HEAD"]).stdout.strip()
if head != sha:
_run(["git", "-C", str(mount), "checkout", "--detach", sha], check=True)
else:
# Create path (SC-02)
_run(["git", "-C", str(MANAGER_REPO), "worktree", "add", "--detach",
str(mount), sha], check=True)
# From here a worktree exists at `mount`. Any failure between now and the
# yield (the verify asserts below) must STILL run teardown — otherwise a
# failed setup leaks an orphaned worktree into the next session (review
# follow-up). Hence the try/finally wraps verify + yield, not just yield.
try:
# Verify (every session)
head = _run(["git", "-C", str(mount), "rev-parse", "HEAD"]).stdout.strip()
assert head == sha, f"mount HEAD {head} != expected {sha} (SC-02)"
print(f"[mount_worktree] Manager mounted at {mount} @ SHA {sha}") # [D2] traceability
assert (mount / ".git").is_file(), (
".git in the mount must be a FILE (gitdir pointer) — worktree layout (SC-02)"
)
# [D2] other half: no pip-installed Manager in the venv; per MM §2.2 no
# assertion anywhere relies on the mounted Manager's OWN version/remote
# self-report (.git-file degradation accepted by design — spec R5).
for dist in ("comfyui-manager", "ComfyUI-Manager"):
rc = _run([str(VENV_PY), "-m", "pip", "show", dist]).returncode
assert rc != 0, f"pip-installed Manager '{dist}' found in venv — violates [D2]"
yield {"path": mount, "sha": sha}
finally:
if os.environ.get("E2E_KEEP_MOUNT"):
print(f"[mount_worktree] E2E_KEEP_MOUNT set — keeping {mount}")
else:
# Exception-safe: prune + absence asserts run even when remove fails
# (review iter-2 — crash residue must still be surfaced honestly).
try:
_run(["git", "-C", str(MANAGER_REPO), "worktree", "remove", "--force", str(mount)],
check=True)
finally:
_run(["git", "-C", str(MANAGER_REPO), "worktree", "prune"])
porcelain = _run(["git", "-C", str(MANAGER_REPO), "worktree", "list", "--porcelain"]).stdout
assert f"worktree {mount}" not in porcelain, "mount still listed after remove (SC-07)"
assert not mount.exists(), "mount dir still present after remove (SC-07)"
@pytest.fixture(scope="class")
def deny_server(mount_worktree):
"""L-D: both flags ABSENT (live 'missing key reads false'), loopback."""
_pre_guards() # SC-20
_stage("deny") # SC-06
holder = ServerHolder()
_start_server(holder, "L-D") # SC-04
yield holder
# Exception-safe teardown chain (review iter-2 must-fix): a failing
# stop is exactly the crashed-run shape SC-23 exists for — the guard
# and the config restore MUST run regardless.
try:
_stop_server(holder) # SC-07 (current handle, whatever is live)
finally:
try:
_reservation_guard() # SC-23 — UNCONDITIONAL
finally:
_restore_config() # SC-07: restore + DELETE backup
@pytest.fixture(scope="class")
def allow_server(mount_worktree):
"""L-A: both flags true, loopback. SC-14 mutates the holder to R-A."""
_pre_guards() # SC-20 (re-guards before the allow arm)
_stage("allow") # SC-06
holder = ServerHolder()
_start_server(holder, "L-A")
yield holder
# Exception-safe teardown chain (review iter-2 must-fix): every
# residual guard runs even when the stop (or an earlier sweep step)
# raises — SC-23 is contractually UNCONDITIONAL (R3 leak class).
try:
_stop_server(holder) # stops the CURRENT identity (L-A or R-A)
finally:
try:
_remove_pack(PACK_NAME) # defensive re-sweep (primary assert is SC-21)
_pip_uninstall() # defensive (primary assert is SC-22)
# Amendment A2: sweep the S-A fixture's transitive-dep residual
# class (python-slugify + text-unidecode ride the git
# transaction; verified NOT in ComfyUI's own requirements).
_run([str(VENV_PY), "-m", "pip", "uninstall", "-y", *TRANSITIVE_DEPS])
finally:
try:
_reservation_guard() # SC-23 — UNCONDITIONAL (failure path cover)
finally:
_restore_config()
@pytest.fixture(scope="class")
def public_server(mount_worktree):
"""L-P (opt-in, Q-7): both flags true, 0.0.0.0 listener."""
_pre_guards()
_stage("allow")
holder = ServerHolder()
_start_server(holder, "L-P", listen="0.0.0.0")
yield holder
# Exception-safe teardown chain (review iter-2 must-fix).
try:
_stop_server(holder)
finally:
try:
_reservation_guard()
finally:
_restore_config()
# ---------------------------------------------------------------------------
# Classes — definition order IS execution order (deny first on the fresh env)
# ---------------------------------------------------------------------------
class TestDenyArms:
"""L-D launch: SC-05 smoke, SC-10, SC-11 (deny rows are offline-safe —
denial happens before any network access)."""
def test_00_smoke_manager_version(self, deny_server):
_smoke(deny_server) # SC-05
def test_01_sa_deny(self, deny_server):
"""E2E-SC-10: S-A deny — 403 + exact flag token + no artifact + honest log."""
_require_smoke(deny_server)
r = requests.post(f"{BASE_URL}/customnode/install/git_url",
json={"url": NODEPACK_URL}, timeout=30)
assert r.status_code == 403
assert r.json() == {"error": "allow_git_url_install"}, (
f"deny body must carry the flag token, got {r.text!r}"
)
assert not _pack_exists(PACK_NAME), "clone artifact created on DENY (SC-10)"
log = _launch_log(deny_server)
assert DENY_COPY_GIT in log, "flag-naming denial copy missing from L-D log"
assert OLD_COPY_GENERAL not in log and OLD_COPY_NORMAL_MINUS not in log, (
"denial attributed to security_level — honest-copy violation (SC-10)"
)
def test_02_sb_deny(self, deny_server):
"""E2E-SC-11: S-B deny — 403 + flag token + no reservation + not importable."""
_require_smoke(deny_server)
r = requests.post(f"{BASE_URL}/customnode/install/pip",
json={"packages": PIP_URL}, timeout=30)
assert r.status_code == 403
assert r.json() == {"error": "allow_pip_install"}
assert _scripts_clean(), "reservation recorded on DENY (SC-11)"
assert _pip_import_rc() != 0, "pip fixture importable after DENY (SC-11)"
log = _launch_log(deny_server)
assert DENY_COPY_PIP in log, "flag-naming denial copy missing from L-D log"
class TestAllowArms:
"""L-A launch + R-A restart. ORDERED methods (donor sequential-class
precedent): SC-12 -> SC-13 -> SC-14 -> SC-21 -> SC-22 -> SC-42."""
def test_00_smoke_manager_version(self, allow_server):
_smoke(allow_server) # SC-05 (re-smoke on the new launch)
@needs_network
def test_01_git_url_allow(self, allow_server):
"""E2E-SC-12: S-A allow — 200 + real clone + clone-target proof."""
_require_smoke(allow_server)
r = requests.post(f"{BASE_URL}/customnode/install/git_url",
json={"url": NODEPACK_URL}, timeout=120)
assert r.status_code == 200, f"S-A allow expected 200, got {r.status_code}: {r.text!r}"
assert _wait_for(lambda: _pack_exists(PACK_NAME)), (
f"{PACK_NAME} not cloned within {POLL_TIMEOUT}s (SC-12)"
)
git_dir = _pack_dir() / ".git"
assert git_dir.is_dir(), "no .git DIRECTORY — not a real clone (SC-12)"
# Donor clone-target proof: .git/config [remote "origin"] url matches
# the requested URL modulo the .git suffix.
cp = configparser.ConfigParser()
cp.read(git_dir / "config")
section = 'remote "origin"'
assert section in cp, f'[{section}] missing from .git/config: {cp.sections()!r}'
remote_url = cp[section].get("url", "").rstrip("/")
expected = NODEPACK_URL.rstrip("/")
assert remote_url in (expected, expected + ".git"), (
f"clone targeted the WRONG repo: {remote_url!r} != {expected!r} (SC-12)"
)
@needs_network
def test_02_pip_allow_reserved(self, allow_server):
"""E2E-SC-13 (VERBATIM anti-false-PASS oracle): 200 = RESERVED, NOT
INSTALLED. Asserting import success here would be the exact false-PASS
the MM correction exists to prevent."""
_require_smoke(allow_server)
r = requests.post(f"{BASE_URL}/customnode/install/pip",
json={"packages": PIP_URL}, timeout=30)
assert r.status_code == 200, f"S-B allow expected 200, got {r.status_code}: {r.text!r}"
assert SCRIPTS_FILE.is_file(), "no reservation file after S-B allow (SC-13)"
content = SCRIPTS_FILE.read_text(errors="ignore")
reserved_lines = [
ln for ln in content.splitlines()
if "'#FORCE'" in ln and PIP_PKG in ln
]
assert reserved_lines, (
f"no reservation line with '#FORCE' + {PIP_PKG!r} in {SCRIPTS_FILE}:\n{content}"
)
# MANDATORY: the package is NOT installed at this point.
assert _pip_import_rc() != 0, (
"pip fixture importable right after the 200 — reservation semantics "
"violated, or a previous run leaked state (SC-13 anti-false-PASS)"
)
@needs_network
def test_03_restart_consumes_reservation(self, allow_server):
"""E2E-SC-14: R-A restart THROUGH the holder; the consuming boot
executes + removes the reservation; MARKER import proves field-level."""
_require_smoke(allow_server)
assert SCRIPTS_FILE.is_file(), "precondition: reservation must exist (SC-13 first)"
# Restart THROUGH the holder (spec §3 binding item 3): stop the live
# L-A process, relaunch as R-A with the SAME staged config, replace
# the handle — class teardown then stops R-A.
_stop_server(allow_server)
_start_server(allow_server, "R-A")
_smoke(allow_server)
# Field-level positive proof (not just exit code):
marker = _pip_marker_rc()
assert marker.returncode == 0, (
f"MARKER import failed after the consuming restart (SC-14):\n"
f"{marker.stderr}\nR-A log tail:\n{_named_log('R-A')[-3000:]}"
)
assert not SCRIPTS_FILE.exists(), (
"install-scripts.txt NOT removed by the consuming boot (SC-14 self-clean)"
)
ra_log = _named_log("R-A")
assert "## ComfyUI-Manager: EXECUTE =>" in ra_log and PIP_PKG in ra_log, (
"R-A log lacks the startup-script execution block (SC-14)"
)
assert "Startup script completed." in ra_log, (
"R-A log lacks the startup-script completion line (SC-14)"
)
@needs_network
def test_04_clone_residual_cleanup(self, allow_server):
"""E2E-SC-21: clone-dir hygiene; FS-absence primary + installed-index
cross-check while the server is still up (defensive, donor pattern)."""
_remove_pack(PACK_NAME)
assert not _pack_exists(PACK_NAME), "clone dir still present (SC-21 primary)"
try:
r = requests.get(f"{BASE_URL}/customnode/installed", timeout=15)
if r.status_code == 200:
installed = r.json()
assert PACK_NAME not in installed, (
f"{PACK_NAME} still in /customnode/installed after removal (SC-21)"
)
for key, pkg in installed.items():
if isinstance(pkg, dict):
assert pkg.get("cnr_id") != PACK_NAME and pkg.get("aux_id") != PACK_NAME, (
f"installed entry {key!r} still references {PACK_NAME!r} (SC-21)"
)
except (ValueError, requests.RequestException):
# Spec SC-21: if the response schema proves awkward, FS-absence
# alone satisfies this row.
pass
@needs_network
def test_05_pip_residual_uninstall(self, allow_server):
"""E2E-SC-22: S-B residual class 1 (venv package)."""
r = _pip_uninstall()
assert r.returncode == 0, f"pip uninstall failed (SC-22):\n{r.stdout}\n{r.stderr}"
assert _pip_import_rc() != 0, "pip fixture importable after uninstall (SC-22)"
@needs_network
def test_06_requirements_watchdog(self, allow_server):
"""E2E-SC-42 (Q-6 watchdog, amendment A2): every management-script
EXECUTE in the L-A launch log must be attributable to the owned
fixture's OWN pinned requirements (python-slugify==8.0.4 — the
nodepack fixture's deliberate invariant-4 ride-along requirement).
Any other EXECUTE (e.g. a Manager-requirements install — the Q-6
risk this row guards) FAILS the watchdog.
The allowlisted line doubles as LIVE proof of the invariant-4
ride-along class: a dependency pip install executed inside the
git-URL transaction without consulting allow_pip_install."""
la_log = _named_log("L-A")
banner = "## ComfyUI-Manager: EXECUTE =>"
idx = 0
execs = []
while True:
idx = la_log.find(banner, idx)
if idx < 0:
break
execs.append(la_log[idx: idx + 600])
idx += len(banner)
# Non-vacuity (review iter-2 / A2 positive half): the ride-along
# MUST have happened — exactly ONE management-script execution,
# the fixture's single pinned requirement.
assert len(execs) == 1, (
f"expected exactly 1 management-script execution during L-A "
f"(the fixture's pinned requirement ride-along), found "
f"{len(execs)} (SC-42 / A2)"
)
window = execs[0]
assert NODEPACK_PINNED_REQ in window, (
"unexpected management-script execution during L-A — not "
"attributable to the fixture's pinned requirement "
f"({NODEPACK_PINNED_REQ}) (SC-42 watchdog):\n{window}"
)
# Line-level shape: it must be a pip-install command, not an
# arbitrary script that merely mentions the requirement string.
assert "'pip'" in window and "'install'" in window, (
f"EXECUTE block is not a pip-install command (SC-42):\n{window}"
)
@pytest.mark.skipif(
not os.environ.get("E2E_PUBLIC_LISTEN"),
reason="public-listener row is opt-in (E2E_PUBLIC_LISTEN=1) — Q-7 default-off",
)
class TestPublicListener:
"""E2E-SC-40 (opt-in): flags=true + 0.0.0.0 -> still 403 on both surfaces.
Live proof of invariant 2 (predicate = flag AND loopback at REQUEST time)."""
def test_00_smoke_manager_version(self, public_server):
_smoke(public_server)
def test_01_sa_public_deny(self, public_server):
_require_smoke(public_server)
r = requests.post(f"{BASE_URL}/customnode/install/git_url",
json={"url": NODEPACK_URL}, timeout=30)
assert r.status_code == 403
assert r.json() == {"error": "allow_git_url_install"}
assert not _pack_exists(PACK_NAME)
def test_02_sb_public_deny(self, public_server):
_require_smoke(public_server)
r = requests.post(f"{BASE_URL}/customnode/install/pip",
json={"packages": PIP_URL}, timeout=30)
assert r.status_code == 403
assert r.json() == {"error": "allow_pip_install"}
assert _scripts_clean()
class TestZeroResidual:
"""E2E-SC-24: the complete [D3] residual inventory in one assertion block.
Runs AFTER the server classes (their class-scoped fixtures have finalized:
server stopped, config restored, backup deleted). The unmount half of the
inventory is asserted by the mount_worktree finalizer itself — it cannot
be asserted from inside the session while the mount is still live."""
def test_99_zero_residual_sweep(self, mount_worktree):
# custom_nodes clean (incl. .trash_ fallback leftovers)
assert not _pack_exists(PACK_NAME), "nodepack residue in custom_nodes (SC-24)"
leftovers = [p.name for p in CN_DIR.iterdir()
if p.name.startswith((".trash_", PACK_NAME))]
assert not leftovers, f"residual entries in custom_nodes: {leftovers} (SC-24)"
# venv clean
assert _pip_import_rc() != 0, "pip fixture still importable (SC-24)"
# Amendment A2: transitive-dep residual class swept
for dep in TRANSITIVE_DEPS:
rc = _run([str(VENV_PY), "-m", "pip", "show", dep]).returncode
assert rc != 0, f"transitive dep {dep!r} survived the sweep (SC-24 / A2)"
# reservation clean
assert _scripts_clean(), "pip-test1 reservation residue (SC-24)"
# config restored + backup DELETED
assert CFG.is_file(), "config.ini missing after restore (SC-24)"
cfg_text = CFG.read_text(errors="ignore")
assert "allow_git_url_install" not in cfg_text, "staged flag leaked into restored config (SC-24)"
assert "allow_pip_install" not in cfg_text, "staged flag leaked into restored config (SC-24)"
assert not CFG_BACKUP.exists(), "stale config backup survived (SC-24 / peer R2)"
# port free
assert _port_free(), f"port {PORT} still bound (SC-24)"
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-v"]))
-159
View File
@@ -1,159 +0,0 @@
"""Lift real production JS out of the shipped files and execute it in node.
WHY LIFT RATHER THAN IMPORT: the manager's front-end modules pull in
``../../scripts/app.js`` and touch ``document`` at module scope, so node cannot
import them. WHY LIFT RATHER THAN RETYPE: a retyped copy of a formatter stops
tracking the formatter the moment someone edits it, and then the guard passes
while the shipped code regresses. Lifting keeps the executed bytes the shipped
bytes — if the production function changes, so does the text under test.
This mirrors tests/test_manager_markdown_escaping.py, which AST-extracts
``convert_markdown_to_html`` rather than importing manager_server.
Consumers point ``JsSource`` at a directory of .js files; an override directory
(e.g. one populated with ``git show <base>:js/foo.js``) makes the RED half of a
fix reproducible in one command.
"""
import json
import shutil
import subprocess
from html.parser import HTMLParser
from pathlib import Path
NODE = shutil.which("node")
def _skip_literal(source: str, pos: int) -> int:
"""If a literal or comment starts at pos, return the index just past it.
Returns pos unchanged when nothing starts there. Template literals are
consumed whole, which is safe for brace counting because a `${...}`
substitution is itself balanced. A lone `/` is read as a regex literal —
sanitizeHTML's own `.replace(/'/g, ...)` hides an apostrophe inside one, and
no scanned range uses `/` as division. Were that to change, the assertion
below fails loudly rather than returning a wrong slice.
"""
ch = source[pos]
nxt = source[pos + 1] if pos + 1 < len(source) else ""
if ch == "/" and nxt == "/":
return source.index("\n", pos)
if ch == "/" and nxt == "*":
return source.index("*/", pos) + 2
if ch not in "\"'`/":
return pos
cursor = pos + 1
while cursor < len(source):
if source[cursor] == "\\":
cursor += 2
continue
if source[cursor] == ch:
return cursor + 1
cursor += 1
raise AssertionError("unterminated literal at offset %d" % (pos,))
def slice_braced(source: str, start_marker: str) -> str:
"""Return start_marker plus the balanced {...} block that follows it."""
start = source.index(start_marker)
pos = source.index("{", start + len(start_marker))
depth = 0
while pos < len(source):
skipped = _skip_literal(source, pos)
if skipped != pos:
pos = skipped
continue
if source[pos] == "{":
depth += 1
elif source[pos] == "}":
depth -= 1
if depth == 0:
return source[start:pos + 1]
pos += 1
raise AssertionError("unbalanced braces after %r" % (start_marker,))
def slice_object_entry(source: str, marker: str, indent: str = "\t\t") -> str:
"""Return one object literal out of a `}, {`-chained array, by id marker.
These objects are literals inside an array, so the first `{` after the
marker belongs to the NEXT entry — brace matching cannot be used. The entry
instead ends at the first `}` sitting at the array's own indent.
"""
start = source.index(marker)
end = source.index("\n%s}" % indent, start)
return source[start:end]
def line_containing(source: str, marker: str) -> str:
"""Return the single source line that holds `marker` (fails if absent)."""
start = source.index(marker)
line_start = source.rfind("\n", 0, start) + 1
return source[line_start:source.index("\n", start)]
class JsSource:
"""The shipped .js files under test, read from `js_dir`."""
def __init__(self, js_dir):
self.js_dir = Path(js_dir)
self._cache = {}
def text(self, filename: str) -> str:
if filename not in self._cache:
self._cache[filename] = (self.js_dir / filename).read_text(encoding="utf-8")
return self._cache[filename]
def lift_declaration(self, filename: str, marker: str) -> str:
"""Lift an `export function`/`export const` declaration, minus `export`."""
return slice_braced(self.text(filename), marker).replace("export ", "", 1)
def lift_formatter(self, filename: str, anchor: str) -> str:
"""Lift the `formatter: ...` at `anchor` as a bare function expression."""
block = slice_braced(self.text(filename), anchor)
marker = "formatter:"
return block[block.index(marker) + len(marker):].strip()
def lift_span(self, filename: str, start_marker: str, end_marker: str) -> str:
"""Lift the source between two markers, end_marker included."""
source = self.text(filename)
start = source.index(start_marker)
end = source.index(end_marker, start) + len(end_marker)
return source[start:end]
def run_node(script: str) -> dict:
"""Execute an ES-module script and parse the single JSON object it prints."""
assert NODE is not None, "node is required to execute the lifted production JS"
result = subprocess.run(
[NODE, "--input-type=module", "-e", script],
capture_output=True, text=True, timeout=60,
)
assert result.returncode == 0, "node failed:\n%s" % (result.stderr,)
return json.loads(result.stdout)
class Collector(HTMLParser):
"""Collects the tags and attributes a browser would actually build."""
def __init__(self):
super().__init__()
self.tags = []
self.attrs = []
def handle_starttag(self, tag, attrs):
self.tags.append(tag)
self.attrs.extend(attrs)
handle_startendtag = handle_starttag
def parse(markup: str) -> Collector:
collector = Collector()
collector.feed(markup)
collector.close()
return collector
def event_handlers(markup: str):
"""Every on* attribute a browser would attach for this markup."""
return [name for name, _ in parse(markup).attrs if name.lower().startswith("on")]
-32
View File
@@ -1,32 +0,0 @@
"""Load Python escaping code without importing the ComfyUI server.
MANAGER_GLOB_DIR can point to another revision for regression checks. Loading
manager_util by path avoids shadowing the standard library's glob module.
"""
import ast
import importlib.util
import os
import re
from pathlib import Path
GLOB_DIR = Path(os.environ.get("MANAGER_GLOB_DIR") or (Path(__file__).resolve().parent.parent / "glob"))
def load_manager_util():
path = GLOB_DIR / "manager_util.py"
spec = importlib.util.spec_from_file_location("_manager_util_under_test", path)
assert spec is not None and spec.loader is not None, f"cannot load {path}"
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def load_markdown_functions(manager_util):
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
names = {"convert_markdown_to_html", "populate_markdown"}
functions = [node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name in names]
assert len(functions) == len(names) and {node.name for node in functions} == names
namespace = {"re": re, "manager_util": manager_util}
exec(compile(ast.Module(body=functions, type_ignores=[]), "<markdown-extract>", "exec"), namespace)
return namespace
-172
View File
@@ -1,172 +0,0 @@
"""Cache freshness and durability:
- freshness must be mtime-based: on Windows getctime is the CREATION time,
and in-place rewrites never changed it, so every rewritten cache was
'expired' forever after day one;
- writes must be atomic: a kill mid-dump used to leave a truncated cache
that looked fresh but served {} for the whole TTL. A write that fails
part-way leaves the previous cache, the cache keeps its mode, and a cache
that stays open elsewhere is left as it is rather than written in place.
"""
import errno
import json
import os
import sys
import time
from unittest.mock import patch
import pytest
from manager_test_utils import load_manager_util
MANAGER_UTIL = load_manager_util()
def _fresh_cache(tmp_path, body):
cache = tmp_path / "cache.json"
cache.write_text(json.dumps(body), encoding="utf-8")
return cache
def test_rewritten_cache_stays_fresh(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
stale_creation = time.time() - 86401
with patch.object(MANAGER_UTIL, "get_cache_path", return_value=str(cache)), \
patch.object(os.path, "getctime", return_value=stale_creation):
MANAGER_UTIL.save_to_cache("https://example/list.json", {"b": 2}, silent=True)
# the rewrite moved mtime forward; freshness must hold even with a
# creation time older than a day (the Windows getctime regression)
assert MANAGER_UTIL.is_file_created_within_one_day(str(cache)) is True
# age the file explicitly: only then is it expired
old = time.time() - 86401
os.utime(cache, (old, old))
assert MANAGER_UTIL.is_file_created_within_one_day(str(cache)) is False
def test_save_to_cache_leaves_no_tmp_debris_and_valid_json(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
with patch.object(MANAGER_UTIL, "get_cache_path", return_value=str(cache)):
MANAGER_UTIL.save_to_cache("https://example/list.json", {"b": 2}, silent=True)
assert json.loads(cache.read_text(encoding="utf-8")) == {"b": 2}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
def _save(cache, body):
with patch.object(MANAGER_UTIL, "get_cache_path", return_value=str(cache)):
MANAGER_UTIL.save_to_cache("https://example/list.json", body, silent=True)
def test_write_that_fails_on_a_value_keeps_the_previous_cache(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
with pytest.raises(TypeError):
_save(cache, {"b": 2, "c": object()})
assert json.loads(cache.read_text(encoding="utf-8")) == {"a": 1}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
def test_write_that_runs_out_of_space_keeps_the_previous_cache(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
def disk_full(obj, file, **_):
file.write('{"b": ')
raise OSError(errno.ENOSPC, "No space left on device")
with patch.object(MANAGER_UTIL.json, "dump", disk_full), pytest.raises(OSError):
_save(cache, {"b": 2})
assert json.loads(cache.read_text(encoding="utf-8")) == {"a": 1}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits")
def test_cache_keeps_its_mode(tmp_path):
plain = tmp_path / "plain"
plain.write_text("")
default_mode = plain.stat().st_mode & 0o777
plain.unlink()
cache = tmp_path / "cache.json"
_save(cache, {"a": 1})
assert cache.stat().st_mode & 0o777 == default_mode
other_mode = default_mode ^ 0o040 # never what a new file gets
os.chmod(cache, other_mode)
_save(cache, {"b": 2})
assert cache.stat().st_mode & 0o777 == other_mode
def test_cache_is_replaced_where_its_mode_cannot_be_set(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
replace = 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)
with patch.object(os, "chmod", refuse), patch.object(os, "replace", record):
_save(cache, {"b": 2})
assert replaced == [str(cache)]
assert json.loads(cache.read_text(encoding="utf-8")) == {"b": 2}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
def _refusing_replace(refusals):
"""An os.replace that refuses the given number of times, as Windows does
while another reader has the file open, and then replaces."""
replace = 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)
return attempt, attempts
def test_cache_is_replaced_once_the_reader_has_closed_it(tmp_path):
cache = _fresh_cache(tmp_path, {"a": 1})
attempt, attempts = _refusing_replace(2)
with patch.object(os, "replace", attempt), patch.object(MANAGER_UTIL.time, "sleep"), \
patch.object(MANAGER_UTIL.json, "dump", wraps=json.dump) as dump:
_save(cache, {"b": 2})
assert len(attempts) == 3
assert dump.call_count == 1, "the cache must not be written in place"
assert json.loads(cache.read_text(encoding="utf-8")) == {"b": 2}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
def test_cache_that_stays_open_elsewhere_is_left_as_it_is(tmp_path, caplog):
cache = _fresh_cache(tmp_path, {"a": 1})
attempt, attempts = _refusing_replace(100)
with patch.object(os, "replace", attempt), patch.object(MANAGER_UTIL.time, "sleep"), \
patch.object(MANAGER_UTIL, "get_cache_path", return_value=str(cache)), caplog.at_level("INFO"):
# the caller sees no error: it goes on with the data it fetched
MANAGER_UTIL.save_to_cache("https://example/list.json", {"b": 2})
assert len(attempts) == 3
assert json.loads(cache.read_text(encoding="utf-8")) == {"a": 1}
assert [p.name for p in tmp_path.iterdir()] == ["cache.json"]
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(tmp_path):
# a scanner that opens the new file keeps Windows from replacing with it and from removing it
cache = _fresh_cache(tmp_path, {"a": 1})
attempt, attempts = _refusing_replace(100)
def refuse(path):
raise PermissionError(13, "The process cannot access the file", path)
with patch.object(os, "replace", attempt), patch.object(os, "remove", refuse), \
patch.object(MANAGER_UTIL.time, "sleep"):
assert MANAGER_UTIL.write_cache_file(str(cache), {"b": 2}) is False
assert len(attempts) == 3
assert json.loads(cache.read_text(encoding="utf-8")) == {"a": 1}
-131
View File
@@ -1,131 +0,0 @@
"""A channel response that is not JSON is not cached and does not empty the list (#3480).
The channel is a local HTTP server. `get_data_by_mode` is the real function from
manager_core.py, run against a temporary cache directory and a temporary bundled list.
"""
import ast
import asyncio
import json
import os
import pytest
from aiohttp import web
from aiohttp.test_utils import TestServer
from manager_test_utils import GLOB_DIR, load_manager_util
FILENAME = "model-list.json"
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"),
]
@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")
def load_get_data_by_mode(manager_util, channel_url):
source = (GLOB_DIR / "manager_core.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "get_data_by_mode"]
assert len(nodes) == 1
config = {"channel_url": channel_url, "network_mode": "public"}
namespace = {"os": os, "json": json, "manager_util": manager_util,
"get_config": lambda: config, "normalize_channel": lambda channel: channel}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "manager_core.py", "exec"), namespace)
return namespace["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(tmp_path, 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:
manager_util = load_manager_util()
manager_util.comfyui_manager_path = str(tmp_path / "manager")
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)
channel_url = str(server.make_url("/main"))
return await scenario(channel, manager_util, load_get_data_by_mode(manager_util, channel_url), channel_url)
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(tmp_path, status, text):
async def scenario(channel, manager_util, get_data_by_mode, channel_url):
channel.serve(status, text)
with pytest.raises(json.JSONDecodeError):
await manager_util.get_data(f"{channel_url}/{FILENAME}")
run(tmp_path, scenario)
@pytest.mark.parametrize("status, text", NOT_JSON)
def test_bundled_list_is_used_and_nothing_is_cached(tmp_path, status, text):
async def scenario(channel, manager_util, get_data_by_mode, channel_url):
channel.serve(status, text)
return await get_data_by_mode("cache", FILENAME), os.listdir(manager_util.cache_dir), channel.requests
result, cached, requests = run(tmp_path, scenario)
assert requests == 1
assert result == BUNDLED
assert cached == []
@pytest.mark.parametrize("status, text", NOT_JSON)
def test_channel_is_read_again_once_it_answers_with_the_list(tmp_path, status, text):
async def scenario(channel, manager_util, get_data_by_mode, channel_url):
channel.serve(status, text)
await get_data_by_mode("cache", FILENAME)
channel.serve(200, json.dumps(SERVED))
return await get_data_by_mode("cache", FILENAME)
assert run(tmp_path, scenario) == SERVED
def test_list_from_the_channel_is_cached(tmp_path):
async def scenario(channel, manager_util, get_data_by_mode, channel_url):
first = await get_data_by_mode("cache", FILENAME)
second = await get_data_by_mode("cache", FILENAME)
return first, second, channel.requests
assert run(tmp_path, scenario) == (SERVED, SERVED, 1)
def test_unreadable_local_file_still_reads_as_empty(tmp_path):
async def scenario(channel, manager_util, get_data_by_mode, 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(tmp_path, scenario) == {}
-229
View File
@@ -1,229 +0,0 @@
import json
import os
import re
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
REGISTERED = re.compile(r'api\.addEventListener\("(cm-check-update|reconnected)", this\.(\w+)\);')
ROWS = {
"git-a": {"state": "enabled", "version": "nightly"},
"git-b": {"state": "enabled", "version": "unknown"},
"versioned-with-update": {"state": "enabled", "version": "1.0.0", "update-state": "true"},
}
TAKEN = {"data": {}}
CHECK = 'POST /customnode/check_update {"mode":"cache","ui_id":"check-1"}'
LIST = "GET /customnode/getlist?mode=cache&skip_update=true"
LOADING, LOADED = "loading", "loading ended"
WAIT = "status: Checking updates ..."
def run(steps, check_answers=(TAKEN,), ends_before_the_answer=None):
source = JS.text("custom-nodes-manager.js")
registered = list(REGISTERED.finditer(source))
script = """
console.log = () => {};
globalThis.window = {};
%(sanitize_html)s
%(show_mode)s;
const calls = [];
const updateFilter = {value: ShowMode.UPDATE, hasData: false};
const self = {
filterList: [updateFilter],
restartMap: {},
element: {querySelector: () => ({})},
getFilterItem: (value) => value === ShowMode.UPDATE ? updateFilter : undefined,
loadNodes: async () => {},
showLoading: () => calls.push('loading'),
hideLoading: () => calls.push('loading ended'),
showStatus: (text) => calls.push('status: ' + text),
showError: (text) => calls.push('error: ' + text),
renderGrid() {
const updatable = Object.values(this.custom_nodes).filter((row) => row.action === 'updatable');
calls.push('shown as updatable: ' + updatable.map((row) => row.key).join(' '));
},
%(load_data)s,
%(check_update)s,
%(ask_for_check)s,
%(listeners)s,
};
const CustomNodesManager = {instance: self};
const manager_instance = {datasrc_combo: {value: 'cache'}};
const md5 = (text) => 'hash of ' + text;
let asked = 0;
const generateUUID = () => 'check-' + (++asked);
const infoToast = () => calls.push('toast');
const heard = {};
const api = {addEventListener: (name, listener) => { heard[name] = listener; }};
(function() { %(registrations)s }).call(self);
const checkAnswers = %(check_answers)s;
const answeredLater = [];
const fetchData = async (route, options = {}) => {
calls.push((options.method ?? 'GET') + ' ' + route + (options.body ? ' ' + options.body : ''));
if(!route.endsWith('/check_update')) {
return {data: {channel: 'default', node_packs: structuredClone(%(rows)s)}};
}
if(%(ends_before_the_answer)s) {
heard['cm-check-update']({detail: %(ends_before_the_answer)s});
}
const answer = checkAnswers.length > 1 ? checkAnswers.shift() : checkAnswers[0];
return answer == 'later' ? new Promise((resolve) => answeredLater.push(resolve)) : answer;
};
const settle = async () => {
for(let i = 0; i < 20; i++) {
await new Promise((resolve) => setTimeout(resolve));
}
};
const done = [];
for(const [kind, value] of %(steps)s) {
calls.length = 0;
if(kind == 'load') {
self.loadData(value);
}
else if(kind == 'answer') {
answeredLater.shift()(value);
}
else {
await heard[kind]?.({detail: value});
}
await settle();
done.push([...calls]);
}
process.stdout.write(JSON.stringify({steps: done, update_filter: Object.keys(updateFilter.hashMap ?? {})}));
""" % {
"sanitize_html": JS.lift_declaration("common.js", "export function sanitizeHTML("),
"show_mode": slice_braced(source, "const ShowMode = "),
"load_data": slice_braced(source, "async loadData(show_mode = ShowMode.NORMAL)"),
"check_update": slice_braced(source, "async checkUpdate(mode)"),
"ask_for_check": slice_braced(source, "async askForCheck(mode)"),
"listeners": ",".join(slice_braced(source, re.search(r"\n\t(async )?%s\(" % found.group(2), source).group(0))
for found in registered),
"registrations": "\n".join(found.group(0) for found in registered),
"check_answers": json.dumps(check_answers),
"ends_before_the_answer": json.dumps(ends_before_the_answer),
"rows": json.dumps(ROWS),
"steps": json.dumps(steps),
}
return run_node(script)
def progress(done_count):
return ["cm-check-update", {"status": "in_progress", "done_count": done_count, "total_count": 2}]
def result(*updatable, of="check-1"):
return ["cm-check-update", {"status": "done", "updatable": list(updatable), "ui_ids": ["of another page", of]}]
RECONNECTED = ["reconnected", None]
def test_check_update_asks_for_the_check_and_loads_the_list_when_it_has_ended():
data = run([["load", "Update"], progress(1), progress(2), result("git-b")])
asked, first, second, ended = data["steps"]
assert asked == [LOADING, "toast", WAIT, CHECK]
assert first == ["status: Checking updates (1/2) ..."]
assert second == ["status: Checking updates (2/2) ..."]
assert ended == ["status: Loading custom nodes (cache) ...", LIST, "shown as updatable: git-b versioned-with-update", LOADED]
assert data["update_filter"] == ["hash of git-b", "hash of versioned-with-update"]
def test_a_check_that_ends_before_the_request_for_it_is_answered_is_not_missed():
data = run([["load", "Update"]], ends_before_the_answer=result("git-b")[1])
assert data["steps"] == [[LOADING, "toast", WAIT, CHECK, "status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: git-b versioned-with-update", LOADED]]
def test_a_check_that_finds_no_update_shows_the_list():
data = run([["load", "Update"], result()])
assert data["steps"][1] == ["status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: versioned-with-update", LOADED]
def test_a_nodepack_that_left_the_list_during_the_check_is_passed_over():
data = run([["load", "Update"], result("git-b", "uninstalled-meanwhile")])
assert data["steps"][1][-2:] == ["shown as updatable: git-b versioned-with-update", LOADED]
def test_the_end_of_a_check_that_does_not_answer_this_page_is_passed_over():
data = run([["load", "Update"], result("git-a", of="of a third page"), result("git-b")])
assert data["steps"][1:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: git-b versioned-with-update", LOADED]]
def test_a_check_that_is_asked_for_again_waits_for_its_own_end():
data = run([["load", "Update"], ["load", "Update"], result("git-a"), result("git-b", of="check-2")])
assert data["steps"][1] == [LOADING, "toast", WAIT, CHECK.replace("check-1", "check-2")]
assert data["steps"][2:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: git-b versioned-with-update", LOADED]]
def test_a_check_that_failed_ends_the_loading_with_an_error():
data = run([["load", "Update"], ["cm-check-update", {"status": "done", "updatable": None, "ui_ids": ["check-1"]}]])
assert data["steps"][1] == ["error: Failed to check updates.", LOADED]
def test_the_list_alone_asks_for_no_check():
data = run([["load", "Normal"]])
assert data["steps"] == [[LOADING, "status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: versioned-with-update", LOADED]]
@pytest.mark.parametrize("answer", [{"status": 400, "error": "Bad Request"}, {"status": 404, "error": "Not Found"}],
ids=["refused", "a-server-without-the-check"])
def test_a_check_that_the_server_does_not_take_ends_the_loading_with_an_error(answer):
data = run([["load", "Update"], progress(1), result("git-b")], check_answers=[answer])
assert data["steps"] == [[LOADING, "toast", WAIT, CHECK, "error: Failed to check updates.", LOADED], [], []]
def test_a_connection_that_came_back_during_the_check_asks_for_the_check_again():
data = run([["load", "Update"], progress(1), RECONNECTED, result("git-b")])
assert data["steps"][2:] == [[CHECK], ["status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: git-b versioned-with-update", LOADED]]
def test_a_check_that_the_server_does_not_take_after_the_connection_came_back_ends_the_loading_with_an_error():
data = run([["load", "Update"], RECONNECTED, result("git-b")], check_answers=[TAKEN, {"status": 404, "error": "Not Found"}])
assert data["steps"][1:] == [[CHECK, "error: Failed to check updates.", LOADED], []]
def test_the_late_failure_of_an_earlier_request_does_not_end_the_check_that_was_asked_for_after_it():
data = run([["load", "Update"], ["load", "Update"], ["answer", {"status": 400, "error": "Bad Request"}],
result("git-b", of="check-2")], check_answers=["later", TAKEN])
assert data["steps"][2:] == [[], ["status: Loading custom nodes (cache) ...", LIST,
"shown as updatable: git-b versioned-with-update", LOADED]]
def test_a_check_that_ends_after_another_list_was_opened_leaves_that_list():
data = run([["load", "Update"], ["load", "Normal"], result("git-b")])
assert data["steps"][1][-2:] == ["shown as updatable: versioned-with-update", LOADED]
assert data["steps"][2] == []
@pytest.mark.parametrize("before", [[["load", "Normal"]], [["load", "Update"], result("git-a")]],
ids=["it-asked-for-none", "its-own-has-ended"])
def test_the_events_of_a_check_this_page_did_not_wait_for_change_nothing(before):
data = run([*before, progress(1), result("git-b"), RECONNECTED])
assert data["steps"][-3:] == [[], [], []]
-350
View File
@@ -1,350 +0,0 @@
import pytest
from test_invalid_installation import PRELUDE
from test_install_flags_config import _run_child
CHECK = '''
import queue, threading, traceback
fetched = []
answers = {}
during_a_fetch = []
def fetch(path):
name = pathlib.Path(path).name
fetched.append(name)
if during_a_fetch:
during_a_fetch.pop()()
if isinstance(answers.get(name), Exception):
raise answers[name]
return answers.get(name, (False, True))
core.git_repo_update_check_with = fetch
core.get_channel_dict = lambda: {'default': core.DEFAULT_CHANNEL}
other_lists = {}
async def get_data_by_mode(mode, filename, channel_url=None):
node_list = other_lists.get('the local mode' if mode == 'local' else channel_url, NODE_LIST)
return {'custom-node-list.json': {'custom_nodes': [dict(item) for item in node_list]},
'extras.json': {'favorites': []}}.get(filename, {})
core.get_data_by_mode = get_data_by_mode
def listed(name):
url = f'https://github.com/example/{name}'
NODE_LIST.append({'author': 'example', 'title': name, 'reference': url, 'files': [url],
'install_type': 'git-clone', 'description': ''})
return url
def request(query=None, body=None):
async def json_body():
return body
return SimpleNamespace(rel_url=SimpleNamespace(query=query), json=json_body)
def node_list(query):
handler = server_function('fetch_customnode_list', core=core, populate_markdown=lambda row: None,
web=SimpleNamespace(json_response=lambda result, content_type: result))
return asyncio.run(handler(request(query=query)))['node_packs']
class Lock:
def __init__(self):
self.held = threading.Lock()
self.after_the_end = []
def __enter__(self):
self.held.acquire()
def __exit__(self, *error):
self.held.release()
if self.after_the_end and update_check_done.is_set():
self.after_the_end.pop()()
class EndMark(threading.Event):
def __init__(self):
super().__init__()
self.queue_waits = threading.Event()
def wait(self):
self.queue_waits.set()
super().wait()
events = []
update_check_done = EndMark()
update_check_done.set()
update_check_lock = Lock()
update_check_paths = {}
update_check_ui_ids = set()
started = []
def sent(name, data):
events.append([name, {key: sorted(value) if isinstance(value, list) else value for key, value in data.items()}])
def started_later(target):
return SimpleNamespace(start=lambda: started.append(target))
def ask_for_a_check(mode='cache', ui_id='the page', thread=started_later):
ask = server_function(
'check_update', core=core, update_check_done=update_check_done, update_check_lock=update_check_lock,
update_check_paths=update_check_paths, update_check_ui_ids=update_check_ui_ids, traceback=traceback,
threading=SimpleNamespace(Thread=lambda target: thread(target)),
_reject_non_json_content_type=lambda request: None, web=SimpleNamespace(json_response=lambda data: data),
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=sent)))
return asyncio.run(ask(request(body={'mode': mode, 'ui_id': ui_id})))
def check_for_updates(mode='cache', ui_id='the page'):
answer = ask_for_a_check(mode, ui_id)
fetched_by_the_request = list(fetched)
started.pop()()
return {'answer': answer, 'fetched by the request': fetched_by_the_request, 'fetched': sorted(fetched),
'check': [event for name, event in events if name == 'cm-check-update']}
DISABLE = ('disable', ('a-row', 'ComfyUI-Foo', False))
def run_the_queue(*tasks):
order = []
config['model_download_by_agent'] = True
core.update_path = lambda path: order.append('ComfyUI is updated') or 'skipped'
manager.unified_disable = lambda node_name, is_unknown: order.append('the task') or core.ManagedResult('disable')
manager.unified_update = lambda node_name, node_ver: order.append('the task') or SimpleNamespace(ver='unknown', result=True, action='skip')
task_queue = queue.Queue()
for task in tasks:
task_queue.put(task)
worker = server_function(
'task_worker', core=core, logging=logging, traceback=traceback, queue=queue, task_queue=task_queue,
update_check_done=update_check_done, nodepack_result={}, model_result={}, tasks_in_progress=set(),
task_worker_lock=threading.Lock(), os=os, folder_paths=SimpleNamespace(__file__=str(nodes.parent / 'folder_paths.py')),
get_model_path=lambda data: str(nodes.parent / data['filename']),
download_url_with_agent=lambda url, path: order.append('the model is downloaded') or True,
manager_util=SimpleNamespace(clear_pip_cache=lambda: None),
PromptServer=SimpleNamespace(instance=SimpleNamespace(send_sync=lambda name, data: None)))
queue_run = threading.Thread(target=lambda: asyncio.run(worker()), daemon=True)
queue_run.start()
return order, queue_run
def run_the_queue_during_a_check(*tasks):
update_check_done.clear()
order, queue_run = run_the_queue(*tasks)
update_check_done.queue_waits.wait(5)
order.append('the check ends')
update_check_done.set()
queue_run.join()
return order
'''
def run(body):
return _run_child(PRELUDE + CHECK + body)
def progress(total):
return [{'status': 'in_progress', 'done_count': done, 'total_count': total} for done in range(1, total + 1)]
def done(updatable, *ui_ids):
return {'status': 'done', 'updatable': sorted(updatable), 'ui_ids': sorted(ui_ids or ['the page'])}
@pytest.mark.parametrize('query', [{'mode': 'cache'}, {'mode': 'cache', 'skip_update': 'true'}],
ids=['without-skip_update', 'with-skip_update'])
def test_the_request_for_the_node_list_fetches_no_repository(query):
data = run(f'''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
rows = node_list({query!r})
emit({{'installed': {{key: row['active_version'] for key, row in rows.items() if row['state'] == 'enabled'}}, 'fetched': fetched}})
''')
assert data == {'installed': {'comfyui-foo': 'nightly', 'ComfyUI-Bar': 'unknown'}, 'fetched': []}
def test_a_check_fetches_the_enabled_git_nodepacks_of_the_list_once_its_request_is_answered():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('bar-clone', git_url=BAR_URL)
pack('.disabled/ComfyUI-Bar')
pack('comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
pack('.disabled/ComfyUI-Disabled', git_url=listed('ComfyUI-Disabled'))
listed('ComfyUI-Invalid')
pack('ComfyUI-Invalid')
pack('ComfyUI-NotListed', git_url='https://github.com/example/ComfyUI-NotListed')
answers.update({'ComfyUI-Foo': (True, True), 'bar-clone': (True, True)})
emit(check_for_updates())
''')
assert data['answer'] == {}
assert data['fetched by the request'] == []
assert data['fetched'] == ['ComfyUI-Foo', 'bar-clone']
assert data['check'] == progress(2) + [done(['ComfyUI-Bar', 'comfyui-foo'])]
@pytest.mark.parametrize('shown', [
"mode = 'local'; listed_under = 'the local mode'",
"config['channel_url'] = listed_under = 'https://example.invalid/a-channel'; core.valid_channels.add(listed_under)",
], ids=['the-local-list', 'the-list-of-another-channel'])
def test_a_check_is_of_the_list_that_the_page_shows(shown):
data = run(f'''
mode = 'cache'
{shown}
other_lists[listed_under] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
emit(check_for_updates(mode=mode))
''')
assert data['fetched'] == ['ComfyUI-Foo']
def test_a_nodepack_that_cannot_be_fetched_does_not_end_the_check():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
pack('ComfyUI-Qux', git_url=listed('ComfyUI-Qux'))
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': OSError('no route to the remote')})
emit(check_for_updates())
''')
assert data['fetched'] == ['ComfyUI-Bar', 'ComfyUI-Foo', 'ComfyUI-Qux']
assert data['check'] == progress(3) + [done(['comfyui-foo'])]
def test_a_check_of_no_nodepack_ends_with_an_empty_result():
data = run('''
pack('comfyui-baz', 'comfyui-baz', version='2.0.0', tracking=True)
emit(check_for_updates())
''')
assert data['answer'] == {}
assert data['check'] == [done([])]
def test_a_check_that_is_asked_for_while_one_runs_starts_no_second_one():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
answers['ComfyUI-Foo'] = (True, True)
answered = [ask_for_a_check(ui_id='a page'), ask_for_a_check(ui_id='another page')]
running = len(started)
started.pop()()
ended = [event for name, event in events if event['status'] == 'done']
ask_for_a_check()
emit({'answered': answered, 'running': running, 'ended': ended, 'started after the end': len(started)})
''')
assert data == {'answered': [{}, {}], 'running': 1, 'ended': [done(['comfyui-foo'], 'a page', 'another page')],
'started after the end': 1}
def test_a_check_that_is_asked_for_while_one_runs_adds_the_nodepacks_that_one_does_not_have():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
ask_for_a_check('local', ui_id='a page')
during_a_fetch.append(lambda: ask_for_a_check(ui_id='another page'))
started.pop()()
emit({'fetched': fetched, 'started': len(started), 'check': [event for name, event in events]})
''')
assert data == {'fetched': ['ComfyUI-Foo', 'ComfyUI-Bar'], 'started': 0, 'check': [
{'status': 'in_progress', 'done_count': 1, 'total_count': 2},
{'status': 'in_progress', 'done_count': 2, 'total_count': 2},
done(['comfyui-foo', 'ComfyUI-Bar'], 'a page', 'another page')]}
def test_a_request_that_comes_when_the_check_has_had_its_last_look_is_answered_by_the_next_check():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
answers.update({'ComfyUI-Foo': (True, True), 'ComfyUI-Bar': (True, True)})
ask_for_a_check('local', ui_id='a page')
update_check_lock.after_the_end.append(lambda: ask_for_a_check(ui_id='another page'))
started.pop()()
first = [event for name, event in events]
checks_started, a_check_runs = len(started), not update_check_done.is_set()
del fetched[:]
if started:
started.pop()()
emit({'first': first, 'checks started': checks_started, 'a check runs': a_check_runs, 'next': [event for name, event in events[len(first):]],
'fetched by the next': sorted(fetched)})
''')
assert data == {'first': progress(1) + [done(['comfyui-foo'], 'a page')], 'checks started': 1, 'a check runs': True,
'next': progress(2) + [done(['comfyui-foo', 'ComfyUI-Bar'], 'another page')],
'fetched by the next': ['ComfyUI-Bar', 'ComfyUI-Foo']}
def test_a_check_is_not_of_the_requests_of_the_check_before():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
pack('ComfyUI-Bar', git_url=BAR_URL)
other_lists['the local mode'] = [item for item in NODE_LIST if item['title'] == 'ComfyUI-Foo']
check_for_updates(ui_id='a page')
del fetched[:]
emit(check_for_updates('local', ui_id='another page'))
''')
assert data['fetched'] == ['ComfyUI-Foo']
assert data['check'][-1] == done([], 'another page')
def test_a_check_whose_thread_cannot_start_does_not_stand_in_the_way_of_the_next():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
def no_thread(target):
raise RuntimeError("can't start new thread")
try:
ask_for_a_check(thread=no_thread)
except RuntimeError:
pass
ask_for_a_check()
emit(len(started))
''')
assert data == 1
def test_a_check_that_fails_tells_the_pages_that_wait_for_it_and_does_not_hold_the_tasks_of_the_queue():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
during_the_check = [lambda: ask_for_a_check(ui_id='a page that asks during the check')]
def fails(paths, on_fetched):
if during_the_check:
during_the_check.pop()()
raise RuntimeError("can't start new thread")
core.fetch_git_node_packs = fails
ask_for_a_check()
update_check_lock.after_the_end.append(lambda: ask_for_a_check(ui_id='a page that asks after it'))
started.pop()()
failed = [event for name, event in events]
checks_started = len(started)
if started:
started.pop()()
order, queue_run = run_the_queue(DISABLE)
queue_run.join(5)
emit({'failed': failed, 'checks started': checks_started, 'next': [event for name, event in events[len(failed):]], 'order': order})
''')
assert data == {'failed': [{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks during the check', 'the page']}],
'checks started': 1,
'next': [{'status': 'done', 'updatable': None, 'ui_ids': ['a page that asks after it']}],
'order': ['the task']}
@pytest.mark.parametrize('task', [('disable', ('a-row', 'ComfyUI-Foo', False)), ('update-main', ('ComfyUI-Foo', 'ComfyUI-Foo', 'unknown'))],
ids=['disable', 'Update-All'])
def test_a_task_of_the_queue_waits_for_the_check_that_runs(task):
assert run(f'emit(run_the_queue_during_a_check({task!r}))') == ['the check ends', 'the task']
@pytest.mark.parametrize('task, work', [
(('install-model', ('a-model', {'name': 'a', 'url': 'https://example.invalid/a.safetensors', 'filename': 'a.safetensors'})),
'the model is downloaded'),
(('update-comfyui', ('comfyui', False)), 'ComfyUI is updated'),
], ids=['a-model-download', 'an-update-of-ComfyUI'])
def test_a_model_download_and_an_update_of_ComfyUI_do_not_wait_for_the_check(task, work):
assert run(f'emit(run_the_queue_during_a_check({task!r}, DISABLE))') == [work, 'the check ends', 'the task']
def test_the_request_that_fetched_inside_itself_is_gone():
data = run('''
pack('ComfyUI-Foo', git_url=FOO_URL)
handler = server_function('fetch_updates', _reject_non_json_content_type=lambda request: None,
web=SimpleNamespace(json_response=lambda data, status: [status, data['deprecated']]))
emit({'answer': asyncio.run(handler(request(body={'mode': 'cache'}))), 'fetched': fetched})
''')
assert data == {'answer': [410, True], 'fetched': []}
-320
View File
@@ -1,320 +0,0 @@
"""A disabled node pack that another extension asks for is enabled, and then ComfyUI restarts.
An extension asks through `cm.try-install-custom-node` for a node pack it needs. When the pack is
disabled, the user is asked whether to enable it and restart. The pack is enabled as the Enable
button of the Custom Nodes Manager does: it is found in the node list, put in the queue, and the
queue is awaited. ComfyUI restarts only after the queue reports success.
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 / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
STATUS = "/manager/queue/status"
GETLIST = "/customnode/getlist"
RESET = "/manager/queue/reset"
INSTALL = "/manager/queue/install"
START = "/manager/queue/start"
REBOOT = "/manager/reboot"
ENABLE = [("GET", GETLIST), ("GET", STATUS), ("POST", RESET), ("POST", INSTALL), ("POST", START)]
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 /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 install route `result`, which the queue reports for the pack:
# `during` the install request, as for a pack from the registry, or after the queue is started.
# As the server does, the queue reports once more when it is started with nothing in it. A
# report of an earlier run arrives before the pack is queued. With `silent`, no report of the
# started queue reaches the page.
"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');
}
const nothing = () => this.report({status: 'done', nodepack_result: {}, model_result: {}});
if(route == '/manager/queue/reset') {
nothing();
}
if(answer.result !== undefined) {
const report = () => {
this.report({status: 'in_progress', target: body.ui_id, ui_target: 'nodepack_manager'});
this.report({status: 'done', nodepack_result: {[body.ui_id]: answer.result}, model_result: {}});
};
if(answer.during) report(); else this.reportWhenStarted = report;
}
if(route == '/manager/queue/start' && !window.answers['/manager/queue/install'].silent) {
setTimeout(this.reportWhenStarted ?? nothing, 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()
def answers(install=None, reboot=None, packs=PACKS, getlist=None, status=None):
"""How the routes answer; by default the pack is listed as disabled, is enabled, and the restart is accepted."""
return {
STATUS: {"json": {"is_processing": False}} if status is None else status,
GETLIST: {"json": {"channel": "default", "node_packs": packs}} if getlist is None else getlist,
INSTALL: {"result": "success"} if install is None else install,
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"
# what the Enable button of the Custom Nodes Manager sends for this row
assert page.evaluate("window.requested[3].body") == {**PACKS["other-pack"], "channel": "default", "mode": "cache",
"ui_id": UI_ID, "skip_post_install": True}
assert page.errors == []
def test_a_report_that_arrives_while_the_install_request_is_handled_is_not_missed(page):
ask(page, answers(install={"result": "success", "during": True}))
confirm(page)
shown(page, "Rebooting...")
assert requested(page) == ENABLE + [("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("install, reason, requests", [
({"status": 403}, "This action is not allowed with this security level configuration.", ENABLE[:4]),
({"status": 404}, "The request was refused (404). Please check the terminal log.", ENABLE[:4]),
({"result": "Cannot resolve install target: 'other-pack@None'"},
"Cannot resolve install target: 'other-pack@None'", ENABLE),
({}, "The queue finished without this node pack. Please try again.", ENABLE),
], ids=["not allowed at this security level", "refused", "failed in the queue", "gone from the queue"])
def test_comfyui_does_not_restart_when_the_pack_was_not_enabled(page, install, reason, requests):
ask(page, answers(install=install))
confirm(page)
shown(page, "Failed to enable 'Other Pack'.")
shown(page, reason)
page.wait_for_timeout(300)
assert requested(page) == requests
assert page.errors == []
def test_the_wait_ends_when_no_report_reaches_the_page(page):
page.clock.install()
ask(page, answers(install={"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.")
# a later report for the same row, as its Disable in the Custom Nodes Manager sends
page.evaluate("""async (ui_id) => {
const { api } = await import('/scripts/api.js');
api.report({status: 'done', nodepack_result: {[ui_id]: 'success'}, model_result: {}});
}""", 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.")
page.wait_for_timeout(300)
assert requested(page) == ENABLE[:2]
assert page.errors == []
@pytest.mark.parametrize("packs", [
{**PACKS, "other-pack": {**PACKS["other-pack"], "state": "enabled"}},
{key: pack for key, pack in PACKS.items() if key != "other-pack"},
], ids=["listed as enabled", "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]),
({"install": {"fails": True}}, ENABLE[:4]),
], ids=["the node list", "the install 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(install={"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) == []
-86
View File
@@ -1,86 +0,0 @@
from test_snapshot_restore_pins import run
PACKS = '''
import ast, io, traceback
from typing_extensions import Annotated, List
import typer
from rich.console import Console
def cm_cli(*names):
found = [node for node in ast.parse(pathlib.Path('cm-cli.py').read_text(encoding='utf-8')).body if isinstance(node, ast.FunctionDef)
and node.name in names]
for node in found:
node.decorator_list = []
out = io.StringIO()
scope = {'typer': typer, 'List': List, 'Annotated': Annotated, 'asyncio': asyncio, 'traceback': traceback,
'print': Console(file=out, width=1000, color_system=None).print,
'cmd_ctx': Mock(no_deps=False), 'unified_manager': manager, 'auto_save_snapshot': AsyncMock()}
exec(compile(ast.Module(body=found, type_ignores=[]), 'cm-cli.py', 'exec'), scope)
return scope, lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if 'pack' in line]
def command(name):
scope, said = cm_cli(name, 'for_each_nodes', 'get_all_installed_node_specs', 'enable_node', 'disable_node')
scope[name](['all'], None, None, None)
return [line.split('=>')[-1].strip() for line in said()]
for name in ('enabled-pack', '.disabled/registry-pack@1_0_0', '.disabled/rc-pack@1_0_0-rc1', '.disabled/git-pack'):
(nodes / name).mkdir(parents=True)
manager.active_nodes['enabled-pack'] = ('2.0.0', str(nodes / 'enabled-pack'))
manager.cnr_inactive_nodes['registry-pack'] = {'1.0.0': str(nodes / '.disabled/registry-pack@1_0_0')}
manager.cnr_inactive_nodes['rc-pack'] = {'1.0.0-rc1': str(nodes / '.disabled/rc-pack@1_0_0-rc1')}
manager.unknown_inactive_nodes['git-pack'] = ('https://github.com/owner/git-pack', str(nodes / '.disabled/git-pack'))
'''
def all_of(name):
return run(PACKS + f'''
said = command({name!r})
print(json.dumps({{'said': said, 'enabled': sorted(os.listdir(nodes)), 'disabled': sorted(os.listdir(nodes / '.disabled'))}}))
''')
def test_enable_all_enables_every_disabled_nodepack():
result = all_of('enable')
assert result['enabled'] == ['.disabled', 'enabled-pack', 'git-pack', 'rc-pack', 'registry-pack']
assert result['disabled'] == []
assert result['said'][0] == 'Already enabled'
def test_disable_all_disables_every_enabled_nodepack_and_leaves_the_disabled_ones():
result = all_of('disable')
assert result['enabled'] == ['.disabled']
assert result['disabled'] == ['enabled-pack@2_0_0', 'git-pack', 'rc-pack@1_0_0-rc1', 'registry-pack@1_0_0']
assert result['said'][1:] == ['Already disabled', 'Already disabled', 'Already disabled']
def test_latest_names_the_installed_nodepack_as_a_bare_id_does():
result = run(PACKS + '''
for name, latest in (('enabled-pack', '3.0.0'), ('registry-pack', '1.5.0')):
manager.cnr_map[name] = {'id': name, 'latest_version': {'version': latest}}
manager.unified_update = lambda node_id, version_spec=None, **kwargs: core.ManagedResult('update').with_target('3.0.0')
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
scope, said = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
for act, name in (('update_node', 'enabled-pack'), ('fix_node', 'enabled-pack'), ('disable_node', 'enabled-pack'), ('enable_node', 'registry-pack')):
scope[act](name + '@latest')
print(json.dumps({'said': said(), 'enabled': sorted(os.listdir(nodes)), 'disabled': sorted(os.listdir(nodes / '.disabled'))}))
''')
assert result['said'] == ['[ UPDATED ]: enabled-pack => (2.0.0 -> 3.0.0)', '[ FIXING ]: enabled-pack [2.0.0]', '[DISABLED] enabled-pack',
'[ENABLED] registry-pack']
assert result['enabled'] == ['.disabled', 'registry-pack']
assert 'enabled-pack@2_0_0' in result['disabled']
def test_a_registry_nodepack_that_is_not_installed_is_not_called_disabled():
result = run(PACKS + '''
manager.cnr_map['absent-pack'] = {'id': 'absent-pack', 'latest_version': {'version': '1.0.0'}}
scope, said = cm_cli('update_node', 'fix_node', 'disable_node', 'enable_node')
for name in ('absent-pack', 'absent-pack@latest'):
for act in ('update_node', 'fix_node', 'disable_node', 'enable_node'):
scope[act](name)
print(json.dumps({'said': [line.split('=>')[-1].strip() for line in said()]}))
''')
assert result['said'] == ['Not installed', 'Not installed', 'Not found', 'Not found'] * 2
-304
View File
@@ -1,304 +0,0 @@
import os
import pytest
from test_snapshot_restore_pins import run
CLI = '''
import ast, inspect, io, sys, threading, concurrent.futures, traceback
from typing import Optional
from typing_extensions import Annotated, List
import rich, typer, typer.testing
def binds_print(node):
if isinstance(node, ast.Assign):
return any(isinstance(target, ast.Name) and target.id == 'print' for target in node.targets)
return isinstance(node, ast.ImportFrom) and any((name.asname or name.name) == 'print' for name in node.names)
def cm_cli(*names, width=1000, color_system=None, **more):
found = [node for node in ast.parse(pathlib.Path('cm-cli.py').read_text(encoding='utf-8')).body
if isinstance(node, ast.FunctionDef) and node.name in names or binds_print(node)]
if 'app' not in more:
for node in found:
node.decorator_list = []
out = io.StringIO()
rich.reconfigure(file=out, width=width, color_system=color_system, no_color=False)
scope = {'typer': typer, 'List': List, 'Annotated': Annotated, 'Optional': Optional, 'asyncio': asyncio, 'traceback': traceback,
'os': os, 'sys': sys, 'json': json, 'threading': threading, 'concurrent': concurrent,
'core': core, 'cnr_utils': cnr_utils,
'cmd_ctx': Mock(no_deps=False, channel='default', mode='cache'), 'unified_manager': manager,
'auto_save_snapshot': AsyncMock(), 'manager_util': Mock(), 'comfy_path': tmp, **more}
exec(compile(ast.Module(body=found, type_ignores=[]), 'cm-cli.py', 'exec'), scope)
return scope, lambda: [' '.join(line.split()) for line in out.getvalue().splitlines() if line.strip()]
def command(scope, name, **given):
try:
scope[name](**{**dict.fromkeys(inspect.signature(scope[name]).parameters), **given})
except (SystemExit, typer.Exit):
pass
GIT_PACK = ('https://example.invalid/git-pack', str(nodes / 'git-pack'))
folder = os.path.join(tmp, '[my] files')
os.mkdir(folder)
'''
def said(body):
return run(CLI + body + '\nprint(json.dumps(lines()))\n')
@pytest.mark.parametrize('installed, name, label', [
("manager.unknown_active_nodes['git-pack'] = GIT_PACK", 'git-pack', '[unknown]'),
("manager.active_nodes['git-pack'] = ('nightly', GIT_PACK[1])", 'git-pack@nightly', '[nightly]'),
], ids=['unknown', 'nightly'])
def test_fix_names_the_version_of_a_git_nodepack(installed, name, label):
assert said(f'''
{installed}
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
scope, lines = cm_cli('fix_node')
scope['fix_node']({name!r}, cnt_msg='1/1')
''') == [f'1/1 [ FIXING ]: git-pack {label}']
def test_fix_that_fails_says_why():
assert said('''
manager.unknown_active_nodes['git-pack'] = GIT_PACK
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix').fail('cannot fix [the reason]')
scope, lines = cm_cli('fix_node')
scope['fix_node']('git-pack', cnt_msg='1/1')
''')[1:] == ['ERROR: cannot fix [the reason]']
def test_fix_all_has_a_line_for_each_nodepack_it_counts():
assert said('''
manager.unknown_active_nodes['git-pack'] = GIT_PACK
manager.unknown_inactive_nodes['old-pack'] = ('https://example.invalid/old-pack', str(nodes / '.disabled/old-pack'))
manager.unified_fix = lambda node_id, version_spec, **kwargs: core.ManagedResult('fix')
scope, lines = cm_cli('fix', 'for_each_nodes', 'get_all_installed_node_specs', 'fix_node')
command(scope, 'fix', nodes=['all'])
''') == ['1/2 [ FIXING ]: git-pack [unknown]', '2/2 [ SKIPPED ]: old-pack@unknown => Disabled']
def test_url_that_is_not_installed_says_why():
assert said('''
core.gitclone_install = AsyncMock(return_value=core.ManagedResult('install-git').fail('cannot clone [the reason]'))
scope, lines = cm_cli('install_node')
scope['install_node'](GIT_PACK[0], cnt_msg='1/1')
''') == ['cannot clone [the reason]', "ERROR: An error occurred while installing 'https://example.invalid/git-pack'."]
def test_install_of_an_id_that_no_list_has_says_where_it_was_looked_for():
assert said('''
scope, lines = cm_cli('install_node')
scope['install_node']('no-such-pack', cnt_msg='1/1')
''') == ["ERROR: An error occurred while installing 'no-such-pack'.", "Node 'no-such-pack@unknown' not found in [default, cache]"]
@pytest.mark.parametrize('installed, act, line', [
("manager.unknown_inactive_nodes['git-pack'] = GIT_PACK; manager.unified_enable = lambda *args: core.ManagedResult('enable').fail(REASON)",
'enable_node', '1/1 [ FAIL ] git-pack => cannot move [the folder]'),
("manager.unknown_inactive_nodes['git-pack'] = GIT_PACK; manager.unified_enable = lambda *args: core.ManagedResult('skip').with_msg(REASON)",
'enable_node', '1/1 [ SKIP ] git-pack => cannot move [the folder]'),
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_disable = lambda *args: core.ManagedResult('disable').fail(REASON)",
'disable_node', '1/1 [ FAIL ] git-pack => cannot move [the folder]'),
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_disable = lambda *args: core.ManagedResult('skip').with_msg(REASON)",
'disable_node', '1/1 [ SKIP ] git-pack => cannot move [the folder]'),
("manager.unknown_active_nodes['git-pack'] = GIT_PACK; manager.unified_update = lambda *args, **kwargs: core.ManagedResult('skip').with_msg(REASON)",
'update_node', '1/1 [ SKIPPED ]: git-pack => cannot move [the folder]'),
], ids=['enable_fails', 'enable_is_skipped', 'disable_fails', 'disable_is_skipped', 'update_is_skipped'])
def test_reason_in_square_brackets_is_printed_whole(installed, act, line):
assert said(f'''
REASON = 'cannot move [the folder]'
{installed}
scope, lines = cm_cli({act!r})
scope[{act!r}]('git-pack', cnt_msg='1/1')
''') == [line]
@pytest.mark.parametrize('name, installed, act, line', [
('git-pack[old]', "manager.unknown_inactive_nodes[NAME] = PACK; manager.unified_enable = lambda *args: core.ManagedResult('enable')",
'enable_node', '1/1 [ENABLED] git-pack[old]'),
('git-pack[old]', "manager.unknown_active_nodes[NAME] = PACK; manager.unified_disable = lambda *args: core.ManagedResult('disable')",
'disable_node', '1/1 [DISABLED] git-pack[old]'),
('comfyui-manager[old]', "manager.unknown_active_nodes[NAME] = PACK",
'disable_node', "1/1 [ SKIP ] comfyui-manager[old] => Not disabled: its name has 'comfyui-manager'"),
('git-pack[old]', "manager.unknown_inactive_nodes[NAME] = PACK", 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Disabled'),
('git-pack[old]', "", 'fix_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
('git-pack[old]', "", 'update_node', '1/1 [ SKIPPED ]: git-pack[old] => Not installed'),
], ids=['enable', 'disable', 'disable_of_the_manager', 'fix_of_a_disabled_one', 'fix_of_one_that_is_not_installed',
'update_of_one_that_is_not_installed'])
def test_name_in_square_brackets_is_printed_whole(name, installed, act, line):
assert said(f'''
NAME = {name!r}
PACK = ('https://example.invalid/git-pack', str(nodes / NAME))
{installed}
scope, lines = cm_cli({act!r})
scope[{act!r}](NAME, cnt_msg='1/1')
''') == [line]
def test_line_longer_than_the_console_is_wide_is_written_as_one_line():
assert said('''
manager.unknown_active_nodes['git-pack'] = GIT_PACK
scope, lines = cm_cli('enable_node', width=80)
scope['enable_node']('git-pack', cnt_msg='1/1')
''') == ['1/1 [ SKIP ] git-pack => Already enabled']
def test_error_of_a_nodepack_in_a_run_over_several_is_printed_whole():
assert said('''
def act(name, **kwargs):
raise RuntimeError('no such [thing] for ' + name)
scope, lines = cm_cli('for_each_nodes', traceback=Mock())
scope['for_each_nodes'](['git-pack'], act)
''') == ['ERROR: no such [thing] for git-pack']
def test_error_of_an_update_in_a_run_over_several_is_printed_whole():
assert said('''
scope, lines = cm_cli('update_parallel', update_node=Mock(side_effect=RuntimeError('no such [thing]')), traceback=Mock())
scope['update_parallel'](['git-pack'])
''') == ['ERROR: no such [thing]']
def test_show_versions_prints_a_changelog_with_square_brackets():
assert said('''
cnr_utils.all_versions_of_node = lambda name: [{'createdAt': '2026-01-02T03:04:05', 'version': '1.0.1', 'changelog': '[fix] a crash'}]
scope, lines = cm_cli('show_versions')
scope['show_versions']('git-pack')
''') == ['[2026-01-02] 1.0.1 -- [fix] a crash']
def test_show_prints_a_title_and_an_author_with_square_brackets():
assert said('''
manager.get_custom_nodes = AsyncMock(return_value={
'listed-pack': {'title': 'Listed [gist-wrapper] Pack', 'author': 'some[one]', 'files': ['https://github.com/someone/listed-pack']},
})
manager.cnr_map['registry-pack'] = {'id': 'registry-pack', 'name': 'Registry[official] Pack', 'publisher': {'name': 'someone'},
'latest_version': {'version': '1.0.0'}}
manager.active_nodes['registry-pack'] = ('1.0.0', str(nodes / 'registry-pack'))
manager.unknown_active_nodes['listed-pack'] = ('https://github.com/someone/listed-pack', str(nodes / 'listed-pack'))
scope, lines = cm_cli('show', 'simple_show', 'show_list')
scope['show']('installed', None, None, None)
scope['simple_show']('installed', None, None, None)
''') == ['[ ENABLED ] Registry[official] Pack registry-pack (author: someone ) [1.0.0]',
'[ ENABLED ] Listed [gist-wrapper] Pack listed-pack (author: some[one] ) [UNKNOWN]',
'Registry[official] Pack@1.0.0', 'Listed [gist-wrapper] Pack@unknown']
def test_show_of_a_word_that_is_no_list_is_refused_in_plain_words():
assert said('''
sys.stderr = refusal = io.StringIO()
scope, lines = cm_cli('simple_show')
command(scope, 'simple_show', arg='[nodes]')
lines = lambda: refusal.getvalue().split()
''') == ['Invalid', 'command:', '`show', '[nodes]`']
def test_names_of_snapshots_are_listed_whole():
assert said('''
open(os.path.join(folder, 'before [the update].json'), 'w').close()
scope, lines = cm_cli('show_snapshot_list')
scope['cmd_ctx'].get_snapshot_path.return_value = folder
scope['show_snapshot_list']()
''') == ['before [the update].json']
PATHS = {
'restore-snapshot of a file that is not there': (
"scope['cmd_ctx'].get_snapshot_path.return_value = folder; command(scope, 'restore_snapshot', snapshot_name='gone.json')",
f'ERROR: `{{folder}}{os.sep}gone.json` is not exists.'),
'save-snapshot into a folder that is not there': (
"command(scope, 'save_snapshot', output=folder + '/gone/snapshot.json')", 'ERROR: {folder}/gone/snapshot.json path not exists.'),
'save-snapshot': (
"core.save_snapshot_with_postfix = AsyncMock(return_value=folder + '/snapshot.json'); command(scope, 'save_snapshot', output=folder + '/snapshot.json')",
'Current snapshot is saved as `{folder}/snapshot.json`'),
'deps-in-workflow of a file that is not there': (
"command(scope, 'deps_in_workflow', workflow=folder + '/gone.json', output='deps.json')", 'File not found: {folder}/gone.json'),
'deps-in-workflow': (
"open(folder + '/workflow.json', 'w').close(); core.extract_nodes_from_workflow = AsyncMock(return_value=({}, []));"
" command(scope, 'deps_in_workflow', workflow=folder + '/workflow.json', output=folder + '/deps.json')",
'Workflow dependencies are being saved into {folder}/deps.json.'),
'install-deps of a file that is not there': ("command(scope, 'install_deps', deps=folder + '/gone.json')", 'File not found: {folder}/gone.json'),
'install-deps of a file that is not JSON': (
"open(folder + '/deps.json', 'w').close(); command(scope, 'install_deps', deps=folder + '/deps.json')", 'Invalid json file: {folder}/deps.json'),
}
@pytest.mark.parametrize('case', PATHS)
def test_path_with_square_brackets_is_printed_whole(case):
call, line = PATHS[case]
assert said(f'''
scope, said = cm_cli('restore_snapshot', 'save_snapshot', 'deps_in_workflow', 'install_deps')
{call}
lines = lambda: [line.replace(folder, '{{folder}}') for line in said()][-1:]
''') == [line]
@pytest.mark.parametrize('path', [r'C:\ComfyUI\[My] files\deps.json', '/nodes/' + 'long-folder-name/' * 5 + 'deps.json', '/nodes/x:100:y/deps.json'],
ids=['a backslash before a bracket', 'longer than the console is wide', 'the code of an emoji'])
@pytest.mark.parametrize('call, line', [
("command(scope, 'install_deps', deps=path)", 'File not found: {}'),
("core.save_snapshot_with_postfix = AsyncMock(return_value=path); command(scope, 'save_snapshot')", 'Current snapshot is saved as `{}`'),
], ids=['a coloured line', 'a line without a colour'])
def test_line_is_written_as_it_is(call, line, path):
assert said(f'''
path = {path!r}
scope, lines = cm_cli('install_deps', 'save_snapshot', width=80)
{call}
''') == [line.format(path)]
@pytest.mark.parametrize('call, line', [
("command(scope, 'install_deps', deps='deps.json')", '\x1b[1;31mFile not found: deps.json\x1b[0m'),
("open(os.path.join(folder, \"the 'old' one.json\"), 'w').close(); scope['cmd_ctx'].get_snapshot_path.return_value = folder;"
" scope['show_snapshot_list']()", "the \x1b[32m'old'\x1b[0m one.json"),
], ids=['a line that cm-cli colours', 'a quoted text in another line'])
def test_line_keeps_its_colour(call, line):
assert said(f'''
scope, lines = cm_cli('install_deps', 'show_snapshot_list', color_system='standard')
{call}
''') == [line]
@pytest.mark.parametrize('app', ['typer.Typer()', 'typer.Typer(rich_markup_mode=None)'], ids=['with rich markup', 'without'])
def test_help_names_the_values_that_an_argument_and_an_option_take(app):
assert said(f'''
scope, said = cm_cli('show', 'update', app={app})
help = lambda name: ' '.join(typer.testing.CliRunner().invoke(scope['app'], [name, '--help'], env={{'COLUMNS': '200'}}).output.split())
lines = lambda: [text in help(name) and chr(92) not in help(name) for name, text in (
('show', 'installed|enabled|not-installed'), ('show', 'remote|local|cache'),
('update', 'all|List of custom nodes to update'), ('update', 'remote|local|cache'))]
''') == [True, True, True, True]
def test_disable_says_why_the_manager_is_not_disabled():
assert said('''
scope, lines = cm_cli('disable_node')
scope['disable_node']('comfyui-manager', cnt_msg='1/1')
''') == ["1/1 [ SKIP ] comfyui-manager => Not disabled: its name has 'comfyui-manager'"]
def test_disable_all_has_a_line_for_each_nodepack_it_counts():
assert [line.split()[0] for line in said('''
for name in ('comfyui-manager', 'git-pack'):
(nodes / name).mkdir()
manager.unknown_active_nodes[name] = ('https://example.invalid/' + name, str(nodes / name))
scope, lines = cm_cli('disable', 'for_each_nodes', 'get_all_installed_node_specs', 'disable_node')
scope['disable'](['all'], None, None, None)
''')] == ['1/2', '2/2']
def test_restore_dependencies_runs_for_the_nodepacks_only():
assert said('''
for name in ('a-pack', '__pycache__', 'b-pack.disabled', '.disabled'):
os.mkdir(os.path.join(folder, name))
manager.execute_install_script = Mock()
scope, said = cm_cli('restore_dependencies')
scope['cmd_ctx'].get_custom_nodes_paths.return_value = [folder]
command(scope, 'restore_dependencies')
lines = lambda: ([line.replace(folder, '{folder}') for line in said() if line.startswith('Restoring')]
+ [os.path.basename(call.args[1]) for call in manager.execute_install_script.call_args_list])
''') == ['Restoring [1/1]: {folder}' + os.sep + 'a-pack', 'a-pack']
@@ -1,133 +0,0 @@
"""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 node pack, so that installing the pack 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 error. An uninstall
whose directory can neither be removed nor scheduled for removal is still an error.
The cases run in the isolated child of tests/test_install_flags_config.py, against
the real glob/manager_core and the real extraction.
"""
import pytest
from test_install_flags_config import _run_child
PRELUDE = '''
import pathlib, zipfile
from types import SimpleNamespace
from unittest.mock import Mock
import cnr_utils
core = manager_core
nodes = pathlib.Path(tmp) / 'custom_nodes'
nodes.mkdir()
core.get_default_custom_nodes_path = lambda: str(nodes)
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()
core.unified_manager = manager
manager.execute_install_script = Mock(return_value=True)
def good(path):
with zipfile.ZipFile(path, 'w') as archive:
archive.writestr('__init__.py', 'VERSION = "2.0.0"')
def 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 not_a_zip(path):
pathlib.Path(path).write_bytes(b'<html>502 Bad Gateway</html>')
def install(write_archive):
core.manager_downloader.download_url = lambda url, directory, name: write_archive(pathlib.Path(directory) / name)
return manager.cnr_install('fixture', '2.0.0', instant_execution=True, no_deps=True)
def left():
return sorted(path.name for path in nodes.iterdir())
'''
def run(body):
return _run_child(PRELUDE + body)
@pytest.mark.parametrize('archive, message', [
('failing_midway', 'Failed to extract archive: fixture@2.0.0: '),
('not_a_zip', 'Empty archive file: fixture@2.0.0'),
])
def test_failed_extraction_leaves_nothing_behind(archive, message):
data = run(f'''
result = install({archive})
print(json.dumps({{'ok': result.result, 'message': result.msg, 'left': left()}}))
''')
assert data['ok'] is False
assert data['message'].startswith(message), data
assert data['left'] == []
def test_install_succeeds_after_a_failed_extraction():
data = run('''
install(failing_midway)
result = install(good)
print(json.dumps({'ok': result.result, 'message': result.msg, 'left': left(),
'file': (nodes / 'fixture/__init__.py').read_text()}))
''')
assert data == {'ok': True, 'message': data['message'], 'left': ['fixture'], 'file': 'VERSION = "2.0.0"'}
@pytest.mark.parametrize('archive, message', [
('failing_midway', 'Failed to extract archive: fixture@2.0.0: '),
('not_a_zip', 'Empty archive file: fixture@2.0.0'),
])
def test_cleanup_that_fails_does_not_hide_the_extraction_error(archive, message):
data = run(f'''
core.try_rmtree = Mock(side_effect=OSError('the directory cannot be removed'))
error = None
try:
result = install({archive})
except Exception as e:
error = repr(e)
print(json.dumps({{'error': error, 'message': error or result.msg, 'cleanups': core.try_rmtree.call_count}}))
''')
assert data['error'] is None, data
assert data['message'].startswith(message), data
assert data['cleanups'] == 1
def test_uninstall_that_can_neither_remove_nor_schedule_is_an_error():
data = run('''
installed = nodes / 'fixture'
installed.mkdir()
manager.active_nodes['fixture'] = ('2.0.0', str(installed))
core.shutil.rmtree = Mock(side_effect=OSError('the directory is in use'))
core.reserve_script = Mock(side_effect=OSError('the startup script cannot be written'))
try:
outcome = 'reported as ' + manager.unified_uninstall('fixture', False).action
except OSError as e:
outcome = 'error: ' + str(e)
print(json.dumps({'outcome': outcome, 'left': left()}))
''')
assert data == {'outcome': 'error: the startup script cannot be written', 'left': ['fixture']}
def test_uninstall_schedules_a_directory_it_cannot_remove():
data = run('''
installed = nodes / 'fixture'
installed.mkdir()
manager.active_nodes['fixture'] = ('2.0.0', str(installed))
core.shutil.rmtree = Mock(side_effect=OSError('the directory is in use'))
scheduled = []
core.reserve_script = lambda title, commands: scheduled.append([title] + commands)
result = manager.unified_uninstall('fixture', False)
print(json.dumps({'action': result.action, 'ok': result.result,
'scheduled': scheduled == [['fixture', '#LAZY-DELETE-NODEPACK', str(installed)]]}))
''')
assert data == {'action': 'uninstall', 'ok': True, 'scheduled': True}
-238
View File
@@ -1,238 +0,0 @@
import ast
import asyncio
import json
import logging
import os
import re
import shutil
import subprocess
import sys
from types import SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
LEVELS = ["strong", "normal", "normal-", "weak"]
SERVER = {"is_allowed_security_level", "security_403_response", "_reject_non_json_content_type", "comfyui_switch_version"}
CORE = {"parse_semver", "is_comfyui_downgrade"}
class GitCommandError(Exception):
pass
def functions(name, names):
source = (GLOB_DIR / name).read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names
or isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("SECURITY_MESSAGE_")]
assert names <= {getattr(node, "name", None) for node in nodes}
return compile(ast.Module(body=nodes, type_ignores=[]), name, "exec")
def load(security_level, loopback, described="v0.3.60"):
def describe(*args):
if described is None:
raise GitCommandError("fatal: No names found, cannot describe anything.")
return described
git = SimpleNamespace(Repo=lambda path: SimpleNamespace(git=SimpleNamespace(describe=describe)),
GitCommandError=GitCommandError)
core = {"re": re, "git": git, "comfy_path": "comfyui"}
exec(functions("manager_core.py", CORE), core)
switched = []
server = {
"routes": web.RouteTableDef(), "web": web, "logging": logging, "sys": sys,
"is_local_mode": loopback,
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level},
is_comfyui_downgrade=core["is_comfyui_downgrade"], switch_comfyui=switched.append),
"manager_migration": SimpleNamespace(has_system_user_api=lambda: True),
}
exec(functions("manager_server.py", SERVER), server)
return server["comfyui_switch_version"], switched
def call(handler, body):
async def read_json():
return body
try:
response = asyncio.run(handler(SimpleNamespace(json=read_json, content_type="application/json")))
except Exception:
return 500, None
return response.status, json.loads(response.text) if response.text else None
REFUSED = (403, {"error": "security_level"})
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_an_older_release_needs_normal_minus_on_loopback_and_weak_otherwise(security_level, loopback):
comfyui_switch_version, switched = load(security_level, loopback)
answer = call(comfyui_switch_version, {"ver": "v0.3.59"})
if security_level == "weak" or loopback and security_level == "normal-":
assert answer == (200, None)
assert switched == ["v0.3.59"]
else:
assert answer == REFUSED
assert switched == []
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
@pytest.mark.parametrize("version", ["nightly", "v0.3.60", "v0.3.61", "v0.4.0", "v1.0.0"],
ids=["nightly", "the same release", "a newer patch", "a newer minor", "a newer major"])
def test_an_update_is_not_held_to_a_level(version, security_level, loopback):
comfyui_switch_version, switched = load(security_level, loopback)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described, version, older", [
("v0.3.60-12-gabc1234", "v0.3.60", True), ("v0.3.60-12-gabc1234", "v0.3.61", False),
("v0.3.60-12-gabc1234", "v0.3.59", True), ("v0.3.60-1-gabc1234", "v0.3.60", True),
("v0.45.0-32-g0123abc", "v0.45.0", True), ("v0.45.0-32-g0123abc", "v0.45.4", False),
("v0.9.0", "v0.10.0", False), ("v0.10.0", "v0.9.0", True), ("v0.10.0", "v0.9.99", True),
("v1.0.0", "v0.99.99", True), ("v0.3.60", "v0.3.060", False), ("v0.3.60", "v0.2.61", True),
], ids=["commits after a release, that release", "commits after a release, a newer one", "commits after a release, an older one",
"one commit after a release, that release", "nightly, the first release of its minor", "nightly, a later patch release",
"a two-digit minor is newer", "a one-digit minor is older", "a higher patch of a lower minor",
"a lower major", "leading zeros", "a higher patch of an older minor"])
def test_releases_are_compared_by_their_numbers(described, version, older):
comfyui_switch_version, switched = load("strong", True, described)
answer = call(comfyui_switch_version, {"ver": version})
assert (answer, switched) == ((REFUSED, []) if older else ((200, None), [version]))
@pytest.mark.parametrize("version", [
"master", "HEAD~100", "abc1234", "0.3.61", "v0.3", "v0.3.61.1", "v0.3.61-rc1", "V0.3.61", " v0.3.61", "v0.3.61 ",
"refs/tags/v0.3.61", "latest", "Nightly", "v0.3.61\n", "v0.3.61\nv0.3.59", "\nv0.3.61", "",
], ids=["a branch", "an ancestor", "a commit", "no v", "two numbers", "four numbers", "a suffix", "upper case",
"a leading space", "a trailing space", "a full ref", "another name", "nightly in another case", "a trailing newline",
"two lines", "a leading newline", "empty"])
def test_what_is_not_a_release_tag_is_held_like_an_older_release(version):
comfyui_switch_version, switched = load("normal", True)
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
assert switched == []
comfyui_switch_version, switched = load("normal-", True)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described", [None, "", "latest", "latest-3-gabc1234", "0.3.60", "v0.3"],
ids=["no tag", "nothing", "another tag", "commits after another tag", "no v", "two numbers"])
@pytest.mark.parametrize("version", ["v0.3.61", "v9.9.9"])
def test_without_a_release_to_compare_with_every_release_is_held(described, version):
comfyui_switch_version, switched = load("normal", True, described)
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
assert switched == []
comfyui_switch_version, switched = load("weak", False, described)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described", [None, "latest"], ids=["no tag", "another tag"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_nightly_needs_no_release_to_compare_with(security_level, described):
comfyui_switch_version, switched = load(security_level, False, described)
assert call(comfyui_switch_version, {"ver": "nightly"}) == (200, None)
assert switched == ["nightly"]
@pytest.mark.parametrize("version", [None, 1, 0.3, ["v0.3.61"], {"v": "0.3.61"}, True],
ids=["null", "an integer", "a number", "a list", "an object", "a boolean"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_a_version_that_is_not_text_switches_nothing(security_level, version):
comfyui_switch_version, switched = load(security_level, True)
status, _ = call(comfyui_switch_version, {"ver": version})
assert status == 400
assert switched == []
@pytest.mark.parametrize("body", [{}, {"version": "v0.3.59"}], ids=["no fields", "another field"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_a_request_without_a_version_does_nothing(security_level, body):
comfyui_switch_version, switched = load(security_level, False)
assert call(comfyui_switch_version, body) == (200, None)
assert switched == []
@pytest.mark.parametrize("security_level", ["", "STRONG", "middle", "high"])
def test_a_security_level_that_is_not_one_of_the_four_allows_no_older_release(security_level):
comfyui_switch_version, switched = load(security_level, True)
assert call(comfyui_switch_version, {"ver": "v0.3.59"}) == REFUSED
assert call(comfyui_switch_version, {"ver": "v0.3.61"}) == (200, None)
assert switched == ["v0.3.61"]
@pytest.fixture
def repository(tmp_path, monkeypatch):
if shutil.which("git") is None:
pytest.skip("git is not installed")
# git takes its repository from these when they are set, as they are under a git hook
for name in [name for name in os.environ if name.startswith("GIT_")]:
monkeypatch.delenv(name)
def run(*args):
subprocess.run(["git", "-C", str(tmp_path), "-c", "user.name=test", "-c", "user.email=test@example.invalid",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True)
run("init", "-q")
for release in ("v0.3.59", "v0.3.60"):
run("commit", "-q", "--allow-empty", "-m", release)
run("tag", release)
return tmp_path, run
def is_downgrade(path, tag):
core = {"re": re, "git": pytest.importorskip("git"), "comfy_path": str(path)}
exec(functions("manager_core.py", CORE), core)
return core["is_comfyui_downgrade"](tag)
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", False), ("v0.3.61", False), ("nightly", False),
("master", True)])
def test_in_a_repository_at_a_release_only_an_older_one_goes_back(repository, tag, older):
path, _ = repository
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", True), ("v0.3.61", False), ("nightly", False)])
def test_in_a_repository_with_a_commit_after_the_release_that_release_goes_back(repository, tag, older):
path, run = repository
run("commit", "-q", "--allow-empty", "-m", "after the release")
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.59", False), ("v0.3.60", False), ("v0.3.58", True)])
def test_in_a_repository_checked_out_at_an_earlier_release_the_later_one_does_not_go_back(repository, tag, older):
path, run = repository
run("checkout", "-q", "v0.3.59")
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.60", True), ("nightly", False)])
def test_in_a_repository_without_a_release_tag_every_release_goes_back(repository, tag, older):
path, run = repository
run("tag", "-d", "v0.3.59", "v0.3.60")
assert is_downgrade(path, tag) is older
-41
View File
@@ -1,41 +0,0 @@
"""`comfyui_versions` answers 400 when the versions of ComfyUI cannot be read.
Each case runs the real handler of `glob/manager_server.py`; `core` is replaced.
"""
import ast
import asyncio
import logging
import sys
from types import SimpleNamespace
from aiohttp import web
from manager_test_utils import GLOB_DIR
def fail():
raise RuntimeError("not a git repository")
def answer(get_comfyui_versions):
"""The status and text `comfyui_versions` answers."""
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
handler = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "comfyui_versions"]
assert len(handler) == 1
namespace = {"web": web, "logging": logging, "sys": sys,
"core": SimpleNamespace(get_comfyui_versions=get_comfyui_versions),
"routes": SimpleNamespace(get=lambda path: lambda handler: handler)}
exec(compile(ast.Module(body=handler, type_ignores=[]), "<comfyui_versions>", "exec"), namespace)
response = asyncio.run(namespace["comfyui_versions"](None))
return response.status, response.text
def test_version_list_that_cannot_be_read_is_answered_with_400(caplog):
assert answer(fail) == (400, None)
assert "ComfyUI update fail: not a git repository" in caplog.text
def test_version_list_is_answered_with_the_versions():
assert answer(lambda: (["nightly", "v0.3.1"], "v0.3.1", "v0.3.1")) == (
200, '{"versions": ["nightly", "v0.3.1"], "current": "v0.3.1"}')
-62
View File
@@ -1,62 +0,0 @@
import json
import os
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
COMPONENT = {"packname": "a pack", "category": "", "nodes": [], "links": [], "external": []}
def load(status, body):
source = JS.text("components-manager.js")
script = """
const registered = [];
const app = {graph: {}};
const api = {fetchApi: async () => ({status: %s, json: async () => JSON.parse(%s)})};
const SEPARATOR = '/';
const sleep = async () => {};
const register_pack_map = () => {};
class GroupNodeConfig {
constructor(name, data) { this.name = name; }
async registerType(category) { registered.push([this.name, category]); }
}
%s
%s
let failed = null;
try { await load_components(); } catch(e) { failed = String(e); }
console.log(JSON.stringify({groupNodes: app.graph.extra?.groupNodes ?? {}, registered, failed}));
""" % (
json.dumps(status), json.dumps(body),
slice_braced(source, "function storeGroupNode(name, data, register=true)"),
JS.lift_declaration("components-manager.js", "export async function load_components()"),
)
return run_node(script)
@pytest.mark.parametrize("status, body", [
(403, '{"error": "comfyui_outdated"}'), (403, '{"error": "security_level"}'), (403, ""),
(400, ""), (404, "404: Not Found"), (500, "<html><body>500 Internal Server Error</body></html>"),
(502, "<html><body><h1>502 Bad Gateway</h1></body></html>"), (403, json.dumps({"a component": COMPONENT})),
], ids=["an outdated ComfyUI", "a security level", "403 without a body", "400 without a body", "404", "500 with a page",
"502 from a proxy", "403 with a list"])
def test_an_answer_that_is_not_a_success_has_no_components(status, body):
assert load(status, body) == {"groupNodes": {}, "registered": [], "failed": None}
def test_a_success_without_components_adds_nothing():
assert load(200, "{}") == {"groupNodes": {}, "registered": [], "failed": None}
@pytest.mark.parametrize("names", [["a component"], ["a component", "error", "another"]], ids=["one", "three, one named error"])
def test_the_components_of_a_success_are_registered_as_before(names):
loaded = load(200, json.dumps({name: COMPONENT for name in names}))
assert loaded["failed"] is None
assert list(loaded["groupNodes"]) == names
assert loaded["registered"] == [[name, "a pack"] for name in names]
-148
View File
@@ -1,148 +0,0 @@
import json
import subprocess
import sys
import textwrap
import pytest
from manager_test_utils import GLOB_DIR
VALUES = {
"security_level": ["normal", "strong", "normal-", "weak"],
"network_mode": ["public", "private", "offline"],
"db_mode": ["cache", "local", "remote"],
"update_policy": ["stable-comfyui", "nightly-comfyui"],
"component_policy": ["workflow", "higher", "mine"],
}
NON_DEFAULT = {key: values[1] for key, values in VALUES.items()}
CHILD = textwrap.dedent(
"""
import sys, types, tempfile, os, json, io, contextlib, logging
tmp = tempfile.mkdtemp(prefix="cm_config_values_")
stub = types.ModuleType("folder_paths")
stub.get_user_directory = lambda: tmp
stub.get_system_user_directory = lambda *a, **k: os.path.join(tmp, "sysuser")
sys.modules["folder_paths"] = stub
written, changes, glob_dir = json.loads(sys.argv[1])
sys.path.insert(0, glob_dir)
with contextlib.redirect_stdout(io.StringIO()):
import manager_core
path = os.path.join(tmp, "config.ini")
manager_core.manager_config_path = path
manager_core.cached_config = None
if written is not None:
with open(path, "wb") as f:
f.write(written.encode("latin-1"))
warnings = []
handler = logging.Handler(logging.WARNING)
handler.emit = lambda record: warnings.append(record.getMessage())
logging.getLogger().addHandler(handler)
with contextlib.redirect_stdout(io.StringIO()):
settings = dict(manager_core.get_config())
for key, value in changes:
manager_core.get_config()[key] = value
if changes:
manager_core.write_config()
after = open(path, "rb").read().decode("latin-1") if os.path.exists(path) else None
print(json.dumps({"settings": settings, "warnings": warnings, "file": after}))
"""
)
def read(written, changes=()):
done = subprocess.run([sys.executable, "-c", CHILD, json.dumps([written, list(changes), str(GLOB_DIR)])],
capture_output=True, text=True, timeout=180)
assert done.returncode == 0, done.stderr[-2000:]
result = json.loads(done.stdout.strip().splitlines()[-1])
return result["settings"], "\n".join(result["warnings"]), result["file"]
def section(settings):
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
@pytest.mark.parametrize("value", ["100%", "%(downgrade_blacklist)s", "%", "bogus", "weak,normal", "<b>weak</b>", "nor mal",
"[/x]", "[bold]weak", "cache[/]"])
@pytest.mark.parametrize("key", sorted(VALUES))
def test_a_value_that_a_setting_cannot_have_gives_its_default_and_changes_no_other_setting(key, value):
text = section({**NON_DEFAULT, key: value, "downgrade_blacklist": "kornia"})
settings, printed, file = read(text)
assert {name: settings[name] for name in VALUES} == {**NON_DEFAULT, key: VALUES[key][0]}
assert settings["downgrade_blacklist"] == "kornia"
assert f"{key} = {value!r} in config.ini is not valid; '{VALUES[key][0]}' is used." in printed
assert file == text
@pytest.mark.parametrize("key", sorted(VALUES))
def test_a_value_that_a_setting_cannot_have_stays_in_config_ini_when_another_setting_is_saved(key):
text = section({**NON_DEFAULT, key: "bogus"})
_, _, file = read(text, changes=[("share_option", "none")])
assert f"{key} = bogus\n" in file
assert "share_option = none\n" in file
@pytest.mark.parametrize("key, value", [(key, value) for key, values in sorted(VALUES.items()) for value in values])
@pytest.mark.parametrize("written", [str.lower, str.upper], ids=["lower case", "upper case"])
def test_a_value_that_a_setting_can_have_is_read_and_nothing_is_said(key, value, written):
settings, printed, _ = read(section({key: written(value)}))
assert settings[key] == value
assert printed == ""
def test_a_config_ini_without_these_settings_has_their_defaults_and_nothing_is_said():
settings, printed, _ = read(section({"file_logging": "True"}))
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert printed == ""
@pytest.mark.parametrize("key, value", [
("downgrade_blacklist", "100%"), ("downgrade_blacklist", "%(security_level)s"), ("git_exe", "/opt/100%/git"),
("channel_url", "https://example.invalid/some%20one/channel"), ("channel_url", "%"), ("git_exe", "/opt/100%%/git"),
], ids=["a percent sign", "the form of a reference", "a path", "a percent-encoded url", "only a percent sign",
"two percent signs"])
def test_a_percent_sign_is_plain_text_and_the_other_settings_are_read(key, value):
text = section({**NON_DEFAULT, key: value})
settings, printed, file = read(text)
assert settings[key] == value
assert {name: settings[name] for name in VALUES} == NON_DEFAULT
assert printed == ""
assert file == text
def test_a_setting_is_written_beside_a_value_with_a_percent_sign_and_one_with_it_is_written():
text = section({"security_level": "strong", "downgrade_blacklist": "100%"})
_, _, file = read(text, changes=[("db_mode", "local"), ("channel_url", "https://example.invalid/some%20one/channel")])
assert "security_level = strong\n" in file and "downgrade_blacklist = 100%\n" in file
assert "db_mode = local\n" in file and "channel_url = https://example.invalid/some%20one/channel\n" in file
@pytest.mark.parametrize("text", ["security_level = strong\n", "\ufeff[default]\nsecurity_level = strong\n".encode("utf-8").decode("latin-1"),
"[default\nsecurity_level = strong\n", "[other]\nsecurity_level = strong\n", "",
"[default]\nsecurity_level = strong\nnot a setting [/x]\n"],
ids=["no section", "a byte order mark", "an unclosed section", "no default section", "empty",
"a line that is not a setting"])
def test_a_config_ini_that_cannot_be_read_gives_the_defaults_and_says_so(text):
settings, printed, file = read(text)
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert "could not be read" in printed and "the default settings are used" in printed
assert file == text
def test_without_a_config_ini_the_defaults_are_used_and_nothing_is_said():
settings, printed, file = read(None)
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert printed == ""
assert file is None
-46
View File
@@ -1,46 +0,0 @@
"""`print` of `manager_core` writes its text as it is.
The cases take what binds the name `print` out of `glob/manager_core.py`, an
import or a function, and call it.
"""
import ast
import io
import pytest
from manager_test_utils import GLOB_DIR
def core_print():
source = (GLOB_DIR / "manager_core.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, (ast.Import, ast.ImportFrom)) and "rich" in ast.unparse(node)
or isinstance(node, ast.FunctionDef) and node.name == "print"]
namespace = {}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<manager_core print>", "exec"), namespace)
return namespace["print"]
def printed(*objects, **options):
out = io.StringIO()
core_print()(*objects, file=out, **options)
return out.getvalue()
@pytest.mark.parametrize("text", [
"Install(git-clone) error: https://example.com/a[/b] / failed",
"## ComfyUI-Manager: EXECUTE => ['python', '-m', 'pip', 'install', 'diffusers[torch]']",
"skip black listed pip installation: 'requests[socks]'",
"Uninstall: custom_nodes/pack:100:backup",
"Download: git clone 'https://github.com/" + "a" * 120 + "'",
], ids=["closing tag", "list with an extra", "extra", "emoji code", "longer than 80 columns"])
def test_text_is_written_as_it_is(text):
assert printed(text) == text + "\n"
def test_objects_are_written_as_their_text():
assert printed("Update error:", ValueError("no section [/x]"), 3) == "Update error: no section [/x] 3\n"
def test_end_and_sep_are_kept():
assert printed("a", "b", sep="-", end="") == "a-b"
-156
View File
@@ -1,156 +0,0 @@
import pytest
from manager_test_utils import load_manager_util
from test_install_flags_config import _run_child
COMFY_ORG = 'https://raw.githubusercontent.com/Comfy-Org/ComfyUI-Manager/main'
LTDRDATA = 'https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main'
MIRROR = 'https://example.invalid/mirror'
FILES = ['custom-node-list.json', 'extension-node-map.json', 'model-list.json', 'github-stats.json']
SPELLINGS = [pytest.param(COMFY_ORG, id='Comfy-Org'), pytest.param(LTDRDATA, id='ltdrdata')]
CONFIGS = [pytest.param(None, id='no channel_url')] + SPELLINGS
CACHED = [pytest.param((), id='DEFAULT_CHANNEL'), pytest.param(('default_cache_as_channel_url = True',), id='channel_url')]
PRELUDE = '''
import ast, asyncio, logging, pathlib, traceback
from types import SimpleNamespace
from aiohttp import web
import cnr_utils
import manager_util
core = manager_core
user = pathlib.Path(tmp)
nodes = user / 'custom_nodes'
nodes.mkdir()
sys.modules['folder_paths'].get_folder_paths = lambda name: [str(nodes)]
core.manager_channel_list_path = str(user / 'channels.list')
manager_util.cache_dir = str(user / 'cache')
manager_util.comfyui_manager_path = str(user / 'manager')
os.makedirs(manager_util.cache_dir)
os.makedirs(manager_util.comfyui_manager_path)
BAR_URL = 'https://github.com/example/ComfyUI-Bar'
SERVED = {
'custom-node-list.json': {'custom_nodes': [{'author': 'example', 'title': 'ComfyUI-Bar', 'reference': BAR_URL, 'files': [BAR_URL],
'install_type': 'git-clone', 'description': ''}]},
'extension-node-map.json': {BAR_URL: [['BarNode'], {'title_aux': 'ComfyUI-Bar'}]},
'model-list.json': {'models': [{'name': 'served by the channel'}]},
'github-stats.json': {BAR_URL: {'stars': 7, 'last_update': '2026-11-01 00:00:00', 'author_account_age_days': 900}},
}
BUNDLED = {'custom-node-list.json': {'custom_nodes': []}, 'extension-node-map.json': {}, 'model-list.json': {'models': []},
'github-stats.json': {}, 'extras.json': {'favorites': []}}
for name, data in BUNDLED.items():
(pathlib.Path(manager_util.comfyui_manager_path) / name).write_text(json.dumps(data))
REGISTRY = [{'id': 'comfyui-foo', 'name': 'Foo', 'repository': 'https://github.com/example/ComfyUI-Foo',
'publisher': {'name': 'example'}, 'description': '', 'latest_version': {'version': '1.0.1'}}]
requests = []
get_data = manager_util.get_data
async def from_the_channel(uri, silent=False):
if uri.startswith('https://'):
requests.append(uri)
return json.loads(json.dumps(SERVED[os.path.basename(uri)]))
return await get_data(uri, silent)
async def get_cnr_data(*args, **kwargs):
return REGISTRY
manager_util.get_data = from_the_channel
cnr_utils.get_cnr_data = get_cnr_data
core.unified_manager = core.UnifiedManager()
SERVER = pathlib.Path(core.__file__).with_name('manager_server.py')
route = lambda path: lambda handler: handler
def server(*names):
functions = [node for node in ast.parse(SERVER.read_text(encoding='utf-8')).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
scope = {'core': core, 'manager_util': manager_util, 'os': os, 'logging': logging, 'traceback': traceback, 'asyncio': asyncio,
'web': web, 'routes': SimpleNamespace(get=route, post=route), 'populate_markdown': lambda node_pack: None}
exec(compile(ast.Module(functions, []), str(SERVER), 'exec'), scope)
return scope
def configure(channel_url, default_url, *lines):
config = ['[default]'] + ([f'channel_url = {channel_url}'] if channel_url else []) + list(lines)
pathlib.Path(CONFIG_PATH).write_text('\\n'.join(config) + '\\n')
(user / 'channels.list').write_text(f'default::{default_url}\\nrecent::{default_url}/node_db/new\\nmirror::https://example.invalid/mirror\\n')
def start():
try:
asyncio.run(server('default_cache_update')['default_cache_update']())
except Exception as e:
return repr(e)
def answer(name, **query):
response = asyncio.run(server(name)[name](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
return json.loads(response.text)
def emit(value):
print()
print(json.dumps(value))
'''
def run(body):
return _run_child(PRELUDE + body)
@pytest.mark.parametrize('cached', CACHED)
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_start_writes_the_lists_every_reader_reads(channel_url, default_url, cached):
data = run(f'''
configure({channel_url!r}, {default_url!r}, *{cached!r})
failed = start()
started = len(os.listdir(manager_util.cache_dir))
requests.clear()
unread = [[channel, filename] for channel in (None, 'default', {COMFY_ORG!r}, {LTDRDATA!r}) for filename in SERVED
if asyncio.run(core.get_data_by_mode('cache', filename, channel)) != SERVED[filename]]
level = asyncio.run(server('get_risky_level')['get_risky_level']([BAR_URL], []))
emit({{'failed': failed, 'cache': [started, len(os.listdir(manager_util.cache_dir))], 'unread': unread,
'fetched': requests, 'level': level}})
''')
assert data == {'failed': None, 'cache': [len(FILES), len(FILES)], 'unread': [], 'fetched': [], 'level': 'middle'}
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_custom_nodes_manager_lists_the_registry_nodepacks_on_the_default_channel(channel_url, default_url):
data = run(f'''
configure({channel_url!r}, {default_url!r})
start()
listed = answer('fetch_customnode_list', mode='cache')
emit({{'channel': listed['channel'], 'node_packs': {{key: row['reference'] for key, row in listed['node_packs'].items()}}}})
''')
assert data == {'channel': 'default', 'node_packs': {
'ComfyUI-Bar': 'https://github.com/example/ComfyUI-Bar', 'comfyui-foo': 'https://registry.comfy.org/nodes/comfyui-foo'}}
@pytest.mark.parametrize('default_url', SPELLINGS)
@pytest.mark.parametrize('channel_url', CONFIGS)
def test_channel_menu_selects_the_default_channel(channel_url, default_url):
data = run(f'''
configure({channel_url!r}, {default_url!r})
emit(answer('get_channel_url_list')['selected'])
''')
assert data == 'default'
@pytest.mark.parametrize('default_url', SPELLINGS)
def test_another_channel_keeps_its_own_lists(default_url):
data = run(f'''
configure({MIRROR!r}, {default_url!r}, 'default_cache_as_channel_url = True')
failed = start()
cache = sorted(os.listdir(manager_util.cache_dir))
listed = answer('fetch_customnode_list', mode='cache')
requests.clear()
emit({{'failed': failed, 'cache': cache,
'read': {{filename: asyncio.run(core.get_data_by_mode('cache', filename)) == SERVED[filename] for filename in SERVED}},
'fetched': requests, 'selected': answer('get_channel_url_list')['selected'],
'listed': [listed['channel'], list(listed['node_packs'])]}})
''')
simple_hash = load_manager_util().simple_hash
assert data == {'failed': None, 'cache': sorted(f'{simple_hash(f"{MIRROR}/{filename}")}_{filename}' for filename in FILES),
'read': dict.fromkeys(FILES, True), 'fetched': [], 'selected': 'mirror', 'listed': ['mirror', ['ComfyUI-Bar']]}
-59
View File
@@ -1,59 +0,0 @@
import pytest
from test_install_flags_config import _run_child
@pytest.fixture(scope='module')
def fixes():
return _run_child("""
import pathlib
from types import SimpleNamespace
import cm_global, manager_util
manager_util.make_pip_cmd = lambda cmd: ['python', '-m', 'pip', *cmd]
manager_util.get_installed_packages = lambda renew=False: {}
manager_util.PIPFixer = lambda *args: SimpleNamespace(fix_broken=lambda: None)
cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist, cm_global.pip_overrides = set(), [], {}
manager_core.manager_startup_script_path = tmp
manager = manager_core.unified_manager
pack = pathlib.Path(tmp) / 'pack'
pack.mkdir()
(pack / 'requirements.txt').write_text('first\\nsecond\\n', encoding='utf-8')
(pack / 'install.py').write_text('', encoding='utf-8')
manager.unknown_active_nodes = {'pack': ('https://example.invalid/pack', str(pack))}
def fix(fails=(), node='pack', system='Linux', always_lazy_install=False):
manager_core.manager_funcs.run_script = lambda cmd, cwd='.': int(cmd[-1] in fails)
manager_core.platform.system = lambda: system
manager_core.get_config()['always_lazy_install'] = always_lazy_install
manager.processed_install = set()
result = manager.unified_fix(node, 'unknown')
return [result.result, result.msg]
print(json.dumps({
'every command runs': fix(),
'a requirement cannot be installed': fix(fails=['second']),
'install.py fails': fix(fails=['install.py']),
'reserved by always_lazy_install': fix(fails=['second'], always_lazy_install=True),
'reserved on Windows': fix(fails=['second'], system='Windows'),
'no such nodepack': fix(node='missing'),
}))
""")
def test_fix_whose_commands_all_run_succeeds(fixes):
assert fixes['every command runs'] == [True, None]
@pytest.mark.parametrize('case', ['a requirement cannot be installed', 'install.py fails'])
def test_fix_fails_when_a_command_of_its_install_script_fails(fixes, case):
assert fixes[case] == [False, 'Failed to execute install script: pack@unknown']
@pytest.mark.parametrize('case', ['reserved by always_lazy_install', 'reserved on Windows'])
def test_fix_that_is_reserved_succeeds_before_its_commands_run(fixes, case):
assert fixes[case] == [True, None]
def test_fix_of_a_nodepack_that_is_not_there_fails(fixes):
assert fixes['no such nodepack'] == [False, 'not found: missing@unknown']
-330
View File
@@ -1,330 +0,0 @@
"""Behavioral checks against real v3 modules in an isolated ComfyUI runtime."""
import pytest
from test_install_flags_config import _run_child
PRELUDE = '''
import asyncio, io, logging, pathlib, zipfile
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import cnr_utils, manager_util
from comfy.cli_args import args
args.listen = '0.0.0.0'
core = manager_core
core.manager_funcs.is_flagged_install_allowed = lambda: False
config = core.get_config()
config['allow_flagged_nodepack_install'] = False
nodes = pathlib.Path(tmp) / 'custom_nodes'
nodes.mkdir()
core.get_default_custom_nodes_path = lambda: str(nodes)
manager = core.UnifiedManager()
core.unified_manager = manager
terminal = io.StringIO()
logging.getLogger().addHandler(logging.StreamHandler(terminal))
status = 'NodeVersionStatusFlagged'
http = 200
get = Mock(side_effect=lambda *a, **k: SimpleNamespace(status_code=http, json=lambda: {
'id': 'version-id', 'node_id': 'fixture', 'version': '2.0.0', 'status': status,
'downloadUrl': 'https://example.invalid/fixture.zip',
}))
cnr_utils.requests.get = get
def download(url, directory, name):
with zipfile.ZipFile(pathlib.Path(directory) / name, 'w') as archive:
archive.writestr('__init__.py', 'VERSION = "2.0.0"')
archive.writestr('pyproject.toml', '[project]\\nname = "fixture"\\nversion = "2.0.0"\\n')
core.manager_downloader.download_url = Mock(side_effect=download)
core.manager_downloader.basic_download_url = core.manager_downloader.download_url
manager.execute_install_script = Mock(return_value=True)
'''
def run(body):
stub = '''
comfy = types.ModuleType('comfy')
cli_args = types.ModuleType('comfy.cli_args')
cli_args.args = types.SimpleNamespace(listen='127.0.0.1')
sys.modules['comfy'] = comfy
sys.modules['comfy.cli_args'] = cli_args
'''
return _run_child(stub + PRELUDE + body)
@pytest.mark.parametrize('permission,allowed', [(None, True), ('true', True), ('false', False)])
def test_cli_install_uses_only_parent_permission(permission, allowed):
data = run(f'''
permission = {permission!r}
os.environ.pop('_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED', None)
if permission is not None:
os.environ['_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED'] = permission
core.manager_funcs = core.ManagerFuncs()
args.listen = '127.0.0.1' if permission == 'false' else '0.0.0.0'
config['allow_flagged_nodepack_install'] = permission == 'false'
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
print(json.dumps({{'ok': result.result, 'queries': get.call_count,
'downloads': core.manager_downloader.download_url.call_count}}))
''')
assert data == {'ok': allowed, 'queries': 1, 'downloads': int(allowed)}
@pytest.mark.parametrize('status,permission,allowed', [
('Active', False, True), ('Pending', False, True),
('Flagged', False, False), ('Flagged', True, True),
])
def test_install_policy_before_download(status, permission, allowed):
data = run(f'''
status = {'NodeVersionStatus' + status!r}
core.manager_funcs.is_flagged_install_allowed = lambda: {permission!r}
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
print(json.dumps({{'ok': result.result, 'message': result.msg,
'terminal': terminal.getvalue(),
'queries': get.call_count, 'downloads': core.manager_downloader.download_url.call_count,
'installed': (nodes / 'fixture/__init__.py').exists()}}))
''')
assert data['ok'] is allowed, data
assert data['installed'] is allowed, data
assert data['downloads'] == int(allowed), data
assert data['queries'] == 1, data
if not allowed:
assert data['message'] == ('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 data['terminal'], data
else:
assert 'allow_flagged_nodepack_install' not in data['terminal']
@pytest.mark.parametrize('http', [403, 404, 500])
def test_override_does_not_bypass_registry_refusal(http):
data = run(f'''
http = {http}
core.manager_funcs.is_flagged_install_allowed = lambda: True
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
print(json.dumps({{'ok': result.result, 'queries': get.call_count,
'downloads': core.manager_downloader.download_url.call_count}}))
''')
assert data == {'ok': False, 'queries': 1, 'downloads': 0}
@pytest.mark.parametrize('operation', ['install', 'lazy', 'instant'])
@pytest.mark.parametrize('return_postinstall', [False, True])
def test_direct_cnr_execution_and_postinstall(operation, return_postinstall):
data = run(f'''
status = 'NodeVersionStatusActive'
operation = {operation!r}
return_postinstall = {return_postinstall!r}
installed = nodes / '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)
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, 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
before = effect.call_count
if return_postinstall:
assert result.postinstall()
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}}
print(json.dumps({{'queries': get.call_count,
'downloads': core.manager_downloader.download_url.call_count,
'before': before, 'after': effect.call_count,
'content': (installed / '__init__.py').read_text()}}))
''')
assert data == {'queries': 1, 'downloads': int(operation != 'lazy'),
'before': int(not return_postinstall), 'after': 1,
'content': 'original' if operation == 'lazy' else 'VERSION = "2.0.0"'}
@pytest.mark.parametrize('operation', ['install', 'reinstall', 'lazy', 'instant', 'snapshot'])
def test_denial_preserves_installed_version(operation):
data = run(f'''
installed = nodes / 'fixture'
installed.mkdir()
(installed / '__init__.py').write_text('VERSION = "1.0.0"')
(installed / '.tracking').write_text('__init__.py')
manager.active_nodes['fixture'] = ('1.0.0', str(installed))
manager.reserve_cnr_switch = Mock(return_value=True)
operation = {operation!r}
if operation == 'snapshot':
manager.reload = AsyncMock()
manager.get_custom_nodes = AsyncMock(return_value={{}})
core.manager_util.restore_pip_snapshot = Mock()
snapshot = pathlib.Path(tmp) / '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)))
elif operation in ('lazy', 'instant'):
result = manager.cnr_switch_version('fixture', '2.0.0', instant_execution=operation == 'instant')
assert not result.result, result.msg
elif operation == 'reinstall':
result = asyncio.run(manager.reinstall_by_id('fixture', '2.0.0'))
assert not result.result, result.msg
else:
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
assert not result.result, result.msg
print(json.dumps({{'files': (installed / '__init__.py').read_text(),
'queries': get.call_count, 'downloads': core.manager_downloader.download_url.call_count,
'reservations': manager.reserve_cnr_switch.call_count}}))
''')
assert data == {'files': 'VERSION = "1.0.0"', 'queries': 1, 'downloads': 0, 'reservations': 0}
@pytest.mark.parametrize('listen,allowed', [
('127.0.0.1', True), ('::1', True), ('127.0.0.1,::1', True),
('0.0.0.0', False), ('::', False), ('0.0.0.0,::', False),
('192.168.1.2', False), ('127.0.0.1,0.0.0.0', False), ('', False),
])
def test_all_listener_addresses_must_be_loopback(listen, allowed):
data = run(f'''
print(json.dumps(manager_util.is_cnr_install_allowed('NodeVersionStatusFlagged', False, {listen!r})))
''')
assert data is allowed
@pytest.mark.parametrize('addresses,allowed', [
(['127.0.0.1', '::1'], True), (['127.0.0.1', '192.168.1.2'], False),
([], False), (None, False),
])
def test_hostname_must_resolve_exclusively_to_loopback(addresses, allowed):
data = run(f'''
addresses = {addresses!r}
if addresses is None:
manager_util.socket.getaddrinfo = Mock(side_effect=OSError('unresolvable'))
else:
manager_util.socket.getaddrinfo = Mock(return_value=[
(0, 0, 0, '', (ip, 0)) for ip in addresses])
print(json.dumps(manager_util.is_cnr_install_allowed('NodeVersionStatusFlagged', False, 'host.test')))
''')
assert data is allowed
@pytest.mark.parametrize('state', ['nightly', 'disabled'])
def test_denial_preserves_enabled_state(state):
data = run(f'''
state = {state!r}
installed = nodes / ('fixture' if state == 'nightly' else '.disabled/fixture@1_0_0')
installed.mkdir(parents=True)
(installed / '__init__.py').write_text('original')
if state == 'nightly':
manager.active_nodes['fixture'] = ('nightly', str(installed))
else:
manager.cnr_inactive_nodes['fixture'] = {{'1.0.0': str(installed)}}
before = repr((manager.active_nodes, manager.cnr_inactive_nodes))
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
print(json.dumps({{'ok': result.result, 'original': (installed / '__init__.py').read_text(),
'unchanged': before == repr((manager.active_nodes, manager.cnr_inactive_nodes)),
'queries': get.call_count, 'downloads': core.manager_downloader.download_url.call_count}}))
''')
assert data == {'ok': False, 'original': 'original', 'unchanged': True, 'queries': 1, 'downloads': 0}
def test_exact_installed_version_enables_without_registry_lookup():
data = run('''
installed = nodes / '.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)}
result = asyncio.run(manager.install_by_id('fixture', '2.0.0'))
assert manager.active_nodes['fixture'] == ('2.0.0', str(nodes / 'fixture'))
assert asyncio.run(manager.install_by_id('fixture', '2.0.0')).action == 'skip'
print(json.dumps({'ok': result.result, 'old_path': installed.exists(),
'content': (nodes / 'fixture/__init__.py').read_text(), 'queries': get.call_count,
'downloads': core.manager_downloader.download_url.call_count,
'scripts': manager.execute_install_script.call_count}))
''')
assert data == {'ok': True, 'old_path': False, 'content': 'already installed',
'queries': 0, 'downloads': 0, 'scripts': 0}
def test_reinstall_stops_when_the_installed_folder_cannot_be_moved_aside():
data = run('''
status = 'NodeVersionStatusActive'
installed = nodes / 'fixture'
installed.mkdir()
manager.active_nodes['fixture'] = ('1.0.0', str(installed))
rename = os.rename
os.rename = Mock(side_effect=PermissionError('cannot move'))
result = asyncio.run(manager.reinstall_by_id('fixture', '2.0.0'))
os.rename = rename
print(json.dumps({'ok': result.result, 'moved': 'cannot move' in result.msg, 'kept': installed.is_dir(),
'queries': get.call_count, 'downloads': core.manager_downloader.download_url.call_count}))
''')
assert data == {'ok': False, 'moved': True, 'kept': True, 'queries': 1, 'downloads': 0}
@pytest.mark.parametrize('version', ['nightly', 'unknown'])
def test_git_reinstall_replaces_pack_and_reruns_script(version):
data = run(f'''
version = {version!r}
installed = nodes / 'fixture'
installed.mkdir()
(installed / 'original.txt').write_text('original')
repo_url = 'https://example.invalid/fixture'
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]}},
}})
get.side_effect = AssertionError('Git needs no CNR install query')
manager.processed_install.add(str(installed / 'install.py'))
manager.execute_install_script = core.UnifiedManager.execute_install_script.__get__(manager)
core.try_install_script = Mock(return_value=True)
def clone(url, path, **kwargs):
assert url == repo_url
path = pathlib.Path(path)
assert not path.exists()
path.mkdir()
(path / 'replacement.txt').write_text('installed')
(path / 'install.py').write_text('')
assert manager.execute_install_script(url, str(path))
return core.ManagedResult('install-git')
manager.repo_install = Mock(side_effect=clone)
result = asyncio.run(manager.reinstall_by_id('fixture', version))
print(json.dumps({{'ok': result.result, 'original': (installed / 'original.txt').exists(),
'replacement': (installed / 'replacement.txt').read_text(),
'clones': manager.repo_install.call_count, 'scripts': core.try_install_script.call_count}}))
''')
assert data == {'ok': True, 'original': False, 'replacement': 'installed', 'clones': 1, 'scripts': 1}
def test_config_defaults_and_manual_edits_survive_settings_save():
data = _run_child('''
write_ini('[default]\\nsecurity_level = normal\\n')
first = fresh_read()['allow_flagged_nodepack_install']
write_ini('[default]\\nsecurity_level = normal\\nallow_flagged_nodepack_install = true\\n')
manager_core.get_config()['db_mode'] = 'local'
manager_core.write_config()
cached = manager_core.get_config()['allow_flagged_nodepack_install']
fresh = fresh_read()['allow_flagged_nodepack_install']
print(json.dumps([first, cached, fresh]))
''')
assert data == [False, False, True]
@pytest.mark.parametrize('raw,expected', [('TRUE', True), ('false', False), ('garbage', False)])
def test_config_value_roundtrip(raw, expected):
data = _run_child(f'''
write_ini('[default]\\nallow_flagged_nodepack_install = {raw}\\n')
loaded = fresh_read()['allow_flagged_nodepack_install']
manager_core.get_config()['allow_flagged_nodepack_install'] = not loaded
manager_core.write_config()
print(json.dumps([loaded, fresh_read()['allow_flagged_nodepack_install']]))
''')
assert data == [expected, not expected]
-278
View File
@@ -1,278 +0,0 @@
import os
import pytest
from test_snapshot_restore_pins import run
REPOSITORY = '''
def repository(path):
path.mkdir(parents=True)
commits = []
for version in (1, 2):
(path / '__init__.py').write_text('VERSION = %d' % version)
for args in (['init', '-q'], ['add', '.'],
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
commits.append(head(path))
return commits
def head(path):
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
'''
def lines(body):
return run(REPOSITORY + body + '\nprint(json.dumps(result))\n')
def test_ref_that_head_names_is_read():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
head_file = nodes / 'fixture/.git/HEAD'
branch = head_file.read_text().strip()[5:]
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
head_file.write_text('ref:' + branch + '\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
head_file.write_text('ref: \\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == [True, True, 'unknown']
def test_commit_of_a_pack_whose_refs_are_packed_is_read():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
with open(nodes / 'fixture/.git/packed-refs', 'a') as packed:
packed.write('\\n')
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
result = [(nodes / 'fixture/.git' / branch).exists(), git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
''') == [False, True]
def test_ref_whose_place_is_a_folder_is_not_read_as_a_file():
"""git takes a folder there for no ref: after `git pack-refs`, and after `git checkout --orphan feature` beside a branch `feature/x`."""
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
(nodes / 'fixture/.git' / branch).mkdir(parents=True)
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
subprocess.run(['git', 'branch', 'feature/x'], cwd=nodes / 'fixture', check=True)
subprocess.run(['git', 'checkout', '-q', '--orphan', 'feature'], cwd=nodes / 'fixture', check=True)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == [True, 'unknown']
def test_commit_that_is_not_ascii_is_read_without_an_error():
assert lines('''
import git_utils
repository(nodes / 'fixture')
git_dir = nodes / 'fixture/.git'
branch = (git_dir / 'HEAD').read_text().strip()[5:]
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
(git_dir / 'packed-refs').write_bytes(b'0123\\xff ' + branch.encode() + b'\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
(git_dir / branch).write_bytes(b'0123\\xff\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / 'HEAD').write_bytes(b'0123\\xff\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == ['0123\ufffd'] * 3
def test_head_that_cannot_be_opened_has_no_commit():
assert lines('''
import git_utils
(nodes / 'fixture/.git/HEAD').mkdir(parents=True)
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['unknown']
def test_files_that_may_not_be_read_have_no_commit(tmp_path):
(tmp_path / 'probe').touch()
(tmp_path / 'probe').chmod(0)
try:
open(tmp_path / 'probe').close()
except OSError:
pass
else:
pytest.skip('a file can be read here whatever its mode, as by root or on Windows')
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
git_dir = nodes / 'fixture/.git'
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
branch = (git_dir / 'HEAD').read_text().strip()[5:]
result = []
(git_dir / 'packed-refs').chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / branch).write_text(commits[1])
(git_dir / branch).chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / 'HEAD').chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == ['unknown', 'unknown', 'unknown']
def test_commit_is_read_beside_refs_that_are_not_utf8():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
packed = nodes / 'fixture/.git/packed-refs'
packed.write_bytes(b'0123456789abcdef0123456789abcdef01234567 refs/heads/\\xff\\xfe\\n' + packed.read_bytes())
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
''') == [True]
def test_head_that_is_not_utf8_is_read(tmp_path):
try:
open(os.fsencode(tmp_path) + b'/\xff\xfe', 'wb').close()
except (OSError, ValueError):
pytest.skip('this file system has no file of such a name, as that of Windows')
assert lines('''
import git_utils
heads = nodes / 'fixture/.git/refs/heads'
heads.mkdir(parents=True)
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/\\xff\\xfe\\n')
with open(os.fsencode(heads) + b'/\\xff\\xfe', 'wb') as ref:
ref.write(b'0123456789abcdef0123456789abcdef01234567\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['0123456789abcdef0123456789abcdef01234567']
# what MinGit 2.56 named the file of a branch that was cloned on Windows
NAMES_OF_GIT_FOR_WINDOWS = [
(b'rel-\xfe', 'rel-\u00fe'),
(b'caf\xe9', 'caf\u00e9'),
(b'rel-\x81', 'rel-81'),
('\ud55c\uae00'.encode(), '\ud55c\uae00'),
('\ud55c'.encode() + b'\xfe\xe9\xc3', '\ud55c\u00fe\u00e9\u00c3'),
('a\U0001f600'.encode(), 'a\U0001f600'),
(b'\xe0\x80\x80', '\u00e08080'),
# a surrogate in UTF-8, which `xutftowcsn` of compat/mingw.c of git takes as one
(b'\xed\xa0\x80', '\ud800'),
]
def test_file_of_a_ref_is_named_as_git_for_windows_names_it():
assert lines('''
import git_utils
result = [git_utils.file_name_of_git_for_windows(name) for name in %r]
''' % [name for name, _ in NAMES_OF_GIT_FOR_WINDOWS]) == [file_name for _, file_name in NAMES_OF_GIT_FOR_WINDOWS]
@pytest.mark.skipif(os.name != 'nt', reason='the names that Git for Windows gives its files')
def test_ref_that_git_for_windows_made_is_read():
"""A name that is not UTF-8 is no name of a file there, and Git for Windows writes the file under another."""
assert lines('''
import git_utils
heads = nodes / 'fixture/.git/refs/heads'
heads.mkdir(parents=True)
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/rel-\\xfe\\n')
(heads / 'rel-\\u00fe').write_text('0123456789abcdef0123456789abcdef01234567\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['0123456789abcdef0123456789abcdef01234567']
def test_packed_ref_is_matched_by_its_bytes():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
git_dir = nodes / 'fixture/.git'
other = b'0123456789abcdef0123456789abcdef01234567 refs/heads/release-\\xff\\n'
(git_dir / 'packed-refs').write_bytes(other + (git_dir / 'packed-refs').read_bytes())
(git_dir / 'HEAD').write_bytes(b'ref: refs/heads/release-\\xfe\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
(git_dir / 'packed-refs').write_bytes(other + commits[1].encode() + b' refs/heads/release-\\xfe\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
''') == ['unknown', True]
SUBMODULE = '''
os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='protocol.file.allow', GIT_CONFIG_VALUE_0='always')
def git(path, *args):
subprocess.run(['git', '-c', 'protocol.file.allow=always', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True)
library = repository(pathlib.Path(tmp) / 'library')
origin = pathlib.Path(tmp) / 'origin'
origin.mkdir()
git(origin, 'init', '-q')
git(origin, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
pinned_commits = []
for commit in library:
git(origin / 'library', 'checkout', '-q', commit)
git(origin, 'commit', '-q', '-a', '-m', 'library at ' + commit)
pinned_commits.append(head(origin))
'''
@pytest.mark.parametrize('clone', [['--recursive'], []], ids=['with its submodules', 'without its submodules'])
def test_checkout_brings_the_submodules_to_the_commit(clone):
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', *%r, str(origin), 'fixture')
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[0]), head(nodes / 'fixture') == pinned_commits[0],
head(nodes / 'fixture/library') == library[0]]
''' % clone) == [True, True, True]
def test_submodules_are_brought_to_the_commit_of_a_pack_that_is_at_it_already():
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', '--recursive', str(origin), 'fixture')
git(nodes / 'fixture/library', 'checkout', '-q', library[0])
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), head(nodes / 'fixture/library') == library[1]]
''') == [False, True]
def test_submodule_that_was_never_fetched_is_left_alone_in_a_pack_cloned_without_its_submodules():
"""As git does without `--init`: no submodule of such a clone is active."""
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', str(origin), 'fixture')
# moved, as git makes files read-only that Windows does not remove
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), list((nodes / 'fixture/library').iterdir())]
''') == [False, []]
@pytest.mark.parametrize('reachable', [True, False], ids=['reachable', 'away'])
def test_submodule_that_was_never_fetched_is_fetched_in_a_pack_cloned_as_the_manager_clones(reachable):
"""`clone --recursive` makes every submodule active, also one of a later commit: git updates it without `--init`."""
result = lines(SUBMODULE + '''
import io, logging
log = io.StringIO()
logging.getLogger().addHandler(logging.StreamHandler(log))
plain = pathlib.Path(tmp) / 'plain'
plain.mkdir()
git(plain, 'init', '-q')
git(plain, 'commit', '-q', '--allow-empty', '-m', 'no submodule')
git(nodes, 'clone', '-q', '--recursive', str(plain), 'fixture')
git(plain, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
git(plain, 'commit', '-q', '-m', 'a submodule')
git(nodes / 'fixture', 'pull', '-q')
if not %r:
# moved, as git makes files read-only that Windows does not remove
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
result = [core.repo_switch_commit(str(nodes / 'fixture'), head(plain)), (nodes / 'fixture/library/__init__.py').exists(),
"'" + str(nodes / 'fixture') + "'" in log.getvalue(), 'library' in log.getvalue()]
''' % reachable)
assert result == ([False, True, False, False] if reachable else [None, False, True, True])
def test_git_is_not_run_for_the_submodules_of_a_pack_that_has_none():
assert lines('''
import git
commits = repository(nodes / 'fixture')
ran = []
execute = git.Git.execute
def recorded(self, command, *args, **kwargs):
ran.append(list(command))
return execute(self, command, *args, **kwargs)
git.Git.execute = recorded
result = [core.repo_switch_commit(str(nodes / 'fixture'), commits[1]), [command for command in ran if 'submodule' in command]]
''') == [False, []]
-145
View File
@@ -1,145 +0,0 @@
import configparser
import importlib.util
import logging
import os
import pytest
from manager_test_utils import GLOB_DIR
from test_git_exe_setting import take
URL = "https://github.com/someone/some%20pack"
PLAIN = '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
PERCENT = f'[core]\n\tbare = false\n[remote "origin"]\n\turl = {URL}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
NO_VALUE = '[core]\n\tbare\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
NO_VALUE_THEN_DEEPER = '[core]\n\tbare\n\t\tfilemode = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
NO_REMOTE = '[core]\n\tbare = false\n'
BOM = "\ufeff" + PLAIN
NOT_A_CONFIG = "ref: refs/heads/master\n" + PLAIN
NOT_ASCII = PLAIN + '[user]\n\tname = 홍길동\n'
NOT_UTF8 = PLAIN.encode() + b'[user]\n\tname = \xff\xfe\n'
BRANCH_NOT_UTF8 = PLAIN.encode() + b'[branch "release-\xfe"]\n\tremote = origin\n\tmerge = refs/heads/release-\xfe\n'
ORIGIN = '[remote "origin"]\n\turl = https://github.com/someone/pack\n'
OTHER = '\t[remote "other"]\n\turl = https://github.com/someone/other\n'
VALUE_OVER_TWO_LINES = '[core]\n\tdescription = a \\\n' + OTHER + ORIGIN
QUOTED_VALUE_OVER_TWO_LINES = '[core]\n\tdescription = "a # b \\\n' + OTHER.replace('\n', '"\n', 1) + ORIGIN
COMMENT_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\t# a comment \\\n' + ORIGIN
VALUE_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\tdescription = a\\\\\n' + ORIGIN
VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS = '[remote "origin"]\n\turl = https://github.com/someone/pack\\'
URL_BEFORE_THE_FIRST_SECTION = "url = https://someone:a-token@github.com/someone/pack\n" + PLAIN
def git_utils():
spec = importlib.util.spec_from_file_location("_git_utils", GLOB_DIR / "git_utils.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def git_url():
return git_utils().git_url
def resolve():
return take(GLOB_DIR / "manager_core.py", "resolve_giturl_from_path", {
"os": os, "configparser": configparser, "logging": logging, "git_utils": git_utils(),
})
@pytest.fixture(params=[git_url, resolve], ids=["git_url", "resolve_giturl_from_path"])
def read(request, tmp_path):
reader = request.param()
def read(config, mode=None):
(tmp_path / ".git").mkdir(exist_ok=True)
(tmp_path / ".git" / "config").write_bytes(config if isinstance(config, bytes) else config.encode())
if mode is not None:
(tmp_path / ".git" / "config").chmod(mode)
return reader(str(tmp_path))
return read
def test_url_is_read(read):
assert read(PLAIN) == "https://github.com/someone/pack"
def test_url_with_a_percent_sign_is_read_as_it_is(read):
assert read(PERCENT) == URL
def test_url_is_read_beside_a_key_without_a_value(read):
assert read(NO_VALUE) == "https://github.com/someone/pack"
def test_config_without_a_remote_has_no_url(read):
assert read(NO_REMOTE) is None
def test_url_without_a_value_is_no_url(read):
assert read('[remote "origin"]\n\turl\n') is None
def test_url_is_read_after_a_byte_order_mark(read):
assert read(BOM) == "https://github.com/someone/pack"
def test_url_is_read_beside_text_that_is_not_ascii(read):
assert read(NOT_ASCII) == "https://github.com/someone/pack"
def test_url_is_read_beside_bytes_that_are_not_utf8(read):
assert read(NOT_UTF8) == "https://github.com/someone/pack"
def test_url_is_read_beside_a_branch_that_is_not_utf8(read):
assert read(BRANCH_NOT_UTF8) == "https://github.com/someone/pack"
def test_config_that_cannot_be_parsed_has_no_url_and_is_reported(read, caplog, tmp_path):
assert read(NOT_A_CONFIG) is None
assert str(tmp_path / ".git" / "config") in caplog.text
def test_key_before_a_deeper_line_is_read(read):
"""For git a line that is indented more is a key of its own; the parser would take it as more of the value before it."""
assert read(NO_VALUE_THEN_DEEPER) == "https://github.com/someone/pack"
assert read('[remote "origin"]\n\turl = https://github.com/someone/pack\n\t\tfetch = +refs/heads/*:refs/remotes/origin/*\n') == "https://github.com/someone/pack"
def test_value_that_goes_on_at_the_next_line_is_one_value(read):
"""As for git: what looks like a section in the second line of a value is text of that value."""
assert read(VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
assert read(QUOTED_VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
assert read(VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS) == "https://github.com/someone/pack"
def test_line_that_does_not_go_on_is_a_line_of_its_own(read):
assert read(COMMENT_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
assert read(VALUE_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
def test_config_that_cannot_be_parsed_is_reported_without_its_text(read, caplog, tmp_path):
assert read(URL_BEFORE_THE_FIRST_SECTION) is None
assert str(tmp_path / ".git" / "config") in caplog.text
assert "a-token" not in caplog.text
def test_config_that_cannot_be_parsed_is_reported_once(read, caplog, tmp_path):
for _ in range(3):
assert read(NOT_A_CONFIG) is None
assert caplog.text.count(f"Cannot read '{tmp_path / '.git' / 'config'}'") == 1
def test_config_that_may_not_be_read_has_no_url_and_is_reported(read, caplog, tmp_path):
url = read(PLAIN, mode=0)
try:
open(tmp_path / ".git" / "config").close()
except OSError:
pass
else:
pytest.skip("the file can be read here, as by root or on Windows")
assert url is None
assert str(tmp_path / ".git" / "config") in caplog.text

Some files were not shown because too many files have changed in this diff Show More