diff --git a/CHANGELOG.md b/CHANGELOG.md index 655b0f7d1..ce9c3f4e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,11 @@ history. - DynamicGroup workflow conversion, row editing and validation, including row templates in node discovery and the widget catalog. Refuse incompatible saved widget layouts and ambiguous names instead of editing a different widget. +- DynamicGroup refusals carry their own `error.code` in the edit, `apply`, + `foreach`, `slots`, `validate`, `run` and `decompose` envelopes: + `dynamic_group_unsupported`, `dynamic_group_binding_mismatch`, + `dynamic_group_count_out_of_range` and `dynamic_group_rows_linked`, in place + of `workflow_edit_invalid` and the conversion codes. Messages are unchanged. - `comfy deploy cancel [PATH] [--deployment ]` ends the update a deployment waits on and keeps it serving the release it served; `--json` diff --git a/comfy_cli/command/run/__init__.py b/comfy_cli/command/run/__init__.py index 790db34ef..8800e706c 100644 --- a/comfy_cli/command/run/__init__.py +++ b/comfy_cli/command/run/__init__.py @@ -256,7 +256,7 @@ def execute( workflow = convert_ui_to_api(raw_workflow, object_info) except WorkflowConversionError as e: renderer.error( - code="conversion_error", + code=e.code or "conversion_error", message=f"Workflow conversion failed: {e}", hint="use ComfyUI's 'File > Export (API)' to save as API format", ) @@ -1012,7 +1012,7 @@ def execute_cloud( raw_workflow = convert_ui_to_api(raw_workflow, object_info) except WorkflowConversionError as e: renderer.error( - code="conversion_error", + code=e.code or "conversion_error", message=f"Workflow conversion failed: {e}", hint="use ComfyUI's 'File > Export (API)' to save as API format and retry", ) diff --git a/comfy_cli/command/workflow.py b/comfy_cli/command/workflow.py index afa7eee3d..8f2f1e47a 100644 --- a/comfy_cli/command/workflow.py +++ b/comfy_cli/command/workflow.py @@ -215,9 +215,14 @@ def slots_cmd( input_path, host, port, on_stale=lambda key, err: _stale.update(stale=True, source=key, reason=err) ) + from comfy_cli.cql.engine import DynamicGroupBindingError + template_id = template_id or p.stem try: schema = graph.get_template_schema(template_id, workflow) + except DynamicGroupBindingError as e: + renderer.error(code=e.code, message=f"Could not extract slots: {e}") + raise typer.Exit(code=1) from e except (ValueError, KeyError) as e: renderer.error(code="workflow_slot_invalid", message=f"Could not extract slots: {e}") raise typer.Exit(code=1) from e @@ -1741,7 +1746,7 @@ def validate_api_workflow( except WorkflowConversionError as e: renderer.error( command=command, - code="workflow_not_api_format", + code=e.code or "workflow_not_api_format", message=f"Workflow is a UI export that could not be converted to API format: {e}", hint="use ComfyUI's 'File > Export (API)' to save as API format", ) diff --git a/comfy_cli/command/workflow_edit.py b/comfy_cli/command/workflow_edit.py index 01de997b6..06a85923d 100644 --- a/comfy_cli/command/workflow_edit.py +++ b/comfy_cli/command/workflow_edit.py @@ -26,6 +26,7 @@ _load_workflow_or_fail, _parse_value, ) +from comfy_cli.cql.engine import DynamicGroupBindingError from comfy_cli.output import get_renderer, rprint # Shared option aliases — the edit commands (add-node/set-widget/connect/ @@ -75,7 +76,12 @@ def _emit_edit_error(renderer, e: ValueError, *, hint: str) -> None: details={k: v for k, v in f.items() if k != "message"}, ) return - renderer.error(code="workflow_edit_invalid", message=str(e), hint=hint) + renderer.error(code=_edit_error_code(e), message=str(e), hint=hint) + + +def _edit_error_code(e: Exception) -> str: + """A DynamicGroup refusal keeps its own code; every other edit failure is ``workflow_edit_invalid``.""" + return e.code if isinstance(e, DynamicGroupBindingError) else "workflow_edit_invalid" def _split_addr(addr: str, renderer) -> tuple[Any, str]: @@ -915,12 +921,12 @@ def apply_cmd( "failed": { "index": getattr(e, "spec_index", None), "op": getattr(e, "spec_op", None), - "code": "workflow_edit_invalid", + "code": _edit_error_code(e), }, # Specs applied before the abort — all discarded (atomic batch). "applied_count": getattr(e, "applied_count", 0), } - renderer.error(code="workflow_edit_invalid", message=f"batch failed: {e}", details=details) + renderer.error(code=_edit_error_code(e), message=f"batch failed: {e}", details=details) raise typer.Exit(code=1) from e workflow_ops.strip_internal(workflow) @@ -1093,7 +1099,7 @@ def foreach_cmd( # leaves the earlier files on disk. Surface them (in the hint AND machine- # readable details) so the caller isn't blind to the partial output. renderer.error( - code="workflow_edit_invalid", + code=_edit_error_code(e), message=f"foreach failed: {e}", hint=( f"{len(written)} workflow(s) were written to {out} before the failure — " diff --git a/comfy_cli/command/workflow_fragments.py b/comfy_cli/command/workflow_fragments.py index 4c78ea930..fedccce81 100644 --- a/comfy_cli/command/workflow_fragments.py +++ b/comfy_cli/command/workflow_fragments.py @@ -271,7 +271,7 @@ def decompose_cmd( api_workflow = convert_ui_to_api(data, object_info) except WorkflowConversionError as e: renderer.error( - code="workflow_conversion_failed", + code=e.code or "workflow_conversion_failed", message=f"Could not convert frontend workflow to API format: {e}", hint="re-export from ComfyUI, or pass a matching --input object_info.json", ) diff --git a/comfy_cli/cql/engine.py b/comfy_cli/cql/engine.py index 2e82e348f..4d5cbda1f 100644 --- a/comfy_cli/cql/engine.py +++ b/comfy_cli/cql/engine.py @@ -3932,13 +3932,30 @@ def _dynamic_group_widgets(port: Port, prefix: str = "") -> list[Port]: class DynamicGroupBindingError(ValueError): - pass + """A DynamicGroup refusal; ``code`` is its ``error.code`` in ``comfy_cli/error_codes.py``. + + Raised directly, it means the class's DynamicGroup schema is one this CLI does not support. + """ + + code = "dynamic_group_unsupported" + + +class DynamicGroupLayoutError(DynamicGroupBindingError): + code = "dynamic_group_binding_mismatch" + + +class DynamicGroupCountError(DynamicGroupBindingError): + code = "dynamic_group_count_out_of_range" + + +class DynamicGroupLinkedRowsError(DynamicGroupBindingError): + code = "dynamic_group_rows_linked" def _dynamic_group_row_count(value: Any, available: int, width: int) -> int: # A corrupt controller must not allocate a roster larger than the saved data. if isinstance(value, bool) or not isinstance(value, int) or value < 0 or not width or value * width > available: - raise DynamicGroupBindingError("DynamicGroup row count does not match the saved widget values") + raise DynamicGroupLayoutError("DynamicGroup row count does not match the saved widget values") return value @@ -4018,28 +4035,28 @@ def _validate_dynamic_group_layout(node: dict, m: Morphism) -> list[_WidgetEntry source = values if "widgets_values_form" in node: if not isinstance(form, dict) or set(form) != {"order"}: - raise DynamicGroupBindingError("widgets_values_form must contain only an order array") + raise DynamicGroupLayoutError("widgets_values_form must contain only an order array") order = form["order"] if not isinstance(order, list) or not order or any(not isinstance(n, str) or not n for n in order): - raise DynamicGroupBindingError("widgets_values_form.order must be a non-empty array of widget names") + raise DynamicGroupLayoutError("widgets_values_form.order must be a non-empty array of widget names") if isinstance(values, list): if len(values) != len(order): - raise DynamicGroupBindingError("widgets_values_form length does not match widgets_values") + raise DynamicGroupLayoutError("widgets_values_form length does not match widgets_values") source = dict(zip(order, values)) elif isinstance(values, dict): if len(order) != len(set(order)) or any(n not in values for n in order): - raise DynamicGroupBindingError("widgets_values_form has duplicated or missing named values") + raise DynamicGroupLayoutError("widgets_values_form has duplicated or missing named values") else: - raise DynamicGroupBindingError("widgets_values_form requires array or object widgets_values") + raise DynamicGroupLayoutError("widgets_values_form requires array or object widgets_values") entries = _expand_widget_entries(m, source if isinstance(source, (list, dict)) else []) saved_length = len(values) if isinstance(values, list) else len(form["order"]) if form is not None else None if saved_length is not None: while len(entries) > saved_length and entries[-1].frontend_injected: entries.pop() if form is not None and form["order"] != [e.name for e in entries]: - raise DynamicGroupBindingError("widgets_values_form does not match the available DynamicGroup schema") + raise DynamicGroupLayoutError("widgets_values_form does not match the available DynamicGroup schema") if isinstance(values, list) and len(entries) != len(values): - raise DynamicGroupBindingError("DynamicGroup schema does not match the saved widget values") + raise DynamicGroupLayoutError("DynamicGroup schema does not match the saved widget values") for index, entry in enumerate(entries): if entry.owner is None or entry.port is None or entry.port.raw_spec is not None: continue @@ -4047,7 +4064,7 @@ def _validate_dynamic_group_layout(node: dict, m: Morphism) -> list[_WidgetEntry continue companion = source[entry.name] if isinstance(source, dict) else source[index] if entry.port.validate_shape(companion) or entry.port.validate_catalog(companion): - raise DynamicGroupBindingError(f"DynamicGroup companion {entry.name!r} must use a supported control mode") + raise DynamicGroupLayoutError(f"DynamicGroup companion {entry.name!r} must use a supported control mode") return entries @@ -4108,7 +4125,7 @@ def emit(name: str, port: Port, owner: str | None, depth: int) -> None: ): rows.add(row) if rows and name not in widgets_values: - raise DynamicGroupBindingError(f"DynamicGroup controller {name!r} is missing for saved rows") + raise DynamicGroupLayoutError(f"DynamicGroup controller {name!r} is missing for saved rows") count = _dynamic_group_row_count(saved_value(name, idx, 0), len(rows), 1) limit = str(count) count = _dynamic_group_row_count(count, sum((len(row), row) < (len(limit), limit) for row in rows), 1) @@ -4456,7 +4473,7 @@ def _write_widget(node: dict, input_name: str, value: Any, graph: Graph, *, exte group_entries = _validate_dynamic_group_layout(node, m) has_group = group_entries is not None if has_group and "widgets_values_named" in node and not isinstance(node["widgets_values_named"], dict): - raise ValueError("widgets_values_named must be an object before editing widgets") + raise DynamicGroupLayoutError("widgets_values_named must be an object before editing widgets") raw_values = node.get("widgets_values") widgets = _widgets_as_positional(node.get("widgets_values"), graph, node_type) order = graph.widget_order_for_node(node_type, widgets) @@ -4526,7 +4543,7 @@ def _write_dynamic_group_count( minimum = port.options.min if port.options.min is not None else 0 maximum = port.options.max if port.options.max is not None else 20 if isinstance(count, bool) or not isinstance(count, int) or not minimum <= count <= maximum: - raise ValueError(f"{port.name}: row count must be an integer between {minimum} and {maximum}") + raise DynamicGroupCountError(f"{port.name}: row count must be an integer between {minimum} and {maximum}") if "inputs" in node and ( not isinstance(node["inputs"], list) or any(not isinstance(inp, dict) for inp in node["inputs"]) ): @@ -4542,14 +4559,14 @@ def _write_dynamic_group_count( names = {p.name for p in new_fields} removed = {e.name for e in old_entries} - names if any(i.get("name") in removed and i.get("link") is not None for i in node.get("inputs", [])): - raise ValueError(f"{port.name}: disconnect the removed rows before reducing their count") + raise DynamicGroupLinkedRowsError(f"{port.name}: disconnect the removed rows before reducing their count") surviving_inputs = [ (index, inp) for index, inp in enumerate(node.get("inputs") or []) if inp.get("name") not in removed ] if any( inp.get("link") is not None and previous != current for current, (previous, inp) in enumerate(surviving_inputs) ): - raise ValueError(f"{port.name}: disconnect shifted inputs before reducing their count") + raise DynamicGroupLinkedRowsError(f"{port.name}: disconnect shifted inputs before reducing their count") old_names = {e.name for e in old_entries} new_values = { p.name: old_values[p.name] if p.name in old_values else _widget_default(p) diff --git a/comfy_cli/error_codes.py b/comfy_cli/error_codes.py index 684db44ed..d72047fca 100644 --- a/comfy_cli/error_codes.py +++ b/comfy_cli/error_codes.py @@ -828,9 +828,30 @@ class ErrorCode: "dynamic_group_unsupported", "A node class has a DynamicGroup schema this CLI does not support, so `comfy nodes widget-catalog` " "left it out of `types`. Consumers store that class's values opaquely and refuse widget writes to it. " - "Surfaced in `data.warnings[]` (not as an error envelope) so every other class is still published.", + "Surfaced in `data.warnings[]` (not as an error envelope) so every other class is still published. " + "The workflow edit commands, `workflow apply`/`foreach`, `workflow slots`, `workflow validate`, `run` " + "and `workflow decompose` raise it as the error code when a workflow uses such a class; nothing is " + "written.", "update comfy-cli, or leave the class's widgets unedited", ), + ErrorCode( + "dynamic_group_binding_mismatch", + "A node's saved DynamicGroup values do not bind to its class's DynamicGroup schema: the saved row count " + "or controller disagrees with the saved rows, `widgets_values_form` or `widgets_values_named` is " + "malformed or disagrees with the schema, or a row's seed control mode is unsupported. Raised by the same " + "commands as `dynamic_group_unsupported`, before anything is read or written.", + "re-save the workflow in a ComfyUI frontend whose node schema matches the catalog, then retry", + ), + ErrorCode( + "dynamic_group_count_out_of_range", + "A DynamicGroup row-count write was not an integer between the group's `min` and `max`. Nothing was written.", + "read the group's `min`/`max` from `comfy nodes widget-catalog` (`dynamic_groups`) and write a count in range", + ), + ErrorCode( + "dynamic_group_rows_linked", + "Reducing a DynamicGroup row count would drop or shift a row input that has a link. Nothing was written.", + "disconnect the links into the rows being removed or shifted, then reduce the count", + ), ErrorCode( "description_ignored", "`comfy workflow save --where local --description` was given a description, but the local " diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index f173e8cb1..7609e2138 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -445,7 +445,8 @@ def _rehint_discarded_batch(e: Exception, pre_batch_hint: str) -> ValueError: "Any node id minted by this batch is gone; re-read ids with " "`comfy workflow slots` / `ls-nodes` before addressing nodes." ) - return ValueError(msg + suffix) + # A DynamicGroup refusal keeps its class, and with it its ``code``. + return (type(e) if isinstance(e, DynamicGroupBindingError) else ValueError)(msg + suffix) def _find_by_str(workflow: dict, node_id: Any) -> dict | None: diff --git a/comfy_cli/workflow_to_api.py b/comfy_cli/workflow_to_api.py index d2df594b1..1aabf50e1 100644 --- a/comfy_cli/workflow_to_api.py +++ b/comfy_cli/workflow_to_api.py @@ -76,7 +76,14 @@ class WorkflowConversionError(Exception): - """Raised when a workflow can't be converted to API format.""" + """Raised when a workflow can't be converted to API format. + + ``code`` is the refusal's own ``error.code`` when it has one (a DynamicGroup refusal), else None. + """ + + def __init__(self, message: str, code: str | None = None): + super().__init__(message) + self.code = code def is_api_format(workflow: Any) -> bool: @@ -183,7 +190,7 @@ def convert_ui_to_api(workflow: dict, object_info: dict) -> dict: nodes_to_exclude=nodes_to_exclude, ) except DynamicGroupBindingError as exc: - raise WorkflowConversionError(f"Node {node_id_str} ({node_type}): {exc}") from exc + raise WorkflowConversionError(f"Node {node_id_str} ({node_type}): {exc}", exc.code) from exc except Exception: # An individual malformed node should not torpedo the whole prompt. # The executor will fail loudly on missing nodes if this matters. diff --git a/tests/comfy_cli/command/test_dynamic_group_error_codes.py b/tests/comfy_cli/command/test_dynamic_group_error_codes.py new file mode 100644 index 000000000..b083fa91d --- /dev/null +++ b/tests/comfy_cli/command/test_dynamic_group_error_codes.py @@ -0,0 +1,107 @@ +"""DynamicGroup refusals carry their registered ``error.code`` in the envelope, +so a caller can count them without matching message text.""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest +from typer.testing import CliRunner + +FIXTURE = json.loads((Path(__file__).resolve().parents[1] / "fixtures" / "dynamic_group.json").read_text()) + + +def _unsupported(info, workflow): + info["DevToolsNodeWithDynamicGroup"]["input"]["required"]["loras"][0] = "COMFY_DYNAMICGROUP_V4" + + +def _mismatched(info, workflow): + workflow["nodes"][0]["widgets_values"][1] = 3 + del workflow["nodes"][0]["widgets_values_named"] + + +def _linked(info, workflow): + workflow["nodes"][0]["inputs"][-1]["link"] = 10 + + +REFUSALS = { + "dynamic_group_unsupported": (_unsupported, "after", '"edited"'), + "dynamic_group_binding_mismatch": (_mismatched, "after", '"edited"'), + "dynamic_group_count_out_of_range": (lambda info, workflow: None, "loras", "4"), + "dynamic_group_rows_linked": (_linked, "loras", "1"), +} + + +def _run(args: list[str]) -> dict: + from comfy_cli.cmdline import app + + result = CliRunner().invoke(app, args, env={"COMFY_OUTPUT": "json"}) + lines = [ln for ln in result.stdout.splitlines() if ln.strip().startswith("{")] + assert lines, f"no JSON envelope: {result.stdout!r}" + return json.loads(lines[-1]) + + +def _files(tmp_path: Path, code: str) -> tuple[str, str]: + info = copy.deepcopy(FIXTURE["object_info"]) + workflow = copy.deepcopy(FIXTURE["cases"]["populated"]["workflow"]) + REFUSALS[code][0](info, workflow) + info_path = tmp_path / "object_info.json" + info_path.write_text(json.dumps(info)) + workflow_path = tmp_path / "wf.json" + workflow_path.write_text(json.dumps(workflow)) + return str(workflow_path), str(info_path) + + +@pytest.mark.parametrize("code", list(REFUSALS)) +def test_set_widget_refusal_carries_its_code(tmp_path, code): + workflow, info = _files(tmp_path, code) + _, widget, value = REFUSALS[code] + + env = _run(["workflow", "set-widget", workflow, f"1.{widget}", value, "--input", info]) + + assert env["error"]["code"] == code + + +@pytest.mark.parametrize("code", list(REFUSALS)) +def test_batch_refusal_carries_its_code(tmp_path, code): + workflow, info = _files(tmp_path, code) + _, widget, value = REFUSALS[code] + ops = tmp_path / "ops.json" + ops.write_text(json.dumps([{"op": "set_widget", "node": 1, "widget": widget, "value": json.loads(value)}])) + + env = _run(["workflow", "apply", workflow, "--ops", str(ops), "--ack", "summary", "--input", info]) + + assert env["error"]["code"] == code + assert env["error"]["details"]["failed"]["code"] == code + + +@pytest.mark.parametrize("code", ["dynamic_group_unsupported", "dynamic_group_binding_mismatch"]) +@pytest.mark.parametrize("command", ["validate", "slots", "decompose"]) +def test_read_refusal_carries_its_code(tmp_path, code, command): + workflow, info = _files(tmp_path, code) + args = ["--workflow", workflow] if command == "validate" else [workflow] + if command == "decompose": + args += ["--lib", str(tmp_path / "fragments")] + + env = _run(["workflow", command, *args, "--input", info]) + + assert env["error"]["code"] == code + + +@pytest.mark.parametrize("command", ["add-node", "foreach"]) +def test_adding_an_unsupported_group_class_carries_its_code(tmp_path, command): + workflow, info = _files(tmp_path, "dynamic_group_unsupported") + if command == "add-node": + args = ["add-node", workflow, "DevToolsNodeWithDynamicGroup"] + else: + recipe = tmp_path / "recipe.json" + recipe.write_text(json.dumps({"ops": [{"op": "add_node", "class_type": "DevToolsNodeWithDynamicGroup"}]})) + params = tmp_path / "params.json" + params.write_text("[{}]") + args = ["foreach", str(recipe), "--params", str(params), "--out-dir", str(tmp_path / "out")] + + env = _run(["workflow", *args, "--input", info]) + + assert env["error"]["code"] == "dynamic_group_unsupported" diff --git a/tests/comfy_cli/output/test_error_code_registry.py b/tests/comfy_cli/output/test_error_code_registry.py index 7d2bd279d..1ae4c1eeb 100644 --- a/tests/comfy_cli/output/test_error_code_registry.py +++ b/tests/comfy_cli/output/test_error_code_registry.py @@ -37,13 +37,16 @@ def _iter_python_files(root: Path): continue if "__pycache__" in p.parts: continue - # engine.py uses internal validation result codes ("unknown_class_type", - # "shape_mismatch", etc.) in return-value dicts, not CLI error codes. - if p.name == "engine.py" and "cql" in p.parts: - continue yield p +def _is_cql_engine(path: Path) -> bool: + """engine.py uses internal validation result codes ("unknown_class_type", + "shape_mismatch", etc.) in return-value dicts, not CLI error codes. Only its + exception classes' ``code`` attributes (the DynamicGroup refusals) are.""" + return path.name == "engine.py" and "cql" in path.parts + + #: ``code=`` is ``renderer.error``'s own kwarg. ``error_code=`` is how #: ``comfy_cli.interaction``'s ``require_option`` / ``confirm`` take the code: #: that helper deliberately hardcodes none, so each command names its own code @@ -66,10 +69,15 @@ def _extract_codes_from_call(call: ast.Call) -> list[str]: for kw in call.keywords: if kw.arg not in _CODE_KWARGS: continue - if isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str): - value = kw.value.value - if error_codes.CODE_PATTERN.match(value): - out.append(value) + # ``code=e.code or "fallback"``: the literal fallback is raised too. + values = kw.value.values if isinstance(kw.value, ast.BoolOp) else [kw.value] + for value in values: + if ( + isinstance(value, ast.Constant) + and isinstance(value.value, str) + and error_codes.CODE_PATTERN.match(value.value) + ): + out.append(value.value) # Positional first arg on ``.error("code", "msg")`` — keep the heuristic # for the small set of callers that use the positional form. func = call.func @@ -141,14 +149,16 @@ def _collect_raised_codes() -> dict[str, list[Path]]: tree = ast.parse(path.read_text(encoding="utf-8")) except (OSError, SyntaxError): continue + # Class-level ``code = "..."`` (e.g. OAuthError subclasses). + for code in _extract_class_code_attrs(tree): + raised.setdefault(code, []).append(path) + if _is_cql_engine(path): + continue for node in ast.walk(tree): if not isinstance(node, ast.Call): continue for code in _extract_codes_from_call(node): raised.setdefault(code, []).append(path) - # Also pick up class-level ``code = "..."`` (e.g. OAuthError subclasses). - for code in _extract_class_code_attrs(tree): - raised.setdefault(code, []).append(path) # Also pick up ``"code": "..."`` in dict literals (inline error dicts). for code in _extract_dict_code_values(tree): raised.setdefault(code, []).append(path)