comfy-ts 2.17.1 → 2.18.0

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 +944 -165
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1154 -408
  5. package/dist/index.d.ts +1154 -408
  6. package/dist/index.js +944 -165
  7. package/dist/index.js.map +1 -1
  8. package/dist/{run-run-tg82jUIk.js → run-run-Wn7H72Zg.js} +2 -2
  9. package/dist/{run-run-tg82jUIk.js.map → run-run-Wn7H72Zg.js.map} +1 -1
  10. package/dist/{run-tui-Bw7BA75d.js → run-tui-VWSj1D_j.js} +2 -2
  11. package/dist/{run-tui-Bw7BA75d.js.map → run-tui-VWSj1D_j.js.map} +1 -1
  12. package/dist/serve-web.js +47 -47
  13. package/dist/{state-zTow5ucI.js → state-DgwWhZWb.js} +945 -166
  14. package/dist/state-DgwWhZWb.js.map +1 -0
  15. package/dist/web.d.ts +1172 -426
  16. package/dist/web.js +944 -165
  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 +31 -10
  48. package/src/host/ComfyManager.ts +448 -62
  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 +14 -0
  55. package/src/litegraph/normalizeWorkflow.ts +1 -0
  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 +176 -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 +141 -33
  80. package/dist/state-zTow5ucI.js.map +0 -1
package/dist/web.js CHANGED
@@ -101,7 +101,7 @@ function getComfyStorage() {
101
101
  }
102
102
  //#endregion
103
103
  //#region package.json
104
- var version = "2.17.1";
104
+ var version = "2.18.0";
105
105
  //#endregion
106
106
  //#region src/litegraph/LiteGraphLinkID.ts
107
107
  const asLiteGraphLinkID = (id) => id;
@@ -257,7 +257,8 @@ const expandOneInstance = (wf, instance, def) => {
257
257
  name: i.name,
258
258
  type: i.type,
259
259
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
260
- widgetName: i.widgetName
260
+ widgetName: i.widgetName,
261
+ widgetSource: i.widgetSource
261
262
  })),
262
263
  outputs: inner.outputs.map((o) => ({
263
264
  name: o.name,
@@ -298,6 +299,20 @@ const expandOneInstance = (wf, instance, def) => {
298
299
  wf.links = wf.links.filter((l) => !dead.has(l.id));
299
300
  pruneDeadLinkRefs(wf, dead);
300
301
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
302
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
303
+ if (outerLinkIntoDefSlot.has(slot)) continue;
304
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
305
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
306
+ if (source == null || sourceInput == null) continue;
307
+ for (const t of targets) {
308
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
309
+ if (input == null || input.widgetName != null || input.link != null) continue;
310
+ input.widgetSource = {
311
+ nodeId: source.nodeId,
312
+ inputName: sourceInput.name
313
+ };
314
+ }
315
+ }
301
316
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
302
317
  wf.nodes.push(...splicedNodes);
303
318
  wf.links.push(...splicedLinks);
@@ -409,7 +424,7 @@ const LiteGraphNodeInput_ark = type({
409
424
  type: "string",
410
425
  "link?": LiteGraphLinkID_.or(type.null),
411
426
  "shape?": "number",
412
- "label?": "string",
427
+ "label?": type.string.or(type.null),
413
428
  "widget?": type({
414
429
  name: "string",
415
430
  "config?": "unknown"
@@ -426,7 +441,7 @@ const LiteGraphNodeOutput_ark = type({
426
441
  type: "string",
427
442
  "links?": LiteGraphLinkID_.array().or(type.null),
428
443
  "shape?": "number",
429
- "slot_index?": LiteGraphSlotIndex_
444
+ "slot_index?": LiteGraphSlotIndex_.or(type.null)
430
445
  });
431
446
  //#endregion
432
447
  //#region src/litegraph/LiteGraphNode.ts
@@ -496,7 +511,7 @@ const LiteGraphSubgraphDef_ark = type({
496
511
  const LiteGraphJSON_ark = type({
497
512
  "id?": "string",
498
513
  "revision?": "number",
499
- "last_node_id?": "number",
514
+ "last_node_id?": "number | string",
500
515
  "last_link_id?": "number",
501
516
  "state?": type.Record("string", "unknown"),
502
517
  nodes: LiteGraphNode_ark.array(),
@@ -595,7 +610,8 @@ const normalizeInput = (i) => {
595
610
  name: i.name,
596
611
  type: i.type,
597
612
  link: i.link ?? null,
598
- widgetName: i.widget?.name ?? null
613
+ widgetName: i.widget?.name ?? null,
614
+ widgetSource: null
599
615
  };
600
616
  };
601
617
  const normalizeOutput = (o) => {
@@ -768,6 +784,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
768
784
  python_module: "nodes"
769
785
  };
770
786
  //#endregion
787
+ //#region src/utils/exhaust.ts
788
+ function exhaust(x) {
789
+ return x;
790
+ }
791
+ //#endregion
771
792
  //#region src/sdk-generator/inputWidgetKind.ts
772
793
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
773
794
  /**
@@ -836,6 +857,14 @@ const parseContainer = (template) => {
836
857
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
837
858
  };
838
859
  };
860
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
861
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
862
+ const parseGroup = (o, template) => ({
863
+ kind: "dynamic-group",
864
+ fields: flattenInputSections(template),
865
+ min: typeof o["min"] === "number" ? o["min"] : 0,
866
+ max: typeof o["max"] === "number" ? o["max"] : 20
867
+ });
839
868
  /**
840
869
  * the single template sub-input's slot type of an autogrow container
841
870
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -910,11 +939,12 @@ const classifyWidgetInput = (p) => {
910
939
  };
911
940
  }
912
941
  const template = o?.["template"];
913
- if (isRecord$1(template)) {
942
+ if (o != null && isRecord$1(template)) {
914
943
  if (isRecord$1(template["input"])) return parseContainer(template);
944
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
915
945
  return { kind: "slot" };
916
946
  }
917
- if (o?.["socketless"] === true) return {
947
+ if (typeof o?.["socketless"] === "boolean") return {
918
948
  kind: "widget",
919
949
  consumes: 1,
920
950
  strictValues: false,
@@ -1087,18 +1117,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1087
1117
  inputs[p.path] = key;
1088
1118
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1089
1119
  };
1120
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1121
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1122
+ const consumeDynamicGroup = (p) => {
1123
+ const r = resolveWidgetValue({
1124
+ promptName: p.path,
1125
+ consumes: 1,
1126
+ prefixLen: 0
1127
+ });
1128
+ const saved = r.filled ? p.min : r.value;
1129
+ 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);
1130
+ const rows = Math.max(p.min, saved);
1131
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1132
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1133
+ };
1090
1134
  const consumeBranchInput = (subPath, sub) => {
1091
1135
  const kind = classifyWidgetInput({
1092
- name: sub.name,
1136
+ name: subPath,
1093
1137
  type: sub.type,
1094
1138
  opts: sub.opts
1095
1139
  });
1096
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1097
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1098
- path: subPath,
1099
- options: kind.options,
1100
- defaultKey: kind.defaultKey
1101
- });
1140
+ switch (kind.kind) {
1141
+ case "slot":
1142
+ case "dynamic-container": return;
1143
+ case "dynamic-combo": return consumeDynamicCombo({
1144
+ path: subPath,
1145
+ options: kind.options,
1146
+ defaultKey: kind.defaultKey
1147
+ });
1148
+ case "dynamic-group": return consumeDynamicGroup({
1149
+ path: subPath,
1150
+ fields: kind.fields,
1151
+ min: kind.min,
1152
+ max: kind.max
1153
+ });
1154
+ case "widget": break;
1155
+ default: return exhaust(kind);
1156
+ }
1102
1157
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1103
1158
  consumePlainWidget({
1104
1159
  promptName: subPath,
@@ -1120,26 +1175,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1120
1175
  strictValues: true,
1121
1176
  prefixValues: []
1122
1177
  };
1123
- if (kind.kind === "widget") consumePlainWidget({
1124
- promptName: field.nameInComfy,
1125
- typeName: field.typeName,
1126
- opts: field.opts,
1127
- consumes: kind.consumes,
1128
- prefixLen: kind.prefixValues.length,
1129
- strict: kind.strictValues,
1130
- linkedInput: input
1131
- });
1132
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1133
- path: field.nameInComfy,
1134
- options: kind.options,
1135
- defaultKey: kind.defaultKey
1136
- });
1137
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1138
- const iname = `${field.nameInComfy}.${instName}`;
1139
- if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1140
- }
1141
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1142
- if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
1178
+ switch (kind.kind) {
1179
+ case "widget":
1180
+ consumePlainWidget({
1181
+ promptName: field.nameInComfy,
1182
+ typeName: field.typeName,
1183
+ opts: field.opts,
1184
+ consumes: kind.consumes,
1185
+ prefixLen: kind.prefixValues.length,
1186
+ strict: kind.strictValues,
1187
+ linkedInput: input
1188
+ });
1189
+ break;
1190
+ case "dynamic-combo":
1191
+ consumeDynamicCombo({
1192
+ path: field.nameInComfy,
1193
+ options: kind.options,
1194
+ defaultKey: kind.defaultKey
1195
+ });
1196
+ break;
1197
+ case "dynamic-group":
1198
+ consumeDynamicGroup({
1199
+ path: field.nameInComfy,
1200
+ fields: kind.fields,
1201
+ min: kind.min,
1202
+ max: kind.max
1203
+ });
1204
+ break;
1205
+ case "dynamic-container":
1206
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1207
+ const iname = `${field.nameInComfy}.${instName}`;
1208
+ 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);
1209
+ }
1210
+ break;
1211
+ case "slot":
1212
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1213
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1214
+ promptName: field.nameInComfy,
1215
+ strict: false
1216
+ });
1217
+ break;
1218
+ }
1219
+ 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);
1220
+ break;
1221
+ default:
1143
1222
  }
1144
1223
  }
1145
1224
  const getParentNode = (linkId) => {
@@ -1245,6 +1324,45 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1245
1324
  class_type: node.type
1246
1325
  };
1247
1326
  }
1327
+ for (const node of workflow.nodes) {
1328
+ const own = prompt[String(node.id)];
1329
+ if (own == null) continue;
1330
+ for (const ipt of node.inputs) {
1331
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1332
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1333
+ if (value !== void 0) own.inputs[ipt.name] = value;
1334
+ }
1335
+ }
1336
+ const missing = /* @__PURE__ */ new Map();
1337
+ for (const node of workflow.nodes) {
1338
+ const own = prompt[String(node.id)];
1339
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1340
+ if (own == null || nodeSchema == null) continue;
1341
+ for (const field of nodeSchema.inputs) {
1342
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1343
+ const kind = classifySchemaInput(field).kind;
1344
+ if (kind !== "slot" && kind !== "widget") continue;
1345
+ missing.set(String(node.id), {
1346
+ node,
1347
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1348
+ });
1349
+ break;
1350
+ }
1351
+ }
1352
+ if (missing.size > 0) {
1353
+ const complete = (id, seen) => {
1354
+ if (seen.has(id)) return true;
1355
+ seen.add(id);
1356
+ if (missing.has(id)) return false;
1357
+ for (const value of Object.values(prompt[id]?.inputs ?? {})) if (Array.isArray(value) && typeof value[0] === "string" && !complete(value[0], seen)) return false;
1358
+ return true;
1359
+ };
1360
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1361
+ const dropped = outputs.filter((id) => !complete(id, /* @__PURE__ */ new Set()));
1362
+ const first = missing.values().next().value;
1363
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1364
+ 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("; ")}`);
1365
+ }
1248
1366
  return prompt;
1249
1367
  };
1250
1368
  //#endregion
@@ -1425,21 +1543,37 @@ var ComfyNode = class ComfyNode {
1425
1543
  _convertPromptExtToPrompt(promptExt) {
1426
1544
  const inputs = {};
1427
1545
  const _done = /* @__PURE__ */ new Set();
1428
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1546
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1429
1547
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1430
1548
  for (const i of this.$schema.inputs) {
1431
1549
  _done.add(i.nameInComfy);
1432
1550
  const kind = classifySchemaInput(i);
1433
- if (kind.kind === "dynamic-combo") {
1434
- this._writeDynamicCombo({
1435
- name: i.nameInComfy,
1436
- options: kind.options,
1437
- defaultKey: kind.defaultKey,
1438
- provided: promptExt.inputs,
1439
- out: inputs,
1440
- claimed: _comboBranchKeys
1441
- });
1442
- continue;
1551
+ switch (kind.kind) {
1552
+ case "dynamic-combo":
1553
+ this._writeDynamicCombo({
1554
+ name: i.nameInComfy,
1555
+ options: kind.options,
1556
+ defaultKey: kind.defaultKey,
1557
+ provided: promptExt.inputs,
1558
+ out: inputs,
1559
+ claimed: _comboBranchKeys
1560
+ });
1561
+ continue;
1562
+ case "dynamic-group":
1563
+ this._writeDynamicGroup({
1564
+ name: i.nameInComfy,
1565
+ fields: kind.fields,
1566
+ min: kind.min,
1567
+ max: kind.max,
1568
+ provided: promptExt.inputs,
1569
+ out: inputs,
1570
+ claimed: _comboBranchKeys
1571
+ });
1572
+ continue;
1573
+ case "widget":
1574
+ case "slot":
1575
+ case "dynamic-container": break;
1576
+ default:
1443
1577
  }
1444
1578
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1445
1579
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1478,6 +1612,42 @@ var ComfyNode = class ComfyNode {
1478
1612
  }) : this.serializeValue(dotted, given);
1479
1613
  }
1480
1614
  }
1615
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1616
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1617
+ * keys are already the rows: they pass through the rest loop untouched */
1618
+ _writeDynamicGroup(p) {
1619
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1620
+ const raw = p.provided[p.name];
1621
+ const prefix = `${p.name}.`;
1622
+ if (raw == null) {
1623
+ 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)`);
1624
+ return;
1625
+ }
1626
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1627
+ if (!Array.isArray(raw)) {
1628
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1629
+ return;
1630
+ }
1631
+ 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}`);
1632
+ raw.forEach((row, ix) => {
1633
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1634
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1635
+ return;
1636
+ }
1637
+ const given = new Map(Object.entries(row));
1638
+ for (const field of p.fields) {
1639
+ const dotted = `${p.name}.${ix}.${field.name}`;
1640
+ const value = given.get(field.name);
1641
+ p.out[dotted] = value == null ? defaultValueForWidget({
1642
+ type: typeof field.type === "string" ? field.type : "COMBO",
1643
+ opts: field.opts,
1644
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1645
+ }) : this.serializeValue(dotted, value);
1646
+ given.delete(field.name);
1647
+ }
1648
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1649
+ });
1650
+ }
1481
1651
  /** return the list of nodes piped into this node */
1482
1652
  _incomingNodes() {
1483
1653
  const incomingNodes = [];
@@ -1621,6 +1791,12 @@ var ComfyNode = class ComfyNode {
1621
1791
  const kind = classifySchemaInput(decl);
1622
1792
  const slotType = containerInstanceSlotType(decl.opts);
1623
1793
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1794
+ if (kind.kind === "dynamic-group") {
1795
+ const rest = name.slice(dot + 1);
1796
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1797
+ const field = kind.fields.find((f) => f.name === fieldName);
1798
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1799
+ }
1624
1800
  }
1625
1801
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1626
1802
  }
@@ -1704,44 +1880,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1704
1880
  const convertNodeToLiteGraphNode = (ctx, node) => {
1705
1881
  const inputs = [];
1706
1882
  const widgets_values = [];
1707
- const pushLinked = (name, type, link, shape) => {
1883
+ const pushLinked = (name, type, link, extra = {}) => {
1708
1884
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1709
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1710
- inputs.push(shape == null ? {
1885
+ const input = {
1711
1886
  name,
1712
1887
  type,
1713
- link: linkId
1714
- } : {
1888
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1889
+ };
1890
+ if (extra.shape != null) input.shape = extra.shape;
1891
+ if (extra.widget === true) input.widget = { name };
1892
+ inputs.push(input);
1893
+ };
1894
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1895
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1896
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1897
+ * never disagree on the run length */
1898
+ const pushWidgetRun = (kind, raw, opts) => {
1899
+ widgets_values.push(...kind.prefixValues, raw);
1900
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1901
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1902
+ };
1903
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1904
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1905
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1906
+ const writeInput = (p) => {
1907
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1908
+ switch (p.kind.kind) {
1909
+ case "widget":
1910
+ if (_isLink(p.value)) {
1911
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
1912
+ pushWidgetRun(p.kind, defaultValueForWidget({
1913
+ type: p.typeName,
1914
+ opts: p.opts
1915
+ }), p.opts);
1916
+ } else pushWidgetRun(p.kind, p.value, p.opts);
1917
+ return;
1918
+ case "slot":
1919
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
1920
+ else inputs.push({
1921
+ name: p.name,
1922
+ type: p.typeName,
1923
+ link: null
1924
+ });
1925
+ return;
1926
+ case "dynamic-combo": {
1927
+ const kind = p.kind;
1928
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
1929
+ const option = kind.options.find((o) => o.key === key);
1930
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
1931
+ widgets_values.push(key);
1932
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
1933
+ return;
1934
+ }
1935
+ case "dynamic-container": {
1936
+ const type = containerInstanceSlotType(p.opts) ?? "*";
1937
+ for (const instance of p.kind.instanceNames) {
1938
+ const name = `${p.name}.${instance}`;
1939
+ const value = node.json.inputs[name];
1940
+ if (value == null) continue;
1941
+ const raw = node.serializeValue(name, value);
1942
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
1943
+ pushLinked(name, type, raw, { shape: 7 });
1944
+ }
1945
+ return;
1946
+ }
1947
+ case "dynamic-group": {
1948
+ const prefix = `${p.name}.`;
1949
+ let rows = 0;
1950
+ for (const key of Object.keys(node.json.inputs)) {
1951
+ if (!key.startsWith(prefix)) continue;
1952
+ const row = Number(key.slice(prefix.length).split(".")[0]);
1953
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
1954
+ }
1955
+ widgets_values.push(rows);
1956
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
1957
+ return;
1958
+ }
1959
+ default: p.kind;
1960
+ }
1961
+ };
1962
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
1963
+ * value is the widget's schema default rather than serializeValue's */
1964
+ const writeSub = (name, sub) => {
1965
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
1966
+ const raw = node.json.inputs[name];
1967
+ writeInput({
1715
1968
  name,
1716
- type,
1717
- shape,
1718
- link: linkId
1969
+ kind: classifyWidgetInput({
1970
+ name,
1971
+ type: sub.type,
1972
+ opts: sub.opts
1973
+ }),
1974
+ typeName,
1975
+ opts: sub.opts,
1976
+ value: raw === void 0 ? defaultValueForWidget({
1977
+ type: typeName,
1978
+ opts: sub.opts
1979
+ }) : raw
1719
1980
  });
1720
1981
  };
1721
1982
  for (const ipt of node.$schema.inputs) {
1722
1983
  const kind = classifySchemaInput(ipt);
1723
- if (kind.kind === "dynamic-container") {
1724
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1725
- for (const instance of kind.instanceNames) {
1726
- const name = `${ipt.nameInComfy}.${instance}`;
1727
- const value = node.json.inputs[name];
1728
- if (value == null) continue;
1729
- const raw = node.serializeValue(name, value);
1730
- if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${node.$schema.nameInComfy}#${node.uid} "${name}" holds a literal; an autogrow instance is a link slot in the editor`);
1731
- pushLinked(name, type, raw, 7);
1732
- }
1733
- continue;
1734
- }
1735
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1736
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1737
- else if (kind.kind === "widget") {
1738
- widgets_values.push(...kind.prefixValues, raw);
1739
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1740
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1741
- } else inputs.push({
1984
+ const raw = node.json.inputs[ipt.nameInComfy];
1985
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
1986
+ writeInput({
1742
1987
  name: ipt.nameInComfy,
1743
- type: ipt.typeName,
1744
- link: null
1988
+ kind,
1989
+ typeName: ipt.typeName,
1990
+ opts: ipt.opts,
1991
+ value
1745
1992
  });
1746
1993
  }
1747
1994
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1927,11 +2174,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1927
2174
  return resultSuccess(txt_chunks);
1928
2175
  };
1929
2176
  //#endregion
1930
- //#region src/utils/exhaust.ts
1931
- function exhaust(x) {
1932
- return x;
1933
- }
1934
- //#endregion
1935
2177
  //#region src/utils/sha1.ts
1936
2178
  function sha1Hex(data) {
1937
2179
  const ml = data.length;
@@ -2066,16 +2308,17 @@ const types$1 = scope({
2066
2308
  },
2067
2309
  _WsMsgExecutedData: {
2068
2310
  node: "ComfyNodeID",
2069
- output: {
2070
- "previews?": [{ filepath: "string" }, "[]"],
2071
- "images?": "ComfyImageInfo[]",
2072
- "audio?": "ComfyImageInfo[]",
2073
- "video?": "ComfyImageInfo[]",
2074
- "gifs?": "ComfyImageInfo[]",
2075
- "text?": "unknown[]"
2076
- },
2311
+ output: "_WsMsgExecutedOutput | null",
2077
2312
  prompt_id: "PromptID"
2078
2313
  },
2314
+ _WsMsgExecutedOutput: {
2315
+ "previews?": [{ filepath: "string" }, "[]"],
2316
+ "images?": "ComfyImageInfo[]",
2317
+ "audio?": "ComfyImageInfo[]",
2318
+ "video?": "ComfyImageInfo[]",
2319
+ "gifs?": "ComfyImageInfo[]",
2320
+ "text?": "unknown[]"
2321
+ },
2079
2322
  WsMsgExecuted: {
2080
2323
  type: "'executed'",
2081
2324
  data: "_WsMsgExecutedData"
@@ -2097,12 +2340,22 @@ const types$1 = scope({
2097
2340
  exception_type: "string",
2098
2341
  traceback: "string[]",
2099
2342
  current_inputs: "Record<string, unknown>",
2100
- current_outputs: "Record<string, unknown>"
2343
+ current_outputs: "ComfyNodeID[]"
2101
2344
  },
2102
2345
  WsMsgExecutionError: {
2103
2346
  type: "'execution_error'",
2104
2347
  data: "_WsMsgExecutionErrorData"
2105
2348
  },
2349
+ _WsMsgExecutionInterruptedData: {
2350
+ prompt_id: "PromptID",
2351
+ node_id: "ComfyNodeID",
2352
+ node_type: "string",
2353
+ executed: "ComfyNodeID[]"
2354
+ },
2355
+ WsMsgExecutionInterrupted: {
2356
+ type: "'execution_interrupted'",
2357
+ data: "_WsMsgExecutionInterruptedData"
2358
+ },
2106
2359
  WSMsgManagerFeedbackData: { data: "string" },
2107
2360
  WSMsgManagerFeedback: {
2108
2361
  type: "'manager-terminal-feedback'",
@@ -2132,11 +2385,51 @@ const types$1 = scope({
2132
2385
  type: "'progress_state'",
2133
2386
  data: "_WsMsgProgressStateData"
2134
2387
  },
2135
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2388
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2136
2389
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2137
2390
  }).export();
2138
2391
  const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2139
2392
  const WsMsg_ark = types$1.WsMsg;
2393
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2394
+ const ROUTED_WS_EVENT_TYPES = [
2395
+ "status",
2396
+ "manager-terminal-feedback",
2397
+ "logs",
2398
+ "execution_start",
2399
+ "execution_cached",
2400
+ "executing",
2401
+ "progress",
2402
+ "progress_state",
2403
+ "executed",
2404
+ "execution_error",
2405
+ "execution_interrupted",
2406
+ "execution_success"
2407
+ ];
2408
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2409
+ * before validation, never logged (architecture.md, ws events) */
2410
+ const IGNORED_WS_EVENT_TYPES = [
2411
+ "feature_flags",
2412
+ "agent_status",
2413
+ "asset_export",
2414
+ "assets.seed.started",
2415
+ "assets.seed.progress",
2416
+ "assets.seed.fast_complete",
2417
+ "assets.seed.enrich_complete",
2418
+ "assets.seed.completed",
2419
+ "assets.seed.cancelled",
2420
+ "assets.seed.error",
2421
+ "assets.seed.paused",
2422
+ "assets.seed.resumed",
2423
+ "cm-queue-status",
2424
+ "cm-api-try-install-customnode",
2425
+ "cm-task-started",
2426
+ "cm-task-completed",
2427
+ "crystools.monitor"
2428
+ ];
2429
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2430
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2431
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2432
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2140
2433
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2141
2434
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2142
2435
  //#endregion
@@ -2426,6 +2719,10 @@ var ComfyExecution = class {
2426
2719
  else if (msg.type === "progress") graph.onProgress(msg);
2427
2720
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2428
2721
  else if (msg.type === "execution_error") return void this.onError(msg);
2722
+ else if (msg.type === "execution_interrupted") return void this._finish({
2723
+ status: "Failure",
2724
+ error: msg
2725
+ });
2429
2726
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2430
2727
  else {
2431
2728
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3339,6 +3636,15 @@ const dynamicComboUnion = (p) => {
3339
3636
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3340
3637
  }).join(" | ")})`;
3341
3638
  };
3639
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3640
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3641
+ const dynamicGroupRow = (fields) => {
3642
+ return `{ ${fields.map((e) => {
3643
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3644
+ const optional = !e.required || opts?.["default"] !== void 0;
3645
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3646
+ }).join("; ")} }`;
3647
+ };
3342
3648
  /**
3343
3649
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3344
3650
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3387,6 +3693,8 @@ function codegenSDK(opts) {
3387
3693
  b.deindent();
3388
3694
  p(`// #endregion`);
3389
3695
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3696
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3697
+ const groupRows = [];
3390
3698
  p(`interface IN {`);
3391
3699
  b.indent();
3392
3700
  for (const n of nodes) {
@@ -3394,23 +3702,37 @@ function codegenSDK(opts) {
3394
3702
  const comboSuffixes = [];
3395
3703
  for (const i of n.inputs) {
3396
3704
  const kind = classifySchemaInput(i);
3397
- if (kind.kind === "dynamic-container") {
3398
- const instType = containerInstanceSlotType(i.opts);
3399
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3400
- const opt = ix >= kind.requiredCount ? "?" : "";
3401
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3402
- });
3403
- continue;
3404
- }
3405
- if (kind.kind === "dynamic-combo") {
3406
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3407
- comboSuffixes.push(dynamicComboUnion({
3408
- name: i.nameInComfy,
3409
- nameEscaped: i.nameInComfyEscaped,
3410
- options: kind.options,
3411
- keyOptional: optsDyn?.default !== void 0 || !i.required
3412
- }));
3413
- continue;
3705
+ switch (kind.kind) {
3706
+ case "dynamic-container": {
3707
+ const instType = containerInstanceSlotType(i.opts);
3708
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3709
+ const opt = ix >= kind.requiredCount ? "?" : "";
3710
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3711
+ });
3712
+ continue;
3713
+ }
3714
+ case "dynamic-combo": {
3715
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3716
+ comboSuffixes.push(dynamicComboUnion({
3717
+ name: i.nameInComfy,
3718
+ nameEscaped: i.nameInComfyEscaped,
3719
+ options: kind.options,
3720
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3721
+ }));
3722
+ continue;
3723
+ }
3724
+ case "dynamic-group": {
3725
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3726
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3727
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3728
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3729
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3730
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3731
+ continue;
3732
+ }
3733
+ case "widget":
3734
+ case "slot": break;
3735
+ default:
3414
3736
  }
3415
3737
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3416
3738
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3433,6 +3755,15 @@ function codegenSDK(opts) {
3433
3755
  b.deindent();
3434
3756
  p("}");
3435
3757
  p("");
3758
+ if (groupRows.length > 0) {
3759
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3760
+ p(`interface GroupRow {`);
3761
+ b.indent();
3762
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3763
+ b.deindent();
3764
+ p("}");
3765
+ p("");
3766
+ }
3436
3767
  p(`interface OUT {`);
3437
3768
  b.indent();
3438
3769
  for (const n of nodes) {
@@ -3745,9 +4076,13 @@ var ComfySchema = class {
3745
4076
  if (widgetKind?.kind === "dynamic-combo") {
3746
4077
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3747
4078
  }
4079
+ if (widgetKind?.kind === "dynamic-group") {
4080
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4081
+ }
4082
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3748
4083
  node.inputs.push({
3749
4084
  slotName: inputSlotName,
3750
- required: ipt.required && !isAutogrowContainer,
4085
+ required,
3751
4086
  nameInComfy: inputNameInComfy,
3752
4087
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3753
4088
  typeName: inputTypeName,
@@ -3823,7 +4158,12 @@ const types = scope({
3823
4158
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3824
4159
  ComfyInputSpecAlt2: ["ComfyInputType"],
3825
4160
  ComfyInputSpecAlt3: type([type.null]),
3826
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4161
+ ComfyInputSpecAlt4: [
4162
+ "ComfyInputType",
4163
+ "ComfyInputOpts",
4164
+ "unknown"
4165
+ ],
4166
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3827
4167
  ComfyInputType: `string | ComfyEnumDef`,
3828
4168
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3829
4169
  ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
@@ -3889,10 +4229,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3889
4229
  return result;
3890
4230
  }
3891
4231
  //#endregion
4232
+ //#region src/manager/installedView.ts
4233
+ /**
4234
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4235
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4236
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4237
+ */
4238
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4239
+ const InstalledPacks_ark = type.Record("string", type({
4240
+ "cnr_id?": "string | null",
4241
+ "aux_id?": "string | null",
4242
+ enabled: "boolean"
4243
+ }));
4244
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4245
+ const PackMappings_ark = type.Record("string", type(["string[]", { "title_aux?": "string" }]));
4246
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4247
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4248
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4249
+ const attributePacks = (installed, mappings) => {
4250
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4251
+ return Object.entries(installed).map(([dir, p]) => {
4252
+ const aux = p.aux_id ?? null;
4253
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4254
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4255
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4256
+ return {
4257
+ enabled: p.enabled,
4258
+ repo,
4259
+ title,
4260
+ id: cnr ?? aux ?? dir
4261
+ };
4262
+ });
4263
+ };
4264
+ /** is this mirror row among the attributed packs, enabled? */
4265
+ const packIsInstalled = (packs, plugin) => {
4266
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4267
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4268
+ };
4269
+ const buildPluginView = (p) => {
4270
+ const packs = attributePacks(p.installed, p.mappings);
4271
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4272
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4273
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4274
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4275
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4276
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4277
+ const custom_nodes = [];
4278
+ for (const plugin of plugins) {
4279
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4280
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4281
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4282
+ title: plugin.title,
4283
+ installed: "True"
4284
+ });
4285
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4286
+ else custom_nodes.push({
4287
+ title: plugin.title,
4288
+ installed: "False"
4289
+ });
4290
+ }
4291
+ return {
4292
+ list: {
4293
+ chanel: "default",
4294
+ custom_nodes
4295
+ },
4296
+ unattributed: unattributed.map((x) => x.id)
4297
+ };
4298
+ };
4299
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4300
+ const DEFAULT_FOLDER_BY_TYPE = {
4301
+ checkpoints: "checkpoints",
4302
+ checkpoint: "checkpoints",
4303
+ unclip: "checkpoints",
4304
+ text_encoders: "text_encoders",
4305
+ clip: "text_encoders",
4306
+ vae: "vae",
4307
+ lora: "loras",
4308
+ "t2i-adapter": "controlnet",
4309
+ "t2i-style": "controlnet",
4310
+ controlnet: "controlnet",
4311
+ clip_vision: "clip_vision",
4312
+ gligen: "gligen",
4313
+ upscale: "upscale_models",
4314
+ embedding: "embeddings",
4315
+ embeddings: "embeddings",
4316
+ unet: "diffusion_models",
4317
+ diffusion_model: "diffusion_models"
4318
+ };
4319
+ /** what core `get_filename_list` lists in the standard folders */
4320
+ const LISTED_EXTENSIONS = [
4321
+ ".ckpt",
4322
+ ".pt",
4323
+ ".pt2",
4324
+ ".bin",
4325
+ ".pth",
4326
+ ".safetensors",
4327
+ ".pkl",
4328
+ ".sft"
4329
+ ];
4330
+ /**
4331
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4332
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4333
+ */
4334
+ const modelLocation = (m) => {
4335
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4336
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4337
+ if (m.save_path === "default") {
4338
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4339
+ return folder == null ? null : {
4340
+ folder,
4341
+ files: [m.filename]
4342
+ };
4343
+ }
4344
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4345
+ const folder = parts[0];
4346
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4347
+ const sub = [...parts.slice(1), m.filename].join("/");
4348
+ return {
4349
+ folder,
4350
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4351
+ };
4352
+ };
4353
+ const buildModelView = (p) => {
4354
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4355
+ const statusOf = (m) => {
4356
+ const at = modelLocation(m);
4357
+ const files = at == null ? null : listed.get(at.folder);
4358
+ if (at == null || files == null) return null;
4359
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4360
+ };
4361
+ const byName = /* @__PURE__ */ new Map();
4362
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4363
+ const models = [];
4364
+ for (const rows of byName.values()) {
4365
+ const statuses = new Set(rows.map(statusOf));
4366
+ const first = rows[0];
4367
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4368
+ if (first == null || installed == null) continue;
4369
+ models.push({
4370
+ name: first.name,
4371
+ installed,
4372
+ filename: first.filename,
4373
+ save_path: first.save_path,
4374
+ base: first.base
4375
+ });
4376
+ }
4377
+ return { models };
4378
+ };
4379
+ /** the folders the views need listed */
4380
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4381
+ //#endregion
3892
4382
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3893
4383
  const ComfyManagerAPIModelList_ark = type({ models: type({
3894
4384
  name: type.string.as(),
3895
- installed: `'False' | 'True' | 'Update'`
4385
+ installed: `'False' | 'True' | 'Update'`,
4386
+ "filename?": "string",
4387
+ "save_path?": "string",
4388
+ "base?": "string"
3896
4389
  }).array() });
3897
4390
  //#endregion
3898
4391
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3903,28 +4396,155 @@ const ComfyManagerAPIPluginList_ark = type({
3903
4396
  }).array(),
3904
4397
  chanel: "string"
3905
4398
  });
4399
+ const ComfyManagerAPIPack_ark = type({
4400
+ title: type.string.as(),
4401
+ "id?": "string",
4402
+ "files?": "string[]",
4403
+ "repository?": "string",
4404
+ "version?": "string",
4405
+ "state?": "string",
4406
+ "update-state?": "string"
4407
+ });
4408
+ const ComfyManagerAPIPackList_ark = type({
4409
+ channel: "string",
4410
+ node_packs: type.Record("string", ComfyManagerAPIPack_ark)
4411
+ });
3906
4412
  //#endregion
3907
4413
  //#region src/host/ComfyManager.ts
4414
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4415
+ const MANAGER_TIMING = {
4416
+ pollMs: 1e3,
4417
+ installTimeoutMs: 60 * 6e4
4418
+ };
4419
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4420
+ const NOT_SERVED = {
4421
+ v3: [
4422
+ "/manager/queue/batch",
4423
+ "/manager/queue/task",
4424
+ "/manager/queue/history"
4425
+ ],
4426
+ "v4-legacy-ui": [
4427
+ "/manager/queue/install",
4428
+ "/manager/queue/task",
4429
+ "/manager/queue/history",
4430
+ "/manager/terminal"
4431
+ ],
4432
+ v4: [
4433
+ "/customnode/getlist",
4434
+ "/externalmodel/getlist",
4435
+ "/manager/queue/install",
4436
+ "/manager/queue/batch",
4437
+ "/manager/terminal"
4438
+ ]
4439
+ };
4440
+ const QueueStatus_ark = type({
4441
+ is_processing: "boolean",
4442
+ "pending_count?": "number",
4443
+ "total_count?": "number",
4444
+ "done_count?": "number"
4445
+ });
4446
+ const TaskHistory_ark = type({ history: {
4447
+ "status?": {
4448
+ status_str: "string",
4449
+ "messages?": "string[]"
4450
+ },
4451
+ "result?": "string"
4452
+ } });
4453
+ const ModelFolders_ark = type("string[]");
4454
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3908
4455
  var ComfyManager = class {
3909
- constructor(host) {
4456
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3910
4457
  this.host = host;
3911
- this.fetchPluginsAndModels = async () => {
3912
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3913
- this.pluginList = _pluginList;
3914
- this.modelList = _modelList;
4458
+ this.timing = timing;
4459
+ this.mirror = mirror;
4460
+ this.clientId = `comfy-ts-${nanoid(8)}`;
4461
+ this._api = null;
4462
+ this.api = () => {
4463
+ if (this._api == null) {
4464
+ const probe = this.probeApi();
4465
+ this._api = probe;
4466
+ probe.catch(() => {
4467
+ if (this._api === probe) this._api = null;
4468
+ });
4469
+ }
4470
+ return this._api;
4471
+ };
4472
+ this.probeApi = async () => {
4473
+ const v4 = await this.host.fetch("/v2/manager/version");
4474
+ if (v4.ok) {
4475
+ const version = (await v4.text()).trim();
4476
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4477
+ if (!ui.ok) {
4478
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4479
+ return {
4480
+ generation: "v4",
4481
+ version
4482
+ };
4483
+ }
4484
+ const flag = await ui.json();
4485
+ return {
4486
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4487
+ version
4488
+ };
4489
+ }
4490
+ const v3 = await this.host.fetch("/manager/version");
4491
+ if (v3.ok) return {
4492
+ generation: "v3",
4493
+ version: (await v3.text()).trim()
4494
+ };
4495
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4496
+ };
4497
+ this.route = (api, route, query = "") => {
4498
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4499
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4500
+ };
4501
+ this.strategy = (api) => {
4502
+ switch (api.generation) {
4503
+ case "v3": return {
4504
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4505
+ fetchModels: () => this.listedModels(api),
4506
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4507
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4508
+ };
4509
+ case "v4-legacy-ui": return {
4510
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4511
+ fetchModels: () => this.listedModels(api),
4512
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4513
+ const route = this.route(api, "/manager/queue/batch");
4514
+ const res = await this.post(route, { install: [body] });
4515
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4516
+ 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)`);
4517
+ }),
4518
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4519
+ };
4520
+ case "v4": return {
4521
+ fetchPlugins: () => this.installedPluginView(api),
4522
+ fetchModels: () => this.installedModelView(),
4523
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4524
+ settle: (what, uiId) => this.settleByHistory(api, what, uiId)
4525
+ };
4526
+ }
3915
4527
  };
3916
- this.configureLogging = (mi) => {
3917
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4528
+ this.configureLogging = async (mi) => {
4529
+ const api = await this.api();
4530
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4531
+ const response = await this.host.fetch(route);
4532
+ const text = await response.text();
4533
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4534
+ return text;
3918
4535
  };
3919
4536
  this.getModelInfoFinalFilePath = (mi) => {
3920
4537
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3921
4538
  };
3922
4539
  this.restartComfyUI = async () => {
4540
+ const api = await this.api();
4541
+ this._api = null;
4542
+ const route = this.route(api, "/manager/reboot");
3923
4543
  const refusals = [];
3924
4544
  for (const method of ["POST", "GET"]) {
3925
4545
  let response;
3926
4546
  try {
3927
- response = await this.host.fetch("/manager/reboot", { method });
4547
+ response = await this.host.fetch(route, { method });
3928
4548
  } catch {
3929
4549
  return;
3930
4550
  }
@@ -3932,31 +4552,42 @@ var ComfyManager = class {
3932
4552
  refusals.push(`${method} → ${response.status}`);
3933
4553
  if (response.status !== 404) break;
3934
4554
  }
3935
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4555
+ 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`);
4556
+ };
4557
+ this.fetchPluginsAndModels = async () => {
4558
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4559
+ this.pluginList = _pluginList;
4560
+ this.modelList = _modelList;
3936
4561
  };
3937
4562
  this.modelList = null;
3938
- this.fetchModels = () => {
3939
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4563
+ this.fetchModels = async () => {
4564
+ return this.strategy(await this.api()).fetchModels();
3940
4565
  };
3941
4566
  this.fetchLogs = () => {
3942
- return this.fetchGetJSON("/internal/logs");
4567
+ return this.getJSON("/internal/logs");
3943
4568
  };
3944
4569
  this.isModelInstalled = (name) => {
3945
4570
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3946
4571
  };
3947
4572
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3948
4573
  this.installModel = async (model) => {
4574
+ this.modelsBeeingInstalled.add(model.name);
3949
4575
  try {
3950
- this.modelsBeeingInstalled.add(model.name);
3951
- await this.fetchPost("/model/install", model);
3952
- this.modelsBeeingInstalled.delete(model.name);
3953
- logSuccess("Model installed");
3954
- return true;
3955
- } catch (exception) {
3956
- console.error(`Install failed: / ${exception}`);
3957
- logError("Model Installation Failed");
4576
+ return await this.runInstall(`model "${model.name}"`, {
4577
+ enqueue: async (api, uiId) => {
4578
+ const body = {
4579
+ ...model,
4580
+ ui_id: uiId,
4581
+ client_id: this.clientId
4582
+ };
4583
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4584
+ },
4585
+ landed: async (s) => {
4586
+ return (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base)?.installed === "True";
4587
+ }
4588
+ });
4589
+ } finally {
3958
4590
  this.modelsBeeingInstalled.delete(model.name);
3959
- return false;
3960
4591
  }
3961
4592
  };
3962
4593
  this.getModelStatus = (modelName) => {
@@ -3987,47 +4618,173 @@ var ComfyManager = class {
3987
4618
  })();
3988
4619
  };
3989
4620
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
3990
- try {
3991
- const skip_update = skipUpdate ? "&skip_update=true" : "";
3992
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
3993
- } catch (exception) {
3994
- console.error(`node list retrieval failed: ${exception}`);
3995
- logError("node list retrieveal failed");
3996
- throw exception;
3997
- }
4621
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4622
+ };
4623
+ this.installPlugin = async (plugin) => {
4624
+ return this.runInstall(`plugin "${plugin.title}"`, {
4625
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4626
+ landed: async (_s, api) => {
4627
+ const data = await this.installedData(api);
4628
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4629
+ }
4630
+ });
4631
+ };
4632
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4633
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4634
+ if (!("node_packs" in raw)) return raw;
4635
+ const titleByRepo = /* @__PURE__ */ new Map();
4636
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4637
+ return {
4638
+ chanel: raw.channel,
4639
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4640
+ const repo = p.files?.[0];
4641
+ return {
4642
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4643
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4644
+ };
4645
+ })
4646
+ };
4647
+ };
4648
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4649
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4650
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4651
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4652
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4653
+ };
4654
+ this.listedModels = async (api) => {
4655
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4656
+ };
4657
+ this.installedData = async (api) => {
4658
+ 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)]);
4659
+ return {
4660
+ installed,
4661
+ mappings
4662
+ };
4663
+ };
4664
+ this.installedPluginView = async (api) => {
4665
+ const view = buildPluginView({
4666
+ mirror: this.mirror(),
4667
+ ...await this.installedData(api)
4668
+ });
4669
+ 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`);
4670
+ return view.list;
4671
+ };
4672
+ this.installedModelView = async () => {
4673
+ const models = this.mirror().modelRows;
4674
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4675
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4676
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4677
+ return buildModelView({
4678
+ models,
4679
+ files: new Map(lists)
4680
+ });
4681
+ };
4682
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4683
+ const url = plugin.files[0] ?? plugin.reference;
4684
+ const list = await this.fetchPluginWire(api, "cache", true);
4685
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4686
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4687
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4688
+ const [key, row] = found;
4689
+ await send({
4690
+ ...row,
4691
+ id: row.id ?? key,
4692
+ channel: list.channel,
4693
+ mode: "cache",
4694
+ ui_id: uiId,
4695
+ skip_post_install: false
4696
+ });
4697
+ };
4698
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4699
+ const url = plugin.files[0] ?? plugin.reference;
4700
+ const params = {
4701
+ id: repoPath(url).split("/").pop() ?? url,
4702
+ version: "nightly",
4703
+ selected_version: "nightly",
4704
+ repository: url,
4705
+ mode: "cache",
4706
+ channel: "default"
4707
+ };
4708
+ await this.post(this.route(api, "/manager/queue/task"), {
4709
+ ui_id: uiId,
4710
+ client_id: this.clientId,
4711
+ kind: "install",
4712
+ params
4713
+ });
3998
4714
  };
3999
- this.installPlugin = async (model) => {
4715
+ this.settleByHistory = async (api, what, uiId) => {
4716
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4717
+ const entry = await this.waitFor(what, async () => {
4718
+ const status = (await this.getValid(route, TaskHistory_ark)).history.status;
4719
+ if (status == null) await this.restartIdleQueue(api);
4720
+ return status ?? null;
4721
+ });
4722
+ if (entry.status_str === "success" || entry.status_str === "skip") return;
4723
+ const messages = entry.messages ?? [];
4724
+ 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)" : "";
4725
+ throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4726
+ };
4727
+ this.restartIdleQueue = async (api) => {
4728
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4729
+ if (status.is_processing) return "running";
4730
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4731
+ await this.post(this.route(api, "/manager/queue/start"));
4732
+ return "restarted";
4733
+ };
4734
+ this.settleByDrain = async (api, what, landed) => {
4735
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4736
+ if (!await landed()) throw new Error(`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`);
4737
+ };
4738
+ this.runInstall = async (what, p) => {
4000
4739
  try {
4001
- await this.fetchPost("/customnode/install", model);
4002
- console.log("✅ Custom Node installed");
4003
- logSuccess("Custom Node installed");
4740
+ const api = await this.api();
4741
+ const s = this.strategy(api);
4742
+ const uiId = nanoid();
4743
+ await p.enqueue(api, uiId);
4744
+ await this.post(this.route(api, "/manager/queue/start"));
4745
+ await s.settle(what, uiId, () => p.landed(s, api));
4746
+ logSuccess(`${what} installed`);
4004
4747
  return true;
4005
4748
  } catch (exception) {
4006
- console.error(`Install failed: / ${exception}`);
4007
- logError("Custom Node Installation Failed");
4749
+ logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`);
4008
4750
  return false;
4009
4751
  }
4010
4752
  };
4011
- this.fetchPost = async (endpoint, body, validator) => {
4012
- const response = await this.host.fetch(endpoint, {
4753
+ this.waitFor = async (what, check) => {
4754
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4755
+ for (;;) {
4756
+ const value = await check();
4757
+ if (value != null) return value;
4758
+ if (Date.now() >= deadline) throw new Error(`${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4759
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4760
+ }
4761
+ };
4762
+ this.post = async (route, body) => {
4763
+ const response = await this.host.fetch(route, {
4013
4764
  method: "POST",
4014
4765
  headers: { "Content-Type": "application/json" },
4015
- body: JSON.stringify(body)
4766
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4016
4767
  });
4017
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4018
- const status = await response.json();
4019
- if (validator) return softValidate(validator, status);
4020
- return status;
4021
- };
4022
- this.fetchGetJSON = async (endpoint, validator) => {
4023
- const response = await this.host.fetch(endpoint);
4024
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4768
+ const text = await response.text();
4769
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4770
+ if (text === "") return null;
4771
+ try {
4772
+ return JSON.parse(text);
4773
+ } catch {
4774
+ return text;
4775
+ }
4776
+ };
4777
+ this.getJSON = async (route, validator) => {
4778
+ const response = await this.host.fetch(route);
4779
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4025
4780
  const jsonResult = await response.json();
4026
4781
  if (validator) return softValidate(validator, jsonResult);
4027
4782
  return jsonResult;
4028
4783
  };
4029
- this.fetchGetText = async (endopint) => {
4030
- return await (await this.host.fetch(endopint)).text();
4784
+ this.getValid = async (route, schema) => {
4785
+ const res = schema(await this.getJSON(route));
4786
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4787
+ return res;
4031
4788
  };
4032
4789
  }
4033
4790
  get registry() {
@@ -6174,6 +6931,7 @@ var ComfyHost = class {
6174
6931
  this.onLogs = null;
6175
6932
  this.comfySessionId = "temp";
6176
6933
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
6934
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6177
6935
  this.status = null;
6178
6936
  this.lastWsMessageAt = null;
6179
6937
  this.base = parseHostBase(this.data);
@@ -6413,9 +7171,26 @@ var ComfyHost = class {
6413
7171
  }
6414
7172
  return;
6415
7173
  }
6416
- const msg_ = JSON.parse(String(e.data));
6417
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6418
- if (msg_.type === "crystools.monitor") return;
7174
+ let msg_ = JSON.parse(String(e.data));
7175
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7176
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7177
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7178
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7179
+ const key = eventType ?? "<no type>";
7180
+ if (this._unknownWsEventTypes.has(key)) return;
7181
+ this._unknownWsEventTypes.add(key);
7182
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7183
+ return;
7184
+ }
7185
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7186
+ const data = Reflect.get(rec, "data");
7187
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7188
+ type: eventType,
7189
+ data: {
7190
+ ...data,
7191
+ prompt_id: this.activePromptID
7192
+ }
7193
+ };
6419
7194
  }
6420
7195
  const res = WsMsg_ark(msg_);
6421
7196
  if (res instanceof type.errors) {
@@ -6429,7 +7204,11 @@ var ComfyHost = class {
6429
7204
  this.comfySessionId = msg.data.sid;
6430
7205
  this._sessionResolve?.();
6431
7206
  this._sessionResolve = null;
6432
- if (sidChanged) this.onSession?.(msg.data.sid);
7207
+ if (sidChanged) {
7208
+ this._unknownWsEventTypes.clear();
7209
+ this._unknownBinaryFrameTypes.clear();
7210
+ this.onSession?.(msg.data.sid);
7211
+ }
6433
7212
  }
6434
7213
  this.status = msg.data.status;
6435
7214
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6444,7 +7223,7 @@ var ComfyHost = class {
6444
7223
  this.routeOrBuffer(activePromptID, msg);
6445
7224
  return;
6446
7225
  }
6447
- if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
7226
+ if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_interrupted" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
6448
7227
  this.routeOrBuffer(msg.data.prompt_id, msg);
6449
7228
  return;
6450
7229
  }
@@ -6456,8 +7235,6 @@ var ComfyHost = class {
6456
7235
  this.onLogs?.(msg.data);
6457
7236
  return;
6458
7237
  }
6459
- console.log("❌", "Unknown message:", msg);
6460
- logError("Unknown message type: " + JSON.stringify(msg.type));
6461
7238
  }
6462
7239
  };
6463
7240
  //#endregion
@@ -6786,6 +7563,7 @@ const _getKnownModels = (DB) => {
6786
7563
  }
6787
7564
  const knownModelList = canonical.concat(extraModels.models);
6788
7565
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7566
+ DB.modelRows = knownModelList;
6789
7567
  if (DB.opts.genTypes) {
6790
7568
  let out1 = "";
6791
7569
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6954,6 +7732,7 @@ var ComfyRegistry = class ComfyRegistry {
6954
7732
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6955
7733
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6956
7734
  this.knownModels = /* @__PURE__ */ new Map();
7735
+ this.modelRows = [];
6957
7736
  this.alterations = [];
6958
7737
  this.githubStats = /* @__PURE__ */ new Map();
6959
7738
  this.report = new ManagerParseReport();