HEL-892: add opt-in pinned root Set/Get reference projection

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 04:57:59 +08:00
co-authored by multica-agent
parent 8187064129
commit efe68ecd98
29 changed files with 19931 additions and 12 deletions
@@ -39,7 +39,12 @@ from calliope.comfyui.serialization_reference import (
serialize_promoted_node,
serialize_reference_widgets,
)
from calliope.comfyui.structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES
from calliope.comfyui.structure_reference import (
PROMOTED_PROFILES,
SETGET_COMMIT,
SETGET_PROFILES,
STRUCTURE_PROFILES,
)
from calliope.comfyui.ui2api import convert, convert_reference
@@ -293,6 +298,7 @@ REFERENCE_PROFILES = (
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
*SETGET_PROFILES,
)
@@ -495,6 +501,7 @@ def profile_attempt(source, profile):
**PROMOTED_PROFILES,
CASE04_PROFILE: "1.53.6",
**VHS_PROFILES,
**SETGET_PROFILES,
}.get(profile, "1.37.11")
assumptions = {
"frontend": expected,
@@ -572,6 +579,38 @@ def profile_attempt(source, profile):
"serialization-evidence/sources.json",
]
base = {"profile": profile, "assumptions": assumptions}
if profile in SETGET_PROFILES:
assumptions["setget_reference"] = {
"commit": SETGET_COMMIT,
"missing_version": "explicit_fixed_reference_assumption_only",
"provider_policy": "exact_aux_id_required; missing/literal/conflict_rejected",
"scope": "root_only; nested_and_cross_boundary_rejected",
"name": "widgets_values/0 exact string; no normalization or previousName lookup",
"duplicates": "reject_all; frontend_first_match_is_not_emulated",
"unmodified_pinned_extensions": True,
"target_installation_and_UE_match": "unknown",
}
assumptions["reference_sources"] = [
"setget-reference/sources.json",
"vhs-reference/sources.json",
"serialization-evidence/sources.json",
]
base["verified_reference_facts"] = "setget-reference/contract.json"
base["source_declarations"] = [
{
"pointer": f"/nodes/{i}",
**{k: (n.get("properties") or {}).get(k) for k in ("cnr_id", "aux_id", "ver")},
}
for i, n in enumerate(source.get("nodes", []))
]
if not any(n.get("type") in ("SetNode", "GetNode") for n in source.get("nodes", [])):
return {
**base,
"status": "not_applicable",
"issues": [
{"code": "setget_not_present", "message": "新profile仅覆盖包含Set/Get的根图"}
],
}
if profile in (*CROP_SPLIT_PROFILES, *VHS_PROFILES):
base["source_declarations"] = [
{
@@ -594,21 +633,29 @@ def profile_attempt(source, profile):
else "requires_explicit_1.48.6"
)
assumptions["missing_frontend_policy"] = (
"explicit_media_reference_assumption"
"explicit_1.37.11_reference_assumption"
if profile in SETGET_PROFILES
else "explicit_media_reference_assumption"
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES)
else "explicit_legacy_reference_assumption"
if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE)
else "requires_explicit_declaration"
)
if profile in VHS_PROFILES and expected == "1.48.6":
if profile in (*VHS_PROFILES, *SETGET_PROFILES) and expected == "1.48.6":
assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6"
assumptions["missing_node_declarations"] = [
n["pointer"]
for n in node_inventory(source, include_aux=profile in CROP_SPLIT_PROFILES)
for n in node_inventory(
source, include_aux=profile in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES)
)
if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode")
and (n["provider"] is None or n["version"] is None)
]
if (profile in VHS_PROFILES and expected == "1.48.6" and declared_frontend is None) or (
if (
profile in (*VHS_PROFILES, *SETGET_PROFILES)
and expected == "1.48.6"
and declared_frontend is None
) or (
declared_frontend != expected
and not (
declared_frontend is None
@@ -621,6 +668,7 @@ def profile_attempt(source, profile):
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
*SETGET_PROFILES,
)
)
):
@@ -644,6 +692,11 @@ def profile_attempt(source, profile):
else "serializer_or_structure_rejected",
"issues": result.issues,
"unresolved_boundaries": result.unresolved_boundaries,
**(
{"virtual_resolutions": result.virtual_resolutions}
if profile in SETGET_PROFILES
else {}
),
}
# Legacy core serializers explicitly assume absent declarations. Record
# that assumption instead of implying that a type-name match proved it.
@@ -655,6 +708,11 @@ def profile_attempt(source, profile):
or "restored_saved_state_before_queue_hooks",
"candidate_sha256": canonical_sha(result.prompt),
"candidate_prompt": result.prompt,
**(
{"virtual_resolutions": result.virtual_resolutions}
if profile in SETGET_PROFILES
else {}
),
**(
{"field_evidence": asr_field_evidence(source, result.prompt)}
if profile == ASR_PROFILE
@@ -740,7 +798,7 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
for issue in attempt["issues"]:
gap_inventory = (
node_inventory(source, include_aux=True)
if attempt["profile"] in CROP_SPLIT_PROFILES
if attempt["profile"] in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES)
else inventory
)
matches = [n for n in gap_inventory if n["node_id"] == issue.get("node_id")]
@@ -766,7 +824,11 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
}
if baseline_profiles is None:
excluded_profiles = (
VHS_PROFILES if any(p in VHS_PROFILES for p in profiles) else CROP_SPLIT_PROFILES
SETGET_PROFILES
if any(p in SETGET_PROFILES for p in profiles)
else VHS_PROFILES
if any(p in VHS_PROFILES for p in profiles)
else CROP_SPLIT_PROFILES
)
baseline_profiles = tuple(p for p in profiles if p not in excluded_profiles)
old_complete = {
@@ -14,6 +14,8 @@ import json
import math
from typing import Any
from .structure_reference import SETGET_PROFILES
MP3_PROFILE = "comfy-frontend-1.37.11-mp3-core-0.11.0-reference"
REEL_PROFILE = "comfy-frontend-1.37.11-layerstyle-mixed-core-0.4.0-reference"
MEDIA_PROFILES = (MP3_PROFILE, REEL_PROFILE)
@@ -100,6 +102,8 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
"output": outputs,
}
if profile in SETGET_PROFILES:
return {**reference_definitions(PROFILE), **vhs_definitions()}
if profile in VHS_PROFILES:
return vhs_definitions()
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
@@ -176,6 +180,16 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]:
"""Apply only the pinned identity serializers; reject any extra/missing value."""
if profile in SETGET_PROFILES:
if node.get("type") in vhs_definitions():
return serialize_vhs_node(node)
if any(
k in container
for container in (node, node.get("properties") or {})
for k in ("widgets", "widgets_values_named", "serializeValue", "comfyDynamic")
):
raise ValueError("Set/Get组合核心参考不接受自定义serializer或额外控件")
return serialize_reference_widgets(node, PROFILE)
if profile in VHS_PROFILES:
return serialize_vhs_node(node)
if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES):
@@ -7,11 +7,17 @@ node serializers, third-party behavior, target versions or execution eligibility
from __future__ import annotations
import re
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Any
from uuid import UUID
SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18"
SETGET_PROFILES = {
f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6")
}
STRUCTURE_PROFILES = {
f"comfy-frontend-{version}-structure-reference": version
for version in ("1.48.7", "1.53.6", "1.48.6")
@@ -44,6 +50,292 @@ def _uuid(value):
return False
def project_reference_setget(source: dict) -> Structure:
"""Pinned KJ same-root saved-state projection, never a partial prompt.
Diagnostics may retain literal, unique-name topology when provenance is
ambiguous. Such paths carry rejections and NEVER yield a projected graph.
Every virtual node, edge and dependency cycle is checked, including unused
branches. No subgraph scope, rename callback or type inference is emulated.
"""
from .serialization_reference import validate_reroute
issues, resolved = [], []
def reject(message, nid=""):
issues.append({"code": "setget_reference_invalid", "node_id": str(nid), "message": message})
try:
if (source.get("definitions") or {}).get("subgraphs") or any(
_uuid(n.get("type")) for n in source["nodes"]
):
reject("Set/Get仅覆盖根图;嵌套或跨边界名字作用域未证明")
if any((source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")):
raise ValueError("Set/Get不解释UE附加连线")
nodes, indices, links, link_indices = {}, {}, {}, {}
for i, n in enumerate(source["nodes"]):
nid = _id(n["id"])
if nid in nodes:
raise ValueError("重复根图节点ID")
nodes[nid], indices[nid] = n, i
if n.get("type") not in ("Note", "MarkdownNote") and (
type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0
):
reject("根图运行节点仅支持正常mode=0", nid)
if any(
k in container
for container in (n, n.get("properties") or {})
for k in (
"getInputLink",
"resolveInput",
"resolveOutput",
"onExecute",
"isVirtualNode",
"applyToGraph",
)
):
reject("根图含自定义执行/追线覆盖", nid)
for i, edge in enumerate(source.get("links", [])):
if not isinstance(edge, list) or len(edge) != 6:
raise ValueError("Set/Get仅接受六字段根图连线")
lid, a, oslot, b, islot, typ = edge
if type(lid) is not int or lid < 0 or lid in links:
raise ValueError("连线ID非法或重复")
a, b = _id(a), _id(b)
for nid, slot, direction in ((a, oslot, "outputs"), (b, islot, "inputs")):
if (
nid not in nodes
or type(slot) is not int
or not (0 <= slot < len(nodes[nid].get(direction, [])))
):
raise ValueError("连线端点/原槽缺失")
s = nodes[nid][direction][slot]
if direction == "outputs":
ids = s.get("links") or []
if any(type(x) is not int for x in ids) or ids.count(lid) != 1:
raise ValueError("输出与连线不互指")
elif type(s.get("link")) is not int or s["link"] != lid:
raise ValueError("输入与连线不互指")
if s.get("type") != typ:
raise ValueError("每跳连线类型与两端槽必须精确一致")
if not isinstance(typ, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", typ):
raise ValueError("通配/联合/动态连线类型未证明")
links[lid], link_indices[lid] = edge, i
for nid, n in nodes.items():
for direction in ("inputs", "outputs"):
for slot, s in enumerate(n.get(direction, [])):
ids = (
[s["link"]]
if direction == "inputs" and s.get("link") is not None
else (s.get("links") or [])
if direction == "outputs"
else []
)
for lid in ids:
e = links.get(lid)
offset = 1 if direction == "outputs" else 3
if e is None or [str(e[offset]), e[offset + 1]] != [nid, slot]:
raise ValueError("槽引用缺失连线或错误端点")
setters, names, node_rejections = {}, {}, {}
virtual = {
nid for nid, n in nodes.items() if n.get("type") in ("SetNode", "GetNode", "Reroute")
}
for nid in sorted(virtual):
n = nodes[nid]
start = len(issues)
if type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0:
reject("Set/Get/Reroute只支持正常mode=0", nid)
if n["type"] == "Reroute":
try:
validate_reroute(n)
except ValueError as exc:
reject(str(exc), nid)
types = [s.get("type") for s in n.get("inputs", []) + n.get("outputs", [])]
if (
len(types) != 2
or types[0] != types[1]
or not isinstance(types[0], str)
or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", types[0])
):
reject("Reroute仅支持已保存且精确相同的具体类型", nid)
else:
props = n.get("properties") or {}
if (
props.get("aux_id") != "kijai/ComfyUI-KJNodes"
or props.get("cnr_id") is not None
):
reject("Set/Get提供方歧义或冲突;类名字面aux_id不是来源证明", nid)
if props.get("ver") not in (None, SETGET_COMMIT):
reject("Set/Get显式版本不等于固定完整提交", nid)
values = n.get("widgets_values")
if (
not isinstance(values, list)
or len(values) != 1
or type(values[0]) is not str
or not values[0]
):
reject("Set/Get要求唯一非空字符串名字控件", nid)
else:
names[nid] = values[0]
if n["type"] == "SetNode":
setters.setdefault(values[0], []).append(nid)
if (
len(n.get("inputs", [])) != (1 if n["type"] == "SetNode" else 0)
or len(n.get("outputs", [])) != 1
):
reject("Set/Get有额外或缺失槽", nid)
sockets = n.get("inputs", []) + n.get("outputs", [])
types = [s.get("type") for s in sockets]
if (
not types
or any(
not isinstance(t, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", t)
for t in types
)
or len(set(types)) != 1
):
reject("Set/Get槽类型未知或不一致;不按名字推断类型", nid)
if any(s.get("name") != s.get("type") or s.get("widget") for s in sockets):
reject("Set/Get槽构造/绑定与固定形式不符", nid)
for container in (n, n.get("properties") or {}):
if any(
k in container
for k in (
"widgets",
"widgets_values_named",
"serializeValue",
"comfyDynamic",
"getInputLink",
"onExecute",
"isVirtualNode",
)
):
reject("虚拟节点存在自定义覆盖或额外控件", nid)
props = n.get("properties") or {}
ue = props.get("ue_properties") or {}
if any(
props.get(k) or ue.get(k)
for k in ("widget_ue_connectable", "input_ue_unconnectable")
):
reject("虚拟节点UE自定义绑定未证明", nid)
node_rejections[nid] = issues[start:]
for name, ids in setters.items():
if len(ids) != 1:
reject(f"重名Set:{name!r};保守拒绝而非取首个")
def trace(nid, slot, seen=()):
token = (nid, slot)
if token in seen:
raise ValueError("Set/Get逻辑环或链式自引用")
n = nodes[nid]
hop = {
"node_id": nid,
"output_slot": slot,
"node_pointer": f"/nodes/{indices[nid]}",
"output_pointer": f"/nodes/{indices[nid]}/outputs/{slot}",
}
if nid not in virtual:
return [nid, slot], [hop], []
if slot != 0:
raise ValueError("虚拟节点出口必须为零槽")
rejection = list(node_rejections[nid])
if nid in names:
hop.update(name=names[nid], name_pointer=hop["node_pointer"] + "/widgets_values/0")
if n["type"] == "GetNode":
ids = setters.get(names.get(nid), [])
if len(ids) != 1:
raise ValueError("Get缺少唯一精确名字Set;不使用previousName/标题或规范化")
sid = ids[0]
if n["outputs"][0]["type"] != nodes[sid]["outputs"][0]["type"]:
raise ValueError("Get与Set类型冲突")
endpoint, hops, errors = trace(sid, 0, (*seen, token))
hop.update(
name=names[nid],
name_pointer=hop["node_pointer"] + "/widgets_values/0",
setter_id=sid,
)
return endpoint, [hop, *hops], rejection + errors
lid = n.get("inputs", [{}])[0].get("link")
if lid not in links:
raise ValueError("Set/Reroute无上游实际输入")
e = links[lid]
hop.update(input_slot=0, link_pointer=f"/links/{link_indices[lid]}", original_link=e)
endpoint, hops, errors = trace(str(e[1]), e[2], (*seen, token))
return endpoint, [hop, *hops], rejection + errors
# Include logical binding edges when checking ALL cycles, including
# ordinary-node cycles containing a Set/Get hop and unused bad branches.
adjacency = {nid: [] for nid in nodes}
for e in links.values():
adjacency[str(e[1])].append(str(e[3]))
for nid, n in nodes.items():
if n.get("type") == "GetNode" and len(setters.get(names.get(nid), [])) == 1:
adjacency[setters[names[nid]][0]].append(nid)
indegree = dict.fromkeys(nodes, 0)
for targets in adjacency.values():
for t in targets:
indegree[t] += 1
pending = [k for k, v in indegree.items() if not v]
visited = 0
while pending:
visited += 1
for target in adjacency[pending.pop()]:
indegree[target] -= 1
if not indegree[target]:
pending.append(target)
if visited != len(nodes):
reject("根图含物理或Set/Get逻辑依赖环")
# Resolve every virtual node, even if its output has no consumers.
for nid in sorted(virtual):
try:
trace(nid, 0)
except (ValueError, KeyError, IndexError, TypeError) as exc:
reject(str(exc), nid)
graph = deepcopy(source)
kept = {str(n["id"]): n for n in graph["nodes"] if str(n["id"]) not in virtual}
edges = []
for e in links.values():
if str(e[3]) in virtual:
continue
try:
endpoint, hops, errors = trace(str(e[1]), e[2])
if str(e[1]) in virtual:
resolved.append(
{
"target_node_id": str(e[3]),
"target_input_slot": e[4],
"target_input_name": nodes[str(e[3])]["inputs"][e[4]]["name"],
"original_link_pointer": f"/links/{link_indices[e[0]]}",
"original_link": e,
"endpoint": endpoint,
"hops": hops,
"binding_rejections": errors,
"authority": "literal_topology_only"
if errors or issues
else "pinned_reference_assumption_only",
}
)
edges.append([e[0], int(endpoint[0]), endpoint[1], *e[3:]])
except (ValueError, KeyError, IndexError, TypeError) as exc:
reject(str(exc), e[3])
if issues:
for resolution in resolved:
resolution["whole_graph_rejected"] = True
resolution["authority"] = "literal_topology_only"
return Structure(None, issues, resolved=resolved)
for n in kept.values():
for s in n.get("outputs", []):
s["links"] = []
for e in edges:
kept[str(e[1])]["outputs"][e[2]]["links"].append(e[0])
graph["nodes"], graph["links"] = list(kept.values()), edges
return Structure(graph, resolved=resolved)
except (ValueError, TypeError, KeyError, IndexError, AttributeError, RecursionError) as exc:
reject(str(exc))
return Structure(None, issues, resolved=resolved)
def expand_reference_subgraphs(
source: dict, profile: str, *, widgets: bool = False, case04: bool = False
) -> Structure:
@@ -34,7 +34,13 @@ from .serialization_reference import (
serialize_reference_widgets,
validate_reroute,
)
from .structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES, expand_reference_subgraphs
from .structure_reference import (
PROMOTED_PROFILES,
SETGET_PROFILES,
STRUCTURE_PROFILES,
expand_reference_subgraphs,
project_reference_setget,
)
@dataclass
@@ -46,6 +52,7 @@ class Conversion:
unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
resolved_boundaries: list[dict[str, Any]] = field(default_factory=list)
serialization_stage: str | None = None
virtual_resolutions: list[dict[str, Any]] = field(default_factory=list)
def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion:
@@ -67,6 +74,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
SEPARATION_PROFILE,
*CROP_SPLIT_PROFILES,
*VHS_PROFILES,
*SETGET_PROFILES,
AUX_PROFILE,
PRIMITIVE_PROFILE,
PREVIEW_PROFILE,
@@ -83,6 +91,27 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
True,
)
try:
if profile in SETGET_PROFILES:
expected = SETGET_PROFILES[profile]
declared = (source.get("extra") or {}).get("frontendVersion")
if declared != expected and not (declared is None and expected == "1.37.11"):
raise ValueError("Set/Get前端声明不匹配;缺失仅显式选择1.37.11")
structure = project_reference_setget(source)
if structure.graph is None:
return Conversion(
None, structure.issues, True, virtual_resolutions=structure.resolved
)
result = _convert(
structure.graph,
reference_definitions(profile),
reference=True,
reference_profile=profile,
)
result.reference_only = True
result.virtual_resolutions = structure.resolved
result.diagnostic_graph = structure.graph
result.serialization_stage = "restored_saved_state_before_queue_hooks"
return result
if (
profile in VHS_PROFILES
and VHS_PROFILES[profile] == "1.48.6"
@@ -226,6 +255,7 @@ def _convert(
**PROMOTED_PROFILES,
CASE04_PROFILE: "1.53.6",
**VHS_PROFILES,
**SETGET_PROFILES,
}.get(reference_profile, "1.37.11")
if frontend_version is not None and frontend_version != expected_version:
fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致")
@@ -362,7 +362,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari
profiles = tuple(
p
for p in audit.REFERENCE_PROFILES
if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES)
if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES, *audit.SETGET_PROFILES)
)
baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE)
old = audit.audit_library(REPO, baseline)
@@ -351,7 +351,9 @@ def test_two_disjoint_instances_preserve_nodes_links_and_values(profile):
def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged():
historical_profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES)
historical_profiles = tuple(
p for p in audit.REFERENCE_PROFILES if p not in (*VHS_PROFILES, *audit.SETGET_PROFILES)
)
profiles = tuple(p for p in historical_profiles if p not in CROP_SPLIT_PROFILES)
historical = json.loads((REPO / "docs/hel-892/separation-evidence/library.json").read_bytes())
baseline = audit.audit_library(REPO, profiles)
@@ -0,0 +1,423 @@
"""Saved-state transformation tests; never execute upstream JS or a ComfyUI job."""
from __future__ import annotations
import copy
import json
from pathlib import Path
import pytest
from scripts import audit_reference_conversion as audit
from scripts.verify_frontend_sources import verify
from calliope.comfyui.structure_reference import (
SETGET_PROFILES,
project_reference_setget,
)
from calliope.comfyui.ui2api import convert, convert_reference
REPO = Path(__file__).resolve().parents[2]
PROFILE = next(iter(SETGET_PROFILES))
def virtual(nid, kind, name, typ="IMAGE"):
return {
"id": nid,
"type": kind,
"mode": 0,
"properties": {"aux_id": "kijai/ComfyUI-KJNodes", "previousName": "old"},
"widgets_values": [name],
"inputs": [{"name": typ, "type": typ, "link": None}] if kind == "SetNode" else [],
"outputs": [{"name": typ, "type": typ, "links": []}],
}
def connect(graph, lid, origin, oslot, target, tslot, typ="IMAGE"):
nodes = {n["id"]: n for n in graph["nodes"]}
nodes[origin]["outputs"][oslot].setdefault("links", []).append(lid)
nodes[target]["inputs"][tslot]["link"] = lid
graph["links"].append([lid, origin, oslot, target, tslot, typ])
def synthetic():
graph = {
"nodes": [
{
"id": 1,
"type": "LoadImage",
"widgets_values": ["one.png", "image"],
"inputs": [],
"outputs": [{"type": "IMAGE", "links": []}, {"type": "MASK", "links": []}],
},
virtual(2, "SetNode", "图片"),
virtual(3, "GetNode", "图片"),
{
"id": 4,
"type": "PreviewImage",
"widgets_values": [],
"inputs": [{"name": "images", "type": "IMAGE", "link": None}],
"outputs": [],
},
],
"links": [],
}
connect(graph, 1, 1, 0, 2, 0)
connect(graph, 2, 3, 0, 4, 0)
return graph
def test_fixed_originals_and_registration_call_chain():
root = REPO / "docs/hel-892/setget-reference"
assert len(verify(root)["sources_verified"]) == 19
js = (root / "web__js__setgetnodes.js").read_text()
for text in (
'LiteGraph.registerNodeType("SetNode", SetNode)',
'LiteGraph.registerNodeType("GetNode", GetNode)',
"this.isVirtualNode = true",
"getInputLink(slot)",
"n.type === 'SetNode' && n.widgets[0].value === name",
"if (app.configuringGraph) return;",
"if (this._justAdded && !app.configuringGraph)",
"this.properties.previousName = this.widgets[0].value;",
):
assert text in js
for v in SETGET_PROFILES.values():
dto = (root / f"{v}__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts").read_text()
assert "const virtualLink = this.node.getInputLink(slot)" in dto
assert "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)" in dto
node = (root / f"{v}__src__lib__litegraph__src__LGraphNode.ts").read_text()
assert "widget.value = info.widgets_values[i++]" in node
assert "getInputLink(slot: number)" in node
@pytest.mark.parametrize("profile", SETGET_PROFILES)
def test_complete_projection_and_production_stays_closed(profile):
g = synthetic()
g["extra"] = {"frontendVersion": SETGET_PROFILES[profile]}
original = copy.deepcopy(g)
result = convert_reference(g, profile)
assert result.prompt is not None, result.issues
assert set(result.prompt) == {"1", "4"}
assert result.prompt["4"]["inputs"]["images"] == ["1", 0]
assert result.prompt["1"]["inputs"]["image"] == "one.png"
assert [h["node_id"] for h in result.virtual_resolutions[0]["hops"]] == ["3", "2", "1"]
assert result.reference_only
assert convert(g).prompt is None
assert g == original
@pytest.mark.parametrize("name", ["图片", " A ", "a", "A", "e\u0301", "\u00e9", " "])
def test_exact_names_rename_previous_name_and_upstream_changes(name):
g = synthetic()
g["nodes"][1]["widgets_values"] = [name]
g["nodes"][2]["widgets_values"] = [name]
g["nodes"][1]["properties"]["previousName"] = "图片"
result = convert_reference(g, PROFILE)
assert result.prompt is not None
assert result.virtual_resolutions[0]["hops"][0]["name"] == name
g["nodes"][0]["widgets_values"][0] = "changed.png"
assert convert_reference(g, PROFILE).prompt["1"]["inputs"]["image"] == "changed.png"
g["nodes"][2]["widgets_values"] = ["not_current"]
g["nodes"][1]["properties"]["previousName"] = "not_current"
g["nodes"][1]["title"] = "not_current"
assert convert_reference(g, PROFILE).prompt is None
@pytest.mark.parametrize("other", ["a", "A ", " A", "e\u0301"])
def test_no_name_normalization(other):
g = synthetic()
g["nodes"][1]["widgets_values"] = ["A" if other != "e\u0301" else "\u00e9"]
g["nodes"][2]["widgets_values"] = [other]
assert convert_reference(g, PROFILE).prompt is None
def test_multiple_names_and_changing_binding_selects_correct_source():
g = synthetic()
other = copy.deepcopy(g["nodes"][0])
other["id"] = 11
other["widgets_values"][0] = "two.png"
other["outputs"][0]["links"] = []
g["nodes"] += [other, virtual(12, "SetNode", "second")]
connect(g, 11, 11, 0, 12, 0)
assert convert_reference(g, PROFILE).prompt["4"]["inputs"]["images"] == ["1", 0]
g["nodes"][2]["widgets_values"] = ["second"]
result = convert_reference(g, PROFILE)
assert result.prompt["4"]["inputs"]["images"] == ["11", 0]
assert result.prompt["11"]["inputs"]["image"] == "two.png"
def test_fanout_direct_set_and_multilevel_reroute_preserve_original_slot():
g = synthetic()
g["nodes"][0]["outputs"][1]["type"] = "IMAGE" # topology fixture only
g["nodes"][0]["outputs"][0]["links"] = []
g["nodes"][0]["outputs"][1]["links"] = [1]
g["links"][0][2] = 1
g["nodes"] += [
virtual(5, "GetNode", "图片"),
virtual(6, "SetNode", "next"),
virtual(7, "GetNode", "next"),
{
"id": 8,
"type": "Reroute",
"widgets_values": [],
"inputs": [{"name": "", "type": "IMAGE", "link": None}],
"outputs": [{"name": "", "type": "IMAGE", "links": []}],
},
copy.deepcopy(g["nodes"][3]),
]
g["nodes"][-1]["id"] = 9
g["nodes"][-1]["inputs"][0]["link"] = None
connect(g, 3, 5, 0, 6, 0)
connect(g, 4, 7, 0, 8, 0)
connect(g, 5, 8, 0, 9, 0)
# Direct Set output feeds an additional sink; Get fanout is independent.
sink = copy.deepcopy(g["nodes"][3])
sink["id"] = 10
sink["inputs"][0]["link"] = None
g["nodes"].append(sink)
connect(g, 6, 2, 0, 10, 0)
projected = project_reference_setget(g)
assert projected.graph is not None, projected.issues
assert {tuple(e["endpoint"]) for e in projected.resolved} == {("1", 1)}
assert len(projected.resolved) == 3
last = next(r for r in projected.resolved if r["target_node_id"] == "9")
assert [h["node_id"] for h in last["hops"]] == ["8", "7", "6", "5", "2", "1"]
assert [e[2] for e in projected.graph["links"]] == [1, 1, 1]
@pytest.mark.parametrize(
"mutation",
[
"duplicate",
"missing_set",
"empty",
"bad_name",
"extra_widget",
"mapping_widget",
"bad_aux",
"missing_aux",
"literal_aux",
"bad_version",
"bad_cnr",
"extra_input",
"extra_output",
"bad_type",
"wildcard",
"union",
"mode",
"bool_mode",
"custom_serializer",
"custom_properties",
"custom_binding",
"bad_slot_name",
"bad_reciprocal",
"dangling",
"bool_slot",
"bool_link",
"wrong_edge_type",
"physical_cycle",
"logical_cycle",
"unused_bad_get",
"unused_bad_set",
"nested",
"uuid",
"ue_edges",
],
)
def test_fail_closed_mutations_including_unused_branches(mutation):
g = synthetic()
s = g["nodes"][1]
get = g["nodes"][2]
if mutation == "duplicate":
extra = copy.deepcopy(s)
extra["id"] = 22
extra["inputs"][0]["link"] = None
g["nodes"].append(extra)
elif mutation == "missing_set":
s["widgets_values"] = ["other"]
elif mutation == "empty":
get["widgets_values"] = [""]
elif mutation == "bad_name":
get["widgets_values"] = [True]
elif mutation == "extra_widget":
get["widgets_values"].append("extra")
elif mutation == "mapping_widget":
get["widgets_values"] = {"Constant": "图片"}
elif mutation == "bad_aux":
s["properties"]["aux_id"] = "rgthree/rgthree-comfy"
elif mutation == "missing_aux":
s["properties"].pop("aux_id")
elif mutation == "literal_aux":
s["properties"]["aux_id"] = "SetNode"
elif mutation == "bad_version":
s["properties"]["ver"] = "1.0.0"
elif mutation == "bad_cnr":
s["properties"]["cnr_id"] = "other"
elif mutation == "extra_input":
get["inputs"] = [{"name": "IMAGE", "type": "IMAGE", "link": None}]
elif mutation == "extra_output":
get["outputs"].append(copy.deepcopy(get["outputs"][0]))
elif mutation == "bad_type":
get["outputs"][0]["type"] = "FLOAT"
g["links"][1][5] = "FLOAT"
g["nodes"][3]["inputs"][0]["type"] = "FLOAT"
elif mutation in ("wildcard", "union"):
s["outputs"][0]["type"] = "*" if mutation == "wildcard" else "IMAGE,MASK"
elif mutation == "mode":
get["mode"] = 4
elif mutation == "bool_mode":
get["mode"] = False
elif mutation == "custom_serializer":
get["serializeValue"] = "override"
elif mutation == "custom_properties":
s["properties"]["getInputLink"] = "override"
elif mutation == "custom_binding":
s["properties"]["ue_properties"] = {"widget_ue_connectable": {"Constant": True}}
elif mutation == "bad_slot_name":
s["inputs"][0]["name"] = "other"
elif mutation == "bad_reciprocal":
g["nodes"][0]["outputs"][0]["links"] = []
elif mutation == "dangling":
g["links"][0][1] = 999
elif mutation == "bool_slot":
g["links"][0][2] = False
elif mutation == "bool_link":
g["links"][0][0] = True
elif mutation == "wrong_edge_type":
g["links"][0][5] = "MASK"
elif mutation in ("physical_cycle", "logical_cycle"):
g["nodes"][0]["outputs"][0]["links"] = []
g["links"].pop(0)
connect(g, 1, 2 if mutation == "physical_cycle" else 3, 0, 2, 0)
elif mutation == "unused_bad_get":
g["nodes"].append(virtual(99, "GetNode", "missing"))
elif mutation == "unused_bad_set":
g["nodes"].append(virtual(99, "SetNode", "unused"))
elif mutation == "nested":
g["definitions"] = {"subgraphs": [{"id": "any"}]}
elif mutation == "uuid":
g["nodes"].append({"id": 88, "type": "e61f4fd0-e251-4d58-bfa4-cf163fa86577"})
elif mutation == "ue_edges":
g["extra"] = {"ue_links": [1]}
result = convert_reference(g, PROFILE)
assert result.prompt is None, mutation
assert result.issues, mutation
def test_unknown_ordinary_node_blocks_whole_graph_with_reference_trace_retained():
g = synthetic()
g["nodes"][0]["type"] = "UnknownImageProducer"
result = convert_reference(g, PROFILE)
assert result.prompt is None
assert result.virtual_resolutions[0]["endpoint"] == ["1", 0]
assert any(i["code"] == "reference_node_unsupported" for i in result.issues)
def test_ambiguous_provider_trace_is_explicitly_untrusted():
g = synthetic()
g["nodes"][1]["properties"]["aux_id"] = "SetNode"
result = convert_reference(g, PROFILE)
assert result.prompt is None and result.diagnostic_graph is None
trace = result.virtual_resolutions[0]
assert trace["endpoint"] == ["1", 0]
assert trace["authority"] == "literal_topology_only" and trace["binding_rejections"]
def test_wrong_frontend_missing_policy_and_profile_inventory():
p1486 = list(SETGET_PROFILES)[1]
assert convert_reference(synthetic(), p1486).prompt is None
for v in ["1.48.7", "1.53.6", "1.37.11-other"]:
g = synthetic()
g["extra"] = {"frontendVersion": v}
assert convert_reference(g, PROFILE).prompt is None
assert len(audit.REFERENCE_PROFILES) == 20
@pytest.mark.parametrize("profile", SETGET_PROFILES)
def test_vhs_composition_preserves_nonzero_audio_slot_and_exact_commits(profile):
prefix = "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/"
source = json.loads((REPO / (prefix + "多视频合成分屏展示.json")).read_bytes())
load = next(n for n in source["nodes"] if n["id"] == 17)
source = json.loads(
(
REPO
/ (
"example_ComfyUI_workflows/4-视频生成/Minimax-h3/"
"Minimax_H3_T8双时钟采样_参考生视频-8步高质量极速版.json"
)
).read_bytes()
)
combine = next(n for n in source["nodes"] if n["id"] == 12)
for n in (load, combine):
n.pop("widgets_values_named", None)
for s in n["inputs"]:
s["link"] = None
for s in n["outputs"]:
s["links"] = []
graph = {
"nodes": [
load,
combine,
virtual(900, "SetNode", "audio", "AUDIO"),
virtual(901, "GetNode", "audio", "AUDIO"),
],
"links": [],
"extra": {"frontendVersion": SETGET_PROFILES[profile]},
}
connect(graph, 1, 17, 0, 12, 0)
connect(graph, 2, 17, 2, 900, 0, "AUDIO")
connect(graph, 3, 901, 0, 12, 1, "AUDIO")
result = convert_reference(graph, profile)
assert result.prompt is not None, result.issues
assert result.prompt["12"]["inputs"]["audio"] == ["17", 2]
assert result.prompt["12"]["inputs"]["images"] == ["17", 0]
assert result.prompt["17"]["inputs"]["force_rate"] == 16
load["widgets_values"]["force_rate"] = 20
assert convert_reference(graph, profile).prompt["17"]["inputs"]["force_rate"] == 20
load["properties"]["ver"] = "1.7.9"
assert convert_reference(graph, profile).prompt is None
@pytest.mark.parametrize(
"mutation", ["reroute_type", "ordinary_override", "ordinary_mode", "ordinary_cycle"]
)
def test_combined_structure_rejects_other_graph_overrides_and_cycles(mutation):
g = synthetic()
if mutation == "reroute_type":
g["nodes"][1] = {
"id": 2,
"type": "Reroute",
"widgets_values": [],
"inputs": [{"name": "", "type": "IMAGE", "link": 1}],
"outputs": [{"type": "MASK", "links": []}],
}
elif mutation == "ordinary_override":
g["nodes"][0]["resolveOutput"] = "custom"
elif mutation == "ordinary_mode":
g["nodes"][0]["mode"] = False
else:
# Ordinary producer feeds Set, Get feeds the same producer input.
g["nodes"][0]["inputs"] = [{"name": "images", "type": "IMAGE", "link": None}]
connect(g, 3, 3, 0, 1, 0)
assert convert_reference(g, PROFILE).prompt is None
def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged():
old = json.loads((REPO / "docs/hel-892/vhs-evidence/library.json").read_bytes())
baseline = tuple(p for p in audit.REFERENCE_PROFILES if p not in SETGET_PROFILES)
now = audit.audit_library(REPO, baseline_profiles=baseline)
actual_old = audit.audit_library(REPO, baseline)
assert len(baseline) == 18
assert actual_old["gap_groups"] == old["gap_groups"]
for historical, previous, current in zip(old["cases"], actual_old["cases"], now["cases"]):
assert historical["source_path"] == previous["source_path"] == current["source_path"]
assert historical["attempts"] == previous["attempts"] == current["attempts"][:18]
assert (
historical.get("comparisons")
== previous.get("comparisons")
== current.get("comparisons")
)
assert now["coverage_delta"]["baseline_profiles"] == list(baseline)
assert audit.audit(REPO, "case04-batch-reference") == json.loads(
(REPO / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes()
)
+6 -2
View File
@@ -285,9 +285,13 @@ def test_real_five_load_instances_are_distinct_and_modes_not_dropped():
def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected():
old = json.loads((REPO / "docs/hel-892/crop-split-evidence/library.json").read_bytes())
profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES)
# Freeze this batch's 18-profile history; Set/Get has separate current protection.
historical_profiles = tuple(
p for p in audit.REFERENCE_PROFILES if p not in audit.SETGET_PROFILES
)
profiles = tuple(p for p in historical_profiles if p not in VHS_PROFILES)
baseline = audit.audit_library(REPO, profiles)
now = audit.audit_library(REPO, baseline_profiles=profiles)
now = audit.audit_library(REPO, historical_profiles, baseline_profiles=profiles)
assert len(profiles) == 16 and len(now["profiles"]) == 18
assert old["gap_groups"] == baseline["gap_groups"]
for previous, before, after in zip(old["cases"], baseline["cases"], now["cases"]):
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,118 @@
import path from 'path'
import type { Plugin } from 'vite'
interface ShimResult {
code: string
exports: string[]
}
const SKIP_WARNING_FILES = new Set(['scripts/app', 'scripts/api'])
/** Files that will be removed in v1.34 */
const DEPRECATED_FILES = ['scripts/ui', 'extensions/core/groupNode'] as const
function getWarningMessage(
fileKey: string,
shimFileName: string
): string | null {
if (SKIP_WARNING_FILES.has(fileKey)) {
return null
}
const isDeprecated = DEPRECATED_FILES.some((deprecatedPath) =>
fileKey.startsWith(deprecatedPath)
)
if (isDeprecated) {
return `[ComfyUI Deprecated] Importing from "${shimFileName}" is deprecated and will be removed in v1.34.`
}
return `[ComfyUI Notice] "${shimFileName}" is an internal module, not part of the public API. Future updates may break this import.`
}
function isLegacyFile(id: string): boolean {
return (
id.endsWith('.ts') &&
(id.includes('src/extensions/core') || id.includes('src/scripts'))
)
}
function transformExports(code: string, id: string): ShimResult {
const moduleName = getModuleName(id)
const exports: string[] = []
let newCode = code
// Regex to match different types of exports
const regex =
/export\s+(const|let|var|function|class|async function)\s+([a-zA-Z$_][a-zA-Z\d$_]*)(\s|\()/g
let match
while ((match = regex.exec(code)) !== null) {
const name = match[2]
// All exports should be bind to the window object as new API endpoint.
if (exports.length == 0) {
newCode += `\nwindow.comfyAPI = window.comfyAPI || {};`
newCode += `\nwindow.comfyAPI.${moduleName} = window.comfyAPI.${moduleName} || {};`
}
newCode += `\nwindow.comfyAPI.${moduleName}.${name} = ${name};`
exports.push(
`export const ${name} = window.comfyAPI.${moduleName}.${name};\n`
)
}
return {
code: newCode,
exports
}
}
function getModuleName(id: string): string {
// Simple example to derive a module name from the file path
const parts = id.split('/')
const fileName = parts[parts.length - 1]
return fileName.replace(/\.\w+$/, '') // Remove file extension
}
export function comfyAPIPlugin(isDev: boolean): Plugin {
return {
name: 'comfy-api-plugin',
transform(code: string, id: string) {
if (isDev) return null
if (isLegacyFile(id)) {
const result = transformExports(code, id)
if (result.exports.length > 0) {
const projectRoot = process.cwd()
const relativePath = path
.relative(path.join(projectRoot, 'src'), id)
.replace(/\\/g, '/')
const shimFileName = relativePath.replace(/\.ts$/, '.js')
let shimContent = `// Shim for ${relativePath}\n`
const fileKey = relativePath.replace(/\.ts$/, '')
const warningMessage = getWarningMessage(fileKey, shimFileName)
if (warningMessage) {
// It will only display once because it is at the root of the file.
shimContent += `console.warn('${warningMessage}');\n`
}
shimContent += result.exports.join('')
this.emitFile({
type: 'asset',
fileName: shimFileName,
source: shimContent
})
}
return {
code: result.code,
map: null // If you're not modifying the source map, return null
}
}
}
}
}
@@ -0,0 +1,43 @@
import { isCloud } from '@/platform/distribution/types'
import {
configValueOrDefault,
remoteConfig
} from '@/platform/remoteConfig/remoteConfig'
const PROD_API_BASE_URL = 'https://api.comfy.org'
const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org'
const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org'
const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org'
const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__
? PROD_API_BASE_URL
: STAGING_API_BASE_URL
const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__
? PROD_PLATFORM_BASE_URL
: STAGING_PLATFORM_BASE_URL
export function getComfyApiBaseUrl(): string {
if (!isCloud) {
return BUILD_TIME_API_BASE_URL
}
return configValueOrDefault(
remoteConfig.value,
'comfy_api_base_url',
BUILD_TIME_API_BASE_URL
)
}
export function getComfyPlatformBaseUrl(): string {
if (!isCloud) {
return BUILD_TIME_PLATFORM_BASE_URL
}
return configValueOrDefault(
remoteConfig.value,
'comfy_platform_base_url',
BUILD_TIME_PLATFORM_BASE_URL
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,408 @@
import type { LGraph } from '@/lib/litegraph/src/LGraph'
import type { LGraphNode, NodeId } from '@/lib/litegraph/src/LGraphNode'
import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError'
import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError'
import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError'
import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError'
import type {
CallbackParams,
CallbackReturn,
ISlotType
} from '@/lib/litegraph/src/interfaces'
import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph'
import type { Subgraph } from './Subgraph'
import type { SubgraphNode } from './SubgraphNode'
export type ExecutionId = string
/**
* Interface describing the data transfer objects used when compiling a graph for execution.
*/
export type ExecutableLGraphNode = Omit<
ExecutableNodeDTO,
'graph' | 'node' | 'subgraphNode'
>
/**
* The end result of resolving a DTO input.
* When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`.
*/
type ResolvedInput = {
/** DTO for the node that the link originates from. */
node: ExecutableLGraphNode
/** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */
origin_id: ExecutionId
/** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */
origin_slot: number
/** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */
widgetInfo?: { value: unknown }
}
/**
* Concrete implementation of {@link ExecutableLGraphNode}.
* @remarks This is the class that is used to create the data transfer objects for executable nodes.
*/
export class ExecutableNodeDTO implements ExecutableLGraphNode {
applyToGraph?(
...args: CallbackParams<typeof this.node.applyToGraph>
): CallbackReturn<typeof this.node.applyToGraph>
/** The graph that this node is a part of. */
readonly graph: LGraph | Subgraph
inputs: { linkId: number | null; name: string; type: ISlotType }[]
/** Backing field for {@link id}. */
#id: ExecutionId
/**
* The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances),
* followed by the actual original node ID within the subgraph. Each segment is separated by `:`.
*
* e.g. `1:2:3`:
* - `1` is the node ID of the first subgraph node in the parent workflow
* - `2` is the node ID of the second subgraph node in the first subgraph
* - `3` is the node ID of the actual node in the subgraph definition
*/
get id() {
return this.#id
}
get type() {
return this.node.type
}
get title() {
return this.node.title
}
get mode() {
return this.node.mode
}
get comfyClass() {
return this.node.comfyClass
}
get isVirtualNode() {
return this.node.isVirtualNode
}
get widgets() {
return this.node.widgets
}
get subgraphId() {
return this.subgraphNode?.subgraph.id
}
constructor(
/** The actual node that this DTO wraps. */
readonly node: LGraphNode | SubgraphNode,
/** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */
readonly subgraphNodePath: readonly NodeId[],
/** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */
readonly nodesByExecutionId: Map<ExecutionId, ExecutableLGraphNode>,
/** The actual subgraph instance that contains this node, otherwise undefined. */
readonly subgraphNode?: SubgraphNode
) {
if (!node.graph) throw new NullGraphError()
// Set the internal ID of the DTO
this.#id = [...this.subgraphNodePath, this.node.id].join(':')
this.graph = node.graph
this.inputs = this.node.inputs.map((x) => ({
linkId: x.link,
name: x.name,
type: x.type
}))
// Only create a wrapper if the node has an applyToGraph method
if (this.node.applyToGraph) {
this.applyToGraph = (...args) => this.node.applyToGraph?.(...args)
}
}
/** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */
getInnerNodes(): ExecutableLGraphNode[] {
return this.node.isSubgraphNode()
? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath)
: [this]
}
/**
* Resolves the executable node & link IDs for a given input slot.
* @param slot The slot index of the input.
* @param visited Leave empty unless overriding this method.
* A set of unique IDs, used to guard against infinite recursion.
* If overriding, ensure that the set is passed on all recursive calls.
* @returns The node and the origin ID / slot index of the output.
*/
resolveInput(
slot: number,
visited = new Set<string>(),
type?: ISlotType
): ResolvedInput | undefined {
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}`
if (visited.has(uniqueId)) {
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
const pathInfo =
this.subgraphNodePath.length > 0
? ` at path ${this.subgraphNodePath.join(':')}`
: ''
throw new RecursionError(
`Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` +
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
)
}
visited.add(uniqueId)
const input = this.inputs.at(slot)
if (!input)
throw new SlotIndexError(
`No input found for flattened id [${this.id}] slot [${slot}]`
)
// Nothing connected
if (input.linkId == null) return
const link = this.graph.getLink(input.linkId)
if (!link)
throw new InvalidLinkError(
`No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}`
)
const { subgraphNode } = this
// Link goes up and out of this subgraph
if (subgraphNode && link.originIsIoNode) {
const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot)
if (!subgraphNodeInput)
throw new SlotIndexError(
`No input found for slot [${link.origin_slot}] ${input.name}`
)
// Nothing connected
const linkId = subgraphNodeInput.link
if (linkId == null) {
const widget = subgraphNode.getWidgetFromSlot(subgraphNodeInput)
if (!widget) return
// Special case: SubgraphNode widget.
return {
node: this,
origin_id: this.id,
origin_slot: -1,
widgetInfo: { value: widget.value }
}
}
const outerLink = subgraphNode.graph.getLink(linkId)
if (!outerLink)
throw new InvalidLinkError(
`No outer link found for slot [${link.origin_slot}] ${input.name}`
)
const subgraphNodeExecutionId = this.subgraphNodePath.join(':')
const subgraphNodeDto = this.nodesByExecutionId.get(
subgraphNodeExecutionId
)
if (!subgraphNodeDto)
throw new Error(
`No subgraph node DTO found for id [${subgraphNodeExecutionId}]`
)
return subgraphNodeDto.resolveInput(outerLink.target_slot, visited)
}
// Not part of a subgraph; use the original link
const outputNode = this.graph.getNodeById(link.origin_id)
if (!outputNode)
throw new InvalidLinkError(
`No input node found for id [${this.id}] slot [${slot}] ${input.name}`
)
const outputNodeExecutionId = [
...this.subgraphNodePath,
outputNode.id
].join(':')
const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId)
if (!outputNodeDto)
throw new Error(
`No output node DTO found for id [${outputNodeExecutionId}]`
)
return outputNodeDto.resolveOutput(
link.origin_slot,
type ?? input.type,
visited
)
}
/**
* Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass).
* @param slot The slot index of the output.
* @param type The type of the input
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
* @returns The node and the origin ID / slot index of the output.
*/
resolveOutput(
slot: number,
type: ISlotType,
visited: Set<string>
): ResolvedInput | undefined {
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}`
if (visited.has(uniqueId)) {
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
const pathInfo =
this.subgraphNodePath.length > 0
? ` at path ${this.subgraphNodePath.join(':')}`
: ''
throw new RecursionError(
`Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` +
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
)
}
visited.add(uniqueId)
// Upstreamed: Bypass nodes are bypassed using the first input with matching type
if (this.mode === LGraphEventMode.BYPASS) {
// Bypass nodes by finding first input with matching type
const matchingIndex = this.#getBypassSlotIndex(slot, type)
// No input types match - bypass not possible
if (matchingIndex === -1) {
console.warn(
`[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`,
this
)
return
}
return this.resolveInput(matchingIndex, visited)
}
const { node } = this
if (node.isSubgraphNode())
return this.#resolveSubgraphOutput(slot, type, visited)
if (node.isVirtualNode) {
const virtualLink = this.node.getInputLink(slot)
if (virtualLink) {
const { inputNode } = virtualLink.resolve(this.graph)
if (!inputNode)
throw new InvalidLinkError(
`Virtual node failed to resolve parent [${this.id}] slot [${slot}]`
)
const inputNodeExecutionId = [
...this.subgraphNodePath,
inputNode.id
].join(':')
const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId)
if (!inputNodeDto)
throw new Error(`No input node DTO found for id [${inputNode.id}]`)
return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)
}
// Virtual nodes without a matching input should be discarded.
return
}
return {
node: this,
origin_id: this.id,
origin_slot: slot
}
}
/**
* Finds the index of the input slot on this node that matches the given output {@link slot} index.
* Used when bypassing nodes.
* @param slot The output slot index on this node
* @param type The type of the final target input (so type list matches are accurate)
* @returns The index of the input slot on this node, otherwise `-1`.
*/
#getBypassSlotIndex(slot: number, type: ISlotType) {
const { inputs } = this
const oppositeInput = inputs[slot]
const outputType = this.node.outputs[slot].type
// Any type short circuit - match slot ID, fallback to first slot
if (type === '*' || type === '') {
return inputs.length > slot ? slot : 0
}
// Prefer input with the same slot ID
if (
oppositeInput &&
LiteGraph.isValidConnection(oppositeInput.type, outputType) &&
LiteGraph.isValidConnection(oppositeInput.type, type)
) {
return slot
}
// Preserve legacy behaviour; use exact match first.
const exactMatch = inputs.findIndex((input) => input.type === type)
if (exactMatch !== -1) return exactMatch
// Find first matching slot - prefer exact type
return inputs.findIndex(
(input) =>
LiteGraph.isValidConnection(input.type, outputType) &&
LiteGraph.isValidConnection(input.type, type)
)
}
/**
* Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph.
* @param slot The slot index of the output on the subgraph node.
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
* @returns A DTO for the node, and the origin ID / slot index of the output.
*/
#resolveSubgraphOutput(
slot: number,
type: ISlotType,
visited: Set<string>
): ResolvedInput | undefined {
const { node } = this
const output = node.outputs.at(slot)
if (!output)
throw new SlotIndexError(
`No output found for flattened id [${this.id}] slot [${slot}]`
)
if (!node.isSubgraphNode())
throw new TypeError(`Node is not a subgraph node: ${node.id}`)
// Link inside the subgraph
const innerResolved = node.resolveSubgraphOutputLink(slot)
if (!innerResolved) return
const innerNode = innerResolved.outputNode
if (!innerNode)
throw new Error(
`No output node found for id [${this.id}] slot [${slot}] ${output.name}`
)
// Recurse into the subgraph
const innerNodeExecutionId = [
...this.subgraphNodePath,
node.id,
innerNode.id
].join(':')
const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId)
if (!innerNodeDto)
throw new Error(
`No inner node DTO found for id [${innerNodeExecutionId}]`
)
return innerNodeDto.resolveOutput(
innerResolved.link.origin_slot,
type,
visited
)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,150 @@
import type {
ExecutableLGraphNode,
ExecutionId,
LGraph
} from '@/lib/litegraph/src/litegraph'
import {
ExecutableNodeDTO,
LGraphEventMode
} from '@/lib/litegraph/src/litegraph'
import type {
ComfyApiWorkflow,
ComfyWorkflowJSON
} from '@/platform/workflow/validation/schemas/workflowSchema'
import { ExecutableGroupNodeDTO, isGroupNode } from './executableGroupNodeDto'
import { compressWidgetInputSlots } from './litegraphUtil'
/**
* Converts the current graph workflow for sending to the API.
* @note Node widgets are updated before serialization to prepare queueing.
*
* @param graph The graph to convert.
* @param options The options for the conversion.
* - `sortNodes`: Whether to sort the nodes by execution order.
* @returns The workflow and node links
*/
export const graphToPrompt = async (
graph: LGraph,
options: { sortNodes?: boolean } = {}
): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => {
const { sortNodes = false } = options
for (const node of graph.computeExecutionOrder(false)) {
const innerNodes = node.getInnerNodes
? node.getInnerNodes(new Map())
: [node]
for (const innerNode of innerNodes) {
if (innerNode.isVirtualNode) {
innerNode.applyToGraph?.()
}
}
}
const workflow = graph.serialize({ sortNodes })
// Remove localized_name from the workflow
for (const node of workflow.nodes) {
for (const slot of node.inputs ?? []) {
delete slot.localized_name
}
for (const slot of node.outputs ?? []) {
delete slot.localized_name
}
}
compressWidgetInputSlots(workflow)
workflow.extra ??= {}
workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__
const nodeDtoMap = new Map<ExecutionId, ExecutableLGraphNode>()
for (const node of graph.computeExecutionOrder(false)) {
const dto: ExecutableLGraphNode = isGroupNode(node)
? new ExecutableGroupNodeDTO(node, [], nodeDtoMap)
: new ExecutableNodeDTO(node, [], nodeDtoMap)
for (const innerNode of dto.getInnerNodes()) {
nodeDtoMap.set(innerNode.id, innerNode)
}
nodeDtoMap.set(dto.id, dto)
}
const output: ComfyApiWorkflow = {}
// Process nodes in order of execution
for (const node of nodeDtoMap.values()) {
// Don't serialize muted nodes
if (
node.isVirtualNode ||
node.mode === LGraphEventMode.NEVER ||
node.mode === LGraphEventMode.BYPASS
) {
continue
}
const inputs: ComfyApiWorkflow[string]['inputs'] = {}
const { widgets } = node
// Store all widget values
if (widgets) {
for (const [i, widget] of widgets.entries()) {
if (!widget.name || widget.options?.serialize === false) continue
const widgetValue = widget.serializeValue
? await widget.serializeValue(node, i)
: widget.value
// By default, Array values are reserved to represent node connections.
// We need to wrap the array as an object to avoid the misinterpretation
// of the array as a node connection.
// The backend automatically unwraps the object to an array during
// execution.
inputs[widget.name] = Array.isArray(widgetValue)
? {
__value__: widgetValue
}
: widgetValue
}
}
// Store all node links
for (const [i, input] of node.inputs.entries()) {
const resolvedInput = node.resolveInput(i)
if (!resolvedInput) continue
// Resolved to an actual widget value rather than a node connection
if (resolvedInput.widgetInfo) {
const { value } = resolvedInput.widgetInfo
inputs[input.name] = Array.isArray(value) ? { __value__: value } : value
continue
}
inputs[input.name] = [
String(resolvedInput.origin_id),
// @ts-expect-error link.origin_slot is already number.
parseInt(resolvedInput.origin_slot)
]
}
output[String(node.id)] = {
inputs,
// TODO(huchenlei): Filter out all nodes that cannot be mapped to a
// comfyClass.
class_type: node.comfyClass!,
// Ignored by the backend.
_meta: {
title: node.title
}
}
}
// Remove inputs connected to removed nodes
for (const { inputs } of Object.values(output)) {
for (const [i, input] of Object.entries(inputs)) {
if (Array.isArray(input) && input.length === 2 && !output[input[0]]) {
delete inputs[i]
}
}
}
return { workflow: workflow as ComfyWorkflowJSON, output }
}
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,123 @@
import path from 'path'
import type { Plugin } from 'vite'
interface ShimResult {
code: string
exports: string[]
}
const SKIP_WARNING_FILES = new Set(['scripts/app', 'scripts/api'])
/** Files that will be removed in v1.34 */
const DEPRECATED_FILES = [
'scripts/ui',
'extensions/core/groupNode',
'extensions/core/nodeTemplates'
] as const
function getWarningMessage(
fileKey: string,
shimFileName: string
): string | null {
if (SKIP_WARNING_FILES.has(fileKey)) {
return null
}
const isDeprecated = DEPRECATED_FILES.some((deprecatedPath) =>
fileKey.startsWith(deprecatedPath)
)
if (isDeprecated) {
return `[ComfyUI Deprecated] Importing from "${shimFileName}" is deprecated and will be removed in v1.34.`
}
return `[ComfyUI Notice] "${shimFileName}" is an internal module, not part of the public API. Future updates may break this import.`
}
function isLegacyFile(id: string): boolean {
return (
id.endsWith('.ts') &&
(id.includes('src/extensions/core') || id.includes('src/scripts'))
)
}
function transformExports(code: string, id: string): ShimResult {
const moduleName = getModuleName(id)
const exports: string[] = []
let newCode = code
// Regex to match different types of exports
const regex =
/export\s+(const|let|var|function|class|async function)\s+([a-zA-Z$_][a-zA-Z\d$_]*)(\s|\()/g
let match
while ((match = regex.exec(code)) !== null) {
const name = match[2]
// All exports should be bind to the window object as new API endpoint.
if (exports.length == 0) {
newCode += `\nwindow.comfyAPI = window.comfyAPI || {};`
newCode += `\nwindow.comfyAPI.${moduleName} = window.comfyAPI.${moduleName} || {};`
}
newCode += `\nwindow.comfyAPI.${moduleName}.${name} = ${name};`
exports.push(
`export const ${name} = window.comfyAPI.${moduleName}.${name};\n`
)
}
return {
code: newCode,
exports
}
}
function getModuleName(id: string): string {
// Simple example to derive a module name from the file path
const parts = id.split('/')
const fileName = parts[parts.length - 1]
return fileName.replace(/\.\w+$/, '') // Remove file extension
}
export function comfyAPIPlugin(isDev: boolean): Plugin {
return {
name: 'comfy-api-plugin',
apply: 'build',
transform(code: string, id: string) {
if (isDev) return null
if (isLegacyFile(id)) {
const result = transformExports(code, id)
if (result.exports.length > 0) {
const projectRoot = process.cwd()
const relativePath = path
.relative(path.join(projectRoot, 'src'), id)
.replace(/\\/g, '/')
const shimFileName = relativePath.replace(/\.ts$/, '.js')
let shimContent = `// Shim for ${relativePath}\n`
const fileKey = relativePath.replace(/\.ts$/, '')
const warningMessage = getWarningMessage(fileKey, shimFileName)
if (warningMessage) {
// It will only display once because it is at the root of the file.
shimContent += `console.warn('${warningMessage}');\n`
}
shimContent += result.exports.join('')
this.emitFile({
type: 'asset',
fileName: shimFileName,
source: shimContent
})
}
return {
code: result.code,
map: null // If you're not modifying the source map, return null
}
}
}
}
}
@@ -0,0 +1,35 @@
import {
configValueOrDefault,
remoteConfig
} from '@/platform/remoteConfig/remoteConfig'
const PROD_API_BASE_URL = 'https://api.comfy.org'
const STAGING_API_BASE_URL = 'https://stagingapi.comfy.org'
const PROD_PLATFORM_BASE_URL = 'https://platform.comfy.org'
const STAGING_PLATFORM_BASE_URL = 'https://stagingplatform.comfy.org'
const BUILD_TIME_API_BASE_URL = __USE_PROD_CONFIG__
? PROD_API_BASE_URL
: (import.meta.env.VITE_STAGING_API_BASE_URL ?? STAGING_API_BASE_URL)
const BUILD_TIME_PLATFORM_BASE_URL = __USE_PROD_CONFIG__
? PROD_PLATFORM_BASE_URL
: (import.meta.env.VITE_STAGING_PLATFORM_BASE_URL ??
STAGING_PLATFORM_BASE_URL)
export function getComfyApiBaseUrl(): string {
return configValueOrDefault(
remoteConfig.value,
'comfy_api_base_url',
BUILD_TIME_API_BASE_URL
)
}
export function getComfyPlatformBaseUrl(): string {
return configValueOrDefault(
remoteConfig.value,
'comfy_platform_base_url',
BUILD_TIME_PLATFORM_BASE_URL
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,429 @@
import { toLinkId } from '@/types/linkId'
import type { LGraph } from '@/lib/litegraph/src/LGraph'
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
import type { SerializedNodeId } from '@/types/nodeId'
import type { LinkId } from '@/lib/litegraph/src/LLink'
import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError'
import { useWidgetValueStore } from '@/stores/widgetValueStore'
import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError'
import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError'
import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError'
import type { ISlotType } from '@/lib/litegraph/src/interfaces'
import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph'
import type { Subgraph } from './Subgraph'
import type { SubgraphNode } from './SubgraphNode'
export type ExecutionId = string
/**
* Interface describing the data transfer objects used when compiling a graph for execution.
*/
export type ExecutableLGraphNode = Omit<
ExecutableNodeDTO,
'graph' | 'node' | 'subgraphNode'
>
/**
* The end result of resolving a DTO input.
* When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`.
*/
type ResolvedInput = {
/** DTO for the node that the link originates from. */
node: ExecutableLGraphNode
/** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */
origin_id: ExecutionId
/** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */
origin_slot: number
/** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */
widgetInfo?: { value: unknown }
}
/**
* Concrete implementation of {@link ExecutableLGraphNode}.
* @remarks This is the class that is used to create the data transfer objects for executable nodes.
*/
export class ExecutableNodeDTO implements ExecutableLGraphNode {
applyToGraph?(
...args: Parameters<NonNullable<typeof this.node.applyToGraph>>
): ReturnType<NonNullable<typeof this.node.applyToGraph>>
/** The graph that this node is a part of. */
readonly graph: LGraph | Subgraph
inputs: { linkId: LinkId | null; name: string; type: ISlotType }[]
/** Backing field for {@link id}. */
private _id: ExecutionId
/**
* The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances),
* followed by the actual original node ID within the subgraph. Each segment is separated by `:`.
*
* e.g. `1:2:3`:
* - `1` is the node ID of the first subgraph node in the parent workflow
* - `2` is the node ID of the second subgraph node in the first subgraph
* - `3` is the node ID of the actual node in the subgraph definition
*/
get id() {
return this._id
}
get type() {
return this.node.type
}
get title() {
return this.node.title
}
get mode() {
return this.node.mode
}
get comfyClass() {
return this.node.comfyClass
}
get isVirtualNode() {
return this.node.isVirtualNode
}
get widgets() {
return this.node.widgets
}
get subgraphId() {
return this.subgraphNode?.subgraph.id
}
constructor(
/** The actual node that this DTO wraps. */
readonly node: LGraphNode | SubgraphNode,
/** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */
readonly subgraphNodePath: readonly SerializedNodeId[],
/** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */
readonly nodesByExecutionId: Map<ExecutionId, ExecutableLGraphNode>,
/** The actual subgraph instance that contains this node, otherwise undefined. */
readonly subgraphNode?: SubgraphNode
) {
if (!node.graph) throw new NullGraphError()
// Set the internal ID of the DTO
this._id = [...this.subgraphNodePath, this.node.id].join(':')
this.graph = node.graph
this.inputs = this.node.inputs.map((x) => ({
linkId: x.link == null ? null : toLinkId(x.link),
name: x.name,
type: x.type
}))
// Only create a wrapper if the node has an applyToGraph method
if (this.node.applyToGraph) {
this.applyToGraph = (...args) => this.node.applyToGraph?.(...args)
}
}
/** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */
getInnerNodes(): ExecutableLGraphNode[] {
return this.node.isSubgraphNode()
? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath)
: [this]
}
/**
* Resolves the executable node & link IDs for a given input slot.
* @param slot The slot index of the input.
* @param visited Leave empty unless overriding this method.
* A set of unique IDs, used to guard against infinite recursion.
* If overriding, ensure that the set is passed on all recursive calls.
* @returns The node and the origin ID / slot index of the output.
*/
resolveInput(
slot: number,
visited = new Set<string>(),
type?: ISlotType
): ResolvedInput | undefined {
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}`
if (visited.has(uniqueId)) {
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
const pathInfo =
this.subgraphNodePath.length > 0
? ` at path ${this.subgraphNodePath.join(':')}`
: ''
throw new RecursionError(
`Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` +
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
)
}
visited.add(uniqueId)
const input = this.inputs.at(slot)
if (!input)
throw new SlotIndexError(
`No input found for flattened id [${this.id}] slot [${slot}]`
)
// Nothing connected
if (input.linkId == null) return
const link = this.graph.getLink(input.linkId)
if (!link)
throw new InvalidLinkError(
`No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}`
)
const { subgraphNode } = this
// Link goes up and out of this subgraph
if (subgraphNode && link.originIsIoNode) {
const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot)
if (!subgraphNodeInput)
throw new SlotIndexError(
`No input found for slot [${link.origin_slot}] ${input.name}`
)
// Nothing connected
const linkId = subgraphNodeInput.link
if (linkId == null) {
const id = subgraphNodeInput.widgetId
if (!id) return
return {
node: this,
origin_id: this.id,
origin_slot: -1,
widgetInfo: { value: useWidgetValueStore().getWidget(id)?.value }
}
}
if (!subgraphNode.graph)
throw new NullGraphError(
`SubgraphNode ${subgraphNode.id} has no graph during input resolution`
)
const outerLink = subgraphNode.graph.getLink(linkId)
if (!outerLink)
throw new InvalidLinkError(
`No outer link found for slot [${link.origin_slot}] ${input.name}`
)
const subgraphNodeExecutionId: ExecutionId =
this.subgraphNodePath.join(':')
const subgraphNodeDto = this.nodesByExecutionId.get(
subgraphNodeExecutionId
)
if (!subgraphNodeDto)
throw new Error(
`No subgraph node DTO found for id [${subgraphNodeExecutionId}]`
)
return subgraphNodeDto.resolveInput(outerLink.target_slot, visited)
}
// Not part of a subgraph; use the original link
const outputNode = this.graph.getNodeById(link.origin_id)
if (!outputNode)
throw new InvalidLinkError(
`No input node found for id [${this.id}] slot [${slot}] ${input.name}`
)
const outputNodeExecutionId: ExecutionId = [
...this.subgraphNodePath,
outputNode.id
].join(':')
const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId)
if (!outputNodeDto)
throw new Error(
`No output node DTO found for id [${outputNodeExecutionId}]`
)
return outputNodeDto.resolveOutput(
link.origin_slot,
type ?? input.type,
visited
)
}
/**
* Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass).
* @param slot The slot index of the output.
* @param type The type of the input
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
* @returns The node and the origin ID / slot index of the output.
*/
resolveOutput(
slot: number,
type: ISlotType,
visited: Set<string>
): ResolvedInput | undefined {
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}`
if (visited.has(uniqueId)) {
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
const pathInfo =
this.subgraphNodePath.length > 0
? ` at path ${this.subgraphNodePath.join(':')}`
: ''
throw new RecursionError(
`Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` +
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
)
}
visited.add(uniqueId)
// Muted nodes produce no output
if (this.mode === LGraphEventMode.NEVER) return
// Upstreamed: Bypass nodes are bypassed using the first input with matching type
if (this.mode === LGraphEventMode.BYPASS) {
// Bypass nodes by finding first input with matching type
const matchingIndex = this._getBypassSlotIndex(slot, type)
// No input types match - bypass not possible
if (matchingIndex === -1) {
console.warn(
`[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`,
this
)
return
}
return this.resolveInput(matchingIndex, visited)
}
const { node } = this
if (node.isSubgraphNode())
return this._resolveSubgraphOutput(slot, type, visited)
if (node.isVirtualNode) {
// Cross-graph virtual nodes (e.g. Set/Get) resolve their source directly.
const virtualSource = this.node.resolveVirtualOutput?.(slot)
if (virtualSource) {
const inputNodeDto = [...this.nodesByExecutionId.values()].find(
(dto) =>
dto instanceof ExecutableNodeDTO && dto.node === virtualSource.node
)
if (!inputNodeDto)
throw new Error(
`No DTO found for virtual source node [${virtualSource.node.id}]`
)
return inputNodeDto.resolveOutput(virtualSource.slot, type, visited)
}
const virtualLink = this.node.getInputLink(slot)
if (virtualLink) {
const { inputNode } = virtualLink.resolve(this.graph)
if (!inputNode)
throw new InvalidLinkError(
`Virtual node failed to resolve parent [${this.id}] slot [${slot}]`
)
const inputNodeExecutionId: ExecutionId = [
...this.subgraphNodePath,
inputNode.id
].join(':')
const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId)
if (!inputNodeDto)
throw new Error(`No input node DTO found for id [${inputNode.id}]`)
return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)
}
// Virtual nodes without a matching input should be discarded.
return
}
return {
node: this,
origin_id: this.id,
origin_slot: slot
}
}
/**
* Finds the index of the input slot on this node that matches the given output {@link slot} index.
* Used when bypassing nodes.
* @param slot The output slot index on this node
* @param type The type of the final target input (so type list matches are accurate)
* @returns The index of the input slot on this node, otherwise `-1`.
*/
private _getBypassSlotIndex(slot: number, type: ISlotType) {
const { inputs } = this
const oppositeInput = inputs[slot]
const outputType = this.node.outputs[slot].type
// Any type short circuit - match slot ID, fallback to first slot
if (type === '*' || type === '') {
return inputs.length > slot ? slot : 0
}
// Prefer input with the same slot ID
if (
oppositeInput &&
LiteGraph.isValidConnection(oppositeInput.type, outputType) &&
LiteGraph.isValidConnection(oppositeInput.type, type)
) {
return slot
}
// Preserve legacy behaviour; use exact match first.
const exactMatch = inputs.findIndex((input) => input.type === type)
if (exactMatch !== -1) return exactMatch
// Find first matching slot - prefer exact type
return inputs.findIndex(
(input) =>
LiteGraph.isValidConnection(input.type, outputType) &&
LiteGraph.isValidConnection(input.type, type)
)
}
/**
* Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph.
* @param slot The slot index of the output on the subgraph node.
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
* @returns A DTO for the node, and the origin ID / slot index of the output.
*/
private _resolveSubgraphOutput(
slot: number,
type: ISlotType,
visited: Set<string>
): ResolvedInput | undefined {
const { node } = this
const output = node.outputs.at(slot)
if (!output)
throw new SlotIndexError(
`No output found for flattened id [${this.id}] slot [${slot}]`
)
if (!node.isSubgraphNode())
throw new TypeError(`Node is not a subgraph node: ${node.id}`)
// Link inside the subgraph
const innerResolved = node.resolveSubgraphOutputLink(slot)
if (!innerResolved) return
const innerNode = innerResolved.outputNode
if (!innerNode)
throw new Error(
`No output node found for id [${this.id}] slot [${slot}] ${output.name}`
)
// Recurse into the subgraph
const innerNodeExecutionId: ExecutionId = [
...this.subgraphNodePath,
node.id,
innerNode.id
].join(':')
const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId)
if (!innerNodeDto)
throw new Error(
`No inner node DTO found for id [${innerNodeExecutionId}]`
)
return innerNodeDto.resolveOutput(
innerResolved.link.origin_slot,
type,
visited
)
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,160 @@
import type {
ExecutableLGraphNode,
ExecutionId,
LGraph
} from '@/lib/litegraph/src/litegraph'
import {
ExecutableNodeDTO,
LGraphEventMode
} from '@/lib/litegraph/src/litegraph'
import type {
ComfyApiWorkflow,
ComfyWorkflowJSON
} from '@/platform/workflow/validation/schemas/workflowSchema'
import { compressWidgetInputSlots } from './litegraphUtil'
/**
* Converts the current graph workflow for sending to the API.
* @note Node widgets are updated before serialization to prepare queueing.
*
* @param graph The graph to convert.
* @param options The options for the conversion.
* - `sortNodes`: Whether to sort the nodes by execution order.
* @returns The workflow and node links
*/
export const graphToPrompt = async (
graph: LGraph,
options: { sortNodes?: boolean } = {}
): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => {
const { sortNodes = false } = options
for (const node of graph.computeExecutionOrder(false)) {
const innerNodes = node.getInnerNodes
? node.getInnerNodes(new Map())
: [node]
for (const innerNode of innerNodes) {
if (innerNode.isVirtualNode) {
innerNode.applyToGraph?.()
}
}
}
const workflow = graph.serialize({ sortNodes })
// Remove localized_name from the workflow
for (const node of workflow.nodes) {
for (const slot of node.inputs ?? []) {
delete slot.localized_name
}
for (const slot of node.outputs ?? []) {
delete slot.localized_name
}
}
compressWidgetInputSlots(workflow)
workflow.extra ??= {}
workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__
const nodeDtoMap = new Map<ExecutionId, ExecutableLGraphNode>()
for (const node of graph.computeExecutionOrder(false)) {
const dto: ExecutableLGraphNode = new ExecutableNodeDTO(
node,
[],
nodeDtoMap
)
nodeDtoMap.set(dto.id, dto)
if (
node.mode === LGraphEventMode.NEVER ||
node.mode === LGraphEventMode.BYPASS
) {
continue
}
for (const innerNode of dto.getInnerNodes()) {
nodeDtoMap.set(innerNode.id, innerNode)
}
}
const output: ComfyApiWorkflow = {}
// Process nodes in order of execution
for (const node of nodeDtoMap.values()) {
// Don't serialize muted nodes
if (
node.isVirtualNode ||
node.mode === LGraphEventMode.NEVER ||
node.mode === LGraphEventMode.BYPASS
) {
continue
}
const inputs: ComfyApiWorkflow[string]['inputs'] = {}
const { widgets } = node
// Store all widget values in the API prompt.
// Note: widget.options.serialize controls prompt inclusion (checked here).
// widget.serialize controls workflow persistence (checked by LGraphNode).
if (widgets) {
for (const [i, widget] of widgets.entries()) {
if (!widget.name || widget.options?.serialize === false) continue
const widgetValue = widget.serializeValue
? await widget.serializeValue(node, i)
: widget.value
// By default, Array values are reserved to represent node connections.
// We need to wrap the array as an object to avoid the misinterpretation
// of the array as a node connection.
// The backend automatically unwraps the object to an array during
// execution.
inputs[widget.name] = Array.isArray(widgetValue)
? widget.type === 'curve'
? { __type__: 'CURVE', __value__: widgetValue }
: { __value__: widgetValue }
: widgetValue
}
}
// Store all node links
for (const [i, input] of node.inputs.entries()) {
const resolvedInput = node.resolveInput(i)
if (!resolvedInput) continue
// Resolved to an actual widget value rather than a node connection
if (resolvedInput.widgetInfo) {
const { value } = resolvedInput.widgetInfo
inputs[input.name] = Array.isArray(value) ? { __value__: value } : value
continue
}
inputs[input.name] = [
String(resolvedInput.origin_id),
// @ts-expect-error link.origin_slot is already number.
parseInt(resolvedInput.origin_slot)
]
}
output[String(node.id)] = {
inputs,
// TODO(huchenlei): Filter out all nodes that cannot be mapped to a
// comfyClass.
class_type: node.comfyClass!,
// Ignored by the backend.
_meta: {
title: node.title
}
}
}
// Remove inputs connected to removed nodes
for (const { inputs } of Object.values(output)) {
for (const [i, input] of Object.entries(inputs)) {
if (Array.isArray(input) && input.length === 2 && !output[input[0]]) {
delete inputs[i]
}
}
}
return { workflow: workflow as ComfyWorkflowJSON, output }
}
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+458
View File
@@ -0,0 +1,458 @@
from .nodes.nodes import (
BOOLConstant, INTConstant, FloatConstant, StringConstant, StringConstantMultiline,
ScaleBatchPromptSchedule, GetLatentsFromBatchIndexed, ConditioningMultiCombine,
AppendStringsToList, JoinStrings, JoinStringMulti, CondPassThrough, ModelPassThrough,
ConditioningSetMaskAndCombine, ConditioningSetMaskAndCombine3,
ConditioningSetMaskAndCombine4, ConditioningSetMaskAndCombine5,
VRAM_Debug, SomethingToString, Sleep, EmptyLatentImagePresets,
EmptyLatentImageCustomPresets, WidgetToString, DummyOut, FlipSigmasAdjusted,
CustomSigmas, StringToFloatList, InjectNoiseToLatent, SoundReactive, GenerateNoise,
StableZero123_BatchSchedule, SV3D_BatchSchedule, Superprompt, CameraPoseVisualizer,
CheckpointPerturbWeights, DifferentialDiffusionAdvanced, FluxBlockLoraSelect,
HunyuanVideoBlockLoraSelect, Wan21BlockLoraSelect, LTX2BlockLoraSelect,
DiTBlockLoraLoader, CustomControlNetWeightsFluxFromList,
SetShakkerLabsUnionControlNetType, ModelSaveKJ, StyleModelApplyAdvanced,
AudioConcatenate, LeapfusionHunyuanI2V, ImageNoiseAugmentation, VAELoaderKJ, VAEMergeKJ,
ScheduledCFGGuidance, ApplyRifleXRoPE_WanVideo, ApplyRifleXRoPE_HunuyanVideo,
TimerNodeKJ, HunyuanVideoEncodeKeyframesToCond, LazySwitchKJ, LatentInpaintTTM,
SimpleCalculatorKJ, GetTrackRange, AddNoiseToTrackPath, VAEDecodeLoopKJ,
WanImageToVideoSVIPro, DeprecatedCompileNodeKJ, VisualizeSigmasKJ,
PreviewLatentNoiseMask, PlaySoundKJ,
)
from .nodes.curve_nodes import (
PlotCoordinates, SplineEditor, CreateShapeMaskOnPath, CreateShapeImageOnPath,
CreateTextOnPath, CreateGradientFromCoords, GradientToFloat, MaskOrImageToWeight,
WeightScheduleConvert, FloatToMask, WeightScheduleExtend, FloatToSigmas, SigmasToFloat,
GLIGENTextBoxApplyBatchCoords, CreateInstanceDiffusionTracking,
AppendInstanceDiffusionTracking, InterpolateCoords, DrawInstanceDiffusionTracking,
PointsEditor, CutAndDragOnPath,
)
from .nodes.batchcrop_nodes import (
BatchCropFromMask, BatchUncrop, BatchCropFromMaskAdvanced,
FilterZeroMasksAndCorrespondingImages, InsertImageBatchByIndexes, BatchUncropAdvanced,
SplitBboxes, BboxToInt, BboxVisualize,
)
from .nodes.audioscheduler_nodes import (
NormalizedAmplitudeToMask, NormalizedAmplitudeToFloatList,
OffsetMaskByNormalizedAmplitude, ImageTransformByNormalizedAmplitude,
)
from .nodes.image_nodes import (
ImagePass, ColorMatch, ColorMatchV2, SaveImageWithAlpha, ImageConcanate,
ImageConcatFromBatch, ImageGridComposite2x2, ImageGridComposite3x3,
ImageBatchTestPattern, ImageGrabPIL, Screencap_mss, ScreencapStream, WebcamCaptureCV2,
AddLabel, GetImageSizeAndCount, GetLatentSizeAndCount, ImageBatchRepeatInterleaving,
ImageUpscaleWithModelBatched, ImageNormalize_Neg1_To_1, RemapImageRange,
SplitImageChannels, MergeImageChannels, ImagePadForOutpaintMasked,
ImagePadForOutpaintTargetSize, ImagePrepForICLora, ImageAndMaskPreview,
CrossFadeImages, CrossFadeImagesMulti, TransitionImagesMulti, TransitionImagesInBatch,
ImageBatchJoinWithTransition, ShuffleImageBatch, GetImageRangeFromBatch,
RandomImageFromBatch, ImageBatchExtendWithOverlap, GetLatentRangeFromBatch,
InsertLatentToIndex, ImageBatchFilter, GetImagesFromBatchIndexed,
InsertImagesToBatchIndexed, PadImageBatchInterleaved, ReplaceImagesInBatch,
ReverseImageBatch, ImageBatchMulti, ImageTensorList, ImageAddMulti, ImageConcatMulti,
PreviewAnimation, ImageResizeKJ, ImageResizeKJv2, LoadAndResizeImage,
LoadImagesFromFolderKJ, ImageGridtoBatch, SaveImageKJ, SaveStringKJ, FastPreview,
FastPreviewBatch, ImageCropByMaskAndResize, ImageCropByMask, ImageUncropByMask,
ImageCropByMaskBatch, ImagePadKJ, LoadVideosFromFolder, EncodeVideoComponents,
DecodeAndSaveVideo, PreviewImageOrMask,
)
from .nodes.mask_nodes import (
BatchCLIPSeg, DownloadAndLoadCLIPSeg, CreateTextMask, ColorToMask, CreateFluidMask,
CreateAudioMask, CreateGradientMask, CreateFadeMask, CreateFadeMaskAdvanced,
CreateMagicMask, CreateShapeMask, CreateVoronoiMask, GetMaskSizeAndCount,
GrowMaskWithBlur, MaskBatchMulti, OffsetMask, RoundMask, ResizeMask, RemapMaskRange,
SeparateMasks, ConsolidateMasksKJ, DrawMaskOnImage, BlockifyMask,
)
from .nodes.model_optimization_nodes import (
PathchSageAttentionKJ, PatchFlashAttentionKJ, CheckpointLoaderKJ, DiffusionModelSelector,
DiffusionModelLoaderKJ, ModelPatchTorchSettings, PatchModelPatcherOrder,
TorchCompileModelFluxAdvancedV2, TorchCompileModelWanVideoV2,
TorchCompileModelAdvanced, TorchCompileVAE, TorchCompileControlNet,
WanVideoTeaCacheKJ, WanVideoEnhanceAVideoKJ, LTXVEnhanceAVideoKJ, WanVideoNAG, Krea2PromptWeight, MossImagePromptWeight,
SkipLayerGuidanceWanVideo, CFGZeroStarAndInit, GGUFLoaderKJ, NABLA_AttentionKJ,
StartRecordCUDAMemoryHistory, EndRecordCUDAMemoryHistory, VisualizeCUDAMemoryHistory,
ModelMemoryUseReportPatch, ModelMemoryUsageFactorOverride, WanChunkFeedForward,
SamplerSelfRefineVideo, PiDColorBiasCorrection, Ideogram4OptimizationsKJ,
)
from .nodes.lora_nodes import LoraExtractKJ, LoraReduceRank
from .nodes.image_transform_node import ImageTransformKJ, BBOXToBoundingBoxKJ
from .nodes.image_compare_node import ImageCompareKJ
from .nodes.sharpen_nodes import ImageSharpenKJ
from .nodes.nodes_looping import LOOP_NODES
from .nodes.hdr_preview_node import HDRPreviewKJ
from .nodes.preview_override_node import ModelPreviewOverrideKJ, GetPreviewOverrideFramesKJ
from .nodes.context_windows_visualizer import ContextWindowsVisualizerKJ
from .nodes.ideogram4_nodes import Ideogram4PromptBuilderKJ
from .nodes.flux3_nodes import Flux3PromptBuilderKJ, Flux3BoxReconcileKJ
from .nodes.moss_image_nodes import MossImagePromptBuilderKJ
import logging
NODE_CONFIG = {
#constants
"BOOLConstant": {"class": BOOLConstant, "name": "BOOL Constant"},
"INTConstant": {"class": INTConstant, "name": "INT Constant"},
"FloatConstant": {"class": FloatConstant, "name": "Float Constant"},
"StringConstant": {"class": StringConstant, "name": "String Constant"},
"StringConstantMultiline": {"class": StringConstantMultiline, "name": "String Constant Multiline"},
#conditioning
"ConditioningMultiCombine": {"class": ConditioningMultiCombine, "name": "Conditioning Multi Combine"},
"ConditioningSetMaskAndCombine": {"class": ConditioningSetMaskAndCombine, "name": "ConditioningSetMaskAndCombine"},
"ConditioningSetMaskAndCombine3": {"class": ConditioningSetMaskAndCombine3, "name": "ConditioningSetMaskAndCombine3"},
"ConditioningSetMaskAndCombine4": {"class": ConditioningSetMaskAndCombine4, "name": "ConditioningSetMaskAndCombine4"},
"ConditioningSetMaskAndCombine5": {"class": ConditioningSetMaskAndCombine5, "name": "ConditioningSetMaskAndCombine5"},
"CondPassThrough": {"class": CondPassThrough},
"WanImageToVideoSVIPro": {"class": WanImageToVideoSVIPro, "name": "Wan Image To Video SVIPro"},
#masking
"DrawMaskOnImage": {"class": DrawMaskOnImage, "name": "Draw Mask On Image"},
"DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"},
"BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"},
"BlockifyMask": {"class": BlockifyMask, "name": "Blockify Mask"},
"ColorToMask": {"class": ColorToMask, "name": "Color To Mask"},
"CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"},
"CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"},
"CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"},
"CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"},
"CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"},
"CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"},
"CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"},
"CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"},
"CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"},
"GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"},
"GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"},
"MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"},
"OffsetMask": {"class": OffsetMask, "name": "Offset Mask"},
"RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"},
"ResizeMask": {"class": ResizeMask, "name": "Resize Mask"},
"RoundMask": {"class": RoundMask, "name": "Round Mask"},
"SeparateMasks": {"class": SeparateMasks, "name": "Separate Masks"},
"ConsolidateMasksKJ": {"class": ConsolidateMasksKJ, "name": "Consolidate Masks"},
#images
"AddLabel": {"class": AddLabel, "name": "Add Label"},
"ColorMatch": {"class": ColorMatch, "name": "Color Match"},
"ColorMatchV2": {"class": ColorMatchV2, "name": "Color Match V2"},
"ImageTensorList": {"class": ImageTensorList, "name": "Image Tensor List"},
"CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"},
"CrossFadeImagesMulti": {"class": CrossFadeImagesMulti, "name": "Cross Fade Images Multi"},
"GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"},
"GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"},
"RandomImageFromBatch": {"class": RandomImageFromBatch, "name": "Random Image From Batch"},
"GetLatentRangeFromBatch": {"class": GetLatentRangeFromBatch, "name": "Get Latent Range From Batch"},
"GetLatentSizeAndCount": {"class": GetLatentSizeAndCount, "name": "Get Latent Size & Count"},
"GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"},
"FastPreview": {"class": FastPreview, "name": "Fast Preview"},
"FastPreviewBatch": {"class": FastPreviewBatch, "name": "Fast Preview Batch"},
"ImageBatchFilter": {"class": ImageBatchFilter, "name": "Image Batch Filter"},
"ImageAndMaskPreview": {"class": ImageAndMaskPreview},
"ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"},
"ImageBatchJoinWithTransition": {"class": ImageBatchJoinWithTransition, "name": "Image Batch Join With Transition"},
"ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"},
"ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving},
"ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"},
"ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"},
"ImageConcatFromBatch": {"class": ImageConcatFromBatch, "name": "Image Concatenate From Batch"},
"ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"},
"ImageCropByMask": {"class": ImageCropByMask, "name": "Image Crop By Mask"},
"ImageCropByMaskAndResize": {"class": ImageCropByMaskAndResize, "name": "Image Crop By Mask And Resize"},
"ImageCropByMaskBatch": {"class": ImageCropByMaskBatch, "name": "Image Crop By Mask Batch"},
"ImageUncropByMask": {"class": ImageUncropByMask, "name": "Image Uncrop By Mask"},
"ImageBatchExtendWithOverlap": {"class": ImageBatchExtendWithOverlap, "name": "Image Batch Extend With Overlap"},
"ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"},
"ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"},
"ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"},
"ImageGridtoBatch": {"class": ImageGridtoBatch, "name": "Image Grid To Batch"},
"ImageNoiseAugmentation": {"class": ImageNoiseAugmentation, "name": "Image Noise Augmentation"},
"ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"},
"ImagePass": {"class": ImagePass},
"ImagePadKJ": {"class": ImagePadKJ, "name": "ImagePad KJ"},
"ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"},
"ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"},
"ImagePrepForICLora": {"class": ImagePrepForICLora, "name": "Image Prep For ICLora"},
"ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image (deprecated)"},
"ImageResizeKJv2": {"class": ImageResizeKJv2, "name": "Resize Image v2"},
"ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"},
"InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"},
"InsertLatentToIndexed": {"class": InsertLatentToIndex, "name": "Insert Latent To Index"},
"LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"},
"LoadImagesFromFolderKJ": {"class": LoadImagesFromFolderKJ, "name": "Load Images From Folder (KJ)"},
"LoadVideosFromFolder": {"class": LoadVideosFromFolder, "name": "Load Videos From Folder"},
"MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"},
"PadImageBatchInterleaved": {"class": PadImageBatchInterleaved, "name": "Pad Image Batch Interleaved"},
"PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"},
"RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"},
"ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"},
"ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"},
"SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"},
"SaveImageKJ": {"class": SaveImageKJ, "name": "Save Image KJ"},
"ShuffleImageBatch": {"class": ShuffleImageBatch, "name": "Shuffle Image Batch"},
"SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"},
"TransitionImagesMulti": {"class": TransitionImagesMulti, "name": "Transition Images Multi"},
"TransitionImagesInBatch": {"class": TransitionImagesInBatch, "name": "Transition Images In Batch"},
"EncodeVideoComponents": {"class": EncodeVideoComponents, "name": "Encode Video Components"},
"DecodeAndSaveVideo": {"class": DecodeAndSaveVideo, "name": "Decode And Save Video"},
"ImageTransformKJ": {"class": ImageTransformKJ, "name": "Image Transform KJ"},
"ImageCompareKJ": {"class": ImageCompareKJ, "name": "Image Compare KJ"},
"BBOXToBoundingBoxKJ": {"class": BBOXToBoundingBoxKJ, "name": "BBOX to Bounding Box KJ"},
"Ideogram4PromptBuilderKJ": {"class": Ideogram4PromptBuilderKJ, "name": "Ideogram 4 Prompt Builder KJ"},
"Flux3PromptBuilderKJ": {"class": Flux3PromptBuilderKJ, "name": "FLUX.3 Prompt Builder KJ"},
"Flux3BoxReconcileKJ": {"class": Flux3BoxReconcileKJ, "name": "FLUX.3 Box Reconcile KJ"},
"MossImagePromptBuilderKJ": {"class": MossImagePromptBuilderKJ, "name": "MOSS-Image Prompt Builder KJ"},
"HDRPreviewKJ": {"class": HDRPreviewKJ, "name": "HDR Preview KJ"},
"ModelPreviewOverrideKJ": {"class": ModelPreviewOverrideKJ, "name": "Model Preview Override KJ"},
"GetPreviewOverrideFramesKJ": {"class": GetPreviewOverrideFramesKJ, "name": "Get Preview Override Frames KJ"},
"PreviewImageOrMask": {"class": PreviewImageOrMask, "name": "Preview Image Or Mask"},
"ImageSharpenKJ": {"class": ImageSharpenKJ, "name": "Image Sharpen KJ"},
#batch cropping
"BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"},
"BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"},
"FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages},
"InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"},
"BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"},
"BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"},
"SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"},
"BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"},
"BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"},
#noise
"GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"},
"FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"},
"InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"},
"CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"},
#utility
"StringToFloatList": {"class": StringToFloatList, "name": "String to Float List"},
"WidgetToString": {"class": WidgetToString, "name": "Widget To String"},
"SaveStringKJ": {"class": SaveStringKJ, "name": "Save String KJ"},
"DummyOut": {"class": DummyOut, "name": "Dummy Out"},
"GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"},
"ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"},
"CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"},
"AppendStringsToList": {"class": AppendStringsToList, "name": "Append Strings To List"},
"JoinStrings": {"class": JoinStrings, "name": "Join Strings"},
"JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"},
"SimpleCalculatorKJ": {"class": SimpleCalculatorKJ, "name": "Simple Calculator KJ"},
"SomethingToString": {"class": SomethingToString, "name": "Something To String"},
"Sleep": {"class": Sleep, "name": "Sleep"},
"VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"},
"EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"},
"EmptyLatentImageCustomPresets": {"class": EmptyLatentImageCustomPresets, "name": "Empty Latent Image Custom Presets"},
"ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"},
"ModelSaveKJ": {"class": ModelSaveKJ, "name": "Model Save KJ"},
"SetShakkerLabsUnionControlNetType": {"class": SetShakkerLabsUnionControlNetType, "name": "Set Shakker Labs Union ControlNet Type"},
"StyleModelApplyAdvanced": {"class": StyleModelApplyAdvanced, "name": "Style Model Apply Advanced"},
"DiffusionModelSelector": {"class": DiffusionModelSelector, "name": "Diffusion Model Selector"},
"LazySwitchKJ": {"class": LazySwitchKJ, "name": "Lazy Switch KJ"},
"VisualizeSigmasKJ": {"class": VisualizeSigmasKJ, "name": "Visualize Sigmas KJ"},
#audioscheduler stuff
"NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask},
"NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList},
"OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude},
"ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude},
"AudioConcatenate": {"class": AudioConcatenate},
#curve nodes
"SplineEditor": {"class": SplineEditor, "name": "Spline Editor"},
"CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"},
"CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"},
"CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"},
"CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"},
"CutAndDragOnPath": {"class": CutAndDragOnPath, "name": "Cut And Drag On Path"},
"GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"},
"WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"},
"MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"},
"WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"},
"FloatToMask": {"class": FloatToMask, "name": "Float To Mask"},
"FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"},
"SigmasToFloat": {"class": SigmasToFloat, "name": "Sigmas To Float"},
"PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"},
"InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"},
"PointsEditor": {"class": PointsEditor, "name": "Points Editor"},
#experimental
"SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"},
"StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"},
"SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"},
"Superprompt": {"class": Superprompt, "name": "Superprompt"},
"GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords},
"CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"},
"Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"},
"ScreencapStream": {"class": ScreencapStream, "name": "Screencap Stream"},
"WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"},
"DifferentialDiffusionAdvanced": {"class": DifferentialDiffusionAdvanced, "name": "Differential Diffusion Advanced"},
"DiTBlockLoraLoader": {"class": DiTBlockLoraLoader, "name": "DiT Block Lora Loader"},
"FluxBlockLoraSelect": {"class": FluxBlockLoraSelect, "name": "Flux Block Lora Select"},
"HunyuanVideoBlockLoraSelect": {"class": HunyuanVideoBlockLoraSelect, "name": "Hunyuan Video Block Lora Select"},
"Wan21BlockLoraSelect": {"class": Wan21BlockLoraSelect, "name": "Wan21 Block Lora Select"},
"LTX2BlockLoraSelect": {"class": LTX2BlockLoraSelect, "name": "LTX2 Block Lora Select"},
"CustomControlNetWeightsFluxFromList": {"class": CustomControlNetWeightsFluxFromList, "name": "Custom ControlNet Weights Flux From List"},
"CheckpointLoaderKJ": {"class": CheckpointLoaderKJ, "name": "CheckpointLoaderKJ"},
"DiffusionModelLoaderKJ": {"class": DiffusionModelLoaderKJ, "name": "Diffusion Model Loader KJ"},
"TorchCompileModelFluxAdvancedV2": {"class": TorchCompileModelFluxAdvancedV2, "name": "TorchCompileModelFluxAdvancedV2"},
"TorchCompileVAE": {"class": TorchCompileVAE, "name": "TorchCompileVAE"},
"TorchCompileControlNet": {"class": TorchCompileControlNet, "name": "TorchCompileControlNet"},
"TorchCompileModelWanVideoV2": {"class": TorchCompileModelWanVideoV2, "name": "TorchCompileModelWanVideoV2"},
"PathchSageAttentionKJ": {"class": PathchSageAttentionKJ, "name": "Patch Sage Attention KJ"},
"PatchFlashAttentionKJ": {"class": PatchFlashAttentionKJ, "name": "Patch Flash Attention KJ"},
"LeapfusionHunyuanI2VPatcher": {"class": LeapfusionHunyuanI2V, "name": "Leapfusion Hunyuan I2V Patcher"},
"VAELoaderKJ": {"class": VAELoaderKJ, "name": "VAELoader KJ"},
"VAEMergeKJ": {"class": VAEMergeKJ, "name": "VAE Merge KJ"},
"VAEDecodeLoopKJ": {"class": VAEDecodeLoopKJ, "name": "VAE Decode Loop KJ"},
"ScheduledCFGGuidance": {"class": ScheduledCFGGuidance, "name": "Scheduled CFG Guidance"},
"ApplyRifleXRoPE_HunuyanVideo": {"class": ApplyRifleXRoPE_HunuyanVideo, "name": "Apply RifleXRoPE HunuyanVideo"},
"ApplyRifleXRoPE_WanVideo": {"class": ApplyRifleXRoPE_WanVideo, "name": "Apply RifleXRoPE WanVideo"},
"WanVideoTeaCacheKJ": {"class": WanVideoTeaCacheKJ, "name": "WanVideo Tea Cache (native)"},
"WanVideoEnhanceAVideoKJ": {"class": WanVideoEnhanceAVideoKJ, "name": "WanVideo Enhance A Video (native)"},
"SkipLayerGuidanceWanVideo": {"class": SkipLayerGuidanceWanVideo, "name": "Skip Layer Guidance WanVideo"},
"TimerNodeKJ": {"class": TimerNodeKJ, "name": "Timer Node KJ"},
"HunyuanVideoEncodeKeyframesToCond": {"class": HunyuanVideoEncodeKeyframesToCond, "name": "HunyuanVideo Encode Keyframes To Cond"},
"CFGZeroStarAndInit": {"class": CFGZeroStarAndInit, "name": "CFG Zero Star/Init"},
"PiDColorBiasCorrection": {"class": PiDColorBiasCorrection, "name": "PiD Color Bias Correction"},
"ModelPatchTorchSettings": {"class": ModelPatchTorchSettings, "name": "Model Patch Torch Settings"},
"WanVideoNAG": {"class": WanVideoNAG, "name": "WanVideoNAG"},
"Krea2PromptWeight": {"class": Krea2PromptWeight, "name": "Krea2 Prompt Weight"},
"MossImagePromptWeight": {"class": MossImagePromptWeight, "name": "MOSS-Image Prompt Weight"},
"GGUFLoaderKJ": {"class": GGUFLoaderKJ, "name": "GGUF Loader KJ"},
"LatentInpaintTTM": {"class": LatentInpaintTTM, "name": "Latent Inpaint TTM"},
"NABLA_AttentionKJ": {"class": NABLA_AttentionKJ, "name": "NABLA Attention KJ"},
"TorchCompileModelAdvanced": {"class": TorchCompileModelAdvanced, "name": "TorchCompileModelAdvanced"},
"StartRecordCUDAMemoryHistory": {"class": StartRecordCUDAMemoryHistory, "name": "Start Recording CUDAMemory History"},
"EndRecordCUDAMemoryHistory": {"class": EndRecordCUDAMemoryHistory, "name": "End Recording CUDAMemory History"},
"VisualizeCUDAMemoryHistory": {"class": VisualizeCUDAMemoryHistory, "name": "Visualize CUDAMemory History"},
"PreviewLatentNoiseMask": {"class": PreviewLatentNoiseMask, "name": "Preview Latent Noise Mask"},
"ModelMemoryUseReportPatch": {"class": ModelMemoryUseReportPatch, "name": "Model Memory Use Report Patch"},
"ModelMemoryUsageFactorOverride": {"class": ModelMemoryUsageFactorOverride, "name": "Model Memory Usage Factor Override"},
"WanChunkFeedForward": {"class": WanChunkFeedForward, "name": "Wan ChunkFeedForward"},
"Ideogram4OptimizationsKJ": {"class": Ideogram4OptimizationsKJ, "name": "Ideogram4 Optimizations KJ"},
"SamplerSelfRefineVideo": {"class": SamplerSelfRefineVideo, "name": "Sampler SelfRefineVideo"},
"PlaySoundKJ": {"class": PlaySoundKJ, "name": "Play Sound KJ"},
#instance diffusion
"CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking},
"AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking},
"DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking},
#lora
"LoraExtractKJ": {"class": LoraExtractKJ, "name": "LoraExtractKJ"},
"LoraReduceRankKJ": {"class": LoraReduceRank, "name": "LoraReduceRank"},
#looping
**{n.GET_SCHEMA().node_id: {"class": n, "name": n.GET_SCHEMA().display_name} for n in LOOP_NODES},
#tracks
"GetTrackRange": {"class": GetTrackRange, "name": "Get Track Range"},
"AddNoiseToTrackPath": {"class": AddNoiseToTrackPath, "name": "Add Noise To Track"},
#context windows
"ContextWindowsVisualizerKJ": {"class": ContextWindowsVisualizerKJ, "name": "Context Windows Visualizer (KJ)"},
# deprecated
"PatchModelPatcherOrder": {"class": PatchModelPatcherOrder, "name": "Patch Model Patcher Order"},
"TorchCompileModelFluxAdvanced": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelFluxAdvanced"},
"TorchCompileLTXModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileLTXModel"},
"TorchCompileCosmosModel": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileCosmosModel"},
"TorchCompileModelHyVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelHyVideo"},
"TorchCompileModelQwenImage": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelQwenImage"},
"TorchCompileModelWanVideo": {"class": DeprecatedCompileNodeKJ, "name": "TorchCompileModelWanVideo"},
}
#ltxv
try:
from .nodes.ltxv_nodes import (
LTXVAddGuideMulti, LTXVAddGuidesFromBatch, LTXVAudioVideoMask, LTX2_NAG,
LTXVChunkFeedForward, LTX2SamplingPreviewOverride,
LTX2AudioLatentNormalizingSampling, LTXVImgToVideoInplaceKJ,
LTX2AttentionTunerPatch, LTX2MemoryEfficientSageAttentionPatch,
LTX2LoraLoaderAdvanced, WanVideoMemoryEfficientSageAttentionPatch,
MiniMaxH3MemoryEfficientSageAttentionPatch,
)
NODE_CONFIG.update({
"LTXVEnhanceAVideoKJ": {"class": LTXVEnhanceAVideoKJ, "name": "LTXV Enhance A Video KJ"},
"LTXVAddGuideMulti": {"class": LTXVAddGuideMulti, "name": "LTXV Add Guide Multi"},
"LTXVAddGuidesFromBatch": {"class": LTXVAddGuidesFromBatch, "name": "LTXV Add Guides From Batch"},
"LTXVAudioVideoMask": {"class": LTXVAudioVideoMask, "name": "LTXV Audio Video Mask"},
"LTX2_NAG": {"class": LTX2_NAG, "name": "LTX2 NAG"},
"LTXVChunkFeedForward": {"class": LTXVChunkFeedForward, "name": "LTXV Chunk Feed Forward"},
"LTX2SamplingPreviewOverride": {"class": LTX2SamplingPreviewOverride, "name": "LTX2 Sampling Preview Override"},
"LTX2AudioLatentNormalizingSampling": {"class": LTX2AudioLatentNormalizingSampling, "name": "LTX2 Audio Latent Normalizing Sampling"},
"LTXVImgToVideoInplaceKJ": {"class": LTXVImgToVideoInplaceKJ, "name": "LTXV Img To Video Inplace KJ"},
"LTX2AttentionTunerPatch": {"class": LTX2AttentionTunerPatch, "name": "LTX2 Attention Tuner Patch"},
"LTX2MemoryEfficientSageAttentionPatch": {"class": LTX2MemoryEfficientSageAttentionPatch, "name": "LTX2 Memory Efficient Sage Attention Patch"},
"LTX2LoraLoaderAdvanced": {"class": LTX2LoraLoaderAdvanced, "name": "LTX2 Lora Loader Advanced"},
"WanVideoMemoryEfficientSageAttentionPatch": {"class": WanVideoMemoryEfficientSageAttentionPatch, "name": "WanVideo Memory Efficient Sage Attention Patch"},
"MiniMaxH3MemoryEfficientSageAttentionPatch": {"class": MiniMaxH3MemoryEfficientSageAttentionPatch, "name": "MiniMax H3 Memory Efficient Sage Attention Patch"},
})
except Exception as e:
logging.warning(f"KJNodes: LTXV nodes could not be imported. LTXV nodes will be unavailable. Error: {e}", exc_info=True)
#minimax
try:
from .nodes.minimax_nodes import MiniMaxChunkFeedForward, MiniMaxLowVRAMAttention, MiniMaxH3TokenCounter
NODE_CONFIG.update({
"MiniMaxChunkFeedForward": {"class": MiniMaxChunkFeedForward, "name": "MiniMax H3 ChunkFeedForward"},
"MiniMaxLowVRAMAttention": {"class": MiniMaxLowVRAMAttention, "name": "MiniMax H3 Low VRAM Attention"},
"MiniMaxH3TokenCounter": {"class": MiniMaxH3TokenCounter, "name": "MiniMax H3 Token Counter"},
})
except Exception as e:
logging.warning(f"KJNodes: MiniMax nodes could not be imported. MiniMax nodes will be unavailable. Error: {e}", exc_info=True)
try:
from .nodes.triton_vae import PatchTritonVAE
NODE_CONFIG.update({
"PatchTritonVAE": {"class": PatchTritonVAE, "name": "Patch Triton VAE"},
})
except Exception:
logging.warning("KJNodes: PatchTritonVAE node could not be imported. PatchTritonVAE will be unavailable.", exc_info=True)
def generate_node_mappings(node_config):
node_class_mappings = {}
node_display_name_mappings = {}
for node_name, node_info in node_config.items():
node_class_mappings[node_name] = node_info["class"]
node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__)
return node_class_mappings, node_display_name_mappings
NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG)
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
WEB_DIRECTORY = "./web"
from aiohttp import web
from server import PromptServer
from pathlib import Path
if hasattr(PromptServer, "instance"):
# NOTE: we add an extra static path to avoid comfy mechanism that loads every script in web.
if not PromptServer.instance.app.router.frozen:
try:
PromptServer.instance.app.add_routes(
[web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())]
)
except Exception:
logging.exception("KJNodes: failed to register /kjweb_async static route")
import asyncio
import os
import folder_paths
@PromptServer.instance.routes.post("/kjnodes/model_mtimes")
async def kjnodes_model_mtimes(request):
# modified times for a combo's model files (Nodes 2.0 folder view date sort); only names already in a model folder listing
try:
values = (await request.json()).get("values")
except Exception:
values = None
if not isinstance(values, list):
return web.json_response({"error": "values must be a list"}, status=400)
wanted = {v for v in values[:50000] if isinstance(v, str)}
def stat():
# the combo list came from object_info, so its folder is already in the filename cache; pick the best match
folder, names = max(((name, wanted.intersection(entry[0])) for name, entry in list(folder_paths.filename_list_cache.items())),
key=lambda x: len(x[1]), default=(None, set()))
out = {}
for name in names:
try:
out[name] = os.path.getmtime(folder_paths.get_full_path(folder, name))
except (OSError, TypeError):
pass
return out
return web.json_response(await asyncio.to_thread(stat))
@@ -0,0 +1,43 @@
{
"authority": "public_reference_only",
"verified_facts": {
"provider": "kijai/ComfyUI-KJNodes",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"registration": "WEB_DIRECTORY -> web/js/setgetnodes.js app.registerExtension/registerCustomNodes -> LiteGraph.registerNodeType",
"virtual": "both constructors set isVirtualNode=true; graphToPrompt omits virtual nodes",
"current_name": "single Constant widget; widgets_values[0] restored unchanged by LGraphNode.configure",
"lookup": "Get.getInputLink(slot) finds first SetNode with strict widgets[0].value === name in graph._nodes, then returns setter.inputs[slot] link",
"set_direct": "inherits LGraphNode.getInputLink(slot); same slot input link",
"frontend_chain": "app.graphToPrompt -> executionUtil.graphToPrompt -> ExecutableNodeDTO.resolveInput/resolveOutput -> virtual getInputLink -> setter input DTO resolveInput -> ultimate entity output",
"callbacks": "app wraps graph.configure with configuringGraphLevel; KJ onConnectionsChange and widget callbacks skip during configuringGraph; onConfigure paste rename requires !configuringGraph",
"previous_name": "Set.update may rename getters through previousName during editing callbacks; it is NOT Get.getInputLink lookup key; titles/labels are not lookup keys",
"scope": "upstream has ancestor/descendant traversal and cross-graph patch; exact current root lookup is separately visible in getInputLink; no scope isolation inferred from execution IDs",
"duplicates": "upstream same-root find returns first; reference rejects all duplicates",
"mode": "upstream can alter bypass Get mode while resolving prompt; reference rejects all nonzero modes without emulation",
"license": "KJ GPL-3.0, frontend GPL-3.0; full license texts and file notices preserved"
},
"explicit_reference_assumptions": {
"missing_version": "only for exact KJ aux_id, select the pinned commit; not target proof",
"missing_provider": "rejected, including literal SetNode/GetNode aux_id",
"missing_frontend": "explicit 1.37.11 only; 1.48.6 requires exact declaration",
"composition": "unmodified pinned root-only KJ plus previously pinned VHS and core widget construction/serialization, before queue hooks; no UE or other override",
"supported_types": "saved concrete equal socket/link types only; no wildcard/union coercion or inference",
"names": "exact saved string; no trim/casefold/Unicode normalization; nonempty whitespace string is valid if exactly matched"
},
"target_unknown": [
"actual provider/version",
"UE behavior and extension overrides",
"models/files/history",
"queue-time hooks",
"execution equivalence"
],
"not_supported": [
"nested/cross-boundary SetGet",
"mute/bypass/loops",
"dynamic type inference",
"arbitrary KJ classes",
"98 other frontend cohort",
"production registration or eligibility"
],
"rules": "sources.json rule_locations; exact line hits against full original byte SHA256"
}
@@ -0,0 +1,15 @@
[project]
name = "comfyui-kjnodes"
description = "Various quality of life -nodes for ComfyUI, mostly just visual stuff to improve usability."
version = "1.5.3"
license = {file = "LICENSE"}
dependencies = ["pillow>=10.3.0", "color-matcher", "matplotlib"]
[project.urls]
Repository = "https://github.com/kijai/ComfyUI-KJNodes"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "kijai"
DisplayName = "ComfyUI-KJNodes"
Icon = "https://avatars.githubusercontent.com/u/40791699"
+500
View File
@@ -0,0 +1,500 @@
{
"sources": [
{
"id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:web/js/setgetnodes.js",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/web/js/setgetnodes.js",
"local_file": "web__js__setgetnodes.js",
"sha256": "6d0b72bfb40f1fbfd60a7e06e6aafd4c6b0a49de35d39567d62383dd842b3274",
"retrieved_at": "2026-10-29T20:48:37.644443+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
1735
]
],
"rule_locations": {
"function getGraphAncestors(graph)#101": [
101,
101
],
"function findSetterByName(graph, name)#190": [
190,
190
],
"function getLink(graph, linkId)#394": [
394,
394
],
"class SetNode extends LGraphNode#571": [
571,
571
],
"class GetNode extends LGraphNode#914": [
914,
914
],
"this.isVirtualNode = true;#588": [
588,
588
],
"this.isVirtualNode = true;#929": [
929,
929
],
"this.properties[\"aux_id\"] = \"kijai/ComfyUI-KJNodes\"#587": [
587,
587
],
"this.properties[\"aux_id\"] = \"kijai/ComfyUI-KJNodes\"#928": [
928,
928
],
"this.addWidget(#590": [
590,
590
],
"this.addWidget(#956": [
956,
956
],
"this.addInput(#606": [
606,
606
],
"this.addOutput(#607": [
607,
607
],
"this.addOutput(#1008": [
1008,
1008
],
"if (app.configuringGraph) return;#617": [
617,
617
],
"if (app.configuringGraph) return;#1022": [
1022,
1022
],
"onConfigure()#770": [
770,
770
],
"onConfigure()#1105": [
1105,
1105
],
"this.properties.previousName = this.widgets[0].value;#601": [
601,
601
],
"this.properties.previousName = this.widgets[0].value;#677": [
677,
677
],
"const name = checkForPreviousName#813": [
813,
813
],
"getInputLink(slot)#1121": [
1121,
1121
],
"n => n.type === 'SetNode' && n.widgets[0].value === name#1127": [
1127,
1127
],
"LiteGraph.registerNodeType(\"SetNode\", SetNode)#906": [
906,
906
],
"LiteGraph.registerNodeType(\"GetNode\", GetNode)#1228": [
1228,
1228
],
"app.graphToPrompt = async function#1589": [
1589,
1589
]
}
},
{
"id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:web/js/utility.js",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/web/js/utility.js",
"local_file": "web__js__utility.js",
"sha256": "edb48d89ed89c9aea0cde2ace1d70034383561cd02124d42e17c3eaa2fcc7177",
"retrieved_at": "2026-10-29T20:48:38.034567+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
291
]
],
"rule_locations": {}
},
{
"id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:__init__.py",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/__init__.py",
"local_file": "__init__.py",
"sha256": "72469fb7da7bbf9e23d327fdc7870ed4c6ee7d8a39e29e212c70bb9b8873f641",
"retrieved_at": "2026-10-29T20:48:38.252708+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
458
]
],
"rule_locations": {
"WEB_DIRECTORY = \"./web\"#415": [
415,
415
]
}
},
{
"id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:pyproject.toml",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/pyproject.toml",
"local_file": "pyproject.toml",
"sha256": "3c84ba5c3d134af053b3d832a67e616d25fcbc4e97b9d906ca608986aabd5b58",
"retrieved_at": "2026-10-29T20:48:38.627867+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
15
]
],
"rule_locations": {}
},
{
"id": "kijai/ComfyUI-KJNodes@ab72eda7ffad6280422d71ab7d54d3fb87c0ba18:LICENSE",
"commit": "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18",
"raw_url": "https://raw.githubusercontent.com/kijai/ComfyUI-KJNodes/ab72eda7ffad6280422d71ab7d54d3fb87c0ba18/LICENSE",
"local_file": "LICENSE",
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
"retrieved_at": "2026-10-29T20:48:38.849665+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
674
]
],
"rule_locations": {}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/config/comfyApi.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/config/comfyApi.ts",
"local_file": "1.37.11__src__config__comfyApi.ts",
"sha256": "231459674610af5d15df37f79bbc27f29cfcefa938c338e54a42d59b130f69dc",
"retrieved_at": "2026-10-29T20:48:39.267718+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
43
]
],
"rule_locations": {}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:build/plugins/comfyAPIPlugin.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/build/plugins/comfyAPIPlugin.ts",
"local_file": "1.37.11__build__plugins__comfyAPIPlugin.ts",
"sha256": "3b57d35aa3cff3d4099c8e30e888e017f87803f3d5d64231346191073f7c204a",
"retrieved_at": "2026-10-29T20:48:39.659975+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
118
]
],
"rule_locations": {
"window.comfyAPI.${moduleName}.${name}#57": [
57,
57
],
"window.comfyAPI.${moduleName}.${name}#59": [
59,
59
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/scripts/app.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/scripts/app.ts",
"local_file": "1.37.11__src__scripts__app.ts",
"sha256": "e57985f7d365abb035bc2fc755a8f5b10efbca97a7dcb5b2a4a05bcbc78b9d5c",
"retrieved_at": "2026-10-29T20:48:40.175830+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
1744
]
],
"rule_locations": {
"app.configuringGraphLevel++#721": [
721,
721
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/lib/litegraph/src/LGraphNode.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/LGraphNode.ts",
"local_file": "1.37.11__src__lib__litegraph__src__LGraphNode.ts",
"sha256": "706225a8a06cd7929f9e04fe2388bcdb8f158cdac756c65c45657c020ab7b319",
"retrieved_at": "2026-10-29T20:48:40.702689+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
4198
]
],
"rule_locations": {
"widget.value = info.widgets_values[i++]#872": [
872,
872
],
"this.onConfigure?.(info)#880": [
880,
880
],
"getInputLink(slot: number)#1159": [
1159,
1159
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
"local_file": "1.37.11__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts",
"sha256": "fd2e19a6b8f4369e6e97d79f407cc1bec130feec9d6d3c979cc03b0a556f249f",
"retrieved_at": "2026-10-29T20:48:41.102250+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
408
]
],
"rule_locations": {
"const virtualLink = this.node.getInputLink(slot)#291": [
291,
291
],
"return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)#307": [
307,
307
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:src/utils/executionUtil.ts",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/executionUtil.ts",
"local_file": "1.37.11__src__utils__executionUtil.ts",
"sha256": "4e51bc54e35cb7ac9bb7cba418a74ccdd5974f640b9b088aa4ae7668f746ab36",
"retrieved_at": "2026-10-29T20:48:41.524838+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
150
]
],
"rule_locations": {
"node.isVirtualNode ||#78": [
78,
78
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@4bf6a1960028cc5cda57d48f9fb01a74dfaade43:LICENSE",
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/LICENSE",
"local_file": "1.37.11__LICENSE",
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
"retrieved_at": "2026-10-29T20:48:41.966937+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
674
]
],
"rule_locations": {}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/config/comfyApi.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/config/comfyApi.ts",
"local_file": "1.48.6__src__config__comfyApi.ts",
"sha256": "439d45da4c437ec06ddf27a3d301905f678113bf0341b674a235417d1e60ab9c",
"retrieved_at": "2026-10-29T20:48:42.376174+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
35
]
],
"rule_locations": {}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:build/plugins/comfyAPIPlugin.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/build/plugins/comfyAPIPlugin.ts",
"local_file": "1.48.6__build__plugins__comfyAPIPlugin.ts",
"sha256": "2bb4aaf83f40b6ac06604188fbc34c26e8616c3e0be223eb09f0ae68a96d60c6",
"retrieved_at": "2026-10-29T20:48:42.779241+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
123
]
],
"rule_locations": {
"window.comfyAPI.${moduleName}.${name}#61": [
61,
61
],
"window.comfyAPI.${moduleName}.${name}#63": [
63,
63
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/scripts/app.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/scripts/app.ts",
"local_file": "1.48.6__src__scripts__app.ts",
"sha256": "e274c5f4420e8aefdacf1a716296ee7ae4c9079e77578272d3eeef05350e4c71",
"retrieved_at": "2026-10-29T20:48:43.166322+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
2260
]
],
"rule_locations": {
"app.configuringGraphLevel++#855": [
855,
855
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/lib/litegraph/src/LGraphNode.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/lib/litegraph/src/LGraphNode.ts",
"local_file": "1.48.6__src__lib__litegraph__src__LGraphNode.ts",
"sha256": "7d312ebe5182c4c69d45b5d5e4434dfd42405f72455310886acded76ce1d60ed",
"retrieved_at": "2026-10-29T20:48:43.577670+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
4360
]
],
"rule_locations": {
"widget.value = info.widgets_values[i++]#991": [
991,
991
],
"this.onConfigure?.(info)#1007": [
1007,
1007
],
"getInputLink(slot: number)#1296": [
1296,
1296
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
"local_file": "1.48.6__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts",
"sha256": "64baa71b46bd67440b032e18e4d9aebb67a6cc135fe7c4509ae1b5bc25acc2a3",
"retrieved_at": "2026-10-29T20:48:44.175734+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
429
]
],
"rule_locations": {
"const virtualLink = this.node.getInputLink(slot)#312": [
312,
312
],
"return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)#328": [
328,
328
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:src/utils/executionUtil.ts",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/src/utils/executionUtil.ts",
"local_file": "1.48.6__src__utils__executionUtil.ts",
"sha256": "264e11395f28880603e7f9fe36d2e61c74cd59d6d88be990225cce8510e3f816",
"retrieved_at": "2026-10-29T20:48:44.542997+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
160
]
],
"rule_locations": {
"node.isVirtualNode ||#86": [
86,
86
]
}
},
{
"id": "Comfy-Org/ComfyUI_frontend@7b4172a243e0d43f1679c0be1c307560cd83c00d:LICENSE",
"commit": "7b4172a243e0d43f1679c0be1c307560cd83c00d",
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7b4172a243e0d43f1679c0be1c307560cd83c00d/LICENSE",
"local_file": "1.48.6__LICENSE",
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
"retrieved_at": "2026-10-29T20:48:44.932058+00:00",
"license": "GPL-3.0",
"lines": [
[
1,
674
]
],
"rule_locations": {}
}
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,291 @@
const { app } = window.comfyAPI.app;
// ─── General-purpose helpers shared across KJNodes JS ───
export function makeUUID() {
let dt = new Date().getTime()
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = ((dt + Math.random() * 16) % 16) | 0
dt = Math.floor(dt / 16)
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
})
return uuid
}
export function chainCallback(object, property, callback) {
if (object == undefined) {
console.error("Tried to add callback to non-existant object")
return;
}
if (property in object) {
const callback_orig = object[property]
object[property] = function () {
const r = callback_orig.apply(this, arguments);
callback.apply(this, arguments);
return r
};
} else {
object[property] = callback;
}
}
export function hideWidgetForGood(node, widget, suffix = '') {
widget.origType = widget.type
widget.origComputeSize = widget.computeSize
widget.origSerializeValue = widget.serializeValue
widget.computeSize = () => [0, -4]
widget.type = "converted-widget" + suffix
if (widget.linkedWidgets) {
for (const w of widget.linkedWidgets) {
hideWidgetForGood(node, w, ':' + widget.name)
}
}
}
// ─── Graph coordinate helpers ───
export function clientToCanvas(lgCanvas, clientX, clientY) {
const rect = lgCanvas.canvas.getBoundingClientRect();
return [
(clientX - rect.left) / lgCanvas.ds.scale - lgCanvas.ds.offset[0],
(clientY - rect.top) / lgCanvas.ds.scale - lgCanvas.ds.offset[1],
];
}
export function getNodeAtPoint(graph, cx, cy) {
for (let i = graph._nodes.length - 1; i >= 0; i--) {
if (graph._nodes[i].isPointInside(cx, cy)) return graph._nodes[i];
}
return null;
}
export function typesCompatible(a, b) {
if (a === "*" || b === "*") return true;
if (a === b) return true;
if (typeof a !== "string" || typeof b !== "string") return false;
if (a.toUpperCase() === b.toUpperCase()) return true;
// ComfyUI accepts union types like "STRING,INT" — match if any token overlaps
if (a.includes(",") || b.includes(",")) {
const aTokens = a.toUpperCase().split(",").map(s => s.trim()).filter(Boolean);
const bTokens = b.toUpperCase().split(",").map(s => s.trim()).filter(Boolean);
if (aTokens.includes("*") || bTokens.includes("*")) return true;
return aTokens.some(t => bTokens.includes(t));
}
return false;
}
// ─── Slot position helper ───
// Uses modern API (DOM-registered positions in Vue mode) with legacy fallback
export function getSlotPos(node, isInput, slotIdx) {
if (isInput && node.getInputPos) return node.getInputPos(slotIdx);
if (!isInput && node.getOutputPos) return node.getOutputPos(slotIdx);
const out = [0, 0];
node.getConnectionPos(isInput, slotIdx, out);
return out;
}
// Link by node id; subgraph IO nodes aren't in graph._nodes and have no connect(), so go through their slot objects
export function connectById(graph, originId, originSlot, targetId, targetSlot, afterRerouteId) {
const target = graph.getNodeById(targetId);
if (graph.inputNode && originId === graph.inputNode.id) {
const input = target?.inputs?.[targetSlot];
return input ? graph.inputNode.slots[originSlot]?.connect(input, target, afterRerouteId) ?? null : null;
}
const origin = graph.getNodeById(originId);
if (!origin) return null;
if (graph.outputNode && targetId === graph.outputNode.id) {
const output = origin.outputs?.[originSlot];
return output ? graph.outputNode.slots[targetSlot]?.connect(output, origin, afterRerouteId) ?? null : null;
}
return target ? origin.connect(originSlot, target, targetSlot, afterRerouteId) : null;
}
// ─── Middle-click pan passthrough for DOM widgets ───
// Allows panning the LiteGraph canvas via middle-click drag on any DOM element
export function addMiddleClickPan(element) {
const onMouseDown = (e) => {
if (e.button !== 1) return;
e.preventDefault();
const ds = app.canvas?.ds;
if (!ds) return;
const startX = e.clientX, startY = e.clientY;
const startOffsetX = ds.offset[0], startOffsetY = ds.offset[1];
const onMove = (me) => {
const scale = ds.scale || 1; // offset is graph-space; LiteGraph pans by (screen delta / scale)
ds.offset[0] = startOffsetX + (me.clientX - startX) / scale;
ds.offset[1] = startOffsetY + (me.clientY - startY) / scale;
app.canvas.setDirty(true, true);
};
const onUp = () => {
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onUp);
};
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onUp);
};
element.addEventListener('mousedown', onMouseDown);
return () => element.removeEventListener('mousedown', onMouseDown);
}
// The widget holding a loader's input file: Load Image "image", VHS-style "video", core Load Video "file"
const sourceFileWidget = (srcNode) => srcNode.widgets?.find((w) => w.name === "image" || w.name === "video" || (w.name === "file" && srcNode.comfyClass === "LoadVideo"));
// ─── Resolve preview image/video from a connected source node ───
// Walks the graph link to find what's connected to node.inputs[inputSlot]
// and returns { url, isVideo, videoEl } or null
export function resolveSourcePreview(node, inputSlot) {
if (!node.graph) return null;
const input = node.inputs?.[inputSlot];
if (!input || input.link == null) return null;
const link = node.graph.links?.get(input.link);
if (!link) return null;
const srcNode = node.graph.getNodeById(link.origin_id);
if (!srcNode) return null;
// Check for VHS-style video preview widget
const vpWidget = srcNode.widgets?.find((w) => w.name === "videopreview");
if (vpWidget?.videoEl?.src) {
return { isVideo: true, videoEl: vpWidget.videoEl };
}
const w = sourceFileWidget(srcNode);
if (w?.value) {
let subfolder = "", fname = w.value;
const lastSlash = fname.lastIndexOf("/");
if (lastSlash >= 0) { subfolder = fname.substring(0, lastSlash); fname = fname.substring(lastSlash + 1); }
const isVideo = w.name !== "image";
const url = `/view?filename=${encodeURIComponent(fname)}&type=input&subfolder=${encodeURIComponent(subfolder)}`;
return { url, isVideo };
}
// Fallback: check node.imgs (set after execution)
if (srcNode.imgs?.length > 0 && srcNode.imgs[0].src) {
return { url: srcNode.imgs[0].src, isVideo: false };
}
return null;
}
// ─── Source input watcher ───
// Watches IMAGE inputs for connection changes and source widget changes.
// Calls onChange(sources) when connections change or the source node's image/video widget changes.
// inputName: an input name, a predicate (input) => bool, or null for every IMAGE input.
// sources: array of { url, isVideo, videoEl, name } per connected matching input (name = that input's name).
// Returns a cleanup function.
export function watchImageInputs(node, inputName, onChange) {
let watchedWidgets = [];
const matches = (inp) => typeof inputName === "function" ? inputName(inp) : inputName ? inp.name === inputName : inp.type === "IMAGE";
const matchingSlots = () => node.inputs.map((inp, i) => matches(inp) ? i : -1).filter(i => i >= 0);
function unwatchWidgets() {
for (const { widget, origCb } of watchedWidgets) widget.callback = origCb;
watchedWidgets = [];
}
function resolve() {
if (!node.inputs) return [];
return matchingSlots().map(i => {
const s = resolveSourcePreview(node, i);
return s && { ...s, name: node.inputs[i].name };
}).filter(s => s);
}
function watch() {
unwatchWidgets();
if (!node.inputs || !node.graph) return;
const slots = matchingSlots();
for (const slotIdx of slots) {
const input = node.inputs[slotIdx];
if (!input || input.link == null) continue;
const link = node.graph.links?.get(input.link);
if (!link) continue;
const srcNode = node.graph.getNodeById(link.origin_id);
if (!srcNode) continue;
const w = sourceFileWidget(srcNode);
if (!w) continue;
const origCb = w.callback;
w.callback = function (...args) {
if (origCb) origCb.apply(this, args);
setTimeout(() => onChange(resolve()), 100);
};
watchedWidgets.push({ widget: w, origCb });
}
}
chainCallback(node, "onConnectionsChange", function (type) {
// Only react to input connection changes, not output
if (type != null && type !== 1) return;
setTimeout(() => {
watch();
onChange(resolve());
}, 100);
});
chainCallback(node, "onRemoved", unwatchWidgets);
return unwatchWidgets;
}
// ─── Video frame capture ───
// Draws the current frame of a video element to a fresh canvas at native resolution.
// If the video isn't decoded yet (readyState < 2), waits once for "loadeddata" before capturing.
// Calls callback(canvas) with the resulting canvas. Caller decides whether to use it directly
// (drawImage accepts canvas) or convert via toDataURL.
export function captureVideoFrame(videoEl, callback) {
const capture = () => {
if (!videoEl.videoWidth || !videoEl.videoHeight) return;
const c = document.createElement("canvas");
c.width = videoEl.videoWidth;
c.height = videoEl.videoHeight;
c.getContext("2d").drawImage(videoEl, 0, 0);
callback(c);
};
if (videoEl.readyState >= 2) {
capture();
} else {
const onReady = () => { videoEl.removeEventListener("loadeddata", onReady); capture(); };
videoEl.addEventListener("loadeddata", onReady);
}
}
// ─── Bounding box hit test ───
// Tests whether (mx, my) hits a corner handle or the interior of a rect defined by (x1, y1)–(x2, y2).
// Returns "resize-tl", "resize-tr", "resize-bl", "resize-br", "resize-t", "resize-b", "resize-l", "resize-r", "move", or null.
export function rectHitTest(mx, my, x1, y1, x2, y2, radius) {
const hit = (cx, cy) => Math.abs(mx - cx) < radius && Math.abs(my - cy) < radius;
// Corners first (higher priority)
if (hit(x1, y1)) return "resize-tl";
if (hit(x2, y1)) return "resize-tr";
if (hit(x1, y2)) return "resize-bl";
if (hit(x2, y2)) return "resize-br";
// Edges
if (mx >= x1 && mx <= x2 && Math.abs(my - y1) < radius) return "resize-t";
if (mx >= x1 && mx <= x2 && Math.abs(my - y2) < radius) return "resize-b";
if (my >= y1 && my <= y2 && Math.abs(mx - x1) < radius) return "resize-l";
if (my >= y1 && my <= y2 && Math.abs(mx - x2) < radius) return "resize-r";
// Interior
if (mx >= x1 && mx <= x2 && my >= y1 && my <= y2) return "move";
return null;
}
// Returns the appropriate CSS cursor for a bbox hit mode string.
export function cursorForBboxMode(mode) {
if (mode === "move") return "move";
if (mode === "resize-tl" || mode === "resize-br") return "nwse-resize";
if (mode === "resize-tr" || mode === "resize-bl") return "nesw-resize";
if (mode === "resize-t" || mode === "resize-b") return "ns-resize";
if (mode === "resize-l" || mode === "resize-r") return "ew-resize";
return null;
}
// ─── Wheel zoom passthrough for DOM widgets ───
// Re-dispatches wheel events to the LiteGraph canvas for zoom
export function addWheelPassthrough(element) {
element.addEventListener("wheel", (e) => {
const gc = document.getElementById("graph-canvas");
if (gc) {
gc.dispatchEvent(new WheelEvent(e.type, e));
e.preventDefault();
}
}, { passive: false });
}