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/index.js CHANGED
@@ -110,7 +110,7 @@ function createNodeStorage() {
110
110
  }
111
111
  //#endregion
112
112
  //#region package.json
113
- var version = "2.17.1";
113
+ var version = "2.18.0";
114
114
  //#endregion
115
115
  //#region src/litegraph/LiteGraphLinkID.ts
116
116
  const asLiteGraphLinkID = (id) => id;
@@ -266,7 +266,8 @@ const expandOneInstance = (wf, instance, def) => {
266
266
  name: i.name,
267
267
  type: i.type,
268
268
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
269
- widgetName: i.widgetName
269
+ widgetName: i.widgetName,
270
+ widgetSource: i.widgetSource
270
271
  })),
271
272
  outputs: inner.outputs.map((o) => ({
272
273
  name: o.name,
@@ -307,6 +308,20 @@ const expandOneInstance = (wf, instance, def) => {
307
308
  wf.links = wf.links.filter((l) => !dead.has(l.id));
308
309
  pruneDeadLinkRefs(wf, dead);
309
310
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
311
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
312
+ if (outerLinkIntoDefSlot.has(slot)) continue;
313
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
314
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
315
+ if (source == null || sourceInput == null) continue;
316
+ for (const t of targets) {
317
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
318
+ if (input == null || input.widgetName != null || input.link != null) continue;
319
+ input.widgetSource = {
320
+ nodeId: source.nodeId,
321
+ inputName: sourceInput.name
322
+ };
323
+ }
324
+ }
310
325
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
311
326
  wf.nodes.push(...splicedNodes);
312
327
  wf.links.push(...splicedLinks);
@@ -418,7 +433,7 @@ const LiteGraphNodeInput_ark = type({
418
433
  type: "string",
419
434
  "link?": LiteGraphLinkID_.or(type.null),
420
435
  "shape?": "number",
421
- "label?": "string",
436
+ "label?": type.string.or(type.null),
422
437
  "widget?": type({
423
438
  name: "string",
424
439
  "config?": "unknown"
@@ -435,7 +450,7 @@ const LiteGraphNodeOutput_ark = type({
435
450
  type: "string",
436
451
  "links?": LiteGraphLinkID_.array().or(type.null),
437
452
  "shape?": "number",
438
- "slot_index?": LiteGraphSlotIndex_
453
+ "slot_index?": LiteGraphSlotIndex_.or(type.null)
439
454
  });
440
455
  //#endregion
441
456
  //#region src/litegraph/LiteGraphNode.ts
@@ -505,7 +520,7 @@ const LiteGraphSubgraphDef_ark = type({
505
520
  const LiteGraphJSON_ark = type({
506
521
  "id?": "string",
507
522
  "revision?": "number",
508
- "last_node_id?": "number",
523
+ "last_node_id?": "number | string",
509
524
  "last_link_id?": "number",
510
525
  "state?": type.Record("string", "unknown"),
511
526
  nodes: LiteGraphNode_ark.array(),
@@ -604,7 +619,8 @@ const normalizeInput = (i) => {
604
619
  name: i.name,
605
620
  type: i.type,
606
621
  link: i.link ?? null,
607
- widgetName: i.widget?.name ?? null
622
+ widgetName: i.widget?.name ?? null,
623
+ widgetSource: null
608
624
  };
609
625
  };
610
626
  const normalizeOutput = (o) => {
@@ -777,6 +793,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
777
793
  python_module: "nodes"
778
794
  };
779
795
  //#endregion
796
+ //#region src/utils/exhaust.ts
797
+ function exhaust(x) {
798
+ return x;
799
+ }
800
+ //#endregion
780
801
  //#region src/sdk-generator/inputWidgetKind.ts
781
802
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
782
803
  /**
@@ -845,6 +866,14 @@ const parseContainer = (template) => {
845
866
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
846
867
  };
847
868
  };
869
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
870
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
871
+ const parseGroup = (o, template) => ({
872
+ kind: "dynamic-group",
873
+ fields: flattenInputSections(template),
874
+ min: typeof o["min"] === "number" ? o["min"] : 0,
875
+ max: typeof o["max"] === "number" ? o["max"] : 20
876
+ });
848
877
  /**
849
878
  * the single template sub-input's slot type of an autogrow container
850
879
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -919,11 +948,12 @@ const classifyWidgetInput = (p) => {
919
948
  };
920
949
  }
921
950
  const template = o?.["template"];
922
- if (isRecord$1(template)) {
951
+ if (o != null && isRecord$1(template)) {
923
952
  if (isRecord$1(template["input"])) return parseContainer(template);
953
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
924
954
  return { kind: "slot" };
925
955
  }
926
- if (o?.["socketless"] === true) return {
956
+ if (typeof o?.["socketless"] === "boolean") return {
927
957
  kind: "widget",
928
958
  consumes: 1,
929
959
  strictValues: false,
@@ -1096,18 +1126,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1096
1126
  inputs[p.path] = key;
1097
1127
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1098
1128
  };
1129
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1130
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1131
+ const consumeDynamicGroup = (p) => {
1132
+ const r = resolveWidgetValue({
1133
+ promptName: p.path,
1134
+ consumes: 1,
1135
+ prefixLen: 0
1136
+ });
1137
+ const saved = r.filled ? p.min : r.value;
1138
+ 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);
1139
+ const rows = Math.max(p.min, saved);
1140
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1141
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1142
+ };
1099
1143
  const consumeBranchInput = (subPath, sub) => {
1100
1144
  const kind = classifyWidgetInput({
1101
- name: sub.name,
1145
+ name: subPath,
1102
1146
  type: sub.type,
1103
1147
  opts: sub.opts
1104
1148
  });
1105
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1106
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1107
- path: subPath,
1108
- options: kind.options,
1109
- defaultKey: kind.defaultKey
1110
- });
1149
+ switch (kind.kind) {
1150
+ case "slot":
1151
+ case "dynamic-container": return;
1152
+ case "dynamic-combo": return consumeDynamicCombo({
1153
+ path: subPath,
1154
+ options: kind.options,
1155
+ defaultKey: kind.defaultKey
1156
+ });
1157
+ case "dynamic-group": return consumeDynamicGroup({
1158
+ path: subPath,
1159
+ fields: kind.fields,
1160
+ min: kind.min,
1161
+ max: kind.max
1162
+ });
1163
+ case "widget": break;
1164
+ default: return exhaust(kind);
1165
+ }
1111
1166
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1112
1167
  consumePlainWidget({
1113
1168
  promptName: subPath,
@@ -1129,26 +1184,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1129
1184
  strictValues: true,
1130
1185
  prefixValues: []
1131
1186
  };
1132
- if (kind.kind === "widget") consumePlainWidget({
1133
- promptName: field.nameInComfy,
1134
- typeName: field.typeName,
1135
- opts: field.opts,
1136
- consumes: kind.consumes,
1137
- prefixLen: kind.prefixValues.length,
1138
- strict: kind.strictValues,
1139
- linkedInput: input
1140
- });
1141
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1142
- path: field.nameInComfy,
1143
- options: kind.options,
1144
- defaultKey: kind.defaultKey
1145
- });
1146
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1147
- const iname = `${field.nameInComfy}.${instName}`;
1148
- if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1149
- }
1150
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1151
- if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
1187
+ switch (kind.kind) {
1188
+ case "widget":
1189
+ consumePlainWidget({
1190
+ promptName: field.nameInComfy,
1191
+ typeName: field.typeName,
1192
+ opts: field.opts,
1193
+ consumes: kind.consumes,
1194
+ prefixLen: kind.prefixValues.length,
1195
+ strict: kind.strictValues,
1196
+ linkedInput: input
1197
+ });
1198
+ break;
1199
+ case "dynamic-combo":
1200
+ consumeDynamicCombo({
1201
+ path: field.nameInComfy,
1202
+ options: kind.options,
1203
+ defaultKey: kind.defaultKey
1204
+ });
1205
+ break;
1206
+ case "dynamic-group":
1207
+ consumeDynamicGroup({
1208
+ path: field.nameInComfy,
1209
+ fields: kind.fields,
1210
+ min: kind.min,
1211
+ max: kind.max
1212
+ });
1213
+ break;
1214
+ case "dynamic-container":
1215
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1216
+ const iname = `${field.nameInComfy}.${instName}`;
1217
+ 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);
1218
+ }
1219
+ break;
1220
+ case "slot":
1221
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1222
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1223
+ promptName: field.nameInComfy,
1224
+ strict: false
1225
+ });
1226
+ break;
1227
+ }
1228
+ 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);
1229
+ break;
1230
+ default:
1152
1231
  }
1153
1232
  }
1154
1233
  const getParentNode = (linkId) => {
@@ -1254,6 +1333,45 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1254
1333
  class_type: node.type
1255
1334
  };
1256
1335
  }
1336
+ for (const node of workflow.nodes) {
1337
+ const own = prompt[String(node.id)];
1338
+ if (own == null) continue;
1339
+ for (const ipt of node.inputs) {
1340
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1341
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1342
+ if (value !== void 0) own.inputs[ipt.name] = value;
1343
+ }
1344
+ }
1345
+ const missing = /* @__PURE__ */ new Map();
1346
+ for (const node of workflow.nodes) {
1347
+ const own = prompt[String(node.id)];
1348
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1349
+ if (own == null || nodeSchema == null) continue;
1350
+ for (const field of nodeSchema.inputs) {
1351
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1352
+ const kind = classifySchemaInput(field).kind;
1353
+ if (kind !== "slot" && kind !== "widget") continue;
1354
+ missing.set(String(node.id), {
1355
+ node,
1356
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1357
+ });
1358
+ break;
1359
+ }
1360
+ }
1361
+ if (missing.size > 0) {
1362
+ const complete = (id, seen) => {
1363
+ if (seen.has(id)) return true;
1364
+ seen.add(id);
1365
+ if (missing.has(id)) return false;
1366
+ for (const value of Object.values(prompt[id]?.inputs ?? {})) if (Array.isArray(value) && typeof value[0] === "string" && !complete(value[0], seen)) return false;
1367
+ return true;
1368
+ };
1369
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1370
+ const dropped = outputs.filter((id) => !complete(id, /* @__PURE__ */ new Set()));
1371
+ const first = missing.values().next().value;
1372
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1373
+ 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("; ")}`);
1374
+ }
1257
1375
  return prompt;
1258
1376
  };
1259
1377
  //#endregion
@@ -1434,21 +1552,37 @@ var ComfyNode = class ComfyNode {
1434
1552
  _convertPromptExtToPrompt(promptExt) {
1435
1553
  const inputs = {};
1436
1554
  const _done = /* @__PURE__ */ new Set();
1437
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1555
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1438
1556
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1439
1557
  for (const i of this.$schema.inputs) {
1440
1558
  _done.add(i.nameInComfy);
1441
1559
  const kind = classifySchemaInput(i);
1442
- if (kind.kind === "dynamic-combo") {
1443
- this._writeDynamicCombo({
1444
- name: i.nameInComfy,
1445
- options: kind.options,
1446
- defaultKey: kind.defaultKey,
1447
- provided: promptExt.inputs,
1448
- out: inputs,
1449
- claimed: _comboBranchKeys
1450
- });
1451
- continue;
1560
+ switch (kind.kind) {
1561
+ case "dynamic-combo":
1562
+ this._writeDynamicCombo({
1563
+ name: i.nameInComfy,
1564
+ options: kind.options,
1565
+ defaultKey: kind.defaultKey,
1566
+ provided: promptExt.inputs,
1567
+ out: inputs,
1568
+ claimed: _comboBranchKeys
1569
+ });
1570
+ continue;
1571
+ case "dynamic-group":
1572
+ this._writeDynamicGroup({
1573
+ name: i.nameInComfy,
1574
+ fields: kind.fields,
1575
+ min: kind.min,
1576
+ max: kind.max,
1577
+ provided: promptExt.inputs,
1578
+ out: inputs,
1579
+ claimed: _comboBranchKeys
1580
+ });
1581
+ continue;
1582
+ case "widget":
1583
+ case "slot":
1584
+ case "dynamic-container": break;
1585
+ default:
1452
1586
  }
1453
1587
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1454
1588
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1487,6 +1621,42 @@ var ComfyNode = class ComfyNode {
1487
1621
  }) : this.serializeValue(dotted, given);
1488
1622
  }
1489
1623
  }
1624
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1625
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1626
+ * keys are already the rows: they pass through the rest loop untouched */
1627
+ _writeDynamicGroup(p) {
1628
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1629
+ const raw = p.provided[p.name];
1630
+ const prefix = `${p.name}.`;
1631
+ if (raw == null) {
1632
+ 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)`);
1633
+ return;
1634
+ }
1635
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1636
+ if (!Array.isArray(raw)) {
1637
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1638
+ return;
1639
+ }
1640
+ 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}`);
1641
+ raw.forEach((row, ix) => {
1642
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1643
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1644
+ return;
1645
+ }
1646
+ const given = new Map(Object.entries(row));
1647
+ for (const field of p.fields) {
1648
+ const dotted = `${p.name}.${ix}.${field.name}`;
1649
+ const value = given.get(field.name);
1650
+ p.out[dotted] = value == null ? defaultValueForWidget({
1651
+ type: typeof field.type === "string" ? field.type : "COMBO",
1652
+ opts: field.opts,
1653
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1654
+ }) : this.serializeValue(dotted, value);
1655
+ given.delete(field.name);
1656
+ }
1657
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1658
+ });
1659
+ }
1490
1660
  /** return the list of nodes piped into this node */
1491
1661
  _incomingNodes() {
1492
1662
  const incomingNodes = [];
@@ -1630,6 +1800,12 @@ var ComfyNode = class ComfyNode {
1630
1800
  const kind = classifySchemaInput(decl);
1631
1801
  const slotType = containerInstanceSlotType(decl.opts);
1632
1802
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1803
+ if (kind.kind === "dynamic-group") {
1804
+ const rest = name.slice(dot + 1);
1805
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1806
+ const field = kind.fields.find((f) => f.name === fieldName);
1807
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1808
+ }
1633
1809
  }
1634
1810
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1635
1811
  }
@@ -1713,44 +1889,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1713
1889
  const convertNodeToLiteGraphNode = (ctx, node) => {
1714
1890
  const inputs = [];
1715
1891
  const widgets_values = [];
1716
- const pushLinked = (name, type, link, shape) => {
1892
+ const pushLinked = (name, type, link, extra = {}) => {
1717
1893
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1718
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1719
- inputs.push(shape == null ? {
1894
+ const input = {
1720
1895
  name,
1721
1896
  type,
1722
- link: linkId
1723
- } : {
1897
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1898
+ };
1899
+ if (extra.shape != null) input.shape = extra.shape;
1900
+ if (extra.widget === true) input.widget = { name };
1901
+ inputs.push(input);
1902
+ };
1903
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1904
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1905
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1906
+ * never disagree on the run length */
1907
+ const pushWidgetRun = (kind, raw, opts) => {
1908
+ widgets_values.push(...kind.prefixValues, raw);
1909
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1910
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1911
+ };
1912
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1913
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1914
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1915
+ const writeInput = (p) => {
1916
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1917
+ switch (p.kind.kind) {
1918
+ case "widget":
1919
+ if (_isLink(p.value)) {
1920
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
1921
+ pushWidgetRun(p.kind, defaultValueForWidget({
1922
+ type: p.typeName,
1923
+ opts: p.opts
1924
+ }), p.opts);
1925
+ } else pushWidgetRun(p.kind, p.value, p.opts);
1926
+ return;
1927
+ case "slot":
1928
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
1929
+ else inputs.push({
1930
+ name: p.name,
1931
+ type: p.typeName,
1932
+ link: null
1933
+ });
1934
+ return;
1935
+ case "dynamic-combo": {
1936
+ const kind = p.kind;
1937
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
1938
+ const option = kind.options.find((o) => o.key === key);
1939
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
1940
+ widgets_values.push(key);
1941
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
1942
+ return;
1943
+ }
1944
+ case "dynamic-container": {
1945
+ const type = containerInstanceSlotType(p.opts) ?? "*";
1946
+ for (const instance of p.kind.instanceNames) {
1947
+ const name = `${p.name}.${instance}`;
1948
+ const value = node.json.inputs[name];
1949
+ if (value == null) continue;
1950
+ const raw = node.serializeValue(name, value);
1951
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
1952
+ pushLinked(name, type, raw, { shape: 7 });
1953
+ }
1954
+ return;
1955
+ }
1956
+ case "dynamic-group": {
1957
+ const prefix = `${p.name}.`;
1958
+ let rows = 0;
1959
+ for (const key of Object.keys(node.json.inputs)) {
1960
+ if (!key.startsWith(prefix)) continue;
1961
+ const row = Number(key.slice(prefix.length).split(".")[0]);
1962
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
1963
+ }
1964
+ widgets_values.push(rows);
1965
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
1966
+ return;
1967
+ }
1968
+ default: p.kind;
1969
+ }
1970
+ };
1971
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
1972
+ * value is the widget's schema default rather than serializeValue's */
1973
+ const writeSub = (name, sub) => {
1974
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
1975
+ const raw = node.json.inputs[name];
1976
+ writeInput({
1724
1977
  name,
1725
- type,
1726
- shape,
1727
- link: linkId
1978
+ kind: classifyWidgetInput({
1979
+ name,
1980
+ type: sub.type,
1981
+ opts: sub.opts
1982
+ }),
1983
+ typeName,
1984
+ opts: sub.opts,
1985
+ value: raw === void 0 ? defaultValueForWidget({
1986
+ type: typeName,
1987
+ opts: sub.opts
1988
+ }) : raw
1728
1989
  });
1729
1990
  };
1730
1991
  for (const ipt of node.$schema.inputs) {
1731
1992
  const kind = classifySchemaInput(ipt);
1732
- if (kind.kind === "dynamic-container") {
1733
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1734
- for (const instance of kind.instanceNames) {
1735
- const name = `${ipt.nameInComfy}.${instance}`;
1736
- const value = node.json.inputs[name];
1737
- if (value == null) continue;
1738
- const raw = node.serializeValue(name, value);
1739
- if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${node.$schema.nameInComfy}#${node.uid} "${name}" holds a literal; an autogrow instance is a link slot in the editor`);
1740
- pushLinked(name, type, raw, 7);
1741
- }
1742
- continue;
1743
- }
1744
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1745
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1746
- else if (kind.kind === "widget") {
1747
- widgets_values.push(...kind.prefixValues, raw);
1748
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1749
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1750
- } else inputs.push({
1993
+ const raw = node.json.inputs[ipt.nameInComfy];
1994
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
1995
+ writeInput({
1751
1996
  name: ipt.nameInComfy,
1752
- type: ipt.typeName,
1753
- link: null
1997
+ kind,
1998
+ typeName: ipt.typeName,
1999
+ opts: ipt.opts,
2000
+ value
1754
2001
  });
1755
2002
  }
1756
2003
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1936,11 +2183,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1936
2183
  return resultSuccess(txt_chunks);
1937
2184
  };
1938
2185
  //#endregion
1939
- //#region src/utils/exhaust.ts
1940
- function exhaust(x) {
1941
- return x;
1942
- }
1943
- //#endregion
1944
2186
  //#region src/utils/sha1.ts
1945
2187
  function sha1Hex(data) {
1946
2188
  const ml = data.length;
@@ -2075,16 +2317,17 @@ const types$1 = scope({
2075
2317
  },
2076
2318
  _WsMsgExecutedData: {
2077
2319
  node: "ComfyNodeID",
2078
- output: {
2079
- "previews?": [{ filepath: "string" }, "[]"],
2080
- "images?": "ComfyImageInfo[]",
2081
- "audio?": "ComfyImageInfo[]",
2082
- "video?": "ComfyImageInfo[]",
2083
- "gifs?": "ComfyImageInfo[]",
2084
- "text?": "unknown[]"
2085
- },
2320
+ output: "_WsMsgExecutedOutput | null",
2086
2321
  prompt_id: "PromptID"
2087
2322
  },
2323
+ _WsMsgExecutedOutput: {
2324
+ "previews?": [{ filepath: "string" }, "[]"],
2325
+ "images?": "ComfyImageInfo[]",
2326
+ "audio?": "ComfyImageInfo[]",
2327
+ "video?": "ComfyImageInfo[]",
2328
+ "gifs?": "ComfyImageInfo[]",
2329
+ "text?": "unknown[]"
2330
+ },
2088
2331
  WsMsgExecuted: {
2089
2332
  type: "'executed'",
2090
2333
  data: "_WsMsgExecutedData"
@@ -2106,12 +2349,22 @@ const types$1 = scope({
2106
2349
  exception_type: "string",
2107
2350
  traceback: "string[]",
2108
2351
  current_inputs: "Record<string, unknown>",
2109
- current_outputs: "Record<string, unknown>"
2352
+ current_outputs: "ComfyNodeID[]"
2110
2353
  },
2111
2354
  WsMsgExecutionError: {
2112
2355
  type: "'execution_error'",
2113
2356
  data: "_WsMsgExecutionErrorData"
2114
2357
  },
2358
+ _WsMsgExecutionInterruptedData: {
2359
+ prompt_id: "PromptID",
2360
+ node_id: "ComfyNodeID",
2361
+ node_type: "string",
2362
+ executed: "ComfyNodeID[]"
2363
+ },
2364
+ WsMsgExecutionInterrupted: {
2365
+ type: "'execution_interrupted'",
2366
+ data: "_WsMsgExecutionInterruptedData"
2367
+ },
2115
2368
  WSMsgManagerFeedbackData: { data: "string" },
2116
2369
  WSMsgManagerFeedback: {
2117
2370
  type: "'manager-terminal-feedback'",
@@ -2141,11 +2394,51 @@ const types$1 = scope({
2141
2394
  type: "'progress_state'",
2142
2395
  data: "_WsMsgProgressStateData"
2143
2396
  },
2144
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2397
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2145
2398
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2146
2399
  }).export();
2147
2400
  const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2148
2401
  const WsMsg_ark = types$1.WsMsg;
2402
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2403
+ const ROUTED_WS_EVENT_TYPES = [
2404
+ "status",
2405
+ "manager-terminal-feedback",
2406
+ "logs",
2407
+ "execution_start",
2408
+ "execution_cached",
2409
+ "executing",
2410
+ "progress",
2411
+ "progress_state",
2412
+ "executed",
2413
+ "execution_error",
2414
+ "execution_interrupted",
2415
+ "execution_success"
2416
+ ];
2417
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2418
+ * before validation, never logged (architecture.md, ws events) */
2419
+ const IGNORED_WS_EVENT_TYPES = [
2420
+ "feature_flags",
2421
+ "agent_status",
2422
+ "asset_export",
2423
+ "assets.seed.started",
2424
+ "assets.seed.progress",
2425
+ "assets.seed.fast_complete",
2426
+ "assets.seed.enrich_complete",
2427
+ "assets.seed.completed",
2428
+ "assets.seed.cancelled",
2429
+ "assets.seed.error",
2430
+ "assets.seed.paused",
2431
+ "assets.seed.resumed",
2432
+ "cm-queue-status",
2433
+ "cm-api-try-install-customnode",
2434
+ "cm-task-started",
2435
+ "cm-task-completed",
2436
+ "crystools.monitor"
2437
+ ];
2438
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2439
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2440
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2441
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2149
2442
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2150
2443
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2151
2444
  //#endregion
@@ -2435,6 +2728,10 @@ var ComfyExecution = class {
2435
2728
  else if (msg.type === "progress") graph.onProgress(msg);
2436
2729
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2437
2730
  else if (msg.type === "execution_error") return void this.onError(msg);
2731
+ else if (msg.type === "execution_interrupted") return void this._finish({
2732
+ status: "Failure",
2733
+ error: msg
2734
+ });
2438
2735
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2439
2736
  else {
2440
2737
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3348,6 +3645,15 @@ const dynamicComboUnion = (p) => {
3348
3645
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3349
3646
  }).join(" | ")})`;
3350
3647
  };
3648
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3649
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3650
+ const dynamicGroupRow = (fields) => {
3651
+ return `{ ${fields.map((e) => {
3652
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3653
+ const optional = !e.required || opts?.["default"] !== void 0;
3654
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3655
+ }).join("; ")} }`;
3656
+ };
3351
3657
  /**
3352
3658
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3353
3659
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3396,6 +3702,8 @@ function codegenSDK(opts) {
3396
3702
  b.deindent();
3397
3703
  p(`// #endregion`);
3398
3704
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3705
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3706
+ const groupRows = [];
3399
3707
  p(`interface IN {`);
3400
3708
  b.indent();
3401
3709
  for (const n of nodes) {
@@ -3403,23 +3711,37 @@ function codegenSDK(opts) {
3403
3711
  const comboSuffixes = [];
3404
3712
  for (const i of n.inputs) {
3405
3713
  const kind = classifySchemaInput(i);
3406
- if (kind.kind === "dynamic-container") {
3407
- const instType = containerInstanceSlotType(i.opts);
3408
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3409
- const opt = ix >= kind.requiredCount ? "?" : "";
3410
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3411
- });
3412
- continue;
3413
- }
3414
- if (kind.kind === "dynamic-combo") {
3415
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3416
- comboSuffixes.push(dynamicComboUnion({
3417
- name: i.nameInComfy,
3418
- nameEscaped: i.nameInComfyEscaped,
3419
- options: kind.options,
3420
- keyOptional: optsDyn?.default !== void 0 || !i.required
3421
- }));
3422
- continue;
3714
+ switch (kind.kind) {
3715
+ case "dynamic-container": {
3716
+ const instType = containerInstanceSlotType(i.opts);
3717
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3718
+ const opt = ix >= kind.requiredCount ? "?" : "";
3719
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3720
+ });
3721
+ continue;
3722
+ }
3723
+ case "dynamic-combo": {
3724
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3725
+ comboSuffixes.push(dynamicComboUnion({
3726
+ name: i.nameInComfy,
3727
+ nameEscaped: i.nameInComfyEscaped,
3728
+ options: kind.options,
3729
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3730
+ }));
3731
+ continue;
3732
+ }
3733
+ case "dynamic-group": {
3734
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3735
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3736
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3737
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3738
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3739
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3740
+ continue;
3741
+ }
3742
+ case "widget":
3743
+ case "slot": break;
3744
+ default:
3423
3745
  }
3424
3746
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3425
3747
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3442,6 +3764,15 @@ function codegenSDK(opts) {
3442
3764
  b.deindent();
3443
3765
  p("}");
3444
3766
  p("");
3767
+ if (groupRows.length > 0) {
3768
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3769
+ p(`interface GroupRow {`);
3770
+ b.indent();
3771
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3772
+ b.deindent();
3773
+ p("}");
3774
+ p("");
3775
+ }
3445
3776
  p(`interface OUT {`);
3446
3777
  b.indent();
3447
3778
  for (const n of nodes) {
@@ -3754,9 +4085,13 @@ var ComfySchema = class {
3754
4085
  if (widgetKind?.kind === "dynamic-combo") {
3755
4086
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3756
4087
  }
4088
+ if (widgetKind?.kind === "dynamic-group") {
4089
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4090
+ }
4091
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3757
4092
  node.inputs.push({
3758
4093
  slotName: inputSlotName,
3759
- required: ipt.required && !isAutogrowContainer,
4094
+ required,
3760
4095
  nameInComfy: inputNameInComfy,
3761
4096
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3762
4097
  typeName: inputTypeName,
@@ -3832,7 +4167,12 @@ const types = scope({
3832
4167
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3833
4168
  ComfyInputSpecAlt2: ["ComfyInputType"],
3834
4169
  ComfyInputSpecAlt3: type([type.null]),
3835
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4170
+ ComfyInputSpecAlt4: [
4171
+ "ComfyInputType",
4172
+ "ComfyInputOpts",
4173
+ "unknown"
4174
+ ],
4175
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3836
4176
  ComfyInputType: `string | ComfyEnumDef`,
3837
4177
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3838
4178
  ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
@@ -3898,10 +4238,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3898
4238
  return result;
3899
4239
  }
3900
4240
  //#endregion
4241
+ //#region src/manager/installedView.ts
4242
+ /**
4243
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4244
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4245
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4246
+ */
4247
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4248
+ const InstalledPacks_ark = type.Record("string", type({
4249
+ "cnr_id?": "string | null",
4250
+ "aux_id?": "string | null",
4251
+ enabled: "boolean"
4252
+ }));
4253
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4254
+ const PackMappings_ark = type.Record("string", type(["string[]", { "title_aux?": "string" }]));
4255
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4256
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4257
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4258
+ const attributePacks = (installed, mappings) => {
4259
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4260
+ return Object.entries(installed).map(([dir, p]) => {
4261
+ const aux = p.aux_id ?? null;
4262
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4263
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4264
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4265
+ return {
4266
+ enabled: p.enabled,
4267
+ repo,
4268
+ title,
4269
+ id: cnr ?? aux ?? dir
4270
+ };
4271
+ });
4272
+ };
4273
+ /** is this mirror row among the attributed packs, enabled? */
4274
+ const packIsInstalled = (packs, plugin) => {
4275
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4276
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4277
+ };
4278
+ const buildPluginView = (p) => {
4279
+ const packs = attributePacks(p.installed, p.mappings);
4280
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4281
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4282
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4283
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4284
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4285
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4286
+ const custom_nodes = [];
4287
+ for (const plugin of plugins) {
4288
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4289
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4290
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4291
+ title: plugin.title,
4292
+ installed: "True"
4293
+ });
4294
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4295
+ else custom_nodes.push({
4296
+ title: plugin.title,
4297
+ installed: "False"
4298
+ });
4299
+ }
4300
+ return {
4301
+ list: {
4302
+ chanel: "default",
4303
+ custom_nodes
4304
+ },
4305
+ unattributed: unattributed.map((x) => x.id)
4306
+ };
4307
+ };
4308
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4309
+ const DEFAULT_FOLDER_BY_TYPE = {
4310
+ checkpoints: "checkpoints",
4311
+ checkpoint: "checkpoints",
4312
+ unclip: "checkpoints",
4313
+ text_encoders: "text_encoders",
4314
+ clip: "text_encoders",
4315
+ vae: "vae",
4316
+ lora: "loras",
4317
+ "t2i-adapter": "controlnet",
4318
+ "t2i-style": "controlnet",
4319
+ controlnet: "controlnet",
4320
+ clip_vision: "clip_vision",
4321
+ gligen: "gligen",
4322
+ upscale: "upscale_models",
4323
+ embedding: "embeddings",
4324
+ embeddings: "embeddings",
4325
+ unet: "diffusion_models",
4326
+ diffusion_model: "diffusion_models"
4327
+ };
4328
+ /** what core `get_filename_list` lists in the standard folders */
4329
+ const LISTED_EXTENSIONS = [
4330
+ ".ckpt",
4331
+ ".pt",
4332
+ ".pt2",
4333
+ ".bin",
4334
+ ".pth",
4335
+ ".safetensors",
4336
+ ".pkl",
4337
+ ".sft"
4338
+ ];
4339
+ /**
4340
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4341
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4342
+ */
4343
+ const modelLocation = (m) => {
4344
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4345
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4346
+ if (m.save_path === "default") {
4347
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4348
+ return folder == null ? null : {
4349
+ folder,
4350
+ files: [m.filename]
4351
+ };
4352
+ }
4353
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4354
+ const folder = parts[0];
4355
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4356
+ const sub = [...parts.slice(1), m.filename].join("/");
4357
+ return {
4358
+ folder,
4359
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4360
+ };
4361
+ };
4362
+ const buildModelView = (p) => {
4363
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4364
+ const statusOf = (m) => {
4365
+ const at = modelLocation(m);
4366
+ const files = at == null ? null : listed.get(at.folder);
4367
+ if (at == null || files == null) return null;
4368
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4369
+ };
4370
+ const byName = /* @__PURE__ */ new Map();
4371
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4372
+ const models = [];
4373
+ for (const rows of byName.values()) {
4374
+ const statuses = new Set(rows.map(statusOf));
4375
+ const first = rows[0];
4376
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4377
+ if (first == null || installed == null) continue;
4378
+ models.push({
4379
+ name: first.name,
4380
+ installed,
4381
+ filename: first.filename,
4382
+ save_path: first.save_path,
4383
+ base: first.base
4384
+ });
4385
+ }
4386
+ return { models };
4387
+ };
4388
+ /** the folders the views need listed */
4389
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4390
+ //#endregion
3901
4391
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3902
4392
  const ComfyManagerAPIModelList_ark = type({ models: type({
3903
4393
  name: type.string.as(),
3904
- installed: `'False' | 'True' | 'Update'`
4394
+ installed: `'False' | 'True' | 'Update'`,
4395
+ "filename?": "string",
4396
+ "save_path?": "string",
4397
+ "base?": "string"
3905
4398
  }).array() });
3906
4399
  //#endregion
3907
4400
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3912,28 +4405,155 @@ const ComfyManagerAPIPluginList_ark = type({
3912
4405
  }).array(),
3913
4406
  chanel: "string"
3914
4407
  });
4408
+ const ComfyManagerAPIPack_ark = type({
4409
+ title: type.string.as(),
4410
+ "id?": "string",
4411
+ "files?": "string[]",
4412
+ "repository?": "string",
4413
+ "version?": "string",
4414
+ "state?": "string",
4415
+ "update-state?": "string"
4416
+ });
4417
+ const ComfyManagerAPIPackList_ark = type({
4418
+ channel: "string",
4419
+ node_packs: type.Record("string", ComfyManagerAPIPack_ark)
4420
+ });
3915
4421
  //#endregion
3916
4422
  //#region src/host/ComfyManager.ts
4423
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4424
+ const MANAGER_TIMING = {
4425
+ pollMs: 1e3,
4426
+ installTimeoutMs: 60 * 6e4
4427
+ };
4428
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4429
+ const NOT_SERVED = {
4430
+ v3: [
4431
+ "/manager/queue/batch",
4432
+ "/manager/queue/task",
4433
+ "/manager/queue/history"
4434
+ ],
4435
+ "v4-legacy-ui": [
4436
+ "/manager/queue/install",
4437
+ "/manager/queue/task",
4438
+ "/manager/queue/history",
4439
+ "/manager/terminal"
4440
+ ],
4441
+ v4: [
4442
+ "/customnode/getlist",
4443
+ "/externalmodel/getlist",
4444
+ "/manager/queue/install",
4445
+ "/manager/queue/batch",
4446
+ "/manager/terminal"
4447
+ ]
4448
+ };
4449
+ const QueueStatus_ark = type({
4450
+ is_processing: "boolean",
4451
+ "pending_count?": "number",
4452
+ "total_count?": "number",
4453
+ "done_count?": "number"
4454
+ });
4455
+ const TaskHistory_ark = type({ history: {
4456
+ "status?": {
4457
+ status_str: "string",
4458
+ "messages?": "string[]"
4459
+ },
4460
+ "result?": "string"
4461
+ } });
4462
+ const ModelFolders_ark = type("string[]");
4463
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3917
4464
  var ComfyManager = class {
3918
- constructor(host) {
4465
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3919
4466
  this.host = host;
3920
- this.fetchPluginsAndModels = async () => {
3921
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3922
- this.pluginList = _pluginList;
3923
- this.modelList = _modelList;
4467
+ this.timing = timing;
4468
+ this.mirror = mirror;
4469
+ this.clientId = `comfy-ts-${nanoid(8)}`;
4470
+ this._api = null;
4471
+ this.api = () => {
4472
+ if (this._api == null) {
4473
+ const probe = this.probeApi();
4474
+ this._api = probe;
4475
+ probe.catch(() => {
4476
+ if (this._api === probe) this._api = null;
4477
+ });
4478
+ }
4479
+ return this._api;
4480
+ };
4481
+ this.probeApi = async () => {
4482
+ const v4 = await this.host.fetch("/v2/manager/version");
4483
+ if (v4.ok) {
4484
+ const version = (await v4.text()).trim();
4485
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4486
+ if (!ui.ok) {
4487
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4488
+ return {
4489
+ generation: "v4",
4490
+ version
4491
+ };
4492
+ }
4493
+ const flag = await ui.json();
4494
+ return {
4495
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4496
+ version
4497
+ };
4498
+ }
4499
+ const v3 = await this.host.fetch("/manager/version");
4500
+ if (v3.ok) return {
4501
+ generation: "v3",
4502
+ version: (await v3.text()).trim()
4503
+ };
4504
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4505
+ };
4506
+ this.route = (api, route, query = "") => {
4507
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4508
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4509
+ };
4510
+ this.strategy = (api) => {
4511
+ switch (api.generation) {
4512
+ case "v3": return {
4513
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4514
+ fetchModels: () => this.listedModels(api),
4515
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4516
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4517
+ };
4518
+ case "v4-legacy-ui": return {
4519
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4520
+ fetchModels: () => this.listedModels(api),
4521
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4522
+ const route = this.route(api, "/manager/queue/batch");
4523
+ const res = await this.post(route, { install: [body] });
4524
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4525
+ 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)`);
4526
+ }),
4527
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4528
+ };
4529
+ case "v4": return {
4530
+ fetchPlugins: () => this.installedPluginView(api),
4531
+ fetchModels: () => this.installedModelView(),
4532
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4533
+ settle: (what, uiId) => this.settleByHistory(api, what, uiId)
4534
+ };
4535
+ }
3924
4536
  };
3925
- this.configureLogging = (mi) => {
3926
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4537
+ this.configureLogging = async (mi) => {
4538
+ const api = await this.api();
4539
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4540
+ const response = await this.host.fetch(route);
4541
+ const text = await response.text();
4542
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4543
+ return text;
3927
4544
  };
3928
4545
  this.getModelInfoFinalFilePath = (mi) => {
3929
4546
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3930
4547
  };
3931
4548
  this.restartComfyUI = async () => {
4549
+ const api = await this.api();
4550
+ this._api = null;
4551
+ const route = this.route(api, "/manager/reboot");
3932
4552
  const refusals = [];
3933
4553
  for (const method of ["POST", "GET"]) {
3934
4554
  let response;
3935
4555
  try {
3936
- response = await this.host.fetch("/manager/reboot", { method });
4556
+ response = await this.host.fetch(route, { method });
3937
4557
  } catch {
3938
4558
  return;
3939
4559
  }
@@ -3941,31 +4561,42 @@ var ComfyManager = class {
3941
4561
  refusals.push(`${method} → ${response.status}`);
3942
4562
  if (response.status !== 404) break;
3943
4563
  }
3944
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4564
+ 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`);
4565
+ };
4566
+ this.fetchPluginsAndModels = async () => {
4567
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4568
+ this.pluginList = _pluginList;
4569
+ this.modelList = _modelList;
3945
4570
  };
3946
4571
  this.modelList = null;
3947
- this.fetchModels = () => {
3948
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4572
+ this.fetchModels = async () => {
4573
+ return this.strategy(await this.api()).fetchModels();
3949
4574
  };
3950
4575
  this.fetchLogs = () => {
3951
- return this.fetchGetJSON("/internal/logs");
4576
+ return this.getJSON("/internal/logs");
3952
4577
  };
3953
4578
  this.isModelInstalled = (name) => {
3954
4579
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3955
4580
  };
3956
4581
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3957
4582
  this.installModel = async (model) => {
4583
+ this.modelsBeeingInstalled.add(model.name);
3958
4584
  try {
3959
- this.modelsBeeingInstalled.add(model.name);
3960
- await this.fetchPost("/model/install", model);
3961
- this.modelsBeeingInstalled.delete(model.name);
3962
- logSuccess("Model installed");
3963
- return true;
3964
- } catch (exception) {
3965
- console.error(`Install failed: / ${exception}`);
3966
- logError("Model Installation Failed");
4585
+ return await this.runInstall(`model "${model.name}"`, {
4586
+ enqueue: async (api, uiId) => {
4587
+ const body = {
4588
+ ...model,
4589
+ ui_id: uiId,
4590
+ client_id: this.clientId
4591
+ };
4592
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4593
+ },
4594
+ landed: async (s) => {
4595
+ return (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base)?.installed === "True";
4596
+ }
4597
+ });
4598
+ } finally {
3967
4599
  this.modelsBeeingInstalled.delete(model.name);
3968
- return false;
3969
4600
  }
3970
4601
  };
3971
4602
  this.getModelStatus = (modelName) => {
@@ -3996,47 +4627,173 @@ var ComfyManager = class {
3996
4627
  })();
3997
4628
  };
3998
4629
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
3999
- try {
4000
- const skip_update = skipUpdate ? "&skip_update=true" : "";
4001
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4002
- } catch (exception) {
4003
- console.error(`node list retrieval failed: ${exception}`);
4004
- logError("node list retrieveal failed");
4005
- throw exception;
4006
- }
4630
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4631
+ };
4632
+ this.installPlugin = async (plugin) => {
4633
+ return this.runInstall(`plugin "${plugin.title}"`, {
4634
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4635
+ landed: async (_s, api) => {
4636
+ const data = await this.installedData(api);
4637
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4638
+ }
4639
+ });
4640
+ };
4641
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4642
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4643
+ if (!("node_packs" in raw)) return raw;
4644
+ const titleByRepo = /* @__PURE__ */ new Map();
4645
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4646
+ return {
4647
+ chanel: raw.channel,
4648
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4649
+ const repo = p.files?.[0];
4650
+ return {
4651
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4652
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4653
+ };
4654
+ })
4655
+ };
4656
+ };
4657
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4658
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4659
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4660
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4661
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4662
+ };
4663
+ this.listedModels = async (api) => {
4664
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4665
+ };
4666
+ this.installedData = async (api) => {
4667
+ 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)]);
4668
+ return {
4669
+ installed,
4670
+ mappings
4671
+ };
4672
+ };
4673
+ this.installedPluginView = async (api) => {
4674
+ const view = buildPluginView({
4675
+ mirror: this.mirror(),
4676
+ ...await this.installedData(api)
4677
+ });
4678
+ 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`);
4679
+ return view.list;
4680
+ };
4681
+ this.installedModelView = async () => {
4682
+ const models = this.mirror().modelRows;
4683
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4684
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4685
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4686
+ return buildModelView({
4687
+ models,
4688
+ files: new Map(lists)
4689
+ });
4690
+ };
4691
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4692
+ const url = plugin.files[0] ?? plugin.reference;
4693
+ const list = await this.fetchPluginWire(api, "cache", true);
4694
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4695
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4696
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4697
+ const [key, row] = found;
4698
+ await send({
4699
+ ...row,
4700
+ id: row.id ?? key,
4701
+ channel: list.channel,
4702
+ mode: "cache",
4703
+ ui_id: uiId,
4704
+ skip_post_install: false
4705
+ });
4706
+ };
4707
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4708
+ const url = plugin.files[0] ?? plugin.reference;
4709
+ const params = {
4710
+ id: repoPath(url).split("/").pop() ?? url,
4711
+ version: "nightly",
4712
+ selected_version: "nightly",
4713
+ repository: url,
4714
+ mode: "cache",
4715
+ channel: "default"
4716
+ };
4717
+ await this.post(this.route(api, "/manager/queue/task"), {
4718
+ ui_id: uiId,
4719
+ client_id: this.clientId,
4720
+ kind: "install",
4721
+ params
4722
+ });
4007
4723
  };
4008
- this.installPlugin = async (model) => {
4724
+ this.settleByHistory = async (api, what, uiId) => {
4725
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4726
+ const entry = await this.waitFor(what, async () => {
4727
+ const status = (await this.getValid(route, TaskHistory_ark)).history.status;
4728
+ if (status == null) await this.restartIdleQueue(api);
4729
+ return status ?? null;
4730
+ });
4731
+ if (entry.status_str === "success" || entry.status_str === "skip") return;
4732
+ const messages = entry.messages ?? [];
4733
+ 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)" : "";
4734
+ throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4735
+ };
4736
+ this.restartIdleQueue = async (api) => {
4737
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4738
+ if (status.is_processing) return "running";
4739
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4740
+ await this.post(this.route(api, "/manager/queue/start"));
4741
+ return "restarted";
4742
+ };
4743
+ this.settleByDrain = async (api, what, landed) => {
4744
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4745
+ 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`);
4746
+ };
4747
+ this.runInstall = async (what, p) => {
4009
4748
  try {
4010
- await this.fetchPost("/customnode/install", model);
4011
- console.log("✅ Custom Node installed");
4012
- logSuccess("Custom Node installed");
4749
+ const api = await this.api();
4750
+ const s = this.strategy(api);
4751
+ const uiId = nanoid();
4752
+ await p.enqueue(api, uiId);
4753
+ await this.post(this.route(api, "/manager/queue/start"));
4754
+ await s.settle(what, uiId, () => p.landed(s, api));
4755
+ logSuccess(`${what} installed`);
4013
4756
  return true;
4014
4757
  } catch (exception) {
4015
- console.error(`Install failed: / ${exception}`);
4016
- logError("Custom Node Installation Failed");
4758
+ logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`);
4017
4759
  return false;
4018
4760
  }
4019
4761
  };
4020
- this.fetchPost = async (endpoint, body, validator) => {
4021
- const response = await this.host.fetch(endpoint, {
4762
+ this.waitFor = async (what, check) => {
4763
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4764
+ for (;;) {
4765
+ const value = await check();
4766
+ if (value != null) return value;
4767
+ if (Date.now() >= deadline) throw new Error(`${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4768
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4769
+ }
4770
+ };
4771
+ this.post = async (route, body) => {
4772
+ const response = await this.host.fetch(route, {
4022
4773
  method: "POST",
4023
4774
  headers: { "Content-Type": "application/json" },
4024
- body: JSON.stringify(body)
4775
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4025
4776
  });
4026
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4027
- const status = await response.json();
4028
- if (validator) return softValidate(validator, status);
4029
- return status;
4030
- };
4031
- this.fetchGetJSON = async (endpoint, validator) => {
4032
- const response = await this.host.fetch(endpoint);
4033
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4777
+ const text = await response.text();
4778
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4779
+ if (text === "") return null;
4780
+ try {
4781
+ return JSON.parse(text);
4782
+ } catch {
4783
+ return text;
4784
+ }
4785
+ };
4786
+ this.getJSON = async (route, validator) => {
4787
+ const response = await this.host.fetch(route);
4788
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4034
4789
  const jsonResult = await response.json();
4035
4790
  if (validator) return softValidate(validator, jsonResult);
4036
4791
  return jsonResult;
4037
4792
  };
4038
- this.fetchGetText = async (endopint) => {
4039
- return await (await this.host.fetch(endopint)).text();
4793
+ this.getValid = async (route, schema) => {
4794
+ const res = schema(await this.getJSON(route));
4795
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4796
+ return res;
4040
4797
  };
4041
4798
  }
4042
4799
  get registry() {
@@ -6183,6 +6940,7 @@ var ComfyHost = class {
6183
6940
  this.onLogs = null;
6184
6941
  this.comfySessionId = "temp";
6185
6942
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
6943
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6186
6944
  this.status = null;
6187
6945
  this.lastWsMessageAt = null;
6188
6946
  this.base = parseHostBase(this.data);
@@ -6422,9 +7180,26 @@ var ComfyHost = class {
6422
7180
  }
6423
7181
  return;
6424
7182
  }
6425
- const msg_ = JSON.parse(String(e.data));
6426
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6427
- if (msg_.type === "crystools.monitor") return;
7183
+ let msg_ = JSON.parse(String(e.data));
7184
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7185
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7186
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7187
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7188
+ const key = eventType ?? "<no type>";
7189
+ if (this._unknownWsEventTypes.has(key)) return;
7190
+ this._unknownWsEventTypes.add(key);
7191
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7192
+ return;
7193
+ }
7194
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7195
+ const data = Reflect.get(rec, "data");
7196
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7197
+ type: eventType,
7198
+ data: {
7199
+ ...data,
7200
+ prompt_id: this.activePromptID
7201
+ }
7202
+ };
6428
7203
  }
6429
7204
  const res = WsMsg_ark(msg_);
6430
7205
  if (res instanceof type.errors) {
@@ -6438,7 +7213,11 @@ var ComfyHost = class {
6438
7213
  this.comfySessionId = msg.data.sid;
6439
7214
  this._sessionResolve?.();
6440
7215
  this._sessionResolve = null;
6441
- if (sidChanged) this.onSession?.(msg.data.sid);
7216
+ if (sidChanged) {
7217
+ this._unknownWsEventTypes.clear();
7218
+ this._unknownBinaryFrameTypes.clear();
7219
+ this.onSession?.(msg.data.sid);
7220
+ }
6442
7221
  }
6443
7222
  this.status = msg.data.status;
6444
7223
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6453,7 +7232,7 @@ var ComfyHost = class {
6453
7232
  this.routeOrBuffer(activePromptID, msg);
6454
7233
  return;
6455
7234
  }
6456
- if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
7235
+ if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_interrupted" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
6457
7236
  this.routeOrBuffer(msg.data.prompt_id, msg);
6458
7237
  return;
6459
7238
  }
@@ -6465,8 +7244,6 @@ var ComfyHost = class {
6465
7244
  this.onLogs?.(msg.data);
6466
7245
  return;
6467
7246
  }
6468
- console.log("❌", "Unknown message:", msg);
6469
- logError("Unknown message type: " + JSON.stringify(msg.type));
6470
7247
  }
6471
7248
  };
6472
7249
  //#endregion
@@ -6795,6 +7572,7 @@ const _getKnownModels = (DB) => {
6795
7572
  }
6796
7573
  const knownModelList = canonical.concat(extraModels.models);
6797
7574
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7575
+ DB.modelRows = knownModelList;
6798
7576
  if (DB.opts.genTypes) {
6799
7577
  let out1 = "";
6800
7578
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6963,6 +7741,7 @@ var ComfyRegistry = class ComfyRegistry {
6963
7741
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6964
7742
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6965
7743
  this.knownModels = /* @__PURE__ */ new Map();
7744
+ this.modelRows = [];
6966
7745
  this.alterations = [];
6967
7746
  this.githubStats = /* @__PURE__ */ new Map();
6968
7747
  this.report = new ManagerParseReport();