HEL-892: add bounded UI widget serialization and Reroute reference conversion
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
"""Small, explicit public-reference contract, never a target object_info snapshot.
|
||||
|
||||
Sources and limits: docs/hel-892/serialization-evidence/sources.json.
|
||||
Only unmodified scalar core widgets are covered. No plugin, dynamic prompt,
|
||||
seed controller, subgraph, bypass or custom serializeValue is inferred.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
PROFILE = "comfy-frontend-1.37.11-core-reference"
|
||||
|
||||
# Widget construction order, including workflow-only upload button. A None type
|
||||
# is a workflow-persisted widget with options.serialize=false in graphToPrompt.
|
||||
_LAYOUTS = {
|
||||
"Canny": (("low_threshold", float), ("high_threshold", float)),
|
||||
"ImageStitch": (
|
||||
("direction", str),
|
||||
("match_image_size", bool),
|
||||
("spacing_width", int),
|
||||
("spacing_color", str),
|
||||
),
|
||||
"LoadImage": (("image", str), ("upload", None)),
|
||||
"PreviewImage": (),
|
||||
}
|
||||
|
||||
|
||||
def reference_definitions() -> dict[str, Any]:
|
||||
"""Only public core reference schemas; no model/file availability assertion."""
|
||||
|
||||
def spec(required, outputs, optional=None):
|
||||
return {
|
||||
"input": {
|
||||
"required": {k: [v] for k, v in required.items()},
|
||||
"optional": {k: [v] for k, v in (optional or {}).items()},
|
||||
},
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
return {
|
||||
"Canny": spec(
|
||||
{"image": "IMAGE", "low_threshold": "FLOAT", "high_threshold": "FLOAT"}, ["IMAGE"]
|
||||
),
|
||||
"ImageStitch": spec(
|
||||
{
|
||||
"image1": "IMAGE",
|
||||
"direction": "COMBO",
|
||||
"match_image_size": "BOOLEAN",
|
||||
"spacing_width": "INT",
|
||||
"spacing_color": "COMBO",
|
||||
},
|
||||
["IMAGE"],
|
||||
{"image2": "IMAGE"},
|
||||
),
|
||||
"LoadImage": spec({"image": "COMBO"}, ["IMAGE", "MASK"]),
|
||||
"PreviewImage": spec({"images": "IMAGE"}, []),
|
||||
}
|
||||
|
||||
|
||||
def serialize_reference_widgets(node: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply only the pinned identity serializers; reject any extra/missing value."""
|
||||
if node.get("mode", 0) != 0:
|
||||
raise ValueError("静音/旁路不在序列化参考契约内")
|
||||
properties = node.get("properties") or {}
|
||||
expected_version = "0.17.0" if node.get("type") == "ImageStitch" else "0.21.1"
|
||||
if (
|
||||
properties.get("cnr_id", "comfy-core") != "comfy-core"
|
||||
or properties.get("ver", expected_version) != expected_version
|
||||
):
|
||||
raise ValueError("源节点声明与固定核心参考版本不符")
|
||||
layout = _LAYOUTS.get(node.get("type"))
|
||||
values = node.get("widgets_values", [])
|
||||
if layout is None or not isinstance(values, list) or len(values) != len(layout):
|
||||
raise ValueError("控件数量/形式或节点类型不在固定参考契约内")
|
||||
result = {}
|
||||
for (name, kind), value in zip(layout, values):
|
||||
if kind is None:
|
||||
if value != "image":
|
||||
raise ValueError("upload 不是已知的前端按钮占位值")
|
||||
continue
|
||||
if (kind is float and type(value) not in (int, float)) or (
|
||||
kind is not float and type(value) is not kind
|
||||
):
|
||||
raise ValueError(f"{name} 的类型不符合固定标量契约")
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def validate_reroute(node: dict[str, Any]) -> None:
|
||||
if (
|
||||
node.get("mode", 0) != 0
|
||||
or node.get("widgets_values") not in (None, [])
|
||||
or len(node.get("inputs", [])) != 1
|
||||
or len(node.get("outputs", [])) != 1
|
||||
or node["inputs"][0].get("name") != ""
|
||||
):
|
||||
raise ValueError("Reroute 必须是无控件、单入口/出口、非旁路的固定参考形式")
|
||||
|
||||
|
||||
def resolve_reference_link(nodes, links, link_id) -> list[Any]:
|
||||
"""Trace legacy six-field links through slot 0 of Reroute, preserving source slot.
|
||||
|
||||
Validate reciprocal endpoints at every hop. Fail instead of the frontend's
|
||||
optional discard of dangling links. This helper is also usable to compare
|
||||
topology alone when unsupported third-party widgets block the whole prompt.
|
||||
It makes no assertion about those third-party nodes' input/output types.
|
||||
"""
|
||||
seen = set()
|
||||
while True:
|
||||
key = str(link_id)
|
||||
if key in seen:
|
||||
raise ValueError("Reroute 链路循环")
|
||||
seen.add(key)
|
||||
link = links.get(key)
|
||||
if not isinstance(link, list) or len(link) != 6:
|
||||
raise ValueError("缺失连线或非六字段旧式连线")
|
||||
_, origin, output_slot, target, input_slot, _ = link
|
||||
upstream, downstream = nodes.get(str(origin)), nodes.get(str(target))
|
||||
if not upstream or not downstream:
|
||||
raise ValueError("悬空节点")
|
||||
for slot, sockets in (
|
||||
(output_slot, upstream.get("outputs", [])),
|
||||
(input_slot, downstream.get("inputs", [])),
|
||||
):
|
||||
if type(slot) is not int or not 0 <= slot < len(sockets):
|
||||
raise ValueError("连线槽无效")
|
||||
outgoing = upstream["outputs"][output_slot].get("links") or []
|
||||
if (
|
||||
sum(str(x) == key for x in outgoing) != 1
|
||||
or str(downstream["inputs"][input_slot].get("link")) != key
|
||||
):
|
||||
raise ValueError("连线与入口/出口记录不互相对应")
|
||||
if upstream.get("mode", 0) != 0 or downstream.get("mode", 0) != 0:
|
||||
raise ValueError("静音/旁路不在追线参考契约内")
|
||||
if upstream.get("type") != "Reroute":
|
||||
return [str(origin), output_slot]
|
||||
validate_reroute(upstream)
|
||||
if output_slot != 0:
|
||||
raise ValueError("Reroute 出口必须为零槽")
|
||||
link_id = upstream["inputs"][0].get("link")
|
||||
if link_id is None:
|
||||
raise ValueError("Reroute 无上游连线")
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
object_info does not define custom frontend widget serialization. Only named
|
||||
widgets pass. Even input_order cannot prove arbitrary frontend serialization.
|
||||
Subgraphs, virtual nodes, seed extra controls, mute and bypass need API exports.
|
||||
The separate convert_reference entry point supports a bounded public-source
|
||||
profile for offline comparison only; it never changes production eligibility.
|
||||
Subgraphs, seed extra controls, mute and bypass remain unsupported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,14 +12,47 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .serialization_reference import (
|
||||
PROFILE,
|
||||
reference_definitions,
|
||||
resolve_reference_link,
|
||||
serialize_reference_widgets,
|
||||
validate_reroute,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Conversion:
|
||||
prompt: dict[str, Any] | None
|
||||
issues: list[dict[str, Any]] = field(default_factory=list)
|
||||
reference_only: bool = False
|
||||
|
||||
|
||||
def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion:
|
||||
return _convert(source, object_info)
|
||||
|
||||
|
||||
def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
"""Offline candidate only. Never consumed by production library import.
|
||||
|
||||
An unknown profile is rejected, not interpreted as a widget-order contract.
|
||||
Public reference definitions cannot establish target execution eligibility.
|
||||
"""
|
||||
if profile != PROFILE or not isinstance(source, dict) or "nodes" not in source:
|
||||
return Conversion(
|
||||
None,
|
||||
[{"code": "invalid_reference_contract", "message": "未知参考版本或不是 UI 图"}],
|
||||
True,
|
||||
)
|
||||
try:
|
||||
result = _convert(source, reference_definitions(), reference=True)
|
||||
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
||||
return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True)
|
||||
result.reference_only = True
|
||||
return result
|
||||
|
||||
|
||||
def _convert(source, object_info=None, *, reference=False) -> Conversion:
|
||||
issues: list[dict[str, Any]] = []
|
||||
|
||||
def fail(code: str, message: str, node_id: Any = "") -> None:
|
||||
@@ -65,6 +100,29 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if str(link[0]) in links:
|
||||
fail("duplicate_link", "连线 ID 重复")
|
||||
links[str(link[0])] = link
|
||||
if reference:
|
||||
frontend_version = (source.get("extra") or {}).get("frontendVersion")
|
||||
if frontend_version is not None and frontend_version != "1.37.11":
|
||||
fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致")
|
||||
# Validate every stored link, even unused branches: never silently drop
|
||||
# an unsupported connection to obtain a partial candidate.
|
||||
for node in nodes.values():
|
||||
for slot, socket in enumerate(node.get("inputs", [])):
|
||||
lid = socket.get("link")
|
||||
if lid is not None:
|
||||
link = links.get(str(lid))
|
||||
if not link or str(link[3]) != str(node["id"]) or link[4] != slot:
|
||||
fail("reference_link_invalid", "输入与连线目标记录不对应", node["id"])
|
||||
for slot, socket in enumerate(node.get("outputs", [])):
|
||||
for lid in socket.get("links") or []:
|
||||
link = links.get(str(lid))
|
||||
if not link or str(link[1]) != str(node["id"]) or link[2] != slot:
|
||||
fail("reference_link_invalid", "输出与连线来源记录不对应", node["id"])
|
||||
for lid in links:
|
||||
try:
|
||||
resolve_reference_link(nodes, links, lid)
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc))
|
||||
prompt = {}
|
||||
for nid, node in nodes.items():
|
||||
ct = node.get("type", "")
|
||||
@@ -73,9 +131,19 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if node.get("mode", 0) != 0:
|
||||
fail("mode_requires_export", f"{ct} 包含静音/旁路状态,需 API 导出核对", nid)
|
||||
continue
|
||||
if reference and ct == "Reroute":
|
||||
try:
|
||||
validate_reroute(node)
|
||||
resolve_reference_link(nodes, links, node["inputs"][0].get("link"))
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc), nid)
|
||||
continue
|
||||
spec = info.get(ct)
|
||||
if not isinstance(spec, dict):
|
||||
fail("node_definition_unavailable", f"待提供目标机节点定义:{ct}", nid)
|
||||
if reference:
|
||||
fail("reference_node_unsupported", f"固定参考契约未覆盖节点:{ct}", nid)
|
||||
else:
|
||||
fail("node_definition_unavailable", f"待提供目标机节点定义:{ct}", nid)
|
||||
continue
|
||||
declared = {
|
||||
**spec.get("input", {}).get("required", {}),
|
||||
@@ -84,7 +152,19 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
sockets = {s["name"]: s for s in node.get("inputs", []) if "name" in s}
|
||||
widgets = node.get("widgets_values") or []
|
||||
inputs = {}
|
||||
if isinstance(widgets, dict):
|
||||
if reference:
|
||||
try:
|
||||
inputs.update(serialize_reference_widgets(node))
|
||||
if [s.get("type") for s in node.get("outputs", [])] != spec["output"]:
|
||||
raise ValueError("源输出槽不符合固定参考契约")
|
||||
names = [s.get("name") for s in node.get("inputs", [])]
|
||||
allowed = set(declared) | ({"upload"} if ct == "LoadImage" else set())
|
||||
if len(names) != len(set(names)) or set(names) - allowed:
|
||||
raise ValueError("额外或重复输入槽不在固定参考契约内")
|
||||
except (ValueError, TypeError, AttributeError) as exc:
|
||||
fail("reference_widget_unverified", str(exc), nid)
|
||||
continue
|
||||
elif isinstance(widgets, dict):
|
||||
if set(widgets) - set(declared):
|
||||
fail("unknown_widget", f"{ct} 存在节点定义以外的具名控件", nid)
|
||||
inputs.update({k: v for k, v in widgets.items() if k in declared})
|
||||
@@ -111,6 +191,13 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if node["inputs"][link[4]].get("name") != name or name not in declared:
|
||||
fail("invalid_socket", f"输入 {name} 的目标槽不匹配", nid)
|
||||
continue
|
||||
if reference:
|
||||
try:
|
||||
resolved = resolve_reference_link(nodes, links, lid)
|
||||
link = [link[0], resolved[0], resolved[1], *link[3:]]
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc), nid)
|
||||
continue
|
||||
upstream = nodes.get(str(link[1]))
|
||||
outputs = info.get((upstream or {}).get("type"), {}).get("output", [])
|
||||
if not upstream or not isinstance(link[2], int) or not 0 <= link[2] < len(outputs):
|
||||
|
||||
Reference in New Issue
Block a user