comfy-ts 2.17.1 → 2.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/index.cjs +1078 -190
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1185 -410
  5. package/dist/index.d.ts +1185 -410
  6. package/dist/index.js +1078 -190
  7. package/dist/index.js.map +1 -1
  8. package/dist/{run-run-tg82jUIk.js → run-run-Zr699h2S.js} +2 -2
  9. package/dist/{run-run-tg82jUIk.js.map → run-run-Zr699h2S.js.map} +1 -1
  10. package/dist/{run-tui-Bw7BA75d.js → run-tui-CeM1GOJP.js} +2 -2
  11. package/dist/{run-tui-Bw7BA75d.js.map → run-tui-CeM1GOJP.js.map} +1 -1
  12. package/dist/serve-web.js +47 -47
  13. package/dist/{state-zTow5ucI.js → state-C067Kbew.js} +1079 -191
  14. package/dist/state-C067Kbew.js.map +1 -0
  15. package/dist/web.d.ts +1203 -428
  16. package/dist/web.js +1078 -190
  17. package/dist/web.js.map +1 -1
  18. package/examples/comfy-cloud/ace-step15-t2a.cflow.ts +163 -0
  19. package/examples/comfy-cloud/anima-t2i-base.cflow.ts +57 -0
  20. package/examples/comfy-cloud/boogu-t2i.cflow.ts +55 -0
  21. package/examples/comfy-cloud/chronoedit-i2i.cflow.ts +95 -0
  22. package/examples/comfy-cloud/ernie-t2i-base.cflow.ts +81 -0
  23. package/examples/comfy-cloud/flux1-t2i-krea.cflow.ts +63 -0
  24. package/examples/comfy-cloud/flux2-i2i-dev.cflow.ts +83 -0
  25. package/examples/comfy-cloud/flux2-t2i-dev.cflow.ts +60 -0
  26. package/examples/comfy-cloud/hidream-o1-i2i.cflow.ts +71 -0
  27. package/examples/comfy-cloud/hidream-o1-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/krea2-i2i.cflow.ts +78 -0
  29. package/examples/comfy-cloud/ltx2-i2v.cflow.ts +175 -0
  30. package/examples/comfy-cloud/ltx2-t2v.cflow.ts +143 -0
  31. package/examples/comfy-cloud/ltx23-i2v.cflow.ts +189 -0
  32. package/examples/comfy-cloud/ltx23-t2v.cflow.ts +151 -0
  33. package/examples/comfy-cloud/mage-flow-i2i-turbo.cflow.ts +72 -0
  34. package/examples/comfy-cloud/mage-flow-i2i.cflow.ts +74 -0
  35. package/examples/comfy-cloud/mage-flow-t2i-turbo.cflow.ts +60 -0
  36. package/examples/comfy-cloud/mage-flow-t2i.cflow.ts +60 -0
  37. package/examples/comfy-cloud/minimax-h3-t2i.cflow.ts +64 -0
  38. package/examples/comfy-cloud/netayume-t2i.cflow.ts +60 -0
  39. package/examples/comfy-cloud/qwen-image-i2i-2509.cflow.ts +75 -0
  40. package/examples/comfy-cloud/qwen-image-t2i-2512.cflow.ts +63 -0
  41. package/examples/comfy-cloud/sdk.d.ts +21683 -13737
  42. package/examples/comfy-cloud/stable-audio3-t2a.cflow.ts +96 -0
  43. package/examples/comfy-cloud/z-image-t2i-base.cflow.ts +54 -0
  44. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +1 -1
  45. package/package.json +2 -2
  46. package/src/graph/ComfyNode.ts +93 -12
  47. package/src/host/ComfyHost.ts +37 -46
  48. package/src/host/ComfyManager.ts +576 -64
  49. package/src/litegraph/CanonicalWorkflow.ts +3 -0
  50. package/src/litegraph/LiteGraphJSON.ts +2 -2
  51. package/src/litegraph/LiteGraphNodeInput.ts +2 -2
  52. package/src/litegraph/LiteGraphNodeOutput.ts +2 -2
  53. package/src/litegraph/convertFlowToLiteGraphJSON.ts +112 -37
  54. package/src/litegraph/expandSubgraphs.ts +72 -4
  55. package/src/litegraph/normalizeWorkflow.ts +7 -1
  56. package/src/manager/ComfyRegistry.ts +2 -0
  57. package/src/manager/generated/KnownComfyCustomNodeName.ts +6354 -1680
  58. package/src/manager/generated/KnownComfyPluginTitle.ts +718 -356
  59. package/src/manager/generated/KnownComfyPluginURL.ts +357 -181
  60. package/src/manager/generated/KnownModel_Base.ts +9 -5
  61. package/src/manager/generated/KnownModel_FileName.ts +135 -0
  62. package/src/manager/generated/KnownModel_Name.ts +135 -0
  63. package/src/manager/generated/KnownModel_SavePath.ts +16 -14
  64. package/src/manager/generated/KnownModel_Type.ts +15 -13
  65. package/src/manager/installedView.ts +178 -0
  66. package/src/manager/json/custom-node-list.json +4018 -2248
  67. package/src/manager/json/extension-node-map.json +8903 -2964
  68. package/src/manager/json/github-stats.json +10796 -10036
  69. package/src/manager/json/model-list.json +298 -1
  70. package/src/manager/loaders/step4_model-list-loader.ts +1 -0
  71. package/src/manager/types/ComfyManagerAPIModelList.ts +3 -0
  72. package/src/manager/types/ComfyManagerAPIPluginList.ts +19 -0
  73. package/src/runner/ComfyExecution.ts +4 -1
  74. package/src/runner/ComfyWsApi.ts +82 -15
  75. package/src/sdk-generator/ComfySchema.ts +10 -1
  76. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +4 -1
  77. package/src/sdk-generator/comfyui-sdk-codegen.ts +61 -20
  78. package/src/sdk-generator/inputWidgetKind.ts +19 -4
  79. package/src/sdk-generator/litegraphToApiRequestPayload.ts +157 -35
  80. package/dist/state-zTow5ucI.js.map +0 -1
package/dist/web.js CHANGED
@@ -101,7 +101,7 @@ function getComfyStorage() {
101
101
  }
102
102
  //#endregion
103
103
  //#region package.json
104
- var version = "2.17.1";
104
+ var version = "2.18.1";
105
105
  //#endregion
106
106
  //#region src/litegraph/LiteGraphLinkID.ts
107
107
  const asLiteGraphLinkID = (id) => id;
@@ -121,8 +121,55 @@ const bang = (x, msg = "") => {
121
121
  /** boundary sentinel ids inside definition link tables */
122
122
  const SUBGRAPH_INPUT_NODE_ID = -10;
123
123
  const SUBGRAPH_OUTPUT_NODE_ID = -20;
124
- /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
125
- const MAX_EXPANSION_PASSES = 32;
124
+ /** expanded node count above which a file is refused before expanding: the largest official
125
+ * template expands to 575 nodes, and fan-out nesting grows geometrically without any cycle */
126
+ const MAX_EXPANDED_NODES = 1e5;
127
+ /**
128
+ * before any expansion: the definitions as a graph (def → the defs its NORMAL-mode instances name,
129
+ * the only ones expansion follows). A cycle reachable from the root is refused with the defs it
130
+ * runs through, and the expanded size is counted, not built, and refused above
131
+ * MAX_EXPANDED_NODES. One explicit stack, no recursion: the file decides the depth
132
+ */
133
+ const checkExpansion = (wf, defs) => {
134
+ const children = (nodes) => nodes.filter((n) => n.mode === "normal" && defs.has(n.type)).map((n) => n.type);
135
+ const own = (nodes) => nodes.filter((n) => !(n.mode === "normal" && defs.has(n.type))).length;
136
+ const name = (id) => JSON.stringify(defs.get(id)?.name ?? id);
137
+ const cap = (n) => Math.min(n, 100001);
138
+ const size = /* @__PURE__ */ new Map();
139
+ const onPath = /* @__PURE__ */ new Set();
140
+ for (const root of new Set(children(wf.nodes))) {
141
+ if (size.has(root)) continue;
142
+ const stack = [{
143
+ id: root,
144
+ kids: children(bang(defs.get(root)).nodes),
145
+ next: 0
146
+ }];
147
+ onPath.add(root);
148
+ while (stack.length > 0) {
149
+ const top = bang(stack[stack.length - 1]);
150
+ const kid = top.kids[top.next++];
151
+ if (kid == null) {
152
+ const total = top.kids.reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(bang(defs.get(top.id)).nodes));
153
+ size.set(top.id, total);
154
+ onPath.delete(top.id);
155
+ stack.pop();
156
+ continue;
157
+ }
158
+ if (size.has(kid)) continue;
159
+ if (onPath.has(kid)) {
160
+ const from = stack.findIndex((frame) => frame.id === kid);
161
+ throw new WorkflowNormalizeError("subgraph-cycle", `subgraph definitions contain themselves: ${[...stack.slice(from).map((frame) => frame.id), kid].map(name).join(" → ")}`, { cycle: stack.slice(from).map((frame) => frame.id) });
162
+ }
163
+ onPath.add(kid);
164
+ stack.push({
165
+ id: kid,
166
+ kids: children(bang(defs.get(kid)).nodes),
167
+ next: 0
168
+ });
169
+ }
170
+ }
171
+ if (children(wf.nodes).reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(wf.nodes)) > 1e5) throw new WorkflowNormalizeError("subgraph-too-large", `subgraph expansion would produce more than ${MAX_EXPANDED_NODES} nodes (the largest official template has 575)`);
172
+ };
126
173
  /**
127
174
  * widget-kind fallback when a def input slot has no boundary target carrying a
128
175
  * widget marker: these litegraph slot types carry widget values. LOCAL copy on
@@ -145,11 +192,12 @@ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
145
192
  * passthrough walk, which needs no interior.
146
193
  */
147
194
  const expandSubgraphs = (wf, defs) => {
195
+ checkExpansion(wf, defs);
148
196
  let passes = 0;
149
197
  while (true) {
150
198
  const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
151
199
  if (expandable.length === 0) return wf;
152
- if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
200
+ if (++passes > defs.size + 1) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion still had instances after ${passes - 1} passes over ${defs.size} definitions`);
153
201
  for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
154
202
  else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
155
203
  }
@@ -257,7 +305,8 @@ const expandOneInstance = (wf, instance, def) => {
257
305
  name: i.name,
258
306
  type: i.type,
259
307
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
260
- widgetName: i.widgetName
308
+ widgetName: i.widgetName,
309
+ widgetSource: i.widgetSource
261
310
  })),
262
311
  outputs: inner.outputs.map((o) => ({
263
312
  name: o.name,
@@ -298,6 +347,20 @@ const expandOneInstance = (wf, instance, def) => {
298
347
  wf.links = wf.links.filter((l) => !dead.has(l.id));
299
348
  pruneDeadLinkRefs(wf, dead);
300
349
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
350
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
351
+ if (outerLinkIntoDefSlot.has(slot)) continue;
352
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
353
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
354
+ if (source == null || sourceInput == null) continue;
355
+ for (const t of targets) {
356
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
357
+ if (input == null || input.widgetName != null || input.link != null) continue;
358
+ input.widgetSource = {
359
+ nodeId: source.nodeId,
360
+ inputName: sourceInput.name
361
+ };
362
+ }
363
+ }
301
364
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
302
365
  wf.nodes.push(...splicedNodes);
303
366
  wf.links.push(...splicedLinks);
@@ -409,7 +472,7 @@ const LiteGraphNodeInput_ark = type({
409
472
  type: "string",
410
473
  "link?": LiteGraphLinkID_.or(type.null),
411
474
  "shape?": "number",
412
- "label?": "string",
475
+ "label?": type.string.or(type.null),
413
476
  "widget?": type({
414
477
  name: "string",
415
478
  "config?": "unknown"
@@ -426,7 +489,7 @@ const LiteGraphNodeOutput_ark = type({
426
489
  type: "string",
427
490
  "links?": LiteGraphLinkID_.array().or(type.null),
428
491
  "shape?": "number",
429
- "slot_index?": LiteGraphSlotIndex_
492
+ "slot_index?": LiteGraphSlotIndex_.or(type.null)
430
493
  });
431
494
  //#endregion
432
495
  //#region src/litegraph/LiteGraphNode.ts
@@ -496,7 +559,7 @@ const LiteGraphSubgraphDef_ark = type({
496
559
  const LiteGraphJSON_ark = type({
497
560
  "id?": "string",
498
561
  "revision?": "number",
499
- "last_node_id?": "number",
562
+ "last_node_id?": "number | string",
500
563
  "last_link_id?": "number",
501
564
  "state?": type.Record("string", "unknown"),
502
565
  nodes: LiteGraphNode_ark.array(),
@@ -595,7 +658,8 @@ const normalizeInput = (i) => {
595
658
  name: i.name,
596
659
  type: i.type,
597
660
  link: i.link ?? null,
598
- widgetName: i.widget?.name ?? null
661
+ widgetName: i.widget?.name ?? null,
662
+ widgetSource: null
599
663
  };
600
664
  };
601
665
  const normalizeOutput = (o) => {
@@ -768,6 +832,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
768
832
  python_module: "nodes"
769
833
  };
770
834
  //#endregion
835
+ //#region src/utils/exhaust.ts
836
+ function exhaust(x) {
837
+ return x;
838
+ }
839
+ //#endregion
771
840
  //#region src/sdk-generator/inputWidgetKind.ts
772
841
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
773
842
  /**
@@ -836,6 +905,14 @@ const parseContainer = (template) => {
836
905
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
837
906
  };
838
907
  };
908
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
909
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
910
+ const parseGroup = (o, template) => ({
911
+ kind: "dynamic-group",
912
+ fields: flattenInputSections(template),
913
+ min: typeof o["min"] === "number" ? o["min"] : 0,
914
+ max: typeof o["max"] === "number" ? o["max"] : 20
915
+ });
839
916
  /**
840
917
  * the single template sub-input's slot type of an autogrow container
841
918
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -910,11 +987,12 @@ const classifyWidgetInput = (p) => {
910
987
  };
911
988
  }
912
989
  const template = o?.["template"];
913
- if (isRecord$1(template)) {
990
+ if (o != null && isRecord$1(template)) {
914
991
  if (isRecord$1(template["input"])) return parseContainer(template);
992
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
915
993
  return { kind: "slot" };
916
994
  }
917
- if (o?.["socketless"] === true) return {
995
+ if (typeof o?.["socketless"] === "boolean") return {
918
996
  kind: "widget",
919
997
  consumes: 1,
920
998
  strictValues: false,
@@ -1014,6 +1092,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1014
1092
  if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
1015
1093
  else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
1016
1094
  }
1095
+ const linksById = new Map(workflow.links.map((l) => [l.id, l]));
1096
+ const nodesById = new Map(workflow.nodes.map((n) => [n.id, n]));
1017
1097
  for (const node of workflow.nodes) {
1018
1098
  if (isNeverExecuted(node)) continue;
1019
1099
  if (node.mode !== "normal") continue;
@@ -1087,18 +1167,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1087
1167
  inputs[p.path] = key;
1088
1168
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1089
1169
  };
1170
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1171
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1172
+ const consumeDynamicGroup = (p) => {
1173
+ const r = resolveWidgetValue({
1174
+ promptName: p.path,
1175
+ consumes: 1,
1176
+ prefixLen: 0
1177
+ });
1178
+ const saved = r.filled ? p.min : r.value;
1179
+ if (typeof saved !== "number" || !Number.isInteger(saved) || saved < 0 || saved > p.max) throw new WorkflowConvertError("invalid-widget-value", `node ${node.id}(${node.type}): dynamic group "${p.path}" row count is not an integer in [0, ${p.max}]: ${JSON.stringify(saved)}`, node);
1180
+ const rows = Math.max(p.min, saved);
1181
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1182
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1183
+ };
1090
1184
  const consumeBranchInput = (subPath, sub) => {
1091
1185
  const kind = classifyWidgetInput({
1092
- name: sub.name,
1186
+ name: subPath,
1093
1187
  type: sub.type,
1094
1188
  opts: sub.opts
1095
1189
  });
1096
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1097
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1098
- path: subPath,
1099
- options: kind.options,
1100
- defaultKey: kind.defaultKey
1101
- });
1190
+ switch (kind.kind) {
1191
+ case "slot":
1192
+ case "dynamic-container": return;
1193
+ case "dynamic-combo": return consumeDynamicCombo({
1194
+ path: subPath,
1195
+ options: kind.options,
1196
+ defaultKey: kind.defaultKey
1197
+ });
1198
+ case "dynamic-group": return consumeDynamicGroup({
1199
+ path: subPath,
1200
+ fields: kind.fields,
1201
+ min: kind.min,
1202
+ max: kind.max
1203
+ });
1204
+ case "widget": break;
1205
+ default: return exhaust(kind);
1206
+ }
1102
1207
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1103
1208
  consumePlainWidget({
1104
1209
  promptName: subPath,
@@ -1120,32 +1225,56 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1120
1225
  strictValues: true,
1121
1226
  prefixValues: []
1122
1227
  };
1123
- if (kind.kind === "widget") consumePlainWidget({
1124
- promptName: field.nameInComfy,
1125
- typeName: field.typeName,
1126
- opts: field.opts,
1127
- consumes: kind.consumes,
1128
- prefixLen: kind.prefixValues.length,
1129
- strict: kind.strictValues,
1130
- linkedInput: input
1131
- });
1132
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1133
- path: field.nameInComfy,
1134
- options: kind.options,
1135
- defaultKey: kind.defaultKey
1136
- });
1137
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1138
- const iname = `${field.nameInComfy}.${instName}`;
1139
- if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1140
- }
1141
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1142
- if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
1228
+ switch (kind.kind) {
1229
+ case "widget":
1230
+ consumePlainWidget({
1231
+ promptName: field.nameInComfy,
1232
+ typeName: field.typeName,
1233
+ opts: field.opts,
1234
+ consumes: kind.consumes,
1235
+ prefixLen: kind.prefixValues.length,
1236
+ strict: kind.strictValues,
1237
+ linkedInput: input
1238
+ });
1239
+ break;
1240
+ case "dynamic-combo":
1241
+ consumeDynamicCombo({
1242
+ path: field.nameInComfy,
1243
+ options: kind.options,
1244
+ defaultKey: kind.defaultKey
1245
+ });
1246
+ break;
1247
+ case "dynamic-group":
1248
+ consumeDynamicGroup({
1249
+ path: field.nameInComfy,
1250
+ fields: kind.fields,
1251
+ min: kind.min,
1252
+ max: kind.max
1253
+ });
1254
+ break;
1255
+ case "dynamic-container":
1256
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1257
+ const iname = `${field.nameInComfy}.${instName}`;
1258
+ if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1259
+ }
1260
+ break;
1261
+ case "slot":
1262
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1263
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1264
+ promptName: field.nameInComfy,
1265
+ strict: false
1266
+ });
1267
+ break;
1268
+ }
1269
+ if (!fieldNamesPresent.has(field.nameInComfy) && field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
1270
+ break;
1271
+ default:
1143
1272
  }
1144
1273
  }
1145
1274
  const getParentNode = (linkId) => {
1146
- const link = workflow.links.find((link) => link.id === linkId);
1275
+ const link = linksById.get(linkId);
1147
1276
  if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1148
- const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1277
+ const parentNode = nodesById.get(link.originId);
1149
1278
  if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
1150
1279
  return {
1151
1280
  node: parentNode,
@@ -1245,6 +1374,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1245
1374
  class_type: node.type
1246
1375
  };
1247
1376
  }
1377
+ for (const node of workflow.nodes) {
1378
+ const own = prompt[String(node.id)];
1379
+ if (own == null) continue;
1380
+ for (const ipt of node.inputs) {
1381
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1382
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1383
+ if (value !== void 0) own.inputs[ipt.name] = value;
1384
+ }
1385
+ }
1386
+ const missing = /* @__PURE__ */ new Map();
1387
+ for (const node of workflow.nodes) {
1388
+ const own = prompt[String(node.id)];
1389
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1390
+ if (own == null || nodeSchema == null) continue;
1391
+ for (const field of nodeSchema.inputs) {
1392
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1393
+ const kind = classifySchemaInput(field).kind;
1394
+ if (kind !== "slot" && kind !== "widget") continue;
1395
+ missing.set(String(node.id), {
1396
+ node,
1397
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1398
+ });
1399
+ break;
1400
+ }
1401
+ }
1402
+ if (missing.size > 0) {
1403
+ const consumers = /* @__PURE__ */ new Map();
1404
+ for (const [id, n] of Object.entries(prompt)) for (const value of Object.values(n.inputs)) if (Array.isArray(value) && typeof value[0] === "string") {
1405
+ const list = consumers.get(value[0]) ?? [];
1406
+ list.push(id);
1407
+ consumers.set(value[0], list);
1408
+ }
1409
+ const blocked = new Set(missing.keys());
1410
+ const queue = [...blocked];
1411
+ for (let head = 0; head < queue.length; head++) for (const next of consumers.get(queue[head] ?? "") ?? []) if (!blocked.has(next)) {
1412
+ blocked.add(next);
1413
+ queue.push(next);
1414
+ }
1415
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1416
+ const dropped = outputs.filter((id) => blocked.has(id));
1417
+ const first = missing.values().next().value;
1418
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1419
+ if (dropped.length > 0 || outputs.length === 0) console.warn(`🟡 [workflow] ComfyUI will skip output node(s) ${dropped.join(", ") || "(none in this graph)"}: ${[...missing.values()].map((m) => m.message).join("; ")}`);
1420
+ }
1248
1421
  return prompt;
1249
1422
  };
1250
1423
  //#endregion
@@ -1425,21 +1598,37 @@ var ComfyNode = class ComfyNode {
1425
1598
  _convertPromptExtToPrompt(promptExt) {
1426
1599
  const inputs = {};
1427
1600
  const _done = /* @__PURE__ */ new Set();
1428
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1601
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1429
1602
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1430
1603
  for (const i of this.$schema.inputs) {
1431
1604
  _done.add(i.nameInComfy);
1432
1605
  const kind = classifySchemaInput(i);
1433
- if (kind.kind === "dynamic-combo") {
1434
- this._writeDynamicCombo({
1435
- name: i.nameInComfy,
1436
- options: kind.options,
1437
- defaultKey: kind.defaultKey,
1438
- provided: promptExt.inputs,
1439
- out: inputs,
1440
- claimed: _comboBranchKeys
1441
- });
1442
- continue;
1606
+ switch (kind.kind) {
1607
+ case "dynamic-combo":
1608
+ this._writeDynamicCombo({
1609
+ name: i.nameInComfy,
1610
+ options: kind.options,
1611
+ defaultKey: kind.defaultKey,
1612
+ provided: promptExt.inputs,
1613
+ out: inputs,
1614
+ claimed: _comboBranchKeys
1615
+ });
1616
+ continue;
1617
+ case "dynamic-group":
1618
+ this._writeDynamicGroup({
1619
+ name: i.nameInComfy,
1620
+ fields: kind.fields,
1621
+ min: kind.min,
1622
+ max: kind.max,
1623
+ provided: promptExt.inputs,
1624
+ out: inputs,
1625
+ claimed: _comboBranchKeys
1626
+ });
1627
+ continue;
1628
+ case "widget":
1629
+ case "slot":
1630
+ case "dynamic-container": break;
1631
+ default:
1443
1632
  }
1444
1633
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1445
1634
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1478,6 +1667,42 @@ var ComfyNode = class ComfyNode {
1478
1667
  }) : this.serializeValue(dotted, given);
1479
1668
  }
1480
1669
  }
1670
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1671
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1672
+ * keys are already the rows: they pass through the rest loop untouched */
1673
+ _writeDynamicGroup(p) {
1674
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1675
+ const raw = p.provided[p.name];
1676
+ const prefix = `${p.name}.`;
1677
+ if (raw == null) {
1678
+ if (!Object.keys(p.provided).some((k) => k.startsWith(prefix)) && p.min > 0) this.graph.recordProblem(`🔴 "${p.name}" on ${where} needs at least ${p.min} row(s)`);
1679
+ return;
1680
+ }
1681
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1682
+ if (!Array.isArray(raw)) {
1683
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1684
+ return;
1685
+ }
1686
+ if (raw.length < p.min || raw.length > p.max) this.graph.recordProblem(`🔴 "${p.name}" on ${where} has ${raw.length} row(s), the host takes ${p.min} to ${p.max}`);
1687
+ raw.forEach((row, ix) => {
1688
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1689
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1690
+ return;
1691
+ }
1692
+ const given = new Map(Object.entries(row));
1693
+ for (const field of p.fields) {
1694
+ const dotted = `${p.name}.${ix}.${field.name}`;
1695
+ const value = given.get(field.name);
1696
+ p.out[dotted] = value == null ? defaultValueForWidget({
1697
+ type: typeof field.type === "string" ? field.type : "COMBO",
1698
+ opts: field.opts,
1699
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1700
+ }) : this.serializeValue(dotted, value);
1701
+ given.delete(field.name);
1702
+ }
1703
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1704
+ });
1705
+ }
1481
1706
  /** return the list of nodes piped into this node */
1482
1707
  _incomingNodes() {
1483
1708
  const incomingNodes = [];
@@ -1621,6 +1846,12 @@ var ComfyNode = class ComfyNode {
1621
1846
  const kind = classifySchemaInput(decl);
1622
1847
  const slotType = containerInstanceSlotType(decl.opts);
1623
1848
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1849
+ if (kind.kind === "dynamic-group") {
1850
+ const rest = name.slice(dot + 1);
1851
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1852
+ const field = kind.fields.find((f) => f.name === fieldName);
1853
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1854
+ }
1624
1855
  }
1625
1856
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1626
1857
  }
@@ -1704,44 +1935,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1704
1935
  const convertNodeToLiteGraphNode = (ctx, node) => {
1705
1936
  const inputs = [];
1706
1937
  const widgets_values = [];
1707
- const pushLinked = (name, type, link, shape) => {
1938
+ const pushLinked = (name, type, link, extra = {}) => {
1708
1939
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1709
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1710
- inputs.push(shape == null ? {
1940
+ const input = {
1711
1941
  name,
1712
1942
  type,
1713
- link: linkId
1714
- } : {
1943
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1944
+ };
1945
+ if (extra.shape != null) input.shape = extra.shape;
1946
+ if (extra.widget === true) input.widget = { name };
1947
+ inputs.push(input);
1948
+ };
1949
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1950
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1951
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1952
+ * never disagree on the run length */
1953
+ const pushWidgetRun = (kind, raw, opts) => {
1954
+ widgets_values.push(...kind.prefixValues, raw);
1955
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1956
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1957
+ };
1958
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1959
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1960
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1961
+ const writeInput = (p) => {
1962
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1963
+ switch (p.kind.kind) {
1964
+ case "widget":
1965
+ if (_isLink(p.value)) {
1966
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
1967
+ pushWidgetRun(p.kind, defaultValueForWidget({
1968
+ type: p.typeName,
1969
+ opts: p.opts
1970
+ }), p.opts);
1971
+ } else pushWidgetRun(p.kind, p.value, p.opts);
1972
+ return;
1973
+ case "slot":
1974
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
1975
+ else inputs.push({
1976
+ name: p.name,
1977
+ type: p.typeName,
1978
+ link: null
1979
+ });
1980
+ return;
1981
+ case "dynamic-combo": {
1982
+ const kind = p.kind;
1983
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
1984
+ const option = kind.options.find((o) => o.key === key);
1985
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
1986
+ widgets_values.push(key);
1987
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
1988
+ return;
1989
+ }
1990
+ case "dynamic-container": {
1991
+ const type = containerInstanceSlotType(p.opts) ?? "*";
1992
+ for (const instance of p.kind.instanceNames) {
1993
+ const name = `${p.name}.${instance}`;
1994
+ const value = node.json.inputs[name];
1995
+ if (value == null) continue;
1996
+ const raw = node.serializeValue(name, value);
1997
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
1998
+ pushLinked(name, type, raw, { shape: 7 });
1999
+ }
2000
+ return;
2001
+ }
2002
+ case "dynamic-group": {
2003
+ const prefix = `${p.name}.`;
2004
+ let rows = 0;
2005
+ for (const key of Object.keys(node.json.inputs)) {
2006
+ if (!key.startsWith(prefix)) continue;
2007
+ const row = Number(key.slice(prefix.length).split(".")[0]);
2008
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
2009
+ }
2010
+ widgets_values.push(rows);
2011
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
2012
+ return;
2013
+ }
2014
+ default: p.kind;
2015
+ }
2016
+ };
2017
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
2018
+ * value is the widget's schema default rather than serializeValue's */
2019
+ const writeSub = (name, sub) => {
2020
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
2021
+ const raw = node.json.inputs[name];
2022
+ writeInput({
1715
2023
  name,
1716
- type,
1717
- shape,
1718
- link: linkId
2024
+ kind: classifyWidgetInput({
2025
+ name,
2026
+ type: sub.type,
2027
+ opts: sub.opts
2028
+ }),
2029
+ typeName,
2030
+ opts: sub.opts,
2031
+ value: raw === void 0 ? defaultValueForWidget({
2032
+ type: typeName,
2033
+ opts: sub.opts
2034
+ }) : raw
1719
2035
  });
1720
2036
  };
1721
2037
  for (const ipt of node.$schema.inputs) {
1722
2038
  const kind = classifySchemaInput(ipt);
1723
- if (kind.kind === "dynamic-container") {
1724
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1725
- for (const instance of kind.instanceNames) {
1726
- const name = `${ipt.nameInComfy}.${instance}`;
1727
- const value = node.json.inputs[name];
1728
- if (value == null) continue;
1729
- const raw = node.serializeValue(name, value);
1730
- if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${node.$schema.nameInComfy}#${node.uid} "${name}" holds a literal; an autogrow instance is a link slot in the editor`);
1731
- pushLinked(name, type, raw, 7);
1732
- }
1733
- continue;
1734
- }
1735
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1736
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1737
- else if (kind.kind === "widget") {
1738
- widgets_values.push(...kind.prefixValues, raw);
1739
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1740
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1741
- } else inputs.push({
2039
+ const raw = node.json.inputs[ipt.nameInComfy];
2040
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
2041
+ writeInput({
1742
2042
  name: ipt.nameInComfy,
1743
- type: ipt.typeName,
1744
- link: null
2043
+ kind,
2044
+ typeName: ipt.typeName,
2045
+ opts: ipt.opts,
2046
+ value
1745
2047
  });
1746
2048
  }
1747
2049
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1927,11 +2229,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1927
2229
  return resultSuccess(txt_chunks);
1928
2230
  };
1929
2231
  //#endregion
1930
- //#region src/utils/exhaust.ts
1931
- function exhaust(x) {
1932
- return x;
1933
- }
1934
- //#endregion
1935
2232
  //#region src/utils/sha1.ts
1936
2233
  function sha1Hex(data) {
1937
2234
  const ml = data.length;
@@ -2066,16 +2363,17 @@ const types$1 = scope({
2066
2363
  },
2067
2364
  _WsMsgExecutedData: {
2068
2365
  node: "ComfyNodeID",
2069
- output: {
2070
- "previews?": [{ filepath: "string" }, "[]"],
2071
- "images?": "ComfyImageInfo[]",
2072
- "audio?": "ComfyImageInfo[]",
2073
- "video?": "ComfyImageInfo[]",
2074
- "gifs?": "ComfyImageInfo[]",
2075
- "text?": "unknown[]"
2076
- },
2366
+ output: "_WsMsgExecutedOutput | null",
2077
2367
  prompt_id: "PromptID"
2078
2368
  },
2369
+ _WsMsgExecutedOutput: {
2370
+ "previews?": [{ filepath: "string" }, "[]"],
2371
+ "images?": "ComfyImageInfo[]",
2372
+ "audio?": "ComfyImageInfo[]",
2373
+ "video?": "ComfyImageInfo[]",
2374
+ "gifs?": "ComfyImageInfo[]",
2375
+ "text?": "unknown[]"
2376
+ },
2079
2377
  WsMsgExecuted: {
2080
2378
  type: "'executed'",
2081
2379
  data: "_WsMsgExecutedData"
@@ -2097,12 +2395,22 @@ const types$1 = scope({
2097
2395
  exception_type: "string",
2098
2396
  traceback: "string[]",
2099
2397
  current_inputs: "Record<string, unknown>",
2100
- current_outputs: "Record<string, unknown>"
2398
+ current_outputs: "ComfyNodeID[]"
2101
2399
  },
2102
2400
  WsMsgExecutionError: {
2103
2401
  type: "'execution_error'",
2104
2402
  data: "_WsMsgExecutionErrorData"
2105
2403
  },
2404
+ _WsMsgExecutionInterruptedData: {
2405
+ prompt_id: "PromptID",
2406
+ node_id: "ComfyNodeID",
2407
+ node_type: "string",
2408
+ executed: "ComfyNodeID[]"
2409
+ },
2410
+ WsMsgExecutionInterrupted: {
2411
+ type: "'execution_interrupted'",
2412
+ data: "_WsMsgExecutionInterruptedData"
2413
+ },
2106
2414
  WSMsgManagerFeedbackData: { data: "string" },
2107
2415
  WSMsgManagerFeedback: {
2108
2416
  type: "'manager-terminal-feedback'",
@@ -2132,11 +2440,51 @@ const types$1 = scope({
2132
2440
  type: "'progress_state'",
2133
2441
  data: "_WsMsgProgressStateData"
2134
2442
  },
2135
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2443
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2136
2444
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2137
2445
  }).export();
2138
2446
  const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2139
2447
  const WsMsg_ark = types$1.WsMsg;
2448
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2449
+ const ROUTED_WS_EVENT_TYPES = [
2450
+ "status",
2451
+ "manager-terminal-feedback",
2452
+ "logs",
2453
+ "execution_start",
2454
+ "execution_cached",
2455
+ "executing",
2456
+ "progress",
2457
+ "progress_state",
2458
+ "executed",
2459
+ "execution_error",
2460
+ "execution_interrupted",
2461
+ "execution_success"
2462
+ ];
2463
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2464
+ * before validation, never logged (architecture.md, ws events) */
2465
+ const IGNORED_WS_EVENT_TYPES = [
2466
+ "feature_flags",
2467
+ "agent_status",
2468
+ "asset_export",
2469
+ "assets.seed.started",
2470
+ "assets.seed.progress",
2471
+ "assets.seed.fast_complete",
2472
+ "assets.seed.enrich_complete",
2473
+ "assets.seed.completed",
2474
+ "assets.seed.cancelled",
2475
+ "assets.seed.error",
2476
+ "assets.seed.paused",
2477
+ "assets.seed.resumed",
2478
+ "cm-queue-status",
2479
+ "cm-api-try-install-customnode",
2480
+ "cm-task-started",
2481
+ "cm-task-completed",
2482
+ "crystools.monitor"
2483
+ ];
2484
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2485
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2486
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2487
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2140
2488
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2141
2489
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2142
2490
  //#endregion
@@ -2426,6 +2774,10 @@ var ComfyExecution = class {
2426
2774
  else if (msg.type === "progress") graph.onProgress(msg);
2427
2775
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2428
2776
  else if (msg.type === "execution_error") return void this.onError(msg);
2777
+ else if (msg.type === "execution_interrupted") return void this._finish({
2778
+ status: "Failure",
2779
+ error: msg
2780
+ });
2429
2781
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2430
2782
  else {
2431
2783
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3339,6 +3691,15 @@ const dynamicComboUnion = (p) => {
3339
3691
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3340
3692
  }).join(" | ")})`;
3341
3693
  };
3694
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3695
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3696
+ const dynamicGroupRow = (fields) => {
3697
+ return `{ ${fields.map((e) => {
3698
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3699
+ const optional = !e.required || opts?.["default"] !== void 0;
3700
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3701
+ }).join("; ")} }`;
3702
+ };
3342
3703
  /**
3343
3704
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3344
3705
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3387,6 +3748,8 @@ function codegenSDK(opts) {
3387
3748
  b.deindent();
3388
3749
  p(`// #endregion`);
3389
3750
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3751
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3752
+ const groupRows = [];
3390
3753
  p(`interface IN {`);
3391
3754
  b.indent();
3392
3755
  for (const n of nodes) {
@@ -3394,23 +3757,37 @@ function codegenSDK(opts) {
3394
3757
  const comboSuffixes = [];
3395
3758
  for (const i of n.inputs) {
3396
3759
  const kind = classifySchemaInput(i);
3397
- if (kind.kind === "dynamic-container") {
3398
- const instType = containerInstanceSlotType(i.opts);
3399
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3400
- const opt = ix >= kind.requiredCount ? "?" : "";
3401
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3402
- });
3403
- continue;
3404
- }
3405
- if (kind.kind === "dynamic-combo") {
3406
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3407
- comboSuffixes.push(dynamicComboUnion({
3408
- name: i.nameInComfy,
3409
- nameEscaped: i.nameInComfyEscaped,
3410
- options: kind.options,
3411
- keyOptional: optsDyn?.default !== void 0 || !i.required
3412
- }));
3413
- continue;
3760
+ switch (kind.kind) {
3761
+ case "dynamic-container": {
3762
+ const instType = containerInstanceSlotType(i.opts);
3763
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3764
+ const opt = ix >= kind.requiredCount ? "?" : "";
3765
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3766
+ });
3767
+ continue;
3768
+ }
3769
+ case "dynamic-combo": {
3770
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3771
+ comboSuffixes.push(dynamicComboUnion({
3772
+ name: i.nameInComfy,
3773
+ nameEscaped: i.nameInComfyEscaped,
3774
+ options: kind.options,
3775
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3776
+ }));
3777
+ continue;
3778
+ }
3779
+ case "dynamic-group": {
3780
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3781
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3782
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3783
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3784
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3785
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3786
+ continue;
3787
+ }
3788
+ case "widget":
3789
+ case "slot": break;
3790
+ default:
3414
3791
  }
3415
3792
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3416
3793
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3433,6 +3810,15 @@ function codegenSDK(opts) {
3433
3810
  b.deindent();
3434
3811
  p("}");
3435
3812
  p("");
3813
+ if (groupRows.length > 0) {
3814
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3815
+ p(`interface GroupRow {`);
3816
+ b.indent();
3817
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3818
+ b.deindent();
3819
+ p("}");
3820
+ p("");
3821
+ }
3436
3822
  p(`interface OUT {`);
3437
3823
  b.indent();
3438
3824
  for (const n of nodes) {
@@ -3745,9 +4131,13 @@ var ComfySchema = class {
3745
4131
  if (widgetKind?.kind === "dynamic-combo") {
3746
4132
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3747
4133
  }
4134
+ if (widgetKind?.kind === "dynamic-group") {
4135
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4136
+ }
4137
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3748
4138
  node.inputs.push({
3749
4139
  slotName: inputSlotName,
3750
- required: ipt.required && !isAutogrowContainer,
4140
+ required,
3751
4141
  nameInComfy: inputNameInComfy,
3752
4142
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3753
4143
  typeName: inputTypeName,
@@ -3823,7 +4213,12 @@ const types = scope({
3823
4213
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3824
4214
  ComfyInputSpecAlt2: ["ComfyInputType"],
3825
4215
  ComfyInputSpecAlt3: type([type.null]),
3826
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4216
+ ComfyInputSpecAlt4: [
4217
+ "ComfyInputType",
4218
+ "ComfyInputOpts",
4219
+ "unknown"
4220
+ ],
4221
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3827
4222
  ComfyInputType: `string | ComfyEnumDef`,
3828
4223
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3829
4224
  ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
@@ -3889,10 +4284,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3889
4284
  return result;
3890
4285
  }
3891
4286
  //#endregion
4287
+ //#region src/manager/installedView.ts
4288
+ /**
4289
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4290
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4291
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4292
+ */
4293
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4294
+ const InstalledPacks_ark = type.Record("string", type({
4295
+ "cnr_id?": "string | null",
4296
+ "aux_id?": "string | null",
4297
+ enabled: "boolean"
4298
+ }));
4299
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4300
+ const PackMappings_ark = type.Record("string", type(["string[]", { "title_aux?": "string" }]));
4301
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4302
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4303
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4304
+ const attributePacks = (installed, mappings) => {
4305
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4306
+ return Object.entries(installed).map(([dir, p]) => {
4307
+ const aux = p.aux_id ?? null;
4308
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4309
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4310
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4311
+ return {
4312
+ enabled: p.enabled,
4313
+ repo,
4314
+ title,
4315
+ id: cnr ?? aux ?? dir
4316
+ };
4317
+ });
4318
+ };
4319
+ /** is this mirror row among the attributed packs, enabled? */
4320
+ const packIsInstalled = (packs, plugin) => {
4321
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4322
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4323
+ };
4324
+ const buildPluginView = (p) => {
4325
+ const packs = attributePacks(p.installed, p.mappings);
4326
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4327
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4328
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4329
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4330
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4331
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4332
+ const custom_nodes = [];
4333
+ for (const plugin of plugins) {
4334
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4335
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4336
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4337
+ title: plugin.title,
4338
+ installed: "True"
4339
+ });
4340
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4341
+ else custom_nodes.push({
4342
+ title: plugin.title,
4343
+ installed: "False"
4344
+ });
4345
+ }
4346
+ return {
4347
+ list: {
4348
+ chanel: "default",
4349
+ custom_nodes
4350
+ },
4351
+ unattributed: unattributed.map((x) => x.id)
4352
+ };
4353
+ };
4354
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4355
+ const DEFAULT_FOLDER_BY_TYPE = {
4356
+ checkpoints: "checkpoints",
4357
+ checkpoint: "checkpoints",
4358
+ unclip: "checkpoints",
4359
+ text_encoders: "text_encoders",
4360
+ clip: "text_encoders",
4361
+ vae: "vae",
4362
+ lora: "loras",
4363
+ "t2i-adapter": "controlnet",
4364
+ "t2i-style": "controlnet",
4365
+ controlnet: "controlnet",
4366
+ clip_vision: "clip_vision",
4367
+ gligen: "gligen",
4368
+ upscale: "upscale_models",
4369
+ embedding: "embeddings",
4370
+ embeddings: "embeddings",
4371
+ unet: "diffusion_models",
4372
+ diffusion_model: "diffusion_models"
4373
+ };
4374
+ /** what core `get_filename_list` lists in the standard folders */
4375
+ const LISTED_EXTENSIONS = [
4376
+ ".ckpt",
4377
+ ".pt",
4378
+ ".pt2",
4379
+ ".bin",
4380
+ ".pth",
4381
+ ".safetensors",
4382
+ ".pkl",
4383
+ ".sft"
4384
+ ];
4385
+ /**
4386
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4387
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4388
+ */
4389
+ const modelLocation = (m) => {
4390
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4391
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4392
+ if (m.save_path === "default") {
4393
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4394
+ return folder == null ? null : {
4395
+ folder,
4396
+ files: [m.filename]
4397
+ };
4398
+ }
4399
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4400
+ const folder = parts[0];
4401
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4402
+ const sub = [...parts.slice(1), m.filename].join("/");
4403
+ return {
4404
+ folder,
4405
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4406
+ };
4407
+ };
4408
+ const buildModelView = (p) => {
4409
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4410
+ const statusOf = (m) => {
4411
+ const at = modelLocation(m);
4412
+ const files = at == null ? null : listed.get(at.folder);
4413
+ if (at == null || files == null) return null;
4414
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4415
+ };
4416
+ const byName = /* @__PURE__ */ new Map();
4417
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4418
+ const models = [];
4419
+ for (const rows of byName.values()) {
4420
+ const statuses = new Set(rows.map(statusOf));
4421
+ const first = rows[0];
4422
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4423
+ if (first == null || installed == null) continue;
4424
+ models.push({
4425
+ name: first.name,
4426
+ installed,
4427
+ filename: first.filename,
4428
+ save_path: first.save_path,
4429
+ base: first.base
4430
+ });
4431
+ }
4432
+ return { models };
4433
+ };
4434
+ /** the folders the views need listed */
4435
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4436
+ //#endregion
3892
4437
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3893
4438
  const ComfyManagerAPIModelList_ark = type({ models: type({
3894
4439
  name: type.string.as(),
3895
- installed: `'False' | 'True' | 'Update'`
4440
+ installed: `'False' | 'True' | 'Update'`,
4441
+ "filename?": "string",
4442
+ "save_path?": "string",
4443
+ "base?": "string"
3896
4444
  }).array() });
3897
4445
  //#endregion
3898
4446
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3903,28 +4451,160 @@ const ComfyManagerAPIPluginList_ark = type({
3903
4451
  }).array(),
3904
4452
  chanel: "string"
3905
4453
  });
4454
+ const ComfyManagerAPIPack_ark = type({
4455
+ title: type.string.as(),
4456
+ "id?": "string",
4457
+ "files?": "string[]",
4458
+ "repository?": "string",
4459
+ "version?": "string",
4460
+ "state?": "string",
4461
+ "update-state?": "string"
4462
+ });
4463
+ const ComfyManagerAPIPackList_ark = type({
4464
+ channel: "string",
4465
+ node_packs: type.Record("string", ComfyManagerAPIPack_ark)
4466
+ });
3906
4467
  //#endregion
3907
4468
  //#region src/host/ComfyManager.ts
4469
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4470
+ const MANAGER_TIMING = {
4471
+ pollMs: 1e3,
4472
+ installTimeoutMs: 60 * 6e4,
4473
+ pollGraceMs: 12e4
4474
+ };
4475
+ /** an install the host refused or reported failed: ends the wait at once */
4476
+ var InstallFailed = class extends Error {};
4477
+ /** we lost sight of the task: the outcome is not known */
4478
+ var OutcomeUnknown = class extends Error {};
4479
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4480
+ const NOT_SERVED = {
4481
+ v3: [
4482
+ "/manager/queue/batch",
4483
+ "/manager/queue/task",
4484
+ "/manager/queue/history"
4485
+ ],
4486
+ "v4-legacy-ui": [
4487
+ "/manager/queue/install",
4488
+ "/manager/queue/task",
4489
+ "/manager/queue/history",
4490
+ "/manager/terminal"
4491
+ ],
4492
+ v4: [
4493
+ "/customnode/getlist",
4494
+ "/externalmodel/getlist",
4495
+ "/manager/queue/install",
4496
+ "/manager/queue/batch",
4497
+ "/manager/terminal"
4498
+ ]
4499
+ };
4500
+ const QueueStatus_ark = type({
4501
+ is_processing: "boolean",
4502
+ "pending_count?": "number",
4503
+ "total_count?": "number",
4504
+ "done_count?": "number"
4505
+ });
4506
+ const TaskHistory_ark = type({ history: {
4507
+ "status?": {
4508
+ status_str: "string",
4509
+ "messages?": "string[]"
4510
+ },
4511
+ "result?": "string"
4512
+ } });
4513
+ const ModelFolders_ark = type("string[]");
4514
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3908
4515
  var ComfyManager = class {
3909
- constructor(host) {
4516
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3910
4517
  this.host = host;
3911
- this.fetchPluginsAndModels = async () => {
3912
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3913
- this.pluginList = _pluginList;
3914
- this.modelList = _modelList;
4518
+ this.timing = timing;
4519
+ this.mirror = mirror;
4520
+ this.clientId = `comfy-ts-${nanoid(8)}`;
4521
+ this._api = null;
4522
+ this.api = () => {
4523
+ if (this._api == null) {
4524
+ const probe = this.probeApi();
4525
+ this._api = probe;
4526
+ probe.catch(() => {
4527
+ if (this._api === probe) this._api = null;
4528
+ });
4529
+ }
4530
+ return this._api;
4531
+ };
4532
+ this.probeApi = async () => {
4533
+ const v4 = await this.host.fetch("/v2/manager/version");
4534
+ if (v4.ok) {
4535
+ const version = (await v4.text()).trim();
4536
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4537
+ if (!ui.ok) {
4538
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4539
+ return {
4540
+ generation: "v4",
4541
+ version
4542
+ };
4543
+ }
4544
+ const flag = await ui.json();
4545
+ return {
4546
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4547
+ version
4548
+ };
4549
+ }
4550
+ const v3 = await this.host.fetch("/manager/version");
4551
+ if (v3.ok) return {
4552
+ generation: "v3",
4553
+ version: (await v3.text()).trim()
4554
+ };
4555
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4556
+ };
4557
+ this.route = (api, route, query = "") => {
4558
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4559
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4560
+ };
4561
+ this.strategy = (api) => {
4562
+ switch (api.generation) {
4563
+ case "v3": return {
4564
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4565
+ fetchModels: () => this.listedModels(api),
4566
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4567
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4568
+ };
4569
+ case "v4-legacy-ui": return {
4570
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4571
+ fetchModels: () => this.listedModels(api),
4572
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4573
+ const route = this.route(api, "/manager/queue/batch");
4574
+ const res = await this.post(route, { install: [body] });
4575
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4576
+ if (Array.isArray(failed) && failed.length > 0) throw new Error(`POST ${route} refused ${JSON.stringify(failed)}: the batch reply carries ids only, the ComfyUI console says why (a 4.x security policy refusal is the usual one)`);
4577
+ }),
4578
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4579
+ };
4580
+ case "v4": return {
4581
+ fetchPlugins: () => this.installedPluginView(api),
4582
+ fetchModels: () => this.installedModelView(),
4583
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4584
+ settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId)
4585
+ };
4586
+ }
3915
4587
  };
3916
- this.configureLogging = (mi) => {
3917
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4588
+ this.configureLogging = async (mi) => {
4589
+ const api = await this.api();
4590
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4591
+ const response = await this.host.fetch(route);
4592
+ const text = await response.text();
4593
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4594
+ return text;
3918
4595
  };
3919
4596
  this.getModelInfoFinalFilePath = (mi) => {
3920
4597
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3921
4598
  };
3922
4599
  this.restartComfyUI = async () => {
4600
+ const api = await this.api();
4601
+ this._api = null;
4602
+ const route = this.route(api, "/manager/reboot");
3923
4603
  const refusals = [];
3924
4604
  for (const method of ["POST", "GET"]) {
3925
4605
  let response;
3926
4606
  try {
3927
- response = await this.host.fetch("/manager/reboot", { method });
4607
+ response = await this.host.fetch(route, { method });
3928
4608
  } catch {
3929
4609
  return;
3930
4610
  }
@@ -3932,31 +4612,44 @@ var ComfyManager = class {
3932
4612
  refusals.push(`${method} → ${response.status}`);
3933
4613
  if (response.status !== 404) break;
3934
4614
  }
3935
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4615
+ throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${route}: ${refusals.join(", ")}) — ComfyUI-Manager ${api.version} is not there any more, or its reboot route moved again`);
4616
+ };
4617
+ this.fetchPluginsAndModels = async () => {
4618
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4619
+ this.pluginList = _pluginList;
4620
+ this.modelList = _modelList;
3936
4621
  };
3937
4622
  this.modelList = null;
3938
- this.fetchModels = () => {
3939
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4623
+ this.fetchModels = async () => {
4624
+ return this.strategy(await this.api()).fetchModels();
3940
4625
  };
3941
4626
  this.fetchLogs = () => {
3942
- return this.fetchGetJSON("/internal/logs");
4627
+ return this.getJSON("/internal/logs");
3943
4628
  };
3944
4629
  this.isModelInstalled = (name) => {
3945
4630
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3946
4631
  };
3947
4632
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3948
- this.installModel = async (model) => {
4633
+ this.installModel = async (model) => await this.installModelOutcome(model) === "installed";
4634
+ this.installModelOutcome = async (model) => {
4635
+ this.modelsBeeingInstalled.add(model.name);
3949
4636
  try {
3950
- this.modelsBeeingInstalled.add(model.name);
3951
- await this.fetchPost("/model/install", model);
3952
- this.modelsBeeingInstalled.delete(model.name);
3953
- logSuccess("Model installed");
3954
- return true;
3955
- } catch (exception) {
3956
- console.error(`Install failed: / ${exception}`);
3957
- logError("Model Installation Failed");
4637
+ return await this.runInstall(`model "${model.name}"`, {
4638
+ enqueue: async (api, uiId) => {
4639
+ const body = {
4640
+ ...model,
4641
+ ui_id: uiId,
4642
+ client_id: this.clientId
4643
+ };
4644
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4645
+ },
4646
+ landed: async (s) => {
4647
+ const row = (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base);
4648
+ return row == null ? null : row.installed === "True";
4649
+ }
4650
+ });
4651
+ } finally {
3958
4652
  this.modelsBeeingInstalled.delete(model.name);
3959
- return false;
3960
4653
  }
3961
4654
  };
3962
4655
  this.getModelStatus = (modelName) => {
@@ -3986,48 +4679,239 @@ var ComfyManager = class {
3986
4679
  return "error";
3987
4680
  })();
3988
4681
  };
4682
+ this.requirementStatus = (req) => {
4683
+ const mirror = this.mirror();
4684
+ const packs = (() => {
4685
+ if (req.type === "customNodesByNodeKey") return mirror.plugins_byNodeKey.get(req.nodeName) ?? [];
4686
+ if (req.type === "customNodesByTitle") return [mirror.plugins_byTitle.get(req.title)].filter((x) => x != null);
4687
+ if (req.type === "customNodesByURI") return [mirror.plugins_byFile.get(req.uri)].filter((x) => x != null);
4688
+ return null;
4689
+ })();
4690
+ if (packs == null) return req.type === "modelInManager" ? this.getModelStatus(req.modelName) : null;
4691
+ if (packs.length === 0) return req.type === "customNodesByNodeKey" ? "unknown" : null;
4692
+ const statuses = packs.map((x) => this.getPluginStatus(x.title));
4693
+ if (statuses.some((x) => x === "installed" || x === "update-available")) return "installed";
4694
+ return statuses.every((x) => x === "not-installed") ? "not-installed" : "unknown";
4695
+ };
4696
+ this.checkRequirements = (requirements) => {
4697
+ const out = {
4698
+ missing: [],
4699
+ undecided: []
4700
+ };
4701
+ for (const req of requirements) {
4702
+ if (req.optional) continue;
4703
+ const status = this.requirementStatus(req);
4704
+ if (status === "not-installed") out.missing.push(req);
4705
+ else if (status === "unknown" || status === "error") out.undecided.push(req);
4706
+ }
4707
+ return out;
4708
+ };
4709
+ this.matchRequirements = (requirements) => {
4710
+ const check = this.checkRequirements(requirements);
4711
+ if (check.undecided.length > 0) logError(`requirements the host lists cannot decide, read as present: ${check.undecided.map((r) => JSON.stringify(r)).join(", ")}` + (this.pluginList == null || this.modelList == null ? " (the lists are not fetched: call fetchPluginsAndModels)" : ""));
4712
+ return check.missing.length === 0;
4713
+ };
3989
4714
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
4715
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4716
+ };
4717
+ this.installPlugin = async (plugin) => await this.installPluginOutcome(plugin) === "installed";
4718
+ this.installPluginOutcome = async (plugin) => {
4719
+ return this.runInstall(`plugin "${plugin.title}"`, {
4720
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4721
+ landed: async (_s, api) => {
4722
+ const data = await this.installedData(api);
4723
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4724
+ }
4725
+ });
4726
+ };
4727
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4728
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4729
+ if (!("node_packs" in raw)) return raw;
4730
+ const titleByRepo = /* @__PURE__ */ new Map();
4731
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4732
+ return {
4733
+ chanel: raw.channel,
4734
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4735
+ const repo = p.files?.[0];
4736
+ return {
4737
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4738
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4739
+ };
4740
+ })
4741
+ };
4742
+ };
4743
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4744
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4745
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4746
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4747
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4748
+ };
4749
+ this.listedModels = async (api) => {
4750
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4751
+ };
4752
+ this.installedData = async (api) => {
4753
+ const [installed, mappings] = await Promise.all([this.getValid(this.route(api, "/customnode/installed"), InstalledPacks_ark), this.getValid(this.route(api, "/customnode/getmappings", "?mode=cache"), PackMappings_ark)]);
4754
+ return {
4755
+ installed,
4756
+ mappings
4757
+ };
4758
+ };
4759
+ this.installedPluginView = async (api) => {
4760
+ const view = buildPluginView({
4761
+ mirror: this.mirror(),
4762
+ ...await this.installedData(api)
4763
+ });
4764
+ if (view.unattributed.length > 0) logError(`ComfyUI-Manager ${api.version} reports installed packs no mirror row can be tied to (${view.unattributed.join(", ")}): the mirror rows they could be read unknown`);
4765
+ return view.list;
4766
+ };
4767
+ this.installedModelView = async () => {
4768
+ const models = this.mirror().modelRows;
4769
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4770
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4771
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4772
+ return buildModelView({
4773
+ models,
4774
+ files: new Map(lists)
4775
+ });
4776
+ };
4777
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4778
+ const url = plugin.files[0] ?? plugin.reference;
4779
+ const list = await this.fetchPluginWire(api, "cache", true);
4780
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4781
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4782
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4783
+ const [key, row] = found;
4784
+ await send({
4785
+ ...row,
4786
+ id: row.id ?? key,
4787
+ channel: list.channel,
4788
+ mode: "cache",
4789
+ ui_id: uiId,
4790
+ skip_post_install: false
4791
+ });
4792
+ };
4793
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4794
+ const url = plugin.files[0] ?? plugin.reference;
4795
+ const id = repoPath(url).split("/").pop() ?? url;
4796
+ const params = {
4797
+ id,
4798
+ version: "nightly",
4799
+ selected_version: "nightly",
4800
+ repository: url,
4801
+ mode: "cache",
4802
+ channel: "default"
4803
+ };
4804
+ await this.post(this.route(api, "/manager/queue/task"), {
4805
+ ui_id: uiId,
4806
+ client_id: this.clientId,
4807
+ kind: "install",
4808
+ params
4809
+ });
4810
+ return id;
4811
+ };
4812
+ this.settleByHistory = async (api, what, uiId, landed, sentId) => {
4813
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4814
+ const readEntry = async () => (await this.getValid(route, TaskHistory_ark)).history.status ?? null;
4815
+ const entry = await this.waitFor(what, async () => {
4816
+ const status = await readEntry();
4817
+ if (status != null) return status;
4818
+ if (await this.restartIdleQueue(api) !== "drained") return null;
4819
+ const late = await readEntry();
4820
+ if (late != null) return late;
4821
+ throw new InstallFailed("the task left the queue with no result (a queue/reset from the Manager UI or another client removes it)");
4822
+ });
4823
+ if (entry.status_str === "success" || entry.status_str === "skip") {
4824
+ if (await this.endState(landed) !== false) return;
4825
+ throw new InstallFailed(sentId != null ? `the Manager reported success, but this pack does not read installed: another pack holds the id "${sentId}" it installs by` : "the Manager reported success, but it does not read installed afterwards");
4826
+ }
4827
+ const messages = entry.messages ?? [];
4828
+ const gate = messages.length === 1 && messages[0] === "failed" ? ": refused by its security policy, which allows installs only with security_level normal or below AND either ComfyUI listening on localhost or network_mode personal_cloud (the ComfyUI console names the rule)" : "";
4829
+ throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4830
+ };
4831
+ this.restartIdleQueue = async (api) => {
4832
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4833
+ if (status.is_processing) return "running";
4834
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4835
+ await this.post(this.route(api, "/manager/queue/start"));
4836
+ return "restarted";
4837
+ };
4838
+ this.settleByDrain = async (api, what, landed) => {
4839
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4840
+ const state = await this.endState(landed);
4841
+ if (state === true) return;
4842
+ if (state === null) throw new OutcomeUnknown("the queue drained, but the lists cannot say whether it is installed");
4843
+ throw new InstallFailed(`the Manager queue drained but it is not installed; ComfyUI-Manager ${api.version} reports why only over its websocket (cm-queue-status) and in the ComfyUI console`);
4844
+ };
4845
+ this.endState = async (landed) => {
3990
4846
  try {
3991
- const skip_update = skipUpdate ? "&skip_update=true" : "";
3992
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4847
+ return await landed();
3993
4848
  } catch (exception) {
3994
- console.error(`node list retrieval failed: ${exception}`);
3995
- logError("node list retrieveal failed");
3996
- throw exception;
4849
+ throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`);
3997
4850
  }
3998
4851
  };
3999
- this.installPlugin = async (model) => {
4852
+ this.runInstall = async (what, p) => {
4853
+ const host = this.host.getServerHostHTTP();
4000
4854
  try {
4001
- await this.fetchPost("/customnode/install", model);
4002
- console.log("✅ Custom Node installed");
4003
- logSuccess("Custom Node installed");
4004
- return true;
4855
+ const api = await this.api();
4856
+ const s = this.strategy(api);
4857
+ const uiId = nanoid();
4858
+ const sentId = await p.enqueue(api, uiId);
4859
+ await this.post(this.route(api, "/manager/queue/start"));
4860
+ await s.settle(what, uiId, () => p.landed(s, api), sentId);
4861
+ logSuccess(`${what} installed`);
4862
+ return "installed";
4005
4863
  } catch (exception) {
4006
- console.error(`Install failed: / ${exception}`);
4007
- logError("Custom Node Installation Failed");
4008
- return false;
4864
+ if (exception instanceof OutcomeUnknown) {
4865
+ logError(`${what}: OUTCOME UNKNOWN on ${host}: ${exception.message}. The Manager may still be installing it: refetch the list (fetchModels / fetchPlugins) and read its status before installing again, a blind retry queues a second download`);
4866
+ return "unknown";
4867
+ }
4868
+ logError(`${what}: install failed on ${host}: ${errorText(exception)}`);
4869
+ return "failed";
4870
+ }
4871
+ };
4872
+ this.waitFor = async (what, check) => {
4873
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4874
+ let lastAnswer = Date.now();
4875
+ for (;;) {
4876
+ try {
4877
+ const value = await check();
4878
+ lastAnswer = Date.now();
4879
+ if (value != null) return value;
4880
+ } catch (exception) {
4881
+ if (exception instanceof InstallFailed) throw exception;
4882
+ if (Date.now() - lastAnswer >= this.timing.pollGraceMs) throw new OutcomeUnknown(`the host gave no answer for ${this.timing.pollGraceMs} ms (manager.timing.pollGraceMs), last: ${errorText(exception)}`);
4883
+ logError(`${what}: poll failed, still waiting: ${errorText(exception)}`);
4884
+ }
4885
+ if (Date.now() >= deadline) throw new OutcomeUnknown(`still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4886
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4009
4887
  }
4010
4888
  };
4011
- this.fetchPost = async (endpoint, body, validator) => {
4012
- const response = await this.host.fetch(endpoint, {
4889
+ this.post = async (route, body) => {
4890
+ const response = await this.host.fetch(route, {
4013
4891
  method: "POST",
4014
4892
  headers: { "Content-Type": "application/json" },
4015
- body: JSON.stringify(body)
4893
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4016
4894
  });
4017
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4018
- const status = await response.json();
4019
- if (validator) return softValidate(validator, status);
4020
- return status;
4021
- };
4022
- this.fetchGetJSON = async (endpoint, validator) => {
4023
- const response = await this.host.fetch(endpoint);
4024
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4895
+ const text = await response.text();
4896
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4897
+ if (text === "") return null;
4898
+ try {
4899
+ return JSON.parse(text);
4900
+ } catch {
4901
+ return text;
4902
+ }
4903
+ };
4904
+ this.getJSON = async (route, validator) => {
4905
+ const response = await this.host.fetch(route);
4906
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4025
4907
  const jsonResult = await response.json();
4026
4908
  if (validator) return softValidate(validator, jsonResult);
4027
4909
  return jsonResult;
4028
4910
  };
4029
- this.fetchGetText = async (endopint) => {
4030
- return await (await this.host.fetch(endopint)).text();
4911
+ this.getValid = async (route, schema) => {
4912
+ const res = schema(await this.getJSON(route));
4913
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4914
+ return res;
4031
4915
  };
4032
4916
  }
4033
4917
  get registry() {
@@ -5891,26 +6775,8 @@ var ComfyHost = class {
5891
6775
  constructor(data) {
5892
6776
  this.data = data;
5893
6777
  this.uploader = new ComfyUploader(this);
5894
- this.matchRequirements = (requirements) => {
5895
- const repo = comfyts.registry;
5896
- for (const req of requirements) {
5897
- if (req.optional) continue;
5898
- if (req.type === "customNodesByNodeKey") {
5899
- if (!(repo.plugins_byNodeKey.get(req.nodeName) ?? []).find((i) => this.manager.isPluginInstalled(i.title))) return false;
5900
- } else if (req.type === "customNodesByTitle") {
5901
- const plugin = repo.plugins_byTitle.get(req.title);
5902
- if (plugin == null) continue;
5903
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5904
- } else if (req.type === "customNodesByURI") {
5905
- const plugin = repo.plugins_byFile.get(req.uri);
5906
- if (plugin == null) continue;
5907
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5908
- } else if (req.type === "modelInManager") {
5909
- if (!this.manager.isModelInstalled(req.modelName)) return false;
5910
- }
5911
- }
5912
- return true;
5913
- };
6778
+ this.matchRequirements = (requirements) => this.manager.matchRequirements(requirements);
6779
+ this.checkRequirements = (requirements) => this.manager.checkRequirements(requirements);
5914
6780
  this.serverLogs = [];
5915
6781
  this.wantLog = true;
5916
6782
  this.maxLogs = 200;
@@ -6174,6 +7040,7 @@ var ComfyHost = class {
6174
7040
  this.onLogs = null;
6175
7041
  this.comfySessionId = "temp";
6176
7042
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7043
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6177
7044
  this.status = null;
6178
7045
  this.lastWsMessageAt = null;
6179
7046
  this.base = parseHostBase(this.data);
@@ -6413,9 +7280,26 @@ var ComfyHost = class {
6413
7280
  }
6414
7281
  return;
6415
7282
  }
6416
- const msg_ = JSON.parse(String(e.data));
6417
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6418
- if (msg_.type === "crystools.monitor") return;
7283
+ let msg_ = JSON.parse(String(e.data));
7284
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7285
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7286
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7287
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7288
+ const key = eventType ?? "<no type>";
7289
+ if (this._unknownWsEventTypes.has(key)) return;
7290
+ this._unknownWsEventTypes.add(key);
7291
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7292
+ return;
7293
+ }
7294
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7295
+ const data = Reflect.get(rec, "data");
7296
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7297
+ type: eventType,
7298
+ data: {
7299
+ ...data,
7300
+ prompt_id: this.activePromptID
7301
+ }
7302
+ };
6419
7303
  }
6420
7304
  const res = WsMsg_ark(msg_);
6421
7305
  if (res instanceof type.errors) {
@@ -6429,7 +7313,11 @@ var ComfyHost = class {
6429
7313
  this.comfySessionId = msg.data.sid;
6430
7314
  this._sessionResolve?.();
6431
7315
  this._sessionResolve = null;
6432
- if (sidChanged) this.onSession?.(msg.data.sid);
7316
+ if (sidChanged) {
7317
+ this._unknownWsEventTypes.clear();
7318
+ this._unknownBinaryFrameTypes.clear();
7319
+ this.onSession?.(msg.data.sid);
7320
+ }
6433
7321
  }
6434
7322
  this.status = msg.data.status;
6435
7323
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6444,7 +7332,7 @@ var ComfyHost = class {
6444
7332
  this.routeOrBuffer(activePromptID, msg);
6445
7333
  return;
6446
7334
  }
6447
- if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
7335
+ if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_interrupted" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
6448
7336
  this.routeOrBuffer(msg.data.prompt_id, msg);
6449
7337
  return;
6450
7338
  }
@@ -6456,8 +7344,6 @@ var ComfyHost = class {
6456
7344
  this.onLogs?.(msg.data);
6457
7345
  return;
6458
7346
  }
6459
- console.log("❌", "Unknown message:", msg);
6460
- logError("Unknown message type: " + JSON.stringify(msg.type));
6461
7347
  }
6462
7348
  };
6463
7349
  //#endregion
@@ -6786,6 +7672,7 @@ const _getKnownModels = (DB) => {
6786
7672
  }
6787
7673
  const knownModelList = canonical.concat(extraModels.models);
6788
7674
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7675
+ DB.modelRows = knownModelList;
6789
7676
  if (DB.opts.genTypes) {
6790
7677
  let out1 = "";
6791
7678
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6954,6 +7841,7 @@ var ComfyRegistry = class ComfyRegistry {
6954
7841
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6955
7842
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6956
7843
  this.knownModels = /* @__PURE__ */ new Map();
7844
+ this.modelRows = [];
6957
7845
  this.alterations = [];
6958
7846
  this.githubStats = /* @__PURE__ */ new Map();
6959
7847
  this.report = new ManagerParseReport();