Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions comfy_cli/command/workflow_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,10 @@ def add_node_cmd(
"(the only UI-only classes this surface can mint)"
)
elif e.subgraph_id:
hint = "pick a node CLASS from `comfy nodes search <text>`; a subgraph instance cannot be added"
hint = (
"reuse the exact definition id from `comfy workflow ls-nodes <file>` only in the workflow that "
"already contains that definition and an instance, or pick a node class with `comfy nodes search <text>`"
)
elif e.close_matches:
hint = f"did you mean: {', '.join(e.close_matches)}?"
else:
Expand Down Expand Up @@ -756,8 +759,8 @@ def ls_nodes_cmd(
# A row's `type` reads like an addable class. Two kinds are not: a
# frontend-only node (Reroute/Note/PrimitiveNode/...) and a subgraph
# instance, whose `type` is its definition uuid. Both stay listed (the
# graph must still be understood); the flag says `add-node` / `nodes
# show` cannot take that type. Only set when true, like `mode`.
# graph must still be understood); the flag distinguishes them from
# catalog classes. Only set when true, like `mode`.
node_type = n.get("type")
if isinstance(node_type, str):
if workflow_ops._UUID_RE.match(node_type) or node_type in subgraph_ids:
Expand Down
29 changes: 27 additions & 2 deletions comfy_cli/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from __future__ import annotations

import math

COL_GAP = 80.0
ROW_GAP = 40.0
NODE_W = 240.0
Expand Down Expand Up @@ -291,12 +293,34 @@ def _pair(value) -> tuple[float, float] | None:
return float(value["0"]), float(value["1"])
except (KeyError, TypeError, ValueError):
return None
if not isinstance(value, (list, tuple)):
return None
try:
return float(value[0]), float(value[1])
except (TypeError, ValueError, IndexError, KeyError):
return None


def normalized_size(value) -> list[float]:
"""Return a usable LiteGraph body size in its canonical list form.

Saved workflows legitimately contain either ``[width, height]`` or
``{"0": width, "1": height}``. A missing or malformed value falls back
to the same default the placement planner uses; finite positive dimensions
are required because a zero/NaN footprint defeats collision detection.
"""
try:
raw_pair = (value.get("0"), value.get("1")) if isinstance(value, dict) else (value[0], value[1])
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
except (TypeError, IndexError, KeyError):
raw_pair = ()
if any(isinstance(item, bool) for item in raw_pair):
return list(DEFAULT_SIZE)
pair = _pair(value)
if pair is None or any(not math.isfinite(item) or item <= 0 for item in pair):
return list(DEFAULT_SIZE)
return [pair[0], pair[1]]


def occupied(pos, size) -> tuple[float, float, float, float]:
"""The rectangle a node actually covers on the canvas, title bar included.

Expand Down Expand Up @@ -406,7 +430,7 @@ def rebase_template(existing_nodes: list, template: dict) -> None:
group["bounding"] = [gx + dx, gy + dy, *bounding[2:]]


def assign_positions(workflow: dict, graph, specs: list) -> list:
def assign_positions(workflow: dict, graph, specs: list, *, unknown_size_resolver=None) -> list:
"""Fill `at` on every add_node spec that lacks one, using the batch's own
connects for dataflow layering. Returns spec copies; non-add specs and
explicit `at` values pass through untouched. Pure: same inputs → same output."""
Expand Down Expand Up @@ -450,7 +474,8 @@ def assign_positions(workflow: dict, graph, specs: list) -> list:
widget_labels=widget_names,
)
else:
size = list(DEFAULT_SIZE) # unknown type: apply_specs will error later
resolved_size = unknown_size_resolver(class_type) if unknown_size_resolver is not None else None
size = resolved_size if resolved_size is not None else list(DEFAULT_SIZE)
key = spec.get("as") or f"__new{i}"
adds[key] = {"i": i, "size": size, "depth": 0, "pinned": spec.get("at")}
order.append(key)
Expand Down
201 changes: 190 additions & 11 deletions comfy_cli/workflow_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,9 +261,8 @@ def __init__(self, node_id: Any, class_type: str, widget: str, *, interior: bool
)

# A subgraph INSTANCE's node `type` is the UUID id of its definition, and
# `ls-nodes` prints that verbatim — so a caller reading ls-nodes output can
# mistake it for a class name. There is no instantiate-a-subgraph command, so
# such an add can never succeed; say why instead of "unknown node type".
# `ls-nodes` prints that verbatim. ``add_node`` can reuse that id only when the
# current workflow contains both the definition and an instance to copy.
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I)


Expand Down Expand Up @@ -296,8 +295,8 @@ def __init__(
)
elif subgraph_id:
msg = (
f"{class_type!r} is a subgraph INSTANCE id, not a node class. `ls-nodes` prints a subgraph "
"instance's definition uuid as its type; there is no command to instantiate a subgraph"
f"{class_type!r} looks like a subgraph definition id, not a node class, but this workflow "
"does not contain a matching definition and reusable instance"
)
else:
msg = f"unknown node type {class_type!r}"
Expand Down Expand Up @@ -661,6 +660,128 @@ def _coerce_pos(pos: Any) -> Any:
return out


def _subgraph_definition_and_template(workflow: dict, definition_id: str) -> tuple[dict | None, dict | None]:
"""Resolve an exact definition id and its first top-level host instance.

Older workflows may serialize a host's ``type`` as the definition name.
The engine's definition index already owns that compatibility rule, so use
object identity from the same resolver instead of duplicating an id-only
comparison here. The CLI input remains the exact definition id.
"""
definitions = workflow.get("definitions")
subgraphs = definitions.get("subgraphs") if isinstance(definitions, dict) else None
definition = next(
(
candidate
for candidate in subgraphs or []
if isinstance(candidate, dict) and candidate.get("id") == definition_id
),
None,
)
if definition is None:
return None, None
from comfy_cli.cql import engine as _engine

definitions_by_key = _engine._subgraph_defs_by_id(workflow)
for node in workflow.get("nodes") or []:
if isinstance(node, dict) and definitions_by_key.get(str(node.get("type", ""))) is definition:
return definition, node
return definition, None


def _reusable_subgraph_instance(workflow: dict, definition_id: str) -> dict | None:
definition, template = _subgraph_definition_and_template(workflow, definition_id)
if definition is None:
return None
if template is None:
raise UnknownNodeType(definition_id, subgraph_id=True)
return template


def _subgraph_instance_paths(workflow: dict, target: dict) -> list[list[str]]:
"""Every live path whose host resolves to ``target``, in document order.

The paths ride in a reused-subgraph ``add_node`` op so conflict detection
can identify a concurrent interior mutation without consulting mutable
workflow state. Cyclic definitions are malformed but possible; record the
cycle edge itself, then stop descending it.
"""
from comfy_cli.cql import engine as _engine

definitions_by_key = _engine._subgraph_defs_by_id(workflow)
paths: list[list[str]] = []

def walk(nodes: Any, prefix: list[str], ancestors: frozenset[int]) -> None:
for node in nodes if isinstance(nodes, list) else []:
if not isinstance(node, dict):
continue
definition = definitions_by_key.get(str(node.get("type", "")))
if definition is None:
continue
path = [*prefix, str(node.get("id"))]
if definition is target:
paths.append(path)
identity = id(definition)
if identity not in ancestors:
walk(definition.get("nodes"), path, ancestors | {identity})

walk(workflow.get("nodes"), [], frozenset())
return paths


def _copy_host_field(template: dict, name: str, expected: type | tuple[type, ...], default: Any) -> Any:
value = template.get(name)
if value is None:
return copy.deepcopy(default)
if not isinstance(value, expected):
expected_names = (
"/".join(item.__name__ for item in expected) if isinstance(expected, tuple) else expected.__name__
)
raise ValueError(f"reusable subgraph host field {name!r} must be {expected_names}, got {type(value).__name__}")
return copy.deepcopy(value)


def _build_subgraph_instance(
node_id: int,
definition_id: str,
template: dict,
pos: list,
size: list,
*,
title: str | None,
) -> dict:
inputs = _copy_host_field(template, "inputs", list, [])
outputs = _copy_host_field(template, "outputs", list, [])
if any(not isinstance(item, dict) for item in inputs):
raise ValueError("reusable subgraph host field 'inputs' must contain only objects")
if any(not isinstance(item, dict) for item in outputs):
raise ValueError("reusable subgraph host field 'outputs' must contain only objects")
node = {
"id": node_id,
"type": definition_id,
"pos": list(pos),
"size": list(size),
"flags": {},
"order": 0,
"mode": 0,
"inputs": inputs,
"outputs": outputs,
"properties": _copy_host_field(template, "properties", dict, {}),
"widgets_values": _copy_host_field(template, "widgets_values", (list, dict), []),
}
for item in node["inputs"]:
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
if isinstance(item, dict):
item["link"] = None
for item in node["outputs"]:
if isinstance(item, dict):
item["links"] = []
if "widgets_values_form" in template:
node["widgets_values_form"] = _copy_host_field(template, "widgets_values_form", dict, {})
if title is not None:
node["title"] = title
return node


def add_node(
workflow: dict,
graph,
Expand Down Expand Up @@ -691,6 +812,7 @@ def add_node(
# executable node.
is_note = class_type in AUTHORABLE_VIRTUAL_NODE_TYPES
m = None if is_note else graph.node(class_type)
subgraph_template = None
if is_note:
if text is None:
text = ""
Expand All @@ -700,12 +822,20 @@ def add_node(
elif m is None:
if class_type in UI_ONLY_NODE_TYPES:
raise UnknownNodeType(class_type, ui_only=True)
if _UUID_RE.match(class_type.strip()):
subgraph_template = _reusable_subgraph_instance(workflow, class_type)
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
if subgraph_template is not None:
if text is not None:
raise ValueError("`text` is not valid for a subgraph instance; edit its promoted widgets by name")
size = layout.normalized_size(subgraph_template.get("size"))
elif _UUID_RE.match(class_type.strip()):
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
raise UnknownNodeType(class_type, subgraph_id=True)
import difflib
else:
import difflib

names = [n.id for n in graph.all_nodes()]
raise UnknownNodeType(class_type, close_matches=difflib.get_close_matches(class_type, names, n=5, cutoff=0.6))
names = [n.id for n in graph.all_nodes()]
raise UnknownNodeType(
class_type, close_matches=difflib.get_close_matches(class_type, names, n=5, cutoff=0.6)
)
else:
if text is not None:
raise ValueError(
Expand Down Expand Up @@ -746,7 +876,9 @@ def add_node(
raise ValueError(f"node position must be two finite numbers, got {pos!r}")
if title is not None and not isinstance(title, str):
raise ValueError(f"node title must be a string, got {title!r}")
if m is None:
if subgraph_template is not None:
node = _build_subgraph_instance(mint_id(), class_type, subgraph_template, pos, size, title=title)
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
Comment thread
christian-byrne marked this conversation as resolved.
Resolved
elif m is None:
node = _build_note_node(mint_id(), class_type, pos, size, text or "", title=title)
else:
node = _build_node(mint_id(), class_type, m, graph, pos, size, title=title)
Expand All @@ -760,6 +892,15 @@ def add_node(
f"invalid node mode {mode!r}; valid: 0 (always), 1 (on-event), 2 (mute), 3 (on-trigger), 4 (bypass)"
)
node["mode"] = mode
subgraph_reuse = None
if subgraph_template is not None:
definition, _template = _subgraph_definition_and_template(workflow, class_type)
if definition is None: # guarded by the successful template lookup above
raise UnknownNodeType(class_type, subgraph_id=True)
subgraph_reuse = {
"definition_id": class_type,
"existing_instance_paths": _subgraph_instance_paths(workflow, definition),
}
op = _new_op(
"add_node",
actor,
Expand All @@ -768,6 +909,7 @@ def add_node(
class_type=class_type,
pos=node["pos"],
node=node,
**({"subgraph_reuse": subgraph_reuse} if subgraph_reuse is not None else {}),
**({"mode": mode} if mode else {}),
**({"title": title} if title is not None else {}),
)
Expand Down Expand Up @@ -2859,7 +3001,14 @@ def apply_specs(
else spec
for spec in specs
]
specs = layout.assign_positions(workflow, graph, specs)

def unknown_size(class_type: Any) -> list[float] | None:
if not isinstance(class_type, str):
return None
_definition, template = _subgraph_definition_and_template(workflow, class_type)
return layout.normalized_size(template.get("size")) if template is not None else None

specs = layout.assign_positions(workflow, graph, specs, unknown_size_resolver=unknown_size)
# Snapshot the inventory BEFORE any op mutates the graph — on failure the
# caller discards everything below, so this is what actually survives.
pre_batch_hint = _available_nodes_hint(workflow)
Expand Down Expand Up @@ -3862,6 +4011,36 @@ def detect_conflict(a: dict, b: dict) -> bool:
the same base conflict here (their batch order is undecidable leaderlessly)
even though :func:`apply_op` keeps both connections and ``canonical`` treats
their order as immaterial."""

def mutated_definition_path(op: dict) -> list[str] | None:
path = op.get("path")
if isinstance(path, list) and path:
# set_widget's path includes the interior target node; the other
# path-scoped ops carry the owning host path directly.
return [str(item) for item in (path[:-1] if op.get("op") == "set_widget" else path)]
promoted = op.get("promoted")
if op.get("op") == "set_widget" and isinstance(promoted, dict) and promoted.get("repair"):
instance_path = promoted.get("instance_path")
if isinstance(instance_path, list) and instance_path:
return [str(item) for item in instance_path]
return None

def reuse_conflicts_with_mutation(reuse_op: dict, mutation_op: dict) -> bool:
metadata = reuse_op.get("subgraph_reuse")
mutation_path = mutated_definition_path(mutation_op)
if not isinstance(metadata, dict) or mutation_path is None:
return False
for raw_path in metadata.get("existing_instance_paths") or []:
if not isinstance(raw_path, list) or not raw_path:
continue
instance_path = [str(item) for item in raw_path]
if mutation_path[: len(instance_path)] == instance_path:
return True
return False

if reuse_conflicts_with_mutation(a, b) or reuse_conflicts_with_mutation(b, a):
return True

target_a = _write_target(a)
target_b = _write_target(b)
if a["op"] == "set_widget" and b["op"] == "set_widget" and target_a[:-1] == target_b[:-1]:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ tests keep the document, those sets, and dispatch tables aligned. Unsupported
operation kinds are rejected rather than silently ignored. Proposed additions
remain clearly marked until ratified into the frozen vocabulary.

Amendment v1.10 in the normative vocabulary extends `add_node` minting to an
existing subgraph definition with an exact reused-host schema contract and
explicit conflict metadata. It does not add an operation kind or weaken this
ADR's versioning and fail-closed requirements.

## Alternatives considered

- Treat Python functions as the contract. Rejected because remote producers
Expand Down
Loading
Loading