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.cjs CHANGED
@@ -134,7 +134,7 @@ function createNodeStorage() {
134
134
  }
135
135
  //#endregion
136
136
  //#region package.json
137
- var version = "2.17.1";
137
+ var version = "2.18.1";
138
138
  //#endregion
139
139
  //#region src/litegraph/LiteGraphLinkID.ts
140
140
  const asLiteGraphLinkID = (id) => id;
@@ -154,8 +154,55 @@ const bang = (x, msg = "") => {
154
154
  /** boundary sentinel ids inside definition link tables */
155
155
  const SUBGRAPH_INPUT_NODE_ID = -10;
156
156
  const SUBGRAPH_OUTPUT_NODE_ID = -20;
157
- /** 48 corpus files nest defs inside defs; a self-referencing def would loop forever */
158
- const MAX_EXPANSION_PASSES = 32;
157
+ /** expanded node count above which a file is refused before expanding: the largest official
158
+ * template expands to 575 nodes, and fan-out nesting grows geometrically without any cycle */
159
+ const MAX_EXPANDED_NODES = 1e5;
160
+ /**
161
+ * before any expansion: the definitions as a graph (def → the defs its NORMAL-mode instances name,
162
+ * the only ones expansion follows). A cycle reachable from the root is refused with the defs it
163
+ * runs through, and the expanded size is counted, not built, and refused above
164
+ * MAX_EXPANDED_NODES. One explicit stack, no recursion: the file decides the depth
165
+ */
166
+ const checkExpansion = (wf, defs) => {
167
+ const children = (nodes) => nodes.filter((n) => n.mode === "normal" && defs.has(n.type)).map((n) => n.type);
168
+ const own = (nodes) => nodes.filter((n) => !(n.mode === "normal" && defs.has(n.type))).length;
169
+ const name = (id) => JSON.stringify(defs.get(id)?.name ?? id);
170
+ const cap = (n) => Math.min(n, 100001);
171
+ const size = /* @__PURE__ */ new Map();
172
+ const onPath = /* @__PURE__ */ new Set();
173
+ for (const root of new Set(children(wf.nodes))) {
174
+ if (size.has(root)) continue;
175
+ const stack = [{
176
+ id: root,
177
+ kids: children(bang(defs.get(root)).nodes),
178
+ next: 0
179
+ }];
180
+ onPath.add(root);
181
+ while (stack.length > 0) {
182
+ const top = bang(stack[stack.length - 1]);
183
+ const kid = top.kids[top.next++];
184
+ if (kid == null) {
185
+ const total = top.kids.reduce((acc, k) => cap(acc + (size.get(k) ?? 0)), own(bang(defs.get(top.id)).nodes));
186
+ size.set(top.id, total);
187
+ onPath.delete(top.id);
188
+ stack.pop();
189
+ continue;
190
+ }
191
+ if (size.has(kid)) continue;
192
+ if (onPath.has(kid)) {
193
+ const from = stack.findIndex((frame) => frame.id === kid);
194
+ 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) });
195
+ }
196
+ onPath.add(kid);
197
+ stack.push({
198
+ id: kid,
199
+ kids: children(bang(defs.get(kid)).nodes),
200
+ next: 0
201
+ });
202
+ }
203
+ }
204
+ 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)`);
205
+ };
159
206
  /**
160
207
  * widget-kind fallback when a def input slot has no boundary target carrying a
161
208
  * widget marker: these litegraph slot types carry widget values. LOCAL copy on
@@ -178,11 +225,12 @@ const PRIMITIVE_WIDGET_TYPES = /* @__PURE__ */ new Set([
178
225
  * passthrough walk, which needs no interior.
179
226
  */
180
227
  const expandSubgraphs = (wf, defs) => {
228
+ checkExpansion(wf, defs);
181
229
  let passes = 0;
182
230
  while (true) {
183
231
  const expandable = wf.nodes.filter((n) => defs.has(n.type) && n.mode !== "bypassed");
184
232
  if (expandable.length === 0) return wf;
185
- if (++passes > MAX_EXPANSION_PASSES) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion did not terminate after ${MAX_EXPANSION_PASSES} passes — self-referencing definitions?`);
233
+ if (++passes > defs.size + 1) throw new WorkflowNormalizeError("subgraph-cycle", `subgraph expansion still had instances after ${passes - 1} passes over ${defs.size} definitions`);
186
234
  for (const instance of expandable) if (instance.mode === "muted") dropMutedInstance(wf, instance);
187
235
  else expandOneInstance(wf, instance, bang(defs.get(instance.type)));
188
236
  }
@@ -290,7 +338,8 @@ const expandOneInstance = (wf, instance, def) => {
290
338
  name: i.name,
291
339
  type: i.type,
292
340
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
293
- widgetName: i.widgetName
341
+ widgetName: i.widgetName,
342
+ widgetSource: i.widgetSource
294
343
  })),
295
344
  outputs: inner.outputs.map((o) => ({
296
345
  name: o.name,
@@ -331,6 +380,20 @@ const expandOneInstance = (wf, instance, def) => {
331
380
  wf.links = wf.links.filter((l) => !dead.has(l.id));
332
381
  pruneDeadLinkRefs(wf, dead);
333
382
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
383
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
384
+ if (outerLinkIntoDefSlot.has(slot)) continue;
385
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
386
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
387
+ if (source == null || sourceInput == null) continue;
388
+ for (const t of targets) {
389
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
390
+ if (input == null || input.widgetName != null || input.link != null) continue;
391
+ input.widgetSource = {
392
+ nodeId: source.nodeId,
393
+ inputName: sourceInput.name
394
+ };
395
+ }
396
+ }
334
397
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
335
398
  wf.nodes.push(...splicedNodes);
336
399
  wf.links.push(...splicedLinks);
@@ -442,7 +505,7 @@ const LiteGraphNodeInput_ark = (0, arktype.type)({
442
505
  type: "string",
443
506
  "link?": LiteGraphLinkID_.or(arktype.type.null),
444
507
  "shape?": "number",
445
- "label?": "string",
508
+ "label?": arktype.type.string.or(arktype.type.null),
446
509
  "widget?": (0, arktype.type)({
447
510
  name: "string",
448
511
  "config?": "unknown"
@@ -459,7 +522,7 @@ const LiteGraphNodeOutput_ark = (0, arktype.type)({
459
522
  type: "string",
460
523
  "links?": LiteGraphLinkID_.array().or(arktype.type.null),
461
524
  "shape?": "number",
462
- "slot_index?": LiteGraphSlotIndex_
525
+ "slot_index?": LiteGraphSlotIndex_.or(arktype.type.null)
463
526
  });
464
527
  //#endregion
465
528
  //#region src/litegraph/LiteGraphNode.ts
@@ -529,7 +592,7 @@ const LiteGraphSubgraphDef_ark = (0, arktype.type)({
529
592
  const LiteGraphJSON_ark = (0, arktype.type)({
530
593
  "id?": "string",
531
594
  "revision?": "number",
532
- "last_node_id?": "number",
595
+ "last_node_id?": "number | string",
533
596
  "last_link_id?": "number",
534
597
  "state?": arktype.type.Record("string", "unknown"),
535
598
  nodes: LiteGraphNode_ark.array(),
@@ -628,7 +691,8 @@ const normalizeInput = (i) => {
628
691
  name: i.name,
629
692
  type: i.type,
630
693
  link: i.link ?? null,
631
- widgetName: i.widget?.name ?? null
694
+ widgetName: i.widget?.name ?? null,
695
+ widgetSource: null
632
696
  };
633
697
  };
634
698
  const normalizeOutput = (o) => {
@@ -801,6 +865,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
801
865
  python_module: "nodes"
802
866
  };
803
867
  //#endregion
868
+ //#region src/utils/exhaust.ts
869
+ function exhaust(x) {
870
+ return x;
871
+ }
872
+ //#endregion
804
873
  //#region src/sdk-generator/inputWidgetKind.ts
805
874
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
806
875
  /**
@@ -869,6 +938,14 @@ const parseContainer = (template) => {
869
938
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
870
939
  };
871
940
  };
941
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
942
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
943
+ const parseGroup = (o, template) => ({
944
+ kind: "dynamic-group",
945
+ fields: flattenInputSections(template),
946
+ min: typeof o["min"] === "number" ? o["min"] : 0,
947
+ max: typeof o["max"] === "number" ? o["max"] : 20
948
+ });
872
949
  /**
873
950
  * the single template sub-input's slot type of an autogrow container
874
951
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -943,11 +1020,12 @@ const classifyWidgetInput = (p) => {
943
1020
  };
944
1021
  }
945
1022
  const template = o?.["template"];
946
- if (isRecord$1(template)) {
1023
+ if (o != null && isRecord$1(template)) {
947
1024
  if (isRecord$1(template["input"])) return parseContainer(template);
1025
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
948
1026
  return { kind: "slot" };
949
1027
  }
950
- if (o?.["socketless"] === true) return {
1028
+ if (typeof o?.["socketless"] === "boolean") return {
951
1029
  kind: "widget",
952
1030
  consumes: 1,
953
1031
  strictValues: false,
@@ -1047,6 +1125,8 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1047
1125
  if (node.widgets.positional.length > 0) PRIMITIVE_VALUES[node.id] = node.widgets.positional[0];
1048
1126
  else if (Object.hasOwn(node.widgets.named, "value")) PRIMITIVE_VALUES[node.id] = node.widgets.named["value"];
1049
1127
  }
1128
+ const linksById = new Map(workflow.links.map((l) => [l.id, l]));
1129
+ const nodesById = new Map(workflow.nodes.map((n) => [n.id, n]));
1050
1130
  for (const node of workflow.nodes) {
1051
1131
  if (isNeverExecuted(node)) continue;
1052
1132
  if (node.mode !== "normal") continue;
@@ -1120,18 +1200,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1120
1200
  inputs[p.path] = key;
1121
1201
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1122
1202
  };
1203
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1204
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1205
+ const consumeDynamicGroup = (p) => {
1206
+ const r = resolveWidgetValue({
1207
+ promptName: p.path,
1208
+ consumes: 1,
1209
+ prefixLen: 0
1210
+ });
1211
+ const saved = r.filled ? p.min : r.value;
1212
+ 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);
1213
+ const rows = Math.max(p.min, saved);
1214
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1215
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1216
+ };
1123
1217
  const consumeBranchInput = (subPath, sub) => {
1124
1218
  const kind = classifyWidgetInput({
1125
- name: sub.name,
1219
+ name: subPath,
1126
1220
  type: sub.type,
1127
1221
  opts: sub.opts
1128
1222
  });
1129
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1130
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1131
- path: subPath,
1132
- options: kind.options,
1133
- defaultKey: kind.defaultKey
1134
- });
1223
+ switch (kind.kind) {
1224
+ case "slot":
1225
+ case "dynamic-container": return;
1226
+ case "dynamic-combo": return consumeDynamicCombo({
1227
+ path: subPath,
1228
+ options: kind.options,
1229
+ defaultKey: kind.defaultKey
1230
+ });
1231
+ case "dynamic-group": return consumeDynamicGroup({
1232
+ path: subPath,
1233
+ fields: kind.fields,
1234
+ min: kind.min,
1235
+ max: kind.max
1236
+ });
1237
+ case "widget": break;
1238
+ default: return exhaust(kind);
1239
+ }
1135
1240
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1136
1241
  consumePlainWidget({
1137
1242
  promptName: subPath,
@@ -1153,32 +1258,56 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1153
1258
  strictValues: true,
1154
1259
  prefixValues: []
1155
1260
  };
1156
- if (kind.kind === "widget") consumePlainWidget({
1157
- promptName: field.nameInComfy,
1158
- typeName: field.typeName,
1159
- opts: field.opts,
1160
- consumes: kind.consumes,
1161
- prefixLen: kind.prefixValues.length,
1162
- strict: kind.strictValues,
1163
- linkedInput: input
1164
- });
1165
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1166
- path: field.nameInComfy,
1167
- options: kind.options,
1168
- defaultKey: kind.defaultKey
1169
- });
1170
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1171
- const iname = `${field.nameInComfy}.${instName}`;
1172
- 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);
1173
- }
1174
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1175
- 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);
1261
+ switch (kind.kind) {
1262
+ case "widget":
1263
+ consumePlainWidget({
1264
+ promptName: field.nameInComfy,
1265
+ typeName: field.typeName,
1266
+ opts: field.opts,
1267
+ consumes: kind.consumes,
1268
+ prefixLen: kind.prefixValues.length,
1269
+ strict: kind.strictValues,
1270
+ linkedInput: input
1271
+ });
1272
+ break;
1273
+ case "dynamic-combo":
1274
+ consumeDynamicCombo({
1275
+ path: field.nameInComfy,
1276
+ options: kind.options,
1277
+ defaultKey: kind.defaultKey
1278
+ });
1279
+ break;
1280
+ case "dynamic-group":
1281
+ consumeDynamicGroup({
1282
+ path: field.nameInComfy,
1283
+ fields: kind.fields,
1284
+ min: kind.min,
1285
+ max: kind.max
1286
+ });
1287
+ break;
1288
+ case "dynamic-container":
1289
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1290
+ const iname = `${field.nameInComfy}.${instName}`;
1291
+ 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);
1292
+ }
1293
+ break;
1294
+ case "slot":
1295
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1296
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1297
+ promptName: field.nameInComfy,
1298
+ strict: false
1299
+ });
1300
+ break;
1301
+ }
1302
+ 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);
1303
+ break;
1304
+ default:
1176
1305
  }
1177
1306
  }
1178
1307
  const getParentNode = (linkId) => {
1179
- const link = workflow.links.find((link) => link.id === linkId);
1308
+ const link = linksById.get(linkId);
1180
1309
  if (link == null) throw new WorkflowConvertError("dangling-link", `node ${node.id}(${node.type}) references a non-existing link (id=${linkId})`, node);
1181
- const parentNode = workflow.nodes.find((n) => n.id === link.originId);
1310
+ const parentNode = nodesById.get(link.originId);
1182
1311
  if (parentNode == null) throw new WorkflowConvertError("dangling-link", `link ${linkId} references a non-existent parent node ${link.originId}`, node);
1183
1312
  return {
1184
1313
  node: parentNode,
@@ -1278,6 +1407,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1278
1407
  class_type: node.type
1279
1408
  };
1280
1409
  }
1410
+ for (const node of workflow.nodes) {
1411
+ const own = prompt[String(node.id)];
1412
+ if (own == null) continue;
1413
+ for (const ipt of node.inputs) {
1414
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1415
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1416
+ if (value !== void 0) own.inputs[ipt.name] = value;
1417
+ }
1418
+ }
1419
+ const missing = /* @__PURE__ */ new Map();
1420
+ for (const node of workflow.nodes) {
1421
+ const own = prompt[String(node.id)];
1422
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1423
+ if (own == null || nodeSchema == null) continue;
1424
+ for (const field of nodeSchema.inputs) {
1425
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1426
+ const kind = classifySchemaInput(field).kind;
1427
+ if (kind !== "slot" && kind !== "widget") continue;
1428
+ missing.set(String(node.id), {
1429
+ node,
1430
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1431
+ });
1432
+ break;
1433
+ }
1434
+ }
1435
+ if (missing.size > 0) {
1436
+ const consumers = /* @__PURE__ */ new Map();
1437
+ for (const [id, n] of Object.entries(prompt)) for (const value of Object.values(n.inputs)) if (Array.isArray(value) && typeof value[0] === "string") {
1438
+ const list = consumers.get(value[0]) ?? [];
1439
+ list.push(id);
1440
+ consumers.set(value[0], list);
1441
+ }
1442
+ const blocked = new Set(missing.keys());
1443
+ const queue = [...blocked];
1444
+ for (let head = 0; head < queue.length; head++) for (const next of consumers.get(queue[head] ?? "") ?? []) if (!blocked.has(next)) {
1445
+ blocked.add(next);
1446
+ queue.push(next);
1447
+ }
1448
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1449
+ const dropped = outputs.filter((id) => blocked.has(id));
1450
+ const first = missing.values().next().value;
1451
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1452
+ 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("; ")}`);
1453
+ }
1281
1454
  return prompt;
1282
1455
  };
1283
1456
  //#endregion
@@ -1458,21 +1631,37 @@ var ComfyNode = class ComfyNode {
1458
1631
  _convertPromptExtToPrompt(promptExt) {
1459
1632
  const inputs = {};
1460
1633
  const _done = /* @__PURE__ */ new Set();
1461
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1634
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1462
1635
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1463
1636
  for (const i of this.$schema.inputs) {
1464
1637
  _done.add(i.nameInComfy);
1465
1638
  const kind = classifySchemaInput(i);
1466
- if (kind.kind === "dynamic-combo") {
1467
- this._writeDynamicCombo({
1468
- name: i.nameInComfy,
1469
- options: kind.options,
1470
- defaultKey: kind.defaultKey,
1471
- provided: promptExt.inputs,
1472
- out: inputs,
1473
- claimed: _comboBranchKeys
1474
- });
1475
- continue;
1639
+ switch (kind.kind) {
1640
+ case "dynamic-combo":
1641
+ this._writeDynamicCombo({
1642
+ name: i.nameInComfy,
1643
+ options: kind.options,
1644
+ defaultKey: kind.defaultKey,
1645
+ provided: promptExt.inputs,
1646
+ out: inputs,
1647
+ claimed: _comboBranchKeys
1648
+ });
1649
+ continue;
1650
+ case "dynamic-group":
1651
+ this._writeDynamicGroup({
1652
+ name: i.nameInComfy,
1653
+ fields: kind.fields,
1654
+ min: kind.min,
1655
+ max: kind.max,
1656
+ provided: promptExt.inputs,
1657
+ out: inputs,
1658
+ claimed: _comboBranchKeys
1659
+ });
1660
+ continue;
1661
+ case "widget":
1662
+ case "slot":
1663
+ case "dynamic-container": break;
1664
+ default:
1476
1665
  }
1477
1666
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1478
1667
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1511,6 +1700,42 @@ var ComfyNode = class ComfyNode {
1511
1700
  }) : this.serializeValue(dotted, given);
1512
1701
  }
1513
1702
  }
1703
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1704
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1705
+ * keys are already the rows: they pass through the rest loop untouched */
1706
+ _writeDynamicGroup(p) {
1707
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1708
+ const raw = p.provided[p.name];
1709
+ const prefix = `${p.name}.`;
1710
+ if (raw == null) {
1711
+ 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)`);
1712
+ return;
1713
+ }
1714
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1715
+ if (!Array.isArray(raw)) {
1716
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1717
+ return;
1718
+ }
1719
+ 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}`);
1720
+ raw.forEach((row, ix) => {
1721
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1722
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1723
+ return;
1724
+ }
1725
+ const given = new Map(Object.entries(row));
1726
+ for (const field of p.fields) {
1727
+ const dotted = `${p.name}.${ix}.${field.name}`;
1728
+ const value = given.get(field.name);
1729
+ p.out[dotted] = value == null ? defaultValueForWidget({
1730
+ type: typeof field.type === "string" ? field.type : "COMBO",
1731
+ opts: field.opts,
1732
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1733
+ }) : this.serializeValue(dotted, value);
1734
+ given.delete(field.name);
1735
+ }
1736
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1737
+ });
1738
+ }
1514
1739
  /** return the list of nodes piped into this node */
1515
1740
  _incomingNodes() {
1516
1741
  const incomingNodes = [];
@@ -1654,6 +1879,12 @@ var ComfyNode = class ComfyNode {
1654
1879
  const kind = classifySchemaInput(decl);
1655
1880
  const slotType = containerInstanceSlotType(decl.opts);
1656
1881
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1882
+ if (kind.kind === "dynamic-group") {
1883
+ const rest = name.slice(dot + 1);
1884
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1885
+ const field = kind.fields.find((f) => f.name === fieldName);
1886
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1887
+ }
1657
1888
  }
1658
1889
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1659
1890
  }
@@ -1737,44 +1968,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1737
1968
  const convertNodeToLiteGraphNode = (ctx, node) => {
1738
1969
  const inputs = [];
1739
1970
  const widgets_values = [];
1740
- const pushLinked = (name, type, link, shape) => {
1971
+ const pushLinked = (name, type, link, extra = {}) => {
1741
1972
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1742
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1743
- inputs.push(shape == null ? {
1973
+ const input = {
1744
1974
  name,
1745
1975
  type,
1746
- link: linkId
1747
- } : {
1976
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1977
+ };
1978
+ if (extra.shape != null) input.shape = extra.shape;
1979
+ if (extra.widget === true) input.widget = { name };
1980
+ inputs.push(input);
1981
+ };
1982
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1983
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1984
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1985
+ * never disagree on the run length */
1986
+ const pushWidgetRun = (kind, raw, opts) => {
1987
+ widgets_values.push(...kind.prefixValues, raw);
1988
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1989
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1990
+ };
1991
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1992
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1993
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1994
+ const writeInput = (p) => {
1995
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1996
+ switch (p.kind.kind) {
1997
+ case "widget":
1998
+ if (_isLink(p.value)) {
1999
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
2000
+ pushWidgetRun(p.kind, defaultValueForWidget({
2001
+ type: p.typeName,
2002
+ opts: p.opts
2003
+ }), p.opts);
2004
+ } else pushWidgetRun(p.kind, p.value, p.opts);
2005
+ return;
2006
+ case "slot":
2007
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
2008
+ else inputs.push({
2009
+ name: p.name,
2010
+ type: p.typeName,
2011
+ link: null
2012
+ });
2013
+ return;
2014
+ case "dynamic-combo": {
2015
+ const kind = p.kind;
2016
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
2017
+ const option = kind.options.find((o) => o.key === key);
2018
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
2019
+ widgets_values.push(key);
2020
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
2021
+ return;
2022
+ }
2023
+ case "dynamic-container": {
2024
+ const type = containerInstanceSlotType(p.opts) ?? "*";
2025
+ for (const instance of p.kind.instanceNames) {
2026
+ const name = `${p.name}.${instance}`;
2027
+ const value = node.json.inputs[name];
2028
+ if (value == null) continue;
2029
+ const raw = node.serializeValue(name, value);
2030
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
2031
+ pushLinked(name, type, raw, { shape: 7 });
2032
+ }
2033
+ return;
2034
+ }
2035
+ case "dynamic-group": {
2036
+ const prefix = `${p.name}.`;
2037
+ let rows = 0;
2038
+ for (const key of Object.keys(node.json.inputs)) {
2039
+ if (!key.startsWith(prefix)) continue;
2040
+ const row = Number(key.slice(prefix.length).split(".")[0]);
2041
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
2042
+ }
2043
+ widgets_values.push(rows);
2044
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
2045
+ return;
2046
+ }
2047
+ default: p.kind;
2048
+ }
2049
+ };
2050
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
2051
+ * value is the widget's schema default rather than serializeValue's */
2052
+ const writeSub = (name, sub) => {
2053
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
2054
+ const raw = node.json.inputs[name];
2055
+ writeInput({
1748
2056
  name,
1749
- type,
1750
- shape,
1751
- link: linkId
2057
+ kind: classifyWidgetInput({
2058
+ name,
2059
+ type: sub.type,
2060
+ opts: sub.opts
2061
+ }),
2062
+ typeName,
2063
+ opts: sub.opts,
2064
+ value: raw === void 0 ? defaultValueForWidget({
2065
+ type: typeName,
2066
+ opts: sub.opts
2067
+ }) : raw
1752
2068
  });
1753
2069
  };
1754
2070
  for (const ipt of node.$schema.inputs) {
1755
2071
  const kind = classifySchemaInput(ipt);
1756
- if (kind.kind === "dynamic-container") {
1757
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1758
- for (const instance of kind.instanceNames) {
1759
- const name = `${ipt.nameInComfy}.${instance}`;
1760
- const value = node.json.inputs[name];
1761
- if (value == null) continue;
1762
- const raw = node.serializeValue(name, value);
1763
- 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`);
1764
- pushLinked(name, type, raw, 7);
1765
- }
1766
- continue;
1767
- }
1768
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1769
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1770
- else if (kind.kind === "widget") {
1771
- widgets_values.push(...kind.prefixValues, raw);
1772
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1773
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1774
- } else inputs.push({
2072
+ const raw = node.json.inputs[ipt.nameInComfy];
2073
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
2074
+ writeInput({
1775
2075
  name: ipt.nameInComfy,
1776
- type: ipt.typeName,
1777
- link: null
2076
+ kind,
2077
+ typeName: ipt.typeName,
2078
+ opts: ipt.opts,
2079
+ value
1778
2080
  });
1779
2081
  }
1780
2082
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1960,11 +2262,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1960
2262
  return resultSuccess(txt_chunks);
1961
2263
  };
1962
2264
  //#endregion
1963
- //#region src/utils/exhaust.ts
1964
- function exhaust(x) {
1965
- return x;
1966
- }
1967
- //#endregion
1968
2265
  //#region src/utils/sha1.ts
1969
2266
  function sha1Hex(data) {
1970
2267
  const ml = data.length;
@@ -2102,16 +2399,17 @@ const types$1 = (0, arktype.scope)({
2102
2399
  },
2103
2400
  _WsMsgExecutedData: {
2104
2401
  node: "ComfyNodeID",
2105
- output: {
2106
- "previews?": [{ filepath: "string" }, "[]"],
2107
- "images?": "ComfyImageInfo[]",
2108
- "audio?": "ComfyImageInfo[]",
2109
- "video?": "ComfyImageInfo[]",
2110
- "gifs?": "ComfyImageInfo[]",
2111
- "text?": "unknown[]"
2112
- },
2402
+ output: "_WsMsgExecutedOutput | null",
2113
2403
  prompt_id: "PromptID"
2114
2404
  },
2405
+ _WsMsgExecutedOutput: {
2406
+ "previews?": [{ filepath: "string" }, "[]"],
2407
+ "images?": "ComfyImageInfo[]",
2408
+ "audio?": "ComfyImageInfo[]",
2409
+ "video?": "ComfyImageInfo[]",
2410
+ "gifs?": "ComfyImageInfo[]",
2411
+ "text?": "unknown[]"
2412
+ },
2115
2413
  WsMsgExecuted: {
2116
2414
  type: "'executed'",
2117
2415
  data: "_WsMsgExecutedData"
@@ -2133,12 +2431,22 @@ const types$1 = (0, arktype.scope)({
2133
2431
  exception_type: "string",
2134
2432
  traceback: "string[]",
2135
2433
  current_inputs: "Record<string, unknown>",
2136
- current_outputs: "Record<string, unknown>"
2434
+ current_outputs: "ComfyNodeID[]"
2137
2435
  },
2138
2436
  WsMsgExecutionError: {
2139
2437
  type: "'execution_error'",
2140
2438
  data: "_WsMsgExecutionErrorData"
2141
2439
  },
2440
+ _WsMsgExecutionInterruptedData: {
2441
+ prompt_id: "PromptID",
2442
+ node_id: "ComfyNodeID",
2443
+ node_type: "string",
2444
+ executed: "ComfyNodeID[]"
2445
+ },
2446
+ WsMsgExecutionInterrupted: {
2447
+ type: "'execution_interrupted'",
2448
+ data: "_WsMsgExecutionInterruptedData"
2449
+ },
2142
2450
  WSMsgManagerFeedbackData: { data: "string" },
2143
2451
  WSMsgManagerFeedback: {
2144
2452
  type: "'manager-terminal-feedback'",
@@ -2168,11 +2476,51 @@ const types$1 = (0, arktype.scope)({
2168
2476
  type: "'progress_state'",
2169
2477
  data: "_WsMsgProgressStateData"
2170
2478
  },
2171
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2479
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2172
2480
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2173
2481
  }).export();
2174
2482
  const PromptInfo_ark = (0, arktype.type)({ prompt_id: types$1.PromptID }).as();
2175
2483
  const WsMsg_ark = types$1.WsMsg;
2484
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2485
+ const ROUTED_WS_EVENT_TYPES = [
2486
+ "status",
2487
+ "manager-terminal-feedback",
2488
+ "logs",
2489
+ "execution_start",
2490
+ "execution_cached",
2491
+ "executing",
2492
+ "progress",
2493
+ "progress_state",
2494
+ "executed",
2495
+ "execution_error",
2496
+ "execution_interrupted",
2497
+ "execution_success"
2498
+ ];
2499
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2500
+ * before validation, never logged (architecture.md, ws events) */
2501
+ const IGNORED_WS_EVENT_TYPES = [
2502
+ "feature_flags",
2503
+ "agent_status",
2504
+ "asset_export",
2505
+ "assets.seed.started",
2506
+ "assets.seed.progress",
2507
+ "assets.seed.fast_complete",
2508
+ "assets.seed.enrich_complete",
2509
+ "assets.seed.completed",
2510
+ "assets.seed.cancelled",
2511
+ "assets.seed.error",
2512
+ "assets.seed.paused",
2513
+ "assets.seed.resumed",
2514
+ "cm-queue-status",
2515
+ "cm-api-try-install-customnode",
2516
+ "cm-task-started",
2517
+ "cm-task-completed",
2518
+ "crystools.monitor"
2519
+ ];
2520
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2521
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2522
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2523
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2176
2524
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2177
2525
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2178
2526
  //#endregion
@@ -2462,6 +2810,10 @@ var ComfyExecution = class {
2462
2810
  else if (msg.type === "progress") graph.onProgress(msg);
2463
2811
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2464
2812
  else if (msg.type === "execution_error") return void this.onError(msg);
2813
+ else if (msg.type === "execution_interrupted") return void this._finish({
2814
+ status: "Failure",
2815
+ error: msg
2816
+ });
2465
2817
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2466
2818
  else {
2467
2819
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3375,6 +3727,15 @@ const dynamicComboUnion = (p) => {
3375
3727
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3376
3728
  }).join(" | ")})`;
3377
3729
  };
3730
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3731
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3732
+ const dynamicGroupRow = (fields) => {
3733
+ return `{ ${fields.map((e) => {
3734
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3735
+ const optional = !e.required || opts?.["default"] !== void 0;
3736
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3737
+ }).join("; ")} }`;
3738
+ };
3378
3739
  /**
3379
3740
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3380
3741
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3423,6 +3784,8 @@ function codegenSDK(opts) {
3423
3784
  b.deindent();
3424
3785
  p(`// #endregion`);
3425
3786
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3787
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3788
+ const groupRows = [];
3426
3789
  p(`interface IN {`);
3427
3790
  b.indent();
3428
3791
  for (const n of nodes) {
@@ -3430,23 +3793,37 @@ function codegenSDK(opts) {
3430
3793
  const comboSuffixes = [];
3431
3794
  for (const i of n.inputs) {
3432
3795
  const kind = classifySchemaInput(i);
3433
- if (kind.kind === "dynamic-container") {
3434
- const instType = containerInstanceSlotType(i.opts);
3435
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3436
- const opt = ix >= kind.requiredCount ? "?" : "";
3437
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3438
- });
3439
- continue;
3440
- }
3441
- if (kind.kind === "dynamic-combo") {
3442
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3443
- comboSuffixes.push(dynamicComboUnion({
3444
- name: i.nameInComfy,
3445
- nameEscaped: i.nameInComfyEscaped,
3446
- options: kind.options,
3447
- keyOptional: optsDyn?.default !== void 0 || !i.required
3448
- }));
3449
- continue;
3796
+ switch (kind.kind) {
3797
+ case "dynamic-container": {
3798
+ const instType = containerInstanceSlotType(i.opts);
3799
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3800
+ const opt = ix >= kind.requiredCount ? "?" : "";
3801
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3802
+ });
3803
+ continue;
3804
+ }
3805
+ case "dynamic-combo": {
3806
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3807
+ comboSuffixes.push(dynamicComboUnion({
3808
+ name: i.nameInComfy,
3809
+ nameEscaped: i.nameInComfyEscaped,
3810
+ options: kind.options,
3811
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3812
+ }));
3813
+ continue;
3814
+ }
3815
+ case "dynamic-group": {
3816
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3817
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3818
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3819
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3820
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3821
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3822
+ continue;
3823
+ }
3824
+ case "widget":
3825
+ case "slot": break;
3826
+ default:
3450
3827
  }
3451
3828
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3452
3829
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3469,6 +3846,15 @@ function codegenSDK(opts) {
3469
3846
  b.deindent();
3470
3847
  p("}");
3471
3848
  p("");
3849
+ if (groupRows.length > 0) {
3850
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3851
+ p(`interface GroupRow {`);
3852
+ b.indent();
3853
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3854
+ b.deindent();
3855
+ p("}");
3856
+ p("");
3857
+ }
3472
3858
  p(`interface OUT {`);
3473
3859
  b.indent();
3474
3860
  for (const n of nodes) {
@@ -3781,9 +4167,13 @@ var ComfySchema = class {
3781
4167
  if (widgetKind?.kind === "dynamic-combo") {
3782
4168
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3783
4169
  }
4170
+ if (widgetKind?.kind === "dynamic-group") {
4171
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4172
+ }
4173
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3784
4174
  node.inputs.push({
3785
4175
  slotName: inputSlotName,
3786
- required: ipt.required && !isAutogrowContainer,
4176
+ required,
3787
4177
  nameInComfy: inputNameInComfy,
3788
4178
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3789
4179
  typeName: inputTypeName,
@@ -3859,7 +4249,12 @@ const types = (0, arktype.scope)({
3859
4249
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3860
4250
  ComfyInputSpecAlt2: ["ComfyInputType"],
3861
4251
  ComfyInputSpecAlt3: (0, arktype.type)([arktype.type.null]),
3862
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4252
+ ComfyInputSpecAlt4: [
4253
+ "ComfyInputType",
4254
+ "ComfyInputOpts",
4255
+ "unknown"
4256
+ ],
4257
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3863
4258
  ComfyInputType: `string | ComfyEnumDef`,
3864
4259
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3865
4260
  ComfyInputHiddenEntry_broken2: arktype.type.Record("string", arktype.type.unknown),
@@ -3925,10 +4320,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3925
4320
  return result;
3926
4321
  }
3927
4322
  //#endregion
4323
+ //#region src/manager/installedView.ts
4324
+ /**
4325
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4326
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4327
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4328
+ */
4329
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4330
+ const InstalledPacks_ark = arktype.type.Record("string", (0, arktype.type)({
4331
+ "cnr_id?": "string | null",
4332
+ "aux_id?": "string | null",
4333
+ enabled: "boolean"
4334
+ }));
4335
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4336
+ const PackMappings_ark = arktype.type.Record("string", (0, arktype.type)(["string[]", { "title_aux?": "string" }]));
4337
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4338
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4339
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4340
+ const attributePacks = (installed, mappings) => {
4341
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4342
+ return Object.entries(installed).map(([dir, p]) => {
4343
+ const aux = p.aux_id ?? null;
4344
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4345
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4346
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4347
+ return {
4348
+ enabled: p.enabled,
4349
+ repo,
4350
+ title,
4351
+ id: cnr ?? aux ?? dir
4352
+ };
4353
+ });
4354
+ };
4355
+ /** is this mirror row among the attributed packs, enabled? */
4356
+ const packIsInstalled = (packs, plugin) => {
4357
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4358
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4359
+ };
4360
+ const buildPluginView = (p) => {
4361
+ const packs = attributePacks(p.installed, p.mappings);
4362
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4363
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4364
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4365
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4366
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4367
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4368
+ const custom_nodes = [];
4369
+ for (const plugin of plugins) {
4370
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4371
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4372
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4373
+ title: plugin.title,
4374
+ installed: "True"
4375
+ });
4376
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4377
+ else custom_nodes.push({
4378
+ title: plugin.title,
4379
+ installed: "False"
4380
+ });
4381
+ }
4382
+ return {
4383
+ list: {
4384
+ chanel: "default",
4385
+ custom_nodes
4386
+ },
4387
+ unattributed: unattributed.map((x) => x.id)
4388
+ };
4389
+ };
4390
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4391
+ const DEFAULT_FOLDER_BY_TYPE = {
4392
+ checkpoints: "checkpoints",
4393
+ checkpoint: "checkpoints",
4394
+ unclip: "checkpoints",
4395
+ text_encoders: "text_encoders",
4396
+ clip: "text_encoders",
4397
+ vae: "vae",
4398
+ lora: "loras",
4399
+ "t2i-adapter": "controlnet",
4400
+ "t2i-style": "controlnet",
4401
+ controlnet: "controlnet",
4402
+ clip_vision: "clip_vision",
4403
+ gligen: "gligen",
4404
+ upscale: "upscale_models",
4405
+ embedding: "embeddings",
4406
+ embeddings: "embeddings",
4407
+ unet: "diffusion_models",
4408
+ diffusion_model: "diffusion_models"
4409
+ };
4410
+ /** what core `get_filename_list` lists in the standard folders */
4411
+ const LISTED_EXTENSIONS = [
4412
+ ".ckpt",
4413
+ ".pt",
4414
+ ".pt2",
4415
+ ".bin",
4416
+ ".pth",
4417
+ ".safetensors",
4418
+ ".pkl",
4419
+ ".sft"
4420
+ ];
4421
+ /**
4422
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4423
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4424
+ */
4425
+ const modelLocation = (m) => {
4426
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4427
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4428
+ if (m.save_path === "default") {
4429
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4430
+ return folder == null ? null : {
4431
+ folder,
4432
+ files: [m.filename]
4433
+ };
4434
+ }
4435
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4436
+ const folder = parts[0];
4437
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4438
+ const sub = [...parts.slice(1), m.filename].join("/");
4439
+ return {
4440
+ folder,
4441
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4442
+ };
4443
+ };
4444
+ const buildModelView = (p) => {
4445
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4446
+ const statusOf = (m) => {
4447
+ const at = modelLocation(m);
4448
+ const files = at == null ? null : listed.get(at.folder);
4449
+ if (at == null || files == null) return null;
4450
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4451
+ };
4452
+ const byName = /* @__PURE__ */ new Map();
4453
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4454
+ const models = [];
4455
+ for (const rows of byName.values()) {
4456
+ const statuses = new Set(rows.map(statusOf));
4457
+ const first = rows[0];
4458
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4459
+ if (first == null || installed == null) continue;
4460
+ models.push({
4461
+ name: first.name,
4462
+ installed,
4463
+ filename: first.filename,
4464
+ save_path: first.save_path,
4465
+ base: first.base
4466
+ });
4467
+ }
4468
+ return { models };
4469
+ };
4470
+ /** the folders the views need listed */
4471
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4472
+ //#endregion
3928
4473
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3929
4474
  const ComfyManagerAPIModelList_ark = (0, arktype.type)({ models: (0, arktype.type)({
3930
4475
  name: arktype.type.string.as(),
3931
- installed: `'False' | 'True' | 'Update'`
4476
+ installed: `'False' | 'True' | 'Update'`,
4477
+ "filename?": "string",
4478
+ "save_path?": "string",
4479
+ "base?": "string"
3932
4480
  }).array() });
3933
4481
  //#endregion
3934
4482
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3939,28 +4487,160 @@ const ComfyManagerAPIPluginList_ark = (0, arktype.type)({
3939
4487
  }).array(),
3940
4488
  chanel: "string"
3941
4489
  });
4490
+ const ComfyManagerAPIPack_ark = (0, arktype.type)({
4491
+ title: arktype.type.string.as(),
4492
+ "id?": "string",
4493
+ "files?": "string[]",
4494
+ "repository?": "string",
4495
+ "version?": "string",
4496
+ "state?": "string",
4497
+ "update-state?": "string"
4498
+ });
4499
+ const ComfyManagerAPIPackList_ark = (0, arktype.type)({
4500
+ channel: "string",
4501
+ node_packs: arktype.type.Record("string", ComfyManagerAPIPack_ark)
4502
+ });
3942
4503
  //#endregion
3943
4504
  //#region src/host/ComfyManager.ts
4505
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4506
+ const MANAGER_TIMING = {
4507
+ pollMs: 1e3,
4508
+ installTimeoutMs: 60 * 6e4,
4509
+ pollGraceMs: 12e4
4510
+ };
4511
+ /** an install the host refused or reported failed: ends the wait at once */
4512
+ var InstallFailed = class extends Error {};
4513
+ /** we lost sight of the task: the outcome is not known */
4514
+ var OutcomeUnknown = class extends Error {};
4515
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4516
+ const NOT_SERVED = {
4517
+ v3: [
4518
+ "/manager/queue/batch",
4519
+ "/manager/queue/task",
4520
+ "/manager/queue/history"
4521
+ ],
4522
+ "v4-legacy-ui": [
4523
+ "/manager/queue/install",
4524
+ "/manager/queue/task",
4525
+ "/manager/queue/history",
4526
+ "/manager/terminal"
4527
+ ],
4528
+ v4: [
4529
+ "/customnode/getlist",
4530
+ "/externalmodel/getlist",
4531
+ "/manager/queue/install",
4532
+ "/manager/queue/batch",
4533
+ "/manager/terminal"
4534
+ ]
4535
+ };
4536
+ const QueueStatus_ark = (0, arktype.type)({
4537
+ is_processing: "boolean",
4538
+ "pending_count?": "number",
4539
+ "total_count?": "number",
4540
+ "done_count?": "number"
4541
+ });
4542
+ const TaskHistory_ark = (0, arktype.type)({ history: {
4543
+ "status?": {
4544
+ status_str: "string",
4545
+ "messages?": "string[]"
4546
+ },
4547
+ "result?": "string"
4548
+ } });
4549
+ const ModelFolders_ark = (0, arktype.type)("string[]");
4550
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3944
4551
  var ComfyManager = class {
3945
- constructor(host) {
4552
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3946
4553
  this.host = host;
3947
- this.fetchPluginsAndModels = async () => {
3948
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3949
- this.pluginList = _pluginList;
3950
- this.modelList = _modelList;
4554
+ this.timing = timing;
4555
+ this.mirror = mirror;
4556
+ this.clientId = `comfy-ts-${(0, nanoid.nanoid)(8)}`;
4557
+ this._api = null;
4558
+ this.api = () => {
4559
+ if (this._api == null) {
4560
+ const probe = this.probeApi();
4561
+ this._api = probe;
4562
+ probe.catch(() => {
4563
+ if (this._api === probe) this._api = null;
4564
+ });
4565
+ }
4566
+ return this._api;
4567
+ };
4568
+ this.probeApi = async () => {
4569
+ const v4 = await this.host.fetch("/v2/manager/version");
4570
+ if (v4.ok) {
4571
+ const version = (await v4.text()).trim();
4572
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4573
+ if (!ui.ok) {
4574
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4575
+ return {
4576
+ generation: "v4",
4577
+ version
4578
+ };
4579
+ }
4580
+ const flag = await ui.json();
4581
+ return {
4582
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4583
+ version
4584
+ };
4585
+ }
4586
+ const v3 = await this.host.fetch("/manager/version");
4587
+ if (v3.ok) return {
4588
+ generation: "v3",
4589
+ version: (await v3.text()).trim()
4590
+ };
4591
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4592
+ };
4593
+ this.route = (api, route, query = "") => {
4594
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4595
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4596
+ };
4597
+ this.strategy = (api) => {
4598
+ switch (api.generation) {
4599
+ case "v3": return {
4600
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4601
+ fetchModels: () => this.listedModels(api),
4602
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4603
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4604
+ };
4605
+ case "v4-legacy-ui": return {
4606
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4607
+ fetchModels: () => this.listedModels(api),
4608
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4609
+ const route = this.route(api, "/manager/queue/batch");
4610
+ const res = await this.post(route, { install: [body] });
4611
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4612
+ 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)`);
4613
+ }),
4614
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4615
+ };
4616
+ case "v4": return {
4617
+ fetchPlugins: () => this.installedPluginView(api),
4618
+ fetchModels: () => this.installedModelView(),
4619
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4620
+ settle: (what, uiId, landed, sentId) => this.settleByHistory(api, what, uiId, landed, sentId)
4621
+ };
4622
+ }
3951
4623
  };
3952
- this.configureLogging = (mi) => {
3953
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4624
+ this.configureLogging = async (mi) => {
4625
+ const api = await this.api();
4626
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4627
+ const response = await this.host.fetch(route);
4628
+ const text = await response.text();
4629
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4630
+ return text;
3954
4631
  };
3955
4632
  this.getModelInfoFinalFilePath = (mi) => {
3956
4633
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3957
4634
  };
3958
4635
  this.restartComfyUI = async () => {
4636
+ const api = await this.api();
4637
+ this._api = null;
4638
+ const route = this.route(api, "/manager/reboot");
3959
4639
  const refusals = [];
3960
4640
  for (const method of ["POST", "GET"]) {
3961
4641
  let response;
3962
4642
  try {
3963
- response = await this.host.fetch("/manager/reboot", { method });
4643
+ response = await this.host.fetch(route, { method });
3964
4644
  } catch {
3965
4645
  return;
3966
4646
  }
@@ -3968,31 +4648,44 @@ var ComfyManager = class {
3968
4648
  refusals.push(`${method} → ${response.status}`);
3969
4649
  if (response.status !== 404) break;
3970
4650
  }
3971
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4651
+ 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`);
4652
+ };
4653
+ this.fetchPluginsAndModels = async () => {
4654
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4655
+ this.pluginList = _pluginList;
4656
+ this.modelList = _modelList;
3972
4657
  };
3973
4658
  this.modelList = null;
3974
- this.fetchModels = () => {
3975
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4659
+ this.fetchModels = async () => {
4660
+ return this.strategy(await this.api()).fetchModels();
3976
4661
  };
3977
4662
  this.fetchLogs = () => {
3978
- return this.fetchGetJSON("/internal/logs");
4663
+ return this.getJSON("/internal/logs");
3979
4664
  };
3980
4665
  this.isModelInstalled = (name) => {
3981
4666
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3982
4667
  };
3983
4668
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3984
- this.installModel = async (model) => {
4669
+ this.installModel = async (model) => await this.installModelOutcome(model) === "installed";
4670
+ this.installModelOutcome = async (model) => {
4671
+ this.modelsBeeingInstalled.add(model.name);
3985
4672
  try {
3986
- this.modelsBeeingInstalled.add(model.name);
3987
- await this.fetchPost("/model/install", model);
3988
- this.modelsBeeingInstalled.delete(model.name);
3989
- logSuccess("Model installed");
3990
- return true;
3991
- } catch (exception) {
3992
- console.error(`Install failed: / ${exception}`);
3993
- logError("Model Installation Failed");
4673
+ return await this.runInstall(`model "${model.name}"`, {
4674
+ enqueue: async (api, uiId) => {
4675
+ const body = {
4676
+ ...model,
4677
+ ui_id: uiId,
4678
+ client_id: this.clientId
4679
+ };
4680
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4681
+ },
4682
+ landed: async (s) => {
4683
+ const row = (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base);
4684
+ return row == null ? null : row.installed === "True";
4685
+ }
4686
+ });
4687
+ } finally {
3994
4688
  this.modelsBeeingInstalled.delete(model.name);
3995
- return false;
3996
4689
  }
3997
4690
  };
3998
4691
  this.getModelStatus = (modelName) => {
@@ -4022,48 +4715,239 @@ var ComfyManager = class {
4022
4715
  return "error";
4023
4716
  })();
4024
4717
  };
4718
+ this.requirementStatus = (req) => {
4719
+ const mirror = this.mirror();
4720
+ const packs = (() => {
4721
+ if (req.type === "customNodesByNodeKey") return mirror.plugins_byNodeKey.get(req.nodeName) ?? [];
4722
+ if (req.type === "customNodesByTitle") return [mirror.plugins_byTitle.get(req.title)].filter((x) => x != null);
4723
+ if (req.type === "customNodesByURI") return [mirror.plugins_byFile.get(req.uri)].filter((x) => x != null);
4724
+ return null;
4725
+ })();
4726
+ if (packs == null) return req.type === "modelInManager" ? this.getModelStatus(req.modelName) : null;
4727
+ if (packs.length === 0) return req.type === "customNodesByNodeKey" ? "unknown" : null;
4728
+ const statuses = packs.map((x) => this.getPluginStatus(x.title));
4729
+ if (statuses.some((x) => x === "installed" || x === "update-available")) return "installed";
4730
+ return statuses.every((x) => x === "not-installed") ? "not-installed" : "unknown";
4731
+ };
4732
+ this.checkRequirements = (requirements) => {
4733
+ const out = {
4734
+ missing: [],
4735
+ undecided: []
4736
+ };
4737
+ for (const req of requirements) {
4738
+ if (req.optional) continue;
4739
+ const status = this.requirementStatus(req);
4740
+ if (status === "not-installed") out.missing.push(req);
4741
+ else if (status === "unknown" || status === "error") out.undecided.push(req);
4742
+ }
4743
+ return out;
4744
+ };
4745
+ this.matchRequirements = (requirements) => {
4746
+ const check = this.checkRequirements(requirements);
4747
+ 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)" : ""));
4748
+ return check.missing.length === 0;
4749
+ };
4025
4750
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
4751
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4752
+ };
4753
+ this.installPlugin = async (plugin) => await this.installPluginOutcome(plugin) === "installed";
4754
+ this.installPluginOutcome = async (plugin) => {
4755
+ return this.runInstall(`plugin "${plugin.title}"`, {
4756
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4757
+ landed: async (_s, api) => {
4758
+ const data = await this.installedData(api);
4759
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4760
+ }
4761
+ });
4762
+ };
4763
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4764
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4765
+ if (!("node_packs" in raw)) return raw;
4766
+ const titleByRepo = /* @__PURE__ */ new Map();
4767
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4768
+ return {
4769
+ chanel: raw.channel,
4770
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4771
+ const repo = p.files?.[0];
4772
+ return {
4773
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4774
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4775
+ };
4776
+ })
4777
+ };
4778
+ };
4779
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4780
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4781
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4782
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4783
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4784
+ };
4785
+ this.listedModels = async (api) => {
4786
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4787
+ };
4788
+ this.installedData = async (api) => {
4789
+ 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)]);
4790
+ return {
4791
+ installed,
4792
+ mappings
4793
+ };
4794
+ };
4795
+ this.installedPluginView = async (api) => {
4796
+ const view = buildPluginView({
4797
+ mirror: this.mirror(),
4798
+ ...await this.installedData(api)
4799
+ });
4800
+ 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`);
4801
+ return view.list;
4802
+ };
4803
+ this.installedModelView = async () => {
4804
+ const models = this.mirror().modelRows;
4805
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4806
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4807
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4808
+ return buildModelView({
4809
+ models,
4810
+ files: new Map(lists)
4811
+ });
4812
+ };
4813
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4814
+ const url = plugin.files[0] ?? plugin.reference;
4815
+ const list = await this.fetchPluginWire(api, "cache", true);
4816
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4817
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4818
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4819
+ const [key, row] = found;
4820
+ await send({
4821
+ ...row,
4822
+ id: row.id ?? key,
4823
+ channel: list.channel,
4824
+ mode: "cache",
4825
+ ui_id: uiId,
4826
+ skip_post_install: false
4827
+ });
4828
+ };
4829
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4830
+ const url = plugin.files[0] ?? plugin.reference;
4831
+ const id = repoPath(url).split("/").pop() ?? url;
4832
+ const params = {
4833
+ id,
4834
+ version: "nightly",
4835
+ selected_version: "nightly",
4836
+ repository: url,
4837
+ mode: "cache",
4838
+ channel: "default"
4839
+ };
4840
+ await this.post(this.route(api, "/manager/queue/task"), {
4841
+ ui_id: uiId,
4842
+ client_id: this.clientId,
4843
+ kind: "install",
4844
+ params
4845
+ });
4846
+ return id;
4847
+ };
4848
+ this.settleByHistory = async (api, what, uiId, landed, sentId) => {
4849
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4850
+ const readEntry = async () => (await this.getValid(route, TaskHistory_ark)).history.status ?? null;
4851
+ const entry = await this.waitFor(what, async () => {
4852
+ const status = await readEntry();
4853
+ if (status != null) return status;
4854
+ if (await this.restartIdleQueue(api) !== "drained") return null;
4855
+ const late = await readEntry();
4856
+ if (late != null) return late;
4857
+ throw new InstallFailed("the task left the queue with no result (a queue/reset from the Manager UI or another client removes it)");
4858
+ });
4859
+ if (entry.status_str === "success" || entry.status_str === "skip") {
4860
+ if (await this.endState(landed) !== false) return;
4861
+ 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");
4862
+ }
4863
+ const messages = entry.messages ?? [];
4864
+ 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)" : "";
4865
+ throw new InstallFailed(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4866
+ };
4867
+ this.restartIdleQueue = async (api) => {
4868
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4869
+ if (status.is_processing) return "running";
4870
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4871
+ await this.post(this.route(api, "/manager/queue/start"));
4872
+ return "restarted";
4873
+ };
4874
+ this.settleByDrain = async (api, what, landed) => {
4875
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4876
+ const state = await this.endState(landed);
4877
+ if (state === true) return;
4878
+ if (state === null) throw new OutcomeUnknown("the queue drained, but the lists cannot say whether it is installed");
4879
+ 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`);
4880
+ };
4881
+ this.endState = async (landed) => {
4026
4882
  try {
4027
- const skip_update = skipUpdate ? "&skip_update=true" : "";
4028
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4883
+ return await landed();
4029
4884
  } catch (exception) {
4030
- console.error(`node list retrieval failed: ${exception}`);
4031
- logError("node list retrieveal failed");
4032
- throw exception;
4885
+ throw new OutcomeUnknown(`the task ran, but its end state could not be read: ${errorText(exception)}`);
4033
4886
  }
4034
4887
  };
4035
- this.installPlugin = async (model) => {
4888
+ this.runInstall = async (what, p) => {
4889
+ const host = this.host.getServerHostHTTP();
4036
4890
  try {
4037
- await this.fetchPost("/customnode/install", model);
4038
- console.log("✅ Custom Node installed");
4039
- logSuccess("Custom Node installed");
4040
- return true;
4891
+ const api = await this.api();
4892
+ const s = this.strategy(api);
4893
+ const uiId = (0, nanoid.nanoid)();
4894
+ const sentId = await p.enqueue(api, uiId);
4895
+ await this.post(this.route(api, "/manager/queue/start"));
4896
+ await s.settle(what, uiId, () => p.landed(s, api), sentId);
4897
+ logSuccess(`${what} installed`);
4898
+ return "installed";
4041
4899
  } catch (exception) {
4042
- console.error(`Install failed: / ${exception}`);
4043
- logError("Custom Node Installation Failed");
4044
- return false;
4900
+ if (exception instanceof OutcomeUnknown) {
4901
+ 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`);
4902
+ return "unknown";
4903
+ }
4904
+ logError(`${what}: install failed on ${host}: ${errorText(exception)}`);
4905
+ return "failed";
4906
+ }
4907
+ };
4908
+ this.waitFor = async (what, check) => {
4909
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4910
+ let lastAnswer = Date.now();
4911
+ for (;;) {
4912
+ try {
4913
+ const value = await check();
4914
+ lastAnswer = Date.now();
4915
+ if (value != null) return value;
4916
+ } catch (exception) {
4917
+ if (exception instanceof InstallFailed) throw exception;
4918
+ 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)}`);
4919
+ logError(`${what}: poll failed, still waiting: ${errorText(exception)}`);
4920
+ }
4921
+ if (Date.now() >= deadline) throw new OutcomeUnknown(`still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4922
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4045
4923
  }
4046
4924
  };
4047
- this.fetchPost = async (endpoint, body, validator) => {
4048
- const response = await this.host.fetch(endpoint, {
4925
+ this.post = async (route, body) => {
4926
+ const response = await this.host.fetch(route, {
4049
4927
  method: "POST",
4050
4928
  headers: { "Content-Type": "application/json" },
4051
- body: JSON.stringify(body)
4929
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4052
4930
  });
4053
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4054
- const status = await response.json();
4055
- if (validator) return softValidate(validator, status);
4056
- return status;
4057
- };
4058
- this.fetchGetJSON = async (endpoint, validator) => {
4059
- const response = await this.host.fetch(endpoint);
4060
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4931
+ const text = await response.text();
4932
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4933
+ if (text === "") return null;
4934
+ try {
4935
+ return JSON.parse(text);
4936
+ } catch {
4937
+ return text;
4938
+ }
4939
+ };
4940
+ this.getJSON = async (route, validator) => {
4941
+ const response = await this.host.fetch(route);
4942
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4061
4943
  const jsonResult = await response.json();
4062
4944
  if (validator) return softValidate(validator, jsonResult);
4063
4945
  return jsonResult;
4064
4946
  };
4065
- this.fetchGetText = async (endopint) => {
4066
- return await (await this.host.fetch(endopint)).text();
4947
+ this.getValid = async (route, schema) => {
4948
+ const res = schema(await this.getJSON(route));
4949
+ if (res instanceof arktype.type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4950
+ return res;
4067
4951
  };
4068
4952
  }
4069
4953
  get registry() {
@@ -5927,26 +6811,8 @@ var ComfyHost = class {
5927
6811
  constructor(data) {
5928
6812
  this.data = data;
5929
6813
  this.uploader = new ComfyUploader(this);
5930
- this.matchRequirements = (requirements) => {
5931
- const repo = comfyts.registry;
5932
- for (const req of requirements) {
5933
- if (req.optional) continue;
5934
- if (req.type === "customNodesByNodeKey") {
5935
- if (!(repo.plugins_byNodeKey.get(req.nodeName) ?? []).find((i) => this.manager.isPluginInstalled(i.title))) return false;
5936
- } else if (req.type === "customNodesByTitle") {
5937
- const plugin = repo.plugins_byTitle.get(req.title);
5938
- if (plugin == null) continue;
5939
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5940
- } else if (req.type === "customNodesByURI") {
5941
- const plugin = repo.plugins_byFile.get(req.uri);
5942
- if (plugin == null) continue;
5943
- if (!this.manager.isPluginInstalled(plugin.title)) return false;
5944
- } else if (req.type === "modelInManager") {
5945
- if (!this.manager.isModelInstalled(req.modelName)) return false;
5946
- }
5947
- }
5948
- return true;
5949
- };
6814
+ this.matchRequirements = (requirements) => this.manager.matchRequirements(requirements);
6815
+ this.checkRequirements = (requirements) => this.manager.checkRequirements(requirements);
5950
6816
  this.serverLogs = [];
5951
6817
  this.wantLog = true;
5952
6818
  this.maxLogs = 200;
@@ -6210,6 +7076,7 @@ var ComfyHost = class {
6210
7076
  this.onLogs = null;
6211
7077
  this.comfySessionId = "temp";
6212
7078
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7079
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6213
7080
  this.status = null;
6214
7081
  this.lastWsMessageAt = null;
6215
7082
  this.base = parseHostBase(this.data);
@@ -6449,9 +7316,26 @@ var ComfyHost = class {
6449
7316
  }
6450
7317
  return;
6451
7318
  }
6452
- const msg_ = JSON.parse(String(e.data));
6453
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6454
- if (msg_.type === "crystools.monitor") return;
7319
+ let msg_ = JSON.parse(String(e.data));
7320
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7321
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7322
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7323
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7324
+ const key = eventType ?? "<no type>";
7325
+ if (this._unknownWsEventTypes.has(key)) return;
7326
+ this._unknownWsEventTypes.add(key);
7327
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7328
+ return;
7329
+ }
7330
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7331
+ const data = Reflect.get(rec, "data");
7332
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7333
+ type: eventType,
7334
+ data: {
7335
+ ...data,
7336
+ prompt_id: this.activePromptID
7337
+ }
7338
+ };
6455
7339
  }
6456
7340
  const res = WsMsg_ark(msg_);
6457
7341
  if (res instanceof arktype.type.errors) {
@@ -6465,7 +7349,11 @@ var ComfyHost = class {
6465
7349
  this.comfySessionId = msg.data.sid;
6466
7350
  this._sessionResolve?.();
6467
7351
  this._sessionResolve = null;
6468
- if (sidChanged) this.onSession?.(msg.data.sid);
7352
+ if (sidChanged) {
7353
+ this._unknownWsEventTypes.clear();
7354
+ this._unknownBinaryFrameTypes.clear();
7355
+ this.onSession?.(msg.data.sid);
7356
+ }
6469
7357
  }
6470
7358
  this.status = msg.data.status;
6471
7359
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6480,7 +7368,7 @@ var ComfyHost = class {
6480
7368
  this.routeOrBuffer(activePromptID, msg);
6481
7369
  return;
6482
7370
  }
6483
- 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") {
7371
+ 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") {
6484
7372
  this.routeOrBuffer(msg.data.prompt_id, msg);
6485
7373
  return;
6486
7374
  }
@@ -6492,8 +7380,6 @@ var ComfyHost = class {
6492
7380
  this.onLogs?.(msg.data);
6493
7381
  return;
6494
7382
  }
6495
- console.log("❌", "Unknown message:", msg);
6496
- logError("Unknown message type: " + JSON.stringify(msg.type));
6497
7383
  }
6498
7384
  };
6499
7385
  //#endregion
@@ -6822,6 +7708,7 @@ const _getKnownModels = (DB) => {
6822
7708
  }
6823
7709
  const knownModelList = canonical.concat(extraModels.models);
6824
7710
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7711
+ DB.modelRows = knownModelList;
6825
7712
  if (DB.opts.genTypes) {
6826
7713
  let out1 = "";
6827
7714
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6990,6 +7877,7 @@ var ComfyRegistry = class ComfyRegistry {
6990
7877
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6991
7878
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6992
7879
  this.knownModels = /* @__PURE__ */ new Map();
7880
+ this.modelRows = [];
6993
7881
  this.alterations = [];
6994
7882
  this.githubStats = /* @__PURE__ */ new Map();
6995
7883
  this.report = new ManagerParseReport();