diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e68e6caf..146f8afee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ history. `asset_upload_refused`; new codes `asset_upload_invalid`, `asset_upload_failed` and `asset_upload_timeout` cover the other ways it can end. + - `comfy knowledge resolve` suggests canonical model ids for an incomplete family/version name such as `Qwen 2.1`. The command still fails with `knowledge_unknown_model` and exit 1, but `error.details.candidate_ids` lists @@ -60,9 +61,17 @@ history. ### Fixed -- `comfy assets library ls` reports a 401 or 403 as `cloud_unauthorized` even - when the server drops the connection partway through its error body, instead - of crashing with `IncompleteRead`. +- Desktop discovery reads both modern and legacy registries. Callers with + running-server launch metadata select that exact instance, resolve its model + YAML and effective data/input/output paths, and keep ambiguous or relative + runtime identities unresolved. The optional discovery fields are documented + in the which/env schemas; unrelated launch arguments are excluded. + +- `comfy which` and `comfy env` report Desktop's split code, data and model + roots without changing launch/install selection. A nonexistent selected + workspace no longer succeeds in `which`; discovery reports malformed Desktop + configuration and marks inferred data roots as unverified. + - A typed `comfy model download` with no `--relative-path` now saves into the folder the running local ComfyUI scans for that model type, and says where. On Comfy Desktop that is the shared library, not the install's `models/`. @@ -112,6 +121,10 @@ history. value. Saves with a real marker have one more value than sockets and still go through the filter. +- `comfy assets library ls` reports a 401 or 403 as `cloud_unauthorized` even + when the server drops the connection partway through its error body, instead + of crashing with `IncompleteRead`. + ## [1.24.0] - 2026-10-29 [Full notes](https://github.com/Comfy-Org/comfy-cli/releases/tag/v1.24.0) · 25 commits since v1.23.0. diff --git a/comfy_cli/cmdline.py b/comfy_cli/cmdline.py index 7f71001ec..caadde0f6 100644 --- a/comfy_cli/cmdline.py +++ b/comfy_cli/cmdline.py @@ -2775,7 +2775,8 @@ def set_default( @tracking.track_command() def which(): renderer = get_renderer() - comfy_path = workspace_manager.workspace_path + workspace = workspace_manager.discovery_data() + comfy_path = workspace["path"] if comfy_path is None: renderer.error( code="not_in_workspace", @@ -2784,15 +2785,25 @@ def which(): ) raise typer.Exit(code=1) - workspace_type_value = ( - workspace_manager.workspace_type.value if workspace_manager.workspace_type is not None else None - ) + workspace_type_value = workspace["type"] + if not workspace["exists"]: + details = {"path": comfy_path, "workspace_type": workspace_type_value} + if "desktop" in workspace: + details["desktop"] = workspace["desktop"] + renderer.error( + code="workspace_not_found", + message=f"Workspace directory does not exist: {comfy_path}", + hint="run: comfy install (or pass --workspace /path/to/ComfyUI)", + details=details, + ) + raise typer.Exit(code=1) if renderer.is_pretty(): import sys as _sys from comfy_cli.env_checker import _display_url from comfy_cli.local_address import resolve_local_host_port from comfy_cli.output.panels import which_panel + from comfy_cli.output.sanitize import sanitize_value host, port = resolve_local_host_port(None, None, background=ConfigManager().background) try: @@ -2808,12 +2819,17 @@ def which(): server_running=server_running, server_url=_display_url(host, port), version=ConfigManager().get_cli_version(), + desktop=workspace.get("desktop"), ) ) + for warning in workspace.get("warnings", []): + renderer.console().print(sanitize_value(warning["message"]), markup=False) renderer.emit( { "workspace_path": str(comfy_path), "workspace_type": workspace_type_value, + "exists": workspace["exists"], + **{key: workspace[key] for key in ("desktop", "warnings") if key in workspace}, }, command="which", ) @@ -2893,6 +2909,9 @@ def env(): # JSON path: collect structured data without printing the table. data = EnvChecker().fill_data() data["workspace"] = workspace_manager.fill_data() + warnings = data["workspace"].pop("warnings", None) + if warnings: + data["warnings"] = warnings renderer.emit(data, command="env") diff --git a/comfy_cli/desktop_install.py b/comfy_cli/desktop_install.py new file mode 100644 index 000000000..789af470c --- /dev/null +++ b/comfy_cli/desktop_install.py @@ -0,0 +1,581 @@ +"""Find a Comfy Desktop 2 install from the records Desktop keeps on disk. + +Desktop 2 splits one install across up to three places, and none of them is +where comfy-cli's own default workspace lives: + +* the **code dir** — a ComfyUI checkout at ``/ComfyUI``; +* the **data dir** — ``models/``, ``custom_nodes/``, ``user/`` and the venv. + For an install adopted from Desktop 1 that is ``adoptedBaseDir`` (Desktop + launches it with ``--base-directory``); otherwise it is the code dir; +* **model roots** — the data dir's ``models/`` plus the shared library in + ``settings.json`` → ``modelsDirs`` (unless the install opted out with + ``useSharedModels: false``) plus the install's own ``modelDirs``. + +Everything is read from files Desktop maintains in its app-data dir +(``installations.json``, ``settings.json``). Nothing here starts Desktop, +talks to a server, or writes a file. +""" + +from __future__ import annotations + +import json +import os +import re +from dataclasses import dataclass, field, replace +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from comfy_cli.constants import OS +from comfy_cli.utils import get_os + +#: Desktop 2's Electron ``userData`` folder name. +APP_DIR_NAME = "Comfy Desktop" +MODERN_APP_DIR_NAME = "comfyui-desktop-2" +#: Desktop 1's ``userData`` folder, which holds ``config.json`` → ``basePath``. +LEGACY_APP_DIR_NAME = "ComfyUI" + +_BARE_RELEASE_RE = re.compile(r"^\d+(?:\.\d+)+$") +_VERSION_MARKER_RE = re.compile(r"""^__version__\s*=\s*['"]([^'"\n]+)['"]""", re.MULTILINE) + + +def desktop_app_data_dir() -> Path | None: + """Desktop 2's app-data dir on this OS (where ``installations.json`` lives).""" + current = get_os() + if current == OS.MACOS: + return Path.home() / "Library" / "Application Support" / APP_DIR_NAME + if current == OS.WINDOWS: + appdata = os.environ.get("APPDATA") + return Path(appdata) / APP_DIR_NAME if appdata else None + base = os.environ.get("XDG_DATA_HOME") or str(Path.home() / ".local" / "share") + return Path(base) / APP_DIR_NAME + + +def legacy_config_dir() -> Path | None: + """Desktop 1's app-data dir (``config.json`` → ``basePath``); none on Linux.""" + current = get_os() + if current == OS.MACOS: + return Path.home() / "Library" / "Application Support" / LEGACY_APP_DIR_NAME + if current == OS.WINDOWS: + appdata = os.environ.get("APPDATA") + return Path(appdata) / LEGACY_APP_DIR_NAME if appdata else None + return None + + +@dataclass(frozen=True) +class ModelRoot: + path: str + #: ``data`` (the install's own ``models/``), ``shared`` (``settings.json`` + #: ``modelsDirs``) or ``install`` (the install record's own ``modelDirs``). + source: str + exists: bool + + def to_dict(self) -> dict[str, Any]: + return {"path": self.path, "source": self.source, "exists": self.exists} + + +@dataclass(frozen=True) +class DesktopInstall: + install_id: str | None + name: str | None + code_dir: str + data_dir: str + python: str | None + model_roots: tuple[ModelRoot, ...] + comfyui_version: str | None + comfyui_commit: str | None + adopted: bool + status: str | None + last_launched_ms: int | None + #: The code dir holds a ComfyUI checkout (``main.py``) — only such an + #: install can be selected. + exists: bool + #: Internal registry ownership for generated config identity; never serialized. + registry_dir: str | None = field(default=None, repr=False) + + @property + def last_launched_at(self) -> str | None: + if not self.last_launched_ms: + return None + try: + stamp = datetime.fromtimestamp(self.last_launched_ms / 1000, tz=timezone.utc) + except (OSError, OverflowError, ValueError): + return None + return stamp.isoformat(timespec="seconds").replace("+00:00", "Z") + + def summary(self, *, selected: bool) -> dict[str, Any]: + """One row of ``desktop.installs``: enough to tell the installs apart.""" + return { + "install_id": self.install_id, + "name": self.name, + "code_dir": self.code_dir, + "data_dir": self.data_dir, + "comfyui_version": self.comfyui_version, + "last_launched_at": self.last_launched_at, + "status": self.status, + "exists": self.exists, + "selected": selected, + } + + +@dataclass(frozen=True) +class DesktopDetection: + app_data_dir: str + installs: tuple[DesktopInstall, ...] = () + selected: DesktopInstall | None = None + selected_reason: str | None = None + #: Records that exist but could not be read, as ``": "``. + problems: tuple[str, ...] = field(default_factory=tuple) + input_dir: str | None = None + output_dir: str | None = None + output_dir_source: str | None = None + + def to_dict(self) -> dict[str, Any]: + """The ``desktop`` block of ``comfy which`` / ``comfy env``. + + The selected install's fields sit at the top level so an agent reads + ``desktop.data_dir`` directly; ``installs`` lists every local install. + """ + chosen = self.selected + block: dict[str, Any] = { + "install_id": chosen.install_id if chosen else None, + "name": chosen.name if chosen else None, + "code_dir": chosen.code_dir if chosen else None, + "data_dir": chosen.data_dir if chosen else None, + "custom_nodes_dir": os.path.join(chosen.data_dir, "custom_nodes") if chosen else None, + "python": chosen.python if chosen else None, + "model_roots": [root.to_dict() for root in chosen.model_roots] if chosen else [], + "comfyui_version": chosen.comfyui_version if chosen else None, + "comfyui_commit": chosen.comfyui_commit if chosen else None, + "selected_reason": self.selected_reason, + "installs": [install.summary(selected=install is chosen) for install in self.installs], + "app_data_dir": self.app_data_dir, + } + if self.input_dir is not None: + block["input_dir"] = self.input_dir + if self.output_dir is not None: + block["output_dir"] = self.output_dir + block["output_dir_source"] = self.output_dir_source + return block + + +def _same_path(a: str, b: str) -> bool: + try: + return os.path.samefile(a, b) + except OSError: + return os.path.normcase(os.path.realpath(a)) == os.path.normcase(os.path.realpath(b)) + + +def _read_json(path: Path) -> Any: + with open(path, encoding="utf-8") as fh: + return json.load(fh) + + +def _venv_python(venv: Path) -> Path | None: + for candidate in (venv / "bin" / "python3", venv / "bin" / "python", venv / "Scripts" / "python.exe"): + if candidate.is_file(): + return candidate + return None + + +def _code_dir(install_path: Path) -> Path: + """Mirror Desktop's ``resolveComfyDir``: ``/ComfyUI``, or the + install path itself when the checkout sits there directly.""" + nested = install_path / "ComfyUI" + if not nested.is_dir() and (install_path / "main.py").is_file(): + return install_path + return nested + + +def _version_from_marker(code_dir: Path) -> str | None: + try: + match = _VERSION_MARKER_RE.search((code_dir / "comfyui_version.py").read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError): + return None + return match.group(1) if match else None + + +def _as_tag(version: str) -> str: + version = version.strip() + return "v" + version if _BARE_RELEASE_RE.match(version) else version + + +def _str_list(value: Any) -> list[str]: + return [item for item in value if isinstance(item, str) and item] if isinstance(value, list) else [] + + +def _model_roots(data_dir: Path, record: dict, shared_dirs: list[str]) -> tuple[ModelRoot, ...]: + """Every root ComfyUI searches for this install, in search order, de-duplicated. + + Desktop writes the shared and per-install dirs into an + ``--extra-model-paths-config`` YAML at launch; ComfyUI always searches the + data dir's own ``models/`` as well. + """ + candidates: list[tuple[str, str]] = [(str(data_dir / "models"), "data")] + if record.get("useSharedModels") is not False: + candidates += [(os.path.abspath(os.path.expanduser(d)), "shared") for d in shared_dirs] + candidates += [(os.path.abspath(os.path.expanduser(d)), "install") for d in _str_list(record.get("modelDirs"))] + roots: list[ModelRoot] = [] + for path, source in candidates: + if any(_same_path(path, root.path) for root in roots): + continue + roots.append(ModelRoot(path=path, source=source, exists=os.path.isdir(path))) + return tuple(roots) + + +def _install_from_record( + record: dict, shared_dirs: list[str], legacy_base_path: str | None, *, registry_dir: Path | None = None +) -> DesktopInstall | None: + install_path = record.get("installPath") + if not isinstance(install_path, str) or not install_path: + return None # a remote entry (Comfy Cloud) has no local files + install_root = Path(os.path.expanduser(install_path)) + code_dir = _code_dir(install_root) + adopted = record.get("adopted") is True + base_dir = record.get("adoptedBaseDir") if adopted else None + if adopted and not (isinstance(base_dir, str) and base_dir): + base_dir = legacy_base_path + data_dir = Path(os.path.expanduser(base_dir)) if isinstance(base_dir, str) and base_dir else code_dir + + python: Path | None = None + adopted_python = record.get("adoptedPythonPath") if adopted else None + if isinstance(adopted_python, str) and Path(adopted_python).is_file(): + python = Path(adopted_python) + if python is None: + python = _venv_python(data_dir / ".venv") + + version_record = record.get("comfyVersion") if isinstance(record.get("comfyVersion"), dict) else {} + base_tag = version_record.get("baseTag") + version = base_tag if isinstance(base_tag, str) and base_tag else _version_from_marker(code_dir) + commit = version_record.get("commit") + last_launched = record.get("lastLaunchedAt") + + return DesktopInstall( + install_id=record.get("id") if isinstance(record.get("id"), str) else None, + name=record.get("name") if isinstance(record.get("name"), str) else None, + code_dir=str(code_dir), + data_dir=str(data_dir), + python=str(python) if python else None, + model_roots=_model_roots(data_dir, record, shared_dirs), + comfyui_version=_as_tag(version) if version else None, + comfyui_commit=commit if isinstance(commit, str) and commit else None, + adopted=adopted, + status=record.get("status") if isinstance(record.get("status"), str) else None, + last_launched_ms=last_launched if isinstance(last_launched, (int, float)) and last_launched > 0 else None, + exists=(code_dir / "main.py").is_file(), + registry_dir=str(registry_dir) if registry_dir is not None else None, + ) + + +def _select(installs: tuple[DesktopInstall, ...]) -> tuple[DesktopInstall | None, str | None]: + """Pick the install an agent should assume, and say why.""" + usable = [install for install in installs if install.exists] + if not usable: + return None, None + if len(usable) == 1: + return usable[0], "the only Comfy Desktop install with a ComfyUI checkout on disk" + launched = [install for install in usable if install.last_launched_at] + if launched: + chosen = max(launched, key=lambda install: install.last_launched_ms or 0) + return chosen, ( + f"the most recently launched of {len(usable)} Comfy Desktop installs (last launched " + f"{chosen.last_launched_at}); pass --workspace to pick another" + ) + return usable[0], ( + f"the first of {len(usable)} Comfy Desktop installs in installations.json (none has been launched); " + "pass --workspace to pick another" + ) + + +def app_data_dirs() -> tuple[Path, ...]: + """Known registry folders, keeping an explicit/test override isolated.""" + primary = desktop_app_data_dir() + if primary is None: + return () + if primary.name not in (APP_DIR_NAME, MODERN_APP_DIR_NAME): + return (primary,) + return tuple(dict.fromkeys((primary, primary.parent / MODERN_APP_DIR_NAME, primary.parent / APP_DIR_NAME))) + + +def _argv_values(argv: list[str], flag: str) -> list[str]: + values: list[str] = [] + for index, item in enumerate(argv): + if item.startswith(flag + "="): + values.append(item.split("=", 1)[1]) + elif item == flag and index + 1 < len(argv): + for value in argv[index + 1 :]: + if value.startswith("--"): + break + values.append(value) + if flag != "--extra-model-paths-config": + break + return values + + +def server_launch_paths(stats: dict[str, Any]) -> dict[str, list[str]]: + """Return only known filesystem launch arguments, excluding unrelated credential flags.""" + system = stats.get("system") or {} + argv = system.get("argv") if isinstance(system, dict) else None + if not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv): + return {} + return { + name: values + for name in ("base_directory", "input_directory", "output_directory", "extra_model_paths_config") + if (values := _argv_values(argv, "--" + name.replace("_", "-"))) + } + + +def _config_identifies_install(config: str, install: DesktopInstall) -> bool: + install_id = install.install_id + if ( + not install.registry_dir + or not install_id + or install_id in (".", "..") + or any(c in install_id for c in "/\\:\x00") + ): + return False + path = Path(config).expanduser() + if not path.is_absolute(): + return False + expected = Path(install.registry_dir) / "instance-model-paths" / f"{install_id}.yaml" + return _same_path(str(path), str(expected)) + + +def _for_server( + found: DesktopDetection, stats: dict[str, Any], *, filesystem_verified: bool = False +) -> DesktopDetection: + """Select using launch identity, never a remembered last-launched record.""" + if not filesystem_verified: + return replace( + found, + selected=None, + selected_reason=None, + input_dir=None, + output_dir=None, + output_dir_source=None, + problems=(*found.problems, "running server filesystem is unverified; pass explicit model/input roots"), + ) + system = stats.get("system") or {} + if not isinstance(system, dict): + system = {} + argv = system.get("argv") or [] + if not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv): + argv = [] + bases = _argv_values(argv, "--base-directory") + configs = _argv_values(argv, "--extra-model-paths-config") + scripts = [arg for arg in argv if Path(arg).is_absolute() and Path(arg).name == "main.py"] + matches = [ + install + for install in found.installs + if install.exists + and ( + any(_same_path(base, install.data_dir) for base in bases) + or any(_same_path(str(Path(script).parent), install.code_dir) for script in scripts) + or any(_config_identifies_install(config, install) for config in configs) + ) + ] + if len(matches) != 1: + detail = "does not identify one recorded Desktop installation" + return replace( + found, + selected=None, + selected_reason=None, + problems=(*found.problems, f"running server {detail}; pass explicit model/input roots"), + ) + chosen = matches[0] + outputs = _argv_values(argv, "--output-directory") + if any( + not Path(path).expanduser().is_absolute() + for path in (*bases, *_argv_values(argv, "--input-directory"), *outputs) + ): + return replace( + found, + selected=None, + selected_reason=None, + problems=( + *found.problems, + "running server uses relative data/input/output paths; verify its working directory", + ), + ) + data_dir = str(Path(bases[-1]).expanduser()) if bases else chosen.data_dir + roots = [root for root in chosen.model_roots if root.source != "data"] if not configs else [] + roots.insert(0, ModelRoot(str(Path(data_dir) / "models"), "data", (Path(data_dir) / "models").is_dir())) + problems = list(found.problems) + for config in configs: + config_path = Path(config).expanduser() + if not config_path.is_absolute(): + problems.append(f"running server model config is relative: {config}; verify its working directory") + continue + try: + import yaml + + contents = yaml.safe_load(config_path.read_text(encoding="utf-8")) + if not isinstance(contents, dict): + raise ValueError("expected a mapping") + for row in contents.values(): + if not isinstance(row, dict): + continue + base = row.get("base_path") + base_path = None + if isinstance(base, str) and base: + base_path = Path(os.path.expandvars(base)).expanduser() + if not base_path.is_absolute(): + base_path = config_path.parent / base_path + base_path = base_path.resolve() + paths = [base_path] if base_path is not None else [] + for kind, value in row.items(): + if kind in ("base_path", "is_default"): + continue + if not isinstance(value, str): + raise ValueError(f"{kind}: expected newline-separated model paths") + for entry in value.splitlines(): + if not entry: + continue + path = Path(entry) + if not path.is_absolute(): + path = (base_path or config_path.parent) / path + path = path.resolve() + # A base covers its descendant type folders. Keep a + # separate root for absolute paths outside that base. + if base_path is None or not path.is_relative_to(base_path): + paths.append(path) + for path in paths: + if not any(_same_path(str(path), root.path) for root in roots): + roots.append(ModelRoot(str(path), "install", path.is_dir())) + except (OSError, ValueError, yaml.YAMLError) as error: + problems.append(f"{config}: {error}") + python = system.get("python") + version = system.get("comfyui_version") + chosen = replace( + chosen, + comfyui_version=_as_tag(version) if isinstance(version, str) and version else chosen.comfyui_version, + data_dir=data_dir, + model_roots=tuple(roots), + python=python if isinstance(python, str) and Path(python).is_file() else None, + ) + inputs = _argv_values(argv, "--input-directory") + input_dir = str(Path(inputs[-1]).expanduser()) if inputs else str(Path(data_dir) / "input") + return replace( + found, + selected=chosen, + selected_reason="matches the running server launch arguments", + installs=tuple(chosen if item is matches[0] else item for item in found.installs), + input_dir=input_dir, + output_dir=str(Path(outputs[-1]).expanduser()) if outputs else str(Path(data_dir) / "output"), + output_dir_source="server_argv" if outputs else "server_default", + problems=tuple(problems), + ) + + +def detect( + app_data_dir: Path | None = None, + legacy_dir: Path | None = None, + *, + server_stats: dict[str, Any] | None = None, + server_filesystem_verified: bool = False, +) -> DesktopDetection | None: + """Read Desktop 2's install records. ``None`` means Desktop 2 is not installed. + + The app-data dirs default to this OS's; tests pass fixture dirs instead. + Server paths require caller-established local process/filesystem provenance; + matching strings or a loopback URL alone are insufficient. + """ + if app_data_dir is None: + detections = [found for directory in app_data_dirs() if (found := detect(directory, legacy_dir)) is not None] + if not detections: + return None + installs = tuple(install for found in detections for install in found.installs) + selected, reason = _select(installs) + origin = next( + (found.app_data_dir for found in detections if selected in found.installs), detections[0].app_data_dir + ) + found = DesktopDetection( + origin, installs, selected, reason, tuple(problem for item in detections for problem in item.problems) + ) + return ( + _for_server(found, server_stats, filesystem_verified=server_filesystem_verified) + if server_stats is not None + else found + ) + app_dir = app_data_dir + if app_dir is None: + return None + installations_file = app_dir / "installations.json" + if not installations_file.is_file(): + return None + + problems: list[str] = [] + try: + records = _read_json(installations_file) + except (OSError, UnicodeDecodeError, ValueError) as error: + return DesktopDetection(app_data_dir=str(app_dir), problems=(f"{installations_file}: {error}",)) + if not isinstance(records, list): + return DesktopDetection( + app_data_dir=str(app_dir), problems=(f"{installations_file}: expected a list of installs",) + ) + + shared_dirs: list[str] = [] + settings_file = app_dir / "settings.json" + if settings_file.is_file(): + try: + settings = _read_json(settings_file) + shared_dirs = _str_list(settings.get("modelsDirs")) if isinstance(settings, dict) else [] + except (OSError, UnicodeDecodeError, ValueError) as error: + problems.append(f"{settings_file}: {error} (shared model roots are missing from model_roots)") + + legacy_base_path: str | None = None + legacy = legacy_dir if legacy_dir is not None else legacy_config_dir() + if legacy is not None and (legacy / "config.json").is_file(): + try: + config = _read_json(legacy / "config.json") + base = config.get("basePath") if isinstance(config, dict) else None + legacy_base_path = base if isinstance(base, str) and base else None + except (OSError, UnicodeDecodeError, ValueError) as error: + legacy_base_path = None + problems.append(f"{legacy / 'config.json'}: {error}") + + if legacy_base_path is None and any( + isinstance(record, dict) + and record.get("adopted") is True + and not (isinstance(record.get("adoptedBaseDir"), str) and record["adoptedBaseDir"]) + for record in records + ): + problems.append( + "an adopted Desktop installation has no readable data path; its data_dir and derived model roots " + "fall back to the code directory and are unverified" + ) + + installs = tuple( + install + for install in ( + _install_from_record(record, shared_dirs, legacy_base_path, registry_dir=app_dir) + for record in records + if isinstance(record, dict) + ) + if install is not None + ) + selected, reason = _select(installs) + found = DesktopDetection( + app_data_dir=str(app_dir), + installs=installs, + selected=selected, + selected_reason=reason, + problems=tuple(problems), + ) + return ( + _for_server(found, server_stats, filesystem_verified=server_filesystem_verified) + if server_stats is not None + else found + ) + + +def install_for_dir(path: str | os.PathLike[str], detection: DesktopDetection | None = None) -> DesktopInstall | None: + """The Desktop install whose code dir or data dir is ``path``, if any.""" + found = detection if detection is not None else detect() + if found is None: + return None + target = os.fspath(path) + for install in found.installs: + if _same_path(target, install.data_dir) or _same_path(target, install.code_dir): + return install + return None diff --git a/comfy_cli/error_codes.py b/comfy_cli/error_codes.py index ff11c8db7..7d23e115a 100644 --- a/comfy_cli/error_codes.py +++ b/comfy_cli/error_codes.py @@ -65,6 +65,16 @@ class ErrorCode: "Resolved no workspace where one was required (e.g. `comfy which`).", "run `comfy install`, or pass `--workspace`", ), + ErrorCode( + "workspace_not_found", + "The workspace reported by `comfy which` does not exist on disk; details.path names the missing directory.", + "run `comfy install`, or pass `--workspace /path/to/ComfyUI`", + ), + ErrorCode( + "desktop_config_unreadable", + "Comfy Desktop installation records or settings could not be read; discovery may be incomplete.", + "check the Desktop configuration file named in the warning", + ), # --- launch / stop lifecycle --------------------------------------------- ErrorCode( "server_already_running", diff --git a/comfy_cli/output/panels.py b/comfy_cli/output/panels.py index e98e31266..0db8d4bcb 100644 --- a/comfy_cli/output/panels.py +++ b/comfy_cli/output/panels.py @@ -224,6 +224,7 @@ def which_panel( server_running: bool = False, server_url: str | None = None, version: str = "0.0.0", + desktop: Mapping[str, Any] | None = None, ) -> Panel: type_badge = Text(workspace_type or "—", style="bold green") if workspace_type else Text("—", style="dim") python_value = Text("—", style="dim") @@ -247,11 +248,21 @@ def which_panel( ) rows: list[tuple[str, Any]] = [ - ("Path", Text(workspace_path, style="bold white")), + ("Path", Text(sanitize_value(workspace_path), style="bold white")), ("Type", type_badge), ("Python", python_value), ("Server", server_value), ] + if desktop: + rows.extend( + [ + ("Desktop code", Text(sanitize_value(desktop["code_dir"]))), + ("Desktop data", Text(sanitize_value(desktop["data_dir"]))), + ("Desktop Python", Text(sanitize_value(desktop["python"] or "—"))), + ("Model roots", Text("\n".join(sanitize_value(root["path"]) for root in desktop["model_roots"]))), + ("Selected because", Text(sanitize_value(desktop["selected_reason"] or "—"))), + ] + ) tbl = Table.grid(padding=(0, 2), expand=False) tbl.add_column(justify="right", style="bold cyan", no_wrap=True) tbl.add_column(overflow="fold") diff --git a/comfy_cli/schemas/env.json b/comfy_cli/schemas/env.json index fced0c67a..0e91f88f9 100644 --- a/comfy_cli/schemas/env.json +++ b/comfy_cli/schemas/env.json @@ -6,6 +6,14 @@ "required": ["python", "config", "workspace", "server"], "additionalProperties": true, "properties": { + "warnings": { + "type": "array", + "items": { + "type": "object", + "required": ["code", "message"], + "properties": {"code": {"type": "string"}, "message": {"type": "string"}} + } + }, "python": { "type": "object", "required": ["version", "executable"], @@ -31,6 +39,36 @@ "type": "object", "additionalProperties": true, "properties": { + "exists": {"type": "boolean", "description": "Whether the workspace directory exists on disk."}, + "desktop": { + "type": "object", + "description": "Desktop installation records, including separate code, data, Python, and model roots.", + "properties": { + "code_dir": {"type": ["string", "null"]}, + "data_dir": {"type": ["string", "null"]}, + "custom_nodes_dir": {"type": ["string", "null"]}, + "python": {"type": ["string", "null"]}, + "input_dir": {"type": "string", "description": "Effective input directory of the selected running Desktop server."}, + "output_dir": {"type": "string", "description": "Effective output directory of the selected running Desktop server."}, + "output_dir_source": {"enum": ["server_argv", "server_default"]}, + "selected_reason": {"type": ["string", "null"]}, + "comfyui_version": {"type": ["string", "null"]}, + "model_roots": { + "type": "array", + "items": { + "type": "object", + "required": ["path", "source", "exists"], + "properties": { + "path": {"type": "string"}, + "source": {"enum": ["data", "shared", "install"]}, + "exists": {"type": "boolean"} + } + } + }, + "installs": {"type": "array", "items": {"type": "object"}}, + "problems": {"type": "array", "items": {"type": "string"}} + } + }, "path": {"type": ["string", "null"]}, "type": {"type": ["string", "null"]}, "manager_mode": {"type": ["string", "null"]}, diff --git a/comfy_cli/schemas/which.json b/comfy_cli/schemas/which.json index a727e4510..f160595ef 100644 --- a/comfy_cli/schemas/which.json +++ b/comfy_cli/schemas/which.json @@ -6,6 +6,44 @@ "required": ["workspace_path"], "additionalProperties": true, "properties": { + "exists": {"type": "boolean", "description": "Whether the workspace directory exists on disk."}, + "desktop": { + "type": "object", + "description": "Desktop installation records, including separate code, data, Python, and model roots.", + "properties": { + "code_dir": {"type": ["string", "null"]}, + "data_dir": {"type": ["string", "null"]}, + "custom_nodes_dir": {"type": ["string", "null"]}, + "python": {"type": ["string", "null"]}, + "input_dir": {"type": "string", "description": "Effective input directory of the selected running Desktop server."}, + "output_dir": {"type": "string", "description": "Effective output directory of the selected running Desktop server."}, + "output_dir_source": {"enum": ["server_argv", "server_default"]}, + "selected_reason": {"type": ["string", "null"]}, + "comfyui_version": {"type": ["string", "null"]}, + "model_roots": { + "type": "array", + "items": { + "type": "object", + "required": ["path", "source", "exists"], + "properties": { + "path": {"type": "string"}, + "source": {"enum": ["data", "shared", "install"]}, + "exists": {"type": "boolean"} + } + } + }, + "installs": {"type": "array", "items": {"type": "object"}}, + "problems": {"type": "array", "items": {"type": "string"}} + } + }, + "warnings": { + "type": "array", + "items": { + "type": "object", + "required": ["code", "message"], + "properties": {"code": {"type": "string"}, "message": {"type": "string"}} + } + }, "workspace_path": {"type": ["string", "null"]}, "workspace_type": {"type": ["string", "null"]} } diff --git a/comfy_cli/workspace_manager.py b/comfy_cli/workspace_manager.py index 4be5b4af7..53d5b774b 100644 --- a/comfy_cli/workspace_manager.py +++ b/comfy_cli/workspace_manager.py @@ -12,6 +12,7 @@ # Route prints through the output shim so they land on stderr in JSON mode # rather than corrupting the envelope on stdout. from comfy_cli.output import rprint as print # noqa: A001 - intentional shadowing +from comfy_cli.output.sanitize import sanitize_markup from comfy_cli.utils import singleton @@ -378,6 +379,36 @@ def _reported_manager_state(self) -> tuple[str, str]: return mode, detected + def discovery_data(self) -> dict: + """Describe the selected workspace, including Desktop's split layout. + + Registry-derived Desktop candidates remain separate from the workspace + used by commands that install or launch code. + """ + from dataclasses import replace + + from comfy_cli import desktop_install + + path = self.workspace_path + kind = self.workspace_type.value if self.workspace_type is not None else None + exists = bool(path and os.path.isdir(path)) + data = {"path": str(path) if path else None, "type": kind, "exists": exists} + found = desktop_install.detect() + selected = desktop_install.install_for_dir(path, found) if path and found else None + if found and (selected or not data["exists"]): + if selected: + reason = found.selected_reason if selected is found.selected else "matches the selected workspace" + found = replace(found, selected=selected, selected_reason=reason) + data["desktop"] = found.to_dict() + if found.problems: + data["desktop"]["problems"] = list(found.problems) + data["warnings"] = [{"code": "desktop_config_unreadable", "message": p} for p in found.problems] + if not data["exists"]: + data.setdefault("warnings", []).insert( + 0, {"code": "workspace_not_found", "message": f"Workspace directory does not exist: {data['path']}"} + ) + return data + def fill_print_table(self): config_manager = ConfigManager() mode, _detected = self._reported_manager_state() @@ -398,11 +429,25 @@ def fill_print_table(self): else: uv_compile_status = "[dim]Disabled[/dim]" - return [ - ("Current selected workspace", f"[bold green]→ {self.workspace_path}[/bold green]"), + discovery = self.discovery_data() + rows = [ + ("Current selected workspace", f"[bold green]→ {sanitize_markup(discovery['path'])}[/bold green]"), ("Manager", manager_status), ("UV Compile Default", uv_compile_status), ] + desktop = discovery.get("desktop") + if desktop and desktop["code_dir"]: + rows.extend( + [ + ("Desktop code", sanitize_markup(desktop["code_dir"])), + ("Desktop data", sanitize_markup(desktop["data_dir"])), + ] + ) + rows.append( + ("Desktop model roots", "\n".join(sanitize_markup(root["path"]) for root in desktop["model_roots"])) + ) + rows.extend(("Warning", sanitize_markup(warning["message"])) for warning in discovery.get("warnings", [])) + return rows def fill_data(self) -> dict: """Structured workspace info for ``comfy env --json``.""" @@ -410,8 +455,7 @@ def fill_data(self) -> dict: uv_compile_value = config_manager.get(constants.CONFIG_KEY_UV_COMPILE_DEFAULT) mode, detected = self._reported_manager_state() return { - "path": str(self.workspace_path) if self.workspace_path else None, - "type": self.workspace_type.value if self.workspace_type is not None else None, + **self.discovery_data(), "manager_mode": mode, "manager_detected": detected, "uv_compile_default": (str(uv_compile_value).lower() == "true" if uv_compile_value is not None else False), diff --git a/docs/adr/DESKTOP-DISCOVERY-0005-preserve-runtime-path-identity.md b/docs/adr/DESKTOP-DISCOVERY-0005-preserve-runtime-path-identity.md new file mode 100644 index 000000000..5b6070efe --- /dev/null +++ b/docs/adr/DESKTOP-DISCOVERY-0005-preserve-runtime-path-identity.md @@ -0,0 +1,100 @@ +# ADR-DESKTOP-DISCOVERY-0005: Preserve Runtime Path Identity + +Date: 2026-10-25 + +## Status + +Proposed + +Relation: Builds on [ADR-AUTOMATION-0003](AUTOMATION-0003-one-versioned-machine-output-dialect.md). +The versioned envelope, additive field/error compatibility and separation of +human diagnostics from machine output remain unchanged. + +## Context + +Desktop separates its code checkout, data directory, interpreter and shared +model folders. Modern and legacy registries can coexist, and an existing +last-launched installation is not necessarily the process serving a workflow. +Model-path YAML and launch flags can override the remembered data/input/output +roots. Choosing another installation silently can inventory or upload unrelated +files while reporting the wrong version. + +## Decision + +- Discover modern `comfyui-desktop-2`, `Comfy Desktop`, and supported legacy + records. Keep each registry's model-root provenance with its installation; + explicit caller/test registry overrides remain isolated. +- Without running-server evidence, describe selection as a registry-derived + candidate and expose its selection reason. Do not claim it identifies the + running process. +- Server launch metadata is not evidence of a shared filesystem, even for a + loopback endpoint (which may be a forwarder). Before using its paths to select + a local Desktop installation or read local configurations/interpreters/roots, + require caller-established direct-endpoint and local-process provenance. Bind + the request to its resolved address, bypass proxies, refuse redirects, match + the address-specific socket owner across the request using PID/create time, + and corroborate the actual Python script/argv/cwd. On Linux, require the same + mount namespace and process root as the CLI; inability to read that evidence + leaves provenance unknown. The pure discovery API defaults provenance to + unknown. Remote, forwarded, container, inaccessible or ambiguous endpoints + retain their reported catalog/metadata but require explicit local roots. +- With verified shared-filesystem provenance, require one recorded existing + installation to match its absolute code/data path or the full resolved generated + config path: that record's owning registry directory plus + `instance-model-paths/.yaml`. A copied filename/stem is insufficient; + retain per-record ownership across coexisting registries and reject path + separators and Windows drive/stream separators in IDs used for config identity. This preserves bundled/shared-code + discovery without conflating registries. Internal ownership adds no public + output fields. Zero or conflicting matches leave selection unresolved instead of combining + unrelated installations. +- Derive effective code/data/model/input/output roots from that selected process. + Resolve its model-path configuration and retain external paths explicitly. + Report the running version when supplied. The output root is the explicit + launch path or that process's data/output default, with its source recorded. +- Relative data/input/output paths cannot be resolved without the process's cwd: + retain uncertainty rather than anchoring them to the agent's cwd. Relative or + unreadable model config paths remain diagnostic evidence, never a claim that + all required model folders were found. +- Surface missing directories with existence flags and warnings. Discovery is + read-only: it creates no default workspace, installs nothing and grants no + permission to inspect/upload every file under a shared root. +- Optional which/env discovery fields remain additive. Runtime launch reporting + contains known path flags only, not arbitrary argv values or credentials. + File-upload scope and approvals belong to the calling operation; discovering + an output directory does not authorize uploading its whole contents. + +## Alternatives considered + +Selecting the newest registry entry alone is insufficient when a caller has +actual process evidence. Combining every existing install/model directory hides +identity errors and expands scope. Guessing relative paths from the CLI's cwd +can point at unrelated files. These approaches are rejected even when their +paths happen to exist. + +## Consequences + +Discovery can support both installed Desktop generations while callers retain +explicit path/selection provenance. Ambiguous, stale or relative process metadata +can require a user's verified path/cwd instead of automatic continuation. +Registry layouts and server metadata remain external compatibility surfaces; +unknown/malformed records are diagnostics rather than evidence of availability. +An interpreter is not inferred solely from a remembered data directory when +verified instance/process information is available. + +## Validation + +`test_desktop_install.py` covers registry isolation, actual process matching, +model-config roots, explicit/default input/output paths, relative-cwd ambiguity +and serialization. `test_which_desktop.py`, workspace-manager and Manager GUI +tests cover public reporting, missing roots and warning compatibility. Run those +tests with the worktree's package first on `PYTHONPATH`, plus Ruff lint/format, +`python scripts/check_adrs.py` and its native validator tests. + +## Revisit triggers + +Reopen if one running process resolves to another installation, if an unresolved +relative path is reported as verified, if server metadata bypasses direct local +process/filesystem proof, if shared folders lose provenance, or if +new Desktop layouts/launch flags require an additional documented discovery +source. A change that allows discovery to mutate installations or grants upload +permission requires a separate decision. diff --git a/tests/comfy_cli/command/test_assets_library.py b/tests/comfy_cli/command/test_assets_library.py index 718655009..6874443ab 100644 --- a/tests/comfy_cli/command/test_assets_library.py +++ b/tests/comfy_cli/command/test_assets_library.py @@ -48,8 +48,22 @@ def reset_singleton(): reset_renderer_for_testing() +@pytest.fixture(scope="module") +def root_cli_ready(): + """Load the actual CLI before a test's target fake can bind into lazy modules.""" + from click import Context + from typer.main import get_command + + from comfy_cli.cmdline import app as root_app + + root = get_command(root_app) + with Context(root) as context: + for name in root.list_commands(context): + root.get_command(context, name) + + @pytest.fixture -def cloud_target(monkeypatch: pytest.MonkeyPatch): +def cloud_target(monkeypatch: pytest.MonkeyPatch, root_cli_ready): from comfy_cli.target import Target fake = Target( diff --git a/tests/comfy_cli/command/test_manager_gui.py b/tests/comfy_cli/command/test_manager_gui.py index a84532090..1ed8e2403 100644 --- a/tests/comfy_cli/command/test_manager_gui.py +++ b/tests/comfy_cli/command/test_manager_gui.py @@ -834,11 +834,12 @@ def test_fill_print_table_disable_mode(self, mock_resolve, mock_workspace_config result = ws.fill_print_table() - assert len(result) == 3 + assert len(result) == 4 assert result[0][0] == "Current selected workspace" assert result[1][0] == "Manager" assert "Disabled" in result[1][1] assert result[2][0] == "UV Compile Default" + assert result[3] == ("Warning", "Workspace directory does not exist: /fake/workspace") @patch("comfy_cli.command.custom_nodes.cm_cli_util.resolve_manager_gui_mode", return_value="enable-gui") def test_fill_print_table_enable_gui_mode(self, mock_resolve, mock_workspace_config_manager): @@ -1056,9 +1057,19 @@ def test_fill_data_keeps_existing_fields(self): with self._env(configured_mode=None, has_cm_cli=True, has_legacy_clone=False) as ws: data = ws.fill_data() - assert set(data) == {"path", "type", "manager_mode", "manager_detected", "uv_compile_default"} + assert set(data) == { + "path", + "type", + "manager_mode", + "manager_detected", + "uv_compile_default", + "exists", + "warnings", + } assert data["path"] == "/fake/workspace" assert data["uv_compile_default"] is False + assert data["exists"] is False + assert data["warnings"][0]["code"] == "workspace_not_found" def test_fill_print_table_reports_legacy_clone(self): """The table view matches the JSON view for the legacy-clone case.""" diff --git a/tests/comfy_cli/command/test_run.py b/tests/comfy_cli/command/test_run.py index 9731c0233..3af335823 100644 --- a/tests/comfy_cli/command/test_run.py +++ b/tests/comfy_cli/command/test_run.py @@ -2363,14 +2363,29 @@ def test_markup_in_node_name_does_not_crash_confirm(self, monkeypatch): class TestExecuteUiWorkflow: + @pytest.fixture(autouse=True) + def local_preflight_catalog(self, monkeypatch): + """Validate against the complete conversion fixture without a live server.""" + from copy import deepcopy + + monkeypatch.setattr("comfy_cli.command.run._fetch_object_info", lambda *a, **k: deepcopy(self.OBJECT_INFO)) + + def unexpected_catalog_request(*args, **kwargs): + pytest.fail("unexpected real catalog request; mock the specific object_info transport") + + monkeypatch.setattr("comfy_cli.http._PLAIN_OPENER.open", unexpected_catalog_request) + monkeypatch.setattr("comfy_cli.cql.engine._load_from_target", unexpected_catalog_request) + + # The conversion success fixture must also be an executable graph: + # PreviewImage consumes IMAGE, not an EmptyLatentImage's LATENT output. UI = { "nodes": [ { "id": 1, - "type": "EmptyLatentImage", + "type": "EmptyImage", "inputs": [], - "outputs": [{"name": "LATENT", "type": "LATENT", "links": [10]}], - "widgets_values": [512, 512, 1], + "outputs": [{"name": "IMAGE", "type": "IMAGE", "links": [10]}], + "widgets_values": [512, 512, 1, 0], "mode": 0, }, { @@ -2384,19 +2399,20 @@ class TestExecuteUiWorkflow: "links": [[10, 1, 0, 2, 0, "IMAGE"]], } OBJECT_INFO = { - "EmptyLatentImage": { + "EmptyImage": { "input": { "required": { "width": ["INT", {"default": 512}], "height": ["INT", {"default": 512}], "batch_size": ["INT", {"default": 1}], + "color": ["INT", {"default": 0}], } }, - "input_order": {"required": ["width", "height", "batch_size"]}, - "output": ["LATENT"], - "output_name": ["LATENT"], + "input_order": {"required": ["width", "height", "batch_size", "color"]}, + "output": ["IMAGE"], + "output_name": ["IMAGE"], "output_node": False, - "display_name": "Empty Latent Image", + "display_name": "Empty Image", }, "PreviewImage": { "input": {"required": {"images": ["IMAGE"]}}, @@ -2435,7 +2451,7 @@ def test_ui_workflow_is_converted_then_executed(self, ui_workflow_file): assert mock_fetch.call_args.args == ("127.0.0.1", 8188, 30) api_workflow = MockExec.call_args.args[0] assert set(api_workflow) == {"1", "2"} - assert api_workflow["1"]["class_type"] == "EmptyLatentImage" + assert api_workflow["1"]["class_type"] == "EmptyImage" assert api_workflow["2"]["inputs"]["images"] == ["1", 0] mock_exec.queue.assert_called_once() diff --git a/tests/comfy_cli/command/test_run_json.py b/tests/comfy_cli/command/test_run_json.py index a6ba3f478..eca122763 100644 --- a/tests/comfy_cli/command/test_run_json.py +++ b/tests/comfy_cli/command/test_run_json.py @@ -52,13 +52,30 @@ def ndjson_renderer(): reset_renderer_for_testing() +@pytest.fixture(autouse=True) +def local_preflight_catalog(monkeypatch): + """Keep event/queue tests independent of any real server on localhost. + + Validation still runs against complete schemas. Tests for conversion HTTP + and deliberately invalid catalogs override their specific boundary below. + """ + from copy import deepcopy + + monkeypatch.setattr("comfy_cli.command.run._fetch_object_info", lambda *a, **k: deepcopy(OBJECT_INFO)) + + def unexpected_catalog_request(*args, **kwargs): + pytest.fail("unexpected real catalog request; mock the specific object_info transport") + + monkeypatch.setattr("comfy_cli.http._PLAIN_OPENER.open", unexpected_catalog_request) + + @pytest.fixture def simple_workflow(): return { "1": { - "class_type": "EmptyLatentImage", - "inputs": {"width": 64, "height": 64, "batch_size": 1}, - "_meta": {"title": "Latent"}, + "class_type": "EmptyImage", + "inputs": {"width": 64, "height": 64, "batch_size": 1, "color": 0}, + "_meta": {"title": "Image"}, }, "2": { "class_type": "SaveImage", @@ -524,8 +541,8 @@ def test_queued_nodes_manifest_from_workflow(self, workflow_file, capsys, simple nodes = queued["nodes"] assert len(nodes) == 2 by_id = {n["node_id"]: n for n in nodes} - assert by_id["1"]["class_type"] == "EmptyLatentImage" - assert by_id["1"]["title"] == "Latent" # _meta.title wins + assert by_id["1"]["class_type"] == "EmptyImage" + assert by_id["1"]["title"] == "Image" # _meta.title wins assert by_id["2"]["class_type"] == "SaveImage" assert by_id["2"]["title"] == "Save" @@ -621,7 +638,7 @@ def test_execution_error(self, workflow_file, capsys): "data": { "prompt_id": "p", "node_id": "1", - "node_type": "EmptyLatentImage", + "node_type": "EmptyImage", "exception_type": "RuntimeError", "exception_message": "boom", "traceback": [' File "x.py"\n', " raise RuntimeError\n"], @@ -635,12 +652,12 @@ def test_execution_error(self, workflow_file, capsys): assert any(e["type"] == "execution_error" for e in _events(lines)) env = _envelope(lines) assert env["error"]["code"] == "execution_error" - assert env["error"]["message"] == "EmptyLatentImage (node 1): boom" + assert env["error"]["message"] == "EmptyImage (node 1): boom" details = env["error"]["details"] assert details["node_id"] == "1" - assert details["class_type"] == "EmptyLatentImage" + assert details["class_type"] == "EmptyImage" assert details["exception_type"] == "RuntimeError" - assert details["title"] == "Latent" # from _meta.title + assert details["title"] == "Image" # from _meta.title # The envelope carries only the traceback tail; the full traceback # stays on the execution_error event. assert isinstance(details["traceback_tail"], list) @@ -658,7 +675,7 @@ def test_execution_error_node_id_coerced_to_str(self, workflow_file, capsys): "data": { "prompt_id": "p", "node_id": 7, - "node_type": "EmptyLatentImage", + "node_type": "EmptyImage", "exception_type": "RuntimeError", "exception_message": "boom", "traceback": [], @@ -797,8 +814,8 @@ def test_node_ids_coerced_to_str(self, simple_workflow, capsys): assert isinstance(ev["node"], str), f"{ev['type']} node is {type(ev['node']).__name__}" def test_title_falls_back_to_class_type(self): - ex = _make_workflow_execution({"1": {"class_type": "EmptyLatentImage", "inputs": {}}}) - assert ex.get_node_title("1") == "EmptyLatentImage" + ex = _make_workflow_execution({"1": {"class_type": "EmptyImage", "inputs": {}}}) + assert ex.get_node_title("1") == "EmptyImage" def test_title_falls_back_to_node_id_for_unknown(self): ex = _make_workflow_execution({}) @@ -809,10 +826,10 @@ def test_title_falls_back_to_node_id_for_unknown(self): "nodes": [ { "id": 1, - "type": "EmptyLatentImage", + "type": "EmptyImage", "inputs": [], - "outputs": [{"name": "LATENT", "type": "LATENT", "links": [10]}], - "widgets_values": [64, 64, 1], + "outputs": [{"name": "IMAGE", "type": "IMAGE", "links": [10]}], + "widgets_values": [64, 64, 1, 0], "mode": 0, }, { @@ -827,17 +844,26 @@ def test_title_falls_back_to_node_id_for_unknown(self): } OBJECT_INFO = { - "EmptyLatentImage": { + "EmptyImage": { "input": { "required": { "width": ["INT", {"default": 512}], "height": ["INT", {"default": 512}], "batch_size": ["INT", {"default": 1}], + "color": ["INT", {"default": 0}], } }, - "input_order": {"required": ["width", "height", "batch_size"]}, + "input_order": {"required": ["width", "height", "batch_size", "color"]}, + "output": ["IMAGE"], + "output_name": ["IMAGE"], "output_node": False, - "display_name": "Empty Latent Image", + "display_name": "Empty Image", + }, + "SaveImage": { + "input": {"required": {"filename_prefix": ["STRING", {"default": "ComfyUI"}], "images": ["IMAGE"]}}, + "input_order": {"required": ["filename_prefix", "images"]}, + "output": [], + "output_node": True, }, "PreviewImage": { "input": {"required": {"images": ["IMAGE"]}}, @@ -970,7 +996,7 @@ def test_api_input_emits_prompt_preview_before_queued(self, workflow_file, capsy assert types[0] == "prompt_preview" assert "queued" in types assert types.index("prompt_preview") < types.index("queued") - assert _events(lines)[0]["prompt"]["1"]["class_type"] == "EmptyLatentImage" + assert _events(lines)[0]["prompt"]["1"]["class_type"] == "EmptyImage" def test_ui_input_emits_converted_then_prompt_preview_then_queued(self, ui_workflow_file, capsys): with ( @@ -1035,7 +1061,7 @@ def test_api_input_emits_prompt_preview_and_envelope_only(self, workflow_file, c assert [e["type"] for e in _events(lines)] == ["prompt_preview"] preview = _events(lines)[0] assert preview["schema"] == "event/1" - assert preview["prompt"]["1"]["class_type"] == "EmptyLatentImage" + assert preview["prompt"]["1"]["class_type"] == "EmptyImage" env = _envelope(lines) assert env["ok"] is True assert env["data"]["status"] == "preview" @@ -1092,7 +1118,7 @@ def test_print_prompt_text_mode_pretty_prints_json(self, workflow_file, capsys): out, _err = capsys.readouterr() parsed = json.loads(out) assert "1" in parsed - assert parsed["1"]["class_type"] == "EmptyLatentImage" + assert parsed["1"]["class_type"] == "EmptyImage" def test_print_prompt_does_not_post_when_workflow_invalid(self, capsys): # Pre-flight failures (workflow_not_found, workflow_not_api_format) @@ -1240,10 +1266,10 @@ def test_execution_cached_event_shape(self, workflow_file, capsys): cached_events = [e for e in _events(lines) if e["type"] == "execution_cached"] assert len(cached_events) == 2 - # Node 1 has _meta.title="Latent"; class_type=EmptyLatentImage + # Node 1 has _meta.title="Image"; class_type=EmptyImage n1 = next(e for e in cached_events if e["node"] == "1") - assert n1["class_type"] == "EmptyLatentImage" - assert n1["title"] == "Latent" + assert n1["class_type"] == "EmptyImage" + assert n1["title"] == "Image" # Node 2 has _meta.title="Save"; class_type=SaveImage n2 = next(e for e in cached_events if e["node"] == "2") assert n2["class_type"] == "SaveImage" @@ -1380,9 +1406,9 @@ class TestErrorPathCoverage: def _make_workflow(self): return { "1": { - "class_type": "EmptyLatentImage", - "inputs": {"width": 64, "height": 64, "batch_size": 1}, - "_meta": {"title": "Latent"}, + "class_type": "EmptyImage", + "inputs": {"width": 64, "height": 64, "batch_size": 1, "color": 0}, + "_meta": {"title": "Image"}, }, "2": { "class_type": "SaveImage", @@ -1399,10 +1425,10 @@ def test_object_info_timeout_routes_to_connection_error(self, capsys): "nodes": [ { "id": 1, - "type": "EmptyLatentImage", + "type": "EmptyImage", "inputs": [], "outputs": [], - "widgets_values": [64, 64, 1], + "widgets_values": [64, 64, 1, 0], "mode": 0, } ], @@ -1414,7 +1440,7 @@ def test_object_info_timeout_routes_to_connection_error(self, capsys): try: with ( patch("comfy_cli.command.run.check_comfy_server_running", return_value=True), - patch("comfy_cli.http._AUTHED_OPENER.open", side_effect=TimeoutError("timed out")), + patch("comfy_cli.http._PLAIN_OPENER.open", side_effect=TimeoutError("timed out")), ): lines, exit_code = _run_execute_capture(path, capsys) assert _envelope(lines)["error"]["code"] == "connection_error" @@ -1427,10 +1453,10 @@ def test_object_info_non_json_body_routes_to_object_info_unavailable(self, capsy "nodes": [ { "id": 1, - "type": "EmptyLatentImage", + "type": "EmptyImage", "inputs": [], "outputs": [], - "widgets_values": [64, 64, 1], + "widgets_values": [64, 64, 1, 0], "mode": 0, } ], @@ -1876,7 +1902,7 @@ def test_api_workflow_async_stream_matches_documented_archetype( assert isinstance(queued["client_id"], str) and queued["client_id"] assert queued["validation_warnings"] == [] assert queued["nodes"] == [ - {"node_id": "1", "class_type": "EmptyLatentImage", "title": "Latent"}, + {"node_id": "1", "class_type": "EmptyImage", "title": "Image"}, {"node_id": "2", "class_type": "SaveImage", "title": "Save"}, ] assert queued["base_url"] == "https://api.comfy.org" diff --git a/tests/comfy_cli/command/test_run_prompt.py b/tests/comfy_cli/command/test_run_prompt.py index c67139558..da6f3c557 100644 --- a/tests/comfy_cli/command/test_run_prompt.py +++ b/tests/comfy_cli/command/test_run_prompt.py @@ -9,6 +9,8 @@ from __future__ import annotations +import json +from pathlib import Path from unittest.mock import MagicMock, patch import pytest @@ -32,11 +34,15 @@ class TestExecuteSubmitsPreloadedGraph: """`preloaded` short-circuits file loading; the in-memory graph is what reaches the submit path (WorkflowExecution).""" + @pytest.fixture(autouse=True) + def preloaded_catalog(self): + """Validate the injected graph against a frozen catalog, without a server.""" + catalog = json.loads((Path(__file__).resolve().parents[1] / "fixtures/sd15_object_info.json").read_text()) + with patch("comfy_cli.command.run._fetch_object_info", return_value=catalog): + yield + def test_preloaded_graph_is_submitted(self): - injected = { - "6": {"class_type": "CLIPTextEncode", "inputs": {"text": "a red fox in snow"}}, - "9": {"class_type": "SaveImage", "inputs": {"images": ["8", 0]}}, - } + injected = build_default_workflow(prompt="a red fox in snow") with ( patch("comfy_cli.command.run.check_comfy_server_running", return_value=True), patch("comfy_cli.command.run.ExecutionProgress"), @@ -63,7 +69,7 @@ def test_preloaded_graph_is_submitted(self): def test_preloaded_skips_file_loading(self): """A non-existent path never triggers workflow_not_found when preloaded.""" - injected = {"9": {"class_type": "SaveImage", "inputs": {}}} + injected = build_default_workflow(prompt="fox") with ( patch("comfy_cli.command.run.check_comfy_server_running", return_value=True), patch("comfy_cli.command.run.ExecutionProgress"), diff --git a/tests/comfy_cli/conftest.py b/tests/comfy_cli/conftest.py index 522edcf38..c16a41126 100644 --- a/tests/comfy_cli/conftest.py +++ b/tests/comfy_cli/conftest.py @@ -169,3 +169,83 @@ def test_my_pretty_thing(pretty_no_stdout): "that to be empty (all output goes to stderr in pretty mode):\n" f" stdout = {captured.out!r}\n" ) + + +@pytest.fixture(autouse=True) +def _isolate_comfy_desktop(tmp_path, monkeypatch): + """Point Comfy Desktop detection at an empty per-test dir. + + ``comfy which`` / ``comfy env`` (and ``comfy build init``) read Desktop's + ``installations.json`` and ``settings.json`` from the real app-data dir. + On a developer machine with Desktop installed, every test touching those + commands would otherwise see that machine's installs. A test that wants a + Desktop install builds one with the ``comfy_desktop`` fixture. + """ + from comfy_cli import desktop_install + + monkeypatch.setattr(desktop_install, "desktop_app_data_dir", lambda: tmp_path / "no-comfy-desktop") + monkeypatch.setattr(desktop_install, "legacy_config_dir", lambda: None) + yield + + +@pytest.fixture +def comfy_desktop(tmp_path, monkeypatch): + """A Comfy Desktop 2 install laid out the way the bug report found it. + + An install adopted from Desktop 1: the ComfyUI checkout under + ``/ComfyUI``, the data (models, custom_nodes, venv) in the + Desktop 1 base path (``config.json`` → ``basePath``, copied into the + record as ``adoptedBaseDir``), and a shared model library listed in + ``settings.json`` → ``modelsDirs`` alongside the data dir's own + ``models/``. Detection is pointed at it; the returned dict names each part. + """ + import json + + from comfy_cli import desktop_install + + install_path = tmp_path / "ComfyUI-Installs" / "ComfyUI" + code = install_path / "ComfyUI" + code.mkdir(parents=True) + (code / "main.py").write_text("") + data = tmp_path / "Documents" / "ComfyUI" + for sub in ("models/checkpoints", "custom_nodes", "user"): + (data / sub).mkdir(parents=True) + python = data / ".venv" / "bin" / "python3" + python.parent.mkdir(parents=True) + python.write_text("") + shared = tmp_path / "ComfyUI-Shared" / "models" + shared.mkdir(parents=True) + legacy = tmp_path / "Application Support" / "ComfyUI" + legacy.mkdir(parents=True) + (legacy / "config.json").write_text(json.dumps({"basePath": str(data)})) + record = { + "id": "inst-adopted", + "name": "ComfyUI", + "sourceId": "standalone", + "installPath": str(install_path), + "adopted": True, + "adoptedBaseDir": str(data), + "adoptedPythonPath": str(python), + "comfyVersion": {"commit": "b53f77a7", "baseTag": "v0.34.2", "commitsAhead": 0}, + "useSharedModels": True, + "status": "installed", + "lastLaunchedAt": 1792188627164, + } + cloud = {"id": "inst-cloud", "name": "Comfy Cloud", "sourceId": "cloud", "remoteUrl": "https://cloud.comfy.org/"} + app = tmp_path / "Application Support" / "Comfy Desktop" + app.mkdir(parents=True) + (app / "installations.json").write_text(json.dumps([record, cloud])) + (app / "settings.json").write_text(json.dumps({"modelsDirs": [str(shared), str(data / "models")]})) + + monkeypatch.setattr(desktop_install, "desktop_app_data_dir", lambda: app) + monkeypatch.setattr(desktop_install, "legacy_config_dir", lambda: legacy) + return { + "app": app, + "legacy": legacy, + "install_path": install_path, + "code": code, + "data": data, + "python": python, + "shared": shared, + "record": record, + } diff --git a/tests/comfy_cli/output/test_envelope_schemas.py b/tests/comfy_cli/output/test_envelope_schemas.py index bcd387916..ae22891d8 100644 --- a/tests/comfy_cli/output/test_envelope_schemas.py +++ b/tests/comfy_cli/output/test_envelope_schemas.py @@ -119,10 +119,16 @@ def test_env_json_validates(): assert envelope["ok"] is True -def test_which_json_validates(): - envelope = _run_cli(["--json", "which"]) +def test_which_json_validates(tmp_path): + workspace = tmp_path / "ComfyUI" + workspace.mkdir() + (workspace / "main.py").write_text("") + envelope = _run_cli(["--json", "--workspace", str(workspace), "which"]) _validator_for("envelope.json").validate(envelope) + assert envelope["ok"] is True _validator_for("which.json").validate(envelope["data"]) + assert envelope["data"]["workspace_path"] == str(workspace) + assert envelope["data"]["exists"] is True def test_help_json_validates(): diff --git a/tests/comfy_cli/output/test_error_envelope_where.py b/tests/comfy_cli/output/test_error_envelope_where.py index e84ae3a06..ed0ae837f 100644 --- a/tests/comfy_cli/output/test_error_envelope_where.py +++ b/tests/comfy_cli/output/test_error_envelope_where.py @@ -324,15 +324,19 @@ def _workflow(tmp_path): def test_cloud(self, tmp_path): err = LoadError("no object_info", details={"hint": "sign in"}) - with patch("comfy_cli.cql.engine.Graph.load", side_effect=err): + with patch("comfy_cli.cql.loader.resilient_load_object_info", side_effect=err) as load: env = _run(["--json", "validate", "--workflow", self._workflow(tmp_path), "--where", "cloud"]) + load.assert_called_once() + assert load.call_args.kwargs["mode"] == "cloud" assert env["error"]["code"] == "cql_no_graph" assert env["where"] == "cloud" def test_local(self, tmp_path): err = LoadError("no object_info", details={"hint": "comfy launch"}) - with patch("comfy_cli.cql.engine.Graph.load", side_effect=err): + with patch("comfy_cli.cql.loader.resilient_load_object_info", side_effect=err) as load: env = _run(["--json", "validate", "--workflow", self._workflow(tmp_path), "--where", "local"]) + load.assert_called_once() + assert load.call_args.kwargs["mode"] == "local" assert env["error"]["code"] == "cql_no_graph" assert env["where"] == "local" diff --git a/tests/comfy_cli/test_desktop_install.py b/tests/comfy_cli/test_desktop_install.py new file mode 100644 index 000000000..3d069bd29 --- /dev/null +++ b/tests/comfy_cli/test_desktop_install.py @@ -0,0 +1,615 @@ +"""Comfy Desktop 2 detection from the records Desktop keeps on disk. + +Every test builds its own fixture layout under ``tmp_path``; none reads the +machine's real Desktop files (the autouse ``_isolate_comfy_desktop`` fixture +points detection at an empty dir unless a test passes its own). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from comfy_cli import desktop_install +from comfy_cli.constants import OS + +# Bound at import, before the autouse isolation fixture replaces the module +# attributes, so the per-OS resolution itself can still be tested. +_real_app_data_dir = desktop_install.desktop_app_data_dir +_real_legacy_config_dir = desktop_install.legacy_config_dir + + +def _checkout(code_dir: Path, version: str | None = None) -> Path: + code_dir.mkdir(parents=True, exist_ok=True) + (code_dir / "main.py").write_text("") + if version: + (code_dir / "comfyui_version.py").write_text(f'__version__ = "{version}"\n') + return code_dir + + +def _venv(root: Path) -> Path: + py = root / ".venv" / "bin" / "python3" + py.parent.mkdir(parents=True, exist_ok=True) + py.write_text("") + return py + + +def _write_desktop(app_dir: Path, installs: list, *, models_dirs: list[str] | None = None) -> Path: + app_dir.mkdir(parents=True, exist_ok=True) + (app_dir / "installations.json").write_text(json.dumps(installs)) + (app_dir / "settings.json").write_text(json.dumps({"modelsDirs": models_dirs or []})) + return app_dir + + +def test_no_installations_file_means_no_desktop(tmp_path): + assert desktop_install.detect(tmp_path / "Comfy Desktop", tmp_path / "legacy") is None + + +def test_adopted_install_reports_its_split_layout(comfy_desktop): + layout = comfy_desktop + + found = desktop_install.detect(layout["app"], layout["legacy"]) + + assert found is not None + install = found.selected + assert install is not None + assert install.install_id == "inst-adopted" + assert install.code_dir == str(layout["code"]) + assert install.data_dir == str(layout["data"]) + assert install.python == str(layout["python"]) + assert install.comfyui_version == "v0.34.2" + assert install.comfyui_commit == "b53f77a7" + # The data dir's own models/ is listed once even though settings.json also + # names it; the shared root follows. + assert [(r.path, r.source) for r in install.model_roots] == [ + (str(layout["data"] / "models"), "data"), + (str(layout["shared"]), "shared"), + ] + assert all(r.exists for r in install.model_roots) + # The Comfy Cloud entry has no local files and is not an install here. + assert [i.install_id for i in found.installs] == ["inst-adopted"] + assert found.selected_reason == "the only Comfy Desktop install with a ComfyUI checkout on disk" + assert found.problems == () + + +def test_to_dict_puts_the_selected_install_at_the_top(comfy_desktop): + layout = comfy_desktop + + block = desktop_install.detect(layout["app"], layout["legacy"]).to_dict() + + assert block["code_dir"] == str(layout["code"]) + assert block["data_dir"] == str(layout["data"]) + assert block["custom_nodes_dir"] == str(layout["data"] / "custom_nodes") + assert block["python"] == str(layout["python"]) + assert block["comfyui_version"] == "v0.34.2" + assert [r["path"] for r in block["model_roots"]] == [str(layout["data"] / "models"), str(layout["shared"])] + assert block["installs"] == [ + { + "install_id": "inst-adopted", + "name": "ComfyUI", + "code_dir": str(layout["code"]), + "data_dir": str(layout["data"]), + "comfyui_version": "v0.34.2", + "last_launched_at": "2026-10-16T22:10:27Z", + "status": "installed", + "exists": True, + "selected": True, + } + ] + assert block["app_data_dir"] == str(layout["app"]) + + +def test_standalone_install_keeps_data_beside_the_code(tmp_path): + install_path = tmp_path / "ComfyUI-Installs" / "Fresh" + code = _checkout(install_path / "ComfyUI") + python = _venv(code) + app = _write_desktop( + tmp_path / "Comfy Desktop", + [{"id": "inst-fresh", "installPath": str(install_path), "comfyVersion": {"baseTag": "v0.41.1"}}], + ) + + install = desktop_install.detect(app, tmp_path / "legacy").selected + + assert install.code_dir == str(code) + assert install.data_dir == str(code) + assert install.python == str(python) + assert [r.path for r in install.model_roots] == [str(code / "models")] + + +def test_most_recently_launched_install_is_selected_and_the_reason_says_so(tmp_path): + older = tmp_path / "Installs" / "Old" + newer = tmp_path / "Installs" / "New" + _checkout(older / "ComfyUI") + _checkout(newer / "ComfyUI") + app = _write_desktop( + tmp_path / "Comfy Desktop", + [ + {"id": "old", "installPath": str(older), "lastLaunchedAt": 1_700_000_000_000}, + {"id": "new", "installPath": str(newer), "lastLaunchedAt": 1_790_000_000_000}, + {"id": "never", "installPath": str(tmp_path / "Installs" / "Gone")}, + ], + ) + + found = desktop_install.detect(app, tmp_path / "legacy") + + assert found.selected.install_id == "new" + assert "most recently launched of 2 Comfy Desktop installs" in found.selected_reason + assert [i.install_id for i in found.installs] == ["old", "new", "never"] + rows = {row["install_id"]: row for row in found.to_dict()["installs"]} + assert rows["new"]["selected"] is True + assert rows["old"]["selected"] is False + # An install whose checkout is gone is listed but never selected. + assert rows["never"]["exists"] is False + assert rows["never"]["selected"] is False + + +def test_no_launch_history_picks_the_first_listed_install(tmp_path): + first = tmp_path / "Installs" / "A" + second = tmp_path / "Installs" / "B" + _checkout(first / "ComfyUI") + _checkout(second / "ComfyUI") + app = _write_desktop( + tmp_path / "Comfy Desktop", + [{"id": "a", "installPath": str(first)}, {"id": "b", "installPath": str(second)}], + ) + + found = desktop_install.detect(app, tmp_path / "legacy") + + assert found.selected.install_id == "a" + assert "none has been launched" in found.selected_reason + + +def test_no_install_with_a_checkout_selects_nothing(tmp_path): + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "gone", "installPath": str(tmp_path / "missing")}]) + + found = desktop_install.detect(app, tmp_path / "legacy") + + assert found.selected is None + assert found.selected_reason is None + assert [i.install_id for i in found.installs] == ["gone"] + + +def test_opting_out_of_shared_models_drops_the_shared_roots(tmp_path): + install_path = tmp_path / "Installs" / "Isolated" + code = _checkout(install_path / "ComfyUI") + extra = tmp_path / "extra-models" + app = _write_desktop( + tmp_path / "Comfy Desktop", + [{"id": "iso", "installPath": str(install_path), "useSharedModels": False, "modelDirs": [str(extra)]}], + models_dirs=[str(tmp_path / "shared")], + ) + + install = desktop_install.detect(app, tmp_path / "legacy").selected + + assert [(r.path, r.source, r.exists) for r in install.model_roots] == [ + (str(code / "models"), "data", False), + (str(extra), "install", False), + ] + + +def test_adopted_record_without_a_base_dir_falls_back_to_desktop_1_config(comfy_desktop): + layout = comfy_desktop + record = dict(layout["record"]) + del record["adoptedBaseDir"] + del record["adoptedPythonPath"] + _write_desktop(layout["app"], [record]) + + install = desktop_install.detect(layout["app"], layout["legacy"]).selected + + assert install.data_dir == str(layout["data"]) + assert install.python == str(layout["python"]) + + +def test_version_falls_back_to_the_checkout_marker(tmp_path): + install_path = tmp_path / "Installs" / "Marker" + _checkout(install_path / "ComfyUI", version="0.41.2") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "m", "installPath": str(install_path)}]) + + install = desktop_install.detect(app, tmp_path / "legacy").selected + + assert install.comfyui_version == "v0.41.2" + + +def test_unreadable_installations_file_is_a_problem_not_a_crash(tmp_path): + app = tmp_path / "Comfy Desktop" + app.mkdir() + (app / "installations.json").write_text("{not json") + + found = desktop_install.detect(app, tmp_path / "legacy") + + assert found is not None + assert found.selected is None + assert len(found.problems) == 1 + assert "installations.json" in found.problems[0] + + +def test_unreadable_settings_file_still_detects_the_install(comfy_desktop): + layout = comfy_desktop + (layout["app"] / "settings.json").write_text("[broken") + + found = desktop_install.detect(layout["app"], layout["legacy"]) + + assert found.selected.install_id == "inst-adopted" + assert [r.source for r in found.selected.model_roots] == ["data"] + assert len(found.problems) == 1 + assert "settings.json" in found.problems[0] + + +def test_install_for_dir_matches_the_code_dir_and_the_data_dir(comfy_desktop, tmp_path): + layout = comfy_desktop + found = desktop_install.detect(layout["app"], layout["legacy"]) + + assert desktop_install.install_for_dir(layout["data"], found).install_id == "inst-adopted" + assert desktop_install.install_for_dir(layout["code"], found).install_id == "inst-adopted" + assert desktop_install.install_for_dir(tmp_path, found) is None + + +@pytest.mark.parametrize( + ("os_value", "env", "expected"), + [ + (OS.MACOS, {}, Path.home() / "Library" / "Application Support" / "Comfy Desktop"), + (OS.WINDOWS, {"APPDATA": "/appdata"}, Path("/appdata") / "Comfy Desktop"), + (OS.LINUX, {"XDG_DATA_HOME": "/xdg"}, Path("/xdg") / "Comfy Desktop"), + ], +) +def test_app_data_dir_per_os(monkeypatch, os_value, env, expected): + monkeypatch.setattr(desktop_install, "get_os", lambda: os_value) + for key in ("APPDATA", "XDG_DATA_HOME"): + monkeypatch.delenv(key, raising=False) + for key, value in env.items(): + monkeypatch.setenv(key, value) + + assert _real_app_data_dir() == expected + + +def test_legacy_config_dir_per_os(monkeypatch): + monkeypatch.setattr(desktop_install, "get_os", lambda: OS.MACOS) + assert _real_legacy_config_dir() == Path.home() / "Library" / "Application Support" / "ComfyUI" + monkeypatch.setattr(desktop_install, "get_os", lambda: OS.LINUX) + assert _real_legacy_config_dir() is None + + +@pytest.mark.parametrize("timestamp", [1e30, float("inf")]) +def test_invalid_launch_timestamp_does_not_break_discovery(tmp_path, timestamp): + install_path = tmp_path / "Installs" / "Valid" + _checkout(install_path / "ComfyUI") + app = _write_desktop( + tmp_path / "Comfy Desktop", + [{"id": "valid", "installPath": str(install_path), "lastLaunchedAt": timestamp}], + ) + + found = desktop_install.detect(app, tmp_path / "legacy") + + assert found.to_dict()["installs"][0]["last_launched_at"] is None + assert found.selected.install_id == "valid" + + +def test_adopted_install_with_unreadable_legacy_config_marks_data_root_uncertain(tmp_path): + code = _checkout(tmp_path / "checkout") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "adopted", "installPath": str(code), "adopted": True}]) + legacy = tmp_path / "legacy" + legacy.mkdir() + (legacy / "config.json").write_text("{broken") + + found = desktop_install.detect(app, legacy) + + assert any("config.json" in problem for problem in found.problems) + assert any("unverified" in problem and "data" in problem for problem in found.problems) + + +def test_detect_scans_modern_userdata_and_keeps_each_registry_roots(tmp_path, monkeypatch): + old = tmp_path / "Comfy Desktop" + modern = tmp_path / "comfyui-desktop-2" + for app, name in ((old, "old"), (modern, "modern")): + code = _checkout(tmp_path / name / "ComfyUI") + _write_desktop( + app, [{"id": name, "installPath": str(code.parent)}], models_dirs=[str(tmp_path / name / "shared")] + ) + monkeypatch.setattr(desktop_install, "desktop_app_data_dir", lambda: old) + found = desktop_install.detect() + assert {install.install_id for install in found.installs} == {"old", "modern"} + modern_install = next(install for install in found.installs if install.install_id == "modern") + assert str(tmp_path / "modern" / "shared") in [root.path for root in modern_install.model_roots] + assert str(tmp_path / "old" / "shared") not in [root.path for root in modern_install.model_roots] + + +def test_running_server_selects_matching_instance_instead_of_latest(tmp_path): + records = [] + for name, launched in (("running", 1), ("latest", 2)): + code = _checkout(tmp_path / name / "ComfyUI") + records.append({"id": name, "installPath": str(code.parent), "lastLaunchedAt": launched}) + app = _write_desktop(tmp_path / "Comfy Desktop", records) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": [str(tmp_path / "running" / "ComfyUI" / "main.py")]}}, + server_filesystem_verified=True, + ) + assert found.selected.install_id == "running" + assert "running server" in found.selected_reason + + +def test_server_instance_config_matches_install_and_applies_effective_paths(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "inst-live", "installPath": str(code.parent)}]) + config = app / "instance-model-paths" / "inst-live.yaml" + config.parent.mkdir() + root = tmp_path / "effective-models" + config.write_text(f"live:\n base_path: {root}\n checkpoints: checkpoints\n") + data = tmp_path / "effective-data" + inputs = tmp_path / "private-inputs" + stats = { + "system": { + "argv": [ + "main.py", + "--extra-model-paths-config", + str(config), + "--base-directory", + str(data), + "--input-directory", + str(inputs), + ] + } + } + found = desktop_install.detect(app, server_stats=stats, server_filesystem_verified=True) + assert found.selected.install_id == "inst-live" + assert found.selected.data_dir == str(data) + assert str(root) in [root.path for root in found.selected.model_roots] + assert found.to_dict()["input_dir"] == str(inputs) + + +def test_server_that_does_not_match_records_is_not_silently_assumed(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "candidate", "installPath": str(code.parent)}]) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": [str(tmp_path / "different" / "main.py")]}}, + server_filesystem_verified=True, + ) + assert found.selected is None + assert any("running server" in problem for problem in found.problems) + + +def test_server_model_configs_replace_stale_shared_settings(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop( + tmp_path / "Comfy Desktop", + [{"id": "live", "installPath": str(code.parent)}], + models_dirs=[str(tmp_path / "stale")], + ) + first, second = tmp_path / "one.yaml", tmp_path / "two.yaml" + first.write_text(f"one:\n base_path: {tmp_path / 'models-one'}\n checkpoints: checkpoints\n") + second.write_text(f"two:\n base_path: {tmp_path / 'models-two'}\n loras: loras\n") + stats = { + "system": { + "argv": [str(code / "main.py"), "--extra-model-paths-config", str(first), str(second)], + "comfyui_version": "0.99.0", + } + } + found = desktop_install.detect(app, server_stats=stats, server_filesystem_verified=True) + paths = [root.path for root in found.selected.model_roots] + assert str(tmp_path / "stale") not in paths + assert str(tmp_path / "models-one") in paths + assert str(tmp_path / "models-two") in paths + assert found.selected.comfyui_version == "v0.99.0" + + +def test_relative_server_data_paths_are_unverified(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "live", "installPath": str(code.parent)}]) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": [str(code / "main.py"), "--base-directory", "relative-data"]}}, + server_filesystem_verified=True, + ) + assert found.selected is None + assert any("relative" in problem for problem in found.problems) + + +def test_server_config_includes_absolute_paths_outside_base_and_no_base_sections(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "live", "installPath": str(code.parent)}]) + config = tmp_path / "models.yaml" + outside = tmp_path / "private-loras" + config.write_text( + f"one:\n base_path: {tmp_path / 'models'}\n loras: {outside}\ntwo:\n checkpoints: relative-checkpoints\n" + ) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": [str(code / "main.py"), "--extra-model-paths-config", str(config)]}}, + server_filesystem_verified=True, + ) + paths = [root.path for root in found.selected.model_roots] + assert str(outside) in paths + assert str(tmp_path / "relative-checkpoints") in paths + assert not found.problems + + +@pytest.mark.parametrize("explicit", [True, False]) +def test_running_server_output_directory_is_reported_with_source(tmp_path, explicit): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "live", "installPath": str(code.parent)}]) + output = tmp_path / "actual-output" if explicit else code / "output" + argv = [str(code / "main.py")] + if explicit: + argv += ["--output-directory", str(output)] + found = desktop_install.detect(app, server_stats={"system": {"argv": argv}}, server_filesystem_verified=True) + assert found.to_dict()["output_dir"] == str(output) + assert found.to_dict()["output_dir_source"] == ("server_argv" if explicit else "server_default") + + +def test_relative_output_directory_requires_process_cwd_verification(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "live", "installPath": str(code.parent)}]) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": [str(code / "main.py"), "--output-directory", "relative-output"]}}, + server_filesystem_verified=True, + ) + assert found.selected is None + assert "output_dir" not in found.to_dict() + + +@pytest.mark.parametrize("override_data", [False, True], ids=["registry-data", "process-data"]) +@pytest.mark.parametrize( + "process_python", ["missing", "none", "empty", "wrong-type", "missing-file", "directory", "valid-file"] +) +def test_server_interpreter_uses_only_a_verified_process_path(tmp_path, override_data, process_python): + code = _checkout(tmp_path / "install" / "ComfyUI") + registry_python = _venv(code) + app = _write_desktop(tmp_path / "Comfy Desktop", [{"id": "live", "installPath": str(code.parent)}]) + legacy = tmp_path / "legacy" + assert desktop_install.detect(app, legacy).selected.python == str(registry_python) + + data = tmp_path / "process-data" if override_data else code + if override_data: + _venv(data) # Even an existing data-directory interpreter is not process evidence. + runtime_python = tmp_path / "process-python" + runtime_python.write_text("") + system = {"argv": [str(code / "main.py"), "--base-directory", str(data)]} + if process_python != "missing": + system["python"] = { + "none": None, + "empty": "", + "wrong-type": 42, + "missing-file": str(tmp_path / "missing-python"), + "directory": str(data), + "valid-file": str(runtime_python), + }[process_python] + + found = desktop_install.detect(app, legacy, server_stats={"system": system}, server_filesystem_verified=True) + + expected_python = str(runtime_python) if process_python == "valid-file" else None + assert found.selected.data_dir == str(data) + assert found.selected.python == expected_python + assert found.to_dict()["python"] == expected_python + + +@pytest.mark.parametrize("match", ["code-path", "config-stem"]) +def test_server_paths_without_filesystem_provenance_do_not_select_local_install(tmp_path, monkeypatch, match): + code = _checkout(tmp_path / "unrelated-local" / "ComfyUI") + _venv(code) + app = _write_desktop(tmp_path / "registry", [{"id": "collision", "installPath": str(code.parent)}]) + config = app / "collision.yaml" + config.write_text("private:\n base_path: /unrelated-local-models\n checkpoints: checkpoints\n") + argv = [str(code / "main.py")] if match == "code-path" else ["/remote/main.py"] + argv += ["--extra-model-paths-config", str(config)] + original = Path.read_text + + def read(path, *args, **kwargs): + assert path != config, "unverified server metadata must not read a local model config" + return original(path, *args, **kwargs) + + monkeypatch.setattr(Path, "read_text", read) + found = desktop_install.detect(app, server_stats={"system": {"argv": argv}}) + + assert found.selected is None + block = found.to_dict() + assert block["python"] is None + assert block["model_roots"] == [] + assert "input_dir" not in block and "output_dir" not in block + assert any("filesystem" in problem for problem in found.problems) + + +def test_verified_local_server_cannot_select_desktop_by_copied_config_stem(tmp_path, monkeypatch): + code = _checkout(tmp_path / "unrelated-desktop" / "ComfyUI") + app = _write_desktop(tmp_path / "registry", [{"id": "collision", "installPath": str(code.parent)}]) + copied = tmp_path / "outside-registry" / "collision.yaml" + copied.parent.mkdir() + copied.write_text("private:\n base_path: /unrelated-private\n loras: loras\n") + original = Path.read_text + + def read(path, *args, **kwargs): + assert path != copied, "a copied config name is not Desktop launch identity" + return original(path, *args, **kwargs) + + monkeypatch.setattr(Path, "read_text", read) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": ["/other/main.py", "--extra-model-paths-config", str(copied)]}}, + server_filesystem_verified=True, + ) + assert found.selected is None + assert found.to_dict()["model_roots"] == [] + + +@pytest.mark.parametrize("selected_registry", [0, 1]) +def test_generated_config_identity_keeps_owning_registry_with_duplicate_ids(tmp_path, monkeypatch, selected_registry): + apps = [] + codes = [] + for name in ("comfyui-desktop-2", "Comfy Desktop"): + code = _checkout(tmp_path / name / "install" / "ComfyUI") + app = _write_desktop(tmp_path / name / "registry", [{"id": "same-id", "installPath": str(code.parent)}]) + config = app / "instance-model-paths" / "same-id.yaml" + config.parent.mkdir() + config.write_text("{}") + apps.append(app) + codes.append(code) + monkeypatch.setattr(desktop_install, "app_data_dirs", lambda: tuple(apps)) + config = apps[selected_registry] / "instance-model-paths" / "same-id.yaml" + found = desktop_install.detect( + server_stats={"system": {"argv": ["/shared/bundled/main.py", "--extra-model-paths-config", str(config)]}}, + server_filesystem_verified=True, + ) + assert found.selected.code_dir == str(codes[selected_registry]) + assert [i.summary(selected=i is found.selected)["selected"] for i in found.installs] == [ + selected_registry == 0, + selected_registry == 1, + ] + block = found.to_dict() + assert "registry_dir" not in block + assert all("registry_dir" not in item for item in block["installs"]) + + +@pytest.mark.parametrize( + "install_id", ["../collision", "nested/id", "nested\\id", "/absolute", "C:collision", "null\x00id"] +) +def test_config_identity_rejects_path_separators_in_record_id(tmp_path, install_id): + if ":" in install_id: + from pathlib import PureWindowsPath + + # A drive-relative component discards the owning registry on Windows. + expected = PureWindowsPath("D:/registry/instance-model-paths") / f"{install_id}.yaml" + assert expected.drive == "C:" and not expected.is_absolute() + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "registry", [{"id": install_id, "installPath": str(code.parent)}]) + config = app / "instance-model-paths" / f"{install_id}.yaml" + found = desktop_install.detect( + app, + server_stats={"system": {"argv": ["/other/main.py", "--extra-model-paths-config", str(config)]}}, + server_filesystem_verified=True, + ) + assert found.selected is None + + +def test_unknown_server_provenance_clears_previously_derived_directories(tmp_path): + from dataclasses import replace + + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "registry", [{"id": "live", "installPath": str(code.parent)}]) + found = replace( + desktop_install.detect(app), + input_dir="/previous/input", + output_dir="/previous/output", + output_dir_source="server_argv", + ) + unresolved = desktop_install._for_server(found, {"system": {"argv": [str(code / "main.py")]}}) + assert unresolved.selected is None + assert unresolved.input_dir is None and unresolved.output_dir is None and unresolved.output_dir_source is None + + +def test_generated_config_identity_accepts_verified_file_alias(tmp_path): + code = _checkout(tmp_path / "install" / "ComfyUI") + app = _write_desktop(tmp_path / "registry", [{"id": "live", "installPath": str(code.parent)}]) + config = app / "instance-model-paths" / "live.yaml" + config.parent.mkdir() + config.write_text("{}") + alias = tmp_path / "verified-config-alias.yaml" + alias.symlink_to(config) + found = desktop_install.detect( + app, + server_stats={"system": {"argv": ["/shared/main.py", "--extra-model-paths-config", str(alias)]}}, + server_filesystem_verified=True, + ) + assert found.selected.install_id == "live" diff --git a/tests/comfy_cli/test_http.py b/tests/comfy_cli/test_http.py index 703199d85..20adb7027 100644 --- a/tests/comfy_cli/test_http.py +++ b/tests/comfy_cli/test_http.py @@ -819,7 +819,6 @@ def test_an_unloadable_supplement_falls_through_to_the_platform_roots(tmp_path, monkeypatch.setitem(sys.modules, "certifi", types.SimpleNamespace(where=lambda: str(broken))) real = ssl.create_default_context - populated = len(pathlib.Path(certifi.where()).read_text().split("-----BEGIN CERTIFICATE-----")) - 1 def platform_with_roots(*args, **kwargs): context = real(*args, **kwargs) @@ -827,13 +826,15 @@ def platform_with_roots(*args, **kwargs): context.load_verify_locations(cafile=certifi.where()) return context + expected_roots = set(platform_with_roots().get_ca_certs(binary_form=True)) + assert expected_roots, "the platform fixture must contain trust roots" monkeypatch.setattr(ssl, "create_default_context", platform_with_roots) # When context = http_mod.ssl_context() # Then - assert context.cert_store_stats()["x509_ca"] == populated, ( + assert set(context.get_ca_certs(binary_form=True)) == expected_roots, ( "the platform roots must survive a supplement that would not load" ) diff --git a/tests/comfy_cli/test_which_desktop.py b/tests/comfy_cli/test_which_desktop.py new file mode 100644 index 000000000..24a24ee59 --- /dev/null +++ b/tests/comfy_cli/test_which_desktop.py @@ -0,0 +1,304 @@ +"""`comfy which` / `comfy env` on a machine where the workspace is missing or is Comfy Desktop's. + +The default workspace comfy-cli falls back to (``~/Documents/comfy/ComfyUI``) +does not exist on a Desktop-only machine. These commands used to report it with +``ok: true``; now a missing path is an error (`which`) or a flagged warning +(`env`), and a Desktop 2 install is reported with its real split layout. +""" + +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path + +import jsonschema +import pytest +from typer.testing import CliRunner + +from comfy_cli import desktop_install, utils +from comfy_cli.cmdline import app, workspace_manager +from comfy_cli.env_checker import EnvChecker + +SCHEMAS_DIR = Path(__file__).resolve().parents[2] / "comfy_cli" / "schemas" + + +def _schema(name: str) -> dict: + return json.loads((SCHEMAS_DIR / name).read_text()) + + +@pytest.fixture +def fallback_workspace(tmp_path, monkeypatch) -> Path: + """comfy-cli's own default workspace, pointed into tmp and not created. + + The cwd is moved to an empty dir so the cwd auto-detect step finds nothing. + """ + fallback = tmp_path / "Documents" / "comfy" / "ComfyUI" + monkeypatch.setattr(utils, "get_not_user_set_default_workspace", lambda: str(fallback)) + elsewhere = tmp_path / "elsewhere" + elsewhere.mkdir() + monkeypatch.chdir(elsewhere) + return fallback + + +def _invoke(*args: str): + result = CliRunner().invoke(app, list(args)) + lines = [line for line in result.stdout.splitlines() if line.strip()] + envelope = json.loads(lines[-1]) if lines and lines[-1].startswith("{") else None + return result, envelope + + +def test_which_keeps_missing_selected_workspace_separate_from_desktop_candidate(comfy_desktop, fallback_workspace): + result, envelope = _invoke("--json", "which") + + assert result.exit_code == 1, result.output + assert envelope["ok"] is False + assert envelope["error"]["code"] == "workspace_not_found" + details = envelope["error"]["details"] + assert details["workspace_type"] == workspace_manager.workspace_type.value == "default" + assert details["path"] == workspace_manager.workspace_path == str(fallback_workspace) + assert not Path(workspace_manager.workspace_path).is_dir() + desktop = details["desktop"] + assert desktop["code_dir"] == str(comfy_desktop["code"]) + assert desktop["data_dir"] == str(comfy_desktop["data"]) + assert desktop["python"] == str(comfy_desktop["python"]) + assert desktop["comfyui_version"] == "v0.34.2" + assert [root["path"] for root in desktop["model_roots"]] == [ + str(comfy_desktop["data"] / "models"), + str(comfy_desktop["shared"]), + ] + assert desktop["selected_reason"] + assert [row["install_id"] for row in desktop["installs"]] == ["inst-adopted"] + + +def test_which_lists_every_desktop_install_and_says_which_it_picked(comfy_desktop, fallback_workspace, tmp_path): + other = tmp_path / "ComfyUI-Installs" / "Test" + (other / "ComfyUI").mkdir(parents=True) + (other / "ComfyUI" / "main.py").write_text("") + records = [ + {"id": "inst-test", "name": "Test", "installPath": str(other), "lastLaunchedAt": 1_700_000_000_000}, + comfy_desktop["record"], + ] + (comfy_desktop["app"] / "installations.json").write_text(json.dumps(records)) + + _, envelope = _invoke("--json", "which") + + desktop = envelope["error"]["details"]["desktop"] + assert desktop["install_id"] == "inst-adopted" + assert "most recently launched of 2" in desktop["selected_reason"] + assert {row["install_id"]: row["selected"] for row in desktop["installs"]} == { + "inst-test": False, + "inst-adopted": True, + } + + +def test_which_errors_when_the_default_workspace_does_not_exist(fallback_workspace): + result, envelope = _invoke("--json", "which") + + assert result.exit_code == 1 + assert envelope["ok"] is False + assert envelope["error"]["code"] == "workspace_not_found" + assert envelope["error"]["details"]["path"] == str(fallback_workspace) + assert envelope["error"]["details"]["workspace_type"] == "default" + assert envelope["error"]["hint"] + + +def test_which_errors_for_a_missing_specified_workspace_even_with_desktop_installed( + comfy_desktop, fallback_workspace, tmp_path +): + missing = tmp_path / "typo" / "ComfyUI" + + result, envelope = _invoke("--json", "--workspace", str(missing), "which") + + assert result.exit_code == 1 + assert envelope["error"]["code"] == "workspace_not_found" + assert envelope["error"]["details"]["path"] == str(missing) + assert envelope["error"]["details"]["workspace_type"] == "specified" + + +def test_which_keeps_an_installed_default_workspace_over_desktop(comfy_desktop, fallback_workspace): + fallback_workspace.mkdir(parents=True) + + result, envelope = _invoke("--json", "which") + + assert result.exit_code == 0, result.output + assert envelope["data"]["workspace_path"] == str(fallback_workspace) + assert envelope["data"]["workspace_type"] == "default" + assert envelope["data"]["exists"] is True + assert "desktop" not in envelope["data"] + + +def test_which_names_unreadable_desktop_records_in_the_error(comfy_desktop, fallback_workspace): + (comfy_desktop["app"] / "installations.json").write_text("{not json") + + result, envelope = _invoke("--json", "which") + + assert result.exit_code == 1 + assert envelope["error"]["code"] == "workspace_not_found" + problems = envelope["error"]["details"]["desktop"]["problems"] + assert len(problems) == 1 + assert "installations.json" in problems[0] + + +def test_which_warns_when_desktop_settings_are_unreadable(comfy_desktop, fallback_workspace): + (comfy_desktop["app"] / "settings.json").write_text("[broken") + + result, envelope = _invoke("--json", "which") + + assert result.exit_code == 1, result.output + assert envelope["error"]["code"] == "workspace_not_found" + desktop = envelope["error"]["details"]["desktop"] + assert any("settings.json" in problem for problem in desktop["problems"]) + + +def test_pretty_which_shows_the_desktop_data_dir(comfy_desktop, fallback_workspace): + result = CliRunner().invoke( + app, + ["--workspace", str(comfy_desktop["code"]), "which"], + env={"COMFY_OUTPUT": "pretty", "COLUMNS": "400"}, + ) + + assert result.exit_code == 0, result.output + assert str(comfy_desktop["data"]) in result.output + assert "Desktop data" in result.output + assert "specified" in result.output + + +def test_env_reports_the_desktop_install(comfy_desktop, fallback_workspace): + result, envelope = _invoke("--json", "env") + + assert result.exit_code == 0, result.output + data = envelope["data"] + jsonschema.validate(data, _schema("env.json")) + workspace = data["workspace"] + assert workspace["type"] == workspace_manager.workspace_type.value == "default" + assert workspace["path"] == workspace_manager.workspace_path == str(fallback_workspace) + assert workspace["exists"] is False + assert workspace["desktop"]["data_dir"] == str(comfy_desktop["data"]) + assert [w["code"] for w in data["warnings"]] == ["workspace_not_found"] + + +def test_env_flags_a_missing_workspace_instead_of_a_silent_default(fallback_workspace): + result, envelope = _invoke("--json", "env") + + assert result.exit_code == 0, result.output + data = envelope["data"] + jsonschema.validate(data, _schema("env.json")) + assert data["workspace"]["path"] == str(fallback_workspace) + assert data["workspace"]["exists"] is False + assert [w["code"] for w in data["warnings"]] == ["workspace_not_found"] + assert str(fallback_workspace) in data["warnings"][0]["message"] + + +@pytest.mark.parametrize("part", ["code", "data"]) +def test_which_enriches_an_explicit_desktop_workspace(comfy_desktop, fallback_workspace, part): + result, envelope = _invoke("--json", "--workspace", str(comfy_desktop[part]), "which") + + assert result.exit_code == 0, result.output + jsonschema.validate(envelope["data"], _schema("which.json")) + assert envelope["data"]["workspace_type"] == "specified" + assert envelope["data"]["workspace_path"] == str(comfy_desktop[part]) + assert envelope["data"]["desktop"]["data_dir"] == str(comfy_desktop["data"]) + assert envelope["data"]["desktop"]["code_dir"] == str(comfy_desktop["code"]) + + +def test_env_warns_when_desktop_settings_are_unreadable(comfy_desktop, fallback_workspace): + (comfy_desktop["app"] / "settings.json").write_text("[broken") + + result, envelope = _invoke("--json", "env") + + assert result.exit_code == 0, result.output + assert [w["code"] for w in envelope["data"]["warnings"]] == ["workspace_not_found", "desktop_config_unreadable"] + + +def test_env_renders_hostile_discovery_values_literally_without_changing_json( + comfy_desktop, fallback_workspace, monkeypatch +): + raw = "[/]literal[red]x[/red]\x1b[2J\x1b]0;osc-title\x07\x9b2J\r\u202e世界" + visible = "[/]literal[red]x[/red]\u202e世界" + selected_path = str(fallback_workspace.parent / raw) + monkeypatch.setattr(utils, "get_not_user_set_default_workspace", lambda: selected_path) + found = desktop_install.detect() + candidate = replace( + found.selected, + code_dir=f"code:{raw}", + data_dir=f"data:{raw}", + model_roots=(desktop_install.ModelRoot(f"model:{raw}", "data", True),), + ) + found = replace(found, installs=(candidate,), selected=candidate, problems=(f"warning:{raw}",)) + monkeypatch.setattr(desktop_install, "detect", lambda: found) + monkeypatch.setattr(EnvChecker(), "fill_print_table", lambda: []) + + json_result, envelope = _invoke("--json", "env") + assert json_result.exit_code == 0, json_result.output + workspace = envelope["data"]["workspace"] + assert workspace["path"] == selected_path + assert workspace["desktop"]["code_dir"] == f"code:{raw}" + assert workspace["desktop"]["data_dir"] == f"data:{raw}" + assert workspace["desktop"]["model_roots"][0]["path"] == f"model:{raw}" + assert any(warning["message"] == f"warning:{raw}" for warning in envelope["data"]["warnings"]) + + result = CliRunner().invoke(app, ["env"], env={"COMFY_OUTPUT": "pretty", "COLUMNS": "600", "NO_COLOR": "1"}) + + assert result.exit_code == 0, result.output + assert str(fallback_workspace.parent / visible) in result.output + assert f"code:{visible}" in result.output + assert f"data:{visible}" in result.output + assert f"model:{visible}" in result.output + assert f"warning:{visible}" in result.output + assert "\x1b" not in result.output and "\x9b" not in result.output + assert "\x07" not in result.output and "\r" not in result.output + assert "osc-title" not in result.output + assert "\u202e世界" in result.output + + +def test_which_renders_hostile_desktop_fields_literally_without_changing_json( + comfy_desktop, fallback_workspace, monkeypatch +): + raw = "[/]literal[red]x[/red]\x1b[2J\x1b]0;osc-title\x07\x9b2J\r\u202e世界" + visible = "[/]literal[red]x[/red]\u202e世界" + code = fallback_workspace.parent / "selected-comfy" + desktop_code = fallback_workspace.parent / f"code:{raw}" + code.mkdir(parents=True) + (code / "main.py").write_text("") + found = desktop_install.detect() + candidate = replace( + found.selected, + code_dir=str(desktop_code), + data_dir=f"data:{raw}", + python=f"python:{raw}", + model_roots=(desktop_install.ModelRoot(f"model:{raw}", "data", True),), + ) + found = replace( + found, installs=(candidate,), selected=candidate, selected_reason=f"reason:{raw}", problems=(f"warning:{raw}",) + ) + monkeypatch.setattr(desktop_install, "detect", lambda: found) + monkeypatch.setattr(desktop_install, "install_for_dir", lambda path, detected: {str(code): candidate}.get(path)) + monkeypatch.setattr("comfy_cli.cmdline.env_checker.check_comfy_server_running", lambda **kwargs: False) + + json_result, envelope = _invoke("--json", "--workspace", str(code), "which") + assert json_result.exit_code == 0, json_result.output + data = envelope["data"] + assert data["workspace_path"] == str(code) + assert data["desktop"]["code_dir"] == str(desktop_code) + assert data["desktop"]["data_dir"] == f"data:{raw}" + assert data["desktop"]["python"] == f"python:{raw}" + assert data["desktop"]["model_roots"][0]["path"] == f"model:{raw}" + assert data["desktop"]["selected_reason"] == f"reason:{raw}" + assert data["warnings"][0]["message"] == f"warning:{raw}" + + result = CliRunner().invoke( + app, ["--workspace", str(code), "which"], env={"COMFY_OUTPUT": "pretty", "COLUMNS": "600", "NO_COLOR": "1"} + ) + + assert result.exit_code == 0, result.output + assert str(fallback_workspace.parent / f"code:{visible}") in result.output + assert f"data:{visible}" in result.output + assert f"python:{visible}" in result.output + assert f"model:{visible}" in result.output + assert f"reason:{visible}" in result.output + assert f"warning:{visible}" in result.output + assert "\x1b" not in result.output and "\x9b" not in result.output + assert "\x07" not in result.output and "\r" not in result.output + assert "osc-title" not in result.output + assert "\u202e世界" in result.output diff --git a/tests/comfy_cli/test_workspace_manager.py b/tests/comfy_cli/test_workspace_manager.py index b5bd3aa67..49a615089 100644 --- a/tests/comfy_cli/test_workspace_manager.py +++ b/tests/comfy_cli/test_workspace_manager.py @@ -721,17 +721,19 @@ def test_no_workspace_probe(self, command): result = self._invoke(["--json", *command]) assert not isinstance(result.exception, AssertionError), result.exception - def test_which_still_resolves_the_workspace(self): + def test_which_still_resolves_the_workspace(self, tmp_path): from typer.testing import CliRunner import comfy_cli.workspace_manager as workspace_manager_module from comfy_cli.cmdline import app - with patch.object(workspace_manager_module, "check_comfy_repo", return_value=(True, "/sentinel/ComfyUI")): + workspace = tmp_path / "ComfyUI" + workspace.mkdir() + with patch.object(workspace_manager_module, "check_comfy_repo", return_value=(True, str(workspace))): result = CliRunner().invoke(app, ["--json", "which"]) assert result.exit_code == 0, result.output - assert "/sentinel/ComfyUI" in result.output + assert str(workspace) in result.output def test_gitpython_is_not_imported(self): import subprocess