diff --git a/comfy_cli/command/workflow_edit.py b/comfy_cli/command/workflow_edit.py index 0f4acb7cb..b7a3d364f 100644 --- a/comfy_cli/command/workflow_edit.py +++ b/comfy_cli/command/workflow_edit.py @@ -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 `; a subgraph instance cannot be added" + hint = ( + "reuse the exact definition id from `comfy workflow ls-nodes ` only in the workflow that " + "already contains that definition and an instance, or pick a node class with `comfy nodes search `" + ) elif e.close_matches: hint = f"did you mean: {', '.join(e.close_matches)}?" else: @@ -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: diff --git a/comfy_cli/layout.py b/comfy_cli/layout.py index 16e10fc71..ace65b2d3 100644 --- a/comfy_cli/layout.py +++ b/comfy_cli/layout.py @@ -8,6 +8,8 @@ from __future__ import annotations +import math + COL_GAP = 80.0 ROW_GAP = 40.0 NODE_W = 240.0 @@ -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]) + 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. @@ -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.""" @@ -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) diff --git a/comfy_cli/workflow_ops.py b/comfy_cli/workflow_ops.py index 5b7dd3231..0d3333973 100644 --- a/comfy_cli/workflow_ops.py +++ b/comfy_cli/workflow_ops.py @@ -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) @@ -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}" @@ -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"]: + 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, @@ -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 = "" @@ -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) + 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()): 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( @@ -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) + 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) @@ -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, @@ -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 {}), ) @@ -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) @@ -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]: diff --git a/docs/adr/OPERATIONS-0002-version-structured-workflow-operations.md b/docs/adr/OPERATIONS-0002-version-structured-workflow-operations.md index cfef42b0e..777990e47 100644 --- a/docs/adr/OPERATIONS-0002-version-structured-workflow-operations.md +++ b/docs/adr/OPERATIONS-0002-version-structured-workflow-operations.md @@ -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 diff --git a/docs/op-vocabulary-v1.md b/docs/op-vocabulary-v1.md index cb2793aeb..e7a2482e6 100644 --- a/docs/op-vocabulary-v1.md +++ b/docs/op-vocabulary-v1.md @@ -81,10 +81,14 @@ refused with `node_deprecated` unless it is `true`. * Idempotency: re-applying the same `op_id` is a no-op; independently, replaying an `add_node` whose `node_id` already exists in the graph is a no-op. -* Conflict: none — ids are minted leaderlessly (section 6), so two concurrent - `add_node` ops never target the same identity. +* Conflict: ids are minted leaderlessly (section 6), so two concurrent + `add_node` ops never target the same identity. Amendment v1.10 adds one + explicit ordering conflict between a reused-subgraph add and a concurrent + mutation inside the definition it turns from single-instance to shared. * Invalid: an unknown `class_type` is rejected at mint time (`UnknownNodeType`, - rendered as `node_not_found` with close matches). + rendered as `node_not_found` with close matches), except for the exact id of + a definition already present with a reusable top-level host instance as + specified by amendment v1.10 (§19). ### 1.2 `connect` @@ -1228,3 +1232,52 @@ v1.9. **No change to §§2-8.** No op kind was added, removed, or re-scoped; `FROZEN_OPS` / `DEFERRED_OPS` / `BATCHABLE_OPS` are untouched. Downstream repos pinning this document by SHA move the SHA together with their comfy-cli pin. + +## 19. Amendment v1.10 — 2026-10-25 (`add_node` reuses an existing subgraph definition) + +An `add_node` spec may use the **exact definition id** of a subgraph already in +the workflow when that definition also has at least one top-level host instance. +This is an extension of the existing `add_node` kind, not a new operation kind. +Unknown ids and definitions with no reusable top-level host still fail closed as +`node_not_found`; definition names are not an authoring alias. + +The first matching top-level host in document order is the authoritative schema +template. Legacy hosts whose `type` is the definition name are resolved through +the same definition index as the rest of the engine. The fresh host copies the +template's `inputs`, `outputs`, `properties`, `widgets_values`, optional +`widgets_values_form`, and valid saved `size`. It clears every input/output link, +resets `flags`, `order`, and `mode`, mints a fresh collision-free node id, and +uses the requested position/title. Malformed host containers fail closed rather +than emitting a partially shaped node. The copied host state is independent; +the definition is deliberately shared. + +The minted op carries the complete authoritative `node` payload as before and +adds: + +```json +{ + "subgraph_reuse": { + "definition_id": "2454ad83-157c-40dd-9f19-5daaf4041ce0", + "existing_instance_paths": [["88"]] + } +} +``` + +`existing_instance_paths` is captured before the new host is applied and +includes nested live paths that resolve to the reused definition. It is +conflict metadata: `detect_conflict` flags this add against a concurrent +interior `set_widget`, `connect`, `disconnect`, `delete_node`, or promoted-input +repair whose mutated definition path is that instance path or a descendant. +Without that flag, replaying the interior mutation before versus after the new +shared instance can fork/refuse in different orders (§8.7) and silently diverge. +The merge consumer must therefore ask for an order for such a pair; all other +`add_node` identity/idempotency rules remain unchanged. + +Batch layout uses the same normalized saved host size as the emitted node, +including LiteGraph's object form (`{"0": width, "1": height}`), so an +unpinned sibling in the same batch is not placed through the reused host. + +No operation kind is added or removed. `FROZEN_OPS`, `DEFERRED_OPS`, and +`BATCHABLE_OPS` are unchanged. Downstream consumers that move their pinned +vocabulary SHA to v1.10 must preserve `subgraph_reuse` conflict metadata even +though replay itself continues to insert `op.node` opaquely. diff --git a/tests/comfy_cli/command/test_add_node_unknown_class.py b/tests/comfy_cli/command/test_add_node_unknown_class.py index 3d96daa5f..26d87bc21 100644 --- a/tests/comfy_cli/command/test_add_node_unknown_class.py +++ b/tests/comfy_cli/command/test_add_node_unknown_class.py @@ -18,6 +18,7 @@ from __future__ import annotations +import copy import json import pytest @@ -29,6 +30,7 @@ reset_singleton, # noqa: F401 (autouse fixture) ) +from comfy_cli import layout, workflow_ops from comfy_cli.command import workflow_edit @@ -73,9 +75,7 @@ def test_ui_only_node_is_rejected_with_a_specific_reason(patched_graph, tmp_path def test_uuid_class_type_is_named_as_a_subgraph_instance(patched_graph, tmp_path, capsys): - """A subgraph INSTANCE's `type` is its definition UUID, and ls-nodes passes - it through verbatim — so the agent sees a UUID that looks like a class name. - There is no instantiate command, so this can never succeed; say so.""" + """An unknown UUID is still rejected as a missing subgraph definition.""" env = _add(tmp_path, capsys, "2454ad83-157c-40dd-9f19-5daaf4041ce0") assert env["ok"] is False err = env["error"] @@ -84,6 +84,179 @@ def test_uuid_class_type_is_named_as_a_subgraph_instance(patched_graph, tmp_path assert "subgraph" in blob, f"must explain the UUID is a subgraph instance id: {err}" +def _workflow_with_subgraph_instance() -> tuple[dict, str]: + definition_id = "2454ad83-157c-40dd-9f19-5daaf4041ce0" + workflow = _base_workflow() + workflow["definitions"] = { + "subgraphs": [ + { + "id": definition_id, + "name": "Prompt module", + "inputs": [], + "outputs": [], + "nodes": [], + "links": [], + } + ] + } + workflow["nodes"].append( + { + "id": 88, + "type": definition_id, + "pos": [400, 300], + "size": [240, 160], + "flags": {"collapsed": True}, + "order": 3, + "mode": 2, + "inputs": [ + {"name": "text", "type": "STRING", "widget": {"name": "text"}, "link": 51}, + {"name": "clip", "type": "CLIP", "link": 52}, + ], + "outputs": [{"name": "CONDITIONING", "type": "CONDITIONING", "links": [53]}], + "properties": {"Node name for S&R": "Prompt module"}, + "widgets_values": ["a photo of a pier", 7], + "widgets_values_form": {"order": ["text", "seed"]}, + "title": "custom first instance", + } + ) + workflow["last_node_id"] = 88 + return workflow, definition_id + + +def test_existing_subgraph_definition_reuses_exact_host_schema_with_fresh_instance_state( + patched_graph, tmp_path, capsys +): + workflow, definition_id = _workflow_with_subgraph_instance() + path = _write(tmp_path, workflow) + + env = _run(["add-node", str(path), definition_id, "--at", "700,300"], capsys) + + assert env["ok"] is True, env + op = env["data"]["op"] + saved = json.loads(path.read_text()) + instances = [node for node in saved["nodes"] if node["type"] == definition_id] + assert len(instances) == 2 + original, reused = instances + assert reused == op["node"] + assert op["subgraph_reuse"] == { + "definition_id": definition_id, + "existing_instance_paths": [["88"]], + } + assert reused["id"] != original["id"] + assert reused["pos"] == [700.0, 300.0] + assert reused["size"] == original["size"] + assert reused["widgets_values"] == original["widgets_values"] + assert reused["widgets_values_form"] == original["widgets_values_form"] + assert reused["properties"] == original["properties"] + assert [item["link"] for item in reused["inputs"]] == [None, None] + assert reused["outputs"][0]["links"] == [] + assert reused["flags"] == {} + assert reused["order"] == 0 + assert reused["mode"] == 0 + assert "title" not in reused + + reused["widgets_values"][0] = "second instance" + assert original["widgets_values"][0] == "a photo of a pier" + + +def test_legacy_name_typed_host_is_resolved_by_definition_id(patched_graph, tmp_path, capsys): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"][-1]["type"] = "Prompt module" + path = _write(tmp_path, workflow) + + env = _run(["add-node", str(path), definition_id, "--at", "700,300"], capsys) + + assert env["ok"] is True, env + assert env["data"]["op"]["node"]["type"] == definition_id + assert env["data"]["op"]["subgraph_reuse"]["existing_instance_paths"] == [["88"]] + + +def test_definition_without_top_level_host_stays_node_not_found(patched_graph, tmp_path, capsys): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"].pop() + path = _write(tmp_path, workflow) + + env = _run(["add-node", str(path), definition_id], capsys) + + assert env["ok"] is False + assert env["error"]["code"] == "node_not_found" + assert "matching definition and reusable instance" in json.dumps(env["error"]) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("inputs", 1), + ("outputs", {}), + ("properties", []), + ("widgets_values", "not-a-container"), + ("widgets_values_form", []), + ], +) +def test_malformed_reusable_host_schema_fails_closed(field, value): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"][-1][field] = value + + with pytest.raises(ValueError, match=f"host field {field!r}"): + workflow_ops.add_node(workflow, _graph(), definition_id) + + +def test_reused_host_preserves_object_form_size_as_a_list(): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"][-1]["size"] = {"0": 640, "1": 360} + + _saved, op = workflow_ops.add_node(workflow, _graph(), definition_id, pos=[900, 300]) + + assert op["node"]["size"] == [640.0, 360.0] + + +def test_reused_host_rejects_string_size_instead_of_reading_characters(): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"][-1]["size"] = "640,360" + + _saved, op = workflow_ops.add_node(workflow, _graph(), definition_id, pos=[900, 300]) + + assert op["node"]["size"] == list(layout.DEFAULT_SIZE) + + +def test_batch_layout_uses_reused_host_size_for_collision_avoidance(): + workflow, definition_id = _workflow_with_subgraph_instance() + workflow["nodes"][-1]["size"] = {"0": 640, "1": 360} + + saved, ops, _aliases = workflow_ops.apply_specs( + workflow, + _graph(), + [ + {"op": "add_node", "class_type": definition_id, "as": "copy"}, + {"op": "add_node", "class_type": "VAEDecode", "as": "decode"}, + ], + ) + + copied, decode = (next(node for node in saved["nodes"] if node["id"] == op["node_id"]) for op in ops) + copied_rect = layout.occupied(copied["pos"], copied["size"]) + decode_rect = layout.occupied(decode["pos"], decode["size"]) + assert not layout._overlaps(copied_rect, decode_rect) + + +def test_reuse_and_concurrent_interior_write_are_reported_as_a_conflict(): + base, definition_id = _workflow_with_subgraph_instance() + inner = copy.deepcopy(next(node for node in _base_workflow()["nodes"] if node["type"] == "KSampler")) + inner["id"] = 27 + base["definitions"]["subgraphs"][0]["nodes"] = [inner] + + _with_copy, reuse = workflow_ops.add_node(copy.deepcopy(base), _graph(), definition_id, actor="copy") + _with_edit, interior = workflow_ops.set_widget(copy.deepcopy(base), _graph(), "88/27", "steps", 9, actor="edit") + copy_then_edit = workflow_ops.apply_op( + workflow_ops.apply_op(copy.deepcopy(base), reuse, _graph()), interior, _graph() + ) + edit_then_copy = workflow_ops.apply_op( + workflow_ops.apply_op(copy.deepcopy(base), interior, _graph()), reuse, _graph() + ) + + assert workflow_ops.canonical(copy_then_edit) != workflow_ops.canonical(edit_then_copy) + assert workflow_ops.detect_conflict(reuse, interior) is True + + def test_known_class_still_adds(patched_graph, tmp_path, capsys): env = _add(tmp_path, capsys, "VAEDecode") assert env["ok"] is True, env