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/index.js CHANGED
@@ -110,7 +110,7 @@ function createNodeStorage() {
110
110
  }
111
111
  //#endregion
112
112
  //#region package.json
113
- var version = "2.17.1";
113
+ var version = "2.18.1";
114
114
  //#endregion
115
115
  //#region src/litegraph/LiteGraphLinkID.ts
116
116
  const asLiteGraphLinkID = (id) => id;
@@ -130,8 +130,55 @@ const bang = (x, msg = "") => {
130
130
  /** boundary sentinel ids inside definition link tables */
131
131
  const SUBGRAPH_INPUT_NODE_ID = -10;
132
132
  const SUBGRAPH_OUTPUT_NODE_ID = -20;
133
- /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
134
- const MAX_EXPANSION_PASSES = 32;
133
+ /** expanded node count above which a file is refused before expanding: the largest official
134
+ * template expands to 575 nodes, and fan-out nesting grows geometrically without any cycle */
135
+ const MAX_EXPANDED_NODES = 1e5;
136
+ /**
137
+ * before any expansion: the definitions as a graph (def → the defs its NORMAL-mode instances name,
138
+ * the only ones expansion follows). A cycle reachable from the root is refused with the defs it
139
+ * runs through, and the expanded size is counted, not built, and refused above
140
+ * MAX_EXPANDED_NODES. One explicit stack, no recursion: the file decides the depth
141
+ */
142
+ const checkExpansion = (wf, defs) => {
143
+ const children = (nodes) => nodes.filter((n) => n.mode === "normal" && defs.has(n.type)).map((n) => n.type);
144
+ const own = (nodes) => nodes.filter((n) => !(n.mode === "normal" && defs.has(n.type))).length;
145
+ const name = (id) => JSON.stringify(defs.get(id)?.name ?? id);
146
+ const cap = (n) => Math.min(n, 100001);
147
+ const size = /* @__PURE__ */ new Map();
148
+ const onPath = /* @__PURE__ */ new Set();
149
+ for (const root of new Set(children(wf.nodes))) {
150
+ if (size.has(root)) continue;
151
+ const stack = [{
152
+ id: root,
153
+ kids: children(bang(defs.get(root)).nodes),
154
+ next: 0
155
+ }];
156
+ onPath.add(root);
157
+ while (stack.length > 0) {
158
+ const top = bang(stack[stack.length - 1]);
159
+ const kid = top.kids[top.next++];
160
+ if (kid == null) {
161
+ const total = top.kids.reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(bang(defs.get(top.id)).nodes));
162
+ size.set(top.id, total);
163
+ onPath.delete(top.id);
164
+ stack.pop();
165
+ continue;
166
+ }
167
+ if (size.has(kid)) continue;
168
+ if (onPath.has(kid)) {
169
+ const from = stack.findIndex((frame) => frame.id === kid);
170
+ 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) });
171
+ }
172
+ onPath.add(kid);
173
+ stack.push({
174
+ id: kid,
175
+ kids: children(bang(defs.get(kid)).nodes),
176
+ next: 0
177
+ });
178
+ }
179
+ }
180
+ 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)`);
181
+ };
135
182
  /**
136
183
  * widget-kind fallback when a def input slot has no boundary target carrying a
137
184
  * widget marker: these litegraph slot types carry widget values. LOCAL copy on
@@ -154,11 +201,12 @@ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
154
201
  * passthrough walk, which needs no interior.
155
202
  */
156
203
  const expandSubgraphs = (wf, defs) => {
204
+ checkExpansion(wf, defs);
157
205
  let passes = 0;
158
206
  while (true) {
159
207
  const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
160
208
  if (expandable.length === 0) return wf;
161
- if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
209
+ if (++passes > defs.size + 1) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion still had instances after ${passes - 1} passes over ${defs.size} definitions`);
162
210
  for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
163
211
  else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
164
212
  }
@@ -266,7 +314,8 @@ const expandOneInstance = (wf, instance, def) => {
266
314
  name: i.name,
267
315
  type: i.type,
268
316
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
269
- widgetName: i.widgetName
317
+ widgetName: i.widgetName,
318
+ widgetSource: i.widgetSource
270
319
  })),
271
320
  outputs: inner.outputs.map((o) => ({
272
321
  name: o.name,
@@ -307,6 +356,20 @@ const expandOneInstance = (wf, instance, def) => {
307
356
  wf.links = wf.links.filter((l) => !dead.has(l.id));
308
357
  pruneDeadLinkRefs(wf, dead);
309
358
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
359
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
360
+ if (outerLinkIntoDefSlot.has(slot)) continue;
361
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
362
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
363
+ if (source == null || sourceInput == null) continue;
364
+ for (const t of targets) {
365
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
366
+ if (input == null || input.widgetName != null || input.link != null) continue;
367
+ input.widgetSource = {
368
+ nodeId: source.nodeId,
369
+ inputName: sourceInput.name
370
+ };
371
+ }
372
+ }
310
373
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
311
374
  wf.nodes.push(...splicedNodes);
312
375
  wf.links.push(...splicedLinks);
@@ -418,7 +481,7 @@ const LiteGraphNodeInput_ark = type({
418
481
  type: "string",
419
482
  "link?": LiteGraphLinkID_.or(type.null),
420
483
  "shape?": "number",
421
- "label?": "string",
484
+ "label?": type.string.or(type.null),
422
485
  "widget?": type({
423
486
  name: "string",
424
487
  "config?": "unknown"
@@ -435,7 +498,7 @@ const LiteGraphNodeOutput_ark = type({
435
498
  type: "string",
436
499
  "links?": LiteGraphLinkID_.array().or(type.null),
437
500
  "shape?": "number",
438
- "slot_index?": LiteGraphSlotIndex_
501
+ "slot_index?": LiteGraphSlotIndex_.or(type.null)
439
502
  });
440
503
  //#endregion
441
504
  //#region src/litegraph/LiteGraphNode.ts
@@ -505,7 +568,7 @@ const LiteGraphSubgraphDef_ark = type({
505
568
  const LiteGraphJSON_ark = type({
506
569
  "id?": "string",
507
570
  "revision?": "number",
508
- "last_node_id?": "number",
571
+ "last_node_id?": "number | string",
509
572
  "last_link_id?": "number",
510
573
  "state?": type.Record("string", "unknown"),
511
574
  nodes: LiteGraphNode_ark.array(),
@@ -604,7 +667,8 @@ const normalizeInput = (i) => {
604
667
  name: i.name,
605
668
  type: i.type,
606
669
  link: i.link ?? null,
607
- widgetName: i.widget?.name ?? null
670
+ widgetName: i.widget?.name ?? null,
671
+ widgetSource: null
608
672
  };
609
673
  };
610
674
  const normalizeOutput = (o) => {
@@ -777,6 +841,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
777
841
  python_module: "nodes"
778
842
  };
779
843
  //#endregion
844
+ //#region src/utils/exhaust.ts
845
+ function exhaust(x) {
846
+ return x;
847
+ }
848
+ //#endregion
780
849
  //#region src/sdk-generator/inputWidgetKind.ts
781
850
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
782
851
  /**
@@ -845,6 +914,14 @@ const parseContainer = (template) => {
845
914
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
846
915
  };
847
916
  };
917
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
918
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
919
+ const parseGroup = (o, template) => ({
920
+ kind: "dynamic-group",
921
+ fields: flattenInputSections(template),
922
+ min: typeof o["min"] === "number" ? o["min"] : 0,
923
+ max: typeof o["max"] === "number" ? o["max"] : 20
924
+ });
848
925
  /**
849
926
  * the single template sub-input's slot type of an autogrow container
850
927
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -919,11 +996,12 @@ const classifyWidgetInput = (p) => {
919
996
  };
920
997
  }
921
998
  const template = o?.["template"];
922
- if (isRecord$1(template)) {
999
+ if (o != null && isRecord$1(template)) {
923
1000
  if (isRecord$1(template["input"])) return parseContainer(template);
1001
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
924
1002
  return { kind: "slot" };
925
1003
  }
926
- if (o?.["socketless"] === true) return {
1004
+ if (typeof o?.["socketless"] === "boolean") return {
927
1005
  kind: "widget",
928
1006
  consumes: 1,
929
1007
  strictValues: false,
@@ -1023,6 +1101,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1023
1101
  if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
1024
1102
  else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
1025
1103
  }
1104
+ const linksById = new Map(workflow.links.map((l) => [l.id, l]));
1105
+ const nodesById = new Map(workflow.nodes.map((n) => [n.id, n]));
1026
1106
  for (const node of workflow.nodes) {
1027
1107
  if (isNeverExecuted(node)) continue;
1028
1108
  if (node.mode !== "normal") continue;
@@ -1096,18 +1176,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1096
1176
  inputs[p.path] = key;
1097
1177
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1098
1178
  };
1179
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1180
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1181
+ const consumeDynamicGroup = (p) => {
1182
+ const r = resolveWidgetValue({
1183
+ promptName: p.path,
1184
+ consumes: 1,
1185
+ prefixLen: 0
1186
+ });
1187
+ const saved = r.filled ? p.min : r.value;
1188
+ 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);
1189
+ const rows = Math.max(p.min, saved);
1190
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1191
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1192
+ };
1099
1193
  const consumeBranchInput = (subPath, sub) => {
1100
1194
  const kind = classifyWidgetInput({
1101
- name: sub.name,
1195
+ name: subPath,
1102
1196
  type: sub.type,
1103
1197
  opts: sub.opts
1104
1198
  });
1105
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1106
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1107
- path: subPath,
1108
- options: kind.options,
1109
- defaultKey: kind.defaultKey
1110
- });
1199
+ switch (kind.kind) {
1200
+ case "slot":
1201
+ case "dynamic-container": return;
1202
+ case "dynamic-combo": return consumeDynamicCombo({
1203
+ path: subPath,
1204
+ options: kind.options,
1205
+ defaultKey: kind.defaultKey
1206
+ });
1207
+ case "dynamic-group": return consumeDynamicGroup({
1208
+ path: subPath,
1209
+ fields: kind.fields,
1210
+ min: kind.min,
1211
+ max: kind.max
1212
+ });
1213
+ case "widget": break;
1214
+ default: return exhaust(kind);
1215
+ }
1111
1216
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1112
1217
  consumePlainWidget({
1113
1218
  promptName: subPath,
@@ -1129,32 +1234,56 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1129
1234
  strictValues: true,
1130
1235
  prefixValues: []
1131
1236
  };
1132
- if (kind.kind === "widget") consumePlainWidget({
1133
- promptName: field.nameInComfy,
1134
- typeName: field.typeName,
1135
- opts: field.opts,
1136
- consumes: kind.consumes,
1137
- prefixLen: kind.prefixValues.length,
1138
- strict: kind.strictValues,
1139
- linkedInput: input
1140
- });
1141
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1142
- path: field.nameInComfy,
1143
- options: kind.options,
1144
- defaultKey: kind.defaultKey
1145
- });
1146
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1147
- const iname = `${field.nameInComfy}.${instName}`;
1148
- 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);
1149
- }
1150
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1151
- 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);
1237
+ switch (kind.kind) {
1238
+ case "widget":
1239
+ consumePlainWidget({
1240
+ promptName: field.nameInComfy,
1241
+ typeName: field.typeName,
1242
+ opts: field.opts,
1243
+ consumes: kind.consumes,
1244
+ prefixLen: kind.prefixValues.length,
1245
+ strict: kind.strictValues,
1246
+ linkedInput: input
1247
+ });
1248
+ break;
1249
+ case "dynamic-combo":
1250
+ consumeDynamicCombo({
1251
+ path: field.nameInComfy,
1252
+ options: kind.options,
1253
+ defaultKey: kind.defaultKey
1254
+ });
1255
+ break;
1256
+ case "dynamic-group":
1257
+ consumeDynamicGroup({
1258
+ path: field.nameInComfy,
1259
+ fields: kind.fields,
1260
+ min: kind.min,
1261
+ max: kind.max
1262
+ });
1263
+ break;
1264
+ case "dynamic-container":
1265
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1266
+ const iname = `${field.nameInComfy}.${instName}`;
1267
+ 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);
1268
+ }
1269
+ break;
1270
+ case "slot":
1271
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1272
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1273
+ promptName: field.nameInComfy,
1274
+ strict: false
1275
+ });
1276
+ break;
1277
+ }
1278
+ 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);
1279
+ break;
1280
+ default:
1152
1281
  }
1153
1282
  }
1154
1283
  const getParentNode = (linkId) => {
1155
- const link = workflow.links.find((link) => link.id === linkId);
1284
+ const link = linksById.get(linkId);
1156
1285
  if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1157
- const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1286
+ const parentNode = nodesById.get(link.originId);
1158
1287
  if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
1159
1288
  return {
1160
1289
  node: parentNode,
@@ -1254,6 +1383,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1254
1383
  class_type: node.type
1255
1384
  };
1256
1385
  }
1386
+ for (const node of workflow.nodes) {
1387
+ const own = prompt[String(node.id)];
1388
+ if (own == null) continue;
1389
+ for (const ipt of node.inputs) {
1390
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1391
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1392
+ if (value !== void 0) own.inputs[ipt.name] = value;
1393
+ }
1394
+ }
1395
+ const missing = /* @__PURE__ */ new Map();
1396
+ for (const node of workflow.nodes) {
1397
+ const own = prompt[String(node.id)];
1398
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1399
+ if (own == null || nodeSchema == null) continue;
1400
+ for (const field of nodeSchema.inputs) {
1401
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1402
+ const kind = classifySchemaInput(field).kind;
1403
+ if (kind !== "slot" && kind !== "widget") continue;
1404
+ missing.set(String(node.id), {
1405
+ node,
1406
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1407
+ });
1408
+ break;
1409
+ }
1410
+ }
1411
+ if (missing.size > 0) {
1412
+ const consumers = /* @__PURE__ */ new Map();
1413
+ for (const [id, n] of Object.entries(prompt)) for (const value of Object.values(n.inputs)) if (Array.isArray(value) && typeof value[0] === "string") {
1414
+ const list = consumers.get(value[0]) ?? [];
1415
+ list.push(id);
1416
+ consumers.set(value[0], list);
1417
+ }
1418
+ const blocked = new Set(missing.keys());
1419
+ const queue = [...blocked];
1420
+ for (let head = 0; head < queue.length; head++) for (const next of consumers.get(queue[head] ?? "") ?? []) if (!blocked.has(next)) {
1421
+ blocked.add(next);
1422
+ queue.push(next);
1423
+ }
1424
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1425
+ const dropped = outputs.filter((id) => blocked.has(id));
1426
+ const first = missing.values().next().value;
1427
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1428
+ 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("; ")}`);
1429
+ }
1257
1430
  return prompt;
1258
1431
  };
1259
1432
  //#endregion
@@ -1434,21 +1607,37 @@ var ComfyNode = class ComfyNode {
1434
1607
  _convertPromptExtToPrompt(promptExt) {
1435
1608
  const inputs = {};
1436
1609
  const _done = /* @__PURE__ */ new Set();
1437
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1610
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1438
1611
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1439
1612
  for (const i of this.$schema.inputs) {
1440
1613
  _done.add(i.nameInComfy);
1441
1614
  const kind = classifySchemaInput(i);
1442
- if (kind.kind === "dynamic-combo") {
1443
- this._writeDynamicCombo({
1444
- name: i.nameInComfy,
1445
- options: kind.options,
1446
- defaultKey: kind.defaultKey,
1447
- provided: promptExt.inputs,
1448
- out: inputs,
1449
- claimed: _comboBranchKeys
1450
- });
1451
- continue;
1615
+ switch (kind.kind) {
1616
+ case "dynamic-combo":
1617
+ this._writeDynamicCombo({
1618
+ name: i.nameInComfy,
1619
+ options: kind.options,
1620
+ defaultKey: kind.defaultKey,
1621
+ provided: promptExt.inputs,
1622
+ out: inputs,
1623
+ claimed: _comboBranchKeys
1624
+ });
1625
+ continue;
1626
+ case "dynamic-group":
1627
+ this._writeDynamicGroup({
1628
+ name: i.nameInComfy,
1629
+ fields: kind.fields,
1630
+ min: kind.min,
1631
+ max: kind.max,
1632
+ provided: promptExt.inputs,
1633
+ out: inputs,
1634
+ claimed: _comboBranchKeys
1635
+ });
1636
+ continue;
1637
+ case "widget":
1638
+ case "slot":
1639
+ case "dynamic-container": break;
1640
+ default:
1452
1641
  }
1453
1642
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1454
1643
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1487,6 +1676,42 @@ var ComfyNode = class ComfyNode {
1487
1676
  }) : this.serializeValue(dotted, given);
1488
1677
  }
1489
1678
  }
1679
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1680
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1681
+ * keys are already the rows: they pass through the rest loop untouched */
1682
+ _writeDynamicGroup(p) {
1683
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1684
+ const raw = p.provided[p.name];
1685
+ const prefix = `${p.name}.`;
1686
+ if (raw == null) {
1687
+ 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)`);
1688
+ return;
1689
+ }
1690
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1691
+ if (!Array.isArray(raw)) {
1692
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1693
+ return;
1694
+ }
1695
+ 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}`);
1696
+ raw.forEach((row, ix) => {
1697
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1698
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1699
+ return;
1700
+ }
1701
+ const given = new Map(Object.entries(row));
1702
+ for (const field of p.fields) {
1703
+ const dotted = `${p.name}.${ix}.${field.name}`;
1704
+ const value = given.get(field.name);
1705
+ p.out[dotted] = value == null ? defaultValueForWidget({
1706
+ type: typeof field.type === "string" ? field.type : "COMBO",
1707
+ opts: field.opts,
1708
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1709
+ }) : this.serializeValue(dotted, value);
1710
+ given.delete(field.name);
1711
+ }
1712
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1713
+ });
1714
+ }
1490
1715
  /** return the list of nodes piped into this node */
1491
1716
  _incomingNodes() {
1492
1717
  const incomingNodes = [];
@@ -1630,6 +1855,12 @@ var ComfyNode = class ComfyNode {
1630
1855
  const kind = classifySchemaInput(decl);
1631
1856
  const slotType = containerInstanceSlotType(decl.opts);
1632
1857
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1858
+ if (kind.kind === "dynamic-group") {
1859
+ const rest = name.slice(dot + 1);
1860
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1861
+ const field = kind.fields.find((f) => f.name === fieldName);
1862
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1863
+ }
1633
1864
  }
1634
1865
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1635
1866
  }
@@ -1713,44 +1944,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1713
1944
  const convertNodeToLiteGraphNode = (ctx, node) => {
1714
1945
  const inputs = [];
1715
1946
  const widgets_values = [];
1716
- const pushLinked = (name, type, link, shape) => {
1947
+ const pushLinked = (name, type, link, extra = {}) => {
1717
1948
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1718
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1719
- inputs.push(shape == null ? {
1949
+ const input = {
1720
1950
  name,
1721
1951
  type,
1722
- link: linkId
1723
- } : {
1952
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1953
+ };
1954
+ if (extra.shape != null) input.shape = extra.shape;
1955
+ if (extra.widget === true) input.widget = { name };
1956
+ inputs.push(input);
1957
+ };
1958
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1959
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1960
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1961
+ * never disagree on the run length */
1962
+ const pushWidgetRun = (kind, raw, opts) => {
1963
+ widgets_values.push(...kind.prefixValues, raw);
1964
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1965
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1966
+ };
1967
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1968
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1969
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1970
+ const writeInput = (p) => {
1971
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1972
+ switch (p.kind.kind) {
1973
+ case "widget":
1974
+ if (_isLink(p.value)) {
1975
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
1976
+ pushWidgetRun(p.kind, defaultValueForWidget({
1977
+ type: p.typeName,
1978
+ opts: p.opts
1979
+ }), p.opts);
1980
+ } else pushWidgetRun(p.kind, p.value, p.opts);
1981
+ return;
1982
+ case "slot":
1983
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
1984
+ else inputs.push({
1985
+ name: p.name,
1986
+ type: p.typeName,
1987
+ link: null
1988
+ });
1989
+ return;
1990
+ case "dynamic-combo": {
1991
+ const kind = p.kind;
1992
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
1993
+ const option = kind.options.find((o) => o.key === key);
1994
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
1995
+ widgets_values.push(key);
1996
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
1997
+ return;
1998
+ }
1999
+ case "dynamic-container": {
2000
+ const type = containerInstanceSlotType(p.opts) ?? "*";
2001
+ for (const instance of p.kind.instanceNames) {
2002
+ const name = `${p.name}.${instance}`;
2003
+ const value = node.json.inputs[name];
2004
+ if (value == null) continue;
2005
+ const raw = node.serializeValue(name, value);
2006
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
2007
+ pushLinked(name, type, raw, { shape: 7 });
2008
+ }
2009
+ return;
2010
+ }
2011
+ case "dynamic-group": {
2012
+ const prefix = `${p.name}.`;
2013
+ let rows = 0;
2014
+ for (const key of Object.keys(node.json.inputs)) {
2015
+ if (!key.startsWith(prefix)) continue;
2016
+ const row = Number(key.slice(prefix.length).split(".")[0]);
2017
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
2018
+ }
2019
+ widgets_values.push(rows);
2020
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
2021
+ return;
2022
+ }
2023
+ default: p.kind;
2024
+ }
2025
+ };
2026
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
2027
+ * value is the widget's schema default rather than serializeValue's */
2028
+ const writeSub = (name, sub) => {
2029
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
2030
+ const raw = node.json.inputs[name];
2031
+ writeInput({
1724
2032
  name,
1725
- type,
1726
- shape,
1727
- link: linkId
2033
+ kind: classifyWidgetInput({
2034
+ name,
2035
+ type: sub.type,
2036
+ opts: sub.opts
2037
+ }),
2038
+ typeName,
2039
+ opts: sub.opts,
2040
+ value: raw === void 0 ? defaultValueForWidget({
2041
+ type: typeName,
2042
+ opts: sub.opts
2043
+ }) : raw
1728
2044
  });
1729
2045
  };
1730
2046
  for (const ipt of node.$schema.inputs) {
1731
2047
  const kind = classifySchemaInput(ipt);
1732
- if (kind.kind === "dynamic-container") {
1733
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1734
- for (const instance of kind.instanceNames) {
1735
- const name = `${ipt.nameInComfy}.${instance}`;
1736
- const value = node.json.inputs[name];
1737
- if (value == null) continue;
1738
- const raw = node.serializeValue(name, value);
1739
- 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`);
1740
- pushLinked(name, type, raw, 7);
1741
- }
1742
- continue;
1743
- }
1744
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1745
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1746
- else if (kind.kind === "widget") {
1747
- widgets_values.push(...kind.prefixValues, raw);
1748
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1749
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1750
- } else inputs.push({
2048
+ const raw = node.json.inputs[ipt.nameInComfy];
2049
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
2050
+ writeInput({
1751
2051
  name: ipt.nameInComfy,
1752
- type: ipt.typeName,
1753
- link: null
2052
+ kind,
2053
+ typeName: ipt.typeName,
2054
+ opts: ipt.opts,
2055
+ value
1754
2056
  });
1755
2057
  }
1756
2058
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1936,11 +2238,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1936
2238
  return resultSuccess(txt_chunks);
1937
2239
  };
1938
2240
  //#endregion
1939
- //#region src/utils/exhaust.ts
1940
- function exhaust(x) {
1941
- return x;
1942
- }
1943
- //#endregion
1944
2241
  //#region src/utils/sha1.ts
1945
2242
  function sha1Hex(data) {
1946
2243
  const ml = data.length;
@@ -2075,16 +2372,17 @@ const types$1 = scope({
2075
2372
  },
2076
2373
  _WsMsgExecutedData: {
2077
2374
  node: "ComfyNodeID",
2078
- output: {
2079
- "previews?": [{ filepath: "string" }, "[]"],
2080
- "images?": "ComfyImageInfo[]",
2081
- "audio?": "ComfyImageInfo[]",
2082
- "video?": "ComfyImageInfo[]",
2083
- "gifs?": "ComfyImageInfo[]",
2084
- "text?": "unknown[]"
2085
- },
2375
+ output: "_WsMsgExecutedOutput | null",
2086
2376
  prompt_id: "PromptID"
2087
2377
  },
2378
+ _WsMsgExecutedOutput: {
2379
+ "previews?": [{ filepath: "string" }, "[]"],
2380
+ "images?": "ComfyImageInfo[]",
2381
+ "audio?": "ComfyImageInfo[]",
2382
+ "video?": "ComfyImageInfo[]",
2383
+ "gifs?": "ComfyImageInfo[]",
2384
+ "text?": "unknown[]"
2385
+ },
2088
2386
  WsMsgExecuted: {
2089
2387
  type: "'executed'",
2090
2388
  data: "_WsMsgExecutedData"
@@ -2106,12 +2404,22 @@ const types$1 = scope({
2106
2404
  exception_type: "string",
2107
2405
  traceback: "string[]",
2108
2406
  current_inputs: "Record<string, unknown>",
2109
- current_outputs: "Record<string, unknown>"
2407
+ current_outputs: "ComfyNodeID[]"
2110
2408
  },
2111
2409
  WsMsgExecutionError: {
2112
2410
  type: "'execution_error'",
2113
2411
  data: "_WsMsgExecutionErrorData"
2114
2412
  },
2413
+ _WsMsgExecutionInterruptedData: {
2414
+ prompt_id: "PromptID",
2415
+ node_id: "ComfyNodeID",
2416
+ node_type: "string",
2417
+ executed: "ComfyNodeID[]"
2418
+ },
2419
+ WsMsgExecutionInterrupted: {
2420
+ type: "'execution_interrupted'",
2421
+ data: "_WsMsgExecutionInterruptedData"
2422
+ },
2115
2423
  WSMsgManagerFeedbackData: { data: "string" },
2116
2424
  WSMsgManagerFeedback: {
2117
2425
  type: "'manager-terminal-feedback'",
@@ -2141,11 +2449,51 @@ const types$1 = scope({
2141
2449
  type: "'progress_state'",
2142
2450
  data: "_WsMsgProgressStateData"
2143
2451
  },
2144
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2452
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2145
2453
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2146
2454
  }).export();
2147
2455
  const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2148
2456
  const WsMsg_ark = types$1.WsMsg;
2457
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2458
+ const ROUTED_WS_EVENT_TYPES = [
2459
+ "status",
2460
+ "manager-terminal-feedback",
2461
+ "logs",
2462
+ "execution_start",
2463
+ "execution_cached",
2464
+ "executing",
2465
+ "progress",
2466
+ "progress_state",
2467
+ "executed",
2468
+ "execution_error",
2469
+ "execution_interrupted",
2470
+ "execution_success"
2471
+ ];
2472
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2473
+ * before validation, never logged (architecture.md, ws events) */
2474
+ const IGNORED_WS_EVENT_TYPES = [
2475
+ "feature_flags",
2476
+ "agent_status",
2477
+ "asset_export",
2478
+ "assets.seed.started",
2479
+ "assets.seed.progress",
2480
+ "assets.seed.fast_complete",
2481
+ "assets.seed.enrich_complete",
2482
+ "assets.seed.completed",
2483
+ "assets.seed.cancelled",
2484
+ "assets.seed.error",
2485
+ "assets.seed.paused",
2486
+ "assets.seed.resumed",
2487
+ "cm-queue-status",
2488
+ "cm-api-try-install-customnode",
2489
+ "cm-task-started",
2490
+ "cm-task-completed",
2491
+ "crystools.monitor"
2492
+ ];
2493
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2494
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2495
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2496
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2149
2497
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2150
2498
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2151
2499
  //#endregion
@@ -2435,6 +2783,10 @@ var ComfyExecution = class {
2435
2783
  else if (msg.type === "progress") graph.onProgress(msg);
2436
2784
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2437
2785
  else if (msg.type === "execution_error") return void this.onError(msg);
2786
+ else if (msg.type === "execution_interrupted") return void this._finish({
2787
+ status: "Failure",
2788
+ error: msg
2789
+ });
2438
2790
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2439
2791
  else {
2440
2792
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3348,6 +3700,15 @@ const dynamicComboUnion = (p) => {
3348
3700
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3349
3701
  }).join(" | ")})`;
3350
3702
  };
3703
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3704
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3705
+ const dynamicGroupRow = (fields) => {
3706
+ return `{ ${fields.map((e) => {
3707
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3708
+ const optional = !e.required || opts?.["default"] !== void 0;
3709
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3710
+ }).join("; ")} }`;
3711
+ };
3351
3712
  /**
3352
3713
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3353
3714
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3396,6 +3757,8 @@ function codegenSDK(opts) {
3396
3757
  b.deindent();
3397
3758
  p(`// #endregion`);
3398
3759
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3760
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3761
+ const groupRows = [];
3399
3762
  p(`interface IN {`);
3400
3763
  b.indent();
3401
3764
  for (const n of nodes) {
@@ -3403,23 +3766,37 @@ function codegenSDK(opts) {
3403
3766
  const comboSuffixes = [];
3404
3767
  for (const i of n.inputs) {
3405
3768
  const kind = classifySchemaInput(i);
3406
- if (kind.kind === "dynamic-container") {
3407
- const instType = containerInstanceSlotType(i.opts);
3408
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3409
- const opt = ix >= kind.requiredCount ? "?" : "";
3410
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3411
- });
3412
- continue;
3413
- }
3414
- if (kind.kind === "dynamic-combo") {
3415
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3416
- comboSuffixes.push(dynamicComboUnion({
3417
- name: i.nameInComfy,
3418
- nameEscaped: i.nameInComfyEscaped,
3419
- options: kind.options,
3420
- keyOptional: optsDyn?.default !== void 0 || !i.required
3421
- }));
3422
- continue;
3769
+ switch (kind.kind) {
3770
+ case "dynamic-container": {
3771
+ const instType = containerInstanceSlotType(i.opts);
3772
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3773
+ const opt = ix >= kind.requiredCount ? "?" : "";
3774
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3775
+ });
3776
+ continue;
3777
+ }
3778
+ case "dynamic-combo": {
3779
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3780
+ comboSuffixes.push(dynamicComboUnion({
3781
+ name: i.nameInComfy,
3782
+ nameEscaped: i.nameInComfyEscaped,
3783
+ options: kind.options,
3784
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3785
+ }));
3786
+ continue;
3787
+ }
3788
+ case "dynamic-group": {
3789
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3790
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3791
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3792
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3793
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3794
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3795
+ continue;
3796
+ }
3797
+ case "widget":
3798
+ case "slot": break;
3799
+ default:
3423
3800
  }
3424
3801
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3425
3802
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3442,6 +3819,15 @@ function codegenSDK(opts) {
3442
3819
  b.deindent();
3443
3820
  p("}");
3444
3821
  p("");
3822
+ if (groupRows.length > 0) {
3823
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3824
+ p(`interface GroupRow {`);
3825
+ b.indent();
3826
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3827
+ b.deindent();
3828
+ p("}");
3829
+ p("");
3830
+ }
3445
3831
  p(`interface OUT {`);
3446
3832
  b.indent();
3447
3833
  for (const n of nodes) {
@@ -3754,9 +4140,13 @@ var ComfySchema = class {
3754
4140
  if (widgetKind?.kind === "dynamic-combo") {
3755
4141
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3756
4142
  }
4143
+ if (widgetKind?.kind === "dynamic-group") {
4144
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4145
+ }
4146
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3757
4147
  node.inputs.push({
3758
4148
  slotName: inputSlotName,
3759
- required: ipt.required && !isAutogrowContainer,
4149
+ required,
3760
4150
  nameInComfy: inputNameInComfy,
3761
4151
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3762
4152
  typeName: inputTypeName,
@@ -3832,7 +4222,12 @@ const types = scope({
3832
4222
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3833
4223
  ComfyInputSpecAlt2: ["ComfyInputType"],
3834
4224
  ComfyInputSpecAlt3: type([type.null]),
3835
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4225
+ ComfyInputSpecAlt4: [
4226
+ "ComfyInputType",
4227
+ "ComfyInputOpts",
4228
+ "unknown"
4229
+ ],
4230
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3836
4231
  ComfyInputType: `string | ComfyEnumDef`,
3837
4232
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3838
4233
  ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
@@ -3898,10 +4293,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3898
4293
  return result;
3899
4294
  }
3900
4295
  //#endregion
4296
+ //#region src/manager/installedView.ts
4297
+ /**
4298
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4299
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4300
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4301
+ */
4302
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4303
+ const InstalledPacks_ark = type.Record("string", type({
4304
+ "cnr_id?": "string | null",
4305
+ "aux_id?": "string | null",
4306
+ enabled: "boolean"
4307
+ }));
4308
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4309
+ const PackMappings_ark = type.Record("string", type(["string[]", { "title_aux?": "string" }]));
4310
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4311
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4312
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4313
+ const attributePacks = (installed, mappings) => {
4314
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4315
+ return Object.entries(installed).map(([dir, p]) => {
4316
+ const aux = p.aux_id ?? null;
4317
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4318
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4319
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4320
+ return {
4321
+ enabled: p.enabled,
4322
+ repo,
4323
+ title,
4324
+ id: cnr ?? aux ?? dir
4325
+ };
4326
+ });
4327
+ };
4328
+ /** is this mirror row among the attributed packs, enabled? */
4329
+ const packIsInstalled = (packs, plugin) => {
4330
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4331
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4332
+ };
4333
+ const buildPluginView = (p) => {
4334
+ const packs = attributePacks(p.installed, p.mappings);
4335
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4336
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4337
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4338
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4339
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4340
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4341
+ const custom_nodes = [];
4342
+ for (const plugin of plugins) {
4343
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4344
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4345
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4346
+ title: plugin.title,
4347
+ installed: "True"
4348
+ });
4349
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4350
+ else custom_nodes.push({
4351
+ title: plugin.title,
4352
+ installed: "False"
4353
+ });
4354
+ }
4355
+ return {
4356
+ list: {
4357
+ chanel: "default",
4358
+ custom_nodes
4359
+ },
4360
+ unattributed: unattributed.map((x) => x.id)
4361
+ };
4362
+ };
4363
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4364
+ const DEFAULT_FOLDER_BY_TYPE = {
4365
+ checkpoints: "checkpoints",
4366
+ checkpoint: "checkpoints",
4367
+ unclip: "checkpoints",
4368
+ text_encoders: "text_encoders",
4369
+ clip: "text_encoders",
4370
+ vae: "vae",
4371
+ lora: "loras",
4372
+ "t2i-adapter": "controlnet",
4373
+ "t2i-style": "controlnet",
4374
+ controlnet: "controlnet",
4375
+ clip_vision: "clip_vision",
4376
+ gligen: "gligen",
4377
+ upscale: "upscale_models",
4378
+ embedding: "embeddings",
4379
+ embeddings: "embeddings",
4380
+ unet: "diffusion_models",
4381
+ diffusion_model: "diffusion_models"
4382
+ };
4383
+ /** what core `get_filename_list` lists in the standard folders */
4384
+ const LISTED_EXTENSIONS = [
4385
+ ".ckpt",
4386
+ ".pt",
4387
+ ".pt2",
4388
+ ".bin",
4389
+ ".pth",
4390
+ ".safetensors",
4391
+ ".pkl",
4392
+ ".sft"
4393
+ ];
4394
+ /**
4395
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4396
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4397
+ */
4398
+ const modelLocation = (m) => {
4399
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4400
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4401
+ if (m.save_path === "default") {
4402
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4403
+ return folder == null ? null : {
4404
+ folder,
4405
+ files: [m.filename]
4406
+ };
4407
+ }
4408
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4409
+ const folder = parts[0];
4410
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4411
+ const sub = [...parts.slice(1), m.filename].join("/");
4412
+ return {
4413
+ folder,
4414
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4415
+ };
4416
+ };
4417
+ const buildModelView = (p) => {
4418
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4419
+ const statusOf = (m) => {
4420
+ const at = modelLocation(m);
4421
+ const files = at == null ? null : listed.get(at.folder);
4422
+ if (at == null || files == null) return null;
4423
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4424
+ };
4425
+ const byName = /* @__PURE__ */ new Map();
4426
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4427
+ const models = [];
4428
+ for (const rows of byName.values()) {
4429
+ const statuses = new Set(rows.map(statusOf));
4430
+ const first = rows[0];
4431
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4432
+ if (first == null || installed == null) continue;
4433
+ models.push({
4434
+ name: first.name,
4435
+ installed,
4436
+ filename: first.filename,
4437
+ save_path: first.save_path,
4438
+ base: first.base
4439
+ });
4440
+ }
4441
+ return { models };
4442
+ };
4443
+ /** the folders the views need listed */
4444
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4445
+ //#endregion
3901
4446
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3902
4447
  const ComfyManagerAPIModelList_ark = type({ models: type({
3903
4448
  name: type.string.as(),
3904
- installed: `'False' | 'True' | 'Update'`
4449
+ installed: `'False' | 'True' | 'Update'`,
4450
+ "filename?": "string",
4451
+ "save_path?": "string",
4452
+ "base?": "string"
3905
4453
  }).array() });
3906
4454
  //#endregion
3907
4455
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3912,28 +4460,160 @@ const ComfyManagerAPIPluginList_ark = type({
3912
4460
  }).array(),
3913
4461
  chanel: "string"
3914
4462
  });
4463
+ const ComfyManagerAPIPack_ark = type({
4464
+ title: type.string.as(),
4465
+ "id?": "string",
4466
+ "files?": "string[]",
4467
+ "repository?": "string",
4468
+ "version?": "string",
4469
+ "state?": "string",
4470
+ "update-state?": "string"
4471
+ });
4472
+ const ComfyManagerAPIPackList_ark = type({
4473
+ channel: "string",
4474
+ node_packs: type.Record("string", ComfyManagerAPIPack_ark)
4475
+ });
3915
4476
  //#endregion
3916
4477
  //#region src/host/ComfyManager.ts
4478
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4479
+ const MANAGER_TIMING = {
4480
+ pollMs: 1e3,
4481
+ installTimeoutMs: 60 * 6e4,
4482
+ pollGraceMs: 12e4
4483
+ };
4484
+ /** an install the host refused or reported failed: ends the wait at once */
4485
+ var InstallFailed = class extends Error {};
4486
+ /** we lost sight of the task: the outcome is not known */
4487
+ var OutcomeUnknown = class extends Error {};
4488
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4489
+ const NOT_SERVED = {
4490
+ v3: [
4491
+ "/manager/queue/batch",
4492
+ "/manager/queue/task",
4493
+ "/manager/queue/history"
4494
+ ],
4495
+ "v4-legacy-ui": [
4496
+ "/manager/queue/install",
4497
+ "/manager/queue/task",
4498
+ "/manager/queue/history",
4499
+ "/manager/terminal"
4500
+ ],
4501
+ v4: [
4502
+ "/customnode/getlist",
4503
+ "/externalmodel/getlist",
4504
+ "/manager/queue/install",
4505
+ "/manager/queue/batch",
4506
+ "/manager/terminal"
4507
+ ]
4508
+ };
4509
+ const QueueStatus_ark = type({
4510
+ is_processing: "boolean",
4511
+ "pending_count?": "number",
4512
+ "total_count?": "number",
4513
+ "done_count?": "number"
4514
+ });
4515
+ const TaskHistory_ark = type({ history: {
4516
+ "status?": {
4517
+ status_str: "string",
4518
+ "messages?": "string[]"
4519
+ },
4520
+ "result?": "string"
4521
+ } });
4522
+ const ModelFolders_ark = type("string[]");
4523
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3917
4524
  var ComfyManager = class {
3918
- constructor(host) {
4525
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3919
4526
  this.host = host;
3920
- this.fetchPluginsAndModels = async () => {
3921
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3922
- this.pluginList = _pluginList;
3923
- this.modelList = _modelList;
4527
+ this.timing = timing;
4528
+ this.mirror = mirror;
4529
+ this.clientId = `comfy-ts-${nanoid(8)}`;
4530
+ this._api = null;
4531
+ this.api = () => {
4532
+ if (this._api == null) {
4533
+ const probe = this.probeApi();
4534
+ this._api = probe;
4535
+ probe.catch(() => {
4536
+ if (this._api === probe) this._api = null;
4537
+ });
4538
+ }
4539
+ return this._api;
4540
+ };
4541
+ this.probeApi = async () => {
4542
+ const v4 = await this.host.fetch("/v2/manager/version");
4543
+ if (v4.ok) {
4544
+ const version = (await v4.text()).trim();
4545
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4546
+ if (!ui.ok) {
4547
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4548
+ return {
4549
+ generation: "v4",
4550
+ version
4551
+ };
4552
+ }
4553
+ const flag = await ui.json();
4554
+ return {
4555
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4556
+ version
4557
+ };
4558
+ }
4559
+ const v3 = await this.host.fetch("/manager/version");
4560
+ if (v3.ok) return {
4561
+ generation: "v3",
4562
+ version: (await v3.text()).trim()
4563
+ };
4564
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4565
+ };
4566
+ this.route = (api, route, query = "") => {
4567
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4568
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4569
+ };
4570
+ this.strategy = (api) => {
4571
+ switch (api.generation) {
4572
+ case "v3": return {
4573
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4574
+ fetchModels: () => this.listedModels(api),
4575
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4576
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4577
+ };
4578
+ case "v4-legacy-ui": return {
4579
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4580
+ fetchModels: () => this.listedModels(api),
4581
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4582
+ const route = this.route(api, "/manager/queue/batch");
4583
+ const res = await this.post(route, { install: [body] });
4584
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4585
+ 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)`);
4586
+ }),
4587
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4588
+ };
4589
+ case "v4": return {
4590
+ fetchPlugins: () => this.installedPluginView(api),
4591
+ fetchModels: () => this.installedModelView(),
4592
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4593
+ settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId)
4594
+ };
4595
+ }
3924
4596
  };
3925
- this.configureLogging = (mi) => {
3926
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4597
+ this.configureLogging = async (mi) => {
4598
+ const api = await this.api();
4599
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4600
+ const response = await this.host.fetch(route);
4601
+ const text = await response.text();
4602
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4603
+ return text;
3927
4604
  };
3928
4605
  this.getModelInfoFinalFilePath = (mi) => {
3929
4606
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3930
4607
  };
3931
4608
  this.restartComfyUI = async () => {
4609
+ const api = await this.api();
4610
+ this._api = null;
4611
+ const route = this.route(api, "/manager/reboot");
3932
4612
  const refusals = [];
3933
4613
  for (const method of ["POST", "GET"]) {
3934
4614
  let response;
3935
4615
  try {
3936
- response = await this.host.fetch("/manager/reboot", { method });
4616
+ response = await this.host.fetch(route, { method });
3937
4617
  } catch {
3938
4618
  return;
3939
4619
  }
@@ -3941,31 +4621,44 @@ var ComfyManager = class {
3941
4621
  refusals.push(`${method} → ${response.status}`);
3942
4622
  if (response.status !== 404) break;
3943
4623
  }
3944
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4624
+ 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`);
4625
+ };
4626
+ this.fetchPluginsAndModels = async () => {
4627
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4628
+ this.pluginList = _pluginList;
4629
+ this.modelList = _modelList;
3945
4630
  };
3946
4631
  this.modelList = null;
3947
- this.fetchModels = () => {
3948
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4632
+ this.fetchModels = async () => {
4633
+ return this.strategy(await this.api()).fetchModels();
3949
4634
  };
3950
4635
  this.fetchLogs = () => {
3951
- return this.fetchGetJSON("/internal/logs");
4636
+ return this.getJSON("/internal/logs");
3952
4637
  };
3953
4638
  this.isModelInstalled = (name) => {
3954
4639
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3955
4640
  };
3956
4641
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3957
- this.installModel = async (model) => {
4642
+ this.installModel = async (model) => await this.installModelOutcome(model) === "installed";
4643
+ this.installModelOutcome = async (model) => {
4644
+ this.modelsBeeingInstalled.add(model.name);
3958
4645
  try {
3959
- this.modelsBeeingInstalled.add(model.name);
3960
- await this.fetchPost("/model/install", model);
3961
- this.modelsBeeingInstalled.delete(model.name);
3962
- logSuccess("Model installed");
3963
- return true;
3964
- } catch (exception) {
3965
- console.error(`Install failed: / ${exception}`);
3966
- logError("Model Installation Failed");
4646
+ return await this.runInstall(`model "${model.name}"`, {
4647
+ enqueue: async (api, uiId) => {
4648
+ const body = {
4649
+ ...model,
4650
+ ui_id: uiId,
4651
+ client_id: this.clientId
4652
+ };
4653
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4654
+ },
4655
+ landed: async (s) => {
4656
+ const row = (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base);
4657
+ return row == null ? null : row.installed === "True";
4658
+ }
4659
+ });
4660
+ } finally {
3967
4661
  this.modelsBeeingInstalled.delete(model.name);
3968
- return false;
3969
4662
  }
3970
4663
  };
3971
4664
  this.getModelStatus = (modelName) => {
@@ -3995,48 +4688,239 @@ var ComfyManager = class {
3995
4688
  return "error";
3996
4689
  })();
3997
4690
  };
4691
+ this.requirementStatus = (req) => {
4692
+ const mirror = this.mirror();
4693
+ const packs = (() => {
4694
+ if (req.type === "customNodesByNodeKey") return mirror.plugins_byNodeKey.get(req.nodeName) ?? [];
4695
+ if (req.type === "customNodesByTitle") return [mirror.plugins_byTitle.get(req.title)].filter((x) => x != null);
4696
+ if (req.type === "customNodesByURI") return [mirror.plugins_byFile.get(req.uri)].filter((x) => x != null);
4697
+ return null;
4698
+ })();
4699
+ if (packs == null) return req.type === "modelInManager" ? this.getModelStatus(req.modelName) : null;
4700
+ if (packs.length === 0) return req.type === "customNodesByNodeKey" ? "unknown" : null;
4701
+ const statuses = packs.map((x) => this.getPluginStatus(x.title));
4702
+ if (statuses.some((x) => x === "installed" || x === "update-available")) return "installed";
4703
+ return statuses.every((x) => x === "not-installed") ? "not-installed" : "unknown";
4704
+ };
4705
+ this.checkRequirements = (requirements) => {
4706
+ const out = {
4707
+ missing: [],
4708
+ undecided: []
4709
+ };
4710
+ for (const req of requirements) {
4711
+ if (req.optional) continue;
4712
+ const status = this.requirementStatus(req);
4713
+ if (status === "not-installed") out.missing.push(req);
4714
+ else if (status === "unknown" || status === "error") out.undecided.push(req);
4715
+ }
4716
+ return out;
4717
+ };
4718
+ this.matchRequirements = (requirements) => {
4719
+ const check = this.checkRequirements(requirements);
4720
+ 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)" : ""));
4721
+ return check.missing.length === 0;
4722
+ };
3998
4723
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
4724
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4725
+ };
4726
+ this.installPlugin = async (plugin) => await this.installPluginOutcome(plugin) === "installed";
4727
+ this.installPluginOutcome = async (plugin) => {
4728
+ return this.runInstall(`plugin "${plugin.title}"`, {
4729
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4730
+ landed: async (_s, api) => {
4731
+ const data = await this.installedData(api);
4732
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4733
+ }
4734
+ });
4735
+ };
4736
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4737
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4738
+ if (!("node_packs" in raw)) return raw;
4739
+ const titleByRepo = /* @__PURE__ */ new Map();
4740
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4741
+ return {
4742
+ chanel: raw.channel,
4743
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4744
+ const repo = p.files?.[0];
4745
+ return {
4746
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4747
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4748
+ };
4749
+ })
4750
+ };
4751
+ };
4752
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4753
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4754
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4755
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4756
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4757
+ };
4758
+ this.listedModels = async (api) => {
4759
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4760
+ };
4761
+ this.installedData = async (api) => {
4762
+ 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)]);
4763
+ return {
4764
+ installed,
4765
+ mappings
4766
+ };
4767
+ };
4768
+ this.installedPluginView = async (api) => {
4769
+ const view = buildPluginView({
4770
+ mirror: this.mirror(),
4771
+ ...await this.installedData(api)
4772
+ });
4773
+ 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`);
4774
+ return view.list;
4775
+ };
4776
+ this.installedModelView = async () => {
4777
+ const models = this.mirror().modelRows;
4778
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4779
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4780
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4781
+ return buildModelView({
4782
+ models,
4783
+ files: new Map(lists)
4784
+ });
4785
+ };
4786
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4787
+ const url = plugin.files[0] ?? plugin.reference;
4788
+ const list = await this.fetchPluginWire(api, "cache", true);
4789
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4790
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4791
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4792
+ const [key, row] = found;
4793
+ await send({
4794
+ ...row,
4795
+ id: row.id ?? key,
4796
+ channel: list.channel,
4797
+ mode: "cache",
4798
+ ui_id: uiId,
4799
+ skip_post_install: false
4800
+ });
4801
+ };
4802
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4803
+ const url = plugin.files[0] ?? plugin.reference;
4804
+ const id = repoPath(url).split("/").pop() ?? url;
4805
+ const params = {
4806
+ id,
4807
+ version: "nightly",
4808
+ selected_version: "nightly",
4809
+ repository: url,
4810
+ mode: "cache",
4811
+ channel: "default"
4812
+ };
4813
+ await this.post(this.route(api, "/manager/queue/task"), {
4814
+ ui_id: uiId,
4815
+ client_id: this.clientId,
4816
+ kind: "install",
4817
+ params
4818
+ });
4819
+ return id;
4820
+ };
4821
+ this.settleByHistory = async (api, what, uiId, landed, sentId) => {
4822
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4823
+ const readEntry = async () => (await this.getValid(route, TaskHistory_ark)).history.status ?? null;
4824
+ const entry = await this.waitFor(what, async () => {
4825
+ const status = await readEntry();
4826
+ if (status != null) return status;
4827
+ if (await this.restartIdleQueue(api) !== "drained") return null;
4828
+ const late = await readEntry();
4829
+ if (late != null) return late;
4830
+ throw new InstallFailed("the task left the queue with no result (a queue/reset from the Manager UI or another client removes it)");
4831
+ });
4832
+ if (entry.status_str === "success" || entry.status_str === "skip") {
4833
+ if (await this.endState(landed) !== false) return;
4834
+ 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");
4835
+ }
4836
+ const messages = entry.messages ?? [];
4837
+ 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)" : "";
4838
+ throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4839
+ };
4840
+ this.restartIdleQueue = async (api) => {
4841
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4842
+ if (status.is_processing) return "running";
4843
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4844
+ await this.post(this.route(api, "/manager/queue/start"));
4845
+ return "restarted";
4846
+ };
4847
+ this.settleByDrain = async (api, what, landed) => {
4848
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4849
+ const state = await this.endState(landed);
4850
+ if (state === true) return;
4851
+ if (state === null) throw new OutcomeUnknown("the queue drained, but the lists cannot say whether it is installed");
4852
+ 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`);
4853
+ };
4854
+ this.endState = async (landed) => {
3999
4855
  try {
4000
- const skip_update = skipUpdate ? "&skip_update=true" : "";
4001
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4856
+ return await landed();
4002
4857
  } catch (exception) {
4003
- console.error(`node list retrieval failed: ${exception}`);
4004
- logError("node list retrieveal failed");
4005
- throw exception;
4858
+ throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`);
4006
4859
  }
4007
4860
  };
4008
- this.installPlugin = async (model) => {
4861
+ this.runInstall = async (what, p) => {
4862
+ const host = this.host.getServerHostHTTP();
4009
4863
  try {
4010
- await this.fetchPost("/customnode/install", model);
4011
- console.log("✅ Custom Node installed");
4012
- logSuccess("Custom Node installed");
4013
- return true;
4864
+ const api = await this.api();
4865
+ const s = this.strategy(api);
4866
+ const uiId = nanoid();
4867
+ const sentId = await p.enqueue(api, uiId);
4868
+ await this.post(this.route(api, "/manager/queue/start"));
4869
+ await s.settle(what, uiId, () => p.landed(s, api), sentId);
4870
+ logSuccess(`${what} installed`);
4871
+ return "installed";
4014
4872
  } catch (exception) {
4015
- console.error(`Install failed: / ${exception}`);
4016
- logError("Custom Node Installation Failed");
4017
- return false;
4873
+ if (exception instanceof OutcomeUnknown) {
4874
+ 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`);
4875
+ return "unknown";
4876
+ }
4877
+ logError(`${what}: install failed on ${host}: ${errorText(exception)}`);
4878
+ return "failed";
4879
+ }
4880
+ };
4881
+ this.waitFor = async (what, check) => {
4882
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4883
+ let lastAnswer = Date.now();
4884
+ for (;;) {
4885
+ try {
4886
+ const value = await check();
4887
+ lastAnswer = Date.now();
4888
+ if (value != null) return value;
4889
+ } catch (exception) {
4890
+ if (exception instanceof InstallFailed) throw exception;
4891
+ 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)}`);
4892
+ logError(`${what}: poll failed, still waiting: ${errorText(exception)}`);
4893
+ }
4894
+ if (Date.now() >= deadline) throw new OutcomeUnknown(`still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4895
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4018
4896
  }
4019
4897
  };
4020
- this.fetchPost = async (endpoint, body, validator) => {
4021
- const response = await this.host.fetch(endpoint, {
4898
+ this.post = async (route, body) => {
4899
+ const response = await this.host.fetch(route, {
4022
4900
  method: "POST",
4023
4901
  headers: { "Content-Type": "application/json" },
4024
- body: JSON.stringify(body)
4902
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4025
4903
  });
4026
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4027
- const status = await response.json();
4028
- if (validator) return softValidate(validator, status);
4029
- return status;
4030
- };
4031
- this.fetchGetJSON = async (endpoint, validator) => {
4032
- const response = await this.host.fetch(endpoint);
4033
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4904
+ const text = await response.text();
4905
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4906
+ if (text === "") return null;
4907
+ try {
4908
+ return JSON.parse(text);
4909
+ } catch {
4910
+ return text;
4911
+ }
4912
+ };
4913
+ this.getJSON = async (route, validator) => {
4914
+ const response = await this.host.fetch(route);
4915
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4034
4916
  const jsonResult = await response.json();
4035
4917
  if (validator) return softValidate(validator, jsonResult);
4036
4918
  return jsonResult;
4037
4919
  };
4038
- this.fetchGetText = async (endopint) => {
4039
- return await (await this.host.fetch(endopint)).text();
4920
+ this.getValid = async (route, schema) => {
4921
+ const res = schema(await this.getJSON(route));
4922
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4923
+ return res;
4040
4924
  };
4041
4925
  }
4042
4926
  get registry() {
@@ -5900,26 +6784,8 @@ var ComfyHost = class {
5900
6784
  constructor(data) {
5901
6785
  this.data = data;
5902
6786
  this.uploader = new ComfyUploader(this);
5903
- this.matchRequirements = (requirements) => {
5904
- const repo = comfyts.registry;
5905
- for (const req of requirements) {
5906
- if (req.optional) continue;
5907
- if (req.type === "customNodesByNodeKey") {
5908
- if (!(repo.plugins_byNodeKey.get(req.nodeName) ?? []).find((i) => this.manager.isPluginInstalled(i.title))) return false;
5909
- } else if (req.type === "customNodesByTitle") {
5910
- const plugin = repo.plugins_byTitle.get(req.title);
5911
- if (plugin == null) continue;
5912
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5913
- } else if (req.type === "customNodesByURI") {
5914
- const plugin = repo.plugins_byFile.get(req.uri);
5915
- if (plugin == null) continue;
5916
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5917
- } else if (req.type === "modelInManager") {
5918
- if (!this.manager.isModelInstalled(req.modelName)) return false;
5919
- }
5920
- }
5921
- return true;
5922
- };
6787
+ this.matchRequirements = (requirements) => this.manager.matchRequirements(requirements);
6788
+ this.checkRequirements = (requirements) => this.manager.checkRequirements(requirements);
5923
6789
  this.serverLogs = [];
5924
6790
  this.wantLog = true;
5925
6791
  this.maxLogs = 200;
@@ -6183,6 +7049,7 @@ var ComfyHost = class {
6183
7049
  this.onLogs = null;
6184
7050
  this.comfySessionId = "temp";
6185
7051
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7052
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6186
7053
  this.status = null;
6187
7054
  this.lastWsMessageAt = null;
6188
7055
  this.base = parseHostBase(this.data);
@@ -6422,9 +7289,26 @@ var ComfyHost = class {
6422
7289
  }
6423
7290
  return;
6424
7291
  }
6425
- const msg_ = JSON.parse(String(e.data));
6426
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6427
- if (msg_.type === "crystools.monitor") return;
7292
+ let msg_ = JSON.parse(String(e.data));
7293
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7294
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7295
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7296
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7297
+ const key = eventType ?? "<no type>";
7298
+ if (this._unknownWsEventTypes.has(key)) return;
7299
+ this._unknownWsEventTypes.add(key);
7300
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7301
+ return;
7302
+ }
7303
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7304
+ const data = Reflect.get(rec, "data");
7305
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7306
+ type: eventType,
7307
+ data: {
7308
+ ...data,
7309
+ prompt_id: this.activePromptID
7310
+ }
7311
+ };
6428
7312
  }
6429
7313
  const res = WsMsg_ark(msg_);
6430
7314
  if (res instanceof type.errors) {
@@ -6438,7 +7322,11 @@ var ComfyHost = class {
6438
7322
  this.comfySessionId = msg.data.sid;
6439
7323
  this._sessionResolve?.();
6440
7324
  this._sessionResolve = null;
6441
- if (sidChanged) this.onSession?.(msg.data.sid);
7325
+ if (sidChanged) {
7326
+ this._unknownWsEventTypes.clear();
7327
+ this._unknownBinaryFrameTypes.clear();
7328
+ this.onSession?.(msg.data.sid);
7329
+ }
6442
7330
  }
6443
7331
  this.status = msg.data.status;
6444
7332
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6453,7 +7341,7 @@ var ComfyHost = class {
6453
7341
  this.routeOrBuffer(activePromptID, msg);
6454
7342
  return;
6455
7343
  }
6456
- 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") {
7344
+ 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") {
6457
7345
  this.routeOrBuffer(msg.data.prompt_id, msg);
6458
7346
  return;
6459
7347
  }
@@ -6465,8 +7353,6 @@ var ComfyHost = class {
6465
7353
  this.onLogs?.(msg.data);
6466
7354
  return;
6467
7355
  }
6468
- console.log("❌", "Unknown message:", msg);
6469
- logError("Unknown message type: " + JSON.stringify(msg.type));
6470
7356
  }
6471
7357
  };
6472
7358
  //#endregion
@@ -6795,6 +7681,7 @@ const _getKnownModels = (DB) => {
6795
7681
  }
6796
7682
  const knownModelList = canonical.concat(extraModels.models);
6797
7683
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7684
+ DB.modelRows = knownModelList;
6798
7685
  if (DB.opts.genTypes) {
6799
7686
  let out1 = "";
6800
7687
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6963,6 +7850,7 @@ var ComfyRegistry = class ComfyRegistry {
6963
7850
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6964
7851
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6965
7852
  this.knownModels = /* @__PURE__ */ new Map();
7853
+ this.modelRows = [];
6966
7854
  this.alterations = [];
6967
7855
  this.githubStats = /* @__PURE__ */ new Map();
6968
7856
  this.report = new ManagerParseReport();