Compare commits

...
Author SHA1 Message Date
Dr.Lt.Data b03a75239f Merge branch 'manager-v4' into desktop-linux-form-factor 2026-12-02 12:55:48 +09:00
Koray Ulusan fdc9c1177d v4: --mode remote reads the channel when the Manager is installed as a pip package (#3590)
When the Manager is installed as a pip package, every mode read the
cached list of the channel, or the list that comes with the package.
`--mode remote` did not read the channel, so a nodepack that was added
to the channel after the package was built did not show.

- `get_data_by_mode` of both cores reads the list from the channel and
  caches it in remote mode on a pip install, unless `network_mode` is
  offline. `cm-cli` uses the legacy core, the server either
- When that read fails, a message says so and the list is read as cache
  mode reads it on a pip install: from the cache, else from the package
- The other modes, offline mode and installs that are not a pip package
  are unchanged
- Add tests and a CHANGELOG entry
2026-12-02 12:55:37 +09:00
Dr.Lt.Data 6c22515d55 v4: The legacy Model Manager finds a model in a subfolder of an extra model path (#3633)
A model whose folder in the list has a subfolder, such as
`checkpoints/SD1.5`, was shown as not installed when its file was in
that subfolder of a folder that `extra_model_paths.yaml` adds (#1844).
The row offered Install, and the Installed filter left it out.

- After its checks, `check_model_installed` asks
  `folder_paths.get_full_path` for the rest of the save path and the
  file name, under the first folder of the save path. ComfyUI looks in
  every folder it has for that name, the extra ones included
- The copy of the function in `glob/utils/model_utils.py` gets the same
  check
- The check only adds a way to be found, so a model that was shown as
  installed still is
- Add tests and a CHANGELOG entry

The same change for main is #3631.
2026-12-02 12:45:43 +09:00
Reinis 86634380db v4: A download through aria2 works again, and one that fails is reported as failed (#3246)
With `COMFYUI_MANAGER_ARIA2_SERVER` set, the install of a registry
nodepack or of a model failed with `No module named 'manager_core'`:
`aria2_download_url` imported the core by its name of the main line
(#3064).

- `aria2_download_url` reads `comfy_path` from
  `comfyui_manager.common.context`, so the download goes through aria2
  again
- It waits while aria2 has the download waiting or active, and fails
  with the error message of aria2 when aria2 fails it
- It fails when the file is not at `<model_dir>/<filename>` once the
  download is over, naming the folder aria2 wrote to and
  `docs/en/use_aria2.md`
- A download of the same file that aria2 still lists is reused only
  while it is waiting or active, or when it is complete and its file is
  there
- Add tests and a CHANGELOG entry
2026-12-02 12:36:54 +09:00
Dr.Lt.Data aa58d0ff43 v4: A conflict in the legacy Custom Nodes Manager counts only enabled nodepacks (#3636)
The Nodes column of the legacy Custom Nodes Manager counted a conflict
for every node name that another nodepack in the list also has, whether
that nodepack is installed or not. An enabled nodepack showed
`N conflicts` for nodepacks that are disabled or not installed, which
ComfyUI does not load (#3092).

- A conflict counts only another enabled nodepack. An enabled nodepack
  shows `N conflicts`, and its node list says
  `Conflict with enabled packs`
- A disabled or not installed nodepack shows `N potential conflicts`
  for the enabled nodepacks it would conflict with, and its node list
  says `Potential conflict if installed/enabled with`
- Two nodepacks that are both not enabled show nothing for each other
- `N potential conflicts` takes two lines in the Nodes column, which is
  100px wide
- Add tests and a CHANGELOG entry

The same change for main is #3273.
2026-12-02 09:08:02 +09:00
Dr.Lt.Data 24b27b7ea6 v4: An install without a version enables a disabled registry nodepack, and Enable fails for one the registry data does not list (#3638)
An install without a version did not see a registry nodepack that was
disabled: with the nodepack disabled at 1.0.0 and the registry at
2.0.0, `cm-cli install <id>` installed 2.0.0. And Enable reported
success for a disabled nodepack that the registry data does not list,
while nothing was enabled (#3469).

- `is_disabled()` of both cores counts a disabled registry version when
  no version is given, so the install enables it with no download
- `unified_enable()` fails with `Specified inactive node not exists:
  <id>` when it can name no version to enable, unless the nodepack is
  enabled. Enable then reports `Failed to enable: '<id>'`
- An install without a version leaves out the disabled versions whose
  folder is gone, when one is left, and enables the newest that is
  there
- Add tests and a CHANGELOG entry

The same change for main is #3528.
2026-12-02 02:34:18 +09:00
Dr.Lt.Data e2124a8585 v4: A nodepack that two node mappings name shows all its nodes in the legacy Custom Nodes Manager, and the list is drawn (#3635)
Two node mappings can name one nodepack, one by its id or git URL and
one by its `title_aux`. In the legacy Custom Nodes Manager the second
mapping replaced the nodes of the first. When another nodepack had a
node of the first mapping, the page failed with `TypeError: Cannot read
properties of undefined (reading 'conflicts')` and drew no list (#2502).
A node that both mappings name showed a conflict with no other
nodepack, or each other nodepack twice.

- `loadNodes()` adds the mappings of one nodepack to one node map and
  skips a name that is already in it, so each pair of name and nodepack
  enters the conflict map once
- The Nodes column and the node list of such a nodepack have the nodes
  of both mappings, so a row can list more nodes than before
- The conflict pass is not changed, and the Nodes Manager of the
  ComfyUI frontend does not run this code
- Add a test and a CHANGELOG entry

The same change for main is #3629.
2026-12-02 02:14:21 +09:00
Dr.Lt.Data 0f7d5f588b v4: An install from a Git URL installs the dependencies when Windows cannot read requirements.txt (#3637)
An install of a nodepack from a Git URL (Install via Git URL of the
legacy Custom Nodes Manager, `cm-cli install <url>`,
`cm-cli install-deps`) read its `requirements.txt` in the encoding of
the locale, which on Windows is the ANSI code page. A UTF-8 file with a
Chinese or Korean comment failed with `UnicodeDecodeError`, and the
nodepack was cloned without its dependencies.

- Read the file of a Git URL install with the new
  `read_requirements_lines()` in both cores: when the locale cannot
  read it, take the encoding that `chardet` names, if that encoding
  reads ASCII bytes as ASCII or is UTF-16/32 and every line is
  printable ASCII outside its comment
- Otherwise fail with the same `UnicodeDecodeError` as before, as for a
  file that is not text or a requirement with a non-ASCII path. Such a
  failure no longer installs the lines in front of the byte it fails on
- Leave `robust_readlines()`, the Registry install and the install at
  startup as they are
- Add tests and a CHANGELOG entry

The same change for main is #3520.
2026-12-02 01:54:18 +09:00
Can H. Tartanoglu d972b17712 v4: dependency_management = off turns off the changes that the Manager makes to Python packages on its own (#2851)
On a Python that cannot be changed, such as one of Nix, Guix or a
distribution, the Manager ran pip at every start and after an install.
It could uninstall `comfy`, install torch again and install the packages
of `pip_auto_fix.list`, and with `use_unified_resolver = True` the
startup batch of the resolver installed packages.

- Add `dependency_management = off` for the `[default]` section of
  `config.ini`, and `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=off`, which
  wins over `config.ini`. With either, none of this runs. The setting is
  on by default, and while it is unset nothing changes
- Install the requirements of an install or update that is asked for
  whatever the setting, also of one that is applied at the next restart.
  The `install.py` of a nodepack still runs
- Apply the setting in `cm-cli` as well, including the `cm-cli` that the
  startup runs to restore a snapshot
- Where the setting skips the startup batch of the resolver, turn the
  resolver off for the session, so that an install uses pip for each
  nodepack
- Say so in the README, and add tests and a CHANGELOG entry
2026-12-02 00:43:47 +09:00
Dr.Lt.Data d917f19598 v4: A nodepack that only the registry lists shows Update in the legacy Custom Nodes Manager when the registry has a newer version (#3634)
A nodepack that is in the registry and not in the node list never showed
Update in the legacy Custom Nodes Manager, and the Update filter did not
list it, even when the registry had a newer version (#3220). Its row
showed Try update, which did update it, but nothing said that an update
was there.

- Give the rows of registry-only nodepacks the `update-state` that the
  page reads, as the rows of the node list have: `true` for an enabled
  nodepack with a newer version in the registry, `false` otherwise. The
  same lines in the glob and the legacy core
- Offer no Update for a nodepack installed as nightly, as for a
  nodepack of the node list
- A registry-only nodepack that failed to import and has a newer
  version shows Update in place of `IMPORT FAILED` and Try fix, as the
  row of a nodepack of the node list already did. The Import Failed
  filter still lists it
- The Nodes Manager already offered Update for such a nodepack and is
  not changed
- Add tests and a CHANGELOG entry

The same change for main is #3261.
2026-12-01 19:14:01 +09:00
H.W.Prinz de0a6111aa v4: The log file has no color codes of the console (#3466)
The Manager writes what ComfyUI prints to the console and to the log
file, `comfyui.log` in the user directory. The color codes of the
console, such as `ESC[32m`, went into the file as well, where an editor
or `grep` shows them as text.

- Leave the color codes out of what is written to the log file: an
  `ESC[` sequence of digits, `;` and `?` that ends in a letter. The
  console gets the text as before, with its colors
- Read the setting `strip_ansi_file_logging` of `config.ini`. Without
  the key the codes are left out, and with `false` the file keeps them
  as before
- Add tests and a CHANGELOG entry

The same change for main is #3315.
2026-12-01 12:25:01 +09:00
Dr.Lt.Data 6fe0d72dc4 v4: Restore the PyTorch builds that were installed before a nodepack (#3618)
When a nodepack changed torch or torchvision, torch_rollback() chose
what to install from the torch version from before. Without a local
label it sent `pip install --force` with the package names, which
installs the newest releases and which uv refuses. With a label it sent
the versions of a table that ends at 2.7.0, or the newest nightly build
for a version that the table lacks. A nodepack that removed torch, or
removed torchvision and left torch as it was, ended the restore in a
KeyError.

- Give torch_rollback() what was installed before and after the
  nodepack, and the names that the torch from before requires, read when
  PIPFixer is constructed. Count a removed torch or torchvision as
  changed
- Install the torch from before as `torch===<build>` with its
  dependencies, then a changed torchvision or torchaudio with
  `--no-deps`, from https://download.pytorch.org/whl/<label> for a local
  label and from the nightly index for a development build
- Put back with torch each of its requirements, still at its version,
  with a file on disk that is not of the size its RECORD gives, such as
  CUDA libraries that a torch of another CUDA version overwrote. pip
  fetches them before torch is replaced
- Resolve last `torch===<build> torchvision torchaudio<next minor>` with
  dependencies: what fits torch stays, what does not is replaced, a
  removed dependency comes back
- Check in a child process that torch, torchvision and torchaudio work.
  For a torch that does not, install again its requirements with a file
  that is gone. Install a torchvision or torchaudio that does not again
  from torch's index, and log an ERROR for what still does not work
- When the torch from before cannot be had, restore by the version table
  as before. Renew the table up to 2.15.0
- With uv, send the command that installs torch, or a changed
  torchvision or torchaudio, at its build only in a form whose
  `--dry-run` resolved, and once more when it fails while it installs
- Do not start the restore when the disk of site-packages has less free
  space than the restore can take: twice the size of what is installed
  again with pip, one and a half times with uv. PIPFixer reads the sizes
  when it is constructed
- Run pip without its cache during the restore (`PIP_NO_CACHE_DIR`):
  with the cache pip holds each wheel twice while it writes the files,
  which took 2.35 times the size for a CUDA torch for Windows
- Drop the cached package list when a restore runs
- Extend tests/test_torch_rollback.py: the tests run fix_broken() with
  pip and with uv
- Add a CHANGELOG entry

A command that fails after torch was replaced can leave torch not
importable; the restore then ends with an ERROR line. What was measured
and what the restore cannot do is listed in #3618.

The same change for main is #3617.
2026-12-01 00:14:19 +09:00
Dr.Lt.Data 7494883c93 bump version to 4.5 2026-11-30 23:42:37 +09:00
Dr.Lt.Data 347473e689 v4: Check a nightly install of the legacy Manager by the repository it clones (#3623)
- Look the repository of a nightly up by the id of the nodepack before
  the install is queued, with the lookup the install itself uses, and
  check that repository
- Refuse a nightly of a nodepack that no list has at once, where it
  failed in the queue
- Add tests and a CHANGELOG entry
2026-11-30 18:47:27 +09:00
Dr.Lt.Data 4bbdb2e95f v4: Reinstall a nodepack named without a version at the version that is installed (#3625)
`cm-cli reinstall <nodepack>` resolved a name without a version to the
latest version of the registry, whatever was installed. A reinstall of
1.0.1 left 1.0.2, and a reinstall of a nightly clone left a registry
version.

- Reinstall the registry version that is installed, enabled or disabled,
  when the nodepack is named by its id without a version; a nightly
  clone is cloned again
- Keep the latest version for a nodepack that is not installed, and what
  `@latest`, `@<version>`, `@nightly` and a URL name
- Add tests, a CHANGELOG entry and a line in the cm-cli docs

The same changes for main are #3624.
2026-11-30 18:36:08 +09:00
Dr.Lt.Data 455ad3acd0 v4: Print the values that cm-cli dropped, and a line for each counted nodepack (#3612)
cm-cli printed every line through rich, which reads a lowercase word in
square brackets as markup and drops it, and typer shows a help text the
same way.

- Print every line with the print of the core, which writes it as it
  is, and give that print a style for the lines that cm-cli colours:
  the version of `fix`, the name of a nodepack, the reason of a failed
  or skipped action, a title and an author of the node list, a
  changelog line, a path, the name of a snapshot and a requirement in
  the report of a failed resolution lost a part in square brackets, a
  path lost a backslash before a bracket, and a line longer than the
  console is wide was broken in two, at 80 columns where no terminal is
  attached
- Write the help texts that were in brackets without them: `--mode` and
  the argument of show, simple-show, update, enable, disable and fix
  showed no help
- Refuse a word that is no list in `simple-show` without the tags of a
  colour around the line
- Print a line for the Manager in `disable all` and for a disabled
  nodepack in `fix all`: each run skipped a number
- Leave `__pycache__` out of restore-dependencies
- Remove the `f` before the reason of a failed fix, and the `print("")`
  after the entry point: the `cm-cli` command imports the module, so
  each command began with an empty line
- Add tests and a CHANGELOG entry

The same changes for main are #3611.
2026-11-29 19:09:01 +09:00
Dr.Lt.Data e32d3a4a71 v4: Restore a git nodepack that a snapshot lists as disabled as disabled (#3610)
A snapshot lists each git nodepack with `disabled`, and restore_snapshot
did not read it, in either core. Since the restore moved into the core
(b3be55683), every git entry of a snapshot was enabled, checked out or
cloned: a nodepack saved as disabled came back enabled, and one removed
since was cloned again.

- Leave a git entry that is listed as disabled out of the restore, so
  that the nodepack is left disabled, is disabled when it is enabled,
  and is not cloned when it is not installed
- Keep the clone of a nodepack saved at a version of the registry as
  what is restored when that version cannot be
- List a URL as enabled in a snapshot when one of its two clones is
  enabled: the clone read last named the entry
- Add tests and a CHANGELOG entry

The same changes for main are #3609.
2026-11-29 15:04:45 +09:00
Dr.Lt.Data 899819d230 v4: Do not move a nodepack into an existing folder on disable or enable (#3614)
unified_disable and unified_enable of both cores move the folder of a
nodepack with shutil.move, which puts it inside the destination when
that is a folder that exists. With an enabled nodepack and a disabled
copy of it, a disable left `.disabled/<name>/<name>` and reported
success.

- Fail a disable or an enable whose destination exists, and leave the
  nodepack in its folder
- Disable the enabled version for another one in one place,
  `disable_for_replacement`: fail with nothing changed when anything but
  the folder of the enabled version is where the other one goes, then
  disable that version when its folder is there, and return the answer.
  unified_enable (for a version and for the nightly clone),
  install_by_id and _install_git each began with a disable whose result
  was dropped
- Stop an install when the disabled version that it enables before a
  switch cannot be enabled: it went on to switch what was in the folder
- Report a failed disable or enable to the page: the disable task of
  both servers tested the result object, which is always true, and the
  enable task dropped its result
- Print the error of an enable that failed in `cm-cli install`: it
  printed `[ ENABLED ]`
- Add tests and a CHANGELOG entry

The same changes for main are #3613.
2026-11-29 01:29:18 +09:00
Dr.Lt.Data a1b0264744 v4: Fix defects of cm-cli, the legacy Model Manager and Custom Nodes Manager, requirements.txt rows and the default channel (#3604)
While each feature of 4.4.3 was driven for its release video, some
`cm-cli` commands and some pages of the legacy Manager did not do what
they say. Each root cause has its test and its CHANGELOG entry.

cm-cli
- Print the snapshot in `show snapshot` and `simple-show snapshot`, as it
  is: both printed only a RuntimeWarning
- End `install --exit-on-fail` with exit code 1 when a nodepack could not
  be installed
- Enable the disabled nodepacks in `enable all`, take `<id>@latest` as the
  installed nodepack, and enable a disabled pre-release version
- Say `Not installed` in `disable`, `update` and `fix` for a registry
  nodepack that is not installed
- List a git nodepack that the lists do not know in `show installed`,
  `show enabled` and `show disabled`
- Tell in `deps-in-workflow` whether a registry nodepack is installed
- Restore an editable install in `restore-snapshot`
- Write the git backend line at the start of the server only: `cm-cli`
  and its shell completion no longer write it

Rows of requirements.txt
- Read a row the same way in every place that installs it, in both
  cores: a requirement with a comment is no longer one argument, and a
  URL keeps its fragment
- Apply an option to its own row only: a row with only an option no
  longer stops the rows after it
- Install an editable row as `-e` and its target
- Install a row that names a path, such as `-e .`, for each nodepack of a
  session
- With uv, install an editable git URL without `-e`, in a row and in a
  line of a snapshot

Legacy pages
- List only the models of the workflow in the In Workflow filter of the
  Model Manager, also for a file named with a folder, and apply Type and
  Base together with the Filter
- End the install in the Custom Nodes Manager when Stop drops its batch
- Refuse Try fix in the Custom Nodes Manager when the security_level does
  not allow it, and say so

Default channel and e2e
- Treat both URLs of the default channel as one channel
- Keep the Manager under test after an e2e test updates ComfyUI

The same changes for main are #3603.
2026-11-28 08:42:46 +09:00
Dr.Lt.Data 9f1faeb0f5 v4: Make torchaudio optional in the PyTorch check and restore (#3606)
ComfyUI no longer needs torchaudio, but PIPFixer.fix_broken() still
required it. On an install with torch and torchvision and without
torchaudio it logged "[ComfyUI-Manager] PyTorch is not installed" at
every start, after a cm-cli install, update or fix, and after the server
installed the requirements of a nodepack, and it never restored PyTorch
when a nodepack changed torch or torchvision.

- Require and compare only torch and torchvision in the check, so such
  an install is not reported as one without PyTorch, and a nodepack that
  changes only torchaudio starts no restore
- Name torchaudio in the restore commands only when it was installed
  before the nodepack or is installed after it, so the restore adds no
  torchaudio to an install that has none
- Add tests that run fix_broken() and check the commands it sends
- Add a CHANGELOG entry

What the restore installs is not changed: an install without torchaudio
gets the commands that an install with torchaudio gets, without
torchaudio.

The same change for main is #3388.
2026-11-27 20:13:57 +09:00
Dr.Lt.Data fef6b412fc v4: Find a registry nodepack whose id has capital letters from a workflow node, in the legacy Custom Nodes Manager (#3599)
GET /v2/customnode/installed of the legacy server gave the id of a nodepack
installed from the registry in lowercase (comfyui_sigmoidoffsetscheduler),
and a node added to a workflow took that id. The legacy Custom Nodes Manager
names the nodepack as the registry writes it (ComfyUI_SigmoidOffsetScheduler)
and did not find it from the node: Custom Nodes In Workflow showed 0 custom
nodes, and Check Missing and Install Missing Custom Nodes said "Failed to
find the following ComfyRegistry list" for the id and then listed the same
nodepack.

identify_node_pack_from_path of the legacy core now returns the name of
pyproject.toml as it is written, as that of the glob core does since
d7799964d. Workflows saved with an earlier install keep the lowercased id,
so the page also matches the id of a node without regard to case when the
list has no exact match.

workflow-metadata.js gives a new node no id when the installed list names
its nodepack comfy-core. That comparison is now made in lowercase, so that
it holds as before with the list in the spelling of pyproject.toml.

A node of ComfyUI itself has the id comfy-core. That id is looked up as it
is written only, so that Check Missing and Custom Nodes In Workflow do not
list a nodepack named Comfy-Core for a built-in node.
2026-11-26 21:56:40 +09:00
Dr.Lt.Data 780c199dc7 v4: Remove the "Alternatives of A1111" filter of the legacy Custom Nodes Manager (#3601)
The choice asked /v2/customnode/alternatives, which no server registers. The
choice, its column, GET /customnode/alternatives, the fetch of alter-list.json
and the copies of the file are removed.
2026-11-26 21:07:57 +09:00
Dr.Lt.Data 25ca413586 v4: Show the result of Update All in the legacy Manager menu (#3597)
Update All made a batch id but did not put it into the batch it sent to
/v2/manager/queue/batch. The server reported the end of that batch with
batch_id null, and the menu, which shows only the end of its own batch,
showed nothing: no result box and no RESTART button. Update All now sends
the id, as Update ComfyUI and the other senders of a batch do.

The batch of Update All Custom Nodes in the desktop app has no result for
ComfyUI, and the menu then called startsWith on null. A missing result for
ComfyUI now leaves the ComfyUI line out of the box.
2026-11-26 20:56:20 +09:00
Dr.Lt.Data 7f28788cd5 bump version to 4.4.3 2026-11-24 20:29:17 +09:00
Dr.Lt.Data a930773408 v4: Run Check Update of the legacy UI in the background, so that it does not stop the server (#3589)
Check Update in the legacy Custom Nodes Manager fetched every git nodepack
inside GET /v2/customnode/getlist. The server answered nothing else until
the last fetch had ended. The ComfyUI frontend waits 60 s for the answer to
a request, so with many git nodepacks the page showed "Failed to get custom
node list." (#3574).

POST /v2/customnode/check_update of the legacy server now starts the check
in a thread of its own and answers at once. The check fetches the enabled
git nodepacks of the list and reports by the cm-check-update event: the
number of fetches that are done, and at the end the nodepacks that have an
update. The page shows that progress, then loads the list and marks them.
A check that is asked for while one runs starts no second one: the
nodepacks of its list that the running check does not have are added to
that check. A request carries a ui_id that the page chooses, the end of a
check names the ui_id of every request that it answers, and the page waits
for the end that names its own. A check that fails tells so to the pages
that wait for it. When the connection to the server comes back during
a check, as after a restart of the server, the events of the check are lost,
and the page asks for the check again.

A task of the queue that is taken while a check runs waits for the check to
end. So a task that is started during a check, such as Update All, runs
after it as before, and the two do not work on one repository at the same
time. A model download and an update of ComfyUI do not touch the
repositories of the nodepacks, and do not wait.

GET /v2/customnode/getlist no longer fetches, with or without skip_update.
GET /v2/customnode/fetch_updates of the legacy server fetched inside the
request in the same way and has no caller, and answers 410 as that of the
new server does.

The check found the folder of a nodepack by the id of its row in the list.
A git nodepack that the registry does not know has none, or one that is not
its repository name, so it was left out. The folder is now found by the key
of the row, and every enabled git nodepack of the list is fetched.

git_repo_update_check_with of the legacy core is left with the check as its
one caller. Its update path, which nothing called, is removed, and it
fetches and checks only. With that path goes a defect on Windows: a check
that found an update put the install script of the nodepack down to run at
the next start, though nothing had been updated.
2026-11-24 18:24:42 +09:00
Dr.Lt.Dataandcenfun aa1620c608 v4: List the best matches first for a search in the legacy Custom Nodes Manager (#3586)
A search only filtered the list, so the rows stayed in the listed order. The
rows of a search are now ordered by their best match in the title, the author
or the description (a whole word before a part of a word), by the number of
columns that match and by the stars. Rows that match alike stay in the listed
order. A click on a column header during a search sorts by that column, and
clearing the search box brings back the listed order or keeps that sort. The
list is filtered 300 ms after the last key. The first click on the Nodes,
stars and Last Update headers sorts from the highest value down.

This is #1666 of the main line with its corrections: the case of a match
weighs less than its position in a word, also for a search with several
keywords, the stars are bounded to the scale, equal scores keep the listed
order, a header sort made during a search is kept when the search is
cleared, and a search that is still waiting leaves the loading of a reload
on.

Co-authored-by: cenfun <cenfun@gmail.com>
2026-11-23 08:50:20 +09:00
Dr.Lt.Data b73b9ea0d9 v4: Recognize a nodepack folder with neither .git nor .tracking as an invalid installation and fix it by reinstalling (#3566)
A folder in custom_nodes with neither .git nor .tracking, left by an
install that broke midway or by a download unpacked by hand, was taken for
a git nodepack: Update All logged "ERROR: An error occurred while updating
..." for it, and its nodepack showed as not installed (#3330).

It is now an invalid installation. Update All and cm-cli update all leave
it alone, /v2/customnode/installed lists it with
invalid_installation: true, the legacy node list marks its row INVALID
INSTALLATION and offers Reinstall, and the startup notice names it.
kind: "reinstall" in /v2/manager/queue/task installs the nodepack again in
its place. By its folder name it is enabled, disabled and uninstalled as
before. An update of the nodepack alone fails with the guidance to
reinstall it, and the console line of a failed update says why the update
failed.

A reinstall, of any nodepack, keeps the folders it replaces until the new
installation is in place, and puts them back when the install fails. It
deleted them first, so a failed download lost the nodepack. cm-cli
reinstall makes the same reinstall and prints [REINSTALLED].

What is in the way of a reinstall, such as a clone of a fork at the install
path or under the name of the nodepack, is moved to
custom_nodes/.disabled/.archived/ and the log says where it is. It is not
deleted and no longer loaded, and it goes back when the install fails. The
legacy server failed there with "Install path already exists", and cm-cli
reinstall deleted it.
2026-11-22 18:11:57 +09:00
Dr.Lt.Data 9107e8fa3a v4: Report a fix of a nodepack as failed when its install script failed (#3582)
unified_fix() of both cores did not read what execute_install_script()
returned, so a fix was a success whenever the nodepack was there. The queue
of the server reports a fix by that result: a fix whose requirement could
not be installed, or whose install.py failed, ended as a success, and only
the log said "install script failed".

unified_fix() now fails with "Failed to execute install script", as an
install does. The task then ends with the status error and "An error
occurred while fixing", and the legacy page shows that message.

A fix that is reserved for the next start, as on Windows or with
always_lazy_install, runs nothing yet, so it is reported as soon as it is
reserved, as before. With use_unified_resolver the glob core leaves the
requirements to the next start as well, and the fix answers for install.py
alone. cm-cli fix is not changed: its commands raise when they fail.
2026-11-22 07:59:45 +09:00
Dr.Lt.Data 4367158b50 v4: Do not install a URL requirement again at startup when it is installed, and install it by force on a fix (#3579)
A requirement that is a URL, as git+https://github.com/owner/repo or the
URL of a wheel, names no package, so is_installed() of the startup script
never found it installed and pip was run for it at every reserved install
of its nodepack: for a repository, a clone and a build (#3575). On Windows,
or with always_lazy_install, every install, update and fix that the server
is asked for is reserved.

pip and uv record where a distribution came from in its direct_url.json
(PEP 610). installed_from() compares the URL with those records, and
is_installed() skips the requirement when a distribution installed from
that URL is there and no distribution of its name differs from it. The
repository is not asked, so a branch that has moved on is not followed, as
a name without a version is not upgraded.

A fix is the way to have such a package installed again. fix_cmd() builds
a forced command for a URL requirement: --force-reinstall --no-deps, and
without the cache of the installer, since with it uv installs the wheel it
has built of a commit before, forced or not, and so does pip for a name
with a commit. The command is run at once or reserved as any other.
Wherever it is run, reinstall() runs it in two steps: the requirement as
an install does it, which brings what the package needs now, and then the
forced command, which puts a clean copy there. When only the forced step
fails, what is installed stays. When the first step fails and the
repository does not answer `git ls-remote`, uv is asked for the installed
commit with --offline: the one use of a cache.

A fix is no longer held back by what the session has processed, only by
what the same fix has done, and one `cm-cli fix` of several nodepacks
shares that between them.
2026-11-22 01:17:35 +09:00
Dr.Lt.Data b08783e963 v4: Do not pass aiohttp's deprecated verify_ssl argument (#3577)
With bypass_ssl = true, the fetch of the legacy notice and get_data() passed
verify_ssl=False to aiohttp.TCPConnector, and aiohttp warns about that
argument when it is False: "DeprecationWarning: verify_ssl is deprecated,
use ssl=False instead" (#2281). Without bypass_ssl the two calls pass True
and aiohttp does not warn, so the warning was left for that setting alone.

Both calls now take their connector from one function of manager_util. With
bypass_ssl it passes ssl=False. Otherwise it gives no connector, and the
session makes aiohttp's default one, which checks the certificate.

ssl=True is not passed, on purpose: aiohttp before 3.9.2 reads ssl=True on
a connector as "do not check", so `ssl=not bypass_ssl` would turn the check
off there. Run on aiohttp 3.8.6: with that form the cases that expect a
certificate to be rejected fail, and with this change they pass.
2026-11-21 08:10:47 +09:00
Dr.Lt.Data d8867456d1 v4: Do not fail a prompt when the console of the server is gone (#3569)
A server started with pipes for stdout and stderr goes on running when the
process that read them exits, and a write to such a pipe fails: with
BrokenPipeError on Linux, with `OSError: [Errno 22] Invalid argument` on
Windows. The log hook of prestartup_script.py wrote to the console and
flushed it with no guard, so the failure reached whatever had printed: the
prompt of a node that prints, and of a sampler at its tqdm progress bar,
ended with that error (#3223).

The same prompts were run without the Manager. The progress bar fails there
as well, in the flush of ComfyUI's own stream, so this change covers it only
while the hook is installed (file_logging, on by default). A short print did
not fail there: the hook flushes the console after every write, which
ComfyUI's stream does not.

The two places of the logger that write to the console now go through one
method. An OSError of the console is dropped there, and the console is not
written to again: a pipe whose reader has exited and a terminal that has
hung up do not come back, and ComfyUI's stream keeps every write it could
not flush, so each further write would be kept as well. A console that fails
for a reason that can pass, as a file on a full disk, is treated the same
and gets nothing more until the server is restarted. BlockingIOError is the
exception: a console that cannot take a write right now is still there.
ValueError is left out on purpose: a write raises it for text the console
cannot encode, which is not a console that is gone, and ComfyUI's stream,
which is strict, fails that write the same way.

The handler that copies the log records into the log file wrote a record
that cannot be formatted to the console as well, with no guard. With stderr
line-buffered (Python started without -u) and a line break in the record,
that write failed the node the same way. It is removed: for a record that
the console shows, Python's logging reports the failure there already, and
the handler still puts the record in the log file.

The line that the handler puts into the log file for such a record named the
record by its repr, which turns the message into text again: a message
object that cannot be printed failed there a second time, and the node with
it. The line now names the file and the line of the call. The error is named
in it by its type and its text, and by its type alone when that text cannot
be made either: an error can carry the message object.

What is written still goes to the log file. One thing changes there while
stderr is gone: ComfyUI's own log handler fails on each record, Python's
logging reports that on sys.stderr, which is the hook, and the report, which
broke off after its first line when the console write raised, is now in the
log file in full.
2026-11-20 21:45:58 +09:00
Dr.Lt.Data 6e1ee9529d v4: Restore the git node packs of a snapshot as the snapshot names them, and say why a clone was refused (#3561) 2026-11-19 23:43:14 +09:00
Dr.Lt.Data 3a72e71f91 bump version to 4.4.2 2026-11-19 20:56:07 +09:00
Dr.Lt.Data 13a10217e7 v4: Keep sharing credentials on the server, tighten the security-level and POST checks, read config.ini values as plain text
Nine changes, each in the CHANGELOG.

- Keep saved sharing credentials out of server answers, and log in to
  matrix.org only
- Hold an update-comfyui task for an older version to the security level
- Take a JSON body only as application/json
- Hold an enable that replaces a registry version with nightly to the
  security level
- Hold a snapshot restore to the security level of the switch route
- Read config.ini values as plain text and default the invalid ones
- 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 9f967363e2 bump version to 4.4.1 2026-11-19 08:17:43 +09:00
Dr.Lt.Data d157bb9b32 v4: Fix the scheduled snapshot restore, the steps of a snapshot restore and reserved install scripts (#3555)
Three fixes. The CHANGELOG describes them.

- Give the scheduled snapshot restore the directories of the server
- Report the failed steps of a snapshot restore, check a cloned nodepack
  out at the pinned commit and run the install step of the nodepacks it
  installs
- Write what is reserved for the next start as UTF-8, and remove the files of
  an old version from the nodepack, and from nowhere else, when a version is
  switched; read the list of those files as UTF-8
2026-11-19 07:14:13 +09:00
Dr.Lt.Data 1c9e57f72a v4: Fix git_exe, start-up without git, .git/config reading, submodules and an update whose git step fails (#3553)
Six fixes. The CHANGELOG describes them.

- Start with a nodepack whose .git/config cannot be read
- Use the git executable set as git_exe, and start without a git
- Read the commit of a nodepack whose refs are packed, and bring its
  submodules to the commit that is checked out
- Update nested submodules with pygit2, fetch them through the proxy and
  over https, and fail when submodules could not be updated
- Do not end a clone or a fetch of pygit2 at a progress message of the
  server that is not UTF-8 by itself
- Fail an update whose pull or submodule update failed, and undo the pull
2026-11-18 22:54:35 +09:00
Perfect Johny 3badbaaebc v4: Replace PrimeVue styling with Manager-owned theme CSS (#3549)
Backport of #3392 to manager-v4. The dialogs of the legacy UI bring their own styles, where they relied on the PrimeVue styles that the current ComfyUI frontend no longer ships: the Manager menu and the dialogs it opens had no background (#3545).

The Playwright cases of the legacy UI find the dialogs by the new classes, with cases for the background and the close button of the four dialogs. The CHANGELOG records the fix.
2026-11-17 19:13:57 +09:00
Dr.Lt.Data 685618664d v4: Leave the tests out of the source distribution
setuptools adds `tests/test*.py` to an sdist by default: one built from
this branch held 32 test files. The wheel does not hold them, and is
unchanged.
2026-11-17 18:30:13 +09:00
Dr.Lt.Data a48433cc9a v4: Fix the legacy batch update, the update policy, console messages and settings (#3544)
Six fixes. The CHANGELOG has an entry for each.

- Queue the legacy ComfyUI update and answer failed version requests
- Check out a branch head by its name with GitPython
- Follow the update policy when an update request names no version line
- Print the messages of manager_core as they are
- Refuse a db_mode or update_policy request the servers cannot use
- Keep a setting chosen while the legacy menu is loading it

The E2E cases wait for the Registry list, which a fresh environment has not
cached, and the Playwright cases no longer depend on the timing of the UI.
2026-11-17 12:40:09 +09:00
Dr.Lt.Data 14626f8602 v4: Leave the log file alone once it is closed (#3539)
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:29 +09:00
Dr.Lt.Data cd9114a933 bump version to 4.4 2026-11-16 00:04:47 +09:00
H.W.Prinz 2479e8c26e v4: Report the console's terminal state from the logger (#3465)
With file logging on, the logger that captures stdout and stderr
answered isatty() with False for every caller and had no closed
attribute. After colorama.init(), colorama took the console for a pipe
and removed the colors of every print(), and tqdm and rich took a
terminal for a pipe (#3259).

- Answer isatty() from the stream the logger wraps, and False when
  that stream cannot answer
- Add closed, which colorama takes as True for a stream without it:
  the state of the wrapped stream, False for a stream that has no such
  attribute, and True for a detached stream
- Answer closed True once the log file is closed. Restarting through
  comfy-cli calls close_log() and then exits, and colorama's exit
  handler would write its reset through the logger
- Add tests for both answers on both streams, for streams that cannot
  answer, and for what colorama does with the answers
- Add a CHANGELOG entry

The same change for main is #3423.
2026-11-15 23:47:46 +09:00
Dr.Lt.Data 8c2a67a7b3 v4: Report why restoring or removing a snapshot failed (#3535)
When the server answers 400 to a restore or a removal, the Snapshot
Manager built its message from target.title and exception. target is
the snapshot's name, a string, and exception is not defined at that
point, so the line threw and the catch block showed "Restore snapshot
failed: undefined / ReferenceError: exception is not defined", for a
removal too. The finally block of the restore then asked for a
restart, although nothing had been scheduled. Any other error status,
such as a 502 from a proxy, was taken as success.

- Show the snapshot's name and the reason, both escaped. The reason is
  the text of a plain-text response, which is how the server gives
  one, and otherwise the status line: most of the server's refusals
  carry no text, and a proxy answers with an HTML page
- Handle every error status this way, where only 400 was looked at
- Return after a failure, and ask for a restart only when the restore
  was accepted
- Name the removal in the removal's messages
- Add Playwright cases for a failed restore and removal, answered with
  400 with and without a reason and with the 502 page of a proxy, for
  a restore refused with 403, and for an accepted restore
- Add a CHANGELOG entry and name the cases in the Playwright README

The same change for main is #3436.
2026-11-15 21:08:03 +09:00
Dr.Lt.DataandArian Moeini 1c3a47b6ce v4: End each model install with its own batch (#3536)
The legacy server reports the end of every batch of tasks with the id
of the batch and two objects keyed by the id of each task. The Model
Manager took the end of any batch for the end of its own install. A
node pack install queued before a model download, or a model install
started earlier, ended the pending install when it finished: the
downloads were shown as done while they were still running, the Stop
button was hidden, and the real completion was then ignored.

- Take progress and completion reports only for a batch the Model
  Manager queued, by batch id, and show a failed download without the
  request to click Refresh (from #3349)
- Keep the pending installs by batch id, and end each with its own
  batch; the Stop button stays while one is pending
- When the queue reports its end, ask the server whether the queue is
  running, and if it is not, end the installs that were queued and got
  no report of their own: Stop empties the queue, and the dialog stayed
  pending with its Stop button. The report can be that of a queue that
  ran before the batch was added, so a running queue ends nothing, nor
  does a question that gets no answer, and an install whose request is
  not answered yet is looked at when the answer arrives
- Take a batch that ended before its request was answered as ended
- Remove the branch for a batch that ends without a model result; the
  server writes a result for every task of a batch
- Count the keys of nodepack_result in the status text of the Custom
  Nodes Manager, which counted "undefined" node packs, and remove its
  guard for an empty result, which never held
- Send the id of the posted batch with the completion in the Model
  Manager's XSS case; a completion without it is no longer taken
- Add Playwright cases for the active batch, for two installs in a
  row, for a stopped queue, for the end of an earlier queue, for a
  question to the queue that is not answered, and for a batch that
  ends before its request is answered; extend the case for partly
  rejected batches to both managers
- Add a CHANGELOG entry

This takes over #3349, which fixes #3303, and is the v4 counterpart of
#3437.

Co-authored-by: Arian Moeini <arianmoeini11@gmail.com>
2026-11-15 17:25:41 +09:00
Dr.Lt.Data 3726fbcfb1 v4: Show node definitions as text in the node preview (#3534)
The preview that the Custom Nodes Manager shows over a node name is
built from ComfyUI's node definitions (/object_info) and inserted with
innerHTML. The name, the input and output names, the default values
and the description went in as they are, so text between angle
brackets was dropped from the preview and markup in a definition was
rendered. Nothing on the way escapes these values; the server-side
escaping of v4 covers the registry fields, not this route.

- Escape the eight values where createNodePreview inserts them; the
  line break of a multi-line default is still shown as <br>
- Add a Playwright case that answers the manager's /object_info
  request with a definition carrying markup in every field
- Add a CHANGELOG entry and name the case in the Playwright README

The same change for main is #3434.
2026-11-15 15:19:11 +09:00
Dr.Lt.Data 9d5f65827c v4: Clean up after a registry archive that cannot be extracted (#3533)
_cnr_install creates the directory of the pack and then extracts the
downloaded archive into it. extract_package_as_zip handles a file that
is not a zip; any other error, such as an entry that cannot be written,
left the function through an exception with the new directory and the
archive still in custom_nodes. The next install of the pack found the
directory and stopped with "Install path already exists".

- Catch the error, remove the directory with try_rmtree and return a
  failed result that names the error, in the glob and the legacy core
- Remove the archive whether the extraction worked or not
- Use try_rmtree for an archive that is not a zip as well, where
  shutil.rmtree was called directly
- Log a cleanup that fails as well and still return the failed result,
  at both calls; try_rmtree raises when it can neither remove nor
  schedule the directory
- Add tests that install from an archive that fails part-way and from
  a file that is not a zip, install again afterwards, and install
  while the cleanup fails
- Add a CHANGELOG entry

The same change for main is #3433.
2026-11-15 14:40:43 +09:00
Dr.Lt.Data 89079387cf v4: Write cache files whole and age them by their last write (#3532)
The cache files of the channel lists and of the registry's node list
were written in place. A write that stopped part-way left a truncated
file, which get_data reads as an empty list.

is_file_created_within_one_day read os.path.getctime. On Windows that
is the creation time, which stays the same when the file is rewritten,
so a cache first created more than a day ago counted as expired however
recently it was written. The age decides whether a list is fetched
only when Manager does not run as a pip package; a pip install fetches
at startup and reads the cache afterwards whatever its age.

- Add write_cache_file, which writes a temporary file beside the cache
  and replaces the cache with it, keeping the mode of the existing
  file. Where the written file cannot be put in place, as on Windows
  while another reader has the cache open, the replace is tried three
  times, 0.1 s apart. A cache that stays open is left as it is, with a
  warning; the caller gets no error and goes on with its data, and
  cm-cli update-cache reports that cache as failed. A failure while
  writing the temporary file leaves the cache as it is as well. Where
  the mode cannot be set, the cache is replaced all the same. A
  temporary file that cannot be removed, because a scanner holds it
  open, is left behind and does not fail the write
- Use it for the seven writes of a cache file: two in manager_util and
  one each in the glob and legacy core, the glob and legacy server, and
  cm-cli update-cache
- Read the modification time for the age
- Add tests for a write that fails and one that runs out of space, the
  mode, a mode that cannot be set, a replace that is refused for a
  moment and one that stays refused, a temporary file that is held
  open, the fetch that caches and the age
- Add a CHANGELOG entry

The same change for main is #3432.
2026-11-15 14:30:16 +09:00
Dr.Lt.Data 5ab11da187 v4: Compare a snapshot's pins with the installed commit and version (#3531)
Two comparisons in restore_snapshot never matched.

get_commit_hash returned the line of .git/HEAD as it is when HEAD is
detached, with its newline, and the snapshot saved it that way. On
restore the checkout of that text failed, repo_switch_commit returned
None, and the pack was listed as skipped at the commit it had. A pack
is left at a detached HEAD by a restore, so a snapshot taken after one
has this.

For a registry pack, the installed version was compared through v[1],
the path of the pack, where v[0] is the version. Every installed pack
was therefore sent to cnr_switch_version, which asks the registry
before it finds the version unchanged; with the registry out of reach
the request raised and the restore stopped.

- Return the hash without the newline
- Strip the hash read from a snapshot, so the snapshots already saved
  restore too
- Compare the version, in the glob and the legacy core
- Add tests for the hash, for a pack at the pinned version and at
  another one, and for the checkout of both forms of the hash in a
  real repository
- Add a CHANGELOG entry

The same change for main is #3426.
2026-11-15 11:06:59 +09:00
Dr.Lt.Data ba3fd681e1 v4: Read pip's exit status when restoring a snapshot's pip packages (#3530)
restore_pip_snapshot kept the return value of subprocess.check_output
as the result of each pip run and compared it with 0. check_output
returns pip's output, never an exit status, so the comparison held for
every run that succeeded: after the one run that installs the packages
named by version, pip was run again for each of them with --no-deps,
and every package of the three groups was reported under "Installation
failed for pip packages".

- Run pip with check_call, which returns the exit status and raises
  when it is not 0
- Add tests that cover the three groups, the fallback after a failed
  run, failures in every group at once, and a group whose option is
  not given
- Add a CHANGELOG entry

The same change for main is #3425.
2026-11-15 10:18:33 +09:00
Dr.Lt.Data b76eb11207 v4: Enable a disabled node pack requested through cm-api before restarting (#3526)
When an extension asks through cm.try-install-custom-node for a node
pack that is disabled, the legacy UI asks whether to enable it and
restart. On confirmation it posted to /v2/customnode/toggle_active,
which neither server has, did not look at the answer, and restarted:
ComfyUI came back with the pack still disabled.

- Enable the pack as the Enable button of the Custom Nodes Manager
  does: find its row in /v2/customnode/getlist, post it to
  /v2/manager/queue/batch, and wait for the queue to report the batch
- Restart only when the queue reports success; otherwise show why the
  pack was not enabled
- Leave a queue that is running alone, and tell the user to try again
- End the wait after a minute, or when the queue finishes without the
  batch; left waiting, the handler would restart ComfyUI on a report
  that arrives much later
- Do not restart while other work is queued behind the pack; ask the
  user to restart after it
- Report a request that gets no answer while the pack is being
  enabled; "Enabling..." stayed on screen
- Show "Rebooting..." when the restart request gets no answer, which
  is what happens when ComfyUI restarts; the rejected request ended
  the handler
- Report a restart that is refused at the current security level:
  show_message was not imported, so nothing was shown
- Remove the branch for a pack that is not installed: the server does
  not send this request for one, and the route it posted to is gone
- Leave the queue listener of the Manager menu while the menu has not
  been created; a queue started from here made it raise
- Add browser tests of the handler and of that listener, and a
  CHANGELOG entry

Found while reviewing #3435.

The same change for main is #3525.
2026-11-14 23:41:26 +09:00
Dr.Lt.Data b4528eedb7 v4: Weigh the clauses of a pip requirement together (#3523)
The downgrade decision and the startup check read each clause of a pip
requirement on its own, and did not read "!=". Found by CodeRabbit on
#3521, #3523 and #3524 and in review.

- Install a requirement for a protected package that allows the
  installed version when another clause sets a minimum above it
  ("==4.*,>=4.58.0" beside 4.57.0); it was skipped
- Skip one that the installed version does not meet and that allows no
  newer version ("[torch]<=4.57.0,!=4.57.0", "<4.58,!=4.57.*"); it was
  installed, and pip replaced the package with an older version
- Install one that excludes the installed version with "!=" while a
  newer version is allowed ("~=4.57.0,!=4.57.0"); without extras it
  was skipped
- At startup, read ">" as pip does: a post-release of its version does
  not meet it, and the requirement is installed when a newer version
  meets every clause
- At startup, take "==0.21.*" as met by an installed 0.21.0rc1, as pip
  does
- At startup, install a requirement that excludes the installed
  version with "!=" and allows a newer one; pip chooses the version,
  which is an older one when no newer release exists
- Ask packaging whether a newer version meets every clause, about the
  versions next to the installed one and next to each clause's version;
  a pre-release counts only when "==", ">=", "<=", "~=" or "===" names
  one, which is when every pip takes one
- Never replace an installed local build, such as a CUDA build, on
  these grounds, and keep a protected one that "!=" excludes unless
  the requirement sets a minimum above it: for such a build the
  changes only add requirements that are skipped
- Add tests and a CHANGELOG entry

The same change for main is #3524.
2026-11-14 21:29:50 +09:00
Dr.Lt.Data 7a6a72d7e9 v4: Fix lists failing after a channel response that is not JSON (#3519)
When the channel answered a start with something that is not JSON, such
as a block page or "404: Not Found", get_data() returned {} and the
startup cache update wrote that {} to the cache, over a list cached by
an earlier start. As an installed package the Manager reads a channel
file from the cache whenever the cache file exists, so the custom node
list and the model list of the legacy UI ended in HTTP 500 and the map
of nodes to node packs came back empty, until a later start got the
lists from the channel. "cm-cli update-cache" wrote the same {} and
then stopped with KeyError: 'custom_nodes'.

- Re-raise the parse error in get_data() when the text came from an
  HTTP response, so such a response is handled like a failed
  connection: both startup cache updates and cm-cli skip the file and
  leave the cache as it is, and without a cached list the one bundled
  with the Manager is used. A local file or cache file that is not
  JSON still reads as {}
- Add tests that run the real get_data(), and the real startup cache
  update and get_data_by_mode() of both servers, against a local HTTP
  server
- Add a CHANGELOG entry

The same change for main is #3518. Refs #3480.
2026-11-14 17:12:05 +09:00
Dr.Lt.Data a4cb6f5b3f v4: Read node pack and pip versions that carry a suffix (#3516)
StrictVersion read each of the first three components of a version
with int(), so it raised on a suffix after the third number. On v4 it
reads node pack versions and the pip versions of pip_auto_fix.list.

- Read a node pack version with a pre-release after the third number,
  following '.' or '-', and write it with '-' as before: a registry
  version such as 1.8.0-beta.1 is recognized, and 0.1.3.post1 no
  longer stops the scan of installed node packs, in the glob and the
  legacy core
- Ask a packaging Specifier for the entries of pip_auto_fix.list, as
  pip does: an installed 2.5.1+cu124 or 4.41.0rc1 no longer skips the
  entry with "Failed to restore", and "~=" becomes a compatible-release
  clause
- Add tests that run the real scan of both cores and the real PIPFixer
- Add a CHANGELOG entry

The same change for main is #3431, which also moves the pip checks at
install time to packaging; v4 did that in #3489.
2026-11-14 15:32:05 +09:00
Dr.Lt.Data 8dd1967fde v4: Share only a file inside the output directory to Matrix (#3515)
The share route joined the file name and subfolder of the selected
output, both taken from the request, onto the output or temp directory
and uploaded that file to the Matrix homeserver named in the same
request. A name such as "../../file" left the directory, so a request
could have any file that ComfyUI can read uploaded. The route runs the
upload only where matrix-nio is installed, which Manager does not
install.

- Refuse, with 400 and the error shape the share dialog shows, a path
  that is not inside the directory, in the glob and the legacy copy
- Compare the normalized path without resolving symlinks, as ComfyUI's
  /view does, and open that same path, so an image that the dialog
  previews through a symlink in the directory can still be shared
- Refuse a path on another Windows drive, for which commonpath raises
  ValueError
- Add tests that run the real route of both copies against a recording
  Matrix client
- Add a CHANGELOG entry

The same change for main is #3427. The other upload that #3427 first
changed was removed from v4 in #3500.
2026-11-14 14:46:35 +09:00
Dr.Lt.Data 5986d2237c v4: Make Fix node (recreate) work inside a subgraph (#3512)
"Fix node (recreate)" looked a node's links, and the nodes at their
other end, up in app.graph, the root graph. A subgraph keeps its own
links and nodes, so inside a subgraph the lookup found nothing: the
entry threw "Cannot read properties of undefined" and, because the
original is removed only afterwards, left the wired original and an
unwired replacement on the canvas.

- Read links and nodes from the graph the node is in
- Reconnect a link that starts at an input of the subgraph, or ends at
  one of its outputs, through that slot; those two are not nodes of
  the graph
- For a link from a subgraph input, skip an input the new node does
  not have or has with a type that does not fit, as connect() does for
  a link from a node; a subgraph input's connect() checks neither
- Extend the Playwright spec to a node inside a subgraph, a node wired
  to the inputs and output of a subgraph, an input the new node lacks
  and an input whose type changed; compare the slot at the other end
  of every link, and the record on the subgraph slot
- Add a CHANGELOG entry

Follow-up to #3507. The same change for main is #3513.
2026-11-14 09:22:03 +09:00
Dr.Lt.Data 175e085fcf v4: Make Fix node (recreate) work when node ids are strings (#3507)
"Fix node (recreate)" rewired the inputs of the new node with
src_node.connect(link.origin_slot, dest.id, input.name).
LGraphNode.connect() looks its target up by id only when the id is a
number, so on a frontend whose node ids are strings the id was taken
for the node itself: the entry threw "findInputSlot is not a function"
and, because the original is removed only afterwards, left the wired
original and an unwired replacement on the canvas.

- Pass the node to connect(), as the output loop below already does
- Add a Playwright spec that clicks the entry in the node context menu
  and checks the page errors and what every KSampler is wired to, with
  node ids as the frontend issues them and with ids rewritten to
  strings
- Add a CHANGELOG entry

Port of #3443 to v4 (#3126).
2026-11-14 05:38:57 +09:00
Dr.Lt.Data 2bb25594b8 v4: Check model installs against the model list, including the url (#3506)
A model install is limited to the entries of the model list. The legacy
server compared save_path, base and filename with the list, but not the
url the file is downloaded from, so a request with a listed name and
another url was queued as given. The glob server lost the list check,
and the check for formats other than .safetensors, when its routes
moved to data models (0be0a2e6), so it queued and downloaded whatever a
request named.

Compare the url in both servers; for the legacy server this is the port
of #3428. In the glob server, run both checks in the worker, which
queue/install_model and queue/task both reach. A default channel list
without models counts as empty there, so the model is refused and the
worker keeps running.
2026-11-13 20:26:44 +09:00
Dr.Lt.Data 72f05493e5 v4: Verify the TLS certificate when fetching the legacy notice (#3504)
The legacy notice route fetched the News page from GitHub with
verify_ssl=False, so certificate verification was off for every user:
whoever sat on the connection could present any certificate for
github.com and choose the notice text and links. The sanitizer limits
the markup, but it cannot tell whose content it is.

- Turn verification off for the notice only when bypass_ssl is set, as
  manager_util.get_data does
- Answer a certificate or connection failure with "Unable to retrieve
  Notice" where it raised and the notice area showed the server's 500
  page
- Add tests that run get_notice against a local HTTPS server behind a
  local CONNECT proxy: an untrusted certificate and a trusted
  certificate for another host are rejected; bypass_ssl accepts the
  untrusted certificate; a CA trusted through SSL_CERT_FILE is
  accepted; a closed proxy, a proxy answering 502 and a proxy that
  never answers end in the unavailable notice, each with one warning
  naming the cause
- Add a CHANGELOG entry

Port of #3424 to v4 (#3302).
2026-11-13 08:19:40 +09:00
Dr.Lt.Data 857e2ca5a5 v4: Remove share destinations that no longer accept workflows (#3500)
Four of the six share destinations of the legacy UI are gone: the
comfyworkflows.com domain registration has expired, the Copus API
answers 410 "ComfyUI direct publishing is no longer supported", the
OpenArt workflow API and pages return 404 or redirect to the home page,
and esheep.com no longer resolves. Manager still offered them, and the
ComfyWorkflows flow would hand the share key, the workflow and the
installed snapshot to whoever answers at that domain next.

- Remove ComfyWorkflows, Copus, OpenArt and eSheep from the share
  chooser, the Share setting, the Workflow Gallery menu and the share
  dialog, with their server routes, the two dialog modules and what the
  Copus theme added to the chooser
- Treat a saved Share setting that names a removed site as All, and do
  not open a removed site saved as the last visited Workflow Gallery
- Sharing to YouML and to Matrix is unchanged; the share request no
  longer carries cw_auth or is_nsfw, which only ComfyWorkflows used
- Update README, CHANGELOG and the Playwright scenario notes
2026-11-12 21:47:35 +09:00
Benjamin Kincses 9e72648931 v4: Respect bypass_ssl in share requests (#3411)
The comfyworkflows share requests in glob/share_3rdparty.py built their
connectors with verify_ssl=False, so certificates were not verified
whatever the bypass_ssl setting said.

Use verify_ssl=not manager_util.bypass_ssl, as manager_util.get_data
does. Verification is on by default, and bypass_ssl = True still turns
it off. The copy under legacy/ is unchanged.
2026-11-12 19:48:51 +09:00
Dr.Lt.Data ad3a2b862b v4: Keep arguments intact when ComfyUI restarts on Windows (#3499)
os.execv on Windows joins its arguments with spaces and quotes nothing, so
only the interpreter and script path, quoted by hand, survived a restart.
An argument with a space, such as --output-directory "D:\My Outputs", was
split in two and ComfyUI failed to start with 'unrecognized arguments'.

Build the command in manager_util.build_restart_command and use it at the
three restart sites: the reboot endpoints of the glob and legacy servers
and the prestartup restart. On Windows every entry is quoted with
subprocess.list2cmdline; other platforms get the same list as before. The
endpoints still drop --windows-standalone-build, now every occurrence
rather than only the first, and the prestartup restart still keeps it.

Port of #3488 to v4 (#3339).
2026-11-12 19:20:36 +09:00
Dr.Lt.Data c53ee36f30 v4: Find a free backup branch name in the legacy core (#3494)
get_backup_branch_name() lists branches through list_heads() since
49e205ac. The legacy core passes GitPython's git.Repo, which has no
such method; the error was swallowed and the name was returned without
a collision check, so creating the backup branch failed when one of
the same second existed.

- Read the branches from heads when the repository has no list_heads()
- Repair the tests: the fake repository still exposed heads, so the
  collision cases exercised the error fallback and failed
- Run the behaviour tests against both copies of the function, add a
  real-repository test as each core opens it, and freeze the clock
2026-11-12 09:00:19 +09:00
Dr.Lt.Data 573742e800 v4: Settle which OpenCV package provides cv2 after the repair (#3493)
The package installed last provides cv2. The repair ranked the
packages with the GUI above the headless ones, so on a Linux without
the graphics libraries it replaced a working headless cv2 with one
that cannot be imported.

- Install a headless package after one with the GUI, and within each
  kind the one with the contrib modules last: opencv-python,
  opencv-contrib-python, opencv-python-headless,
  opencv-contrib-python-headless
- The package that ends up providing cv2 follows from this order alone,
  not from which package was the older one
- Update the tests and correct the CHANGELOG sentence
2026-11-12 08:49:21 +09:00
Dr.Lt.Data e519c56057 v4: Restore PIPFixer's OpenCV version repair (#3492)
* fix(v4): restore the OpenCV version repair in PIPFixer

PIPFixer looked the four OpenCV packages up by their hyphenated names,
but installed packages have been keyed by normalized names since
e87d616b, so the lookups returned nothing and the repair never ran.

- Look the packages up by normalized name
- Compare versions with packaging, so a fourth component such as
  4.11.0.100 is ordered as a number and the newest version is chosen
- Reinstall with --no-deps, so the repair changes only the OpenCV
  packages and leaves numpy as it is
- Add regression tests and a CHANGELOG entry

* fix(v4): keep the most complete OpenCV build and defer to pip_auto_fix.list

- Install the most complete package last, reinstalling it when it was
  already the newest; raising opencv-python replaced the cv2 binary of
  opencv-contrib-python and removed the contrib functions
- Leave the OpenCV packages alone when pip_auto_fix.list lists one;
  the repair and that list would otherwise undo each other at every
  startup
2026-11-12 03:41:09 +09:00
50131e3bb7 v4: Apply pip blacklists however a requirement is written (#3489)
* Fix pip package name matching in downgrade guards

* Apply the pip blacklists however a requirement is written

Build on the name normalization to close the other ways a listed
requirement escaped the pip_blacklist and downgrade_blacklist checks.

- Parse requirements with packaging and share one parser and one
  downgrade decision between both cores, the startup check and the
  unified resolver
- Treat '-', '_' and '.' as one separator in package names
- Read every version clause, so a lower bound written first no longer
  hides an upper bound; read spaces, parentheses, markers, '===' and
  direct references; compare local and four-part versions
- Install a requirement with extras unless it would downgrade the
  protected package
- Check the requirement of every pip install command form, including
  those with --index-url, on the immediate and reserved paths
- Skip a protected package when the requirement cannot be compared and
  log why and how to install it
- At startup, recognize an installed package however its requirement
  spells the name, and upgrade one older than its '~=' version
- Remove the unused is_installed copies from both cores
- Add regression tests; update README, CHANGELOG and the resolver design

---------

Co-authored-by: Annika Zhang <287326049+annikazhang77@users.noreply.github.com>
Co-authored-by: Dr.Lt.Data <dr.lt.data@gmail.com>
2026-11-12 03:05:36 +09:00
Dr.Lt.Data dbdb642ed2 v4: Align minimum Python version with ComfyUI (#3490) 2026-11-12 01:37:59 +09:00
Dr.Lt.Data 215d7d4cb0 v4: Allow selected flagged CNR nodepacks through a whitelist (#3487) 2026-11-11 23:26:09 +09:00
Benjamin Lu 9c069c13c5 v4: Report desktop-linux form factor for Desktop installs on Linux
Desktop runs on Linux now, but get_form_factor mapped a Desktop install on
Linux to 'other', losing the platform in registry data.
2026-10-14 17:22:27 -07:00
Dr.Lt.Data f764cc0e54 bump version to 4.3 2026-09-19 08:46:33 +09:00
Dr.Lt.Data 69bc3ef1c6 v4: Restrict Flagged CNR installs on non-local listeners (#3299) 2026-09-19 08:29:23 +09:00
Dr.Lt.Data 4ad94b2048 v4: Secure legacy UI rendering and preserve administrator settings (#3297) 2026-09-19 08:12:25 +09:00
Dr.Lt.Data a0d89e9a56 Fix uv conflict attribution (#3300) 2026-09-19 06:39:28 +09:00
184 changed files with 29082 additions and 6239 deletions
+8 -5
View File
@@ -37,7 +37,8 @@ jobs:
code-quality:
name: Code Quality Checks
runs-on: ubuntu-latest
# Use a fixed image for syntax checks; E2E separately tests the latest runners.
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v4
with:
@@ -52,11 +53,13 @@ jobs:
files_ignore: |
comfyui_manager/legacy/**
- name: Setup Python
if: steps.changed-py-files.outputs.any_changed == 'true'
- name: Setup minimum supported Python
uses: actions/setup-python@v5
with:
python-version: '3.9'
python-version: '3.10'
- name: Check syntax on minimum supported Python
run: python -m compileall -q comfyui_manager cm_cli
- name: Install dependencies
if: steps.changed-py-files.outputs.any_changed == 'true'
@@ -67,4 +70,4 @@ jobs:
if: steps.changed-py-files.outputs.any_changed == 'true'
run: |
echo "Changed files: ${{ steps.changed-py-files.outputs.all_changed_files }}"
echo "${{ steps.changed-py-files.outputs.all_changed_files }}" | xargs -r ruff check
echo "${{ steps.changed-py-files.outputs.all_changed_files }}" | xargs -r ruff check
+1
View File
@@ -58,6 +58,7 @@ jobs:
shell: bash
env:
MANAGER_ROOT: ${{ github.workspace }}
UV_PYTHON: ${{ matrix.python-version }}
run: |
python tests/e2e/scripts/setup_e2e_env.py
+1132
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -10,5 +10,5 @@ include extension-node-list.json
include extras.json
include github-stats.json
include model-list.json
include alter-list.json
include comfyui_manager/channels.list.template
include comfyui_manager/channels.list.template
prune tests
+102 -6
View File
@@ -14,6 +14,8 @@
## Installation
Requires Python 3.10 or newer, matching ComfyUI's minimum Python version.
* When installing the latest ComfyUI, it will be automatically installed as a dependency, so manual installation is no longer necessary.
* Manual installation of the nightly version:
@@ -77,8 +79,7 @@
![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/topbar.jpg) ![share](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share.jpg)
* You can share the workflow by clicking the Share button at the bottom of the main menu or selecting Share Output from the Context Menu of the Image node.
* Currently, it supports sharing via [https://comfyworkflows.com/](https://comfyworkflows.com/),
[https://openart.ai](https://openart.ai/workflows/dev), [https://youml.com](https://youml.com)
* Currently, it supports sharing via [https://youml.com](https://youml.com)
as well as through the Matrix channel.
![menu](https://raw.githubusercontent.com/ltdrdata/ComfyUI-extension-tutorials/Main/ComfyUI-Manager/images/share-setting.jpg)
@@ -100,6 +101,7 @@ In `ComfyUI-Manager` V4.0.3b4 and later, configuration files and dynamically gen
* Configurable pip overrides: `<USER_DIRECTORY>/__manager/pip_overrides.json`
* Configurable pip blacklist: `<USER_DIRECTORY>/__manager/pip_blacklist.list`
* Configurable pip auto fix: `<USER_DIRECTORY>/__manager/pip_auto_fix.list`
* Configurable flagged nodepack whitelist: `<USER_DIRECTORY>/__manager/nodepack-whitelist.list`
* Saved snapshot files: `<USER_DIRECTORY>/__manager/snapshots`
* Startup script files: `<USER_DIRECTORY>/__manager/startup-scripts`
* Component files: `<USER_DIRECTORY>/__manager/components`
@@ -207,6 +209,7 @@ The following settings are applied based on the section marked as `is_default`.
[default]
git_exe = <Manually specify the path to the git executable. If left empty, the default git executable path will be used.>
use_uv = <Use uv instead of pip for dependency installation.>
dependency_management = <on|off; defaults to on. Disable automatic startup package changes in externally-managed Python environments.>
default_cache_as_channel_url = <Determines whether to retrieve the DB designated as channel_url at startup>
bypass_ssl = <Set to True if SSL errors occur to disable SSL.>
file_logging = <Configure whether to create a log file used by ComfyUI-Manager.>
@@ -216,6 +219,7 @@ The following settings are applied based on the section marked as `is_default`.
security_level = <Set the security level => strong|normal|normal-|weak>
allow_git_url_install = <Allow installing custom nodes from arbitrary git URLs. Independent of security_level. Default: False>
allow_pip_install = <Allow installing arbitrary pip packages via the Manager. Independent of security_level. Default: False>
allow_flagged_nodepack_install = <Allow flagged CNR versions on non-local listeners in trusted private networks. Default: False>
always_lazy_install = <Whether to perform dependency installation on restart even in environments other than Windows.>
network_mode = <Set the network mode => public|private|offline|personal_cloud>
```
@@ -224,7 +228,11 @@ The following settings are applied based on the section marked as `is_default`.
- public: An environment that uses a typical public network.
- private: An environment that uses a closed network, where a private node DB is configured via `channel_url`. (Uses cache if available)
- offline: An environment that does not use any external connections when using an offline network. (Uses cache if available)
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
- personal_cloud: Applies relaxed security features in cloud environments such as Google Colab or Runpod, where strong security is not required.
* `dependency_management = off` skips PIPFixer auto-healing (in the server and in cm-cli) and the startup unified dependency resolver; with the resolver skipped, installs use per-node pip. Read-only package inventory operations remain available.
- `COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off` overrides the config setting. `false`, `0`, `no`, and `disabled` also disable it (case-insensitive).
- Explicit install/update commands, including those applied at the next restart, and custom-node `install.py` scripts remain available and can modify the environment. This setting is not a sandbox; externally-managed installations should use `--no-deps` for explicit node operations where supported and provision dependencies separately.
## Additional Feature
@@ -251,6 +259,7 @@ The following settings are applied based on the section marked as `is_default`.
```
downgrade_blacklist = diffusers, kornia
```
* Names are matched without regard to case or to `-`, `_`, and `.`, so `opencv-python` and `opencv_python` are the same package.
* Custom pip mapping
* When you create the `pip_overrides.json` file, it changes the installation of specific pip packages to installations defined by the user.
@@ -326,10 +335,10 @@ The security settings are applied based on whether the ComfyUI server's listener
| Risky Level | features |
|-------------|---------------------------------------------------------------------------------------------------------------------------------------|
| high+ | * **Switch ComfyUI version**<BR>* **Fix nodepack** |
| high+ | * **Switch ComfyUI version**<BR>* **Restore Snapshot**<BR>* **Fix nodepack** |
| high | _(no features at this tier — `Fix nodepack` promoted to `high+` to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text)_ |
| middle+ | * Uninstall/Update<BR>* Installation of nodepack registered in the `default channel`.<BR>* Restore/Remove Snapshot<BR>* Install model |
| middle | * Restart |
| middle+ | * Uninstall/Update<BR>* Installation of Git/nightly nodepacks registered in the `default channel`.<BR>* Enabling a disabled nightly in the place of an enabled Registry version.<BR>* Install model |
| middle | * Restart<BR>* Remove Snapshot<BR>* Installation of CNR release versions (subject to the flagged-version policy below) |
| low | * Update ComfyUI |
* **Note**: `Install via git url` and `pip install` are no longer gated by `security_level` — they moved to the dedicated flags `allow_git_url_install` / `allow_pip_install`. Installation of a nodepack registered not in the `default channel` likewise requires `allow_git_url_install` (in addition to the `middle+` level preconditions) instead of a `high+` security level. See the [Dedicated install flags](#dedicated-install-flags-allow_git_url_install--allow_pip_install) subsection below.
@@ -359,6 +368,93 @@ The `Install via git url` and `pip install` features are governed by two dedicat
* Changes to these flags require a restart of ComfyUI to take effect.
* Migration note: if you previously relied on `security_level = weak` or `normal-` to use these features, you must now opt in explicitly by setting the flags in the `[default]` section of `config.ini`. The flags are not auto-seeded from your `security_level`.
### Flagged CNR nodepacks
Before downloading a CNR release, Manager checks the selected version's `status`
in the existing `/nodes/{id}/install` response. No additional Registry request is
needed. The check applies to both the default and legacy Manager implementations,
including CNR version changes, updates, and snapshot restores. Legacy batch
reinstallation checks the target before removing the existing nodepack, and a
policy refusal preserves the current installation. For flagged-policy denials,
the UI reports that the current security configuration does not allow the action
and directs users to the terminal. Only the terminal provides loopback-only
`--listen` examples, the private network override setting, the pack whitelist,
and restart instructions.
* Active versions continue through the normal install flow. New HTTP requests
to install CNR releases use the `middle` security level, so they are available
on non-local listeners with `security_level = normal`, `normal-`, or `weak`.
`strong` denies these new requests, including requests for whitelisted packs.
* Flagged versions (`NodeVersionStatusFlagged`) must satisfy the same installation
conditions as Active versions. In addition, **all** addresses in `--listen`
must resolve to loopback, such as `127.0.0.1` and `::1`, unless the explicit
override below is enabled or the pack ID is whitelisted.
* To allow specific packs on any listener without enabling all flagged installs,
edit `nodepack-whitelist.list` beside Manager's `config.ini`
(normally `<USER_DIRECTORY>/__manager/nodepack-whitelist.list`).
At server startup, Manager creates a commented template if the file is missing;
existing files are preserved. The template grants no exceptions by default.
Enter one Registry pack ID per line:
```text
# Nodepack whitelist
# Add one Registry ID per line; each entry applies to all CNR versions.
# Registry IDs are case-insensitive.
comfyui-impact-pack
comfyui-inspire-pack # Inline comments are supported.
```
Entries are case-insensitive and apply to all CNR versions of that pack. Use
Registry IDs, not display names, Git URLs, or `id@version`; wildcards are not
expanded. Blank lines and `#` comments are ignored. Delete an entry or comment
out its line with `#` to revoke that exception. Manager reads the file
for each installation check, so edits and removals apply without restarting.
A missing, unreadable, or NUL-containing file grants no whitelist exceptions.
If mixed encodings introduce NUL characters, Manager logs a warning to save
the file as UTF-8. Whitelist-based permission is logged at WARNING level with
the Registry ID, including in snapshot restore children. This records the policy
decision, not successful installation. Packs absent from the list continue to
use the listener and global option rules.
* To allow flagged versions on a non-local listener in a **trusted private
network**, an administrator can explicitly opt in:
```ini
[default]
allow_flagged_nodepack_install = true
```
* The option defaults to `false`. Only `true` (case-insensitive) enables it;
missing or invalid values are treated as `false`. Restart ComfyUI after editing it.
* With this option enabled, the flagged-version check allows installation
regardless of the listen address. Manager does not automatically detect a
private network. This option does not require `network_mode = private`, and
`network_mode = personal_cloud` alone does not allow flagged versions.
* CNR API refusals, including banned or unavailable packages, still prevent
installation. Neither the option nor the whitelist bypasses the `strong`
restriction on new HTTP install requests or the separate Git/nightly and pip
installation policies.
* Enabling an already installed version does not query the Registry or reinstall it.
* Older deferred switches without a stored status require loopback-only listeners,
the override, or a whitelisted pack ID. Otherwise they are rejected without
changing the installed pack; request the installation again so Manager can
check its current Registry status.
* Newly scheduled deferred version switches retain the returned version status
and check it against the current listen address, option, and whitelist again
at restart.
This uses the saved status; it does not query CNR again for later status changes.
Server-scheduled snapshot restores inherit the permission computed from the
server's current listener and setting, and read the whitelist from the server's
Manager configuration directory.
* Startup execution of deferred CNR switches and server-scheduled snapshot
restores does not recheck `security_level`. Changing it to `strong` does not
cancel previously scheduled work. For example, a flagged version switch
scheduled under `normal` can still run after restarting with `strong` if the
pack remains whitelisted. The startup flagged-version checks described above
still apply. This is existing behavior of scheduled execution.
* Standalone `cm-cli` commands remain local administrator operations and do not
use the server listener policy.
# Disclaimer
-1
View File
@@ -2,7 +2,6 @@
python json-checker.py "custom-node-list.json"
python json-checker.py "model-list.json"
python json-checker.py "alter-list.json"
python json-checker.py "extension-node-map.json"
python json-checker.py "node_db\new\custom-node-list.json"
python json-checker.py "node_db\new\model-list.json"
-1
View File
@@ -6,7 +6,6 @@ echo CHECK1
files=(
"custom-node-list.json"
"model-list.json"
"alter-list.json"
"extension-node-map.json"
"github-stats.json"
"extras.json"
+123 -121
View File
@@ -8,7 +8,7 @@ import threading
from typing import Optional
import typer
from rich import print
import rich
from typing_extensions import List, Annotated
import re
import importlib
@@ -21,17 +21,18 @@ import importlib
comfy_path = os.environ.get('COMFYUI_PATH')
if comfy_path is None:
print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
rich.print("[bold red]cm-cli: environment variable 'COMFYUI_PATH' is not specified.[/bold red]")
exit(-1)
sys.path.append(comfy_path)
if not os.path.exists(os.path.join(comfy_path, 'folder_paths.py')):
print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
rich.print("[bold red]cm-cli: '{comfy_path}' is not a valid 'COMFYUI_PATH' location.[/bold red]")
exit(-1)
import utils.extra_config
from comfyui_manager.common.git_compat import setup_git_environment
from comfyui_manager.common import manager_util
from comfyui_manager.common import cm_global
from comfyui_manager.legacy import manager_core as core
@@ -39,6 +40,8 @@ from comfyui_manager.common import context
from comfyui_manager.legacy.manager_core import unified_manager
from comfyui_manager.common import cnr_utils
print = core.print
comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
cm_global.pip_blacklist = {'torch', 'torchaudio', 'torchsde', 'torchvision'}
@@ -66,7 +69,7 @@ def check_comfyui_hash():
core.comfy_ui_revision = repo.iter_commits_count()
core.comfy_ui_commit_datetime = repo.head_commit_datetime
except Exception:
print('[bold yellow]INFO: Frozen ComfyUI mode.[/bold yellow]')
print('INFO: Frozen ComfyUI mode.', style='bold yellow')
core.comfy_ui_revision = 0
core.comfy_ui_commit_datetime = 0
@@ -74,13 +77,12 @@ def check_comfyui_hash():
check_comfyui_hash() # This is a preparation step for manager_core
core.check_invalid_nodes()
def read_downgrade_blacklist():
try:
import configparser
config = configparser.ConfigParser(strict=False)
config = configparser.ConfigParser(strict=False, interpolation=None)
config.read(context.manager_config_path)
default_conf = config['default']
@@ -135,25 +137,25 @@ class Ctx:
self.no_deps = no_deps
def set_user_directory(self, user_directory):
if user_directory is None:
return
if user_directory is not None:
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
extra_model_paths_yaml = os.path.join(user_directory, 'extra_model_paths.yaml')
if os.path.exists(extra_model_paths_yaml):
utils.extra_config.load_extra_path_config(extra_model_paths_yaml)
context.update_user_directory(user_directory)
context.update_user_directory(user_directory)
if os.path.exists(context.manager_pip_overrides_path):
with open(context.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
if os.path.exists(context.manager_pip_overrides_path):
with open(context.manager_pip_overrides_path, 'r', encoding="UTF-8", errors="ignore") as json_file:
cm_global.pip_overrides = json.load(json_file)
if os.path.exists(context.manager_pip_blacklist_path):
with open(context.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
if os.path.exists(context.manager_pip_blacklist_path):
with open(context.manager_pip_blacklist_path, 'r', encoding="UTF-8", errors="ignore") as f:
for x in f.readlines():
y = x.strip()
if y != '':
cm_global.pip_blacklist.add(y)
setup_git_environment(core.get_config()['git_exe'])
def update_custom_nodes_dir(self, target_dir):
import folder_paths
@@ -196,7 +198,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
res = asyncio.run(core.gitclone_install(node_spec_str, no_deps=cmd_ctx.no_deps))
if not res.result:
print(res.msg)
print(f"[bold red]ERROR: An error occurred while installing '{node_spec_str}'.[/bold red]")
print(f"ERROR: An error occurred while installing '{node_spec_str}'.", style="bold red")
if raise_on_fail:
raise NodeInstallError(node_spec_str)
else:
@@ -217,7 +219,7 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
if res.action == 'skip':
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
elif res.action == 'enable':
elif res.action == 'enable' and res.result:
print(f"{cnt_msg} [ ENABLED ] {node_name:50}")
elif res.action == 'install-git' and res.target == 'nightly':
print(f"{cnt_msg} [INSTALLED] {node_name:50}[NIGHTLY]")
@@ -232,56 +234,62 @@ def install_node(node_spec_str, is_all=False, cnt_msg='', **kwargs):
show_versions(node_name)
print("")
else:
print(f"[bold red]ERROR: An error occurred while installing '{node_name}'.\n{res.msg}[/bold red]")
print(f"ERROR: An error occurred while installing '{node_name}'.\n{res.msg}", style="bold red")
if raise_on_fail:
raise NodeInstallError(node_name)
def reinstall_node(node_spec_str, is_all=False, cnt_msg=''):
repo_url = None
if core.is_valid_url(node_spec_str):
# URL-based: resolve_node_spec returns the full URL as node_name,
# but internal dicts are keyed by repo basename or cnr_id.
url = node_spec_str.rstrip('/')
cnr = unified_manager.get_cnr_by_repo(url)
if cnr:
node_id = cnr['id']
unified_manager.unified_uninstall(node_id, False)
unified_manager.purge_node_state(node_id)
node_name, version_spec = cnr['id'], 'nightly'
else:
repo_name = os.path.splitext(os.path.basename(url))[0]
unified_manager.unified_uninstall(repo_name, True)
unified_manager.purge_node_state(repo_name)
install_node(node_spec_str, is_all=is_all, cnt_msg=cnt_msg, raise_on_fail=True)
node_name, version_spec, repo_url = core.unknown_node_id(url), 'unknown', url
else:
node_spec = unified_manager.resolve_node_spec(node_spec_str)
node_name, version_spec, _ = node_spec
node_name, version_spec, is_specified = unified_manager.resolve_node_spec(node_spec_str)
if not is_specified:
for guess_mode in ('active', 'inactive'):
installed = unified_manager.resolve_unspecified_version(node_name, guess_mode=guess_mode)
if installed not in (None, 'unknown'):
version_spec = installed
break
unified_manager.unified_uninstall(node_name, version_spec == 'unknown')
unified_manager.purge_node_state(node_name)
res = asyncio.run(unified_manager.reinstall_by_id(node_name, version_spec, cmd_ctx.channel, cmd_ctx.mode, instant_execution=True,
no_deps=cmd_ctx.no_deps, repo_url=repo_url))
if res.action == 'skip':
print(f"{cnt_msg} [ SKIP ] {node_name:50} => Already installed")
return
if not res.result:
print(f"ERROR: An error occurred while reinstalling '{node_name}'.\n{res.msg}", style="bold red")
raise NodeInstallError(node_name)
install_node(node_name, is_all=is_all, cnt_msg=cnt_msg, raise_on_fail=True)
target = res.target.upper() if res.target in ('nightly', 'unknown') else res.target
print(f"{cnt_msg} [REINSTALLED] {node_name:50}[{target}]")
def fix_node(node_spec_str, is_all=False, cnt_msg=''):
def fix_node(node_spec_str, is_all=False, cnt_msg='', fixed=None):
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
if node_spec is None:
if not is_all:
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
if unified_manager.resolve_node_spec(node_spec_str, guess_mode='inactive') is not None:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Disabled")
else:
print(f"{cnt_msg} [ SKIPPED ]: {node_spec_str:50} => Not installed")
return
node_name, version_spec, _ = node_spec
print(f"{cnt_msg} [ FIXING ]: {node_name:50}[{version_spec}]")
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps)
res = unified_manager.unified_fix(node_name, version_spec, no_deps=cmd_ctx.no_deps, fixed=fixed)
if not res.result:
print(f"[bold red]ERROR: f{res.msg}[/bold red]")
print(f"ERROR: {res.msg}", style="bold red")
def uninstall_node(node_spec_str: str, is_all: bool = False, cnt_msg: str = ''):
@@ -337,8 +345,9 @@ def update_parallel(nodes):
nodes = []
for x in unified_manager.active_nodes.keys():
nodes.append(x)
for x in unified_manager.unknown_active_nodes.keys():
nodes.append(x+"@unknown")
for k, v in unified_manager.unknown_active_nodes.items():
if v[1] not in unified_manager.invalid_installations:
nodes.append(k+"@unknown")
else:
nodes = [x for x in nodes if x.lower() not in ['comfy', 'comfyui']]
@@ -412,6 +421,7 @@ def enable_node(node_spec_str, is_all=False, cnt_msg=''):
def disable_node(node_spec_str: str, is_all=False, cnt_msg=''):
if 'comfyui-manager' in node_spec_str.lower():
print(f"{cnt_msg} [ SKIP ] {node_spec_str:50} => Not disabled: its name has 'comfyui-manager'")
return
node_spec = unified_manager.resolve_node_spec(node_spec_str, guess_mode='active')
@@ -468,11 +478,7 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_active_nodes.items():
item = repo_unknown.get(k)
if item is None:
continue
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
log_item = "[ ENABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -505,11 +511,7 @@ def show_list(kind, simple=False):
if flag and kind != 'cnr':
for k, v in unified_manager.unknown_inactive_nodes.items():
item = repo_unknown.get(k)
if item is None:
continue
item = repo_unknown.get(k, {'title': k, 'author': 'N/A'})
log_item = "[ DISABLED ] ", item['title'], k, item['author']
unknown_processed.append(log_item)
@@ -543,7 +545,7 @@ def show_list(kind, simple=False):
if simple:
print(title+'@'+ver_spec)
else:
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) \\[{ver_spec}]")
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [{ver_spec}]")
for x in unknown_processed:
prefix, title, short_id, author = x
@@ -553,19 +555,19 @@ def show_list(kind, simple=False):
print(f"{prefix} {title:50} {short_id:30} (author: {author:20}) [UNKNOWN]")
async def show_snapshot(simple_mode=False):
json_obj = await core.get_current_snapshot()
def show_snapshot(simple_mode=False):
json_obj = asyncio.run(core.get_current_snapshot())
if simple_mode:
print(f"[{json_obj['comfyui']}] comfyui")
core.print(f"[{json_obj['comfyui']}] comfyui")
for k, v in json_obj['git_custom_nodes'].items():
print(f"[{v['hash']}] {k}")
core.print(f"[{v['hash']}] {k}")
for v in json_obj['file_custom_nodes']:
print(f"[ N/A ] {v['filename']}")
core.print(f"[ N/A ] {v['filename']}")
else:
formatted_json = json.dumps(json_obj, ensure_ascii=False, indent=4)
print(formatted_json)
core.print(formatted_json)
def show_snapshot_list(simple_mode=False):
@@ -646,7 +648,7 @@ def for_each_nodes(nodes, act, allow_all=True, **kwargs):
failed.append(x)
if failed:
print(f"\n[bold red]Failed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}[/bold red]")
print(f"\nFailed nodes ({len(failed)}/{total}): {', '.join(str(x) for x in failed)}", style="bold red")
sys.exit(1)
@@ -673,7 +675,7 @@ def install(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
no_deps: Annotated[
Optional[bool],
@@ -704,7 +706,7 @@ def install(
cmd_ctx.set_channel_mode(channel, mode)
if uv_compile and no_deps:
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
raise typer.Exit(1)
if uv_compile:
@@ -713,7 +715,7 @@ def install(
cmd_ctx.set_no_deps(no_deps)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for_each_nodes(nodes, act=install_node, exit_on_fail=exit_on_fail)
for_each_nodes(nodes, act=install_node, raise_on_fail=exit_on_fail)
_finalize_resolve(pip_fixer, uv_compile)
@@ -732,7 +734,7 @@ def reinstall(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
no_deps: Annotated[
Optional[bool],
@@ -759,7 +761,7 @@ def reinstall(
cmd_ctx.set_channel_mode(channel, mode)
if uv_compile and no_deps:
print("[bold red]--uv-compile and --no-deps are mutually exclusive.[/bold red]")
print("--uv-compile and --no-deps are mutually exclusive.", style="bold red")
raise typer.Exit(1)
if uv_compile:
@@ -787,7 +789,7 @@ def uninstall(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
):
cmd_ctx.set_channel_mode(channel, mode)
@@ -798,7 +800,7 @@ def uninstall(
def update(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to update]"
help="all|List of custom nodes to update"
),
channel: Annotated[
str,
@@ -809,7 +811,7 @@ def update(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -849,7 +851,7 @@ def update(
def disable(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to disable]"
help="all|List of custom nodes to disable"
),
channel: Annotated[
str,
@@ -860,7 +862,7 @@ def disable(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -880,7 +882,7 @@ def disable(
def enable(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to enable]"
help="all|List of custom nodes to enable"
),
channel: Annotated[
str,
@@ -891,7 +893,7 @@ def enable(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -911,7 +913,7 @@ def enable(
def fix(
nodes: List[str] = typer.Argument(
...,
help="[all|List of custom nodes to fix]"
help="all|List of custom nodes to fix"
),
channel: Annotated[
str,
@@ -922,7 +924,7 @@ def fix(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -947,7 +949,7 @@ def fix(
asyncio.run(auto_save_snapshot())
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
for_each_nodes(nodes, fix_node, allow_all=True)
for_each_nodes(nodes, fix_node, allow_all=True, fixed=set())
_finalize_resolve(pip_fixer, uv_compile)
@@ -965,7 +967,7 @@ def show_versions(node_name: str):
@app.command("show", help="Show node list")
def show(
arg: str = typer.Argument(
help="[installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list]"
help="installed|enabled|not-installed|disabled|all|cnr|snapshot|snapshot-list"
),
channel: Annotated[
str,
@@ -976,7 +978,7 @@ def show(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1010,7 +1012,7 @@ def show(
@app.command("simple-show", help="Show node list (simple mode)")
def simple_show(
arg: str = typer.Argument(
help="[installed|enabled|not-installed|disabled|all|snapshot|snapshot-list]"
help="installed|enabled|not-installed|disabled|all|snapshot|snapshot-list"
),
channel: Annotated[
str,
@@ -1021,7 +1023,7 @@ def simple_show(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1038,7 +1040,7 @@ def simple_show(
"snapshot-list",
]
if arg not in valid_commands:
typer.echo(f"[bold red]Invalid command: `show {arg}`[/bold red]", err=True)
typer.echo(f"Invalid command: `show {arg}`", err=True)
exit(1)
cmd_ctx.set_user_directory(user_directory)
@@ -1072,7 +1074,7 @@ def deps_in_workflow(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1086,7 +1088,7 @@ def deps_in_workflow(
output_path = output
if not os.path.exists(input_path):
print(f"[bold red]File not found: {input_path}[/bold red]")
print(f"File not found: {input_path}", style="bold red")
exit(1)
used_exts, unknown_nodes = asyncio.run(core.extract_nodes_from_workflow(input_path, mode=cmd_ctx.mode, channel_url=cmd_ctx.channel))
@@ -1131,13 +1133,13 @@ def save_snapshot(
if output is not None:
if(not output.endswith('.json') and not output.endswith('.yaml')):
print("[bold red]ERROR: output path should be either '.json' or '.yaml' file.[/bold red]")
print("ERROR: output path should be either '.json' or '.yaml' file.", style="bold red")
raise typer.Exit(code=1)
dir_path = os.path.dirname(output)
if(dir_path != '' and not os.path.exists(dir_path)):
print(f"[bold red]ERROR: {output} path not exists.[/bold red]")
print(f"ERROR: {output} path not exists.", style="bold red")
raise typer.Exit(code=1)
path = asyncio.run(core.save_snapshot_with_postfix('snapshot', output, not full_snapshot))
@@ -1207,14 +1209,14 @@ def restore_snapshot(
else:
snapshot_path = os.path.join(cmd_ctx.get_snapshot_path(), snapshot_name)
if not os.path.exists(snapshot_path):
print(f"[bold red]ERROR: `{snapshot_path}` is not exists.[/bold red]")
print(f"ERROR: `{snapshot_path}` is not exists.", style="bold red")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
try:
asyncio.run(core.restore_snapshot(snapshot_path, extras))
is_restored = asyncio.run(core.restore_snapshot(snapshot_path, extras))
except Exception:
print("[bold red]ERROR: Failed to restore snapshot.[/bold red]")
print("ERROR: Failed to restore snapshot.", style="bold red")
traceback.print_exc()
if uv_compile:
pip_fixer.fix_broken()
@@ -1222,6 +1224,9 @@ def restore_snapshot(
_finalize_resolve(pip_fixer, uv_compile)
if not is_restored:
raise typer.Exit(code=1)
@app.command(
"restore-dependencies", help="Restore dependencies from whole installed custom nodes."
@@ -1250,7 +1255,7 @@ def restore_dependencies(
for base_path in cmd_ctx.get_custom_nodes_paths():
for name in os.listdir(base_path):
target = os.path.join(base_path, name)
if os.path.isdir(target) and not name.endswith('.disabled'):
if os.path.isdir(target) and not name.endswith('.disabled') and name != '__pycache__':
node_paths.append(target)
total = len(node_paths)
@@ -1298,7 +1303,7 @@ def install_deps(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1322,14 +1327,14 @@ def install_deps(
asyncio.run(auto_save_snapshot())
if not os.path.exists(deps):
print(f"[bold red]File not found: {deps}[/bold red]")
print(f"File not found: {deps}", style="bold red")
exit(1)
else:
with open(deps, 'r', encoding="UTF-8", errors="ignore") as json_file:
try:
json_obj = json.load(json_file)
except Exception:
print(f"[bold red]Invalid json file: {deps}[/bold red]")
print(f"Invalid json file: {deps}", style="bold red")
exit(1)
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, context.manager_files_path)
@@ -1340,7 +1345,8 @@ def install_deps(
elif state == 'not-installed':
asyncio.run(core.gitclone_install(k, instant_execution=True, no_deps=bool(uv_compile)))
else: # disabled
core.gitclone_set_active([k], False)
cnr = unified_manager.get_cnr_by_repo(k)
enable_node(cnr['id'] if cnr else core.unknown_node_id(k))
_finalize_resolve(pip_fixer, uv_compile)
@@ -1353,12 +1359,12 @@ def _finalize_resolve(pip_fixer, uv_compile) -> None:
try:
_run_unified_resolve()
except ImportError as e:
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
print(f"[bold red]Batch resolution failed: {e}[/bold red]")
print(f"Batch resolution failed: {e}", style="bold red")
raise typer.Exit(1)
finally:
pip_fixer.fix_broken()
@@ -1378,7 +1384,7 @@ def _run_unified_resolve():
node_pack_paths = collect_node_pack_paths(cmd_ctx.get_custom_nodes_paths())
if not node_pack_paths:
print("[bold yellow]No custom node packs found.[/bold yellow]")
print("No custom node packs found.", style="bold yellow")
return
print(f"Resolving dependencies for {len(node_pack_paths)} node pack(s)...")
@@ -1393,27 +1399,28 @@ def _run_unified_resolve():
try:
result = resolver.resolve_and_install()
except UvNotAvailableError:
print("[bold red]uv is not available. Install uv to use this feature.[/bold red]")
print("uv is not available. Install uv to use this feature.", style="bold red")
raise typer.Exit(1)
if result.success:
collected = result.collected
if collected:
print(
f"[bold green]Resolved {len(collected.requirements)} deps "
f"Resolved {len(collected.requirements)} deps "
f"from {len(collected.sources)} source(s) "
f"(skipped {len(collected.skipped)}).[/bold green]"
f"(skipped {len(collected.skipped)}).",
style="bold green",
)
else:
print("[bold green]Resolution complete (no deps needed).[/bold green]")
print("Resolution complete (no deps needed).", style="bold green")
else:
print(f"[bold red]Resolution failed: {result.error}[/bold red]")
print(f"Resolution failed: {result.error}", style="bold red")
if result.lockfile and result.lockfile.conflicts and result.collected:
attributed = attribute_conflicts(result.collected.sources, result.lockfile.conflicts)
if attributed:
print("[bold yellow]Conflicting packages (by node pack):[/bold yellow]")
print("Conflicting packages (by node pack):", style="bold yellow")
for pkg_name, requesters in sorted(attributed.items()):
print(f" [yellow]{pkg_name}[/yellow]:")
print(f" {pkg_name}:", style="yellow")
for pack_path, pkg_spec in requesters:
print(f" {os.path.basename(pack_path)} → {pkg_spec}")
raise typer.Exit(1)
@@ -1435,12 +1442,12 @@ def unified_uv_compile(
try:
_run_unified_resolve()
except ImportError as e:
print(f"[bold red]Failed to import unified_dep_resolver: {e}[/bold red]")
print(f"Failed to import unified_dep_resolver: {e}", style="bold red")
raise typer.Exit(1)
except typer.Exit:
raise
except Exception as e:
print(f"[bold red]Unexpected error: {e}[/bold red]")
print(f"Unexpected error: {e}", style="bold red")
raise typer.Exit(1)
finally:
pip_fixer.fix_broken()
@@ -1463,7 +1470,7 @@ def export_custom_node_ids(
] = None,
mode: str = typer.Option(
None,
help="[remote|local|cache]"
help="remote|local|cache"
),
user_directory: str = typer.Option(
None,
@@ -1525,7 +1532,6 @@ async def _force_update_cache(channel):
"custom-node-list.json",
"extension-node-map.json",
"model-list.json",
"alter-list.json",
"github-stats.json",
]
@@ -1541,13 +1547,12 @@ async def _force_update_cache(channel):
json_obj = await manager_util.get_data(uri, silent=True)
with manager_util.cache_lock:
with open(cache_uri, "w", encoding='utf-8') as file:
json.dump(json_obj, file, indent=4, sort_keys=True)
if not manager_util.write_cache_file(cache_uri, json_obj):
raise OSError("the cache file is in use")
print(f" [CACHED] {filename}")
except Exception as e:
print(f" [bold red][FAILED] {filename}: {e}[/bold red]")
print(f" [FAILED] {filename}: {e}", style="bold red")
failed.append(filename)
print("Fetching channel data...")
@@ -1560,7 +1565,7 @@ async def _force_update_cache(channel):
try:
await unified_manager.reload('remote', dont_wait=False)
except Exception as e:
print(f" [bold red][FAILED] CNR registry: {e}[/bold red]")
print(f" [FAILED] CNR registry: {e}", style="bold red")
failed.append("CNR registry")
# Step 3: Load nightly data (cache files now exist from Step 1)
@@ -1568,10 +1573,10 @@ async def _force_update_cache(channel):
await unified_manager.load_nightly(channel or 'default', 'cache')
if failed:
print(f"\n[bold red]Cache update incomplete. Failed: {', '.join(failed)}[/bold red]")
print(f"\nCache update incomplete. Failed: {', '.join(failed)}", style="bold red")
sys.exit(1)
else:
print("[bold green]Cache update complete.[/bold green]")
print("Cache update complete.", style="bold green")
def main():
@@ -1581,6 +1586,3 @@ def main():
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(app())
print("")
-224
View File
@@ -1,224 +0,0 @@
{
"items": [
{
"id":"https://github.com/Fannovel16/comfyui_controlnet_aux",
"tags":"controlnet",
"description": "This extension provides preprocessor nodes for using controlnet."
},
{
"id":"https://github.com/comfyanonymous/ComfyUI_experiments",
"tags":"Dynamic Thresholding, DT, CFG, controlnet, reference only",
"description": "This experimental nodes contains a 'Reference Only' node and a 'ModelSamplerTonemapNoiseTest' node corresponding to the 'Dynamic Threshold'."
},
{
"id":"https://github.com/ltdrdata/ComfyUI-Impact-Pack",
"tags":"ddetailer, adetailer, ddsd, DD, loopback scaler, prompt, wildcard, dynamic prompt",
"description": "To implement the feature of automatically detecting faces and enhancing details, various detection nodes and detailers provided by the Impact Pack can be applied. Similarly to Loopback Scaler, it also provides various custom workflows that can apply Ksampler while gradually scaling up."
},
{
"id":"https://github.com/ltdrdata/ComfyUI-Inspire-Pack",
"tags":"lora block weight, effective block analyzer, lbw, variation seed",
"description": "The Inspire Pack provides the functionality of Lora Block Weight, Variation Seed."
},
{
"id":"https://github.com/biegert/ComfyUI-CLIPSeg/raw/main/custom_nodes/clipseg.py",
"tags":"ddsd",
"description": "This extension provides a feature that generates segment masks on an image using a text prompt. When used in conjunction with Impact Pack, it enables applications such as DDSD."
},
{
"id":"https://github.com/BadCafeCode/masquerade-nodes-comfyui",
"tags":"ddetailer",
"description": "This extension is a less feature-rich and well-maintained alternative to Impact Pack, but it has fewer dependencies and may be easier to install on abnormal configurations. The author recommends trying Impact Pack first."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_Cutoff",
"tags":"cutoff",
"description": "By using this extension, prompts like 'blue hair' can be prevented from interfering with other prompts by blocking the attribute 'blue' from being used in prompts other than 'hair'."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb",
"tags":"prompt, weight",
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. With this extension, various settings can be used to implement prompt processing methods similar to A1111. As this feature is also integrated into ComfyUI Cutoff, please download the Cutoff extension if you plan to use it in conjunction with Cutoff."
},
{
"id":"https://github.com/shiimizu/ComfyUI_smZNodes",
"tags":"prompt, weight",
"description": "There are differences in the processing methods of prompts, such as weighting and scheduling, between A1111 and ComfyUI. This extension helps to reproduce the same embedding as A1111."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_Noise",
"tags":"img2img alt, random",
"description": "The extension provides an unsampler that reverses the sampling process, allowing for a function similar to img2img alt to be implemented. Furthermore, ComfyUI uses CPU's Random instead of GPU's Random for better reproducibility compared to A1111. This extension provides the ability to use GPU's Random for Latent Noise. However, since GPU's Random may vary depending on the GPU model, reproducibility on different devices cannot be guaranteed."
},
{
"id":"https://github.com/BlenderNeko/ComfyUI_SeeCoder",
"tags":"seecoder, prompt-free-diffusion",
"description": "The extension provides seecoder feature."
},
{
"id":"https://github.com/lilly1987/ComfyUI_node_Lilly",
"tags":"prompt, wildcard",
"description": "This extension provides features such as a wildcard function that randomly selects prompts belonging to a category and the ability to directly load lora from prompts."
},
{
"id":"https://github.com/Davemane42/ComfyUI_Dave_CustomNode",
"tags":"latent couple",
"description": "ComfyUI already provides the ability to composite latents by default. However, this extension makes it more convenient to use by visualizing the composite area."
},
{
"id":"https://github.com/LEv145/images-grid-comfy-plugin",
"tags":"X/Y Plot",
"description": "This tool provides a viewer node that allows for checking multiple outputs in a grid, similar to the X/Y Plot extension."
},
{
"id":"https://github.com/pythongosssss/ComfyUI-WD14-Tagger",
"tags":"deepbooru, clip interrogation",
"description": "This extension generates clip text by taking an image as input and using the Deepbooru model."
},
{
"id":"https://github.com/szhublox/ambw_comfyui",
"tags":"supermerger",
"description": "This node takes two models, merges individual blocks together at various ratios, and automatically rates each merge, keeping the ratio with the highest score. "
},
{
"id":"https://github.com/ssitu/ComfyUI_UltimateSDUpscale",
"tags":"upscaler, Ultimate SD Upscale",
"description": "ComfyUI nodes for the Ultimate Stable Diffusion Upscale script by Coyote-A. Uses the same script used in the A1111 extension to hopefully replicate images generated using the A1111 webui."
},
{
"id":"https://github.com/dawangraoming/ComfyUI_ksampler_gpu/raw/main/ksampler_gpu.py",
"tags":"random, noise",
"description": "A1111 provides KSampler that uses GPU-based random noise. This extension offers KSampler utilizing GPU-based random noise."
},
{
"id":"https://github.com/space-nuko/nui-suite",
"tags":"prompt, dynamic prompt",
"description": "This extension provides nodes with the functionality of dynamic prompts."
},
{
"id":"https://github.com/melMass/comfy_mtb",
"tags":"roop",
"description": "This extension provides bunch of nodes including roop"
},
{
"id":"https://github.com/ssitu/ComfyUI_roop",
"tags":"roop",
"description": "This extension provides nodes for the roop A1111 webui script."
},
{
"id":"https://github.com/asagi4/comfyui-prompt-control",
"tags":"prompt, prompt editing",
"description": "This extension provides the ability to use prompts like \n\n**a [large::0.1] [cat|dog:0.05] [<lora:somelora:0.5:0.6>::0.5] [in a park:in space:0.4]**\n\n"
},
{
"id":"https://github.com/adieyal/comfyui-dynamicprompts",
"tags":"prompt, dynamic prompt",
"description": "This extension is a port of sd-dynamic-prompt to ComfyUI."
},
{
"id":"https://github.com/kwaroran/abg-comfyui",
"tags":"abg, background remover",
"description": "A Anime Background Remover node for comfyui, based on this hf space, works same as AGB extention in automatic1111."
},
{
"id":"https://github.com/Gourieff/comfyui-reactor-node",
"tags":"reactor, sd-webui-roop-nsfw",
"description": "This is a ported version of ComfyUI for the sd-webui-roop-nsfw extension."
},
{
"id":"https://github.com/laksjdjf/cgem156-ComfyUI",
"tags":"regional prompt, latent couple, prompt",
"description": "This custom nodes provide a functionality similar to regional prompts, offering couple features at the attention level."
},
{
"id":"https://github.com/FizzleDorf/ComfyUI_FizzNodes",
"tags":"deforum",
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
},
{
"id":"https://github.com/seanlynch/comfyui-optical-flow",
"tags":"deforum, vid2vid",
"description": "This custom nodes provide functionality that assists in animation creation, similar to deforum."
},
{
"id":"https://github.com/ssitu/ComfyUI_fabric",
"tags":"fabric",
"description": "Similar to sd-webui-fabric, this custom nodes provide the functionality of [a/FABRIC](https://github.com/sd-fabric/fabric)."
},
{
"id":"https://github.com/Zuellni/ComfyUI-ExLlama",
"tags":"ExLlama, prompt, language model",
"description": "Similar to text-generation-webui, this custom nodes provide the functionality of [a/exllama](https://github.com/turboderp/exllama)."
},
{
"id":"https://github.com/spinagon/ComfyUI-seamless-tiling",
"tags":"tiling",
"description": "ComfyUI node for generating seamless textures Replicates 'Tiling' option from A1111"
},
{
"id":"https://github.com/laksjdjf/cd-tuner_negpip-ComfyUI",
"tags":"cd-tuner, negpip",
"description": "This extension is a port of the [a/sd-webui-cd-tuner](https://github.com/hako-mikan/sd-webui-cd-tuner)(a.k.a. CD(color/Detail) Tuner )and [a/sd-webui-negpip](https://github.com/hako-mikan/sd-webui-negpip)(a.k.a. NegPiP) extensions of A1111 to ComfyUI."
},
{
"id":"https://github.com/mcmonkeyprojects/sd-dynamic-thresholding",
"tags":"DT, dynamic thresholding",
"description": "This custom node is a port of the Dynamic Thresholding extension from A1111 to make it available for use in ComfyUI."
},
{
"id":"https://github.com/hhhzzyang/Comfyui_Lama",
"tags":"lama, inpainting anything",
"description": "This extension provides custom nodes developed based on [a/LaMa](https://github.com/advimman/lama) and [a/Inpainting anything](https://github.com/geekyutao/Inpaint-Anything)."
},
{
"id":"https://github.com/mlinmg/ComfyUI-LaMA-Preprocessor",
"tags":"lama",
"description": "This extension provides custom nodes for [a/LaMa](https://github.com/advimman/lama) functionality."
},
{
"id":"https://github.com/Haoming02/comfyui-diffusion-cg",
"tags":"diffusion-cg",
"description": "This extension provides custom nodes for [a/SD Webui Diffusion Color Grading](https://github.com/Haoming02/sd-webui-diffusion-cg) functionality."
},
{
"id":"https://github.com/asagi4/ComfyUI-CADS",
"tags":"diffusion-cg",
"description": "This extension provides custom nodes for [a/sd-webui-cads](https://github.com/v0xie/sd-webui-cads) functionality."
},
{
"id":"https://git.mmaker.moe/mmaker/sd-webui-color-enhance",
"tags":"color-enhance",
"description": "This extension supports both A1111 and ComfyUI simultaneously."
},
{
"id":"https://github.com/shiimizu/ComfyUI-TiledDiffusion",
"tags":"multidiffusion",
"description": "This extension provides custom nodes for [a/Mixture of Diffusers](https://github.com/albarji/mixture-of-diffusers) and [a/MultiDiffusion](https://github.com/omerbt/MultiDiffusion)"
},
{
"id":"https://github.com/abyz22/image_control",
"tags":"BMAB",
"description": "This extension provides some alternative functionalities of the [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab) extension."
},
{
"id":"https://github.com/blepping/ComfyUI-sonar",
"tags":"sonar",
"description": "This extension provides some alternative functionalities of the [a/stable-diffusion-webui-sonar](https://github.com/Kahsolt/stable-diffusion-webui-sonar) extension."
},
{
"id":"https://github.com/AIFSH/ComfyUI-RVC",
"tags":"sonar",
"description": "a comfyui custom node for [a/Retrieval-based-Voice-Conversion-WebUI](https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git), you can Voice-Conversion in comfyui now!"
},
{
"id":"https://github.com/portu-sim/comfyui-bmab",
"tags":"bmab",
"description": "a comfyui custom node for [a/sd-webui-bmab](https://github.com/portu-sim/sd-webui-bmab)"
},
{
"id":"https://github.com/ThereforeGames/ComfyUI-Unprompted",
"tags":"unprompted",
"description": "This extension is a port of [a/unprompted](https://github.com/ThereforeGames/unprompted)"
}
]
}
+34 -22
View File
@@ -20,6 +20,29 @@ lock = asyncio.Lock()
is_cache_loading = False
def get_form_factor():
"""Form factor reported to the registry, based on environment and platform."""
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
system = platform.system().lower()
if is_desktop:
if system == 'windows':
return 'desktop-win'
if system == 'darwin':
return 'desktop-mac'
if system == 'linux':
return 'desktop-linux'
return 'other'
if system == 'windows':
return 'git-windows'
if system == 'darwin':
return 'git-mac'
if system == 'linux':
return 'git-linux'
return 'other'
async def get_cnr_data(cache_mode=True, dont_wait=True):
try:
return await _get_cnr_data(cache_mode, dont_wait)
@@ -39,12 +62,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
full_nodes = {}
# Determine form factor based on environment and platform
is_desktop = bool(os.environ.get('__COMFYUI_DESKTOP_VERSION__'))
system = platform.system().lower()
is_windows = system == 'windows'
is_mac = system == 'darwin'
is_linux = system == 'linux'
# Get ComfyUI version tag
if is_desktop:
@@ -53,22 +71,7 @@ async def _get_cnr_data(cache_mode=True, dont_wait=True):
else:
comfyui_ver = context.get_comfyui_tag() or 'unknown'
if is_desktop:
if is_windows:
form_factor = 'desktop-win'
elif is_mac:
form_factor = 'desktop-mac'
else:
form_factor = 'other'
else:
if is_windows:
form_factor = 'git-windows'
elif is_mac:
form_factor = 'git-mac'
elif is_linux:
form_factor = 'git-linux'
else:
form_factor = 'other'
form_factor = get_form_factor()
from comfyui_manager.glob import manager_core
verbose = manager_core.get_config().get('verbose', False)
@@ -134,6 +137,7 @@ class NodeVersion:
id: str
version: str
download_url: str
status: str = ''
def map_node_version(api_node_version):
@@ -165,6 +169,7 @@ def map_node_version(api_node_version):
download_url=api_node_version.get(
"downloadUrl", ""
), # Provide a default value if 'downloadUrl' is missing
status=api_node_version.get('status', ''),
)
@@ -237,6 +242,14 @@ def read_cnr_info(fullpath):
return None # not valid CNR node pack
def read_project_name(fullpath):
try:
with open(os.path.join(fullpath, 'pyproject.toml'), "r", encoding="utf-8") as f:
return toml.load(f)['project']['name'].strip()
except Exception:
return None
def generate_cnr_id(fullpath, cnr_id):
cnr_id_path = os.path.join(fullpath, '.git', '.cnr-id')
try:
@@ -257,4 +270,3 @@ def read_cnr_id(fullpath):
pass
return None
+93
View File
@@ -0,0 +1,93 @@
"""Shared settings-file writer for glob and legacy."""
import configparser
import logging
import os
import tempfile
class DirtyTrackingConfig(dict):
"""Track keys assigned after loading the startup configuration."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dirty_keys = set()
def __setitem__(self, key, value):
self.dirty_keys.add(key)
super().__setitem__(key, value)
def update(self, *args, **kwargs):
incoming = dict(*args, **kwargs)
self.dirty_keys.update(incoming)
super().update(incoming)
SETTING_VALUES = {
'security_level': ('normal', 'strong', 'normal-', 'weak'),
'network_mode': ('public', 'private', 'offline', 'personal_cloud'),
'db_mode': ('cache', 'channel', 'local', 'remote'),
'update_policy': ('stable-comfyui', 'nightly-comfyui', 'stable', 'nightly'),
}
def with_valid_values(settings):
for key, values in SETTING_VALUES.items():
default = values[0]
if settings[key] not in values:
logging.warning(f"[ComfyUI-Manager] {key} = {settings[key]!r} in config.ini is not valid; '{default}' is used.")
settings[key] = default
return settings
def write_config_merged(config_path, cached, written_config_keys):
"""Merge changed owned keys onto the latest settings on disk.
Preserve parsed keys and values, not INI comments or formatting."""
config = configparser.ConfigParser(strict=False, interpolation=None)
try:
loaded = config.read(config_path)
except (configparser.Error, UnicodeDecodeError) as e:
# Preserve the existing fallback for malformed files.
logging.warning(f"[ComfyUI-Manager] '{config_path}' could not be parsed ({e}); rewriting it from the current settings.")
config = configparser.ConfigParser(strict=False, interpolation=None)
else:
# ConfigParser.read silently skips unreadable files; do not overwrite one.
if not loaded and os.path.exists(config_path):
raise OSError(f"'{config_path}' exists but could not be read; refusing to overwrite it with default settings. Fix the file's permissions, then retry.")
if config.has_section('default'):
keys = [key for key in written_config_keys if key in cached.dirty_keys]
else:
config['default'] = {}
keys = list(written_config_keys)
section = config['default']
for key in keys:
section[key] = str(cached[key]).replace('\r', '').replace('\n', '').replace('\x00', '')
directory = os.path.dirname(config_path)
if directory and not os.path.exists(directory):
os.makedirs(directory)
# Replace from the same directory so readers never see a partial write.
tmp_path = None
try:
with tempfile.NamedTemporaryFile(
'w', dir=directory or '.', prefix='.config-', suffix='.tmp', delete=False
) as configfile:
tmp_path = configfile.name
config.write(configfile)
configfile.flush()
os.fsync(configfile.fileno())
# Retain the existing mode instead of the temporary file's 0600.
if os.path.exists(config_path):
os.chmod(tmp_path, os.stat(config_path).st_mode & 0o777)
os.replace(tmp_path, config_path)
tmp_path = None
finally:
if tmp_path is not None and os.path.exists(tmp_path):
os.remove(tmp_path)
# Clear only persisted keys, and only after a successful write.
cached.dirty_keys.difference_update(keys)
+2 -1
View File
@@ -9,10 +9,11 @@ class NetworkMode(enum.Enum):
class SecurityLevel(enum.Enum):
STRONG = "strong"
NORMAL = "normal"
NORMAL_MINUS = "normal-minus"
NORMAL_MINUS = "normal-"
WEAK = "weak"
class DBMode(enum.Enum):
LOCAL = "local"
CACHE = "cache"
CHANNEL = "channel"
REMOTE = "remote"
+203 -32
View File
@@ -15,7 +15,10 @@ Exports:
import os
import re
import shutil
import subprocess
import sys
import tempfile
from abc import ABC, abstractmethod
from collections import deque
from datetime import datetime, timezone, timedelta
@@ -52,25 +55,91 @@ def _to_https_url(url):
# Backend selection
# ---------------------------------------------------------------------------
def which_on_path(name):
"""Return the file that the directories of PATH give for a command name.
`shutil.which` looks in the current directory first on Windows, and takes
a directory of PATH that is not absolute.
"""
names = [name]
if os.name == 'nt':
extensions = [x for x in os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep) if x]
if not name.lower().endswith(tuple(x.lower() for x in extensions)):
names = [name + x for x in extensions]
for directory in os.get_exec_path():
for x in names:
path = os.path.join(directory, x)
if os.path.isabs(directory) and os.path.isfile(path) and os.access(path, os.X_OK):
return path
return None
def find_git_executable(git_exe, timeout=10):
# A name without a directory is a command of PATH; GitPython would take it
# as a file of the current directory.
path = shutil.which(git_exe) if os.path.dirname(git_exe) else which_on_path(git_exe)
if path is None:
return None
try:
# The answer goes to a file: with a pipe, Windows waits after the time
# is up for every program that holds the pipe.
with tempfile.TemporaryFile() as answer:
res = subprocess.run([path, 'version'], stdout=answer, stderr=subprocess.DEVNULL,
stdin=subprocess.DEVNULL, timeout=timeout)
answer.seek(0)
is_git = res.returncode == 0 and answer.read(11) == b'git version'
except (OSError, subprocess.SubprocessError):
return None
return os.path.abspath(path) if is_git else None
_PYGIT2_REQUESTED = os.environ.get('CM_USE_PYGIT2', '').strip() == '1'
USE_PYGIT2 = _PYGIT2_REQUESTED
_GIT_EXE = os.environ.get('GIT_EXE_PATH')
_GIT_EXE_FOUND = None
def _find_configured_git():
found = find_git_executable(_GIT_EXE)
if found is not None:
os.environ['GIT_PYTHON_GIT_EXECUTABLE'] = found
else:
print(f"[ComfyUI-Manager] `git_exe = {_GIT_EXE}` is not a working git executable. The default git is used.", file=sys.stderr)
return found
if not USE_PYGIT2 and _GIT_EXE:
_GIT_EXE_FOUND = _find_configured_git()
if not USE_PYGIT2:
try:
import git as _git
_git.Git().execute(['git', '--version'])
_git.Git().execute([_git.Git.GIT_PYTHON_GIT_EXECUTABLE, '--version'])
except Exception:
USE_PYGIT2 = True
if USE_PYGIT2:
# Without a git, GitPython raises already when it is imported, unless it
# is told to keep quiet. The legacy modules import it themselves.
os.environ.setdefault('GIT_PYTHON_REFRESH', 'quiet')
try:
import pygit2 as _pygit2
except ImportError:
# pygit2 not available either — fall back to GitPython and let it
# fail at the point of use, preserving pre-existing behavior.
# fail at the point of use.
USE_PYGIT2 = False
if _PYGIT2_REQUESTED and _GIT_EXE:
_GIT_EXE_FOUND = _find_configured_git()
_PYGIT2_REQUESTED = False
import git as _git
if not _git.GIT_OK:
print("[ComfyUI-Manager] No git executable was found and pygit2 is not installed. What needs git will fail.", file=sys.stderr)
else:
# Disable owner validation once at import time.
# Required for Desktop 2.0 standalone installs where repo directories
@@ -133,11 +202,11 @@ else:
if USE_PYGIT2:
if _PYGIT2_REQUESTED:
print("[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)")
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (CM_USE_PYGIT2=1)"
else:
print("[ComfyUI-Manager] Using pygit2 backend (system git not available)")
BACKEND_LINE = "[ComfyUI-Manager] Using pygit2 backend (system git not available)"
else:
print("[ComfyUI-Manager] Using GitPython backend")
BACKEND_LINE = "[ComfyUI-Manager] Using GitPython backend"
# ===================================================================
@@ -237,7 +306,14 @@ class GitRepo(ABC):
def checkout_new_branch(self, branch_name: str, start_point: str): ...
@abstractmethod
def submodule_update(self): ...
def submodule_update(self, init=True): ...
def undo_pull(self, commit):
self.reset_hard(commit)
try:
self.submodule_update(init=False)
except Exception:
pass
@abstractmethod
def clear_cache(self): ...
@@ -415,13 +491,17 @@ class _GitPythonRepo(GitRepo):
self._repo.create_head(name)
def checkout(self, ref):
# ref can be a _HeadProxy from get_head_by_name
if isinstance(ref, _HeadProxy):
ref = ref.name
self._repo.git.checkout(ref)
def checkout_new_branch(self, branch_name, start_point):
self._repo.git.checkout('-b', branch_name, start_point)
def submodule_update(self):
self._repo.git.submodule('update', '--init', '--recursive')
def submodule_update(self, init=True):
self._repo.git.submodule('update', *(['--init'] if init else []), '--recursive')
def clear_cache(self):
self._repo.git.clear_cache()
@@ -440,6 +520,17 @@ class _GitPythonRepo(GitRepo):
# Pygit2 wrapper
# ===================================================================
def _remote_callbacks():
"""The callbacks of a clone or a fetch, without the one for the progress messages of the server.
pygit2 decodes each piece of such a message as UTF-8 before it calls that one, and a piece can end
in the middle of a character: the clone or the fetch then ended with UnicodeDecodeError.
"""
callbacks = _pygit2.RemoteCallbacks()
callbacks.sideband_progress = None
return callbacks
class _Pygit2Repo(GitRepo):
def __init__(self, path):
repo_path = os.path.abspath(path)
@@ -467,12 +558,12 @@ class _Pygit2Repo(GitRepo):
anon.fetch(
list(refspecs) if refspecs is not None
else list(remote.fetch_refspecs),
proxy=_HTTP_PROXY,
proxy=_HTTP_PROXY, callbacks=_remote_callbacks(),
)
elif refspecs is not None:
remote.fetch(list(refspecs), proxy=_HTTP_PROXY)
remote.fetch(list(refspecs), proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
else:
remote.fetch(proxy=_HTTP_PROXY)
remote.fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
@property
def working_dir(self):
@@ -732,7 +823,11 @@ class _Pygit2Repo(GitRepo):
def stash(self):
sig = _pygit2.Signature('comfyui-manager', 'manager@comfy')
self._repo.stash(sig)
try:
self._repo.stash(sig)
except KeyError:
# nothing to stash, which is no error for git: a submodule that is at another commit makes the repository dirty
pass
def pull_ff_only(self):
branch_name = self.active_branch_name
@@ -841,28 +936,96 @@ class _Pygit2Repo(GitRepo):
self._repo.checkout(branch)
self._repo.set_head(branch.name)
def submodule_update(self):
@staticmethod
def _check_out_from(git_dir, path):
# set before the repository is opened: pygit2 does not open one whose `core.worktree` names a folder that is not there
_pygit2.Config(os.path.join(git_dir, 'config'))['core.worktree'] = os.path.relpath(path, git_dir).replace(os.sep, '/')
repo = _pygit2.Repository(git_dir)
with open(os.path.join(path, '.git'), 'w', encoding='utf-8') as f:
f.write('gitdir: ' + os.path.relpath(git_dir, path).replace(os.sep, '/') + '\n')
if not repo.head_is_unborn:
repo.reset(repo.head.target, _pygit2.GIT_RESET_HARD)
@staticmethod
def _is_left_without_a_checkout(git_dir):
if not os.path.exists(os.path.join(git_dir, 'HEAD')):
return False
# git keeps the repository of a submodule under its name, which can be the path of another one
config = _pygit2.Config(os.path.join(git_dir, 'config'))
return 'core.worktree' not in config or not os.path.exists(os.path.join(git_dir, config['core.worktree'], '.git'))
@staticmethod
def _fetchable_submodules(repo):
# pygit2 lists the submodules by path, and one that is looked up by its path has no url when its name is another
names = {}
gitmodules = os.path.join(repo.workdir, '.gitmodules')
if os.path.exists(gitmodules):
names = {entry.value: entry.name[len('submodule.'):-len('.path')] for entry in _pygit2.Config(gitmodules)
if entry.name.startswith('submodule.') and entry.name.endswith('.path')}
top = os.path.normcase(os.path.realpath(repo.workdir))
named = [repo.submodules.get(names[path]) for path in repo.listall_submodules()
if path in names and os.path.normcase(os.path.realpath(os.path.join(top, path))).startswith(top + os.sep)]
return [submodule.name for submodule in named
if submodule is not None and submodule.head_id is not None and submodule.url is not None]
def _update_submodules(self, repo, init):
def checkout_of(name):
return os.path.join(repo.workdir, repo.submodules[name].path)
fetchable = self._fetchable_submodules(repo)
if init:
for name in fetchable:
# pygit2 does not clone into a folder that is not there
os.makedirs(checkout_of(name), exist_ok=True)
# a repository in `.git/modules` without a checkout: pygit2 refuses to clone into it
leftover = os.path.join(repo.path, 'modules', repo.submodules[name].path)
if not os.path.exists(os.path.join(checkout_of(name), '.git')) and self._is_left_without_a_checkout(leftover):
self._check_out_from(leftover, checkout_of(name))
checked_out = [name for name in fetchable if os.path.exists(os.path.join(checkout_of(name), '.git'))]
names = fetchable if init else checked_out
if init and names:
repo.submodules.init(names)
for name in names:
url = repo.config[f'submodule.{name}.url']
if _to_https_url(url) != url:
repo.config[f'submodule.{name}.url'] = _to_https_url(url)
if _HTTP_PROXY is not None:
# `update` cannot be given the proxy: what it would fetch is fetched here, and it is left the checkout
for name in names:
submodule = repo.submodules[name]
if name not in checked_out:
# the url that `init` resolved: the one of `.gitmodules` may be relative
_pygit2.clone_repository(repo.config[f'submodule.{name}.url'], os.path.join(repo.workdir, submodule.path),
proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
else:
cloned = submodule.open()
if submodule.head_id not in cloned:
cloned.remotes['origin'].fetch(proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
if names:
repo.submodules.update(names, callbacks=_remote_callbacks())
for name in names:
self._update_submodules(repo.submodules[name].open(), init)
def submodule_update(self, init=True):
try:
self._repo.submodules.init()
self._repo.submodules.update()
except Exception:
import subprocess
self._update_submodules(self._repo, init)
except Exception as e:
try:
result = subprocess.run(
['git', 'submodule', 'update', '--init', '--recursive'],
['git', 'submodule', 'update', *(['--init'] if init else []), '--recursive'],
cwd=self._working_dir,
capture_output=True, timeout=120,
)
if result.returncode != 0:
raise GitCommandError(
f"submodule update failed (exit {result.returncode}): "
f"{result.stderr.decode(errors='replace')}")
except FileNotFoundError:
print("[ComfyUI-Manager] pygit2: submodule update requires system git (not installed)", file=sys.stderr)
except GitCommandError:
raise
except Exception as sub_e:
print(f"[ComfyUI-Manager] pygit2: submodule update failed: {sub_e}", file=sys.stderr)
raise GitCommandError(f"submodule update failed: {e}") from e
if result.returncode != 0:
raise GitCommandError(
f"submodule update failed (exit {result.returncode}): "
f"{result.stderr.decode(errors='replace')}")
def clear_cache(self):
pass
@@ -918,9 +1081,9 @@ def clone_repo(url, dest, progress=None):
# configured so proxy-less installs keep working on older pygit2.
# (A configured proxy still needs >=1.18 — see requirements.txt.)
if _HTTP_PROXY is not None:
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY)
_pygit2.clone_repository(_to_https_url(url), dest, proxy=_HTTP_PROXY, callbacks=_remote_callbacks())
else:
_pygit2.clone_repository(_to_https_url(url), dest)
_pygit2.clone_repository(_to_https_url(url), dest, callbacks=_remote_callbacks())
repo = _Pygit2Repo(dest)
repo.submodule_update()
return repo
@@ -934,7 +1097,15 @@ def clone_repo(url, dest, progress=None):
def setup_git_environment(git_exe):
"""Configure the git executable path (GitPython only)."""
if USE_PYGIT2:
if USE_PYGIT2 or not git_exe:
return
if git_exe:
_git.Git().update_environment(GIT_PYTHON_GIT_EXECUTABLE=git_exe)
if git_exe == _GIT_EXE:
found = _GIT_EXE_FOUND
else:
found = find_git_executable(git_exe)
if found is None:
print(f"[ComfyUI-Manager] `git_exe = {git_exe}` is not a working git executable. The default git is used.", file=sys.stderr)
if found is not None and _git.Git.GIT_PYTHON_GIT_EXECUTABLE != found:
_git.refresh(found)
+9 -11
View File
@@ -6,7 +6,7 @@ import traceback
# Make git_compat importable as a standalone subprocess script
sys.path.insert(0, os.path.dirname(__file__))
from git_compat import open_repo, clone_repo, GitCommandError, setup_git_environment
from git_compat import open_repo, clone_repo, GitCommandError
import json
import yaml
import requests
@@ -18,7 +18,6 @@ except ImportError:
comfy_path = os.environ.get('COMFYUI_PATH')
git_exe_path = os.environ.get('GIT_EXE_PATH')
if comfy_path is None:
print("git_helper: environment variable 'COMFYUI_PATH' is not specified.")
@@ -267,6 +266,7 @@ def gitpull(path):
print("CUSTOM NODE PULL: None") # there is no update
return
tip_before_pull = repo.head_commit_hexsha
try:
repo.pull_ff_only()
except GitCommandError:
@@ -276,7 +276,12 @@ def gitpull(path):
repo.reset_hard(f'{remote_name}/{branch_name}')
print(f"[ComfyUI-Manager] Reset to {remote_name}/{branch_name}")
repo.submodule_update()
try:
repo.submodule_update()
except Exception:
repo.undo_pull(tip_before_pull)
raise
new_commit_hash = repo.head_commit_hexsha
if commit_hash != new_commit_hash:
@@ -286,6 +291,7 @@ def gitpull(path):
except Exception as e:
print(e)
print("CUSTOM NODE PULL: Fail") # unknown git error
sys.exit(1)
def checkout_comfyui_hash(target_hash):
@@ -537,14 +543,6 @@ def restore_pip_snapshot(pips, options):
print(f"Installation failed for pip packages: {failed}")
def setup_environment():
if git_exe_path is not None:
setup_git_environment(git_exe_path)
setup_environment()
try:
if sys.argv[1] == "--clone":
repo_path = None
+104 -18
View File
@@ -1,5 +1,6 @@
import os
import configparser
import logging
GITHUB_ENDPOINT = os.getenv('GITHUB_ENDPOINT')
@@ -12,25 +13,110 @@ def is_git_repo(path: str) -> bool:
return os.path.exists(os.path.join(path, '.git'))
def get_commit_hash(fullpath):
git_head = os.path.join(fullpath, '.git', 'HEAD')
if os.path.exists(git_head):
with open(git_head) as f:
line = f.readline()
def file_name_of_git_for_windows(name):
"""The name that Git for Windows gives the file of a ref, whose name is `name` in bytes.
if line.startswith("ref: "):
ref = os.path.join(fullpath, '.git', line[5:].strip())
if os.path.exists(ref):
with open(ref) as f2:
return f2.readline().strip()
else:
return "unknown"
else:
return line
A name that is not UTF-8 is no name of a file there: a byte that is not of a character becomes
the character of its number, or below 0xa0 its two hex digits, as in `xutftowcsn` of compat/mingw.c of git."""
file_name = ''
at = 0
while at < len(name):
size = 1 if name[at] < 0xc2 else 2 if name[at] < 0xe0 else 3 if name[at] < 0xf0 else 4
try:
file_name += name[at:at + size].decode('utf-8', 'surrogatepass')
at += size
except UnicodeDecodeError:
file_name += chr(name[at]) if name[at] >= 0xa0 else '%02x' % name[at]
at += 1
return file_name
def get_commit_hash(fullpath):
git_dir = os.path.join(fullpath, '.git')
try:
with open(os.path.join(git_dir, 'HEAD'), 'rb') as f:
line = f.readline().strip()
if not line.startswith(b"ref:"):
return line.decode('ascii', errors='replace')
ref_name = line[4:].strip()
# put together as git does it, and not with `os.path.join`, for which a name can lead elsewhere
if os.name == 'nt':
ref = git_dir + '/' + file_name_of_git_for_windows(ref_name)
else:
ref = os.fsencode(git_dir) + b'/' + ref_name
# a folder there is no ref, as for git: a branch `feature/x` beside the unborn branch `feature`
if os.path.isfile(ref):
with open(ref, 'rb') as f:
return f.readline().strip().decode('ascii', errors='replace')
# after `git pack-refs` or `git gc` the ref is a line of packed-refs
with open(os.path.join(git_dir, 'packed-refs'), 'rb') as f:
for packed in f:
fields = packed.split()
if len(fields) == 2 and fields[1] == ref_name:
return fields[0].decode('ascii', errors='replace')
except OSError:
pass
return "unknown"
warned_git_configs = set()
def lines_of_git_config(lines):
"""
the lines as git takes them: a `\\` at the end of a line makes the next line more of the same value,
and a line may be indented by any amount
"""
whole, quoted = '', False
for line in lines:
line = line.rstrip('\n')
goes_on = False
i = 0
while i < len(line):
if line[i] == '\\':
goes_on = i == len(line) - 1
i += 1
elif line[i] == '"':
quoted = not quoted
elif line[i] in '#;' and not quoted:
break
i += 1
if goes_on:
whole += line[:-1]
else:
yield (whole + line).lstrip() + '\n'
whole, quoted = '', False
if whole:
yield whole.lstrip() + '\n'
def read_git_config(git_config_path) -> 'configparser.ConfigParser | None':
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
# a url may hold a `%`, git accepts a key without a value, the file may start with a BOM,
# and a value that is not UTF-8 does not make the others unreadable
config = configparser.ConfigParser(strict=False, interpolation=None, allow_no_value=True)
try:
with open(git_config_path, encoding='utf-8-sig', errors='replace') as f:
# the parser would take a line that is indented more as more of the value before it
config.read_file(lines_of_git_config(f))
except (configparser.Error, OSError) as e:
if git_config_path not in warned_git_configs:
warned_git_configs.add(git_config_path)
# the message of a parsing error holds lines of the file, and a url in them can hold a token
reason = e.strerror if isinstance(e, OSError) else type(e).__name__
logging.warning(f"[ComfyUI-Manager] Cannot read '{git_config_path}': {reason}")
return None
return config
def git_url(fullpath):
"""
resolve version of unclassified custom node based on remote url in .git/config
@@ -40,12 +126,12 @@ def git_url(fullpath):
if not os.path.exists(git_config_path):
return None
# Set `strict=False` to allow duplicate `vscode-merge-base` sections, addressing <https://github.com/ltdrdata/ComfyUI-Manager/issues/1529>
config = configparser.ConfigParser(strict=False)
config.read(git_config_path)
config = read_git_config(git_config_path)
if config is None:
return None
for k, v in config.items():
if k.startswith('remote ') and 'url' in v:
if k.startswith('remote ') and v.get('url'):
if 'Comfy-Org/ComfyUI-Manager' in v['url']:
return "https://github.com/ltdrdata/ComfyUI-Manager"
return v['url']
+19 -6
View File
@@ -76,21 +76,28 @@ def aria2_find_task(dir: str, filename: str):
def aria2_download_url(model_url: str, model_dir: str, filename: str):
import manager_core as core
try:
from comfyui_manager.common import context
except ImportError:
import manager_core as context
import tqdm
import time
if model_dir.startswith(core.comfy_path):
model_dir = model_dir[len(core.comfy_path) :]
local_path = os.path.join(model_dir, filename)
if model_dir.startswith(context.comfy_path):
model_dir = model_dir[len(context.comfy_path) :]
download_dir = model_dir if model_dir.startswith('/') else os.path.join('/models', model_dir)
download = aria2_find_task(download_dir, filename)
if download is None:
if download is not None and download.is_complete and os.path.exists(local_path):
return
if download is None or not (download.is_active or download.is_waiting):
options = {'dir': download_dir, 'out': filename}
download = aria2.add(model_url, options)[0]
if download.is_active:
if download.is_active or download.is_waiting:
with tqdm.tqdm(
total=download.total_length,
bar_format='{l_bar}{bar}{r_bar}',
@@ -98,13 +105,19 @@ def aria2_download_url(model_url: str, model_dir: str, filename: str):
unit='B',
unit_scale=True,
) as progress_bar:
while download.is_active:
while download.is_active or download.is_waiting:
if progress_bar.total == 0 and download.total_length != 0:
progress_bar.reset(download.total_length)
progress_bar.update(download.completed_length - progress_bar.n)
time.sleep(1)
download.update()
if download.has_failed:
raise Exception(f"aria2 failed to download '{model_url}' into '{download_dir}': {download.error_message}")
if not os.path.exists(local_path):
raise Exception(f"aria2 saved '{filename}' into its '{download_dir}', but the file is not at '{local_path}'. "
"aria2 must see the ComfyUI folder as '/' (see docs/en/use_aria2.md).")
def download_url_with_agent(url, save_path):
try:
+107 -50
View File
@@ -1,23 +1,13 @@
"""Security helpers for CSRF protection and Content-Type gating.
reject_simple_form_post() is applied ONLY to POST handlers that do not consume
a request body (e.g., snapshot/save, queue/reset, queue/start, reboot). These
are vulnerable to cross-origin <form method=POST> attacks because the server
accepts the request without parsing any body — the attacker needs no ability
to forge a valid payload, only to point a hidden form at the URL.
Handlers that DO read a body via ``await request.json()`` (install/git_url,
install/pip, queue/install_model, db_mode POST, policy/update POST,
channel_url_list POST, queue/batch, queue/task, import_fail_info, etc.) are
NOT gated here — a cross-origin <form method=POST> cannot forge a valid JSON
body because the browser refuses to send ``application/json`` without a CORS
preflight, which this server rejects by not responding with an appropriate
Access-Control-Allow-Origin.
DO NOT add the gate to body-reading handlers (redundant + UX-breaking).
DO NOT remove the gate from no-body handlers (this is the bypass vector).
reject_non_json_post() is applied to every POST handler that changes something.
A page of another origin can make a browser send a POST without a CORS
preflight: as a form, or with no Content-Type at all, with or without a body.
``request.json()`` parses a body whatever its Content-Type. The page cannot
send ``application/json`` without a preflight.
"""
import logging
import os
from enum import Enum
from typing import Optional
@@ -27,45 +17,33 @@ from aiohttp import web
is_personal_cloud_mode = False
handler_policy = {}
FLAGGED_NODEPACK_WHITELIST_FILE = 'nodepack-whitelist.list'
# CORS "simple request" Content-Type set per Fetch spec §3.2.3. Browsers send
# <form method=POST> submissions with one of these three MIME types and do NOT
# trigger a CORS preflight, so a malicious cross-origin page can silently POST
# into state-changing endpoints if we only gate on HTTP method. Blocking these
# three Content-Types on our mutation endpoints forces any non-same-origin POST
# to use a non-simple Content-Type (e.g. application/json), which triggers a
# preflight that this server rejects (no Access-Control-Allow-Origin response).
_SIMPLE_FORM_CONTENT_TYPES = frozenset({
'application/x-www-form-urlencoded',
'multipart/form-data',
'text/plain',
})
FLAGGED_NODEPACK_INSTALL_ERROR = (
'This action is not allowed by the current security configuration. '
'See the terminal for details.'
)
FLAGGED_NODEPACK_INSTALL_GUIDANCE = (
'Installation of this flagged CNR version is blocked. To satisfy the additional '
'flagged-version requirement, choose one of the following:\n'
'1. Run ComfyUI with loopback-only listeners, for example --listen 127.0.0.1 '
'or --listen ::1. All configured listen addresses must be loopback.\n'
' Do not use bare --listen or any non-loopback address, such as 0.0.0.0 or ::.\n'
'2. For a trusted private network, set allow_flagged_nodepack_install = true '
'in the [default] section of ComfyUI-Manager\'s config.ini.\n'
'3. To allow specific packs, add their Registry pack IDs (case-insensitive), one per line, '
f'to {FLAGGED_NODEPACK_WHITELIST_FILE} beside ComfyUI-Manager\'s config.ini. '
'Whitelist changes apply to subsequent installations without a restart.\n'
'Restart ComfyUI after changing the listener or config.ini. '
'All other installation security checks still apply.'
)
def reject_simple_form_post(request) -> Optional[web.Response]:
"""Reject Content-Types that enable preflight-less <form method=POST> CSRF.
These 3 MIME types are the complete CORS "simple request" Content-Type set
(Fetch spec §3.2.3 "CORS-safelisted request-header"). Blocking them
eliminates the <form method=POST> cross-origin CSRF vector, because any
other Content-Type triggers a browser-enforced CORS preflight — and this
server does not answer preflights with ``Access-Control-Allow-Origin``,
effectively blocking cross-origin requests that use non-simple types.
Returns:
web.Response(status=400) when the request has a simple-form
Content-Type that must be rejected. None when the request is allowed
to proceed (no body, application/json, or any non-simple Content-Type).
Note:
aiohttp's ``request.content_type`` normalizes the header (lower-cases,
strips parameters), so a ``multipart/form-data; boundary=----X`` header
is compared as ``multipart/form-data``.
"""
if request.content_type in _SIMPLE_FORM_CONTENT_TYPES:
def reject_non_json_post(request) -> Optional[web.Response]:
if request.content_type != 'application/json':
return web.Response(
status=400,
text='Invalid Content-Type for this endpoint. Use application/json or omit body.',
text='Invalid Content-Type for this endpoint. Use application/json.',
)
return None
@@ -83,6 +61,85 @@ def is_loopback(address):
return False
def is_loopback_listener(listen_address: Optional[str]) -> bool:
"""All addresses bound by --listen must resolve exclusively to loopback."""
import socket
if not isinstance(listen_address, str) or not listen_address:
return False
for address in listen_address.split(','):
address = address.strip()
if not address:
return False
if is_loopback(address):
continue
try:
resolved = socket.getaddrinfo(address, None, type=socket.SOCK_STREAM)
except OSError:
return False
if not resolved or any(not is_loopback(item[4][0]) for item in resolved):
return False
return True
def ensure_nodepack_whitelist(manager_files_path):
"""Create a commented template without replacing an existing whitelist."""
path = os.path.join(manager_files_path, FLAGGED_NODEPACK_WHITELIST_FILE)
try:
os.makedirs(manager_files_path, exist_ok=True)
with open(path, 'x', encoding='utf-8') as file:
file.write(
'# Allow selected flagged CNR nodepacks on non-local listeners.\n'
'# One Registry ID per line; IDs are case-insensitive and apply to all versions.\n'
'# Blank lines and # comments are ignored. Changes apply without restarting.\n'
'# Other installation security checks still apply.\n'
'#\n'
'# Example entries (commented out; uncomment to allow):\n'
'# comfyui-impact-pack\n'
'# comfyui-inspire-pack # Optional inline comment\n'
)
except OSError as exc:
if isinstance(exc, FileExistsError) and os.path.isfile(path):
return
logging.warning('[ComfyUI-Manager] Cannot create nodepack whitelist %s: %s', path, exc)
def is_flagged_nodepack_whitelisted(node_id: str, manager_files_path) -> bool:
"""Match a whole Registry ID, ignoring case, in the current Manager whitelist."""
if not manager_files_path:
return False
path = os.path.join(manager_files_path, FLAGGED_NODEPACK_WHITELIST_FILE)
try:
with open(path, encoding='utf-8-sig') as file:
contents = file.read()
if '\x00' in contents:
raise UnicodeError('NUL characters found; save the file as UTF-8')
entries = (line.split('#', 1)[0].strip() for line in contents.split('\n'))
if node_id.lower() in {entry.lower() for entry in entries if entry}:
logging.warning('[ComfyUI-Manager] CNR installation of %r permitted by nodepack whitelist (%s).', node_id, path)
return True
return False
except FileNotFoundError:
return False
except (OSError, UnicodeError) as exc:
logging.warning('[ComfyUI-Manager] Cannot read flagged nodepack whitelist %s: %s', path, exc)
return False
def is_cnr_install_allowed(
status: str, allow_flagged: bool, listen_address: Optional[str], *,
node_id: Optional[str] = None, manager_files_path=None,
) -> bool:
"""Flagged versions require loopback, explicit permission, or a whitelisted ID.
Restore children pass their parent's resolved permission and no listener.
"""
return (status != 'NodeVersionStatusFlagged'
or bool(allow_flagged)
or is_loopback_listener(listen_address)
or (node_id is not None and is_flagged_nodepack_whitelisted(node_id, manager_files_path)))
def is_dedicated_install_allowed(flag_value: bool, listen_address: str, network_mode: str) -> bool:
"""P-direct predicate for the dedicated install flags (goal265-spec.md §1.2).
File diff suppressed because it is too large Load Diff
+30 -4
View File
@@ -6,6 +6,27 @@ import os
from .git_utils import get_commit_hash
IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
def is_link(path: str) -> bool:
"""
A junction is told by the reparse tag that os.lstat reads on every Python; os.path.isjunction is new in 3.12.
"""
try:
return os.path.islink(path) or getattr(os.lstat(path), 'st_reparse_tag', 0) == IO_REPARSE_TAG_MOUNT_POINT
except OSError:
return False
@dataclass(frozen=True)
class InvalidInstallation:
fullpath: str
unknown_key: str
project_name: str | None
enabled: bool
@dataclass
class InstalledNodePackage:
"""Information about an installed node package."""
@@ -38,11 +59,16 @@ class InstalledNodePackage:
def get_commit_hash(self) -> str:
return get_commit_hash(self.fullpath)
def isValid(self) -> bool:
if self.is_from_cnr:
return os.path.exists(os.path.join(self.fullpath, '.tracking'))
def is_exempt_from_installation_check(self) -> bool:
name = os.path.basename(self.fullpath)
return ('comfyui-manager' in self.id.lower() or is_link(self.fullpath)
or name.startswith('.') or name in ('__MACOSX', '__pycache__'))
return True
def isValid(self) -> bool:
if self.is_exempt_from_installation_check():
return True
return os.path.exists(os.path.join(self.fullpath, '.git')) or os.path.exists(os.path.join(self.fullpath, '.tracking'))
@staticmethod
def from_fullpath(fullpath: str, resolve_from_path) -> InstalledNodePackage:
@@ -0,0 +1,7 @@
"""Installation-denial messages shared by the glob and legacy servers."""
SECURITY_MESSAGE_MIDDLE = "ERROR: To use this action, a security_level of `normal or below` is required. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_MIDDLE_P = "ERROR: To use this action, security_level must be `normal or below`, and network_mode must be set to `personal_cloud`. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_HIGH_P = "ERROR: To use this action, '--listen' must be set to a local IP and security_level must be 'normal-' or lower. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/Comfy-Org/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
+6 -3
View File
@@ -72,8 +72,9 @@ def get_backup_branch_name(repo=None) -> str:
Format: backup_YYYYMMDD_HHMMSS (or backup_YYYYMMDD_HHMMSS_N if exists)
Args:
repo: Optional git.Repo object. If provided, checks for name collisions
and adds sequential suffix if needed.
repo: Optional repository: a git_compat repository (glob core) or
GitPython's git.Repo (legacy core). If provided, checks for name
collisions and adds sequential suffix if needed.
Returns:
Unique backup branch name.
@@ -85,7 +86,9 @@ def get_backup_branch_name(repo=None) -> str:
# Check if branch exists
try:
existing_branches = {b.name for b in repo.list_heads()}
# a git_compat repository lists its branches with list_heads(); git.Repo has heads
heads = repo.list_heads() if hasattr(repo, 'list_heads') else repo.heads
existing_branches = {b.name for b in heads}
except Exception:
return base_name
+30 -37
View File
@@ -122,10 +122,6 @@ _INLINE_DANGEROUS_OPTIONS = re.compile(
# Credential redaction in index URLs.
_CREDENTIAL_PATTERN = re.compile(r'://([^@]+)@')
# Version-spec parsing (same regex as existing ``is_blacklisted()``).
_VERSION_SPEC_PATTERN = re.compile(r'([^<>!~=]+)([<>!~=]=?)([^ ]*)')
def collect_node_pack_paths(custom_nodes_dirs: list[str]) -> list[str]:
"""Collect all installed node-pack directory paths.
@@ -209,11 +205,12 @@ class UnifiedDepResolver:
) -> None:
self.node_pack_paths = node_pack_paths
self.base_requirements = base_requirements or []
self.blacklist: set[str] = blacklist if blacklist is not None else set()
# Requirement names are compared in normalised form, so the lists are too.
self.blacklist: set[str] = {manager_util.normalize_pip_name(x) for x in blacklist or ()}
self.overrides: dict[str, str] = overrides if overrides is not None else {}
self.downgrade_blacklist: list[str] = (
downgrade_blacklist if downgrade_blacklist is not None else []
)
self.downgrade_blacklist: list[str] = [
manager_util.normalize_pip_name(x) for x in downgrade_blacklist or ()
]
# ------------------------------------------------------------------
# Public API
@@ -610,43 +607,34 @@ class UnifiedDepResolver:
@staticmethod
def _extract_package_name(spec: str) -> str:
"""Extract normalised package name from a requirement spec."""
name = re.split(r'[><=!~;\[@ ]', spec)[0].strip()
return name.lower().replace('-', '_')
"""Extract normalised package name from a requirement spec.
The name is read by ``manager_util.parse_pip_spec()``, as in ``is_blacklisted()``.
A line that names no package is compared as a whole.
"""
name = manager_util.parse_pip_spec(spec)[0]
return name if name is not None else manager_util.normalize_pip_name(spec)
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str,
installed: dict) -> bool:
"""Reproduce the downgrade logic from ``is_blacklisted()``.
"""Apply the downgrade rule shared with ``is_blacklisted()``.
Uses ``manager_util.StrictVersion`` — **not** ``packaging.version``.
Parsing and the decision come from ``manager_util.parse_pip_spec()`` and
``manager_util.downgrade_protection()``, so both paths give the same result.
Args:
installed: Pre-fetched snapshot from
``manager_util.get_installed_packages()``.
"""
if pkg_name not in self.downgrade_blacklist:
if pkg_name not in self.downgrade_blacklist or pkg_name not in installed:
return False
match = _VERSION_SPEC_PATTERN.search(pkg_spec)
if match is None:
# No version spec: prevent reinstall if already installed
if pkg_name in installed:
return True
elif match.group(2) in ('<=', '==', '<', '~='):
if pkg_name in installed:
try:
installed_ver = manager_util.StrictVersion(installed[pkg_name])
requested_ver = manager_util.StrictVersion(match.group(3))
if installed_ver >= requested_ver:
return True
except (ValueError, TypeError):
logger.warning(
"[UnifiedDepResolver] version parse failed: %s", pkg_spec,
)
return False
return False
_, extras, clauses = manager_util.parse_pip_spec(pkg_spec)
blocked, error = manager_util.downgrade_protection(
pkg_spec, clauses, extras, installed[pkg_name])
if error is not None:
logger.error("[UnifiedDepResolver] %s", error)
return blocked
# ------------------------------------------------------------------
# Helpers — parsing & output
@@ -656,10 +644,15 @@ class UnifiedDepResolver:
def _parse_conflicts(stderr: str) -> list[str]:
"""Extract conflict descriptions from ``uv pip compile`` stderr."""
conflicts: list[str] = []
for line in stderr.splitlines():
line = line.strip()
if line and ('conflict' in line.lower() or 'error' in line.lower()):
in_diagnostic = False
for raw_line in stderr.splitlines():
line = raw_line.strip()
if line and ('conflict' in line.lower() or 'error' in line.lower()
or (in_diagnostic and raw_line[0].isspace())):
conflicts.append(line)
in_diagnostic = True
else:
in_diagnostic = False
return conflicts or [stderr.strip()] if stderr.strip() else []
@staticmethod
@@ -13,6 +13,7 @@ from pydantic import BaseModel, Field, RootModel
class OperationType(str, Enum):
install = "install"
reinstall = "reinstall"
uninstall = "uninstall"
update = "update"
update_comfyui = "update-comfyui"
@@ -64,6 +65,10 @@ class ManagerPackInstalled(BaseModel):
description="The name of the pack if installed from github (author/repo-name format)",
)
enabled: bool = Field(..., description="Whether the pack is enabled")
invalid_installation: Optional[bool] = Field(
None,
description='True when the folder has neither .git nor .tracking, so the Manager can neither update it nor tell its version; absent or null otherwise. Its ver is then "unknown" and its cnr_id is the registry id of its pack when the registry list has it, otherwise [project].name of its pyproject.toml in lower case (also while the registry list is still loading), otherwise "". A reinstall task fixes it.',
)
class SelectedVersion(str, Enum):
@@ -224,8 +229,12 @@ class UpdateComfyUIQueryParams(BaseModel):
)
ui_id: str = Field(..., description="UI identifier for task tracking")
stable: Optional[bool] = Field(
True,
description="Whether to update to stable version (true) or nightly (false)",
None,
description="Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.",
)
is_stable: Optional[bool] = Field(
None,
description="Another name for `stable`, the one the task parameters use. Read when `stable` is not given.",
)
-9
View File
@@ -1,12 +1,3 @@
SECURITY_MESSAGE_MIDDLE = "ERROR: To use this action, a security_level of `normal or below` is required. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_MIDDLE_P = "ERROR: To use this action, security_level must be `normal or below`, and network_mode must be set to `personal_cloud`. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_HIGH_P = "ERROR: To use this action, '--listen' must be set to a local IP and security_level must be 'normal-' or lower. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS = "ERROR: To use this feature, you must either set '--listen' to a local IP and set the security level to 'normal-' or lower, or set the security level to 'middle' or 'weak'. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_GENERAL = "ERROR: This installation is not allowed in this security_level. Please contact the administrator.\nReference: https://github.com/ltdrdata/ComfyUI-Manager#security-policy"
SECURITY_MESSAGE_NORMAL_MINUS_MODEL = "ERROR: Downloading models that are not in '.safetensors' format is only allowed for models registered in the 'default' channel at this security level. If you want to download this model, set the security level to 'normal-' or lower."
def is_loopback(address):
import ipaddress
File diff suppressed because it is too large Load Diff
+131 -67
View File
@@ -44,7 +44,7 @@ from comfyui_manager.glob.utils import (
from server import PromptServer
from . import manager_core as core
from ..common import manager_util
from ..common import manager_util, manager_security
from ..common import cm_global
from ..common import manager_downloader
from ..common import context
@@ -83,11 +83,14 @@ from ..data_models import (
ComfyUISwitchVersionParams,
)
from .constants import (
model_dir_name_map,
from ..common.security_messages import (
SECURITY_MESSAGE_MIDDLE,
SECURITY_MESSAGE_MIDDLE_P,
SECURITY_MESSAGE_HIGH_P,
SECURITY_MESSAGE_NORMAL_MINUS_MODEL,
)
from .constants import (
model_dir_name_map,
)
if not manager_util.is_manager_pip_package():
@@ -131,6 +134,11 @@ def error_response(
class ManagerFuncsInComfyUI(core.ManagerFuncs):
def is_flagged_install_allowed(self, node_id):
return manager_security.is_cnr_install_allowed(
'NodeVersionStatusFlagged', core.get_config()['allow_flagged_nodepack_install'], args.listen,
node_id=node_id, manager_files_path=context.manager_files_path)
def run_script(self, cmd, cwd="."):
if len(cmd) > 0 and cmd[0].startswith("#"):
logging.error(f"[ComfyUI-Manager] Unexpected behavior: `{cmd}`")
@@ -342,6 +350,7 @@ class TaskQueue:
# Force cache refresh for successful pack-modifying operations
pack_modifying_tasks = {
OperationType.install.value,
OperationType.reinstall.value,
OperationType.uninstall.value,
OperationType.enable.value,
OperationType.disable.value,
@@ -808,15 +817,16 @@ class TaskQueue:
task_queue = TaskQueue()
def replaces_cnr_with_nightly(node_id):
unified = core.unified_manager
return unified.is_enabled(node_id, 'cnr') and unified.resolve_unspecified_version(node_id, guess_mode='inactive') == 'nightly'
async def task_worker():
logging.debug("[ComfyUI-Manager] Task worker started")
await core.unified_manager.reload(ManagerDatabaseSource.cache.value)
async def do_install(params: InstallPackParams) -> str:
if not security_utils.is_allowed_security_level('middle+'):
logging.error(SECURITY_MESSAGE_MIDDLE_P)
return OperationResult.failed.value
async def do_install(params: InstallPackParams, operation: str) -> str:
node_id = params.id
node_version = params.selected_version
channel = params.channel
@@ -842,13 +852,23 @@ async def task_worker():
return f"Cannot resolve install target: '{node_id}@{node_version}'"
node_name, version_spec, is_specified = node_spec
res = await core.unified_manager.install_by_id(
node_name,
version_spec,
channel,
mode,
return_postinstall=skip_post_install,
) # discard post install if skip_post_install mode
# CNR versions have their own flagged-status check before download.
level = 'middle+' if version_spec in ('nightly', 'unknown') else 'middle'
if not security_utils.is_allowed_security_level(level):
logging.error(SECURITY_MESSAGE_MIDDLE_P if level == 'middle+' else SECURITY_MESSAGE_MIDDLE)
return OperationResult.failed.value
if operation == OperationType.reinstall.value:
res = await core.unified_manager.reinstall_by_id(
node_name, version_spec, channel, mode
)
else:
res = await core.unified_manager.install_by_id(
node_name,
version_spec,
channel,
mode,
return_postinstall=skip_post_install,
)
if res.action not in [
"skip",
@@ -872,8 +892,15 @@ async def task_worker():
async def do_enable(params: EnablePackParams) -> str:
cnr_id = params.cnr_id
logging.debug("[ComfyUI-Manager] Enabling node: cnr_id=%s", cnr_id)
core.unified_manager.unified_enable(cnr_id)
return OperationResult.success.value
if replaces_cnr_with_nightly(cnr_id) and not security_utils.is_allowed_security_level('middle+'):
logging.error(SECURITY_MESSAGE_MIDDLE_P)
return OperationResult.failed.value
res = core.unified_manager.unified_enable(cnr_id)
if res.result:
return OperationResult.success.value
logging.error(f"[ComfyUI-Manager] Failed to enable '{cnr_id}': {res.msg}")
return f"Failed to enable: '{cnr_id}'"
async def do_update(params: UpdatePackParams) -> dict[str, str]:
node_name = params.node_name
@@ -892,7 +919,7 @@ async def task_worker():
# the remote URL. Downstream branches at L901/904 already
# handle url is None, so we just need a None-safe title.
# Harmonized with legacy/manager_server.py equivalent (WI #252).
url = core.unified_manager.unknown_active_nodes[node_name][0]
url = core.unified_manager.unknown_active_nodes.get(node_name, (None,))[0]
title = os.path.basename(url) if url else node_name
else:
url = core.unified_manager.cnr_map[node_name].get("repository")
@@ -913,9 +940,9 @@ async def task_worker():
base_res["msg"] = OperationResult.success.value
return base_res
base_res["msg"] = f"An error occurred while updating '{node_name}'."
base_res["msg"] = res.msg or f"An error occurred while updating '{node_name}'."
logging.error(
f"\nERROR: An error occurred while updating '{node_name}'. (res.result={res.result}, res.action={res.action})"
f"\nERROR: An error occurred while updating '{node_name}': {res.msg} (res.result={res.result}, res.action={res.action})"
)
return base_res
except Exception:
@@ -929,6 +956,10 @@ async def task_worker():
# Check if this is a version switch operation
if params.target_version:
if core.is_comfyui_downgrade(params.target_version) and not security_utils.is_allowed_security_level('high+'):
logging.error(SECURITY_MESSAGE_HIGH_P)
return OperationResult.failed.value
# Switch to specific version
logging.info(f"Switching ComfyUI to version: {params.target_version}")
core.switch_comfyui(params.target_version)
@@ -1037,9 +1068,10 @@ async def task_worker():
try:
res = core.unified_manager.unified_disable(node_name, is_unknown)
if res:
if res.result:
return OperationResult.success.value
logging.error(f"[ComfyUI-Manager] Failed to disable '{node_name}': {res.msg}")
except Exception:
traceback.print_exc()
@@ -1052,6 +1084,18 @@ async def task_worker():
json_data = params.model_dump()
# Checked here, not in a route: queue/install_model and queue/task both end up here.
if not await model_utils.check_whitelist_for_model(json_data):
logging.error(f"[ComfyUI-Manager] Invalid model install request is detected: {json_data}")
return "Invalid model install request is detected"
if not json_data["filename"].endswith(".safetensors") and not security_utils.is_allowed_security_level("high+"):
models_json = await core.get_data_by_mode(ManagerDatabaseSource.cache.value, "model-list.json", "default")
if not any(x.get("url") == json_data["url"] for x in models_json.get("models", [])):
logging.error(SECURITY_MESSAGE_NORMAL_MINUS_MODEL)
return "A security error has occurred. Please check the terminal logs"
model_path = model_utils.get_model_path(json_data)
model_url = json_data.get("url")
@@ -1154,8 +1198,8 @@ async def task_worker():
)
try:
if kind == OperationType.install.value:
msg = await do_install(item.params)
if kind in (OperationType.install.value, OperationType.reinstall.value):
msg = await do_install(item.params, kind)
elif kind == OperationType.enable.value:
msg = await do_enable(item.params)
elif kind == OperationType.install_model.value:
@@ -1235,6 +1279,10 @@ async def queue_task(request) -> web.Response:
Returns:
web.Response: HTTP 200 on successful queueing, HTTP 400 on validation error
"""
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
json_data = await request.json()
# Validate input using Pydantic model
@@ -1430,7 +1478,7 @@ async def fetch_updates(request):
@routes.post("/v2/manager/queue/update_all")
async def update_all(request: web.Request) -> web.Response:
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
@@ -1490,6 +1538,9 @@ async def _update_all(params: UpdateAllQueryParams) -> web.Response:
if os.environ.get("__COMFYUI_DESKTOP_VERSION__"):
continue
if v[1] in core.unified_manager.invalid_installations:
continue
update_task = QueueTaskItem(
kind=OperationType.update.value,
ui_id=f"{base_ui_id}_{k}", # Use client's base ui_id + node name
@@ -1543,7 +1594,7 @@ async def get_snapshot_list(request):
@routes.post("/v2/snapshot/remove")
async def remove_snapshot(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("middle"):
@@ -1568,11 +1619,11 @@ async def remove_snapshot(request):
@routes.post("/v2/snapshot/restore")
async def restore_snapshot(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("middle+"):
logging.error(SECURITY_MESSAGE_MIDDLE_P)
if not security_utils.is_allowed_security_level("high+"):
logging.error(SECURITY_MESSAGE_HIGH_P)
return web.Response(status=403)
try:
@@ -1613,7 +1664,7 @@ async def get_current_snapshot_api(request):
@routes.post("/v2/snapshot/save")
async def save_snapshot(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
@@ -1654,6 +1705,10 @@ def unzip_install(files):
@routes.post("/v2/customnode/import_fail_info")
async def import_fail_info(request):
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
json_data = await request.json()
@@ -1688,6 +1743,10 @@ async def import_fail_info(request):
@routes.post("/v2/customnode/import_fail_info_bulk")
async def import_fail_info_bulk(request):
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
json_data = await request.json()
@@ -1749,7 +1808,7 @@ async def import_fail_info_bulk(request):
@routes.post("/v2/manager/queue/reset")
async def reset_queue(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
logging.debug("[ComfyUI-Manager] Queue reset requested")
@@ -1812,7 +1871,7 @@ async def queue_count(request):
@routes.post("/v2/manager/queue/start")
async def queue_start(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
logging.debug("[ComfyUI-Manager] Queue start requested")
@@ -1829,7 +1888,7 @@ async def queue_start(request):
@routes.post("/v2/manager/queue/update_comfyui")
async def update_comfyui(request):
"""Queue a ComfyUI update based on the configured update policy."""
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
@@ -1839,10 +1898,12 @@ async def update_comfyui(request):
)
# Check if stable parameter was provided, otherwise use config
if query_params.stable is None:
is_stable = core.get_config()["update_policy"] != "nightly-comfyui"
else:
if query_params.stable is not None:
is_stable = query_params.stable
elif query_params.is_stable is not None:
is_stable = query_params.is_stable
else:
is_stable = core.get_config()["update_policy"] not in ("nightly", "nightly-comfyui")
client_id = query_params.client_id
ui_id = query_params.ui_id
@@ -1880,10 +1941,10 @@ async def comfyui_versions(request):
@routes.post("/v2/comfyui_manager/comfyui_switch_version")
async def comfyui_switch_version(request):
# Body-reading handler — Content-Type gate omitted per
# comfyui_manager/common/manager_security.py module policy: a cross-origin
# <form method=POST> cannot forge a valid application/json body because
# the browser would trigger a CORS preflight that this server refuses.
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("high+"):
logging.error(SECURITY_MESSAGE_HIGH_P)
return web.Response(status=403)
@@ -1922,6 +1983,10 @@ async def comfyui_switch_version(request):
@routes.post("/v2/manager/queue/install_model")
async def install_model(request):
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
json_data = await request.json()
@@ -1959,11 +2024,12 @@ async def db_mode(request):
@routes.post("/v2/manager/db_mode")
async def set_db_mode_api(request):
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
# Config writes are at the same risk tier as uninstall/update — apply the
# 'middle' gate consistent with snapshot/remove, etc. Content-Type gate is
# NOT applied here: this handler consumes application/json and a
# cross-origin <form method=POST> cannot forge that without triggering
# CORS preflight (see module docstring in common/manager_security.py).
# 'middle' gate consistent with snapshot/remove, etc.
if not security_utils.is_allowed_security_level("middle"):
logging.error(SECURITY_MESSAGE_MIDDLE)
return web.Response(status=403)
@@ -1972,7 +2038,7 @@ async def set_db_mode_api(request):
environment_utils.set_db_mode(data["value"])
core.write_config()
return web.Response(status=200)
except (json.JSONDecodeError, KeyError):
except (json.JSONDecodeError, KeyError, TypeError):
return web.Response(status=400, text="Invalid request")
except ValueError as e:
return web.Response(status=400, text=str(e))
@@ -1985,7 +2051,10 @@ async def update_policy(request):
@routes.post("/v2/manager/policy/update")
async def set_update_policy_api(request):
# See set_db_mode_api above for gate rationale.
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("middle"):
logging.error(SECURITY_MESSAGE_MIDDLE)
return web.Response(status=403)
@@ -1994,7 +2063,7 @@ async def set_update_policy_api(request):
environment_utils.set_update_policy(data["value"])
core.write_config()
return web.Response(status=200)
except (json.JSONDecodeError, KeyError):
except (json.JSONDecodeError, KeyError, TypeError):
return web.Response(status=400, text="Invalid request")
except ValueError as e:
return web.Response(status=400, text=str(e))
@@ -2017,7 +2086,10 @@ async def channel_url_list(request):
@routes.post("/v2/manager/channel_url_list")
async def set_channel_url(request):
# See set_db_mode_api above for gate rationale.
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("middle"):
logging.error(SECURITY_MESSAGE_MIDDLE)
return web.Response(status=403)
@@ -2042,7 +2114,7 @@ async def set_channel_url(request):
@routes.post("/v2/manager/reboot")
def restart(request):
rejection = security_utils.reject_simple_form_post(request)
rejection = security_utils.reject_non_json_post(request)
if rejection is not None:
return rejection
if not security_utils.is_allowed_security_level("middle"):
@@ -2067,17 +2139,9 @@ def restart(request):
"\nRestarting... [Legacy Mode]\n\n"
) # This printing should not be logging - that will be ugly
sys_argv = sys.argv.copy()
if "--windows-standalone-build" in sys_argv:
sys_argv.remove("--windows-standalone-build")
if sys_argv[0].endswith("__main__.py"): # this is a python module
module_name = os.path.basename(os.path.dirname(sys_argv[0]))
cmds = [sys.executable, "-m", module_name] + sys_argv[1:]
elif sys.platform.startswith("win32"):
cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
else:
cmds = [sys.executable] + sys_argv
cmds = manager_util.build_restart_command(
sys.argv, drop_args=("--windows-standalone-build",)
)
print(f"Command: {cmds}", flush=True)
@@ -2130,10 +2194,8 @@ async def default_cache_update():
json_obj = await manager_util.get_data(uri, True)
with manager_util.cache_lock:
with open(cache_uri, "w", encoding="utf-8") as file:
json.dump(json_obj, file, indent=4, sort_keys=True)
logging.debug(f"[ComfyUI-Manager] default cache updated: {uri}")
if manager_util.write_cache_file(cache_uri, json_obj):
logging.debug(f"[ComfyUI-Manager] default cache updated: {uri}")
except Exception as e:
logging.error(
f"[ComfyUI-Manager] Failed to perform initial fetching '{filename}': {e}"
@@ -2144,15 +2206,17 @@ async def default_cache_update():
a = get_cache("custom-node-list.json")
b = get_cache("extension-node-map.json")
c = get_cache("model-list.json")
d = get_cache("alter-list.json")
e = get_cache("github-stats.json")
d = get_cache("github-stats.json")
await asyncio.gather(a, b, c, d, e)
await asyncio.gather(a, b, c, d)
if core.get_config()["network_mode"] == "private":
logging.info(
"[ComfyUI-Manager] The private comfyregistry is not yet supported in `network_mode=private`."
)
await core.unified_manager.reload(
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
)
else:
# load at least once
await core.unified_manager.reload(
@@ -2166,6 +2230,7 @@ async def default_cache_update():
ManagerDatabaseSource.remote.value, dont_wait=False, update_cnr_map=False
)
core.check_invalid_nodes()
logging.info("[ComfyUI-Manager] All startup tasks have been completed.")
@@ -2174,4 +2239,3 @@ threading.Thread(target=lambda: asyncio.run(default_cache_update())).start()
if not os.path.exists(context.manager_config_path):
core.get_config()
core.write_config()
+54 -244
View File
@@ -1,12 +1,11 @@
import mimetypes
from ..common import context
from ..common import manager_security
from . import manager_core as core
import os
from aiohttp import web
import aiohttp
import json
import hashlib
import folder_paths
from server import PromptServer
@@ -22,69 +21,33 @@ except Exception:
matrix_nio_is_available = False
def extract_model_file_names(json_data):
"""Extract unique file names from the input JSON data."""
file_names = set()
model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
# Recursively search for file names in the JSON data
def recursive_search(data):
if isinstance(data, dict):
for value in data.values():
recursive_search(value)
elif isinstance(data, list):
for item in data:
recursive_search(item)
elif isinstance(data, str) and '.' in data:
file_names.add(os.path.basename(data)) # file_names.add(data)
recursive_search(json_data)
return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
def find_file_paths(base_dir, file_names):
"""Find the paths of the files in the base directory."""
file_paths = {}
for root, dirs, files in os.walk(base_dir):
# Exclude certain directories
dirs[:] = [d for d in dirs if d not in ['.git']]
for file in files:
if file in file_names:
file_paths[file] = os.path.join(root, file)
return file_paths
def compute_sha256_checksum(filepath):
"""Compute the SHA256 checksum of a file, in chunks"""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
@PromptServer.instance.routes.get("/v2/manager/share_option")
async def share_option(request):
if "value" in request.rel_url.query:
core.get_config()['share_option'] = request.rel_url.query['value']
core.write_config()
else:
return web.Response(text=core.get_config()['share_option'], status=200)
return web.Response(text=core.get_config()['share_option'], status=200)
@PromptServer.instance.routes.post("/v2/manager/share_option")
async def set_share_option(request):
rejection = manager_security.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
value = (await request.json())['value']
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
if value not in SHARE_OPTIONS:
return web.Response(status=400, text='Invalid request')
core.get_config()['share_option'] = value
core.write_config()
return web.Response(status=200)
def get_openart_auth():
if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
return None
try:
with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
openart_key = f.read().strip()
return openart_key if openart_key else None
except Exception:
return None
def is_matrix_org(homeserver):
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
def get_matrix_auth():
@@ -94,7 +57,7 @@ def get_matrix_auth():
with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
matrix_auth = f.read()
homeserver, username, password = matrix_auth.strip().split("\n")
if not homeserver or not username or not password:
if not is_matrix_org(homeserver) or not username or not password:
return None
return {
"homeserver": homeserver,
@@ -105,101 +68,12 @@ def get_matrix_auth():
return None
def get_comfyworkflows_auth():
if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
return None
try:
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
share_key = f.read()
if not share_key.strip():
return None
return share_key
except Exception:
return None
def get_youml_settings():
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
return None
try:
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
youml_settings = f.read().strip()
return youml_settings if youml_settings else None
except Exception:
return None
def set_youml_settings(settings):
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
f.write(settings)
@PromptServer.instance.routes.get("/v2/manager/get_openart_auth")
async def api_get_openart_auth(request):
# print("Getting stored Matrix credentials...")
openart_key = get_openart_auth()
if not openart_key:
return web.Response(status=404)
return web.json_response({"openart_key": openart_key})
@PromptServer.instance.routes.post("/v2/manager/set_openart_auth")
async def api_set_openart_auth(request):
json_data = await request.json()
openart_key = json_data['openart_key']
with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
f.write(openart_key)
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_matrix_auth")
async def api_get_matrix_auth(request):
# print("Getting stored Matrix credentials...")
matrix_auth = get_matrix_auth()
if not matrix_auth:
return web.Response(status=404)
return web.json_response(matrix_auth)
@PromptServer.instance.routes.get("/v2/manager/youml/settings")
async def api_get_youml_settings(request):
youml_settings = get_youml_settings()
if not youml_settings:
return web.Response(status=404)
return web.json_response(json.loads(youml_settings))
@PromptServer.instance.routes.post("/v2/manager/youml/settings")
async def api_set_youml_settings(request):
json_data = await request.json()
set_youml_settings(json.dumps(json_data))
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_comfyworkflows_auth")
async def api_get_comfyworkflows_auth(request):
# Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
# in the same directory as the ComfyUI base folder
# print("Getting stored Comfyworkflows.com auth...")
comfyworkflows_auth = get_comfyworkflows_auth()
if not comfyworkflows_auth:
return web.Response(status=404)
return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
async def set_esheep_workflow_and_images(request):
json_data = await request.json()
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
json.dump(json_data, file, indent=4)
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
async def get_esheep_workflow_and_images(request):
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
data = json.load(file)
return web.Response(status=200, text=json.dumps(data))
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
@@ -211,42 +85,42 @@ async def get_matrix_dep_status(request):
def set_matrix_auth(json_data):
homeserver = json_data['homeserver']
username = json_data['username']
password = json_data['password']
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
f.write("\n".join([homeserver, username, password]))
def set_comfyworkflows_auth(comfyworkflows_sharekey):
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
f.write(comfyworkflows_sharekey)
path = os.path.join(context.manager_files_path, "matrix_auth")
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
try:
os.chmod(path, 0o600)
except OSError:
pass # a file of another owner keeps its mode
f.truncate()
f.write("\n".join(["matrix.org", username, password]))
def has_provided_matrix_auth(matrix_auth):
return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
return comfyworkflows_sharekey.strip()
@PromptServer.instance.routes.post("/v2/manager/share")
async def share_art(request):
# get json data
rejection = manager_security.reject_non_json_post(request)
if rejection is not None:
return rejection
json_data = await request.json()
matrix_auth = json_data['matrix_auth']
comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
set_matrix_auth(matrix_auth)
set_comfyworkflows_auth(comfyworkflows_sharekey)
saved = get_matrix_auth()
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
matrix_auth['password'] = saved['password']
share_destinations = json_data['share_destinations']
credits = json_data['credits']
title = json_data['title']
description = json_data['description']
is_nsfw = json_data['is_nsfw']
prompt = json_data['prompt']
potential_outputs = json_data['potential_outputs']
selected_output_index = json_data['selected_output_index']
@@ -275,79 +149,20 @@ async def share_art(request):
else:
asset_filepath = os.path.join(output_dir, asset_filename)
# The filename and the subfolder come from the request: share only a file in that directory.
# Like ComfyUI's /view, this follows a symlink that the user placed in the directory.
output_dir = os.path.abspath(output_dir)
asset_filepath = os.path.abspath(asset_filepath)
try:
is_inside = os.path.commonpath((output_dir, asset_filepath)) == output_dir
except ValueError: # on Windows, a path on another drive
is_inside = False
if not is_inside:
return web.json_response({"error": "The selected output is not in the output directory."}, content_type='application/json', status=400)
# get the mime type of the asset
assetFileType = mimetypes.guess_type(asset_filepath)[0]
share_website_host = "UNKNOWN"
if "comfyworkflows" in share_destinations:
share_website_host = "https://comfyworkflows.com"
share_endpoint = f"{share_website_host}/api"
# get presigned urls
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.post(
f"{share_endpoint}/get_presigned_urls",
json={
"assetFileName": asset_filename,
"assetFileType": assetFileType,
"workflowJsonFileName": 'workflow.json',
"workflowJsonFileType": 'application/json',
},
) as resp:
assert resp.status == 200
presigned_urls_json = await resp.json()
assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
assetFileKey = presigned_urls_json["assetFileKey"]
workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
# upload asset
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
assert resp.status == 200
# upload workflow json
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
assert resp.status == 200
model_filenames = extract_model_file_names(prompt['workflow'])
model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
models_info = {}
for filename, filepath in model_file_paths.items():
models_info[filename] = {
"filename": filename,
"sha256_checksum": compute_sha256_checksum(filepath),
"relative_path": os.path.relpath(filepath, folder_paths.base_path),
}
# make a POST request to /api/upload_workflow with form data key values
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
form = aiohttp.FormData()
if comfyworkflows_sharekey:
form.add_field("shareKey", comfyworkflows_sharekey)
form.add_field("source", "comfyui_manager")
form.add_field("assetFileKey", assetFileKey)
form.add_field("assetFileType", assetFileType)
form.add_field("workflowJsonFileKey", workflowJsonFileKey)
form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
form.add_field("shareWorkflowCredits", credits)
form.add_field("shareWorkflowTitle", title)
form.add_field("shareWorkflowDescription", description)
form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
form.add_field("modelsInfo", json.dumps(models_info))
async with session.post(
f"{share_endpoint}/upload_workflow",
data=form,
) as resp:
assert resp.status == 200
upload_workflow_json = await resp.json()
workflowId = upload_workflow_json["workflowId"]
# check if the user has provided Matrix credentials
if matrix_nio_is_available and "matrix" in share_destinations:
comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
@@ -355,14 +170,10 @@ async def share_art(request):
content_type = assetFileType
try:
homeserver = 'matrix.org'
if matrix_auth:
homeserver = matrix_auth.get('homeserver', 'matrix.org')
homeserver = homeserver.replace("http://", "https://")
if not homeserver.startswith("https://"):
homeserver = "https://" + homeserver
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
client = AsyncClient(homeserver, matrix_auth['username'])
client = AsyncClient("https://matrix.org", matrix_auth['username'])
# Login
login_resp = await client.login(matrix_auth['password'])
@@ -370,6 +181,8 @@ async def share_art(request):
await client.close()
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
set_matrix_auth(matrix_auth)
# Upload asset
with open(asset_filepath, 'rb') as f:
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
@@ -442,9 +255,6 @@ async def share_art(request):
return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
return web.json_response({
"comfyworkflows": {
"url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
},
"matrix": {
"success": None if "matrix" not in share_destinations else True
}
@@ -124,7 +124,6 @@ def initialize_environment():
# Legacy database paths - kept for potential future use
# local_db_model = os.path.join(manager_util.comfyui_manager_path, "model-list.json")
# local_db_alter = os.path.join(manager_util.comfyui_manager_path, "alter-list.json")
# local_db_custom_node_list = os.path.join(
# manager_util.comfyui_manager_path, "custom-node-list.json"
# )
@@ -134,5 +133,3 @@ def initialize_environment():
print_comfyui_version()
setup_environment()
core.check_invalid_nodes()
@@ -1,6 +1,5 @@
import locale
import sys
import re
def handle_stream(stream, prefix):
@@ -20,41 +19,3 @@ def handle_stream(stream, prefix):
print(prefix, msg, end="", file=sys.stderr)
else:
print(prefix, msg, end="")
def convert_markdown_to_html(input_text):
pattern_a = re.compile(r"\[a/([^]]+)]\(([^)]+)\)")
pattern_w = re.compile(r"\[w/([^]]+)]")
pattern_i = re.compile(r"\[i/([^]]+)]")
pattern_bold = re.compile(r"\*\*([^*]+)\*\*")
pattern_white = re.compile(r"%%([^*]+)%%")
def replace_a(match):
return f"<a href='{match.group(2)}' target='blank'>{match.group(1)}</a>"
def replace_w(match):
return f"<p class='cm-warn-note'>{match.group(1)}</p>"
def replace_i(match):
return f"<p class='cm-info-note'>{match.group(1)}</p>"
def replace_bold(match):
return f"<B>{match.group(1)}</B>"
def replace_white(match):
return f"<font color='white'>{match.group(1)}</font>"
input_text = (
input_text.replace("\\[", "&#91;")
.replace("\\]", "&#93;")
.replace("<", "&lt;")
.replace(">", "&gt;")
)
result_text = re.sub(pattern_a, replace_a, input_text)
result_text = re.sub(pattern_w, replace_w, result_text)
result_text = re.sub(pattern_i, replace_i, result_text)
result_text = re.sub(pattern_bold, replace_bold, result_text)
result_text = re.sub(pattern_white, replace_white, result_text)
return result_text.replace("\n", "<BR>")
+5 -1
View File
@@ -127,8 +127,10 @@ def check_model_installed(json_obj):
fullpath = os.path.join(
folder_paths.models_dir, item["save_path"], filename
)
subpath = os.path.join(item["save_path"].partition("/")[2], filename)
found = os.path.exists(fullpath) or folder_paths.get_full_path(model_dir_name, subpath)
item["installed"] = "True" if os.path.exists(fullpath) else "False"
item["installed"] = "True" if found else "False"
with concurrent.futures.ThreadPoolExecutor(8) as executor:
for item in json_obj["models"]:
@@ -145,6 +147,7 @@ async def check_whitelist_for_model(item):
x["save_path"] == item["save_path"]
and x["base"] == item["base"]
and x["filename"] == item["filename"]
and x.get("url") == item.get("url")
):
return True
@@ -155,6 +158,7 @@ async def check_whitelist_for_model(item):
x["save_path"] == item["save_path"]
and x["base"] == item["base"]
and x["filename"] == item["filename"]
and x.get("url") == item.get("url")
):
return True
+3 -3
View File
@@ -5,7 +5,7 @@ from comfyui_manager.common.manager_security import (
is_loopback,
is_safe_path_target,
get_safe_file_path,
reject_simple_form_post,
reject_non_json_post,
)
# Re-export for backward compatibility
@@ -13,7 +13,7 @@ __all__ = [
'is_loopback',
'is_safe_path_target',
'get_safe_file_path',
'reject_simple_form_post',
'reject_non_json_post',
'is_allowed_security_level',
'get_risky_level',
]
@@ -53,7 +53,7 @@ async def get_risky_level(files, pip_packages):
json_data2 = await core.get_data_by_mode(
ManagerDatabaseSource.cache.value,
"custom-node-list.json",
channel_url="https://raw.githubusercontent.com/ltdrdata/ComfyUI-Manager/main",
channel_url=core.DEFAULT_CHANNEL,
)
all_urls = set()
-2
View File
@@ -13,8 +13,6 @@ This directory contains the JavaScript frontend implementation for ComfyUI-Manag
## Sharing Components
- **comfyui-share-common.js**: Base functionality for workflow sharing features.
- **comfyui-share-copus.js**: Integration with the ComfyUI Copus sharing platform.
- **comfyui-share-openart.js**: Integration with the OpenArt sharing platform.
- **comfyui-share-youml.js**: Integration with the YouML sharing platform.
## Utility Components
+122 -35
View File
@@ -1,59 +1,146 @@
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { sleep, customConfirm, customAlert } from "./common.js";
import { sleep, customConfirm, customAlert, show_message, sanitizeHTML, generateUUID, md5 } from "./common.js";
// Enable a disabled node pack as the Enable button of the Custom Nodes Manager does: find the pack
// in the node list, put it in the queue, and wait until the queue has finished it.
// Returns { failure }, the reason, when the pack was not enabled, and otherwise { busy }: whether
// the queue still holds other work.
async function enableNodePack(target) {
const list = await api.fetchApi(`/v2/customnode/getlist?mode=cache&skip_update=true`);
if(list.status != 200) {
return { failure: `Failed to get the custom node list (${list.status}).` };
}
const { channel, node_packs } = await list.json();
const key = Object.keys(node_packs).find((k) => {
const pack = node_packs[k];
return pack.state == 'disabled' && pack.files?.some((url) => target.files.includes(url));
});
if(key == undefined) {
return { failure: 'It is not in the custom node list as a disabled node pack. Please enable it in the Custom Nodes Manager.' };
}
// Behind other work the pack would be enabled at some later time, after the wait below has ended.
const status = await api.fetchApi('/v2/manager/queue/status');
if((await status.json()).is_processing) {
return { failure: 'There are already tasks in progress. Please try again after it is completed.' };
}
const batch_id = generateUUID();
const ui_id = md5(key); // the id of this pack's row in the Custom Nodes Manager
// Once the batch is in the queue, 'all-done' without its report ends the wait: something else,
// such as another tab, has emptied the queue.
let listener, queued = false;
const result = new Promise((resolve) => {
listener = (event) => {
const report = event.detail;
if(report.status == 'batch-done' && report.batch_id == batch_id) {
resolve(report);
}
else if(report.status == 'all-done' && queued) {
resolve({ nodepack_result: {} });
}
};
});
// The queue may report the batch before the request below is answered.
api.addEventListener("cm-queue-status", listener);
try {
const response = await api.fetchApi(`/v2/manager/queue/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
batch_id,
install: [{
...node_packs[key],
channel,
mode: 'cache',
ui_id,
skip_post_install: true
}]
})
});
if(response.status != 200) {
return { failure: `The request was refused (${response.status}). Please check the terminal log.` };
}
const { failed } = await response.json();
if(failed.length > 0) {
return { failure: 'The request was refused. Please check the terminal log.' };
}
// A report that does not reach the page would leave the listener in place, and the batch,
// run at some later time, would then restart ComfyUI unasked.
queued = true;
const report = await Promise.race([result, sleep(60000)]);
if(report == undefined) {
return { failure: 'The queue did not report the result. Please check the node pack in the Custom Nodes Manager.' };
}
const message = report.nodepack_result[ui_id] ?? 'The queue finished without a result for this node pack. Please check the node pack in the Custom Nodes Manager.';
if(message != 'success') {
return { failure: String(message) };
}
return { busy: report.remaining_batch_count > 1 }; // the count includes this batch
}
finally {
api.removeEventListener("cm-queue-status", listener);
}
}
async function tryInstallCustomNode(event) {
let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
msg += `The '${event.detail.sender}' extension requires the installation of the '${event.detail.target.title}' extension. `;
const target = event.detail.target;
if(event.detail.target.installed == 'Disabled') {
let msg = '-= [ComfyUI Manager] extension installation request =-\n\n';
msg += `The '${event.detail.sender}' extension requires the installation of the '${target.title}' extension. `;
if(target.installed == 'Disabled') {
msg += 'However, the extension is currently disabled. Would you like to enable it and reboot?'
}
else if(event.detail.target.installed == 'True') {
msg += 'However, it seems that the extension is in an import-fail state or is not compatible with the current version. Please address this issue.';
}
else {
msg += `Would you like to install it and reboot?`;
msg += 'However, it seems that the extension is in an import-fail state or is not compatible with the current version. Please address this issue.';
}
msg += `\n\nRequest message:\n${event.detail.msg}`;
if(event.detail.target.installed == 'True') {
// The server sends this request only for a node pack that is installed: it is disabled, or it failed to load.
if(target.installed != 'Disabled') {
customAlert(msg);
return;
}
const res = await customConfirm(msg);
if(res) {
if(event.detail.target.installed == 'Disabled') {
const response = await api.fetchApi(`/v2/customnode/toggle_active`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.detail.target)
});
}
else {
await sleep(300);
app.ui.dialog.show(`Installing... '${event.detail.target.title}'`);
const title = sanitizeHTML(String(target.title));
const response = await api.fetchApi(`/v2/customnode/install`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event.detail.target)
});
await sleep(300);
app.ui.dialog.show(`Enabling... '${title}'`);
if(response.status == 403) {
show_message('This action is not allowed with this security level configuration.');
return false;
}
else if(response.status == 400) {
let msg = await res.text();
show_message(msg);
return false;
}
const { failure, busy } = await enableNodePack(target).catch((exception) => ({ failure: String(exception) }));
if(failure != undefined) {
show_message(`Failed to enable '${title}'.<BR><BR>${sanitizeHTML(failure)}`);
return false;
}
let response = await api.fetchApi("/v2/manager/reboot", { method: 'POST' });
if(response.status == 403) {
// A restart would cut off the work that was queued behind the pack.
if(busy) {
show_message(`'${title}' is enabled.<BR><BR>Other tasks are still in progress. Please restart ComfyUI after they are completed.`);
return false;
}
let response;
try {
response = await api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
catch(exception) {
// The server restarts without answering.
}
if(response?.status == 403) {
show_message('This action is not allowed with this security level configuration.');
return false;
}
@@ -0,0 +1,82 @@
.cm-ui-overlay {
z-index: 1000;
background: rgb(0 0 0 / 50%);
}
.cm-ui-dialog {
max-width: calc(100vw - 2rem);
max-height: calc(100vh - 2rem);
border: 1px solid var(--border, var(--border-color));
border-radius: 12px;
background: var(--background, var(--comfy-menu-bg));
color: var(--foreground, var(--fg-color));
box-shadow: var(--shadow-lg, 0 8px 24px rgb(0 0 0 / 30%));
}
.cm-ui-header {
flex-shrink: 0;
padding: 1rem;
}
.cm-ui-content {
padding: 0 1rem 1rem;
overflow: auto;
}
.cm-ui-muted {
color: var(--muted-foreground, var(--fg-color));
}
:where(.cm-ui-button) {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--border, var(--border-color));
border-radius: 6px;
background: var(--secondary, var(--comfy-input-bg));
color: var(--foreground, var(--input-text));
font: inherit;
line-height: 1.25;
cursor: pointer;
}
:where(.cm-ui-input) {
padding: 0.5rem;
border: 1px solid var(--border, var(--border-color));
border-radius: 6px;
background: var(--secondary, var(--comfy-input-bg));
color: var(--foreground, var(--input-text));
font: inherit;
}
.cm-ui-button:not(:disabled):hover {
filter: brightness(115%);
}
.cm-ui-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cm-ui-button:focus-visible,
.cm-ui-input:focus-visible {
outline: 2px solid var(--ring, var(--input-text));
outline-offset: 2px;
}
.cm-ui-close {
width: 2rem;
height: 2rem;
flex-shrink: 0;
padding: 0;
border: 0;
border-radius: 50%;
background: transparent;
color: inherit;
}
.cm-ui-close:not(:disabled):hover {
background: var(--accent, var(--comfy-input-bg));
}
+19 -98
View File
@@ -1,4 +1,7 @@
import { $el } from "../../scripts/ui.js";
import { loadCss } from "./common.js";
loadCss("./comfyui-gui-builder.css");
function normalizeContent(content) {
const tmp = document.createElement('div');
@@ -16,7 +19,7 @@ export function createSettingsCombo(label, content) {
const settingItem = $el("div.setting-item", {}, [
$el("div.flex.flex-row.items-center.gap-2",[
$el("div.form-label.flex.grow.items-center", [
$el("span.text-muted", { textContent: label },)
$el("span.cm-ui-muted", { textContent: label },)
]),
$el("div.form-input.flex.justify-end",
[content]
@@ -28,51 +31,27 @@ export function createSettingsCombo(label, content) {
}
export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
parent: document.body,
style: {
position: "fixed",
height: "100%",
width: "100%",
left: "0px",
top: "0px",
display: "flex",
justifyContent: "center",
alignItems: "center",
pointerEvents: "auto",
zIndex: "1000"
},
onclick: (e) => {
if (e.target === dialog_mask) {
owner.close();
}
}
// data-pc-section="mask"
});
const header_actions = $el("div.p-dialog-header-actions", {
// [TODO]
// data-pc-section="headeractions"
}
);
const header_actions = $el("div.flex.items-center");
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
$el("button.cm-ui-button.cm-ui-close", {
parent: header_actions,
type: "button",
ariaLabel: "Close",
onclick: () => owner.close(),
// "data-pc-name": "pcclosebutton",
// "data-p-disabled": "false",
// "data-p-severity": "secondary",
// "data-pc-group-section": "headericon",
// "data-pc-extend": "button",
// "data-pc-section": "root",
// [FIXME] Not sure how to do most of the SVG using $el
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label">&nbsp;</span><!---->'
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
}
);
const dialog_header = $el("div.p-dialog-header",
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
[
$el("div", [
$el("div",
@@ -96,8 +75,8 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
]
);
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
id: dialogId,
parent: dialog_mask,
style: {
@@ -108,76 +87,35 @@ export function buildGuiFrame(dialogId, title, iconClass, content, owner) {
},
role: 'dialog',
ariaModal: 'true',
// [TODO]
// ariaLabbelledby: 'cm-title',
// maximized: 'false',
// data-pc-name: 'dialog',
// data-pc-section: 'root',
// data-pd-focustrap: 'true'
},
[ dialog_header, contentFrame ]
);
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
parent: manager_dialog,
tabindex: "0",
role: "presentation",
ariaHidden: "true",
"data-p-hidden-accessible": "true",
"data-p-hidden-focusable": "true",
"data-pc-section": "firstfocusableelement"
});
return dialog_mask;
}
export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner) {
const dialog_mask = $el("div.p-dialog-mask.p-overlay-mask.p-overlay-mask-enter", {
const dialog_mask = $el("div.cm-ui-overlay.fixed.inset-0.flex.items-center.justify-center", {
parent: document.body,
style: {
position: "fixed",
height: "100%",
width: "100%",
left: "0px",
top: "0px",
display: "flex",
justifyContent: "center",
alignItems: "center",
pointerEvents: "auto",
zIndex: "1000"
},
onclick: (e) => {
if (e.target === dialog_mask) {
owner.close();
}
}
// data-pc-section="mask"
});
const header_actions = $el("div.p-dialog-header-actions", {
// [TODO]
// data-pc-section="headeractions"
}
);
const header_actions = $el("div.flex.items-center");
const close_button = $el("button.p-button.p-component.p-button-icon-only.p-button-secondary.p-button-rounded.p-button-text.p-dialog-close-button", {
$el("button.cm-ui-button.cm-ui-close", {
parent: header_actions,
type: "button",
ariaLabel: "Close",
onclick: () => owner.close(),
// "data-pc-name": "pcclosebutton",
// "data-p-disabled": "false",
// "data-p-severity": "secondary",
// "data-pc-group-section": "headericon",
// "data-pc-extend": "button",
// "data-pc-section": "root",
// [FIXME] Not sure how to do most of the SVG using $el
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" class="p-icon p-button-icon" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg><span class="p-button-label" data-pc-section="label">&nbsp;</span><!---->'
innerHTML: '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M8.01186 7.00933L12.27 2.75116C12.341 2.68501 12.398 2.60524 12.4375 2.51661C12.4769 2.42798 12.4982 2.3323 12.4999 2.23529C12.5016 2.13827 12.4838 2.0419 12.4474 1.95194C12.4111 1.86197 12.357 1.78024 12.2884 1.71163C12.2198 1.64302 12.138 1.58893 12.0481 1.55259C11.9581 1.51625 11.8617 1.4984 11.7647 1.50011C11.6677 1.50182 11.572 1.52306 11.4834 1.56255C11.3948 1.60204 11.315 1.65898 11.2488 1.72997L6.99067 5.98814L2.7325 1.72997C2.59553 1.60234 2.41437 1.53286 2.22718 1.53616C2.03999 1.53946 1.8614 1.61529 1.72901 1.74767C1.59663 1.88006 1.5208 2.05865 1.5175 2.24584C1.5142 2.43303 1.58368 2.61419 1.71131 2.75116L5.96948 7.00933L1.71131 11.2675C1.576 11.403 1.5 11.5866 1.5 11.7781C1.5 11.9696 1.576 12.1532 1.71131 12.2887C1.84679 12.424 2.03043 12.5 2.2219 12.5C2.41338 12.5 2.59702 12.424 2.7325 12.2887L6.99067 8.03052L11.2488 12.2887C11.3843 12.424 11.568 12.5 11.7594 12.5C11.9509 12.5 12.1346 12.424 12.27 12.2887C12.4053 12.1532 12.4813 11.9696 12.4813 11.7781C12.4813 11.5866 12.4053 11.403 12.27 11.2675L8.01186 7.00933Z" fill="currentColor"></path></svg>'
}
);
const _customHeader = normalizeContent(customHeader);
const dialog_header = $el("div.p-dialog-header",
const dialog_header = $el("div.cm-ui-header.flex.items-center.justify-between.gap-2",
[
$el("div", [
$el("div",
@@ -191,8 +129,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
]
);
const contentFrame = $el("div.p-dialog-content", {}, normalizeContent(content));
const manager_dialog = $el("div.p-dialog.p-component.global-dialog", {
const contentFrame = $el("div.cm-ui-content.min-h-0", {}, normalizeContent(content));
$el("div.cm-ui-dialog.global-dialog.flex.flex-col", {
id: dialogId,
parent: dialog_mask,
style: {
@@ -203,25 +141,8 @@ export function buildGuiFrameCustomHeader(dialogId, customHeader, content, owner
},
role: 'dialog',
ariaModal: 'true',
// [TODO]
// ariaLabbelledby: 'cm-title',
// maximized: 'false',
// data-pc-name: 'dialog',
// data-pc-section: 'root',
// data-pd-focustrap: 'true'
},
[ dialog_header, contentFrame ]
);
const hidden_accessible = $el("span.p-hidden-accessible.p-hidden-focusable", {
parent: manager_dialog,
tabindex: "0",
role: "presentation",
ariaHidden: "true",
"data-p-hidden-accessible": "true",
"data-p-hidden-focusable": "true",
"data-pc-section": "firstfocusableelement"
});
return dialog_mask;
}
}
+98 -136
View File
@@ -6,15 +6,13 @@ import {
ShareDialog,
ShareDialogChooser,
getPotentialOutputsAndOutputNodes,
showOpenArtShareDialog,
showShareDialog,
showYouMLShareDialog
} from "./comfyui-share-common.js";
import { OpenArtShareDialog } from "./comfyui-share-openart.js";
import {
free_models, install_pip, install_via_git_url, manager_instance,
rebootAPI, setManagerInstance, show_message, customAlert, customPrompt,
infoToast, showTerminal, setNeedRestart, generateUUID
infoToast, showTerminal, setNeedRestart, generateUUID, sanitizeHTML, sanitizeUrl
} from "./common.js";
import { CustomNodesManager } from "./custom-nodes-manager.js";
import { ModelManager } from "./model-manager.js";
@@ -133,17 +131,6 @@ docStyle.innerHTML = `
text-decoration: underline;
}
#alternatives-grid a {
color: #5555FF;
font-weight: bold;
text-decoration: none;
}
#alternatives-grid a:hover {
color: #7777FF;
text-decoration: underline;
}
.cm-notice-board {
width: auto;
height: 280px;
@@ -234,8 +221,28 @@ var switch_comfyui_button = null;
var update_all_button = null;
var restart_stop_button = null;
var update_policy_combo = null;
var update_policy_chosen = false;
let share_option = 'all';
const share_options = [
['none', 'None'],
['youml', 'YouML'],
['matrix', 'Matrix Server'],
['all', 'All'],
];
// The saved choice may be a share site that Manager no longer has
function to_share_option(value) {
return share_options.some(option => option[0] === value) ? value : 'all';
}
const youml_gallery_url = "https://youml.com/?from=comfyui-share";
// The gallery opened last, unless Manager no longer has it
function last_visited_gallery() {
const url = localStorage.getItem("wg_last_visited");
return url === youml_gallery_url ? url : null;
}
var batch_id = null;
@@ -410,7 +417,7 @@ async function init_share_option() {
api.fetchApi('/v2/manager/share_option')
.then(response => response.text())
.then(data => {
share_option = data || 'all';
share_option = to_share_option(data);
});
}
@@ -477,6 +484,7 @@ async function updateComfyUI() {
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
}
@@ -626,15 +634,6 @@ async function switchComfyUI() {
}
showVersionSelectorDialog(versions, obj.current, async (selected_version) => {
if(selected_version == 'nightly') {
update_policy_combo.value = 'nightly-comfyui';
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'nightly-comfyui'}) });
}
else {
update_policy_combo.value = 'stable-comfyui';
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: 'stable-comfyui'}) });
}
let response = await api.fetchApi('/v2/comfyui_manager/comfyui_switch_version', {
method: 'POST',
cache: "no-store",
@@ -646,8 +645,16 @@ async function switchComfyUI() {
}),
});
if (response.status == 200) {
const update_policy = selected_version == 'nightly' ? 'nightly-comfyui' : 'stable-comfyui';
update_policy_chosen = true;
update_policy_combo.value = update_policy;
api.fetchApi('/v2/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: update_policy}) });
infoToast(`ComfyUI version is switched to ${selected_version}`);
}
else if (response.status == 403) {
customAlert('This action is not allowed with this security level configuration.');
}
else {
customAlert('Failed to switch ComfyUI version.');
}
@@ -659,6 +666,11 @@ async function switchComfyUI() {
}
async function onQueueStatus(event) {
// The buttons exist once the Manager menu has been created; the queue can run before that.
if(update_all_button == null) {
return;
}
const isElectron = 'electronAPI' in window;
if(event.detail.status == 'in_progress') {
@@ -694,7 +706,7 @@ async function onQueueStatus(event) {
let msg = "";
if(success_list.length == 0 && comfyui_state.startsWith('skip')) {
if(success_list.length == 0 && (comfyui_state == null || comfyui_state.startsWith('skip'))) {
if(failed_list.length == 0) {
msg += "You are already up to date.";
}
@@ -706,7 +718,7 @@ async function onQueueStatus(event) {
msg += "ComfyUI has been updated to latest nightly version.<BR><BR>";
infoToast("ComfyUI has been updated to the latest nightly version.");
}
else if(comfyui_state.startsWith('success-stable')) {
else if(comfyui_state?.startsWith('success-stable')) {
const ver = comfyui_state.split("-").pop();
msg += `ComfyUI has been updated to ${ver}.<BR><BR>`;
infoToast(`ComfyUI has been updated to ${ver}`);
@@ -722,13 +734,14 @@ async function onQueueStatus(event) {
msg += "The following custom nodes have been updated:<ul>";
for(let x in success_list) {
let k = success_list[x];
let url = event.detail.nodepack_result[k].url;
let title = event.detail.nodepack_result[k].title;
// queue results are server-authored and not escaped upstream
let url = sanitizeUrl(event.detail.nodepack_result[k].url);
let title = sanitizeHTML(String(event.detail.nodepack_result[k].title ?? ''));
if(url) {
msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
msg += `<li><a href='${sanitizeHTML(url)}' target='_blank' rel='noopener noreferrer'>${title}</a></li>`;
}
else {
msg += `<li>${k}</li>`;
msg += `<li>${sanitizeHTML(String(k))}</li>`;
}
}
msg += "</ul>";
@@ -741,13 +754,13 @@ async function onQueueStatus(event) {
msg += '<br>The update for the following custom nodes has failed:<ul>';
for(let x in failed_list) {
let k = failed_list[x];
let url = event.detail.nodepack_result[k].url;
let title = event.detail.nodepack_result[k].title;
let url = sanitizeUrl(event.detail.nodepack_result[k].url);
let title = sanitizeHTML(String(event.detail.nodepack_result[k].title ?? ''));
if(url) {
msg += `<li><a href='${url}' target='_blank'>${title}</a></li>`;
msg += `<li><a href='${sanitizeHTML(url)}' target='_blank' rel='noopener noreferrer'>${title}</a></li>`;
}
else {
msg += `<li>${k}</li>`;
msg += `<li>${sanitizeHTML(String(k))}</li>`;
}
}
@@ -781,6 +794,7 @@ async function updateAll(update_comfyui) {
batch_id = generateUUID();
let batch = {};
batch['batch_id'] = batch_id;
if(update_comfyui) {
update_all_button.innerText = "Updating ComfyUI...";
batch['update_comfyui'] = true;
@@ -790,6 +804,7 @@ async function updateAll(update_comfyui) {
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
}
@@ -806,7 +821,7 @@ function restartOrStop() {
rebootAPI();
}
else {
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
}
@@ -818,7 +833,7 @@ class ManagerMenuDialog extends ComfyDialog {
const isElectron = 'electronAPI' in window;
update_comfyui_button =
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Update ComfyUI",
style: {
@@ -829,7 +844,7 @@ class ManagerMenuDialog extends ComfyDialog {
});
switch_comfyui_button =
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Switch ComfyUI",
style: {
@@ -840,7 +855,7 @@ class ManagerMenuDialog extends ComfyDialog {
});
restart_stop_button =
$el("button.p-button.p-component.cm-button-red", {
$el("button.cm-ui-button.cm-button-red", {
type: "button",
textContent: "Restart",
onclick: () => restartOrStop()
@@ -848,7 +863,7 @@ class ManagerMenuDialog extends ComfyDialog {
if(isElectron) {
update_all_button =
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Update All Custom Nodes",
onclick:
@@ -857,7 +872,7 @@ class ManagerMenuDialog extends ComfyDialog {
}
else {
update_all_button =
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Update All",
onclick:
@@ -867,7 +882,7 @@ class ManagerMenuDialog extends ComfyDialog {
const res =
[
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Custom Nodes Manager",
onclick:
@@ -879,7 +894,7 @@ class ManagerMenuDialog extends ComfyDialog {
}
}),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Install Missing Custom Nodes",
onclick:
@@ -891,7 +906,7 @@ class ManagerMenuDialog extends ComfyDialog {
}
}),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Custom Nodes In Workflow",
onclick:
@@ -904,7 +919,7 @@ class ManagerMenuDialog extends ComfyDialog {
}),
$el("div", {}, []),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Model Manager",
onclick:
@@ -916,7 +931,7 @@ class ManagerMenuDialog extends ComfyDialog {
}
}),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
type: "button",
textContent: "Install via Git URL",
onclick: async () => {
@@ -950,17 +965,20 @@ class ManagerMenuDialog extends ComfyDialog {
this.datasrc_combo = document.createElement("select");
this.datasrc_combo.setAttribute("title", "Configure where to retrieve node/model information. If set to 'local,' the channel is ignored, and if set to 'channel (remote),' it fetches the latest information each time the list is opened.");
this.datasrc_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled ";
this.datasrc_combo.className = "cm-menu-combo cm-ui-input ";
this.datasrc_combo.appendChild($el('option', { value: 'cache', text: 'Channel (1day cache)' }, []));
this.datasrc_combo.appendChild($el('option', { value: 'local', text: 'Local' }, []));
this.datasrc_combo.appendChild($el('option', { value: 'remote', text: 'Channel (remote)' }, []));
// a choice made before the stored value arrives is not to be replaced by it
let db_mode_chosen = false;
api.fetchApi('/v2/manager/db_mode')
.then(response => response.text())
.then(data => { this.datasrc_combo.value = data; });
.then(data => { if(!db_mode_chosen) this.datasrc_combo.value = data; });
this.datasrc_combo.addEventListener('change', function (event) {
api.fetchApi('/v2/manager/db_mode', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
db_mode_chosen = true;
api.fetchApi('/v2/manager/db_mode', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
});
const dbRetrievalSetttingItem = createSettingsCombo("DB", this.datasrc_combo);
@@ -968,7 +986,7 @@ class ManagerMenuDialog extends ComfyDialog {
// channel
let channel_combo = document.createElement("select");
channel_combo.setAttribute("title", "Configure the channel for retrieving data from the Custom Node list (including missing nodes) or the Model list.");
channel_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
channel_combo.className = "cm-menu-combo cm-ui-input";
api.fetchApi('/v2/manager/channel_url_list')
.then(response => response.json())
.then(async data => {
@@ -982,7 +1000,7 @@ class ManagerMenuDialog extends ComfyDialog {
}
channel_combo.addEventListener('change', function (event) {
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
api.fetchApi('/v2/manager/channel_url_list', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
});
channel_combo.value = data.selected;
@@ -998,31 +1016,26 @@ class ManagerMenuDialog extends ComfyDialog {
// share
let share_combo = document.createElement("select");
share_combo.setAttribute("title", "Hide the share button in the main menu or set the default action upon clicking it. Additionally, configure the default share site when sharing via the context menu's share button.");
share_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
const share_options = [
['none', 'None'],
['openart', 'OpenArt AI'],
['youml', 'YouML'],
['matrix', 'Matrix Server'],
['comfyworkflows', 'ComfyWorkflows'],
['copus', 'Copus'],
['all', 'All'],
];
share_combo.className = "cm-menu-combo cm-ui-input";
for (const option of share_options) {
share_combo.appendChild($el('option', { value: option[0], text: `${option[1]}` }, []));
}
let share_option_chosen = false;
api.fetchApi('/v2/manager/share_option')
.then(response => response.text())
.then(data => {
share_combo.value = data || 'all';
share_option = data || 'all';
if(!share_option_chosen) {
share_option = to_share_option(data);
share_combo.value = share_option;
}
});
share_combo.addEventListener('change', function (event) {
share_option_chosen = true;
const value = event.target.value;
share_option = value;
api.fetchApi(`/v2/manager/share_option?value=${value}`);
api.fetchApi('/v2/manager/share_option', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ value }) });
const shareButton = document.getElementById("shareButton");
if (value === 'none') {
shareButton.style.display = "none";
@@ -1036,17 +1049,19 @@ class ManagerMenuDialog extends ComfyDialog {
update_policy_combo = document.createElement("select");
update_policy_combo.setAttribute("title", "Sets the policy to be applied when performing an update.");
update_policy_combo.className = "cm-menu-combo p-select p-component p-inputwrapper p-inputwrapper-filled";
update_policy_combo.className = "cm-menu-combo cm-ui-input";
update_policy_combo.appendChild($el('option', { value: 'stable-comfyui', text: 'ComfyUI Stable Version' }, []));
update_policy_combo.appendChild($el('option', { value: 'nightly-comfyui', text: 'ComfyUI Nightly Version' }, []));
api.fetchApi('/v2/manager/policy/update')
.then(response => response.text())
.then(data => {
update_policy_combo.value = data;
if(!update_policy_chosen)
update_policy_combo.value = data;
});
update_policy_combo.addEventListener('change', function (event) {
api.fetchApi('/v2/manager/policy/update', { method: 'POST', body: JSON.stringify({value: event.target.value}) });
update_policy_chosen = true;
api.fetchApi('/v2/manager/policy/update', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({value: event.target.value}) });
});
const updateSetttingItem = createSettingsCombo("Update", update_policy_combo);
@@ -1062,7 +1077,7 @@ class ManagerMenuDialog extends ComfyDialog {
//[TODO] replace mt-2 with wrapper div with flex column gap
$el("filedset.cm-experimental.mt-auto", {}, [
$el("legend.cm-experimental-legend", {}, ["EXPERIMENTAL"]),
$el("button.p-button.p-component.cm-button.cm-experimental-button", {
$el("button.cm-ui-button.cm-button.cm-experimental-button", {
type: "button",
textContent: "Snapshot Manager",
onclick:
@@ -1072,7 +1087,7 @@ class ManagerMenuDialog extends ComfyDialog {
SnapshotManager.instance.show();
}
}),
$el("button.p-button.p-component.cm-button.cm-experimental-button.mt-2", {
$el("button.cm-ui-button.cm-button.cm-experimental-button.mt-2", {
type: "button",
textContent: "Install PIP packages",
onclick:
@@ -1090,7 +1105,7 @@ class ManagerMenuDialog extends ComfyDialog {
createControlsRight() {
const elts = [
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
id: 'cm-manual-button',
type: "button",
textContent: "Community Manual",
@@ -1141,14 +1156,14 @@ class ManagerMenuDialog extends ComfyDialog {
})
]),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
id: 'workflowgallery-button',
type: "button",
style: {
// ...(localStorage.getItem("wg_last_visited") ? {height: '50px'} : {})
},
onclick: (e) => {
const last_visited_site = localStorage.getItem("wg_last_visited")
const last_visited_site = last_visited_gallery();
if (!!last_visited_site) {
window.open(last_visited_site, last_visited_site);
} else {
@@ -1168,7 +1183,7 @@ class ManagerMenuDialog extends ComfyDialog {
}, [
$el("p", {
id: 'workflowgallery-button-last-visited-label',
textContent: `(${localStorage.getItem("wg_last_visited") ? localStorage.getItem("wg_last_visited").split('/')[2] : 'none selected'})`,
textContent: `(${last_visited_gallery()?.split('/')[2] ?? 'none selected'})`,
style: {
'text-align': 'center',
'color': 'var(--input-text)',
@@ -1179,12 +1194,12 @@ class ManagerMenuDialog extends ComfyDialog {
})
]),
$el("div.pysssss-workflow-arrow-2", {
id: `comfyworkflows-button-arrow`,
id: `workflowgallery-button-arrow`,
onclick: this.handleWorkflowGalleryButtonClick
})
]),
$el("button.p-button.p-component.cm-button", {
$el("button.cm-ui-button.cm-button", {
id: 'cm-nodeinfo-button',
type: "button",
textContent: "Nodes Info",
@@ -1258,11 +1273,8 @@ class ManagerMenuDialog extends ComfyDialog {
{
title: "Share your art",
callback: () => {
if (share_option === 'openart') {
showOpenArtShareDialog();
return;
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
showShareDialog(share_option);
if (share_option === 'matrix') {
showShareDialog();
return;
} else if (share_option === 'youml') {
showYouMLShareDialog();
@@ -1275,49 +1287,12 @@ class ManagerMenuDialog extends ComfyDialog {
ShareDialogChooser.instance.show();
},
},
{
title: "Open 'openart.ai'",
callback: () => {
const url = "https://openart.ai/workflows/dev";
localStorage.setItem("wg_last_visited", url);
window.open(url, url);
modifyButtonStyle(url);
},
},
{
title: "Open 'youml.com'",
callback: () => {
const url = "https://youml.com/?from=comfyui-share";
localStorage.setItem("wg_last_visited", url);
window.open(url, url);
modifyButtonStyle(url);
},
},
{
title: "Open 'comfyworkflows.com'",
callback: () => {
const url = "https://comfyworkflows.com/";
localStorage.setItem("wg_last_visited", url);
window.open(url, url);
modifyButtonStyle(url);
},
},
{
title: "Open 'esheep'",
callback: () => {
const url = "https://www.esheep.com";
localStorage.setItem("wg_last_visited", url);
window.open(url, url);
modifyButtonStyle(url);
},
},
{
title: "Open 'Copus.io'",
callback: () => {
const url = "https://www.copus.io";
localStorage.setItem("wg_last_visited", url);
window.open(url, url);
modifyButtonStyle(url);
localStorage.setItem("wg_last_visited", youml_gallery_url);
window.open(youml_gallery_url, youml_gallery_url);
modifyButtonStyle(youml_gallery_url);
},
},
{
@@ -1449,11 +1424,8 @@ app.registerExtension({
new(await import("../../scripts/ui/components/button.js")).ComfyButton({
icon: "share",
action: () => {
if (share_option === 'openart') {
showOpenArtShareDialog();
return;
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
showShareDialog(share_option);
if (share_option === 'matrix') {
showShareDialog();
return;
} else if (share_option === 'youml') {
showYouMLShareDialog();
@@ -1487,11 +1459,8 @@ app.registerExtension({
shareButton.id = "shareButton";
shareButton.textContent = "Share";
shareButton.onclick = () => {
if (share_option === 'openart') {
showOpenArtShareDialog();
return;
} else if (share_option === 'matrix' || share_option === 'comfyworkflows') {
showShareDialog(share_option);
if (share_option === 'matrix') {
showShareDialog();
return;
} else if (share_option === 'youml') {
showYouMLShareDialog();
@@ -1545,13 +1514,6 @@ app.registerExtension({
const shareButton = document.getElementById("shareButton");
if (shareButton) {
const currentNode = this;
if (!OpenArtShareDialog.instance) {
OpenArtShareDialog.instance = new OpenArtShareDialog();
}
OpenArtShareDialog.instance.selectedNodeId = currentNode.id;
if (!ShareDialog.instance) {
ShareDialog.instance = new ShareDialog(share_option);
}
ShareDialog.instance.selectedNodeId = currentNode.id;
shareButton.click();
}
+22 -253
View File
@@ -1,8 +1,6 @@
import { api } from "../../scripts/api.js";
import { app } from "../../scripts/app.js";
import { $el, ComfyDialog } from "../../scripts/ui.js";
import { CopusShareDialog } from "./comfyui-share-copus.js";
import { OpenArtShareDialog } from "./comfyui-share-openart.js";
import { YouMLShareDialog } from "./comfyui-share-youml.js";
import { customAlert } from "./common.js";
@@ -166,61 +164,6 @@ export function parseURLPath(urlPath) {
}
export const shareToEsheep= () => {
app.graphToPrompt()
.then(prompt => {
const nodes = app.graph._nodes
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
const workflow = prompt['workflow']
api.fetchApi(`/v2/manager/set_esheep_workflow_and_images`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
workflow: workflow,
images: potential_outputs
})
}).then(response => {
var domain = window.location.hostname;
var port = window.location.port;
port = port || (window.location.protocol === 'http:' ? '80' : window.location.protocol === 'https:' ? '443' : '');
var full_domin = domain + ':' + port
window.open('https://www.esheep.com/app/workflow_upload?from_local='+ full_domin, '_blank');
});
})
}
export const showCopusShareDialog = () => {
if (!CopusShareDialog.instance) {
CopusShareDialog.instance = new CopusShareDialog();
}
return app.graphToPrompt()
.then(prompt => {
return app.graph._nodes;
})
.then(nodes => {
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
CopusShareDialog.instance.show({ potential_outputs, potential_output_nodes});
})
}
export const showOpenArtShareDialog = () => {
if (!OpenArtShareDialog.instance) {
OpenArtShareDialog.instance = new OpenArtShareDialog();
}
return app.graphToPrompt()
.then(prompt => {
// console.log({ prompt })
return app.graph._nodes;
})
.then(nodes => {
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
OpenArtShareDialog.instance.show({ potential_outputs, potential_output_nodes});
})
}
export const showYouMLShareDialog = () => {
if (!YouMLShareDialog.instance) {
YouMLShareDialog.instance = new YouMLShareDialog();
@@ -237,9 +180,9 @@ export const showYouMLShareDialog = () => {
}
export const showShareDialog = async (share_option) => {
export const showShareDialog = async () => {
if (!ShareDialog.instance) {
ShareDialog.instance = new ShareDialog(share_option);
ShareDialog.instance = new ShareDialog();
}
return app.graphToPrompt()
.then(prompt => {
@@ -259,7 +202,7 @@ export const showShareDialog = async (share_option) => {
}
return false;
}
ShareDialog.instance.show({ potential_outputs, potential_output_nodes, share_option });
ShareDialog.instance.show({ potential_outputs, potential_output_nodes });
return true;
});
}
@@ -282,17 +225,6 @@ export class ShareDialogChooser extends ComfyDialog {
createButtons() {
const buttons = [
{
key: "openart",
textContent: "OpenArt AI",
website: "https://openart.ai/workflows/",
description: "Share ComfyUI workflows and art on OpenArt.ai",
onclick: () => {
showOpenArtShareDialog();
this.close();
}
},
{
key: "youml",
textContent: "YouML",
website: "https://youml.com",
description: "Share your workflow or transform it into an interactive app on YouML.com",
@@ -302,47 +234,15 @@ export class ShareDialogChooser extends ComfyDialog {
}
},
{
key: "matrix",
textContent: "Matrix Server",
website: "https://app.element.io/#/room/%23comfyui_space%3Amatrix.org",
description: "Share your art on the official ComfyUI matrix server",
onclick: async () => {
showShareDialog('matrix').then((suc) => {
showShareDialog().then((suc) => {
suc && this.close();
})
}
},
{
key: "comfyworkflows",
textContent: "ComfyWorkflows",
website: "https://comfyworkflows.com",
description: "Share & browse thousands of ComfyUI workflows and art 🎨<br/><br/><a style='color:var(--input-text);' href='https://comfyworkflows.com' target='_blank'>ComfyWorkflows.com</a>",
onclick: () => {
showShareDialog('comfyworkflows').then((suc) => {
suc && this.close();
})
}
},
{
key: "esheep",
textContent: "eSheep",
website: "https://www.esheep.com",
description: "Share & download thousands of ComfyUI workflows on <a style='color:var(--input-text);' href='https://www.esheep.com' target='_blank'>esheep.com</a>",
onclick: () => {
shareToEsheep();
this.close();
}
},
{
key: "Copus",
textContent: "Copus",
website: "https://www.copus.io",
description: "🔴 Earn simple. Get paid from your ComfyUI workflows—no revenue sharing. Ever.",
onclick: () => {
showCopusShareDialog();
this.close();
}
},
];
function createShareButtonsWithDescriptions() {
@@ -357,8 +257,7 @@ export class ShareDialogChooser extends ComfyDialog {
});
buttons.forEach(b => {
const button = $el("button",
{
const button = $el("button", {
type: "button",
textContent: b.textContent,
onclick: b.onclick,
@@ -371,14 +270,8 @@ export class ShareDialogChooser extends ComfyDialog {
'padding': '5px 5px',
'margin-bottom': '5px',
'transition': 'background-color 0.3s',
'position':'relative'
}
},
[
$el("span", { style: {
} }),
]
);
});
button.addEventListener('mouseover', () => {
button.style.backgroundColor = '#007BFF'; // Change color on hover
});
@@ -387,7 +280,7 @@ export class ShareDialogChooser extends ComfyDialog {
});
const description = $el("p", {
innerHTML: b.description,
textContent: b.description,
style: {
'text-align': 'left',
color: 'var(--input-text)',
@@ -396,28 +289,6 @@ export class ShareDialogChooser extends ComfyDialog {
},
});
const copus_ui =$el("div", { style: {
'position': 'absolute',
'height': '100%',
'left': '-25px',
'top': '-26px',
'width': '100%',
'z-index':'-1',
'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
'background-repeat': 'no-repeat',
} });
const copus_ui_bottom =$el("div", { style: {
'position': 'absolute',
'height': '100%',
'left': '25px',
'bottom': '-26px',
'width': '100%',
'transform':'scale(-1, -1)',
'z-index':'-1',
'background':'url("https://static.copus.io/images/client/202412/test/f28ac6ef8f4c6f3d5d50856a272ed02c.png")',
'background-repeat': 'no-repeat',
} });
const websiteLink = $el("a", {
textContent: "🌐 Website",
href: b.website,
@@ -455,17 +326,8 @@ export class ShareDialogChooser extends ComfyDialog {
'border': '1px solid #ddd',
'border-radius': '5px',
'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.1)',
'position':'relative'
}
}, [buttonLinkContainer, description
,
b.key ==='Copus' ?
copus_ui
:'',
b.key ==='Copus' ?
copus_ui_bottom
:'',
]);
}, [buttonLinkContainer, description]);
container.appendChild(column);
});
@@ -518,12 +380,10 @@ export class ShareDialogChooser extends ComfyDialog {
}
export class ShareDialog extends ComfyDialog {
static instance = null;
static matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
static cw_sharekey = "";
static matrix_auth = { homeserver: "matrix.org", username: "" };
constructor(share_option) {
constructor() {
super();
this.share_option = share_option;
this.element = $el("div.comfy-modal", {
parent: document.body, style: {
'overflow-y': "auto",
@@ -541,16 +401,9 @@ export class ShareDialog extends ComfyDialog {
id: "selectOutputImages",
}, []);
this.is_nsfw_checkbox = $el("input", { type: 'checkbox', id: "is_nsfw" }, [])
const is_nsfw_checkbox_text = $el("label", {
}, [" Is this NSFW?"])
this.is_nsfw_checkbox.style.color = "var(--fg-color)";
this.is_nsfw_checkbox.checked = false;
this.matrix_destination_checkbox = $el("input", { type: 'checkbox', id: "matrix_destination" }, [])
const matrix_destination_checkbox_text = $el("label", {}, [" ComfyUI Matrix server"])
this.matrix_destination_checkbox.style.color = "var(--fg-color)";
this.matrix_destination_checkbox.checked = this.share_option === 'matrix'; //true;
try {
api.fetchApi(`/v2/manager/get_matrix_dep_status`)
@@ -566,17 +419,9 @@ export class ShareDialog extends ComfyDialog {
.catch(error => {});
} catch (error) {}
this.comfyworkflows_destination_checkbox = $el("input", { type: 'checkbox', id: "comfyworkflows_destination" }, [])
const comfyworkflows_destination_checkbox_text = $el("label", {}, [" ComfyWorkflows.com"])
this.comfyworkflows_destination_checkbox.style.color = "var(--fg-color)";
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", placeholder: "matrix.org", value: ShareDialog.matrix_auth.homeserver || 'matrix.org' }, []);
this.matrix_homeserver_input = $el("input", { type: 'text', id: "matrix_homeserver", value: "matrix.org", readOnly: true, title: "The share room is on matrix.org; only an account of matrix.org can share." }, []);
this.matrix_username_input = $el("input", { type: 'text', placeholder: "Username", value: ShareDialog.matrix_auth.username || '' }, []);
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password", value: ShareDialog.matrix_auth.password || '' }, []);
this.cw_sharekey_input = $el("input", { type: 'text', placeholder: "Share key (found on your profile page)", value: ShareDialog.cw_sharekey || '' }, []);
this.cw_sharekey_input.style.width = "100%";
this.matrix_password_input = $el("input", { type: 'password', placeholder: "Password" }, []);
this.credits_input = $el("input", {
type: "text",
@@ -626,8 +471,6 @@ export class ShareDialog extends ComfyDialog {
textContent: "Close",
onclick: () => {
// Reset state
this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
this.share_button.textContent = "Share";
this.share_button.style.display = "inline-block";
this.final_message.innerHTML = "";
@@ -635,7 +478,6 @@ export class ShareDialog extends ComfyDialog {
this.credits_input.value = "";
this.title_input.value = "";
this.description_input.value = "";
this.is_nsfw_checkbox.checked = false;
this.selectedOutputIndex = 0;
// hide the final message
@@ -713,28 +555,6 @@ export class ShareDialog extends ComfyDialog {
]),
]),
$el("details", {
style: {
border: "1px solid #999",
marginTop: "10px",
padding: "5px",
borderRadius: "5px",
backgroundColor: "#222"
},
}, [
$el("summary", {
style: {
color: "white",
cursor: "pointer",
}
}, [`Comfyworkflows.com account`]),
$el("h4", {
textContent: "Share key (found on your profile page)",
}, []),
$el("p", { size: 3, color: "white" }, ["If provided, your art will be saved to your account. Otherwise, it will be shared anonymously."]),
this.cw_sharekey_input,
]),
$el("div", {}, [
$el("p", {
size: 3, color: "white", style: {
@@ -743,9 +563,6 @@ export class ShareDialog extends ComfyDialog {
}, [`Select where to share your art:`]),
this.matrix_destination_checkbox,
matrix_destination_checkbox_text,
$el("br", {}, []),
this.comfyworkflows_destination_checkbox,
comfyworkflows_destination_checkbox_text,
]),
$el("h4", {
@@ -779,9 +596,6 @@ export class ShareDialog extends ComfyDialog {
}
}, []),
this.description_input,
$el("br", {}, []),
$el("div", {}, [this.is_nsfw_checkbox, is_nsfw_checkbox_text]),
// $el("br", {}, []),
// this.final_message,
@@ -798,8 +612,6 @@ export class ShareDialog extends ComfyDialog {
textContent: "Close",
onclick: () => {
// Reset state
this.matrix_destination_checkbox.checked = this.share_option === 'matrix';
this.comfyworkflows_destination_checkbox.checked = this.share_option !== 'matrix';
this.share_button.textContent = "Share";
this.share_button.style.display = "inline-block";
this.final_message.innerHTML = "";
@@ -807,7 +619,6 @@ export class ShareDialog extends ComfyDialog {
this.credits_input.value = "";
this.title_input.value = "";
this.description_input.value = "";
this.is_nsfw_checkbox.checked = false;
this.selectedOutputIndex = 0;
// hide the final message
@@ -823,33 +634,15 @@ export class ShareDialog extends ComfyDialog {
]),
]);
// get the user's existing matrix auth and share key
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "", password: "" };
// get the user's existing matrix auth
ShareDialog.matrix_auth = { homeserver: "matrix.org", username: "" };
try {
api.fetchApi(`/v2/manager/get_matrix_auth`)
.then(response => response.json())
.then(data => {
ShareDialog.matrix_auth = data;
this.matrix_homeserver_input.value = ShareDialog.matrix_auth.homeserver;
this.matrix_username_input.value = ShareDialog.matrix_auth.username;
this.matrix_password_input.value = ShareDialog.matrix_auth.password;
})
.catch(error => {
// console.log(error);
});
} catch (error) {
// console.log(error);
}
// get the user's existing comfyworkflows share key
ShareDialog.cw_sharekey = "";
try {
// console.log("Fetching comfyworkflows share key")
api.fetchApi(`/v2/manager/get_comfyworkflows_auth`)
.then(response => response.json())
.then(data => {
ShareDialog.cw_sharekey = data.comfyworkflows_sharekey;
this.cw_sharekey_input.value = ShareDialog.cw_sharekey;
this.matrix_password_input.placeholder = "Saved password (leave empty to use it)";
})
.catch(error => {
// console.log(error);
@@ -868,23 +661,17 @@ export class ShareDialog extends ComfyDialog {
if (this.matrix_destination_checkbox.checked) {
destinations.push("matrix");
}
if (this.comfyworkflows_destination_checkbox.checked) {
destinations.push("comfyworkflows");
}
// if destinations includes matrix, make an api call to /manager/check_matrix to ensure that the user has configured their matrix settings
if (destinations.includes("matrix")) {
let definedMatrixAuth = !!this.matrix_homeserver_input.value && !!this.matrix_username_input.value && !!this.matrix_password_input.value;
const usesSavedPassword = this.matrix_username_input.value == ShareDialog.matrix_auth.username;
let definedMatrixAuth = !!this.matrix_username_input.value && (!!this.matrix_password_input.value || usesSavedPassword);
if (!definedMatrixAuth) {
customAlert("Please set your Matrix account details.");
return;
}
}
if (destinations.includes("comfyworkflows") && !this.cw_sharekey_input.value && false) { //!confirm("You have NOT set your ComfyWorkflows.com share key. Your art will NOT be connected to your account (it will be shared anonymously). Continue?")) {
return;
}
const { potential_outputs, potential_output_nodes } = getPotentialOutputsAndOutputNodes(nodes);
// console.log({ potential_outputs, potential_output_nodes })
@@ -914,14 +701,10 @@ export class ShareDialog extends ComfyDialog {
username: this.matrix_username_input.value,
password: this.matrix_password_input.value,
},
cw_auth: {
cw_sharekey: this.cw_sharekey_input.value,
},
share_destinations: destinations,
credits: this.credits_input.value,
title: this.title_input.value,
description: this.description_input.value,
is_nsfw: this.is_nsfw_checkbox.checked,
prompt,
potential_outputs,
selected_output_index: this.selectedOutputIndex,
@@ -950,15 +733,9 @@ export class ShareDialog extends ComfyDialog {
const response_json = await response.json();
if (response_json.comfyworkflows.url) {
this.final_message.innerHTML = "Your art has been shared: <a href='" + response_json.comfyworkflows.url + "' target='_blank'>" + response_json.comfyworkflows.url + "</a>";
if (response_json.matrix.success) {
this.final_message.innerHTML += "<br>Your art has been shared in the ComfyUI Matrix server's #share channel!";
}
} else {
if (response_json.matrix.success) {
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
}
if (response_json.matrix.success) {
this.final_message.innerHTML = "Your art has been shared in the ComfyUI Matrix server's #share channel!";
ShareDialog.matrix_auth = { homeserver: this.matrix_homeserver_input.value, username: this.matrix_username_input.value };
}
this.final_message.style.color = "green";
@@ -991,7 +768,7 @@ export class ShareDialog extends ComfyDialog {
return res;
}
show({potential_outputs, potential_output_nodes, share_option}) {
show({potential_outputs, potential_output_nodes}) {
// Sort `potential_output_nodes` by node ID to make the order always
// consistent, but we should also keep `potential_outputs` in the same
// order as `potential_output_nodes`.
@@ -1103,14 +880,6 @@ export class ShareDialog extends ComfyDialog {
// this.radio_buttons.appendChild(subheader);
this.radio_buttons.appendChild(new_radio_buttons);
this.element.style.display = "block";
share_option = share_option || this.share_option;
if (share_option === 'comfyworkflows') {
this.matrix_destination_checkbox.checked = false;
this.comfyworkflows_destination_checkbox.checked = true;
} else {
this.matrix_destination_checkbox.checked = true;
this.comfyworkflows_destination_checkbox.checked = false;
}
this.matrix_destination_checkbox.checked = true;
}
}
File diff suppressed because it is too large Load Diff
-746
View File
@@ -1,746 +0,0 @@
import {app} from "../../scripts/app.js";
import {api} from "../../scripts/api.js";
import {ComfyDialog, $el} from "../../scripts/ui.js";
import { customAlert } from "./common.js";
const LOCAL_STORAGE_KEY = "openart_comfy_workflow_key";
const DEFAULT_HOMEPAGE_URL = "https://openart.ai/workflows/dev?developer=true";
//const DEFAULT_HOMEPAGE_URL = "http://localhost:8080/workflows/dev?developer=true";
const API_ENDPOINT = "https://openart.ai/api";
//const API_ENDPOINT = "http://localhost:8080/api";
const style = `
.openart-share-dialog a {
color: #f8f8f8;
}
.openart-share-dialog a:hover {
color: #007bff;
}
.output_label {
border: 5px solid transparent;
}
.output_label:hover {
border: 5px solid #59E8C6;
}
.output_label.checked {
border: 5px solid #59E8C6;
}
`;
// Shared component styles
const sectionStyle = {
marginBottom: 0,
padding: 0,
borderRadius: "8px",
boxShadow: "0 2px 4px rgba(0, 0, 0, 0.05)",
display: "flex",
flexDirection: "column",
justifyContent: "center",
};
export class OpenArtShareDialog extends ComfyDialog {
static instance = null;
constructor() {
super();
$el("style", {
textContent: style,
parent: document.head,
});
this.element = $el(
"div.comfy-modal.openart-share-dialog",
{
parent: document.body,
style: {
"overflow-y": "auto",
},
},
[$el("div.comfy-modal-content", {}, [...this.createButtons()])]
);
this.selectedOutputIndex = 0;
this.selectedNodeId = null;
this.uploadedImages = [];
this.selectedFile = null;
}
async readKey() {
let key = ""
try {
key = await api.fetchApi(`/v2/manager/get_openart_auth`)
.then(response => response.json())
.then(data => {
return data.openart_key;
})
.catch(error => {
// console.log(error);
});
} catch (error) {
// console.log(error);
}
return key || "";
}
async saveKey(value) {
await api.fetchApi(`/v2/manager/set_openart_auth`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
openart_key: value
})
});
}
createButtons() {
const inputStyle = {
display: "block",
minWidth: "500px",
width: "100%",
padding: "10px",
margin: "10px 0",
borderRadius: "4px",
border: "1px solid #ddd",
boxSizing: "border-box",
};
const hyperLinkStyle = {
display: "block",
marginBottom: "15px",
fontWeight: "bold",
fontSize: "14px",
};
const labelStyle = {
color: "#f8f8f8",
display: "block",
margin: "10px 0 0 0",
fontWeight: "bold",
textDecoration: "none",
};
const buttonStyle = {
padding: "10px 80px",
margin: "10px 5px",
borderRadius: "4px",
border: "none",
cursor: "pointer",
color: "#fff",
backgroundColor: "#007bff",
};
// upload images input
this.uploadImagesInput = $el("input", {
type: "file",
multiple: false,
style: inputStyle,
accept: "image/*",
});
this.uploadImagesInput.addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) {
this.previewImage.src = "";
this.previewImage.style.display = "none";
return;
}
const reader = new FileReader();
reader.onload = async (e) => {
const imgData = e.target.result;
this.previewImage.src = imgData;
this.previewImage.style.display = "block";
this.selectedFile = null
// Once user uploads an image, we uncheck all radio buttons
this.radioButtons.forEach((ele) => {
ele.checked = false;
ele.parentElement.classList.remove("checked");
});
// Add the opacity style toggle here to indicate that they only need
// to upload one image or choose one from the outputs.
this.outputsSection.style.opacity = 0.35;
this.uploadImagesInput.style.opacity = 1;
};
reader.readAsDataURL(file);
});
// preview image
this.previewImage = $el("img", {
src: "",
style: {
width: "100%",
maxHeight: "100px",
objectFit: "contain",
display: "none",
marginTop: '10px',
},
});
this.keyInput = $el("input", {
type: "password",
placeholder: "Copy & paste your API key",
style: inputStyle,
});
this.NameInput = $el("input", {
type: "text",
placeholder: "Title (required)",
style: inputStyle,
});
this.descriptionInput = $el("textarea", {
placeholder: "Description (optional)",
style: {
...inputStyle,
minHeight: "100px",
},
});
// Header Section
const headerSection = $el("h3", {
textContent: "Share your workflow to OpenArt",
size: 3,
color: "white",
style: {
'text-align': 'center',
color: 'var(--input-text)',
margin: '0 0 10px 0',
}
});
// LinkSection
this.communityLink = $el("a", {
style: hyperLinkStyle,
href: DEFAULT_HOMEPAGE_URL,
target: "_blank"
}, ["👉 Check out thousands of workflows shared from the community"])
this.getAPIKeyLink = $el("a", {
style: {
...hyperLinkStyle,
color: "#59E8C6"
},
href: DEFAULT_HOMEPAGE_URL,
target: "_blank"
}, ["👉 Get your API key here"])
const linkSection = $el(
"div",
{
style: {
marginTop: "10px",
display: "flex",
flexDirection: "column",
},
},
[
this.communityLink,
this.getAPIKeyLink,
]
);
// Account Section
const accountSection = $el("div", {style: sectionStyle}, [
$el("label", {style: labelStyle}, ["1️⃣ OpenArt API Key"]),
this.keyInput,
]);
// Output Upload Section
const outputUploadSection = $el("div", {style: sectionStyle}, [
$el("label", {
style: {
...labelStyle,
margin: "10px 0 0 0"
}
}, ["2️⃣ Image/Thumbnail (Required)"]),
this.previewImage,
this.uploadImagesInput,
]);
// Outputs Section
this.outputsSection = $el("div", {
id: "selectOutputs",
}, []);
// Additional Inputs Section
const additionalInputsSection = $el("div", {style: sectionStyle}, [
$el("label", {style: labelStyle}, ["3️⃣ Workflow Information"]),
this.NameInput,
this.descriptionInput,
]);
// OpenArt Contest Section
/*
this.joinContestCheckbox = $el("input", {
type: 'checkbox',
id: "join_contest"s
}, [])
this.joinContestDescription = $el("a", {
style: {
...hyperLinkStyle,
display: 'inline-block',
color: "#59E8C6",
fontSize: '12px',
marginLeft: '10px',
marginBottom: 0,
},
href: "https://contest.openart.ai/",
target: "_blank"
}, ["🏆 I'm participating in the OpenArt workflow contest"])
this.joinContestLabel = $el("label", {
style: {
display: 'flex',
alignItems: 'center',
cursor: 'pointer',
}
}, [this.joinContestCheckbox, this.joinContestDescription])
const contestSection = $el("div", {style: sectionStyle}, [
this.joinContestLabel,
]);
*/
// Message Section
this.message = $el(
"div",
{
style: {
color: "#ff3d00",
textAlign: "center",
padding: "10px",
fontSize: "20px",
},
},
[]
);
this.shareButton = $el("button", {
type: "submit",
textContent: "Share",
style: buttonStyle,
onclick: () => {
this.handleShareButtonClick();
},
});
// Share and Close Buttons
const buttonsSection = $el(
"div",
{
style: {
textAlign: "right",
marginTop: "20px",
display: "flex",
justifyContent: "space-between",
},
},
[
$el("button", {
type: "button",
textContent: "Close",
style: {
...buttonStyle,
backgroundColor: undefined,
},
onclick: () => {
this.close();
},
}),
this.shareButton,
]
);
// Composing the full layout
const layout = [
headerSection,
linkSection,
accountSection,
outputUploadSection,
this.outputsSection,
additionalInputsSection,
// contestSection,
this.message,
buttonsSection,
];
return layout;
}
async fetchApi(path, options, statusText) {
if (statusText) {
this.message.textContent = statusText;
}
const addSearchParams = (url, params = {}) =>
new URL(
`${url.origin}${url.pathname}?${new URLSearchParams([
...Array.from(url.searchParams.entries()),
...Object.entries(params),
])}`
);
const fullPath = addSearchParams(new URL(API_ENDPOINT + path), {
workflow_api_key: this.keyInput.value,
});
const response = await fetch(fullPath, options);
if (!response.ok) {
throw new Error(response.statusText);
}
if (statusText) {
this.message.textContent = "";
}
const data = await response.json();
return {
ok: response.ok,
statusText: response.statusText,
status: response.status,
data,
};
}
async uploadThumbnail(uploadFile) {
const form = new FormData();
form.append("file", uploadFile);
try {
const res = await this.fetchApi(
`/v2/workflows/upload_thumbnail`,
{
method: "POST",
body: form,
},
"Uploading thumbnail..."
);
if (res.ok && res.data) {
const {image_url, width, height} = res.data;
this.uploadedImages.push({
url: image_url,
width,
height,
});
}
} catch (e) {
if (e?.response?.status === 413) {
throw new Error("File size is too large (max 20MB)");
} else {
throw new Error("Error uploading thumbnail: " + e.message);
}
}
}
async handleShareButtonClick() {
this.message.textContent = "";
await this.saveKey(this.keyInput.value);
try {
this.shareButton.disabled = true;
this.shareButton.textContent = "Sharing...";
await this.share();
} catch (e) {
customAlert(e.message);
}
this.shareButton.disabled = false;
this.shareButton.textContent = "Share";
}
async share() {
const prompt = await app.graphToPrompt();
const workflowJSON = prompt["workflow"];
const workflowAPIJSON = prompt["output"];
const form_values = {
name: this.NameInput.value,
description: this.descriptionInput.value,
};
if (!this.keyInput.value) {
throw new Error("API key is required");
}
if (!this.uploadImagesInput.files[0] && !this.selectedFile) {
throw new Error("Thumbnail is required");
}
if (!form_values.name) {
throw new Error("Title is required");
}
const current_snapshot = await api.fetchApi(`/v2/snapshot/get_current`)
.then(response => response.json())
.catch(error => {
// console.log(error);
});
if (!this.uploadedImages.length) {
if (this.selectedFile) {
await this.uploadThumbnail(this.selectedFile);
} else {
for (const file of this.uploadImagesInput.files) {
try {
await this.uploadThumbnail(file);
} catch (e) {
this.uploadedImages = [];
throw new Error(e.message);
}
}
if (this.uploadImagesInput.files.length === 0) {
throw new Error("No thumbnail uploaded");
}
}
}
// const join_contest = this.joinContestCheckbox.checked;
try {
const response = await this.fetchApi(
"/v2/workflows/publish",
{
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
workflow_json: workflowJSON,
upload_images: this.uploadedImages,
form_values,
advanced_config: {
workflow_api_json: workflowAPIJSON,
snapshot: current_snapshot,
},
// join_contest,
}),
},
"Uploading workflow..."
);
if (response.ok) {
const {workflow_id} = response.data;
if (workflow_id) {
const url = `https://openart.ai/workflows/-/-/${workflow_id}`;
this.message.innerHTML = `Workflow has been shared successfully. <a href="${url}" target="_blank">Click here to view it.</a>`;
this.previewImage.src = "";
this.previewImage.style.display = "none";
this.uploadedImages = [];
this.NameInput.value = "";
this.descriptionInput.value = "";
this.radioButtons.forEach((ele) => {
ele.checked = false;
ele.parentElement.classList.remove("checked");
});
this.selectedOutputIndex = 0;
this.selectedNodeId = null;
this.selectedFile = null;
}
}
} catch (e) {
throw new Error("Error sharing workflow: " + e.message);
}
}
async fetchImageBlob(url) {
const response = await fetch(url);
const blob = await response.blob();
return blob;
}
async show({potential_outputs, potential_output_nodes} = {}) {
// Sort `potential_output_nodes` by node ID to make the order always
// consistent, but we should also keep `potential_outputs` in the same
// order as `potential_output_nodes`.
const potential_output_to_order = {};
potential_output_nodes.forEach((node, index) => {
if (node.id in potential_output_to_order) {
potential_output_to_order[node.id][1].push(potential_outputs[index]);
} else {
potential_output_to_order[node.id] = [node, [potential_outputs[index]]];
}
})
// Sort the object `potential_output_to_order` by key (node ID)
const sorted_potential_output_to_order = Object.fromEntries(
Object.entries(potential_output_to_order).sort((a, b) => a[0].id - b[0].id)
);
const sorted_potential_outputs = []
const sorted_potential_output_nodes = []
for (const [key, value] of Object.entries(sorted_potential_output_to_order)) {
sorted_potential_output_nodes.push(value[0]);
sorted_potential_outputs.push(...value[1]);
}
potential_output_nodes = sorted_potential_output_nodes;
potential_outputs = sorted_potential_outputs;
this.message.innerHTML = "";
this.message.textContent = "";
this.element.style.display = "block";
this.previewImage.src = "";
this.previewImage.style.display = "none";
const key = await this.readKey();
this.keyInput.value = key;
this.uploadedImages = [];
// If `selectedNodeId` is provided, we will select the corresponding radio
// button for the node. In addition, we move the selected radio button to
// the top of the list.
if (this.selectedNodeId) {
const index = potential_output_nodes.findIndex(node => node.id === this.selectedNodeId);
if (index >= 0) {
this.selectedOutputIndex = index;
}
}
this.radioButtons = [];
const new_radio_buttons = $el("div",
{
id: "selectOutput-Options",
style: {
'overflow-y': 'scroll',
'max-height': '200px',
'display': 'grid',
'grid-template-columns': 'repeat(auto-fit, minmax(100px, 1fr))',
'grid-template-rows': 'auto',
'grid-column-gap': '10px',
'grid-row-gap': '10px',
'margin-bottom': '10px',
'padding': '10px',
'border-radius': '8px',
'box-shadow': '0 2px 4px rgba(0, 0, 0, 0.05)',
'background-color': 'var(--bg-color)',
}
},
potential_outputs.map((output, index) => {
const {node_id} = output;
const radio_button = $el("input", {
type: 'radio',
name: "selectOutputImages",
value: index,
required: index === 0
}, [])
let radio_button_img;
let filename;
if (output.type === "image" || output.type === "temp") {
radio_button_img = $el("img", {
src: `/view?filename=${output.image.filename}&subfolder=${output.image.subfolder}&type=${output.image.type}`,
style: {
width: "100px",
height: "100px",
objectFit: "cover",
borderRadius: "5px"
}
}, []);
filename = output.image.filename
} else if (output.type === "output") {
radio_button_img = $el("img", {
src: output.output.value,
style: {
width: "auto",
height: "100px",
objectFit: "cover",
borderRadius: "5px"
}
}, []);
filename = output.filename
} else {
// unsupported output type
// this should never happen
// TODO
radio_button_img = $el("img", {
src: "",
style: {width: "auto", height: "100px"}
}, []);
}
const radio_button_text = $el("span", {
style: {
color: 'gray',
display: 'block',
fontSize: '12px',
overflowX: 'hidden',
textOverflow: 'ellipsis',
textWrap: 'nowrap',
maxWidth: '100px',
}
}, [output.title])
const node_id_chip = $el("span", {
style: {
color: '#FBFBFD',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)',
fontSize: '12px',
overflowX: 'hidden',
padding: '2px 3px',
textOverflow: 'ellipsis',
textWrap: 'nowrap',
maxWidth: '100px',
position: 'absolute',
top: '3px',
left: '3px',
borderRadius: '3px',
}
}, [`Node: ${node_id}`])
radio_button.style.color = "var(--fg-color)";
radio_button.checked = this.selectedOutputIndex === index;
radio_button.onchange = async () => {
this.selectedOutputIndex = parseInt(radio_button.value);
// Remove the "checked" class from all radio buttons
this.radioButtons.forEach((ele) => {
ele.parentElement.classList.remove("checked");
});
radio_button.parentElement.classList.add("checked");
this.fetchImageBlob(radio_button_img.src).then((blob) => {
const file = new File([blob], filename, {
type: blob.type,
});
this.previewImage.src = radio_button_img.src;
this.previewImage.style.display = "block";
this.selectedFile = file;
})
// Add the opacity style toggle here to indicate that they only need
// to upload one image or choose one from the outputs.
this.outputsSection.style.opacity = 1;
this.uploadImagesInput.style.opacity = 0.35;
};
if (radio_button.checked) {
this.fetchImageBlob(radio_button_img.src).then((blob) => {
const file = new File([blob], filename, {
type: blob.type,
});
this.previewImage.src = radio_button_img.src;
this.previewImage.style.display = "block";
this.selectedFile = file;
})
// Add the opacity style toggle here to indicate that they only need
// to upload one image or choose one from the outputs.
this.outputsSection.style.opacity = 1;
this.uploadImagesInput.style.opacity = 0.35;
}
this.radioButtons.push(radio_button);
return $el(`label.output_label${radio_button.checked ? '.checked' : ''}`, {
style: {
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
marginBottom: "10px",
cursor: "pointer",
position: 'relative',
}
}, [radio_button_img, radio_button_text, radio_button, node_id_chip]);
})
);
const header =
$el("p", {
textContent: this.radioButtons.length === 0 ? "Queue Prompt to see the outputs" : "Or choose one from the outputs (scroll to see all)",
size: 2,
color: "white",
style: {
color: 'var(--input-text)',
margin: '0 0 5px 0',
fontSize: '12px',
},
}, [])
this.outputsSection.innerHTML = "";
this.outputsSection.appendChild(header);
this.outputsSection.appendChild(new_radio_buttons);
}
}
+8 -22
View File
@@ -1,7 +1,7 @@
import {app} from "../../scripts/app.js";
import {api} from "../../scripts/api.js";
import {ComfyDialog, $el} from "../../scripts/ui.js";
import { customAlert } from "./common.js";
import { customAlert, sanitizeHTML, sanitizeUrl } from "./common.js";
const BASE_URL = "https://youml.com";
//const BASE_URL = "http://localhost:3000";
@@ -176,25 +176,12 @@ export class YouMLShareDialog extends ComfyDialog {
this.selectedFile = null;
}
async loadToken() {
let key = ""
try {
const response = await api.fetchApi(`/v2/manager/youml/settings`)
const settings = await response.json()
return settings.token
} catch (error) {
}
return key || "";
loadToken() {
return localStorage.getItem("youml_token") || "";
}
async saveToken(value) {
await api.fetchApi(`/v2/manager/youml/settings`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
token: value
})
});
saveToken(value) {
localStorage.setItem("youml_token", value);
}
createLayout() {
@@ -342,7 +329,7 @@ export class YouMLShareDialog extends ComfyDialog {
async handleShareButtonClick() {
this.message.textContent = "";
await this.saveToken(this.apiTokenInput.value);
this.saveToken(this.apiTokenInput.value);
try {
this.shareButton.disabled = true;
this.shareButton.textContent = "Sharing...";
@@ -420,7 +407,7 @@ export class YouMLShareDialog extends ComfyDialog {
}
}
this.message.innerHTML = `${messagePrefix} To turn your workflow into an interactive app, ` +
`<a href="${recipePageUrl}" target="_blank">visit it on YouML</a>`;
`<a href="${sanitizeHTML(sanitizeUrl(recipePageUrl))}" target="_blank" rel="noopener noreferrer">visit it on YouML</a>`;
this.uploadedImages = [];
this.nameInput.value = "";
@@ -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";
+107 -6
View File
@@ -172,7 +172,7 @@ export function rebootAPI() {
customConfirm("Are you sure you'd like to reboot the server?").then((isConfirmed) => {
if (isConfirmed) {
try {
api.fetchApi("/v2/manager/reboot", { method: 'POST' });
api.fetchApi("/v2/manager/reboot", { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
catch(exception) {}
}
@@ -212,11 +212,12 @@ export async function install_pip(packages) {
const res = await api.fetchApi("/v2/customnode/install/pip", {
method: "POST",
body: packages,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ packages: packages }),
});
if(res.status == 403) {
show_message("To use this feature, set <code>allow_pip_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required.");
show_message(await install_denial_message(res, 'allow_pip_install'));
return;
}
@@ -247,11 +248,12 @@ export async function install_via_git_url(url, manager_dialog) {
const res = await api.fetchApi("/v2/customnode/install/git_url", {
method: "POST",
body: url,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: url }),
});
if(res.status == 403) {
show_message("To use this feature, set <code>allow_git_url_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required.");
show_message(await install_denial_message(res, 'allow_git_url_install'));
return;
}
@@ -347,6 +349,55 @@ export function md5(inputString) {
return rh(a)+rh(b)+rh(c)+rh(d);
}
const levenArray = [];
const levenCodeCache = [];
export const leven = (first, second) => {
if (first === second) {
return 0;
}
const swap = first;
if (first.length > second.length) {
first = second;
second = swap;
}
let firstLength = first.length;
let secondLength = second.length;
while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) {
firstLength--;
secondLength--;
}
let start = 0;
while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) {
start++;
}
firstLength -= start;
secondLength -= start;
if (firstLength === 0) {
return secondLength;
}
let bCharacterCode;
let result;
let temporary;
let temporary2;
let index = 0;
let index2 = 0;
while (index < firstLength) {
levenCodeCache[index] = first.charCodeAt(start + index);
levenArray[index] = ++index;
}
while (index2 < secondLength) {
bCharacterCode = second.charCodeAt(start + index2);
temporary = index2++;
result = index2;
for (index = 0; index < firstLength; index++) {
temporary2 = bCharacterCode === levenCodeCache[index] ? temporary : temporary + 1;
temporary = levenArray[index];
result = levenArray[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2);
}
}
return result;
}
export async function fetchData(route, options) {
let err;
const res = await api.fetchApi(route, options).catch(e => {
@@ -659,4 +710,54 @@ function initTooltip () {
document.body.addEventListener('mouseleave', mouseleaveHandler, true);
}
initTooltip();
initTooltip();
// Installation flags and network mode take effect after a restart.
const INSTALL_DENIAL_RESTART_NOTE = "<BR>Both values are read once at ComfyUI startup, so changing either one needs a restart, done with the server down: STOP ComfyUI, change the setting, then start it again.";
export const INSTALL_DENIAL_MESSAGES = {
allow_git_url_install: "To use this feature, set <code>allow_git_url_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required." + INSTALL_DENIAL_RESTART_NOTE,
allow_pip_install: "To use this feature, set <code>allow_pip_install = true</code> in the [default] section of config.ini. This setting is independent of security_level.<BR>Note: if the ComfyUI listener is not local, <code>network_mode = personal_cloud</code> is also required." + INSTALL_DENIAL_RESTART_NOTE
};
// Last resort when no entry above applies. Names no flag on purpose.
const INSTALL_DENIAL_UNKNOWN_REASON = "This action was refused by the server, and the client could not determine which setting caused it. The server terminal log states the exact condition. Please contact the administrator.";
// Use the endpoint's flag when the 403 response body is missing or malformed.
export async function install_denial_message(res, fallbackReason) {
let reason = fallbackReason;
try {
const data = await res.json();
if (typeof data === 'object' && data !== null && typeof data.reason === 'string'
&& Object.prototype.hasOwnProperty.call(INSTALL_DENIAL_MESSAGES, data.reason)) {
reason = data.reason;
}
}
catch {
// absent / non-JSON body: keep the fallback
}
return INSTALL_DENIAL_MESSAGES[reason] ?? INSTALL_DENIAL_UNKNOWN_REASON;
}
/**
* Scheme allow-list for registry-supplied URLs that land in an href.
* Returns the URL if it is http(s) or relative, otherwise "". Never throws.
*/
export function sanitizeUrl(url) {
const raw = String(url ?? '').trim();
if (!raw) {
return '';
}
let parsed;
try {
parsed = new URL(raw);
}
catch {
// not absolute: keep a scheme-less relative path, drop anything else
return /^[a-z][a-z0-9+.\-]*:/i.test(raw) ? '' : raw;
}
// URL parsing already normalised the scheme (`java\tscript:` collapses).
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return raw;
}
return '';
}
+10 -16
View File
@@ -103,7 +103,7 @@
line-height: 28px;
cursor: pointer;
padding: 0.5em 0.5em;
padding: 0 0.5em;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--comfy-input-bg);
@@ -218,6 +218,7 @@
.cn-manager-grid .cn-pack-conflicts {
color: orange;
white-space: normal;
}
.cn-popover {
@@ -590,20 +591,6 @@
word-break: break-word;
}
.cn-tag-list {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
margin-bottom: 5px;
}
.cn-tag-list > div {
background-color: var(--border-color);
border-radius: 5px;
padding: 0 5px;
}
.cn-install-buttons {
display: flex;
flex-direction: column;
@@ -657,6 +644,13 @@
color: white;
}
.cn-manager .cn-btn-invalid-installation {
background-color: #A65E00;
font-size: 10px;
font-weight: bold;
color: white;
}
.cn-manager .cn-btn-install {
background-color: black;
color: white;
@@ -726,4 +720,4 @@
.cn-manager-light .cn-btn-install {
background-color: #333;
}
}
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
import { Grid } from "./turbogrid.esm.js";
// Keep Manager's search hardening outside the vendored TurboGrid bundle.
export default class ManagerGrid extends Grid {
highlightKeywordsFilter(rowItem, columns, value) {
const { textKey, textGenerator, highlightKey } = this.options.highlightKeywords;
for (const column of columns) {
rowItem[`${highlightKey}${column}`] = null;
}
const keywords = value ? String(value).trim().toLowerCase().split(/\s+/).filter(Boolean) : [];
if (!keywords.length) return true;
let matched = false;
for (const column of columns) {
const value = typeof textGenerator === "function" ? textGenerator(rowItem, column) : rowItem[column];
if (value === null || value === undefined) continue;
let text = String(value).trim();
if (!text) continue;
const key = `${textKey}${column}`;
if (rowItem[key] === null || rowItem[key] === undefined) {
// A detached element's innerHTML can still run image handlers.
rowItem[key] = new DOMParser().parseFromString(text, "text/html").body.textContent;
}
text = rowItem[key].toLowerCase();
let offset = 0;
const found = keywords.every(keyword => {
const index = text.indexOf(keyword, offset);
if (index === -1) return false;
offset = index + keyword.length;
return true;
});
if (found) {
rowItem[`${highlightKey}${column}`] = true;
this.highlightKeywords = keywords;
matched = true;
}
}
return matched;
}
highlightTextNodes(nodes, keywords) {
if (!keywords.length) return;
let keywordIndex = 0;
for (const node of nodes) {
const text = node.textContent;
const lower = text.toLowerCase();
const wrapper = document.createElement("span");
let offset = 0;
while (offset < text.length) {
const keyword = keywords[keywordIndex];
const index = lower.indexOf(keyword, offset);
if (index === -1) break;
wrapper.append(text.slice(offset, index));
const mark = document.createElement("mark");
mark.textContent = text.slice(index, index + keyword.length);
wrapper.append(mark);
offset = index + keyword.length;
keywordIndex = (keywordIndex + 1) % keywords.length;
}
if (wrapper.childNodes.length) {
// Decoded cell text stays in text nodes, including inside <mark>.
wrapper.append(text.slice(offset));
node.replaceWith(wrapper);
}
}
}
}
+2 -2
View File
@@ -71,7 +71,7 @@
line-height: 28px;
cursor: pointer;
padding: 0.5em 0.5em;
padding: 0 0.5em;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--comfy-input-bg);
@@ -234,4 +234,4 @@
.cmm-manager-light .cmm-btn-install {
background-color: #333;
}
}
+189 -144
View File
@@ -3,17 +3,22 @@ import { $el } from "../../scripts/ui.js";
import {
manager_instance, rebootAPI,
fetchData, md5, icons, show_message, customAlert, infoToast, showTerminal,
storeColumnWidth, restoreColumnWidth, loadCss, generateUUID
storeColumnWidth, restoreColumnWidth, loadCss, generateUUID,
sanitizeHTML, sanitizeUrl
} from "./common.js";
// Model names and descriptions are server-escaped; other fields are raw.
import { api } from "../../scripts/api.js";
// https://cenfun.github.io/turbogrid/api.html
import TG from "./turbogrid.esm.js";
import ManagerGrid from "./manager-grid.js";
import { buildGuiFrameCustomHeader, createSettingsCombo } from "./comfyui-gui-builder.js";
loadCss("./model-manager.css");
const gridId = "model";
const escapeCell = (value) => sanitizeHTML(String(value ?? ""));
const pageHtml = `
<div class="cmm-manager cmm-manager-dark">
@@ -21,8 +26,8 @@ const pageHtml = `
<div class="cmm-manager-selection"></div>
<div class="cmm-manager-message"></div>
<div class="cmm-manager-footer">
<button class="cmm-manager-refresh p-button p-component">Refresh</button>
<button class="cmm-manager-stop p-button p-component">Stop</button>
<button class="cmm-manager-refresh cm-ui-button">Refresh</button>
<button class="cmm-manager-stop cm-ui-button">Stop</button>
<div class="cmm-flex-auto"></div>
</div>
</div>
@@ -41,6 +46,9 @@ export class ModelManager {
this.base = '';
this.keywords = '';
// Installs that are waiting for the end of their batch, by batch id
this.install_contexts = new Map();
this.init();
api.addEventListener("cm-queue-status", this.onQueueStatus);
@@ -51,7 +59,7 @@ export class ModelManager {
createSettingsCombo("Filter", $el("select.cmm-manager-filter")),
createSettingsCombo("Type", $el("select.cmm-manager-type")),
createSettingsCombo("Base", $el("select.cmm-manager-base")),
$el("input.cmm-manager-keywords.p-inputtext.p-component", { type: "search", placeholder: "Search" }),
$el("input.cmm-manager-keywords.cm-ui-input", { type: "search", placeholder: "Search" }),
$el("div.cmm-manager-status"),
$el("div.cmm-flex-auto")
]);
@@ -101,22 +109,17 @@ export class ModelManager {
updateFilter() {
const $filter = this.element.querySelector(".cmm-manager-filter");
$filter.innerHTML = this.filterList.map(item => {
const selected = item.value === this.filter ? " selected" : "";
return `<option value="${item.value}"${selected}>${item.label}</option>`
}).join("");
const option = (item, current) => {
const selected = item.value === current ? " selected" : "";
return `<option value="${sanitizeHTML(String(item.value ?? ''))}"${selected}>${sanitizeHTML(String(item.label ?? ''))}</option>`;
};
$filter.innerHTML = this.filterList.map(item => option(item, this.filter)).join("");
const $type = this.element.querySelector(".cmm-manager-type");
$type.innerHTML = this.typeList.map(item => {
const selected = item.value === this.type ? " selected" : "";
return `<option value="${item.value}"${selected}>${item.label}</option>`
}).join("");
$type.innerHTML = this.typeList.map(item => option(item, this.type)).join("");
const $base = this.element.querySelector(".cmm-manager-base");
$base.innerHTML = this.baseList.map(item => {
const selected = item.value === this.base ? " selected" : "";
return `<option value="${item.value}"${selected}>${item.label}</option>`
}).join("");
$base.innerHTML = this.baseList.map(item => option(item, this.base)).join("");
}
@@ -170,7 +173,7 @@ export class ModelManager {
".cmm-manager-stop": {
click: () => {
api.fetchApi('/v2/manager/queue/reset', { method: 'POST' });
api.fetchApi('/v2/manager/queue/reset', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
infoToast('Cancel', 'Remaining tasks will stop after completing the current task.');
}
},
@@ -199,7 +202,7 @@ export class ModelManager {
initGrid() {
const container = this.element.querySelector(".cmm-manager-grid");
const grid = new TG.Grid(container);
const grid = new ManagerGrid(container);
this.grid = grid;
grid.bind('onUpdated', (e, d) => {
@@ -227,6 +230,9 @@ export class ModelManager {
});
grid.setOption({
highlightKeywords: {
textGenerator: (row, column) => ['name', 'description'].includes(column) ? row[column] : escapeCell(row[column])
},
theme: 'dark',
selectVisible: true,
@@ -252,31 +258,20 @@ export class ModelManager {
rowFilter: (rowItem) => {
const searchableColumns = ["name", "type", "base", "description", "filename", "save_path"];
const models_extensions = ['.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'];
let shouldShown = grid.highlightKeywordsFilter(rowItem, searchableColumns, this.keywords);
if (shouldShown) {
if(this.filter) {
if (this.filter == "in_workflow") {
rowItem.in_workflow = null;
if (Array.isArray(app.graph._nodes)) {
app.graph._nodes.forEach((item, i) => {
if (Array.isArray(item.widgets_values)) {
item.widgets_values.forEach((_item, i) => {
if (rowItem.in_workflow === null && _item !== null && models_extensions.includes("." + _item.toString().split('.').pop())) {
let filename = _item.match(/([^\/]+)(?=\.\w+$)/)[0];
if (grid.highlightKeywordsFilter(rowItem, searchableColumns, filename)) {
rowItem.in_workflow = "True";
grid.highlightKeywordsFilter(rowItem, searchableColumns, "");
}
}
});
}
});
}
}
return ((this.filter == "installed" && rowItem.installed == "True") || (this.filter == "not_installed" && rowItem.installed == "False") || (this.filter == "in_workflow" && rowItem.in_workflow == "True"));
if(this.filter == "installed" && rowItem.installed !== "True") {
return false;
}
if(this.filter == "not_installed" && rowItem.installed !== "False") {
return false;
}
if(this.filter == "in_workflow" && !app.graph._nodes.some(node => Array.isArray(node.widgets_values) && node.widgets_values.some(value => String(value).split(/[\\/]/).pop() === rowItem.filename))) {
return false;
}
if(this.type && rowItem.type !== this.type) {
@@ -325,7 +320,12 @@ export class ModelManager {
maxWidth: 500,
classMap: 'cmm-node-name',
formatter: function(name, rowItem, columnItem, cellNode) {
return `<a href=${rowItem.reference} target="_blank"><b>${name}</b></a>`;
// Names are server-escaped; raw references need URL and attribute handling.
const href = sanitizeUrl(rowItem.reference);
if (!href) {
return `<b>${String(name ?? '')}</b>`;
}
return `<a href="${sanitizeHTML(href)}" target="_blank" rel="noopener noreferrer"><b>${String(name ?? '')}</b></a>`;
}
}, {
id: 'installed',
@@ -342,7 +342,7 @@ export class ModelManager {
if (installed === "True") {
return `<div class="cmm-icon-passed">${icons.passed}</div>`;
}
return `<button class="cmm-btn-install p-button p-component" mode="install">Install</button>`;
return `<button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`;
}
}, {
id: 'url',
@@ -351,7 +351,11 @@ export class ModelManager {
sortable: false,
align: 'center',
formatter: (url, rowItem, columnItem) => {
return `<a class="cmm-btn-download" tooltip="Download file" href="${url}" target="_blank">${icons.download}</a>`;
const href = sanitizeUrl(url);
if (!href) {
return '';
}
return `<a class="cmm-btn-download" tooltip="Download file" href="${sanitizeHTML(href)}" target="_blank" rel="noopener noreferrer">${icons.download}</a>`;
}
}, {
id: 'size',
@@ -361,29 +365,33 @@ export class ModelManager {
if (typeof size === "number") {
return this.formatSize(size);
}
return size;
return sanitizeHTML(String(size ?? ''));
}
}, {
id: 'type',
name: 'Type',
width: 100
width: 100,
formatter: escapeCell
}, {
id: 'base',
name: 'Base'
name: 'Base',
formatter: escapeCell
}, {
id: 'description',
name: 'Description',
width: 400,
maxWidth: 5000,
classMap: 'cmm-node-desc'
classMap: 'cmm-node-desc' // composed HTML from the server (convert_markdown_to_html)
}, {
id: "save_path",
name: 'Save Path',
width: 200
width: 200,
formatter: escapeCell
}, {
id: 'filename',
name: 'Filename',
width: 200
width: 200,
formatter: escapeCell
}];
restoreColumnWidth(gridId, columns);
@@ -415,7 +423,7 @@ export class ModelManager {
}
this.selectedModels = selectedList;
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install p-button p-component" mode="install">Install</button>`);
this.showSelection(`<span>Selected <b>${selectedList.length}</b> models <button class="cmm-btn-install cm-ui-button" mode="install">Install</button>`);
}
focusInstall(item) {
@@ -433,7 +441,6 @@ export class ModelManager {
btn.classList.add("cmm-btn-loading");
this.showError("");
let needRefresh = false;
let errorMsg = "";
let target_items = [];
@@ -454,6 +461,8 @@ export class ModelManager {
const data = item.originalData;
data.ui_id = item.hash;
// Batch rejections refer to id; models need a stable request ID.
data.id ??= item.hash;
if(batch['install_model']) {
@@ -464,49 +473,133 @@ export class ModelManager {
}
}
this.install_context = {btn: btn, targets: target_items};
const batch_id = generateUUID();
batch['batch_id'] = batch_id;
this.install_contexts.set(batch_id, {btn: btn, targets: target_items, queued: false});
if(errorMsg) {
this.showError(errorMsg);
show_message("[Installation Errors]\n"+errorMsg);
// reset
for(let k in target_items) {
const item = target_items[k];
this.grid.updateCell(item, "installed");
}
}
else {
this.batch_id = generateUUID();
batch['batch_id'] = this.batch_id;
const res = await api.fetchApi(`/v2/manager/queue/batch`, {
let failed;
try {
const { data, error } = await fetchData(`/v2/manager/queue/batch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
if (error) throw error;
if (!Array.isArray(data?.failed)) throw new Error('Invalid batch response.');
failed = data.failed;
} catch (error) {
errorMsg = `Failed to submit installation request: ${sanitizeHTML(String(error))}`;
this.showError(errorMsg);
show_message("[Installation Errors]\n" + errorMsg);
this.endInstall(batch_id);
return;
}
for (const id of failed) {
const item = target_items.find(item => item.originalData.id === id);
errorMsg += `[FAIL] ${item?.name ?? sanitizeHTML(String(id))}\n`;
}
if (errorMsg) {
this.showError(errorMsg);
show_message("[Installation Errors]\n" + errorMsg);
}
let failed = await res.json();
showTerminal();
if(failed.length > 0) {
for(let k in failed) {
let hash = failed[k];
const item = self.grid.getRowItemBy("hash", hash);
errorMsg = `[FAIL] ${item.title}`;
}
// No queued work means the server will not send batch-done.
if (target_items.every(item => failed.includes(item.originalData.id))) {
this.endInstall(batch_id);
return;
}
// The batch can end before its request is answered.
const context = this.install_contexts.get(batch_id);
if (!context) {
return;
}
context.queued = true;
this.showStop();
if (context.queue_ended) {
this.endDroppedInstalls();
}
}
// Forget a pending install and return its button and rows to idle.
// The Stop button goes with the last pending install.
endInstall(batch_id) {
const context = this.install_contexts.get(batch_id);
if (!context) {
return;
}
this.install_contexts.delete(batch_id);
context.btn.classList.remove("cmm-btn-loading");
for (const item of context.targets) {
this.grid.updateCell(item, "installed");
}
if (this.install_contexts.size == 0) {
this.hideLoading();
this.hideStop();
}
return context;
}
// The end of the queue was reported: a batch that was queued and has not ended was dropped
// by Stop. The report can also be that of a queue that ran before the batch was added, so
// the installs are ended only if the queue is not running now.
async endDroppedInstalls() {
const queued = [...this.install_contexts].filter(([, context]) => context.queued);
if (queued.length == 0) {
return;
}
// Without an answer the queue may still be running.
const { data } = await fetchData('/v2/manager/queue/status');
if (!data || data.is_processing) {
return;
}
let downloaded = false;
for (const [batch_id, context] of queued) {
if (this.endInstall(batch_id)) {
downloaded ||= context.targets.some(item => item.refresh);
}
this.showStop();
showTerminal();
}
if (downloaded) {
this.showRefresh();
this.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
}
}
async onQueueStatus(event) {
let self = ModelManager.instance;
const detail = event.detail;
if(event.detail.status == 'in_progress' && event.detail.ui_target == 'model_manager') {
const hash = event.detail.target;
if (!self) {
return;
}
if (detail.status == 'all-done') {
// An install whose request is not answered yet is looked at when it is.
for (const context of self.install_contexts.values()) {
context.queue_ended = !context.queued;
}
self.endDroppedInstalls();
return;
}
if (!self.install_contexts.has(detail.batch_id)) {
return;
}
if(detail.status == 'in_progress' && detail.ui_target == 'model_manager') {
const hash = detail.target;
const item = self.grid.getRowItemBy("hash", hash);
if (!item) return;
item.refresh = true;
self.grid.setRowSelected(item, false);
@@ -514,29 +607,20 @@ export class ModelManager {
// self.grid.updateCell(item, "tg-column-select");
self.grid.updateRow(item);
}
else if(event.detail.status == 'batch-done') {
self.hideStop();
self.onQueueCompleted(event.detail);
else if(detail.status == 'batch-done') {
self.onQueueCompleted(detail);
}
}
async onQueueCompleted(info) {
let result = info.model_result;
if(result.length == 0) {
return;
}
let self = ModelManager.instance;
if(!self.install_context) {
if(!self?.install_contexts.has(info.batch_id)) {
return;
}
self.endInstall(info.batch_id);
let btn = self.install_context.btn;
self.hideLoading();
btn.classList.remove("cmm-btn-loading");
const result = info.model_result ?? {};
let errorMsg = "";
@@ -544,26 +628,22 @@ export class ModelManager {
let v = result[hash];
if(v != 'success')
errorMsg += v + '\n';
}
for(let k in self.install_context.targets) {
let item = self.install_context.targets[k];
self.grid.updateCell(item, "installed");
errorMsg += sanitizeHTML(String(v)) + '\n';
}
if (errorMsg) {
self.showError(errorMsg);
show_message("Installation Error:\n"+errorMsg);
} else {
self.showStatus(`Install ${result.length} models successfully`);
self.showStatus(`Install ${Object.keys(result).length} models successfully`);
}
self.showRefresh();
self.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
if (!errorMsg) {
self.showMessage(`To apply the installed model, please click the 'Refresh' button.`, "red")
}
infoToast('Tasks done', `[ComfyUI-Manager] All model downloading tasks in the queue have been completed.\n${info.done_count}/${info.total_count}`);
self.install_context = undefined;
}
getModelList(models) {
@@ -720,22 +800,20 @@ export class ModelManager {
this.showMessage(err, "red");
}
// Messages contain HTML: preserve server-escaped names and escape raw values at the caller.
showMessage(msg, color) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
this.element.querySelector(".cmm-manager-message").innerHTML = msg;
const element = this.element.querySelector(".cmm-manager-message");
element.style.color = color || "";
element.innerHTML = msg ?? "";
}
showStatus(msg, color) {
if (color) {
msg = `<font color="${color}">${msg}</font>`;
}
this.element.querySelector(".cmm-manager-status").innerHTML = msg;
const element = this.element.querySelector(".cmm-manager-status");
element.style.color = color || "";
element.innerHTML = msg ?? "";
}
showLoading() {
// this.setDisabled(true);
if (this.grid) {
this.grid.showLoading();
this.grid.showMask({
@@ -745,45 +823,12 @@ export class ModelManager {
}
hideLoading() {
// this.setDisabled(false);
if (this.grid) {
this.grid.hideLoading();
this.grid.hideMask();
}
}
setDisabled(disabled) {
const $close = this.element.querySelector(".cmm-manager-close");
const $refresh = this.element.querySelector(".cmm-manager-refresh");
const $stop = this.element.querySelector(".cmm-manager-stop");
const list = [
".cmm-manager-header input",
".cmm-manager-header select",
".cmm-manager-footer button",
".cmm-manager-selection button"
].map(s => {
return Array.from(this.element.querySelectorAll(s));
})
.flat()
.filter(it => {
return it !== $close && it !== $refresh && it !== $stop;
});
list.forEach($elem => {
if (disabled) {
$elem.setAttribute("disabled", "disabled");
} else {
$elem.removeAttribute("disabled");
}
});
Array.from(this.element.querySelectorAll(".cmm-btn-loading")).forEach($elem => {
$elem.classList.remove("cmm-btn-loading");
});
}
showRefresh() {
this.element.querySelector(".cmm-manager-refresh").style.display = "block";
}
+25 -6
View File
@@ -92,6 +92,9 @@ function connect_inputs(nearest_inputs, node) {
}
function node_info_copy(src, dest, connect_both, copy_shape) {
// The graph the node is in. A subgraph keeps its own links and nodes.
const graph = src.graph;
// copy input connections
for(let i in src.inputs) {
let input = src.inputs[i];
@@ -100,9 +103,19 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
dest.convertWidgetToInput(destWidget);
}
if(input.link) {
let link = app.graph.links[input.link];
let src_node = app.graph.getNodeById(link.origin_id);
src_node.connect(link.origin_slot, dest.id, input.name);
let link = graph.links[input.link];
if(link.origin_id === graph.inputNode?.id) {
// The link starts at an input of the subgraph, which is not a node of the graph.
// Unlike a node's connect(), it takes any input, so the checks are made here.
let subgraph_input = graph.inputNode.slots[link.origin_slot];
let dest_input = dest.inputs[dest.findInputSlot(input.name)];
if(dest_input && LiteGraph.isValidConnection(subgraph_input.type, dest_input.type))
subgraph_input.connect(dest_input, dest);
}
else {
let src_node = graph.getNodeById(link.origin_id);
src_node.connect(link.origin_slot, dest, input.name);
}
}
}
@@ -114,7 +127,7 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
if(output.links) {
let links = [];
for(let j in output.links) {
links.push(app.graph.links[output.links[j]]);
links.push(graph.links[output.links[j]]);
}
output_links[output.name] = links;
}
@@ -125,8 +138,14 @@ function node_info_copy(src, dest, connect_both, copy_shape) {
if(links) {
for(let j in links) {
let link = links[j];
let target_node = app.graph.getNodeById(link.target_id);
dest.connect(parseInt(i), target_node, link.target_slot);
if(link.target_id === graph.outputNode?.id) {
// The link ends at an output of the subgraph, whose connect() checks the type itself.
graph.outputNode.slots[link.target_slot].connect(dest.outputs[i], dest);
}
else {
let target_node = graph.getNodeById(link.target_id);
dest.connect(parseInt(i), target_node, link.target_slot);
}
}
}
}
+31 -17
View File
@@ -1,35 +1,48 @@
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js"
import { ComfyDialog, $el } from "../../scripts/ui.js";
import { manager_instance, rebootAPI, show_message, loadCss } from "./common.js";
import { manager_instance, rebootAPI, show_message, loadCss, sanitizeHTML } from "./common.js";
import { buildGuiFrame } from "./comfyui-gui-builder.js";
loadCss("./snapshot.css");
// The server gives its reason as plain text, and most refusals carry none.
// For those, and for the error page of a proxy, show the status line.
async function failureReason(response) {
const plain = (response.headers.get('Content-Type') || '').startsWith('text/plain');
const text = plain ? await response.text() : '';
return sanitizeHTML(text || `HTTP ${response.status} ${response.statusText}`.trim());
}
async function restore_snapshot(target) {
if(SnapshotManager.instance) {
let scheduled = false;
try {
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', cache: "no-store" });
const response = await api.fetchApi(`/v2/snapshot/restore?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
if(response.status == 403) {
show_message('This action is not allowed with this security level configuration.');
return false;
}
if(response.status == 400) {
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
if(!response.ok) {
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
return false;
}
app.ui.dialog.close();
scheduled = true;
return true;
}
catch(exception) {
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
show_message(`Restore snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
return false;
}
finally {
await SnapshotManager.instance.invalidateControl();
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='p-button p-component'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
if(scheduled) {
SnapshotManager.instance.updateMessage("<BR>To apply the snapshot, please <button id='cm-reboot-button2' class='cm-ui-button'>RESTART</button> ComfyUI. And refresh browser.", 'cm-reboot-button2');
}
}
}
}
@@ -37,22 +50,23 @@ async function restore_snapshot(target) {
async function remove_snapshot(target) {
if(SnapshotManager.instance) {
try {
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', cache: "no-store" });
const response = await api.fetchApi(`/v2/snapshot/remove?target=${target}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
if(response.status == 403) {
show_message('This action is not allowed with this security level configuration.');
return false;
}
if(response.status == 400) {
show_message(`Remove snapshot failed: ${target.title} / ${exception}`);
if(!response.ok) {
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${await failureReason(response)}`);
return false;
}
app.ui.dialog.close();
return true;
}
catch(exception) {
show_message(`Restore snapshot failed: ${target.title} / ${exception}`);
show_message(`Remove snapshot failed: ${sanitizeHTML(String(target))} / ${sanitizeHTML(String(exception))}`);
return false;
}
finally {
@@ -63,7 +77,7 @@ async function remove_snapshot(target) {
async function save_current_snapshot() {
try {
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', cache: "no-store" });
const response = await api.fetchApi('/v2/snapshot/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, cache: "no-store" });
app.ui.dialog.close();
return true;
}
@@ -122,7 +136,7 @@ export class SnapshotManager extends ComfyDialog {
createControls() {
return [
$el("button.p-button.p-component", {
$el("button.cm-ui-button", {
type: "button",
textContent: "Close",
onclick: () => { this.close(); }
@@ -133,7 +147,7 @@ export class SnapshotManager extends ComfyDialog {
startRestore(target) {
const self = SnapshotManager.instance;
self.updateMessage(`<BR><font color="green">Restore snapshot '${target.name}'</font>`);
self.updateMessage(`<BR><font color="green">Restore snapshot '${sanitizeHTML(String(target.name ?? ''))}'</font>`);
for(let i in self.restore_buttons) {
self.restore_buttons[i].disabled = true;
@@ -214,13 +228,13 @@ export class SnapshotManager extends ComfyDialog {
data1.style.textAlign = "center";
data1.innerHTML = i+1;
var data2 = document.createElement('td');
data2.innerHTML = `&nbsp;${data}`;
data2.textContent = `\u00a0${data}`;
var data_button = document.createElement('td');
data_button.style.textAlign = "center";
data_button.className = "data-btns";
var restoreBtn = document.createElement('button');
restoreBtn.className = "snapshot-restore-btn p-button p-component";
restoreBtn.className = "snapshot-restore-btn cm-ui-button";
restoreBtn.innerHTML = 'Restore';
restoreBtn.style.width = "100px";
@@ -229,7 +243,7 @@ export class SnapshotManager extends ComfyDialog {
});
var removeBtn = document.createElement('button');
removeBtn.className = "snapshot-remove-btn p-button p-component";
removeBtn.className = "snapshot-remove-btn cm-ui-button";
removeBtn.innerHTML = 'Remove';
removeBtn.style.width = "100px";
@@ -279,7 +293,7 @@ export class SnapshotManager extends ComfyDialog {
async createBottomControls() {
var save_button = document.createElement("button");
save_button.className = "p-button p-component";
save_button.className = "cm-ui-button";
save_button.innerHTML = "Save snapshot";
save_button.onclick = () => { save_current_snapshot(); }
save_button.style.horizontalAlign = "right";
+1 -1
View File
@@ -67,7 +67,7 @@ class WorkflowMetadataExtension {
this.installedNodes[nodePackageName.toLowerCase()] ??
{};
if (cnr_id === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id?.toLowerCase() === "comfy-core") return; // don't allow hijacking comfy-core name
if (cnr_id) nodeProperties.cnr_id = cnr_id;
else nodeProperties.aux_id = aux_id;
if (ver) nodeProperties.ver = ver.trim();
+82
View File
@@ -0,0 +1,82 @@
"""HTML rendering helpers used only by the legacy Manager UI."""
import re
from html import escape, unescape
from html.entities import html5
SAFE_URL_SCHEMES = frozenset({'http', 'https'})
_URL_SCHEME_NOISE = re.compile(r'[\x00-\x20\x7f]')
_URL_HEAD_DELIMITERS = ('/', '?', '#')
def escape_html_attribute(value):
"""Escape a value for a quoted HTML attribute."""
return escape(str(value), quote=True)
_HTML_ENTITY = re.compile(r'&(#[0-9]+|#[xX][0-9a-fA-F]+|[A-Za-z][A-Za-z0-9]*);')
_HTML_TEXT_TOKEN = re.compile(_HTML_ENTITY.pattern + "|[&<>\"']")
def unescape_html_entities(text):
"""Decode complete entities once, leaving query keys such as &notebook intact."""
def replace(match):
entity = match.group(1)
if entity.startswith('#'):
return unescape(match.group(0))
return html5.get(entity + ';', match.group(0))
return _HTML_ENTITY.sub(replace, text)
def escape_html_text(value):
"""Escape HTML text without double-escaping existing entities."""
return _HTML_TEXT_TOKEN.sub(
lambda m: m.group(0) if m.group(1) else escape_html_attribute(m.group(0)),
str(value),
)
def sanitize_url(url):
"""Allow HTTP(S), relative URLs and anchors.
HTML callers must also escape the result as an attribute."""
raw = '' if url is None else str(url)
probe = _URL_SCHEME_NOISE.sub('', raw)
if not probe:
return '#'
cut = len(probe)
for delimiter in _URL_HEAD_DELIMITERS:
found = probe.find(delimiter)
if found != -1:
cut = min(cut, found)
head = probe[:cut]
if ':' in head:
return raw.strip() if head.split(':', 1)[0].lower() in SAFE_URL_SCHEMES else '#'
return raw.strip()
def sanitize_html_fragment(fragment):
"""Sanitize notice HTML, preserving its formatting and opening links safely."""
# Keep nh3 loading within the legacy notice path.
import nh3
return nh3.clean(
'' if fragment is None else str(fragment),
tags=nh3.ALLOWED_TAGS | {'font'},
attributes={
**nh3.ALLOWED_ATTRIBUTES,
'*': {'class', 'title', 'align', 'width', 'height'},
'font': {'color'},
},
# These elements previously hid their contents from the notice.
clean_content_tags={
'script', 'style', 'iframe', 'object', 'embed', 'svg', 'math',
'template', 'noscript', 'textarea', 'title',
},
url_schemes=SAFE_URL_SCHEMES,
set_tag_attribute_values={'a': {'target': '_blank'}},
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+54 -244
View File
@@ -1,12 +1,11 @@
import mimetypes
from ..common import context
from ..common import manager_security
from . import manager_core as core
import os
from aiohttp import web
import aiohttp
import json
import hashlib
import folder_paths
from server import PromptServer
@@ -22,69 +21,33 @@ except Exception:
matrix_nio_is_available = False
def extract_model_file_names(json_data):
"""Extract unique file names from the input JSON data."""
file_names = set()
model_filename_extensions = {'.safetensors', '.ckpt', '.pt', '.pth', '.bin'}
# Recursively search for file names in the JSON data
def recursive_search(data):
if isinstance(data, dict):
for value in data.values():
recursive_search(value)
elif isinstance(data, list):
for item in data:
recursive_search(item)
elif isinstance(data, str) and '.' in data:
file_names.add(os.path.basename(data)) # file_names.add(data)
recursive_search(json_data)
return [f for f in list(file_names) if os.path.splitext(f)[1] in model_filename_extensions]
def find_file_paths(base_dir, file_names):
"""Find the paths of the files in the base directory."""
file_paths = {}
for root, dirs, files in os.walk(base_dir):
# Exclude certain directories
dirs[:] = [d for d in dirs if d not in ['.git']]
for file in files:
if file in file_names:
file_paths[file] = os.path.join(root, file)
return file_paths
def compute_sha256_checksum(filepath):
"""Compute the SHA256 checksum of a file, in chunks"""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
SHARE_OPTIONS = ('all', 'none', 'youml', 'matrix')
@PromptServer.instance.routes.get("/v2/manager/share_option")
async def share_option(request):
if "value" in request.rel_url.query:
core.get_config()['share_option'] = request.rel_url.query['value']
core.write_config()
else:
return web.Response(text=core.get_config()['share_option'], status=200)
return web.Response(text=core.get_config()['share_option'], status=200)
@PromptServer.instance.routes.post("/v2/manager/share_option")
async def set_share_option(request):
rejection = manager_security.reject_non_json_post(request)
if rejection is not None:
return rejection
try:
value = (await request.json())['value']
except (json.JSONDecodeError, UnicodeDecodeError, KeyError, TypeError):
return web.Response(status=400, text='Invalid request')
if value not in SHARE_OPTIONS:
return web.Response(status=400, text='Invalid request')
core.get_config()['share_option'] = value
core.write_config()
return web.Response(status=200)
def get_openart_auth():
if not os.path.exists(os.path.join(context.manager_files_path, ".openart_key")):
return None
try:
with open(os.path.join(context.manager_files_path, ".openart_key"), "r") as f:
openart_key = f.read().strip()
return openart_key if openart_key else None
except Exception:
return None
def is_matrix_org(homeserver):
return homeserver.replace("http://", "https://").removeprefix("https://") == "matrix.org"
def get_matrix_auth():
@@ -94,7 +57,7 @@ def get_matrix_auth():
with open(os.path.join(context.manager_files_path, "matrix_auth"), "r") as f:
matrix_auth = f.read()
homeserver, username, password = matrix_auth.strip().split("\n")
if not homeserver or not username or not password:
if not is_matrix_org(homeserver) or not username or not password:
return None
return {
"homeserver": homeserver,
@@ -105,101 +68,12 @@ def get_matrix_auth():
return None
def get_comfyworkflows_auth():
if not os.path.exists(os.path.join(context.manager_files_path, "comfyworkflows_sharekey")):
return None
try:
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "r") as f:
share_key = f.read()
if not share_key.strip():
return None
return share_key
except Exception:
return None
def get_youml_settings():
if not os.path.exists(os.path.join(context.manager_files_path, ".youml")):
return None
try:
with open(os.path.join(context.manager_files_path, ".youml"), "r") as f:
youml_settings = f.read().strip()
return youml_settings if youml_settings else None
except Exception:
return None
def set_youml_settings(settings):
with open(os.path.join(context.manager_files_path, ".youml"), "w") as f:
f.write(settings)
@PromptServer.instance.routes.get("/v2/manager/get_openart_auth")
async def api_get_openart_auth(request):
# print("Getting stored Matrix credentials...")
openart_key = get_openart_auth()
if not openart_key:
return web.Response(status=404)
return web.json_response({"openart_key": openart_key})
@PromptServer.instance.routes.post("/v2/manager/set_openart_auth")
async def api_set_openart_auth(request):
json_data = await request.json()
openart_key = json_data['openart_key']
with open(os.path.join(context.manager_files_path, ".openart_key"), "w") as f:
f.write(openart_key)
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_matrix_auth")
async def api_get_matrix_auth(request):
# print("Getting stored Matrix credentials...")
matrix_auth = get_matrix_auth()
if not matrix_auth:
return web.Response(status=404)
return web.json_response(matrix_auth)
@PromptServer.instance.routes.get("/v2/manager/youml/settings")
async def api_get_youml_settings(request):
youml_settings = get_youml_settings()
if not youml_settings:
return web.Response(status=404)
return web.json_response(json.loads(youml_settings))
@PromptServer.instance.routes.post("/v2/manager/youml/settings")
async def api_set_youml_settings(request):
json_data = await request.json()
set_youml_settings(json.dumps(json_data))
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_comfyworkflows_auth")
async def api_get_comfyworkflows_auth(request):
# Check if the user has provided Matrix credentials in a file called 'matrix_accesstoken'
# in the same directory as the ComfyUI base folder
# print("Getting stored Comfyworkflows.com auth...")
comfyworkflows_auth = get_comfyworkflows_auth()
if not comfyworkflows_auth:
return web.Response(status=404)
return web.json_response({"comfyworkflows_sharekey": comfyworkflows_auth})
@PromptServer.instance.routes.post("/v2/manager/set_esheep_workflow_and_images")
async def set_esheep_workflow_and_images(request):
json_data = await request.json()
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), "w", encoding='utf-8') as file:
json.dump(json_data, file, indent=4)
return web.Response(status=200)
@PromptServer.instance.routes.get("/v2/manager/get_esheep_workflow_and_images")
async def get_esheep_workflow_and_images(request):
with open(os.path.join(context.manager_files_path, "esheep_share_message.json"), 'r', encoding='utf-8') as file:
data = json.load(file)
return web.Response(status=200, text=json.dumps(data))
return web.json_response({"homeserver": matrix_auth["homeserver"], "username": matrix_auth["username"]})
@PromptServer.instance.routes.get("/v2/manager/get_matrix_dep_status")
@@ -211,42 +85,42 @@ async def get_matrix_dep_status(request):
def set_matrix_auth(json_data):
homeserver = json_data['homeserver']
username = json_data['username']
password = json_data['password']
with open(os.path.join(context.manager_files_path, "matrix_auth"), "w") as f:
f.write("\n".join([homeserver, username, password]))
def set_comfyworkflows_auth(comfyworkflows_sharekey):
with open(os.path.join(context.manager_files_path, "comfyworkflows_sharekey"), "w") as f:
f.write(comfyworkflows_sharekey)
path = os.path.join(context.manager_files_path, "matrix_auth")
# The mode of os.open is for a new file; a file that is there gets the mode before the password is written.
with open(os.open(path, os.O_WRONLY | os.O_CREAT, 0o600), "w") as f:
try:
os.chmod(path, 0o600)
except OSError:
pass # a file of another owner keeps its mode
f.truncate()
f.write("\n".join(["matrix.org", username, password]))
def has_provided_matrix_auth(matrix_auth):
return matrix_auth['homeserver'].strip() and matrix_auth['username'].strip() and matrix_auth['password'].strip()
def has_provided_comfyworkflows_auth(comfyworkflows_sharekey):
return comfyworkflows_sharekey.strip()
@PromptServer.instance.routes.post("/v2/manager/share")
async def share_art(request):
# get json data
rejection = manager_security.reject_non_json_post(request)
if rejection is not None:
return rejection
json_data = await request.json()
matrix_auth = json_data['matrix_auth']
comfyworkflows_sharekey = json_data['cw_auth']['cw_sharekey']
set_matrix_auth(matrix_auth)
set_comfyworkflows_auth(comfyworkflows_sharekey)
saved = get_matrix_auth()
if saved and not matrix_auth['password'] and matrix_auth['username'] == saved['username']:
matrix_auth['password'] = saved['password']
share_destinations = json_data['share_destinations']
credits = json_data['credits']
title = json_data['title']
description = json_data['description']
is_nsfw = json_data['is_nsfw']
prompt = json_data['prompt']
potential_outputs = json_data['potential_outputs']
selected_output_index = json_data['selected_output_index']
@@ -275,79 +149,20 @@ async def share_art(request):
else:
asset_filepath = os.path.join(output_dir, asset_filename)
# The filename and the subfolder come from the request: share only a file in that directory.
# Like ComfyUI's /view, this follows a symlink that the user placed in the directory.
output_dir = os.path.abspath(output_dir)
asset_filepath = os.path.abspath(asset_filepath)
try:
is_inside = os.path.commonpath((output_dir, asset_filepath)) == output_dir
except ValueError: # on Windows, a path on another drive
is_inside = False
if not is_inside:
return web.json_response({"error": "The selected output is not in the output directory."}, content_type='application/json', status=400)
# get the mime type of the asset
assetFileType = mimetypes.guess_type(asset_filepath)[0]
share_website_host = "UNKNOWN"
if "comfyworkflows" in share_destinations:
share_website_host = "https://comfyworkflows.com"
share_endpoint = f"{share_website_host}/api"
# get presigned urls
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.post(
f"{share_endpoint}/get_presigned_urls",
json={
"assetFileName": asset_filename,
"assetFileType": assetFileType,
"workflowJsonFileName": 'workflow.json',
"workflowJsonFileType": 'application/json',
},
) as resp:
assert resp.status == 200
presigned_urls_json = await resp.json()
assetFilePresignedUrl = presigned_urls_json["assetFilePresignedUrl"]
assetFileKey = presigned_urls_json["assetFileKey"]
workflowJsonFilePresignedUrl = presigned_urls_json["workflowJsonFilePresignedUrl"]
workflowJsonFileKey = presigned_urls_json["workflowJsonFileKey"]
# upload asset
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.put(assetFilePresignedUrl, data=open(asset_filepath, "rb")) as resp:
assert resp.status == 200
# upload workflow json
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
async with session.put(workflowJsonFilePresignedUrl, data=json.dumps(prompt['workflow']).encode('utf-8')) as resp:
assert resp.status == 200
model_filenames = extract_model_file_names(prompt['workflow'])
model_file_paths = find_file_paths(folder_paths.base_path, model_filenames)
models_info = {}
for filename, filepath in model_file_paths.items():
models_info[filename] = {
"filename": filename,
"sha256_checksum": compute_sha256_checksum(filepath),
"relative_path": os.path.relpath(filepath, folder_paths.base_path),
}
# make a POST request to /api/upload_workflow with form data key values
async with aiohttp.ClientSession(trust_env=True, connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
form = aiohttp.FormData()
if comfyworkflows_sharekey:
form.add_field("shareKey", comfyworkflows_sharekey)
form.add_field("source", "comfyui_manager")
form.add_field("assetFileKey", assetFileKey)
form.add_field("assetFileType", assetFileType)
form.add_field("workflowJsonFileKey", workflowJsonFileKey)
form.add_field("sharedWorkflowWorkflowJsonString", json.dumps(prompt['workflow']))
form.add_field("sharedWorkflowPromptJsonString", json.dumps(prompt['output']))
form.add_field("shareWorkflowCredits", credits)
form.add_field("shareWorkflowTitle", title)
form.add_field("shareWorkflowDescription", description)
form.add_field("shareWorkflowIsNSFW", str(is_nsfw).lower())
form.add_field("currentSnapshot", json.dumps(await core.get_current_snapshot()))
form.add_field("modelsInfo", json.dumps(models_info))
async with session.post(
f"{share_endpoint}/upload_workflow",
data=form,
) as resp:
assert resp.status == 200
upload_workflow_json = await resp.json()
workflowId = upload_workflow_json["workflowId"]
# check if the user has provided Matrix credentials
if matrix_nio_is_available and "matrix" in share_destinations:
comfyui_share_room_id = '!LGYSoacpJPhIfBqVfb:matrix.org'
@@ -355,14 +170,10 @@ async def share_art(request):
content_type = assetFileType
try:
homeserver = 'matrix.org'
if matrix_auth:
homeserver = matrix_auth.get('homeserver', 'matrix.org')
homeserver = homeserver.replace("http://", "https://")
if not homeserver.startswith("https://"):
homeserver = "https://" + homeserver
if not is_matrix_org(matrix_auth.get('homeserver', 'matrix.org')):
return web.json_response({"error": "Only an account of matrix.org can share."}, content_type='application/json', status=400)
client = AsyncClient(homeserver, matrix_auth['username'])
client = AsyncClient("https://matrix.org", matrix_auth['username'])
# Login
login_resp = await client.login(matrix_auth['password'])
@@ -370,6 +181,8 @@ async def share_art(request):
await client.close()
return web.json_response({"error": "Invalid Matrix credentials."}, content_type='application/json', status=400)
set_matrix_auth(matrix_auth)
# Upload asset
with open(asset_filepath, 'rb') as f:
upload_resp, _maybe_keys = await client.upload(f, content_type=content_type, filename=filename)
@@ -442,9 +255,6 @@ async def share_art(request):
return web.json_response({"error": "An error occurred when sharing your art to Matrix."}, content_type='application/json', status=500)
return web.json_response({
"comfyworkflows": {
"url": None if "comfyworkflows" not in share_destinations else f"{share_website_host}/workflows/{workflowId}",
},
"matrix": {
"success": None if "matrix" not in share_destinations else True
}
+195 -123
View File
@@ -16,6 +16,7 @@ from .common import security_check
from .common import manager_util
from .common import cm_global
from .common import manager_downloader
from .common import manager_security
from .common.timestamp_utils import current_timestamp
import folder_paths
@@ -34,6 +35,11 @@ message_collapses = [skip_pip_spam]
import_failed_extensions = set()
cm_global.variables['cm.on_revision_detected_handler'] = []
enable_file_logging = True
# When file logging is on, strip ANSI color/escape codes from the bytes written to
# the disk log so the file stays plain and readable. The console ALWAYS keeps its
# original (colored) output -- this only ever touches the file branch of sync_write.
# Default on; set `strip_ansi_file_logging = False` in config.ini to keep ANSI in the file.
strip_ansi_file_logging = True
def register_message_collapse(f):
@@ -67,6 +73,7 @@ comfyui_manager_path = os.path.abspath(os.path.dirname(__file__))
custom_nodes_base_path = folder_paths.get_folder_paths('custom_nodes')[0]
manager_files_path = folder_paths.get_system_user_directory("manager")
manager_security.ensure_nodepack_whitelist(manager_files_path)
manager_pip_overrides_path = os.path.join(manager_files_path, "pip_overrides.json")
manager_pip_blacklist_path = os.path.join(manager_files_path, "pip_blacklist.list")
restore_snapshot_path = os.path.join(manager_files_path, "startup-scripts", "restore-snapshot.json")
@@ -78,7 +85,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:
@@ -93,17 +100,48 @@ def read_unified_resolver_mode():
if 'use_unified_resolver' in default_conf:
manager_util.use_unified_resolver = default_conf['use_unified_resolver'].lower() == 'true'
def read_dependency_management_mode():
# Config: [default] dependency_management = on|off (default on).
# Env override: COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT=on|off wins over config.
# `off` opts out of automatic Python-package mutation Manager performs at
# startup (PIPFixer auto-heal, unified resolver batch).
# Intended for distro-packaged / externally-managed Python environments
# where the interpreter is read-only (Nix, Guix, system packages, etc.).
manager_util.apply_dependency_management_setting(default_conf.get('dependency_management'))
if not manager_util.dependency_management_enabled:
logging.info("[ComfyUI-Manager] dependency management disabled; auto-install/upgrade/uninstall paths will be skipped.")
def check_file_logging():
global enable_file_logging
if 'file_logging' in default_conf and default_conf['file_logging'].lower() == 'false':
enable_file_logging = False
def check_strip_ansi_file_logging():
global strip_ansi_file_logging
if 'strip_ansi_file_logging' in default_conf and default_conf['strip_ansi_file_logging'].lower() == 'false':
strip_ansi_file_logging = False
def set_git_executable():
# read as written: a path of Windows may hold a `%`, which the parser takes as the start of a reference
git_exe = default_conf.get('git_exe', '', raw=True) if 'git_exe' in default_conf else ''
if git_exe != '':
os.environ['GIT_EXE_PATH'] = git_exe
read_config()
set_git_executable()
from .common import git_compat # noqa: E402
print(git_compat.BACKEND_LINE, file=sys.stderr)
read_uv_mode()
read_unified_resolver_mode()
read_dependency_management_mode()
security_check.security_check()
check_file_logging()
check_strip_ansi_file_logging()
# Module-level flag set by startup batch resolver when it succeeds.
# Used by execute_lazy_install_script() to skip per-node pip installs.
@@ -124,15 +162,6 @@ if os.path.exists(manager_pip_blacklist_path):
cm_global.pip_blacklist.add(y)
def remap_pip_package(pkg):
if pkg in cm_global.pip_overrides:
res = cm_global.pip_overrides[pkg]
print(f"[ComfyUI-Manager] '{pkg}' is remapped to '{res}'")
return res
else:
return pkg
std_log_lock = threading.Lock()
@@ -259,6 +288,10 @@ try:
pat_tqdm = r'\d+%.*\[(.*?)\]'
pat_import_fail = r'seconds \(IMPORT FAILED\):(.*)$'
# CSI (ECMA-48) escape sequences: ESC [ <params: digits/;/> <?> <final letter>.
# Covers SGR color codes (m), cursor moves, clears, and the tqdm/progress-bar
# control codes that also land in the startup log.
pat_ansi = r'\x1b\[[0-9;?]*[a-zA-Z]'
is_start_mode = True
@@ -268,6 +301,7 @@ try:
self.is_stdout = is_stdout
self.encoding = "utf-8"
self.last_char = ''
self.console_is_gone = False
def fileno(self):
try:
@@ -280,7 +314,36 @@ try:
raise ValueError("The object does not have a fileno method")
def isatty(self):
return False
# Delegate to the real console we wrap, not a hardcoded False.
# Returning False here made colorama (and any ANSI-aware lib) believe
# the stream is a pipe and strip every ANSI code from the print() path
# in both the console and the file log. The console still receives the
# text unchanged -- this only tells colorama the truth about the target.
stream = original_stdout if self.is_stdout else original_stderr
try:
return stream.isatty()
except (AttributeError, ValueError, OSError):
return False
@property
def closed(self):
# Same reasoning as isatty(): without this attribute, colorama's
# StreamWrapper.closed falls back to True (AttributeError -> closed),
# which again forces strip=True. Report the real underlying state.
if log_file.closed:
# after close_log() nothing can be written through this logger;
# colorama, which keeps it, would write its reset at exit
return True
stream = original_stdout if self.is_stdout else original_stderr
try:
return stream.closed
except AttributeError:
# the output still goes to a stream that cannot say whether it is closed
return False
except ValueError:
# a detached stream
return True
def write(self, message):
global is_start_mode
@@ -312,36 +375,60 @@ try:
if '100%' in message:
self.sync_write(message)
else:
write_stderr(message)
original_stderr.flush()
self.write_console(message)
else:
self.sync_write(message)
else:
self.sync_write(message)
def write_console(self, message):
# A console that is gone does not come back, and ComfyUI's stream keeps every write
# it could not flush, so it is not written to again.
if self.console_is_gone:
return
try:
if self.is_stdout:
write_stdout(message)
original_stdout.flush()
else:
write_stderr(message)
original_stderr.flush()
except BlockingIOError:
pass
except OSError:
self.console_is_gone = True
def _file_message(self, message):
# The disk log is the ONLY place file content and console content are
# allowed to diverge: here we drop ANSI so the file stays plain text.
# The console path below always uses the
# original, unmodified message, so its coloring is never affected.
if strip_ansi_file_logging:
return re.sub(pat_ansi, '', message)
return message
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:
file_message = self._file_message(message)
timestamp = current_timestamp()
if self.last_char != '\n':
log_file.write(file_message)
else:
log_file.write(f"[{timestamp}] {file_message}")
try:
log_file.flush()
except Exception:
pass
try:
log_file.flush()
except Exception:
pass
self.last_char = message if message == '' else message[-1]
if not file_only:
with std_log_lock:
if self.is_stdout:
write_stdout(message)
original_stdout.flush()
else:
write_stderr(message)
original_stderr.flush()
self.write_console(message)
def flush(self):
try:
@@ -368,12 +455,15 @@ try:
def close_log(self):
sys.stderr = original_stderr
sys.stdout = original_stdout
log_file.close()
with log_lock:
log_file.close()
def close_log():
sys.stderr = original_stderr
sys.stdout = original_stdout
log_file.close()
# a write that has found the file open finishes first
with log_lock:
log_file.close()
if enable_file_logging:
@@ -394,8 +484,12 @@ try:
try:
message = record.getMessage()
except Exception as e:
message = f"<<logging error>>: {record} - {e}"
original_stderr.write(message)
try:
error = f"{type(e).__name__}: {e}"
except Exception:
# an error can carry the message that cannot be turned into text
error = type(e).__name__
message = f"<<logging error>>: {record.pathname}:{record.lineno} - {error}"
if is_start_mode:
match = re.search(pat_import_fail, message)
@@ -486,53 +580,34 @@ script_list_path = os.path.join(manager_files_path, "startup-scripts", "install-
pip_fixer = manager_util.PIPFixer(manager_util.get_installed_packages(), comfy_path, manager_files_path)
def is_installed(name):
def is_installed(name, reinstall=False):
name = name.strip()
if name.startswith('#'):
return True
pattern = r'([^<>!~=]+)([<>!~=]=?)([0-9.a-zA-Z]*)'
match = re.search(pattern, name)
if match:
name = match.group(1)
if name in cm_global.pip_blacklist:
reason = manager_util.pip_block_reason(name, cm_global.pip_blacklist, cm_global.pip_downgrade_blacklist)
if reason is not None:
if reason == 'downgrade blacklisted':
print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
return True
if name in cm_global.pip_downgrade_blacklist:
pips = manager_util.get_installed_packages()
pkg_name, extras, clauses = manager_util.parse_pip_spec(name)
if extras:
return False # extras to add: let pip decide
if match is None:
if name in pips:
return True
elif match.group(2) in ['<=', '==', '<', '~=']:
if name in pips:
if manager_util.StrictVersion(pips[name]) >= manager_util.StrictVersion(match.group(3)):
print(f"[ComfyUI-Manager] skip black listed pip installation: '{name}'")
return True
if clauses and clauses[0][0] == '@':
return not reinstall and manager_util.installed_from(clauses[0][1], pkg_name) is not None
pkg = manager_util.get_installed_packages().get(name.lower())
if pkg_name is None:
return False # a path or an option: let pip decide
pkg = manager_util.get_installed_packages().get(pkg_name)
if pkg is None:
return False # update if not installed
if match is None:
return True # don't update if version is not specified
if match.group(2) in ['>', '>=']:
if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
return False
elif manager_util.StrictVersion(pkg) > manager_util.StrictVersion(match.group(3)):
print(f"[SKIP] Downgrading pip package isn't allowed: {name.lower()} (cur={pkg})")
if match.group(2) == '==':
if manager_util.StrictVersion(pkg) < manager_util.StrictVersion(match.group(3)):
return False
if match.group(2) == '~=':
if manager_util.StrictVersion(pkg) == manager_util.StrictVersion(match.group(3)):
return False
if manager_util.requires_newer_version(clauses, pkg):
return False
return True # prevent downgrade
@@ -570,7 +645,15 @@ if os.path.exists(restore_snapshot_path):
if 'COMFYUI_PATH' not in new_env:
new_env['COMFYUI_PATH'] = os.path.dirname(folder_paths.__file__)
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path]
from comfy.cli_args import args
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
new_env['_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED'] = str(
allow_flagged or manager_security.is_loopback_listener(args.listen)
).lower()
new_env['_COMFYUI_MANAGER_CNR_WHITELIST_DIR'] = manager_files_path
cmd_str = [sys.executable, '-m', 'cm_cli', 'restore-snapshot', restore_snapshot_path,
'--user-directory', manager_files_path, '--restore-to', custom_nodes_base_path]
exit_code = process_wrap(cmd_str, custom_nodes_base_path, handler=msg_capture, env=new_env)
if exit_code != 0:
@@ -597,16 +680,9 @@ def execute_lazy_install_script(repo_path, executable):
lines = manager_util.robust_readlines(requirements_path)
for line in lines:
package_name = remap_pip_package(line.strip())
package_name = package_name.split('#')[0].strip()
if package_name and not is_installed(package_name):
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
else:
install_cmd = manager_util.make_pip_cmd(["install", package_name])
process_wrap(install_cmd, repo_path)
install_args = manager_util.pip_install_args(line, cm_global.pip_overrides)
if install_args and not is_installed(install_args[0]):
process_wrap(manager_util.make_pip_cmd(["install", *install_args]), repo_path)
if os.path.exists(install_script_path) and f'{repo_path}/install.py' not in processed_install:
processed_install.add(f'{repo_path}/install.py')
@@ -619,18 +695,30 @@ def execute_lazy_install_script(repo_path, executable):
process_wrap(install_cmd, repo_path, env=new_env)
def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom_nodes_path):
def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom_nodes_path, status=''):
import uuid
import shutil
from comfy.cli_args import args
allow_flagged = default_conf.get('allow_flagged_nodepack_install', '').lower() == 'true'
if not manager_security.is_cnr_install_allowed(
status or 'NodeVersionStatusFlagged', allow_flagged, args.listen,
node_id=target, manager_files_path=manager_files_path):
if not status:
logging.error("Cannot execute reserved CNR switch for '%s': stored Registry status is missing. Request the installation again so its current status can be checked.", target)
else:
logging.error(manager_security.FLAGGED_NODEPACK_INSTALL_GUIDANCE)
return False
# 1. download
archive_name = f"CNR_temp_{str(uuid.uuid4())}.zip" # should be unpredictable name - security precaution
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:
@@ -639,36 +727,16 @@ def execute_lazy_cnr_switch(target, zip_url, from_path, to_path, no_deps, custom
print(f'Empty archive file: {target}')
return False
if from_path != to_path:
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 3. calculate garbage files (.tracking - extracted)
tracking_info_file = os.path.join(from_path, '.tracking')
prev_files = set()
with open(tracking_info_file, 'r') as f:
for line in f:
prev_files.add(line.strip())
garbage = prev_files.difference(extracted)
garbage = [os.path.join(custom_nodes_path, x) for x in garbage]
# 4-1. remove garbage files
for x in garbage:
if os.path.isfile(x):
os.remove(x)
# 4-2. remove garbage dir if empty
for x in garbage:
if os.path.isdir(x):
if not os.listdir(x):
os.rmdir(x)
# 5. rename dir name <node_id>@<prev_ver> ==> <node_id>@<cur_ver>
print(f"'{from_path}' is moved to '{to_path}'")
shutil.move(from_path, to_path)
# 6. create .tracking file
tracking_info_file = os.path.join(to_path, '.tracking')
with open(tracking_info_file, "w", encoding='utf-8') as file:
file.write('\n'.join(list(extracted)))
return True
script_executed = False
@@ -724,26 +792,35 @@ def execute_startup_script():
execute_lazy_install_script(script[0], script[2])
elif script[1] == "#LAZY-CNR-SWITCH-SCRIPT":
execute_lazy_cnr_switch(script[0], script[2], script[3], script[4], script[5], script[6])
execute_lazy_install_script(script[3], script[7])
status = script[8] if len(script) > 8 else ''
to_path = script[4]
if execute_lazy_cnr_switch(script[0], script[2], script[3], to_path, script[5], script[6], status):
execute_lazy_install_script(to_path, script[7])
elif script[1] == "#LAZY-DELETE-NODEPACK":
execute_lazy_delete(script[2])
elif os.path.exists(script[0]):
reinstall = False
if script[1] == "#FORCE":
del script[1]
else:
if 'pip' in script[1:] and 'install' in script[1:] and is_installed(script[-1]):
reinstall = manager_util.is_reinstall(script[1:])
requirement = manager_util.pip_install_requirement(script[1:])
if requirement is not None and is_installed(requirement, reinstall):
continue
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
if not reinstall:
print(f"\n## ComfyUI-Manager: EXECUTE => {script[1:]}")
print(f"\n## Execute management script for '{script[0]}'")
new_env = os.environ.copy()
if 'COMFYUI_FOLDERS_BASE_PATH' not in new_env:
new_env["COMFYUI_FOLDERS_BASE_PATH"] = comfy_path
exit_code = process_wrap(script[1:], script[0], env=new_env)
if reinstall:
exit_code = manager_util.reinstall(script[1:], lambda cmd: process_wrap(cmd, script[0], env=new_env))
else:
exit_code = process_wrap(script[1:], script[0], env=new_env)
if exit_code != 0:
print(f"management script failed: {script[0]}")
@@ -764,7 +841,10 @@ def execute_startup_script():
# --- Unified dependency resolver: batch resolution at startup ---
# Runs unconditionally when enabled, independent of install-scripts.txt existence.
if manager_util.use_unified_resolver:
if manager_util.use_unified_resolver and not manager_util.dependency_management_enabled:
logging.info("[ComfyUI-Manager] dependency management disabled; skipping unified dependency resolver, installs use per-node pip")
manager_util.use_unified_resolver = False
elif manager_util.use_unified_resolver:
try:
from .common.unified_dep_resolver import (
UnifiedDepResolver,
@@ -816,15 +896,7 @@ if script_executed:
print("--------------------------------------------------------------------------\n")
exit(0)
else:
sys_argv = sys.argv.copy()
if sys_argv[0].endswith("__main__.py"): # this is a python module
module_name = os.path.basename(os.path.dirname(sys_argv[0]))
cmds = [sys.executable, '-m', module_name] + sys_argv[1:]
elif sys.platform.startswith('win32'):
cmds = ['"' + sys.executable + '"', '"' + sys_argv[0] + '"'] + sys_argv[1:]
else:
cmds = [sys.executable] + sys_argv
cmds = manager_util.build_restart_command(sys.argv)
print(f"Command: {cmds}", flush=True)
print("--------------------------------------------------------------------------\n")
@@ -835,7 +907,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']
+53 -67
View File
@@ -12,7 +12,7 @@ comfyui_manager/
│ ├── manager_util.py # Existing: get_pip_cmd(), PIPFixer, use_uv flag
│ ├── cm_global.py # Existing: pip_overrides, pip_blacklist (runtime dynamic assignment)
│ └── unified_dep_resolver.py # New: Unified dependency resolution module
├── prestartup_script.py # Existing: config reading, remap_pip_package, cm_global initialization
├── prestartup_script.py # Existing: config reading, cm_global initialization
└── legacy/
└── manager_core.py # Legacy (not a modification target)
cm_cli/
@@ -199,6 +199,12 @@ def collect_requirements(self) -> CollectedDeps:
sources = defaultdict(list)
extra_index_urls = []
# Snapshot installed packages once; skipped when downgrade_blacklist is empty
installed_snapshot = (
manager_util.get_installed_packages()
if self.downgrade_blacklist else {}
)
for path in self.node_pack_paths:
# Exclude disabled node packs (directory-based mechanism)
# Disabled node packs are actually moved to custom_nodes/.disabled/,
@@ -242,7 +248,7 @@ def collect_requirements(self) -> CollectedDeps:
skipped.append((line, f"rejected: path separator in package name"))
continue
# 2. Apply remap_pip_package (using cm_global.pip_overrides)
# 2. Apply cm_global.pip_overrides
pkg_spec = self._remap_package(line)
# 3. Blacklist check (cm_global.pip_blacklist)
@@ -252,7 +258,7 @@ def collect_requirements(self) -> CollectedDeps:
continue
# 4. Downgrade blacklist check (includes version comparison)
if self._is_downgrade_blacklisted(pkg_name, pkg_spec):
if self._is_downgrade_blacklisted(pkg_name, pkg_spec, installed_snapshot):
skipped.append((pkg_spec, "downgrade blacklisted"))
continue
@@ -288,45 +294,31 @@ def _split_index_url(self, line: str) -> tuple[str, str | None]:
return pkg_spec, url
return line, None
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str) -> bool:
"""Reproduce the downgrade version comparison from existing is_blacklisted() logic.
def _is_downgrade_blacklisted(self, pkg_name: str, pkg_spec: str, installed: dict) -> bool:
"""Apply the downgrade rule shared with is_blacklisted().
Same logic as manager_core.py's is_blacklisted():
- No version spec and already installed → block (prevent reinstall)
- Operator is one of ['<=', '==', '<', '~='] and
installed version >= requested version → block (prevent downgrade)
- Version comparison uses manager_util.StrictVersion (NOT packaging.version)
Parsing and the decision come from manager_util.parse_pip_spec() and
manager_util.downgrade_protection(), so both paths give the same result:
- Any clause with operator ['<', '<=', '==', '===', '~='] that would make pip
install an older version → block (prevent downgrade)
- No version spec, or a clause that allows exactly the installed version,
and no extras → block (pip would change nothing)
- The same two cases with extras → allow (the extras' dependencies are added)
- A clause that cannot be compared → block, and log why and how to proceed
- Requirements and versions are parsed with `packaging` (PEP 508 / PEP 440)
"""
if pkg_name not in self.downgrade_blacklist:
if pkg_name not in self.downgrade_blacklist or pkg_name not in installed:
return False
installed_packages = manager_util.get_installed_packages()
# Version spec parsing (same pattern as existing is_blacklisted())
pattern = r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
match = re.search(pattern, pkg_spec)
if match is None:
# No version spec: prevent reinstall if already installed
if pkg_name in installed_packages:
return True
elif match.group(2) in ['<=', '==', '<', '~=']:
# Downgrade operator: block if installed version >= requested version
if pkg_name in installed_packages:
try:
installed_ver = manager_util.StrictVersion(installed_packages[pkg_name])
requested_ver = manager_util.StrictVersion(match.group(3))
if installed_ver >= requested_ver:
return True
except (ValueError, TypeError):
logging.warning(f"[UnifiedDepResolver] version parse failed: {pkg_spec}")
return False
return False
_, extras, clauses = manager_util.parse_pip_spec(pkg_spec)
blocked, error = manager_util.downgrade_protection(
pkg_spec, clauses, extras, installed[pkg_name])
if error is not None:
logger.error("[UnifiedDepResolver] %s", error)
return blocked
def _remap_package(self, pkg: str) -> str:
"""Package name remapping based on cm_global.pip_overrides.
Reuses existing remap_pip_package() logic."""
"""Package name remapping based on cm_global.pip_overrides."""
if pkg in self.overrides:
remapped = self.overrides[pkg]
logging.info(f"[UnifiedDepResolver] '{pkg}' remapped to '{remapped}'")
@@ -621,7 +613,7 @@ comfyui_manager/prestartup_script.py # Config reading + startup batch reso
|-----------|---------|-------|
| `uv` | Dependency resolution and installation | Already included in project dependencies |
| `cm_global` | pip_overrides, pip_blacklist, pip_downgrade_blacklist | Reuse existing global state (runtime dynamic assignment) |
| `manager_util` | StrictVersion, get_installed_packages, use_unified_resolver flag | Reuse existing utilities |
| `manager_util` | parse_pip_spec, downgrade_protection, normalize_pip_name, get_installed_packages, use_unified_resolver flag | Reuse existing utilities |
| `tempfile` | Temporary requirements files, mkdtemp | Standard library |
| `subprocess` | uv process execution | Standard library |
| `dataclasses` | Result data structures | Standard library |
@@ -696,8 +688,8 @@ sequenceDiagram
| Credential redaction | `user:pass@host` URL masked in log output |
| `_redact_url` | `://user:pass@host` → `://****@host` conversion, no-credential URL passthrough |
| `cleanup_stale_tmp` | Delete stale dirs >1 hour, preserve recent dirs, ignore permission errors |
| Downgrade operators | `<=`, `==`, `<`, `~=` blocked; `>=`, `>`, `!=` pass; no spec + installed → blocked |
| `StrictVersion` comparison | Verify `manager_util.StrictVersion` is used (not `packaging.version`) |
| Downgrade operators | `<`, `<=`, `==`, `===`, `~=` that require an older version blocked; `>=`, `>`, `!=` pass; no spec or the installed version + installed → blocked, unless the requirement has extras |
| Shared downgrade decision | Verify `manager_util.parse_pip_spec` and `manager_util.downgrade_protection` are used, as in `is_blacklisted()` |
### 9.2 Integration Tests
@@ -742,15 +734,11 @@ sequenceDiagram
> **Note**: Line numbers may shift as code changes, so references use symbol names (function/class names).
> Use `grep -n` or IDE symbol search for exact locations.
### remap_pip_package Location (Code Duplication Exists)
### pip_overrides Outside the Resolver
```
comfyui_manager/glob/manager_core.py — def remap_pip_package(pkg)
comfyui_manager/prestartup_script.py — def remap_pip_package(pkg)
```
Both reference `cm_global.pip_overrides` with identical logic.
The unified resolver uses `cm_global.pip_overrides` directly to avoid adding more duplication.
The paths that install one line at a time read each line with
`manager_util.pip_install_args(line, cm_global.pip_overrides)`, which applies the override.
The unified resolver applies `cm_global.pip_overrides` itself in `_remap_package()`.
### cm_global Global State
@@ -783,30 +771,28 @@ pip_fixer.fix_broken()
The unified resolver does not call PIPFixer directly.
The caller (execute_install_script) calls PIPFixer as part of the existing flow.
### is_blacklisted() Logic (Must Be Reproduced in Unified Resolver)
### is_blacklisted() Logic (Shared with the Unified Resolver)
```python
# manager_core.py — def is_blacklisted(name)
# 1. Simple pip_blacklist membership check
# manager_core.py — def is_blacklisted(name) → manager_util.pip_block_reason()
# 1. pip_blacklist membership check, names compared in normalized form
# (manager_util.normalize_pip_name: lowercase; '-', '_' and '.' are one separator)
# 2. pip_downgrade_blacklist version comparison:
# - Parse spec with regex r'([^<>!~=]+)([<>!~=]=?)([^ ]*)'
# - match is None (no version spec) + installed → block
# - Operator in ['<=', '==', '<', '~='] + installed version >= requested version → block
# - Version comparison uses manager_util.StrictVersion (NOT packaging.version)
# - Parse the requirement with manager_util.parse_pip_spec() (packaging, PEP 508)
# - Any clause in ['<', '<=', '==', '===', '~='] that requires an older version → block
# - No version spec, or a clause that allows exactly the installed version → block,
# unless the requirement has extras
# - A clause that cannot be compared → block, with an error that explains how to proceed
# - Versions are compared with packaging.version (PEP 440)
```
The unified resolver's `_is_downgrade_blacklisted()` method faithfully reproduces this logic.
It uses `manager_util.StrictVersion` instead of `packaging.version.parse()` to ensure consistency with existing behavior.
The unified resolver's `_is_downgrade_blacklisted()` method calls the same
`manager_util.parse_pip_spec()` and `manager_util.downgrade_protection()`, so the two
paths cannot diverge.
### Existing Code --index-url Handling (Asymmetric)
### Existing Code --index-url Handling
```python
# Only exists in standalone function execute_install_script():
if '--index-url' in package_name:
s = package_name.split('--index-url')
install_cmd = manager_util.make_pip_cmd(["install", s[0].strip(), '--index-url', s[1].strip()])
# UnifiedManager.execute_install_script() method does NOT have this handling
```
The unified resolver unifies both paths for consistent handling via `_split_index_url()`.
On every path that installs one line at a time, `manager_util.pip_install_args()` gives a
requirement followed by `--index-url URL` or `--extra-index-url URL` to the installer with that
requirement only, and leaves out a line that has only an option.
The unified resolver collects index URLs for the whole batch via `_split_index_url()`.
+5 -3
View File
@@ -25,11 +25,13 @@ rm -rf /tmp/e2e_test
| Script | Purpose | Input | Output |
|--------|---------|-------|--------|
| `setup_e2e_env.sh` | Full environment setup (8 steps) | `E2E_ROOT`, `MANAGER_ROOT`, `COMFYUI_BRANCH` (default: master), `PYTHON` (default: python3) | `E2E_ROOT=<path>` on last line |
| `setup_e2e_env.sh` | Full environment setup (8 steps) | `E2E_ROOT`, `MANAGER_ROOT`, `COMFYUI_BRANCH` (default: master), `UV_PYTHON` (optional uv request) | `E2E_ROOT=<path>` on last line |
| `start_comfyui.sh` | Foreground-blocking launcher | `E2E_ROOT`, `PORT` (default: 8199), `TIMEOUT` (default: 120s) | `COMFYUI_PID=<pid> PORT=<port>` |
| `stop_comfyui.sh` | Graceful shutdown | `E2E_ROOT`, `PORT` (default: 8199) | — |
**Idempotent**: `setup_e2e_env.sh` checks for a `.e2e_setup_complete` marker file and skips setup if the environment already exists.
**Interpreter selection**: both setup scripts use `uv venv --project "$MANAGER_ROOT"`, so uv reads Manager's `pyproject.toml` and honors its `.python-version` file and `UV_PYTHON`. To select a specific interpreter, set `UV_PYTHON` to a request such as `3.10` or an absolute executable path. The scripts do not read the old `PYTHON` variable. Explicit uv selections can override the project requirement, so the resulting venv is still checked for Python 3.10+. Selection applies only to new venvs.
**Idempotent**: both setup scripts reuse a completed environment only after checking that its venv runs Python 3.10+. If an existing venv is too old or its interpreter cannot run, recreate it with a supported interpreter in a fresh `E2E_ROOT`.
**Blocking mechanism**: `start_comfyui.sh` uses `tail -n +1 -f | grep -q -m1 'To see the GUI'` to block until ComfyUI is ready. No polling loop needed.
@@ -37,7 +39,7 @@ rm -rf /tmp/e2e_test
## Prerequisites
- Python 3.9+
- Python 3.10+ in the E2E venv (selected automatically by uv during automated setup)
- Git
- `uv` (install via `pip install uv` or [standalone](https://docs.astral.sh/uv/getting-started/installation/))
+1 -1
View File
@@ -104,7 +104,7 @@ ComfyUI-Loopchain
* Detailed Operations
* `install`: Installs the specified custom nodes.
* `reinstall`: Removes and then reinstalls the specified custom nodes.
* `reinstall`: Removes and then reinstalls the specified custom nodes. A nodepack named by its id without a version is reinstalled at the version that is installed.
* `uninstall`: Uninstalls the specified custom nodes.
* `update`: Updates the specified custom nodes.
* `disable`: Disables the specified custom nodes.
+1 -1
View File
@@ -105,7 +105,7 @@ ComfyUI-Loopchain
* 세부 동작
* `install`: 지정된 커스텀 노드들을 설치합니다
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다.
* `reinstall`: 지정된 커스텀 노드를 삭제하고 재설치 합니다. 버전 없이 이름만 지정하면 설치되어 있는 버전으로 재설치합니다.
* `uninstall`: 지정된 커스텀 노드들을 삭제합니다.
* `update`: 지정된 커스텀 노드들을 업데이트합니다.
* `disable`: 지정된 커스텀 노드들을 비활성화합니다.
-1
View File
@@ -19,7 +19,6 @@ Each subdirectory contains a standard set of JSON files:
- **custom-node-list.json**: Primary database of custom nodes with metadata
- **extension-node-map.json**: Maps between extensions and individual nodes they provide
- **model-list.json**: Catalog of models that can be downloaded through the manager
- **alter-list.json**: Alternative implementations of nodes for compatibility or functionality
- **github-stats.json**: GitHub repository statistics for node popularity metrics
## Database Schema
-1
View File
@@ -1 +0,0 @@
{}
-4
View File
@@ -1,4 +0,0 @@
{
"items": [
]
}
+43 -20
View File
@@ -20,7 +20,7 @@ components:
schemas:
OperationType:
type: string
enum: [install, uninstall, update, update-comfyui, fix, disable, enable, install-model]
enum: [install, reinstall, uninstall, update, update-comfyui, fix, disable, enable, install-model]
description: Type of operation or task being performed
OperationResult:
type: string
@@ -226,6 +226,9 @@ components:
enabled:
type: boolean
description: Whether the pack is enabled
invalid_installation:
type: [boolean, 'null']
description: True when the folder has neither .git nor .tracking, so the Manager can neither update it nor tell its version; absent or null otherwise. Its ver is then "unknown" and its cnr_id is the registry id of its pack when the registry list has it, otherwise [project].name of its pyproject.toml in lower case (also while the registry list is still loading), otherwise "". A reinstall task fixes it.
required: [ver, enabled]
SelectedVersion:
type: string
@@ -422,8 +425,10 @@ components:
description: UI identifier for task tracking
stable:
type: boolean
default: true
description: Whether to update to stable version (true) or nightly (false)
description: Whether to update to stable version (true) or nightly (false). When neither this nor `is_stable` is given, the update policy decides.
is_stable:
type: boolean
description: Another name for `stable`, the one the task parameters use. Read when `stable` is not given.
required: [client_id, ui_id]
ComfyUISwitchVersionParams:
type: object
@@ -923,6 +928,18 @@ paths:
selected_version: "latest"
mode: "remote"
channel: "default"
reinstall:
summary: Reinstall a custom node in place of its folders, which are kept if the install fails
value:
ui_id: "task_132"
client_id: "client_abc"
kind: "reinstall"
params:
id: "comfyui-impact-pack"
version: "latest"
selected_version: "latest"
mode: "remote"
channel: "default"
update:
summary: Update a custom node
value:
@@ -1057,12 +1074,14 @@ paths:
/v2/manager/queue/start:
post:
summary: Start queue processing
description: Starts processing the operation queue.
description: Starts processing the operation queue. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Processing started
'201':
description: Processing already in progress
'400':
description: Content-Type is not application/json
/v2/customnode/import_fail_info_bulk:
post:
@@ -1092,14 +1111,16 @@ paths:
/v2/manager/queue/reset:
post:
summary: Reset queue
description: Resets the operation queue.
description: Resets the operation queue. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Queue reset successfully
'400':
description: Content-Type is not application/json
/v2/manager/queue/update_all:
post:
summary: Update all custom nodes
description: Queues update operations for all installed custom nodes. Parameters are read from the query string.
description: Queues update operations for all installed custom nodes. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
security:
- securityLevel: []
parameters:
@@ -1110,7 +1131,7 @@ paths:
'200':
description: Update queued successfully
'400':
description: Missing required parameters
description: Content-Type is not application/json, or missing required parameters
'401':
description: Processing already in progress
'403':
@@ -1118,7 +1139,7 @@ paths:
/v2/manager/queue/update_comfyui:
post:
summary: Update ComfyUI
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string.
description: Queues an update operation for ComfyUI itself. Parameters are read from the query string. The request has no body and needs the Content-Type `application/json`.
parameters:
- $ref: '#/components/parameters/clientIdRequiredParam'
- $ref: '#/components/parameters/uiIdRequiredParam'
@@ -1126,7 +1147,7 @@ paths:
'200':
description: Update queued successfully
'400':
description: Missing required parameters
description: Content-Type is not application/json, or missing required parameters
/v2/manager/queue/install_model:
post:
summary: Install model
@@ -1232,7 +1253,7 @@ paths:
/v2/snapshot/remove:
post:
summary: Remove snapshot
description: Removes a specified snapshot. The `target` parameter is read from the query string.
description: Removes a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
security:
- securityLevel: []
parameters:
@@ -1241,13 +1262,13 @@ paths:
'200':
description: Snapshot removed successfully
'400':
description: Error removing snapshot
description: Content-Type is not application/json, or error removing snapshot
'403':
description: Security policy violation
/v2/snapshot/restore:
post:
summary: Restore snapshot
description: Restores a specified snapshot. The `target` parameter is read from the query string.
description: Restores a specified snapshot. The `target` parameter is read from the query string. The request has no body and needs the Content-Type `application/json`.
security:
- securityLevel: []
parameters:
@@ -1256,7 +1277,7 @@ paths:
'200':
description: Snapshot restoration scheduled
'400':
description: Error restoring snapshot
description: Content-Type is not application/json, or error restoring snapshot
'403':
description: Security policy violation
/v2/snapshot/get_current:
@@ -1275,12 +1296,12 @@ paths:
/v2/snapshot/save:
post:
summary: Save snapshot
description: Saves the current system state as a new snapshot.
description: Saves the current system state as a new snapshot. The request has no body and needs the Content-Type `application/json`.
responses:
'200':
description: Snapshot saved successfully
'400':
description: Error saving snapshot
description: Content-Type is not application/json, or error saving snapshot
# ComfyUI Management Endpoints (v2)
/v2/comfyui_manager/comfyui_versions:
get:
@@ -1333,7 +1354,7 @@ paths:
text/plain:
schema:
type: string
enum: [channel, local, remote]
enum: [cache, channel, local, remote]
post:
summary: Set database mode
description: Sets the database mode. Payload is a JSON object with a `value` field.
@@ -1347,7 +1368,7 @@ paths:
properties:
value:
type: string
enum: [channel, local, remote]
enum: [cache, channel, local, remote]
description: New database mode
responses:
'200':
@@ -1365,7 +1386,7 @@ paths:
text/plain:
schema:
type: string
enum: [stable, nightly, nightly-comfyui]
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
post:
summary: Set update policy
description: Sets the update policy. Payload is a JSON object with a `value` field.
@@ -1379,7 +1400,7 @@ paths:
properties:
value:
type: string
enum: [stable, nightly, nightly-comfyui]
enum: [stable, stable-comfyui, nightly, nightly-comfyui]
description: New update policy
responses:
'200':
@@ -1431,12 +1452,14 @@ paths:
/v2/manager/reboot:
post:
summary: Reboot ComfyUI
description: Restarts the ComfyUI server.
description: Restarts the ComfyUI server. The request has no body and needs the Content-Type `application/json`.
security:
- securityLevel: []
responses:
'200':
description: Reboot initiated
'400':
description: Content-Type is not application/json
'403':
description: Security policy violation
/v2/manager/version:
+5 -16
View File
@@ -5,8 +5,8 @@ build-backend = "setuptools.build_meta"
[project]
name = "comfyui-manager"
license = { text = "GPL-3.0-only" }
version = "4.2.2"
requires-python = ">= 3.9"
version = "4.5"
requires-python = ">=3.10"
description = "ComfyUI-Manager provides features to install and manage custom nodes for ComfyUI, as well as various functionalities to assist with ComfyUI."
readme = "README.md"
keywords = ["comfyui", "comfyui-manager"]
@@ -35,7 +35,9 @@ dependencies = [
"typing-extensions",
"toml",
"uv",
"chardet"
"chardet",
"packaging",
"nh3>=0.3.7"
]
[project.optional-dependencies]
@@ -50,16 +52,3 @@ include = ["comfyui_manager*", "cm_cli*"]
[project.scripts]
cm-cli = "cm_cli:main"
[tool.ruff]
line-length = 120
target-version = "py39"
[tool.ruff.lint]
select = [
"E4", # default
"E7", # default
"E9", # default
"F", # default
"I", # isort-like behavior (import statement sorting)
]
+23 -25
View File
@@ -397,12 +397,11 @@
## 22. tests/e2e/test_e2e_legacy_endpoints.py — Legacy-only endpoint positive-path suite (WI-TT + WI-UU deliverable)
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All seven routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
**Reference**: WI-TT seeded this file with 6 GET positive-path tests closing pytest-N gaps (wi-031/032/033/034/035/036). WI-UU extends the file with a 7th test — the POST `/v2/manager/queue/batch` positive-path (wi-039) — closing the pytest-I gap for the high-fanout queue-batch endpoint. All six routes are registered only in `legacy/manager_server.py` and reachable only under `--enable-manager-legacy-ui`, so they share the same legacy fixture (`start_comfyui_legacy.sh`, PORT 8199) mirroring the `test_e2e_csrf_legacy.py` pattern.
**Scope**: Positive-path assertions — status 200 + response-shape verification for each legacy-only endpoint. `disabled_versions` additionally accepts 400 as a valid branch because the handler returns 400 when the target node has no disabled versions (empty-result convention, not a validation error). `queue/batch` uses an empty-payload strategy to exercise the full handler path (parse → action-loop no-op → finalize-with-empty-guard → `_queue_start()` → JSON 200) with zero state mutation, plus a queue/status liveness check to verify the worker lock was released cleanly.
| Test | Design Goal | Verdict | Evidence |
|---|---|---|---|
| `TestLegacyCustomNodeAlternatives::test_returns_dict_of_alternatives` | Endpoint contract (alternatives — wi-031) | ✅ PASS | GET `/customnode/alternatives?mode=local` → 200 + dict body. Exercises unified-key mapping path (handler L1072-1084). |
| `TestLegacyCustomNodeDisabledVersions::test_endpoint_reachable_and_parses_param` | Endpoint contract (disabled_versions — wi-032) | ✅ PASS | GET `/v2/customnode/disabled_versions/ComfyUI_SigmoidOffsetScheduler` → status ∈ {200, 400}; 200 body asserted as list of `{version}` entries. Seed pack has no disabled versions → 400 is the live branch, 200 is guarded for when state is mutated. |
| `TestLegacyCustomNodeGetList::test_returns_channel_and_node_packs` | Endpoint contract (getlist — wi-033) | ✅ PASS | GET `/v2/customnode/getlist?mode=local&skip_update=true` → 200 + `{channel, node_packs}` dict with node_packs as dict. Exercises the unified `get_unified_total_nodes + populate_*` pipeline. |
| `TestLegacyCustomNodeVersions::test_returns_versions_list_for_seed_pack` | Endpoint contract (versions — wi-034) | ✅ PASS | GET `/v2/customnode/versions/ComfyUI_SigmoidOffsetScheduler` → 200 + non-empty list. Verifies CNR version lookup for the seed pack (handler L1262-1270). |
@@ -410,7 +409,7 @@
| `TestLegacyManagerNotice::test_returns_text_body` | Endpoint contract (notice — wi-036) | ✅ PASS | GET `/v2/manager/notice` → 200 + non-empty text body. Handler returns text/html (not JSON); both the markdown-fetch branch and the 'Unable to retrieve Notice' fallback return 200 with body. |
| `TestLegacyQueueBatch::test_accepts_empty_payload_returns_failed_list` | Endpoint contract (queue/batch — wi-039) | ✅ PASS | POST `/v2/manager/queue/batch` with `{}` → 200 + `{"failed": []}`. Safe-payload choice (empty body) exercises full handler path with zero state mutation; `finalize_temp_queue_batch` no-ops via its `if len(temp_queue_batch):` guard (handler L444), and `_queue_start()` releases the task-worker lock cleanly. Post-POST `/v2/manager/queue/status` returns 200 — lock-release liveness check. Closes the wi-039 pytest-I gap (was CSRF-only direct + indirect-via-callers). |
**File verdict**: 7/7 ✅ PASS.
**File verdict**: 6/6 ✅ PASS.
---
@@ -431,32 +430,32 @@
| test_e2e_csrf_legacy.py | 29 | 0 | 0 | 0 | 29 |
| test_e2e_secgate_strict.py | 1 | 0 | 0 | 0 | 1 |
| test_e2e_secgate_default.py | 1 | 0 | 0 | 0 | 1 |
| test_e2e_legacy_endpoints.py | 7 | 0 | 0 | 0 | 7 |
| test_e2e_legacy_endpoints.py | 6 | 0 | 0 | 0 | 6 |
| legacy-ui-manager-menu.spec.ts | 5 | 0 | 0 | 0 | 5 |
| legacy-ui-custom-nodes.spec.ts | 5 | 0 | 0 | 0 | 5 |
| legacy-ui-model-manager.spec.ts | 4 | 0 | 0 | 0 | 4 |
| legacy-ui-snapshot.spec.ts | 3 | 0 | 0 | 0 | 3 |
| legacy-ui-navigation.spec.ts | 2 | 0 | 0 | 0 | 2 |
| legacy-ui-install.spec.ts | 2 | 0 | 0 | 0 | 2 |
| **TOTAL** | **122** | **0** | **0** | **1** | **123** |
| **TOTAL** | **121** | **0** | **0** | **1** | **122** |
(Count adjusted to 109 after Wave1 WI-L/M/N: 10 WEAK→PASS upgrades across 5 files (endpoint, git_clone, customnode_info, queue_lifecycle, version_mgmt) + 1 WEAK-row retired via WI-M dedup (test_get_current_returns_dict folded into strengthened test_get_current_snapshot — the folded row is treated as a deletion rather than a separate upgrade). Stage2 WI-F earlier established the 110 baseline from 112 by retiring 4 INADEQUATE legacy-ui tests with net +2 PASS. Wave2 WI-P/Q added 7 more WEAK→PASS upgrades (WI-P: task_operations 6 upgrades for update/fix effect + params; WI-Q: snapshot_lifecycle 1 upgrade for save_snapshot disk + content verification). Wave3 WI-T/U/W completed the reconciliation with 10 further WEAK→PASS upgrades: WI-T Cluster C+G strengthened queue_lifecycle (3), customnode_info (1), system_info (1) for field-level effect checks; WI-U Cluster H rewrote 3 Playwright legacy-ui specs (manager-menu 2, custom-nodes 1, model-manager 2) to verify UI state via dialog reopen / `<select>.value` assertions instead of direct API; WI-W fixed the TaskHistoryItem schema-drop regression enabling queue_lifecycle un-skip. Cumulative **upgrade** count across the three waves = 10 + 7 + 10 = **27** (unchanged). WI-Z reconciled the audit with the actual test-file surface (no upgrades, only inventory): Y1 recorded the pre-existing `test_remove_path_traversal_rejected` in snapshot_lifecycle (§7, 6→7), and Y3 recorded 5 pre-existing config_api rows (junk_value rejections ×3 + persists_to_config_ini ×2 from WI-E/WI-I, §4, 10→15). WI-AA recorded the pre-existing `legacy-ui-install.spec.ts` (LB1 + LB2) as new §16 — these UI-driven install/uninstall tests (from WI-U Cluster) close the LB1/LB2 gap formerly flagged in `coverage_gaps.md`. WI-GG added new §19 for `test_e2e_csrf_legacy.py` (from WI-FF): 4 new test functions / 26 parametrized invocations closing the legacy-side CSRF regression-guard gap — counted per-invocation (+26 PASS rows) for parity with the CSRF endpoint-fixture accounting in `endpoint_scenarios.md`; this is an accounting-granularity choice, not a contract addition (CSRF-M1/M2/M3 Goals were already referenced in §18). Total test count progression: **109 → 115 (WI-Z) → 117 (WI-AA) → 143 (WI-GG) → 146 (WI-JJ) → 148 (WI-LL)**; all 39 added rows were **pre-existing** tests or newly-added tests from their source WIs, not new engineering work performed by the audit reconciliation itself.)
> **Note**: The matrix above counts *tests* (148), not *design Goals* (92).
> See `reports/verification_design.md` for the 92 Goals and the RV-B trace
> **Note**: The matrix above counts *tests* (147), not *design Goals* (91).
> See `reports/verification_design.md` for the 91 Goals and the RV-B trace
> (adhoc-rv-b-trace session evidence) for the Goal↔test cross-reference.
> **Design-Goal coverage: 70/92 Goals referenced (76.1%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **73/95** (76.8%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
> **Design-Goal coverage: 69/91 Goals referenced (75.8%), 22 Goals absent from this audit** — see § Design-Goal Coverage Gap below. With the 3 CSRF-mitigation Goals (CSRF-M1/M2/M3) from `verification_design.md` Section 10 added as supplementary coverage, the superset tally is **72/94** (76.6%). (WI-Z Y1 strengthens SR3 coverage from Key-gap note to an actual ✅ PASS row (`test_remove_path_traversal_rejected`); WI-AA adds ✅ PASS rows for LB1/LB2 via `legacy-ui-install.spec.ts`. WI-GG adds a second test-reference for CSRF-M1/M2/M3 via `test_e2e_csrf_legacy.py` but does NOT introduce new Goals — each CSRF-M Goal is now backed by paired glob + legacy coverage. WI-LL adds two previously T2 SECGATE-PENDING Goals (SR4 via `test_e2e_secgate_strict.py` §20, CV4 via `test_e2e_secgate_default.py` §21) as formal ✅ PASS rows — reclassifying them from "T2-pending" Key-gap notes to test-backed coverage. The 68→70 base tally uplift reflects this formal-status upgrade: SR4 and CV4 transition from Key-gap reference to explicit test-row-backed Goals.)
Percentages (excluding N/A, denominator = 122+0+0 = 122):
- ✅ PASS: 122 / 122 = 100%
- ⚠️ WEAK: 0 / 122 = 0%
- ❌ INADEQUATE: 0 / 122 = 0%
Percentages (excluding N/A, denominator = 121+0+0 = 121):
- ✅ PASS: 121 / 121 = 100%
- ⚠️ WEAK: 0 / 121 = 0%
- ❌ INADEQUATE: 0 / 121 = 0%
---
# Design-Goal Coverage Gap
24 of 92 design Goals (`reports/verification_design.md`) have no corresponding row in
24 of 91 design Goals (`reports/verification_design.md`) have no corresponding row in
the test audit above. Full list:
| Section | Goal | Intent | Recommended |
@@ -481,12 +480,12 @@ the test audit above. Full list:
| 5.4 | CV2 | Non-git error branch | NORMAL add |
| 6.1 | LB4 | UI update-all | NORMAL add |
| 6.1 | LB5 | Batch partial failure | NORMAL add |
| 6.2 | LG2 | skip_update perf | NORMAL add |
| 6.4 | LM2 | Install flag seed | NORMAL add |
| 6.5 | LV1 | Version dropdown | NORMAL add |
| 6.5 | LV2 | Unknown pack 400 | NORMAL add |
| 6.2 | LG2 | List without fetch | NORMAL add |
| 6.3 | LM2 | Install flag seed | NORMAL add |
| 6.4 | LV1 | Version dropdown | NORMAL add |
| 6.4 | LV2 | Unknown pack 400 | NORMAL add |
Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 95 Goals: KEEP 25 / rest unchanged.
Final Goal-class tally (91 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL) / NORMAL strengthen 25 / NORMAL add 39 (22 UNREF + 14 GAP + 3 T1 DESTRUCTIVE-SAFE) / T2 PENDING-SECGATE **reduced 8 → 4 and reclassified** (see WI-KK SECGATE Harness Design block below) / T3 IRREDUCIBLE-NA 0. With the supplementary CSRF-M1/M2/M3 Goals covered by `verification_design.md` Section 10, superset tally is 94 Goals: KEEP 25 / rest unchanged.
---
@@ -539,7 +538,6 @@ Final Goal-class tally (92 design Goals): KEEP 22 (SR4 + CV4 promoted post-WI-LL
- LN1-LN4 manager/notice tests (4 variants)
- LPP1/LPP2 pip install tests
- LGU1/LGU2 git_url install tests
- LA1 alternatives display test
- LDV1 disabled_versions test
## Classification policy (tier rule)
@@ -599,9 +597,9 @@ should land as one cross-cutting item" collapses into a 4-sub-tier structure:
| T2-TASKLEVEL | IM4 | Queue-observation pattern (not HTTP 403) — pattern TBD | Open design question; not a simple mechanical add |
Propagation plan (post-PR):
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 136/151 TOTAL.
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 138/153.
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 139/154. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
1. Land SR6, V5, UA2 in `test_e2e_secgate_strict.py` using the SR4 template; adds 3 PASS rows, brings this audit to 135/150 TOTAL.
2. Create `test_e2e_secgate_legacy_default.py` for LGU2 + LPP2; +2 PASS → 137/152.
3. Design the IM4 queue-observation pattern (distinct from the HTTP 403 pattern used in §20/§21); +1 PASS → 138/153. This item may be reclassified to T3 IRREDUCIBLE-NA if the observable turns out to be log-only.
---
@@ -617,11 +615,11 @@ Cumulative Wave1+Wave2+Wave3 upgrade count: **27 WEAK → PASS** (10 + 7 + 10).
- Check status code without verifying the actual effect (WEAK — 0%) ✅
- Use direct API in UI tests (INADEQUATE — 0%) ✅
- Are outside endpoint-effect scope (N/A — 15/148 ≈ 10.1% of total)
- Are outside endpoint-effect scope (N/A — 15/147 ≈ 10.2% of total)
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/92 absent, 70/92 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
Remaining 🟢 gaps (not WEAK): ~~**SR3 snapshot-remove path-traversal**~~ (RESOLVED by WI-Z Y1 — `test_remove_path_traversal_rejected`) and **QH2 queue-history path-traversal** (destructive-safe security test, already present via `test_history_path_traversal_rejected` in queue_lifecycle § Key gaps). Design-Goal coverage gap (22/91 absent, 69/91 referenced) is tracked separately in § Design-Goal Coverage Gap and is not a test-quality issue.
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (133/133 PASS, excluding 15 N/A). Audit is in a terminal state for the current 148 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
Post-Wave3 + WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL state: **100% adequate coverage achieved** (132/132 PASS, excluding 15 N/A). Audit is in a terminal state for the current 147 tests. Further coverage expansion (design-Goal additions, the 3 T2-pending harness-ready Goals, NORMAL-legacy Goals, T2-TASKLEVEL IM4) is new-work territory — propagation plan is documented in the WI-KK SECGATE Harness Design block above — not reconciliation.
> **WI-Z + WI-AA + WI-GG + WI-JJ + WI-LL note**: Total test count 109 → 115 (WI-Z Y1 +1 snapshot, Y3 +5 config_api) → 117 (WI-AA +2 LB1/LB2) → 143 (WI-GG +26 legacy CSRF per-invocation rows) → 146 (WI-JJ +3 legacy-side install/parity rows) → 148 (WI-LL +2 SECGATE PoC rows) reflects inventory reconciliation plus WI-KK's newly-landed secgate coverage. Cumulative **upgrade** count remains 27 (unchanged since Wave3). WI-LL is the first audit-reflect WI to also introduce a Classification-policy reshape (T2 SECGATE-PENDING 8 → 4 sub-tiers), not just row additions.
+23 -20
View File
@@ -10,14 +10,14 @@
| Category | Endpoints | Unique Scenarios |
|---|---:|---:|
| Glob v2 | 30 | 120 |
| Legacy-only (not in glob) | 9 | 34 |
| Legacy-only (not in glob) | 8 | 33 |
| Legacy-shared (same path as glob) | 29 | — (see glob) |
| **TOTAL unique HTTP handlers** | **39** | **154** |
| **TOTAL unique HTTP handlers** | **38** | **153** |
Security-gated endpoints:
- `middle`: reboot, snapshot/remove, _uninstall_custom_node, _update_custom_node
- `middle+`: update_all, snapshot/restore, _install_custom_node, _install_model
- `high+`: comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
- `middle+`: update_all, _install_custom_node, _install_model
- `high+`: comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version` (glob worker step), install/git_url, install/pip, non-safetensors model install, _fix_custom_node (raised from `high` to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text — WI-#235; prior `middle` → `high` upgrade was commit `c8992e5d`)
---
@@ -188,7 +188,7 @@ Security-gated endpoints:
### POST /v2/snapshot/restore
- **Handler**: `restore_snapshot` (L1543)
- **Security gate**: `middle+` → 403
- **Security gate**: `high+` → 403
- **Query**: `target`
- **Scenarios**:
1. Success — copies snapshot to startup script path (applied on next reboot) → 200
@@ -291,21 +291,24 @@ Endpoints in this section exist **only in the legacy server** (not registered in
7. `install` with security gate fail → failed set entry
8. Empty body `{}` → 200 `{failed: []}`
### POST /v2/customnode/check_update
- **Handler**: `check_update`
- **Body**: `{mode, ui_id}` (required; `ui_id` is chosen by the client)
- **Scenarios**:
1. Success — starts a background check that fetches the enabled git packs of the list and answers `{}` at once → 200. The check reports by the `cm-check-update` event (`in_progress` with `done_count`/`total_count`, then `done` with `updatable` and the `ui_ids` of the requests it answers)
2. A check already runs — no second check is started; the nodepacks of this request that the running check does not have are added to it (`total_count` grows), and its `done` names this request too → 200
3. A task on nodepacks that the queue takes while a check runs waits for the check to end; a model download and an update of ComfyUI do not wait
4. The check fails — `done` with `updatable: null` names the requests that waited, and the page shows `Failed to check updates.`
### GET /v2/customnode/getlist
- **Handler**: `fetch_customnode_list` (L1018)
- **Query**: `mode` (required), `skip_update?` (bool string)
- **Query**: `mode` (required), `skip_update?` (not used)
- **Scenarios**:
1. Success — returns `{channel, node_packs}` with installed/update state populated → 200
2. `skip_update=true` — skips git update check (faster)
1. Success — returns `{channel, node_packs}` with installed state and the update state of versioned packs populated → 200
2. With or without `skip_update` — no git fetch; the page marks the git packs that have an update from the result of `POST /v2/customnode/check_update`
3. Removes comfyui-manager self-entry from results
4. Channel lookup resolves to 'default'/'custom'/known name
### GET /customnode/alternatives
- **Handler**: `fetch_customnode_alternatives` (L1072)
- **Query**: `mode` (required)
- **Scenarios**:
1. Success — alter-list.json items keyed by id → 200
### GET /v2/externalmodel/getlist
- **Handler**: `fetch_externalmodel_list` (L1143)
- **Query**: `mode` (required)
@@ -331,7 +334,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
### POST /v2/customnode/install/git_url
- **Handler**: `install_custom_node_git_url` (L1502)
- **Security gate**: `high+` → 403
- **Body**: plain text URL
- **Body**: JSON `{"url": ...}`, sent as `application/json`
- **Scenarios**:
1. Success install → 200
2. Already installed (skip action) → 200
@@ -341,7 +344,7 @@ Endpoints in this section exist **only in the legacy server** (not registered in
### POST /v2/customnode/install/pip
- **Handler**: `install_custom_node_pip` (L1522)
- **Security gate**: `high+` → 403
- **Body**: plain text space-separated packages
- **Body**: JSON `{"packages": ...}` (space-separated), sent as `application/json`
- **Scenarios**:
1. Success — pip install completes → 200
2. Security blocked → 403
@@ -378,14 +381,14 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
| Level | Glob endpoints | Legacy endpoints |
|---|---|---|
| **middle** | snapshot/remove, reboot | snapshot/remove, reboot, _uninstall, _update |
| **middle+** | update_all, snapshot/restore, install_model | update_all, snapshot/restore, _install_custom_node, _install_model |
| **high+** | comfyui_switch_version, _fix_custom_node | comfyui_switch_version, install/git_url, install/pip, non-safetensors model install, _fix |
| **middle+** | update_all, install_model | update_all, _install_custom_node, _install_model |
| **high+** | comfyui_switch_version, snapshot/restore, `update-comfyui` task with an older `target_version`, _fix_custom_node | comfyui_switch_version, snapshot/restore, install/git_url, install/pip, non-safetensors model install, _fix |
> Note: `_fix` / `_fix_custom_node` security-level history: `middle` → `high` in commit `c8992e5d` (2026-04-04, which also added a previously-missing gate to the legacy handler); subsequent `high` → `high+` in WI-#235 to align the enforcement gate with the `SECURITY_MESSAGE_HIGH_P` log text (and tighten the gate for a state-mutating fix path). README 'Risky Level Table' has been updated in lockstep.
# Deprecated / Removed
- **GET /v2/customnode/fetch_updates** — glob returns 410; legacy still attempts fetch (may succeed but deprecated in concept)
- **GET /v2/customnode/fetch_updates** — glob and legacy return 410
- **Individual queue/{install,uninstall,update,fix,disable,reinstall,abort_current}** — removed from legacy in recent work (replaced by queue/batch aggregator)
- **GET /manager/notice** (v1, no /v2 prefix) — removed from legacy
@@ -407,7 +410,7 @@ These paths exist in BOTH glob and legacy files (29 endpoints). Semantics are ty
| 6 | `/v2/manager/queue/task` | POST | POST (pre-existing) | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/queue/task]` |
| 7 | `/v2/snapshot/save` | GET | POST | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/save]` |
| 8 | `/v2/snapshot/remove` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/remove]` |
| 9 | `/v2/snapshot/restore` | GET | POST | middle+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
| 9 | `/v2/snapshot/restore` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/snapshot/restore]` |
| 10 | `/v2/manager/reboot` | GET | POST | middle | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/reboot]` |
| 11 | `/v2/comfyui_manager/comfyui_switch_version` | GET | POST | high+ | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/comfyui_manager/comfyui_switch_version]` |
| 12 | `/v2/manager/db_mode` | GET (dual) | POST (write); GET preserved for read | default | `TestStateChangingEndpointsRejectGet::test_get_is_rejected[/v2/manager/db_mode]` |
+2 -11
View File
@@ -384,18 +384,10 @@ Purpose: **feed the Custom Nodes Manager dialog with the list of available + ins
| Scenario | Effect to verify |
|---|---|
| Success | Response has `channel` + `node_packs`; each pack includes install state (installed/disabled), stars (github-stats), update availability (if skip_update=false) |
| skip_update=true | No git fetch performed (check timing / no remote calls) |
| Success | Response has `channel` + `node_packs`; each pack includes install state (installed/disabled), stars (github-stats), update availability of versioned packs |
| With or without skip_update | No git fetch performed (check timing / no remote calls) |
| Channel resolution | Maps URL back to name (default/custom/etc.) |
### GET /customnode/alternatives (legacy)
Purpose: **show alternative pack recommendations for a given pack**.
| Scenario | Effect to verify |
|---|---|
| Success | Response dict keyed by unified pack id; values from `alter-list.json` with markdown processed |
### GET /v2/externalmodel/getlist (legacy)
Purpose: **list available external models with install state for Model Manager dialog**.
@@ -473,7 +465,6 @@ For Playwright tests, the "UI→effect" contract requires:
| Click "Disable" on row | POST queue/batch (disable) | Pack in `.disabled/` + row state "Disabled" |
| Click "Update" on outdated row | POST queue/batch (update) | Pack version changes + row state update |
| Click "Fix" on row | POST queue/batch (fix) | Dependencies restored |
| Click "Try alternatives" | GET /customnode/alternatives | Alternatives list rendered |
| Open "Versions" dropdown on row | GET customnode/versions/{id} | Version list rendered in UI |
| Open "Disabled Versions" on row | GET customnode/disabled_versions/{id} | Disabled versions rendered |
| Click "Install via Git URL" button + enter URL + confirm | POST customnode/install/git_url | Pack cloned; dir visible in UI |
+5 -11
View File
@@ -219,7 +219,7 @@ Intent categories used:
| Success | Recovery: rollback to a known-good state after bad update |
| Nonexistent | Input resilience |
| Path traversal | Security boundary |
| Security denied | Security boundary: middle+ required (restore is destructive) |
| Security denied | Security boundary: high+ required (restore is destructive) |
## 1.4 Configuration
@@ -313,15 +313,9 @@ Same as db_mode: observability of current policy + user choice to change update
| Scenario | Intent |
|---|---|
| Success | User capability: populate Custom Nodes Manager dialog with full available pack catalog |
| skip_update=true | Performance: fast load when user doesn't need remote fetch |
| With or without skip_update | Performance: the list loads without a remote fetch; a check for updates runs in the background |
| Channel resolution | Observability: user sees which channel data came from |
### GET /customnode/alternatives
| Scenario | Intent |
|---|---|
| Success | User capability: recommend alternative packs when one is discontinued/unavailable |
### GET /v2/externalmodel/getlist
| Scenario | Intent |
@@ -385,7 +379,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Security level denial (middle/middle+/high+) | destructive endpoints | Security boundary — tier privileged ops per deployment risk profile |
| Idempotent re-call on empty state | queue/reset, history_list, snapshot/getlist, installed | Idempotency — safe to poll or retry |
| Repeated read returns same value | version, db_mode, policy/update | Data integrity — config/runtime state is stable |
| Empty collection returned cleanly | history, getlist, installed, alternatives | Input resilience — empty is valid, not an error |
| Empty collection returned cleanly | history, getlist, installed | Input resilience — empty is valid, not an error |
---
@@ -393,7 +387,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Intent category | # scenarios | Notes |
|---|---:|---|
| User capability (positive user need) | 62 | The "happy paths" |
| User capability (positive user need) | 61 | The "happy paths" |
| Input resilience | 32 | Mostly 400s for bad input |
| Security boundary | 15 | Security levels + path traversal |
| Idempotency | 14 | No-op / retry safety |
@@ -402,7 +396,7 @@ Some scenarios recur across many endpoints with consistent intent:
| Recovery | 5 | Fix, restore, reset |
| Concurrency safety | 2 | Worker dedup |
Total unique scenarios mapped: ~154 (matches Report A).
Total unique scenarios mapped: ~153 (matches Report A).
---
+11 -18
View File
@@ -359,7 +359,7 @@ Negative check: <what must NOT happen>
- **Observable**: manager_startup_script_path for `restore-snapshot.json`
- **Assertion**: restore-snapshot.json exists; content == target snapshot; (downstream: reboot → state reverts)
### Goal SR6 — Security gate (<middle+)
### Goal SR6 — Security gate (<high+)
- **Assertion**: 403; no marker file
---
@@ -513,19 +513,12 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Observable**: UI grid rows
- **Assertion**: rows > 0; each row has Title + Installed/Not-Installed state + Install/Uninstall button
### Goal LG2 — skip_update=true optimizes loading
- **Action (UI)**: open dialog with flag set (URL param or setting)
### Goal LG2 — the list loads without a git fetch
- **Action (UI)**: open dialog (with or without `skip_update`)
- **Observable**: loading time; network log
- **Assertion**: no git fetch calls; load time < N seconds
## 6.3 GET /customnode/alternatives
### Goal LA1 — Show alternatives on dedicated UI flow
- **Action (UI)**: trigger alternatives display (specific button or context)
- **Observable**: alternatives panel/dialog
- **Assertion**: populated with alter-list.json entries (at least one if data exists)
## 6.4 GET /v2/externalmodel/getlist
## 6.3 GET /v2/externalmodel/getlist
### Goal LM1 — Populate Model Manager dialog
- **Action (UI)**: open Model Manager
@@ -537,7 +530,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Action (UI)**: open Model Manager
- **Assertion**: that model row shows "Installed"
## 6.5 GET /v2/customnode/versions/{node_name}
## 6.4 GET /v2/customnode/versions/{node_name}
### Goal LV1 — Version dropdown on Install click
- **Action (UI)**: click Install on a CNR pack row
@@ -548,7 +541,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Action**: direct API call with bogus node_name
- **Assertion**: 400; UI shows error or skips
## 6.6 GET /v2/customnode/disabled_versions/{node_name}
## 6.5 GET /v2/customnode/disabled_versions/{node_name}
### Goal LDV1 — Show disabled versions for re-enable
- **Precondition**: pack has disabled versions
@@ -556,7 +549,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Observable**: dropdown options
- **Assertion**: options match backend disabled_versions response
## 6.7 POST /v2/customnode/install/git_url
## 6.6 POST /v2/customnode/install/git_url
### Goal LGU1 — Install via "Install via Git URL" button
- **Precondition**: security_level ≥ high+; pack absent
@@ -568,7 +561,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
- **Precondition**: security_level < high+
- **Assertion**: 403 from API; UI shows error; no clone occurs
## 6.8 POST /v2/customnode/install/pip
## 6.7 POST /v2/customnode/install/pip
### Goal LPP1 — Install pip packages via UI
- **Action (UI)**: trigger pip install flow with known package
@@ -578,7 +571,7 @@ All verification here assumes Playwright UI interaction as the Action. Effect is
### Goal LPP2 — Security gate
- **Assertion**: 403 at lower security; no pip invocation
## 6.9 GET /v2/manager/notice
## 6.8 GET /v2/manager/notice
### Goal LN1 — Fetch and display News
- **Precondition**: GitHub reachable
@@ -666,7 +659,7 @@ Reusable verification templates organized by intent category. Apply the template
**Security tiers to cover**:
- `middle` — reboot, snapshot/remove, _uninstall, _update
- `middle+` — update_all, snapshot/restore, _install_custom_node, _install_model
- `middle+` — update_all, _install_custom_node, _install_model
- `high+` — comfyui_switch_version, install/git_url, install/pip, non-safetensors model, _fix (`middle` → `high` in commit `c8992e5d`; subsequent `high` → `high+` in WI-#235 to align the gate with the `SECURITY_MESSAGE_HIGH_P` log text)
**Path-traversal sub-template** (within security boundary):
@@ -752,7 +745,7 @@ Reusable verification templates organized by intent category. Apply the template
| Intent category | Template | Scenarios using | Test type needed |
|---|---|---:|---|
| User capability | 7.1 | 62 | E2E effect verification (real install/remove/save etc.) |
| User capability | 7.1 | 61 | E2E effect verification (real install/remove/save etc.) |
| Input resilience | 7.2 | 32 | Negative tests with negative-check assertions |
| Security boundary | 7.3 | 15 | Permission tests at each security level |
| Observability | 7.4 | 16 | GET correctness + traceability tests |
+2
View File
@@ -10,3 +10,5 @@ typing-extensions
toml
uv
chardet
packaging
nh3>=0.3.7
+6
View File
@@ -175,3 +175,9 @@ def import_glob_security_utils():
(the glob copy of the security_level gate matrix — guard rows
SC-25C / SC-28)."""
return _import_real("comfyui_manager.glob.utils.security_utils")
# what `git rev-parse --local-env-vars` lists: with one of them, git does not work on the repository of its directory
GIT_LOCATION = ('GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'GIT_OBJECT_DIRECTORY',
'GIT_DIR', 'GIT_WORK_TREE', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_INDEX_FILE', 'GIT_NO_REPLACE_OBJECTS',
'GIT_REPLACE_REF_BASE', 'GIT_PREFIX', 'GIT_SHALLOW_FILE', 'GIT_COMMON_DIR')
@@ -0,0 +1,220 @@
"""
Tests for the `dependency_management` opt-out switch without a ComfyUI runtime.
Load the actual utility module and startup functions with isolated collaborators;
never execute startup's host-side registration, network, or interpreter mutations.
"""
import ast
import importlib.util
import logging
import os
from pathlib import Path
import sys
import tempfile
import types
import unittest
from unittest import mock
_PACKAGE = Path(__file__).resolve().parents[2] / "comfyui_manager"
def _import_manager_util():
# Other tests replace the public module with a resolver stub. Import a fresh
# private instance rather than depending on collection order or booting the
# package's __init__, which imports the full ComfyUI application.
spec = importlib.util.spec_from_file_location(
"dependency_management_test_util", _PACKAGE / "common" / "manager_util.py"
)
module = importlib.util.module_from_spec(spec)
# HTTP is unrelated to dependency policy and is never called by these tests.
with mock.patch.dict(sys.modules, {"aiohttp": types.ModuleType("aiohttp")}):
spec.loader.exec_module(module)
return module
def _startup_namespace(manager_util):
return {
"manager_util": manager_util,
"os": os,
"logging": logging,
"default_conf": {},
"processed_install": set(),
"_unified_resolver_succeeded": False,
"comfy_path": "/externally-managed-comfy",
"process_wrap": mock.Mock(return_value=0),
"is_installed": mock.Mock(return_value=False),
"cm_global": types.SimpleNamespace(pip_overrides={}),
}
def _load_startup_nodes(namespace, predicate):
path = _PACKAGE / "prestartup_script.py"
parsed = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
nodes = [node for node in parsed.body if predicate(node)]
if not nodes:
raise AssertionError("Startup policy code was not found")
exec(compile(ast.Module(body=nodes, type_ignores=[]), str(path), "exec"), namespace)
class DependencyManagementFlagTest(unittest.TestCase):
def setUp(self):
self.manager_util = _import_manager_util()
self._prev = self.manager_util.dependency_management_enabled
self.addCleanup(setattr, self.manager_util, "dependency_management_enabled", self._prev)
def test_default_is_enabled(self):
# Default must preserve today's behavior.
self.assertTrue(self._prev)
def test_environment_is_applied_when_the_module_loads(self):
# A cm-cli process loads manager_util without running prestartup_script.
for environment, expected in [({"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": "off"}, False), ({}, True)]:
with self.subTest(environment=environment):
with mock.patch.dict(os.environ, environment, clear=True):
self.assertEqual(_import_manager_util().dependency_management_enabled, expected)
def test_pip_fixer_short_circuits_when_disabled(self):
self.manager_util.dependency_management_enabled = False
class _Stub(self.manager_util.PIPFixer):
def __init__(self): # bypass parent init
pass
with mock.patch.object(self.manager_util, "get_installed_packages") as patched:
_Stub().fix_broken()
patched.assert_not_called()
def test_pip_fixer_runs_when_enabled(self):
# The enabled path must read the current installed package inventory.
self.manager_util.dependency_management_enabled = True
class _Stub(self.manager_util.PIPFixer):
def __init__(self):
self.prev_pip_versions = {}
self.comfyui_path = "/nonexistent"
self.manager_files_path = "/nonexistent"
class InventoryRead(Exception):
pass
with mock.patch.object(self.manager_util, "get_installed_packages", side_effect=InventoryRead) as patched:
with self.assertRaises(InventoryRead):
_Stub().fix_broken()
patched.assert_called_once_with(True)
def test_make_pip_cmd_not_gated(self):
# make_pip_cmd is consulted for both read and write ops (pip list,
# pip install, …). Gating it would break read paths the UI relies on.
# Assert the helper still produces a runnable command when the flag
# is off — gating happens at call sites that perform writes.
self.manager_util.dependency_management_enabled = False
with mock.patch.object(self.manager_util, "get_pip_cmd", return_value=[sys.executable, "-m", "pip"]):
cmd = self.manager_util.make_pip_cmd(["list"])
install_cmd = self.manager_util.make_pip_cmd(["install", "some-pkg"])
self.assertIsInstance(cmd, list)
self.assertGreaterEqual(len(cmd), 3)
self.assertIn("list", cmd)
self.assertIn("install", install_cmd)
self.assertIn("some-pkg", install_cmd)
class StartupDependencyPolicyTest(unittest.TestCase):
def setUp(self):
self.manager_util = _import_manager_util()
self.namespace = _startup_namespace(self.manager_util)
_load_startup_nodes(
self.namespace,
lambda node: isinstance(node, ast.FunctionDef)
and node.name in {"read_dependency_management_mode", "execute_lazy_install_script"},
)
def test_config_off(self):
self.namespace["default_conf"]["dependency_management"] = "off"
with mock.patch.dict(os.environ, {}, clear=True):
self.namespace["read_dependency_management_mode"]()
self.assertFalse(self.manager_util.dependency_management_enabled)
def test_environment_wins_in_both_directions(self):
for config, environment, expected in [("off", "on", True), ("on", "off", False)]:
with self.subTest(config=config, environment=environment):
self.namespace["default_conf"]["dependency_management"] = config
with mock.patch.dict(os.environ, {"COMFYUI_MANAGER_DEPENDENCY_MANAGEMENT": environment}, clear=True):
self.namespace["read_dependency_management_mode"]()
self.assertEqual(self.manager_util.dependency_management_enabled, expected)
def test_lazy_requirements_of_a_scheduled_install_still_install_when_disabled(self):
# An install or update the user scheduled for the restart is explicit: its requirements are installed.
self.manager_util.dependency_management_enabled = False
with tempfile.TemporaryDirectory() as directory:
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
with (
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
):
self.namespace["execute_lazy_install_script"](directory, sys.executable)
self.namespace["process_wrap"].assert_called_once_with(
["pip", "install", "example-package==1.0"], directory
)
def test_lazy_requirements_are_installed_when_enabled(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, "requirements.txt").write_text("example-package==1.0\n")
with (
mock.patch.object(self.manager_util, "robust_readlines", return_value=["example-package==1.0\n"]),
mock.patch.object(self.manager_util, "make_pip_cmd", return_value=["pip", "install", "example-package==1.0"]),
):
self.namespace["execute_lazy_install_script"](directory, sys.executable)
self.namespace["process_wrap"].assert_called_once_with(
["pip", "install", "example-package==1.0"], directory
)
def test_explicit_node_install_script_is_not_gated(self):
self.manager_util.dependency_management_enabled = False
with tempfile.TemporaryDirectory() as directory:
Path(directory, "install.py").write_text("# Explicitly scheduled node installation\n")
self.namespace["execute_lazy_install_script"](directory, sys.executable)
call = self.namespace["process_wrap"].call_args
self.assertEqual(call.args, ([sys.executable, "install.py"], directory))
self.assertEqual(call.kwargs["env"]["COMFYUI_FOLDERS_BASE_PATH"], self.namespace["comfy_path"])
def test_disabled_startup_turns_the_resolver_off_so_installs_use_pip(self):
# The resolver batch does not run, so an install must not defer its requirements to it.
self.manager_util.dependency_management_enabled = False
self.manager_util.use_unified_resolver = True
_load_startup_nodes(
self.namespace,
lambda node: isinstance(node, ast.If)
and any(isinstance(part, ast.Attribute) and part.attr == "use_unified_resolver" for part in ast.walk(node.test)),
)
self.assertFalse(self.manager_util.use_unified_resolver)
self.assertFalse(self.namespace["_unified_resolver_succeeded"])
class IsOffValueTest(unittest.TestCase):
"""`is_off_value` is the single source of truth for the config/env vocabulary."""
def setUp(self):
self.manager_util = _import_manager_util()
def test_off_synonyms(self):
for value in ("off", "OFF", " false ", "0", "no", "Disabled"):
with self.subTest(value=value):
self.assertTrue(self.manager_util.is_off_value(value))
def test_on_values(self):
# Anything not in the off vocabulary — including the empty string and
# typos — keeps dependency management enabled. Better to be noisy than
# to silently swallow installs.
for value in ("on", "true", "1", "yes", "enabled", "auto", "", " ", "off-ish"):
with self.subTest(value=value):
self.assertFalse(self.manager_util.is_off_value(value))
if __name__ == "__main__":
unittest.main()
+71 -23
View File
@@ -2,10 +2,13 @@
git_helper.py runs as a subprocess on Windows and must NOT import comfyui_manager.
Tests validate: (1) no forbidden imports via AST, (2) subprocess-level standalone
execution, (3) get_backup_branch_name behavioural correctness.
execution, (3) get_backup_branch_name behavioural correctness, for the copy in
git_helper.py and the copy in timestamp_utils.py that both cores call, (4) the name
each core gets for a real repository.
"""
import ast
import importlib.util
import pathlib
import subprocess
import sys
@@ -16,6 +19,14 @@ import pytest
_GIT_HELPER_PATH = pathlib.Path(__file__).resolve().parents[2] / "comfyui_manager" / "common" / "git_helper.py"
def _load_common_module(name):
"""Load a standalone module of comfyui_manager/common without importing the package."""
spec = importlib.util.spec_from_file_location(name, _GIT_HELPER_PATH.with_name(f"{name}.py"))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# ---------------------------------------------------------------------------
# 1. No comfyui_manager imports (AST check — no execution)
# ---------------------------------------------------------------------------
@@ -81,12 +92,25 @@ def test_standalone_subprocess_can_load(tmp_path):
# ---------------------------------------------------------------------------
# 3. get_backup_branch_name behavioural tests (function extracted via AST)
# 3. get_backup_branch_name behavioural tests, for both copies of the function
# ---------------------------------------------------------------------------
@pytest.fixture(scope="module")
def _get_backup_branch_name():
"""Extract and compile get_backup_branch_name from git_helper.py source."""
@pytest.fixture(params=["git_helper", "timestamp_utils"])
def _get_backup_branch_name(request, monkeypatch):
"""Return get_backup_branch_name from git_helper.py or from timestamp_utils.py."""
import time
# Branch setup and the function call must use the same second.
strftime = time.strftime
fixed_time = time.struct_time((2026, 9, 17, 12, 0, 0, 3, 260, -1))
monkeypatch.setattr(time, "strftime", lambda fmt, *args: strftime(fmt, args[0] if args else fixed_time))
if request.param == "timestamp_utils":
timestamp_utils = _load_common_module("timestamp_utils")
monkeypatch.setattr(timestamp_utils, "get_timestamp_for_filename", lambda: time.strftime("%Y%m%d_%H%M%S"))
return timestamp_utils.get_backup_branch_name
# git_helper.py runs its command line on import, so the function is compiled from its source.
source = _GIT_HELPER_PATH.read_text(encoding="utf-8")
tree = ast.parse(source)
@@ -108,21 +132,21 @@ class _FakeHead:
class _FakeRepo:
def __init__(self, branch_names):
self.heads = [_FakeHead(n) for n in branch_names]
self._heads = [_FakeHead(n) for n in branch_names]
def list_heads(self):
return self._heads
def test_basic_name_format(_get_backup_branch_name):
import time
name = _get_backup_branch_name()
assert name.startswith("backup_")
expected = f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
assert name == expected
assert _get_backup_branch_name() == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
def test_no_collision(_get_backup_branch_name):
import time
repo = _FakeRepo(["main", "dev"])
name = _get_backup_branch_name(repo)
assert name.startswith("backup_")
assert _get_backup_branch_name(repo) == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
def test_single_collision(_get_backup_branch_name):
@@ -141,22 +165,16 @@ def test_multi_collision(_get_backup_branch_name):
assert name == f"backup_{ts}_3"
def test_repo_none_returns_base(_get_backup_branch_name):
name = _get_backup_branch_name(None)
assert name.startswith("backup_")
def test_repo_heads_exception_returns_base(_get_backup_branch_name):
"""When repo.heads raises, fall back to base name without suffix."""
def test_repo_list_heads_exception_returns_base(_get_backup_branch_name):
"""When listing branches fails, return the timestamp without a suffix."""
import time
class _BrokenRepo:
@property
def heads(self):
def list_heads(self):
raise RuntimeError("simulated git error")
name = _get_backup_branch_name(_BrokenRepo())
assert name.startswith("backup_")
assert "_1" not in name # no suffix — exception path returns base
assert name == f"backup_{time.strftime('%Y%m%d_%H%M%S')}"
def test_uuid_fallback_on_full_collision(_get_backup_branch_name):
@@ -171,3 +189,33 @@ def test_uuid_fallback_on_full_collision(_get_backup_branch_name):
# UUID suffix is 6 hex chars
suffix = name[len(f"backup_{ts}_"):]
assert len(suffix) == 6, f"Expected 6-char UUID suffix, got: {suffix}"
# ---------------------------------------------------------------------------
# 4. The name each core gets for a real repository
# ---------------------------------------------------------------------------
def _open_as_legacy_core(path):
"""The legacy core opens GitPython's git.Repo, which has `heads` and no `list_heads()`."""
import git
return git.Repo(path)
def _open_as_glob_core(path):
"""The glob core opens the repository through git_compat."""
return _load_common_module("git_compat").open_repo(str(path))
@pytest.mark.parametrize("open_repo", [_open_as_legacy_core, _open_as_glob_core], ids=["legacy core", "glob core"])
def test_real_repository_with_a_backup_from_the_same_second(open_repo, tmp_path, monkeypatch):
"""A backup branch of the same second exists, so the next free name is returned."""
git = pytest.importorskip("git")
timestamp_utils = _load_common_module("timestamp_utils")
monkeypatch.setattr(timestamp_utils, "get_timestamp_for_filename", lambda: "20260917_120000")
with git.Repo.init(tmp_path) as repo:
repo.index.commit("initial")
repo.create_head("backup_20260917_120000")
with open_repo(tmp_path) as repo:
assert timestamp_utils.get_backup_branch_name(repo) == "backup_20260917_120000_1"
+21 -4
View File
@@ -1,12 +1,14 @@
"""Cross-platform E2E environment setup for ComfyUI + Manager.
Creates an isolated ComfyUI installation with ComfyUI-Manager for E2E testing.
Idempotent: skips setup if marker file and key artifacts already exist.
Idempotent: skips setup if marker, key artifacts, and a supported venv already exist.
uv reads the Manager project's Python requirement when creating a venv.
Input env vars:
E2E_ROOT — target directory (required)
MANAGER_ROOT — manager repo root (default: auto-detected)
COMFYUI_BRANCH — ComfyUI branch to clone (default: master)
UV_PYTHON — optional uv Python request for a new venv
Output (last line of stdout):
E2E_ROOT=/path/to/environment
@@ -46,6 +48,18 @@ def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
return subprocess.run(cmd, check=True, **kwargs)
def check_python_version(python: str) -> None:
try:
version = subprocess.check_output(
[python, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"],
text=True,
).strip()
except (OSError, subprocess.CalledProcessError) as exc:
die(f"Cannot run venv Python: {python}: {exc}. Recreate the E2E environment with Python 3.10+.")
if tuple(map(int, version.split("."))) < (3, 10):
die(f"Python 3.10+ required, found {version} ({python}). Recreate the E2E environment.")
def detect_manager_root() -> Path:
"""Walk up from this script to find pyproject.toml."""
d = Path(__file__).resolve().parent
@@ -69,7 +83,7 @@ def venv_bin(root: Path, name: str) -> str:
return str(root / "venv" / "bin" / name)
def is_already_setup(root: Path, manager_root: Path) -> bool:
def is_already_setup(root: Path) -> bool:
marker = root / ".e2e_setup_complete"
comfyui = root / "comfyui"
venv = root / "venv"
@@ -119,7 +133,9 @@ def main() -> None:
branch = os.environ.get("COMFYUI_BRANCH", "master")
# Idempotency
if is_already_setup(root, manager_root):
if (root / "venv").is_dir():
check_python_version(venv_python(root))
if is_already_setup(root):
log("Environment already set up (marker file exists). Skipping.")
print(f"E2E_ROOT={root}")
return
@@ -138,7 +154,8 @@ def main() -> None:
log("Step 2/7: venv already exists, skipping")
else:
log("Step 2/7: Creating virtual environment...")
run(["uv", "venv", str(venv_dir)])
run(["uv", "venv", "--project", str(manager_root), str(venv_dir)])
check_python_version(venv_python(root))
py = venv_python(root)
+15 -16
View File
@@ -2,13 +2,13 @@
# setup_e2e_env.sh — Automated E2E environment setup for ComfyUI + Manager
#
# Creates an isolated ComfyUI installation with ComfyUI-Manager for E2E testing.
# Idempotent: skips setup if marker file and key artifacts already exist.
# Idempotent: skips setup if marker, key artifacts, and a supported venv already exist.
#
# Input env vars:
# E2E_ROOT — target directory (default: auto-generated via mktemp)
# MANAGER_ROOT — manager repo root (default: auto-detected from script location)
# COMFYUI_BRANCH — ComfyUI branch to clone (default: master)
# PYTHON — Python executable (default: python3)
# UV_PYTHON — optional uv Python request for a new venv
#
# Output (last line of stdout):
# E2E_ROOT=/path/to/environment
@@ -44,29 +44,25 @@ detect_manager_root() {
return 1
}
check_python_version() {
"$1" -c 'import sys
if sys.version_info < (3, 10):
sys.exit(f"Python 3.10+ required, found {sys.version_info.major}.{sys.version_info.minor}")' \
|| die "Cannot use venv Python: $1. Recreate the E2E environment with Python 3.10+."
}
# --- Validate prerequisites ---
validate_prerequisites() {
local py="${PYTHON:-python3}"
local missing=()
command -v git >/dev/null 2>&1 || missing+=("git")
command -v uv >/dev/null 2>&1 || missing+=("uv")
command -v "$py" >/dev/null 2>&1 || missing+=("$py")
if [[ ${#missing[@]} -gt 0 ]]; then
die "Missing prerequisites: ${missing[*]}"
fi
# Verify Python version >= 3.9
local py_version
py_version=$("$py" -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
local major minor
major="${py_version%%.*}"
minor="${py_version##*.}"
if [[ "$major" -lt 3 ]] || { [[ "$major" -eq 3 ]] && [[ "$minor" -lt 9 ]]; }; then
die "Python 3.9+ required, found $py_version"
fi
log "Prerequisites OK (python=$py_version, git=$(git --version | awk '{print $3}'), uv=$(uv --version 2>&1 | awk '{print $2}'))"
log "Prerequisites OK (git=$(git --version | awk '{print $3}'), uv=$(uv --version 2>&1 | awk '{print $2}'))"
}
# --- Check idempotency: skip if already set up ---
@@ -151,7 +147,6 @@ log "MANAGER_ROOT=$MANAGER_ROOT"
# Validate prerequisites
validate_prerequisites
PYTHON="${PYTHON:-python3}"
COMFYUI_BRANCH="${COMFYUI_BRANCH:-master}"
# Create or use E2E_ROOT
@@ -166,6 +161,9 @@ else
fi
# Idempotency check
if [[ -d "$E2E_ROOT/venv" ]]; then
check_python_version "$E2E_ROOT/venv/bin/python"
fi
check_already_setup "$E2E_ROOT"
# Cleanup trap: remove E2E_ROOT on failure only if we created it
@@ -191,7 +189,8 @@ log "Step 2/8: Creating virtual environment..."
if [[ -d "$E2E_ROOT/venv" ]]; then
log " venv already exists, skipping"
else
uv venv "$E2E_ROOT/venv"
uv venv --project "$MANAGER_ROOT" "$E2E_ROOT/venv"
check_python_version "$E2E_ROOT/venv/bin/python"
fi
VENV_PY="$E2E_ROOT/venv/bin/python"
+1 -1
View File
@@ -122,7 +122,7 @@ def _assert_config_ini_persists_across_reboot(
to work.
"""
try:
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
if resp.status_code == 403:
pytest.skip(
"reboot denied by security policy "
+23 -51
View File
@@ -149,14 +149,14 @@ class TestCsrfPostWorks:
def test_queue_reset_post_works(self, comfyui):
"""POST queue/reset should succeed (the same path rejects GET)."""
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
assert resp.status_code == 200, (
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
)
def test_snapshot_save_post_works(self, comfyui):
"""POST snapshot/save should succeed."""
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
assert resp.status_code == 200, (
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
)
@@ -168,6 +168,7 @@ class TestCsrfPostWorks:
requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": items[0]},
headers={"Content-Type": "application/json"},
timeout=10,
)
@@ -207,18 +208,10 @@ class TestCsrfReadEndpointsStillAllowGet:
# Content-Type gate — second CSRF mitigation layer
# ---------------------------------------------------------------------------
#
# GET→POST conversion alone does NOT block <form method=POST> from a malicious
# cross-origin page, because browsers mark form submissions with one of three
# CORS "simple request" Content-Types (Fetch spec §3.2.3) and do NOT preflight
# them. These 9 high-risk state mutation endpoints therefore additionally
# reject those three MIME types at the handler entry. Bare POST (no body) and
# application/json remain accepted — same-origin fetch() and existing
# manager-core JS callers are unaffected.
#
# Source of truth for the gated handler list:
# comfyui_manager/common/manager_security.py :: reject_simple_form_post
# comfyui_manager/glob/manager_server.py :: 9 handlers call it
FORM_REJECTED_POST_ENDPOINTS = [
# A page of another origin can make a browser send a POST without a CORS
# preflight: as a form, or with no Content-Type at all, with or without a body.
# It cannot send application/json without a preflight.
BODYLESS_POST_ENDPOINTS = [
"/v2/manager/queue/update_all",
"/v2/snapshot/remove",
"/v2/snapshot/restore",
@@ -228,65 +221,47 @@ FORM_REJECTED_POST_ENDPOINTS = [
"/v2/manager/queue/update_comfyui",
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
# migrated from query-string to JSON body, now a body-reading handler.
# Per the module policy in common/manager_security.py, body-reading
# handlers are NOT gated (CORS preflight on application/json already
# blocks cross-origin form POST forgery).
"/v2/manager/reboot",
]
SIMPLE_FORM_CONTENT_TYPES = [
NOT_JSON_CONTENT_TYPES = [
None,
"application/x-www-form-urlencoded",
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
"text/plain",
]
class TestFormContentTypeRejected:
"""Every gated state-changing endpoint MUST reject CORS simple-request
Content-Types to block preflight-less <form method=POST> CSRF.
Matrix: 9 endpoints × 3 Content-Types = 27 assertions.
"""
class TestContentTypeThatIsNotJsonRejected:
@pytest.mark.parametrize(
"content_type",
SIMPLE_FORM_CONTENT_TYPES,
ids=["urlencoded", "multipart", "textplain"],
NOT_JSON_CONTENT_TYPES,
ids=["none", "urlencoded", "multipart", "textplain"],
)
@pytest.mark.parametrize(
"path",
FORM_REJECTED_POST_ENDPOINTS,
ids=FORM_REJECTED_POST_ENDPOINTS,
BODYLESS_POST_ENDPOINTS,
ids=BODYLESS_POST_ENDPOINTS,
)
def test_form_content_type_rejected(self, comfyui, path, content_type):
"""POST with a simple-form Content-Type must be rejected with 400.
The handler's Content-Type gate runs BEFORE the security_level check,
def test_content_type_that_is_not_json_rejected(self, comfyui, path, content_type):
"""The handler's Content-Type gate runs BEFORE the security_level check,
so the expected status is 400 even under security levels that would
otherwise return 403.
"""
resp = requests.post(
f"{BASE_URL}{path}",
headers={"Content-Type": content_type},
data="", # empty body still counts: browsers would not preflight
headers={} if content_type is None else {"Content-Type": content_type},
data="",
timeout=10,
)
assert resp.status_code == 400, (
f"CSRF FORM-POST GATE BYPASS: POST {path} with "
f"CSRF GATE BYPASS: POST {path} with "
f"Content-Type={content_type!r} returned {resp.status_code} "
f"(expected 400): {resp.text[:200]}"
)
class TestNoBodyPostStillAccepted:
"""Positive control: bare POST (no body, no Content-Type) must still pass
the form-content-type gate.
The existing frontend (snapshot.js, comfyui-manager.js, etc.) issues
fetch()/XHR POSTs without an explicit body for these idempotent-ish
operations; a regression here would break those callers.
"""
class TestJsonPostWithoutBodyAccepted:
@pytest.mark.parametrize(
"path",
# Subset — pick endpoints whose happy path is deterministic under the
@@ -300,16 +275,13 @@ class TestNoBodyPostStillAccepted:
],
ids=["queue-reset", "queue-start", "snapshot-save"],
)
def test_no_body_post_still_accepted(self, comfyui, path):
"""Bare POST (no Content-Type, no body) must NOT be rejected by the
form-content-type gate. Any response other than 400-with-form-text
proves the gate did not fire."""
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
def test_json_post_without_body_accepted(self, comfyui, path):
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
# The gate returns 400 with a very specific text. Non-gate 400s
# (validation errors, etc.) are allowed — we only assert the gate
# itself didn't trigger.
if resp.status_code == 400:
assert "Invalid Content-Type for this endpoint" not in resp.text, (
f"POST {path} (bare) hit the form-content-type gate: "
f"POST {path} (application/json) hit the content-type gate: "
f"{resp.text[:200]}"
)
+22 -35
View File
@@ -182,14 +182,14 @@ class TestLegacyCsrfPostWorks:
def test_queue_reset_post_works(self, comfyui_legacy):
"""POST queue/reset should succeed (the same path rejects GET)."""
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
assert resp.status_code == 200, (
f"POST queue/reset should succeed, got {resp.status_code}: {resp.text[:200]}"
)
def test_snapshot_save_post_works(self, comfyui_legacy):
"""POST snapshot/save should succeed on legacy."""
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
assert resp.status_code == 200, (
f"POST snapshot/save should succeed, got {resp.status_code}: {resp.text[:200]}"
)
@@ -201,6 +201,7 @@ class TestLegacyCsrfPostWorks:
requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": items[0]},
headers={"Content-Type": "application/json"},
timeout=10,
)
@@ -280,11 +281,10 @@ class TestLegacyIsLegacyManagerUIReturnsTrue:
# Content-Type gate — legacy-side parity with test_e2e_csrf.py
# ---------------------------------------------------------------------------
#
# The 9 legacy handlers mirrored from glob each call
# manager_security.reject_simple_form_post() before their security-level
# check. This suite verifies the legacy route table enforces the same
# CORS-simple-request Content-Type rejection contract.
LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
# A page of another origin can make a browser send a POST without a CORS
# preflight: as a form, or with no Content-Type at all, with or without a body.
# It cannot send application/json without a preflight.
LEGACY_BODYLESS_POST_ENDPOINTS = [
"/v2/manager/queue/update_all",
"/v2/snapshot/remove",
"/v2/snapshot/restore",
@@ -293,57 +293,46 @@ LEGACY_FORM_REJECTED_POST_ENDPOINTS = [
"/v2/manager/queue/start",
"/v2/manager/queue/update_comfyui",
# "/v2/comfyui_manager/comfyui_switch_version" — removed in WI #258:
# migrated from query-string to JSON body on legacy + glob in parallel,
# body-reading handler is not Content-Type-gated (see module policy in
# common/manager_security.py).
# migrated from query-string to JSON body on legacy + glob in parallel.
"/v2/manager/reboot",
]
LEGACY_SIMPLE_FORM_CONTENT_TYPES = [
LEGACY_NOT_JSON_CONTENT_TYPES = [
None,
"application/x-www-form-urlencoded",
"multipart/form-data; boundary=----WebKitFormBoundaryTest",
"text/plain",
]
class TestLegacyFormContentTypeRejected:
"""Legacy counterpart to TestFormContentTypeRejected in test_e2e_csrf.py.
Matrix: 9 endpoints × 3 Content-Types = 27 assertions against the legacy
route table.
"""
class TestLegacyContentTypeThatIsNotJsonRejected:
@pytest.mark.parametrize(
"content_type",
LEGACY_SIMPLE_FORM_CONTENT_TYPES,
ids=["urlencoded", "multipart", "textplain"],
LEGACY_NOT_JSON_CONTENT_TYPES,
ids=["none", "urlencoded", "multipart", "textplain"],
)
@pytest.mark.parametrize(
"path",
LEGACY_FORM_REJECTED_POST_ENDPOINTS,
ids=LEGACY_FORM_REJECTED_POST_ENDPOINTS,
LEGACY_BODYLESS_POST_ENDPOINTS,
ids=LEGACY_BODYLESS_POST_ENDPOINTS,
)
def test_form_content_type_rejected(
def test_content_type_that_is_not_json_rejected(
self, comfyui_legacy, path, content_type
):
"""POST with a simple-form Content-Type must be rejected with 400
on the legacy route table as well."""
resp = requests.post(
f"{BASE_URL}{path}",
headers={"Content-Type": content_type},
headers={} if content_type is None else {"Content-Type": content_type},
data="",
timeout=10,
)
assert resp.status_code == 400, (
f"CSRF FORM-POST GATE BYPASS (legacy): POST {path} with "
f"CSRF GATE BYPASS (legacy): POST {path} with "
f"Content-Type={content_type!r} returned {resp.status_code} "
f"(expected 400): {resp.text[:200]}"
)
class TestLegacyNoBodyPostStillAccepted:
"""Positive control for the legacy route table: bare POST still works."""
class TestLegacyJsonPostWithoutBodyAccepted:
@pytest.mark.parametrize(
"path",
[
@@ -353,13 +342,11 @@ class TestLegacyNoBodyPostStillAccepted:
],
ids=["queue-reset", "queue-start", "snapshot-save"],
)
def test_no_body_post_still_accepted(self, comfyui_legacy, path):
"""Bare POST (no Content-Type, no body) must not hit the gate on
legacy either."""
resp = requests.post(f"{BASE_URL}{path}", timeout=30)
def test_json_post_without_body_accepted(self, comfyui_legacy, path):
resp = requests.post(f"{BASE_URL}{path}", headers={"Content-Type": "application/json"}, timeout=30)
if resp.status_code == 400:
assert "Invalid Content-Type for this endpoint" not in resp.text, (
f"POST {path} (bare, legacy) hit the form-content-type gate: "
f"POST {path} (application/json, legacy) hit the content-type gate: "
f"{resp.text[:200]}"
)
+18 -4
View File
@@ -49,6 +49,10 @@ PACK_VERSION = "1.0.1"
POLL_TIMEOUT = 30 # max seconds to wait for an operation
POLL_INTERVAL = 0.5 # seconds between polls
# A fresh environment has no cache of the Registry list. Manager fetches the
# list when the server starts, and an install is refused until it is cached.
REGISTRY_TIMEOUT = 300
pytestmark = pytest.mark.skipif(
not E2E_ROOT
or not os.path.isfile(os.path.join(E2E_ROOT, ".e2e_setup_complete")),
@@ -98,7 +102,7 @@ def _queue_task(task: dict) -> None:
timeout=10,
)
resp.raise_for_status()
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
def _remove_pack(name: str) -> None:
@@ -143,6 +147,11 @@ def _wait_for(predicate, timeout=POLL_TIMEOUT, interval=POLL_INTERVAL):
return False
def _registry_list_is_cached() -> bool:
cache = os.path.join(COMFYUI_PATH, "user", "__manager", "cache")
return os.path.isdir(cache) and any(name.endswith("_nodes.json") for name in os.listdir(cache))
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -152,9 +161,14 @@ def comfyui():
"""Start ComfyUI once for the module, stop after all tests."""
_remove_pack(PACK_DIR_NAME)
pid = _start_comfyui()
yield pid
_stop_comfyui()
_remove_pack(PACK_DIR_NAME)
try:
assert _wait_for(_registry_list_is_cached, timeout=REGISTRY_TIMEOUT), (
f"Manager did not cache the Registry list within {REGISTRY_TIMEOUT}s; an install fails without it"
)
yield pid
finally:
_stop_comfyui()
_remove_pack(PACK_DIR_NAME)
# ---------------------------------------------------------------------------
+666
View File
@@ -0,0 +1,666 @@
"""Real ComfyUI HTTP/queue/install tests with a local CNR service and harmless ZIPs.
Run with E2E_ROOT pointing to the existing ComfyUI + venv fixture. Each server
uses an isolated base directory; no installed nodes or user config are changed.
"""
import ast
import configparser
import io
import json
import os
import socket
import subprocess
import threading
import time
import uuid
import zipfile
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qs, urlparse
import pytest
import requests
E2E_ROOT = Path(os.environ.get('E2E_ROOT', '/nonexistent'))
REPO_ROOT = Path(__file__).resolve().parents[2]
pytestmark = pytest.mark.skipif(
not (E2E_ROOT / 'venv/bin/python').is_file(), reason='E2E_ROOT is required',
)
PACKS = ['fixture-active', 'fixture-flagged', 'fixture-pending', 'fixture-banned',
'fixture-latest', 'fixture-switch', 'fixture-update', 'fixture-reinstall', 'fixture-snapshot']
@pytest.fixture(scope='module')
def registry():
calls = []
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass
def do_GET(self):
parsed = urlparse(self.path)
calls.append(parsed.path + ('?' + parsed.query if parsed.query else ''))
parts = parsed.path.strip('/').split('/')
version = parse_qs(parsed.query).get('version', ['2.0.0'])[0]
node = parts[1] if len(parts) > 1 else ''
base = f'http://127.0.0.1:{self.server.server_port}'
def metadata(node, version):
status = {'1.0.0': 'Active', '1.1.0': 'Active', '2.0.0': 'Flagged', '3.0.0': 'Pending'}[version]
return {'id': f'{node}-{version}', 'node_id': node, 'version': version,
'status': 'NodeVersionStatus' + status, 'dependencies': [],
'downloadUrl': f'{base}/zip/{node}/{version}'}
status = 200
if parts[0] == 'zip':
node, version = parts[1:]
archive = io.BytesIO()
with zipfile.ZipFile(archive, 'w') as z:
z.writestr('__init__.py', 'NODE_CLASS_MAPPINGS = {}\n')
z.writestr('pyproject.toml', f'[project]\nname = "{node}"\nversion = "{version}"\n')
z.writestr('install.py', 'from pathlib import Path\n'
f'Path("installed.txt").write_text("{version}")\n')
body = archive.getvalue()
elif parsed.path == '/nodes':
body = json.dumps({'nodes': [
{'id': name, 'name': name, 'description': '', 'status': 'NodeStatusActive',
'repository': f'https://example.invalid/{name}',
'publisher': {'id': 'fixture', 'name': 'Fixture'},
'latest_version': metadata(name, '2.0.0')}
for name in PACKS], 'totalPages': 1}).encode()
elif len(parts) == 3 and parts[0] == 'nodes' and parts[2] == 'install':
if node == 'fixture-banned':
status, body = 404, b'{"message":"Not found"}'
else:
body = json.dumps(metadata(node, version)).encode()
else:
status, body = 404, b'{}'
self.send_response(status)
self.send_header('Content-Length', str(len(body)))
self.send_header('Content-Type', 'application/zip' if parts[0] == 'zip' else 'application/json')
self.end_headers()
self.wfile.write(body)
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield SimpleNamespace(url=f'http://127.0.0.1:{server.server_port}', calls=calls)
server.shutdown()
server.server_close()
thread.join()
REGISTRY_BOOTSTRAP = '''
import json, os, urllib.request
from comfyui_manager.common import cnr_utils, manager_util
cnr_utils.base_url = os.environ['CM_E2E_REGISTRY']
with urllib.request.urlopen(os.environ['CM_E2E_CATALOG_URL']) as response:
manager_util.save_to_cache(cnr_utils.base_url + '/nodes', json.load(response))
'''
BOOTSTRAP = '''
import os, runpy, sys
sys.argv = [os.environ['CM_E2E_MAIN'], *sys.argv[1:]]
import comfy.options
comfy.options.enable_args_parsing()
''' + REGISTRY_BOOTSTRAP + "\nrunpy.run_path(sys.argv[0], run_name='__main__')\n"
RESTORE_BOOTSTRAP = '''
import os
from comfy.cli_args import args
args.base_directory = os.environ['CM_E2E_BASE']
''' + REGISTRY_BOOTSTRAP + '''
from comfyui_manager.legacy import manager_core as core
core.unified_manager.custom_node_map_cache[(core.normalize_channel('default'), 'cache')] = core.NormalizedKeyDict()
'''
def prepare_environment(root, override, security, registry):
(root / 'custom_nodes').mkdir(exist_ok=True)
config_dir = root / 'user/__manager'
config_dir.mkdir(parents=True, exist_ok=True)
(config_dir / 'config.ini').write_text(
'[default]\nnetwork_mode = offline\nuse_uv = false\n'
f'security_level = {security}\nallow_flagged_nodepack_install = {override}\n'
)
# The real restore subprocess inherits the same isolated Registry and paths.
(root / 'sitecustomize.py').write_text(
"import sys\nif sys.argv[0] == '-m' and 'cm_cli' in sys.orig_argv:\n"
+ '\n'.join(' ' + line for line in RESTORE_BOOTSTRAP.splitlines())
)
env = dict(os.environ, PYTHONUNBUFFERED='1',
PYTHONPATH=os.pathsep.join([str(root), str(REPO_ROOT), str(E2E_ROOT / 'comfyui')]),
COMFYUI_PATH=str(E2E_ROOT / 'comfyui'), COMFYUI_FOLDERS_BASE_PATH=str(root),
CM_E2E_BASE=str(root),
CM_E2E_MAIN=str(E2E_ROOT / 'comfyui/main.py'), CM_E2E_REGISTRY=registry.url,
CM_E2E_CATALOG_URL=getattr(registry, 'catalog_url', registry.url + '/nodes'))
return env
@contextmanager
def running_server(root, tree, listen, override, security, registry):
env = prepare_environment(root, override, security, registry)
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
base = f'http://127.0.0.1:{port}'
command = [str(E2E_ROOT / 'venv/bin/python'), '-c', BOOTSTRAP,
'--cpu', '--enable-manager', '--base-directory', str(root),
'--listen', listen, '--port', str(port),
'--database-url', f'sqlite:///{root / "comfyui.db"}']
if tree == 'legacy':
command.append('--enable-manager-legacy-ui')
log_path = root / 'server.log'
with log_path.open('w') as log:
process = subprocess.Popen(command, env=env, cwd=E2E_ROOT / 'comfyui', stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
assert process.poll() is None, log_path.read_text()
try:
if requests.get(base + '/system_stats', timeout=1).status_code == 200:
break
except requests.RequestException:
pass
time.sleep(.2)
else:
pytest.fail('ComfyUI did not start:\n' + log_path.read_text())
yield SimpleNamespace(root=root, tree=tree, base=base, listen=listen,
override=override, security=security, registry=registry,
process=process, command=command, env=env)
finally:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
@pytest.fixture(scope='module', params=[
(tree, listen, override, security)
for tree in ('legacy', 'glob')
for listen, override, security in [
('127.0.0.1', False, 'normal'),
('0.0.0.0', False, 'normal'),
('0.0.0.0', True, 'normal'),
('0.0.0.0', True, 'strong'),
('127.0.0.1', False, 'strong'),
]
], ids=lambda row: '-'.join(map(str, row)))
def comfy_server(request, tmp_path_factory, registry):
tree, listen, override, security = request.param
root = tmp_path_factory.mktemp('flagged-' + tree)
with running_server(root, tree, listen, override, security, registry) as server:
yield server
def install(server, node, version, operation='install', *, repository='https://example.invalid/fixture'):
ui_id = uuid.uuid4().hex
params = {'id': node, 'version': '1.0.0', 'selected_version': version,
'mode': 'cache', 'channel': 'default', 'ui_id': ui_id,
'repository': repository}
if server.tree == 'legacy':
response = requests.post(server.base + '/v2/manager/queue/batch',
json={'batch_id': ui_id, operation: [params]}, timeout=10)
response.raise_for_status()
if response.json()['failed']:
return response.json()
query = {'id': ui_id}
else:
if operation == 'update':
params = {'node_name': node, 'node_ver': '1.0.0'}
response = requests.post(server.base + '/v2/manager/queue/task', json={
'ui_id': ui_id, 'client_id': 'flagged-e2e', 'kind': operation, 'params': params,
}, timeout=10)
response.raise_for_status()
requests.post(server.base + '/v2/manager/queue/start', headers={'Content-Type': 'application/json'}, timeout=10).raise_for_status()
query = {'ui_id': ui_id}
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
response = requests.get(server.base + '/v2/manager/queue/history', params=query, timeout=5)
if response.status_code == 200:
data = response.json()
if server.tree == 'legacy' or data.get('history'):
return data
time.sleep(.1)
pytest.fail('Install did not complete:\n' + (server.root / 'server.log').read_text()[-6000:])
@pytest.mark.parametrize('command', ['save-snapshot', 'restore-snapshot'])
def test_cli_does_not_create_server_whitelist(tmp_path, command):
base = tmp_path / 'cli-base'
(base / 'custom_nodes').mkdir(parents=True)
server_manager = tmp_path / 'server-user/__manager'
server_manager.mkdir(parents=True)
whitelist = server_manager / 'nodepack-whitelist.list'
whitelist.write_text('comfyui-impact-pack\n')
requested_user = tmp_path / 'requested-user'
# Stop after CLI initialization, before any snapshot work or network access.
if command == 'save-snapshot':
arguments = [command, '--user-directory', str(requested_user),
'--output', str(tmp_path / 'invalid-extension.txt')]
expected_error = 'output path should be either'
else:
arguments = [command, str(tmp_path / 'missing-snapshot.json')]
expected_error = 'is not exists.'
bootstrap = '''
import runpy, sys
from comfy.cli_args import args
args.base_directory = sys.argv[1]
sys.argv = ['cm-cli', *sys.argv[2:]]
runpy.run_module('cm_cli', run_name='__main__')
'''
env = dict(os.environ,
PYTHONPATH=os.pathsep.join([str(REPO_ROOT), str(E2E_ROOT / 'comfyui')]),
COMFYUI_PATH=str(E2E_ROOT / 'comfyui'), COMFYUI_FOLDERS_BASE_PATH=str(base),
_COMFYUI_MANAGER_CNR_ALLOW_FLAGGED='false',
_COMFYUI_MANAGER_CNR_WHITELIST_DIR=str(server_manager))
result = subprocess.run([str(E2E_ROOT / 'venv/bin/python'), '-c', bootstrap,
str(base), *arguments], env=env, cwd=tmp_path,
capture_output=True, text=True, timeout=30)
output = result.stdout + result.stderr
assert result.returncode == 1 and expected_error in output, output
assert whitelist.read_text() == 'comfyui-impact-pack\n'
assert sorted(tmp_path.rglob('nodepack-whitelist.list')) == [whitelist]
def assert_terminal_guidance(log):
for detail in ('--listen 127.0.0.1', '--listen ::1', '0.0.0.0', '[default]',
'allow_flagged_nodepack_install = true', 'config.ini', 'nodepack-whitelist.list',
'trusted private network', 'Restart ComfyUI'):
assert detail in log
def assert_flagged_denial(result, log):
message = json.dumps(result)
assert ('This action is not allowed by the current security configuration. '
'See the terminal for details.') in message, result
assert 'allow_flagged_nodepack_install' not in message, result
assert '--listen' not in message, result
assert_terminal_guidance(log)
@pytest.mark.parametrize('node,version', [
('fixture-active', '1.0.0'), ('fixture-flagged', '2.0.0'),
('fixture-pending', '3.0.0'), ('fixture-banned', '1.0.0'),
('fixture-latest', 'latest'),
])
def test_install_policy(comfy_server, node, version):
server = comfy_server
log_before = len((server.root / 'server.log').read_text())
before = len(server.registry.calls)
result = install(server, node, version)
calls = server.registry.calls[before:]
strong = server.security == 'strong'
flagged = version in ('2.0.0', 'latest')
allowed = not strong and node != 'fixture-banned' and (
not flagged or server.override or server.listen == '127.0.0.1')
marker = server.root / 'custom_nodes' / node / 'installed.txt'
assert marker.exists() is allowed, (result, (server.root / 'server.log').read_text()[-6000:])
assert sum('/install' in call for call in calls) == (0 if strong else 1), calls
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
if allowed:
assert marker.read_text() == ('2.0.0' if version == 'latest' else version)
if server.tree == 'legacy':
assert list(result['nodepack_result'].values()) == ['success'], result
else:
assert result['history']['result'] == 'success', result
elif flagged and not strong:
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
def test_whitelist_install_policy(tmp_path, registry, tree):
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry) as server:
log_path = tmp_path / 'server.log'
whitelist = tmp_path / 'user/__manager/nodepack-whitelist.list'
template = whitelist.read_text()
assert template.strip() and all(line.lstrip().startswith('#') for line in template.splitlines() if line.strip())
# Edited after startup: no restart is required to pick up this policy.
whitelist.write_text('Fixture-Flagged\nfixture-banned\nfixture-switch\n')
for node, version, expected_error in [
('fixture-flagged', '2.0.0', None),
('fixture-latest', 'latest', 'This action is not allowed by the current security configuration.'),
('fixture-banned', '1.0.0', 'not available node: fixture-banned@1.0.0'),
]:
log_before = len(log_path.read_text())
before = len(registry.calls)
result = install(server, node, version)
allowed = expected_error is None
marker = tmp_path / 'custom_nodes' / node / 'installed.txt'
assert marker.exists() is allowed, (result, log_path.read_text()[log_before:])
calls = registry.calls[before:]
assert any(call.startswith('/zip/') for call in calls) is allowed
assert sum('/install' in call for call in calls) == 1, calls
assert ('permitted by nodepack whitelist' in log_path.read_text()[log_before:]) is allowed
assert 'permitted by nodepack whitelist' not in json.dumps(result)
if allowed:
assert marker.read_text() == version
if tree == 'legacy':
assert list(result['nodepack_result'].values()) == ['success'], result
else:
assert result['history']['result'] == 'success', result
else:
assert expected_error in json.dumps(result), result
if node == 'fixture-latest':
assert_flagged_denial(result, log_path.read_text()[log_before:])
# Removing the file revokes the exception for another listed pack.
whitelist.unlink()
log_before = len(log_path.read_text())
before = len(registry.calls)
result = install(server, 'fixture-switch', '2.0.0')
assert not (tmp_path / 'custom_nodes/fixture-switch').exists(), result
calls = registry.calls[before:]
assert sum('/install' in call for call in calls) == 1, calls
assert not any(call.startswith('/zip/') for call in calls), calls
assert_flagged_denial(result, log_path.read_text()[log_before:])
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
def test_whitelist_does_not_override_strong_security(tmp_path, registry, tree):
with running_server(tmp_path, tree, '0.0.0.0', False, 'strong', registry) as server:
(tmp_path / 'user/__manager/nodepack-whitelist.list').write_text('Fixture-Flagged\n')
log_path = tmp_path / 'server.log'
log_before = len(log_path.read_text())
before = len(registry.calls)
result = install(server, 'fixture-flagged', '2.0.0')
if tree == 'legacy':
assert result['failed'] == ['fixture-flagged'], result
else:
assert result['history']['result'] == 'failed', result
assert 'normal or below' in log_path.read_text()[log_before:]
assert not (tmp_path / 'custom_nodes/fixture-flagged').exists()
assert not any('/install' in call or call.startswith('/zip/') for call in registry.calls[before:])
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
@pytest.mark.parametrize('keep_listed', [False, True])
def test_restart_rechecks_whitelist(tmp_path, registry, tree, keep_listed):
whitelist = tmp_path / 'user/__manager/nodepack-whitelist.list'
marker = tmp_path / 'custom_nodes/fixture-switch/installed.txt'
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry) as server:
whitelist.write_text('Fixture-Switch\n')
install(server, 'fixture-switch', '1.0.0')
install(server, 'fixture-switch', '2.0.0')
reserved = tmp_path / 'user/__manager/startup-scripts/install-scripts.txt'
assert 'NodeVersionStatusFlagged' in reserved.read_text()
assert marker.read_text() == '1.0.0'
if not keep_listed:
whitelist.write_text('fixture-other\n')
before = len(registry.calls)
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry):
assert whitelist.read_text() == ('Fixture-Switch\n' if keep_listed else 'fixture-other\n')
calls = registry.calls[before:]
assert not any('/install' in call for call in calls), calls
assert any(call.startswith('/zip/') for call in calls) is keep_listed, calls
assert marker.read_text() == ('2.0.0' if keep_listed else '1.0.0')
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
def test_scheduled_snapshot_uses_whitelist(tmp_path, registry, tree):
config_dir = tmp_path / 'user/__manager'
startup_dir = config_dir / 'startup-scripts'
startup_dir.mkdir(parents=True)
(config_dir / 'nodepack-whitelist.list').write_text('Fixture-Flagged\n')
reservation = startup_dir / 'restore-snapshot.json'
reservation.write_text(json.dumps({
'cnr_custom_nodes': {'fixture-flagged': '2.0.0', 'fixture-latest': '2.0.0'},
'git_custom_nodes': {}, 'file_custom_nodes': [],
}))
before = len(registry.calls)
with running_server(tmp_path, tree, '0.0.0.0', False, 'normal', registry):
log = (tmp_path / 'server.log').read_text()
assert 'Restore snapshot done.' in log, log[-6000:]
assert 'Restore snapshot failed.' not in log, log[-6000:]
assert not reservation.exists()
installed = tmp_path / 'custom_nodes/fixture-flagged'
assert 'version = "2.0.0"' in (installed / 'pyproject.toml').read_text()
assert not (tmp_path / 'custom_nodes/fixture-latest').exists()
assert "CNR installation of 'fixture-flagged' permitted by nodepack whitelist" in log, log[-6000:]
assert "CNR installation of 'fixture-latest' permitted by nodepack whitelist" not in log
calls = registry.calls[before:]
assert sum('/install' in call for call in calls) == 2, calls
# torchvision may probe redirects before downloading the same archive.
assert {call for call in calls if call.startswith('/zip/')} == {'/zip/fixture-flagged/2.0.0'}
@pytest.mark.parametrize('operation', ['install', 'update'])
def test_flagged_transition_preserves_active_version(comfy_server, operation):
server = comfy_server
if server.security == 'strong':
pytest.skip('No installed version in strong mode')
# Keep this state separate from test_install_policy, regardless of test order.
node = 'fixture-switch' if operation == 'install' else 'fixture-update'
marker = server.root / 'custom_nodes' / node / 'installed.txt'
install(server, node, '1.0.0')
log_before = len((server.root / 'server.log').read_text())
before = len(server.registry.calls)
result = install(server, node, '2.0.0', operation)
calls = server.registry.calls[before:]
assert sum('/install' in call for call in calls) == 1
assert not any(call.startswith('/zip/') for call in calls)
assert marker.read_text() == '1.0.0'
reserved = server.root / 'user/__manager/startup-scripts/install-scripts.txt'
if server.override or server.listen == '127.0.0.1':
assert '#LAZY-CNR-SWITCH-SCRIPT' in reserved.read_text()
if server.tree == 'legacy':
assert list(result['nodepack_result'].values()) == ['success'], result
else:
assert result['history']['result'] == 'success', result
else:
assert not reserved.exists()
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
@pytest.mark.parametrize('listen,override', [
('127.0.0.1', False), ('0.0.0.0', False), ('0.0.0.0', True),
])
@pytest.mark.parametrize('version', ['1.0.0', '2.0.0'])
def test_legacy_reinstall_preserves_denied_pack_and_runs_allowed_script(
tmp_path, registry, listen, override, version):
with running_server(tmp_path, 'legacy', listen, override, 'normal', registry) as server:
node = 'fixture-reinstall'
install(server, node, '1.0.0')
marker = tmp_path / 'custom_nodes' / node / 'installed.txt'
assert marker.read_text() == '1.0.0'
original = (marker.read_bytes(), marker.stat().st_mtime_ns)
stale = marker.parent / 'stale.txt'
stale.write_text('removed only by an allowed reinstall')
before = len(registry.calls)
log_before = len((server.root / 'server.log').read_text())
result = install(server, node, version, 'reinstall')
calls = registry.calls[before:]
allowed = version == '1.0.0' or override or listen == '127.0.0.1'
assert sum('/install' in call for call in calls) == 1, calls
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
if allowed:
assert list(result['nodepack_result'].values()) == ['success'], result
assert marker.read_text() == version, result
assert not stale.exists()
else:
assert_flagged_denial(result, (server.root / 'server.log').read_text()[log_before:])
assert marker.exists(), 'Rejected reinstall removed the existing pack'
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
assert stale.exists()
def test_nonlocal_override_does_not_allow_nightly(comfy_server):
server = comfy_server
if server.listen == '127.0.0.1':
pytest.skip('This regression checks the non-local Git gate')
log_path = server.root / 'server.log'
log_before = len(log_path.read_text())
before = len(server.registry.calls)
result = install(server, 'fixture-nightly', 'nightly')
# A missing node or a failed clone must not count as a security rejection.
if server.tree == 'legacy':
assert result['failed'] == ['fixture-nightly'], result
else:
assert result['history']['result'] == 'failed', result
expected_reason = ('normal or below' if server.security == 'strong' and server.tree == 'legacy'
else 'network_mode must be set to `personal_cloud`')
assert expected_reason in log_path.read_text()[log_before:], result
assert not (server.root / 'custom_nodes/fixture-nightly').exists()
assert not any('/install' in call or call.startswith('/zip/')
for call in server.registry.calls[before:])
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
@pytest.mark.parametrize('listen,override,restart_listen,restart_override,allowed', [
('127.0.0.1', False, '0.0.0.0', False, False),
('0.0.0.0', True, '0.0.0.0', False, False),
('127.0.0.1', False, '127.0.0.1', False, True),
('0.0.0.0', True, '0.0.0.0', True, True),
])
@pytest.mark.parametrize('stored_status', [True, False])
def test_restart_applies_current_policy_without_registry_query(
tree, listen, override, restart_listen, restart_override, allowed, stored_status, tmp_path, registry):
with running_server(tmp_path, tree, listen, override, 'normal', registry) as server:
marker = server.root / 'custom_nodes/fixture-active/installed.txt'
install(server, 'fixture-active', '1.0.0')
reserved = server.root / 'user/__manager/startup-scripts/install-scripts.txt'
install(server, 'fixture-active', '2.0.0')
assert 'NodeVersionStatusFlagged' in reserved.read_text()
original_marker = (marker.read_bytes(), marker.stat().st_mtime_ns)
server.process.terminate()
server.process.wait(timeout=10)
if not stored_status:
record = ast.literal_eval(reserved.read_text().strip())
assert record[1] == '#LAZY-CNR-SWITCH-SCRIPT'
assert len(record) == 9
reserved.write_text(repr(record[:8]) + '\n')
config_path = server.root / 'user/__manager/config.ini'
config = configparser.ConfigParser()
config.read(config_path)
config['default']['allow_flagged_nodepack_install'] = str(restart_override)
with config_path.open('w') as config_file:
config.write(config_file)
command = list(server.command)
command[command.index('--listen') + 1] = restart_listen
before = len(server.registry.calls)
log_path = server.root / 'restart.log'
with log_path.open('w') as log:
process = subprocess.Popen(command, env=server.env, cwd=E2E_ROOT / 'comfyui',
stdout=log, stderr=subprocess.STDOUT)
try:
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
assert process.poll() is None, log_path.read_text()[-6000:]
try:
if requests.get(server.base + '/system_stats', timeout=1).status_code == 200:
break
except requests.RequestException:
pass
time.sleep(.2)
else:
pytest.fail(log_path.read_text()[-6000:])
calls = server.registry.calls[before:]
assert not any('/install' in call for call in calls), calls
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
if allowed:
assert marker.read_text() == '2.0.0', log_path.read_text()[-6000:]
else:
if stored_status:
assert_terminal_guidance(log_path.read_text())
else:
assert 'stored Registry status is missing' in log_path.read_text()
assert 'Request the installation again' in log_path.read_text()
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original_marker
finally:
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=5)
@pytest.mark.parametrize('operation', ['install', 'restore-snapshot'])
def test_direct_cli_installs_flagged_without_server_options(tmp_path, registry, operation):
env = prepare_environment(tmp_path, False, 'normal', registry)
command = [str(E2E_ROOT / 'venv/bin/python'), '-m', 'cm_cli', operation]
if operation == 'install':
command += ['fixture-flagged@2.0.0', '--mode', 'cache']
else:
snapshot = tmp_path / 'direct-snapshot.json'
snapshot.write_text(json.dumps({'cnr_custom_nodes': {'fixture-flagged': '2.0.0'},
'git_custom_nodes': {}, 'file_custom_nodes': []}))
command.append(str(snapshot))
command += ['--user-directory', str(tmp_path / 'user')]
before = len(registry.calls)
result = subprocess.run(command, env=env, cwd=E2E_ROOT / 'comfyui',
capture_output=True, text=True, timeout=60)
output = result.stdout + result.stderr
assert result.returncode == 0, output
installed = tmp_path / 'custom_nodes/fixture-flagged'
assert 'version = "2.0.0"' in (installed / 'pyproject.toml').read_text(), output
if operation == 'install':
assert (installed / 'installed.txt').read_text() == '2.0.0', output
assert sum('/install' in call for call in registry.calls[before:]) == 1
assert 'Installation of this flagged CNR version is blocked' not in output
@pytest.mark.parametrize('tree', ['legacy', 'glob'])
@pytest.mark.parametrize('existing', [False, True])
@pytest.mark.parametrize('version,listen,override,allowed', [
('1.1.0', '0.0.0.0', False, True),
('2.0.0', '0.0.0.0', False, False),
('2.0.0', '0.0.0.0', True, True),
('2.0.0', '127.0.0.1', False, True),
])
def test_scheduled_snapshot_restores_through_server_restart(
tmp_path, registry, tree, existing, version, listen, override, allowed):
installed = tmp_path / 'custom_nodes/fixture-snapshot'
marker = installed / 'installed.txt'
reservation = tmp_path / 'user/__manager/startup-scripts/restore-snapshot.json'
with running_server(tmp_path, tree, '127.0.0.1', False, 'normal-', registry) as server:
if existing:
install(server, 'fixture-snapshot', '1.0.0')
assert marker.read_text() == '1.0.0'
original = (marker.read_bytes(), marker.stat().st_mtime_ns)
snapshot = tmp_path / 'user/__manager/snapshots/flagged-policy.json'
snapshot.write_text(json.dumps({'cnr_custom_nodes': {'fixture-snapshot': version},
'git_custom_nodes': {}, 'file_custom_nodes': []}))
before = len(registry.calls)
response = requests.post(server.base + '/v2/snapshot/restore',
params={'target': snapshot.stem}, json={}, timeout=10)
assert response.status_code == 200, response.text
assert reservation.read_bytes() == snapshot.read_bytes()
assert registry.calls[before:] == []
if existing:
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
else:
assert not installed.exists()
before = len(registry.calls)
with running_server(tmp_path, tree, listen, override, 'normal', registry):
log = (tmp_path / 'server.log').read_text()
calls = registry.calls[before:]
assert 'Restore snapshot done.' in log, log[-6000:]
assert 'Restore snapshot failed.' not in log, log[-6000:]
assert 'Error in sitecustomize' not in log, log[-6000:]
assert not reservation.exists()
assert sum('/install' in call for call in calls) == 1, (calls, log[-6000:])
assert any(call.startswith('/zip/') for call in calls) is allowed, calls
if allowed:
assert f'version = "{version}"' in (installed / 'pyproject.toml').read_text(), log[-6000:]
assert 'allow_flagged_nodepack_install' not in log
else:
assert_terminal_guidance(log)
if existing:
assert (marker.read_bytes(), marker.stat().st_mtime_ns) == original
assert '1.0.0' in (installed / 'pyproject.toml').read_text()
else:
assert not installed.exists()
+24 -1
View File
@@ -153,7 +153,7 @@ def _queue_task(task: dict) -> None:
"""Queue a Manager task and start the worker."""
resp = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=task, timeout=10)
resp.raise_for_status()
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
def _remove_pack(name: str) -> None:
@@ -348,3 +348,26 @@ class TestNightlyInstallCycle:
f"Installed entry {pkg_key!r} still references {PACK_TEST1!r} "
f"via cnr_id/aux_id: {pkg!r}"
)
class TestGitBackendLine:
def test_server_log_has_the_line(self, comfyui):
with open(os.path.join(E2E_ROOT, "logs", "comfyui.log")) as f:
log = f.read()
assert "Using GitPython backend" in log or "Using pygit2 backend" in log
def test_cm_cli_does_not_write_the_line(self, comfyui):
r = subprocess.run([_cm_cli_path(), "--help"], capture_output=True, text=True, timeout=120,
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
assert r.returncode == 0, r.stderr
assert "Using GitPython backend" not in r.stdout + r.stderr
assert "Using pygit2 backend" not in r.stdout + r.stderr
def test_cm_cli_writes_no_empty_line_before_the_output_of_its_command(self, comfyui):
r = subprocess.run([_cm_cli_path(), "simple-show", "snapshot-list"], capture_output=True, text=True, timeout=120,
env={**os.environ, "COMFYUI_PATH": COMFYUI_PATH})
assert r.returncode == 0, r.stderr
assert not r.stdout.startswith("\n")
+1 -21
View File
@@ -1,12 +1,11 @@
"""E2E positive-path tests for legacy-only GET endpoints.
SCOPE — closes the 6 pytest-N gaps from reports/api-coverage-matrix.md
SCOPE — closes the pytest-N gaps from reports/api-coverage-matrix.md
(WI-TT). Each target endpoint is registered ONLY in
`comfyui_manager/legacy/manager_server.py` and thus reachable only when
ComfyUI runs with `--enable-manager-legacy-ui`.
Endpoints covered:
- GET /customnode/alternatives (legacy L1072)
- GET /v2/customnode/disabled_versions/{node_name} (legacy L1273)
- GET /v2/customnode/getlist (legacy L1018)
- GET /v2/customnode/versions/{node_name} (legacy L1262)
@@ -96,25 +95,6 @@ def comfyui_legacy():
_stop_comfyui()
class TestLegacyCustomNodeAlternatives:
"""GET /customnode/alternatives?mode=local (wi-031)."""
def test_returns_dict_of_alternatives(self, comfyui_legacy):
resp = requests.get(
f"{BASE_URL}/customnode/alternatives",
params={"mode": "local"},
timeout=30,
)
assert resp.status_code == 200, (
f"Expected 200, got {resp.status_code}: {resp.text[:200]}"
)
data = resp.json()
assert isinstance(data, dict), (
f"alternatives response should be a dict keyed by unified id, "
f"got {type(data).__name__}"
)
class TestLegacyCustomNodeDisabledVersions:
"""GET /v2/customnode/disabled_versions/{node_name} (wi-032).
+5 -6
View File
@@ -320,12 +320,13 @@ class TestUpdateComfyuiQueued:
def test_direct_endpoint_returns_200(self, comfyui_legacy):
resp = requests.post(
f"{BASE_URL}/v2/manager/queue/update_comfyui", timeout=15
f"{BASE_URL}/v2/manager/queue/update_comfyui", headers={"Content-Type": "application/json"}, timeout=15
)
assert resp.status_code == 200, (
f"update_comfyui should return 200 at default security_level, "
f"got {resp.status_code}: {resp.text[:200]}"
)
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10).raise_for_status()
class TestInstallModelRealDownload:
@@ -468,7 +469,7 @@ class TestSwitchComfyuiSelfSwitch:
class TestInstallViaGitUrlRealClone:
"""Real E2E for wi-037 POST /v2/customnode/install/git_url.
Strategy: POST with body=TRUSTED_GIT_URL (plain text). Handler
Handler
(legacy/manager_server.py:1502-1519) runs core.gitclone_install(url)
synchronously; 200 on success + 'After restarting ComfyUI' log;
'skip' action on already-installed → also 200.
@@ -492,8 +493,7 @@ class TestInstallViaGitUrlRealClone:
try:
resp = requests.post(
f"{BASE_URL}/v2/customnode/install/git_url",
data=TRUSTED_GIT_URL,
headers={"Content-Type": "text/plain"},
json={"url": TRUSTED_GIT_URL},
timeout=180,
)
assert resp.status_code == 200, (
@@ -558,8 +558,7 @@ class TestInstallPipRealExecute:
try:
resp = requests.post(
f"{BASE_URL}/v2/customnode/install/pip",
data=TRUSTED_PIP_PKG,
headers={"Content-Type": "text/plain"},
json={"packages": TRUSTED_PIP_PKG},
timeout=30,
)
assert resp.status_code == 200, (
+6 -6
View File
@@ -127,7 +127,7 @@ class TestQueueLifecycle:
must be 0/False. Any non-zero count here would indicate a leak from an
earlier test module or a reset-handler regression.
"""
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
assert resp.status_code == 200, (
f"Queue reset failed with status {resp.status_code}"
)
@@ -179,13 +179,13 @@ class TestQueueLifecycle:
`start_worker()` accidentally spawns a hot-loop that never exits.
"""
# Ensure idle baseline (pending empty before start).
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
pre = requests.get(f"{BASE_URL}/v2/manager/queue/status", timeout=10).json()
assert pre["pending_count"] == 0, (
f"Pre-condition: pending_count must be 0 before idle-start test, got {pre['pending_count']}"
)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
assert resp.status_code in (200, 201), (
f"Queue start returned unexpected status {resp.status_code}"
)
@@ -223,7 +223,7 @@ class TestQueueLifecycle:
# Reset to clean slate. Note: reset wipes pending/running but not
# file-based batch history, so we track completion by our OWN ui_id
# rather than a global done_count which can reflect unrelated tasks.
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
UI_ID = "e2e-queue-lifecycle"
# Queue a lightweight task (install a small CNR package)
@@ -249,7 +249,7 @@ class TestQueueLifecycle:
)
# Start processing
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
assert resp.status_code in (200, 201), (
f"Queue start failed with status {resp.status_code}"
)
@@ -342,7 +342,7 @@ class TestQueueLifecycle:
}
r = requests.post(f"{BASE_URL}/v2/manager/queue/task", json=seed_payload, timeout=10)
assert r.status_code == 200, f"seed queue/task failed: {r.status_code} {r.text[:200]}"
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
r = requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
assert r.status_code in (200, 201), f"seed queue/start failed: {r.status_code}"
def _seed_done():
+93 -5
View File
@@ -59,6 +59,7 @@ otherwise (harness precedent: tests/e2e/test_e2e_secgate_default.py).
from __future__ import annotations
import configparser
import json
import os
import shutil
import subprocess
@@ -203,13 +204,13 @@ comfyui_flags_h = _make_flags_server_fixture(
def _post_git_url(url: str) -> requests.Response:
return requests.post(
f"{BASE_URL}/v2/customnode/install/git_url", data=url, timeout=120,
f"{BASE_URL}/v2/customnode/install/git_url", json={"url": url}, timeout=120,
)
def _post_pip(packages: str) -> requests.Response:
return requests.post(
f"{BASE_URL}/v2/customnode/install/pip", data=packages, timeout=60,
f"{BASE_URL}/v2/customnode/install/pip", json={"packages": packages}, timeout=60,
)
@@ -506,6 +507,94 @@ class TestFlagsOffWeakLevel:
)
# ===========================================================================
# The 403 denial reason code
#
# A denied install returns 403 with a JSON body naming the flag that denied it
# — `{"reason": "allow_git_url_install"}` or `{"reason": "allow_pip_install"}`
# — so the browser can tell the user WHICH setting to change instead of
# guessing from the endpoint it happened to call. The full
# SECURITY_MESSAGE_FLAG_* text still goes to the terminal via `logging.error`;
# only the flag name goes on the wire.
#
# Every other assertion on these endpoints tests `status_code` alone, so
# nothing else in this file can see the body at all — these rows are the only
# coverage the wire contract has.
#
# Reuses CFG-D (git=F, pip=F, sl=weak) — the config that already produces a 403
# on both arms, so these rows add no new server boot.
# ===========================================================================
class TestDenialReasonCode:
"""The 403 body must name WHICH flag denied — and nothing more."""
def _denial_body(self, resp):
"""Parse the 403 body as the wire contract, with the failure message
carrying what was actually received."""
assert resp.status_code == 403, (
f"precondition: expected 403, got {resp.status_code}"
)
try:
return json.loads(resp.text)
except json.JSONDecodeError as exc:
pytest.fail(
"the 403 body is not JSON. Expected a JSON object carrying "
"the denial reason code; "
f"observed {resp.text!r} (len={len(resp.text)}). "
f"JSONDecodeError: {exc}. A 403 emitted with no `text=` leaves "
"the body EMPTY, and the client then has nothing to derive its "
"message from."
)
def test_t9_pip_denial_body_names_the_flag(self, comfyui_flags_d):
"""The pip 403 body carries the reason code.
Expected: a JSON OBJECT whose `reason` is the string
`allow_pip_install`.
"""
resp = _post_pip("text-unidecode")
body = self._denial_body(resp)
assert isinstance(body, dict), (
"the 403 body must be a JSON OBJECT (the client's guard is "
"`typeof data === 'object' && data !== null && typeof data.reason "
f"=== 'string'`); observed {type(body).__name__} {body!r}"
)
assert body.get("reason") == "allow_pip_install", (
"expected the pip 403 body to carry "
"{'reason': 'allow_pip_install'} so the client can name the "
f"condition the SERVER actually failed on; observed {body!r}"
)
def test_t9_git_url_denial_body_names_the_flag(self, comfyui_flags_d):
"""The git_url 403 body carries its own code.
A separate node from the pip arm on purpose: the two emissions are
separate `return` statements, so one can be changed while the other is
missed.
"""
resp = _post_git_url(UNKNOWN_GIT_URL)
body = self._denial_body(resp)
assert isinstance(body, dict), (
"the 403 body must be a JSON OBJECT; observed "
f"{type(body).__name__} {body!r}"
)
assert body.get("reason") == "allow_git_url_install", (
"expected the git_url 403 body to carry "
f"{{'reason': 'allow_git_url_install'}}; observed {body!r}"
)
def test_t9b_denial_body_discloses_nothing_further(self, comfyui_flags_d):
"""Denied requests expose only the failed flag name."""
responses = {
"allow_pip_install": _post_pip("text-unidecode"),
"allow_git_url_install": _post_git_url(UNKNOWN_GIT_URL),
}
for reason, response in responses.items():
assert self._denial_body(response) == {"reason": reason}
# ===========================================================================
# CFG-E: git=T, pip=T, sl=weak, nm=public — Q1 guard
# ===========================================================================
@@ -537,7 +626,7 @@ class TestUnknownPipStaysBlocked:
# ===========================================================================
def _batch_op_item(ui_id: str) -> dict:
"""Item for middle-gated batch ops (fix/uninstall/update). The GATE
"""Item for middle-gated batch ops (uninstall/update). The GATE
check precedes node resolution, so a placeholder spec is sufficient:
the queue worker's later failure on the nonexistent node is irrelevant
to the synchronous gate observable (the response's failed list)."""
@@ -557,10 +646,9 @@ class _LegacyGuardRows:
flags_label = ""
def _assert_sc25a(self):
"""SC-25A: legacy middle-gated ops (fix/uninstall/update) stay
"""SC-25A: legacy middle-gated ops (uninstall/update) stay
allowed at sl=normal local for this flag combination."""
payload = {
"fix": [_batch_op_item(f"sc25a-fix-{self.flags_label}")],
"uninstall": [_batch_op_item(f"sc25a-unin-{self.flags_label}")],
"update": [_batch_op_item(f"sc25a-upd-{self.flags_label}")],
}
+2 -1
View File
@@ -10,7 +10,7 @@ without elevating the security_level to STRONG.
The 4 T2 SECGATE-PENDING Goals at middle/middle+ that depend on this harness:
- SR4 (snapshot/remove, gate=middle) ← THIS PoC
- SR6 (snapshot/restore, gate=middle+) ← follow-up
- SR6 (snapshot/restore, gate=high+) ← follow-up
- V5 (manager/reboot, gate=middle) ← follow-up
- UA2 (manager/queue/update_all, gate=middle+) ← follow-up
@@ -156,6 +156,7 @@ class TestSecurityGate403_SR4:
resp = requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": seed_name},
headers={"Content-Type": "application/json"},
timeout=10,
)
+5 -2
View File
@@ -181,7 +181,7 @@ class TestSnapshotLifecycle:
if os.path.isdir(SNAPSHOT_DIR):
files_before = {f for f in os.listdir(SNAPSHOT_DIR) if f.endswith(".json")}
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
assert resp.status_code == 200, (
f"Snapshot save failed with status {resp.status_code}"
)
@@ -251,7 +251,7 @@ class TestSnapshotLifecycle:
asserts. Does not depend on prior tests in this module.
"""
# SETUP: create a snapshot so we have a deterministic target
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", timeout=30)
save_resp = requests.post(f"{BASE_URL}/v2/snapshot/save", headers={"Content-Type": "application/json"}, timeout=30)
assert save_resp.status_code == 200, "setup save failed"
# Find the newly created snapshot by diffing against pre-save list
@@ -267,6 +267,7 @@ class TestSnapshotLifecycle:
resp = requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": target},
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 200, (
@@ -290,6 +291,7 @@ class TestSnapshotLifecycle:
resp = requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": "nonexistent_snapshot_99999"},
headers={"Content-Type": "application/json"},
timeout=10,
)
# Server returns 200 even when file doesn't exist (no-op behavior)
@@ -317,6 +319,7 @@ class TestSnapshotLifecycle:
resp = requests.post(
f"{BASE_URL}/v2/snapshot/remove",
params={"target": target},
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 400, (
+1 -1
View File
@@ -204,7 +204,7 @@ class TestReboot:
# Trigger reboot — server may drop connection mid-response
try:
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", timeout=10)
resp = requests.post(f"{BASE_URL}/v2/manager/reboot", headers={"Content-Type": "application/json"}, timeout=10)
if resp.status_code == 403:
pytest.skip(
"Reboot denied by security policy "
+18 -13
View File
@@ -93,7 +93,7 @@ def _queue_task(task: dict) -> None:
timeout=10,
)
resp.raise_for_status()
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
def _remove_pack(name: str) -> None:
@@ -241,7 +241,7 @@ def _ensure_pack_installed_with_tracking():
def _reset_queue():
"""Reset the queue to clean state."""
requests.post(f"{BASE_URL}/v2/manager/queue/reset", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/reset", headers={"Content-Type": "application/json"}, timeout=10)
def _wait_queue_idle(timeout=POLL_TIMEOUT):
@@ -643,10 +643,10 @@ class TestInstallModel:
advances beyond baseline within a bounded timeout)
(c) optionally, queue/history records a row matching this ui_id
Download completion to a real model file is NOT an E2E responsibility —
it depends on external network + the target URL. The test URL points
to example.com, which will not yield a valid safetensors file; the
task will still transition through running → history (as failed /
trivial-success), which is the E2E-observable we need.
it depends on external network + the target URL. The test model is
not in the model list, so the worker refuses it without a download;
the task still transitions through running → history (as failed),
which is the E2E-observable we need.
"""
_reset_queue()
@@ -696,7 +696,7 @@ class TestInstallModel:
# - done_count advanced → task already ran to history
# Either proves the enqueued task left the pending state under
# worker control. This does NOT assert download success.
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
def _worker_observed_task() -> bool:
try:
@@ -827,10 +827,10 @@ class TestUpdateAll:
if isinstance(pkg, dict) and pkg.get("enabled", True):
active_packs += 1
# The handler runs reload + get_custom_nodes synchronously, which can
# be slow (up to ~2 min on cache-cold runs). Use an explicit long
# timeout; a timeout here is a real server-perf regression, NOT
# something to hide as a pass.
# The handler fetches the whole Registry list before it answers. The
# list is fetched 30 nodepacks per page with a pause after each page,
# to keep the load on the Registry low: about three minutes for 6,500
# nodepacks, and longer as the list grows.
resp = requests.post(
f"{BASE_URL}/v2/manager/queue/update_all",
params={
@@ -838,7 +838,8 @@ class TestUpdateAll:
"client_id": "e2e-update-all",
"ui_id": "e2e-update-all",
},
timeout=180,
headers={"Content-Type": "application/json"},
timeout=600,
)
# Detect expected outcome based on server security configuration.
@@ -875,6 +876,7 @@ class TestUpdateAll:
"""POST /v2/manager/queue/update_all without required params -> 400."""
resp = requests.post(
f"{BASE_URL}/v2/manager/queue/update_all",
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 400, (
@@ -903,6 +905,7 @@ class TestUpdateComfyUI:
"client_id": "e2e-update-comfyui",
"ui_id": "e2e-update-comfyui",
},
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 200, (
@@ -927,6 +930,7 @@ class TestUpdateComfyUI:
"""POST /v2/manager/queue/update_comfyui without required params -> 400."""
resp = requests.post(
f"{BASE_URL}/v2/manager/queue/update_comfyui",
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 400, (
@@ -944,6 +948,7 @@ class TestUpdateComfyUI:
"ui_id": "e2e-update-comfyui-stable",
"stable": "true",
},
headers={"Content-Type": "application/json"},
timeout=10,
)
assert resp.status_code == 200, (
@@ -961,7 +966,7 @@ class TestUpdateComfyUI:
# never reaches history (silent empty-history regression). The
# actual update work will fail fast in E2E (no real git remote),
# but the task completes and moves to history regardless.
requests.post(f"{BASE_URL}/v2/manager/queue/start", timeout=10)
requests.post(f"{BASE_URL}/v2/manager/queue/start", headers={"Content-Type": "application/json"}, timeout=10)
_wait_queue_idle(timeout=POLL_TIMEOUT)
# Try to inspect queued task params via JSON path.
+125
View File
@@ -0,0 +1,125 @@
"""Opt-in production Registry/CDN verification; never collected by pytest.
Requires E2E_ROOT with comfyui/ and venv/bin/python, as for the local E2E suite.
Pass two explicitly chosen ID@version values via --listed and --unlisted, and a
new --output directory. Both versions must currently be Flagged. The listed
archive must have no install.py or requirements.txt. Servers use isolated data
directories, the normal installation path, and do not reload installed nodes.
"""
import argparse
import hashlib
import json
import subprocess
import zipfile
from datetime import datetime, timezone
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import quote
import requests
import test_e2e_flagged_nodepacks as harness
REGISTRY = 'https://api.comfy.org'
def get_json(path, **params):
response = requests.get(REGISTRY + path, params=params, timeout=30)
response.raise_for_status()
return response.json()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--listed', required=True, metavar='ID@VERSION')
parser.add_argument('--unlisted', required=True, metavar='ID@VERSION')
parser.add_argument('--output', required=True, type=Path)
args = parser.parse_args()
if not (harness.E2E_ROOT / 'venv/bin/python').is_file():
parser.error('E2E_ROOT must point to the ComfyUI + venv fixture')
packs = []
for value in (args.listed, args.unlisted):
node, separator, version = value.rpartition('@')
if not node or not separator or not version:
parser.error('Specify each pack as ID@VERSION')
catalog = get_json('/nodes/' + quote(node, safe=''))
assert catalog['id'] == node, catalog
packs.append((catalog, version))
assert packs[0][0]['id'].lower() != packs[1][0]['id'].lower(), 'Choose two different packs'
output = args.output.resolve()
output.mkdir(parents=True)
catalog = {'nodes': [pack for pack, _ in packs], 'totalPages': 1}
catalog_path = output / 'catalog.json'
catalog_path.write_text(json.dumps(catalog, indent=2), encoding='utf-8')
# Seed only the catalog cache from live /nodes/{id} responses. Installation
# metadata and ZIP downloads still go directly to the production services.
registry = SimpleNamespace(url=REGISTRY, catalog_url=catalog_path.as_uri())
results = []
def check(server, label, pack, version, allowed):
node = pack['id']
metadata = get_json('/nodes/' + quote(node, safe='') + '/install', version=version)
assert metadata['status'] == 'NodeVersionStatusFlagged', metadata
assert metadata['node_id'] == node and metadata['version'] == version, metadata
expected = {}
if allowed:
response = requests.get(metadata['downloadUrl'], timeout=60)
response.raise_for_status()
archive_path = server.root / 'cdn.zip'
archive_path.write_bytes(response.content)
with zipfile.ZipFile(archive_path) as archive:
assert 'install.py' not in archive.namelist(), 'Choose a pack without an install script'
assert 'requirements.txt' not in archive.namelist(), 'Choose a pack without pip requirements'
for member in archive.infolist():
if not member.is_dir():
expected[member.filename] = hashlib.sha256(archive.read(member)).hexdigest()
assert expected, 'CDN archive is empty'
log_path = server.root / 'server.log'
offset = len(log_path.read_text())
queue = harness.install(server, node, version, repository=pack['repository'])
installed = server.root / 'custom_nodes' / node
assert installed.exists() is allowed, queue
if allowed:
if server.tree == 'legacy':
assert list(queue['nodepack_result'].values()) == ['success'], queue
else:
assert queue['history']['result'] == 'success', queue
for name, digest in expected.items():
assert hashlib.sha256((installed / name).read_bytes()).hexdigest() == digest, name
assert (installed / '.tracking').is_file()
else:
harness.assert_flagged_denial(queue, log_path.read_text()[offset:])
assert not any(installed.parent.glob('CNR_temp_*'))
results.append({'tree': server.tree, 'label': label,
'observed_at': datetime.now(timezone.utc).isoformat(),
'registry_response': metadata, 'queue_response': queue,
'installed': installed.exists(), 'matched_archive_files': expected})
(output / 'results.json').write_text(json.dumps(results, indent=2), encoding='utf-8')
print(f'{server.tree} {label}: installed={installed.exists()}, verified_files={len(expected)}', flush=True)
for tree in ('glob', 'legacy'):
root = output / tree
root.mkdir()
with harness.running_server(root, tree, '0.0.0.0', False, 'normal', registry) as server:
whitelist = root / 'user/__manager/nodepack-whitelist.list'
template = whitelist.read_text()
assert template.strip() and all(line.lstrip().startswith('#') for line in template.splitlines() if line.strip())
listed, version = packs[0]
check(server, 'default-template', listed, version, False)
whitelist.write_text(listed['id'].swapcase() + '\n', encoding='utf-8')
check(server, 'listed-different-case', listed, version, True)
check(server, 'unlisted-control', *packs[1], False)
manifest = {
'tested_commit': subprocess.check_output(
['git', 'rev-parse', 'HEAD'], cwd=harness.REPO_ROOT, text=True).strip(),
'completed_cases': len(results), 'registry': REGISTRY,
'archive_sha256': {str(path.relative_to(output)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in output.glob('*/cdn.zip')},
}
(output / 'manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
print(f'PASS: {len(results)} live Registry cases; evidence: {output}', flush=True)
if __name__ == '__main__':
main()
+159
View File
@@ -0,0 +1,159 @@
"""Lift real production JS out of the shipped files and execute it in node.
WHY LIFT RATHER THAN IMPORT: the manager's front-end modules pull in
``../../scripts/app.js`` and touch ``document`` at module scope, so node cannot
import them. WHY LIFT RATHER THAN RETYPE: a retyped copy of a formatter stops
tracking the formatter the moment someone edits it, and then the guard passes
while the shipped code regresses. Lifting keeps the executed bytes the shipped
bytes — if the production function changes, so does the text under test.
This mirrors tests/test_manager_markdown_escaping.py, which AST-extracts
``convert_markdown_to_html`` rather than importing manager_server.
Consumers point ``JsSource`` at a directory of .js files; an override directory
(e.g. one populated with ``git show <base>:js/foo.js``) makes the RED half of a
fix reproducible in one command.
"""
import json
import shutil
import subprocess
from html.parser import HTMLParser
from pathlib import Path
NODE = shutil.which("node")
def _skip_literal(source: str, pos: int) -> int:
"""If a literal or comment starts at pos, return the index just past it.
Returns pos unchanged when nothing starts there. Template literals are
consumed whole, which is safe for brace counting because a `${...}`
substitution is itself balanced. A lone `/` is read as a regex literal —
sanitizeHTML's own `.replace(/'/g, ...)` hides an apostrophe inside one, and
no scanned range uses `/` as division. Were that to change, the assertion
below fails loudly rather than returning a wrong slice.
"""
ch = source[pos]
nxt = source[pos + 1] if pos + 1 < len(source) else ""
if ch == "/" and nxt == "/":
return source.index("\n", pos)
if ch == "/" and nxt == "*":
return source.index("*/", pos) + 2
if ch not in "\"'`/":
return pos
cursor = pos + 1
while cursor < len(source):
if source[cursor] == "\\":
cursor += 2
continue
if source[cursor] == ch:
return cursor + 1
cursor += 1
raise AssertionError("unterminated literal at offset %d" % (pos,))
def slice_braced(source: str, start_marker: str) -> str:
"""Return start_marker plus the balanced {...} block that follows it."""
start = source.index(start_marker)
pos = source.index("{", start + len(start_marker))
depth = 0
while pos < len(source):
skipped = _skip_literal(source, pos)
if skipped != pos:
pos = skipped
continue
if source[pos] == "{":
depth += 1
elif source[pos] == "}":
depth -= 1
if depth == 0:
return source[start:pos + 1]
pos += 1
raise AssertionError("unbalanced braces after %r" % (start_marker,))
def slice_object_entry(source: str, marker: str, indent: str = "\t\t") -> str:
"""Return one object literal out of a `}, {`-chained array, by id marker.
These objects are literals inside an array, so the first `{` after the
marker belongs to the NEXT entry — brace matching cannot be used. The entry
instead ends at the first `}` sitting at the array's own indent.
"""
start = source.index(marker)
end = source.index("\n%s}" % indent, start)
return source[start:end]
def line_containing(source: str, marker: str) -> str:
"""Return the single source line that holds `marker` (fails if absent)."""
start = source.index(marker)
line_start = source.rfind("\n", 0, start) + 1
return source[line_start:source.index("\n", start)]
class JsSource:
"""The shipped .js files under test, read from `js_dir`."""
def __init__(self, js_dir):
self.js_dir = Path(js_dir)
self._cache = {}
def text(self, filename: str) -> str:
if filename not in self._cache:
self._cache[filename] = (self.js_dir / filename).read_text(encoding="utf-8")
return self._cache[filename]
def lift_declaration(self, filename: str, marker: str) -> str:
"""Lift an `export function`/`export const` declaration, minus `export`."""
return slice_braced(self.text(filename), marker).replace("export ", "", 1)
def lift_formatter(self, filename: str, anchor: str) -> str:
"""Lift the `formatter: ...` at `anchor` as a bare function expression."""
block = slice_braced(self.text(filename), anchor)
marker = "formatter:"
return block[block.index(marker) + len(marker):].strip()
def lift_span(self, filename: str, start_marker: str, end_marker: str) -> str:
"""Lift the source between two markers, end_marker included."""
source = self.text(filename)
start = source.index(start_marker)
end = source.index(end_marker, start) + len(end_marker)
return source[start:end]
def run_node(script: str) -> dict:
"""Execute an ES-module script and parse the single JSON object it prints."""
assert NODE is not None, "node is required to execute the lifted production JS"
result = subprocess.run(
[NODE, "--input-type=module", "-e", script],
capture_output=True, text=True, timeout=60,
)
assert result.returncode == 0, "node failed:\n%s" % (result.stderr,)
return json.loads(result.stdout)
class Collector(HTMLParser):
"""Collects the tags and attributes a browser would actually build."""
def __init__(self):
super().__init__()
self.tags = []
self.attrs = []
def handle_starttag(self, tag, attrs):
self.tags.append(tag)
self.attrs.extend(attrs)
handle_startendtag = handle_starttag
def parse(markup: str) -> Collector:
collector = Collector()
collector.feed(markup)
collector.close()
return collector
def event_handlers(markup: str):
"""Every on* attribute a browser would attach for this markup."""
return [name for name, _ in parse(markup).attrs if name.lower().startswith("on")]
+36
View File
@@ -0,0 +1,36 @@
"""Execute the legacy renderer without starting ComfyUI or its network threads."""
import ast
import importlib.util
import json
import re
import sys
import types
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
PACKAGE = ROOT / 'comfyui_manager'
def load_functions(path, names, namespace=None):
namespace = {} if namespace is None else namespace
nodes = [node for node in ast.parse(path.read_text(encoding='utf-8')).body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name in names]
assert len(nodes) == len(names)
exec(compile(ast.Module(nodes, []), str(path), 'exec'), namespace)
return namespace
def load_renderer():
path = PACKAGE / 'legacy/html_utils.py'
spec = importlib.util.spec_from_file_location('_legacy_html_utils', path)
helpers = importlib.util.module_from_spec(spec)
spec.loader.exec_module(helpers)
util = load_functions(PACKAGE / 'common/manager_util.py', {'sanitize_tag'})
return load_functions(PACKAGE / 'legacy/manager_server.py', {'convert_markdown_to_html', 'populate_markdown'},
{'re': re, 'html_utils': helpers, 'manager_util': types.SimpleNamespace(**util)})
if __name__ == '__main__':
item = json.load(sys.stdin)
load_renderer()['populate_markdown'](item)
print(json.dumps(item))
+13 -4
View File
@@ -5,20 +5,25 @@ Browser-based E2E tests for the ComfyUI-Manager legacy UI.
## Prerequisites
1. **E2E environment** built via `python tests/e2e/scripts/setup_e2e_env.py`
2. **Playwright installed**: `npx playwright install chromium`
2. **Playwright runner and Chromium** (from the repository root):
`npm install --no-save --package-lock=false @playwright/test@1.59.1`, then
`npx playwright install chromium`.
3. **ComfyUI running** with legacy UI enabled:
```bash
E2E_ROOT=/tmp/e2e_full_test
PORT=8199
$E2E_ROOT/venv/bin/python $E2E_ROOT/comfyui/main.py \
PYTHONPATH="$PWD" $E2E_ROOT/venv/bin/python $E2E_ROOT/comfyui/main.py \
--listen 127.0.0.1 --port $PORT \
--enable-manager-legacy-ui \
--enable-manager --enable-manager-legacy-ui \
--cpu
```
## Running Tests
Run from the repository root. XSS fixtures execute the checkout's Python renderer
using `python3`; set `PYTHON=/path/to/python` to select another interpreter.
```bash
# With server already running:
PORT=8199 npx playwright test
@@ -40,5 +45,9 @@ PORT=8199 npx playwright test --debug
| `legacy-ui-manager-menu.spec.ts` | Menu dialog rendering, settings dropdowns, API round-trip |
| `legacy-ui-custom-nodes.spec.ts` | Node list grid, filter, search, footer buttons |
| `legacy-ui-model-manager.spec.ts` | Model list grid, filter, search |
| `legacy-ui-snapshot.spec.ts` | Snapshot list, save, remove |
| `legacy-ui-snapshot.spec.ts` | Snapshot list, save, remove, failed restore and remove |
| `legacy-ui-navigation.spec.ts` | Dialog open/close, nested navigation, no duplicates |
| `custom-nodes-xss.spec.ts` | Node metadata, node preview, Markdown, links, errors, search highlighting |
| `model-manager-xss.spec.ts` | Model metadata, links, errors, search highlighting |
| `legacy-message-errors.spec.ts` | Batch rejection IDs, batch completion, name readability, DOM colors, lookup errors |
| `legacy-ui-node-fixer.spec.ts` | "Fix node (recreate)" context-menu entry: one node left, links rewired, numeric and string node ids, inside a subgraph |
+4 -6
View File
@@ -54,9 +54,8 @@ ComfyUI's `api.fetchApi()` automatically prepends the `/api` prefix to every pat
| 2-3 | Installed filter | Filter → "Installed" | rows ≤ All | Client-side filter |
| 2-4 | Not Installed filter | Filter → "Not Installed" | rows > 0 | Client-side filter |
| 2-5 | Import Failed filter | Filter → "Import Failed" | Filter works | Client-side filter |
| 2-6 | Check Update | "Check Update" button | Filter flips to "Update", API re-called | `GET /api/v2/customnode/getlist?mode=cache` (no `skip_update`) |
| 2-6 | Check Update | "Check Update" button | Filter flips to "Update", the check runs in the background, the list is loaded when the `cm-check-update` event tells its end | `POST /api/v2/customnode/check_update`, then `GET /api/v2/customnode/getlist?mode=cache&skip_update=true` |
| 2-7 | Check Missing | "Check Missing" button | Filter flips to "Missing" | `GET /api/v2/customnode/getmappings?mode=cache` |
| 2-8 | Alternatives filter | Filter → "Alternatives of A1111" | Data loads | `GET /api/customnode/alternatives?mode=cache` |
## 3. Full node install lifecycle
@@ -156,7 +155,7 @@ Note: skipped when no import-failed nodes are present.
| File | New/Enhanced | Scenarios | Target Endpoints |
|------|----------|:-------:|---------------|
| `legacy-ui-manager-menu.spec.ts` | enhanced | 7 | db_mode, channel_url_list, policy/update, notice |
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 9 | getlist, getmappings, alternatives, import_fail_info |
| `legacy-ui-custom-nodes.spec.ts` | enhanced | 8 | getlist, getmappings, import_fail_info |
| `legacy-ui-node-lifecycle.spec.ts` | **new** | 8 | versions/{id}, disabled_versions/{id}, queue/batch (install/uninstall/update/fix/disable/enable) |
| `legacy-ui-node-versions.spec.ts` | **new** | 2 | versions/{id}, disabled_versions/{id} |
| `legacy-ui-batch-operations.spec.ts` | **new** | 4 | queue/batch (update_all, update_comfyui), queue/reset |
@@ -165,7 +164,7 @@ Note: skipped when no import-failed nodes are present.
| `legacy-ui-snapshot.spec.ts` | enhanced | 4 | snapshot/getlist, save, restore, remove |
| `legacy-ui-navigation.spec.ts` | existing | 4 | is_legacy_manager_ui, version |
**Total: 44 scenarios**
**Total: 43 scenarios**
## Legacy-only endpoint coverage
@@ -173,7 +172,6 @@ Note: skipped when no import-failed nodes are present.
|----------|---------|
| `GET /api/v2/customnode/getlist` | 2-1, 2-6 |
| `GET /api/v2/customnode/getmappings` | 2-2, 2-7 |
| `GET /api/customnode/alternatives` | 2-8 |
| `GET /api/v2/customnode/versions/{id}` | 3-1, 4-1 |
| `GET /api/v2/customnode/disabled_versions/{id}` | 3-6, 4-2 |
| `POST /api/v2/customnode/import_fail_info` | 7-1 |
@@ -191,7 +189,7 @@ Note: skipped when no import-failed nodes are present.
## Exclusions
- `share_option` — per user instruction
- **External-service auth/integration** (9 endpoints) — external services are unreachable from E2E
- **External-service auth/integration** (4 endpoints) — external services are unreachable from E2E
- **Individual queue endpoints** (6) — unused by JS; delegated internally through `queue/batch`
- `queue/abort_current` — unused by JS (Stop uses `queue/reset`)
- `/manager/notice` (v1) — superseded by v2
+801
View File
@@ -0,0 +1,801 @@
/**
* Browser-level XSS regression suite for the Custom Nodes manager UI.
*
* Every row feeds hostile node-pack metadata through a stubbed registry
* response and asserts the value renders as INERT TEXT: the payload is visible
* as literal characters, no element is constructed from it, and its `onerror`
* never runs. The three checks are made together because they fail
* differently — see `expectInert` in ./helpers.ts.
*
* NOT EVERY ROW CLOSES A LIVE HOLE, and the distinction matters when reading a
* failure. `version`/`cnr_latest`, `author`, `stars` and `last_update` are
* served unsanitized and sit in always-visible columns, so opening the manager
* is the whole exploit; so are node names from `/v2/customnode/getmappings`,
* a route that sanitizes nothing. Those fields are escaped ON THE CLIENT and
* their rows target that escape.
*
* `title` / `name` / `description` are different: `populate_markdown` ->
* `sanitize_tag` escapes them SERVER-SIDE, and the client renders them as-is
* on purpose. Escaping them again is not free safety — `sanitizeHTML` also maps
* `&`, so a second pass turns the server's `&lt;` into `&amp;lt;` and the pack
* `ComfyUI-<Impact-Pack>` reaches the user as literal `ComfyUI-&lt;Impact-Pack&gt;`.
* The rows targeting those fields assert the SERVER->CLIENT CHAIN, not an
* independent client guarantee.
*
* CAVEAT: `page.route()` REPLACES the HTTP response, so every fixture here
* bypasses `populate_markdown`. For the raw fields that is exactly what a live
* server delivers. For the server-escaped fields it is NOT, so those rows pass
* their payload through `serverSanitizeTag` first — the real transform, read
* out of `manager_util.py` — and assert on the wire form the server would
* actually have emitted.
*
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT (see
* tests/playwright/README.md).
*/
import { test, expect } from '@playwright/test';
import {
waitForComfyUI,
openManagerMenu,
openCustomNodesManager,
routeNodeList,
routeMappings,
makePack,
expectInert,
serverSanitizeTag,
serverPopulateMarkdown,
serverInstallDenialRestartClause,
XSS_PAYLOAD,
XSS_PAYLOAD_NOSPACE,
} from './helpers';
const GRID = '.cn-manager-grid';
const FLYOVER = '.cn-flyover';
/** Collect page errors so the rows that assert "did not throw" can see them. */
function trackPageErrors(page: import('@playwright/test').Page) {
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(String(e)));
return errors;
}
test.describe('grid render sinks', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
test('hostile title renders inert through the server escape', async ({ page }) => {
// NOT defence-in-depth, and the fixture is what says so. `title` is in the
// populate_markdown set, so the SERVER escape is the one defence and the
// client deliberately renders the value as-is — escaping it a second time
// printed `&lt;` to every user (see the double-escape row below).
//
// The fixture is therefore the server's own sanitize_tag OUTPUT, lifted
// from manager_util.py. A raw payload here would assert the opposite of the
// design and fail by construction, on a wire form the live server cannot
// emit; what this row asserts is that the form it DOES emit stays inert
// once the client renders it.
await routeNodeList(page, {
hostile: makePack('hostile', { title: serverSanitizeTag(XSS_PAYLOAD) }),
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'title');
});
// This row needs a WIDER VIEWPORT THAN THE REST, so it gets its own describe.
//
// turbogrid virtualises columns horizontally: at the config's default
// viewport the `.cn-pack-stars` and `.cn-pack-last-update` BODY CELLS are
// not in the DOM at all — a dump returned `stars: []`, `lastUpdate: []`
// with `rowCount: 4`, while the HEADER showed both columns. The row's
// `last_update` leg then failed leg 1 (presence) with legs 2 and 3 passing,
// which is expectInert's own signature for "the payload never rendered",
// i.e. the row was reporting the viewport, not the sink. Measured: at
// 2600x1000 both cells render and both are inert. Pin the viewport so this
// row asserts on the sink it names.
test.describe('wide viewport — stars/last_update are column-virtualised', () => {
test.use({ viewport: { width: 2600, height: 1000 } });
test('hostile version/author/stars/last_update render inert (LIVE no-user-action)', async ({ page }) => {
// The four fields that carry the no-user-action property: served
// unsanitized AND in always-visible columns, so opening the manager is
// the whole exploit.
await routeNodeList(page, {
p1: makePack('p1', { version: XSS_PAYLOAD, cnr_latest: XSS_PAYLOAD }),
p2: makePack('p2', { author: XSS_PAYLOAD }),
// `stars` must be a NON-number to reach the raw fall-through
// (`if (typeof stars === 'number') return stars.toLocaleString()`).
p3: makePack('p3', { stars: XSS_PAYLOAD }),
// `last_update` is cut at the first space, so the payload must be
// space-free or the row would pass for the wrong reason.
p4: makePack('p4', { last_update: XSS_PAYLOAD_NOSPACE }),
});
await openManagerMenu(page);
await openCustomNodesManager(page);
// PRECONDITION — the two virtualised columns must actually have body
// cells before their legs mean anything. Without this the row can go
// pass again the moment a layout change hides them, on a fixture that
// proved nothing.
await expect(
page.locator(`${GRID} .cn-pack-stars`).first(),
'precondition: no .cn-pack-stars body cell rendered — the stars column is virtualised away at this viewport, so its leg would pass vacuously.',
).toBeVisible({ timeout: 15_000 });
await expect(
page.locator(`${GRID} .cn-pack-last-update`).first(),
'precondition: no .cn-pack-last-update body cell rendered — the last_update column is virtualised away at this viewport, so its leg would pass vacuously.',
).toBeVisible({ timeout: 15_000 });
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'version/cnr_latest');
await expectInert(page, GRID, XSS_PAYLOAD, 'img', 'author');
await expectInert(page, GRID, XSS_PAYLOAD_NOSPACE, 'img', 'last_update');
});
});
test('a server-escaped title renders decoded (no double-escape)', async ({ page }) => {
// THE REGRESSION GUARD FOR THE DOUBLE-ESCAPE FIX, and it only guards
// anything because the fixture is the WIRE form.
//
// The earlier shape of this row fed the RAW authored title straight to the
// grid. That is input the live server cannot deliver — getlist runs every
// pack through populate_markdown -> sanitize_tag first — and the row passed
// either way: escaped once, `<3` comes back as `<3`; not escaped at
// all, `<3` is not a tag start so it renders as text too. It asserted
// nothing about the chain it was named for.
//
// Now the fixture is the OUTPUT of the server's own sanitize_tag, read out
// of manager_util.py at run time (serverSanitizeTag) rather than re-typed,
// so what enters the client is exactly what the server would have emitted:
// wire form in, authored text out. A client that escapes the field a second
// time prints the entity and BOTH legs below flip.
//
// page.route still carries it: the escaped fields originate in third-party
// registry data (no live pack title contains an angle bracket), so this is
// the only deterministic way to place a known value in the grid. What
// page.route replaces is the TRANSPORT — the transform is the real one.
const AUTHORED = 'Tom & Jerry <3';
const ON_THE_WIRE = serverSanitizeTag(AUTHORED);
expect(
ON_THE_WIRE,
'serverSanitizeTag returned its input unchanged, so the fixture is NOT the ' +
'wire form and this row is back to proving nothing. Check that sanitize_tag ' +
'in comfyui_manager/common/manager_util.py still escapes < and >.',
).not.toBe(AUTHORED);
await routeNodeList(page, { legit: makePack('legit', { title: ON_THE_WIRE }) });
await openManagerMenu(page);
await openCustomNodesManager(page);
const text = (await page.locator(GRID).first().textContent()) ?? '';
const diagnostic =
`authored: ${JSON.stringify(AUTHORED)}\n` +
`on the wire (server sanitize_tag output): ${JSON.stringify(ON_THE_WIRE)}\n` +
`grid text (first 300 chars): ${JSON.stringify(text.slice(0, 300))}`;
expect(
text,
`the server-escaped title did not render as the author wrote it. The client ` +
`escaped an ALREADY-escaped value, so sanitizeHTML mapped the server's & to ` +
`&amp; and the entity reached the user as literal text.\n${diagnostic}`,
).toContain(AUTHORED);
expect(
text,
`the wire form is visible in the grid as literal text — that IS the ` +
`double-escape. A field in the populate_markdown set (title/name/description) ` +
`must reach innerHTML AS-IS.\n${diagnostic}`,
).not.toContain(ON_THE_WIRE);
});
test('missing title/version/author renders without throwing', async ({ page }) => {
// Expected to PASS — `sanitizeHTML(undefined)` raises TypeError inside a
// render path, so the escape MUST be sanitizeHTML(String(v)).
// This row is what turns that mistake into a visible failure.
const errors = trackPageErrors(page);
const bare = makePack('bare');
delete (bare as Record<string, unknown>).title;
delete (bare as Record<string, unknown>).version;
delete (bare as Record<string, unknown>).author;
await routeNodeList(page, { bare });
await openManagerMenu(page);
await openCustomNodesManager(page);
await expect(page.locator(GRID).first()).toBeVisible();
expect(
errors,
`the grid threw while rendering a row with absent title/version/author — sanitizeHTML(undefined) raises TypeError, so the escape must pass String(v). pageerrors: ${errors.join(' | ')}`,
).toEqual([]);
});
test('composed-HTML description keeps rendering as markup (anti-regression)', async ({ page }) => {
// MANDATORY anti-regression. `description` is SERVER-COMPOSED HTML; the
// cheapest way to pass every other row here is to blind-escape the grid,
// which would print literal <a href=...> / <B> to every user. This row
// guards the ESCAPING, not the defect — it is expected to pass both before
// and after, and must never be forced to fail.
const composed = serverPopulateMarkdown({ description: 'See [a/the docs](https://example.com/x) for **details**' }).description;
await routeNodeList(page, { doc: makePack('doc', { description: composed }) });
await openManagerMenu(page);
await openCustomNodesManager(page);
const anchors = await page.locator(`${GRID} a[href="https://example.com/x"]`).count();
expect(
anchors,
'the composed-HTML description no longer renders as markup — a working <a href> is gone, so the description column was blind-escaped. That is a regression, not a fix.',
).toBeGreaterThan(0);
const bold = await page.locator(`${GRID} b, ${GRID} B`).count();
expect(
bold,
'the composed-HTML description lost its <B> markup — the column was escaped wholesale.',
).toBeGreaterThan(0);
});
});
test.describe('URL / scheme sink', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
test('the title link href carries no javascript: scheme (LIVE, click-gated)', async ({ page }) => {
// `link.href = <registry URL>` with no scheme allow-list. This is the
// client-side twin of the server composer's scheme-trust hole.
//
// Asserted on the href PROPERTY, not on rendered text: the
// rendered label is the pack title and would look perfectly innocent while
// the anchor still carries a javascript: target.
await routeNodeList(page, {
evil: makePack('evil', {
repository: 'javascript:window.__xss_fired=1',
reference: 'javascript:window.__xss_fired=1',
}),
});
await openManagerMenu(page);
await openCustomNodesManager(page);
const hrefs = await page.locator(`${GRID} a`).evaluateAll(
(els) => els.map((e) => (e as HTMLAnchorElement).href),
);
// PRECONDITION — the row asserts that no anchor carries a bad scheme, and
// a grid with NO anchors satisfies that having tested nothing. Pin that at
// least one anchor rendered before reading anything into the result below.
expect(
hrefs.length,
`precondition: the grid rendered no anchors at all, so the href assertion below would pass over an empty list and prove nothing about the URL sink. Observed ${hrefs.length} anchors.`,
).toBeGreaterThan(0);
// ASSERTED AGAINST THE ALLOW-LIST, not against a list of dangerous schemes.
const allowed = ['http:', 'https:'];
const offending = hrefs.filter((h) => {
const scheme = new URL(h).protocol;
return scheme !== null && !allowed.includes(scheme);
});
expect(
offending,
`the title link's href PROPERTY carries a scheme outside the allow-list — a ` +
`registry-controlled URL reached href unfiltered, so one click executes it. ` +
`sanitizeUrl admits ${JSON.stringify(allowed)}; observed anchors: ` +
`${JSON.stringify(hrefs.slice(0, 10))}`,
).toEqual([]);
});
});
test.describe('flyover sinks', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
/** Open the node flyover by clicking the Nodes cell of the first row.
*
* Targets `.cn-pack-nodes` specifically — that div is emitted ONLY by the
* `nodes` column formatter, and only when `rowItem.nodes` is truthy. The
* grid's onClick handler routes to `showNodes` on `columnItem.id ===
* "nodes"`, so any looser selector (e.g. "a cell containing a digit") lands
* on the ID column, silently never opens the flyover, and turns the row
* into a timeout that LOOKS like a failed assertion. Waiting for this
* element first therefore doubles as a precondition that the getmappings
* fixture actually produced a node count. */
async function openFlyover(page: import('@playwright/test').Page) {
const nodesCell = page.locator(`${GRID} .cn-pack-nodes`).first();
await expect(
nodesCell,
'flyover precondition: no .cn-pack-nodes cell rendered, so the getmappings fixture did not attach a node count to the pack — the flyover cannot open and the row would time out for a fixture reason, not a defect.',
).toBeVisible({ timeout: 15_000 });
await nodesCell.click();
await page.waitForSelector(FLYOVER, { state: 'visible', timeout: 10_000 });
}
test('flyover pack title renders inert through the server escape', async ({ page }) => {
// Same contract as the grid title row: `title` is server-escaped, the
// client renders it as-is, so the fixture must be the WIRE form.
await routeNodeList(page, { h: makePack('h', { title: serverSanitizeTag(XSS_PAYLOAD) }) });
await routeMappings(page, {
'https://github.com/example/h': [['NodeA'], { title_aux: 'h' }],
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await openFlyover(page);
await expectInert(page, FLYOVER, XSS_PAYLOAD, 'img', 'flyover title');
});
test('flyover node NAME renders inert (LIVE, click-gated)', async ({ page }) => {
// `/v2/customnode/getmappings` performs NO sanitization —
// `populate_markdown` is never called on that route — so
// this node name is genuinely RAW, not defence-in-depth.
await routeNodeList(page, { h: makePack('h') });
await routeMappings(page, {
'https://github.com/example/h': [[XSS_PAYLOAD], { title_aux: 'h' }],
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await openFlyover(page);
await expectInert(page, FLYOVER, XSS_PAYLOAD, 'img', 'flyover node name');
});
test('node preview renders the node definition inert (LIVE, hover-gated)', async ({ page }) => {
// The preview is built from ComfyUI's node definitions (/object_info),
// which Manager's server never touches, so every field is RAW.
await routeNodeList(page, { h: makePack('h') });
await routeMappings(page, {
'https://github.com/example/h': [['NodeA'], { title_aux: 'h' }],
});
const fields = ['name', 'slot', 'text', 'blank', 'count', 'default', 'output', 'description'];
const hostile = Object.fromEntries(fields.map((field) => [field, `${field} ${XSS_PAYLOAD}`]));
// The frontend has loaded its own node definitions by now, so this answers
// only the request the manager makes when its dialog is created.
await page.route('**/object_info', (route) => route.fulfill({ json: {
NodeA: {
name: hostile.name,
description: hostile.description,
input: { required: {
[hostile.slot]: ['IMAGE'],
[hostile.text]: ['STRING', { default: `first line\n${hostile.default}` }],
[hostile.blank]: ['STRING', { multiline: true }],
[hostile.count]: ['INT', { default: hostile.default }],
} },
input_order: { required: [hostile.slot, hostile.text, hostile.blank, hostile.count] },
output: ['IMAGE'],
output_name: [hostile.output],
output_is_list: [false],
},
} }));
const definitions = page.waitForResponse('**/object_info');
await openManagerMenu(page);
await openCustomNodesManager(page);
await definitions;
await openFlyover(page);
await page.locator(`${FLYOVER} .cn-nodes-name`).first().hover();
await page.waitForSelector('.cn-preview', { state: 'visible', timeout: 10_000 });
await expectInert(page, '.cn-preview', XSS_PAYLOAD, 'img', 'node preview');
const preview = page.locator('.cn-preview');
// A text input shows its default value, and its name only when it has none.
for (const field of fields.filter((field) => field !== 'text')) {
await expect(preview, `node preview: ${field}`).toContainText(hostile[field]);
}
// The line break of a multi-line default is the one piece of markup kept.
await expect(preview.locator('.cn-preview-string br')).toHaveCount(1);
});
});
// ===========================================================================
// selection bar
// ===========================================================================
test.describe('selection bar', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
for (const state of ['not-a-known-install-group', 'constructor', '__proto__']) {
test(`an unrecognised pack state still renders the selection bar: ${state}`, async ({ page }) => {
const errors = trackPageErrors(page);
await routeNodeList(page, { odd: makePack('odd', { state }) });
await openManagerMenu(page);
await openCustomNodesManager(page);
const checkbox = page.locator(`${GRID} .tg-body .tg-row .tg-checkbox`).first();
await expect(checkbox).toBeVisible({ timeout: 15_000 });
await checkbox.click();
const bar = page.locator('.cn-manager-selection').first();
await expect(bar).toContainText('Selected');
await expect(bar).toContainText(state);
await expect(bar.locator('button')).toHaveCount(0);
expect(errors).toEqual([]);
});
}
});
// ===========================================================================
// Install status uses the same server-composed names as the grid.
// ===========================================================================
test.describe('install status sink', () => {
for (const [source, visible] of [
[XSS_PAYLOAD, XSS_PAYLOAD],
['Pack &amp; Friends <Flux>', 'Pack & Friends <Flux>'],
['Pack &amp;lt;Flux&amp;gt;', 'Pack &lt;Flux&gt;'],
]) {
test(`server title remains readable and inert: ${source}`, async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeNodeList(page, { victim: makePack('victim', {
title: serverSanitizeTag(source), version: 'unknown',
}) });
await page.route('**/v2/manager/queue/batch', route => route.fulfill({
status: 200, contentType: 'application/json', body: '{"failed": []}',
}));
await openManagerMenu(page);
await openCustomNodesManager(page);
await page.locator(`${GRID} .cn-btn-install`).first().click();
await expectInert(page, '.cn-manager-status', visible, 'img', 'install title');
const status = page.locator('.cn-manager-status');
await expect(status).toContainText(visible);
});
}
});
// ===========================================================================
// batch error dialog
// ===========================================================================
test.describe('batch error dialog', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
test('server-authored batch failure text renders inert (LIVE)', async ({ page }) => {
// REAL CONSUMPTION PATH, not a synthetic fixture. The chain exercised here
// is the production one end to end on the client side:
// real Install click -> real POST /v2/manager/queue/batch
// -> real `cm-queue-status` batch-done event on ComfyUI's api
// -> real onQueueStatus -> onQueueCompleted -> errorMsg += v (:1604)
// -> real showError (:1613) -> showMessage -> .cn-manager-message
// .innerHTML (:2091)
// Only the SERVER's two responses are stubbed, which is exactly what
// Tier A is for — the attacker-controlled value enters at `result[hash]`,
// the same slot a real queue result fills.
let capturedBatchId = '';
await page.route('**/v2/manager/queue/batch', async (route) => {
capturedBatchId = route.request().postDataJSON()?.batch_id ?? '';
await route.fulfill({ status: 200, contentType: 'application/json', body: '{"failed": []}' });
});
// `version: 'unknown'` is load-bearing, not filler. The grid click handler
// routes install through a VERSION SELECTOR dialog when
// `item.originalData.version != 'unknown'` (:555), and the batch POST only
// happens after a version is chosen. The unknown-version shape takes the
// direct `installNodes` path (:559), which is the same branch the Python
// e2e rows drive, and keeps this test on the error-render path it is about
// instead of on version-picker UI.
await routeNodeList(page, {
victim: makePack('victim', { state: 'not-installed', version: 'unknown' }),
});
await openManagerMenu(page);
await openCustomNodesManager(page);
const installBtn = page.locator(`${GRID} .cn-btn-install`).first();
await expect(
installBtn,
'precondition: no .cn-btn-install rendered, so the batch flow was never entered and install_context/batch_id were never set — the queue event would be dropped by onQueueCompleted and the row would prove nothing.',
).toBeVisible({ timeout: 15_000 });
await installBtn.click();
// CAPTURE THE SINK'S WRITES, because the settled element cannot be read.
//
// onQueueCompleted writes the error into .cn-manager-message via
// showError (:1613) and then OVERWRITES the same element with the restart
// notice via showMessage (:1620) — inside ONE synchronous handler. So by
// the time any assertion runs, the element holds "To apply the
// installed/updated... restart ComfyUI", and the value under test is
// gone. A MutationObserver does not help: its callback is a microtask and
// both writes land before it runs (measured — it reports only the final
// state). Wrapping the innerHTML SETTER records each write at the moment
// it happens, which is the only way to assert on what the sink actually
// received. Installed here rather than via addInitScript because the
// writes under test all happen after this point.
await page.evaluate(() => {
const w = window as unknown as Record<string, any>;
w.__cnMessageWrites = [];
const desc = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML')!;
Object.defineProperty(Element.prototype, 'innerHTML', {
configurable: true,
get() {
return desc.get!.call(this);
},
set(value) {
try {
if ((this as Element).classList?.contains('cn-manager-message')) {
w.__cnMessageWrites.push(String(value));
}
} catch {
/* never let the probe break the page under test */
}
desc.set!.call(this, value);
},
});
});
await expect
.poll(() => capturedBatchId, {
timeout: 15_000,
message: 'precondition: the client never POSTed /v2/manager/queue/batch, so no batch_id exists to address the completion event to.',
})
.not.toBe('');
// Deliver the completion event exactly as the server does over the socket.
await page.evaluate(
({ batchId, payload }) => {
const api = (window as unknown as Record<string, any>).comfyAPI.api.api;
api.dispatchEvent(
new CustomEvent('cm-queue-status', {
detail: { status: 'batch-done', batch_id: batchId, nodepack_result: [payload] },
}),
);
},
{ batchId: capturedBatchId, payload: XSS_PAYLOAD },
);
// The write carrying the payload must arrive, and arrive inert. The three
// legs are the same ones expectInert applies, evaluated against the value
// the sink RECEIVED rather than against the element's settled content:
// leg 1 presence — the payload is there as literal text;
// leg 2 structure — parsing that write constructs no <img>;
// leg 3 execution — window.__xss_fired never set (document-wide).
const sink = await page.evaluate((payload) => {
const w = window as unknown as Record<string, any>;
const writes: string[] = w.__cnMessageWrites ?? [];
// Parse each write the way the browser did, in a detached element.
const probe = document.createElement('div');
const parsed = writes.map((html) => {
probe.innerHTML = html;
return { html, text: probe.textContent ?? '', imgs: probe.querySelectorAll('img').length };
});
return {
writes,
carrying: parsed.filter((p) => p.text.includes(payload)),
imgsAnywhere: parsed.reduce((n, p) => n + p.imgs, 0),
firedGlobal: w.__xss_fired,
liveImgs: document.querySelectorAll('img[src="x"]').length,
};
}, XSS_PAYLOAD);
const diagnostic =
`queue failure text — writes observed at .cn-manager-message: ${JSON.stringify(sink.writes)}`;
expect(
sink.carrying.length,
`precondition: no write to .cn-manager-message carried the payload at all, so the sink was never exercised and the row proves nothing — check that onQueueCompleted reached showError. ${diagnostic}`,
).toBeGreaterThan(0);
expect(
sink.imgsAnywhere,
`a write to .cn-manager-message parsed into a live <img> — the server-authored queue text reached innerHTML AS MARKUP. ${diagnostic}`,
).toBe(0);
expect(
sink.liveImgs,
`an <img src=x> from the payload is live in the document. ${diagnostic}`,
).toBe(0);
expect(
sink.firedGlobal,
`the payload EXECUTED (window.__xss_fired is set). ${diagnostic}`,
).toBeUndefined();
});
});
// ===========================================================================
// client-side 403 denial text
// ===========================================================================
// The selectors below are load-bearing and were arrived at the hard way.
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box
// (`.cn-manager-keywords`, in `.cm-ui-header`) before it matches the prompt
// field, so a `.first()` on it silently types the URL into the search box:
// install_via_git_url is never called, the denial modal never renders, and the
// row fails as though the client produced nothing. Targeting
// `.prompt-dialog-content input` hits the prompt on the first attempt.
//
// The general lesson: a selector that matches SOMETHING makes a broken fixture
// look like a product failure, and only checking WHAT it matched tells the two
// apart.
test.describe('403 denial text', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeNodeList(page, { p: makePack('p') });
});
/** Drive the REAL "Install via Git URL" entry point: footer button ->
* customPrompt (ComfyUI's PrimeVue dialog) -> install_via_git_url ->
* the 403 arm at common.js:254. */
async function installViaGitUrl(page: import('@playwright/test').Page, url: string) {
// The REAL entry point, driven exactly as a user does it: footer button ->
// customPrompt (common.js:149 -> app.extensionManager.dialog.prompt) ->
// install_via_git_url -> the 403 arm at common.js:254.
//
// `.prompt-dialog-content input` is the load-bearing selector. A broader
// `.cm-ui-dialog input` matches the Custom Nodes SEARCH box first, which is
// silent: the URL lands in the search field, no request is made, and the
// row fails at the denial assertion as though the client rendered nothing.
await page.locator('.cn-manager-install-url').first().click();
const input = page.locator('.prompt-dialog-content input').first();
await expect(
input,
'precondition: the customPrompt dialog never rendered its input, so install_via_git_url was never called and the 403 arm was never reached — the row would prove nothing.',
).toBeVisible({ timeout: 10_000 });
await input.fill(url);
await input.press('Enter');
}
/** The denial modal is `app.ui.dialog.element` (`show_message` ->
* `app.ui.dialog.show`, common.js:98). Several `.comfy-modal` nodes exist,
* so filter by the denial copy rather than taking `.first()`. */
function denialDialog(page: import('@playwright/test').Page) {
return page.locator('.comfy-modal').filter({ hasText: /config\.ini/ }).first();
}
const MALFORMED = [
{ label: 'empty body', body: '' },
{ label: 'non-JSON', body: 'not json' },
{ label: 'JSON null', body: 'null' },
{ label: 'JSON array', body: '[]' },
{ label: 'reason is a number', body: '{"reason": 42}' },
{ label: 'unknown reason code', body: '{"reason": "unknown_flag"}' },
];
for (const variant of MALFORMED) {
test(`403 with ${variant.label} falls back without throwing`, async ({ page }) => {
// The client PARSES the 403 body to learn which condition failed, and
// `res.json()` resolves for far more than an object: `null`, `[]`,
// `"str"` and `3` all parse cleanly. `null.reason` would throw inside the
// render path, while `[].reason` and `{"reason":42}` yield `undefined`
// and would put the literal string "undefined" in front of the user.
// `install_denial_message` guards each of those shapes and falls back to
// the calling endpoint's own condition; this row is what holds that
// guard in place, one variant per malformed shape.
const errors: string[] = [];
page.on('pageerror', (e) => errors.push(String(e)));
await page.route('**/v2/customnode/install/git_url', async (route) => {
await route.fulfill({ status: 403, contentType: 'application/json', body: variant.body });
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await installViaGitUrl(page, 'https://github.com/example/pack');
const dialog = denialDialog(page);
await expect(
dialog,
`${variant.label}: the denial dialog did not render its fallback text. A 403 whose body cannot be interpreted is STILL a denial and must still be explained.`,
).toBeVisible({ timeout: 10_000 });
const text = (await dialog.textContent()) ?? '';
expect(
text,
`${variant.label}: the rendered denial text contains the literal string "undefined" — a malformed body leaked through the reason lookup. text: ${text.slice(0, 300)}`,
).not.toContain('undefined');
expect(
errors,
`${variant.label}: the 403 handler threw. pageerrors: ${errors.join(' | ')}`,
).toEqual([]);
});
}
test('the denial text is SELECTED BY the server reason code', async ({ page }) => {
// CROSS-WIRED ON PURPOSE. Each install arm has its own denial text, so a
// per-endpoint check cannot tell a server-DERIVED selection from a
// hand-maintained constant that happens to match the endpoint it sits on.
// Answering the git_url endpoint with the PIP reason code separates them:
// a client that reads the server's reason names allow_pip_install, and a
// client that prints a per-call-site literal names the other flag no
// matter what the server said. That drift is what this row catches.
await page.route('**/v2/customnode/install/git_url', async (route) => {
await route.fulfill({
status: 403,
contentType: 'application/json',
body: JSON.stringify({ reason: 'allow_pip_install' }),
});
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await installViaGitUrl(page, 'https://github.com/example/pack');
const dialog = denialDialog(page);
await expect(dialog).toBeVisible({ timeout: 10_000 });
const text = (await dialog.textContent()) ?? '';
expect(
text,
`the server said reason="allow_pip_install" and the client must name THAT condition. Observed text names the other flag, i.e. the message is a hand-maintained constant per call site rather than being selected from the server's reason code. text: ${text.slice(0, 400)}`,
).toContain('allow_pip_install');
});
test('the denial text states the SERVER\'s restart requirement', async ({ page }) => {
// THE STANDING GUARD FOR A HAND-MAINTAINED COPY. Only the reason CODE is
// derived from the server; the wording lives in js/common.js, and nothing
// makes the two move together. They had already come apart: the server
// constants say the flag and network_mode are read once at STARTUP, so a
// user who edits config.ini and retries is denied identically — and the
// client text omitted it, leaving that user with a correct edit and no hint
// that a restart is what is missing.
//
// The expected sentence is READ OUT of the server constants
// (serverInstallDenialRestartClause), not typed here, so this row cannot
// become a third copy that drifts on its own. Reword the server and the
// client must follow; drop it from the server and this row says so.
const restartClause = serverInstallDenialRestartClause();
await page.route('**/v2/customnode/install/git_url', async (route) => {
await route.fulfill({
status: 403,
contentType: 'application/json',
body: JSON.stringify({ reason: 'allow_git_url_install' }),
});
});
await openManagerMenu(page);
await openCustomNodesManager(page);
await installViaGitUrl(page, 'https://github.com/example/pack');
const dialog = denialDialog(page);
await expect(dialog).toBeVisible({ timeout: 10_000 });
const text = (await dialog.textContent()) ?? '';
expect(
text,
`the client denial text does not state the restart requirement the SERVER states. ` +
`A user who edits config.ini and retries is denied identically, with nothing in ` +
`the UI saying a restart is what is missing.\n` +
`expected (from SECURITY_MESSAGE_FLAG_*): ${JSON.stringify(restartClause)}\n` +
`observed dialog text: ${JSON.stringify(text.slice(0, 600))}`,
).toContain(restartClause);
});
});
// ===========================================================================
// search-keyword highlight — the grid re-renders matched cells from
// textContent, which would undo the formatter escaping unless the bundle
// escapes every slice it splices (see tests/test_grid_highlight_escaping.py)
// ===========================================================================
test.describe('keyword highlight re-render', () => {
test.use({ viewport: { width: 2600, height: 1000 } });
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
test('a keyword matching inside an escaped raw field stays inert after highlight', async ({ page }) => {
// The keyword must match VISIBLE text: the match cache decodes markup-
// shaped values to their text, and a bare <img> has none.
const payload = XSS_PAYLOAD + 'PWN_author';
await routeNodeList(page, { p: makePack('p', { author: payload }) });
await openManagerMenu(page);
await openCustomNodesManager(page);
const search = page.locator('.cn-manager-keywords').first();
await expect(search, 'precondition: search box not rendered').toBeVisible();
await search.fill('PWN');
// PRECONDITION: the highlighter actually ran on the payload cell.
await expect(
page.locator(`${GRID} .cn-pack-author mark`).first(),
'precondition: no highlight marker rendered in the author cell, so the re-render path was never exercised',
).toBeVisible({ timeout: 10_000 });
await expectInert(page, GRID, payload, 'img', 'author after keyword highlight');
});
});
+252 -10
View File
@@ -6,8 +6,14 @@
* Model, Snapshot) are launched.
*/
import * as fs from 'fs';
import { execFileSync } from 'child_process';
import * as path from 'path';
import { type Page, expect } from '@playwright/test';
/** Repository root, resolved from this file (tests/playwright/helpers.ts). */
const REPO_ROOT = path.resolve(__dirname, '..', '..');
/** Wait for the ComfyUI page to be fully loaded (queue ready). */
export async function waitForComfyUI(page: Page) {
// ComfyUI shows the canvas once the app is ready. Wait for the
@@ -95,19 +101,33 @@ export async function clickMenuButton(page: Page, text: string) {
await dialog.locator(`button:has-text("${text}")`).click();
}
/**
* Close the toasts of the ComfyUI frontend. One of them, such as the error
* `getCanvas: canvas is null` that the frontend can raise while several pages
* load at once, can lie over a button of a Manager dialog, and a click on
* that button then never arrives.
*/
export async function closeToasts(page: Page) {
const closeButtons = page.locator('[data-testid="toast"]').getByRole('button', { name: 'Close' });
// A closed toast leaves the page and the others move up, so each click is
// on the one that is first by then.
for (let left = await closeButtons.count(); left > 0; left--) {
await closeButtons.first().click({ timeout: 2_000 }).catch(() => {});
await expect(closeButtons).toHaveCount(left - 1, { timeout: 2_000 }).catch(() => {});
}
}
/** Close the topmost dialog via its X (close) button or Escape. */
export async function closeDialog(page: Page) {
// Try clicking close buttons on visible dialogs. The manager-menu dialog
// (`#cm-manager-dialog`) is a ComfyDialog with `.p-dialog-close-button` (X),
// while sub-dialogs use `.cm-close-btn`. Try both.
// Every Manager dialog has a `.cm-ui-close` (X). A sub-dialog lies
// over the manager-menu dialog (`#cm-manager-dialog`), whose X stays visible
// but cannot be clicked then, so the sub-dialogs are tried first.
for (const sel of [
'#cn-manager-dialog button.cm-close-btn',
'#cmm-manager-dialog button.cm-close-btn',
'#snapshot-manager-dialog button.cm-close-btn',
'#cm-manager-dialog button.cm-close-btn',
'#cm-manager-dialog .p-dialog-close-button',
'.cm-close-btn',
'.p-dialog-close-button',
'#cn-manager-dialog .cm-ui-close',
'#cmm-manager-dialog .cm-ui-close',
'#snapshot-manager-dialog .cm-ui-close',
'#cm-manager-dialog .cm-ui-close',
'.cm-ui-close',
]) {
const btn = page.locator(sel).last();
if (await btn.isVisible({ timeout: 500 }).catch(() => false)) {
@@ -126,3 +146,225 @@ export async function assertManagerMenuVisible(page: Page) {
const dialog = page.locator('#cm-manager-dialog').first();
await expect(dialog).toBeVisible();
}
// ---------------------------------------------------------------------------
// XSS fixtures. Additive — nothing above is changed.
// ---------------------------------------------------------------------------
/**
* The payload used by every XSS row. Assertions on it have THREE legs, because
* a payload can be neutered in a way that also deletes it:
* (1) presence — the container's textContent contains the literal payload
* (2) structure — no element the payload would have created exists
* (3) execution — window.__xss_fired is undefined after render
*/
export const XSS_PAYLOAD = '<img src=x onerror="window.__xss_fired=1">';
/** Space-free variant — the `last_update` formatter cuts its value at the
* first space with `.split(' ')[0]`, so a spaced payload would be truncated
* and the row would pass for the wrong reason. */
export const XSS_PAYLOAD_NOSPACE = '<img/src=x/onerror="window.__xss_fired=1">';
/** One `/v2/customnode/getlist` pack, shaped exactly like the live response
* (verified against the running server: {channel, node_packs: {id: item}}). */
export function makePack(id: string, overrides: Record<string, unknown> = {}) {
return {
author: 'author-' + id,
description: 'description of ' + id,
files: [`https://github.com/example/${id}`],
install_type: 'git-clone',
reference: `https://github.com/example/${id}`,
repository: `https://github.com/example/${id}`,
title: id,
cnr_latest: '1.0.0',
id,
health: '-',
state: 'not-installed',
version: '1.0.0',
'update-state': 'false',
stars: 5,
last_update: '2026-01-01 00:00:00',
trust: false,
...overrides,
};
}
/** Replace the pack list the grid renders from.
*
* NOTE, because any result read from these fixtures depends on it:
* page.route() REPLACES the HTTP response, so the fixture BYPASSES
* populate_markdown. For
* RAW fields that is what a live server can actually deliver; for
* SERVER-ESCAPED fields it delivers input the live server currently cannot,
* so such a fixture must be pre-transformed with `serverSanitizeTag` below —
* otherwise the row asserts against a wire form that does not exist. */
export async function routeNodeList(page: Page, packs: Record<string, unknown>) {
await page.route('**/customnode/getlist**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ channel: 'default', node_packs: packs }),
});
});
}
/** Seed `/v2/customnode/getmappings` — that route performs NO server-side
* sanitization, so the values it returns are genuinely raw. */
export async function routeMappings(page: Page, mappings: Record<string, unknown>) {
await page.route('**/customnode/getmappings**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(mappings),
});
});
}
/** Open Manager menu -> Custom Nodes Manager and wait for the grid to fill. */
export async function openCustomNodesManager(page: Page) {
await clickMenuButton(page, 'Custom Nodes Manager');
await page.waitForSelector('#cn-manager-dialog', { timeout: 15_000 });
await page.waitForSelector('.cn-manager-grid, .tg-body', { timeout: 15_000 });
await page.waitForFunction(
() => document.querySelectorAll('.tg-body .tg-row, .cn-manager-grid tr').length > 0,
{ timeout: 30_000, polling: 500 },
);
}
/** The three legs, applied to one container. `payload` is the literal string
* the user must SEE; `createdSelector` is what the payload would have built. */
export async function expectInert(
page: Page,
containerSelector: string,
payload: string,
createdSelector: string,
label: string,
) {
// ALL THREE LEGS ARE EVALUATED BEFORE ANY ASSERTION FIRES, and that is
// load-bearing rather than stylistic. Asserting presence first and
// short-circuiting cannot distinguish the two ways leg 1 fails:
// - the payload was PARSED AS MARKUP (the defect) — textContent holds the
// rendered result, not the literal source, so presence fails; or
// - the payload NEVER RENDERED (a broken fixture) — presence fails too.
// Those are opposite conclusions from an identical symptom, so a failure whose
// message cannot tell them apart is not evidence of anything. The
// diagnostic below reports all three observations on every failure.
const text = (await page.locator(containerSelector).first().textContent()) ?? '';
const created = await page.locator(`${containerSelector} ${createdSelector}`).count();
const fired = await page.evaluate(() => (window as unknown as Record<string, unknown>).__xss_fired);
const present = text.includes(payload);
const diagnostic =
`${label} — three-leg result in ${containerSelector}:\n` +
` leg 1 presence : ${present ? 'PASS (payload visible as literal text)' : 'FAIL (payload not present as literal text)'}\n` +
` leg 2 structure : ${created === 0 ? 'PASS (no <' + createdSelector + '> constructed)' : `FAIL (${created} live <${createdSelector}> constructed — the value reached innerHTML AS MARKUP)`}\n` +
` leg 3 execution : ${fired === undefined ? 'PASS (window.__xss_fired unset)' : `FAIL (window.__xss_fired=${JSON.stringify(fired)} — the payload EXECUTED)`}\n` +
` READ IT THIS WAY: leg 2 or leg 3 failing = the sink is LIVE (this is the failure being demonstrated).\n` +
` leg 1 failing while legs 2 and 3 PASS = the payload never rendered at all — a BROKEN FIXTURE, not a defect;\n` +
` the row proves nothing in that state and must be fixed rather than reported.\n` +
` container text (first 300 chars): ${JSON.stringify(text.slice(0, 300))}`;
expect(created, diagnostic).toBe(0);
expect(fired, diagnostic).toBeUndefined();
expect(present, diagnostic).toBe(true);
}
/** Run the shipped Python renderer, including its title/name/description contract. */
export function serverPopulateMarkdown(item: Record<string, unknown>): Record<string, any> {
return JSON.parse(execFileSync(process.env.PYTHON || 'python3',
[path.join(REPO_ROOT, 'tests', 'legacy_html_testutil.py')],
{ input: JSON.stringify(item), encoding: 'utf-8' }));
}
export function serverSanitizeTag(value: string): string {
return serverPopulateMarkdown({ title: value }).title;
}
/** The RESTART clause both server install-denial constants state.
*
* `js/common.js: INSTALL_DENIAL_MESSAGES` is a hand-written client copy of a
* fact the SERVER owns: the install flag and `network_mode` are read once at
* ComfyUI startup, so editing config.ini and retrying is denied identically
* until the server is restarted. Nothing makes the two texts move together, so
* the client copy is exactly the kind of thing that silently falls behind — it
* already had, which is why this helper exists.
*
* Read from `SECURITY_MESSAGE_FLAG_GIT_URL` / `SECURITY_MESSAGE_FLAG_PIP` and
* cross-checked against each other, so the assertion is against the SERVER's
* wording rather than a third copy typed into the test. The word "restart" is
* only the search key; the whole asserted sentence comes from the source. */
export function serverInstallDenialRestartClause(): string {
const srcPath = path.join(REPO_ROOT, 'comfyui_manager', 'legacy', 'manager_server.py');
const src = fs.readFileSync(srcPath, 'utf-8');
const names = ['SECURITY_MESSAGE_FLAG_GIT_URL', 'SECURITY_MESSAGE_FLAG_PIP'];
const clauses = names.map((name) => {
const m = new RegExp(`^${name}\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"`, 'm').exec(src);
if (!m) {
throw new Error(
`serverInstallDenialRestartClause: ${name} not found as a double-quoted ` +
`string literal in ${srcPath} — the server constant moved or changed shape.`,
);
}
const sentence = m[1].split('. ').find((s) => /\brestart\b/i.test(s));
if (!sentence) {
throw new Error(
`serverInstallDenialRestartClause: ${name} states no sentence mentioning a ` +
'restart. Either the server dropped the fact (and the client copy should ' +
'drop it too) or the wording changed — do not paper over it here.',
);
}
return `${sentence.trim()}.`;
});
if (clauses[0] !== clauses[1]) {
throw new Error(
'serverInstallDenialRestartClause: the two server constants state DIFFERENT ' +
`restart clauses, so there is no single fact to check the client against:\n` +
` ${names[0]}: ${JSON.stringify(clauses[0])}\n` +
` ${names[1]}: ${JSON.stringify(clauses[1])}`,
);
}
return clauses[0];
}
// ---------------------------------------------------------------------------
// Model Manager fixtures.
// ---------------------------------------------------------------------------
/** One `/v2/externalmodel/getlist` model, shaped like the live response. */
export function makeModel(name: string, overrides: Record<string, unknown> = {}) {
return {
name,
type: 'checkpoint',
base: 'SD1.5',
save_path: 'checkpoints',
description: 'description of ' + name,
reference: 'https://example.com/' + name,
filename: name + '.safetensors',
url: 'https://example.com/' + name + '.safetensors',
size: '1.0MB',
installed: 'False',
...overrides,
};
}
/** Replace the model list the Model Manager grid renders from. */
export async function routeModelList(page: Page, models: Record<string, unknown>[]) {
await page.route('**/externalmodel/getlist**', async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ models }),
});
});
}
/** Open Manager menu -> Model Manager and wait for the grid to fill. */
export async function openModelManager(page: Page) {
await clickMenuButton(page, 'Model Manager');
await page.waitForSelector('#cmm-manager-dialog', { timeout: 15_000 });
await page.waitForSelector('.cmm-manager-grid, .tg-body', { timeout: 15_000 });
await page.waitForFunction(
() => document.querySelectorAll('.tg-body .tg-row, .cmm-manager-grid tr').length > 0,
{ timeout: 30_000, polling: 500 },
);
}
@@ -0,0 +1,575 @@
import { test, expect, type Page } from '@playwright/test';
import {
waitForComfyUI, openManagerMenu, openCustomNodesManager, openModelManager,
routeNodeList, routeModelList, makePack, makeModel, serverSanitizeTag, XSS_PAYLOAD,
} from './helpers';
/** The grid replaces the status line with its row count as soon as it redraws, so record the
* texts that the manager passes to it; read them from `window.__statuses`. */
async function recordStatuses(page: Page, file: string, exported: string) {
await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
const showStatus = manager.showStatus.bind(manager);
(window as any).__statuses = [];
manager.showStatus = (msg: string, color?: string) => {
(window as any).__statuses.push(msg);
showStatus(msg, color);
};
}, { file, exported });
}
for (const kind of ['nodes', 'models']) {
const prefix = kind === 'nodes' ? 'cn' : 'cmm';
const file = kind === 'nodes' ? 'custom-nodes-manager' : 'model-manager';
const exported = kind === 'nodes' ? 'CustomNodesManager' : 'ModelManager';
for (const failure of ['network', 'http', 'json', 'shape']) {
test(`${kind}: ${failure} batch failure clears pending controls`, async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
if (kind === 'nodes') {
await routeNodeList(page, { victim: makePack('victim', { version: 'unknown' }) });
} else {
await routeModelList(page, [makeModel('victim')]);
}
await page.route('**/v2/manager/queue/batch', async route => {
if (failure === 'network') return route.abort('failed');
if (failure === 'http') return route.fulfill({ status: 500, json: { failed: [] } });
if (failure === 'json') return route.fulfill({ contentType: 'application/json', body: 'invalid' });
return route.fulfill({ json: { failed: {} } });
});
await openManagerMenu(page);
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
await page.locator(`.${prefix}-manager-grid .${prefix}-btn-install`).first().click();
await expect(page.locator(`.${prefix}-manager-message`)).toContainText('Failed to submit installation request');
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
expect(await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
// The Model Manager keeps one pending install for each batch.
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
}, { file, exported })).toBe(false);
expect(errors).toEqual([]);
});
}
test(`${kind}: rejected batch names and unknown IDs reach both error displays safely`, async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
const title = serverSanitizeTag('Pack &amp; Friends ' + XSS_PAYLOAD);
if (kind === 'nodes') {
await routeNodeList(page, { victim: makePack('victim', { title, version: 'unknown' }) });
} else {
await routeModelList(page, [makeModel(title)]);
}
await page.route('**/v2/manager/queue/batch', async route => {
const batch = route.request().postDataJSON();
const items = batch[kind === 'nodes' ? 'install' : 'install_model'];
expect(items[0].id).toBeTruthy();
// The socket event may arrive before the HTTP rejection response.
await page.evaluate(async () => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: { status: 'all-done' } }));
});
await route.fulfill({ json: { failed: [items[0].id, XSS_PAYLOAD] } });
});
await openManagerMenu(page);
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
if (kind === 'models') {
await page.locator('.cmm-manager-type').evaluate(select => select.setAttribute('disabled', ''));
}
await page.locator(`.${prefix}-manager-grid .${prefix}-btn-install`).first().click();
const message = page.locator(`.${prefix}-manager-message`);
await expect(message).toContainText('[FAIL] Pack & Friends ' + XSS_PAYLOAD);
await expect(message).toContainText('[FAIL] ' + XSS_PAYLOAD);
expect(await message.locator('img').count()).toBe(0);
const dialog = await page.evaluate(async () => {
const { app } = await import('/scripts/app.js');
return { text: app.ui.dialog.element.textContent, images: app.ui.dialog.element.querySelectorAll('img').length };
});
expect(dialog.text).toContain('[FAIL] Pack & Friends ' + XSS_PAYLOAD);
expect(dialog.text).toContain('[FAIL] ' + XSS_PAYLOAD);
expect(dialog.images).toBe(0);
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
if (kind === 'models') {
await expect(page.locator('.cmm-manager-type')).toBeDisabled();
}
expect(await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
}, { file, exported })).toBe(false);
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
expect(errors).toEqual([]);
});
for (const rejectedCount of [0, 1]) {
test(`${kind}: ${rejectedCount} rejections keep accepted work pending until completion`, async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
if (kind === 'nodes') {
await routeNodeList(page, {
first: makePack('first', { version: 'unknown' }),
second: makePack('second', { version: 'unknown' }),
});
} else {
await routeModelList(page, [makeModel('first'), makeModel('second')]);
}
let completion: Record<string, unknown>;
await page.route('**/v2/manager/queue/batch', async route => {
const batch = route.request().postDataJSON();
const items = batch[kind === 'nodes' ? 'install' : 'install_model'];
const result = Object.fromEntries(items.slice(rejectedCount).map(item => [item.ui_id, 'success']));
completion = { status: 'batch-done', batch_id: batch.batch_id,
nodepack_result: kind === 'nodes' ? result : {}, model_result: kind === 'models' ? result : {},
done_count: items.length - rejectedCount, total_count: items.length - rejectedCount };
await route.fulfill({ json: { failed: items.slice(0, rejectedCount).map(item => item.id) } });
});
await openManagerMenu(page);
await (kind === 'nodes' ? openCustomNodesManager(page) : openModelManager(page));
await page.evaluate(async ({ file, exported, kind, prefix }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
const button = manager.element.querySelector(`.${prefix}-btn-install`);
if (kind === 'nodes') {
await manager.installNodes(Object.values(manager.custom_nodes).map((item: any) => item.hash),
{ target: button, label: 'Install', mode: 'install' });
} else {
await manager.installModels(manager.modelList, button);
}
}, { file, exported, kind, prefix });
await expect(page.locator(`.${prefix}-manager-stop`)).toBeVisible();
expect(await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
// The Model Manager keeps one pending install for each batch.
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
}, { file, exported })).toBe(true);
// A batch that carries no result for this manager is another manager's batch.
await page.evaluate(async detail => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail }));
}, { status: 'batch-done', batch_id: 'another-batch', nodepack_result: kind === 'nodes' ? {} : { other: 'success' },
model_result: kind === 'models' ? {} : { other: 'success' }, done_count: 1, total_count: 1 });
expect(await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
// The Model Manager keeps one pending install for each batch.
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
}, { file, exported })).toBe(true);
await recordStatuses(page, file, exported);
await page.evaluate(async detail => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail }));
}, completion!);
await expect(page.locator(`.${prefix}-manager-stop`)).toBeHidden();
await expect(page.locator(`.${prefix}-btn-loading`)).toHaveCount(0);
expect(await page.evaluate(() => (window as any).__statuses)).toContain(
`Install ${2 - rejectedCount} ${kind === 'nodes' ? 'custom node(s)' : 'models'} successfully`);
expect(await page.evaluate(async ({ file, exported }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = module[exported].instance;
// The Model Manager keeps one pending install for each batch.
return manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
}, { file, exported })).toBe(false);
});
}
test(`${kind}: HTML messages preserve names and assign color through the DOM`, async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
const wire = serverSanitizeTag('Pack &amp; Friends <Flux>');
const result = await page.evaluate(async ({ file, exported, prefix, wire }) => {
const module = await import(`/extensions/comfyui-manager-legacy/${file}.js`);
const manager = Object.create(module[exported].prototype);
manager.element = document.createElement('div');
manager.element.innerHTML = `<div class="${prefix}-manager-message"></div><div class="${prefix}-manager-status"></div>`;
document.body.append(manager.element);
manager.showMessage(wire, 'rgb(1, 2, 3)');
manager.showStatus(wire, '"><img src=x onerror="window.__xss_fired=1">');
const [message, status] = manager.element.children;
const result = { message: message.textContent, status: status.textContent,
color: message.style.color, children: status.children.length };
manager.showMessage('done');
return { ...result, resetColor: message.style.color };
}, { file, exported, prefix, wire });
expect(result).toEqual({ message: 'Pack & Friends <Flux>', status: 'Pack & Friends <Flux>',
color: 'rgb(1, 2, 3)', children: 0, resetColor: '' });
});
}
for (const outcome of ['success', 'failure']) {
test(`models: only the active batch can update progress and complete (${outcome})`, async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
let batch: { batch_id: string; install_model: { ui_id: string }[] };
await page.route('**/v2/manager/queue/batch', async route => {
batch = route.request().postDataJSON();
await route.fulfill({ json: { failed: [] } });
});
await openManagerMenu(page);
await openModelManager(page);
await page.evaluate(async () => {
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
const manager = ModelManager.instance;
const button = manager.element.querySelector('.cmm-btn-install');
await manager.installModels(manager.modelList, button);
});
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
const target = batch!.install_model[0].ui_id;
const status = (batchId: string, state: string, modelResult: Record<string, string>) => ({
status: state, batch_id: batchId, ui_target: 'model_manager', target,
model_result: modelResult, done_count: 1, total_count: 1,
});
const dispatch = async (detail: ReturnType<typeof status>) => {
await page.evaluate(async value => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: value }));
}, detail);
};
const state = () => page.evaluate(async hash => {
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
const manager = ModelManager.instance;
const pending = manager.install_contexts ? manager.install_contexts.size > 0 : !!manager.install_context;
return { pending, refresh: !!manager.grid.getRowItemBy('hash', hash)?.refresh };
}, target);
await dispatch(status('other-batch', 'in_progress', {}));
expect(await state()).toEqual({ pending: true, refresh: false });
await dispatch(status('other-batch', 'batch-done', { [target]: 'success' }));
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
expect(await state()).toEqual({ pending: true, refresh: false });
await dispatch(status(batch!.batch_id, 'in_progress', {}));
expect(await state()).toEqual({ pending: true, refresh: true });
const result = { [target]: outcome === 'success' ? 'success' : 'download failed' };
await recordStatuses(page, 'model-manager', 'ModelManager');
await dispatch(status(batch!.batch_id, 'batch-done', result));
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
expect((await state()).pending).toBe(false);
const statuses = await page.evaluate(() => (window as any).__statuses);
const refresh = "To apply the installed model, please click the 'Refresh' button.";
if (outcome === 'success') {
expect(statuses).toContain('Install 1 models successfully');
await expect(page.locator('.cmm-manager-message')).toContainText(refresh);
} else {
await expect(page.locator('.cmm-manager-message')).toContainText('download failed');
await expect(page.locator('.cmm-manager-message')).not.toContainText(refresh);
}
await dispatch(status(batch!.batch_id, 'batch-done', { [target]: 'success' }));
expect((await state()).pending).toBe(false);
expect(errors).toEqual([]);
});
}
type PostedBatch = { batch_id: string; install_model: { ui_id: string }[] };
/** Answer the Model Manager's question whether the queue is running. The batch request is replaced
* in these cases, so the real server never has the batch in its queue. */
async function routeQueueStatus(page: Page, isProcessing: boolean) {
await page.route('**/v2/manager/queue/status', route => route.fulfill({
json: { total_count: 0, done_count: 0, in_progress_count: 0, is_processing: isProcessing },
}));
}
/** Keep the Model Manager's checks of the queue, so that a case can wait until they have finished. */
async function recordQueueChecks(page: Page) {
await page.evaluate(async () => {
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
const manager = ModelManager.instance;
const check = manager.endDroppedInstalls.bind(manager);
(window as any).__queueChecks = [];
manager.endDroppedInstalls = () => {
const finished = check();
(window as any).__queueChecks.push(finished);
return finished;
};
});
}
/** Resolve once every check of the queue that was started has handled its answer. */
async function queueChecked(page: Page) {
await page.evaluate(async () => {
const checks = (window as any).__queueChecks;
if (checks.length === 0) throw new Error('The queue was not checked');
await Promise.all(checks);
});
}
/** Start one install for each of the listed models, as clicking Install in their rows does one after
* the other; resolve with the id and the target of each batch that was posted. */
async function installEachModel(page: Page, onBatchPosted?: (batch: PostedBatch) => Promise<void>) {
const batches: PostedBatch[] = [];
await page.route('**/v2/manager/queue/batch', async route => {
batches.push(route.request().postDataJSON());
await onBatchPosted?.(batches.at(-1)!);
await route.fulfill({ json: { failed: [] } });
});
await openManagerMenu(page);
await openModelManager(page);
await page.evaluate(async () => {
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
const manager = ModelManager.instance;
for (const item of manager.modelList) {
const button = manager.grid.getCellNode(item, 'installed').querySelector('button[mode="install"]');
await manager.installModels([item], button);
}
});
return batches.map(batch => ({ id: batch.batch_id, target: batch.install_model[0].ui_id }));
}
async function dispatchQueueStatus(page: Page, detail: Record<string, unknown>) {
await page.evaluate(async value => {
const { api } = await import('/scripts/api.js');
api.dispatchEvent(new CustomEvent('cm-queue-status', { detail: value }));
}, detail);
}
/** How many installs are pending, and which of the given rows are marked as downloaded. */
async function modelInstallState(page: Page, targets: string[]) {
return page.evaluate(async hashes => {
const { ModelManager } = await import('/extensions/comfyui-manager-legacy/model-manager.js');
const manager = ModelManager.instance;
return {
// A manager that keeps one install only has one pending at most.
pending: manager.install_contexts ? manager.install_contexts.size : (manager.install_context ? 1 : 0),
downloaded: hashes.map(hash => !!manager.grid.getRowItemBy('hash', hash)?.refresh),
};
}, targets);
}
test('models: each of two installs started in a row ends with its own batch', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('first'), makeModel('second')]);
const [first, second] = await installEachModel(page);
const targets = [first.target, second.target];
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(2);
expect(await modelInstallState(page, targets)).toEqual({ pending: 2, downloaded: [false, false] });
const report = (batch: { id: string; target: string }, status: string) => dispatchQueueStatus(page, {
status, batch_id: batch.id, ui_target: 'model_manager', target: batch.target,
model_result: { [batch.target]: 'success' }, done_count: 1, total_count: 1,
});
await report(first, 'in_progress');
await report(first, 'batch-done');
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(1);
expect(await modelInstallState(page, targets)).toEqual({ pending: 1, downloaded: [true, false] });
await report(second, 'in_progress');
await report(second, 'batch-done');
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
expect(await modelInstallState(page, targets)).toEqual({ pending: 0, downloaded: [true, true] });
expect(errors).toEqual([]);
});
test('models: a queue that ends without the batch returns the install to idle', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('first'), makeModel('second')]);
// Stop empties the queue: the task that is running ends, and then only the end of the queue is reported.
await routeQueueStatus(page, false);
const [first, second] = await installEachModel(page);
const targets = [first.target, second.target];
await dispatchQueueStatus(page, { status: 'in_progress', batch_id: first.id, ui_target: 'model_manager', target: first.target });
expect(await modelInstallState(page, targets)).toEqual({ pending: 2, downloaded: [true, false] });
await dispatchQueueStatus(page, { status: 'all-done' });
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
expect(await modelInstallState(page, targets)).toEqual({ pending: 0, downloaded: [true, false] });
await expect(page.locator('.cmm-manager-message')).toContainText("To apply the installed model, please click the 'Refresh' button.");
expect(errors).toEqual([]);
});
test('models: a stopped queue that downloaded nothing asks for no refresh', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
await routeQueueStatus(page, false);
const [batch] = await installEachModel(page);
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
await dispatchQueueStatus(page, { status: 'all-done' });
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
await expect(page.locator('.cmm-manager-message')).toHaveText('');
await expect(page.locator('.cmm-manager-refresh')).toBeHidden();
});
test('models: the end of an earlier queue does not end an install that is being queued', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
// The report of the queue that ran before reaches the page while the batch is still being posted.
// The batch is then added to the queue and runs.
await routeQueueStatus(page, true);
let asked = 0;
page.on('request', request => { if (request.url().endsWith('/v2/manager/queue/status')) asked++; });
const [batch] = await installEachModel(page, async () => {
await recordQueueChecks(page);
await dispatchQueueStatus(page, { status: 'all-done' });
});
await queueChecked(page);
expect(asked).toBe(1);
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
});
test('models: an install that was dropped while it was being queued returns to idle', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
// Stop emptied the queue after the batch was added to it, and the end of the queue is reported
// before the answer to the batch request arrives.
await routeQueueStatus(page, false);
const [batch] = await installEachModel(page, () => dispatchQueueStatus(page, { status: 'all-done' }));
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
});
test('models: the end of an earlier queue does not end an install that is running', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
// The report of the queue that ran before reaches the page after the answer to the batch request.
await routeQueueStatus(page, true);
const [batch] = await installEachModel(page);
await recordQueueChecks(page);
await dispatchQueueStatus(page, { status: 'all-done' });
await queueChecked(page);
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(1);
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
await dispatchQueueStatus(page, { status: 'batch-done', batch_id: batch.id,
model_result: { [batch.target]: 'success' }, done_count: 1, total_count: 1 });
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
});
test('models: an install stays pending when the queue cannot be asked', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
// Without an answer the queue may still be running the batch.
await page.route('**/v2/manager/queue/status', route => route.fulfill({ status: 500, body: 'error' }));
const [batch] = await installEachModel(page);
await recordQueueChecks(page);
await dispatchQueueStatus(page, { status: 'all-done' });
await queueChecked(page);
await expect(page.locator('.cmm-manager-stop')).toBeVisible();
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 1, downloaded: [false] });
// The next report of the end of the queue that can be checked ends it.
await page.unroute('**/v2/manager/queue/status');
await routeQueueStatus(page, false);
await dispatchQueueStatus(page, { status: 'all-done' });
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
});
test('models: a batch that ends before its request is answered completes the install', async ({ page }) => {
const errors: string[] = [];
page.on('pageerror', error => errors.push(String(error)));
await page.goto('/');
await waitForComfyUI(page);
await routeModelList(page, [makeModel('victim')]);
const [batch] = await installEachModel(page, posted => dispatchQueueStatus(page, {
status: 'batch-done', batch_id: posted.batch_id,
model_result: { [posted.install_model[0].ui_id]: 'download failed' }, done_count: 1, total_count: 1,
}));
await expect(page.locator('.cmm-manager-message')).toContainText('download failed');
await expect(page.locator('.cmm-manager-stop')).toBeHidden();
await expect(page.locator('.cmm-btn-loading')).toHaveCount(0);
expect(await modelInstallState(page, [batch.target])).toEqual({ pending: 0, downloaded: [false] });
expect(errors).toEqual([]);
});
test('nodes: lookup errors and missing row IDs remain literal text', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
const results = await page.evaluate(async payload => {
const { CustomNodesManager } = await import('/extensions/comfyui-manager-legacy/custom-nodes-manager.js');
const common = await import('/extensions/comfyui-manager-legacy/common.js');
const { api } = await import('/scripts/api.js');
const manager = Object.create(CustomNodesManager.prototype);
manager.element = document.createElement('div');
manager.element.innerHTML = '<div class="cn-manager-message"></div><div class="cn-manager-status"></div>';
document.body.append(manager.element);
manager.grid = { getRowItemBy: () => undefined, updateCell: () => { throw new Error('Missing row updated'); } };
const saved = api.fetchApi;
const previousManager = common.manager_instance;
common.setManagerInstance({ datasrc_combo: { value: 'cache' } });
api.fetchApi = async () => ({ status: 500, statusText: payload });
const results = [];
try {
for (const invoke of [
() => manager.getMissingNodesLegacy({}, new Set()),
() => manager.installNodes([payload], { target: document.createElement('button'), mode: 'install' }),
]) {
await invoke();
const message = manager.element.querySelector('.cn-manager-message');
results.push({ text: message.textContent, images: message.querySelectorAll('img').length });
}
} finally {
api.fetchApi = saved;
common.setManagerInstance(previousManager);
}
return results;
}, XSS_PAYLOAD);
expect(results).toHaveLength(2);
for (const result of results) {
expect(result.text).toContain(XSS_PAYLOAD);
expect(result.images).toBe(0);
}
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
});
test('nodes: workflow registry IDs remain inert in the Missing Nodes dialog', async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
const result = await page.evaluate(async payload => {
const { app } = await import('/scripts/app.js');
const { CustomNodesManager } = await import('/extensions/comfyui-manager-legacy/custom-nodes-manager.js');
const manager = Object.create(CustomNodesManager.prototype);
manager.custom_nodes = {};
manager.getMissingNodesLegacy = async () => {};
const nodes = app.graph._nodes;
try {
app.graph._nodes = [{ type: 'MissingTestNode', properties: { cnr_id: payload } }];
await manager.getMissingNodes();
} finally {
app.graph._nodes = nodes;
}
const dialog = app.ui.dialog.element;
return { text: dialog.textContent, images: dialog.querySelectorAll('img').length };
}, XSS_PAYLOAD + ' &amp; Registry');
expect(result.images).toBe(0);
expect(result.text).toContain(XSS_PAYLOAD + ' &amp; Registry');
expect(await page.evaluate(() => (window as any).__xss_fired)).toBeUndefined();
});
@@ -0,0 +1,54 @@
/**
* E2E tests: the Manager dialogs bring their own styles.
*
* The ComfyUI frontend no longer ships the PrimeVue dialog styles. A dialog
* that relies on them has no background, and its buttons lie over the canvas.
*
* Requires ComfyUI running with --enable-manager-legacy-ui on PORT.
*/
import { test, expect, type Page } from '@playwright/test';
import { waitForComfyUI, openManagerMenu, clickMenuButton } from './helpers';
const TRANSPARENT = 'rgba(0, 0, 0, 0)';
const DIALOGS: [string, string | null, string][] = [
['Manager menu', null, '#cm-manager-dialog'],
['Custom Nodes Manager', 'Custom Nodes Manager', '#cn-manager-dialog'],
['Model Manager', 'Model Manager', '#cmm-manager-dialog'],
['Snapshot Manager', 'Snapshot Manager', '#snapshot-manager-dialog'],
];
async function open(page: Page, button: string | null, selector: string) {
await openManagerMenu(page);
if (button) await clickMenuButton(page, button);
await page.waitForSelector(selector, { timeout: 15_000 });
return page.locator(selector).last();
}
function background(locator: ReturnType<Page['locator']>) {
return locator.evaluate((element) => getComputedStyle(element).backgroundColor);
}
test.describe('Dialog styles', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await waitForComfyUI(page);
});
for (const [name, button, selector] of DIALOGS) {
test(`${name} has a background and dims the page behind it`, async ({ page }) => {
const dialog = await open(page, button, selector);
expect(await background(dialog)).not.toBe(TRANSPARENT);
expect(await background(dialog.locator('xpath=..'))).not.toBe(TRANSPARENT);
});
test(`${name} is closed by its close button`, async ({ page }) => {
const dialog = await open(page, button, selector);
await dialog.getByRole('button', { name: 'Close' }).click();
await expect(dialog).toBeHidden();
});
}
});
+8 -11
View File
@@ -100,7 +100,7 @@ test.describe('UI-driven install/uninstall', () => {
test('LB1 Install button triggers install effect', async ({ page }) => {
// Reset queue at start for deterministic done_count baseline in waitForAllDone
await page.request.post('/v2/manager/queue/reset');
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
// Precondition: pack must NOT be installed. If the seed pack is already
// installed (prior pytest runs, pre-seeded E2E environment), the
@@ -128,7 +128,7 @@ test.describe('UI-driven install/uninstall', () => {
headers: { 'Content-Type': 'application/json' },
});
expect(queueResp.ok()).toBe(true);
await page.request.post('/v2/manager/queue/start');
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
await waitForAllDone(page, 60_000);
// Hard fail if setup itself couldn't uninstall the pack
expect(await isPackInstalled(page)).toBe(false);
@@ -141,16 +141,13 @@ test.describe('UI-driven install/uninstall', () => {
// Wait for grid to populate before applying filter (avoids race on empty grid)
await expect(page.locator('.tg-body .tg-row').first()).toBeVisible({ timeout: 30_000 });
const initialRowCount = await page.locator('.tg-body .tg-row').count();
// Filter to Not Installed to make install buttons visible. Wait for
// filtered row count to actually change (DOM state, not wall-clock).
// Filter to Not Installed to make install buttons visible. The grid
// renders only the rows in view, so their number does not tell whether
// the filter was applied; the search below waits for its own result.
const filterSelect = page.locator('select.cn-manager-filter').first();
if (await filterSelect.isVisible().catch(() => false)) {
await filterSelect.selectOption({ value: 'not-installed' });
await expect
.poll(async () => page.locator('.tg-body .tg-row').count(), { timeout: 10_000 })
.not.toBe(initialRowCount);
}
// Search for the specific test pack. Wait for search to narrow results.
@@ -198,7 +195,7 @@ test.describe('UI-driven install/uninstall', () => {
test('LB2 Uninstall button triggers uninstall effect', async ({ page }) => {
// Reset queue at start for deterministic done_count baseline in waitForAllDone
await page.request.post('/v2/manager/queue/reset');
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
// Precondition: pack must be installed. Install via API as test SETUP
// (not verification). This makes LB2 independent of LB1 — hard-failing
@@ -207,7 +204,7 @@ test.describe('UI-driven install/uninstall', () => {
// is async, so waitForAllDone is still required after queue/start.
const preinstalled = await isPackInstalled(page);
if (!preinstalled) {
await page.request.post('/v2/manager/queue/reset');
await page.request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
const queueResp = await page.request.post('/v2/manager/queue/batch', {
data: JSON.stringify({
batch_id: 'lb2-setup-install',
@@ -225,7 +222,7 @@ test.describe('UI-driven install/uninstall', () => {
expect(queueResp.ok()).toBe(true);
const queueBody = await queueResp.json();
expect(queueBody.failed ?? []).toEqual([]);
await page.request.post('/v2/manager/queue/start');
await page.request.post('/v2/manager/queue/start', { headers: { 'Content-Type': 'application/json' } });
// Poll the terminal state directly: isPackInstalled returning true is
// the unambiguous success signal. Using waitForAllDone here is racy —
// fast-path installs (pack already on disk / cached CNR artifacts) can
@@ -56,7 +56,7 @@ test.describe('Manager Menu Dialog', () => {
// No page.request / page.waitForResponse — pure UI interaction + dialog
// close-reopen as the persistence proof. networkidle is used only as a
// settle barrier (wait), never as assertion input. Close via the dialog's
// own `.p-dialog-close-button` (X button) because Escape doesn't close
// own `.cm-ui-close` (X button) because Escape doesn't close
// ComfyDialog reliably.
await openManagerMenu(page);
const dialog = page.locator('#cm-manager-dialog').first();
@@ -72,7 +72,7 @@ test.describe('Manager Menu Dialog', () => {
await page.waitForLoadState('networkidle');
// Close + reopen (UI-only persistence proof)
await dialog.locator('.p-dialog-close-button').first().click();
await dialog.locator('.cm-ui-close').first().click();
// ComfyDialog.close() sets display:none but keeps the element in DOM,
// so check visibility (toBeHidden), not presence (toHaveCount 0).
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
@@ -106,6 +106,63 @@ test.describe('Manager Menu Dialog', () => {
}
});
for (const setting of [
{ name: 'DB mode', route: '/v2/manager/db_mode', options: /Cache|Local|Channel/, values: ['local', 'remote'] },
{ name: 'Update Policy', route: '/v2/manager/policy/update', options: /Stable|Nightly/, values: ['nightly-comfyui', 'stable-comfyui'] },
{ name: 'Share', route: '/v2/manager/share_option', options: /YouML|Matrix/, values: ['youml', 'matrix'] },
]) {
test(`${setting.name}: a choice made while the setting is still loading is kept`, async ({ page }) => {
// The dialog asks the server for the setting when it is first opened.
// Hold the answer back after the server has given it, choose another
// value, then let the answer through. The value that is chosen is not
// the first option, which the select shows before the answer and which
// a user therefore cannot choose.
const reads = (request: { method(): string; url(): string }) =>
request.method() === 'GET' && request.url().includes(setting.route);
const saves = (request: { method(): string; url(): string }) => request.url().includes(setting.route) && !reads(request);
const save = (value: string) =>
page.request.post(setting.route, { data: JSON.stringify({ value }), headers: { 'Content-Type': 'application/json' } });
const stored = await (await page.request.get(setting.route)).text();
const chosen = setting.values.find((value) => value !== stored)!;
let release!: () => void;
const held = new Promise<void>((resolve) => { release = resolve; });
let answered!: () => void;
const answer = new Promise<void>((resolve) => { answered = resolve; });
await page.route(`**${setting.route}*`, async (route) => {
if (!reads(route.request())) {
await route.continue();
return;
}
const response = await route.fetch();
answered();
await held;
await route.fulfill({ response });
});
try {
await openManagerMenu(page);
const combo = page.locator('#cm-manager-dialog').first().locator('select').filter({ hasText: setting.options }).first();
// The answer that is held back is one the server gave before the choice.
await answer;
const saved = page.waitForResponse((response) => saves(response.request()));
await combo.selectOption(chosen);
await saved;
const loaded = page.waitForResponse((response) => reads(response.request()));
release();
await loaded;
await page.waitForTimeout(300);
await expect(combo).toHaveValue(chosen);
expect(await (await page.request.get(setting.route)).text()).toBe(chosen);
} finally {
release();
await page.unroute(`**${setting.route}*`);
await save(stored);
}
});
}
test('Update Policy dropdown persists via UI (close-reopen verification)', async ({ page }) => {
// Wave3 WI-U Cluster H target 2: same UI-only pattern as the DB mode test.
await openManagerMenu(page);
@@ -119,7 +176,7 @@ test.describe('Manager Menu Dialog', () => {
await policyCombo.selectOption(newValue);
await page.waitForLoadState('networkidle');
await dialog.locator('.p-dialog-close-button').first().click();
await dialog.locator('.cm-ui-close').first().click();
// ComfyDialog.close() sets display:none but keeps the element in DOM,
// so check visibility (toBeHidden), not presence (toHaveCount 0).
await expect(page.locator('#cm-manager-dialog').first()).toBeHidden({ timeout: 5_000 });
@@ -316,7 +373,7 @@ test.describe('Manager Menu Dialog', () => {
expect(statusBefore.status()).toBe(200);
const statusJson = await statusBefore.json();
const resetResp = await request.post('/v2/manager/queue/reset');
const resetResp = await request.post('/v2/manager/queue/reset', { headers: { 'Content-Type': 'application/json' } });
expect(resetResp.status()).toBe(200);
// Post-check: queue/status still callable (handler released locks
@@ -42,9 +42,9 @@ test.describe('Dialog Navigation', () => {
timeout: 15_000,
});
// Close the Model Manager dialog via its close button (p-dialog-close-button)
const mmMask = page.locator('.p-dialog-mask:has(#cmm-manager-dialog)');
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .p-dialog-close-button').first();
// Close the Model Manager dialog via its close button
const mmMask = page.locator('.cm-ui-overlay:has(#cmm-manager-dialog)');
const mmCloseBtn = mmMask.locator('button[aria-label="Close"], .cm-ui-close').first();
if (await mmCloseBtn.isVisible({ timeout: 2_000 }).catch(() => false)) {
await mmCloseBtn.click();
} else {

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