Skip to content

The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.

Add deploy to cloud endpoints and feature flag (#17203)

guill4281eb0a1478
diff --git a/app/comfy_api_env.py b/app/comfy_api_env.py
index 17b47933f..e96f9a3a3 100644
--- a/app/comfy_api_env.py
+++ b/app/comfy_api_env.py
@@ -13,6 +13,9 @@ from comfy.cli_args import args
_STAGING_API_HOST = "stagingapi.comfy.org"
_TESTENV_HOST_SUFFIX = ".testenvs.comfy.org"
_STAGING_PLATFORM_BASE_URL = "https://stagingplatform.comfy.org"
+_PROD_PLATFORM_BASE_URL = "https://platform.comfy.org"
+_STAGING_BUILDER_BASE_URL = "https://stagingplatformapi.comfy.org/builder"
+_PROD_BUILDER_BASE_URL = "https://platformapi.comfy.org/builder"
def _is_staging_tier(host: str) -> bool:
@@ -44,3 +47,16 @@ def environment_overrides_for_base(base_url: str) -> dict[str, Any] | None:
def get_environment_overrides() -> dict[str, Any] | None:
return environment_overrides_for_base(getattr(args, "comfy_api_base", "") or "")
+
+
+def _staging_selected() -> bool:
+ return _is_staging_tier(urlparse(getattr(args, "comfy_api_base", "") or "").hostname or "")
+
+
+def builder_base_url() -> str:
+ """comfy-builder API base for the --comfy-api-base tier; fixed mapping, never taken from request data."""
+ return _STAGING_BUILDER_BASE_URL if _staging_selected() else _PROD_BUILDER_BASE_URL
+
+
+def platform_base_url() -> str:
+ return _STAGING_PLATFORM_BASE_URL if _staging_selected() else _PROD_PLATFORM_BASE_URL
diff --git a/app/deploy_to_cloud.py b/app/deploy_to_cloud.py
new file mode 100644
index 000000000..67f6fa187
--- /dev/null
+++ b/app/deploy_to_cloud.py
@@ -0,0 +1,438 @@
+import asyncio
+import configparser
+import importlib.metadata
+import json
+import logging
+import os
+import platform
+import re
+import sys
+import urllib.parse
+from datetime import datetime, timezone
+
+import aiohttp
+from aiohttp import web
+
+import folder_paths
+from comfy.cli_args import args
+from comfy_api import feature_flags
+from app.comfy_api_env import builder_base_url, platform_base_url
+from comfyui_version import __version__
+
+HEADLESS_MARKER = "used_headlessly"
+_marker_warning_logged = False
+
+
+def headless_marker_path() -> str:
+ return os.path.join(folder_paths.get_user_directory(), HEADLESS_MARKER)
+
+
+def used_headlessly() -> bool:
+ return os.path.exists(headless_marker_path())
+
+
+def update_feature_flag() -> None:
+ feature_flags.set_server_feature("deploy_to_cloud", not args.offline and used_headlessly())
+
+
+def mark_used_headlessly() -> None:
+ """Record, once and permanently, that a prompt was queued without a client_id."""
+ global _marker_warning_logged
+ path = headless_marker_path()
+ if os.path.exists(path):
+ return
+ try:
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ open(path, "a").close()
+ except OSError as e:
+ if not _marker_warning_logged:
+ _marker_warning_logged = True
+ logging.warning("Could not write headless marker %s: %s", path, e)
+ return
+ update_feature_flag()
+
+
+# Installation snapshot in Comfy-Desktop's "comfyui-desktop-2-snapshot" format.
+# Local file reads only (no git binary, no network); bad or unreadable data drops
+# the affected field or entry instead of raising.
+
+_SHA = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
+# tomllib is 3.11+ and ComfyUI supports 3.10, so name/version are read from the [project] table text.
+_PROJECT_FIELD = re.compile(r"""^\s*(name|version)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)')""", re.MULTILINE)
+
+
+def _read_text(path: str) -> str | None:
+ try:
+ with open(path, encoding="utf-8", errors="replace") as f:
+ return f.read()
+ except OSError:
+ return None
+
+
+def _pyproject_fields(path: str) -> dict[str, str]:
+ """First name/version in [project]: from its header line up to the next line starting with `[`."""
+ table = []
+ inside = False
+ for line in (_read_text(path) or "").splitlines():
+ if inside and line.startswith("["):
+ break
+ if inside:
+ table.append(line)
+ elif line.strip() == "[project]":
+ inside = True
+ fields = {}
+ for m in _PROJECT_FIELD.finditer("\n".join(table)):
+ fields.setdefault(m.group(1), m.group(2) if m.group(2) is not None else m.group(3))
+ return fields
+
+
+def _git_dir(path: str) -> str | None:
+ dot_git = os.path.join(path, ".git")
+ if os.path.isdir(dot_git):
+ return dot_git
+ m = re.search(r"^gitdir:\s*(.+?)\s*$", _read_text(dot_git) or "", re.MULTILINE)
+ return os.path.normpath(os.path.join(path, m.group(1))) if m else None
+
+
+def _git_head(gitdir: str) -> str | None:
+ head = (_read_text(os.path.join(gitdir, "HEAD")) or "").strip()
+ if not head.startswith("ref:"):
+ return head if _SHA.fullmatch(head) else None
+ ref = head[4:].strip()
+ parts = ref.split("/")
+ if parts[0] != "refs" or ".." in parts:
+ return None
+ # simplification: a linked worktree's refs live under its `commondir`, which is not followed.
+ sha = (_read_text(os.path.join(gitdir, *parts)) or "").strip()
+ if _SHA.fullmatch(sha):
+ return sha
+ for line in (_read_text(os.path.join(gitdir, "packed-refs")) or "").splitlines():
+ fields = line.split()
+ if len(fields) == 2 and fields[1] == ref and _SHA.fullmatch(fields[0]):
+ return fields[0]
+ return None
+
+
+_GIT_ESCAPES = {"\\": "\\", '"': '"', "n": "\n", "t": "\t", "b": "\b"}
+
+
+def _git_config_value(raw: str) -> str | None:
+ """Decode a value the way git does: `"` toggles quoting, backslash escapes, an unquoted ; or # starts a comment.
+ None for an unknown escape or an unterminated quote."""
+ # configparser appends deeper-indented lines to the value; git reads them as separate entries.
+ chars = iter(raw.partition("\n")[0])
+ value, quoted = "", False
+ for c in chars:
+ if c == '"':
+ quoted = not quoted
+ elif c == "\\":
+ c = _GIT_ESCAPES.get(next(chars, ""))
+ if c is None:
+ return None
+ value += c
+ elif c in ";#" and not quoted:
+ break
+ else:
+ value += c
+ return None if quoted else value.strip()
+
+
+_REMOTE_SCHEMES = ("http", "https", "ssh", "git")
+_SCP_LIKE = re.compile(r"[A-Za-z0-9._-]+@([A-Za-z0-9.-]+):[^/\\]\S*")
+
+
+def _strip_userinfo(url: str) -> str | None:
+ """http(s)/ssh/git URLs reduced to scheme/host/port/path, keeping a password-less ssh:// user (ssh://git@host/...);
+ scp-like user@host:path only for a dotted host.
+ None for everything else: remote helpers (`::`), file://, local paths, internal scp-like hosts."""
+ if "::" in url:
+ return None
+ scp = _SCP_LIKE.fullmatch(url)
+ if scp:
+ return url if "." in scp.group(1) else None
+ try:
+ parts = urllib.parse.urlsplit(url)
+ except ValueError:
+ return None
+ # An unencoded / ? or # in the password ends the netloc early and pushes the rest of the userinfo past it.
+ if parts.scheme not in _REMOTE_SCHEMES or not parts.hostname or "@" in parts.path + parts.query + parts.fragment:
+ return None
+ user, _, host = parts.netloc.rpartition("@")
+ if parts.scheme == "ssh" and re.fullmatch(r"[A-Za-z0-9._-]+", user):
+ host = f"{user}@{host}"
+ return urllib.parse.urlunsplit((parts.scheme, host, parts.path, "", ""))
+
+
+def _git_origin_url(gitdir: str) -> str | None:
+ config = configparser.ConfigParser(strict=False, interpolation=None)
+ try:
+ config.read(os.path.join(gitdir, "config"), encoding="utf-8")
+ url = _git_config_value(config.get('remote "origin"', "url", fallback=""))
+ except (configparser.Error, UnicodeDecodeError):
+ return None
+ return _strip_userinfo(url) if url else None
+
+
+# Shipped inside the ComfyUI checkout itself, so not an installed node (Desktop CORE_FILE_NODES).
+_CORE_FILE_NODES = {"websocket_image_save.py"}
+
+
+def _scan_dir(path: str, name: str, enabled: bool) -> dict | None:
+ try:
+ entries = os.listdir(path)
+ except OSError: # unreadable or vanished directory
+ return None
+ if ".tracking" in entries:
+ fields = _pyproject_fields(os.path.join(path, "pyproject.toml"))
+ node = {"id": fields.get("name") or name, "type": "cnr", "dirName": name, "enabled": enabled}
+ if fields.get("version"):
+ node["version"] = fields["version"]
+ return node
+ node = {"id": name, "type": "git", "dirName": name, "enabled": enabled}
+ gitdir = _git_dir(path) if ".git" in entries else None
+ if gitdir is not None:
+ url, commit = _git_origin_url(gitdir), _git_head(gitdir)
+ if url:
+ node["url"] = url
+ if commit:
+ node["commit"] = commit
+ return node
+ # An unmanaged directory is a node only with a pyproject.toml or top-level Python, so stray folders are skipped.
+ if "pyproject.toml" in entries or any(e.endswith(".py") for e in entries):
+ return node
+ return None
+
+
+def scan_custom_nodes(dirs: list[str]) -> list[dict]:
+ """Desktop ScannedNode entries for each custom_nodes dir and the directories in its .disabled/ subfolder (enabled False).
+ A directory named *.disabled is reported disabled and a *.py.disabled file is skipped, as ComfyUI's loader skips both."""
+ nodes = []
+ for base in dirs:
+ for root, enabled in ((base, True), (os.path.join(base, ".disabled"), False)):
+ try:
+ names = sorted(os.listdir(root))
+ except OSError:
+ continue
+ for name in names:
+ path = os.path.join(root, name)
+ if name.startswith(".") or name == "__pycache__":
+ continue
+ if os.path.isdir(path):
+ node = _scan_dir(path, name, enabled and not name.endswith(".disabled"))
+ if node is not None:
+ nodes.append(node)
+ elif enabled and name.endswith(".py") and name != "__init__.py" and name not in _CORE_FILE_NODES:
+ nodes.append({"id": name[:-3], "type": "file", "dirName": name, "enabled": True})
+ return nodes
+
+
+def count_custom_nodes() -> int:
+ return sum(1 for n in scan_custom_nodes(folder_paths.get_folder_paths("custom_nodes")) if n["enabled"])
+
+
+# Pathless stand-in for a local install: not a PEP 440 release, so comfy-builder's parsePins reports it unpinnable, and Desktop restore skips any value containing "://".
+_LOCAL_REFERENCE = "file://local"
+
+
+def _pip_version(dist: importlib.metadata.Distribution) -> str:
+ """The version, or for a PEP 610 direct-URL install the reference Desktop's parsePipFreeze stores
+ (`git+<url>@<commit>` for VCS, `<url>` for an archive) with credentials stripped; local or malformed -> _LOCAL_REFERENCE."""
+ try:
+ raw = dist.read_text("direct_url.json")
+ if raw is None:
+ return dist.version
+ direct = json.loads(raw)
+ url = _strip_userinfo(direct["url"])
+ if url is None or "dir_info" in direct:
+ return _LOCAL_REFERENCE
+ if "vcs_info" in direct:
+ return f"{direct['vcs_info']['vcs']}+{url}@{direct['vcs_info']['commit_id']}"
+ return url
+ except (ValueError, TypeError, KeyError):
+ return _LOCAL_REFERENCE
+
+
+def pip_packages() -> dict[str, str]:
+ """This environment's distributions, like Desktop's `uv pip freeze --python <venv python>`: only sys.path
+ entries under sys.prefix are read, so user site-packages and a venv's base interpreter are left out."""
+ prefix = os.path.join(os.path.normcase(os.path.realpath(sys.prefix)), "")
+ paths = [p for p in sys.path if os.path.join(os.path.normcase(os.path.realpath(p)), "").startswith(prefix)]
+ packages = {}
+ for dist in importlib.metadata.distributions(path=paths):
+ name = dist.metadata.get("Name")
+ if name: # the first distribution of a name is the one imports resolve to
+ packages.setdefault(name, _pip_version(dist))
+ return packages
+
+
+MODEL_EXTENSIONS = set(folder_paths.supported_pt_extensions) | {".gguf", ".onnx"}
+
+
+def list_models() -> list[dict]:
+ """Model files as folder name + /-separated relative path. Identical relative paths under two roots of one folder collapse to one entry."""
+ return [
+ {"directory": folder, "filename": filename.replace(os.sep, "/")}
+ for folder in list(folder_paths.folder_names_and_paths)
+ if folder not in ("custom_nodes", "configs")
+ for filename in folder_paths.get_filename_list(folder)
+ if os.path.splitext(filename)[1].lower() in MODEL_EXTENSIONS
+ ]
+
+
+def build_snapshot() -> dict:
+ now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+ tag = "v" + __version__
+ return {
+ "type": "comfyui-desktop-2-snapshot",
+ "version": 2,
+ "exportedAt": now,
+ "installationName": os.path.basename(os.path.abspath(folder_paths.base_path)),
+ "snapshots": [{
+ "version": 2,
+ "createdAt": now,
+ "trigger": "manual",
+ "label": None,
+ "comfyui": {"ref": tag, "commit": None, "releaseTag": tag, "variant": "comfyui-core", "baseTag": tag},
+ "customNodes": scan_custom_nodes(folder_paths.get_folder_paths("custom_nodes")),
+ "pipPackages": pip_packages(),
+ "pythonVersion": platform.python_version(),
+ }],
+ }
+
+
+def collect() -> tuple[dict, list[dict]]:
+ return build_snapshot(), list_models()
+
+
+# Routes. Registered on the app directly (not PromptServer.routes) so they exist only under /api.
+# The bundle upload is ComfyUI's only outbound request here: explicit user action, never under --offline.
+
+_API_KEY = re.compile(r"comfyui-[0-9a-f]{64}")
+_UPLOAD_TIMEOUT = aiohttp.ClientTimeout(total=60)
+# Builder status -> (our status, error code), after the builder_busy cases in bundle();
+# anything not listed (and transport failures) -> 502 builder_unavailable.
+_BUILDER_ERRORS = {
+ 401: (401, "unauthorized"),
+ 403: (403, "unauthorized"),
+ 413: (413, "too_large"),
+ 429: (429, "too_many_bundles"),
+}
+
+
+def _error(status: int, code: str, message: str | None = None) -> web.Response:
+ body = {"error": code} if message is None else {"error": code, "message": message}
+ return web.json_response(body, status=status)
+
+
+def _credential(request: web.Request) -> tuple[str, str] | web.Response:
+ """The single caller credential header to forward verbatim, or the error response.
+ Only a non-empty Bearer Authorization counts; other schemes (e.g. a proxy's Basic auth) are ignored, never forwarded."""
+ auth = request.headers.get("Authorization", "")
+ bearer = auth.startswith("Bearer ") and bool(auth[7:].strip())
+ key = request.headers.get("X-API-Key")
+ if bearer and key is not None:
+ return _error(400, "multiple_credentials")
+ if key is not None:
+ return ("X-API-Key", key) if _API_KEY.fullmatch(key) else _error(400, "invalid_api_key_format")
+ if bearer:
+ return ("Authorization", auth)
+ return _error(401, "missing_credentials")
+
+
+async def _bundle_fields(request: web.Request) -> dict | web.Response:
+ """Optional workflow/name from the request body (null counts as absent)."""
+ try:
+ body = await request.json()
+ except ValueError:
+ return _error(400, "invalid_body", "body must be a JSON object")
+ if not isinstance(body, dict):
+ return _error(400, "invalid_body", "body must be a JSON object")
+ workflow, name = body.get("workflow"), body.get("name")
+ if workflow is not None and not isinstance(workflow, dict):
+ return _error(400, "invalid_body", "workflow must be an object")
+ if name is not None and not (isinstance(name, str) and len(name) <= 200):
+ return _error(400, "invalid_body", "name must be a string of at most 200 characters")
+ return {k: v for k, v in (("workflow", workflow), ("name", name)) if v is not None}
+
+
+def _created(data) -> tuple | None:
+ """(id, workspaceId, expiresAt) when all three are non-empty strings."""
+ if not isinstance(data, dict):
+ return None
+ fields = (data.get("id"), data.get("workspaceId"), data.get("expiresAt"))
+ return fields if all(isinstance(f, str) and f for f in fields) else None
+
+
+class DeployToCloudRoutes:
+ def __init__(self, prompt_server):
+ self.prompt_server = prompt_server
+ update_feature_flag()
+
+ def add_routes(self, app: web.Application) -> None:
+ app.add_routes([
+ web.get("/api/deploy/summary", self.summary),
+ web.post("/api/deploy/bundle", self.bundle),
+ ])
+
+ async def summary(self, request: web.Request) -> web.Response:
+ if args.offline:
+ return _error(403, "offline")
+ custom_nodes = await asyncio.to_thread(count_custom_nodes)
+ models = await asyncio.to_thread(list_models)
+ return web.json_response({"custom_nodes": custom_nodes, "models": len(models)})
+
+ async def bundle(self, request: web.Request) -> web.Response:
+ if args.offline:
+ return _error(403, "offline")
+ credential = _credential(request)
+ if isinstance(credential, web.Response):
+ return credential
+ fields = await _bundle_fields(request)
+ if isinstance(fields, web.Response):
+ return fields
+
+ snapshot, models = await asyncio.to_thread(collect)
+ payload = {"snapshot": snapshot, "models": models, **fields, "source": "comfyui"}
+ try:
+ async with self.prompt_server.client_session.post(
+ builder_base_url() + "/v1/import-bundles",
+ json=payload,
+ headers=dict([credential]),
+ timeout=_UPLOAD_TIMEOUT,
+ allow_redirects=False,
+ ) as resp:
+ status = resp.status
+ retry_after = resp.headers.get("Retry-After", "")
+ try:
+ data = await resp.json(content_type=None) if status in (201, 400, 429, 503) else None
+ except ValueError: # a non-JSON 400 is still a rejection; a non-JSON 201 has no bundle
+ data = None
+ except (aiohttp.ClientError, asyncio.TimeoutError) as e:
+ logging.warning("Deploy to cloud: builder request failed (%s)", type(e).__name__)
+ return _error(502, "builder_unavailable")
+
+ created = _created(data) if status == 201 else None
+ if created is not None:
+ bundle_id, workspace_id, expires_at = created
+ logging.info("Deploy to cloud: uploaded import bundle %s", bundle_id)
+ query = urllib.parse.urlencode({
+ "step": "import", "bundle": bundle_id, "workspace": workspace_id, "bundle_workspace": workspace_id,
+ })
+ return web.json_response({
+ "url": f"{platform_base_url()}/profile/builds/new?{query}",
+ "bundle_id": bundle_id,
+ "workspace_id": workspace_id,
+ "expires_at": expires_at,
+ })
+
+ logging.warning("Deploy to cloud: builder returned status %d", status)
+ if status == 400:
+ message = data.get("message") if isinstance(data, dict) else None
+ return _error(502, "builder_rejected", message[:500] if isinstance(message, str) else "")
+ builder_code = data.get("error") if isinstance(data, dict) else None
+ # Only IMPORT_BUNDLE_LIMIT is the per-user bundle cap; any other 429 (e.g. IMPORT_BUNDLE_IN_PROGRESS) is transient.
+ if (status == 429 and builder_code != "IMPORT_BUNDLE_LIMIT") or (status == 503 and builder_code == "IMPORT_BUNDLE_BUSY"):
+ headers = {"Retry-After": retry_after} if re.fullmatch(r"[0-9]+", retry_after) else None
+ return web.json_response({"error": "builder_busy"}, status=503, headers=headers)
+ mapped_status, code = _BUILDER_ERRORS.get(status, (502, "builder_unavailable"))
+ return _error(mapped_status, code)
diff --git a/comfy_api/feature_flags.py b/comfy_api/feature_flags.py
index 22c99721e..6bc29ba9c 100644
--- a/comfy_api/feature_flags.py
+++ b/comfy_api/feature_flags.py
@@ -123,8 +123,14 @@ _CORE_FEATURE_FLAGS: dict[str, Any] = {
"assets": not args.disable_assets,
}
-# CLI-provided flags cannot overwrite core flags. Startup code may: main.py sets "assets".
-_cli_flags = {k: v for k, v in _parse_cli_feature_flags().items() if k not in _CORE_FEATURE_FLAGS}
+# Owned by app.deploy_to_cloud, which sets it via set_server_feature.
+_SERVER_SET_FEATURE_FLAGS = ("deploy_to_cloud",)
+
+# CLI-provided flags cannot overwrite core or server-set flags. Startup code may: main.py sets "assets".
+_cli_flags = {
+ k: v for k, v in _parse_cli_feature_flags().items()
+ if k not in _CORE_FEATURE_FLAGS and k not in _SERVER_SET_FEATURE_FLAGS
+}
SERVER_FEATURE_FLAGS: dict[str, Any] = {**_CORE_FEATURE_FLAGS, **_cli_flags}
@@ -180,3 +186,8 @@ def get_server_features() -> dict[str, Any]:
Dictionary of server feature flags
"""
return SERVER_FEATURE_FLAGS.copy()
+
+
+def set_server_feature(name: str, value: Any) -> None:
+ """Set a server feature flag reported to clients and returned by get_server_features."""
+ SERVER_FEATURE_FLAGS[name] = value
diff --git a/main.py b/main.py
index e66d9c0c3..dc484c7eb 100644
--- a/main.py
+++ b/main.py
@@ -595,7 +595,7 @@ def start_comfyui(asyncio_loop=None):
stop_startup("missing_packages", f"The assets system needs packages that could not be imported: {missing}.\n"
f"{get_missing_requirements_message()}\n{WITHOUT_ASSETS}")
asset_manager: AssetManager = default_asset_manager()
- feature_flags.SERVER_FEATURE_FLAGS["assets"] = asset_manager.enabled
+ feature_flags.set_server_feature("assets", asset_manager.enabled)
if not asset_manager.enabled:
cleanup_temp_filesystem()
diff --git a/openapi.yaml b/openapi.yaml
index 45421e2df..684bbd002 100644
--- a/openapi.yaml
+++ b/openapi.yaml
@@ -255,6 +255,29 @@ components:
- base_version
- workflow_json
type: object
+ DeployToCloudError:
+ description: Error body of local ComfyUI's /api/deploy/* routes. Branch on `error`, never on `message`.
+ properties:
+ error:
+ enum:
+ - offline
+ - multiple_credentials
+ - invalid_api_key_format
+ - invalid_body
+ - missing_credentials
+ - unauthorized
+ - too_large
+ - too_many_bundles
+ - builder_rejected
+ - builder_unavailable
+ - builder_busy
+ type: string
+ message:
+ description: Human-readable detail, present for invalid_body and builder_rejected.
+ type: string
+ required:
+ - error
+ type: object
ErrorResponse:
description: Standard error response with a machine-readable code and human-readable message.
properties:
@@ -2646,6 +2669,135 @@ paths:
summary: Get the default workflow
tags:
- workflow
+ /api/deploy/bundle:
+ post:
+ description: On explicit user action, collects this installation's snapshot (comfyui-desktop-2-snapshot) and installed model list, sends them with the optional workflow and name to comfy-builder's POST /v1/import-bundles, and returns the Create a Build wizard link that opens it. The caller's credential is forwarded verbatim and never stored; exactly one of a Bearer Authorization header or an X-API-Key header must be sent. Never available under --offline.
+ operationId: createDeployBundle
+ requestBody:
+ content:
+ application/json:
+ schema:
+ description: A JSON object; `{}` is valid. Null members count as absent.
+ properties:
+ name:
+ description: Optional label for the bundle.
+ maxLength: 200
+ nullable: true
+ type: string
+ workflow:
+ additionalProperties: true
+ description: The workflow open in ComfyUI, sent as is.
+ nullable: true
+ type: object
+ type: object
+ required: true
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ bundle_id:
+ format: uuid
+ type: string
+ expires_at:
+ description: When the bundle stops being readable (24 hours after creation).
+ format: date-time
+ type: string
+ url:
+ description: The Create a Build wizard link that opens the bundle (/profile/builds/new?step=import&bundle=&workspace=&bundle_workspace=).
+ format: uri
+ type: string
+ workspace_id:
+ description: The workspace the bundle belongs to (the credential's).
+ type: string
+ required:
+ - url
+ - bundle_id
+ - workspace_id
+ - expires_at
+ type: object
+ description: Bundle stored on comfy-builder
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: 'Rejected before upload: `multiple_credentials` (both headers sent), `invalid_api_key_format` (X-API-Key is not comfyui- followed by 64 hex characters) or `invalid_body` (not a JSON object, or a bad workflow or name).'
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: '`missing_credentials` (no credential sent) or `unauthorized` (the builder refused the credential).'
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: '`offline` (the server runs with --offline) or `unauthorized` (the builder refused the credential).'
+ "413":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: The bundle exceeds the builder's size cap (`too_large`).
+ "429":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: The user already holds the builder's limit of unexpired bundles in this workspace (`too_many_bundles`); clears as older bundles expire.
+ "502":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: '`builder_rejected` (the builder refused the bundle as invalid; `message` carries its reason, at most 500 characters) or `builder_unavailable` (the builder could not be reached or answered unexpectedly).'
+ "503":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: The builder is busy (`builder_busy`); retry after Retry-After seconds when present.
+ headers:
+ Retry-After:
+ description: Seconds to wait, when the builder sent one.
+ schema:
+ type: integer
+ security:
+ - BearerAuth: []
+ - ApiKeyAuth: []
+ summary: Upload this installation to Cloud as an import bundle
+ /api/deploy/summary:
+ get:
+ description: Counts the custom nodes and model files this local installation would send in an import bundle, so the UI can describe the upload before the user confirms it. Local reads only; makes no network request.
+ operationId: getDeploySummary
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ custom_nodes:
+ description: Custom node packages found in the custom_nodes folders
+ type: integer
+ models:
+ description: Model files found across the model folders
+ type: integer
+ required:
+ - custom_nodes
+ - models
+ type: object
+ description: Counts of what the bundle would include
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeployToCloudError'
+ description: The server runs with --offline (error `offline`)
+ security: []
+ summary: Count what a Deploy to Cloud bundle would carry
/api/embeddings:
get:
description: Returns the list of text-encoder embeddings available on disk.
@@ -2771,6 +2923,11 @@ paths:
schema:
additionalProperties: true
properties:
+ deploy_to_cloud:
+ description: 'Local ComfyUI only: whether the UI should offer Deploy to Cloud. True when the server is not --offline and this installation has ever had a prompt queued by a non-browser client (a persistent marker in the user directory). A discovery hint only: it grants nothing, and the /api/deploy/* routes do not check it. Not settable with --feature-flag.'
+ type: boolean
+ x-runtime:
+ - local
free_tier_balance:
description: Free-tier job allowance for an authenticated non-paid (FREE-tier) user in the rollout. Absent for paid users and unauthenticated requests. Synthesized from config before a grant row exists so a brand-new user still sees their full allowance.
properties:
diff --git a/server.py b/server.py
index 718b67872..3eb75d925 100644
--- a/server.py
+++ b/server.py
@@ -64,6 +64,7 @@ from app.user_manager import UserManager
from app.model_manager import ModelFileManager
from app.custom_node_manager import CustomNodeManager
from app.subgraph_manager import SubgraphManager
+from app import deploy_to_cloud
from app.node_replace_manager import NodeReplaceManager
from typing import TYPE_CHECKING, Optional, Union
from api_server.routes.internal.internal_routes import InternalRoutes
@@ -267,6 +268,7 @@ class PromptServer():
self.subgraph_manager = SubgraphManager()
self.node_replace_manager = NodeReplaceManager()
self.internal_routes = InternalRoutes(self)
+ self.deploy_to_cloud_routes = deploy_to_cloud.DeployToCloudRoutes(self)
self.supports = ["custom_nodes_from_web"]
self.prompt_queue = execution.PromptQueue(self)
self.loop = loop
@@ -1226,6 +1228,9 @@ class PromptServer():
sensitive[sensitive_val] = extra_data.pop(sensitive_val)
extra_data["create_time"] = int(time.time() * 1000) # timestamp in milliseconds
self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute, sensitive))
+ # The frontend can queue with an empty client_id before its socket id arrives.
+ if not json_data.get("client_id") and extra_data.get("comfy_usage_source") != "comfyui-frontend":
+ deploy_to_cloud.mark_used_headlessly()
response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
return web.json_response(response)
else:
@@ -1341,6 +1346,8 @@ class PromptServer():
api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
self.app.add_routes(api_routes)
self.app.add_routes(self.routes)
+ # Registered after the /api duplication above, so these exist only under /api.
+ self.deploy_to_cloud_routes.add_routes(self.app)
# Add routes from web extensions.
for name, dir in nodes.EXTENSION_WEB_DIRS.items():
diff --git a/tests-unit/deploy_to_cloud_test/test_headless.py b/tests-unit/deploy_to_cloud_test/test_headless.py
new file mode 100644
index 000000000..944528b9f
--- /dev/null
+++ b/tests-unit/deploy_to_cloud_test/test_headless.py
@@ -0,0 +1,172 @@
+"""Tests for the headless-use marker and the deploy_to_cloud feature flag the server reports"""
+
+import os
+import subprocess
+import sys
+from unittest.mock import MagicMock
+
+import pytest
+import pytest_asyncio
+import torch
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer
+
+from comfy.cli_args import args
+
+if not torch.cuda.is_available():
+ args.cpu = True
+
+import execution # noqa: E402
+import folder_paths # noqa: E402
+import server # noqa: E402
+from app import deploy_to_cloud # noqa: E402
+
+
+def user_dir(tmp_path, monkeypatch):
+ path = tmp_path / "user"
+ monkeypatch.setattr(folder_paths, "user_directory", str(path))
+ return path
+
+
+def marker(user_dir):
+ return user_dir / deploy_to_cloud.HEADLESS_MARKER
+
+
+def test_mark_creates_the_marker_in_the_user_directory(user_dir):
+ deploy_to_cloud.mark_used_headlessly()
+ assert marker(user_dir).is_file()
+ assert deploy_to_cloud.headless_marker_path() == str(marker(user_dir))
+
+
+def test_mark_is_idempotent(user_dir):
+ deploy_to_cloud.mark_used_headlessly()
+ deploy_to_cloud.mark_used_headlessly()
+ assert os.listdir(user_dir) == [deploy_to_cloud.HEADLESS_MARKER]
+
+
+def test_mark_swallows_os_error_and_warns_once(user_dir, monkeypatch, caplog):
+ def fail(*a, **kw):
+ raise PermissionError("read-only")
+ monkeypatch.setattr("builtins.open", fail)
+ monkeypatch.setattr(deploy_to_cloud, "_marker_warning_logged", False)
+ deploy_to_cloud.mark_used_headlessly()
+ deploy_to_cloud.mark_used_headlessly()
+ assert not marker(user_dir).exists()
+ assert [r.getMessage() for r in caplog.records].count(f"Could not write headless marker {marker(user_dir)}: read-only") == 1
+
+
+def test_cli_feature_flag_cannot_claim_server_reserved_flags(tmp_path):
+ code = (
+ "import sys, comfy.options; comfy.options.enable_args_parsing(); "
+ "from comfy_api.feature_flags import get_server_features; f = get_server_features(); "
+ "print('deploy_to_cloud' in f, f.get('show_signin_button'), 'app.deploy_to_cloud' in sys.modules)"
+ )
+ out = subprocess.run(
+ [sys.executable, "-c", code, "--base-directory", str(tmp_path),
+ "--feature-flag", "deploy_to_cloud=true", "--feature-flag", "show_signin_button=true"],
+ capture_output=True, text=True, check=True,
+ )
+ assert out.stdout.split()[-3:] == ["False", "True", "False"]
+
+
+def validation(monkeypatch):
+ result = {"valid": True}
+
+ async def validate_prompt(prompt_id, prompt, partial_execution_targets):
+ if result["valid"]:
+ return (True, None, ["1"], {})
+ return (False, {"type": "invalid", "message": "bad"}, [], {})
+ monkeypatch.setattr(execution, "validate_prompt", validate_prompt)
+ return result
+
+
+@pytest_asyncio.fixture
+async def client(validation, user_dir):
+ prompt_server = server.PromptServer(None, MagicMock(enabled=False))
+ prompt_server.prompt_queue = MagicMock()
+ prompt_server.prompt_queue.get_tasks_remaining.return_value = 0
+ for route in prompt_server.routes:
+ if isinstance(route, web.RouteDef) and (route.method, route.path) in (("POST", "/prompt"), ("GET", "/features"), ("GET", "/ws")):
+ prompt_server.app.router.add_route(route.method, "/api" + route.path, route.handler)
+ async with TestClient(TestServer(prompt_server.app)) as c:
+ c.prompt_queue = prompt_server.prompt_queue
+ yield c
+
+
+async def features_endpoint(client):
+ resp = await client.get("/api/features")
+ assert resp.status == 200
+ return await resp.json()
+
+
+async def features_handshake(client):
+ async with client.ws_connect("/api/ws") as ws:
+ await ws.send_json({"type": "feature_flags", "data": {}})
+ while (msg := await ws.receive_json(timeout=5))["type"] != "feature_flags":
+ pass
+ return msg["data"]
+
+
+READERS = pytest.mark.parametrize("read_features", [features_endpoint, features_handshake])
+
+
+@READERS
+async def test_deploy_to_cloud_flag_flips_after_marking(client, user_dir, read_features):
+ assert (await read_features(client))["deploy_to_cloud"] is False
+ deploy_to_cloud.mark_used_headlessly()
+ assert (await read_features(client))["deploy_to_cloud"] is True
+ assert "used_headlessly" not in await read_features(client)
+
+
+@READERS
+async def test_offline_hides_deploy_to_cloud_but_not_shared_flags(client, user_dir, monkeypatch, read_features):
+ monkeypatch.setattr(args, "offline", True)
+ deploy_to_cloud.mark_used_headlessly()
+ features = await read_features(client)
+ assert features["deploy_to_cloud"] is False
+ assert features["supports_preview_metadata"] is True
+
+
+PROMPT = {"1": {"class_type": "PrimitiveInt", "inputs": {"value": 1}}}
+
+
[email protected]("body,headless", [
+ ({}, True),
+ ({"client_id": ""}, True),
+ ({"client_id": None}, True),
+ ({"client_id": "abc"}, False),
+ ({"client_id": "", "extra_data": {"comfy_usage_source": "comfyui-frontend"}}, False),
+ ({"extra_data": {"comfy_usage_source": "comfyui-frontend"}}, False),
+ ({"client_id": "", "extra_data": {"comfy_usage_source": "my-script"}}, True),
+])
+async def test_post_prompt_marks_only_without_client_id(client, user_dir, body, headless):
+ resp = await client.post("/api/prompt", json={"prompt": PROMPT, **body})
+ assert resp.status == 200
+ client.prompt_queue.put.assert_called_once()
+ assert marker(user_dir).exists() is headless
+
+
+async def test_invalid_prompt_does_not_mark(client, user_dir, validation):
+ validation["valid"] = False
+ resp = await client.post("/api/prompt", json={"prompt": PROMPT})
+ assert resp.status == 400
+ client.prompt_queue.put.assert_not_called()
+ assert not marker(user_dir).exists()
+
+
+async def test_marker_write_failure_still_queues_prompt(client, user_dir, monkeypatch):
+ def fail(*a, **kw):
+ raise OSError("disk full")
+ monkeypatch.setattr(deploy_to_cloud.os, "makedirs", fail)
+ resp = await client.post("/api/prompt", json={"prompt": PROMPT})
+ assert resp.status == 200
+ assert "prompt_id" in await resp.json()
+ client.prompt_queue.put.assert_called_once()
+ assert not marker(user_dir).exists()
diff --git a/tests-unit/deploy_to_cloud_test/test_routes.py b/tests-unit/deploy_to_cloud_test/test_routes.py
new file mode 100644
index 000000000..d16f7bfd4
--- /dev/null
+++ b/tests-unit/deploy_to_cloud_test/test_routes.py
@@ -0,0 +1,377 @@
+"""Tests for GET /api/deploy/summary and POST /api/deploy/bundle, against a real fake comfy-builder server"""
+
+import asyncio
+import json
+from unittest.mock import MagicMock
+
+import pytest
+import pytest_asyncio
+import torch
+from aiohttp import web
+from aiohttp.test_utils import TestClient, TestServer, unused_port
+
+from comfy.cli_args import args
+
+if not torch.cuda.is_available():
+ args.cpu = True
+
+import folder_paths # noqa: E402
+import server # noqa: E402
+from app import deploy_to_cloud # noqa: E402
+from app import comfy_api_env # noqa: E402
+
+BEARER = "Bearer eyJhbGciOiJSUzI1NiJ9.test.sig"
+API_KEY = "comfyui-" + "0123456789abcdef" * 4
+SHA = "a" * 40
+CREATED = {"id": "0b9a3f4e-1c2d-4e5f-8a9b-0c1d2e3f4a5b", "workspaceId": "ws 1/a", "expiresAt": "2026-10-17T12:00:00Z"}
+WORKFLOW = {"last_node_id": 1, "nodes": [{"id": 1, "type": "KSampler"}]}
+
+# Every `error` value the routes can return: error_of rejects any other, and
+# test_expected_error_codes_are_all_exercised requires each one to be asserted by some test.
+EXPECTED_ERROR_CODES = {
+ "offline",
+ "missing_credentials",
+ "multiple_credentials",
+ "invalid_api_key_format",
+ "invalid_body",
+ "unauthorized",
+ "too_large",
+ "too_many_bundles",
+ "builder_busy",
+ "builder_rejected",
+ "builder_unavailable",
+}
+
+
+def write(path, text=""):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+
+def installation(tmp_path, monkeypatch):
+ """A realistic local install: cnr, git and file custom nodes, a disabled pack, and models in two folders."""
+ base = tmp_path / "ComfyUI"
+ nodes = base / "custom_nodes"
+ write(nodes / "ComfyUI-KJNodes" / ".tracking")
+ write(nodes / "ComfyUI-KJNodes" / "pyproject.toml", '[project]\nname = "comfyui-kjnodes"\nversion = "1.1.2"\n')
+ gitdir = nodes / "ComfyUI-Impact-Pack" / ".git"
+ write(gitdir / "HEAD", "ref: refs/heads/main\n")
+ write(gitdir / "refs" / "heads" / "main", SHA + "\n")
+ write(gitdir / "config", '[remote "origin"]\n\turl = https://user:[email protected]/ltdrdata/ComfyUI-Impact-Pack.git\n')
+ write(nodes / "my_local_nodes" / "__init__.py")
+ write(nodes / "simple_node.py")
+ write(nodes / ".disabled" / "old_pack" / "__init__.py")
+ models = base / "models"
+ for rel in ("checkpoints/sd_xl_base_1.0.safetensors", "checkpoints/flux/flux1-dev-Q4.gguf",
+ "checkpoints/readme.txt", "loras/detail.safetensors"):
+ write(models / rel)
+ monkeypatch.setattr(folder_paths, "base_path", str(base))
+ monkeypatch.setattr(folder_paths, "filename_list_cache", {})
+ monkeypatch.setattr(folder_paths, "folder_names_and_paths", {
+ "custom_nodes": ([str(nodes)], set()),
+ "configs": ([str(models / "configs")], {".yaml"}),
+ # .gguf is registered for checkpoints by GGUF loader packs in real installs
+ "checkpoints": ([str(models / "checkpoints")], set(folder_paths.supported_pt_extensions) | {".gguf"}),
+ "loras": ([str(models / "loras")], set(folder_paths.supported_pt_extensions)),
+ })
+ return base
+
+
+def builder_state():
+ return {"status": 201, "body": CREATED, "headers": {}, "delay": 0, "requests": [], "redirect_hits": 0}
+
+
+@pytest_asyncio.fixture
+async def builder(builder_state, monkeypatch):
+ """Fake comfy-builder on a real localhost socket, recording what it receives."""
+ async def create(request):
+ builder_state["requests"].append({"headers": dict(request.headers), "body": await request.json()})
+ await asyncio.sleep(builder_state["delay"])
+ if builder_state["status"] == 302:
+ raise web.HTTPFound("/redirect-target")
+ headers = builder_state["headers"]
+ if isinstance(builder_state["body"], bytes):
+ return web.Response(body=builder_state["body"], status=builder_state["status"], content_type="text/html", headers=headers)
+ return web.json_response(builder_state["body"], status=builder_state["status"], headers=headers)
+
+ async def redirect_target(request):
+ builder_state["redirect_hits"] += 1
+ return web.json_response(CREATED, status=201)
+
+ app = web.Application()
+ app.router.add_post("/builder/v1/import-bundles", create)
+ app.router.add_route("*", "/redirect-target", redirect_target)
+ async with TestServer(app) as srv:
+ monkeypatch.setattr(deploy_to_cloud, "builder_base_url", lambda: str(srv.make_url("/builder")))
+ yield builder_state
+
+
+@pytest_asyncio.fixture
+async def client(monkeypatch):
+ monkeypatch.setattr(args, "offline", False)
+ monkeypatch.setattr(args, "comfy_api_base", "https://api.comfy.org")
+ prompt_server = server.PromptServer(None, MagicMock(enabled=False))
+ prompt_server.add_routes()
+ await prompt_server.setup()
+ try:
+ async with TestClient(TestServer(prompt_server.app)) as c:
+ yield c
+ finally:
+ await prompt_server.client_session.close()
+
+
+async def error_of(resp, status):
+ assert resp.status == status
+ code = (await resp.json())["error"]
+ assert code in EXPECTED_ERROR_CODES
+ return code
+
+
+# --- summary ---
+
+async def test_summary_returns_only_counts(client, installation, monkeypatch):
+ def no_pip():
+ raise AssertionError("summary must not collect pip packages")
+ monkeypatch.setattr(deploy_to_cloud, "pip_packages", no_pip)
+ resp = await client.get("/api/deploy/summary")
+ assert resp.status == 200
+ body = await resp.json()
+ assert set(body) == {"custom_nodes", "models"}
+ assert body == {"custom_nodes": 4, "models": 3}
+
+
[email protected]("method,path", [
+ ("GET", "/deploy/summary"),
+ ("GET", "/api/api/deploy/summary"),
+ ("POST", "/deploy/bundle"),
+ ("POST", "/api/api/deploy/bundle"),
+])
+async def test_no_route_aliases(client, method, path):
+ resp = await client.request(method, path)
+ assert resp.status in (404, 405)
+
+
+async def test_summary_offline(client, monkeypatch):
+ monkeypatch.setattr(args, "offline", True)
+ assert await error_of(await client.get("/api/deploy/summary"), 403) == "offline"
+
+
+# --- bundle: success ---
+
+async def test_bundle_success_with_bearer(client, builder, installation, tmp_path):
+ resp = await client.post("/api/deploy/bundle", json={"workflow": WORKFLOW, "name": "My install"},
+ headers={"Authorization": BEARER})
+ assert resp.status == 200
+ assert await resp.json() == {
+ "url": "https://platform.comfy.org/profile/builds/new?step=import"
+ "&bundle=0b9a3f4e-1c2d-4e5f-8a9b-0c1d2e3f4a5b&workspace=ws+1%2Fa&bundle_workspace=ws+1%2Fa",
+ "bundle_id": CREATED["id"],
+ "workspace_id": CREATED["workspaceId"],
+ "expires_at": CREATED["expiresAt"],
+ }
+ [received] = builder["requests"]
+ (tmp_path / "bundle-request.json").write_text(json.dumps(received["body"], indent=2))
+ assert received["headers"]["Authorization"] == BEARER
+ assert "X-API-Key" not in received["headers"]
+ assert received["headers"]["Content-Type"].startswith("application/json")
+ body = received["body"]
+ assert body["source"] == "comfyui"
+ assert body["workflow"] == WORKFLOW
+ assert body["name"] == "My install"
+ assert body["snapshot"]["type"] == "comfyui-desktop-2-snapshot"
+ assert body["snapshot"]["installationName"] == "ComfyUI"
+ assert {(n["type"], n["dirName"]) for n in body["snapshot"]["snapshots"][0]["customNodes"]} == {
+ ("cnr", "ComfyUI-KJNodes"), ("git", "ComfyUI-Impact-Pack"), ("git", "my_local_nodes"),
+ ("file", "simple_node.py"), ("git", "old_pack"),
+ }
+ assert body["models"] == [
+ {"directory": "checkpoints", "filename": "flux/flux1-dev-Q4.gguf"},
+ {"directory": "checkpoints", "filename": "sd_xl_base_1.0.safetensors"},
+ {"directory": "loras", "filename": "detail.safetensors"},
+ ]
+
+
+async def test_bundle_success_with_api_key_and_no_optional_fields(client, builder, installation):
+ resp = await client.post("/api/deploy/bundle", json={"workflow": None}, headers={"X-API-Key": API_KEY})
+ assert resp.status == 200
+ [received] = builder["requests"]
+ assert received["headers"]["X-API-Key"] == API_KEY
+ assert "Authorization" not in received["headers"]
+ assert set(received["body"]) == {"snapshot", "models", "source"}
+
+
+async def test_proxy_basic_auth_is_ignored_and_api_key_forwarded_alone(client, builder, installation):
+ resp = await client.post("/api/deploy/bundle", json={},
+ headers={"Authorization": "Basic dXNlcjpwYXNz", "X-API-Key": API_KEY})
+ assert resp.status == 200
+ [received] = builder["requests"]
+ assert received["headers"]["X-API-Key"] == API_KEY
+ assert "Authorization" not in received["headers"]
+
+
+async def test_staging_tier_returns_staging_platform_url(client, builder, installation, monkeypatch):
+ monkeypatch.setattr(args, "comfy_api_base", "https://stagingapi.comfy.org")
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert (await resp.json())["url"].startswith("https://stagingplatform.comfy.org/profile/builds/new?")
+
+
+# --- bundle: rejected locally, before collection or network ---
+
+LOCAL_ERRORS = [
+ ({}, {}, 401, "missing_credentials"),
+ ({"Authorization": "Basic abc"}, {}, 401, "missing_credentials"),
+ ({"Authorization": BEARER, "X-API-Key": API_KEY}, {}, 400, "multiple_credentials"),
+ ({"X-API-Key": "comfyui-short"}, {}, 400, "invalid_api_key_format"),
+ ({"X-API-Key": "sk-" + "0" * 64}, {}, 400, "invalid_api_key_format"),
+ ({"Authorization": "Basic dXNlcjpwYXNz", "X-API-Key": "comfyui-short"}, {}, 400, "invalid_api_key_format"),
+ ({"Authorization": BEARER}, [1, 2], 400, "invalid_body"),
+ ({"Authorization": BEARER}, "not json", 400, "invalid_body"),
+ ({"Authorization": BEARER}, {"workflow": [1]}, 400, "invalid_body"),
+ ({"Authorization": BEARER}, {"name": "x" * 201}, 400, "invalid_body"),
+ ({"Authorization": BEARER}, {"name": 5}, 400, "invalid_body"),
+]
+
+
[email protected]("headers,body,status,code", LOCAL_ERRORS)
+async def test_bundle_local_rejections_skip_collection_and_network(client, builder, monkeypatch, headers, body, status, code):
+ def no_collect():
+ raise AssertionError("collect must not run")
+ monkeypatch.setattr(deploy_to_cloud, "collect", no_collect)
+ kwargs = {"data": body} if isinstance(body, str) else {"json": body}
+ resp = await client.post("/api/deploy/bundle", headers=headers, **kwargs)
+ assert await error_of(resp, status) == code
+ assert builder["requests"] == []
+
+
+async def test_bundle_offline_makes_no_request(client, builder, monkeypatch):
+ monkeypatch.setattr(args, "offline", True)
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert await error_of(resp, 403) == "offline"
+ assert builder["requests"] == []
+
+
+async def test_name_of_200_chars_is_accepted(client, builder, installation):
+ resp = await client.post("/api/deploy/bundle", json={"name": "é" * 200}, headers={"Authorization": BEARER})
+ assert resp.status == 200
+
+
+# --- bundle: builder outcomes ---
+
+BUILDER_ERRORS = [
+ (401, {"error": "UNAUTHORIZED", "message": "no"}, 401, "unauthorized"),
+ (403, {"error": "FORBIDDEN", "message": "no"}, 403, "unauthorized"),
+ (413, {"error": "IMPORT_BUNDLE_TOO_LARGE", "message": "big"}, 413, "too_large"),
+ (429, {"error": "IMPORT_BUNDLE_LIMIT", "message": "20"}, 429, "too_many_bundles"),
+ (429, {"error": "IMPORT_BUNDLE_IN_PROGRESS", "message": "wait"}, 503, "builder_busy"),
+ (429, b"<html>429 Too Many Requests</html>", 503, "builder_busy"),
+ (503, {"error": "IMPORT_BUNDLE_BUSY", "message": "busy"}, 503, "builder_busy"),
+ (503, {"error": "IMPORT_BUNDLE_STORAGE_UNAVAILABLE", "message": "down"}, 502, "builder_unavailable"),
+ (503, b"<html>503 Service Unavailable</html>", 502, "builder_unavailable"),
+ (408, {"error": "IMPORT_BUNDLE_TIMEOUT", "message": "slow"}, 502, "builder_unavailable"),
+ (415, {"error": "UNSUPPORTED_MEDIA_TYPE", "message": "json"}, 502, "builder_unavailable"),
+ (400, {"error": "INVALID_IMPORT_BUNDLE", "message": "bad"}, 502, "builder_rejected"),
+ (400, b"<html>400 Bad Request</html>", 502, "builder_rejected"),
+ (404, {"error": "NOT_FOUND"}, 502, "builder_unavailable"),
+ (405, {"error": "METHOD_NOT_ALLOWED"}, 502, "builder_unavailable"),
+ (500, {"error": "INTERNAL"}, 502, "builder_unavailable"),
+ (302, None, 502, "builder_unavailable"),
+ (201, {"id": "x"}, 502, "builder_unavailable"), # 201 without a usable id/workspace never yields a link
+ (201, "not an object", 502, "builder_unavailable"),
+ (201, b"<html>created</html>", 502, "builder_unavailable"),
+]
+
+
[email protected]("builder_status,builder_body,status,code", BUILDER_ERRORS)
+async def test_bundle_builder_outcomes(client, builder, installation, builder_status, builder_body, status, code):
+ builder["status"], builder["body"] = builder_status, builder_body
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert await error_of(resp, status) == code
+ assert len(builder["requests"]) == 1
+ assert builder["redirect_hits"] == 0
+
+
[email protected]("builder_status,builder_error,retry_after,expected", [
+ (429, "IMPORT_BUNDLE_IN_PROGRESS", "5", "5"),
+ (503, "IMPORT_BUNDLE_BUSY", "5", "5"),
+ (429, "IMPORT_BUNDLE_IN_PROGRESS", None, None),
+ (503, "IMPORT_BUNDLE_BUSY", "Wed, 21 Oct 2026 07:28:00 GMT", None),
+ (429, "IMPORT_BUNDLE_IN_PROGRESS", "-1", None),
+ (429, "IMPORT_BUNDLE_LIMIT", "5", None),
+ (503, "IMPORT_BUNDLE_STORAGE_UNAVAILABLE", "5", None),
+])
+async def test_retry_after_passes_through_only_digits_on_builder_busy(client, builder, installation, builder_status, builder_error, retry_after, expected):
+ builder["status"], builder["body"] = builder_status, {"error": builder_error}
+ builder["headers"] = {} if retry_after is None else {"Retry-After": retry_after}
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert resp.headers.get("Retry-After") == expected
+
+
[email protected]("builder_body,message", [
+ ({"error": "INVALID_IMPORT_BUNDLE", "message": "m" * 600, "extra": 1}, "m" * 500),
+ (b"<html>400 Bad Request</html>", ""),
+])
+async def test_builder_rejection_forwards_only_a_truncated_message(client, builder, installation, builder_body, message):
+ builder["status"], builder["body"] = 400, builder_body
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert resp.status == 502
+ assert await resp.json() == {"error": "builder_rejected", "message": message}
+
+
+async def test_builder_connection_refused(client, installation, monkeypatch):
+ monkeypatch.setattr(deploy_to_cloud, "builder_base_url", lambda: f"http://127.0.0.1:{unused_port()}/builder")
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert await error_of(resp, 502) == "builder_unavailable"
+
+
+async def test_builder_timeout(client, builder, installation, monkeypatch):
+ monkeypatch.setattr(deploy_to_cloud, "_UPLOAD_TIMEOUT", deploy_to_cloud.aiohttp.ClientTimeout(total=0.2))
+ builder["delay"] = 2
+ resp = await client.post("/api/deploy/bundle", json={}, headers={"Authorization": BEARER})
+ assert await error_of(resp, 502) == "builder_unavailable"
+
+
+async def test_credentials_and_payload_never_logged(client, builder, installation, caplog):
+ caplog.set_level("DEBUG")
+ await client.post("/api/deploy/bundle", json={"name": "secret-name"}, headers={"Authorization": BEARER})
+ builder["status"] = 500
+ await client.post("/api/deploy/bundle", json={}, headers={"X-API-Key": API_KEY})
+ assert CREATED["id"] in caplog.text
+ for secret in (BEARER.split()[1], API_KEY, "secret-name", "ComfyUI-KJNodes"):
+ assert secret not in caplog.text
+
+
+def test_expected_error_codes_are_all_exercised():
+ asserted = {"offline"} | {c for *_, c in LOCAL_ERRORS} | {c for *_, c in BUILDER_ERRORS}
+ assert asserted == EXPECTED_ERROR_CODES
+
+
+# --- comfy_api_env tier mapping ---
+
[email protected]("base,builder_url,platform_url", [
+ ("https://api.comfy.org", "https://platformapi.comfy.org/builder", "https://platform.comfy.org"),
+ ("", "https://platformapi.comfy.org/builder", "https://platform.comfy.org"),
+ ("https://stagingapi.comfy.org", "https://stagingplatformapi.comfy.org/builder", "https://stagingplatform.comfy.org"),
+ ("https://pr-7.testenvs.comfy.org", "https://stagingplatformapi.comfy.org/builder", "https://stagingplatform.comfy.org"),
+])
+def test_builder_and_platform_urls_follow_api_tier(monkeypatch, base, builder_url, platform_url):
+ monkeypatch.setattr(args, "comfy_api_base", base)
+ assert comfy_api_env.builder_base_url() == builder_url
+ assert comfy_api_env.platform_base_url() == platform_url
diff --git a/tests-unit/deploy_to_cloud_test/test_snapshot.py b/tests-unit/deploy_to_cloud_test/test_snapshot.py
new file mode 100644
index 000000000..fec5cda61
--- /dev/null
+++ b/tests-unit/deploy_to_cloud_test/test_snapshot.py
@@ -0,0 +1,307 @@
+"""Tests for the local installation snapshot + models collector used by deploy to cloud"""
+
+import json
+import platform
+
+import pytest
+
+import folder_paths
+from app import deploy_to_cloud
+from comfyui_version import __version__
+
+SHA_A = "a" * 40
+SHA_B = "b" * 40
+SHA_C = "c" * 40
+SHA_D = "d" * 40
+SHA_E = "e" * 40
+NODE_KEYS = {"id", "type", "dirName", "enabled", "version", "commit", "url"}
+
+
+def write(path, text=""):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+
+
+def git_repo(gitdir, head, origin=None):
+ write(gitdir / "HEAD", head + "\n")
+ if origin:
+ write(gitdir / "config", f'[core]\n\tbare = false\n[remote "origin"]\n\turl = {origin}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n')
+
+
+def custom_nodes(tmp_path):
+ root = tmp_path / "custom_nodes"
+ cnr = root / "cnr_pack"
+ write(cnr / ".tracking")
+ write(cnr / "pyproject.toml", '[project]\nname = "comfyui-cnr-pack"\nversion = "1.2.3"\n')
+
+ git_repo(root / "loose_ref" / ".git", "ref: refs/heads/main")
+ write(root / "loose_ref" / ".git" / "refs" / "heads" / "main", SHA_A + "\n")
+
+ git_repo(root / "packed_ref" / ".git", "ref: refs/heads/main")
+ write(root / "packed_ref" / ".git" / "packed-refs", f"# pack-refs with: peeled fully-peeled sorted\n{SHA_C} refs/heads/dev\n{SHA_B} refs/heads/main\n^{SHA_C}\n")
+
+ git_repo(root / "detached" / ".git", SHA_C)
+
+ git_repo(tmp_path / "modules" / "linked", SHA_D)
+ write(root / "gitdir_file" / ".git", "gitdir: ../../modules/linked\n")
+
+ git_repo(root / "with_origin" / ".git", SHA_E, origin="https://github.com/a/b.git")
+
+ write(root / "plain_dir" / "nodes.py")
+ write(root / "toml_only" / "pyproject.toml", '[project]\nname = "x"\n')
+ (root / "stray_dir").mkdir()
+ write(root / "stray_dir" / "readme.txt")
+ write(root / "bad_gitfile" / ".git", "not a gitdir pointer\n")
+ write(root / "foo.py")
+ write(root / "websocket_image_save.py")
+ write(root / "__init__.py")
+ write(root / "__pycache__" / "x.pyc")
+ write(root / "notes.txt")
+ git_repo(root / "corrupt_head" / ".git", "not a sha")
+ write(root / "renamed_off.disabled" / "__init__.py")
+ write(root / "bar.py.disabled")
+ write(root / ".disabled" / "old_pack" / "__init__.py")
+ write(root / ".disabled" / "foo_off.py")
+ (root / ".disabled" / "stray_off").mkdir()
+ return root
+
+
+def test_scan_custom_nodes_identifies_every_kind(custom_nodes):
+ assert deploy_to_cloud.scan_custom_nodes([str(custom_nodes)]) == [
+ {"id": "comfyui-cnr-pack", "type": "cnr", "dirName": "cnr_pack", "enabled": True, "version": "1.2.3"},
+ {"id": "corrupt_head", "type": "git", "dirName": "corrupt_head", "enabled": True},
+ {"id": "detached", "type": "git", "dirName": "detached", "enabled": True, "commit": SHA_C},
+ {"id": "foo", "type": "file", "dirName": "foo.py", "enabled": True},
+ {"id": "gitdir_file", "type": "git", "dirName": "gitdir_file", "enabled": True, "commit": SHA_D},
+ {"id": "loose_ref", "type": "git", "dirName": "loose_ref", "enabled": True, "commit": SHA_A},
+ {"id": "packed_ref", "type": "git", "dirName": "packed_ref", "enabled": True, "commit": SHA_B},
+ {"id": "plain_dir", "type": "git", "dirName": "plain_dir", "enabled": True},
+ {"id": "renamed_off.disabled", "type": "git", "dirName": "renamed_off.disabled", "enabled": False},
+ {"id": "toml_only", "type": "git", "dirName": "toml_only", "enabled": True},
+ {"id": "with_origin", "type": "git", "dirName": "with_origin", "enabled": True, "url": "https://github.com/a/b.git", "commit": SHA_E},
+ {"id": "old_pack", "type": "git", "dirName": "old_pack", "enabled": False},
+ ]
+
+
+def test_scan_skips_what_desktop_skips(custom_nodes):
+ names = {n["dirName"] for n in deploy_to_cloud.scan_custom_nodes([str(custom_nodes)])}
+ # core file node, stray dir without pyproject/Python, .git file without gitdir:, .disabled/ files and stray dirs, *.py.disabled
+ assert not names & {"websocket_image_save.py", "stray_dir", "bad_gitfile", "foo_off.py", "stray_off", "__init__.py", "notes.txt", "bar.py.disabled"}
+
+
+def test_scan_skips_missing_dirs(tmp_path):
+ assert deploy_to_cloud.scan_custom_nodes([str(tmp_path / "missing")]) == []
+
+
+def test_scan_skips_unreadable_dir(custom_nodes, monkeypatch):
+ real_listdir = deploy_to_cloud.os.listdir
+
+ def listdir(path):
+ if str(path).endswith("plain_dir"):
+ raise PermissionError(path)
+ return real_listdir(path)
+
+ monkeypatch.setattr(deploy_to_cloud.os, "listdir", listdir)
+ names = [n["dirName"] for n in deploy_to_cloud.scan_custom_nodes([str(custom_nodes)])]
+ assert "plain_dir" not in names
+ assert "loose_ref" in names
+
+
+def test_count_custom_nodes_counts_enabled_only(custom_nodes, monkeypatch):
+ monkeypatch.setitem(folder_paths.folder_names_and_paths, "custom_nodes", ([str(custom_nodes)], set()))
+ assert deploy_to_cloud.count_custom_nodes() == 10
+
+
[email protected]("pyproject, expected", [
+ ('[project]\nname = "dq"\nversion = "1.0"\n', {"id": "dq", "version": "1.0"}),
+ ("[project]\nname = 'sq'\nversion = '2.0'\n", {"id": "sq", "version": "2.0"}),
+ ('[project]\nversion = "3.0"\n\n[tool.x]\nname = "not-this"\n', {"id": "pack", "version": "3.0"}),
+ ('[tool.comfy]\nname = "x"\nversion = "9"\n', {"id": "pack"}),
+ (None, {"id": "pack"}),
+])
+def test_cnr_pyproject_parsing(tmp_path, pyproject, expected):
+ write(tmp_path / "pack" / ".tracking")
+ if pyproject is not None:
+ write(tmp_path / "pack" / "pyproject.toml", pyproject)
+ assert deploy_to_cloud.scan_custom_nodes([str(tmp_path)]) == [{"type": "cnr", "dirName": "pack", "enabled": True, **expected}]
+
+
[email protected]("url, expected", [
+ ("https://user:[email protected]/a/b.git", "https://github.com/a/b.git"),
+ ("http://[email protected]:8080/a/b?x=1#f", "http://example.com:8080/a/b"),
+ ("https://github.com/a/b.git", "https://github.com/a/b.git"),
+ ("[email protected]:a/b.git", "[email protected]:a/b.git"),
+ ("ssh://user:secret@host/x.git", "ssh://host/x.git"),
+ ("ssh://[email protected]/org/repo.git", "ssh://[email protected]/org/repo.git"),
+ ("ssh://git:@github.com:22/org/repo.git", "ssh://github.com:22/org/repo.git"),
+ ("ssh://al%40ice@host/x.git", "ssh://host/x.git"),
+ ("https://[email protected]/org/repo.git", "https://github.com/org/repo.git"),
+ ("git://user@host:9418/x.git", "git://host:9418/x.git"),
+ ("HTTPS://github.com/a/b.git", "https://github.com/a/b.git"),
+ # only http(s)/ssh/git URLs with a host, and scp-like remotes on a dotted host, are reported
+ ("[email protected]:team/repo.git", "[email protected]:team/repo.git"),
+ ("user@internal-host:repo.git", None),
+ ("[email protected]:/abs/repo.git", None),
+ ("https::https://a:b@h/x", None),
+ ("ext::ssh -i key host %S x", None),
+ ("https://[::1]/x.git", None),
+ ("https://user:123/pw@host/x.git", None),
+ ("https://user@/x.git", None),
+ ("file:///srv/x.git", None),
+ ("ftp://host/x.git", None),
+ ("/srv/x.git", None),
+ ("../x.git", None),
+ ("C:\\repos\\x.git", None),
+ # git's value syntax: quotes, escapes and comments are decoded before the URL is classified
+ ('"https://alice:[email protected]/org/repo.git"', "https://github.com/org/repo.git"),
+ ('"https://al\\"ice:se\\\\[email protected]/org/my\\"repo.git"', 'https://github.com/org/my"repo.git'),
+ ('"ssh://alice:secret@host/x.git" # pinned', "ssh://host/x.git"),
+ ("https://alice:[email protected]/a/b.git ; set by script", "https://github.com/a/b.git"),
+ ("https://github.com/a/b.git\n\t\tpushurl = https://alice:[email protected]/a/b.git", "https://github.com/a/b.git"),
+ ('"https://alice:[email protected]/a/b.git', None),
+ ('"https://alice:se\\[email protected]/a/b.git"', None),
+ ("https://alice:[email protected]/a/b.git\\", None),
+])
+def test_git_origin_url_strips_userinfo(tmp_path, url, expected):
+ git_repo(tmp_path, SHA_A, origin=url)
+ assert deploy_to_cloud._git_origin_url(str(tmp_path)) == expected
+
+
+def test_git_origin_url_tolerates_bad_config(tmp_path):
+ write(tmp_path / "config", "garbage without section\n")
+ assert deploy_to_cloud._git_origin_url(str(tmp_path)) is None
+ assert deploy_to_cloud._git_origin_url(str(tmp_path / "missing")) is None
+
+
+def test_git_head_rejects_ref_escaping_gitdir(tmp_path):
+ write(tmp_path / "outside", SHA_A)
+ write(tmp_path / "g" / "HEAD", "ref: refs/../../outside\n")
+ assert deploy_to_cloud._git_head(str(tmp_path / "g")) is None
+
+
+def test_pip_packages_are_name_to_version():
+ packages = deploy_to_cloud.pip_packages()
+ assert "aiohttp" in packages
+ assert all(isinstance(k, str) and isinstance(v, str) for k, v in packages.items())
+
+
+def dist_info(site, name, version):
+ write(site / f"{name}-{version}.dist-info" / "METADATA", f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n")
+
+
+def env(tmp_path, monkeypatch):
+ """A fake sys.prefix; each test sets sys.path to the site directories it builds."""
+ prefix = tmp_path / "env"
+ prefix.mkdir()
+ monkeypatch.setattr(deploy_to_cloud.sys, "prefix", str(prefix))
+ return prefix
+
+
+def test_pip_packages_keep_first_distribution_of_a_name(env, monkeypatch):
+ dist_info(env / "first", "dup", "1.0")
+ dist_info(env / "second", "dup", "2.0")
+ write(env / "second" / "nameless-1.0.dist-info" / "METADATA", "Metadata-Version: 2.1\nVersion: 1.0\n")
+ monkeypatch.setattr(deploy_to_cloud.sys, "path", [str(env / "first"), str(env / "second")])
+ assert deploy_to_cloud.pip_packages() == {"dup": "1.0"}
+
+
+def test_pip_packages_read_only_sys_path_entries_under_sys_prefix(tmp_path, env, monkeypatch):
+ dist_info(env / "lib" / "site-packages", "inside", "1.0")
+ dist_info(tmp_path / "user-site", "user-only", "1.0")
+ dist_info(tmp_path / "base" / "site-packages", "base-only", "1.0")
+ dist_info(tmp_path / "env_sibling" / "site-packages", "sibling-only", "1.0")
+ monkeypatch.setattr(deploy_to_cloud.sys, "path", [
+ str(tmp_path / "comfyui"), str(tmp_path / "user-site"), str(env / "lib" / "site-packages"),
+ str(tmp_path / "base" / "site-packages"), str(tmp_path / "env_sibling" / "site-packages"),
+ ])
+ assert deploy_to_cloud.pip_packages() == {"inside": "1.0"}
+
+
+def test_pip_packages_compare_resolved_paths(tmp_path, env, monkeypatch):
+ dist_info(env / "site", "inside", "1.0")
+ dist_info(tmp_path / "user-site", "user-only", "1.0")
+ try:
+ (tmp_path / "env-link").symlink_to(env, target_is_directory=True)
+ (env / "escape").symlink_to(tmp_path / "user-site", target_is_directory=True)
+ except OSError:
+ pytest.skip("symlinks unavailable")
+ monkeypatch.setattr(deploy_to_cloud.sys, "prefix", str(tmp_path / "env-link"))
+ monkeypatch.setattr(deploy_to_cloud.sys, "path", [str(env / "site"), str(env / "escape")])
+ assert deploy_to_cloud.pip_packages() == {"inside": "1.0"}
+
+
[email protected]("direct_url, expected", [
+ (None, "1.0"),
+ ({"url": "file:///home/alice/src/pkg", "dir_info": {"editable": True}}, "file://local"),
+ ({"url": "file:///home/alice/src/pkg", "dir_info": {}}, "file://local"),
+ ({"url": "https://alice:[email protected]/a/b.git", "vcs_info": {"vcs": "git", "commit_id": SHA_A, "requested_revision": "main"}},
+ f"git+https://github.com/a/b.git@{SHA_A}"),
+ ({"url": "ssh://[email protected]/a/b.git", "vcs_info": {"vcs": "git", "commit_id": SHA_B}}, f"git+ssh://[email protected]/a/b.git@{SHA_B}"),
+ ({"url": "https://[email protected]/x/pkg-1.0.tar.gz?sig=s#sha256=00", "archive_info": {"hash": "sha256=00"}},
+ "https://files.example.com/x/pkg-1.0.tar.gz"),
+ ({"url": "file:///home/alice/wheels/pkg-1.0-py3-none-any.whl", "archive_info": {}}, "file://local"),
+ ({"url": "file:///home/alice/repo", "vcs_info": {"vcs": "git", "commit_id": SHA_A}}, "file://local"),
+ ({"url": "https://github.com/a/b.git", "vcs_info": {"vcs": "git"}}, "file://local"),
+ ({"url": "https://github.com/a/b.git", "vcs_info": "git"}, "file://local"),
+ ({"url": 5, "archive_info": {}}, "file://local"),
+ ({"archive_info": {}}, "file://local"),
+ (["https://github.com/a/b.git"], "file://local"),
+ ("{not json", "file://local"),
+])
+def test_pip_packages_report_direct_url_installs_without_paths_or_credentials(env, monkeypatch, direct_url, expected):
+ dist_info(env / "site", "pkg", "1.0")
+ if direct_url is not None:
+ write(env / "site" / "pkg-1.0.dist-info" / "direct_url.json", direct_url if isinstance(direct_url, str) else json.dumps(direct_url))
+ monkeypatch.setattr(deploy_to_cloud.sys, "path", [str(env / "site")])
+ assert deploy_to_cloud.pip_packages() == {"pkg": expected}
+
+
+def test_build_snapshot_envelope(custom_nodes, monkeypatch):
+ monkeypatch.setitem(folder_paths.folder_names_and_paths, "custom_nodes", ([str(custom_nodes)], set()))
+ monkeypatch.setattr(folder_paths, "base_path", str(custom_nodes.parent / "MyComfy"))
+ s = deploy_to_cloud.build_snapshot()
+ assert s["type"] == "comfyui-desktop-2-snapshot"
+ assert s["version"] == 2
+ assert s["installationName"] == "MyComfy"
+ assert s["exportedAt"].endswith("Z")
+ [snap] = s["snapshots"]
+ tag = "v" + __version__
+ assert snap["createdAt"] == s["exportedAt"]
+ assert (snap["version"], snap["trigger"], snap["label"]) == (2, "manual", None)
+ assert snap["comfyui"] == {"ref": tag, "commit": None, "releaseTag": tag, "variant": "comfyui-core", "baseTag": tag}
+ assert snap["pythonVersion"] == platform.python_version()
+ assert "aiohttp" in snap["pipPackages"]
+ assert snap["customNodes"] == deploy_to_cloud.scan_custom_nodes([str(custom_nodes)])
+
+
+def test_build_snapshot_golden_json(custom_nodes, monkeypatch):
+ monkeypatch.setitem(folder_paths.folder_names_and_paths, "custom_nodes", ([str(custom_nodes)], set()))
+ parsed = json.loads(json.dumps(deploy_to_cloud.build_snapshot()))
+ nodes = parsed["snapshots"][0]["customNodes"]
+ assert len(nodes) == 12
+ for node in nodes:
+ assert set(node) <= NODE_KEYS
+
+
+def test_list_models(monkeypatch):
+ files = {
+ "checkpoints": ["sd.safetensors", "sub/dir/model.GGUF", "readme.txt", "preview.png"],
+ "configs": ["v1.yaml", "weird.safetensors"],
+ "custom_nodes": ["pack/model.safetensors"],
+ "text_encoders": ["t5.onnx", "t5.yaml"],
+ }
+ monkeypatch.setattr(folder_paths, "folder_names_and_paths", {k: ([], set()) for k in files})
+ monkeypatch.setattr(folder_paths, "get_filename_list", lambda folder: files[folder])
+ assert deploy_to_cloud.list_models() == [
+ {"directory": "checkpoints", "filename": "sd.safetensors"},
+ {"directory": "checkpoints", "filename": "sub/dir/model.GGUF"},
+ {"directory": "text_encoders", "filename": "t5.onnx"},
+ ]
+
+
+def test_collect_returns_snapshot_and_models(monkeypatch):
+ monkeypatch.setattr(deploy_to_cloud, "build_snapshot", lambda: {"type": "s"})
+ monkeypatch.setattr(deploy_to_cloud, "list_models", lambda: [{"directory": "d", "filename": "f"}])
+ assert deploy_to_cloud.collect() == ({"type": "s"}, [{"directory": "d", "filename": "f"}])