diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ade79741..0084d81b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,23 @@ history. ### Fixed +- `comfy update` no longer dies with a `FileNotFoundError` traceback when the + configured workspace directory does not exist (never installed, or deleted). + It now fails with a `not_in_workspace` error that points at `comfy install`, + including when `--recent` cannot resolve a workspace, keeping the resolver's + exit status. + +- `comfy update cli` works for a `uv tool install` of comfy-cli. Those envs ship + without pip, so the old `python -m pip install -U` always failed; it now runs + `uv tool upgrade comfy-cli`, and any installer failure is reported as an + `update_cli_failed` error rather than a traceback. The upgrade targets the + running installation's tool directory even when `UV_TOOL_DIR` is absent or + selects a different directory in the current shell; when `uv` is not on PATH, + the hint names that directory too. The installer still runs without a time + limit, since stopping it partway can leave comfy-cli half-replaced. An exact uv version pin + is preserved and reported with manual reinstall guidance. Installer diagnostics + stay on stderr in JSON/NDJSON modes, which end with one success or error envelope. + - UI→API conversion expands a `COMFY_DYNAMICCOMBO_V3` selector's sub-inputs in the order the workflow was SAVED with, when the saved graph records one, instead of the option's current order. An option that has since gained a diff --git a/comfy_cli/cmdline.py b/comfy_cli/cmdline.py index 7f71001ec..1583cd4cc 100644 --- a/comfy_cli/cmdline.py +++ b/comfy_cli/cmdline.py @@ -1759,13 +1759,44 @@ def update( raise typer.Exit(code=1) if "cli" == target: - from comfy_cli.update import upgrade_cli + from comfy_cli.update import UpgradeUnavailable, upgrade_cli rprint("Updating comfy-cli...") - upgrade_cli() + try: + upgrade_cli() + except UpgradeUnavailable as e: + get_renderer().error(code="update_cli_failed", message=str(e), hint=e.hint) + raise typer.Exit(code=1) from e + except subprocess.CalledProcessError as e: + get_renderer().error( + code="update_cli_failed", + message=f"`{' '.join(map(str, e.cmd))}` failed with exit code {e.returncode}.", + hint="see the installer output above; re-running `comfy update cli` is safe", + details={"returncode": e.returncode}, + ) + raise typer.Exit(code=1) from e + except OSError as e: + get_renderer().error( + code="update_cli_failed", + message=f"Could not start the comfy-cli installer: {e}", + hint="check the installer executable and its permissions, then re-run `comfy update cli`", + ) + raise typer.Exit(code=1) from e + get_renderer().emit({"target": "cli"}, command="update") return - comfy_path = workspace_manager.workspace_path + try: + comfy_path = workspace_manager.workspace_path + except typer.Exit as error: + if target != "comfy": + raise + get_renderer().error( + code="not_in_workspace", + message="ComfyUI workspace could not be resolved.", + hint="run `comfy install`, or pass `--workspace` to point at an existing install", + exit_code=error.exit_code, + ) + raise if "all" == target: # Without raise_on_error, execute_cm_cli swallows a cm-cli exit 1 and returns None, @@ -1798,10 +1829,20 @@ def update( ) raise typer.Exit(code=code) from e else: - rprint(f"Updating ComfyUI in {comfy_path}...") - if comfy_path is None: - rprint("ComfyUI path is not found.") + # The default workspace path comes from config and can name a directory that + # was never installed (or was deleted), so check existence, not just None. + if comfy_path is None or not os.path.isdir(comfy_path): + get_renderer().error( + code="not_in_workspace", + message=( + "ComfyUI workspace not found." + if comfy_path is None + else f"ComfyUI workspace not found: {comfy_path}" + ), + hint="run `comfy install`, or pass `--workspace` to point at an existing install", + ) raise typer.Exit(code=1) + rprint(f"Updating ComfyUI in {comfy_path}...") if version is not None: _switch_comfy_version(comfy_path, version, stash=not no_stash) else: diff --git a/comfy_cli/error_codes.py b/comfy_cli/error_codes.py index ff11c8db7..d402b1332 100644 --- a/comfy_cli/error_codes.py +++ b/comfy_cli/error_codes.py @@ -1257,6 +1257,15 @@ class ErrorCode: "CLI usage error).", "read the cm-cli output above for the failing pack, then re-run `comfy update all`", ), + ErrorCode( + "update_cli_failed", + "`comfy update cli` could not upgrade comfy-cli: either no usable installer was found " + "(a `uv tool` env without `uv` on PATH, or an env without pip), the uv receipt is unreadable " + "or pins the CLI to an exact version, or the installer could not start or exited non-zero. " + "`details.returncode` carries a non-zero exit status.", + "follow the error's hint; for a `uv tool` install, ensure `uv` is on PATH and use the stated " + "UV_TOOL_DIR; change an exact version pin only through an explicit reinstall", + ), ErrorCode( "version_switch_unknown_version", "`comfy update comfy --version X` could not resolve X to a ComfyUI tag; the workspace was left untouched.", diff --git a/comfy_cli/update.py b/comfy_cli/update.py index aecea53b7..aa9043001 100644 --- a/comfy_cli/update.py +++ b/comfy_cli/update.py @@ -1,3 +1,4 @@ +import importlib.util import json import logging import os @@ -9,6 +10,8 @@ import requests from packaging import version +from comfy_cli._safe_exec import resolve_binary + logger = logging.getLogger(__name__) UPDATE_CHECK_TTL_SECONDS = 24 * 60 * 60 @@ -39,10 +42,121 @@ def check_for_newer_pypi_version(package_name, current_version): return False, current_version +class UpgradeUnavailable(RuntimeError): + """The running installation cannot be upgraded automatically.""" + + def __init__(self, message: str, hint: str): + super().__init__(message) + self.hint = hint + + +def _check_uv_tool_pin(receipt: Path) -> None: + """Preserve exact primary-tool constraints rather than reporting a no-op upgrade.""" + from packaging.requirements import Requirement + from packaging.specifiers import SpecifierSet + from packaging.utils import canonicalize_name + from tomlkit import parse + from tomlkit.exceptions import ParseError + + tool_root = receipt.parent.parent + hint = ( + "Review the receipt. To change or remove a pin, explicitly reinstall using your chosen requirement " + "(for example `uv tool install --force comfy-cli` to remove it); " + f"first set UV_TOOL_DIR to {tool_root} to target this installation." + ) + pinned = False + try: + tool = parse(receipt.read_text(encoding="utf-8")).unwrap().get("tool") + if not isinstance(tool, dict): + raise ValueError("missing tool table") + for field in ("requirements", "constraints"): + rows = tool.get(field, []) + if not isinstance(rows, list): + raise ValueError("invalid requirement list") + for row in rows: + if isinstance(row, str): + requirement = Requirement(row) + name, specifiers = requirement.name, requirement.specifier + elif isinstance(row, dict): + name = row.get("name") + if not isinstance(name, str): + raise ValueError("missing requirement name") + parsed_name = Requirement(name) + if parsed_name.extras or parsed_name.url or parsed_name.specifier or parsed_name.marker: + raise ValueError("invalid package name") + if canonicalize_name(name) != "comfy-cli": + continue + specifier = row.get("specifier", "") + if not isinstance(specifier, str): + raise ValueError("invalid primary specifier") + specifiers = SpecifierSet(specifier) + else: + raise ValueError("invalid requirement row") + if canonicalize_name(name) == "comfy-cli" and any( + spec.operator == "===" or (spec.operator == "==" and not spec.version.endswith(".*")) + for spec in specifiers + ): + pinned = True + except (OSError, ValueError, ParseError) as error: + raise UpgradeUnavailable("The running uv tool receipt could not be read or understood.", hint=hint) from error + if pinned: + raise UpgradeUnavailable( + "The running comfy-cli installation has an exact uv version pin; this command will not remove it.", + hint=hint, + ) + + def upgrade_cli(): - """Upgrade the ``comfy-cli`` package itself via pip against the running - interpreter. Raises ``CalledProcessError`` if pip fails — fail fast.""" - subprocess.run([sys.executable, "-m", "pip", "install", "-U", "comfy-cli"], check=True) + """Upgrade the ``comfy-cli`` package itself in the environment it runs from. + + A ``uv tool install`` env ships without pip, so it is upgraded through + ``uv tool upgrade``; anything else goes through pip against the running + interpreter. Exact uv pins remain unchanged. Raises ``UpgradeUnavailable`` + for unusable installers or receipts, and propagates installer exit or start + failures to the command. + + Neither installer gets a deadline. Both replace the running installation's + files in place: pip uninstalls the old version before installing the new + one and restores it only from its own exception handler, which a killed + process never reaches. Stopping it partway can leave ``comfy`` itself + missing, so a slow upgrade is left to finish.""" + from comfy_cli.output import get_renderer + + installer_stdout = sys.stderr if get_renderer().is_json() else None + receipt = Path(sys.prefix) / "uv-receipt.toml" + if receipt.is_file(): + tool_root = Path(sys.prefix).parent + uv = resolve_binary("uv") + if uv is None: + raise UpgradeUnavailable( + "comfy-cli was installed with `uv tool`, but `uv` is not on PATH.", + hint=( + "run `uv tool upgrade comfy-cli` from a shell where uv is available; " + f"first set UV_TOOL_DIR to {tool_root} to target this installation" + ), + ) + _check_uv_tool_pin(receipt) + # Upgrade the running installation even if its original tool-dir override + # is absent now, or the current shell selects another tools directory. + installer_env = os.environ.copy() + installer_env["UV_TOOL_DIR"] = str(tool_root) + subprocess.run( + [uv, "tool", "upgrade", "comfy-cli"], + check=True, + env=installer_env, + stdout=installer_stdout, + ) + return + if importlib.util.find_spec("pip") is None: + raise UpgradeUnavailable( + f"pip is not installed in the comfy-cli environment ({sys.prefix}).", + hint="upgrade comfy-cli with the tool that installed it (e.g. `pipx upgrade comfy-cli`)", + ) + subprocess.run( + [sys.executable, "-m", "pip", "install", "-U", "comfy-cli"], + check=True, + stdout=installer_stdout, + ) def _read_fresh_cache(cache_file, now): diff --git a/tests/comfy_cli/command/test_update_missing_workspace.py b/tests/comfy_cli/command/test_update_missing_workspace.py new file mode 100644 index 000000000..2b8f72096 --- /dev/null +++ b/tests/comfy_cli/command/test_update_missing_workspace.py @@ -0,0 +1,261 @@ +"""Tests for ``comfy update`` when the ComfyUI workspace does not exist. + +The default workspace path is resolved from config even when nothing was ever +installed there, so ``workspace_path`` can be a string naming a missing +directory. ``update`` only guarded against ``None`` and then ``os.chdir``-ed +into the path, crashing with a raw ``FileNotFoundError`` traceback — no +envelope under ``--json``, no hint to run ``comfy install``. +""" + +from __future__ import annotations + +import json +import re +import subprocess +import sys +from importlib.machinery import ModuleSpec +from unittest.mock import patch + +import pytest +import typer +from typer.testing import CliRunner + +from comfy_cli import cmdline, constants +from comfy_cli.workspace_manager import WorkspaceType + +runner = CliRunner() + +SUBPROCESS_RUN = "comfy_cli.cmdline.subprocess.run" +SWITCH_VERSION = "comfy_cli.cmdline._switch_comfy_version" + + +def _strip_ansi(text: str) -> str: + return re.sub(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", "", text) + + +def _resolve_to(path): + # The root callback re-runs ``setup_workspace_manager``, which drops any + # value patched onto ``workspace_path``; pin the resolver underneath instead. + return patch.object(cmdline.workspace_manager, "get_workspace_path", return_value=(path, WorkspaceType.DEFAULT)) + + +@pytest.fixture +def missing_workspace(tmp_path): + path = str(tmp_path / "ComfyUI") + with _resolve_to(path): + yield path + + +class TestMissingWorkspace: + def test_missing_path_is_a_structured_error_in_json_mode(self, missing_workspace): + with patch(SUBPROCESS_RUN) as mock_run: + result = runner.invoke(cmdline.app, ["--json", "update"]) + + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["ok"] is False + assert envelope["error"]["code"] == "not_in_workspace" + assert missing_workspace in envelope["error"]["message"] + assert "comfy install" in envelope["error"]["hint"] + mock_run.assert_not_called() + + def test_missing_path_is_explained_in_pretty_mode(self, missing_workspace): + with patch(SUBPROCESS_RUN) as mock_run: + result = runner.invoke(cmdline.app, ["--no-json", "update", "comfy"]) + + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + assert "not_in_workspace" in _strip_ansi(result.stdout) + mock_run.assert_not_called() + + def test_missing_path_blocks_a_version_switch(self, missing_workspace): + with patch(SWITCH_VERSION) as mock_switch: + result = runner.invoke(cmdline.app, ["--json", "update", "comfy", "--version", "nightly"]) + + assert result.exit_code == 1 + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["error"]["code"] == "not_in_workspace" + mock_switch.assert_not_called() + + def test_unresolved_path_is_a_structured_error(self): + with _resolve_to(None): + result = runner.invoke(cmdline.app, ["--json", "update"]) + + assert result.exit_code == 1 + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["error"]["code"] == "not_in_workspace" + assert "comfy install" in envelope["error"]["hint"] + + +class TestRecentWorkspaceResolution: + @pytest.mark.parametrize("output_flag", ["--json", "--no-json"]) + @pytest.mark.parametrize("target_args", [[], ["comfy"], ["comfy", "--version", "nightly"]]) + def test_missing_recent_has_structured_comfy_failure(self, monkeypatch, output_flag, target_args): + manager_config = cmdline.workspace_manager.config_manager + original_get = manager_config.get + monkeypatch.setattr( + manager_config, + "get", + lambda key: None if key == constants.CONFIG_KEY_RECENT_WORKSPACE else original_get(key), + ) + with patch(SUBPROCESS_RUN) as installer, patch(SWITCH_VERSION) as switch: + result = runner.invoke(cmdline.app, [output_flag, "--recent", "update", *target_args]) + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + if output_flag == "--json": + lines = [line for line in result.stdout.splitlines() if line.strip()] + assert len(lines) == 1 + envelope = json.loads(lines[0]) + assert envelope["ok"] is False + assert envelope["error"]["code"] == "not_in_workspace" + assert "comfy install" in envelope["error"]["hint"] + else: + assert "not_in_workspace" in _strip_ansi(result.stdout) + installer.assert_not_called() + switch.assert_not_called() + + @pytest.mark.parametrize("exit_code", [1, 7]) + def test_comfy_resolution_keeps_resolver_exit_status(self, exit_code): + with ( + patch.object(cmdline.workspace_manager, "get_workspace_path", side_effect=typer.Exit(code=exit_code)), + patch(SUBPROCESS_RUN) as installer, + ): + result = runner.invoke(cmdline.app, ["--json", "update", "comfy"]) + assert result.exit_code == exit_code + lines = [line for line in result.stdout.splitlines() if line.strip()] + assert len(lines) == 1 + assert json.loads(lines[0])["error"]["code"] == "not_in_workspace" + installer.assert_not_called() + + @pytest.mark.parametrize("exit_code", [1, 7]) + def test_all_resolution_keeps_existing_exit_without_manager_execution(self, exit_code): + with ( + patch.object(cmdline.workspace_manager, "get_workspace_path", side_effect=typer.Exit(code=exit_code)), + patch("comfy_cli.command.custom_nodes.command.execute_cm_cli") as manager, + ): + result = runner.invoke(cmdline.app, ["--json", "update", "all"]) + assert result.exit_code == exit_code + assert "not_in_workspace" not in result.stdout + manager.assert_not_called() + + +class TestUpdateCliFailures: + """`comfy update cli` used to let installer failures escape as tracebacks.""" + + def test_unavailable_installer_is_a_structured_error(self): + from comfy_cli import update + + err = update.UpgradeUnavailable("no pip here", hint="run `uv tool upgrade comfy-cli`") + with patch("comfy_cli.update.upgrade_cli", side_effect=err): + result = runner.invoke(cmdline.app, ["--json", "update", "cli"]) + + assert result.exit_code == 1 + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["error"]["code"] == "update_cli_failed" + assert envelope["error"]["hint"] == "run `uv tool upgrade comfy-cli`" + + def test_failed_installer_is_a_structured_error(self): + err = subprocess.CalledProcessError(1, ["uv", "tool", "upgrade", "comfy-cli"]) + with patch("comfy_cli.update.upgrade_cli", side_effect=err): + result = runner.invoke(cmdline.app, ["--json", "update", "cli"]) + + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["error"]["code"] == "update_cli_failed" + assert envelope["error"]["details"]["returncode"] == 1 + + @pytest.mark.parametrize("output_flag", ["--json", "--no-json"]) + @pytest.mark.parametrize( + "installer_error", + [ + FileNotFoundError("installer disappeared"), + PermissionError("installer is not executable"), + ], + ids=["missing-installer", "installer-permissions"], + ) + def test_installer_start_failures_are_structured(self, installer_error, output_flag): + with patch("comfy_cli.update.upgrade_cli", side_effect=installer_error): + result = runner.invoke(cmdline.app, [output_flag, "update", "cli"]) + + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + if output_flag == "--json": + envelope = json.loads(result.stdout.strip().splitlines()[-1]) + assert envelope["error"]["code"] == "update_cli_failed" + assert envelope["error"]["hint"] + else: + assert "update_cli_failed" in _strip_ansi(result.stdout) + + +class TestUpdateCliInstallerOutput: + @pytest.mark.parametrize("installer", ["pip", "uv"]) + @pytest.mark.parametrize("output_flag", ["--json", "--json-stream", "--no-json"]) + @pytest.mark.parametrize("fails", [False, True]) + def test_installer_diagnostics_follow_output_mode(self, tmp_path, monkeypatch, installer, output_flag, fails): + from comfy_cli import update + + prefix = tmp_path / "tools" / "comfy-cli" + prefix.mkdir(parents=True) + if installer == "uv": + (prefix / "uv-receipt.toml").write_text('[tool]\nrequirements = [{ name = "comfy-cli" }]\n') + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + monkeypatch.setattr(update.importlib.util, "find_spec", lambda name: ModuleSpec("pip", loader=None)) + + def simulated_installer(argv, **kwargs): + print("installer diagnostic sentinel", file=kwargs.get("stdout") or sys.stdout) + if fails: + raise subprocess.CalledProcessError(3, argv) + return subprocess.CompletedProcess(argv, 0) + + monkeypatch.setattr(update.subprocess, "run", simulated_installer) + result = runner.invoke(cmdline.app, [output_flag, "update", "cli"]) + assert result.exit_code == (1 if fails else 0) + if output_flag == "--no-json": + assert "installer diagnostic sentinel" in result.stdout + assert "installer diagnostic sentinel" not in result.stderr + else: + assert "installer diagnostic sentinel" not in result.stdout + assert "installer diagnostic sentinel" in result.stderr + lines = [line for line in result.stdout.splitlines() if line.strip()] + assert len(lines) == 1 + envelope = json.loads(lines[0]) + assert envelope["type"] == "envelope" + assert envelope["ok"] is not fails + if fails: + assert envelope["error"]["code"] == "update_cli_failed" + assert envelope["error"]["details"]["returncode"] == 3 + else: + assert envelope["data"] == {"target": "cli"} + + +@pytest.mark.parametrize("output_flag", ["--json", "--json-stream", "--no-json"]) +def test_pinned_uv_receipt_is_a_structured_cli_failure(tmp_path, monkeypatch, output_flag): + from comfy_cli import update + + prefix = tmp_path / "custom tools" / "comfy-cli" + prefix.mkdir(parents=True) + path = prefix / "uv-receipt.toml" + receipt = '[tool]\nrequirements = [{ name = "comfy-cli", specifier = "==1.2.3" }]\n' + path.write_text(receipt) + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + with patch("comfy_cli.update.subprocess.run") as installer: + result = runner.invoke(cmdline.app, [output_flag, "update", "cli"]) + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + if output_flag == "--no-json": + assert "update_cli_failed" in _strip_ansi(result.stdout) + assert "reinstall" in _strip_ansi(result.stdout).lower() + else: + lines = [line for line in result.stdout.splitlines() if line.strip()] + assert len(lines) == 1 + error = json.loads(lines[0])["error"] + assert error["code"] == "update_cli_failed" + assert "reinstall" in error["hint"].lower() + assert str(prefix.parent) in error["hint"] + assert "UV_TOOL_DIR" in error["hint"] + assert path.read_text() == receipt + installer.assert_not_called() diff --git a/tests/comfy_cli/test_update.py b/tests/comfy_cli/test_update.py index 11010b1b1..567f441b7 100644 --- a/tests/comfy_cli/test_update.py +++ b/tests/comfy_cli/test_update.py @@ -1,5 +1,6 @@ import json import time +from importlib.machinery import ModuleSpec from unittest.mock import MagicMock, patch import pytest @@ -101,11 +102,88 @@ def test_corrupt_cache_does_not_raise(self, mock_check, tmp_path): class TestUpgradeCli: @patch("comfy_cli.update.subprocess.run") - def test_runs_pip_install_upgrade(self, mock_run): - upgrade_cli() + def test_runs_pip_install_upgrade(self, mock_run, tmp_path): + with ( + patch.object(update.sys, "prefix", str(tmp_path)), + patch("comfy_cli.update.importlib.util.find_spec", return_value=ModuleSpec("pip", loader=None)), + ): + upgrade_cli() args = mock_run.call_args[0][0] assert args[1:] == ["-m", "pip", "install", "-U", "comfy-cli"] assert mock_run.call_args[1]["check"] is True + assert "timeout" not in mock_run.call_args[1] + + @patch("comfy_cli.update.subprocess.run") + def test_uv_tool_install_upgrades_through_uv(self, mock_run, tmp_path): + """A `uv tool install` env has no pip, so `python -m pip` always fails there.""" + (tmp_path / "uv-receipt.toml").write_text("[tool]\n") + with ( + patch.object(update.sys, "prefix", str(tmp_path)), + patch("comfy_cli.update.resolve_binary", return_value="/opt/bin/uv"), + ): + upgrade_cli() + assert mock_run.call_args[0][0] == ["/opt/bin/uv", "tool", "upgrade", "comfy-cli"] + assert mock_run.call_args[1]["check"] is True + assert "timeout" not in mock_run.call_args[1] + + @pytest.mark.parametrize("ambient_tool_dir", [None, "other", "current"]) + @patch("comfy_cli.update.subprocess.run") + def test_uv_upgrade_targets_running_install_not_ambient_tool_dir( + self, mock_run, tmp_path, monkeypatch, ambient_tool_dir + ): + tool_root = tmp_path / "custom-tools" + prefix = tool_root / "comfy-cli" + prefix.mkdir(parents=True) + (prefix / "uv-receipt.toml").write_text("[tool]\n") + previous = ( + None + if ambient_tool_dir is None + else str(tool_root if ambient_tool_dir == "current" else tmp_path / "other-tools") + ) + if previous is None: + monkeypatch.delenv("UV_TOOL_DIR", raising=False) + else: + monkeypatch.setenv("UV_TOOL_DIR", previous) + monkeypatch.setenv("UV_SELF_UPGRADE_TEST_SENTINEL", "preserved") + with ( + patch.object(update.sys, "prefix", str(prefix)), + patch("comfy_cli.update.resolve_binary", return_value="/opt/bin/uv"), + ): + upgrade_cli() + installer_env = mock_run.call_args.kwargs.get("env", {}) + assert installer_env.get("UV_TOOL_DIR") == str(tool_root) + assert installer_env.get("UV_SELF_UPGRADE_TEST_SENTINEL") == "preserved" + assert update.os.environ.get("UV_TOOL_DIR") == previous + assert mock_run.call_args.args[0] == ["/opt/bin/uv", "tool", "upgrade", "comfy-cli"] + assert "timeout" not in mock_run.call_args.kwargs + + @patch("comfy_cli.update.subprocess.run") + def test_uv_tool_install_without_uv_on_path_is_unavailable(self, mock_run, tmp_path): + tool_root = tmp_path / "custom-tools" + prefix = tool_root / "comfy-cli" + prefix.mkdir(parents=True) + (prefix / "uv-receipt.toml").write_text("[tool]\n") + with ( + patch.object(update.sys, "prefix", str(prefix)), + patch("comfy_cli.update.resolve_binary", return_value=None), + pytest.raises(update.UpgradeUnavailable) as excinfo, + ): + upgrade_cli() + assert "uv tool upgrade comfy-cli" in excinfo.value.hint + # The next shell may select another tools directory; the hint names this one. + assert "UV_TOOL_DIR" in excinfo.value.hint + assert str(tool_root) in excinfo.value.hint + mock_run.assert_not_called() + + @patch("comfy_cli.update.subprocess.run") + def test_env_without_pip_is_unavailable(self, mock_run, tmp_path): + with ( + patch.object(update.sys, "prefix", str(tmp_path)), + patch("comfy_cli.update.importlib.util.find_spec", return_value=None), + pytest.raises(update.UpgradeUnavailable), + ): + upgrade_cli() + mock_run.assert_not_called() @pytest.mark.parametrize("payload", ["[]", '"x"', '{"checked_at": "abc"}']) @@ -126,3 +204,107 @@ def test_latest_upgrade_version_survives_missing_latest_key(mock_check, tmp_path def test_latest_upgrade_version_survives_unparseable_latest(tmp_path): (tmp_path / "update-check.json").write_text(json.dumps({"checked_at": time.time(), "latest": "unknown"})) assert update.latest_upgrade_version("1.0.0", str(tmp_path)) is None + + +@pytest.mark.parametrize( + "receipt", + [ + '[tool]\nrequirements = [{ name = "comfy-cli", specifier = "==1.2.3" }]\n', + '[tool]\nrequirements = [{ name = "comfy-cli", specifier = "===1.2.3" }]\n', + '[tool]\nrequirements = [{ name = "Comfy_Cli", specifier = ">=1,==1.2.3" }]\n', + '[tool]\nrequirements = ["comfy-cli==1.2.3"]\n', + '[tool]\nrequirements = [{ name = "comfy-cli" }]\nconstraints = [{ name = "comfy-cli", specifier = "==1.2.3" }]\n', + ], + ids=["exact", "arbitrary-exact", "mixed-normalized", "legacy", "constraint"], +) +def test_uv_exact_pin_blocks_installer_and_preserves_receipt(tmp_path, monkeypatch, receipt): + prefix = tmp_path / "original tools" / "comfy-cli" + prefix.mkdir(parents=True) + path = prefix / "uv-receipt.toml" + path.write_text(receipt) + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + with patch("comfy_cli.update.subprocess.run") as installer, pytest.raises(update.UpgradeUnavailable) as failure: + upgrade_cli() + assert "pin" in str(failure.value).lower() + assert "UV_TOOL_DIR" in failure.value.hint + assert str(prefix.parent) in failure.value.hint + assert "reinstall" in failure.value.hint.lower() + assert path.read_text() == receipt + installer.assert_not_called() + + +@pytest.mark.parametrize( + "receipt", + [ + "[tool]\n", + '[tool]\nrequirements = [{ name = "comfy-cli" }]\n', + '[tool]\nrequirements = [{ name = "comfy-cli", specifier = ">=1,<2" }]\n', + '[tool]\nrequirements = [{ name = "comfy-cli", specifier = "==1.2.*" }]\n', + '[tool]\nrequirements = [{ name = "comfy-cli", specifier = ">=1" }, { name = "helper", specifier = "==2" }]\nconstraints = [{ name = "helper", specifier = "==2" }]\n', + '[tool]\nrequirements = ["comfy-cli>=1", "helper==2"]\n', + ], + ids=["legacy-empty", "unbounded", "range", "wildcard", "other-dependency", "legacy-range"], +) +def test_uv_unpinned_or_ranged_receipt_keeps_existing_upgrade(tmp_path, monkeypatch, receipt): + prefix = tmp_path / "tools" / "comfy-cli" + prefix.mkdir(parents=True) + path = prefix / "uv-receipt.toml" + path.write_text(receipt) + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + with patch("comfy_cli.update.subprocess.run") as installer: + upgrade_cli() + assert installer.call_count == 1 + assert installer.call_args.args[0] == ["/opt/bin/uv", "tool", "upgrade", "comfy-cli"] + assert installer.call_args.kwargs["env"]["UV_TOOL_DIR"] == str(prefix.parent) + assert installer.call_args.kwargs["check"] is True + assert "timeout" not in installer.call_args.kwargs + assert path.read_text() == receipt + + +@pytest.mark.parametrize( + "receipt", + [ + "[tool", + 'other = "invalid"\n', + '[tool]\nrequirements = "invalid"\n', + "[tool]\nrequirements = [7]\n", + '[tool]\nrequirements = [{name="comfy-cli", specifier="token=secret"}]\n', + ], +) +def test_malformed_uv_receipt_is_structured_and_never_runs_installer(tmp_path, monkeypatch, receipt): + prefix = tmp_path / "tools" / "comfy-cli" + prefix.mkdir(parents=True) + path = prefix / "uv-receipt.toml" + path.write_text(receipt) + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + with patch("comfy_cli.update.subprocess.run") as installer, pytest.raises(update.UpgradeUnavailable) as failure: + upgrade_cli() + assert "receipt" in str(failure.value).lower() + assert "token=secret" not in str(failure.value) + assert "UV_TOOL_DIR" in failure.value.hint + installer.assert_not_called() + + +def test_unreadable_uv_receipt_is_unavailable_without_exposing_details(tmp_path, monkeypatch): + prefix = tmp_path / "tools" / "comfy-cli" + prefix.mkdir(parents=True) + receipt = prefix / "uv-receipt.toml" + receipt.write_text("[tool]\n") + monkeypatch.setattr(update.sys, "prefix", str(prefix)) + monkeypatch.setattr(update, "resolve_binary", lambda name: "/opt/bin/uv") + original_read = update.Path.read_text + + def guarded_read(path, *args, **kwargs): + if path == receipt: + raise PermissionError("sensitive-parser-details") + return original_read(path, *args, **kwargs) + + monkeypatch.setattr(update.Path, "read_text", guarded_read) + with patch("comfy_cli.update.subprocess.run") as installer, pytest.raises(update.UpgradeUnavailable) as failure: + upgrade_cli() + assert "receipt" in str(failure.value).lower() + assert "sensitive-parser-details" not in str(failure.value) + installer.assert_not_called()