Compare commits

...
10 Commits
Author SHA1 Message Date
Dr.Lt.Data f450f61d1f bump version to 3.43.2 2026-11-19 20:56:07 +09:00
Dr.Lt.Data a288523cd3 On an old ComfyUI, serve only the update of ComfyUI
Five changes, each in the CHANGELOG.

- On a ComfyUI without the System User API, refuse every route but the
  update of ComfyUI, leave a scheduled restore and the pip files of the
  unprotected directory alone, and migrate only the settings that are
  preferences
- Refuse there in the security gate, not by changing the security level
  that was read
- After the update, install the requirements of ComfyUI in prestartup,
  and keep a backup of the legacy directory that is already there
- Read config.ini values as plain text and default the invalid ones
- Report a failed legacy backup without its error text

Reported by:
- anir0y
2026-11-19 20:43:37 +09:00
Dr.Lt.Data 480dc05d99 Keep sharing credentials on the server and tighten the security-level and POST checks
Seven changes, each in the CHANGELOG.

- Keep saved sharing credentials out of server answers, and log in to
  matrix.org only
- Hold a switch of ComfyUI to an older version to the security level
- Take a JSON body only as application/json
- Hold a snapshot restore to the security level of a switch to an older
  version
- Save only a choice of the share menu as the share option
- Write the saved Matrix account as a file of its user only
- Hold every POST that changes something to application/json, and save
  the share option with a POST

Reported by:
- gistrec
- sondt99
- dungNHVhust
- ascanner
- godzeo
- naroSEC
- Liam-G
- manus-pi
- eliteaja11-dev
2026-11-19 20:43:37 +09:00
Dr.Lt.Data 5688993b0b Add the Kornia SAM safetensors models to the model list 2026-11-19 12:00:41 +09:00
Dr.Lt.Data 09cac4f075 bump version to 3.43.1 2026-11-19 08:17:43 +09:00
Dr.Lt.Data de1c60c962 Fix the scheduled snapshot restore, the steps of a snapshot restore and reserved install scripts (#3554)
Three fixes. The CHANGELOG has an entry for each.

- Give the scheduled snapshot restore the directories of the server
- Report the failed steps of a snapshot restore, check a cloned node pack
  out at the pinned commit and run the install step of the node packs it
  installs
- Write what is reserved for the next start as UTF-8, and remove the files of
  an old version from the node pack, and from nowhere else, when a version is
  switched; read the list of those files as UTF-8
2026-11-19 07:14:01 +09:00
Dr.Lt.Data 8a75836a7b Fix git_exe, .git/config reading, the commit and submodules of a node pack and an update whose git step fails (#3552)
Four fixes. The CHANGELOG has an entry for each.

- Use the git executable set as git_exe
- Read the commit of a node pack whose refs are packed, and bring its
  submodules to the commit that is checked out
- Start with a node pack whose .git/config cannot be read
- Fail an update whose pull or submodule update failed, and undo the pull
2026-11-18 22:54:23 +09:00
Dr.Lt.Data 3a2177fb24 Fix failure answers, console messages and settings (#3543)
Five fixes. The CHANGELOG has an entry for each.

- Log a failed read of the ComfyUI versions instead of raising
- Print the messages of manager_core as they are
- Answer 400 to an install request whose body is not usable
- Refuse a db_mode, update_policy or component_policy request the server cannot use
- Keep a setting chosen while the Manager menu is loading it
2026-11-17 12:39:56 +09:00
Dr.Lt.Data c8bf0d48f3 update DB 2026-11-16 09:03:04 +09:00
Dr.Lt.Data afd1b1e606 Leave the log file alone once it is closed (#3538)
Restarting through comfy-cli calls close_log() and then exits from the
request handler. asyncio logs the exit, the Manager's logging handler
passes the record to the logger for the log file, and the write to the
closed file raised ValueError: the console showed it twice at every
such restart.

- Write to the log file only while it is open; the console still gets
  what is written to it
- Close the log file under the lock of the writes, so that a write
  that has found it open is not overtaken by the close
- Add tests for writes to an open and to a closed log file, and for
  the lock around the close
- Add a CHANGELOG entry
2026-11-16 08:38:20 +09:00
69 changed files with 5966 additions and 721 deletions
+347 -11
View File
@@ -2,6 +2,348 @@
## Unreleased
### A failed legacy backup is reported without the text of the error, and leaves no part of a backup
When the legacy directory could not be moved to its backup, the startup notice
carried the text of the error, which has paths of that directory in it. The
notice now says only that the backup failed, and the error is in the terminal.
When the move fails while it copies, the legacy directory is as it was and the
next start tries again; what was copied is removed, so that the starts do not
each leave another part of a backup.
### On an old ComfyUI, Manager only updates ComfyUI
On a ComfyUI without the System User API (before 0.3.76), Manager's data
directory is not protected, so installs are refused there and startup scripts
are not run. Other requests were still served, and other files of that
directory were still acted on. Now only the update of ComfyUI is served there:
every other request to Manager is answered with `comfyui_outdated`. A snapshot
restore scheduled in that directory is left alone at the start, and the start
says so; its `pip_auto_fix.list` and `pip_overrides.json` are not applied by
the start or by the update. Update ComfyUI to use Manager again.
After that update, the first start moves `config.ini` to the protected
directory. It moved every setting and raised only a security level below
`normal`. Now it moves the settings that are preferences and leaves behind
those that permit an install (`allow_git_url_install`, `allow_pip_install`,
`allow_flagged_nodepack_install`) or change where Manager fetches from
(`channel_url`, `http_channel_enabled`, `bypass_ssl`, `git_exe`), and any it
does not know. Those are back at their defaults, and the terminal lists the
ones that had another value; set them again if you need them. A security level
that is not a security level is set to `normal` like one below it.
### Every POST that changes something is taken only as `application/json`, and the share option is saved by POST
A page of another site can make the browser send a GET, and a POST without a
body and without a Content-Type, for which no preflight is made. The Manager
routes that take no body (`queue/start`, `queue/reset`, `queue/update_comfyui`,
`snapshot/save`, `reboot`) now answer 400 unless the request has
`Content-Type: application/json`, as the routes that read a JSON body do: a
browser does not send that header to another site without a preflight. The
share option is saved with `POST /manager/share_option` and a JSON body
`{"value": ...}`; `GET /manager/share_option` only answers with the saved
option, and a `value` given to it is ignored. The Manager's own pages send the
header. A script that calls one of these routes has to send it too, and one
that saved the share option with `?value=` has to POST.
### The file of the saved Matrix account is readable by its user only
The share dialog saves the Matrix account, with its password, in `matrix_auth`
in Manager's data directory. The file was written with the default mode of
new files, which other users of the machine can usually read. It is now written
with mode `0600`, and a file that is already there gets that mode the next
time an account is saved.
### The share option that is saved is one of the choices of the share menu
`/manager/share_option` saved any text as the share option. It now saves
`all`, `none`, `youml` or `matrix`, the choices of the menu, and answers 400
for another value.
### Restoring a snapshot needs the security level of a switch to an older version
A snapshot restore takes the node packs back to the versions that the
snapshot recorded, older ones too. `POST /snapshot/restore` needed `middle`, which the
default `security_level = normal` gives on any listener; a switch of ComfyUI to
an older version needs `high`. A restore now needs `high` as well: `normal-` or
lower on a loopback listener, `weak` otherwise. At `normal`, `Restore` in the
Snapshot Manager is refused; `cm-cli restore-snapshot` is not changed.
### Routes that read a JSON body take it only as `application/json`
A POST route that reads a JSON body parsed it whatever the Content-Type of the
request. These routes now answer 400 unless the Content-Type is
`application/json`. The Manager's own scripts send it; a script or tool that
posts JSON to the Manager without that header has to add it.
### Switching ComfyUI to an older version is held to the security level
Switching the ComfyUI version was not checked against `security_level`. A
switch to an older release, or to anything that is not a release tag, now needs
`normal-` or lower when ComfyUI listens on a loopback address, and `weak`
otherwise; at the default `normal`, `Switch ComfyUI` in the Manager menu
answers that the security level does not allow it. A switch to `nightly` or to
a newer release is an update and works at every level, as before. A ComfyUI
with commits after its release, as on `nightly`, would go back by a switch to
that release, so that counts as older; in a repository without release tags,
such as a clone without tags, every version but `nightly` does. The menu
changes the update policy to that of the chosen version only after the switch
has happened; it did so before asking for the switch.
### The server no longer returns saved sharing credentials
`GET /manager/get_matrix_auth` answered with the saved Matrix homeserver,
username and password, to any client that could reach the server. It now answers
without the password. The share dialog leaves the password field empty for the
saved account, and the server uses the saved password for the username it was
saved with; for another account a password has to be typed. An account is saved
once it has logged in; a share request no longer replaces the saved account
before that. If others could reach the server while a Matrix password was saved,
change that password.
Sharing to Matrix logs in to matrix.org, where the share room is, and to no
other homeserver. The homeserver of the share dialog can no longer be changed, a
share request that names another homeserver is refused, and an account that was
saved for another homeserver is not used: an account of matrix.org has to be
entered. Before, the server logged in to any homeserver that a request named,
with the password of the request.
The YouML API token is kept in the browser that shares, which is what sends it
to YouML; the server stored it, and `GET /manager/youml/settings` answered with
it in the same way. Both `/manager/youml/settings` routes are removed. The token
has to be entered once more in the YouML share dialog. Delete `.youml` in
Manager's data directory (`<USER_DIRECTORY>/__manager/`, or
`<USER_DIRECTORY>/default/ComfyUI-Manager/` on older ComfyUI), and if others
could reach the server while a token was saved, issue a new token.
### A setting chosen while the Manager menu is loading it is kept
The Manager menu asks the server for the database mode, the component policy,
the update policy and the share option when it is first opened. A value chosen
before the answer arrived was saved, but the menu went back to showing the old
one. The menu keeps the chosen value.
### Setting requests with an unknown value are refused
The routes that set `db_mode`, `update_policy` and `component_policy` stored
whatever value a request carried and wrote it to `config.ini`. They answer 400
for a value that is not one of those the Manager's menu offers, and for a JSON
body without a `value`, which ended with status 500.
### `git_exe` chooses the git executable
The path set as `git_exe` in `config.ini` was read but not used: git commands
kept running the `git` found on `PATH`. The Manager, cm-cli and the git helper
now run the configured executable. For the Manager it no longer has to be on
`PATH`: the Manager also starts when the only git is the one named by
`git_exe`. cm-cli still needs a git on `PATH` to start.
A value that is not a working git is reported in the log, and the default git
is used. The value is read as it is written: with a `%` in it, as in a path
of Windows, the Manager read every setting of `config.ini` as its default.
`git_exe` is used only when the configuration file is in a protected
directory, that is with a ComfyUI that has the System User API.
### The commit and the submodules of a git node pack
A snapshot recorded no commit for a git node pack whose refs were packed, as
after `git gc`. The commit is read from `packed-refs` too. A `HEAD` that is
not UTF-8, as one that names a branch in another encoding, raised an error
where the commit of a node pack is read. It is read as bytes now. On Windows
the commit of a branch whose name is not ASCII, as a Korean one, could be
unknown as well: the file of the branch is looked for under the name that Git
for Windows gives it. The commit is read while the Manager is loading, and an
error there kept the Manager from loading: also for a `.git` with a folder
where the file of the branch would be, as after
`git checkout --orphan feature` beside a branch `feature/x`, or with a file
that cannot be read. The commit of such a node pack is unknown now.
When a snapshot restore checks a git node pack out, its submodules are brought
to the commits that the commit names, also when the node pack is at the commit
of the snapshot already. A submodule that was never fetched is then fetched
too in a node pack that the Manager installed, as the Manager clones a node
pack with its submodules; in a node pack cloned without them, it is fetched
only when the node pack itself is checked out.
### A node pack whose `.git/config` cannot be read
The Manager reads the remote url of every installed node pack from its
`.git/config` while it is loading. A url with a `%`, such as one with `%20`,
a key without a value, such as `bare` alone, a key on a line that is indented
more than the one before it, a byte order mark at the start of the file, or
text that the encoding of the system cannot decode, such as the name of a
branch in another encoding, raised an error there, and the Manager did not
load. These files are read now, and for a file that cannot be read the url of
that node pack is unknown and a warning names the file once.
### An update whose git step fails is a failure, and can be done again
On Windows the pull of an update runs in a helper process, which ended with 0
when the pull failed, and its result was not read: the update went on to the
install script and ended as done. The helper ends with 1 now, and the update
fails.
When the update of its submodules failed, a node pack stayed at the new
commit: the next update found nothing to do, and the install script of the
update never ran. The pull is undone, and the submodules that were updated
before the one that failed go back with it. A node pack with a submodule
that cannot be fetched at all is not updated until it can.
### A snapshot restore reports what failed, and restores the pinned commit
The summary of a restore listed a node pack as `INSTALLED`, `DISABLED` or
`ENABLED` without looking at the result of the step: a clone that failed, for
example because the directory already existed or the url could not be reached,
was `INSTALLED`. A step that fails is now listed as `FAILED`, and the Manager
itself is no longer listed as `DISABLED`. A registry that cannot be reached
ended the restore at the first node pack to install from it, and so did a
node pack whose directory could not be moved to disable or enable it; such a
node pack is listed as `FAILED`, and the restore goes on. `cm-cli
restore-snapshot` ends with 1 when a step failed or a pip package that a
`--pip-*` option selects was not installed, and a scheduled restore then says
`Restore snapshot failed.`: it ended with 0. A url of the snapshot that cannot
be parsed ended the restore as well; the node pack is listed as `FAILED`.
A git node pack that the restore had to clone stayed at the newest commit. It
is checked out at the commit of the snapshot, and its install script runs after
that. When the commit cannot be checked out, the install script still runs, at
the commit the clone is at, and the node pack is listed as `FAILED`. An
installed git node pack that the registry does not know was checked out only
when cm-cli was run from `custom_nodes`, as a scheduled restore does; it is
checked out from any directory.
A git node pack of the registry that was already installed, or that the
restore enabled, was listed a second time as `SKIPPED`; it is listed once. An
installed one that is checked out is listed by its name, as the others are: it
was listed by its path.
A registry node pack that the restore had to install was unpacked, but its
requirements were not installed and its install script did not run. The
restore now runs them, and lists the node pack as `FAILED` when they fail.
A requirement or an install script that failed was taken as done until the
next start: the next node pack that names the requirement skipped it, and
installing or fixing the node pack again did not run the script. Both are
tried again. The install script of a git node pack was skipped in the same way
when it was cloned where another version of the node pack had been installed
since the start, as a restore does for a snapshot that has both; it runs.
### Install requests with an unusable body are answered with 400
`/customnode/install/git_url` and `/customnode/install/pip` answered 500 when
the JSON body was not an object, or when `url` or `packages` was not a string.
They answer 400, as they do for a missing field.
### What is reserved for the next start is written as UTF-8
The install script of an update, the removal of a node pack whose files are in
use and a switch of version are reserved in a file that the start-up script
reads as UTF-8, and that was written in the encoding of the system. On Windows
a path with a character outside ASCII was lost: one that the code page cannot
write, such as a Korean folder name with code page 1252, raised an error and
nothing was reserved; one that it can write was read back as another path, and
what was reserved was not carried out at the next start. The file is written
as UTF-8.
A switch of version that is carried out at the next start looked for the files
that the new version no longer has in `custom_nodes` in place of the directory
of the node pack: they stayed in the node pack, and a file of the same name in
`custom_nodes` was removed. They are removed from the node pack. A switch of
version, at the next start or at once, removes the files that the new version
no longer has before it extracts the archive of the new version: where two
names are one file, as `./a.py` and `a.py`, or names that differ in case alone
on Windows, a file of the new version was removed after it was extracted.
A name of the old list that leads out of the node pack, with `..` or as an
absolute path, removed a file outside it; nothing is removed for such a name.
A file that the old version has alone and that cannot be removed, as one that
another program has open on Windows, is left with a warning, and the switch
goes on with the files of the new version.
A folder that the files of the old version left empty, or with nothing but the
`__pycache__` of Python, stayed, and a file of the new version could not take
its place; such a folder is removed.
A node pack whose directory keeps its name is no longer moved onto itself at
the next start, which Windows refuses while a file in it is open.
When the switch moves the node pack to another directory, the install script
of the new version runs there; it was looked for in the directory that the
node pack was moved from, and did not run.
That list is written as UTF-8 and was read in the encoding of the system. On
Windows a switch of version of a node pack with a file name that the code page
of the system cannot decode ended in the middle: the files of the new version
were unpacked, its install script did not run and the files of the old version
stayed. The list is read as UTF-8. A name of the list is read as it is written:
a space at its start or its end was dropped, and the file of the other name was
the one removed.
### A scheduled snapshot restore works with `--base-directory`
With `--base-directory`, where `custom_nodes` is not inside the ComfyUI
directory, a snapshot restore scheduled for the next start failed with
`ModuleNotFoundError: No module named 'utils'`, and the request was dropped.
The restore now gets the path of ComfyUI, and the user directory and
`custom_nodes` directory the server uses.
### Console messages show paths, URLs and package names as they are
Manager printed many of its messages through rich, which reads square
brackets as markup. A package name such as `diffusers[torch]` was shown as
`diffusers`, a text such as `:100:` as an emoji, and a line longer than the
console was broken in the middle of a path or a URL. A text with a closing
tag such as `[/b]` raised `MarkupError` instead of being printed, in the
middle of the operation that reported it. These messages are now printed as
they are; numbers and quoted strings keep their colors.
### The list of ComfyUI versions answers a failure with 400 again
When the versions of ComfyUI could not be read, the request for the list ended
with status 500 and a `TypeError` in the log: the call that logs the cause was
given an argument it does not take. The cause is logged, and the answer is 400.
### A value of config.ini is plain text, and one that a setting cannot have gives its default
Manager read `%(name)s` in a value of `config.ini` as a reference to another
setting, and a `%` that is not of that form made the whole file unreadable:
every setting was then at its default, `security_level` too, and nothing said
so. A value is now read as it is written; `%%`, which was read as one `%`, is
now two. `security_level`, `network_mode`, `db_mode`, `update_policy` and
`component_policy` have their default when `config.ini` gives a value that
they cannot have, and Manager logs a warning that names it; the other settings
are read as before, and `config.ini` keeps the value. Before, a
`security_level` that is not a level refused every action that needs one; now
it is `normal`. A `config.ini` that cannot be read at all still gives the
default settings, and is still written anew from them when a setting is
saved; Manager now logs a warning when it reads one.
### After an update from an old ComfyUI, the requirements of ComfyUI are installed before the node packs are loaded
On Windows, or with `always_lazy_install`, the update of ComfyUI reserves the
install of its requirements for the next start. On a ComfyUI without the
System User API that was reserved in the legacy directory, which the updated
ComfyUI does not read. Manager installed them only at a start that found a
`config.ini` in both directories, after ComfyUI and the node packs had been
loaded. It now installs them at the start that still finds the legacy
`config.ini`, before the node packs are loaded. A ComfyUI that cannot start
without one of its new requirements does not get as far as Manager, as
before: install them with `pip install -r requirements.txt` then. The legacy
directory is moved to `.legacy-manager-backup` as before; a backup that is
already there is no longer deleted, the new one gets a numbered name, and the
start reminds of each of them.
### An old ComfyUI no longer leaves `security_level = strong` in config.ini
On a ComfyUI without the System User API, Manager refused installs by changing
the security level it had read to `strong`. A `config.ini` that Manager
created there was written with that `strong`, and installs stayed refused
after ComfyUI was updated. Now Manager does not change the security level:
the check of the security level refuses on such a ComfyUI, whatever the level
is. A `config.ini` that already has `security_level = strong` is not changed:
if you did not choose it, set it to `normal`.
### Restarting under comfy-cli no longer reports a closed log file
Restarting ComfyUI from the Manager under comfy-cli printed `ValueError: I/O
operation on closed file` on the console. The log file is closed before the
process exits, and what was logged after that was still written to it.
### Libraries are told whether the console is a terminal
With file logging on, the logger that captures the output answered every
@@ -232,18 +574,12 @@ allow_pip_install = true
Changes take effect after a **restart** (no hot reload).
#### Residual-risk note — outdated ComfyUI behavior change
#### Outdated ComfyUI
On outdated ComfyUI versions (no system-user API), the manager previously
forced `security_level = strong`, which unconditionally denied the
git-URL/pip install surfaces. After this change those surfaces are governed
by the new flags instead: an operator who explicitly sets a flag to `true`
on a **loopback** listener can now perform installs on outdated ComfyUI
where the forced-strong policy previously denied them. This is an accepted,
deliberate trade-off: it requires explicit operator opt-in, remains bounded
to loopback listeners, and the flag-deny path on outdated ComfyUI still
surfaces the `comfyui_outdated` notice. If you operate an outdated ComfyUI
deployment, leave both flags at their default `false` and update ComfyUI.
On outdated ComfyUI versions (no system-user API) the flags do not apply:
git-URL and pip installs are refused there like every other install, whatever
the flags and the listener are, and the answer is the `comfyui_outdated`
notice. Update ComfyUI to use them.
### Removed share destinations
+4 -2
View File
@@ -178,7 +178,7 @@ The following settings are applied based on the section marked as `is_default`.
* Press the "Restore" button to revert to the installation status of the respective snapshot.
* However, for custom nodes not managed by Git, snapshot support is incomplete.
* When you press `Restore`, it will take effect on the next ComfyUI startup.
* The selected snapshot file is saved in `<USER_DIRECTORY>/default/ComfyUI-Manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
* The selected snapshot file is saved in `<USER_DIRECTORY>/__manager/startup-scripts/restore-snapshot.json`, and upon restarting ComfyUI, the snapshot is applied and then deleted.
![model-install-dialog](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/snapshot.jpg)
@@ -386,6 +386,8 @@ When you run the `scan.sh` script:
* `high` level risky features
* Downloading models that are not in `.safetensors` format and not
registered in the `default channel` model list
* Switch ComfyUI to an older version
* Restore Snapshot
* NOTE: `Install via git url`, `pip install`, and installation of custom nodes
not registered in the `default channel` are **no longer governed by
`security_level`** — they are governed by the dedicated install flags
@@ -395,7 +397,7 @@ When you run the `scan.sh` script:
* Uninstall/Update
* Installation of custom nodes registered in the `default channel`.
* Fix custom nodes
* Restore/Remove Snapshot
* Remove Snapshot
* Restart
* `low` level risky features
+20 -17
View File
@@ -81,7 +81,7 @@ core.check_invalid_nodes()
def read_downgrade_blacklist():
try:
import configparser
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(core.manager_config_path)
default_conf = config['default']
@@ -136,25 +136,25 @@ class Ctx:
self.no_deps = no_deps
def set_user_directory(self, user_directory):
if user_directory is None:
return
if user_directory is not None:
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
core.update_user_directory(user_directory)
core.update_user_directory(user_directory)
if os.path.exists(core.manager_pip_overrides_path):
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
if os.path.exists(core.manager_pip_overrides_path):
with open(core.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
if os.path.exists(core.manager_pip_blacklist_path):
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
if os.path.exists(core.manager_pip_blacklist_path):
with open(core.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
core.setup_git_executable()
def update_custom_nodes_dir(self, target_dir):
import folder_paths
@@ -1130,13 +1130,16 @@ def restore_snapshot(
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, core.manager_files_path)
try:
asyncio.run(core.restore_snapshot(snapshot_path, extras))
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
except Exception:
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
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."
-11
View File
@@ -12930,17 +12930,6 @@
"install_type": "git-clone",
"description": "Utility custom nodes for special effects, image manipulation and quality of life tools."
},
{
"author": "ruiqutech",
"title": "RuiquNodes for ComfyUI",
"id": "RuiquNodes",
"reference": "https://github.com/ruiqutech/ComfyUI-RuiquNodes",
"files": [
"https://github.com/ruiqutech/ComfyUI-RuiquNodes"
],
"install_type": "git-clone",
"description": "Nodes of EvaluateMultiple1, EvaluateMultiple3...\nSupport the execution of any fragment of Python code, generating multiple outputs from multiple inputs."
},
{
"author": "teward",
"title": "ComfyUI-Helper-Nodes",
+32 -11
View File
@@ -49,7 +49,18 @@ When you start ComfyUI with the new System User Protection API, Manager automati
### Step 1: Configuration Migration
Only `config.ini` is migrated automatically.
Only `config.ini` is migrated automatically, and of it only the settings that are preferences.
Settings that permit an install (`allow_git_url_install`, `allow_pip_install`, `allow_flagged_nodepack_install`) or change where Manager fetches from (`channel_url`, `http_channel_enabled`, `bypass_ssl`, `git_exe`), and settings that Manager does not know, are **not** migrated: the old `config.ini` was not protected, so they may have been changed without your knowledge. They are back at their defaults after the migration, and the terminal lists those that had another value than the default:
```
======================================================================
[ComfyUI-Manager] WARNING: Settings not migrated
- ['allow_git_url_install', 'channel_url']
- The legacy config.ini was not protected, so these are back at their defaults.
- Set them again in /path/to/ComfyUI/user/__manager/config.ini if you need them.
======================================================================
```
**Important**: Snapshots are **NOT** automatically migrated. You must copy them manually if needed.
@@ -67,6 +78,8 @@ During migration, if your security level is below `normal` (i.e., `weak` or `nor
If you need a lower security level, you can manually edit the config after migration.
A security level that is not one of `strong`, `normal`, `normal-` and `weak` is set to `normal` as well. Only that setting changes.
### Step 3: Legacy Backup
Your entire legacy directory is moved to a backup location:
@@ -74,7 +87,13 @@ Your entire legacy directory is moved to a backup location:
user/__manager/.legacy-manager-backup/
```
This backup is preserved until you manually delete it.
This backup is preserved until you manually delete it. If a backup is already there, it is kept, and the new one is named `.legacy-manager-backup-2`, `-3`, and so on.
### Requirements of ComfyUI
Before these steps, the start that finds the legacy `config.ini` installs the requirements of ComfyUI, before the node packs are loaded. On an old ComfyUI the update of ComfyUI could only reserve that install on Windows or with `always_lazy_install`, in the legacy directory, which is not read anymore.
If the updated ComfyUI does not start because one of its requirements is missing, it does not get as far as Manager. Install them yourself, with the Python that runs ComfyUI: `python -m pip install -r requirements.txt` in the ComfyUI directory.
---
@@ -91,7 +110,7 @@ As long as the backup exists, Manager will remind you on **every startup**:
----------------------------------------------------------------------
```
**To stop this notification**: Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it.
**To stop this notification**: Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it. If there are numbered ones (`.legacy-manager-backup-2`, ...), the notification lists them as well and stops when all are deleted.
---
@@ -107,13 +126,14 @@ If you need your old snapshots, copy the contents of `.legacy-manager-backup/sna
If you're running an older version of ComfyUI without the System User Protection API, Manager will:
1. **Force security level to `strong`** - All installations are blocked
2. **Display warning message**:
1. **Block all installations** - They are refused at every `security_level`. The `security_level` of `config.ini` is not changed
2. **Serve only the update of ComfyUI** - Every other request to Manager is answered with `comfyui_outdated` (HTTP 403), and files in Manager's data directory that schedule a restore or direct pip (`restore-snapshot.json`, `pip_auto_fix.list`, `pip_overrides.json`) are not acted on
3. **Display warning message**:
```
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
[ComfyUI-Manager] ERROR: ComfyUI version is outdated!
- Most operations are blocked for security.
- Every operation but the update of ComfyUI is blocked for security.
- ComfyUI update is still allowed.
- Please update ComfyUI to use Manager normally.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
@@ -133,7 +153,7 @@ If you're running an older version of ComfyUI without the System User Protection
| `weak` | All operations allowed, including from remote connections. |
**Notes:**
- `strong` is forced on outdated ComfyUI versions.
- On outdated ComfyUI versions all installations are blocked at every level.
- `normal` is the default and recommended for most users.
- `normal-` is for developers who need to install unregistered nodes locally.
- `weak` should only be used in isolated development environments.
@@ -154,7 +174,7 @@ security_level = normal
This error appears when:
- Your ComfyUI doesn't have the System User Protection API
- All installations are blocked until you update ComfyUI
- Everything but the update of ComfyUI is blocked until you update ComfyUI
**Solution**: Update ComfyUI to the latest version.
@@ -190,12 +210,13 @@ On older ComfyUI versions, the `__manager` directory is not normally created. If
### All my installations are blocked
**Check 1**: Is your ComfyUI updated?
- Old ComfyUI forces `security_level = strong`
- Old ComfyUI blocks all installations at every `security_level`
- Update ComfyUI to resolve
**Check 2**: What's your security level?
- Check `user/__manager/config.ini`
- `security_level = strong` blocks all installations
- Manager 3.43 and earlier wrote `security_level = strong` into a `config.ini` that it created on an old ComfyUI. If you did not choose it, set it to `normal`
### My snapshots are missing
@@ -203,11 +224,11 @@ Snapshots are not automatically migrated. You need to manually copy the `snapsho
### I keep seeing the backup notification
Delete the `.legacy-manager-backup` folder inside `user/__manager/` after confirming you don't need any data from it.
Delete the `.legacy-manager-backup` folder inside `user/__manager/`, and any numbered one (`.legacy-manager-backup-2`, ...), after confirming you don't need any data from it.
### Snapshot restore is blocked
On old ComfyUI (without System User API), snapshot restore is blocked because security is forced to `strong`. Update ComfyUI to enable snapshot restore.
On old ComfyUI (without System User API), snapshot restore is blocked, as is everything but the update of ComfyUI. A restore that is already scheduled is not run at the start either. Update ComfyUI to enable snapshot restore.
---
-31
View File
@@ -73387,37 +73387,6 @@
"title_aux": "RUI-Nodes"
}
],
"https://github.com/ruiqutech/ComfyUI-RuiquNodes": [
[
"EvaluateListMultiple1",
"EvaluateListMultiple3",
"EvaluateListMultiple6",
"EvaluateListMultiple9",
"EvaluateMultiple1",
"EvaluateMultiple3",
"EvaluateMultiple6",
"EvaluateMultiple9",
"ImageDilate",
"ImageErode",
"ListPath",
"MaskDilate",
"MaskErode",
"PreviewMask",
"RangeSplit",
"SaveMask",
"StringAsAny",
"StringConcat1",
"StringConcat3",
"StringConcat6",
"StringConcat9",
"StringPathStem",
"TermsToList",
"VAEDecodeSave"
],
{
"title_aux": "RuiquNodes for ComfyUI"
}
],
"https://github.com/ruminar/ComfyUI-CheckpointHandpickerSuite": [
[
"CheckpointListSelector",
+16 -10
View File
@@ -13,7 +13,6 @@ from git.remote import RemoteProgress
comfy_path = os.environ.get('COMFYUI_PATH')
git_exe_path = os.environ.get('GIT_EXE_PATH')
if comfy_path is None:
print("\nWARN: The `COMFYUI_PATH` environment variable is not set. Assuming `custom_nodes/ComfyUI-Manager/../../` as the ComfyUI path.", file=sys.stderr)
@@ -181,6 +180,14 @@ def switch_to_default_branch(repo):
return False
def undo_pull(repo, commit):
repo.git.reset('--hard', commit)
try:
repo.git.submodule('update', '--recursive')
except Exception:
pass
def gitpull(path):
# Check if the path is a git repository
if not os.path.exists(os.path.join(path, '.git')):
@@ -220,6 +227,7 @@ def gitpull(path):
repo.close()
return
tip_before_pull = repo.head.commit.hexsha
try:
repo.git.pull('--ff-only')
except git.GitCommandError:
@@ -229,7 +237,12 @@ def gitpull(path):
repo.git.reset('--hard', f'{remote_name}/{branch_name}')
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
repo.git.submodule('update', '--init', '--recursive')
try:
repo.git.submodule('update', '--init', '--recursive')
except Exception:
undo_pull(repo, tip_before_pull)
raise
new_commit_hash = repo.head.commit.hexsha
if commit_hash != new_commit_hash:
@@ -239,6 +252,7 @@ def gitpull(path):
except Exception as e:
print(e)
print("CUSTOM NODE PULL: Fail") # unknown git error
sys.exit(1)
repo.close()
@@ -492,14 +506,6 @@ def restore_pip_snapshot(pips, options):
print(f"Installation failed for pip packages: {failed}")
def setup_environment():
if git_exe_path is not None:
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe_path)
setup_environment()
try:
if sys.argv[1] == "--clone":
repo_path = None
-5
View File
@@ -25114,11 +25114,6 @@
"last_update": "2026-08-19 01:47:50",
"author_account_age_days": 1348
},
"https://github.com/ruiqutech/ComfyUI-RuiquNodes": {
"stars": 0,
"last_update": "2024-05-23 01:21:50",
"author_account_age_days": 944
},
"https://github.com/ruminar/ComfyUI-CheckpointHandpickerSuite": {
"stars": 3,
"last_update": "2026-08-25 12:47:02",
+107 -21
View File
@@ -1,5 +1,6 @@
import os
import configparser
import logging
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
@@ -12,28 +13,113 @@ def is_git_repo(path: str) -> bool:
return os.path.exists(os.path.join(path, '.git'))
def get_commit_hash(fullpath):
git_head = os.path.join(fullpath, '.git', 'HEAD')
if os.path.exists(git_head):
with open(git_head) as f:
line = f.readline()
def file_name_of_git_for_windows(name):
"""The name that Git for Windows gives the file of a ref, whose name is `name` in bytes.
if line.startswith("ref: "):
ref = os.path.join(fullpath, '.git', line[5:].strip())
if os.path.exists(ref):
with open(ref) as f2:
return f2.readline().strip()
else:
return "unknown"
else:
# detached HEAD: the file holds the sha followed by a newline;
# without the strip the pinned hash carries that newline into
# snapshots, and the next restore's checkout of that hash fails
return line.strip()
A name that is not UTF-8 is no name of a file there: a byte that is not of a character becomes
the character of its number, or below 0xa0 its two hex digits, as in `xutftowcsn` of compat/mingw.c of git."""
file_name = ''
at = 0
while at < len(name):
size = 1 if name[at] < 0xc2 else 2 if name[at] < 0xe0 else 3 if name[at] < 0xf0 else 4
try:
file_name += name[at:at + size].decode('utf-8', 'surrogatepass')
at += size
except UnicodeDecodeError:
file_name += chr(name[at]) if name[at] >= 0xa0 else '%02x' % name[at]
at += 1
return file_name
def get_commit_hash(fullpath):
git_dir = os.path.join(fullpath, '.git')
try:
with open(os.path.join(git_dir, 'HEAD'), 'rb') as f:
line = f.readline().strip()
if not line.startswith(b"ref:"):
# detached HEAD: the file holds the sha followed by a newline;
# without the strip the pinned hash carries that newline into
# snapshots, and the next restore's checkout of that hash fails
return line.decode('ascii', errors='replace')
ref_name = line[4:].strip()
# put together as git does it, and not with `os.path.join`, for which a name can lead elsewhere
if os.name == 'nt':
ref = git_dir + '/' + file_name_of_git_for_windows(ref_name)
else:
ref = os.fsencode(git_dir) + b'/' + ref_name
# a folder there is no ref, as for git: a branch `feature/x` beside the unborn branch `feature`
if os.path.isfile(ref):
with open(ref, 'rb') as f:
return f.readline().strip().decode('ascii', errors='replace')
# after `git pack-refs` or `git gc` the ref is a line of packed-refs
with open(os.path.join(git_dir, 'packed-refs'), 'rb') as f:
for packed in f:
fields = packed.split()
if len(fields) == 2 and fields[1] == ref_name:
return fields[0].decode('ascii', errors='replace')
except OSError:
pass
return "unknown"
warned_git_configs = set()
def lines_of_git_config(lines):
"""
the lines as git takes them: a `\\` at the end of a line makes the next line more of the same value,
and a line may be indented by any amount
"""
whole, quoted = '', False
for line in lines:
line = line.rstrip('\n')
goes_on = False
i = 0
while i < len(line):
if line[i] == '\\':
goes_on = i == len(line) - 1
i += 1
elif line[i] == '"':
quoted = not quoted
elif line[i] in '#;' and not quoted:
break
i += 1
if goes_on:
whole += line[:-1]
else:
yield (whole + line).lstrip() + '\n'
whole, quoted = '', False
if whole:
yield whole.lstrip() + '\n'
def read_git_config(git_config_path) -> 'configparser.ConfigParser | None':
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
# a url may hold a `%`, git accepts a key without a value, the file may start with a BOM,
# and a value that is not UTF-8 does not make the others unreadable
config = configparser.ConfigParser(strict=False, interpolation=None, allow_no_value=True)
try:
with open(git_config_path, encoding='utf-8-sig', errors='replace') as f:
# the parser would take a line that is indented more as more of the value before it
config.read_file(lines_of_git_config(f))
except (configparser.Error, OSError) as e:
if git_config_path not in warned_git_configs:
warned_git_configs.add(git_config_path)
# the message of a parsing error holds lines of the file, and a url in them can hold a token
reason = e.strerror if isinstance(e, OSError) else type(e).__name__
logging.warning(f"[ComfyUI-Manager] Cannot read '{git_config_path}': {reason}")
return None
return config
def git_url(fullpath):
"""
resolve version of unclassified custom node based on remote url in .git/config
@@ -43,12 +129,12 @@ def git_url(fullpath):
if not os.path.exists(git_config_path):
return None
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
config = configparser.ConfigParser(strict=False)
config.read(git_config_path)
config = read_git_config(git_config_path)
if config is None:
return None
for k, v in config.items():
if k.startswith('remote ') and 'url' in v:
if k.startswith('remote ') and v.get('url'):
if 'Comfy-Org/ComfyUI-Manager' in v['url']:
return "https://github.com/ltdrdata/ComfyUI-Manager"
return v['url']
+240 -118
View File
@@ -27,7 +27,9 @@ import toml
orig_print = print
from rich import print
import rich
from rich.console import Console
from rich.markup import escape
from packaging import version
import uuid
@@ -44,7 +46,13 @@ import manager_migration
from node_package import InstalledNodePackage
version_code = [3, 43]
def print(*objects, sep=" ", end="\n", file=None):
# rich's print with its highlighting only, so that a path, a URL or an error text is written as it is
console = rich.get_console() if file is None else Console(file=file)
console.print(*objects, sep=sep, end=end, markup=False, emoji=False, soft_wrap=True)
version_code = [3, 43, 2]
version_str = f"V{version_code[0]}.{version_code[1]}" + (f'.{version_code[2]}' if len(version_code) > 2 else '')
@@ -108,9 +116,8 @@ def get_current_comfyui_ver():
def get_script_env():
new_env = os.environ.copy()
git_exe = get_config().get('git_exe')
if git_exe is not None:
new_env['GIT_EXE_PATH'] = git_exe
# the scripts run the git that this process runs, which `git_exe` can name: GitPython reads this when it is imported
new_env['GIT_PYTHON_GIT_EXECUTABLE'] = git.Git.GIT_PYTHON_GIT_EXECUTABLE
if 'COMFYUI_PATH' not in new_env:
new_env['COMFYUI_PATH'] = comfy_path
@@ -121,6 +128,23 @@ def get_script_env():
return new_env
def setup_git_executable():
git_exe = get_config()['git_exe']
if git_exe == '':
return
if not manager_migration.has_system_user_api():
logging.warning("[ComfyUI-Manager] `git_exe` is not used, because this ComfyUI does not keep the configuration file in a protected directory.")
return
path = manager_util.find_git_executable(git_exe)
if path is None:
logging.error(f"[ComfyUI-Manager] `git_exe = {git_exe}` is not a working git executable. The default git is used.")
else:
git.refresh(path)
invalid_nodes = {}
@@ -773,7 +797,7 @@ class UnifiedManager:
channel_url = normalize_channel(channel)
if channel_url:
if mode not in ['remote', 'local', 'cache']:
print(f"[bold red]ERROR: Invalid mode is specified `--mode {mode}`[/bold red]", file=sys.stderr)
rich.print(f"[bold red]ERROR: Invalid mode is specified `--mode {escape(mode)}`[/bold red]", file=sys.stderr)
return {}
# validate channel - only the channel set by the user is allowed.
@@ -859,30 +883,32 @@ class UnifiedManager:
else:
if os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if manager_migration.has_system_user_api() else None)
lines = manager_util.robust_readlines(requirements_path)
for line in lines:
package_name = remap_pip_package(line.strip())
if package_name and not package_name.startswith('#') and package_name not in self.processed_install:
self.processed_install.add(package_name)
clean_package_name = package_name.split('#')[0].strip()
install_cmd = manager_util.make_pip_cmd(["install", clean_package_name])
if clean_package_name != "" and not clean_package_name.startswith('#'):
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
if res:
self.processed_install.add(package_name)
pip_fixer.fix_broken()
if os.path.exists(install_script_path) and install_script_path not in self.processed_install:
self.processed_install.add(install_script_path)
print("Install: install script")
install_cmd = [sys.executable, "install.py"]
return res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
res = res and try_install_script(url, repo_path, install_cmd, instant_execution=instant_execution)
if res:
self.processed_install.add(install_script_path)
return res
def reserve_cnr_switch(self, target, zip_url, from_path, to_path, no_deps, status=''):
script_path = os.path.join(manager_startup_script_path, "install-scripts.txt")
with open(script_path, "a") as file:
with open(script_path, "a", encoding="utf-8") as file:
obj = [target, "#LAZY-CNR-SWITCH-SCRIPT", zip_url, from_path, to_path, no_deps, get_default_custom_nodes_path(), sys.executable, status]
file.write(f"{obj}\n")
@@ -967,10 +993,11 @@ class UnifiedManager:
download_path = os.path.join(get_default_custom_nodes_path(), archive_name)
manager_downloader.basic_download_url(node_info.download_url, get_default_custom_nodes_path(), archive_name)
# 2. extract files into <node_id>
install_path = self.active_nodes[node_id][1]
extracted = manager_util.extract_package_as_zip(download_path, install_path)
os.remove(download_path)
try:
extracted = manager_util.switch_package_files(download_path, install_path)
finally:
os.remove(download_path)
if extracted is None:
if len(os.listdir(install_path)) == 0:
@@ -978,32 +1005,10 @@ class UnifiedManager:
return result.fail(f'Empty archive file: {node_id}@{version_spec}')
# 3. calculate garbage files (.tracking - extracted)
tracking_info_file = os.path.join(install_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(install_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. create .tracking file
tracking_info_file = os.path.join(install_path, '.tracking')
with open(tracking_info_file, "w", encoding='utf-8') as file:
file.write('\n'.join(list(extracted)))
# 6. post install
result.target = version_spec
def postinstall():
@@ -1337,6 +1342,9 @@ class UnifiedManager:
repo.git.clear_cache()
repo.close()
# an install script that ran in this folder was of the pack that was there before the clone
self.processed_install.discard(os.path.join(repo_path, 'install.py'))
def postinstall():
return self.execute_install_script(url, repo_path, instant_execution=instant_execution, no_deps=no_deps)
@@ -1736,14 +1744,6 @@ class DirtyTrackingConfig(dict):
recording `__setitem__` is what makes "only what changed" knowable.
`update()` is covered too, so a future caller written that way cannot
lose its change silently.
The wrapper is applied in `get_config()` AFTER `read_config()` has
returned, and that ordering is load-bearing:
`manager_migration.force_security_level_if_needed()` mutates the config
through a parameter alias from inside BOTH `read_config()` branches. If
that mutation were recorded, `security_level` would be dirty before the
user does anything, and every write would push the forced value over the
user's on-disk one - the exact clobber this tracking exists to remove.
"""
def __init__(self, *args, **kwargs):
@@ -1777,14 +1777,14 @@ def write_config():
the "stop -> edit -> start" advice in the install-denial messages stays
correct; what changes is that the edit is no longer destroyed in between.
"""
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
try:
loaded = config.read(manager_config_path)
except Exception as e:
# An unparsable config.ini must not make a settings change raise. Fall
# back to the pre-merge behaviour and rewrite the file from scratch.
print(f"[ComfyUI-Manager] Warning: '{manager_config_path}' could not be parsed ({e}); rewriting it from the current settings.")
config = configparser.ConfigParser(strict=False)
logging.warning(f"[ComfyUI-Manager] '{manager_config_path}' could not be parsed ({e}); rewriting it from the current settings.")
config = configparser.ConfigParser(strict=False, interpolation=None)
else:
# `read()` opens each filename inside its own `try/except OSError` and
# SKIPS the ones it could not open, so a file that exists but denies
@@ -1863,9 +1863,18 @@ def write_config():
cached.dirty_keys.difference_update(keys)
SETTING_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'),
}
def read_config():
try:
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(manager_config_path)
default_conf = config['default']
@@ -1878,7 +1887,8 @@ def read_config():
result = {
'http_channel_enabled': get_bool('http_channel_enabled', False),
'preview_method': default_conf.get('preview_method', manager_funcs.get_current_preview_method()).lower(),
'git_exe': default_conf.get('git_exe', ''),
# 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),
'use_uv': get_bool('use_uv', False),
'channel_url': default_conf.get('channel_url', DEFAULT_CHANNEL),
'default_cache_as_channel_url': get_bool('default_cache_as_channel_url', False),
@@ -1898,10 +1908,19 @@ def read_config():
'allow_pip_install': get_bool('allow_pip_install', False),
'allow_flagged_nodepack_install': get_bool('allow_flagged_nodepack_install', False),
}
manager_migration.force_security_level_if_needed(result)
for key, values in SETTING_VALUES.items():
default = values[0]
if result[key] not in values:
logging.warning(f"[ComfyUI-Manager] {key} = {result[key]!r} in config.ini is not valid; '{default}' is used.")
result[key] = default
return result
except Exception:
except Exception as e:
if os.path.exists(manager_config_path):
logging.warning(f"[ComfyUI-Manager] '{manager_config_path}' could not be read ({e!r}); the default settings are used.")
import importlib.util
# temporary disable `uv` on Windows by default (https://github.com/Comfy-Org/ComfyUI-Manager/issues/1969)
manager_util.use_uv = importlib.util.find_spec("uv") is not None and platform.system() != "Windows"
@@ -1930,7 +1949,6 @@ def read_config():
'allow_pip_install': False,
'allow_flagged_nodepack_install': False,
}
manager_migration.force_security_level_if_needed(result)
return result
@@ -1938,10 +1956,6 @@ def get_config():
global cached_config
if cached_config is None:
# Wrapped HERE, after read_config() has returned: the migration hook it
# calls internally mutates the config through a parameter alias, and
# that mutation must NOT count as a user change (see
# DirtyTrackingConfig).
cached_config = DirtyTrackingConfig(read_config())
if cached_config['http_channel_enabled']:
print("[ComfyUI-Manager] Warning: http channel enabled, make sure server in secure env")
@@ -2010,7 +2024,7 @@ def reserve_script(repo_path, install_cmds):
os.makedirs(manager_startup_script_path)
script_path = os.path.join(manager_startup_script_path, "install-scripts.txt")
with open(script_path, "a") as file:
with open(script_path, "a", encoding="utf-8") as file:
obj = [repo_path] + install_cmds
file.write(f"{obj}\n")
@@ -2120,7 +2134,8 @@ def __win_check_git_update(path, do_fetch=False, do_update=False):
def __win_check_git_pull(path):
command = [sys.executable, git_script_path, "--pull", path]
process = subprocess.Popen(command, env=get_script_env(), cwd=get_default_custom_nodes_path())
process.wait()
if process.wait() != 0:
raise ValueError(f"Failed to pull: {path}")
def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=False, no_deps=False):
@@ -2134,7 +2149,7 @@ def execute_install_script(url, repo_path, lazy_mode=False, instant_execution=Fa
else:
if os.path.exists(requirements_path) and not no_deps:
print("Install: pip packages")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if manager_migration.has_system_user_api() else None)
with open(requirements_path, "r") as requirements_file:
for line in requirements_file:
#handle comments
@@ -2301,16 +2316,19 @@ class GitProgress(RemoteProgress):
def is_valid_url(url):
# Check for HTTP/HTTPS URL format
try:
# Check for HTTP/HTTPS URL format
result = urlparse(url)
if all([result.scheme, result.netloc]):
return True
finally:
# Check for SSH git URL format
pattern = re.compile(r"^(.+@|ssh://).+:.+$")
if pattern.match(url):
return True
except ValueError:
# what cannot be parsed, as a host with a bracket that is not closed, is not such a url
pass
# Check for SSH git URL format
pattern = re.compile(r"^(.+@|ssh://).+:.+$")
if pattern.match(url):
return True
return False
@@ -2392,6 +2410,14 @@ async def gitclone_install(url, instant_execution=False, msg_prefix='', no_deps=
return result.fail(f"Install(git-clone)[1] error: {url} / {e}")
def undo_pull(repo, commit):
repo.git.reset('--hard', commit)
try:
repo.git.submodule('update', '--recursive')
except Exception:
pass
def git_pull(path):
# Check if the path is a git repository
if not os.path.exists(os.path.join(path, '.git')):
@@ -2413,6 +2439,7 @@ def git_pull(path):
current_branch = repo.active_branch
remote_name = current_branch.tracking_branch().remote_name
commit_hash = repo.head.commit.hexsha
try:
repo.git.pull('--ff-only')
@@ -2424,7 +2451,11 @@ def git_pull(path):
repo.git.reset('--hard', f'{remote_name}/{branch_name}')
logging.info(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
repo.git.submodule('update', '--init', '--recursive')
try:
repo.git.submodule('update', '--init', '--recursive')
except Exception:
undo_pull(repo, commit_hash)
raise
repo.close()
@@ -3274,6 +3305,30 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
installed_node_packs = []
failed = []
def run_postinstall(res):
try:
return res.postinstall()
except Exception:
traceback.print_exc()
return False
def attempt(step, *args):
try:
return step(*args)
except Exception as e:
logging.error(f"[ComfyUI-Manager] {e}")
return ManagedResult('fail').fail(str(e))
def finish_clone(res, name, path, commit_hash):
is_switched = repo_switch_commit(path, commit_hash)
is_installed = run_postinstall(res)
if is_switched is None:
failed.append(f"{name}@{commit_hash}")
elif not is_installed:
failed.append(name)
else:
cloned_repos.append(name)
await unified_manager.reload('cache')
await unified_manager.get_custom_nodes('default', 'cache')
@@ -3283,8 +3338,6 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
print("Restore snapshot.")
postinstalls = []
with open(snapshot_path, 'r', encoding="UTF-8") as snapshot_file:
if snapshot_path.endswith('.json'):
info = json.load(snapshot_file)
@@ -3319,11 +3372,16 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
skip_node_packs.append(k)
for x in todo_disable:
unified_manager.unified_disable(x, False)
disabled_repos.append(x)
if attempt(unified_manager.unified_disable, x, False).result:
disabled_repos.append(x)
else:
failed.append(x)
for x in todo_checkout:
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
try:
ps = unified_manager.cnr_switch_version(x[0], x[1], instant_execution=True, no_deps=True, return_postinstall=False)
except Exception as e:
ps = ManagedResult('switch-cnr').fail(str(e))
if ps.action == 'switch-cnr' and ps.result:
switched_node_packs.append(f"{x[0]}@{x[1]}")
elif ps.action == 'skip':
@@ -3338,18 +3396,17 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
if 'comfyui-manager' in k or k in checked_cnr:
continue
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
if ps.action == 'install-cnr' and ps.result:
installed_node_packs.append(f"{k}@{v}")
elif not ps.result:
try:
ps = await unified_manager.install_by_id(k, version_spec=v, instant_execution=True, return_postinstall=True)
except Exception as e:
ps = ManagedResult('install-cnr').fail(str(e))
if not ps.result:
failed.append(f"{k}@{v}")
logging.error(ps.msg)
if ps is not None and ps.result:
if hasattr(ps, 'postinstall'):
postinstalls.append(ps.postinstall)
else:
print("cm-cli: unexpected [0001]")
elif not run_postinstall(ps):
failed.append(f"{k}@{v}")
elif ps.action == 'install-cnr':
installed_node_packs.append(f"{k}@{v}")
# for nightly restore
_git_info = info.get('git_custom_nodes')
@@ -3361,6 +3418,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
if 'comfyui-manager' in k.lower():
continue
v.setdefault('hash', 'unknown')
# Snapshots saved at a detached HEAD used to keep the newline that follows the hash.
if isinstance(v.get('hash'), str):
v['hash'] = v['hash'].strip()
@@ -3386,7 +3445,8 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
todo_disable.append(k)
else:
commit_hash = git_info[normalized_url]['hash']
todo_checkout.append((v[1], commit_hash))
todo_checkout.append((k, v[1], commit_hash))
processed_urls.append(normalized_url)
for k, v in unified_manager.nightly_inactive_nodes.items():
if 'comfyui-manager' in k:
@@ -3402,35 +3462,52 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
processed_urls.append(normalized_url)
for x in todo_disable:
unified_manager.unified_disable(x, False)
disabled_repos.append(x)
if attempt(unified_manager.unified_disable, x, False).result:
disabled_repos.append(x)
else:
failed.append(x)
for x in todo_enable:
res = unified_manager.unified_enable(x[0], 'nightly')
res = attempt(unified_manager.unified_enable, x[0], 'nightly')
is_switched = False
if res and res.target:
is_switched = repo_switch_commit(res.target, x[1])
if is_switched:
if not res.result:
failed.append(x[0])
elif is_switched is None:
failed.append(f"{x[0]}@{x[1]}")
elif is_switched:
checkout_repos.append(f"{x[0]}@{x[1]}")
else:
enabled_repos.append(x[0])
for x in todo_checkout:
is_switched = repo_switch_commit(x[0], x[1])
for name, path, commit_hash in todo_checkout:
is_switched = repo_switch_commit(path, commit_hash)
if is_switched:
checkout_repos.append(f"{x[0]}@{x[1]}")
checkout_repos.append(f"{name}@{commit_hash}")
elif is_switched is None:
failed.append(f"{name}@{commit_hash}")
else:
skip_node_packs.append(name)
for x in git_info.keys():
if x in processed_urls:
continue
normalized_url = git_utils.normalize_url(x)
cnr = unified_manager.repo_cnr_map.get(normalized_url)
if cnr is not None:
pack_id = cnr['id']
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=False)
try:
res = await unified_manager.install_by_id(pack_id, 'nightly', instant_execution=True, no_deps=False, return_postinstall=True)
except Exception as e:
logging.error(f"[ComfyUI-Manager] {e}")
res = ManagedResult('fail').fail(str(e))
if res.action == 'install-git' and res.result:
cloned_repos.append(pack_id)
finish_clone(res, pack_id, unified_manager.active_nodes[pack_id][1], git_info[x]['hash'])
elif res.action == 'skip':
skip_node_packs.append(pack_id)
elif not res.result:
@@ -3448,6 +3525,9 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
processed_urls = []
for k2, v2 in unified_manager.unknown_active_nodes.items():
if 'comfyui-manager' in k2.lower():
continue
repo_url = resolve_giturl_from_path(v2[1])
if repo_url is None:
@@ -3459,7 +3539,7 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
todo_disable.append(k2)
else:
commit_hash = git_info[normalized_url]['hash']
todo_checkout.append((k2, commit_hash))
todo_checkout.append((k2, v2[1], commit_hash))
processed_urls.append(normalized_url)
for k2, v2 in unified_manager.unknown_inactive_nodes.items():
@@ -3476,28 +3556,36 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
processed_urls.append(normalized_url)
for x in todo_disable:
unified_manager.unified_disable(x, True)
disabled_repos.append(x)
if attempt(unified_manager.unified_disable, x, True).result:
disabled_repos.append(x)
else:
failed.append(x)
for x in todo_enable:
res = unified_manager.unified_enable(x[0], 'unknown')
res = attempt(unified_manager.unified_enable, x[0], 'unknown')
is_switched = False
if res and res.target:
is_switched = repo_switch_commit(res.target, x[1])
if is_switched:
if not res.result:
failed.append(x[0])
elif is_switched is None:
failed.append(f"{x[0]}@{x[1]}")
elif is_switched:
checkout_repos.append(f"{x[0]}@{x[1]}")
else:
enabled_repos.append(x[0])
for x in todo_checkout:
is_switched = repo_switch_commit(x[0], x[1])
for name, path, commit_hash in todo_checkout:
is_switched = repo_switch_commit(path, commit_hash)
if is_switched:
checkout_repos.append(f"{x[0]}@{x[1]}")
checkout_repos.append(f"{name}@{commit_hash}")
elif is_switched is None:
failed.append(f"{name}@{commit_hash}")
else:
skip_node_packs.append(x[0])
skip_node_packs.append(name)
for x in processed_urls:
if x in git_info:
@@ -3509,10 +3597,14 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
repo_name = repo_name[:-4]
to_path = os.path.join(get_default_custom_nodes_path(), repo_name)
unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=False)
cloned_repos.append(repo_name)
res = unified_manager.repo_install(repo_url, to_path, instant_execution=True, no_deps=False, return_postinstall=True)
if not res.result:
failed.append(repo_name)
continue
manager_util.restore_pip_snapshot(pips, git_helper_extras)
finish_clone(res, repo_name, to_path, git_info[repo_url]['hash'])
pips_not_installed = manager_util.restore_pip_snapshot(pips, git_helper_extras)
# print summary
for x in cloned_repos:
@@ -3529,11 +3621,15 @@ async def restore_snapshot(snapshot_path, git_helper_extras=None):
print(f"[ DISABLED ] {x}")
for x in skip_node_packs:
print(f"[ SKIPPED ] {x}")
for x in failed:
for x in dict.fromkeys(failed):
print(f"[ FAILED ] {x}")
# if is_failed:
# print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
return not failed and not pips_not_installed
def parse_semver(tag_name):
match = re.fullmatch(r'v(\d+)\.(\d+)\.(\d+)', tag_name)
return tuple(int(x) for x in match.groups()) if match else None
def get_comfyui_versions(repo=None):
@@ -3546,10 +3642,6 @@ def get_comfyui_versions(repo=None):
except:
logging.error("[ComfyUI-Manager] Failed to fetch ComfyUI")
def parse_semver(tag_name):
match = re.match(r'^v(\d+)\.(\d+)\.(\d+)$', tag_name)
return tuple(int(x) for x in match.groups()) if match else None
def normalize_describe(tag_name):
if not tag_name:
return None
@@ -3615,6 +3707,24 @@ def get_comfyui_versions(repo=None):
return versions, current_tag, latest_tag
def is_comfyui_downgrade(tag):
if tag == 'nightly':
return False
try:
described = git.Repo(comfy_path).git.describe('--tags')
except git.GitCommandError:
return True
release, _, commits_after_release = described.partition('-')
current = parse_semver(release)
target = parse_semver(tag)
if current is None or target is None:
return True
return target <= current if commits_after_release else target < current
def switch_comfyui(tag):
repo = git.Repo(comfy_path)
@@ -3638,23 +3748,35 @@ def resolve_giturl_from_path(fullpath):
if not os.path.exists(git_config_path):
return "unknown"
config = configparser.ConfigParser(strict=False)
config.read(git_config_path)
config = git_utils.read_git_config(git_config_path)
if config is None:
return None
for k, v in config.items():
if k.startswith('remote ') and 'url' in v:
if k.startswith('remote ') and v.get('url'):
return v['url'].replace("git@github.com:", "https://github.com/")
return None
def redo_submodule_update(repo, repo_path):
if os.path.exists(os.path.join(repo_path, '.gitmodules')):
repo.git.submodule('update', '--recursive')
def repo_switch_commit(repo_path, commit_hash):
if commit_hash == 'unknown':
return False
try:
repo = git.Repo(repo_path)
if repo.head.commit.hexsha == commit_hash:
return False
if repo.head.commit.hexsha != commit_hash:
repo.git.checkout(commit_hash)
repo.git.submodule('update', '--init', '--recursive')
return True
repo.git.checkout(commit_hash)
return True
except:
redo_submodule_update(repo, repo_path)
return False
except Exception as e:
logging.error(f"[ComfyUI-Manager] Failed to check out '{repo_path}' at {commit_hash}: {e}")
return None
+75 -50
View File
@@ -4,8 +4,6 @@ Handles migration from legacy paths to new __manager path structure.
"""
import os
import sys
import subprocess
import configparser
# Startup notices for notice board
@@ -74,20 +72,28 @@ def run_migration_checks(user_dir, manager_files_path):
warn_outdated_comfyui()
LEGACY_BACKUP_NAME = '.legacy-manager-backup'
def check_legacy_backup(manager_files_path):
"""Check for legacy backup and notify user to verify and remove it.
This runs on every startup to remind users about pending legacy backup.
"""
backup_dir = os.path.join(manager_files_path, '.legacy-manager-backup')
if not os.path.exists(backup_dir):
if not os.path.isdir(manager_files_path):
return
backup_dirs = [os.path.join(manager_files_path, name) for name in sorted(os.listdir(manager_files_path))
if name.startswith(LEGACY_BACKUP_NAME)]
if not backup_dirs:
return
# Terminal output
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: Legacy backup exists")
print(" - Your old Manager data was backed up to:")
print(f" {backup_dir}")
for backup_dir in backup_dirs:
print(f" {backup_dir}")
print(" - Please verify and remove it when no longer needed.")
print("-"*70 + "\n")
@@ -118,7 +124,7 @@ def check_suspicious_manager(user_dir):
if not os.path.exists(config_path):
return False
config = configparser.ConfigParser()
config = configparser.ConfigParser(interpolation=None)
config.read(config_path)
sec_level = config.get('default', 'security_level', fallback='normal').lower()
@@ -149,14 +155,14 @@ def warn_outdated_comfyui():
# Terminal output
print("\n" + "!"*70)
print("[ComfyUI-Manager] ERROR: ComfyUI version is outdated!")
print(" - Most operations are blocked for security.")
print(" - Every operation but the update of ComfyUI is blocked for security.")
print(" - ComfyUI update is still allowed.")
print(" - Please update ComfyUI to use Manager normally.")
print("!"*70 + "\n")
# Notice board output
add_startup_notice(
"[Security Alert] ComfyUI outdated. Installations blocked (update allowed).<BR>"
"[Security Alert] ComfyUI outdated. Everything but its update is blocked.<BR>"
"Update ComfyUI for normal operation.",
level='error'
)
@@ -171,7 +177,6 @@ def migrate_legacy_config(user_dir, manager_files_path):
Scenarios:
1. Legacy exists, New doesn't exist → Migrate config.ini
2. Legacy exists, New exists → First update after upgrade
- Run ComfyUI dependency installation
- Rename legacy to .backup
3. Legacy doesn't exist → No migration needed
@@ -211,6 +216,7 @@ def migrate_legacy_config(user_dir, manager_files_path):
print(f" - New: {new_config}")
print(" - Migrating config.ini only (other files are NOT migrated).")
print(" - Security level below 'normal' will be raised.")
print(" - Settings that permit installs or change the channel are not migrated.")
print("-"*70 + "\n")
_migrate_config_with_security_check(legacy_config, new_config)
@@ -229,30 +235,13 @@ def _handle_first_update_migration(user_dir, legacy_dir, manager_files_path):
- ComfyUI was updated (now has System User API)
- Manager already created __manager on first new run
- But legacy directory still exists
Actions:
1. Run ComfyUI dependency installation
2. Move legacy to __manager/.legacy-manager-backup
"""
# Terminal output
print("\n" + "-"*70)
print("[ComfyUI-Manager] NOTICE: First update after ComfyUI upgrade detected")
print(" - Both legacy and new directories exist.")
print(" - Running ComfyUI dependency installation...")
print("-"*70 + "\n")
# Run ComfyUI dependency installation
# Path: glob/manager_migration.py → glob → comfyui-manager → custom_nodes → ComfyUI
try:
comfyui_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
requirements_path = os.path.join(comfyui_path, 'requirements.txt')
if os.path.exists(requirements_path):
subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', requirements_path],
capture_output=True, check=False)
print("[ComfyUI-Manager] ComfyUI dependencies installation completed.")
except Exception as e:
print(f"[ComfyUI-Manager] WARNING: Failed to install ComfyUI dependencies: {e}")
# Move legacy to backup inside __manager
_move_legacy_to_backup(legacy_dir, manager_files_path)
@@ -265,11 +254,13 @@ def _move_legacy_to_backup(legacy_dir, manager_files_path):
"""
import shutil
backup_dir = os.path.join(manager_files_path, '.legacy-manager-backup')
backup_dir = os.path.join(manager_files_path, LEGACY_BACKUP_NAME)
count = 1
while os.path.exists(backup_dir):
count += 1
backup_dir = os.path.join(manager_files_path, f'{LEGACY_BACKUP_NAME}-{count}')
try:
if os.path.exists(backup_dir):
shutil.rmtree(backup_dir) # Remove old backup if exists
shutil.move(legacy_dir, backup_dir)
# Terminal output (full paths shown here only)
@@ -287,19 +278,34 @@ def _move_legacy_to_backup(legacy_dir, manager_files_path):
)
return backup_dir
except Exception as e:
print(f"[ComfyUI-Manager] WARNING: Failed to backup legacy directory: {e}")
copy_failed = isinstance(e, shutil.Error)
if copy_failed:
shutil.rmtree(backup_dir, ignore_errors=True)
print(f"[ComfyUI-Manager] WARNING: Failed to backup legacy directory: {str(e)!r}")
add_startup_notice(
f"[MIGRATION] Failed to backup legacy directory: {e}",
"[MIGRATION] Failed to backup legacy directory. See terminal for details.",
level='warning'
)
return None
# The settings that are carried over from config.ini of the legacy path. That file could be written
# through ComfyUI's /userdata, so a setting that permits an install or changes where Manager
# fetches from, and one that is not known here, is left behind.
MIGRATED_SETTINGS = {
'security_level', 'network_mode', 'db_mode', 'preview_method', 'share_option', 'component_policy',
'update_policy', 'use_uv', 'file_logging', 'always_lazy_install', 'default_cache_as_channel_url',
'model_download_by_agent', 'downgrade_blacklist', 'windows_selector_event_loop_policy',
}
VALUES_WRITTEN_BY_DEFAULT = {'false', '', 'https://raw.githubusercontent.com/ltdrdata/comfyui-manager/main'}
def _migrate_config_with_security_check(legacy_path, new_path):
"""Migrate legacy config, raising security level only if below default."""
config = configparser.ConfigParser()
legacy = configparser.ConfigParser(interpolation=None)
try:
config.read(legacy_path)
legacy.read(legacy_path)
except Exception as e:
print(f"[ComfyUI-Manager] WARNING: Failed to parse config.ini: {e}")
print(" - Creating fresh config with default settings.")
@@ -309,6 +315,27 @@ def _migrate_config_with_security_check(legacy_path, new_path):
)
return # Skip migration, let Manager create fresh config
config = configparser.ConfigParser(interpolation=None)
if 'default' in legacy:
settings = dict(legacy.items('default'))
config['default'] = {key: value for key, value in settings.items() if key in MIGRATED_SETTINGS}
not_migrated = sorted(key for key, value in settings.items()
if key not in MIGRATED_SETTINGS and value.lower() not in VALUES_WRITTEN_BY_DEFAULT)
if not_migrated:
print("\n" + "="*70)
print("[ComfyUI-Manager] WARNING: Settings not migrated")
print(f" - {not_migrated!r}")
print(" - The legacy config.ini was not protected, so these are back at their defaults.")
print(f" - Set them again in {new_path} if you need them.")
print("="*70 + "\n")
add_startup_notice(
f"[MIGRATION] Settings of the legacy config.ini that were not migrated: {len(not_migrated)}.<BR>"
"That file was not protected, so they are back at their defaults. See terminal for details.",
level='warning'
)
# Security level hierarchy: strong > normal > normal- > weak
# Default is 'normal', only raise if below default
if 'default' in config:
@@ -331,26 +358,24 @@ def _migrate_config_with_security_check(legacy_path, new_path):
"To prevent unauthorized remote access.",
level='warning'
)
elif current_level not in ('strong', 'normal'):
config['default']['security_level'] = 'normal'
print("\n" + "="*70)
print("[ComfyUI-Manager] WARNING: Security level adjusted")
print(f" - Previous: {current_level!r} is not a security level → New: 'normal'")
print("="*70 + "\n")
add_startup_notice(
"[MIGRATION] The security level of the legacy config.ini was not a security level.<BR>"
"It is back at 'normal'. See terminal for details.",
level='warning'
)
else:
print(f" - Security level: '{current_level}' (no change needed)")
print(f" - Security level: {current_level!r} (no change needed)")
# Ensure directory exists
os.makedirs(os.path.dirname(new_path), exist_ok=True)
with open(new_path, 'w') as f:
config.write(f)
def force_security_level_if_needed(config_dict):
"""Force security level to 'strong' if on old ComfyUI.
Args:
config_dict: Configuration dictionary to modify in-place
Returns:
bool: True if security level was forced
"""
if not has_system_user_api():
config_dict['security_level'] = 'strong'
return True
return False
+159 -87
View File
@@ -34,7 +34,7 @@ comfy_ui_hash = "-"
comfyui_tag = None
SECURITY_MESSAGE_MIDDLE_OR_BELOW = "ERROR: To use this action, security_level must be any value other than 'strong' (allowed: normal, normal-, weak). security_level is read once at ComfyUI startup, so changing it needs a restart, done with the server down: STOP ComfyUI, edit config.ini, then start it again. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. To download this model, set security_level to 'weak' - or to 'normal-' if ComfyUI is listening on a loopback address (--listen 127.0.0.1 or ::1). Both security_level and the listen address are read once at ComfyUI startup, so changing either needs a restart, done with the server down: stop ComfyUI, edit config.ini, then start it again."
SECURITY_MESSAGE_FLAG_GIT_URL = "ERROR: This action requires BOTH: (1) 'allow_git_url_install = true' in config.ini ([default] section), AND (2) ComfyUI launched with a loopback --listen (127.0.0.1 or ::1) - currently listening on {listen}. BOTH values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again. Both are independent of security_level. Reference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
@@ -125,6 +125,9 @@ model_dir_name_map = {
def is_allowed_security_level(level):
if not manager_migration.has_system_user_api():
return False
if level == 'block':
return False
elif level == 'high':
@@ -237,13 +240,24 @@ else:
)
ALLOWED_COMPONENT_POLICIES = ('workflow', 'higher', 'mine')
ALLOWED_UPDATE_POLICIES = ('stable-comfyui', 'nightly-comfyui')
ALLOWED_DB_MODES = ('cache', 'local', 'remote')
def set_component_policy(mode):
if mode not in ALLOWED_COMPONENT_POLICIES:
raise ValueError(f"Invalid component_policy {mode!r}; must be one of {ALLOWED_COMPONENT_POLICIES}")
core.get_config()['component_policy'] = mode
def set_update_policy(mode):
if mode not in ALLOWED_UPDATE_POLICIES:
raise ValueError(f"Invalid update_policy {mode!r}; must be one of {ALLOWED_UPDATE_POLICIES}")
core.get_config()['update_policy'] = mode
def set_db_mode(mode):
if mode not in ALLOWED_DB_MODES:
raise ValueError(f"Invalid db_mode {mode!r}; must be one of {ALLOWED_DB_MODES}")
core.get_config()['db_mode'] = mode
def print_comfyui_version():
@@ -303,19 +317,10 @@ def print_comfyui_version():
logging.info("### ComfyUI Revision: UNKNOWN (The currently installed ComfyUI is not a Git repository)")
core.setup_git_executable()
print_comfyui_version()
core.check_invalid_nodes()
def setup_environment():
git_exe = core.get_config()['git_exe']
if git_exe != '':
git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
setup_environment()
# Expand Server api
from aiohttp import web
@@ -339,54 +344,16 @@ def security_403_response(flag_token=None):
return web.json_response({"error": "security_level"}, status=403)
# CORS "simple request" Content-Type set per Fetch spec §3.2.3. Browsers send
# <form method=POST> submissions with one of these three MIME types and do NOT
# trigger a CORS preflight, so a malicious cross-origin page can silently POST
# into state-changing endpoints if we only gate on HTTP method. Blocking these
# three Content-Types on no-body mutation endpoints forces any non-same-origin
# POST to use a non-simple Content-Type (e.g. application/json), which triggers
# a preflight that this server rejects by not advertising an Access-Control-
# Allow-Origin response.
_SIMPLE_FORM_CONTENT_TYPES = frozenset({
'application/x-www-form-urlencoded',
'multipart/form-data',
'text/plain',
})
def _reject_simple_form_content_type(request):
"""Reject Content-Types that enable preflight-less <form method=POST> CSRF.
Applied ONLY to POST handlers that act before consuming a request body:
the ones that take no body (e.g., /snapshot/save,
/manager/queue/{reset,start,update_comfyui}, /manager/reboot) and
/manager/queue/update_all, which writes the autosave snapshot before it
reads its body. These are vulnerable to cross-origin <form method=POST>
attacks because the handler acts without parsing any body —
the attacker needs no ability to forge a valid payload, only to point a
hidden form at the URL.
Handlers that read a body via ``await request.json()`` before doing
anything else are NOT gated here: their cross-origin protection is
ComfyUI's origin middleware, not this gate.
DO NOT add this gate to handlers that read the body first — UX-breaking.
DO NOT remove this gate from the handlers above — this is the bypass vector.
aiohttp's ``request.content_type`` normalizes the header (lower-cases,
strips parameters), so ``multipart/form-data; boundary=----X`` is compared
as ``multipart/form-data``.
Returns:
web.Response(status=400) when the request has a simple-form
Content-Type that must be rejected. None when the request is allowed
to proceed (no Content-Type, application/json, or any non-simple
Content-Type).
def _reject_non_json_content_type(request):
"""A page of another origin can make a browser send a POST without a CORS
preflight: as a form, or with no Content-Type at all, with or without a body.
``request.json()`` parses a body whatever its Content-Type. The page cannot
send application/json without a preflight.
"""
if request.content_type in _SIMPLE_FORM_CONTENT_TYPES:
if request.content_type != 'application/json':
return web.Response(
status=400,
text='Invalid Content-Type for this endpoint. Use application/json or omit body.',
text='Invalid Content-Type for this endpoint. Use application/json.',
)
return None
@@ -821,6 +788,10 @@ async def fetch_customnode_mappings(request):
@routes.post("/customnode/fetch_updates")
async def fetch_updates(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
json_data = await request.json()
mode = json_data.get("mode", "default")
@@ -931,9 +902,7 @@ async def get_node_types_in_workflows(request):
@routes.post("/manager/queue/update_all")
async def update_all(request):
# Keep this gate first: a form POST is refused before this handler does
# anything. The autosave snapshot below is written before the body is read.
resp = _reject_simple_form_content_type(request)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
@@ -1204,6 +1173,10 @@ def get_safe_snapshot_path(target):
@routes.post("/snapshot/remove")
async def remove_snapshot(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
return security_403_response()
@@ -1227,8 +1200,12 @@ async def remove_snapshot(request):
@routes.post("/snapshot/restore")
async def restore_snapshot(request):
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('high'):
logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
return security_403_response()
try:
@@ -1266,7 +1243,7 @@ async def get_current_snapshot_api(request):
@routes.post("/snapshot/save")
async def save_snapshot(request):
resp = _reject_simple_form_content_type(request)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
@@ -1297,7 +1274,7 @@ def unzip_install(files):
os.remove(temp_filename)
except Exception as e:
logging.error(f"Install(unzip) error: {url} / {e}", file=sys.stderr)
logging.error(f"Install(unzip) error: {url} / {e}")
return False
logging.info("Installation was successful.")
@@ -1319,7 +1296,7 @@ def copy_install(files, js_path_name=None):
download_url(url, path, filename)
except Exception as e:
logging.error(f"Install(copy) error: {url} / {e}", file=sys.stderr)
logging.error(f"Install(copy) error: {url} / {e}")
return False
logging.info("Installation was successful.")
@@ -1340,7 +1317,7 @@ def copy_uninstall(files, js_path_name='.'):
elif os.path.exists(file_path + ".disabled"):
os.remove(file_path + ".disabled")
except Exception as e:
logging.error(f"Uninstall(copy) error: {url} / {e}", file=sys.stderr)
logging.error(f"Uninstall(copy) error: {url} / {e}")
return False
logging.info("Uninstallation was successful.")
@@ -1371,7 +1348,7 @@ def copy_set_active(files, is_disable, js_path_name='.'):
os.rename(current_name, new_name)
except Exception as e:
logging.error(f"{action_name}(copy) error: {url} / {e}", file=sys.stderr)
logging.error(f"{action_name}(copy) error: {url} / {e}")
return False
@@ -1408,6 +1385,10 @@ async def get_disabled_versions(request):
@routes.post("/customnode/import_fail_info")
async def import_fail_info(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
if 'cnr_id' in json_data:
@@ -1430,7 +1411,7 @@ async def reinstall_custom_node(request):
@routes.post("/manager/queue/reset")
async def reset_queue(request):
resp = _reject_simple_form_content_type(request)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
global task_queue
@@ -1459,6 +1440,10 @@ async def install_custom_node(request):
async def _queue_node_install(request, operation):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
@@ -1550,7 +1535,7 @@ task_worker_thread:threading.Thread = None
@routes.post("/manager/queue/start")
async def queue_start(request):
resp = _reject_simple_form_content_type(request)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
global nodepack_result
@@ -1571,6 +1556,10 @@ async def queue_start(request):
@routes.post("/manager/queue/fix")
async def fix_custom_node(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_GENERAL)
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
@@ -1593,20 +1582,22 @@ async def fix_custom_node(request):
@routes.post("/customnode/install/git_url")
async def install_custom_node_git_url(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_dedicated_install_allowed(core.get_config()['allow_git_url_install'], args.listen):
logging.error(SECURITY_MESSAGE_FLAG_GIT_URL.format(listen=args.listen))
return security_403_response(flag_token='allow_git_url_install')
# Read the body as JSON (not raw text): a cross-origin <form method=POST>
# cannot forge an application/json body without a CORS preflight, which this
# server does not answer — same body-handler convention as every other
# request.json() route (see _reject_simple_form_content_type docstring).
# A malformed body or a missing 'url' is a client error (400), not a 500:
# don't let JSONDecodeError/KeyError bubble up as a server fault.
# A malformed body, a missing 'url' or one that is not a string is a client
# error (400), not a 500: don't let it bubble up as a server fault.
try:
json_data = await request.json()
url = json_data['url']
except (KeyError, ValueError):
except (KeyError, TypeError, ValueError):
url = None
if not isinstance(url, str):
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'url' field")
res = await core.gitclone_install(url)
@@ -1623,17 +1614,20 @@ async def install_custom_node_git_url(request):
@routes.post("/customnode/install/pip")
async def install_custom_node_pip(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_dedicated_install_allowed(core.get_config()['allow_pip_install'], args.listen):
logging.error(SECURITY_MESSAGE_FLAG_PIP.format(listen=args.listen))
return security_403_response(flag_token='allow_pip_install')
# JSON body (not raw text) for the same preflight-forcing reason as
# /customnode/install/git_url above; malformed body or missing 'packages'
# is a 400, not a 500.
try:
json_data = await request.json()
packages = json_data['packages']
except (KeyError, ValueError):
except (KeyError, TypeError, ValueError):
packages = None
if not isinstance(packages, str):
return web.Response(status=400, text="Invalid request body: expected JSON object with a 'packages' field")
core.pip_install(packages.split(' '))
@@ -1642,6 +1636,10 @@ async def install_custom_node_pip(request):
@routes.post("/manager/queue/uninstall")
async def uninstall_custom_node(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
@@ -1665,6 +1663,10 @@ async def uninstall_custom_node(request):
@routes.post("/manager/queue/update")
async def update_custom_node(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
logging.error(SECURITY_MESSAGE_MIDDLE_OR_BELOW)
return web.Response(status=403, text="A security error has occurred. Please check the terminal logs")
@@ -1686,7 +1688,7 @@ async def update_custom_node(request):
@routes.post("/manager/queue/update_comfyui")
async def update_comfyui(request):
resp = _reject_simple_form_content_type(request)
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
is_stable = core.get_config()['update_policy'] != 'nightly-comfyui'
@@ -1700,27 +1702,39 @@ async def comfyui_versions(request):
res, current, latest = core.get_comfyui_versions()
return web.json_response({'versions': res, 'current': current}, status=200, content_type='application/json')
except Exception as e:
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
logging.error(f"ComfyUI update fail: {e}")
return web.Response(status=400)
@routes.post("/comfyui_manager/comfyui_switch_version")
async def comfyui_switch_version(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
json_data = await request.json()
if "ver" in json_data:
if core.is_comfyui_downgrade(json_data['ver']) and not is_allowed_security_level('high'):
logging.error(SECURITY_MESSAGE_NORMAL_MINUS)
return security_403_response()
core.switch_comfyui(json_data['ver'])
return web.Response(status=200)
except Exception as e:
logging.error(f"ComfyUI update fail: {e}", file=sys.stderr)
logging.error(f"ComfyUI update fail: {e}")
return web.Response(status=400)
@routes.post("/manager/queue/disable")
async def disable_node(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
node_id = json_data.get('id')
@@ -1756,6 +1770,10 @@ async def check_whitelist_for_model(item):
@routes.post("/manager/queue/install_model")
async def install_model(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
if not is_allowed_security_level('middle'):
@@ -1795,6 +1813,10 @@ async def get_preview_method(request):
@routes.post("/manager/preview_method")
async def set_preview_method_handler(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
if COMFYUI_HAS_PER_QUEUE_PREVIEW:
return web.Response(text="DISABLED", status=403)
@@ -1811,8 +1833,17 @@ async def get_db_mode(request):
@routes.post("/manager/db_mode")
async def set_db_mode_handler(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
set_db_mode(json_data['value'])
try:
set_db_mode(json_data['value'])
except (KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
except ValueError as e:
return web.Response(status=400, text=str(e))
core.write_config()
return web.Response(status=200)
@@ -1824,8 +1855,17 @@ async def get_component_policy(request):
@routes.post("/manager/policy/component")
async def set_component_policy_handler(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
set_component_policy(json_data['value'])
try:
set_component_policy(json_data['value'])
except (KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
except ValueError as e:
return web.Response(status=400, text=str(e))
core.write_config()
return web.Response(status=200)
@@ -1837,8 +1877,17 @@ async def get_update_policy(request):
@routes.post("/manager/policy/update")
async def set_update_policy_handler(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
set_update_policy(json_data['value'])
try:
set_update_policy(json_data['value'])
except (KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
except ValueError as e:
return web.Response(status=400, text=str(e))
core.write_config()
return web.Response(status=200)
@@ -1861,6 +1910,10 @@ async def get_channel_url_list(request):
@routes.post("/manager/channel_url_list")
async def set_channel_url_list(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
channels = core.get_channel_dict()
channel_url = channels.get(json_data['value'])
@@ -1956,7 +2009,7 @@ async def get_startup_alerts(request):
@routes.post("/manager/reboot")
def restart(self):
resp = _reject_simple_form_content_type(self)
resp = _reject_non_json_content_type(self)
if resp is not None:
return resp
if not is_allowed_security_level('middle'):
@@ -1986,6 +2039,10 @@ def restart(self):
@routes.post("/manager/component/save")
async def save_component(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
data = await request.json()
name = data['name']
@@ -2105,7 +2162,22 @@ async def default_cache_update():
logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
COMFYUI_UPDATE_HANDLERS = {update_comfyui, queue_start, reset_queue, queue_count, get_version, get_notice, get_startup_alerts}
@web.middleware
async def serve_only_comfyui_update(request, handler):
matched = request.match_info.handler
if matched.__module__ in ('manager_server', 'share_3rdparty') and matched not in COMFYUI_UPDATE_HANDLERS:
return security_403_response()
return await handler(request)
if manager_migration.has_system_user_api():
threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
else:
PromptServer.instance.app.middlewares.append(serve_only_comfyui_update)
if not os.path.exists(core.manager_config_path):
core.get_config()
+108
View File
@@ -10,8 +10,10 @@ import aiohttp
import json
import threading
import os
import shutil
from datetime import datetime
import subprocess
import tempfile
import sys
import re
import logging
@@ -458,6 +460,70 @@ def extract_package_as_zip(file_path, extract_path):
return None
def is_inside(directory, name):
directory = os.path.abspath(directory)
try:
return os.path.commonpath((directory, os.path.abspath(os.path.join(directory, name)))) == directory
except ValueError:
# on Windows, a path of another drive
return False
def switch_package_files(file_path, path):
import zipfile
try:
with zipfile.ZipFile(file_path, "r") as zip_ref:
extracted = zip_ref.namelist()
except zipfile.BadZipFile:
logging.error(f"File '{file_path}' is not a zip or is corrupted.")
return None
with open(os.path.join(path, '.tracking'), 'r', encoding='utf-8') as f:
# as the list is written: a name can start or end with a space
prev_files = {line.rstrip('\n') for line in f}
root = os.path.abspath(path)
garbage = prev_files - set(extracted)
garbage = [os.path.abspath(os.path.join(root, x)) for x in garbage if is_inside(root, x)]
for x in garbage:
try:
if os.path.isfile(x):
os.remove(x)
except OSError as e:
logging.warning(f"[ComfyUI-Manager] A file of the old version is left: {e}")
folders = set()
for x in garbage:
while len(x) > len(root):
folders.add(x)
x = os.path.dirname(x)
real_root = os.path.realpath(root)
def reached_without_a_link(x):
return os.path.normcase(os.path.realpath(x)) == os.path.normcase(real_root + x[len(root):])
for x in sorted(folders, key=len, reverse=True):
try:
if not os.path.isdir(x) or not reached_without_a_link(x):
continue
# the files of a `__pycache__` are caches of the modules that were there, as those of Python and of numba
cache = os.path.join(x, '__pycache__')
if os.listdir(x) == ['__pycache__'] and reached_without_a_link(cache):
for name in os.listdir(cache):
os.remove(os.path.join(cache, name))
os.rmdir(cache)
if not os.listdir(x):
os.rmdir(x)
except OSError as e:
logging.warning(f"[ComfyUI-Manager] A folder of the old version is left: {e}")
# after the files are removed: two names can be one file, as names that differ in case alone are on Windows
return extract_package_as_zip(file_path, path)
# The functions below import packaging where they use it: prestartup_script imports this module
# before its ensure_dependencies() has installed a missing dependency.
def normalize_pip_name(name):
@@ -950,6 +1016,9 @@ class PIPFixer:
logging.error(e)
# restore based on custom list
if self.manager_files_path is None:
return
pip_auto_fix_path = os.path.join(self.manager_files_path, "pip_auto_fix.list")
if os.path.exists(pip_auto_fix_path):
from packaging.specifiers import Specifier # imported on use, as in parse_pip_spec()
@@ -1109,3 +1178,42 @@ def restore_pip_snapshot(pips, options):
failed.append(x)
print(f"Installation failed for pip packages: {failed}")
return failed
def which_on_path(name):
"""
the file that the directories of PATH give for the name of a command
`shutil.which` looks in the current directory first on Windows, and takes a directory of PATH that is not absolute
"""
names = [name]
if os.name == 'nt':
extensions = [x for x in os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) if x]
if not name.lower().endswith(tuple(x.lower() for x in extensions)):
names = [name + x for x in extensions]
for directory in os.get_exec_path():
for x in names:
path = os.path.join(directory, x)
if os.path.isabs(directory) and os.path.isfile(path) and os.access(path, os.X_OK):
return path
return None
def find_git_executable(git_exe, timeout=10):
# a name without a directory is a command of PATH; GitPython would take it as a file of the current directory
path = shutil.which(git_exe) if os.path.dirname(git_exe) else which_on_path(git_exe)
if path is None:
return None
try:
# the answer goes to a file: with a pipe, Windows waits after the time is up for every program that holds the pipe
with tempfile.TemporaryFile() as answer:
res = subprocess.run([path, 'version'], stdout=answer, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL, timeout=timeout)
answer.seek(0)
is_git = res.returncode == 0 and answer.read(11) == b'git version'
except (OSError, subprocess.SubprocessError):
return None
return os.path.abspath(path) if is_git else None
+47 -50
View File
@@ -6,19 +6,38 @@ import json
import folder_paths
from server import PromptServer
from manager_server import _reject_non_json_content_type
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
@PromptServer.instance.routes.get("/manager/share_option")
async def share_option(request):
if "value" in request.rel_url.query:
core.get_config()['share_option'] = request.rel_url.query['value']
core.write_config()
else:
return web.Response(text=core.get_config()['share_option'], status=200)
return web.Response(text=core.get_config()['share_option'], status=200)
@PromptServer.instance.routes.post("/manager/share_option")
async def set_share_option(request):
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
try:
value = (await request.json())['value']
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
if value not in SHARE_OPTIONS:
return web.Response(status=400, text='Invalid request')
core.get_config()['share_option'] = value
core.write_config()
return web.Response(status=200)
def is_matrix_org(homeserver):
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
def get_matrix_auth():
if not os.path.exists(os.path.join(core.manager_files_path, "matrix_auth")):
return None
@@ -26,7 +45,7 @@ def get_matrix_auth():
with open(os.path.join(core.manager_files_path, "matrix_auth"), "r") as f:
matrix_auth = f.read()
homeserver, username, password = matrix_auth.strip().split("\n")
if not homeserver or not username or not password:
if not is_matrix_org(homeserver) or not username or not password:
return None
return {
"homeserver": homeserver,
@@ -37,52 +56,26 @@ def get_matrix_auth():
return None
def get_youml_settings():
if not os.path.exists(os.path.join(core.manager_files_path, ".youml")):
return None
try:
with open(os.path.join(core.manager_files_path, ".youml"), "r") as f:
youml_settings = f.read().strip()
return youml_settings if youml_settings else None
except:
return None
def set_youml_settings(settings):
with open(os.path.join(core.manager_files_path, ".youml"), "w") as f:
f.write(settings)
@PromptServer.instance.routes.get("/manager/get_matrix_auth")
async def api_get_matrix_auth(request):
# print("Getting stored Matrix credentials...")
matrix_auth = get_matrix_auth()
if not matrix_auth:
return web.Response(status=404)
return web.json_response(matrix_auth)
@PromptServer.instance.routes.get("/manager/youml/settings")
async def api_get_youml_settings(request):
youml_settings = get_youml_settings()
if not youml_settings:
return web.Response(status=404)
return web.json_response(json.loads(youml_settings))
@PromptServer.instance.routes.post("/manager/youml/settings")
async def api_set_youml_settings(request):
json_data = await request.json()
set_youml_settings(json.dumps(json_data))
return web.Response(status=200)
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
def set_matrix_auth(json_data):
homeserver = json_data['homeserver']
username = json_data['username']
password = json_data['password']
with open(os.path.join(core.manager_files_path, "matrix_auth"), "w") as f:
f.write("\n".join([homeserver, username, password]))
path = os.path.join(core.manager_files_path, "matrix_auth")
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
try:
os.chmod(path, 0o600)
except OSError:
pass # a file of another owner keeps its mode
f.truncate()
f.write("\n".join(["matrix.org", username, password]))
def has_provided_matrix_auth(matrix_auth):
@@ -92,11 +85,17 @@ def has_provided_matrix_auth(matrix_auth):
@PromptServer.instance.routes.post("/manager/share")
async def share_art(request):
# get json data
resp = _reject_non_json_content_type(request)
if resp is not None:
return resp
json_data = await request.json()
matrix_auth = json_data['matrix_auth']
set_matrix_auth(matrix_auth)
saved = get_matrix_auth()
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
matrix_auth['password'] = saved['password']
share_destinations = json_data['share_destinations']
credits = json_data['credits']
@@ -153,14 +152,10 @@ async def share_art(request):
try:
from nio import AsyncClient, LoginResponse, UploadResponse
homeserver = 'matrix.org'
if matrix_auth:
homeserver = matrix_auth.get('homeserver', 'matrix.org')
homeserver = homeserver.replace("http://", "https://")
if not homeserver.startswith("https://"):
homeserver = "https://" + homeserver
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
client = AsyncClient(homeserver, matrix_auth['username'])
client = AsyncClient("https://matrix.org", matrix_auth['username'])
# Login
login_resp = await client.login(matrix_auth['password'])
@@ -168,6 +163,8 @@ async def share_art(request):
await client.close()
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
set_matrix_auth(matrix_auth)
# Upload asset
with open(asset_filepath, 'rb') as f:
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
+3 -3
View File
@@ -48,7 +48,7 @@ async function enableNodePack(target) {
// A node pack from the registry is enabled while the install request is handled, and reported then.
api.addEventListener("cm-queue-status", listener);
try {
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
const response = await api.fetchApi(`/manager/queue/install`, {
method: 'POST',
@@ -70,7 +70,7 @@ async function enableNodePack(target) {
}
started = true;
await api.fetchApi('/manager/queue/start', { method: 'POST' });
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// A report that does not reach the page would leave the listener in place, and a later report
// for the same row, such as its Disable, would then restart ComfyUI unasked.
@@ -121,7 +121,7 @@ async function tryInstallCustomNode(event) {
let response;
try {
response = await api.fetchApi("/manager/reboot", { method: 'POST' });
response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
catch(exception) {
// The server restarts without answering.
+34 -21
View File
@@ -235,6 +235,7 @@ var switch_comfyui_button = null;
var update_all_button = null;
var restart_stop_button = null;
var update_policy_combo = null;
var update_policy_chosen = false;
let share_option = 'all';
const share_options = [
@@ -488,12 +489,12 @@ async function updateComfyUI() {
set_inprogress_mode();
const response = await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST' });
const response = await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
showTerminal();
is_updating = true;
await api.fetchApi('/manager/queue/start', { method: 'POST' });
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
function showVersionSelectorDialog(versions, current, onSelect) {
@@ -641,19 +642,18 @@ async function switchComfyUI() {
}
showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
if(selected_version == 'nightly') {
update_policy_combo.value = 'nightly-comfyui';
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: 'nightly-comfyui' }) });
}
else {
update_policy_combo.value = 'stable-comfyui';
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: 'stable-comfyui' }) });
}
let response = await api.fetchApi('/comfyui_manager/comfyui_switch_version', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ver: selected_version }), cache: "no-store" });
if (response.status == 200) {
const update_policy = selected_version == 'nightly' ? 'nightly-comfyui' : 'stable-comfyui';
update_policy_chosen = true;
update_policy_combo.value = update_policy;
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: update_policy }) });
infoToast(`ComfyUI version is switched to ${selected_version}`);
}
else if (response.status == 403) {
await handle403Response(response);
}
else {
customAlert('Failed to switch ComfyUI version.');
}
@@ -792,7 +792,7 @@ async function updateAll(update_comfyui) {
if(update_comfyui) {
update_all_button.innerText = "Updating ComfyUI...";
await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST' });
await api.fetchApi('/manager/queue/update_comfyui', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
const response = await api.fetchApi('/manager/queue/update_all', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: mode }) });
@@ -807,7 +807,7 @@ async function updateAll(update_comfyui) {
}
else if(response.status == 200) {
is_updating = true;
await api.fetchApi('/manager/queue/start', { method: 'POST' });
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
}
@@ -836,7 +836,7 @@ function restartOrStop() {
rebootAPI();
}
else {
api.fetchApi('/manager/queue/reset', { method: 'POST' });
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
}
@@ -996,11 +996,14 @@ class ManagerMenuDialog extends ComfyDialog {
this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'Local' }, []));
this.datasrc_combo.appendChild($el('option', { value: 'remote', text: 'Channel (remote)' }, []));
// a choice made before the stored value arrives is not to be replaced by it
let db_mode_chosen = false;
api.fetchApi('/manager/db_mode')
.then(response => response.text())
.then(data => { this.datasrc_combo.value = data; });
.then(data => { if(!db_mode_chosen) this.datasrc_combo.value = data; });
this.datasrc_combo.addEventListener('change', function (event) {
db_mode_chosen = true;
api.fetchApi('/manager/db_mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
});
@@ -1142,17 +1145,21 @@ class ManagerMenuDialog extends ComfyDialog {
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
}
let share_option_chosen = false;
api.fetchApi('/manager/share_option')
.then(response => response.text())
.then(data => {
share_option = to_share_option(data);
share_combo.value = share_option;
if(!share_option_chosen) {
share_option = to_share_option(data);
share_combo.value = share_option;
}
});
share_combo.addEventListener('change', function (event) {
share_option_chosen = true;
const value = event.target.value;
share_option = value;
api.fetchApi(`/manager/share_option?value=${value}`);
api.fetchApi('/manager/share_option', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
const shareButton = document.getElementById("shareButton");
if (value === 'none') {
shareButton.style.display = "none";
@@ -1169,14 +1176,18 @@ class ManagerMenuDialog extends ComfyDialog {
component_policy_combo.appendChild($el('option', { value: 'workflow', text: 'Use workflow version' }, []));
component_policy_combo.appendChild($el('option', { value: 'higher', text: 'Use higher version' }, []));
component_policy_combo.appendChild($el('option', { value: 'mine', text: 'Use my version' }, []));
let component_policy_chosen = false;
api.fetchApi('/manager/policy/component')
.then(response => response.text())
.then(data => {
component_policy_combo.value = data;
set_component_policy(data);
if(!component_policy_chosen) {
component_policy_combo.value = data;
set_component_policy(data);
}
});
component_policy_combo.addEventListener('change', function (event) {
component_policy_chosen = true;
api.fetchApi('/manager/policy/component', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
set_component_policy(event.target.value);
});
@@ -1192,10 +1203,12 @@ class ManagerMenuDialog extends ComfyDialog {
api.fetchApi('/manager/policy/update')
.then(response => response.text())
.then(data => {
update_policy_combo.value = data;
if(!update_policy_chosen)
update_policy_combo.value = data;
});
update_policy_combo.addEventListener('change', function (event) {
update_policy_chosen = true;
api.fetchApi('/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value: event.target.value }) });
});
+8 -7
View File
@@ -380,7 +380,7 @@ export class ShareDialogChooser extends ComfyDialog {
}
export class ShareDialog extends ComfyDialog {
static instance = null;
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
static matrix_auth = { homeserver: "matrix.org", username: "" };
constructor() {
super();
@@ -405,9 +405,9 @@ export class ShareDialog extends ComfyDialog {
const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
this.matrix_destination_checkbox.style.color = "var(--fg-color)";
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", value: "matrix.org", readOnly: true, title: "The share room is on matrix.org; only an account of matrix.org can share." }, []);
this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password" }, []);
this.credits_input = $el("input", {
type: "text",
@@ -621,15 +621,14 @@ export class ShareDialog extends ComfyDialog {
]);
// get the user's existing matrix auth
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
try {
api.fetchApi(`/manager/get_matrix_auth`)
.then(response => response.json())
.then(data => {
ShareDialog.matrix_auth = data;
this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
this.matrix_username_input.value = ShareDialog.matrix_auth.username;
this.matrix_password_input.value = ShareDialog.matrix_auth.password;
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
})
.catch(error => {
// console.log(error);
@@ -651,7 +650,8 @@ export class ShareDialog extends ComfyDialog {
// if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
if (destinations.includes("matrix")) {
let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
const usesSavedPassword = this.matrix_username_input.value == ShareDialog.matrix_auth.username;
let definedMatrixAuth = !!this.matrix_username_input.value && (!!this.matrix_password_input.value || usesSavedPassword);
if (!definedMatrixAuth) {
customAlert("Please set your Matrix account details.");
return;
@@ -721,6 +721,7 @@ export class ShareDialog extends ComfyDialog {
if (response_json.matrix.success) {
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
ShareDialog.matrix_auth = { homeserver: this.matrix_homeserver_input.value, username: this.matrix_username_input.value };
}
this.final_message.style.color = "green";
+6 -20
View File
@@ -176,25 +176,12 @@ export class YouMLShareDialog extends ComfyDialog {
this.selectedFile = null;
}
async loadToken() {
let key = ""
try {
const response = await api.fetchApi(`/manager/youml/settings`)
const settings = await response.json()
return settings.token
} catch (error) {
}
return key || "";
loadToken() {
return localStorage.getItem("youml_token") || "";
}
async saveToken(value) {
await api.fetchApi(`/manager/youml/settings`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
token: value
})
});
saveToken(value) {
localStorage.setItem("youml_token", value);
}
createLayout() {
@@ -342,7 +329,7 @@ export class YouMLShareDialog extends ComfyDialog {
async handleShareButtonClick() {
this.message.textContent = "";
await this.saveToken(this.apiTokenInput.value);
this.saveToken(this.apiTokenInput.value);
try {
this.shareButton.disabled = true;
this.shareButton.textContent = "Sharing...";
@@ -560,8 +547,7 @@ export class YouMLShareDialog extends ComfyDialog {
this.message.innerHTML = "";
this.message.textContent = "";
const token = await this.loadToken();
this.apiTokenInput.value = token;
this.apiTokenInput.value = this.loadToken();
this.uploadedImages = [];
this.element.style.display = "block";
+2 -1
View File
@@ -185,7 +185,7 @@ export async function rebootAPI() {
const isConfirmed = await customConfirm("Are you sure you'd like to reboot the server?");
if (isConfirmed) {
try {
const response = await api.fetchApi("/manager/reboot", { method: 'POST' });
const response = await api.fetchApi("/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
if (response.status == 403) {
await handle403Response(response);
return false;
@@ -691,6 +691,7 @@ export async function uninstallNodes(nodeList, options = {}) {
const res = await api.fetchApi(`/manager/queue/uninstall`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
+4
View File
@@ -65,6 +65,10 @@ function storeGroupNode(name, data, register=true) {
export async function load_components() {
let data = await api.fetchApi('/manager/component/loads', {method: "POST"});
if(data.status != 200) {
return;
}
let components = await data.json();
let start_time = Date.now();
+4 -3
View File
@@ -471,7 +471,7 @@ export class CustomNodesManager {
".cn-manager-stop": {
click: () => {
api.fetchApi('/manager/queue/reset', { method: 'POST' });
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
@@ -1423,7 +1423,7 @@ export class CustomNodesManager {
let needRestart = false;
let errorMsg = "";
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// Set install_context BEFORE per-item queue enqueue calls so that any
// server-side synchronous completion (e.g., sync enable of an inactive
@@ -1476,6 +1476,7 @@ export class CustomNodesManager {
const res = await api.fetchApi(`/manager/queue/${api_mode}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
@@ -1513,7 +1514,7 @@ export class CustomNodesManager {
}
}
else {
await api.fetchApi('/manager/queue/start', { method: 'POST' });
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
this.showStop();
showTerminal();
}
+4 -3
View File
@@ -171,7 +171,7 @@ export class ModelManager {
".cmm-manager-stop": {
click: () => {
api.fetchApi('/manager/queue/reset', { method: 'POST' });
api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
@@ -454,7 +454,7 @@ export class ModelManager {
let needRefresh = false;
let errorMsg = "";
await api.fetchApi('/manager/queue/reset', { method: 'POST' });
await api.fetchApi('/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
let target_items = [];
@@ -476,6 +476,7 @@ export class ModelManager {
const res = await api.fetchApi(`/manager/queue/install_model`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
@@ -515,7 +516,7 @@ export class ModelManager {
}
}
else {
await api.fetchApi('/manager/queue/start', { method: 'POST' });
await api.fetchApi('/manager/queue/start', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
// The queue can end before this request is answered.
if(this.install_context === context) {
this.showStop();
+1
View File
@@ -357,6 +357,7 @@ export class NodeUsageAnalyzer {
const res = await api.fetchApi(`/manager/queue/install_model`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
+1 -1
View File
@@ -77,7 +77,7 @@ async function remove_snapshot(target) {
async function save_current_snapshot() {
try {
const response = await api.fetchApi('/snapshot/save', { method: 'POST', cache: "no-store" });
const response = await api.fetchApi('/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
app.ui.dialog.close();
return true;
}
+33
View File
@@ -1973,6 +1973,39 @@
"url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth",
"size": "375.0MB"
},
{
"name": "ViT-H SAM model (safetensors)",
"type": "sam",
"base": "SAM",
"save_path": "sams",
"description": "Segment Anything SAM model (ViT-H) in the safetensors format, from Kornia",
"reference": "https://huggingface.co/kornia/sam",
"filename": "sam_vit_h_4b8939.safetensors",
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_h_4b8939.safetensors",
"size": "2.56GB"
},
{
"name": "ViT-L SAM model (safetensors)",
"type": "sam",
"base": "SAM",
"save_path": "sams",
"description": "Segment Anything SAM model (ViT-L) in the safetensors format, from Kornia",
"reference": "https://huggingface.co/kornia/sam",
"filename": "sam_vit_l_0b3195.safetensors",
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_l_0b3195.safetensors",
"size": "1.25GB"
},
{
"name": "ViT-B SAM model (safetensors)",
"type": "sam",
"base": "SAM",
"save_path": "sams",
"description": "Segment Anything SAM model (ViT-B) in the safetensors format, from Kornia",
"reference": "https://huggingface.co/kornia/sam",
"filename": "sam_vit_b_01ec64.safetensors",
"url": "https://huggingface.co/kornia/sam/resolve/main/sam_vit_b_01ec64.safetensors",
"size": "375.0MB"
},
{
"name": "sam2.1_hiera_tiny.pt",
+11
View File
@@ -1,5 +1,16 @@
{
"custom_nodes": [
{
"author": "ruiqutech",
"title": "RuiquNodes for ComfyUI [SECURITY ISSUE]",
"id": "RuiquNodes",
"reference": "https://github.com/ruiqutech/ComfyUI-RuiquNodes",
"files": [
"https://github.com/ruiqutech/ComfyUI-RuiquNodes"
],
"install_type": "git-clone",
"description": "Nodes of EvaluateMultiple1, EvaluateMultiple3...\nSupport the execution of any fragment of Python code, generating multiple outputs from multiple inputs. [w/This nodepack has a remote code execution vulnerability. Its Evaluate nodes run any Python code the workflow supplies, with no restriction, so a workflow you queue, or a request sent to a ComfyUI server reachable from the network, can run any program on the host.]"
},
{
"author": "rohit267",
"title": "Champdev Custom Nodes [SECURITY ISSUE]",
-31
View File
@@ -73387,37 +73387,6 @@
"title_aux": "RUI-Nodes"
}
],
"https://github.com/ruiqutech/ComfyUI-RuiquNodes": [
[
"EvaluateListMultiple1",
"EvaluateListMultiple3",
"EvaluateListMultiple6",
"EvaluateListMultiple9",
"EvaluateMultiple1",
"EvaluateMultiple3",
"EvaluateMultiple6",
"EvaluateMultiple9",
"ImageDilate",
"ImageErode",
"ListPath",
"MaskDilate",
"MaskErode",
"PreviewMask",
"RangeSplit",
"SaveMask",
"StringAsAny",
"StringConcat1",
"StringConcat3",
"StringConcat6",
"StringConcat9",
"StringPathStem",
"TermsToList",
"VAEDecodeSave"
],
{
"title_aux": "RuiquNodes for ComfyUI"
}
],
"https://github.com/ruminar/ComfyUI-CheckpointHandpickerSuite": [
[
"CheckpointListSelector",
+34 -12
View File
@@ -405,9 +405,14 @@ paths:
requestBody:
required: true
content:
text/plain:
application/json:
schema:
type: string
type: object
required: [url]
properties:
url:
type: string
description: Git repository URL
responses:
'200':
description: Installation successful or already installed
@@ -425,9 +430,14 @@ paths:
requestBody:
required: true
content:
text/plain:
application/json:
schema:
type: string
type: object
required: [packages]
properties:
packages:
type: string
description: Space-separated pip packages
responses:
'200':
description: Installation successful
@@ -483,10 +493,12 @@ paths:
/manager/queue/reset:
post:
summary: Reset queue
description: Resets the operation queue
description: Resets the operation queue. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Queue reset successfully
'400':
description: Content-Type is not application/json
/manager/queue/status:
get:
@@ -523,12 +535,14 @@ paths:
/manager/queue/start:
post:
summary: Start queue processing
description: Starts processing the operation queue
description: Starts processing the operation queue. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Processing started
'201':
description: Processing already in progress
'400':
description: Content-Type is not application/json
/manager/queue/fix:
post:
@@ -619,10 +633,12 @@ paths:
/manager/queue/update_comfyui:
post:
summary: Update ComfyUI
description: Queues an update operation for ComfyUI itself
description: Queues an update operation for ComfyUI itself. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Update queued successfully
'400':
description: Content-Type is not application/json
/manager/queue/install_model:
post:
@@ -729,12 +745,12 @@ paths:
/snapshot/save:
post:
summary: Save snapshot
description: Saves the current system state as a new snapshot
description: Saves the current system state as a new snapshot. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Snapshot saved successfully
'400':
description: Error saving snapshot
description: Content-Type is not application/json, or error saving snapshot
# ComfyUI Management Endpoints
/comfyui_manager/comfyui_versions:
@@ -761,9 +777,11 @@ paths:
/comfyui_manager/comfyui_switch_version:
post:
summary: Switch ComfyUI version
description: Switches to a specified ComfyUI version
description: Switches to a specified ComfyUI version. Only a switch to an older version is held to the security level.
security:
- securityLevel: []
requestBody:
required: false
required: true
content:
application/json:
schema:
@@ -777,16 +795,20 @@ paths:
description: Version switch successful
'400':
description: Error switching version
'403':
description: Security policy violation
/manager/reboot:
post:
summary: Reboot ComfyUI
description: Restarts the ComfyUI server
description: Restarts the ComfyUI server. The request has no body and needs the Content-Type `application/json`.
security:
- securityLevel: []
responses:
'200':
description: Reboot initiated
'400':
description: Content-Type is not application/json
'403':
description: Security policy violation
+52 -47
View File
@@ -108,7 +108,7 @@ def read_config():
global default_conf
try:
import configparser
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(manager_config_path)
default_conf = config['default']
except Exception:
@@ -123,15 +123,25 @@ def check_file_logging():
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
enable_file_logging = False
def set_git_executable():
# GitPython reads this when it is imported, so that a git that is not on PATH can be named
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
if git_exe != '' and _has_system_user_api:
git_exe = manager_util.find_git_executable(git_exe)
if git_exe is not None:
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = git_exe
read_config()
set_git_executable()
read_uv_mode()
security_check.security_check()
check_file_logging()
cm_global.pip_overrides = {}
if os.path.exists(manager_pip_overrides_path):
if _has_system_user_api and os.path.exists(manager_pip_overrides_path):
with open(manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
@@ -370,16 +380,18 @@ try:
def sync_write(self, message, file_only=False):
with log_lock:
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(message)
else:
log_file.write(f"[{timestamp}] {message}")
# after close_log() the output goes to the console only
if not log_file.closed:
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(message)
else:
log_file.write(f"[{timestamp}] {message}")
try:
log_file.flush()
except Exception:
pass
try:
log_file.flush()
except Exception:
pass
self.last_char = message if message == '' else message[-1]
@@ -417,12 +429,15 @@ try:
def close_log(self):
sys.stderr = original_stderr
sys.stdout = original_stdout
log_file.close()
with log_lock:
log_file.close()
def close_log():
sys.stderr = original_stderr
sys.stdout = original_stdout
log_file.close()
# a write that has found the file open finishes first
with log_lock:
log_file.close()
if enable_file_logging:
@@ -574,7 +589,7 @@ check_bypass_ssl()
processed_install = set()
# Use manager_files_path for consistency (fixes path inconsistency bug)
script_list_path = os.path.join(manager_files_path, "startup-scripts", "install-scripts.txt")
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path if _has_system_user_api else None)
def is_installed(name):
@@ -603,7 +618,10 @@ def is_installed(name):
return True # prevent downgrade
if os.path.exists(restore_snapshot_path):
if not _has_system_user_api:
if os.path.exists(restore_snapshot_path):
print("[ComfyUI-Manager] Snapshot restore blocked on old ComfyUI version.")
elif os.path.exists(restore_snapshot_path):
try:
cloned_repos = []
@@ -630,6 +648,8 @@ if os.path.exists(restore_snapshot_path):
print("[ComfyUI-Manager] Restore snapshot.")
new_env = os.environ.copy()
if 'COMFYUI_PATH' not in new_env:
new_env["COMFYUI_PATH"] = os.path.dirname(folder_paths.__file__)
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
@@ -639,7 +659,8 @@ if os.path.exists(restore_snapshot_path):
new_env['_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED'] = str(
allow_flagged or manager_util.is_loopback_listener(args.listen)
).lower()
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path]
cmd_str = [sys.executable, cm_cli_path, 'restore-snapshot', restore_snapshot_path,
'--user-directory', folder_paths.get_user_directory(), '--restore-to', custom_nodes_base_path]
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
if exit_code != 0:
@@ -705,9 +726,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
download_path = os.path.join(custom_nodes_path, archive_name)
manager_downloader.download_url(zip_url, custom_nodes_path, archive_name)
# 2. extract files into <node_id>@<cur_ver>
extracted = manager_util.extract_package_as_zip(download_path, from_path)
os.remove(download_path)
try:
extracted = manager_util.switch_package_files(download_path, from_path)
finally:
os.remove(download_path)
if extracted is None:
if len(os.listdir(from_path)) == 0:
@@ -716,32 +738,10 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
print(f'Empty archive file: {target}')
return False
if from_path != to_path:
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 3. calculate garbage files (.tracking - extracted)
tracking_info_file = os.path.join(from_path, '.tracking')
prev_files = set()
with open(tracking_info_file, 'r') as f:
for line in f:
prev_files.add(line.strip())
garbage = prev_files.difference(extracted)
garbage = [os.path.join(custom_nodes_path, x) for x in garbage]
# 4-1. remove garbage files
for x in garbage:
if os.path.isfile(x):
os.remove(x)
# 4-2. remove garbage dir if empty
for x in garbage:
if os.path.isdir(x):
if not os.listdir(x):
os.rmdir(x)
# 5. rename dir name <node_id>@<prev_ver> ==> <node_id>@<cur_ver>
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 6. create .tracking file
tracking_info_file = os.path.join(to_path, '.tracking')
with open(tracking_info_file, "w", encoding='utf-8') as file:
file.write('\n'.join(list(extracted)))
@@ -804,8 +804,9 @@ def execute_startup_script():
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
status = script[8] if len(script) > 8 else ''
if execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6], status):
execute_lazy_install_script(script[3], script[7])
to_path = script[4]
if execute_lazy_cnr_switch(script[0], script[2], script[3], to_path, script[5], script[6], status):
execute_lazy_install_script(to_path, script[7])
elif script[1] == "#LAZY-DELETE-NODEPACK":
execute_lazy_delete(script[2])
@@ -851,6 +852,10 @@ if not _has_system_user_api:
elif os.path.exists(script_list_path):
execute_startup_script()
if _has_system_user_api and os.path.exists(os.path.join(folder_paths.get_user_directory(), 'default', 'ComfyUI-Manager', 'config.ini')):
print("[ComfyUI-Manager] The legacy config.ini is still there: installing the requirements of ComfyUI.")
execute_lazy_install_script(comfy_path, sys.executable)
pip_fixer.fix_broken()
@@ -880,7 +885,7 @@ if script_executed:
def check_windows_event_loop_policy():
try:
import configparser
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(manager_config_path)
default_conf = config['default']
+1 -1
View File
@@ -1,7 +1,7 @@
[project]
name = "comfyui-manager"
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
version = "3.43"
version = "3.43.2"
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"]
+2 -3
View File
@@ -9,8 +9,7 @@ a constructed ``PromptServer``). pytest 8 collects any ancestor
directory that carries an ``__init__.py`` as a ``Package`` node and
IMPORTS that ``__init__.py`` during test setup (observed module name:
``__init__``). Outside a live ComfyUI process that import can never
succeed, so EVERY test under tests/ errors at setup — including the
pre-existing tests/test_csrf_content_type_helper.py — whenever pytest's
succeed, so EVERY test under tests/ errors at setup whenever pytest's
rootdir ends up at or above the repo root (e.g. running inside a git
worktree nested under the parent checkout).
@@ -21,7 +20,7 @@ executing the plugin entrypoint. Conftest files load before the setup
phase, so the stub is always in place in time. This does NOT touch
production code and does NOT alter what the tests import themselves
(they use AST-extraction / subprocess isolation per the
tests/test_csrf_content_type_helper.py precedent — ``glob/`` is never
tests/test_json_body_content_type.py precedent — ``glob/`` is never
added to the runner's sys.path).
"""
import sys
+2 -2
View File
@@ -225,7 +225,7 @@ def install(server, node, version, operation='install'):
async with session.post(server.base + '/manager/queue/' + operation, json=params) as response:
if response.status != 200:
return {'http': response.status, 'message': await response.text()}
async with session.post(server.base + '/manager/queue/start') as response:
async with session.post(server.base + '/manager/queue/start', headers={'Content-Type': 'application/json'}) as response:
response.raise_for_status()
while True:
event = await ws.receive_json(timeout=30)
@@ -359,7 +359,7 @@ def test_scheduled_snapshot_inherits_parent_policy(tmp_path, registry, existing,
installed = tmp_path / 'custom_nodes/fixture-snapshot'
marker = installed / 'installed.txt'
reservation = tmp_path / 'user/__manager/startup-scripts/restore-snapshot.json'
with running_server(tmp_path, '127.0.0.1', False, registry) as server:
with running_server(tmp_path, '127.0.0.1', False, registry, security='normal-') as server:
if existing:
assert install(server, 'fixture-snapshot', '1.0.0')['message'] == 'success'
assert marker.read_text() == '1.0.0'
+238
View File
@@ -0,0 +1,238 @@
import ast
import asyncio
import json
import logging
import os
import re
import shutil
import subprocess
import sys
from types import SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
LEVELS = ["strong", "normal", "normal-", "weak"]
SERVER = {"is_allowed_security_level", "security_403_response", "_reject_non_json_content_type", "comfyui_switch_version"}
CORE = {"parse_semver", "is_comfyui_downgrade"}
class GitCommandError(Exception):
pass
def functions(name, names):
source = (GLOB_DIR / name).read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names
or isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("SECURITY_MESSAGE_")]
assert names <= {getattr(node, "name", None) for node in nodes}
return compile(ast.Module(body=nodes, type_ignores=[]), name, "exec")
def load(security_level, loopback, described="v0.3.60"):
def describe(*args):
if described is None:
raise GitCommandError("fatal: No names found, cannot describe anything.")
return described
git = SimpleNamespace(Repo=lambda path: SimpleNamespace(git=SimpleNamespace(describe=describe)),
GitCommandError=GitCommandError)
core = {"re": re, "git": git, "comfy_path": "comfyui"}
exec(functions("manager_core.py", CORE), core)
switched = []
server = {
"routes": web.RouteTableDef(), "web": web, "logging": logging, "sys": sys,
"is_local_mode": loopback,
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level},
is_comfyui_downgrade=core["is_comfyui_downgrade"], switch_comfyui=switched.append),
"manager_migration": SimpleNamespace(has_system_user_api=lambda: True),
}
exec(functions("manager_server.py", SERVER), server)
return server["comfyui_switch_version"], switched
def call(handler, body):
async def read_json():
return body
try:
response = asyncio.run(handler(SimpleNamespace(json=read_json, content_type="application/json")))
except Exception:
return 500, None
return response.status, json.loads(response.text) if response.text else None
REFUSED = (403, {"error": "security_level"})
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_an_older_release_needs_normal_minus_on_loopback_and_weak_otherwise(security_level, loopback):
comfyui_switch_version, switched = load(security_level, loopback)
answer = call(comfyui_switch_version, {"ver": "v0.3.59"})
if security_level == "weak" or loopback and security_level == "normal-":
assert answer == (200, None)
assert switched == ["v0.3.59"]
else:
assert answer == REFUSED
assert switched == []
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
@pytest.mark.parametrize("version", ["nightly", "v0.3.60", "v0.3.61", "v0.4.0", "v1.0.0"],
ids=["nightly", "the same release", "a newer patch", "a newer minor", "a newer major"])
def test_an_update_is_not_held_to_a_level(version, security_level, loopback):
comfyui_switch_version, switched = load(security_level, loopback)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described, version, older", [
("v0.3.60-12-gabc1234", "v0.3.60", True), ("v0.3.60-12-gabc1234", "v0.3.61", False),
("v0.3.60-12-gabc1234", "v0.3.59", True), ("v0.3.60-1-gabc1234", "v0.3.60", True),
("v0.45.0-32-g0123abc", "v0.45.0", True), ("v0.45.0-32-g0123abc", "v0.45.4", False),
("v0.9.0", "v0.10.0", False), ("v0.10.0", "v0.9.0", True), ("v0.10.0", "v0.9.99", True),
("v1.0.0", "v0.99.99", True), ("v0.3.60", "v0.3.060", False), ("v0.3.60", "v0.2.61", True),
], ids=["commits after a release, that release", "commits after a release, a newer one", "commits after a release, an older one",
"one commit after a release, that release", "nightly, the first release of its minor", "nightly, a later patch release",
"a two-digit minor is newer", "a one-digit minor is older", "a higher patch of a lower minor",
"a lower major", "leading zeros", "a higher patch of an older minor"])
def test_releases_are_compared_by_their_numbers(described, version, older):
comfyui_switch_version, switched = load("strong", True, described)
answer = call(comfyui_switch_version, {"ver": version})
assert (answer, switched) == ((REFUSED, []) if older else ((200, None), [version]))
@pytest.mark.parametrize("version", [
"master", "HEAD~100", "abc1234", "0.3.61", "v0.3", "v0.3.61.1", "v0.3.61-rc1", "V0.3.61", " v0.3.61", "v0.3.61 ",
"refs/tags/v0.3.61", "latest", "Nightly", "v0.3.61\n", "v0.3.61\nv0.3.59", "\nv0.3.61", "",
], ids=["a branch", "an ancestor", "a commit", "no v", "two numbers", "four numbers", "a suffix", "upper case",
"a leading space", "a trailing space", "a full ref", "another name", "nightly in another case", "a trailing newline",
"two lines", "a leading newline", "empty"])
def test_what_is_not_a_release_tag_is_held_like_an_older_release(version):
comfyui_switch_version, switched = load("normal", True)
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
assert switched == []
comfyui_switch_version, switched = load("normal-", True)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described", [None, "", "latest", "latest-3-gabc1234", "0.3.60", "v0.3"],
ids=["no tag", "nothing", "another tag", "commits after another tag", "no v", "two numbers"])
@pytest.mark.parametrize("version", ["v0.3.61", "v9.9.9"])
def test_without_a_release_to_compare_with_every_release_is_held(described, version):
comfyui_switch_version, switched = load("normal", True, described)
assert call(comfyui_switch_version, {"ver": version}) == REFUSED
assert switched == []
comfyui_switch_version, switched = load("weak", False, described)
assert call(comfyui_switch_version, {"ver": version}) == (200, None)
assert switched == [version]
@pytest.mark.parametrize("described", [None, "latest"], ids=["no tag", "another tag"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_nightly_needs_no_release_to_compare_with(security_level, described):
comfyui_switch_version, switched = load(security_level, False, described)
assert call(comfyui_switch_version, {"ver": "nightly"}) == (200, None)
assert switched == ["nightly"]
@pytest.mark.parametrize("version", [None, 1, 0.3, ["v0.3.61"], {"v": "0.3.61"}, True],
ids=["null", "an integer", "a number", "a list", "an object", "a boolean"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_a_version_that_is_not_text_switches_nothing(security_level, version):
comfyui_switch_version, switched = load(security_level, True)
status, _ = call(comfyui_switch_version, {"ver": version})
assert status == 400
assert switched == []
@pytest.mark.parametrize("body", [{}, {"version": "v0.3.59"}], ids=["no fields", "another field"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_a_request_without_a_version_does_nothing(security_level, body):
comfyui_switch_version, switched = load(security_level, False)
assert call(comfyui_switch_version, body) == (200, None)
assert switched == []
@pytest.mark.parametrize("security_level", ["", "STRONG", "middle", "high"])
def test_a_security_level_that_is_not_one_of_the_four_allows_no_older_release(security_level):
comfyui_switch_version, switched = load(security_level, True)
assert call(comfyui_switch_version, {"ver": "v0.3.59"}) == REFUSED
assert call(comfyui_switch_version, {"ver": "v0.3.61"}) == (200, None)
assert switched == ["v0.3.61"]
@pytest.fixture
def repository(tmp_path, monkeypatch):
if shutil.which("git") is None:
pytest.skip("git is not installed")
# git takes its repository from these when they are set, as they are under a git hook
for name in [name for name in os.environ if name.startswith("GIT_")]:
monkeypatch.delenv(name)
def run(*args):
subprocess.run(["git", "-C", str(tmp_path), "-c", "user.name=test", "-c", "user.email=test@example.invalid",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True)
run("init", "-q")
for release in ("v0.3.59", "v0.3.60"):
run("commit", "-q", "--allow-empty", "-m", release)
run("tag", release)
return tmp_path, run
def is_downgrade(path, tag):
core = {"re": re, "git": pytest.importorskip("git"), "comfy_path": str(path)}
exec(functions("manager_core.py", CORE), core)
return core["is_comfyui_downgrade"](tag)
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", False), ("v0.3.61", False), ("nightly", False),
("master", True)])
def test_in_a_repository_at_a_release_only_an_older_one_goes_back(repository, tag, older):
path, _ = repository
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.59", True), ("v0.3.60", True), ("v0.3.61", False), ("nightly", False)])
def test_in_a_repository_with_a_commit_after_the_release_that_release_goes_back(repository, tag, older):
path, run = repository
run("commit", "-q", "--allow-empty", "-m", "after the release")
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.59", False), ("v0.3.60", False), ("v0.3.58", True)])
def test_in_a_repository_checked_out_at_an_earlier_release_the_later_one_does_not_go_back(repository, tag, older):
path, run = repository
run("checkout", "-q", "v0.3.59")
assert is_downgrade(path, tag) is older
@pytest.mark.parametrize("tag, older", [("v0.3.60", True), ("nightly", False)])
def test_in_a_repository_without_a_release_tag_every_release_goes_back(repository, tag, older):
path, run = repository
run("tag", "-d", "v0.3.59", "v0.3.60")
assert is_downgrade(path, tag) is older
+41
View File
@@ -0,0 +1,41 @@
"""`comfyui_versions` answers 400 when the versions of ComfyUI cannot be read.
Each case runs the real handler of `glob/manager_server.py`; `core` is replaced.
"""
import ast
import asyncio
import logging
import sys
from types import SimpleNamespace
from aiohttp import web
from manager_test_utils import GLOB_DIR
def fail():
raise RuntimeError("not a git repository")
def answer(get_comfyui_versions):
"""The status and text `comfyui_versions` answers."""
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
handler = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "comfyui_versions"]
assert len(handler) == 1
namespace = {"web": web, "logging": logging, "sys": sys,
"core": SimpleNamespace(get_comfyui_versions=get_comfyui_versions),
"routes": SimpleNamespace(get=lambda path: lambda handler: handler)}
exec(compile(ast.Module(body=handler, type_ignores=[]), "<comfyui_versions>", "exec"), namespace)
response = asyncio.run(namespace["comfyui_versions"](None))
return response.status, response.text
def test_version_list_that_cannot_be_read_is_answered_with_400(caplog):
assert answer(fail) == (400, None)
assert "ComfyUI update fail: not a git repository" in caplog.text
def test_version_list_is_answered_with_the_versions():
assert answer(lambda: (["nightly", "v0.3.1"], "v0.3.1", "v0.3.1")) == (
200, '{"versions": ["nightly", "v0.3.1"], "current": "v0.3.1"}')
+62
View File
@@ -0,0 +1,62 @@
import json
import os
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
COMPONENT = {"packname": "a pack", "category": "", "nodes": [], "links": [], "external": []}
def load(status, body):
source = JS.text("components-manager.js")
script = """
const registered = [];
const app = {graph: {}};
const api = {fetchApi: async () => ({status: %s, json: async () => JSON.parse(%s)})};
const SEPARATOR = '/';
const sleep = async () => {};
const register_pack_map = () => {};
class GroupNodeConfig {
constructor(name, data) { this.name = name; }
async registerType(category) { registered.push([this.name, category]); }
}
%s
%s
let failed = null;
try { await load_components(); } catch(e) { failed = String(e); }
console.log(JSON.stringify({groupNodes: app.graph.extra?.groupNodes ?? {}, registered, failed}));
""" % (
json.dumps(status), json.dumps(body),
slice_braced(source, "function storeGroupNode(name, data, register=true)"),
JS.lift_declaration("components-manager.js", "export async function load_components()"),
)
return run_node(script)
@pytest.mark.parametrize("status, body", [
(403, '{"error": "comfyui_outdated"}'), (403, '{"error": "security_level"}'), (403, ""),
(400, ""), (404, "404: Not Found"), (500, "<html><body>500 Internal Server Error</body></html>"),
(502, "<html><body><h1>502 Bad Gateway</h1></body></html>"), (403, json.dumps({"a component": COMPONENT})),
], ids=["an outdated ComfyUI", "a security level", "403 without a body", "400 without a body", "404", "500 with a page",
"502 from a proxy", "403 with a list"])
def test_an_answer_that_is_not_a_success_has_no_components(status, body):
assert load(status, body) == {"groupNodes": {}, "registered": [], "failed": None}
def test_a_success_without_components_adds_nothing():
assert load(200, "{}") == {"groupNodes": {}, "registered": [], "failed": None}
@pytest.mark.parametrize("names", [["a component"], ["a component", "error", "another"]], ids=["one", "three, one named error"])
def test_the_components_of_a_success_are_registered_as_before(names):
loaded = load(200, json.dumps({name: COMPONENT for name in names}))
assert loaded["failed"] is None
assert list(loaded["groupNodes"]) == names
assert loaded["registered"] == [[name, "a pack"] for name in names]
+148
View File
@@ -0,0 +1,148 @@
import json
import subprocess
import sys
import textwrap
import pytest
from manager_test_utils import GLOB_DIR
VALUES = {
"security_level": ["normal", "strong", "normal-", "weak"],
"network_mode": ["public", "private", "offline"],
"db_mode": ["cache", "local", "remote"],
"update_policy": ["stable-comfyui", "nightly-comfyui"],
"component_policy": ["workflow", "higher", "mine"],
}
NON_DEFAULT = {key: values[1] for key, values in VALUES.items()}
CHILD = textwrap.dedent(
"""
import sys, types, tempfile, os, json, io, contextlib, logging
tmp = tempfile.mkdtemp(prefix="cm_config_values_")
stub = types.ModuleType("folder_paths")
stub.get_user_directory = lambda: tmp
stub.get_system_user_directory = lambda *a, **k: os.path.join(tmp, "sysuser")
sys.modules["folder_paths"] = stub
written, changes, glob_dir = json.loads(sys.argv[1])
sys.path.insert(0, glob_dir)
with contextlib.redirect_stdout(io.StringIO()):
import manager_core
path = os.path.join(tmp, "config.ini")
manager_core.manager_config_path = path
manager_core.cached_config = None
if written is not None:
with open(path, "wb") as f:
f.write(written.encode("latin-1"))
warnings = []
handler = logging.Handler(logging.WARNING)
handler.emit = lambda record: warnings.append(record.getMessage())
logging.getLogger().addHandler(handler)
with contextlib.redirect_stdout(io.StringIO()):
settings = dict(manager_core.get_config())
for key, value in changes:
manager_core.get_config()[key] = value
if changes:
manager_core.write_config()
after = open(path, "rb").read().decode("latin-1") if os.path.exists(path) else None
print(json.dumps({"settings": settings, "warnings": warnings, "file": after}))
"""
)
def read(written, changes=()):
done = subprocess.run([sys.executable, "-c", CHILD, json.dumps([written, list(changes), str(GLOB_DIR)])],
capture_output=True, text=True, timeout=180)
assert done.returncode == 0, done.stderr[-2000:]
result = json.loads(done.stdout.strip().splitlines()[-1])
return result["settings"], "\n".join(result["warnings"]), result["file"]
def section(settings):
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
@pytest.mark.parametrize("value", ["100%", "%(downgrade_blacklist)s", "%", "bogus", "weak,normal", "<b>weak</b>", "nor mal",
"[/x]", "[bold]weak", "cache[/]"])
@pytest.mark.parametrize("key", sorted(VALUES))
def test_a_value_that_a_setting_cannot_have_gives_its_default_and_changes_no_other_setting(key, value):
text = section({**NON_DEFAULT, key: value, "downgrade_blacklist": "kornia"})
settings, printed, file = read(text)
assert {name: settings[name] for name in VALUES} == {**NON_DEFAULT, key: VALUES[key][0]}
assert settings["downgrade_blacklist"] == "kornia"
assert f"{key} = {value!r} in config.ini is not valid; '{VALUES[key][0]}' is used." in printed
assert file == text
@pytest.mark.parametrize("key", sorted(VALUES))
def test_a_value_that_a_setting_cannot_have_stays_in_config_ini_when_another_setting_is_saved(key):
text = section({**NON_DEFAULT, key: "bogus"})
_, _, file = read(text, changes=[("share_option", "none")])
assert f"{key} = bogus\n" in file
assert "share_option = none\n" in file
@pytest.mark.parametrize("key, value", [(key, value) for key, values in sorted(VALUES.items()) for value in values])
@pytest.mark.parametrize("written", [str.lower, str.upper], ids=["lower case", "upper case"])
def test_a_value_that_a_setting_can_have_is_read_and_nothing_is_said(key, value, written):
settings, printed, _ = read(section({key: written(value)}))
assert settings[key] == value
assert printed == ""
def test_a_config_ini_without_these_settings_has_their_defaults_and_nothing_is_said():
settings, printed, _ = read(section({"file_logging": "True"}))
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert printed == ""
@pytest.mark.parametrize("key, value", [
("downgrade_blacklist", "100%"), ("downgrade_blacklist", "%(security_level)s"), ("git_exe", "/opt/100%/git"),
("channel_url", "https://example.invalid/some%20one/channel"), ("channel_url", "%"), ("git_exe", "/opt/100%%/git"),
], ids=["a percent sign", "the form of a reference", "a path", "a percent-encoded url", "only a percent sign",
"two percent signs"])
def test_a_percent_sign_is_plain_text_and_the_other_settings_are_read(key, value):
text = section({**NON_DEFAULT, key: value})
settings, printed, file = read(text)
assert settings[key] == value
assert {name: settings[name] for name in VALUES} == NON_DEFAULT
assert printed == ""
assert file == text
def test_a_setting_is_written_beside_a_value_with_a_percent_sign_and_one_with_it_is_written():
text = section({"security_level": "strong", "downgrade_blacklist": "100%"})
_, _, file = read(text, changes=[("db_mode", "local"), ("channel_url", "https://example.invalid/some%20one/channel")])
assert "security_level = strong\n" in file and "downgrade_blacklist = 100%\n" in file
assert "db_mode = local\n" in file and "channel_url = https://example.invalid/some%20one/channel\n" in file
@pytest.mark.parametrize("text", ["security_level = strong\n", "\ufeff[default]\nsecurity_level = strong\n".encode("utf-8").decode("latin-1"),
"[default\nsecurity_level = strong\n", "[other]\nsecurity_level = strong\n", "",
"[default]\nsecurity_level = strong\nnot a setting [/x]\n"],
ids=["no section", "a byte order mark", "an unclosed section", "no default section", "empty",
"a line that is not a setting"])
def test_a_config_ini_that_cannot_be_read_gives_the_defaults_and_says_so(text):
settings, printed, file = read(text)
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert "could not be read" in printed and "the default settings are used" in printed
assert file == text
def test_without_a_config_ini_the_defaults_are_used_and_nothing_is_said():
settings, printed, file = read(None)
assert {name: settings[name] for name in VALUES} == {key: values[0] for key, values in VALUES.items()}
assert printed == ""
assert file is None
+46
View File
@@ -0,0 +1,46 @@
"""`print` of `manager_core` writes its text as it is.
The cases take what binds the name `print` out of `glob/manager_core.py`, an
import or a function, and call it.
"""
import ast
import io
import pytest
from manager_test_utils import GLOB_DIR
def core_print():
source = (GLOB_DIR / "manager_core.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, (ast.Import, ast.ImportFrom)) and "rich" in ast.unparse(node)
or isinstance(node, ast.FunctionDef) and node.name == "print"]
namespace = {}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<manager_core print>", "exec"), namespace)
return namespace["print"]
def printed(*objects, **options):
out = io.StringIO()
core_print()(*objects, file=out, **options)
return out.getvalue()
@pytest.mark.parametrize("text", [
"Install(git-clone) error: https://example.com/a[/b] / failed",
"## ComfyUI-Manager: EXECUTE => ['python', '-m', 'pip', 'install', 'diffusers[torch]']",
"skip black listed pip installation: 'requests[socks]'",
"Uninstall: custom_nodes/pack:100:backup",
"Download: git clone 'https://github.com/" + "a" * 120 + "'",
], ids=["closing tag", "list with an extra", "extra", "emoji code", "longer than 80 columns"])
def test_text_is_written_as_it_is(text):
assert printed(text) == text + "\n"
def test_objects_are_written_as_their_text():
assert printed("Update error:", ValueError("no section [/x]"), 3) == "Update error: no section [/x] 3\n"
def test_end_and_sep_are_kept():
assert printed("a", "b", sep="-", end="") == "a-b"
-121
View File
@@ -1,121 +0,0 @@
"""AC verification for wi-001 (B2): Content-Type rejection helper.
Validates _reject_simple_form_content_type against the 5-item curl matrix
from the WI's acceptance criteria using aiohttp test client. The test
builds a minimal aiohttp app that mirrors the helper's wiring into a
no-body POST handler, so we exercise the real request.content_type
parsing path rather than a mock.
AC matrix:
form-url → 400
multipart → 400
text/plain → 400
no-CT → 200
application/json → 200
"""
import asyncio
import unittest
from pathlib import Path
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
# Parse the helper from manager_server.py without importing it, to avoid
# pulling in the full ComfyUI/PromptServer stack. Note: we intentionally do
# NOT add the `glob/` directory to sys.path — the dir name would shadow
# Python's stdlib `glob` module and break pytest collection.
REPO_ROOT = Path(__file__).resolve().parent.parent
def _load_helper():
"""Parse manager_server.py and execute only the helper definition."""
import ast
source = (REPO_ROOT / "glob" / "manager_server.py").read_text()
tree = ast.parse(source)
wanted = {"_SIMPLE_FORM_CONTENT_TYPES", "_reject_simple_form_content_type"}
nodes = []
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name) and target.id in wanted:
nodes.append(node)
elif isinstance(node, ast.FunctionDef) and node.name in wanted:
nodes.append(node)
module = ast.Module(body=nodes, type_ignores=[])
ns = {"web": web, "frozenset": frozenset}
exec(compile(module, "manager_server_helpers", "exec"), ns)
return ns["_reject_simple_form_content_type"]
_reject_simple_form_content_type = _load_helper()
async def _handler(request):
resp = _reject_simple_form_content_type(request)
if resp is not None:
return resp
return web.Response(status=200)
class ContentTypeRejectionTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.loop = asyncio.new_event_loop()
asyncio.set_event_loop(cls.loop)
app = web.Application()
app.router.add_post("/noop", _handler)
cls.server = TestServer(app, loop=cls.loop)
cls.client = TestClient(cls.server, loop=cls.loop)
cls.loop.run_until_complete(cls.client.start_server())
@classmethod
def tearDownClass(cls):
cls.loop.run_until_complete(cls.client.close())
cls.loop.close()
def _post(self, headers):
async def go():
return await self.client.post("/noop", headers=headers, data=b"")
return self.loop.run_until_complete(go())
def test_form_urlencoded_rejected(self):
r = self._post({"Content-Type": "application/x-www-form-urlencoded"})
self.assertEqual(r.status, 400)
def test_multipart_form_data_rejected(self):
# aiohttp requires a boundary for multipart; helper should still reject
# based on the primary mimetype.
r = self._post({"Content-Type": "multipart/form-data; boundary=xyz"})
self.assertEqual(r.status, 400)
def test_text_plain_rejected(self):
r = self._post({"Content-Type": "text/plain"})
self.assertEqual(r.status, 400)
def test_no_content_type_allowed(self):
# Explicitly strip Content-Type: aiohttp client may add a default,
# so we use a raw request to ensure absence is tested.
async def go():
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.post(
self.client.make_url("/noop"),
data=None,
skip_auto_headers=["Content-Type"],
) as resp:
return resp.status
status = self.loop.run_until_complete(go())
self.assertEqual(status, 200)
def test_application_json_allowed(self):
r = self._post({"Content-Type": "application/json"})
self.assertEqual(r.status, 200)
if __name__ == "__main__":
unittest.main(verbosity=2)
+278
View File
@@ -0,0 +1,278 @@
import os
import pytest
from test_snapshot_restore_pins import run
REPOSITORY = '''
def repository(path):
path.mkdir(parents=True)
commits = []
for version in (1, 2):
(path / '__init__.py').write_text('VERSION = %d' % version)
for args in (['init', '-q'], ['add', '.'],
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
commits.append(head(path))
return commits
def head(path):
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
'''
def lines(body):
return run(REPOSITORY + body + '\nprint(json.dumps(result))\n')
def test_ref_that_head_names_is_read():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
head_file = nodes / 'fixture/.git/HEAD'
branch = head_file.read_text().strip()[5:]
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
head_file.write_text('ref:' + branch + '\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
head_file.write_text('ref: \\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == [True, True, 'unknown']
def test_commit_of_a_pack_whose_refs_are_packed_is_read():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
with open(nodes / 'fixture/.git/packed-refs', 'a') as packed:
packed.write('\\n')
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
result = [(nodes / 'fixture/.git' / branch).exists(), git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
''') == [False, True]
def test_ref_whose_place_is_a_folder_is_not_read_as_a_file():
"""git takes a folder there for no ref: after `git pack-refs`, and after `git checkout --orphan feature` beside a branch `feature/x`."""
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
branch = (nodes / 'fixture/.git/HEAD').read_text().strip()[5:]
(nodes / 'fixture/.git' / branch).mkdir(parents=True)
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
subprocess.run(['git', 'branch', 'feature/x'], cwd=nodes / 'fixture', check=True)
subprocess.run(['git', 'checkout', '-q', '--orphan', 'feature'], cwd=nodes / 'fixture', check=True)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == [True, 'unknown']
def test_commit_that_is_not_ascii_is_read_without_an_error():
assert lines('''
import git_utils
repository(nodes / 'fixture')
git_dir = nodes / 'fixture/.git'
branch = (git_dir / 'HEAD').read_text().strip()[5:]
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
(git_dir / 'packed-refs').write_bytes(b'0123\\xff ' + branch.encode() + b'\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
(git_dir / branch).write_bytes(b'0123\\xff\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / 'HEAD').write_bytes(b'0123\\xff\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == ['0123\ufffd'] * 3
def test_head_that_cannot_be_opened_has_no_commit():
assert lines('''
import git_utils
(nodes / 'fixture/.git/HEAD').mkdir(parents=True)
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['unknown']
def test_files_that_may_not_be_read_have_no_commit(tmp_path):
(tmp_path / 'probe').touch()
(tmp_path / 'probe').chmod(0)
try:
open(tmp_path / 'probe').close()
except OSError:
pass
else:
pytest.skip('a file can be read here whatever its mode, as by root or on Windows')
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
git_dir = nodes / 'fixture/.git'
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
branch = (git_dir / 'HEAD').read_text().strip()[5:]
result = []
(git_dir / 'packed-refs').chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / branch).write_text(commits[1])
(git_dir / branch).chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
(git_dir / 'HEAD').chmod(0)
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')))
''') == ['unknown', 'unknown', 'unknown']
def test_commit_is_read_beside_refs_that_are_not_utf8():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
packed = nodes / 'fixture/.git/packed-refs'
packed.write_bytes(b'0123456789abcdef0123456789abcdef01234567 refs/heads/\\xff\\xfe\\n' + packed.read_bytes())
result = [git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1]]
''') == [True]
def test_head_that_is_not_utf8_is_read(tmp_path):
try:
open(os.fsencode(tmp_path) + b'/\xff\xfe', 'wb').close()
except (OSError, ValueError):
pytest.skip('this file system has no file of such a name, as that of Windows')
assert lines('''
import git_utils
heads = nodes / 'fixture/.git/refs/heads'
heads.mkdir(parents=True)
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/\\xff\\xfe\\n')
with open(os.fsencode(heads) + b'/\\xff\\xfe', 'wb') as ref:
ref.write(b'0123456789abcdef0123456789abcdef01234567\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['0123456789abcdef0123456789abcdef01234567']
# what MinGit 2.56 named the file of a branch that was cloned on Windows
NAMES_OF_GIT_FOR_WINDOWS = [
(b'rel-\xfe', 'rel-\u00fe'),
(b'caf\xe9', 'caf\u00e9'),
(b'rel-\x81', 'rel-81'),
('\ud55c\uae00'.encode(), '\ud55c\uae00'),
('\ud55c'.encode() + b'\xfe\xe9\xc3', '\ud55c\u00fe\u00e9\u00c3'),
('a\U0001f600'.encode(), 'a\U0001f600'),
(b'\xe0\x80\x80', '\u00e08080'),
# a surrogate in UTF-8, which `xutftowcsn` of compat/mingw.c of git takes as one
(b'\xed\xa0\x80', '\ud800'),
]
def test_file_of_a_ref_is_named_as_git_for_windows_names_it():
assert lines('''
import git_utils
result = [git_utils.file_name_of_git_for_windows(name) for name in %r]
''' % [name for name, _ in NAMES_OF_GIT_FOR_WINDOWS]) == [file_name for _, file_name in NAMES_OF_GIT_FOR_WINDOWS]
@pytest.mark.skipif(os.name != 'nt', reason='the names that Git for Windows gives its files')
def test_ref_that_git_for_windows_made_is_read():
"""A name that is not UTF-8 is no name of a file there, and Git for Windows writes the file under another."""
assert lines('''
import git_utils
heads = nodes / 'fixture/.git/refs/heads'
heads.mkdir(parents=True)
(nodes / 'fixture/.git/HEAD').write_bytes(b'ref: refs/heads/rel-\\xfe\\n')
(heads / 'rel-\\u00fe').write_text('0123456789abcdef0123456789abcdef01234567\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
''') == ['0123456789abcdef0123456789abcdef01234567']
def test_packed_ref_is_matched_by_its_bytes():
assert lines('''
import git_utils
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'pack-refs', '--all'], cwd=nodes / 'fixture', check=True)
git_dir = nodes / 'fixture/.git'
other = b'0123456789abcdef0123456789abcdef01234567 refs/heads/release-\\xff\\n'
(git_dir / 'packed-refs').write_bytes(other + (git_dir / 'packed-refs').read_bytes())
(git_dir / 'HEAD').write_bytes(b'ref: refs/heads/release-\\xfe\\n')
result = [git_utils.get_commit_hash(str(nodes / 'fixture'))]
(git_dir / 'packed-refs').write_bytes(other + commits[1].encode() + b' refs/heads/release-\\xfe\\n')
result.append(git_utils.get_commit_hash(str(nodes / 'fixture')) == commits[1])
''') == ['unknown', True]
SUBMODULE = '''
os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='protocol.file.allow', GIT_CONFIG_VALUE_0='always')
def git(path, *args):
subprocess.run(['git', '-c', 'protocol.file.allow=always', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args],
cwd=path, check=True, capture_output=True)
library = repository(pathlib.Path(tmp) / 'library')
origin = pathlib.Path(tmp) / 'origin'
origin.mkdir()
git(origin, 'init', '-q')
git(origin, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
pinned_commits = []
for commit in library:
git(origin / 'library', 'checkout', '-q', commit)
git(origin, 'commit', '-q', '-a', '-m', 'library at ' + commit)
pinned_commits.append(head(origin))
'''
@pytest.mark.parametrize('clone', [['--recursive'], []], ids=['with its submodules', 'without its submodules'])
def test_checkout_brings_the_submodules_to_the_commit(clone):
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', *%r, str(origin), 'fixture')
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[0]), head(nodes / 'fixture') == pinned_commits[0],
head(nodes / 'fixture/library') == library[0]]
''' % clone) == [True, True, True]
def test_submodules_are_brought_to_the_commit_of_a_pack_that_is_at_it_already():
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', '--recursive', str(origin), 'fixture')
git(nodes / 'fixture/library', 'checkout', '-q', library[0])
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), head(nodes / 'fixture/library') == library[1]]
''') == [False, True]
def test_submodule_that_was_never_fetched_is_left_alone_in_a_pack_cloned_without_its_submodules():
"""As git does without `--init`: no submodule of such a clone is active."""
assert lines(SUBMODULE + '''
git(nodes, 'clone', '-q', str(origin), 'fixture')
# moved, as git makes files read-only that Windows does not remove
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
result = [core.repo_switch_commit(str(nodes / 'fixture'), pinned_commits[1]), list((nodes / 'fixture/library').iterdir())]
''') == [False, []]
@pytest.mark.parametrize('reachable', [True, False], ids=['reachable', 'away'])
def test_submodule_that_was_never_fetched_is_fetched_in_a_pack_cloned_as_the_manager_clones(reachable):
"""`clone --recursive` makes every submodule active, also one of a later commit: git updates it without `--init`."""
result = lines(SUBMODULE + '''
import io, logging
log = io.StringIO()
logging.getLogger().addHandler(logging.StreamHandler(log))
plain = pathlib.Path(tmp) / 'plain'
plain.mkdir()
git(plain, 'init', '-q')
git(plain, 'commit', '-q', '--allow-empty', '-m', 'no submodule')
git(nodes, 'clone', '-q', '--recursive', str(plain), 'fixture')
git(plain, 'submodule', 'add', '-q', str(pathlib.Path(tmp) / 'library'), 'library')
git(plain, 'commit', '-q', '-m', 'a submodule')
git(nodes / 'fixture', 'pull', '-q')
if not %r:
# moved, as git makes files read-only that Windows does not remove
(pathlib.Path(tmp) / 'library').rename(pathlib.Path(tmp) / 'library.away')
result = [core.repo_switch_commit(str(nodes / 'fixture'), head(plain)), (nodes / 'fixture/library/__init__.py').exists(),
"'" + str(nodes / 'fixture') + "'" in log.getvalue(), 'library' in log.getvalue()]
''' % reachable)
assert result == ([False, True, False, False] if reachable else [None, False, True, True])
def test_git_is_not_run_for_the_submodules_of_a_pack_that_has_none():
assert lines('''
import git
commits = repository(nodes / 'fixture')
ran = []
execute = git.Git.execute
def recorded(self, command, *args, **kwargs):
ran.append(list(command))
return execute(self, command, *args, **kwargs)
git.Git.execute = recorded
result = [core.repo_switch_commit(str(nodes / 'fixture'), commits[1]), [command for command in ran if 'submodule' in command]]
''') == [False, []]
+145
View File
@@ -0,0 +1,145 @@
import configparser
import importlib.util
import logging
import os
import pytest
from manager_test_utils import GLOB_DIR
from test_git_exe_setting import take
URL = "https://github.com/someone/some%20pack"
PLAIN = '[core]\n\tbare = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
PERCENT = f'[core]\n\tbare = false\n[remote "origin"]\n\turl = {URL}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n'
NO_VALUE = '[core]\n\tbare\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
NO_VALUE_THEN_DEEPER = '[core]\n\tbare\n\t\tfilemode = false\n[remote "origin"]\n\turl = https://github.com/someone/pack\n'
NO_REMOTE = '[core]\n\tbare = false\n'
BOM = "\ufeff" + PLAIN
NOT_A_CONFIG = "ref: refs/heads/master\n" + PLAIN
NOT_ASCII = PLAIN + '[user]\n\tname = 홍길동\n'
NOT_UTF8 = PLAIN.encode() + b'[user]\n\tname = \xff\xfe\n'
BRANCH_NOT_UTF8 = PLAIN.encode() + b'[branch "release-\xfe"]\n\tremote = origin\n\tmerge = refs/heads/release-\xfe\n'
ORIGIN = '[remote "origin"]\n\turl = https://github.com/someone/pack\n'
OTHER = '\t[remote "other"]\n\turl = https://github.com/someone/other\n'
VALUE_OVER_TWO_LINES = '[core]\n\tdescription = a \\\n' + OTHER + ORIGIN
QUOTED_VALUE_OVER_TWO_LINES = '[core]\n\tdescription = "a # b \\\n' + OTHER.replace('\n', '"\n', 1) + ORIGIN
COMMENT_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\t# a comment \\\n' + ORIGIN
VALUE_THAT_ENDS_IN_A_BACKSLASH = '[core]\n\tdescription = a\\\\\n' + ORIGIN
VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS = '[remote "origin"]\n\turl = https://github.com/someone/pack\\'
URL_BEFORE_THE_FIRST_SECTION = "url = https://someone:a-token@github.com/someone/pack\n" + PLAIN
def git_utils():
spec = importlib.util.spec_from_file_location("_git_utils", GLOB_DIR / "git_utils.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def git_url():
return git_utils().git_url
def resolve():
return take(GLOB_DIR / "manager_core.py", "resolve_giturl_from_path", {
"os": os, "configparser": configparser, "logging": logging, "git_utils": git_utils(),
})
@pytest.fixture(params=[git_url, resolve], ids=["git_url", "resolve_giturl_from_path"])
def read(request, tmp_path):
reader = request.param()
def read(config, mode=None):
(tmp_path / ".git").mkdir(exist_ok=True)
(tmp_path / ".git" / "config").write_bytes(config if isinstance(config, bytes) else config.encode())
if mode is not None:
(tmp_path / ".git" / "config").chmod(mode)
return reader(str(tmp_path))
return read
def test_url_is_read(read):
assert read(PLAIN) == "https://github.com/someone/pack"
def test_url_with_a_percent_sign_is_read_as_it_is(read):
assert read(PERCENT) == URL
def test_url_is_read_beside_a_key_without_a_value(read):
assert read(NO_VALUE) == "https://github.com/someone/pack"
def test_config_without_a_remote_has_no_url(read):
assert read(NO_REMOTE) is None
def test_url_without_a_value_is_no_url(read):
assert read('[remote "origin"]\n\turl\n') is None
def test_url_is_read_after_a_byte_order_mark(read):
assert read(BOM) == "https://github.com/someone/pack"
def test_url_is_read_beside_text_that_is_not_ascii(read):
assert read(NOT_ASCII) == "https://github.com/someone/pack"
def test_url_is_read_beside_bytes_that_are_not_utf8(read):
assert read(NOT_UTF8) == "https://github.com/someone/pack"
def test_url_is_read_beside_a_branch_that_is_not_utf8(read):
assert read(BRANCH_NOT_UTF8) == "https://github.com/someone/pack"
def test_config_that_cannot_be_parsed_has_no_url_and_is_reported(read, caplog, tmp_path):
assert read(NOT_A_CONFIG) is None
assert str(tmp_path / ".git" / "config") in caplog.text
def test_key_before_a_deeper_line_is_read(read):
"""For git a line that is indented more is a key of its own; the parser would take it as more of the value before it."""
assert read(NO_VALUE_THEN_DEEPER) == "https://github.com/someone/pack"
assert read('[remote "origin"]\n\turl = https://github.com/someone/pack\n\t\tfetch = +refs/heads/*:refs/remotes/origin/*\n') == "https://github.com/someone/pack"
def test_value_that_goes_on_at_the_next_line_is_one_value(read):
"""As for git: what looks like a section in the second line of a value is text of that value."""
assert read(VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
assert read(QUOTED_VALUE_OVER_TWO_LINES) == "https://github.com/someone/pack"
assert read(VALUE_THAT_GOES_ON_WHERE_THE_FILE_ENDS) == "https://github.com/someone/pack"
def test_line_that_does_not_go_on_is_a_line_of_its_own(read):
assert read(COMMENT_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
assert read(VALUE_THAT_ENDS_IN_A_BACKSLASH) == "https://github.com/someone/pack"
def test_config_that_cannot_be_parsed_is_reported_without_its_text(read, caplog, tmp_path):
assert read(URL_BEFORE_THE_FIRST_SECTION) is None
assert str(tmp_path / ".git" / "config") in caplog.text
assert "a-token" not in caplog.text
def test_config_that_cannot_be_parsed_is_reported_once(read, caplog, tmp_path):
for _ in range(3):
assert read(NOT_A_CONFIG) is None
assert caplog.text.count(f"Cannot read '{tmp_path / '.git' / 'config'}'") == 1
def test_config_that_may_not_be_read_has_no_url_and_is_reported(read, caplog, tmp_path):
url = read(PLAIN, mode=0)
try:
open(tmp_path / ".git" / "config").close()
except OSError:
pass
else:
pytest.skip("the file can be read here, as by root or on Windows")
assert url is None
assert str(tmp_path / ".git" / "config") in caplog.text
+276
View File
@@ -0,0 +1,276 @@
import ast
import configparser
import logging
import os
import shutil
import signal
import subprocess
import sys
import time
from types import SimpleNamespace
import git
import pytest
from manager_test_utils import GLOB_DIR, load_manager_util
from test_install_flags_config import GIT_LOCATION, _run_child
pytestmark = pytest.mark.skipif(os.name == "nt", reason="the executables of the cases are shell scripts")
ROOT = GLOB_DIR.parent
NOT_A_GIT = {
"a path that does not exist": None,
"a program that fails": "#!/bin/sh\nexit 3\n",
"a program that is not git": "#!/bin/sh\necho hello\n",
"a program that waits": "#!/bin/sh\nexec sleep 30\n",
"a program that prints bytes that are not text": "#!/bin/sh\nprintf '\\377\\376'\n",
"a file that cannot be run": "not a program\n",
}
def take(path, name, namespace):
function = [node for node in ast.parse(path.read_text(encoding="utf-8")).body
if isinstance(node, ast.FunctionDef) and node.name == name]
assert len(function) == 1
exec(compile(ast.Module(body=function, type_ignores=[]), str(path), "exec"), namespace)
return namespace[name]
@pytest.fixture
def manager_util(monkeypatch):
module = load_manager_util()
find = module.find_git_executable
monkeypatch.setattr(module, "find_git_executable", lambda git_exe, timeout=2: find(git_exe, timeout=timeout))
return module
@pytest.fixture(autouse=True)
def default_git(monkeypatch):
for name in (*GIT_LOCATION, 'GIT_PYTHON_GIT_EXECUTABLE'):
monkeypatch.delenv(name, raising=False)
# GitPython keeps the git that the variable of the shell named when it last looked
git.refresh()
yield
# the variables a case set are removed before GitPython looks for its git again
monkeypatch.undo()
git.refresh()
@pytest.fixture
def recording_git(tmp_path):
calls = tmp_path / "calls"
executable = tmp_path / "recording-git"
executable.write_text(f'#!/bin/sh\necho "$@" >> "{calls}"\nexec "{shutil.which("git")}" "$@"\n')
executable.chmod(0o755)
return SimpleNamespace(path=str(executable),
calls=lambda: calls.read_text().splitlines() if calls.exists() else [],
forget=lambda: calls.unlink(missing_ok=True))
@pytest.fixture(params=NOT_A_GIT)
def not_a_git(request, tmp_path):
path = tmp_path / "not-a-git"
if NOT_A_GIT[request.param] is not None:
path.write_text(NOT_A_GIT[request.param])
path.chmod(0o755)
return str(path)
def setup_git_executable(manager_util, git_exe, protected=True):
take(GLOB_DIR / "manager_core.py", "setup_git_executable", {
"git": git, "logging": logging, "manager_util": manager_util,
"manager_migration": SimpleNamespace(has_system_user_api=lambda: protected),
"get_config": lambda: {"git_exe": git_exe},
})()
def test_configured_git_is_run(manager_util, recording_git, tmp_path):
setup_git_executable(manager_util, recording_git.path)
recording_git.forget()
git.Repo.init(tmp_path / "repo")
assert any(line.startswith("init") for line in recording_git.calls())
assert (tmp_path / "repo" / ".git").is_dir()
def test_empty_setting_keeps_the_default_git(manager_util, recording_git, tmp_path, caplog):
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
with caplog.at_level(logging.WARNING):
setup_git_executable(manager_util, "")
assert caplog.text == ""
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
def test_setting_that_is_no_git_is_reported_and_the_default_kept(manager_util, not_a_git, tmp_path, caplog):
default = git.Git.GIT_PYTHON_GIT_EXECUTABLE
flags = git.remote.FetchInfo._flag_map.copy()
with caplog.at_level(logging.WARNING):
setup_git_executable(manager_util, not_a_git)
assert not_a_git in caplog.text
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default and git.remote.FetchInfo._flag_map == flags
git.Repo.init(tmp_path / "repo")
assert (tmp_path / "repo" / ".git").is_dir()
def test_setting_of_an_unprotected_configuration_is_not_used(manager_util, recording_git, tmp_path, caplog):
with caplog.at_level(logging.WARNING):
setup_git_executable(manager_util, recording_git.path, protected=False)
git.Repo.init(tmp_path / "repo")
assert recording_git.calls() == []
assert "git_exe" in caplog.text
def set_git_executable(manager_util, monkeypatch, git_exe, protected=True):
# set and removed, so that the variable the function sets is removed after the case, also when there was none
monkeypatch.setenv("GIT_PYTHON_GIT_EXECUTABLE", "")
monkeypatch.delenv("GIT_PYTHON_GIT_EXECUTABLE")
config = configparser.ConfigParser(strict=False)
config.read_string("[default]\n" + ("" if git_exe is None else f"git_exe = {git_exe}\n"))
take(ROOT / "prestartup_script.py", "set_git_executable", {
"os": os, "manager_util": manager_util, "_has_system_user_api": protected, "default_conf": config["default"],
})()
return os.environ.get("GIT_PYTHON_GIT_EXECUTABLE")
def test_git_is_known_before_gitpython_is_imported(manager_util, monkeypatch, recording_git):
assert set_git_executable(manager_util, monkeypatch, recording_git.path) == recording_git.path
def test_gitpython_is_imported_without_a_git_on_path(manager_util, monkeypatch, recording_git, tmp_path):
"""GitPython looks for its git when it is imported, and the import fails when it finds none."""
set_git_executable(manager_util, monkeypatch, recording_git.path)
(tmp_path / "empty").mkdir()
recording_git.forget()
imported = subprocess.run([sys.executable, "-c", "import git, sys; git.Repo.init(sys.argv[1])", str(tmp_path / "repository")],
env={**os.environ, "PATH": str(tmp_path / "empty")}, capture_output=True, text=True)
assert imported.returncode == 0, imported.stderr
assert any(call.startswith("init") for call in recording_git.calls())
def test_git_in_a_directory_with_a_percent_sign_is_known(manager_util, monkeypatch, recording_git, tmp_path):
"""A path of Windows may hold a `%`, which the parser takes as the start of a reference."""
(tmp_path / "100%").mkdir()
path = shutil.copy(recording_git.path, tmp_path / "100%" / "git")
assert set_git_executable(manager_util, monkeypatch, str(path)) == str(path)
def test_start_up_without_a_configuration_file_sets_nothing(manager_util, monkeypatch):
monkeypatch.setenv("GIT_PYTHON_GIT_EXECUTABLE", "")
monkeypatch.delenv("GIT_PYTHON_GIT_EXECUTABLE")
take(ROOT / "prestartup_script.py", "set_git_executable", {
"os": os, "manager_util": manager_util, "_has_system_user_api": True, "default_conf": {},
})()
assert os.environ.get("GIT_PYTHON_GIT_EXECUTABLE") is None
def test_setting_with_a_percent_sign_is_read_as_written_and_the_others_kept():
config = _run_child(r'''
write_ini("[default]\ngit_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe\ndb_mode = local\nnetwork_mode = offline\n")
cfg = fresh_read()
print(json.dumps([cfg["git_exe"], cfg["db_mode"], cfg["network_mode"]]))
''')
assert config == ["%LOCALAPPDATA%\\Git\\bin\\git.exe", "local", "offline"]
@pytest.mark.parametrize("git_exe", ["", None])
def test_no_setting_leaves_the_environment_alone(manager_util, monkeypatch, git_exe):
assert set_git_executable(manager_util, monkeypatch, git_exe) is None
def test_setting_of_an_unprotected_configuration_is_not_put_in_the_environment(manager_util, monkeypatch, recording_git):
assert set_git_executable(manager_util, monkeypatch, recording_git.path, protected=False) is None
def test_setting_that_is_no_git_is_not_put_in_the_environment(manager_util, monkeypatch, not_a_git):
assert set_git_executable(manager_util, monkeypatch, not_a_git) is None
def test_git_named_by_a_command_on_path_is_run_by_its_full_path(manager_util, tmp_path, monkeypatch):
"""GitPython takes a name without a directory as a file of the current directory."""
monkeypatch.chdir(tmp_path)
setup_git_executable(manager_util, "git")
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == shutil.which("git")
git.Repo.init(tmp_path / "repo")
assert (tmp_path / "repo" / ".git").is_dir()
def test_git_named_by_a_command_is_not_taken_from_the_current_directory(manager_util, recording_git, tmp_path, monkeypatch):
"""Windows looks for a command in the current directory first. Here it is PATH that names that directory."""
default = shutil.which("git")
shutil.copy(recording_git.path, tmp_path / "git")
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("PATH", os.pathsep.join([".", os.environ["PATH"]]))
setup_git_executable(manager_util, "git")
assert git.Git.GIT_PYTHON_GIT_EXECUTABLE == default
assert recording_git.calls() == []
def test_check_does_not_wait_for_a_program_that_the_setting_started(manager_util, tmp_path):
"""With a pipe for the answer, the check would wait for every program that holds the pipe: on Windows also after its time is up."""
executable = tmp_path / "starts-a-program"
executable.write_text(f'#!/bin/sh\nsleep 30 &\necho $! > "{tmp_path}/pid"\n')
executable.chmod(0o755)
started = time.monotonic()
try:
assert manager_util.find_git_executable(str(executable), timeout=20) is None
assert time.monotonic() - started < 10
finally:
os.kill(int((tmp_path / "pid").read_text()), signal.SIGTERM)
def test_setting_saved_beside_a_git_exe_with_a_percent_sign_keeps_it():
saved = _run_child(r'''
write_ini("[default]\ngit_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe\ndb_mode = local\n")
cfg = fresh_read()
cfg["db_mode"] = "remote"
manager_core.write_config()
print(json.dumps(sorted(line for line in open(CONFIG_PATH).read().splitlines() if line.startswith(("git_exe", "db_mode")))))
''')
assert saved == ["db_mode = remote", "git_exe = %LOCALAPPDATA%\\Git\\bin\\git.exe"]
def test_git_helper_runs_the_git_of_the_process_that_starts_it(recording_git, tmp_path):
result = _run_child(f'''
import pathlib, subprocess
write_ini("[default]\\ngit_exe = {recording_git.path}\\n")
fresh_read()
manager_core.manager_migration.has_system_user_api = lambda: True
manager_core.setup_git_executable()
work = pathlib.Path({str(tmp_path)!r})
(work / "folder_paths.py").touch()
def git(where, *args):
return subprocess.run(["git", "-c", "user.name=test", "-c", "user.email=test@example.invalid", *args],
cwd=where, check=True, capture_output=True, text=True).stdout.strip()
(work / "origin").mkdir()
git(work / "origin", "init", "-q")
git(work / "origin", "commit", "-q", "--allow-empty", "-m", "first")
git(work, "clone", "-q", str(work / "origin"), "pack")
git(work / "origin", "commit", "-q", "--allow-empty", "-m", "second")
(work / "calls").unlink(missing_ok=True)
helper = subprocess.run([sys.executable, manager_core.git_script_path, "--pull", str(work / "pack")], cwd=str(work),
env={{**manager_core.get_script_env(), "COMFYUI_PATH": str(work)}}, capture_output=True)
print(json.dumps([helper.returncode, git(work / "pack", "rev-parse", "HEAD") == git(work / "origin", "rev-parse", "HEAD")]))
''')
assert result == [0, True]
assert any(line.startswith("pull") for line in recording_git.calls())
+185
View File
@@ -0,0 +1,185 @@
import pytest
from test_install_flags_config import _run_child
PRELUDE = '''
import asyncio, os, pathlib, subprocess
from unittest.mock import AsyncMock, Mock
core = manager_core
tmp = pathlib.Path(tmp)
os.environ.update(GIT_CONFIG_COUNT='1', GIT_CONFIG_KEY_0='protocol.file.allow', GIT_CONFIG_VALUE_0='always')
(tmp / 'folder_paths.py').touch()
os.environ['COMFYUI_PATH'] = str(tmp)
nodes = tmp / 'custom_nodes'
nodes.mkdir()
core.get_default_custom_nodes_path = lambda: str(nodes)
core.get_custom_nodes_paths = lambda: [str(nodes)]
core.is_valid_url = lambda url: True
manager = core.UnifiedManager()
manager.reload = AsyncMock()
manager.get_custom_nodes = AsyncMock(return_value={})
manager.get_cnr_by_repo = Mock(return_value=None)
manager.execute_install_script = Mock(return_value=True)
core.unified_manager = manager
core.execute_install_script = Mock(return_value=True)
def git(path, *args):
subprocess.run(['git', '-c', 'user.name=test', '-c', 'user.email=test@example.invalid', *args], cwd=path, check=True, capture_output=True)
def head(path):
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
def failed(call, *args, **options):
try:
call(*args, **options)
except Exception:
return True
return False
asset, library, origin, pack = tmp / 'asset', tmp / 'library', tmp / 'origin', tmp / 'pack'
for repository in (asset, library, origin):
repository.mkdir()
git(repository, 'init', '-q')
commits = []
for version in (1, 2):
for submodule in (asset, library):
(submodule / '__init__.py').write_text('VERSION = %d' % version)
git(submodule, 'add', '.')
git(submodule, 'commit', '-q', '-m', 'version %d' % version)
if version == 1:
git(origin, 'submodule', 'add', '-q', str(submodule), submodule.name)
else:
git(origin / submodule.name, 'pull', '-q')
git(origin, 'commit', '-q', '-a', '-m', 'library %d' % version)
commits.append(head(origin))
if version == 1:
git(tmp, 'clone', '-q', '--recursive', str(origin), 'pack')
away = tmp / 'library.away'
library.rename(away)
'''
PULL_TWICE = '''
first = failed(core.git_pull, str(pack))
after_first = head(pack) == commits[0]
asset_after_first = (pack / 'asset/__init__.py').read_text()
away.rename(library)
second = failed(core.git_pull, str(pack))
print(json.dumps({'first failed': first, 'at its commit': after_first, 'asset at its commit': asset_after_first, 'second failed': second,
'updated': head(pack) == commits[1], 'library': (pack / 'library/__init__.py').read_text()}))
'''
PULLED = {'first failed': True, 'at its commit': True, 'asset at its commit': 'VERSION = 1', 'second failed': False, 'updated': True, 'library': 'VERSION = 2'}
def run(body):
return _run_child(PRELUDE + body)
def test_pull_that_fails_at_the_submodules_leaves_the_pack_at_its_commit():
assert run(PULL_TWICE) == PULLED
def test_pull_of_the_git_helper_that_fails_is_a_failure():
assert run("core.platform.system = lambda: 'Windows'\n" + PULL_TWICE) == PULLED
LIBRARY_NOT_CLONED = '''
git(pack, 'submodule', 'deinit', '-q', '-f', 'library')
# moved, as git makes files read-only that Windows does not remove
(pack / '.git/modules/library').rename(tmp / 'library.modules')
'''
def test_pull_of_the_git_helper_that_fails_at_the_submodules_puts_them_back():
data = run('''
away.rename(library)
nested = tmp / 'nested'
nested.mkdir()
git(nested, 'init', '-q')
git(nested, 'commit', '-q', '--allow-empty', '-m', 'nested')
git(asset, 'submodule', 'add', '-q', str(nested), 'nested')
git(asset, 'commit', '-q', '-m', 'a submodule')
git(origin / 'asset', 'pull', '-q')
git(origin, 'commit', '-q', '-a', '-m', 'asset with a submodule')
nested.rename(tmp / 'nested.away')
core.platform.system = lambda: 'Windows'
first = failed(core.git_pull, str(pack))
print(json.dumps({'failed': first, 'at its commit': head(pack) == commits[0], 'asset at its commit': not (pack / 'asset/.gitmodules').exists()}))
''')
assert data == {'failed': True, 'at its commit': True, 'asset at its commit': True}
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
def test_pull_of_a_pack_whose_branch_is_ahead_of_its_remote_is_no_failure(where):
data = run(where + '''
away.rename(library)
git(pack, 'pull', '-q', '--recurse-submodules')
git(pack, 'commit', '-q', '--allow-empty', '-m', 'a commit of the pack alone')
tip = head(pack)
print(json.dumps({'failed': failed(core.git_pull, str(pack)), 'at its commit': head(pack) == tip}))
''')
assert data == {'failed': False, 'at its commit': True}
LIBRARY_AT_A_COMMIT_AWAY = '''
(library / '__init__.py').write_text('VERSION = 3')
git(library, 'commit', '-q', '-a', '-m', 'version 3')
git(origin / 'library', 'pull', '-q')
git(origin, 'commit', '-q', '-a', '-m', 'library 3')
version_3 = head(library)
library.rename(away)
'''
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
def test_pull_that_fails_puts_back_the_branch_of_a_pack_that_was_not_on_it(where):
data = run(where + '''
away.rename(library)
git(pack, 'pull', '-q', '--recurse-submodules')
git(pack, 'checkout', '-q', commits[0])
git(pack, 'submodule', 'update', '-q', '--recursive')
''' + LIBRARY_NOT_CLONED + LIBRARY_AT_A_COMMIT_AWAY + '''
print(json.dumps({'failed': failed(core.git_pull, str(pack)), 'at the commit of its branch': head(pack) == commits[1]}))
''')
assert data == {'failed': True, 'at the commit of its branch': True}
def test_pull_whose_submodules_cannot_be_put_back_either_fails_with_the_error_of_the_update():
data = run('''
away.rename(library)
git(pack, 'pull', '-q', '--no-recurse-submodules')
''' + LIBRARY_AT_A_COMMIT_AWAY + '''
error = ''
try:
core.platform.system = lambda: 'Linux'
core.git_pull(str(pack))
except Exception as e:
error = str(e)
helper = subprocess.run([sys.executable, core.git_script_path, '--pull', str(pack)], env=core.get_script_env(), cwd=nodes,
capture_output=True, text=True)
print(json.dumps({'in the server process': version_3 in error, 'in the git helper': [helper.returncode, version_3 in helper.stdout]}))
''')
assert data == {'in the server process': True, 'in the git helper': [1, True]}
@pytest.mark.parametrize('where', ['', "core.platform.system = lambda: 'Windows'\n"], ids=['in the server process', 'in the git helper'])
def test_pull_that_fails_leaves_a_submodule_that_was_never_fetched_alone(where):
data = run(where + '''
away.rename(library)
git(tmp, 'clone', '-q', str(origin), 'plain')
plain = tmp / 'plain'
git(plain, 'submodule', 'update', '-q', '--init', 'asset')
extra = tmp / 'extra'
extra.mkdir()
git(extra, 'init', '-q')
(extra / 'x.py').write_text('x')
git(extra, 'add', '.')
git(extra, 'commit', '-q', '-m', 'x')
git(origin, 'rm', '-q', 'library')
git(origin, 'submodule', 'add', '-q', str(extra), 'extra')
git(origin, 'commit', '-q', '-m', 'library removed, extra added')
extra.rename(tmp / 'extra.away')
before = head(plain)
print(json.dumps({'failed': failed(core.git_pull, str(plain)), 'at its commit': head(plain) == before, 'library': os.listdir(plain / 'library')}))
''')
assert data == {'failed': True, 'at its commit': True, 'library': []}
+73
View File
@@ -0,0 +1,73 @@
"""The two direct install routes answer 400 to a body they cannot use.
Each case runs the real handler of `glob/manager_server.py` with the install
allowed; `core` is replaced and records what it is asked to install.
"""
import ast
import asyncio
import json
import logging
from types import SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
GIT_URL, PIP = "install_custom_node_git_url", "install_custom_node_pip"
def post(name, body):
"""The status the handler answers for the raw request body, and what it asked `core` to install."""
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
handler = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == name]
assert len(handler) == 1
asked = []
async def gitclone_install(url):
asked.append(url)
return SimpleNamespace(action="install-git", result=True, target=url, msg="")
namespace = {
"web": web, "logging": logging, "_reject_non_json_content_type": lambda request: None,
"routes": SimpleNamespace(post=lambda path: lambda handler: handler),
"is_dedicated_install_allowed": lambda flag, listen: True,
"args": SimpleNamespace(listen="127.0.0.1"),
"core": SimpleNamespace(get_config=lambda: {"allow_git_url_install": True, "allow_pip_install": True},
gitclone_install=gitclone_install, pip_install=asked.append),
}
exec(compile(ast.Module(body=handler, type_ignores=[]), "<install handler>", "exec"), namespace)
async def read():
return json.loads(body)
return asyncio.run(namespace[name](SimpleNamespace(json=read))).status, asked
NOT_AN_OBJECT = ["[]", '"text"', "7", "null"]
NOT_A_STRING = ["7", "null", '["a"]', '{"a": 1}']
def test_git_url_is_installed():
assert post(GIT_URL, '{"url": "https://github.com/a/b"}') == (200, ["https://github.com/a/b"])
def test_packages_are_installed():
assert post(PIP, '{"packages": "numpy scipy"}') == (200, [["numpy", "scipy"]])
@pytest.mark.parametrize("name", [GIT_URL, PIP])
@pytest.mark.parametrize("body", NOT_AN_OBJECT + ["{}", "not json"])
def test_body_without_the_field_is_answered_with_400(name, body):
assert post(name, body) == (400, [])
@pytest.mark.parametrize("value", NOT_A_STRING)
def test_url_that_is_not_a_string_is_answered_with_400(value):
assert post(GIT_URL, '{"url": %s}' % value) == (400, [])
@pytest.mark.parametrize("value", NOT_A_STRING)
def test_packages_that_are_not_a_string_are_answered_with_400(value):
assert post(PIP, '{"packages": %s}' % value) == (400, [])
+8 -3
View File
@@ -10,13 +10,13 @@ quirk the flags rely on stays frozen.
Harness: the child process injects a stub `folder_paths` (routing
import-time side effects into a tmpdir, and making has_system_user_api()
True so force_security_level_if_needed does not force 'strong'), prepends
`glob/` to ITS OWN sys.path (shadowing of stdlib `glob` confined to the
child), points manager_core.manager_config_path at a tmp config.ini,
True), prepends `glob/` to ITS OWN sys.path (shadowing of stdlib `glob`
confined to the child), points manager_core.manager_config_path at a tmp config.ini,
resets cached_config, runs the scenario, and prints one JSON line for the
parent to assert.
"""
import json
import os
import subprocess
import sys
import textwrap
@@ -24,6 +24,10 @@ import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
# what `git rev-parse --local-env-vars` lists: with one of them, git does not work on the repository of its directory
GIT_LOCATION = ("GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_CONFIG", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT", "GIT_OBJECT_DIRECTORY",
"GIT_DIR", "GIT_WORK_TREE", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_INDEX_FILE", "GIT_NO_REPLACE_OBJECTS",
"GIT_REPLACE_REF_BASE", "GIT_PREFIX", "GIT_SHALLOW_FILE", "GIT_COMMON_DIR")
_CHILD_PREAMBLE = textwrap.dedent(
"""
@@ -65,6 +69,7 @@ def _run_child(body):
text=True,
timeout=180,
cwd=str(REPO_ROOT),
env={name: value for name, value in os.environ.items() if name not in GIT_LOCATION},
)
if proc.returncode != 0:
raise AssertionError(
+169
View File
@@ -0,0 +1,169 @@
import ast
import asyncio
import os
import re
from pathlib import Path
from types import SimpleNamespace
import pytest
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from js_lift import _skip_literal
from manager_test_utils import GLOB_DIR
JS_DIR = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
FILES = sorted(path.name for path in GLOB_DIR.glob("*.py"))
CHECK = "_reject_non_json_content_type"
NOT_GET = ("routes.post", "routes.put", "routes.patch", "routes.delete")
READS_ONLY = {"/manager/component/loads"}
NOT_JSON = [
None, "text/plain", "text/plain;charset=UTF-8", "application/x-www-form-urlencoded",
"multipart/form-data; boundary=x", "application/octet-stream", "text/json", "application/jsonp",
"application/json-patch+json", "application/ld+json", "",
]
JSON = ["application/json", "application/json; charset=utf-8", "application/json;charset=UTF-8", "Application/JSON"]
def functions(filename):
tree = ast.parse((GLOB_DIR / filename).read_text(encoding="utf-8"))
return {node.name: node for node in tree.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
def routes_that_change_something():
found = []
for filename in FILES:
for node in functions(filename).values():
for decorator in node.decorator_list:
if isinstance(decorator, ast.Call) and ast.unparse(decorator.func).endswith(NOT_GET) \
and decorator.args[0].value not in READS_ONLY:
found.append((filename, decorator.args[0].value, node.name))
return found
ROUTES = routes_that_change_something()
def load_check():
node = functions("manager_server.py").get(CHECK)
assert node is not None, "manager_server.py has no " + CHECK
namespace = {"web": web}
exec(compile(ast.Module(body=[node], type_ignores=[]), "manager_server.py", "exec"), namespace)
return namespace[CHECK]
def load_handler(filename, name):
routes = web.RouteTableDef()
namespace = {"web": web, "routes": routes, "PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)),
CHECK: load_check()}
defined = functions(filename)
defined.pop(CHECK, None)
exec(compile(ast.Module(body=list(defined.values()), type_ignores=[]), filename, "exec"), namespace)
return namespace[name]
def test_the_routes_are_found():
routes = {route for _, route, _ in ROUTES}
assert len(ROUTES) >= 28
assert {"/manager/queue/install", "/manager/queue/reinstall", "/manager/queue/update_all", "/manager/db_mode",
"/comfyui_manager/comfyui_switch_version", "/manager/share", "/manager/share_option"} <= routes
assert {"/manager/queue/start", "/manager/queue/reset", "/manager/queue/update_comfyui", "/snapshot/save",
"/manager/reboot"} <= routes
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/octet-stream"])
@pytest.mark.parametrize("filename, route, name", ROUTES, ids=[route for _, route, _ in ROUTES])
def test_a_route_refuses_a_request_that_is_not_json_before_anything_else(filename, route, name, content_type):
read = []
async def read_json():
read.append(True)
return {}
request = SimpleNamespace(content_type=content_type, json=read_json)
try:
response = load_handler(filename, name)(request)
if asyncio.iscoroutine(response):
response = asyncio.run(response)
except NameError as error:
pytest.fail("the handler went on to use `%s`" % error.name)
assert response.status == 400
assert "application/json" in response.text
assert read == []
def answer(content_type):
check = load_check()
async def handler(request):
return check(request) or web.Response(status=200)
async def post():
app = web.Application()
app.router.add_post("/", handler)
async with TestClient(TestServer(app)) as client:
headers = {} if content_type is None else {"Content-Type": content_type}
async with client.post("/", data=b'{"value": "x"}', headers=headers, skip_auto_headers=["Content-Type"]) as response:
return response.status
return asyncio.run(post())
@pytest.mark.parametrize("content_type", NOT_JSON, ids=[repr(c) for c in NOT_JSON])
def test_a_content_type_that_is_not_json_is_refused(content_type):
assert answer(content_type) == 400
@pytest.mark.parametrize("content_type", JSON)
def test_json_is_accepted_with_any_parameters_and_in_any_case(content_type):
assert answer(content_type) == 200
def script_calls():
found = []
for path in sorted(JS_DIR.glob("*.js")):
source = path.read_text(encoding="utf-8")
for match in re.finditer(r"\bfetch(?:Api|Data)\(", source):
pos, depth, commas = match.end(), 1, []
while depth:
skipped = _skip_literal(source, pos)
if skipped != pos:
pos = skipped
continue
depth += {"(": 1, "[": 1, "{": 1, ")": -1, "]": -1, "}": -1}.get(source[pos], 0)
if source[pos] == "," and depth == 1:
commas.append(pos)
pos += 1
options = source[commas[0] + 1:[*commas, pos - 1][1]].strip() if commas else ""
found.append((path.name, source.count("\n", 0, match.start()) + 1, source[match.start():pos], options))
return found
PASSES_ITS_OPTIONS_ON = [("common.js", "fetchData(route, options)"), ("common.js", "fetchApi(route, options)")]
def test_the_options_of_a_call_are_written_where_it_is_made():
assert [(name, call) for name, _, call, options in script_calls()
if options and not options.startswith("{")] == PASSES_ITS_OPTIONS_ON
def calls_that_post():
return [(name, line, call) for name, line, call, _ in script_calls()
if re.search(r"""['"]?\bbody\b['"]?\s*[:,}]|\bmethod\s*:\s*['"](?!GET)""", call)
and not any(route in call for route in READS_ONLY)]
CALLS = calls_that_post()
def test_the_calls_are_found():
assert len(CALLS) >= 36
@pytest.mark.parametrize("name, line, call", CALLS, ids=["%s:%d" % (name, line) for name, line, _ in CALLS])
def test_a_script_that_posts_names_json(name, line, call):
assert re.search(r"""['"]Content-Type['"]\s*:\s*['"]application/json['"]""", call), call
+290
View File
@@ -0,0 +1,290 @@
import configparser
import importlib.util
import os
import shutil
import pytest
from manager_test_utils import GLOB_DIR
PREFERENCES = {
"security_level": "strong", "network_mode": "private", "db_mode": "local", "preview_method": "taesd",
"share_option": "none", "component_policy": "mine", "update_policy": "nightly-comfyui", "use_uv": "True",
"file_logging": "False", "always_lazy_install": "True", "default_cache_as_channel_url": "True",
"model_download_by_agent": "True", "downgrade_blacklist": "diffusers, kornia",
"windows_selector_event_loop_policy": "True",
}
LEFT_BEHIND = ["allow_git_url_install", "allow_pip_install", "allow_flagged_nodepack_install",
"channel_url", "http_channel_enabled", "bypass_ssl", "git_exe"]
@pytest.fixture
def migration(tmp_path):
spec = importlib.util.spec_from_file_location("_manager_migration", GLOB_DIR / "manager_migration.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.legacy = tmp_path / "user" / "default" / "ComfyUI-Manager" / "config.ini"
module.new = tmp_path / "user" / "__manager" / "config.ini"
module.legacy.parent.mkdir(parents=True)
return module
def migrated(migration, text):
migration.legacy.write_text(text, encoding="utf-8")
migration._migrate_config_with_security_check(str(migration.legacy), str(migration.new))
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(migration.new, encoding="utf-8")
assert config.sections() in ([], ["default"])
assert not config.defaults()
return dict(config["default"]) if "default" in config else {}
def section(settings):
return "[default]\n" + "".join(f"{key} = {value}\n" for key, value in settings.items())
def test_preferences_are_migrated_as_they_were_written(migration, capsys):
assert migrated(migration, section(PREFERENCES)) == PREFERENCES
assert "not migrated" not in capsys.readouterr().out
assert migration.startup_notices == []
@pytest.mark.parametrize("value", ["True", "true", "1", "yes", "https://channel.example/list", "/usr/bin/other-git"])
@pytest.mark.parametrize("key", LEFT_BEHIND)
def test_a_setting_that_permits_an_install_or_changes_the_source_is_left_behind(migration, capsys, key, value):
assert migrated(migration, section({**PREFERENCES, key: value})) == PREFERENCES
assert key in capsys.readouterr().out
assert [level for _, level in migration.startup_notices] == ["warning"]
AS_WRITTEN = {
"allow_git_url_install": "False", "allow_pip_install": "False", "allow_flagged_nodepack_install": "False",
"http_channel_enabled": "False", "bypass_ssl": "False", "git_exe": "",
"channel_url": "https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main",
}
@pytest.mark.parametrize("settings", [AS_WRITTEN, {key: value.upper() for key, value in AS_WRITTEN.items() if value in ("False",)},
{key: value.lower() for key, value in AS_WRITTEN.items() if value in ("False",)}],
ids=["as written", "upper case", "lower case"])
def test_a_setting_that_was_never_changed_is_left_behind_without_a_warning(migration, capsys, settings):
assert migrated(migration, section({**PREFERENCES, **settings})) == PREFERENCES
assert "not migrated" not in capsys.readouterr().out
assert migration.startup_notices == []
@pytest.mark.parametrize("key", LEFT_BEHIND)
def test_one_changed_setting_among_those_never_changed_is_the_one_reported(migration, capsys, key):
changed = "True" if AS_WRITTEN[key] == "False" else "something-else"
assert migrated(migration, section({**PREFERENCES, **AS_WRITTEN, key: changed})) == PREFERENCES
printed = capsys.readouterr().out
assert f"['{key}']" in printed
assert len(migration.startup_notices) == 1
@pytest.mark.parametrize("key", ["ALLOW_GIT_URL_INSTALL", "Allow_Pip_Install", "allow_git_url_install ", "CHANNEL_URL"],
ids=["upper case", "mixed case", "trailing space", "upper case channel"])
def test_a_setting_is_left_behind_however_its_name_is_written(migration, key):
assert migrated(migration, section({**PREFERENCES, key: "True"})) == PREFERENCES
@pytest.mark.parametrize("text", [
"[DEFAULT]\nallow_git_url_install = True\n[default]\ndb_mode = local\n",
"[DEFAULT]\nallow_git_url_install = True\ndb_mode = local\n[default]\n",
"[default]\ndb_mode = local\nallow_git_url_install: True\n",
"[default]\ndb_mode = local\n[other]\nallow_git_url_install = True\n",
"[default]\ndb_mode = local\n[default2]\nallow_pip_install = True\n",
], ids=["in the DEFAULT section", "all in the DEFAULT section", "with a colon", "in another section",
"in a section of a similar name"])
def test_a_setting_is_left_behind_wherever_the_file_has_it(migration, text):
assert migrated(migration, text) == {"db_mode": "local"}
@pytest.mark.parametrize("value", ["True", "False", ""])
@pytest.mark.parametrize("key", ["a_setting_of_a_later_version", "allow_everything", "security_level2", "x"])
def test_a_setting_that_is_not_known_is_left_behind(migration, key, value):
assert migrated(migration, section({**PREFERENCES, key: value})) == PREFERENCES
def test_all_of_them_at_once_leave_only_the_preferences(migration, capsys):
assert migrated(migration, section({**PREFERENCES, **{key: "True" for key in LEFT_BEHIND}})) == PREFERENCES
printed = capsys.readouterr().out
assert all(key in printed for key in LEFT_BEHIND)
assert len(migration.startup_notices) == 1
@pytest.mark.parametrize("name", ["<img src=x onerror=alert(1)>", "<b>bold</b>", "a&b", "\x1b[2Jcleared"],
ids=["an element", "a tag", "an ampersand", "an escape sequence"])
def test_the_text_of_the_file_does_not_reach_the_notice_or_the_terminal_as_written(migration, capsys, name):
assert migrated(migration, section({name: "True", "db_mode": "local"})) == {"db_mode": "local"}
message, _ = migration.startup_notices[0]
assert name.lower() not in message.lower()
assert "\x1b" not in capsys.readouterr().out
@pytest.mark.parametrize("level", ["\x1b[2Jcleared", "strong\x1b[31m", "\x07"], ids=["an escape sequence", "after a level", "a bell"])
def test_a_security_level_with_a_control_character_does_not_reach_the_terminal_as_written(migration, capsys, level):
migrated(migration, section({"security_level": level}))
printed = capsys.readouterr().out
assert "\x1b" not in printed and "\x07" not in printed
@pytest.mark.parametrize("level, expected", [("weak", "normal"), ("normal-", "normal"), ("WEAK", "normal"),
("normal", "normal"), ("strong", "strong")])
def test_a_security_level_below_normal_is_raised(migration, level, expected):
assert migrated(migration, section({"security_level": level, "allow_git_url_install": "True"})) == {"security_level": expected}
@pytest.mark.parametrize("value", ["100%", "%(db_mode)s", "a%%b", "50% off", "%"])
@pytest.mark.parametrize("key", sorted(set(PREFERENCES) - {"security_level"}))
def test_a_value_with_a_percent_sign_is_migrated_as_it_was_written(migration, key, value):
assert migrated(migration, section({**PREFERENCES, key: value})) == {**PREFERENCES, key: value}
@pytest.mark.parametrize("level", ["100%", "%(downgrade_blacklist)s", "%(db_mode)s%(share_option)s", "storng", "high", "normal+", "0",
"<b>weak</b>", "wea k", "weak,normal"])
def test_a_security_level_that_is_not_one_is_back_at_normal_and_no_other_setting_with_it(migration, capsys, level):
settings = {**PREFERENCES, "security_level": level}
assert migrated(migration, section(settings)) == {**settings, "security_level": "normal"}
assert "is not a security level" in capsys.readouterr().out
assert [level in message for message, _ in migration.startup_notices] == [False]
def test_a_legacy_file_without_a_security_level_gets_none(migration):
assert migrated(migration, section({"db_mode": "local"})) == {"db_mode": "local"}
@pytest.mark.parametrize("text", ["", "\n", "[other]\ndb_mode = local\n"], ids=["empty", "a newline", "no default section"])
def test_a_file_without_settings_migrates_none(migration, text):
assert migrated(migration, text) == {}
@pytest.mark.parametrize("text", ["db_mode = local\n", "[default\ndb_mode = local\n", "[default]\n[default]\n"],
ids=["no section", "an unclosed section", "a section twice"])
def test_a_file_that_cannot_be_parsed_is_not_migrated(migration, text):
assert migrated(migration, text) == {}
assert not migration.new.exists()
def test_the_migration_of_the_legacy_directory_leaves_the_install_settings_behind(migration, tmp_path, monkeypatch):
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
migration.legacy.write_text(section({**PREFERENCES, **{key: "True" for key in LEFT_BEHIND}}), encoding="utf-8")
assert migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent)) is True
config = configparser.ConfigParser(interpolation=None)
config.read(migration.new, encoding="utf-8")
assert dict(config["default"]) == PREFERENCES
assert not migration.legacy.exists()
def test_an_earlier_backup_of_the_legacy_directory_is_kept(migration, tmp_path, monkeypatch):
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
backups = [migration.new.parent / ".legacy-manager-backup", migration.new.parent / ".legacy-manager-backup-2",
migration.new.parent / ".legacy-manager-backup-3"]
for number, backup in enumerate(backups):
migration.legacy.parent.mkdir(parents=True, exist_ok=True)
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
(migration.legacy.parent / "kept.txt").write_text(str(number), encoding="utf-8")
assert migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent)) is True
assert not migration.legacy.parent.exists()
assert [(b / "kept.txt").read_text(encoding="utf-8") for b in backups[:number + 1]] == [str(n) for n in range(number + 1)]
@pytest.mark.parametrize("backups", [[".legacy-manager-backup"], [".legacy-manager-backup-2"],
[".legacy-manager-backup", ".legacy-manager-backup-2", ".legacy-manager-backup-3"]],
ids=["the first backup", "only a later backup", "three backups"])
def test_a_start_reminds_of_every_backup_that_is_there(migration, capsys, backups):
for name in backups:
(migration.new.parent / name).mkdir(parents=True)
migration.check_legacy_backup(str(migration.new.parent))
printed = capsys.readouterr().out
assert [line.strip() for line in printed.splitlines() if ".legacy-manager-backup" in line] == \
[str(migration.new.parent / name) for name in backups]
assert [level for _, level in migration.startup_notices] == ["info"]
@pytest.mark.parametrize("there", [False, True], ids=["no data directory", "a data directory without a backup"])
def test_a_start_without_a_backup_reminds_of_nothing(migration, capsys, there):
if there:
migration.new.parent.mkdir(parents=True)
migration.new.write_text(section({"db_mode": "local"}), encoding="utf-8")
migration.check_legacy_backup(str(migration.new.parent))
assert capsys.readouterr().out == ""
assert migration.startup_notices == []
NAMES = ["kept.txt", "<img src=x>.json", "a&b.json", "\x1b[2Jcleared.json", "a'b\"c.json"]
@pytest.mark.parametrize("error", [
*[lambda path, name=name: PermissionError(13, "Permission denied", path + name) for name in NAMES],
lambda path: OSError("cannot move \x1b[2J" + path),
lambda path: shutil.Error([(path + "\x1b[2Ja.json", path + "b.json", "[Errno 13] Permission denied: \x07")]),
], ids=["a plain name", "an element", "an ampersand", "an escape sequence", "quotes", "a text with an escape sequence",
"the errors of a copy"])
def test_a_backup_that_fails_is_reported_without_the_text_of_the_error(migration, monkeypatch, capsys, error):
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
error = error(str(migration.legacy.parent) + "/")
def move(source, destination):
raise error
monkeypatch.setattr(shutil, "move", move)
assert migration._move_legacy_to_backup(str(migration.legacy.parent), str(migration.new.parent)) is None
assert migration.startup_notices == [("[MIGRATION] Failed to backup legacy directory. See terminal for details.", "warning")]
printed = capsys.readouterr().out
assert "Failed to backup legacy directory: " + repr(str(error)) in printed
assert "\x1b" not in printed and "\x07" not in printed
assert migration.legacy.exists()
@pytest.mark.skipif(os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), reason="needs a file that cannot be read")
def test_a_copy_that_fails_leaves_the_legacy_directory_and_no_part_of_a_backup(migration, tmp_path, monkeypatch):
monkeypatch.setattr(migration, "has_system_user_api", lambda: True)
monkeypatch.setattr(os, "rename", lambda source, destination: (_ for _ in ()).throw(OSError(18, "Invalid cross-device link")))
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
(migration.legacy.parent / "kept.txt").write_text("kept", encoding="utf-8")
unreadable = migration.legacy.parent / "unreadable.json"
unreadable.write_text("{}", encoding="utf-8")
unreadable.chmod(0)
for _ in range(3):
migration.migrate_legacy_config(str(tmp_path / "user"), str(migration.new.parent))
assert sorted(path.name for path in migration.legacy.parent.iterdir()) == ["config.ini", "kept.txt", "unreadable.json"]
assert [path.name for path in migration.new.parent.iterdir() if path.name.startswith(".legacy-manager-backup")] == []
unreadable.chmod(0o600)
def test_a_backup_that_was_copied_is_kept_when_the_legacy_directory_cannot_be_removed(migration, monkeypatch):
monkeypatch.setattr(os, "rename", lambda source, destination: (_ for _ in ()).throw(OSError(18, "Invalid cross-device link")))
migration.legacy.write_text(section({"db_mode": "local"}), encoding="utf-8")
(migration.legacy.parent / "kept.txt").write_text("kept", encoding="utf-8")
migration.new.parent.mkdir(parents=True)
def rmtree(path, *args, **kwargs):
raise PermissionError(13, "Permission denied", str(path))
monkeypatch.setattr(shutil, "rmtree", rmtree)
assert migration._move_legacy_to_backup(str(migration.legacy.parent), str(migration.new.parent)) is None
backup = migration.new.parent / ".legacy-manager-backup"
assert sorted(path.name for path in backup.iterdir()) == ["config.ini", "kept.txt"]
assert (backup / "kept.txt").read_text(encoding="utf-8") == "kept"
+79 -2
View File
@@ -2,10 +2,14 @@
A logger that always answered "not a terminal" made colorama, and any other library that
asks, strip its colors and hide its progress display for the whole session.
The last cases are about what is written once the log file is closed: the restart under
comfy-cli closes it and then exits, and what is logged on the way out must not fail.
"""
import ast
import io
import textwrap
import threading
from pathlib import Path
from types import SimpleNamespace
@@ -35,15 +39,53 @@ class StreamThatCannotBeAsked:
raise OSError("The handle is invalid")
def loggers(stdout, stderr, log_closed=False):
class LogFile:
def __init__(self, closed=False):
self.closed = closed
self.written = []
def write(self, text):
if self.closed:
raise ValueError("I/O operation on closed file.")
self.written.append(text)
def flush(self):
pass
def loggers(stdout, stderr, log_closed=False, **module_globals):
"""Lift ComfyUIManagerLogger; importing prestartup_script would run the startup."""
source = SOURCE.read_text(encoding="utf-8")
node = next(n for n in ast.walk(ast.parse(source)) if isinstance(n, ast.ClassDef) and n.name == "ComfyUIManagerLogger")
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed)}
scope = {"original_stdout": stdout, "original_stderr": stderr, "log_file": SimpleNamespace(closed=log_closed),
**module_globals}
exec(textwrap.dedent("\n".join(source.splitlines()[node.lineno - 1:node.end_lineno])), scope)
return scope["ComfyUIManagerLogger"](True), scope["ComfyUIManagerLogger"](False)
def close_logs(log_file, log_lock):
"""The two ways to close the log file: the logger's method, and the function run at exit."""
source = SOURCE.read_text(encoding="utf-8")
tree = ast.parse(source)
in_class = {id(n) for c in ast.walk(tree) if isinstance(c, ast.ClassDef) for n in ast.walk(c)}
function = next(n for n in ast.walk(tree)
if isinstance(n, ast.FunctionDef) and n.name == "close_log" and id(n) not in in_class)
scope = {"sys": SimpleNamespace(), "original_stdout": None, "original_stderr": None,
"log_file": log_file, "log_lock": log_lock}
exec(textwrap.dedent("\n".join(source.splitlines()[function.lineno - 1:function.end_lineno])), scope)
out, _ = loggers(None, None, **{name: scope[name] for name in ("sys", "log_file", "log_lock")})
return out.close_log, scope["close_log"]
def writing_logger(log_file):
"""The stderr logger with what its writes need, and the list of what reached the console."""
console = []
stream = SimpleNamespace(flush=lambda: None)
_, err = loggers(stream, stream, log_file=log_file, log_lock=threading.Lock(), std_log_lock=threading.Lock(),
current_timestamp=lambda: "12:00:00", write_stdout=console.append, write_stderr=console.append)
return err, console
@pytest.fixture
def ansitowin32(monkeypatch):
"""colorama's stream wrapper, with its probe of the Windows console answered.
@@ -121,3 +163,38 @@ def test_colorama_keeps_ansi_codes_only_on_a_terminal(ansitowin32, stream, kept)
out, _ = loggers(stream, stream)
assert ansitowin32.AnsiToWin32(out).strip is (not kept)
def test_open_log_file_gets_what_is_written():
log_file = LogFile()
logger, console = writing_logger(log_file)
logger.sync_write("first\n")
logger.sync_write("logged only\n", file_only=True)
assert log_file.written == ["first\n", "[12:00:00] logged only\n"]
assert console == ["first\n"]
def test_closed_log_file_is_left_alone():
log_file = LogFile(closed=True)
logger, console = writing_logger(log_file)
# what the logging handler does with a record that arrives after close_log()
logger.sync_write("logged only\n", file_only=True)
logger.sync_write("still shown\n")
assert log_file.written == []
assert console == ["still shown\n"]
@pytest.mark.parametrize("which", [0, 1])
def test_log_file_is_closed_under_the_lock_of_the_writes(which):
log_lock = threading.Lock()
held = []
log_file = SimpleNamespace(close=lambda: held.append(log_lock.locked()))
close_logs(log_file, log_lock)[which]()
# a write checks that the file is open and writes to it under this lock
assert held == [True]
+1 -1
View File
@@ -14,7 +14,7 @@ IMPORT DISCIPLINE (load-bearing, see tests/conftest.py):
- `glob/manager_server.py` starts a network thread at import and needs the
ComfyUI stack, so it is NEVER imported. `convert_markdown_to_html` is
AST-extracted and executed in an isolated namespace instead — the same
technique tests/test_csrf_content_type_helper.py already uses in this repo.
technique tests/test_json_body_content_type.py already uses in this repo.
"""
import unittest
+305
View File
@@ -0,0 +1,305 @@
import ast
import asyncio
import json
import mimetypes
import os
import sys
from types import ModuleType, SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
MATRIX_ORG = "https://matrix.org"
SAVED = ("matrix.org", "user", "the saved password")
PASSWORDS_THAT_LOG_IN = {SAVED[2], "a new password"}
FUNCTIONS = ("is_matrix_org", "get_matrix_auth", "set_matrix_auth", "api_get_matrix_auth", "share_art")
class LoginResponse:
access_token = "token"
class UploadResponse:
content_uri = "mxc://test/asset"
@pytest.fixture
def manager(monkeypatch, tmp_path):
logins = []
class AsyncClient:
def __init__(self, homeserver, username):
self.homeserver, self.username = homeserver, username
async def login(self, password):
logins.append((self.homeserver, self.username, password))
return LoginResponse() if password in PASSWORDS_THAT_LOG_IN else None
async def upload(self, data, content_type=None, filename=None):
return UploadResponse(), None
async def room_send(self, **kwargs):
pass
async def close(self):
pass
nio = ModuleType("nio")
nio.AsyncClient, nio.LoginResponse, nio.UploadResponse = AsyncClient, LoginResponse, UploadResponse
monkeypatch.setitem(sys.modules, "nio", nio)
files = tmp_path / "manager"
output_dir = tmp_path / "output"
files.mkdir()
output_dir.mkdir()
(output_dir / "a.png").write_bytes(b"output image")
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in FUNCTIONS]
assert len(nodes) == len(FUNCTIONS)
namespace = {
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
get_temp_directory=lambda: str(tmp_path / "temp")),
"core": SimpleNamespace(manager_files_path=str(files)),
"os": os, "web": web, "json": json, "mimetypes": mimetypes,
"_reject_non_json_content_type": lambda request: None,
}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
return SimpleNamespace(file=files / "matrix_auth", logins=logins, **{name: namespace[name] for name in FUNCTIONS})
def share(manager, matrix_auth, destinations=("matrix",)):
body = {
"matrix_auth": matrix_auth, "share_destinations": list(destinations),
"credits": "", "title": "", "description": "", "prompt": {"workflow": {}}, "selected_output_index": 0,
"potential_outputs": [{"type": "image", "image": {"filename": "a.png", "subfolder": "", "type": "output"}}],
}
async def read_json():
return body
try:
return asyncio.run(manager.share_art(SimpleNamespace(json=read_json))).status
except Exception:
return 500
def account(homeserver=SAVED[0], username=SAVED[1], password=""):
return {"homeserver": homeserver, "username": username, "password": password}
MATRIX_ORG_FORMS = ["matrix.org", "https://matrix.org", "http://matrix.org"]
OTHER_HOMESERVERS = [
"matrix.example", "matrix.org.example", "sub.matrix.org", "matrix", "org", "Matrix.org", "MATRIX.ORG",
"matrix.org/", "matrix.org.", " matrix.org", "matrix.org ", "matrix.org:8448", "matrix.org:443",
"user@matrix.org", "matrix.org@other.example", "other.example/matrix.org", "other.example#matrix.org",
"other.example?matrix.org", "https://other.example", "http://other.example", "https://https://matrix.org",
"ftp://matrix.org", "//matrix.org", "matrix.org\\other.example", "matrix.org\nother.example", "127.0.0.1", "localhost:8188",
]
@pytest.mark.parametrize("text", [
"matrix.org\nuser\nthe saved password",
"matrix.org\nuser\nthe saved password\n",
"\n\nmatrix.org\nuser\nthe saved password\n\n",
], ids=["three lines", "a final newline", "blank lines around"])
def test_the_answer_has_the_homeserver_and_the_username(manager, text):
manager.file.write_text(text)
response = asyncio.run(manager.api_get_matrix_auth(None))
assert response.status == 200
assert json.loads(response.text) == {"homeserver": "matrix.org", "username": "user"}
@pytest.mark.parametrize("text", [
None, "", "matrix.org\nuser", "matrix.org\nuser\nthe saved password\nmore",
"matrix.org\n\nthe saved password", "matrix.org\nuser\n", "\nuser\nthe saved password",
], ids=["no file", "an empty file", "two lines", "four lines", "an empty username", "an empty password",
"an empty homeserver"])
def test_a_file_that_is_not_an_account_is_answered_as_nothing_saved(manager, text):
if text is not None:
manager.file.write_text(text)
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
assert share(manager, account()) == 400
assert manager.logins == [(MATRIX_ORG, "user", "")]
@pytest.mark.parametrize("homeserver", [h for h in OTHER_HOMESERVERS if h == h.strip() and "\n" not in h])
def test_an_account_saved_for_another_homeserver_is_not_used(manager, homeserver):
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
manager.file.write_text(text)
assert asyncio.run(manager.api_get_matrix_auth(None)).status == 404
assert share(manager, account()) == 400
assert manager.logins == [(MATRIX_ORG, "user", "")]
assert manager.file.read_text() == text
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS[1:])
def test_matrix_org_saved_with_a_scheme_is_the_saved_account(manager, homeserver):
text = "\n".join((homeserver, SAVED[1], SAVED[2]))
manager.file.write_text(text)
assert json.loads(asyncio.run(manager.api_get_matrix_auth(None)).text) == {"homeserver": homeserver, "username": "user"}
assert share(manager, account()) == 200
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
@pytest.mark.parametrize("password", ["", None], ids=["empty", "null"])
def test_no_password_for_the_saved_account_logs_in_with_the_saved_one(manager, password):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(password=password)) == 200
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("matrix_auth", [
*(account(homeserver) for homeserver in MATRIX_ORG_FORMS), {"username": "user", "password": ""},
], ids=[*MATRIX_ORG_FORMS, "no homeserver field"])
def test_matrix_org_is_logged_in_however_the_request_writes_it(manager, matrix_auth):
manager.file.write_text("\n".join(SAVED))
assert share(manager, matrix_auth) == 200
assert manager.logins == [(MATRIX_ORG, "user", SAVED[2])]
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("homeserver", OTHER_HOMESERVERS + [""])
@pytest.mark.parametrize("password", ["", "a new password"], ids=["no password", "a password that logs in"])
def test_another_homeserver_is_refused_before_any_login(manager, homeserver, password):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(homeserver, password=password)) == 400
assert manager.logins == []
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("username", ["User", "user ", " user", "user2", "use", ""],
ids=["upper case", "trailing space", "leading space", "longer", "shorter", "empty"])
def test_a_username_written_otherwise_is_another_account(manager, username):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(username=username)) == 400
assert manager.logins == [(MATRIX_ORG, username, "")]
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("homeserver", MATRIX_ORG_FORMS)
def test_a_password_that_logs_in_replaces_the_saved_account(manager, homeserver):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(homeserver, "someone", "a new password")) == 200
assert manager.logins == [(MATRIX_ORG, "someone", "a new password")]
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
@pytest.mark.parametrize("password", ["a wrong password", " "], ids=["wrong", "a space"])
def test_a_password_that_does_not_log_in_leaves_the_saved_account(manager, password):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(password=password)) == 400
assert manager.logins == [(MATRIX_ORG, "user", password)]
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("homeserver", ["matrix.org", "other.example"])
def test_sharing_without_matrix_leaves_the_saved_account(manager, homeserver):
manager.file.write_text("\n".join(SAVED))
assert share(manager, account(homeserver), destinations=()) == 200
assert manager.logins == []
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.parametrize("matrix_auth", [
None, [], {}, {"homeserver": "matrix.org", "username": "user"},
{"homeserver": None, "username": "user", "password": ""},
{"homeserver": ["matrix.org"], "username": "user", "password": ""},
{"homeserver": 1, "username": "user", "password": ""},
{"homeserver": "matrix.org", "username": None, "password": None},
{"homeserver": "matrix.org", "username": 1, "password": 0},
], ids=["null", "a list", "no fields", "no password field", "null homeserver", "a list as homeserver",
"a number as homeserver", "null username", "numbers"])
def test_a_malformed_account_leaves_the_saved_account(manager, matrix_auth):
manager.file.write_text("\n".join(SAVED))
assert share(manager, matrix_auth) >= 400
assert SAVED[2] not in [login[2] for login in manager.logins]
assert all(login[0] == MATRIX_ORG for login in manager.logins)
assert manager.file.read_text() == "\n".join(SAVED)
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
@pytest.mark.parametrize("umask", [0o022, 0o002, 0o000])
@pytest.mark.parametrize("before", [None, 0o664, 0o644, 0o600], ids=["no file", "0664", "0644", "0600"])
def test_the_saved_account_is_a_file_of_its_user_only(manager, before, umask):
if before is not None:
manager.file.write_text("\n".join(SAVED))
manager.file.chmod(before)
previous = os.umask(umask)
try:
assert share(manager, account(username="someone", password="a new password")) == 200
finally:
os.umask(previous)
assert manager.file.stat().st_mode & 0o777 == 0o600
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
def test_the_password_is_written_after_the_file_is_of_its_user_only(manager, monkeypatch):
manager.file.write_text("\n".join(SAVED))
manager.file.chmod(0o644)
seen = []
chmod = os.chmod
def record(path, mode):
chmod(path, mode)
seen.append((manager.file.stat().st_mode & 0o777, manager.file.read_text()))
monkeypatch.setattr(os, "chmod", record)
assert share(manager, account(username="someone", password="a new password")) == 200
assert seen == [(0o600, "\n".join(SAVED))]
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
def test_a_file_whose_mode_cannot_be_set_is_saved_all_the_same(manager, monkeypatch):
manager.file.write_text("\n".join(SAVED))
def refuse(path, mode):
raise PermissionError(1, "Operation not permitted", str(path))
monkeypatch.setattr(os, "chmod", refuse)
assert share(manager, account(username="someone", password="a new password")) == 200
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
@pytest.mark.skipif(os.name == "nt", reason="the mode of a file is not kept on Windows")
def test_a_new_file_is_of_its_user_only_from_the_moment_it_is_made(manager, monkeypatch):
seen = []
monkeypatch.setattr(os, "chmod", lambda path, mode: seen.append(manager.file.stat().st_mode & 0o777))
previous = os.umask(0)
try:
assert share(manager, account(username="someone", password="a new password")) == 200
finally:
os.umask(previous)
assert seen == [0o600]
assert manager.file.stat().st_mode & 0o777 == 0o600
def test_a_shorter_account_replaces_a_longer_one_whole(manager):
manager.file.write_text("matrix.org\n" + "a" * 200 + "\nthe saved password")
assert share(manager, account(username="someone", password="a new password")) == 200
assert manager.file.read_text() == "matrix.org\nsomeone\na new password"
+112
View File
@@ -0,0 +1,112 @@
import ast
import configparser
import json
import subprocess
import sys
import textwrap
from types import SimpleNamespace
import pytest
from manager_test_utils import GLOB_DIR
LEVELS = ["strong", "normal", "normal-", "weak"]
SOURCE = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
GATE = next(node for node in ast.parse(SOURCE).body
if isinstance(node, ast.FunctionDef) and node.name == "is_allowed_security_level")
def allowed(needed, security_level, loopback, has_system_user_api):
namespace = {
"is_local_mode": loopback,
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level}),
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
}
exec(compile(ast.Module(body=[GATE], type_ignores=[]), "manager_server.py", "exec"), namespace)
return namespace["is_allowed_security_level"](needed)
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS + ["", "a level that Manager does not know"])
@pytest.mark.parametrize("needed", ["middle", "high", "block", "low", ""])
def test_an_old_comfyui_is_refused_at_every_level_of_config_ini(needed, security_level, loopback):
assert allowed(needed, security_level, loopback, has_system_user_api=False) is False
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_with_the_system_user_api_the_level_of_config_ini_decides(security_level, loopback):
api = dict(security_level=security_level, loopback=loopback, has_system_user_api=True)
assert allowed("block", **api) is False
assert allowed("middle", **api) is (security_level != "strong")
assert allowed("high", **api) is (security_level == "weak" or security_level == "normal-" and loopback)
assert allowed("low", **api) is True
CHILD = textwrap.dedent(
"""
import sys, types, tempfile, os, json
tmp = tempfile.mkdtemp(prefix="cm_old_comfyui_")
stub = types.ModuleType("folder_paths")
stub.get_user_directory = lambda: tmp
if {has_system_user_api!r}:
stub.get_system_user_directory = lambda *a, **k: os.path.join(tmp, "sysuser")
sys.modules["folder_paths"] = stub
sys.path.insert(0, {glob_dir!r})
import manager_core
path = os.path.join(tmp, "config.ini")
manager_core.manager_config_path = path
manager_core.cached_config = None
written = {written!r}
if written is not None:
with open(path, "w") as f:
f.write(written)
read = manager_core.get_config()["security_level"]
for key, value in {changes!r}:
manager_core.get_config()[key] = value
manager_core.write_config()
with open(path) as f:
print(json.dumps({{"read": read, "file": f.read()}}))
"""
)
def config_after_a_write(has_system_user_api, written, changes=()):
script = CHILD.format(has_system_user_api=has_system_user_api, glob_dir=str(GLOB_DIR), written=written, changes=list(changes))
done = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=180)
assert done.returncode == 0, done.stderr[-2000:]
result = json.loads(done.stdout.strip().splitlines()[-1])
config = configparser.ConfigParser(strict=False)
config.read_string(result["file"])
return result["read"], dict(config["default"])
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
def test_the_first_config_ini_is_written_with_the_default_level(has_system_user_api):
read, written = config_after_a_write(has_system_user_api, None)
assert read == "normal"
assert written["security_level"] == "normal"
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_the_level_of_config_ini_is_read_and_kept_as_the_user_wrote_it(security_level, has_system_user_api):
text = f"[default]\nsecurity_level = {security_level}\ndb_mode = cache\n"
read, written = config_after_a_write(has_system_user_api, text, changes=[("db_mode", "local")])
assert read == security_level
assert written["security_level"] == security_level
assert written["db_mode"] == "local"
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
def test_a_config_ini_without_a_level_is_not_given_one_by_another_setting(has_system_user_api):
read, written = config_after_a_write(has_system_user_api, "[default]\ndb_mode = cache\n", changes=[("db_mode", "local")])
assert read == "normal"
assert "security_level" not in written
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
def test_a_config_ini_that_cannot_be_parsed_is_rewritten_with_the_default_level(has_system_user_api):
read, written = config_after_a_write(has_system_user_api, "security_level = weak\n")
assert read == "normal"
assert written["security_level"] == "normal"
+179
View File
@@ -0,0 +1,179 @@
import ast
import asyncio
from types import SimpleNamespace
import pytest
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from manager_test_utils import GLOB_DIR
SERVED = {
("POST", "/manager/queue/update_comfyui"), ("POST", "/manager/queue/start"), ("POST", "/manager/queue/reset"),
("GET", "/manager/queue/status"), ("GET", "/manager/version"), ("GET", "/manager/notice"),
("GET", "/manager/startup_alerts"),
}
OTHERS = [("GET", "/system_stats", "server"), ("POST", "/prompt", "server"), ("POST", "/a_pack/run", "a_pack.routes"),
("GET", "/manager/of_another_pack", "another_manager")]
PREFIXES = ["", "/api"]
def routes_of(path):
found = []
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
for decorator in getattr(node, "decorator_list", []):
if isinstance(decorator, ast.Call) and ast.unparse(decorator.func).endswith(("routes.get", "routes.post")):
found.append((decorator.func.attr.upper(), decorator.args[0].value, path.stem, node.name))
return found
ROUTES = [route for path in sorted(GLOB_DIR.glob("*.py")) for route in routes_of(path)]
REQUESTS = [(prefix, method, path) for prefix in PREFIXES for method, path, _, _ in ROUTES]
def serve(has_system_user_api):
ran = []
def recording(method, path, module):
async def handler(request):
ran.append((method, path))
return web.Response(text="served")
handler.__module__ = module
return handler
handlers = {(module, name): recording(method, path, module) for method, path, module, name in ROUTES}
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if getattr(node, "name", None) in ("security_403_response", "serve_only_comfyui_update")
or isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "COMFYUI_UPDATE_HANDLERS"
or isinstance(node, ast.If) and "middlewares" in ast.unparse(node)]
middlewares = []
namespace = {
"web": web, "manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
"PromptServer": SimpleNamespace(instance=SimpleNamespace(app=SimpleNamespace(middlewares=middlewares))),
"threading": SimpleNamespace(Thread=lambda target: SimpleNamespace(start=lambda: None)),
**{name: handler for (module, name), handler in handlers.items() if module == "manager_server"},
}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "manager_server.py", "exec"), namespace)
app = web.Application(middlewares=middlewares)
for prefix in PREFIXES:
for method, path, module, name in ROUTES:
app.router.add_route(method, prefix + path, handlers[module, name])
for method, path, module in OTHERS:
app.router.add_route(method, prefix + path, recording(method, path, module))
return app, ran, middlewares == [namespace.get("serve_only_comfyui_update")]
def answers(has_system_user_api, requests):
app, ran, added = serve(has_system_user_api)
async def run():
async with TestClient(TestServer(app)) as client:
return [(response.status, await response.text())
for response in [await client.request(method, url) for method, url in requests]]
return asyncio.run(run()), ran, added
def url(path):
return path.replace("{node_name}", "a-pack")
OUTDATED = (403, '{"error": "comfyui_outdated"}')
def test_the_routes_are_found():
found = {(method, path) for method, path, _, _ in ROUTES}
assert len(ROUTES) >= 50
assert SERVED <= found
assert {("POST", "/manager/queue/install"), ("POST", "/manager/reboot"), ("GET", "/customnode/getlist"),
("POST", "/snapshot/restore"), ("GET", "/snapshot/getlist"), ("POST", "/manager/share"),
("GET", "/manager/get_matrix_auth"), ("GET", "/customnode/versions/{node_name}")} <= found
def test_every_route_is_in_a_file_that_the_middleware_knows():
assert {module for _, _, module, _ in ROUTES} == {"manager_server", "share_3rdparty"}
@pytest.mark.parametrize("prefix, method, path", REQUESTS, ids=[f"{method} {prefix}{path}" for prefix, method, path in REQUESTS])
def test_on_an_older_comfyui_only_the_update_of_comfyui_is_served(prefix, method, path):
(answer,), ran, added = answers(False, [(method, prefix + url(path))])
assert added
if (method, path) in SERVED:
assert answer == (200, "served")
assert ran == [(method, path)]
else:
assert answer == OUTDATED
assert ran == []
def test_with_the_system_user_api_every_route_is_served():
requests = [(method, prefix + url(path)) for prefix, method, path in REQUESTS]
got, ran, added = answers(True, requests)
assert not added
assert got == [(200, "served")] * len(REQUESTS)
assert len(ran) == len(REQUESTS)
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
@pytest.mark.parametrize("prefix", PREFIXES, ids=["without a prefix", "under /api"])
def test_routes_that_are_not_of_manager_are_served(prefix, has_system_user_api):
got, ran, _ = answers(has_system_user_api, [(method, prefix + path) for method, path, _ in OTHERS])
assert got == [(200, "served")] * len(OTHERS)
assert ran == [(method, path) for method, path, _ in OTHERS]
@pytest.mark.parametrize("method, path, status", [
("GET", "/manager/no_such_route", 404), ("GET", "/no_such_route", 404), ("GET", "/api/api/manager/version", 404),
("GET", "/manager/queue/start", 405), ("POST", "/api/manager/version", 405), ("DELETE", "/manager/queue/update_comfyui", 405),
], ids=["an unknown route of that prefix", "an unknown route", "the prefix twice", "GET for a served POST",
"POST for a served GET", "another method"])
def test_on_an_older_comfyui_an_unknown_request_is_answered_as_before(method, path, status):
(answer,), ran, _ = answers(False, [(method, path)])
assert answer[0] == status
assert ran == []
@pytest.mark.parametrize("path, served_as", [
("/manager/queue/update_comfyui?x=1", "/manager/queue/update_comfyui"), ("/api/manager/queue/start?mode=cache", "/manager/queue/start"),
("/manager/queue/./start", "/manager/queue/start"),
("/manager/queue/update_comfyui/", None), ("/manager/queue/install?x=/manager/queue/start", None),
("/api/manager/queue/install?x=/api/manager/queue/start", None),
("/manager/queue//start", None), ("/manager/queue/update_all", None), ("/api/manager/queue/update", None),
("/manager/queue/install", None),
], ids=["a query", "a query on start", "a dot segment", "a trailing slash", "a served path in the query",
"a served path in the query under /api", "a doubled slash", "update_all", "update", "install"])
def test_on_an_older_comfyui_a_path_is_served_only_as_a_route_that_updates_comfyui(path, served_as):
(answer,), ran, _ = answers(False, [("POST", path)])
if served_as:
assert answer == (200, "served")
assert ran == [("POST", served_as)]
else:
assert answer[0] in (403, 404)
assert ran == []
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
def test_the_lists_are_fetched_at_the_start_only_with_the_system_user_api(has_system_user_api):
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
statements = [node for node in ast.parse(source).body if isinstance(node, (ast.If, ast.Expr)) and "default_cache_update" in ast.unparse(node)]
assert len(statements) == 1
started = []
exec(compile(ast.Module(body=statements, type_ignores=[]), "manager_server.py", "exec"), {
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
"threading": SimpleNamespace(Thread=lambda target: SimpleNamespace(start=lambda: started.append(target))),
"PromptServer": SimpleNamespace(instance=SimpleNamespace(app=SimpleNamespace(middlewares=[]))),
"serve_only_comfyui_update": None,
})
assert len(started) == (1 if has_system_user_api else 0)
+98
View File
@@ -0,0 +1,98 @@
import ast
import os
import subprocess
from pathlib import Path
from types import SimpleNamespace
import pytest
from manager_test_utils import GLOB_DIR, load_manager_util
MANAGER_UTIL = load_manager_util()
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
LISTED = "a-package==2.0\nanother==1.5 --index-url https://index.example/simple\n"
@pytest.fixture
def fix_broken(monkeypatch, tmp_path):
def run(manager_files_path, installed):
packages = {"torchvision": "0.20.1", "torchaudio": "2.5.1", "comfyui_frontend_package": "1.30.6", **installed}
pip_list = "Package Version\n------- -------\n" + "".join(f"{name} {version}\n" for name, version in packages.items())
commands = []
def check_output(cmd, **_):
if cmd[-1] == "list":
return pip_list
commands.append(" ".join(cmd[3:]))
return ""
monkeypatch.setattr(MANAGER_UTIL, "make_pip_cmd", lambda cmd: ["python", "-m", "pip", *cmd])
monkeypatch.setattr(MANAGER_UTIL, "subprocess", SimpleNamespace(
check_output=check_output, CalledProcessError=subprocess.CalledProcessError))
monkeypatch.setattr(MANAGER_UTIL, "pip_map", None)
(tmp_path / "pip_auto_fix.list").write_text(LISTED, encoding="utf-8")
previous = MANAGER_UTIL.get_installed_packages(True)
MANAGER_UTIL.PIPFixer(previous, str(tmp_path), manager_files_path and str(tmp_path)).fix_broken()
return commands
return run
def test_with_a_data_directory_the_listed_packages_are_restored(fix_broken):
assert fix_broken(True, {"a-package": "1.0"}) == [
"install a-package==2.0", "install another==1.5 --index-url https://index.example/simple"]
@pytest.mark.parametrize("installed", [{"a-package": "1.0"}, {}, {"a-package": "2.0", "another": "1.5"}],
ids=["another version installed", "not installed", "as listed"])
def test_without_a_data_directory_nothing_is_restored_from_a_list(fix_broken, installed):
assert fix_broken(None, installed) == []
@pytest.mark.parametrize("data_directory", [True, None], ids=["with a data directory", "without one"])
def test_a_repair_that_uses_no_list_runs_either_way(fix_broken, data_directory):
assert fix_broken(data_directory, {"comfy": "0.0.1", "a-package": "2.0", "another": "1.5"}) == ["uninstall comfy"]
def directory_given_at_start(has_system_user_api):
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
if isinstance(node, ast.Assign) and "PIPFixer(" in ast.unparse(node)]
assert len(statements) == 1
given = []
namespace = {
"manager_util": SimpleNamespace(get_installed_packages=dict, PIPFixer=lambda previous, comfy_path, path: given.append(path)),
"comfy_path": "comfyui", "manager_files_path": "the data directory", "_has_system_user_api": has_system_user_api,
}
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
return given
def test_a_start_with_the_system_user_api_gives_the_data_directory():
assert directory_given_at_start(True) == ["the data directory"]
def test_a_start_on_an_older_comfyui_gives_no_data_directory():
assert directory_given_at_start(False) == [None]
def directories_given_by_the_server(has_system_user_api):
path = GLOB_DIR / "manager_core.py"
statements = [node for node in ast.walk(ast.parse(path.read_text(encoding="utf-8")))
if isinstance(node, ast.Assign) and "PIPFixer(" in ast.unparse(node)]
given = []
namespace = {
"manager_util": SimpleNamespace(get_installed_packages=dict, PIPFixer=lambda previous, comfy_path, path: given.append(path)),
"manager_migration": SimpleNamespace(has_system_user_api=lambda: has_system_user_api),
"comfy_path": "comfyui", "manager_files_path": "the data directory",
}
exec(compile(ast.Module(body=statements, type_ignores=[]), str(path), "exec"), namespace)
return given
def test_an_install_with_the_system_user_api_gives_the_data_directory():
assert directories_given_by_the_server(True) == ["the data directory", "the data directory"]
def test_an_install_on_an_older_comfyui_gives_no_data_directory():
assert directories_given_by_the_server(False) == [None, None]
+46
View File
@@ -0,0 +1,46 @@
import ast
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
OVERRIDES = [{"a-package": "another-package==2.0"}, {"a-package": "a-package==1.0", "torch": "torch==2.5.1"}, {}]
def overrides_after_start(has_system_user_api, path):
body = ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
first = next(index for index, node in enumerate(body)
if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "cm_global.pip_overrides")
statements = body[first:first + 2]
assert isinstance(statements[1], ast.If) and "manager_pip_overrides_path" in ast.unparse(statements[1].test)
cm_global = SimpleNamespace()
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), {
"cm_global": cm_global, "os": os, "json": json,
"manager_pip_overrides_path": str(path), "_has_system_user_api": has_system_user_api,
})
return cm_global.pip_overrides
@pytest.mark.parametrize("overrides", OVERRIDES, ids=["one package", "two packages", "empty"])
def test_with_the_system_user_api_the_file_is_read(tmp_path, overrides):
path = tmp_path / "pip_overrides.json"
path.write_text(json.dumps(overrides), encoding="utf-8")
assert overrides_after_start(True, path) == overrides
@pytest.mark.parametrize("text", [json.dumps(OVERRIDES[0]), json.dumps(OVERRIDES[1]), "{}", "", "not json"],
ids=["one package", "two packages", "empty", "an empty file", "not json"])
def test_on_an_older_comfyui_the_file_is_not_read(tmp_path, text):
path = tmp_path / "pip_overrides.json"
path.write_text(text, encoding="utf-8")
assert overrides_after_start(False, path) == {}
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the API", "an older ComfyUI"])
def test_without_a_file_no_package_is_remapped(tmp_path, has_system_user_api):
assert overrides_after_start(has_system_user_api, tmp_path / "pip_overrides.json") == {}
@@ -0,0 +1,47 @@
import ast
import os
import sys
import types
from pathlib import Path
import pytest
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
def start(tmp_path, has_system_user_api, legacy):
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
if isinstance(node, ast.If) and "execute_lazy_install_script(comfy_path" in ast.unparse(node)]
assert len(statements) == 1
directory = tmp_path / "user" / "default" / "ComfyUI-Manager"
if legacy is not None:
directory.mkdir(parents=True)
for name in legacy:
(directory / name).write_text("", encoding="utf-8")
installed = []
namespace = {
"os": os, "sys": sys, "_has_system_user_api": has_system_user_api, "comfy_path": "comfyui",
"folder_paths": types.SimpleNamespace(get_user_directory=lambda: str(tmp_path / "user")),
"execute_lazy_install_script": lambda repo_path, executable: installed.append((repo_path, executable)),
}
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
return installed
def test_the_first_start_after_the_update_installs_the_requirements_of_comfyui(tmp_path, capsys):
assert start(tmp_path, True, ["config.ini"]) == [("comfyui", sys.executable)]
assert "installing the requirements of ComfyUI" in capsys.readouterr().out
@pytest.mark.parametrize("legacy", [None, [], ["channels.list"]],
ids=["no legacy directory", "an empty legacy directory", "a legacy directory without config.ini"])
def test_a_start_that_is_not_the_first_after_the_update_installs_nothing(tmp_path, legacy, capsys):
assert start(tmp_path, True, legacy) == []
assert capsys.readouterr().out == ""
@pytest.mark.parametrize("legacy", [None, ["config.ini"]], ids=["no data directory yet", "with its config.ini"])
def test_an_old_comfyui_installs_nothing_at_the_start(tmp_path, legacy):
assert start(tmp_path, False, legacy) == []
@@ -0,0 +1,68 @@
import ast
import locale
import os
import sys
import types
from pathlib import Path
import pytest
PRESTARTUP = Path(os.environ.get("MANAGER_PRESTARTUP") or (Path(__file__).resolve().parent.parent / "prestartup_script.py"))
SNAPSHOT = '{"comfyui": null, "git_custom_nodes": {}, "cnr_custom_nodes": {}, "file_custom_nodes": [], "pips": {}}'
def start(monkeypatch, tmp_path, has_system_user_api, scheduled=True, exit_code=0):
statements = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
if isinstance(node, ast.If) and "'restore-snapshot'" in ast.unparse(node)]
assert len(statements) == 1
cli_args = types.ModuleType("comfy.cli_args")
cli_args.args = types.SimpleNamespace(listen="127.0.0.1")
monkeypatch.setitem(sys.modules, "comfy", types.ModuleType("comfy"))
monkeypatch.setitem(sys.modules, "comfy.cli_args", cli_args)
path = tmp_path / "startup-scripts" / "restore-snapshot.json"
if scheduled:
path.parent.mkdir()
path.write_text(SNAPSHOT, encoding="utf-8")
commands = []
def process_wrap(command, cwd, handler=None, env=None):
commands.append(command)
return exit_code
namespace = {
"os": os, "sys": sys, "locale": locale, "_has_system_user_api": has_system_user_api,
"restore_snapshot_path": str(path), "comfy_path": str(tmp_path), "custom_nodes_base_path": str(tmp_path),
"cm_cli_path": "cm-cli.py", "default_conf": {}, "process_wrap": process_wrap,
"manager_util": types.SimpleNamespace(is_loopback_listener=lambda listen: True),
"folder_paths": types.SimpleNamespace(__file__=str(tmp_path / "folder_paths.py"), get_user_directory=lambda: str(tmp_path / "user")),
}
exec(compile(ast.Module(body=statements, type_ignores=[]), str(PRESTARTUP), "exec"), namespace)
return commands, path.exists()
@pytest.mark.parametrize("exit_code", [0, 1], ids=["cm-cli succeeds", "cm-cli fails"])
def test_with_the_system_user_api_a_scheduled_restore_runs_once(monkeypatch, tmp_path, exit_code):
commands, left = start(monkeypatch, tmp_path, has_system_user_api=True, exit_code=exit_code)
assert [command[:4] for command in commands] == [
[sys.executable, "cm-cli.py", "restore-snapshot", str(tmp_path / "startup-scripts" / "restore-snapshot.json")]]
assert left is False
def test_on_an_older_comfyui_a_scheduled_restore_does_not_run(monkeypatch, tmp_path, capsys):
commands, left = start(monkeypatch, tmp_path, has_system_user_api=False)
assert commands == []
assert left is True
assert "blocked on old ComfyUI" in capsys.readouterr().out
@pytest.mark.parametrize("has_system_user_api", [True, False], ids=["with the System User API", "older ComfyUI"])
def test_without_a_scheduled_restore_nothing_runs(monkeypatch, tmp_path, has_system_user_api, capsys):
commands, left = start(monkeypatch, tmp_path, has_system_user_api, scheduled=False)
assert commands == []
assert left is False
assert capsys.readouterr().out == ""
+42
View File
@@ -0,0 +1,42 @@
import json
import os
import subprocess
import sys
from test_install_flags_config import _CHILD_PREAMBLE, REPO_ROOT
BODY = '''
import ast, pathlib
core = manager_core
core.manager_startup_script_path = tmp
core.get_default_custom_nodes_path = lambda: tmp
path = str(pathlib.Path(tmp) / '한글 node pack')
def reserved():
with open(pathlib.Path(tmp) / 'install-scripts.txt', encoding='utf-8') as file:
return [ast.literal_eval(line) for line in file]
'''
def run(tmp_path, body):
# from a file: with this locale a command line cannot hold the name of the node pack
(tmp_path / 'reserve.py').write_text(_CHILD_PREAMBLE.format(glob_path=str(REPO_ROOT / 'glob')) + BODY + body, encoding='utf-8')
child = subprocess.run([sys.executable, str(tmp_path / 'reserve.py')], capture_output=True, text=True, cwd=str(REPO_ROOT),
env={**os.environ, 'LC_ALL': 'C', 'PYTHONUTF8': '0', 'PYTHONCOERCECLOCALE': '0'})
assert child.returncode == 0, child.stderr[-600:]
return json.loads(child.stdout.strip().splitlines()[-1])
def test_install_script_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path):
assert run(tmp_path, '''
core.reserve_script(path, ['install.py'])
print(json.dumps(reserved() == [[path, 'install.py']]))
''') is True
def test_switch_of_a_pack_whose_path_the_locale_cannot_write_is_reserved(tmp_path):
assert run(tmp_path, '''
core.UnifiedManager().reserve_cnr_switch('fixture', 'https://example.invalid/fixture.zip', path, path, False)
entry, = reserved()
print(json.dumps(entry[3:5] == [path, path]))
''') is True
+11 -1
View File
@@ -49,7 +49,7 @@ def restore(monkeypatch, capsys):
check_call=check_call, check_output=check_output,
CalledProcessError=subprocess.CalledProcessError))
manager_util.restore_pip_snapshot(PIPS, options)
run.not_installed = manager_util.restore_pip_snapshot(PIPS, options)
report = capsys.readouterr().out.strip().splitlines()[-1]
return commands, report
@@ -104,6 +104,16 @@ def test_every_failed_package_is_reported(restore):
assert report == f"Installation failed for pip packages: {['alpha==1.0', 'beta==2.0', *urls]}"
@pytest.mark.parametrize('failing, not_installed', [
([], []),
(['beta', 'delta'], ['beta==2.0', 'file:///wheels/delta.whl']),
])
def test_packages_that_were_not_installed_are_returned(restore, failing, not_installed):
restore(['--pip-non-url', '--pip-non-local-url', '--pip-local-url'], failing=failing)
assert restore.not_installed == not_installed
def test_group_without_its_option_is_left_alone(restore):
commands, report = restore([])
+495
View File
@@ -0,0 +1,495 @@
import ast
import asyncio
import os
import pathlib
import traceback
from types import SimpleNamespace
from typing import Optional
from unittest.mock import AsyncMock, Mock
import pytest
from test_snapshot_restore_pins import run
CM_CLI = pathlib.Path(__file__).resolve().parent.parent / 'cm-cli.py'
URL = 'https://github.com/owner/fixture'
HASH = '0123456789abcdef0123456789abcdef01234567'
SUMMARY = '''
import contextlib, io
URL = 'https://github.com/owner/fixture'
HASH = '0123456789abcdef0123456789abcdef01234567'
def summary(**snapshot):
out = io.StringIO()
with contextlib.redirect_stdout(out):
restore(**snapshot)
return [line.strip() for line in out.getvalue().splitlines() if line.startswith('[ ')]
def pinned(url):
return {'git_custom_nodes': {url: {'hash': HASH, 'disabled': False}}}
def git_pack(name, url):
path = nodes / name
(path / '.git').mkdir(parents=True)
(path / '.git/config').write_text('[remote "origin"]\\n\\turl = %s\\n' % url)
return url, str(path)
def in_registry():
manager.repo_cnr_map[URL] = {'id': 'fixture'}
manager.get_custom_nodes.return_value = {'fixture': {'repository': URL}}
def clones(kind, clone):
if kind == 'url':
manager.repo_install = lambda url, path, return_postinstall=False, **options: clone(path, return_postinstall)
return
async def install(pack_id, version_spec, return_postinstall=False, **options):
manager.active_nodes[pack_id] = (version_spec, str(nodes / pack_id))
return clone(str(nodes / pack_id), return_postinstall)
in_registry()
manager.install_by_id = install
def answer(action, ok):
result = core.ManagedResult(action)
return Mock(return_value=result if ok else result.fail('failed'))
def repository(path):
path.mkdir(parents=True)
commits = []
for version in (1, 2):
(path / '__init__.py').write_text('VERSION = %d' % version)
for args in (['init', '-q'], ['add', '.'],
['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', 'commit', '-q', '-m', 'version %d' % version]):
subprocess.run(['git', *args], cwd=path, check=True, capture_output=True)
commits.append(head(path))
return commits
def head(path):
return subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=path, check=True, capture_output=True, text=True).stdout.strip()
'''
def lines(body):
return run(SUMMARY + body + '\nprint(json.dumps(result))\n')
CLONES = pytest.mark.parametrize('kind', ['registry', 'url'])
@pytest.mark.parametrize('cloned, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
def test_clone_follows_its_result(cloned, line):
assert lines(f'''
manager.repo_install = answer('install-git', {cloned})
core.repo_switch_commit = Mock(return_value=True)
result = summary(**pinned('{URL}.git')) + [manager.repo_install.call_args.args[1] == str(nodes / 'fixture')]
''') == [line, True]
def test_url_that_is_not_cloned_is_reported_as_failed():
assert lines('''
result = summary(**pinned('/home/someone/repos/fixture')) + [(nodes / 'fixture').exists()]
''') == ['[ FAILED ] fixture', False]
def test_url_that_cannot_be_parsed_is_reported_as_failed_and_the_restore_goes_on():
assert lines('''
entry = {'hash': HASH, 'disabled': False}
result = summary(git_custom_nodes={'https://[not-a-host/first': dict(entry), '/home/someone/repos/second': dict(entry)})
''') == ['[ FAILED ] first', '[ FAILED ] second']
def test_cloned_pack_is_checked_out_at_the_pinned_commit():
assert lines(f'''
commits = repository(pathlib.Path(tmp) / 'origin')
def clone(url, path, **options):
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), path], check=True, capture_output=True)
return core.ManagedResult('install-git')
manager.repo_install = clone
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
result += [head(nodes / 'fixture') == commits[0], (nodes / 'fixture/__init__.py').read_text()]
''') == ['[ INSTALLED ] fixture', True, 'VERSION = 1']
def test_cloned_registry_pack_is_checked_out_at_the_pinned_commit():
assert lines(f'''
commits = repository(pathlib.Path(tmp) / 'origin')
async def install(pack_id, version_spec, **options):
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), nodes / pack_id], check=True, capture_output=True)
manager.active_nodes[pack_id] = (version_spec, str(nodes / pack_id))
return core.ManagedResult('install-git')
manager.repo_cnr_map['{URL}'] = {{'id': 'fixture'}}
manager.install_by_id = install
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
result += [head(nodes / 'fixture') == commits[0]]
''') == ['[ INSTALLED ] fixture', True]
def test_cloned_pack_that_cannot_be_checked_out_is_reported_as_failed():
assert lines(f'''
manager.repo_install = answer('install-git', True)
result = summary(**pinned('{URL}'))
''') == [f'[ FAILED ] fixture@{HASH}']
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
def test_disabling_a_git_pack_that_is_not_in_the_snapshot_follows_its_result(disabled, line):
assert lines(f'''
manager.unknown_active_nodes['fixture'] = git_pack('fixture', '{URL}')
manager.unified_disable = answer('disable', {disabled})
result = summary()
''') == [line]
@pytest.mark.parametrize('disabled, line', [(True, '[ DISABLED ] fixture'), (False, '[ FAILED ] fixture')])
def test_disabling_a_registry_pack_that_is_not_in_the_snapshot_follows_its_result(disabled, line):
assert lines(f'''
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
manager.unified_disable = answer('disable', {disabled})
result = summary()
''') == [line]
@pytest.mark.parametrize('name', ['ComfyUI-Manager', 'comfyui-manager'])
def test_the_manager_itself_is_not_listed(name):
assert lines(f'''
manager.unknown_active_nodes['{name}'] = git_pack('{name}', 'https://github.com/ltdrdata/ComfyUI-Manager')
manager.unified_disable = answer('disable', True)
result = summary() + [manager.unified_disable.call_count]
''') == [0]
@pytest.mark.parametrize('enabled, line', [(True, '[ ENABLED ] fixture'), (False, '[ FAILED ] fixture')])
def test_enabling_a_git_pack_of_the_snapshot_follows_its_result(enabled, line):
assert lines(f'''
manager.unknown_inactive_nodes['fixture'] = git_pack('.disabled/fixture', '{URL}')
manager.unified_enable = answer('enable', {enabled})
manager.unified_enable.return_value.target = str(nodes / 'fixture') if {enabled} else None
core.repo_switch_commit = Mock(return_value=False)
result = summary(**pinned('{URL}')) + [[x.args for x in core.repo_switch_commit.call_args_list] == ([(str(nodes / 'fixture'), HASH)] if {enabled} else [])]
''') == [line, True]
def test_installed_git_pack_the_registry_does_not_know_is_checked_out_at_the_pinned_commit():
assert lines(f'''
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'remote', 'add', 'origin', '{URL}'], cwd=nodes / 'fixture', check=True)
manager.unknown_active_nodes['fixture'] = ('{URL}', str(nodes / 'fixture'))
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}})
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[0]]
''') == ['[ CHECKOUT ] fixture@PINNED', True]
@pytest.mark.parametrize('installed', ['unknown_git_pack', 'disabled_unknown_git_pack', 'registry_git_pack', 'disabled_registry_git_pack'])
def test_checkout_that_fails_is_reported_as_failed(installed):
assert lines(f'''
name, url = 'fixture', URL
{MOVED[installed][0]}
result = summary(**pinned(URL))
''') == [f'[ FAILED ] fixture@{HASH}']
NO_COMMIT = pytest.mark.parametrize('entry', [{'hash': 'unknown', 'disabled': False}, {'disabled': False}], ids=['unknown', 'no hash'])
@NO_COMMIT
def test_pack_without_a_commit_in_the_snapshot_is_left_where_it_is(entry):
assert lines(f'''
commits = repository(nodes / 'fixture')
subprocess.run(['git', 'remote', 'add', 'origin', '{URL}'], cwd=nodes / 'fixture', check=True)
manager.unknown_active_nodes['fixture'] = ('{URL}', str(nodes / 'fixture'))
result = summary(git_custom_nodes={{'{URL}': {entry!r}}}) + [head(nodes / 'fixture') == commits[1]]
''') == ['[ SKIPPED ] fixture', True]
@CLONES
@NO_COMMIT
def test_cloned_pack_without_a_commit_in_the_snapshot_is_installed(kind, entry):
assert lines(f'''
ran = []
clones('{kind}', lambda path, return_postinstall: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True))
result = summary(git_custom_nodes={{'{URL}': {entry!r}}}) + [ran == [str(nodes / 'fixture')]]
''') == ['[ INSTALLED ] fixture', True]
@CLONES
@pytest.mark.parametrize('installed, line', [(True, '[ INSTALLED ] fixture'), (False, '[ FAILED ] fixture')])
def test_install_script_of_a_cloned_pack_runs_at_the_pinned_commit(kind, installed, line):
assert lines(f'''
commits = repository(pathlib.Path(tmp) / 'origin')
ran_at = []
def clone(path, return_postinstall):
subprocess.run(['git', 'clone', '-q', str(pathlib.Path(tmp) / 'origin'), path], check=True, capture_output=True)
def postinstall():
ran_at.append(head(path))
return {installed}
result = core.ManagedResult('install-git')
return result.with_postinstall(postinstall) if return_postinstall else (result if postinstall() else result.fail('install script'))
clones('{kind}', clone)
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[0], 'disabled': False}}}}) + [ran_at == [commits[0]]]
''') == [line, True]
@CLONES
def test_install_script_that_raises_is_reported_as_failed_and_the_restore_goes_on(kind):
assert lines(f'''
def clone(path, return_postinstall):
def postinstall():
raise subprocess.CalledProcessError(1, ['python', 'install.py'])
return core.ManagedResult('install-git').with_postinstall(postinstall)
manager.repo_install = lambda url, path, **options: clone(path, True)
clones('{kind}', clone)
core.repo_switch_commit = Mock(return_value=True)
result = summary(git_custom_nodes={{'{URL}': {{'hash': HASH, 'disabled': False}}, '{URL}-other': {{'hash': HASH, 'disabled': False}}}})
''') == ['[ FAILED ] fixture', '[ FAILED ] fixture-other']
def test_install_script_of_a_cloned_pack_runs_also_when_the_commit_cannot_be_checked_out():
assert lines(f'''
ran = []
manager.repo_install = lambda url, path, **options: core.ManagedResult('install-git').with_postinstall(lambda: ran.append(path) or True)
result = summary(**pinned('{URL}')) + [ran == [str(nodes / 'fixture')]]
''') == [f'[ FAILED ] fixture@{HASH}', True]
def test_install_script_of_a_cloned_registry_pack_runs_also_when_the_commit_cannot_be_checked_out():
assert lines(f'''
ran = []
async def install(pack_id, version_spec, **options):
manager.active_nodes[pack_id] = (version_spec, str(nodes / pack_id))
return core.ManagedResult('install-git').with_postinstall(lambda: ran.append(pack_id) or True)
manager.repo_cnr_map['{URL}'] = {{'id': 'fixture'}}
manager.install_by_id = install
result = summary(**pinned('{URL}')) + [ran]
''') == [f'[ FAILED ] fixture@{HASH}', ['fixture']]
@pytest.mark.parametrize('outcome, line', [('return True', '[ INSTALLED ] fixture@1.0.0'), ('return False', '[ FAILED ] fixture@1.0.0'),
("raise subprocess.CalledProcessError(1, ['python', 'install.py'])", '[ FAILED ] fixture@1.0.0')])
def test_install_script_of_a_registry_pack_is_run(outcome, line):
assert lines(f'''
ran = []
def postinstall():
ran.append('fixture')
{outcome}
async def install(pack_id, **options):
ran.append(options['return_postinstall'])
return core.ManagedResult('install-cnr').with_postinstall(postinstall)
manager.install_by_id = install
result = summary(cnr_custom_nodes={{'fixture': '1.0.0'}}) + [ran]
''') == [line, [True, 'fixture']]
def test_registry_pack_whose_install_raises_is_reported_as_failed_and_the_restore_goes_on():
assert lines('''
async def install(pack_id, **options):
if pack_id == 'fixture':
raise ConnectionError('the registry cannot be reached')
return core.ManagedResult('install-cnr')
manager.install_by_id = install
result = summary(cnr_custom_nodes={'fixture': '1.0.0', 'other': '1.0.0'})
''') == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@1.0.0']
def test_registry_pack_whose_switch_raises_is_reported_as_failed_and_the_restore_goes_on():
assert lines('''
async def install(pack_id, **options):
return core.ManagedResult('install-cnr')
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
manager.cnr_switch_version = Mock(side_effect=ConnectionError('the registry cannot be reached'))
manager.install_by_id = install
result = summary(cnr_custom_nodes={'fixture': '2.0.0', 'other': '1.0.0'})
''') == ['[ INSTALLED ] other@1.0.0', '[ FAILED ] fixture@2.0.0']
MOVED = {
'registry_pack': ("manager.active_nodes[name] = ('1.0.0', str(nodes / name))", 'unified_disable', False),
'registry_git_pack': ("manager.active_nodes[name] = ('nightly', str(nodes / name)); manager.repo_cnr_map[url] = {'id': name}", 'unified_disable', False),
'unknown_git_pack': ("manager.unknown_active_nodes[name] = git_pack(name, url)", 'unified_disable', False),
'disabled_registry_git_pack': ("manager.nightly_inactive_nodes[name] = git_pack('.disabled/' + name, url)[1]; manager.repo_cnr_map[url] = {'id': name}", 'unified_enable', True),
'disabled_unknown_git_pack': ("manager.unknown_inactive_nodes[name] = git_pack('.disabled/' + name, url)", 'unified_enable', True),
}
@pytest.mark.parametrize('installed', MOVED)
def test_pack_whose_directory_cannot_be_moved_is_reported_as_failed_and_the_restore_goes_on(installed):
"""The second node pack is the proof that the restore goes on."""
arrange, step, in_snapshot = MOVED[installed]
assert lines(f'''
packs = {{'fixture': URL, 'second': URL + '-2'}}
for name, url in packs.items():
{arrange}
manager.{step} = Mock(side_effect=PermissionError(13, 'Permission denied'))
snapshot = {{url: {{'hash': HASH, 'disabled': False}} for url in packs.values()}} if {in_snapshot} else {{}}
result = summary(git_custom_nodes=snapshot) + [manager.{step}.call_count]
''') == ['[ FAILED ] fixture', '[ FAILED ] second', 2]
def test_pack_that_fails_at_two_steps_is_listed_once():
assert lines(f'''
manager.active_nodes['fixture'] = ('1.0.0', str(nodes / 'fixture'))
in_registry()
manager.unified_disable = answer('disable', False)
async def install(pack_id, version_spec, **options):
return core.ManagedResult('install-git').fail('failed')
manager.install_by_id = install
result = summary(cnr_custom_nodes={{}}, **pinned('{URL}'))
''') == ['[ FAILED ] fixture']
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@PINNED'), (1, '[ ENABLED ] fixture')])
def test_registry_git_pack_that_is_enabled_is_listed_once(pinned_at, line):
assert lines(f'''
commits = repository(nodes / '.disabled/fixture')
manager.nightly_inactive_nodes['fixture'] = str(nodes / '.disabled/fixture')
in_registry()
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[{pinned_at}], 'disabled': False}}}})
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[{pinned_at}]]
''') == [line, True]
@pytest.mark.parametrize('pinned_at, line', [(0, '[ CHECKOUT ] fixture@PINNED'), (1, '[ SKIPPED ] fixture')])
def test_registry_git_pack_that_is_installed_is_listed_once(pinned_at, line):
assert lines(f'''
commits = repository(nodes / 'fixture')
manager.active_nodes['fixture'] = ('nightly', str(nodes / 'fixture'))
in_registry()
result = summary(git_custom_nodes={{'{URL}': {{'hash': commits[{pinned_at}], 'disabled': False}}}})
result = [line.replace(commits[0], 'PINNED') for line in result] + [head(nodes / 'fixture') == commits[{pinned_at}]]
''') == [line, True]
INSTALLS = '''
import os
def packs(**files):
for name in ('first', 'second'):
(nodes / name).mkdir()
for file, text in files.items():
(nodes / name / file).write_text(text)
return str(nodes / 'first'), str(nodes / 'second')
def installs(*answers):
answers, ran = list(answers), []
def try_install_script(url, repo_path, install_cmd, instant_execution=False):
ran.append(os.path.basename(repo_path) + ' ' + install_cmd[-1])
return answers.pop(0)
core.try_install_script = try_install_script
core.remap_pip_package = lambda package: package
manager_util.PIPFixer = Mock()
manager_util.get_installed_packages = Mock(return_value={})
return ran
'''
def install_steps(body):
return lines(INSTALLS + body)
def test_requirement_that_was_not_installed_is_tried_for_the_next_pack():
assert install_steps('''
first, second = packs(**{'requirements.txt': 'shareddep==1\\n'})
ran = installs(False, True)
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
''') == [False, True, ['first shareddep==1', 'second shareddep==1']]
def test_requirement_after_one_that_failed_is_tried_for_the_next_pack():
assert install_steps('''
first, second = packs(**{'requirements.txt': 'fails==1\\nshareddep==1\\n'})
ran = installs(False, True, True)
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
''') == [False, True, ['first fails==1', 'second fails==1', 'second shareddep==1']]
def test_requirement_that_was_installed_is_not_installed_twice():
assert install_steps('''
first, second = packs(**{'requirements.txt': 'shareddep==1\\n'})
ran = installs(True)
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, second), ran]
''') == [True, True, ['first shareddep==1']]
def test_install_script_that_failed_is_run_when_asked_again():
assert install_steps('''
first, _ = packs(**{'install.py': ''})
ran = installs(False, True)
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, first), ran]
''') == [False, True, ['first install.py', 'first install.py']]
def test_install_script_not_run_after_a_requirement_failed_is_run_when_asked_again():
assert install_steps('''
first, _ = packs(**{'requirements.txt': 'fails==1\\n', 'install.py': ''})
ran = installs(False, True, True)
result = [manager.execute_install_script(None, first), manager.execute_install_script(None, first), ran]
''') == [False, True, ['first fails==1', 'first fails==1', 'first install.py']]
def test_install_script_of_a_pack_that_is_cloned_where_another_was_installed_is_run():
assert install_steps(f'''
first, _ = packs(**{{'install.py': ''}})
ran = installs(True, True)
manager.execute_install_script(None, first)
os.rename(first, nodes / '.disabled')
def clone(url, path, **options):
os.mkdir(path)
open(os.path.join(path, 'install.py'), 'w').close()
return Mock()
core.git.Repo.clone_from = clone
result = [manager.repo_install('{URL}', first, instant_execution=True).result, ran]
''') == [True, ['first install.py', 'first install.py']]
@pytest.mark.parametrize('cloned', [True, False])
def test_restore_tells_whether_every_step_was_done(cloned):
assert lines(f'''
manager.repo_install = answer('install-git', {cloned})
core.repo_switch_commit = Mock(return_value=True)
with contextlib.redirect_stdout(io.StringIO()):
result = restore(**pinned('{URL}'))
''') is cloned
@pytest.mark.parametrize('not_installed, restored', [([], True), (['alpha==1.0'], False)])
def test_restore_tells_whether_every_pip_package_was_installed(not_installed, restored):
assert lines(f'''
manager_util.restore_pip_snapshot = Mock(return_value={not_installed})
with contextlib.redirect_stdout(io.StringIO()):
result = restore()
''') is restored
class Exit(Exception):
def __init__(self, code=0):
self.code = code
@pytest.mark.parametrize('restored, code', [(True, None), (False, 1)])
def test_cm_cli_ends_with_1_when_a_step_of_the_restore_failed(tmp_path, restored, code):
command = next(node for node in ast.parse(CM_CLI.read_text(encoding='utf-8')).body
if isinstance(node, ast.FunctionDef) and node.name == 'restore_snapshot')
command.decorator_list = []
fixer = Mock()
scope = {'typer': SimpleNamespace(Option=Mock(), Exit=Exit), 'Optional': Optional, 'os': os, 'asyncio': asyncio, 'traceback': traceback,
'cmd_ctx': Mock(), 'comfy_path': '', 'manager_util': SimpleNamespace(PIPFixer=Mock(return_value=fixer), get_installed_packages=Mock()),
'core': SimpleNamespace(restore_snapshot=AsyncMock(return_value=restored), manager_files_path='')}
exec(compile(ast.Module(body=[command], type_ignores=[]), str(CM_CLI), 'exec'), scope)
snapshot = tmp_path / 'snapshot.json'
snapshot.touch()
ended = None
try:
scope['restore_snapshot'](str(snapshot), None, None, None, None, None)
except Exit as e:
ended = e.code
assert ended == code
fixer.fix_broken.assert_called_once()
+64
View File
@@ -0,0 +1,64 @@
import ast
import os
import sys
import types
from pathlib import Path
import pytest
PRESTARTUP = Path(__file__).resolve().parent.parent / "prestartup_script.py"
COMFY = os.path.join(os.sep, "opt", "ComfyUI")
LAUNCHER = os.path.join(os.sep, "opt", "launcher")
BASE = os.path.join(os.sep, "data", "comfy")
def restore(tmp_path, monkeypatch, environ):
scheduled = tmp_path / "restore-snapshot.json"
scheduled.write_text("{}")
block = [node for node in ast.parse(PRESTARTUP.read_text(encoding="utf-8")).body
if isinstance(node, ast.If) and "'restore-snapshot'" in ast.unparse(node)]
assert len(block) == 1
cli_args = types.ModuleType("comfy.cli_args")
cli_args.args = types.SimpleNamespace(listen="127.0.0.1")
monkeypatch.setitem(sys.modules, "comfy", types.ModuleType("comfy"))
monkeypatch.setitem(sys.modules, "comfy.cli_args", cli_args)
for name in ("COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"):
monkeypatch.delenv(name, raising=False)
for name, value in environ.items():
monkeypatch.setenv(name, value)
started = []
def process_wrap(cmd, cwd=None, handler=None, env=None):
started.append((cmd, cwd, env))
return 0
exec(compile(ast.Module(body=block, type_ignores=[]), str(PRESTARTUP), "exec"), {
"os": os, "sys": sys, "_has_system_user_api": True, "restore_snapshot_path": str(scheduled), "comfy_path": LAUNCHER,
"cm_cli_path": "cm-cli.py", "custom_nodes_base_path": os.path.join(BASE, "custom_nodes"),
"folder_paths": types.SimpleNamespace(__file__=os.path.join(COMFY, "folder_paths.py"),
get_user_directory=lambda: os.path.join(BASE, "user")),
"default_conf": {}, "manager_util": types.SimpleNamespace(is_loopback_listener=lambda listen: True),
"process_wrap": process_wrap,
})
assert len(started) == 1 and not scheduled.exists()
return started[0]
def test_cm_cli_is_given_the_comfyui_path(tmp_path, monkeypatch):
_, _, env = restore(tmp_path, monkeypatch, {})
assert env.get("COMFYUI_PATH") == COMFY
def test_cm_cli_is_given_the_directories_of_the_server(tmp_path, monkeypatch):
cmd, _, _ = restore(tmp_path, monkeypatch, {})
assert cmd[1:4] == ["cm-cli.py", "restore-snapshot", str(tmp_path / "restore-snapshot.json")]
assert cmd[4:] == ["--user-directory", os.path.join(BASE, "user"),
"--restore-to", os.path.join(BASE, "custom_nodes")]
@pytest.mark.parametrize("name", ["COMFYUI_PATH", "COMFYUI_FOLDERS_BASE_PATH"])
def test_a_path_set_in_the_environment_is_kept(tmp_path, monkeypatch, name):
_, _, env = restore(tmp_path, monkeypatch, {name: os.path.join(os.sep, "elsewhere")})
assert env[name] == os.path.join(os.sep, "elsewhere")
+60
View File
@@ -0,0 +1,60 @@
"""The server stores only a `db_mode`, an `update_policy` or a `component_policy` that the Manager knows.
Each case runs the real handler of `glob/manager_server.py` with the functions
and the lists of values it uses; `core` holds a configuration in memory and
counts how often it is written.
"""
import ast
import asyncio
import json
from types import SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
SETTINGS = [
("set_db_mode_handler", "db_mode", ["cache", "local", "remote"]),
("set_update_policy_handler", "update_policy", ["stable-comfyui", "nightly-comfyui"]),
("set_component_policy_handler", "component_policy", ["workflow", "higher", "mine"]),
]
NAMES = {handler for handler, key, values in SETTINGS} | {"set_db_mode", "set_update_policy", "set_component_policy"}
BEFORE = "the value before the request"
def post(handler, key, body):
"""The status the handler answers, the stored value and how often the configuration was written."""
source = (GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if (isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in NAMES)
or (isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "").startswith("ALLOWED_"))]
config, written = {key: BEFORE}, []
namespace = {
"web": web, "routes": SimpleNamespace(post=lambda path: lambda function: function),
"_reject_non_json_content_type": lambda request: None,
"core": SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config))),
}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "<setting handlers>", "exec"), namespace)
async def read():
return json.loads(body)
return asyncio.run(namespace[handler](SimpleNamespace(json=read))).status, config[key], len(written)
@pytest.mark.parametrize("handler, key, value", [(handler, key, value) for handler, key, values in SETTINGS for value in values])
def test_known_value_is_stored(handler, key, value):
assert post(handler, key, json.dumps({"value": value})) == (200, value, 1)
@pytest.mark.parametrize("handler, key, values", SETTINGS)
@pytest.mark.parametrize("value", ['"no-such-value"', '""', '"CACHE"', "7", "null", '["cache"]'])
def test_unknown_value_is_refused(handler, key, values, value):
assert post(handler, key, '{"value": %s}' % value) == (400, BEFORE, 0)
@pytest.mark.parametrize("handler, key, values", SETTINGS)
@pytest.mark.parametrize("body", ["{}", "[]", '"cache"', "7", "null"])
def test_request_without_a_value_is_refused(handler, key, values, body):
assert post(handler, key, body) == (400, BEFORE, 0)
+6 -5
View File
@@ -55,14 +55,15 @@ def load_share_art(monkeypatch, output_dir, temp_dir, os_module: object = os):
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name == "share_art"]
assert len(nodes) == 1
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in ("share_art", "is_matrix_org")]
assert len(nodes) == 2
namespace = {
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=web.RouteTableDef())),
"folder_paths": SimpleNamespace(get_output_directory=lambda: str(output_dir),
get_temp_directory=lambda: str(temp_dir)),
"os": os_module, "web": web, "json": json, "mimetypes": mimetypes,
"set_matrix_auth": lambda matrix_auth: None,
"get_matrix_auth": lambda: None, "set_matrix_auth": lambda matrix_auth: None,
"_reject_non_json_content_type": lambda request: None,
}
exec(compile(ast.Module(body=nodes, type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
return namespace["share_art"], uploads
@@ -70,7 +71,7 @@ def load_share_art(monkeypatch, output_dir, temp_dir, os_module: object = os):
def share(share_art, output):
body = {
"matrix_auth": {"homeserver": "matrix.example", "username": "user", "password": "password"},
"matrix_auth": {"homeserver": "matrix.org", "username": "user", "password": "password"},
"share_destinations": ["matrix"], "credits": "", "title": "", "description": "",
"prompt": {"workflow": {}}, "potential_outputs": [output], "selected_output_index": 0,
}
@@ -112,7 +113,7 @@ def test_a_file_in_the_directory_is_shared(monkeypatch, dirs, output, content):
response = share(share_art, output)
assert response.status == 200
assert uploads[0] == ("https://matrix.example", content)
assert uploads[0] == ("https://matrix.org", content)
@pytest.mark.parametrize("output", [
+224
View File
@@ -0,0 +1,224 @@
import os
from pathlib import Path
import pytest
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
JS = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js"))
EXTENSION = "http://manager.test/extensions/comfyui-manager/"
SAVED = {"homeserver": "matrix.org", "username": "user"}
ASK_FOR_ACCOUNT = "Please set your Matrix account details."
SCRIPTS = {
"api.js": """
export const api = {
addEventListener() {},
async fetchApi(path, options) {
window.requested.push({path, method: options?.method ?? 'GET', body: options?.body ? JSON.parse(options.body) : null});
if(path == '/manager/get_matrix_auth') {
if(window.offline) throw new TypeError('Failed to fetch');
if(window.saved) return {status: 200, json: async () => window.saved};
return {status: 404, json: async () => { throw new SyntaxError('Unexpected end of JSON input'); }};
}
return {status: 200, json: async () => ({matrix: {success: true}})};
}
};
""",
"app.js": """
const image = {filename: 'a.png', subfolder: '', type: 'output'};
export const app = {
graph: {_nodes: [{type: 'SaveImage', id: 1, title: 'Save Image', images: [image]}]},
graphToPrompt: async () => ({workflow: {}, output: {}}),
ui: {dialog: {element: document.body, show() {}}},
};
""",
"ui.js": """
export function $el(tag, props, children) {
const names = tag.split('.');
const element = document.createElement(names.shift());
element.classList.add(...names);
const {parent, style, ...rest} = props ?? {};
Object.assign(element.style, style);
Object.assign(element, rest);
element.append(...(children ?? []));
parent?.append(element);
return element;
}
export class ComfyDialog {
close() { this.element.style.display = 'none'; }
}
""",
}
@pytest.fixture
def page(browser): # noqa: F811
page = browser.new_page()
def route(request):
url = request.request.url
name = url.rsplit("/", 1)[-1]
if url == "http://manager.test/":
request.fulfill(body="<body></body>", content_type="text/html")
elif url.startswith(EXTENSION) and (JS / name).is_file():
request.fulfill(path=str(JS / name), content_type="text/javascript")
elif url == "http://manager.test/scripts/" + name and name in SCRIPTS:
request.fulfill(body=SCRIPTS[name], content_type="text/javascript")
else:
request.abort()
page.route("**/*", route)
page.errors = []
page.alerts = []
page.on("pageerror", lambda error: page.errors.append(str(error)))
page.on("dialog", lambda dialog: (page.alerts.append(dialog.message), dialog.dismiss()))
page.goto("http://manager.test/")
yield page
page.close()
def open_dialog(page, saved, offline=False):
page.evaluate("""async ({saved, offline, module}) => {
window.requested = [];
window.saved = saved;
window.offline = offline;
const { ShareDialog, getPotentialOutputsAndOutputNodes } = await import(module);
const { app } = await import('/scripts/app.js');
window.dialog = new ShareDialog();
window.dialog.show(getPotentialOutputsAndOutputNodes(app.graph._nodes));
}""", {"saved": saved, "offline": offline, "module": EXTENSION + "comfyui-share-common.js"})
page.wait_for_timeout(200)
def fields(page):
return page.evaluate("""() => ({
homeserver: dialog.matrix_homeserver_input.value,
username: dialog.matrix_username_input.value,
password: dialog.matrix_password_input.value,
})""")
def share_to_matrix(page, matrix=True, **typed):
page.evaluate("""async ({typed, matrix}) => {
for(const [name, value] of Object.entries(typed)) {
dialog[`matrix_${name}_input`].value = value;
}
dialog.matrix_destination_checkbox.checked = matrix;
await dialog.share_button.onclick();
}""", {"typed": typed, "matrix": matrix})
page.wait_for_timeout(200)
def shared(page):
return [request["body"]["matrix_auth"] for request in page.evaluate("window.requested")
if request["path"] == "/manager/share"]
def test_the_saved_account_is_shown_without_its_password(page):
open_dialog(page, SAVED)
assert fields(page) == {**SAVED, "password": ""}
assert "Saved password" in page.evaluate("dialog.matrix_password_input.placeholder")
assert page.errors == []
def test_the_saved_account_is_shared_with_an_empty_password(page):
open_dialog(page, SAVED)
share_to_matrix(page)
assert shared(page) == [{**SAVED, "password": ""}]
assert page.alerts == []
assert page.errors == []
def test_another_account_needs_a_password(page):
open_dialog(page, SAVED)
share_to_matrix(page, username="someone-else")
assert page.alerts == [ASK_FOR_ACCOUNT]
assert shared(page) == []
def test_the_homeserver_cannot_be_typed(page):
open_dialog(page, SAVED)
assert page.evaluate("dialog.matrix_homeserver_input.readOnly") is True
assert fields(page)["homeserver"] == "matrix.org"
@pytest.mark.parametrize("homeserver", ["other.example", "https://matrix.org", "", None],
ids=["another homeserver", "matrix.org with a scheme", "empty", "null"])
def test_a_saved_homeserver_does_not_reach_the_field_or_the_request(page, homeserver):
open_dialog(page, {"homeserver": homeserver, "username": "user"})
assert fields(page) == {"homeserver": "matrix.org", "username": "user", "password": ""}
share_to_matrix(page)
assert shared(page) == [{"homeserver": "matrix.org", "username": "user", "password": ""}]
assert page.errors == []
def test_a_typed_password_is_sent(page):
open_dialog(page, SAVED)
share_to_matrix(page, username="someone-else", password="a new password")
assert shared(page) == [{"homeserver": "matrix.org", "username": "someone-else", "password": "a new password"}]
assert page.alerts == []
def test_without_a_saved_account_a_password_is_needed(page):
open_dialog(page, None)
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
assert page.evaluate("dialog.matrix_password_input.placeholder") == "Password"
share_to_matrix(page, username="user")
assert page.alerts == [ASK_FOR_ACCOUNT]
assert shared(page) == []
assert page.errors == []
def test_the_account_that_was_shared_is_the_saved_one_afterwards(page):
open_dialog(page, SAVED)
share_to_matrix(page, username="someone-else", password="a new password")
share_to_matrix(page, username="user", password="")
assert page.alerts == [ASK_FOR_ACCOUNT]
share_to_matrix(page, username="someone-else", password="")
assert shared(page)[1:] == [{"homeserver": "matrix.org", "username": "someone-else", "password": ""}]
def test_a_field_changed_and_changed_back_is_the_saved_account(page):
open_dialog(page, SAVED)
share_to_matrix(page, username="someone-else")
share_to_matrix(page, username="user")
assert page.alerts == [ASK_FOR_ACCOUNT]
assert shared(page) == [{**SAVED, "password": ""}]
def test_the_saved_account_that_cannot_be_read_is_no_saved_account(page):
open_dialog(page, SAVED, offline=True)
assert fields(page) == {"homeserver": "matrix.org", "username": "", "password": ""}
share_to_matrix(page, username="user")
assert page.alerts == [ASK_FOR_ACCOUNT]
assert shared(page) == []
assert page.errors == []
def test_sharing_without_matrix_needs_no_account(page):
open_dialog(page, None)
share_to_matrix(page, matrix=False)
assert page.alerts == []
assert page.evaluate("window.requested.at(-1).body.share_destinations") == []
+119
View File
@@ -0,0 +1,119 @@
import ast
import asyncio
import json
import os
import re
from pathlib import Path
from types import SimpleNamespace
import pytest
from aiohttp import web
from manager_test_utils import GLOB_DIR
MENU = Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")) / "comfyui-manager.js"
CHOICES = ["all", "none", "youml", "matrix"]
ROUTE = "/manager/share_option"
@pytest.fixture
def route():
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
nodes = [node for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) and node.name in ("share_option", "set_share_option")
or isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "SHARE_OPTIONS"]
assert len(nodes) == 3
check = next(node for node in ast.parse((GLOB_DIR / "manager_server.py").read_text(encoding="utf-8")).body
if isinstance(node, ast.FunctionDef) and node.name == "_reject_non_json_content_type")
routes = web.RouteTableDef()
config, written, read = {"share_option": "all"}, [], []
namespace = {
"PromptServer": SimpleNamespace(instance=SimpleNamespace(routes=routes)), "web": web, "json": json,
"core": SimpleNamespace(get_config=lambda: config, write_config=lambda: written.append(dict(config))),
}
exec(compile(ast.Module(body=[check, *nodes], type_ignores=[]), "share_3rdparty.py", "exec"), namespace)
def get(query):
response = asyncio.run(namespace["share_option"](SimpleNamespace(rel_url=SimpleNamespace(query=query))))
return response.status, response.text
def post(body, content_type="application/json"):
async def read_json():
read.append(True)
return json.loads(body)
return asyncio.run(namespace["set_share_option"](SimpleNamespace(content_type=content_type, json=read_json))).status
return SimpleNamespace(get=get, post=post, config=config, written=written, read=read, choices=namespace["SHARE_OPTIONS"],
methods=sorted((entry.method, entry.path) for entry in routes))
def test_the_choices_are_those_of_the_share_menu(route):
menu = re.search(r"const share_options = \[(.*?)\];", MENU.read_text(encoding="utf-8"), re.S).group(1)
assert sorted(route.choices) == sorted(re.findall(r"\['(\w+)',", menu)) == sorted(CHOICES)
def test_the_option_is_read_with_get_and_saved_with_post(route):
assert route.methods == [("GET", ROUTE), ("POST", ROUTE)]
@pytest.mark.parametrize("saved", CHOICES)
@pytest.mark.parametrize("value", CHOICES)
def test_a_choice_of_the_menu_is_saved(route, saved, value):
route.config["share_option"] = saved
assert route.post(json.dumps({"value": value})) == 200
assert route.written == [{"share_option": value}]
@pytest.mark.parametrize("value", [
"", " ", "ALL", "All", "all ", " all", "all,none", "none\n", "openart", "comfyworkflows", "true", "<b>all</b>", "all\x00",
"a" * 5000, None, 0, 1, True, ["all"], {"all": "none"},
], ids=repr)
@pytest.mark.parametrize("saved", ["all", "none"])
def test_any_other_value_is_refused_and_nothing_is_saved(route, saved, value):
route.config["share_option"] = saved
assert route.post(json.dumps({"value": value})) == 400
assert route.config == {"share_option": saved}
assert route.written == []
@pytest.mark.parametrize("body", ['{}', '{"other": "none"}', '[]', '["value"]', '"none"', 'null', '1', '', '{"value": "none"', 'value=none',
b'{"value": "\xff"}', b'\xff\xfe'], ids=repr)
def test_a_body_without_a_value_is_refused_and_nothing_is_saved(route, body):
assert route.post(body) == 400
assert route.config == {"share_option": "all"}
assert route.written == []
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "multipart/form-data",
"application/octet-stream"])
def test_a_value_that_is_not_sent_as_json_is_refused_before_the_body_is_read(route, content_type):
assert route.post(json.dumps({"value": "none"}), content_type) == 400
assert route.read == []
assert route.written == []
@pytest.mark.parametrize("saved", [*CHOICES, "openart", ""], ids=lambda saved: saved or "empty")
def test_get_answers_the_saved_option_as_it_is(route, saved):
route.config["share_option"] = saved
assert route.get({}) == (200, saved)
assert route.written == []
@pytest.mark.parametrize("value", [*CHOICES, "openart"])
def test_get_saves_nothing_whatever_it_is_given(route, value):
assert route.get({"value": value}) == (200, "all")
assert route.config == {"share_option": "all"}
assert route.written == []
def test_the_menu_saves_the_option_with_a_json_post():
source = MENU.read_text(encoding="utf-8")
assert "share_option?value=" not in source
assert re.search(r"fetchApi\(\s*'/manager/share_option'\s*,\s*\{[^;]*?\bmethod:\s*'POST'[^;]*?\bbody:\s*JSON\.stringify\(\{\s*value\s*\}\)",
source)
+71
View File
@@ -0,0 +1,71 @@
import asyncio
import logging
import os
import shutil
from types import SimpleNamespace
import pytest
from aiohttp import web
from test_comfyui_downgrade_level import LEVELS, functions
SERVER = {"is_allowed_security_level", "security_403_response", "_reject_non_json_content_type", "restore_snapshot"}
def restore_allowed(security_level, loopback):
return security_level == "weak" or security_level == "normal-" and loopback
@pytest.fixture
def server(tmp_path):
snapshot = tmp_path / "snapshots" / "saved.json"
snapshot.parent.mkdir()
snapshot.write_text("{}", encoding="utf-8")
scheduled = tmp_path / "startup-scripts" / "restore-snapshot.json"
def restore(security_level, loopback, body={"target": "saved"}, content_type="application/json"):
namespace = {
"routes": web.RouteTableDef(), "web": web, "logging": logging, "os": os, "shutil": shutil,
"is_local_mode": loopback,
"core": SimpleNamespace(get_config=lambda: {"security_level": security_level},
manager_startup_script_path=str(scheduled.parent)),
"manager_migration": SimpleNamespace(has_system_user_api=lambda: True),
"get_safe_snapshot_path": lambda target: str(snapshot) if target == "saved" else None,
}
exec(functions("manager_server.py", SERVER), namespace)
async def read_json():
return body
response = asyncio.run(namespace["restore_snapshot"](SimpleNamespace(json=read_json, content_type=content_type)))
return response.status, scheduled.exists()
return restore
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
def test_a_restore_needs_the_level_of_a_switch_to_an_older_version(server, security_level, loopback):
status, scheduled = server(security_level, loopback)
if restore_allowed(security_level, loopback):
assert (status, scheduled) == (200, True)
else:
assert (status, scheduled) == (403, False)
@pytest.mark.parametrize("loopback", [True, False], ids=["loopback", "not loopback"])
@pytest.mark.parametrize("security_level", LEVELS)
@pytest.mark.parametrize("body", [{"target": "another"}, {"target": ""}, {"target": None}, {}, {"target": ["saved"]}],
ids=["a snapshot that does not exist", "an empty name", "null", "no target", "a list"])
def test_a_request_for_no_snapshot_schedules_nothing_at_any_level(server, security_level, loopback, body):
status, scheduled = server(security_level, loopback, body)
assert status == (400 if restore_allowed(security_level, loopback) else 403)
assert scheduled is False
@pytest.mark.parametrize("security_level", LEVELS)
@pytest.mark.parametrize("content_type", ["text/plain", "application/x-www-form-urlencoded", "application/octet-stream"])
def test_a_body_that_is_not_json_is_refused_before_the_level(server, security_level, content_type):
assert server(security_level, True, content_type=content_type) == (400, False)
+2 -2
View File
@@ -27,7 +27,7 @@ core = manager_core
nodes = pathlib.Path(tmp) / 'custom_nodes'
nodes.mkdir()
core.get_default_custom_nodes_path = lambda: str(nodes)
manager_util.restore_pip_snapshot = Mock()
manager_util.restore_pip_snapshot = Mock(return_value=[])
manager = core.UnifiedManager()
manager.reload = AsyncMock()
manager.get_custom_nodes = AsyncMock(return_value={})
@@ -36,7 +36,7 @@ core.unified_manager = manager
def restore(**snapshot):
path = pathlib.Path(tmp) / 'snapshot.json'
path.write_text(json.dumps({'cnr_custom_nodes': {}, 'git_custom_nodes': {}, 'file_custom_nodes': [], **snapshot}))
asyncio.run(core.restore_snapshot(str(path)))
return asyncio.run(core.restore_snapshot(str(path)))
def git(*args):
return subprocess.run(['git', *args], cwd=nodes / 'fixture', check=True, capture_output=True, text=True).stdout.strip()
+76
View File
@@ -0,0 +1,76 @@
import json
import os
from pathlib import Path
import pytest
from js_lift import NODE, JsSource, run_node, slice_braced
JS = JsSource(Path(os.environ.get("MANAGER_JS_DIR") or (Path(__file__).resolve().parent.parent / "js")))
pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to execute the lifted production JS")
def switch(version, status, versions_status=200):
script = """
const shown = [], requested = [];
const api = {fetchApi: async (path, options) => {
if(path == '/comfyui_manager/comfyui_versions') {
return {status: %s, json: async () => ({versions: ['nightly', 'v0.3.60'], current: 'v0.3.59'})};
}
requested.push({path, body: JSON.parse(options.body)});
return {status: path == '/comfyui_manager/comfyui_switch_version' ? %s : 200};
}};
const switch_comfyui_button = {style: {}};
const update_policy_combo = {value: 'unchanged'};
let update_policy_chosen = false;
let chosen;
const showVersionSelectorDialog = (versions, current, onSelect) => { chosen = onSelect(%s); };
const infoToast = (text) => shown.push('toast: ' + text);
const customAlert = (text) => shown.push('alert: ' + text);
const handle403Response = async () => shown.push('security level message');
%s
await switchComfyUI();
await chosen;
console.log(JSON.stringify({shown, requested, update_policy: update_policy_combo.value, update_policy_chosen,
button_disabled: switch_comfyui_button.disabled}));
""" % (json.dumps(versions_status), json.dumps(status), json.dumps(version),
slice_braced(JS.text("comfyui-manager.js"), "async function switchComfyUI()"))
return run_node(script)
def switch_request(version):
return {"path": "/comfyui_manager/comfyui_switch_version", "body": {"ver": version}}
@pytest.mark.parametrize("version, update_policy", [("nightly", "nightly-comfyui"), ("v0.3.60", "stable-comfyui")])
def test_a_switch_that_happened_sets_the_update_policy_of_the_version(version, update_policy):
did = switch(version, 200)
assert did["requested"] == [switch_request(version), {"path": "/manager/policy/update", "body": {"value": update_policy}}]
assert did["update_policy"] == update_policy
assert did["update_policy_chosen"] is True
assert did["shown"] == ["toast: ComfyUI version is switched to " + version]
@pytest.mark.parametrize("version", ["nightly", "v0.3.60"])
@pytest.mark.parametrize("status, shown", [
(403, "security level message"),
(400, "alert: Failed to switch ComfyUI version."),
(500, "alert: Failed to switch ComfyUI version."),
])
def test_a_switch_that_did_not_happen_leaves_the_update_policy(version, status, shown):
did = switch(version, status)
assert did["requested"] == [switch_request(version)]
assert did["update_policy"] == "unchanged"
assert did["update_policy_chosen"] is False
assert did["shown"] == [shown]
def test_without_the_list_of_versions_nothing_is_switched():
did = switch("v0.3.60", 200, versions_status=400)
assert did["requested"] == []
assert did["shown"] == ["alert: Failed to fetch ComfyUI versions."]
assert did["button_disabled"] is False
+496
View File
@@ -0,0 +1,496 @@
import ast
import json
import logging
import os
import shutil
import subprocess
import sys
import types
import zipfile
import pytest
from manager_test_utils import GLOB_DIR, load_manager_util
from test_install_flags_config import _CHILD_PREAMBLE, REPO_ROOT
PRESTARTUP_SCRIPT = GLOB_DIR.resolve().parent / 'prestartup_script.py'
OTHER_ENCODING = {'LC_ALL': 'C', 'PYTHONUTF8': '0', 'PYTHONCOERCECLOCALE': '0'}
def download_url(url, directory, name, member='__init__.py'):
with zipfile.ZipFile(os.path.join(directory, name), 'w') as archive:
archive.writestr(member, 'VERSION = 2')
def download_that_is_not_a_zip(url, directory, name):
with open(os.path.join(directory, name), 'w') as file:
file.write('<html></html>')
def startup_functions(set_module, download=download_url, **module_globals):
"""Importing prestartup_script would run the start-up."""
cli_args = types.ModuleType('comfy.cli_args')
cli_args.args = types.SimpleNamespace(listen='127.0.0.1')
set_module('comfy', types.ModuleType('comfy'))
set_module('comfy.cli_args', cli_args)
functions = [node for node in ast.parse(PRESTARTUP_SCRIPT.read_text(encoding='utf-8')).body
if isinstance(node, ast.FunctionDef) and node.name in ('execute_lazy_cnr_switch', 'execute_lazy_install_script', 'execute_startup_script')]
scope = {'os': os, 'ast': ast, 'logging': logging, 'default_conf': {}, 'manager_util': load_manager_util(),
'manager_downloader': types.SimpleNamespace(download_url=download), **module_globals}
exec(compile(ast.Module(body=functions, type_ignores=[]), str(PRESTARTUP_SCRIPT), 'exec'), scope)
return scope
def reserved_switch(set_module, download=download_url):
return startup_functions(set_module, download)['execute_lazy_cnr_switch']
@pytest.fixture
def switch(monkeypatch):
return reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module))
def old_version(custom_nodes, directory, *tracked):
old = custom_nodes / directory
old.mkdir(parents=True)
for name in ('__init__.py', 'removed.py'):
(old / name).write_text('VERSION = 1')
(old / '.tracking').write_text('\n'.join(('__init__.py', *tracked)), encoding='utf-8')
(custom_nodes / 'removed.py').write_text('a file that is not of the pack')
return old
def switch_at_once(custom_nodes, encoding=(), member='__init__.py', not_a_zip=False):
script = _CHILD_PREAMBLE.format(glob_path=str(REPO_ROOT / 'glob')) + '''
import pathlib, zipfile
from types import SimpleNamespace
from unittest.mock import Mock
core = manager_core
custom_nodes = pathlib.Path(%r)
member, not_a_zip = %r, %r
def download(url, directory, name):
if not_a_zip:
(pathlib.Path(directory) / name).write_text('<html></html>')
return
with zipfile.ZipFile(pathlib.Path(directory) / name, 'w') as archive:
archive.writestr(member, 'VERSION = 2')
core.get_default_custom_nodes_path = lambda: str(custom_nodes)
core.manager_downloader.basic_download_url = download
manager = core.UnifiedManager()
manager.active_nodes['fixture'] = ('1.0.0', str(custom_nodes / 'fixture'))
manager.execute_install_script = Mock(return_value=True)
version = SimpleNamespace(version='2.0.0', download_url='https://example.invalid/fixture.zip', status='NodeVersionStatusActive')
print(json.dumps(manager._cnr_switch_version('fixture', version, instant_execution=True, no_deps=True).result))
''' % (str(custom_nodes), member, not_a_zip)
child = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True, cwd=str(REPO_ROOT), env={**os.environ, **dict(encoding)})
assert child.returncode == 0, child.stderr[-600:]
return json.loads(child.stdout.strip().splitlines()[-1])
def test_files_that_the_new_version_lacks_are_removed_from_the_pack(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (custom_nodes / 'removed.py').exists()
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
assert (new / '__init__.py').read_text() == 'VERSION = 2'
@pytest.mark.parametrize('name', ['../removed.py', '{custom_nodes}/removed.py'])
def test_reserved_switch_leaves_a_file_outside_the_pack(switch, tmp_path, name):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', name.format(custom_nodes=custom_nodes)), custom_nodes / 'fixture@2_0_0'
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (custom_nodes / 'removed.py').exists()
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'removed.py']
@pytest.mark.parametrize('name, inside', [
('removed.py', True), ('nodes/removed.py', True), ('nodes/', True), ('nodes/../removed.py', True), ('', True),
('..', False), ('../removed.py', False), ('nodes/../../removed.py', False), ('{pack}/../removed.py', False),
('{pack}/removed.py', True), ('{pack}@2/removed.py', False),
])
def test_name_of_a_file_of_the_pack(tmp_path, name, inside):
pack = tmp_path / 'custom_nodes/fixture'
pack.mkdir(parents=True)
assert load_manager_util().is_inside(str(pack), name.format(pack=pack)) is inside
@pytest.mark.parametrize('name', ['removed.py', '../removed.py', '{custom_nodes}/removed.py'])
def test_switch_at_once_removes_the_files_of_the_pack_alone(tmp_path, name):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', name.format(custom_nodes=custom_nodes))
assert switch_at_once(custom_nodes) is True
assert (custom_nodes / 'removed.py').exists()
assert sorted(os.listdir(pack)) == (['.tracking', '__init__.py'] if name == 'removed.py' else ['.tracking', '__init__.py', 'removed.py'])
def test_reserved_switch_keeps_a_file_that_the_new_archive_names_in_another_way(monkeypatch, tmp_path):
"""`__init__.py` and `./__init__.py` are extracted to the same file."""
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module),
lambda url, directory, name: download_url(url, directory, name, './__init__.py'))
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (new / '__init__.py').read_text() == 'VERSION = 2'
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
def test_switch_at_once_keeps_a_file_that_the_new_archive_names_in_another_way(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', 'removed.py')
assert switch_at_once(custom_nodes, member='./__init__.py') is True
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
def two_names_of_one_file(pack):
try:
(pack / 'alias').symlink_to('.', target_is_directory=True)
except OSError:
pytest.skip('a link cannot be made here')
def test_reserved_switch_keeps_a_file_that_the_old_list_names_in_a_way_of_its_own(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'alias/__init__.py'), custom_nodes / 'fixture@2_0_0'
two_names_of_one_file(old)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (new / '__init__.py').read_text() == 'VERSION = 2'
def test_switch_at_once_keeps_a_file_that_the_old_list_names_in_a_way_of_its_own(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', 'alias/__init__.py')
two_names_of_one_file(pack)
assert switch_at_once(custom_nodes) is True
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
def test_reserved_switch_removes_a_folder_that_the_new_version_lacks(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(old / 'olddir').mkdir()
(old / 'olddir/old.py').write_text('VERSION = 1')
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
def modules_that_were_imported(pack):
"""`olddir/a/b/c/d/old.py`, and what Python and numba write beside a module that is imported, which no list names."""
(pack / 'olddir/a/b/c/d/__pycache__').mkdir(parents=True)
(pack / 'olddir/__pycache__').mkdir()
(pack / 'olddir/a/b/c/d/old.py').write_text('VERSION = 1')
for cache in (pack / 'olddir/a/b/c/d/__pycache__', pack / 'olddir/__pycache__'):
for name in ('old.cpython-312.pyc', 'old.run-3.py312.nbi', 'old.run-3.py312.1.nbc'):
(cache / name).write_bytes(b'')
TRACKED = pytest.mark.parametrize('tracked', [
('olddir/a/b/c/d/old.py',),
('olddir/', 'olddir/a/', 'olddir/a/b/', 'olddir/a/b/c/', 'olddir/a/b/c/d/', 'olddir/a/b/c/d/old.py'),
], ids=['the list names the files alone', 'the list names the folders as well'])
@TRACKED
def test_reserved_switch_removes_the_folders_that_the_old_files_leave_empty(switch, tmp_path, tracked):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', *tracked, 'removed.py'), custom_nodes / 'fixture@2_0_0'
modules_that_were_imported(old)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
@TRACKED
def test_reserved_switch_puts_a_file_where_the_old_version_has_a_folder(monkeypatch, tmp_path, tracked):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', *tracked), custom_nodes / 'fixture@2_0_0'
modules_that_were_imported(old)
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module),
lambda url, directory, name: download_url(url, directory, name, member='olddir'))
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (new / 'olddir').read_text() == 'VERSION = 2'
def test_reserved_switch_keeps_a_folder_with_a_file_that_is_not_of_the_old_version(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(old / 'olddir/a').mkdir(parents=True)
(old / 'olddir/a/old.py').write_text('VERSION = 1')
(old / 'olddir/made by the user.txt').write_text('kept')
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new / 'olddir')) == ['made by the user.txt']
def test_reserved_switch_removes_an_empty_folder_that_the_list_names(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(old / 'olddir').mkdir()
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
def test_reserved_switch_keeps_a_folder_that_is_in_the_cache(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(old / 'olddir/__pycache__/made by the user').mkdir(parents=True)
(old / 'olddir/old.py').write_text('VERSION = 1')
(old / 'olddir/__pycache__/made by the user/kept.txt').write_text('kept')
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (new / 'olddir/__pycache__/made by the user/kept.txt').read_text() == 'kept'
def link_of_a_folder(link, target, junction):
"""A symbolic link, or a junction, which Windows makes without a privilege."""
if junction:
subprocess.run(['cmd', '/c', 'mklink', '/J', str(link), str(target)], check=True, capture_output=True)
return
try:
link.symlink_to(target, target_is_directory=True)
except OSError:
pytest.skip('a link cannot be made here')
@pytest.mark.parametrize('junction', [False, pytest.param(True, marks=pytest.mark.skipif(os.name != 'nt', reason='a junction is of Windows'))],
ids=['symbolic link', 'junction'])
@pytest.mark.parametrize('link, cache', [('olddir', 'olddir/__pycache__'), ('olddir/__pycache__', 'olddir/__pycache__'), ('olddir', 'olddir/a/__pycache__')],
ids=['the folder is a link', 'the cache is a link', 'the folder is behind a link'])
def test_reserved_switch_leaves_the_cache_behind_a_link(switch, tmp_path, link, cache, junction):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', os.path.dirname(cache) + '/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
kept = tmp_path / 'elsewhere' / cache[len(link) + 1:] / 'other.cpython-312.pyc'
kept.parent.mkdir(parents=True)
kept.write_bytes(b'')
(old / link).parent.mkdir(exist_ok=True)
link_of_a_folder(old / link, tmp_path / 'elsewhere', junction)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert kept.exists()
assert (new / link).is_dir()
def test_reserved_switch_leaves_a_folder_behind_a_link(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(tmp_path / 'elsewhere/a').mkdir(parents=True)
(tmp_path / 'elsewhere/a/old.py').write_text('VERSION = 1')
link_of_a_folder(old / 'olddir', tmp_path / 'elsewhere', False)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert (tmp_path / 'elsewhere/a').is_dir()
def test_reserved_switch_removes_the_folders_of_a_pack_that_is_reached_through_a_link(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
(tmp_path / 'elsewhere').mkdir()
link_of_a_folder(custom_nodes, tmp_path / 'elsewhere', False)
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/a/b/c/d/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
modules_that_were_imported(old)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
def file_that_cannot_be_removed(pack):
(pack / 'olddir').mkdir()
(pack / 'olddir/old.py').write_text('VERSION = 1')
(pack / 'olddir').chmod(0o555)
if os.access(pack / 'olddir', os.W_OK):
pytest.skip('the file can be removed here, as by root or on Windows')
def archives(custom_nodes):
return [name for name in os.listdir(custom_nodes) if name.endswith('.zip')]
def test_reserved_switch_goes_on_past_a_file_that_cannot_be_removed(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/old.py', 'removed.py'), custom_nodes / 'fixture@2_0_0'
file_that_cannot_be_removed(old)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'olddir']
assert (new / '__init__.py').read_text() == 'VERSION = 2'
assert archives(custom_nodes) == []
def test_switch_at_once_goes_on_past_a_file_that_cannot_be_removed(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', 'olddir/old.py', 'removed.py')
file_that_cannot_be_removed(pack)
assert switch_at_once(custom_nodes) is True
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'olddir']
assert (pack / '__init__.py').read_text() == 'VERSION = 2'
assert archives(custom_nodes) == []
def test_reserved_switch_goes_on_past_a_folder_that_cannot_be_removed(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'olddir/', 'removed.py'), custom_nodes / 'fixture@2_0_0'
(old / 'olddir').mkdir(mode=0)
if os.access(old / 'olddir', os.R_OK):
pytest.skip('the folder can be read here, as by root or on Windows')
try:
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'olddir']
assert (new / '__init__.py').read_text() == 'VERSION = 2'
finally:
(next(pack for pack in (new, old) if pack.exists()) / 'olddir').chmod(0o700)
def test_reserved_switch_does_not_move_a_pack_that_keeps_its_directory(switch, monkeypatch, tmp_path):
def move(source, target):
raise PermissionError(13, 'Access is denied', source, 5, target)
monkeypatch.setattr(shutil, 'move', move)
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', 'removed.py')
assert switch('fixture', 'https://example.invalid/fixture.zip', str(pack), str(pack), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
assert (pack / '.tracking').read_text() == '__init__.py'
def test_install_script_of_a_reserved_switch_runs_where_the_pack_was_moved_to(monkeypatch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture'
commands = []
startup = startup_functions(lambda name, module: monkeypatch.setitem(sys.modules, name, module),
lambda url, directory, name: download_url(url, directory, name, 'install.py'),
script_list_path=str(tmp_path / 'install-scripts.txt'), processed_install=set(), comfy_path=str(tmp_path),
process_wrap=lambda command, cwd=None, **options: commands.append((command, cwd)) or 0)
(tmp_path / 'install-scripts.txt').write_text(repr(
['fixture', '#LAZY-CNR-SWITCH-SCRIPT', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'python', 'NodeVersionStatusActive']))
startup['execute_startup_script']()
assert commands == [(['python', 'install.py'], str(new))]
def test_reserved_switch_that_fails_leaves_no_archive(switch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0'), custom_nodes / 'fixture@2_0_0'
(old / '.tracking').unlink()
with pytest.raises(FileNotFoundError):
switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert archives(custom_nodes) == []
def test_switch_at_once_that_fails_leaves_no_archive(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
(old_version(custom_nodes, 'fixture') / '.tracking').unlink()
with pytest.raises(AssertionError, match='FileNotFoundError'):
switch_at_once(custom_nodes)
assert archives(custom_nodes) == []
def test_reserved_switch_to_a_download_that_is_not_a_zip_leaves_the_pack_as_it_is(monkeypatch, tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', 'removed.py'), custom_nodes / 'fixture@2_0_0'
switch = reserved_switch(lambda name, module: monkeypatch.setitem(sys.modules, name, module), download_that_is_not_a_zip)
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive') is False
assert not new.exists()
assert sorted(os.listdir(old)) == ['.tracking', '__init__.py', 'removed.py']
assert (old / '__init__.py').read_text() == 'VERSION = 1'
assert archives(custom_nodes) == []
def test_switch_at_once_to_a_download_that_is_not_a_zip_leaves_the_pack_as_it_is(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', 'removed.py')
assert switch_at_once(custom_nodes, not_a_zip=True) is False
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'removed.py']
assert (pack / '__init__.py').read_text() == 'VERSION = 1'
assert archives(custom_nodes) == []
def test_reserved_switch_reads_the_list_as_it_is_written(tmp_path):
"""The file with the Korean name is not there: the file system of the child cannot name it."""
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', '예제 사용자.json', 'removed.py'), custom_nodes / 'fixture@2_0_0'
call = ('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
script = (f'import sys; sys.path.insert(0, {os.path.dirname(__file__)!r})\n'
'import test_version_switch_old_files as cases\n'
f'sys.exit(not cases.reserved_switch(sys.modules.__setitem__)(*{call!r}))\n')
child = subprocess.run([sys.executable, '-c', script], capture_output=True, text=True, env={**os.environ, **OTHER_ENCODING})
assert child.returncode == 0, child.stderr[-600:]
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py']
def test_switch_at_once_reads_the_list_as_it_is_written(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', '예제 사용자.json', 'removed.py')
assert switch_at_once(custom_nodes, OTHER_ENCODING) is True
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py']
def test_reserved_switch_reads_a_name_with_a_space_at_its_start_as_it_is_written(switch, tmp_path):
"""`removed.py` is not in the list: it is a file that someone put into the node pack."""
custom_nodes = tmp_path / 'custom_nodes'
old, new = old_version(custom_nodes, 'fixture@1_0_0', ' removed.py'), custom_nodes / 'fixture@2_0_0'
(old / ' removed.py').write_text('VERSION = 1')
assert switch('fixture', 'https://example.invalid/fixture.zip', str(old), str(new), False, str(custom_nodes), 'NodeVersionStatusActive')
assert sorted(os.listdir(new)) == ['.tracking', '__init__.py', 'removed.py']
def test_switch_at_once_reads_a_name_with_a_space_at_its_start_as_it_is_written(tmp_path):
custom_nodes = tmp_path / 'custom_nodes'
pack = old_version(custom_nodes, 'fixture', ' removed.py')
(pack / ' removed.py').write_text('VERSION = 1')
assert switch_at_once(custom_nodes) is True
assert sorted(os.listdir(pack)) == ['.tracking', '__init__.py', 'removed.py']
-7
View File
@@ -40,13 +40,6 @@ Harness: the subprocess-isolated child from `tests/test_install_flags_config.py`
— stub `folder_paths`, `glob/` on the CHILD's sys.path only, `manager_core`
imported (NEVER `manager_server`: module level starts a network thread at
`:2093`), `manager_config_path` pointed at a tmp file, `cached_config` reset.
`force_security_level_if_needed` (MM HAZARD C-1) is NOT stubbed — it runs on
the real `read_config` path. The `folder_paths` stub supplies a system-user
directory, so `has_system_user_api()` is True and the function takes its
no-force branch and returns without mutating. The alias-mutation branch is
therefore present but not exercised here; the GREEN step must keep it in view
when it pins the dirty-tracking wrap point.
"""
import json
import subprocess
+49
View File
@@ -0,0 +1,49 @@
import ast
import pytest
from manager_test_utils import GLOB_DIR
from test_grid_highlight_escaping import browser # noqa: F401 -- fixture
from test_share_dialog_matrix_password import EXTENSION, page # noqa: F401 -- fixture
def test_the_server_has_no_route_for_the_token():
source = (GLOB_DIR / "share_3rdparty.py").read_text(encoding="utf-8")
paths = [decorator.args[0].value for node in ast.parse(source).body
if isinstance(node, ast.AsyncFunctionDef) for decorator in node.decorator_list]
assert "/manager/share" in paths
assert [path for path in paths if "youml" in path] == []
def open_dialog(page, stored): # noqa: F811
page.evaluate("""async ({stored, module}) => {
window.requested = [];
localStorage.clear();
if(stored !== null) localStorage.setItem('youml_token', stored);
const { YouMLShareDialog } = await import(module);
window.dialog = new YouMLShareDialog();
await window.dialog.show([], []);
}""", {"stored": stored, "module": EXTENSION + "comfyui-share-youml.js"})
@pytest.mark.parametrize("stored, shown", [(None, ""), ("", ""), ("the token", "the token")],
ids=["nothing stored", "an empty token", "a token"])
def test_the_dialog_opens_with_the_stored_token(page, stored, shown): # noqa: F811
open_dialog(page, stored)
assert page.evaluate("dialog.apiTokenInput.value") == shown
assert page.evaluate("window.requested") == []
assert page.errors == []
def test_sharing_stores_the_token_in_the_browser(page): # noqa: F811
open_dialog(page, "an old token")
page.evaluate("""async () => {
dialog.apiTokenInput.value = 'a new token';
await dialog.handleShareButtonClick();
}""")
assert page.evaluate("localStorage.getItem('youml_token')") == "a new token"
assert [request for request in page.evaluate("window.requested") if "youml" in request["path"]] == []