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
@@ -185,6 +185,11 @@ const wrapQuote = (s) => {
185
185
  return `'${s}'`;
186
186
  };
187
187
  //#endregion
188
+ //#region src/utils/exhaust.ts
189
+ function exhaust(x) {
190
+ return x;
191
+ }
192
+ //#endregion
188
193
  //#region src/sdk-generator/inputWidgetKind.ts
189
194
  const isRecord = (x) => typeof x === "object" && x != null && !Array.isArray(x);
190
195
  /**
@@ -253,6 +258,14 @@ const parseContainer = (template) => {
253
258
  requiredCount: isRecord(input) && isRecord(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
254
259
  };
255
260
  };
261
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
262
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
263
+ const parseGroup = (o, template) => ({
264
+ kind: "dynamic-group",
265
+ fields: flattenInputSections(template),
266
+ min: typeof o["min"] === "number" ? o["min"] : 0,
267
+ max: typeof o["max"] === "number" ? o["max"] : 20
268
+ });
256
269
  /**
257
270
  * the single template sub-input's slot type of an autogrow container
258
271
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -327,11 +340,12 @@ const classifyWidgetInput = (p) => {
327
340
  };
328
341
  }
329
342
  const template = o?.["template"];
330
- if (isRecord(template)) {
343
+ if (o != null && isRecord(template)) {
331
344
  if (isRecord(template["input"])) return parseContainer(template);
345
+ if (isRecord(template["required"]) || isRecord(template["optional"])) return parseGroup(o, template);
332
346
  return { kind: "slot" };
333
347
  }
334
- if (o?.["socketless"] === true) return {
348
+ if (typeof o?.["socketless"] === "boolean") return {
335
349
  kind: "widget",
336
350
  consumes: 1,
337
351
  strictValues: false,
@@ -394,6 +408,15 @@ const dynamicComboUnion = (p) => {
394
408
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
395
409
  }).join(" | ")})`;
396
410
  };
411
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
412
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
413
+ const dynamicGroupRow = (fields) => {
414
+ return `{ ${fields.map((e) => {
415
+ const opts = isRecord(e.opts) ? e.opts : null;
416
+ const optional = !e.required || opts?.["default"] !== void 0;
417
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
418
+ }).join("; ")} }`;
419
+ };
397
420
  /**
398
421
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
399
422
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -442,6 +465,8 @@ function codegenSDK(opts) {
442
465
  b.deindent();
443
466
  p(`// #endregion`);
444
467
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
468
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
469
+ const groupRows = [];
445
470
  p(`interface IN {`);
446
471
  b.indent();
447
472
  for (const n of nodes) {
@@ -449,23 +474,37 @@ function codegenSDK(opts) {
449
474
  const comboSuffixes = [];
450
475
  for (const i of n.inputs) {
451
476
  const kind = classifySchemaInput(i);
452
- if (kind.kind === "dynamic-container") {
453
- const instType = containerInstanceSlotType(i.opts);
454
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
455
- const opt = ix >= kind.requiredCount ? "?" : "";
456
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
457
- });
458
- continue;
459
- }
460
- if (kind.kind === "dynamic-combo") {
461
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
462
- comboSuffixes.push(dynamicComboUnion({
463
- name: i.nameInComfy,
464
- nameEscaped: i.nameInComfyEscaped,
465
- options: kind.options,
466
- keyOptional: optsDyn?.default !== void 0 || !i.required
467
- }));
468
- continue;
477
+ switch (kind.kind) {
478
+ case "dynamic-container": {
479
+ const instType = containerInstanceSlotType(i.opts);
480
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
481
+ const opt = ix >= kind.requiredCount ? "?" : "";
482
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
483
+ });
484
+ continue;
485
+ }
486
+ case "dynamic-combo": {
487
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
488
+ comboSuffixes.push(dynamicComboUnion({
489
+ name: i.nameInComfy,
490
+ nameEscaped: i.nameInComfyEscaped,
491
+ options: kind.options,
492
+ keyOptional: optsDyn?.default !== void 0 || !i.required
493
+ }));
494
+ continue;
495
+ }
496
+ case "dynamic-group": {
497
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
498
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
499
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
500
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
501
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
502
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
503
+ continue;
504
+ }
505
+ case "widget":
506
+ case "slot": break;
507
+ default:
469
508
  }
470
509
  const opts_ = typeof i.opts === "string" ? null : i.opts;
471
510
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -488,6 +527,15 @@ function codegenSDK(opts) {
488
527
  b.deindent();
489
528
  p("}");
490
529
  p("");
530
+ if (groupRows.length > 0) {
531
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
532
+ p(`interface GroupRow {`);
533
+ b.indent();
534
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
535
+ b.deindent();
536
+ p("}");
537
+ p("");
538
+ }
491
539
  p(`interface OUT {`);
492
540
  b.indent();
493
541
  for (const n of nodes) {
@@ -800,9 +848,13 @@ var ComfySchema = class {
800
848
  if (widgetKind?.kind === "dynamic-combo") {
801
849
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
802
850
  }
851
+ if (widgetKind?.kind === "dynamic-group") {
852
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
853
+ }
854
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
803
855
  node.inputs.push({
804
856
  slotName: inputSlotName,
805
- required: ipt.required && !isAutogrowContainer,
857
+ required,
806
858
  nameInComfy: inputNameInComfy,
807
859
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
808
860
  typeName: inputTypeName,
@@ -850,7 +902,7 @@ var ComfySchema = class {
850
902
  };
851
903
  //#endregion
852
904
  //#region package.json
853
- var version = "2.17.1";
905
+ var version = "2.18.0";
854
906
  //#endregion
855
907
  //#region src/litegraph/LiteGraphLinkID.ts
856
908
  const asLiteGraphLinkID = (id) => id;
@@ -996,7 +1048,8 @@ const expandOneInstance = (wf, instance, def) => {
996
1048
  name: i.name,
997
1049
  type: i.type,
998
1050
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
999
- widgetName: i.widgetName
1051
+ widgetName: i.widgetName,
1052
+ widgetSource: i.widgetSource
1000
1053
  })),
1001
1054
  outputs: inner.outputs.map((o) => ({
1002
1055
  name: o.name,
@@ -1037,6 +1090,20 @@ const expandOneInstance = (wf, instance, def) => {
1037
1090
  wf.links = wf.links.filter((l) => !dead.has(l.id));
1038
1091
  pruneDeadLinkRefs(wf, dead);
1039
1092
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
1093
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
1094
+ if (outerLinkIntoDefSlot.has(slot)) continue;
1095
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
1096
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
1097
+ if (source == null || sourceInput == null) continue;
1098
+ for (const t of targets) {
1099
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
1100
+ if (input == null || input.widgetName != null || input.link != null) continue;
1101
+ input.widgetSource = {
1102
+ nodeId: source.nodeId,
1103
+ inputName: sourceInput.name
1104
+ };
1105
+ }
1106
+ }
1040
1107
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
1041
1108
  wf.nodes.push(...splicedNodes);
1042
1109
  wf.links.push(...splicedLinks);
@@ -1148,7 +1215,7 @@ const LiteGraphNodeInput_ark = type({
1148
1215
  type: "string",
1149
1216
  "link?": LiteGraphLinkID_.or(type.null),
1150
1217
  "shape?": "number",
1151
- "label?": "string",
1218
+ "label?": type.string.or(type.null),
1152
1219
  "widget?": type({
1153
1220
  name: "string",
1154
1221
  "config?": "unknown"
@@ -1165,7 +1232,7 @@ const LiteGraphNodeOutput_ark = type({
1165
1232
  type: "string",
1166
1233
  "links?": LiteGraphLinkID_.array().or(type.null),
1167
1234
  "shape?": "number",
1168
- "slot_index?": LiteGraphSlotIndex_
1235
+ "slot_index?": LiteGraphSlotIndex_.or(type.null)
1169
1236
  });
1170
1237
  //#endregion
1171
1238
  //#region src/litegraph/LiteGraphNode.ts
@@ -1235,7 +1302,7 @@ const LiteGraphSubgraphDef_ark = type({
1235
1302
  const LiteGraphJSON_ark = type({
1236
1303
  "id?": "string",
1237
1304
  "revision?": "number",
1238
- "last_node_id?": "number",
1305
+ "last_node_id?": "number | string",
1239
1306
  "last_link_id?": "number",
1240
1307
  "state?": type.Record("string", "unknown"),
1241
1308
  nodes: LiteGraphNode_ark.array(),
@@ -1334,7 +1401,8 @@ const normalizeInput = (i) => {
1334
1401
  name: i.name,
1335
1402
  type: i.type,
1336
1403
  link: i.link ?? null,
1337
- widgetName: i.widget?.name ?? null
1404
+ widgetName: i.widget?.name ?? null,
1405
+ widgetSource: null
1338
1406
  };
1339
1407
  };
1340
1408
  const normalizeOutput = (o) => {
@@ -1598,18 +1666,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1598
1666
  inputs[p.path] = key;
1599
1667
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1600
1668
  };
1669
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1670
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1671
+ const consumeDynamicGroup = (p) => {
1672
+ const r = resolveWidgetValue({
1673
+ promptName: p.path,
1674
+ consumes: 1,
1675
+ prefixLen: 0
1676
+ });
1677
+ const saved = r.filled ? p.min : r.value;
1678
+ 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);
1679
+ const rows = Math.max(p.min, saved);
1680
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1681
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1682
+ };
1601
1683
  const consumeBranchInput = (subPath, sub) => {
1602
1684
  const kind = classifyWidgetInput({
1603
- name: sub.name,
1685
+ name: subPath,
1604
1686
  type: sub.type,
1605
1687
  opts: sub.opts
1606
1688
  });
1607
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1608
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1609
- path: subPath,
1610
- options: kind.options,
1611
- defaultKey: kind.defaultKey
1612
- });
1689
+ switch (kind.kind) {
1690
+ case "slot":
1691
+ case "dynamic-container": return;
1692
+ case "dynamic-combo": return consumeDynamicCombo({
1693
+ path: subPath,
1694
+ options: kind.options,
1695
+ defaultKey: kind.defaultKey
1696
+ });
1697
+ case "dynamic-group": return consumeDynamicGroup({
1698
+ path: subPath,
1699
+ fields: kind.fields,
1700
+ min: kind.min,
1701
+ max: kind.max
1702
+ });
1703
+ case "widget": break;
1704
+ default: return exhaust(kind);
1705
+ }
1613
1706
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1614
1707
  consumePlainWidget({
1615
1708
  promptName: subPath,
@@ -1631,26 +1724,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1631
1724
  strictValues: true,
1632
1725
  prefixValues: []
1633
1726
  };
1634
- if (kind.kind === "widget") consumePlainWidget({
1635
- promptName: field.nameInComfy,
1636
- typeName: field.typeName,
1637
- opts: field.opts,
1638
- consumes: kind.consumes,
1639
- prefixLen: kind.prefixValues.length,
1640
- strict: kind.strictValues,
1641
- linkedInput: input
1642
- });
1643
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1644
- path: field.nameInComfy,
1645
- options: kind.options,
1646
- defaultKey: kind.defaultKey
1647
- });
1648
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1649
- const iname = `${field.nameInComfy}.${instName}`;
1650
- 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);
1651
- }
1652
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1653
- 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);
1727
+ switch (kind.kind) {
1728
+ case "widget":
1729
+ consumePlainWidget({
1730
+ promptName: field.nameInComfy,
1731
+ typeName: field.typeName,
1732
+ opts: field.opts,
1733
+ consumes: kind.consumes,
1734
+ prefixLen: kind.prefixValues.length,
1735
+ strict: kind.strictValues,
1736
+ linkedInput: input
1737
+ });
1738
+ break;
1739
+ case "dynamic-combo":
1740
+ consumeDynamicCombo({
1741
+ path: field.nameInComfy,
1742
+ options: kind.options,
1743
+ defaultKey: kind.defaultKey
1744
+ });
1745
+ break;
1746
+ case "dynamic-group":
1747
+ consumeDynamicGroup({
1748
+ path: field.nameInComfy,
1749
+ fields: kind.fields,
1750
+ min: kind.min,
1751
+ max: kind.max
1752
+ });
1753
+ break;
1754
+ case "dynamic-container":
1755
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1756
+ const iname = `${field.nameInComfy}.${instName}`;
1757
+ 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);
1758
+ }
1759
+ break;
1760
+ case "slot":
1761
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1762
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1763
+ promptName: field.nameInComfy,
1764
+ strict: false
1765
+ });
1766
+ break;
1767
+ }
1768
+ 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);
1769
+ break;
1770
+ default:
1654
1771
  }
1655
1772
  }
1656
1773
  const getParentNode = (linkId) => {
@@ -1756,6 +1873,45 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1756
1873
  class_type: node.type
1757
1874
  };
1758
1875
  }
1876
+ for (const node of workflow.nodes) {
1877
+ const own = prompt[String(node.id)];
1878
+ if (own == null) continue;
1879
+ for (const ipt of node.inputs) {
1880
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1881
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1882
+ if (value !== void 0) own.inputs[ipt.name] = value;
1883
+ }
1884
+ }
1885
+ const missing = /* @__PURE__ */ new Map();
1886
+ for (const node of workflow.nodes) {
1887
+ const own = prompt[String(node.id)];
1888
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1889
+ if (own == null || nodeSchema == null) continue;
1890
+ for (const field of nodeSchema.inputs) {
1891
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1892
+ const kind = classifySchemaInput(field).kind;
1893
+ if (kind !== "slot" && kind !== "widget") continue;
1894
+ missing.set(String(node.id), {
1895
+ node,
1896
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1897
+ });
1898
+ break;
1899
+ }
1900
+ }
1901
+ if (missing.size > 0) {
1902
+ const complete = (id, seen) => {
1903
+ if (seen.has(id)) return true;
1904
+ seen.add(id);
1905
+ if (missing.has(id)) return false;
1906
+ for (const value of Object.values(prompt[id]?.inputs ?? {})) if (Array.isArray(value) && typeof value[0] === "string" && !complete(value[0], seen)) return false;
1907
+ return true;
1908
+ };
1909
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1910
+ const dropped = outputs.filter((id) => !complete(id, /* @__PURE__ */ new Set()));
1911
+ const first = missing.values().next().value;
1912
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1913
+ 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("; ")}`);
1914
+ }
1759
1915
  return prompt;
1760
1916
  };
1761
1917
  //#endregion
@@ -1925,21 +2081,37 @@ var ComfyNode = class ComfyNode {
1925
2081
  _convertPromptExtToPrompt(promptExt) {
1926
2082
  const inputs = {};
1927
2083
  const _done = /* @__PURE__ */ new Set();
1928
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
2084
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1929
2085
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1930
2086
  for (const i of this.$schema.inputs) {
1931
2087
  _done.add(i.nameInComfy);
1932
2088
  const kind = classifySchemaInput(i);
1933
- if (kind.kind === "dynamic-combo") {
1934
- this._writeDynamicCombo({
1935
- name: i.nameInComfy,
1936
- options: kind.options,
1937
- defaultKey: kind.defaultKey,
1938
- provided: promptExt.inputs,
1939
- out: inputs,
1940
- claimed: _comboBranchKeys
1941
- });
1942
- continue;
2089
+ switch (kind.kind) {
2090
+ case "dynamic-combo":
2091
+ this._writeDynamicCombo({
2092
+ name: i.nameInComfy,
2093
+ options: kind.options,
2094
+ defaultKey: kind.defaultKey,
2095
+ provided: promptExt.inputs,
2096
+ out: inputs,
2097
+ claimed: _comboBranchKeys
2098
+ });
2099
+ continue;
2100
+ case "dynamic-group":
2101
+ this._writeDynamicGroup({
2102
+ name: i.nameInComfy,
2103
+ fields: kind.fields,
2104
+ min: kind.min,
2105
+ max: kind.max,
2106
+ provided: promptExt.inputs,
2107
+ out: inputs,
2108
+ claimed: _comboBranchKeys
2109
+ });
2110
+ continue;
2111
+ case "widget":
2112
+ case "slot":
2113
+ case "dynamic-container": break;
2114
+ default:
1943
2115
  }
1944
2116
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1945
2117
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1978,6 +2150,42 @@ var ComfyNode = class ComfyNode {
1978
2150
  }) : this.serializeValue(dotted, given);
1979
2151
  }
1980
2152
  }
2153
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
2154
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
2155
+ * keys are already the rows: they pass through the rest loop untouched */
2156
+ _writeDynamicGroup(p) {
2157
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
2158
+ const raw = p.provided[p.name];
2159
+ const prefix = `${p.name}.`;
2160
+ if (raw == null) {
2161
+ 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)`);
2162
+ return;
2163
+ }
2164
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
2165
+ if (!Array.isArray(raw)) {
2166
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
2167
+ return;
2168
+ }
2169
+ 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}`);
2170
+ raw.forEach((row, ix) => {
2171
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
2172
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
2173
+ return;
2174
+ }
2175
+ const given = new Map(Object.entries(row));
2176
+ for (const field of p.fields) {
2177
+ const dotted = `${p.name}.${ix}.${field.name}`;
2178
+ const value = given.get(field.name);
2179
+ p.out[dotted] = value == null ? defaultValueForWidget({
2180
+ type: typeof field.type === "string" ? field.type : "COMBO",
2181
+ opts: field.opts,
2182
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
2183
+ }) : this.serializeValue(dotted, value);
2184
+ given.delete(field.name);
2185
+ }
2186
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
2187
+ });
2188
+ }
1981
2189
  /** return the list of nodes piped into this node */
1982
2190
  _incomingNodes() {
1983
2191
  const incomingNodes = [];
@@ -2121,6 +2329,12 @@ var ComfyNode = class ComfyNode {
2121
2329
  const kind = classifySchemaInput(decl);
2122
2330
  const slotType = containerInstanceSlotType(decl.opts);
2123
2331
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
2332
+ if (kind.kind === "dynamic-group") {
2333
+ const rest = name.slice(dot + 1);
2334
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
2335
+ const field = kind.fields.find((f) => f.name === fieldName);
2336
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
2337
+ }
2124
2338
  }
2125
2339
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
2126
2340
  }
@@ -2204,44 +2418,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
2204
2418
  const convertNodeToLiteGraphNode = (ctx, node) => {
2205
2419
  const inputs = [];
2206
2420
  const widgets_values = [];
2207
- const pushLinked = (name, type, link, shape) => {
2421
+ const pushLinked = (name, type, link, extra = {}) => {
2208
2422
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
2209
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
2210
- inputs.push(shape == null ? {
2423
+ const input = {
2211
2424
  name,
2212
2425
  type,
2213
- link: linkId
2214
- } : {
2426
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
2427
+ };
2428
+ if (extra.shape != null) input.shape = extra.shape;
2429
+ if (extra.widget === true) input.widget = { name };
2430
+ inputs.push(input);
2431
+ };
2432
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
2433
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
2434
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
2435
+ * never disagree on the run length */
2436
+ const pushWidgetRun = (kind, raw, opts) => {
2437
+ widgets_values.push(...kind.prefixValues, raw);
2438
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
2439
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
2440
+ };
2441
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
2442
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
2443
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
2444
+ const writeInput = (p) => {
2445
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
2446
+ switch (p.kind.kind) {
2447
+ case "widget":
2448
+ if (_isLink(p.value)) {
2449
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
2450
+ pushWidgetRun(p.kind, defaultValueForWidget({
2451
+ type: p.typeName,
2452
+ opts: p.opts
2453
+ }), p.opts);
2454
+ } else pushWidgetRun(p.kind, p.value, p.opts);
2455
+ return;
2456
+ case "slot":
2457
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
2458
+ else inputs.push({
2459
+ name: p.name,
2460
+ type: p.typeName,
2461
+ link: null
2462
+ });
2463
+ return;
2464
+ case "dynamic-combo": {
2465
+ const kind = p.kind;
2466
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
2467
+ const option = kind.options.find((o) => o.key === key);
2468
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
2469
+ widgets_values.push(key);
2470
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
2471
+ return;
2472
+ }
2473
+ case "dynamic-container": {
2474
+ const type = containerInstanceSlotType(p.opts) ?? "*";
2475
+ for (const instance of p.kind.instanceNames) {
2476
+ const name = `${p.name}.${instance}`;
2477
+ const value = node.json.inputs[name];
2478
+ if (value == null) continue;
2479
+ const raw = node.serializeValue(name, value);
2480
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
2481
+ pushLinked(name, type, raw, { shape: 7 });
2482
+ }
2483
+ return;
2484
+ }
2485
+ case "dynamic-group": {
2486
+ const prefix = `${p.name}.`;
2487
+ let rows = 0;
2488
+ for (const key of Object.keys(node.json.inputs)) {
2489
+ if (!key.startsWith(prefix)) continue;
2490
+ const row = Number(key.slice(prefix.length).split(".")[0]);
2491
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
2492
+ }
2493
+ widgets_values.push(rows);
2494
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
2495
+ return;
2496
+ }
2497
+ default: p.kind;
2498
+ }
2499
+ };
2500
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
2501
+ * value is the widget's schema default rather than serializeValue's */
2502
+ const writeSub = (name, sub) => {
2503
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
2504
+ const raw = node.json.inputs[name];
2505
+ writeInput({
2215
2506
  name,
2216
- type,
2217
- shape,
2218
- link: linkId
2507
+ kind: classifyWidgetInput({
2508
+ name,
2509
+ type: sub.type,
2510
+ opts: sub.opts
2511
+ }),
2512
+ typeName,
2513
+ opts: sub.opts,
2514
+ value: raw === void 0 ? defaultValueForWidget({
2515
+ type: typeName,
2516
+ opts: sub.opts
2517
+ }) : raw
2219
2518
  });
2220
2519
  };
2221
2520
  for (const ipt of node.$schema.inputs) {
2222
2521
  const kind = classifySchemaInput(ipt);
2223
- if (kind.kind === "dynamic-container") {
2224
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
2225
- for (const instance of kind.instanceNames) {
2226
- const name = `${ipt.nameInComfy}.${instance}`;
2227
- const value = node.json.inputs[name];
2228
- if (value == null) continue;
2229
- const raw = node.serializeValue(name, value);
2230
- 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`);
2231
- pushLinked(name, type, raw, 7);
2232
- }
2233
- continue;
2234
- }
2235
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
2236
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
2237
- else if (kind.kind === "widget") {
2238
- widgets_values.push(...kind.prefixValues, raw);
2239
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
2240
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
2241
- } else inputs.push({
2522
+ const raw = node.json.inputs[ipt.nameInComfy];
2523
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
2524
+ writeInput({
2242
2525
  name: ipt.nameInComfy,
2243
- type: ipt.typeName,
2244
- link: null
2526
+ kind,
2527
+ typeName: ipt.typeName,
2528
+ opts: ipt.opts,
2529
+ value
2245
2530
  });
2246
2531
  }
2247
2532
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -2401,11 +2686,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
2401
2686
  return resultSuccess(txt_chunks);
2402
2687
  };
2403
2688
  //#endregion
2404
- //#region src/utils/exhaust.ts
2405
- function exhaust(x) {
2406
- return x;
2407
- }
2408
- //#endregion
2409
2689
  //#region src/graph/ComfyNodeID.ts
2410
2690
  const ComfyNodeId_ark = type.string.as();
2411
2691
  type({
@@ -2466,16 +2746,17 @@ const types$1 = scope({
2466
2746
  },
2467
2747
  _WsMsgExecutedData: {
2468
2748
  node: "ComfyNodeID",
2469
- output: {
2470
- "previews?": [{ filepath: "string" }, "[]"],
2471
- "images?": "ComfyImageInfo[]",
2472
- "audio?": "ComfyImageInfo[]",
2473
- "video?": "ComfyImageInfo[]",
2474
- "gifs?": "ComfyImageInfo[]",
2475
- "text?": "unknown[]"
2476
- },
2749
+ output: "_WsMsgExecutedOutput | null",
2477
2750
  prompt_id: "PromptID"
2478
2751
  },
2752
+ _WsMsgExecutedOutput: {
2753
+ "previews?": [{ filepath: "string" }, "[]"],
2754
+ "images?": "ComfyImageInfo[]",
2755
+ "audio?": "ComfyImageInfo[]",
2756
+ "video?": "ComfyImageInfo[]",
2757
+ "gifs?": "ComfyImageInfo[]",
2758
+ "text?": "unknown[]"
2759
+ },
2479
2760
  WsMsgExecuted: {
2480
2761
  type: "'executed'",
2481
2762
  data: "_WsMsgExecutedData"
@@ -2497,12 +2778,22 @@ const types$1 = scope({
2497
2778
  exception_type: "string",
2498
2779
  traceback: "string[]",
2499
2780
  current_inputs: "Record<string, unknown>",
2500
- current_outputs: "Record<string, unknown>"
2781
+ current_outputs: "ComfyNodeID[]"
2501
2782
  },
2502
2783
  WsMsgExecutionError: {
2503
2784
  type: "'execution_error'",
2504
2785
  data: "_WsMsgExecutionErrorData"
2505
2786
  },
2787
+ _WsMsgExecutionInterruptedData: {
2788
+ prompt_id: "PromptID",
2789
+ node_id: "ComfyNodeID",
2790
+ node_type: "string",
2791
+ executed: "ComfyNodeID[]"
2792
+ },
2793
+ WsMsgExecutionInterrupted: {
2794
+ type: "'execution_interrupted'",
2795
+ data: "_WsMsgExecutionInterruptedData"
2796
+ },
2506
2797
  WSMsgManagerFeedbackData: { data: "string" },
2507
2798
  WSMsgManagerFeedback: {
2508
2799
  type: "'manager-terminal-feedback'",
@@ -2532,11 +2823,51 @@ const types$1 = scope({
2532
2823
  type: "'progress_state'",
2533
2824
  data: "_WsMsgProgressStateData"
2534
2825
  },
2535
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2826
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2536
2827
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2537
2828
  }).export();
2538
2829
  const PromptInfo_ark = type({ prompt_id: types$1.PromptID }).as();
2539
2830
  const WsMsg_ark = types$1.WsMsg;
2831
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2832
+ const ROUTED_WS_EVENT_TYPES = [
2833
+ "status",
2834
+ "manager-terminal-feedback",
2835
+ "logs",
2836
+ "execution_start",
2837
+ "execution_cached",
2838
+ "executing",
2839
+ "progress",
2840
+ "progress_state",
2841
+ "executed",
2842
+ "execution_error",
2843
+ "execution_interrupted",
2844
+ "execution_success"
2845
+ ];
2846
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2847
+ * before validation, never logged (architecture.md, ws events) */
2848
+ const IGNORED_WS_EVENT_TYPES = [
2849
+ "feature_flags",
2850
+ "agent_status",
2851
+ "asset_export",
2852
+ "assets.seed.started",
2853
+ "assets.seed.progress",
2854
+ "assets.seed.fast_complete",
2855
+ "assets.seed.enrich_complete",
2856
+ "assets.seed.completed",
2857
+ "assets.seed.cancelled",
2858
+ "assets.seed.error",
2859
+ "assets.seed.paused",
2860
+ "assets.seed.resumed",
2861
+ "cm-queue-status",
2862
+ "cm-api-try-install-customnode",
2863
+ "cm-task-started",
2864
+ "cm-task-completed",
2865
+ "crystools.monitor"
2866
+ ];
2867
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2868
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2869
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2870
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2540
2871
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2541
2872
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2542
2873
  //#endregion
@@ -2759,6 +3090,10 @@ var ComfyExecution = class {
2759
3090
  else if (msg.type === "progress") graph.onProgress(msg);
2760
3091
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2761
3092
  else if (msg.type === "execution_error") return void this.onError(msg);
3093
+ else if (msg.type === "execution_interrupted") return void this._finish({
3094
+ status: "Failure",
3095
+ error: msg
3096
+ });
2762
3097
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2763
3098
  else {
2764
3099
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3500,7 +3835,12 @@ const types = scope({
3500
3835
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3501
3836
  ComfyInputSpecAlt2: ["ComfyInputType"],
3502
3837
  ComfyInputSpecAlt3: type([type.null]),
3503
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
3838
+ ComfyInputSpecAlt4: [
3839
+ "ComfyInputType",
3840
+ "ComfyInputOpts",
3841
+ "unknown"
3842
+ ],
3843
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3504
3844
  ComfyInputType: `string | ComfyEnumDef`,
3505
3845
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3506
3846
  ComfyInputHiddenEntry_broken2: type.Record("string", type.unknown),
@@ -3566,10 +3906,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3566
3906
  return result;
3567
3907
  }
3568
3908
  //#endregion
3909
+ //#region src/manager/installedView.ts
3910
+ /**
3911
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
3912
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
3913
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
3914
+ */
3915
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
3916
+ const InstalledPacks_ark = type.Record("string", type({
3917
+ "cnr_id?": "string | null",
3918
+ "aux_id?": "string | null",
3919
+ enabled: "boolean"
3920
+ }));
3921
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
3922
+ const PackMappings_ark = type.Record("string", type(["string[]", { "title_aux?": "string" }]));
3923
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
3924
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
3925
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
3926
+ const attributePacks = (installed, mappings) => {
3927
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
3928
+ return Object.entries(installed).map(([dir, p]) => {
3929
+ const aux = p.aux_id ?? null;
3930
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
3931
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
3932
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
3933
+ return {
3934
+ enabled: p.enabled,
3935
+ repo,
3936
+ title,
3937
+ id: cnr ?? aux ?? dir
3938
+ };
3939
+ });
3940
+ };
3941
+ /** is this mirror row among the attributed packs, enabled? */
3942
+ const packIsInstalled = (packs, plugin) => {
3943
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
3944
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
3945
+ };
3946
+ const buildPluginView = (p) => {
3947
+ const packs = attributePacks(p.installed, p.mappings);
3948
+ const plugins = [...p.mirror.plugins_byTitle.values()];
3949
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
3950
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
3951
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
3952
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
3953
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
3954
+ const custom_nodes = [];
3955
+ for (const plugin of plugins) {
3956
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
3957
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
3958
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
3959
+ title: plugin.title,
3960
+ installed: "True"
3961
+ });
3962
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
3963
+ else custom_nodes.push({
3964
+ title: plugin.title,
3965
+ installed: "False"
3966
+ });
3967
+ }
3968
+ return {
3969
+ list: {
3970
+ chanel: "default",
3971
+ custom_nodes
3972
+ },
3973
+ unattributed: unattributed.map((x) => x.id)
3974
+ };
3975
+ };
3976
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
3977
+ const DEFAULT_FOLDER_BY_TYPE = {
3978
+ checkpoints: "checkpoints",
3979
+ checkpoint: "checkpoints",
3980
+ unclip: "checkpoints",
3981
+ text_encoders: "text_encoders",
3982
+ clip: "text_encoders",
3983
+ vae: "vae",
3984
+ lora: "loras",
3985
+ "t2i-adapter": "controlnet",
3986
+ "t2i-style": "controlnet",
3987
+ controlnet: "controlnet",
3988
+ clip_vision: "clip_vision",
3989
+ gligen: "gligen",
3990
+ upscale: "upscale_models",
3991
+ embedding: "embeddings",
3992
+ embeddings: "embeddings",
3993
+ unet: "diffusion_models",
3994
+ diffusion_model: "diffusion_models"
3995
+ };
3996
+ /** what core `get_filename_list` lists in the standard folders */
3997
+ const LISTED_EXTENSIONS = [
3998
+ ".ckpt",
3999
+ ".pt",
4000
+ ".pt2",
4001
+ ".bin",
4002
+ ".pth",
4003
+ ".safetensors",
4004
+ ".pkl",
4005
+ ".sft"
4006
+ ];
4007
+ /**
4008
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4009
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4010
+ */
4011
+ const modelLocation = (m) => {
4012
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4013
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4014
+ if (m.save_path === "default") {
4015
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4016
+ return folder == null ? null : {
4017
+ folder,
4018
+ files: [m.filename]
4019
+ };
4020
+ }
4021
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4022
+ const folder = parts[0];
4023
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4024
+ const sub = [...parts.slice(1), m.filename].join("/");
4025
+ return {
4026
+ folder,
4027
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4028
+ };
4029
+ };
4030
+ const buildModelView = (p) => {
4031
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4032
+ const statusOf = (m) => {
4033
+ const at = modelLocation(m);
4034
+ const files = at == null ? null : listed.get(at.folder);
4035
+ if (at == null || files == null) return null;
4036
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4037
+ };
4038
+ const byName = /* @__PURE__ */ new Map();
4039
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4040
+ const models = [];
4041
+ for (const rows of byName.values()) {
4042
+ const statuses = new Set(rows.map(statusOf));
4043
+ const first = rows[0];
4044
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4045
+ if (first == null || installed == null) continue;
4046
+ models.push({
4047
+ name: first.name,
4048
+ installed,
4049
+ filename: first.filename,
4050
+ save_path: first.save_path,
4051
+ base: first.base
4052
+ });
4053
+ }
4054
+ return { models };
4055
+ };
4056
+ /** the folders the views need listed */
4057
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4058
+ //#endregion
3569
4059
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3570
4060
  const ComfyManagerAPIModelList_ark = type({ models: type({
3571
4061
  name: type.string.as(),
3572
- installed: `'False' | 'True' | 'Update'`
4062
+ installed: `'False' | 'True' | 'Update'`,
4063
+ "filename?": "string",
4064
+ "save_path?": "string",
4065
+ "base?": "string"
3573
4066
  }).array() });
3574
4067
  //#endregion
3575
4068
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3580,28 +4073,155 @@ const ComfyManagerAPIPluginList_ark = type({
3580
4073
  }).array(),
3581
4074
  chanel: "string"
3582
4075
  });
4076
+ const ComfyManagerAPIPack_ark = type({
4077
+ title: type.string.as(),
4078
+ "id?": "string",
4079
+ "files?": "string[]",
4080
+ "repository?": "string",
4081
+ "version?": "string",
4082
+ "state?": "string",
4083
+ "update-state?": "string"
4084
+ });
4085
+ const ComfyManagerAPIPackList_ark = type({
4086
+ channel: "string",
4087
+ node_packs: type.Record("string", ComfyManagerAPIPack_ark)
4088
+ });
3583
4089
  //#endregion
3584
4090
  //#region src/host/ComfyManager.ts
4091
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4092
+ const MANAGER_TIMING = {
4093
+ pollMs: 1e3,
4094
+ installTimeoutMs: 60 * 6e4
4095
+ };
4096
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4097
+ const NOT_SERVED = {
4098
+ v3: [
4099
+ "/manager/queue/batch",
4100
+ "/manager/queue/task",
4101
+ "/manager/queue/history"
4102
+ ],
4103
+ "v4-legacy-ui": [
4104
+ "/manager/queue/install",
4105
+ "/manager/queue/task",
4106
+ "/manager/queue/history",
4107
+ "/manager/terminal"
4108
+ ],
4109
+ v4: [
4110
+ "/customnode/getlist",
4111
+ "/externalmodel/getlist",
4112
+ "/manager/queue/install",
4113
+ "/manager/queue/batch",
4114
+ "/manager/terminal"
4115
+ ]
4116
+ };
4117
+ const QueueStatus_ark = type({
4118
+ is_processing: "boolean",
4119
+ "pending_count?": "number",
4120
+ "total_count?": "number",
4121
+ "done_count?": "number"
4122
+ });
4123
+ const TaskHistory_ark = type({ history: {
4124
+ "status?": {
4125
+ status_str: "string",
4126
+ "messages?": "string[]"
4127
+ },
4128
+ "result?": "string"
4129
+ } });
4130
+ const ModelFolders_ark = type("string[]");
4131
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3585
4132
  var ComfyManager = class {
3586
- constructor(host) {
4133
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3587
4134
  this.host = host;
3588
- this.fetchPluginsAndModels = async () => {
3589
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3590
- this.pluginList = _pluginList;
3591
- this.modelList = _modelList;
4135
+ this.timing = timing;
4136
+ this.mirror = mirror;
4137
+ this.clientId = `comfy-ts-${nanoid(8)}`;
4138
+ this._api = null;
4139
+ this.api = () => {
4140
+ if (this._api == null) {
4141
+ const probe = this.probeApi();
4142
+ this._api = probe;
4143
+ probe.catch(() => {
4144
+ if (this._api === probe) this._api = null;
4145
+ });
4146
+ }
4147
+ return this._api;
4148
+ };
4149
+ this.probeApi = async () => {
4150
+ const v4 = await this.host.fetch("/v2/manager/version");
4151
+ if (v4.ok) {
4152
+ const version = (await v4.text()).trim();
4153
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4154
+ if (!ui.ok) {
4155
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4156
+ return {
4157
+ generation: "v4",
4158
+ version
4159
+ };
4160
+ }
4161
+ const flag = await ui.json();
4162
+ return {
4163
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4164
+ version
4165
+ };
4166
+ }
4167
+ const v3 = await this.host.fetch("/manager/version");
4168
+ if (v3.ok) return {
4169
+ generation: "v3",
4170
+ version: (await v3.text()).trim()
4171
+ };
4172
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4173
+ };
4174
+ this.route = (api, route, query = "") => {
4175
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4176
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4177
+ };
4178
+ this.strategy = (api) => {
4179
+ switch (api.generation) {
4180
+ case "v3": return {
4181
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4182
+ fetchModels: () => this.listedModels(api),
4183
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4184
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4185
+ };
4186
+ case "v4-legacy-ui": return {
4187
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4188
+ fetchModels: () => this.listedModels(api),
4189
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4190
+ const route = this.route(api, "/manager/queue/batch");
4191
+ const res = await this.post(route, { install: [body] });
4192
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4193
+ 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)`);
4194
+ }),
4195
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4196
+ };
4197
+ case "v4": return {
4198
+ fetchPlugins: () => this.installedPluginView(api),
4199
+ fetchModels: () => this.installedModelView(),
4200
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4201
+ settle: (what, uiId) => this.settleByHistory(api, what, uiId)
4202
+ };
4203
+ }
3592
4204
  };
3593
- this.configureLogging = (mi) => {
3594
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4205
+ this.configureLogging = async (mi) => {
4206
+ const api = await this.api();
4207
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4208
+ const response = await this.host.fetch(route);
4209
+ const text = await response.text();
4210
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4211
+ return text;
3595
4212
  };
3596
4213
  this.getModelInfoFinalFilePath = (mi) => {
3597
4214
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3598
4215
  };
3599
4216
  this.restartComfyUI = async () => {
4217
+ const api = await this.api();
4218
+ this._api = null;
4219
+ const route = this.route(api, "/manager/reboot");
3600
4220
  const refusals = [];
3601
4221
  for (const method of ["POST", "GET"]) {
3602
4222
  let response;
3603
4223
  try {
3604
- response = await this.host.fetch("/manager/reboot", { method });
4224
+ response = await this.host.fetch(route, { method });
3605
4225
  } catch {
3606
4226
  return;
3607
4227
  }
@@ -3609,31 +4229,42 @@ var ComfyManager = class {
3609
4229
  refusals.push(`${method} → ${response.status}`);
3610
4230
  if (response.status !== 404) break;
3611
4231
  }
3612
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4232
+ 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`);
4233
+ };
4234
+ this.fetchPluginsAndModels = async () => {
4235
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4236
+ this.pluginList = _pluginList;
4237
+ this.modelList = _modelList;
3613
4238
  };
3614
4239
  this.modelList = null;
3615
- this.fetchModels = () => {
3616
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4240
+ this.fetchModels = async () => {
4241
+ return this.strategy(await this.api()).fetchModels();
3617
4242
  };
3618
4243
  this.fetchLogs = () => {
3619
- return this.fetchGetJSON("/internal/logs");
4244
+ return this.getJSON("/internal/logs");
3620
4245
  };
3621
4246
  this.isModelInstalled = (name) => {
3622
4247
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3623
4248
  };
3624
4249
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3625
4250
  this.installModel = async (model) => {
4251
+ this.modelsBeeingInstalled.add(model.name);
3626
4252
  try {
3627
- this.modelsBeeingInstalled.add(model.name);
3628
- await this.fetchPost("/model/install", model);
3629
- this.modelsBeeingInstalled.delete(model.name);
3630
- logSuccess("Model installed");
3631
- return true;
3632
- } catch (exception) {
3633
- console.error(`Install failed: / ${exception}`);
3634
- logError("Model Installation Failed");
4253
+ return await this.runInstall(`model "${model.name}"`, {
4254
+ enqueue: async (api, uiId) => {
4255
+ const body = {
4256
+ ...model,
4257
+ ui_id: uiId,
4258
+ client_id: this.clientId
4259
+ };
4260
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4261
+ },
4262
+ landed: async (s) => {
4263
+ return (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base)?.installed === "True";
4264
+ }
4265
+ });
4266
+ } finally {
3635
4267
  this.modelsBeeingInstalled.delete(model.name);
3636
- return false;
3637
4268
  }
3638
4269
  };
3639
4270
  this.getModelStatus = (modelName) => {
@@ -3664,47 +4295,173 @@ var ComfyManager = class {
3664
4295
  })();
3665
4296
  };
3666
4297
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
3667
- try {
3668
- const skip_update = skipUpdate ? "&skip_update=true" : "";
3669
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
3670
- } catch (exception) {
3671
- console.error(`node list retrieval failed: ${exception}`);
3672
- logError("node list retrieveal failed");
3673
- throw exception;
3674
- }
4298
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4299
+ };
4300
+ this.installPlugin = async (plugin) => {
4301
+ return this.runInstall(`plugin "${plugin.title}"`, {
4302
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4303
+ landed: async (_s, api) => {
4304
+ const data = await this.installedData(api);
4305
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4306
+ }
4307
+ });
4308
+ };
4309
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4310
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4311
+ if (!("node_packs" in raw)) return raw;
4312
+ const titleByRepo = /* @__PURE__ */ new Map();
4313
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4314
+ return {
4315
+ chanel: raw.channel,
4316
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4317
+ const repo = p.files?.[0];
4318
+ return {
4319
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4320
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4321
+ };
4322
+ })
4323
+ };
4324
+ };
4325
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4326
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4327
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4328
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4329
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4330
+ };
4331
+ this.listedModels = async (api) => {
4332
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
3675
4333
  };
3676
- this.installPlugin = async (model) => {
4334
+ this.installedData = async (api) => {
4335
+ 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)]);
4336
+ return {
4337
+ installed,
4338
+ mappings
4339
+ };
4340
+ };
4341
+ this.installedPluginView = async (api) => {
4342
+ const view = buildPluginView({
4343
+ mirror: this.mirror(),
4344
+ ...await this.installedData(api)
4345
+ });
4346
+ 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`);
4347
+ return view.list;
4348
+ };
4349
+ this.installedModelView = async () => {
4350
+ const models = this.mirror().modelRows;
4351
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4352
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4353
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4354
+ return buildModelView({
4355
+ models,
4356
+ files: new Map(lists)
4357
+ });
4358
+ };
4359
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4360
+ const url = plugin.files[0] ?? plugin.reference;
4361
+ const list = await this.fetchPluginWire(api, "cache", true);
4362
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4363
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4364
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4365
+ const [key, row] = found;
4366
+ await send({
4367
+ ...row,
4368
+ id: row.id ?? key,
4369
+ channel: list.channel,
4370
+ mode: "cache",
4371
+ ui_id: uiId,
4372
+ skip_post_install: false
4373
+ });
4374
+ };
4375
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4376
+ const url = plugin.files[0] ?? plugin.reference;
4377
+ const params = {
4378
+ id: repoPath(url).split("/").pop() ?? url,
4379
+ version: "nightly",
4380
+ selected_version: "nightly",
4381
+ repository: url,
4382
+ mode: "cache",
4383
+ channel: "default"
4384
+ };
4385
+ await this.post(this.route(api, "/manager/queue/task"), {
4386
+ ui_id: uiId,
4387
+ client_id: this.clientId,
4388
+ kind: "install",
4389
+ params
4390
+ });
4391
+ };
4392
+ this.settleByHistory = async (api, what, uiId) => {
4393
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4394
+ const entry = await this.waitFor(what, async () => {
4395
+ const status = (await this.getValid(route, TaskHistory_ark)).history.status;
4396
+ if (status == null) await this.restartIdleQueue(api);
4397
+ return status ?? null;
4398
+ });
4399
+ if (entry.status_str === "success" || entry.status_str === "skip") return;
4400
+ const messages = entry.messages ?? [];
4401
+ 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)" : "";
4402
+ throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4403
+ };
4404
+ this.restartIdleQueue = async (api) => {
4405
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4406
+ if (status.is_processing) return "running";
4407
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4408
+ await this.post(this.route(api, "/manager/queue/start"));
4409
+ return "restarted";
4410
+ };
4411
+ this.settleByDrain = async (api, what, landed) => {
4412
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4413
+ 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`);
4414
+ };
4415
+ this.runInstall = async (what, p) => {
3677
4416
  try {
3678
- await this.fetchPost("/customnode/install", model);
3679
- console.log("✅ Custom Node installed");
3680
- logSuccess("Custom Node installed");
4417
+ const api = await this.api();
4418
+ const s = this.strategy(api);
4419
+ const uiId = nanoid();
4420
+ await p.enqueue(api, uiId);
4421
+ await this.post(this.route(api, "/manager/queue/start"));
4422
+ await s.settle(what, uiId, () => p.landed(s, api));
4423
+ logSuccess(`${what} installed`);
3681
4424
  return true;
3682
4425
  } catch (exception) {
3683
- console.error(`Install failed: / ${exception}`);
3684
- logError("Custom Node Installation Failed");
4426
+ logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`);
3685
4427
  return false;
3686
4428
  }
3687
4429
  };
3688
- this.fetchPost = async (endpoint, body, validator) => {
3689
- const response = await this.host.fetch(endpoint, {
4430
+ this.waitFor = async (what, check) => {
4431
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4432
+ for (;;) {
4433
+ const value = await check();
4434
+ if (value != null) return value;
4435
+ if (Date.now() >= deadline) throw new Error(`${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4436
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4437
+ }
4438
+ };
4439
+ this.post = async (route, body) => {
4440
+ const response = await this.host.fetch(route, {
3690
4441
  method: "POST",
3691
4442
  headers: { "Content-Type": "application/json" },
3692
- body: JSON.stringify(body)
4443
+ body: body === void 0 ? void 0 : JSON.stringify(body)
3693
4444
  });
3694
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
3695
- const status = await response.json();
3696
- if (validator) return softValidate(validator, status);
3697
- return status;
3698
- };
3699
- this.fetchGetJSON = async (endpoint, validator) => {
3700
- const response = await this.host.fetch(endpoint);
3701
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4445
+ const text = await response.text();
4446
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4447
+ if (text === "") return null;
4448
+ try {
4449
+ return JSON.parse(text);
4450
+ } catch {
4451
+ return text;
4452
+ }
4453
+ };
4454
+ this.getJSON = async (route, validator) => {
4455
+ const response = await this.host.fetch(route);
4456
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
3702
4457
  const jsonResult = await response.json();
3703
4458
  if (validator) return softValidate(validator, jsonResult);
3704
4459
  return jsonResult;
3705
4460
  };
3706
- this.fetchGetText = async (endopint) => {
3707
- return await (await this.host.fetch(endopint)).text();
4461
+ this.getValid = async (route, schema) => {
4462
+ const res = schema(await this.getJSON(route));
4463
+ if (res instanceof type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4464
+ return res;
3708
4465
  };
3709
4466
  }
3710
4467
  get registry() {
@@ -4309,6 +5066,7 @@ var ComfyHost = class {
4309
5066
  this.onLogs = null;
4310
5067
  this.comfySessionId = "temp";
4311
5068
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
5069
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
4312
5070
  this.status = null;
4313
5071
  this.lastWsMessageAt = null;
4314
5072
  this.base = parseHostBase(this.data);
@@ -4548,9 +5306,26 @@ var ComfyHost = class {
4548
5306
  }
4549
5307
  return;
4550
5308
  }
4551
- const msg_ = JSON.parse(String(e.data));
4552
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
4553
- if (msg_.type === "crystools.monitor") return;
5309
+ let msg_ = JSON.parse(String(e.data));
5310
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
5311
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
5312
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
5313
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
5314
+ const key = eventType ?? "<no type>";
5315
+ if (this._unknownWsEventTypes.has(key)) return;
5316
+ this._unknownWsEventTypes.add(key);
5317
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
5318
+ return;
5319
+ }
5320
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
5321
+ const data = Reflect.get(rec, "data");
5322
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
5323
+ type: eventType,
5324
+ data: {
5325
+ ...data,
5326
+ prompt_id: this.activePromptID
5327
+ }
5328
+ };
4554
5329
  }
4555
5330
  const res = WsMsg_ark(msg_);
4556
5331
  if (res instanceof type.errors) {
@@ -4564,7 +5339,11 @@ var ComfyHost = class {
4564
5339
  this.comfySessionId = msg.data.sid;
4565
5340
  this._sessionResolve?.();
4566
5341
  this._sessionResolve = null;
4567
- if (sidChanged) this.onSession?.(msg.data.sid);
5342
+ if (sidChanged) {
5343
+ this._unknownWsEventTypes.clear();
5344
+ this._unknownBinaryFrameTypes.clear();
5345
+ this.onSession?.(msg.data.sid);
5346
+ }
4568
5347
  }
4569
5348
  this.status = msg.data.status;
4570
5349
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -4579,7 +5358,7 @@ var ComfyHost = class {
4579
5358
  this.routeOrBuffer(activePromptID, msg);
4580
5359
  return;
4581
5360
  }
4582
- 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") {
5361
+ 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") {
4583
5362
  this.routeOrBuffer(msg.data.prompt_id, msg);
4584
5363
  return;
4585
5364
  }
@@ -4591,8 +5370,6 @@ var ComfyHost = class {
4591
5370
  this.onLogs?.(msg.data);
4592
5371
  return;
4593
5372
  }
4594
- console.log("❌", "Unknown message:", msg);
4595
- logError("Unknown message type: " + JSON.stringify(msg.type));
4596
5373
  }
4597
5374
  };
4598
5375
  //#endregion
@@ -4921,6 +5698,7 @@ const _getKnownModels = (DB) => {
4921
5698
  }
4922
5699
  const knownModelList = canonical.concat(extraModels.models);
4923
5700
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
5701
+ DB.modelRows = knownModelList;
4924
5702
  if (DB.opts.genTypes) {
4925
5703
  let out1 = "";
4926
5704
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -5089,6 +5867,7 @@ var ComfyRegistry = class ComfyRegistry {
5089
5867
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
5090
5868
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
5091
5869
  this.knownModels = /* @__PURE__ */ new Map();
5870
+ this.modelRows = [];
5092
5871
  this.alterations = [];
5093
5872
  this.githubStats = /* @__PURE__ */ new Map();
5094
5873
  this.report = new ManagerParseReport();
@@ -5250,4 +6029,4 @@ var ComfyTS = class ComfyTS {
5250
6029
  //#endregion
5251
6030
  export { ComfySchema as a, importSharp as i, settingsPathFor as n, readableStringify as r, ComfyTS as t };
5252
6031
 
5253
- //# sourceMappingURL=state-zTow5ucI.js.map
6032
+ //# sourceMappingURL=state-DgwWhZWb.js.map