comfy-ts 2.17.0 → 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 (100) hide show
  1. package/dist/{ServeApp-BSA5yzxZ.js → ServeApp-qXcQfdgT.js} +3 -3
  2. package/dist/ServeApp-qXcQfdgT.js.map +1 -0
  3. package/dist/cli.js +58 -8
  4. package/dist/cli.js.map +1 -1
  5. package/dist/index.cjs +956 -151
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +1154 -408
  8. package/dist/index.d.ts +1154 -408
  9. package/dist/index.js +956 -151
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-run-DnaMLCFn.js → run-run-Wn7H72Zg.js} +3 -3
  12. package/dist/{run-run-DnaMLCFn.js.map → run-run-Wn7H72Zg.js.map} +1 -1
  13. package/dist/{run-serve-CbKxIu6i.js → run-serve-DaXzoVTS.js} +58 -12
  14. package/dist/run-serve-DaXzoVTS.js.map +1 -0
  15. package/dist/{run-tui-B0AQWbad.js → run-tui-VWSj1D_j.js} +3 -3
  16. package/dist/{run-tui-B0AQWbad.js.map → run-tui-VWSj1D_j.js.map} +1 -1
  17. package/dist/serve-web.js +56 -48
  18. package/dist/{state-C2oDiQ26.js → state-DgwWhZWb.js} +957 -152
  19. package/dist/state-DgwWhZWb.js.map +1 -0
  20. package/dist/web.d.ts +1172 -426
  21. package/dist/web.js +956 -151
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/ace-step15-t2a.cflow.ts +163 -0
  24. package/examples/comfy-cloud/anima-t2i-base.cflow.ts +57 -0
  25. package/examples/comfy-cloud/boogu-t2i.cflow.ts +55 -0
  26. package/examples/comfy-cloud/chronoedit-i2i.cflow.ts +95 -0
  27. package/examples/comfy-cloud/ernie-t2i-base.cflow.ts +81 -0
  28. package/examples/comfy-cloud/flux1-t2i-krea.cflow.ts +63 -0
  29. package/examples/comfy-cloud/flux2-i2i-dev.cflow.ts +83 -0
  30. package/examples/comfy-cloud/flux2-t2i-dev.cflow.ts +60 -0
  31. package/examples/comfy-cloud/hidream-o1-i2i.cflow.ts +71 -0
  32. package/examples/comfy-cloud/hidream-o1-t2i.cflow.ts +62 -0
  33. package/examples/comfy-cloud/krea2-i2i.cflow.ts +78 -0
  34. package/examples/comfy-cloud/ltx2-i2v.cflow.ts +175 -0
  35. package/examples/comfy-cloud/ltx2-t2v.cflow.ts +143 -0
  36. package/examples/comfy-cloud/ltx23-i2v.cflow.ts +189 -0
  37. package/examples/comfy-cloud/ltx23-t2v.cflow.ts +151 -0
  38. package/examples/comfy-cloud/mage-flow-i2i-turbo.cflow.ts +72 -0
  39. package/examples/comfy-cloud/mage-flow-i2i.cflow.ts +74 -0
  40. package/examples/comfy-cloud/mage-flow-t2i-turbo.cflow.ts +60 -0
  41. package/examples/comfy-cloud/mage-flow-t2i.cflow.ts +60 -0
  42. package/examples/comfy-cloud/minimax-h3-t2i.cflow.ts +64 -0
  43. package/examples/comfy-cloud/netayume-t2i.cflow.ts +60 -0
  44. package/examples/comfy-cloud/qwen-image-i2i-2509.cflow.ts +75 -0
  45. package/examples/comfy-cloud/qwen-image-t2i-2512.cflow.ts +63 -0
  46. package/examples/comfy-cloud/sdk.d.ts +21683 -13737
  47. package/examples/comfy-cloud/stable-audio3-t2a.cflow.ts +96 -0
  48. package/examples/comfy-cloud/z-image-t2i-base.cflow.ts +54 -0
  49. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +1 -1
  50. package/package.json +2 -2
  51. package/src/cli/bunHop.ts +49 -0
  52. package/src/cli/comfy-ts-cli.ts +4 -4
  53. package/src/cli/serve/run-serve.ts +51 -13
  54. package/src/cli/serve/web/components/App.tsx +2 -0
  55. package/src/cli/serve/web/components/DialogLayer.tsx +55 -0
  56. package/src/cli/serve/web/components/DraftTabs.tsx +8 -3
  57. package/src/cli/serve/web/components/PromptEnhancer.tsx +15 -9
  58. package/src/cli/serve/web/components/SideMenu.tsx +16 -8
  59. package/src/cli/serve/web/state/WebSt.ts +10 -1
  60. package/src/cli/serve/web/state/dialog.ts +59 -0
  61. package/src/cli/serve/web/state/keptLines.ts +1 -1
  62. package/src/cli/serve/web/styles.ts +8 -0
  63. package/src/graph/ComfyNode.ts +93 -12
  64. package/src/host/ComfyHost.ts +31 -10
  65. package/src/host/ComfyManager.ts +448 -62
  66. package/src/litegraph/CanonicalWorkflow.ts +3 -0
  67. package/src/litegraph/LiteGraphJSON.ts +2 -2
  68. package/src/litegraph/LiteGraphNodeInput.ts +2 -2
  69. package/src/litegraph/LiteGraphNodeOutput.ts +2 -2
  70. package/src/litegraph/convertFlowToLiteGraphJSON.ts +127 -34
  71. package/src/litegraph/expandSubgraphs.ts +14 -0
  72. package/src/litegraph/normalizeWorkflow.ts +1 -0
  73. package/src/manager/ComfyRegistry.ts +2 -0
  74. package/src/manager/generated/KnownComfyCustomNodeName.ts +6354 -1680
  75. package/src/manager/generated/KnownComfyPluginTitle.ts +718 -356
  76. package/src/manager/generated/KnownComfyPluginURL.ts +357 -181
  77. package/src/manager/generated/KnownModel_Base.ts +9 -5
  78. package/src/manager/generated/KnownModel_FileName.ts +135 -0
  79. package/src/manager/generated/KnownModel_Name.ts +135 -0
  80. package/src/manager/generated/KnownModel_SavePath.ts +16 -14
  81. package/src/manager/generated/KnownModel_Type.ts +15 -13
  82. package/src/manager/installedView.ts +176 -0
  83. package/src/manager/json/custom-node-list.json +4018 -2248
  84. package/src/manager/json/extension-node-map.json +8903 -2964
  85. package/src/manager/json/github-stats.json +10796 -10036
  86. package/src/manager/json/model-list.json +298 -1
  87. package/src/manager/loaders/step4_model-list-loader.ts +1 -0
  88. package/src/manager/types/ComfyManagerAPIModelList.ts +3 -0
  89. package/src/manager/types/ComfyManagerAPIPluginList.ts +19 -0
  90. package/src/promptEnhancers.ts +1 -1
  91. package/src/runner/ComfyExecution.ts +4 -1
  92. package/src/runner/ComfyWsApi.ts +82 -15
  93. package/src/sdk-generator/ComfySchema.ts +10 -1
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +4 -1
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +61 -20
  96. package/src/sdk-generator/inputWidgetKind.ts +19 -4
  97. package/src/sdk-generator/litegraphToApiRequestPayload.ts +141 -33
  98. package/dist/ServeApp-BSA5yzxZ.js.map +0 -1
  99. package/dist/run-serve-CbKxIu6i.js.map +0 -1
  100. package/dist/state-C2oDiQ26.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -134,7 +134,7 @@ function createNodeStorage() {
134
134
  }
135
135
  //#endregion
136
136
  //#region package.json
137
- var version = "2.17.0";
137
+ var version = "2.18.0";
138
138
  //#endregion
139
139
  //#region src/litegraph/LiteGraphLinkID.ts
140
140
  const asLiteGraphLinkID = (id) => id;
@@ -290,7 +290,8 @@ const expandOneInstance = (wf, instance, def) => {
290
290
  name: i.name,
291
291
  type: i.type,
292
292
  link: i.link != null ? newLinkIds.get(i.link) ?? null : null,
293
- widgetName: i.widgetName
293
+ widgetName: i.widgetName,
294
+ widgetSource: i.widgetSource
294
295
  })),
295
296
  outputs: inner.outputs.map((o) => ({
296
297
  name: o.name,
@@ -331,6 +332,20 @@ const expandOneInstance = (wf, instance, def) => {
331
332
  wf.links = wf.links.filter((l) => !dead.has(l.id));
332
333
  pruneDeadLinkRefs(wf, dead);
333
334
  promoteInstanceWidgets(instance, def, splicedNodes, newNodeIds, boundaryTargetsByInSlot);
335
+ for (const [slot, targets] of boundaryTargetsByInSlot) {
336
+ if (outerLinkIntoDefSlot.has(slot)) continue;
337
+ const source = targets.find((t) => innerInputAt(splicedNodes, t)?.widgetName != null);
338
+ const sourceInput = source != null ? innerInputAt(splicedNodes, source) : null;
339
+ if (source == null || sourceInput == null) continue;
340
+ for (const t of targets) {
341
+ const input = splicedNodes.find((n) => n.id === t.nodeId)?.inputs[t.slot];
342
+ if (input == null || input.widgetName != null || input.link != null) continue;
343
+ input.widgetSource = {
344
+ nodeId: source.nodeId,
345
+ inputName: sourceInput.name
346
+ };
347
+ }
348
+ }
334
349
  wf.nodes = wf.nodes.filter((n) => n.id !== instance.id);
335
350
  wf.nodes.push(...splicedNodes);
336
351
  wf.links.push(...splicedLinks);
@@ -442,7 +457,7 @@ const LiteGraphNodeInput_ark = (0, arktype.type)({
442
457
  type: "string",
443
458
  "link?": LiteGraphLinkID_.or(arktype.type.null),
444
459
  "shape?": "number",
445
- "label?": "string",
460
+ "label?": arktype.type.string.or(arktype.type.null),
446
461
  "widget?": (0, arktype.type)({
447
462
  name: "string",
448
463
  "config?": "unknown"
@@ -459,7 +474,7 @@ const LiteGraphNodeOutput_ark = (0, arktype.type)({
459
474
  type: "string",
460
475
  "links?": LiteGraphLinkID_.array().or(arktype.type.null),
461
476
  "shape?": "number",
462
- "slot_index?": LiteGraphSlotIndex_
477
+ "slot_index?": LiteGraphSlotIndex_.or(arktype.type.null)
463
478
  });
464
479
  //#endregion
465
480
  //#region src/litegraph/LiteGraphNode.ts
@@ -529,7 +544,7 @@ const LiteGraphSubgraphDef_ark = (0, arktype.type)({
529
544
  const LiteGraphJSON_ark = (0, arktype.type)({
530
545
  "id?": "string",
531
546
  "revision?": "number",
532
- "last_node_id?": "number",
547
+ "last_node_id?": "number | string",
533
548
  "last_link_id?": "number",
534
549
  "state?": arktype.type.Record("string", "unknown"),
535
550
  nodes: LiteGraphNode_ark.array(),
@@ -628,7 +643,8 @@ const normalizeInput = (i) => {
628
643
  name: i.name,
629
644
  type: i.type,
630
645
  link: i.link ?? null,
631
- widgetName: i.widget?.name ?? null
646
+ widgetName: i.widget?.name ?? null,
647
+ widgetSource: null
632
648
  };
633
649
  };
634
650
  const normalizeOutput = (o) => {
@@ -801,6 +817,11 @@ const ComfyDefaultNodeWhenUnknown_Schema = {
801
817
  python_module: "nodes"
802
818
  };
803
819
  //#endregion
820
+ //#region src/utils/exhaust.ts
821
+ function exhaust(x) {
822
+ return x;
823
+ }
824
+ //#endregion
804
825
  //#region src/sdk-generator/inputWidgetKind.ts
805
826
  const isRecord$1 = (x) => typeof x === "object" && x != null && !Array.isArray(x);
806
827
  /**
@@ -869,6 +890,14 @@ const parseContainer = (template) => {
869
890
  requiredCount: isRecord$1(input) && isRecord$1(input["required"]) && Object.keys(input["required"]).length > 0 ? Math.min(min, names.length) : 0
870
891
  };
871
892
  };
893
+ /** dynamic group (`template` holding `required`/`optional` sections itself): fields in the
894
+ * frontend's creation order, required then optional; `_io.py _DynamicGroup` defaults min 0, max 20 */
895
+ const parseGroup = (o, template) => ({
896
+ kind: "dynamic-group",
897
+ fields: flattenInputSections(template),
898
+ min: typeof o["min"] === "number" ? o["min"] : 0,
899
+ max: typeof o["max"] === "number" ? o["max"] : 20
900
+ });
872
901
  /**
873
902
  * the single template sub-input's slot type of an autogrow container
874
903
  * (`'IMAGE'` for TextEncodeBooguEdit.images). null when opts are not an
@@ -943,11 +972,12 @@ const classifyWidgetInput = (p) => {
943
972
  };
944
973
  }
945
974
  const template = o?.["template"];
946
- if (isRecord$1(template)) {
975
+ if (o != null && isRecord$1(template)) {
947
976
  if (isRecord$1(template["input"])) return parseContainer(template);
977
+ if (isRecord$1(template["required"]) || isRecord$1(template["optional"])) return parseGroup(o, template);
948
978
  return { kind: "slot" };
949
979
  }
950
- if (o?.["socketless"] === true) return {
980
+ if (typeof o?.["socketless"] === "boolean") return {
951
981
  kind: "widget",
952
982
  consumes: 1,
953
983
  strictValues: false,
@@ -1120,18 +1150,43 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1120
1150
  inputs[p.path] = key;
1121
1151
  for (const sub of opt.inputs) consumeBranchInput(`${p.path}.${sub.name}`, sub);
1122
1152
  };
1153
+ /** the row count first (named, else positional, else `min`), then every row's fields in
1154
+ * template order: the frontend's saved run (architecture.md, dynamic group) */
1155
+ const consumeDynamicGroup = (p) => {
1156
+ const r = resolveWidgetValue({
1157
+ promptName: p.path,
1158
+ consumes: 1,
1159
+ prefixLen: 0
1160
+ });
1161
+ const saved = r.filled ? p.min : r.value;
1162
+ 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);
1163
+ const rows = Math.max(p.min, saved);
1164
+ if (r.filled || rows !== saved) LOG(`${node.type}#${node.id}.${p.path} = ${rows} rows (min ${p.min})`);
1165
+ for (let row = 0; row < rows; row++) for (const field of p.fields) consumeBranchInput(`${p.path}.${row}.${field.name}`, field);
1166
+ };
1123
1167
  const consumeBranchInput = (subPath, sub) => {
1124
1168
  const kind = classifyWidgetInput({
1125
- name: sub.name,
1169
+ name: subPath,
1126
1170
  type: sub.type,
1127
1171
  opts: sub.opts
1128
1172
  });
1129
- if (kind.kind === "slot" || kind.kind === "dynamic-container") return;
1130
- if (kind.kind === "dynamic-combo") return consumeDynamicCombo({
1131
- path: subPath,
1132
- options: kind.options,
1133
- defaultKey: kind.defaultKey
1134
- });
1173
+ switch (kind.kind) {
1174
+ case "slot":
1175
+ case "dynamic-container": return;
1176
+ case "dynamic-combo": return consumeDynamicCombo({
1177
+ path: subPath,
1178
+ options: kind.options,
1179
+ defaultKey: kind.defaultKey
1180
+ });
1181
+ case "dynamic-group": return consumeDynamicGroup({
1182
+ path: subPath,
1183
+ fields: kind.fields,
1184
+ min: kind.min,
1185
+ max: kind.max
1186
+ });
1187
+ case "widget": break;
1188
+ default: return exhaust(kind);
1189
+ }
1135
1190
  const inlineEnum = Array.isArray(sub.type) ? sub.type.filter((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean") : void 0;
1136
1191
  consumePlainWidget({
1137
1192
  promptName: subPath,
@@ -1153,26 +1208,50 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1153
1208
  strictValues: true,
1154
1209
  prefixValues: []
1155
1210
  };
1156
- if (kind.kind === "widget") consumePlainWidget({
1157
- promptName: field.nameInComfy,
1158
- typeName: field.typeName,
1159
- opts: field.opts,
1160
- consumes: kind.consumes,
1161
- prefixLen: kind.prefixValues.length,
1162
- strict: kind.strictValues,
1163
- linkedInput: input
1164
- });
1165
- else if (kind.kind === "dynamic-combo") consumeDynamicCombo({
1166
- path: field.nameInComfy,
1167
- options: kind.options,
1168
- defaultKey: kind.defaultKey
1169
- });
1170
- else if (kind.kind === "dynamic-container") for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1171
- const iname = `${field.nameInComfy}.${instName}`;
1172
- if (inputsInNodeJSON.find((i) => i.name === iname)?.link == null) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): autogrow "${field.nameInComfy}" requires instance "${iname}" connected (template.min = ${kind.requiredCount})`, node);
1173
- }
1174
- else if (!fieldNamesPresent.has(field.nameInComfy)) {
1175
- if (field.required) throw new WorkflowConvertError("missing-required-input", `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) has neither widget value nor link`, node);
1211
+ switch (kind.kind) {
1212
+ case "widget":
1213
+ consumePlainWidget({
1214
+ promptName: field.nameInComfy,
1215
+ typeName: field.typeName,
1216
+ opts: field.opts,
1217
+ consumes: kind.consumes,
1218
+ prefixLen: kind.prefixValues.length,
1219
+ strict: kind.strictValues,
1220
+ linkedInput: input
1221
+ });
1222
+ break;
1223
+ case "dynamic-combo":
1224
+ consumeDynamicCombo({
1225
+ path: field.nameInComfy,
1226
+ options: kind.options,
1227
+ defaultKey: kind.defaultKey
1228
+ });
1229
+ break;
1230
+ case "dynamic-group":
1231
+ consumeDynamicGroup({
1232
+ path: field.nameInComfy,
1233
+ fields: kind.fields,
1234
+ min: kind.min,
1235
+ max: kind.max
1236
+ });
1237
+ break;
1238
+ case "dynamic-container":
1239
+ for (const instName of kind.instanceNames.slice(0, kind.requiredCount)) {
1240
+ const iname = `${field.nameInComfy}.${instName}`;
1241
+ 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);
1242
+ }
1243
+ break;
1244
+ case "slot":
1245
+ if (input?.link == null && Object.hasOwn(named, field.nameInComfy)) {
1246
+ inputs[field.nameInComfy] = toPromptValue(named[field.nameInComfy], {
1247
+ promptName: field.nameInComfy,
1248
+ strict: false
1249
+ });
1250
+ break;
1251
+ }
1252
+ 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);
1253
+ break;
1254
+ default:
1176
1255
  }
1177
1256
  }
1178
1257
  const getParentNode = (linkId) => {
@@ -1278,6 +1357,45 @@ const convertLiteGraphToPrompt = (schema, workflow, opts = {}) => {
1278
1357
  class_type: node.type
1279
1358
  };
1280
1359
  }
1360
+ for (const node of workflow.nodes) {
1361
+ const own = prompt[String(node.id)];
1362
+ if (own == null) continue;
1363
+ for (const ipt of node.inputs) {
1364
+ if (ipt.link != null || ipt.widgetSource == null || Object.hasOwn(own.inputs, ipt.name)) continue;
1365
+ const value = prompt[String(ipt.widgetSource.nodeId)]?.inputs[ipt.widgetSource.inputName];
1366
+ if (value !== void 0) own.inputs[ipt.name] = value;
1367
+ }
1368
+ }
1369
+ const missing = /* @__PURE__ */ new Map();
1370
+ for (const node of workflow.nodes) {
1371
+ const own = prompt[String(node.id)];
1372
+ const nodeSchema = schema.nodesByNameInComfy[node.type];
1373
+ if (own == null || nodeSchema == null) continue;
1374
+ for (const field of nodeSchema.inputs) {
1375
+ if (!field.required || Object.hasOwn(own.inputs, field.nameInComfy)) continue;
1376
+ const kind = classifySchemaInput(field).kind;
1377
+ if (kind !== "slot" && kind !== "widget") continue;
1378
+ missing.set(String(node.id), {
1379
+ node,
1380
+ message: `node ${node.id}(${node.type}): required input "${field.nameInComfy}" (${field.typeName}) is unlinked and no value covers it`
1381
+ });
1382
+ break;
1383
+ }
1384
+ }
1385
+ if (missing.size > 0) {
1386
+ const complete = (id, seen) => {
1387
+ if (seen.has(id)) return true;
1388
+ seen.add(id);
1389
+ if (missing.has(id)) return false;
1390
+ for (const value of Object.values(prompt[id]?.inputs ?? {})) if (Array.isArray(value) && typeof value[0] === "string" && !complete(value[0], seen)) return false;
1391
+ return true;
1392
+ };
1393
+ const outputs = Object.keys(prompt).filter((id) => schema.data.spec[prompt[id]?.class_type ?? ""]?.output_node === true);
1394
+ const dropped = outputs.filter((id) => !complete(id, /* @__PURE__ */ new Set()));
1395
+ const first = missing.values().next().value;
1396
+ if (first != null && outputs.length > 0 && dropped.length === outputs.length) throw new WorkflowConvertError("missing-required-input", first.message, first.node);
1397
+ 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("; ")}`);
1398
+ }
1281
1399
  return prompt;
1282
1400
  };
1283
1401
  //#endregion
@@ -1458,21 +1576,37 @@ var ComfyNode = class ComfyNode {
1458
1576
  _convertPromptExtToPrompt(promptExt) {
1459
1577
  const inputs = {};
1460
1578
  const _done = /* @__PURE__ */ new Set();
1461
- /** every dotted key of every branch: the selected ones are written here, the rest are dropped */
1579
+ /** every dotted key a dynamic input wrote or dropped on purpose: the rest loop skips them */
1462
1580
  const _comboBranchKeys = /* @__PURE__ */ new Set();
1463
1581
  for (const i of this.$schema.inputs) {
1464
1582
  _done.add(i.nameInComfy);
1465
1583
  const kind = classifySchemaInput(i);
1466
- if (kind.kind === "dynamic-combo") {
1467
- this._writeDynamicCombo({
1468
- name: i.nameInComfy,
1469
- options: kind.options,
1470
- defaultKey: kind.defaultKey,
1471
- provided: promptExt.inputs,
1472
- out: inputs,
1473
- claimed: _comboBranchKeys
1474
- });
1475
- continue;
1584
+ switch (kind.kind) {
1585
+ case "dynamic-combo":
1586
+ this._writeDynamicCombo({
1587
+ name: i.nameInComfy,
1588
+ options: kind.options,
1589
+ defaultKey: kind.defaultKey,
1590
+ provided: promptExt.inputs,
1591
+ out: inputs,
1592
+ claimed: _comboBranchKeys
1593
+ });
1594
+ continue;
1595
+ case "dynamic-group":
1596
+ this._writeDynamicGroup({
1597
+ name: i.nameInComfy,
1598
+ fields: kind.fields,
1599
+ min: kind.min,
1600
+ max: kind.max,
1601
+ provided: promptExt.inputs,
1602
+ out: inputs,
1603
+ claimed: _comboBranchKeys
1604
+ });
1605
+ continue;
1606
+ case "widget":
1607
+ case "slot":
1608
+ case "dynamic-container": break;
1609
+ default:
1476
1610
  }
1477
1611
  const value = this.serializeValue(i.nameInComfy, promptExt.inputs[i.nameInComfy]);
1478
1612
  if (value !== void 0) inputs[i.nameInComfy] = value;
@@ -1511,6 +1645,42 @@ var ComfyNode = class ComfyNode {
1511
1645
  }) : this.serializeValue(dotted, given);
1512
1646
  }
1513
1647
  }
1648
+ /** dynamic group → the row array becomes `<decl>.<row>.<field>` keys, absent fields filled
1649
+ * from the schema (architecture.md, dynamic group). No array = a prompt json whose dotted
1650
+ * keys are already the rows: they pass through the rest loop untouched */
1651
+ _writeDynamicGroup(p) {
1652
+ const where = `${this.$schema.nodeKey}#${this.uid}`;
1653
+ const raw = p.provided[p.name];
1654
+ const prefix = `${p.name}.`;
1655
+ if (raw == null) {
1656
+ 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)`);
1657
+ return;
1658
+ }
1659
+ for (const k of Object.keys(p.provided)) if (k.startsWith(prefix)) p.claimed.add(k);
1660
+ if (!Array.isArray(raw)) {
1661
+ this.graph.recordProblem(`🔴 "${p.name}" on ${where} takes an array of rows, got ${JSON.stringify(raw)}`);
1662
+ return;
1663
+ }
1664
+ 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}`);
1665
+ raw.forEach((row, ix) => {
1666
+ if (typeof row !== "object" || row == null || Array.isArray(row)) {
1667
+ this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} is not an object: ${JSON.stringify(row)}`);
1668
+ return;
1669
+ }
1670
+ const given = new Map(Object.entries(row));
1671
+ for (const field of p.fields) {
1672
+ const dotted = `${p.name}.${ix}.${field.name}`;
1673
+ const value = given.get(field.name);
1674
+ p.out[dotted] = value == null ? defaultValueForWidget({
1675
+ type: typeof field.type === "string" ? field.type : "COMBO",
1676
+ opts: field.opts,
1677
+ enumValues: Array.isArray(field.type) ? field.type.filter(isScalarValue) : void 0
1678
+ }) : this.serializeValue(dotted, value);
1679
+ given.delete(field.name);
1680
+ }
1681
+ for (const extra of given.keys()) this.graph.recordProblem(`🔴 "${p.name}" row ${ix} on ${where} has no field "${extra}"`);
1682
+ });
1683
+ }
1514
1684
  /** return the list of nodes piped into this node */
1515
1685
  _incomingNodes() {
1516
1686
  const incomingNodes = [];
@@ -1654,6 +1824,12 @@ var ComfyNode = class ComfyNode {
1654
1824
  const kind = classifySchemaInput(decl);
1655
1825
  const slotType = containerInstanceSlotType(decl.opts);
1656
1826
  if (kind.kind === "dynamic-container" && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null) return slotType;
1827
+ if (kind.kind === "dynamic-group") {
1828
+ const rest = name.slice(dot + 1);
1829
+ const fieldName = rest.slice(rest.indexOf(".") + 1);
1830
+ const field = kind.fields.find((f) => f.name === fieldName);
1831
+ if (rest.includes(".") && typeof field?.type === "string") return field.type;
1832
+ }
1657
1833
  }
1658
1834
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1659
1835
  }
@@ -1737,24 +1913,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1737
1913
  const convertNodeToLiteGraphNode = (ctx, node) => {
1738
1914
  const inputs = [];
1739
1915
  const widgets_values = [];
1916
+ const pushLinked = (name, type, link, extra = {}) => {
1917
+ const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1918
+ const input = {
1919
+ name,
1920
+ type,
1921
+ link: ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
1922
+ };
1923
+ if (extra.shape != null) input.shape = extra.shape;
1924
+ if (extra.widget === true) input.widget = { name };
1925
+ inputs.push(input);
1926
+ };
1927
+ /** frontend button-widget values ride BEFORE the real value (LOAD_3D); the control_after_generate
1928
+ * phantom AFTER it: the classifier's consumes covers prefix + value + control, config-driven
1929
+ * (the 2024 INT-named-seed heuristic lives inside controlConsumes), so export and import can
1930
+ * never disagree on the run length */
1931
+ const pushWidgetRun = (kind, raw, opts) => {
1932
+ widgets_values.push(...kind.prefixValues, raw);
1933
+ const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1934
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(opts));
1935
+ };
1936
+ /** one input, the way the editor saves it: a widget writes its run (a linked one too, with
1937
+ * its widget socket, since the editor serializes every widget), a dynamic combo its key then
1938
+ * the selected branch inline, a group its row count then the rows, a slot its socket */
1939
+ const writeInput = (p) => {
1940
+ const where = `${node.$schema.nameInComfy}#${node.uid} "${p.name}"`;
1941
+ switch (p.kind.kind) {
1942
+ case "widget":
1943
+ if (_isLink(p.value)) {
1944
+ pushLinked(p.name, p.typeName, p.value, { widget: true });
1945
+ pushWidgetRun(p.kind, defaultValueForWidget({
1946
+ type: p.typeName,
1947
+ opts: p.opts
1948
+ }), p.opts);
1949
+ } else pushWidgetRun(p.kind, p.value, p.opts);
1950
+ return;
1951
+ case "slot":
1952
+ if (_isLink(p.value)) pushLinked(p.name, p.typeName, p.value);
1953
+ else inputs.push({
1954
+ name: p.name,
1955
+ type: p.typeName,
1956
+ link: null
1957
+ });
1958
+ return;
1959
+ case "dynamic-combo": {
1960
+ const kind = p.kind;
1961
+ const key = typeof p.value === "string" ? p.value : kind.defaultKey;
1962
+ const option = kind.options.find((o) => o.key === key);
1963
+ if (option == null) throw new Error(`🔴 [toWorkflowJson] ${where}: "${key}" is not one of its options`);
1964
+ widgets_values.push(key);
1965
+ for (const sub of option.inputs) writeSub(`${p.name}.${sub.name}`, sub);
1966
+ return;
1967
+ }
1968
+ case "dynamic-container": {
1969
+ const type = containerInstanceSlotType(p.opts) ?? "*";
1970
+ for (const instance of p.kind.instanceNames) {
1971
+ const name = `${p.name}.${instance}`;
1972
+ const value = node.json.inputs[name];
1973
+ if (value == null) continue;
1974
+ const raw = node.serializeValue(name, value);
1975
+ if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${where}.${instance} holds a literal; an autogrow instance is a link slot in the editor`);
1976
+ pushLinked(name, type, raw, { shape: 7 });
1977
+ }
1978
+ return;
1979
+ }
1980
+ case "dynamic-group": {
1981
+ const prefix = `${p.name}.`;
1982
+ let rows = 0;
1983
+ for (const key of Object.keys(node.json.inputs)) {
1984
+ if (!key.startsWith(prefix)) continue;
1985
+ const row = Number(key.slice(prefix.length).split(".")[0]);
1986
+ if (Number.isInteger(row) && row >= rows) rows = row + 1;
1987
+ }
1988
+ widgets_values.push(rows);
1989
+ for (let row = 0; row < rows; row++) for (const field of p.kind.fields) writeSub(`${prefix}${row}.${field.name}`, field);
1990
+ return;
1991
+ }
1992
+ default: p.kind;
1993
+ }
1994
+ };
1995
+ /** a dotted input (dynamic combo branch, group row field): never a schema input, so its absent
1996
+ * value is the widget's schema default rather than serializeValue's */
1997
+ const writeSub = (name, sub) => {
1998
+ const typeName = typeof sub.type === "string" ? sub.type : "COMBO";
1999
+ const raw = node.json.inputs[name];
2000
+ writeInput({
2001
+ name,
2002
+ kind: classifyWidgetInput({
2003
+ name,
2004
+ type: sub.type,
2005
+ opts: sub.opts
2006
+ }),
2007
+ typeName,
2008
+ opts: sub.opts,
2009
+ value: raw === void 0 ? defaultValueForWidget({
2010
+ type: typeName,
2011
+ opts: sub.opts
2012
+ }) : raw
2013
+ });
2014
+ };
1740
2015
  for (const ipt of node.$schema.inputs) {
1741
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1742
2016
  const kind = classifySchemaInput(ipt);
1743
- if (_isLink(raw)) {
1744
- const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber, `link target node "${raw[0]}" not found in graph`);
1745
- inputs.push({
1746
- name: ipt.nameInComfy,
1747
- type: ipt.typeName,
1748
- link: ctx.allocateLink(nodeUidNumber, raw[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), ipt.typeName)
1749
- });
1750
- } else if (kind.kind === "widget") {
1751
- widgets_values.push(...kind.prefixValues, raw);
1752
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1753
- for (let i = 0; i < phantoms; i++) widgets_values.push(false);
1754
- } else inputs.push({
2017
+ const raw = node.json.inputs[ipt.nameInComfy];
2018
+ const value = kind.kind === "widget" || kind.kind === "slot" ? node.serializeValue(ipt.nameInComfy, raw) : raw;
2019
+ writeInput({
1755
2020
  name: ipt.nameInComfy,
1756
- type: ipt.typeName,
1757
- link: null
2021
+ kind,
2022
+ typeName: ipt.typeName,
2023
+ opts: ipt.opts,
2024
+ value
1758
2025
  });
1759
2026
  }
1760
2027
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1773,6 +2040,12 @@ const convertNodeToLiteGraphNode = (ctx, node) => {
1773
2040
  widgets_values
1774
2041
  };
1775
2042
  };
2043
+ /** the editor's control widget is a combo (fixed, increment, decrement, randomize):
2044
+ * a config naming a mode keeps it, anything else is `fixed`, the seed the code pinned */
2045
+ const controlMode = (opts) => {
2046
+ const mode = typeof opts === "object" && opts != null ? Reflect.get(opts, "control_after_generate") : null;
2047
+ return typeof mode === "string" ? mode : "fixed";
2048
+ };
1776
2049
  const _isLink = (v) => {
1777
2050
  return Array.isArray(v) && v.length === 2 && typeof v[0] === "string" && typeof v[1] === "number";
1778
2051
  };
@@ -1934,11 +2207,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1934
2207
  return resultSuccess(txt_chunks);
1935
2208
  };
1936
2209
  //#endregion
1937
- //#region src/utils/exhaust.ts
1938
- function exhaust(x) {
1939
- return x;
1940
- }
1941
- //#endregion
1942
2210
  //#region src/utils/sha1.ts
1943
2211
  function sha1Hex(data) {
1944
2212
  const ml = data.length;
@@ -2076,16 +2344,17 @@ const types$1 = (0, arktype.scope)({
2076
2344
  },
2077
2345
  _WsMsgExecutedData: {
2078
2346
  node: "ComfyNodeID",
2079
- output: {
2080
- "previews?": [{ filepath: "string" }, "[]"],
2081
- "images?": "ComfyImageInfo[]",
2082
- "audio?": "ComfyImageInfo[]",
2083
- "video?": "ComfyImageInfo[]",
2084
- "gifs?": "ComfyImageInfo[]",
2085
- "text?": "unknown[]"
2086
- },
2347
+ output: "_WsMsgExecutedOutput | null",
2087
2348
  prompt_id: "PromptID"
2088
2349
  },
2350
+ _WsMsgExecutedOutput: {
2351
+ "previews?": [{ filepath: "string" }, "[]"],
2352
+ "images?": "ComfyImageInfo[]",
2353
+ "audio?": "ComfyImageInfo[]",
2354
+ "video?": "ComfyImageInfo[]",
2355
+ "gifs?": "ComfyImageInfo[]",
2356
+ "text?": "unknown[]"
2357
+ },
2089
2358
  WsMsgExecuted: {
2090
2359
  type: "'executed'",
2091
2360
  data: "_WsMsgExecutedData"
@@ -2107,12 +2376,22 @@ const types$1 = (0, arktype.scope)({
2107
2376
  exception_type: "string",
2108
2377
  traceback: "string[]",
2109
2378
  current_inputs: "Record<string, unknown>",
2110
- current_outputs: "Record<string, unknown>"
2379
+ current_outputs: "ComfyNodeID[]"
2111
2380
  },
2112
2381
  WsMsgExecutionError: {
2113
2382
  type: "'execution_error'",
2114
2383
  data: "_WsMsgExecutionErrorData"
2115
2384
  },
2385
+ _WsMsgExecutionInterruptedData: {
2386
+ prompt_id: "PromptID",
2387
+ node_id: "ComfyNodeID",
2388
+ node_type: "string",
2389
+ executed: "ComfyNodeID[]"
2390
+ },
2391
+ WsMsgExecutionInterrupted: {
2392
+ type: "'execution_interrupted'",
2393
+ data: "_WsMsgExecutionInterruptedData"
2394
+ },
2116
2395
  WSMsgManagerFeedbackData: { data: "string" },
2117
2396
  WSMsgManagerFeedback: {
2118
2397
  type: "'manager-terminal-feedback'",
@@ -2142,11 +2421,51 @@ const types$1 = (0, arktype.scope)({
2142
2421
  type: "'progress_state'",
2143
2422
  data: "_WsMsgProgressStateData"
2144
2423
  },
2145
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2424
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2146
2425
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2147
2426
  }).export();
2148
2427
  const PromptInfo_ark = (0, arktype.type)({ prompt_id: types$1.PromptID }).as();
2149
2428
  const WsMsg_ark = types$1.WsMsg;
2429
+ /** every json event type ComfyHost.onMessage routes; checked against the WsMsg union below */
2430
+ const ROUTED_WS_EVENT_TYPES = [
2431
+ "status",
2432
+ "manager-terminal-feedback",
2433
+ "logs",
2434
+ "execution_start",
2435
+ "execution_cached",
2436
+ "executing",
2437
+ "progress",
2438
+ "progress_state",
2439
+ "executed",
2440
+ "execution_error",
2441
+ "execution_interrupted",
2442
+ "execution_success"
2443
+ ];
2444
+ /** events a server or a custom node sends by design that comfy-ts has no use for: dropped
2445
+ * before validation, never logged (architecture.md, ws events) */
2446
+ const IGNORED_WS_EVENT_TYPES = [
2447
+ "feature_flags",
2448
+ "agent_status",
2449
+ "asset_export",
2450
+ "assets.seed.started",
2451
+ "assets.seed.progress",
2452
+ "assets.seed.fast_complete",
2453
+ "assets.seed.enrich_complete",
2454
+ "assets.seed.completed",
2455
+ "assets.seed.cancelled",
2456
+ "assets.seed.error",
2457
+ "assets.seed.paused",
2458
+ "assets.seed.resumed",
2459
+ "cm-queue-status",
2460
+ "cm-api-try-install-customnode",
2461
+ "cm-task-started",
2462
+ "cm-task-completed",
2463
+ "crystools.monitor"
2464
+ ];
2465
+ const ROUTED_SET = new Set(ROUTED_WS_EVENT_TYPES);
2466
+ const IGNORED_SET = new Set(IGNORED_WS_EVENT_TYPES);
2467
+ const isRoutedWsEventType = (t) => ROUTED_SET.has(t);
2468
+ const isIgnoredWsEventType = (t) => IGNORED_SET.has(t);
2150
2469
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2151
2470
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2152
2471
  //#endregion
@@ -2436,6 +2755,10 @@ var ComfyExecution = class {
2436
2755
  else if (msg.type === "progress") graph.onProgress(msg);
2437
2756
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2438
2757
  else if (msg.type === "execution_error") return void this.onError(msg);
2758
+ else if (msg.type === "execution_interrupted") return void this._finish({
2759
+ status: "Failure",
2760
+ error: msg
2761
+ });
2439
2762
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2440
2763
  else {
2441
2764
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3349,6 +3672,15 @@ const dynamicComboUnion = (p) => {
3349
3672
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3350
3673
  }).join(" | ")})`;
3351
3674
  };
3675
+ /** one dynamic-group row as an object type: a field is optional when it has a default or sits in
3676
+ * the template's optional section (ComfyNode fills it, agent/sdk-codegen.md) */
3677
+ const dynamicGroupRow = (fields) => {
3678
+ return `{ ${fields.map((e) => {
3679
+ const opts = isRecord$1(e.opts) ? e.opts : null;
3680
+ const optional = !e.required || opts?.["default"] !== void 0;
3681
+ return `${escapeJSKey(e.name)}${optional ? "?" : ""}: ${branchInputType(e)}`;
3682
+ }).join("; ")} }`;
3683
+ };
3352
3684
  /**
3353
3685
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3354
3686
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3397,6 +3729,8 @@ function codegenSDK(opts) {
3397
3729
  b.deindent();
3398
3730
  p(`// #endregion`);
3399
3731
  const nodes = this.nodes.toSorted((a, b) => a.nodeKey.localeCompare(b.nodeKey));
3732
+ /** one row type per dynamic group, named once so a long COMBO union is not printed twice */
3733
+ const groupRows = [];
3400
3734
  p(`interface IN {`);
3401
3735
  b.indent();
3402
3736
  for (const n of nodes) {
@@ -3404,23 +3738,37 @@ function codegenSDK(opts) {
3404
3738
  const comboSuffixes = [];
3405
3739
  for (const i of n.inputs) {
3406
3740
  const kind = classifySchemaInput(i);
3407
- if (kind.kind === "dynamic-container") {
3408
- const instType = containerInstanceSlotType(i.opts);
3409
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3410
- const opt = ix >= kind.requiredCount ? "?" : "";
3411
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3412
- });
3413
- continue;
3414
- }
3415
- if (kind.kind === "dynamic-combo") {
3416
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3417
- comboSuffixes.push(dynamicComboUnion({
3418
- name: i.nameInComfy,
3419
- nameEscaped: i.nameInComfyEscaped,
3420
- options: kind.options,
3421
- keyOptional: optsDyn?.default !== void 0 || !i.required
3422
- }));
3423
- continue;
3741
+ switch (kind.kind) {
3742
+ case "dynamic-container": {
3743
+ const instType = containerInstanceSlotType(i.opts);
3744
+ if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3745
+ const opt = ix >= kind.requiredCount ? "?" : "";
3746
+ p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3747
+ });
3748
+ continue;
3749
+ }
3750
+ case "dynamic-combo": {
3751
+ const optsDyn = typeof i.opts === "string" ? null : i.opts;
3752
+ comboSuffixes.push(dynamicComboUnion({
3753
+ name: i.nameInComfy,
3754
+ nameEscaped: i.nameInComfyEscaped,
3755
+ options: kind.options,
3756
+ keyOptional: optsDyn?.default !== void 0 || !i.required
3757
+ }));
3758
+ continue;
3759
+ }
3760
+ case "dynamic-group": {
3761
+ const rowKey = `${n.nodeKey}.${i.nameInComfy}`;
3762
+ groupRows.push([rowKey, dynamicGroupRow(kind.fields)]);
3763
+ const row = `GroupRow[${JSON.stringify(rowKey)}]`;
3764
+ p(` /** min=${kind.min} max=${kind.max} rows */`);
3765
+ if (kind.min > 0) p(` ${i.nameInComfyEscaped}: [${row}, ...${row}[]]`);
3766
+ else p(` ${i.nameInComfyEscaped}?: ${row}[]`);
3767
+ continue;
3768
+ }
3769
+ case "widget":
3770
+ case "slot": break;
3771
+ default:
3424
3772
  }
3425
3773
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3426
3774
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3443,6 +3791,15 @@ function codegenSDK(opts) {
3443
3791
  b.deindent();
3444
3792
  p("}");
3445
3793
  p("");
3794
+ if (groupRows.length > 0) {
3795
+ p(`/** one row of each dynamic group input, keyed \`<node>.<input>\` */`);
3796
+ p(`interface GroupRow {`);
3797
+ b.indent();
3798
+ for (const [key, row] of groupRows) p(`${JSON.stringify(key)}: ${row}`);
3799
+ b.deindent();
3800
+ p("}");
3801
+ p("");
3802
+ }
3446
3803
  p(`interface OUT {`);
3447
3804
  b.indent();
3448
3805
  for (const n of nodes) {
@@ -3755,9 +4112,13 @@ var ComfySchema = class {
3755
4112
  if (widgetKind?.kind === "dynamic-combo") {
3756
4113
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3757
4114
  }
4115
+ if (widgetKind?.kind === "dynamic-group") {
4116
+ for (const entry of widgetKind.fields) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
4117
+ }
4118
+ const required = widgetKind?.kind === "dynamic-group" ? widgetKind.min > 0 : ipt.required && !isAutogrowContainer;
3758
4119
  node.inputs.push({
3759
4120
  slotName: inputSlotName,
3760
- required: ipt.required && !isAutogrowContainer,
4121
+ required,
3761
4122
  nameInComfy: inputNameInComfy,
3762
4123
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3763
4124
  typeName: inputTypeName,
@@ -3833,7 +4194,12 @@ const types = (0, arktype.scope)({
3833
4194
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3834
4195
  ComfyInputSpecAlt2: ["ComfyInputType"],
3835
4196
  ComfyInputSpecAlt3: (0, arktype.type)([arktype.type.null]),
3836
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4197
+ ComfyInputSpecAlt4: [
4198
+ "ComfyInputType",
4199
+ "ComfyInputOpts",
4200
+ "unknown"
4201
+ ],
4202
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3837
4203
  ComfyInputType: `string | ComfyEnumDef`,
3838
4204
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3839
4205
  ComfyInputHiddenEntry_broken2: arktype.type.Record("string", arktype.type.unknown),
@@ -3899,10 +4265,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3899
4265
  return result;
3900
4266
  }
3901
4267
  //#endregion
4268
+ //#region src/manager/installedView.ts
4269
+ /**
4270
+ * PURE builders of the public plugin and model lists where the Manager serves none (4.x default ui),
4271
+ * from our mirror and what the host reports (agent/architecture.md, Manager HTTP client).
4272
+ * A row the data cannot decide is left OUT (reads `unknown`), never given a guessed status.
4273
+ */
4274
+ /** `GET customnode/installed`: a disk scan, keyed by directory */
4275
+ const InstalledPacks_ark = arktype.type.Record("string", (0, arktype.type)({
4276
+ "cnr_id?": "string | null",
4277
+ "aux_id?": "string | null",
4278
+ enabled: "boolean"
4279
+ }));
4280
+ /** `GET customnode/getmappings`: the extension-node-map, registered repos rekeyed by registry id */
4281
+ const PackMappings_ark = arktype.type.Record("string", (0, arktype.type)(["string[]", { "title_aux?": "string" }]));
4282
+ /** `https://github.com/Owner/Repo.git/` → `owner/repo` */
4283
+ const repoPath = (url) => url.toLowerCase().replace(/\/+$/, "").replace(/\.git$/, "").split("/").slice(-2).join("/");
4284
+ /** git clone → its `owner/repo`; registry install → its registry id's `title_aux` (= the mirror title) */
4285
+ const attributePacks = (installed, mappings) => {
4286
+ const titleById = new Map(Object.entries(mappings).map(([k, v]) => [k.toLowerCase(), v[1].title_aux]));
4287
+ return Object.entries(installed).map(([dir, p]) => {
4288
+ const aux = p.aux_id ?? null;
4289
+ const cnr = p.cnr_id != null && p.cnr_id !== "" ? p.cnr_id : null;
4290
+ const repo = aux != null && aux.includes("/") ? repoPath(aux) : null;
4291
+ const title = cnr != null ? titleById.get(cnr.toLowerCase()) ?? null : null;
4292
+ return {
4293
+ enabled: p.enabled,
4294
+ repo,
4295
+ title,
4296
+ id: cnr ?? aux ?? dir
4297
+ };
4298
+ });
4299
+ };
4300
+ /** is this mirror row among the attributed packs, enabled? */
4301
+ const packIsInstalled = (packs, plugin) => {
4302
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4303
+ return packs.some((p) => p.enabled && (p.repo === repo || p.title === plugin.title));
4304
+ };
4305
+ const buildPluginView = (p) => {
4306
+ const packs = attributePacks(p.installed, p.mappings);
4307
+ const plugins = [...p.mirror.plugins_byTitle.values()];
4308
+ const mirrorRepos = new Set(plugins.flatMap((x) => x.files.map(repoPath)));
4309
+ const mirrorTitles = new Set(plugins.map((x) => x.title));
4310
+ const joins = (x) => x.repo != null && mirrorRepos.has(x.repo) || x.title != null && mirrorTitles.has(x.title);
4311
+ const unattributed = packs.filter((x) => x.enabled && x.repo == null && !joins(x));
4312
+ const serverTitles = new Set(Object.values(p.mappings).flatMap((v) => v[1].title_aux != null ? [v[1].title_aux] : []));
4313
+ const custom_nodes = [];
4314
+ for (const plugin of plugins) {
4315
+ const repo = repoPath(plugin.files[0] ?? plugin.reference);
4316
+ const joined = packs.filter((x) => x.repo === repo || x.title === plugin.title);
4317
+ if (joined.some((x) => x.enabled)) custom_nodes.push({
4318
+ title: plugin.title,
4319
+ installed: "True"
4320
+ });
4321
+ else if (joined.length === 0 && unattributed.length > 0 && !serverTitles.has(plugin.title)) continue;
4322
+ else custom_nodes.push({
4323
+ title: plugin.title,
4324
+ installed: "False"
4325
+ });
4326
+ }
4327
+ return {
4328
+ list: {
4329
+ chanel: "default",
4330
+ custom_nodes
4331
+ },
4332
+ unattributed: unattributed.map((x) => x.id)
4333
+ };
4334
+ };
4335
+ /** the Manager's `type` → folder map for `save_path: default` (model_utils.get_model_dir, 4.4) */
4336
+ const DEFAULT_FOLDER_BY_TYPE = {
4337
+ checkpoints: "checkpoints",
4338
+ checkpoint: "checkpoints",
4339
+ unclip: "checkpoints",
4340
+ text_encoders: "text_encoders",
4341
+ clip: "text_encoders",
4342
+ vae: "vae",
4343
+ lora: "loras",
4344
+ "t2i-adapter": "controlnet",
4345
+ "t2i-style": "controlnet",
4346
+ controlnet: "controlnet",
4347
+ clip_vision: "clip_vision",
4348
+ gligen: "gligen",
4349
+ upscale: "upscale_models",
4350
+ embedding: "embeddings",
4351
+ embeddings: "embeddings",
4352
+ unet: "diffusion_models",
4353
+ diffusion_model: "diffusion_models"
4354
+ };
4355
+ /** what core `get_filename_list` lists in the standard folders */
4356
+ const LISTED_EXTENSIONS = [
4357
+ ".ckpt",
4358
+ ".pt",
4359
+ ".pt2",
4360
+ ".bin",
4361
+ ".pth",
4362
+ ".safetensors",
4363
+ ".pkl",
4364
+ ".sft"
4365
+ ];
4366
+ /**
4367
+ * where this model counts as installed, in core's `/models/<folder>` terms; null when not decidable.
4368
+ * The Manager's own check accepts the folder root as well as the `save_path` sub folder.
4369
+ */
4370
+ const modelLocation = (m) => {
4371
+ if (m.filename === "<huggingface>" || /[\\/:]/.test(m.filename)) return null;
4372
+ if (!LISTED_EXTENSIONS.some((ext) => m.filename.toLowerCase().endsWith(ext))) return null;
4373
+ if (m.save_path === "default") {
4374
+ const folder = DEFAULT_FOLDER_BY_TYPE[m.type.toLowerCase()];
4375
+ return folder == null ? null : {
4376
+ folder,
4377
+ files: [m.filename]
4378
+ };
4379
+ }
4380
+ const parts = m.save_path.replaceAll("\\", "/").split("/").filter((s) => s !== "");
4381
+ const folder = parts[0];
4382
+ if (folder == null || folder === "custom_nodes" || parts.includes("..")) return null;
4383
+ const sub = [...parts.slice(1), m.filename].join("/");
4384
+ return {
4385
+ folder,
4386
+ files: sub === m.filename ? [m.filename] : [m.filename, sub]
4387
+ };
4388
+ };
4389
+ const buildModelView = (p) => {
4390
+ const listed = new Map([...p.files].map(([folder, files]) => [folder, new Set(files.map((f) => f.replaceAll("\\", "/")))]));
4391
+ const statusOf = (m) => {
4392
+ const at = modelLocation(m);
4393
+ const files = at == null ? null : listed.get(at.folder);
4394
+ if (at == null || files == null) return null;
4395
+ return at.files.some((f) => files.has(f)) ? "True" : "False";
4396
+ };
4397
+ const byName = /* @__PURE__ */ new Map();
4398
+ for (const m of p.models) byName.set(m.name, [...byName.get(m.name) ?? [], m]);
4399
+ const models = [];
4400
+ for (const rows of byName.values()) {
4401
+ const statuses = new Set(rows.map(statusOf));
4402
+ const first = rows[0];
4403
+ const installed = statuses.size === 1 ? [...statuses][0] : null;
4404
+ if (first == null || installed == null) continue;
4405
+ models.push({
4406
+ name: first.name,
4407
+ installed,
4408
+ filename: first.filename,
4409
+ save_path: first.save_path,
4410
+ base: first.base
4411
+ });
4412
+ }
4413
+ return { models };
4414
+ };
4415
+ /** the folders the views need listed */
4416
+ const modelFolders = (models) => new Set([...models].flatMap((m) => modelLocation(m)?.folder ?? []));
4417
+ //#endregion
3902
4418
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3903
4419
  const ComfyManagerAPIModelList_ark = (0, arktype.type)({ models: (0, arktype.type)({
3904
4420
  name: arktype.type.string.as(),
3905
- installed: `'False' | 'True' | 'Update'`
4421
+ installed: `'False' | 'True' | 'Update'`,
4422
+ "filename?": "string",
4423
+ "save_path?": "string",
4424
+ "base?": "string"
3906
4425
  }).array() });
3907
4426
  //#endregion
3908
4427
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3913,28 +4432,155 @@ const ComfyManagerAPIPluginList_ark = (0, arktype.type)({
3913
4432
  }).array(),
3914
4433
  chanel: "string"
3915
4434
  });
4435
+ const ComfyManagerAPIPack_ark = (0, arktype.type)({
4436
+ title: arktype.type.string.as(),
4437
+ "id?": "string",
4438
+ "files?": "string[]",
4439
+ "repository?": "string",
4440
+ "version?": "string",
4441
+ "state?": "string",
4442
+ "update-state?": "string"
4443
+ });
4444
+ const ComfyManagerAPIPackList_ark = (0, arktype.type)({
4445
+ channel: "string",
4446
+ node_packs: arktype.type.Record("string", ComfyManagerAPIPack_ark)
4447
+ });
3916
4448
  //#endregion
3917
4449
  //#region src/host/ComfyManager.ts
4450
+ /** 🔶 NAMING DISCLAIMER: I call a "custom node package" => "PLUGIN" */
4451
+ const MANAGER_TIMING = {
4452
+ pollMs: 1e3,
4453
+ installTimeoutMs: 60 * 6e4
4454
+ };
4455
+ /** what each generation does NOT serve (history means the `?ui_id=` form) */
4456
+ const NOT_SERVED = {
4457
+ v3: [
4458
+ "/manager/queue/batch",
4459
+ "/manager/queue/task",
4460
+ "/manager/queue/history"
4461
+ ],
4462
+ "v4-legacy-ui": [
4463
+ "/manager/queue/install",
4464
+ "/manager/queue/task",
4465
+ "/manager/queue/history",
4466
+ "/manager/terminal"
4467
+ ],
4468
+ v4: [
4469
+ "/customnode/getlist",
4470
+ "/externalmodel/getlist",
4471
+ "/manager/queue/install",
4472
+ "/manager/queue/batch",
4473
+ "/manager/terminal"
4474
+ ]
4475
+ };
4476
+ const QueueStatus_ark = (0, arktype.type)({
4477
+ is_processing: "boolean",
4478
+ "pending_count?": "number",
4479
+ "total_count?": "number",
4480
+ "done_count?": "number"
4481
+ });
4482
+ const TaskHistory_ark = (0, arktype.type)({ history: {
4483
+ "status?": {
4484
+ status_str: "string",
4485
+ "messages?": "string[]"
4486
+ },
4487
+ "result?": "string"
4488
+ } });
4489
+ const ModelFolders_ark = (0, arktype.type)("string[]");
4490
+ const errorText = (e) => e instanceof Error ? e.message : String(e);
3918
4491
  var ComfyManager = class {
3919
- constructor(host) {
4492
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3920
4493
  this.host = host;
3921
- this.fetchPluginsAndModels = async () => {
3922
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3923
- this.pluginList = _pluginList;
3924
- this.modelList = _modelList;
4494
+ this.timing = timing;
4495
+ this.mirror = mirror;
4496
+ this.clientId = `comfy-ts-${(0, nanoid.nanoid)(8)}`;
4497
+ this._api = null;
4498
+ this.api = () => {
4499
+ if (this._api == null) {
4500
+ const probe = this.probeApi();
4501
+ this._api = probe;
4502
+ probe.catch(() => {
4503
+ if (this._api === probe) this._api = null;
4504
+ });
4505
+ }
4506
+ return this._api;
4507
+ };
4508
+ this.probeApi = async () => {
4509
+ const v4 = await this.host.fetch("/v2/manager/version");
4510
+ if (v4.ok) {
4511
+ const version = (await v4.text()).trim();
4512
+ const ui = await this.host.fetch("/v2/manager/is_legacy_manager_ui");
4513
+ if (!ui.ok) {
4514
+ logError(`ComfyUI-Manager ${version}: GET /v2/manager/is_legacy_manager_ui → ${ui.status}, assuming the default ui`);
4515
+ return {
4516
+ generation: "v4",
4517
+ version
4518
+ };
4519
+ }
4520
+ const flag = await ui.json();
4521
+ return {
4522
+ generation: typeof flag === "object" && flag != null && "is_legacy_manager_ui" in flag && flag.is_legacy_manager_ui === true ? "v4-legacy-ui" : "v4",
4523
+ version
4524
+ };
4525
+ }
4526
+ const v3 = await this.host.fetch("/manager/version");
4527
+ if (v3.ok) return {
4528
+ generation: "v3",
4529
+ version: (await v3.text()).trim()
4530
+ };
4531
+ throw new Error(`🔴 no ComfyUI-Manager answers at ${this.host.getServerHostHTTP()} (GET /v2/manager/version → ${v4.status}, GET /manager/version → ${v3.status})`);
4532
+ };
4533
+ this.route = (api, route, query = "") => {
4534
+ if (NOT_SERVED[api.generation].includes(route)) throw new Error(`🔴 ComfyUI-Manager ${api.version} (${api.generation}) does not serve ${route}`);
4535
+ return `${api.generation === "v3" ? "" : "/v2"}${route}${query}`;
4536
+ };
4537
+ this.strategy = (api) => {
4538
+ switch (api.generation) {
4539
+ case "v3": return {
4540
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4541
+ fetchModels: () => this.listedModels(api),
4542
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, (body) => this.post(this.route(api, "/manager/queue/install"), body)),
4543
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4544
+ };
4545
+ case "v4-legacy-ui": return {
4546
+ fetchPlugins: (mode, skipUpdate) => this.listedPlugins(api, mode, skipUpdate),
4547
+ fetchModels: () => this.listedModels(api),
4548
+ enqueuePlugin: (plugin, uiId) => this.enqueueListedPlugin(api, plugin, uiId, async (body) => {
4549
+ const route = this.route(api, "/manager/queue/batch");
4550
+ const res = await this.post(route, { install: [body] });
4551
+ const failed = typeof res === "object" && res != null && "failed" in res ? res.failed : null;
4552
+ 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)`);
4553
+ }),
4554
+ settle: (what, _uiId, landed) => this.settleByDrain(api, what, landed)
4555
+ };
4556
+ case "v4": return {
4557
+ fetchPlugins: () => this.installedPluginView(api),
4558
+ fetchModels: () => this.installedModelView(),
4559
+ enqueuePlugin: (plugin, uiId) => this.enqueuePluginTask(api, plugin, uiId),
4560
+ settle: (what, uiId) => this.settleByHistory(api, what, uiId)
4561
+ };
4562
+ }
3925
4563
  };
3926
- this.configureLogging = (mi) => {
3927
- return this.fetchGetText(`/manager/terminal?mode=${mi}`);
4564
+ this.configureLogging = async (mi) => {
4565
+ const api = await this.api();
4566
+ const route = this.route(api, "/manager/terminal", `?mode=${mi}`);
4567
+ const response = await this.host.fetch(route);
4568
+ const text = await response.text();
4569
+ if (!response.ok) throw new Error(`🔴 GET ${route} → ${response.status} ${text}`);
4570
+ return text;
3928
4571
  };
3929
4572
  this.getModelInfoFinalFilePath = (mi) => {
3930
4573
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3931
4574
  };
3932
4575
  this.restartComfyUI = async () => {
4576
+ const api = await this.api();
4577
+ this._api = null;
4578
+ const route = this.route(api, "/manager/reboot");
3933
4579
  const refusals = [];
3934
4580
  for (const method of ["POST", "GET"]) {
3935
4581
  let response;
3936
4582
  try {
3937
- response = await this.host.fetch("/manager/reboot", { method });
4583
+ response = await this.host.fetch(route, { method });
3938
4584
  } catch {
3939
4585
  return;
3940
4586
  }
@@ -3942,31 +4588,42 @@ var ComfyManager = class {
3942
4588
  refusals.push(`${method} → ${response.status}`);
3943
4589
  if (response.status !== 404) break;
3944
4590
  }
3945
- throw new Error(`🔴 ${this.host.getServerHostHTTP()} refused to reboot (${refusals.join(", ")}) — ComfyUI-Manager is not installed there, or its reboot route moved again`);
4591
+ 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`);
4592
+ };
4593
+ this.fetchPluginsAndModels = async () => {
4594
+ const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
4595
+ this.pluginList = _pluginList;
4596
+ this.modelList = _modelList;
3946
4597
  };
3947
4598
  this.modelList = null;
3948
- this.fetchModels = () => {
3949
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4599
+ this.fetchModels = async () => {
4600
+ return this.strategy(await this.api()).fetchModels();
3950
4601
  };
3951
4602
  this.fetchLogs = () => {
3952
- return this.fetchGetJSON("/internal/logs");
4603
+ return this.getJSON("/internal/logs");
3953
4604
  };
3954
4605
  this.isModelInstalled = (name) => {
3955
4606
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3956
4607
  };
3957
4608
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3958
4609
  this.installModel = async (model) => {
4610
+ this.modelsBeeingInstalled.add(model.name);
3959
4611
  try {
3960
- this.modelsBeeingInstalled.add(model.name);
3961
- await this.fetchPost("/model/install", model);
3962
- this.modelsBeeingInstalled.delete(model.name);
3963
- logSuccess("Model installed");
3964
- return true;
3965
- } catch (exception) {
3966
- console.error(`Install failed: / ${exception}`);
3967
- logError("Model Installation Failed");
4612
+ return await this.runInstall(`model "${model.name}"`, {
4613
+ enqueue: async (api, uiId) => {
4614
+ const body = {
4615
+ ...model,
4616
+ ui_id: uiId,
4617
+ client_id: this.clientId
4618
+ };
4619
+ await this.post(this.route(api, "/manager/queue/install_model"), body);
4620
+ },
4621
+ landed: async (s) => {
4622
+ return (await s.fetchModels()).models.find((x) => x.filename === model.filename && x.save_path === model.save_path && x.base === model.base)?.installed === "True";
4623
+ }
4624
+ });
4625
+ } finally {
3968
4626
  this.modelsBeeingInstalled.delete(model.name);
3969
- return false;
3970
4627
  }
3971
4628
  };
3972
4629
  this.getModelStatus = (modelName) => {
@@ -3997,47 +4654,173 @@ var ComfyManager = class {
3997
4654
  })();
3998
4655
  };
3999
4656
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
4000
- try {
4001
- const skip_update = skipUpdate ? "&skip_update=true" : "";
4002
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4003
- } catch (exception) {
4004
- console.error(`node list retrieval failed: ${exception}`);
4005
- logError("node list retrieveal failed");
4006
- throw exception;
4007
- }
4657
+ return this.strategy(await this.api()).fetchPlugins(mode, skipUpdate);
4658
+ };
4659
+ this.installPlugin = async (plugin) => {
4660
+ return this.runInstall(`plugin "${plugin.title}"`, {
4661
+ enqueue: (api, uiId) => this.strategy(api).enqueuePlugin(plugin, uiId),
4662
+ landed: async (_s, api) => {
4663
+ const data = await this.installedData(api);
4664
+ return packIsInstalled(attributePacks(data.installed, data.mappings), plugin);
4665
+ }
4666
+ });
4667
+ };
4668
+ this.listedPlugins = async (api, mode, skipUpdate) => {
4669
+ const raw = await this.fetchPluginWire(api, mode, skipUpdate);
4670
+ if (!("node_packs" in raw)) return raw;
4671
+ const titleByRepo = /* @__PURE__ */ new Map();
4672
+ for (const p of this.mirror().plugins_byTitle.values()) for (const f of p.files) titleByRepo.set(repoPath(f), p.title);
4673
+ return {
4674
+ chanel: raw.channel,
4675
+ custom_nodes: Object.values(raw.node_packs).map((p) => {
4676
+ const repo = p.files?.[0];
4677
+ return {
4678
+ title: (repo != null ? titleByRepo.get(repoPath(repo)) : void 0) ?? p.title,
4679
+ installed: p.state !== "enabled" ? "False" : p["update-state"] === "true" ? "Update" : "True"
4680
+ };
4681
+ })
4682
+ };
4683
+ };
4684
+ this.fetchPluginWire = async (api, mode, skipUpdate) => {
4685
+ const query = `?mode=${mode}${skipUpdate ? "&skip_update=true" : ""}`;
4686
+ const json = await this.getJSON(this.route(api, "/customnode/getlist", query));
4687
+ if (typeof json === "object" && json != null && "custom_nodes" in json) return softValidate(ComfyManagerAPIPluginList_ark, json);
4688
+ return softValidate(ComfyManagerAPIPackList_ark, json);
4689
+ };
4690
+ this.listedModels = async (api) => {
4691
+ return this.getJSON(this.route(api, "/externalmodel/getlist", "?mode=cache"), ComfyManagerAPIModelList_ark);
4692
+ };
4693
+ this.installedData = async (api) => {
4694
+ 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)]);
4695
+ return {
4696
+ installed,
4697
+ mappings
4698
+ };
4699
+ };
4700
+ this.installedPluginView = async (api) => {
4701
+ const view = buildPluginView({
4702
+ mirror: this.mirror(),
4703
+ ...await this.installedData(api)
4704
+ });
4705
+ 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`);
4706
+ return view.list;
4707
+ };
4708
+ this.installedModelView = async () => {
4709
+ const models = this.mirror().modelRows;
4710
+ const registered = new Set(await this.getValid("/models", ModelFolders_ark));
4711
+ const folders = [...modelFolders(models)].filter((f) => registered.has(f));
4712
+ const lists = await Promise.all(folders.map(async (f) => [f, await this.getValid(`/models/${encodeURIComponent(f)}`, ModelFolders_ark)]));
4713
+ return buildModelView({
4714
+ models,
4715
+ files: new Map(lists)
4716
+ });
4717
+ };
4718
+ this.enqueueListedPlugin = async (api, plugin, uiId, send) => {
4719
+ const url = plugin.files[0] ?? plugin.reference;
4720
+ const list = await this.fetchPluginWire(api, "cache", true);
4721
+ if (!("node_packs" in list)) throw new Error(`ComfyUI-Manager ${api.version} lists packs in the pre-V3 shape and has no queue install`);
4722
+ const found = Object.entries(list.node_packs).find(([, p]) => (p.files ?? []).some((f) => repoPath(f) === repoPath(url)));
4723
+ if (found == null) throw new Error(`${url} is not in the Manager's own list (channel ${list.channel}), so it refuses to install it`);
4724
+ const [key, row] = found;
4725
+ await send({
4726
+ ...row,
4727
+ id: row.id ?? key,
4728
+ channel: list.channel,
4729
+ mode: "cache",
4730
+ ui_id: uiId,
4731
+ skip_post_install: false
4732
+ });
4733
+ };
4734
+ this.enqueuePluginTask = async (api, plugin, uiId) => {
4735
+ const url = plugin.files[0] ?? plugin.reference;
4736
+ const params = {
4737
+ id: repoPath(url).split("/").pop() ?? url,
4738
+ version: "nightly",
4739
+ selected_version: "nightly",
4740
+ repository: url,
4741
+ mode: "cache",
4742
+ channel: "default"
4743
+ };
4744
+ await this.post(this.route(api, "/manager/queue/task"), {
4745
+ ui_id: uiId,
4746
+ client_id: this.clientId,
4747
+ kind: "install",
4748
+ params
4749
+ });
4008
4750
  };
4009
- this.installPlugin = async (model) => {
4751
+ this.settleByHistory = async (api, what, uiId) => {
4752
+ const route = this.route(api, "/manager/queue/history", `?ui_id=${encodeURIComponent(uiId)}`);
4753
+ const entry = await this.waitFor(what, async () => {
4754
+ const status = (await this.getValid(route, TaskHistory_ark)).history.status;
4755
+ if (status == null) await this.restartIdleQueue(api);
4756
+ return status ?? null;
4757
+ });
4758
+ if (entry.status_str === "success" || entry.status_str === "skip") return;
4759
+ const messages = entry.messages ?? [];
4760
+ 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)" : "";
4761
+ throw new Error(`the Manager reports ${entry.status_str}: ${messages.join(" | ")}${gate}`);
4762
+ };
4763
+ this.restartIdleQueue = async (api) => {
4764
+ const status = await this.getValid(this.route(api, "/manager/queue/status"), QueueStatus_ark);
4765
+ if (status.is_processing) return "running";
4766
+ if ((status.pending_count ?? (status.total_count ?? 0) - (status.done_count ?? 0)) <= 0) return "drained";
4767
+ await this.post(this.route(api, "/manager/queue/start"));
4768
+ return "restarted";
4769
+ };
4770
+ this.settleByDrain = async (api, what, landed) => {
4771
+ await this.waitFor(what, async () => await this.restartIdleQueue(api) === "drained" ? true : null);
4772
+ 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`);
4773
+ };
4774
+ this.runInstall = async (what, p) => {
4010
4775
  try {
4011
- await this.fetchPost("/customnode/install", model);
4012
- console.log("✅ Custom Node installed");
4013
- logSuccess("Custom Node installed");
4776
+ const api = await this.api();
4777
+ const s = this.strategy(api);
4778
+ const uiId = (0, nanoid.nanoid)();
4779
+ await p.enqueue(api, uiId);
4780
+ await this.post(this.route(api, "/manager/queue/start"));
4781
+ await s.settle(what, uiId, () => p.landed(s, api));
4782
+ logSuccess(`${what} installed`);
4014
4783
  return true;
4015
4784
  } catch (exception) {
4016
- console.error(`Install failed: / ${exception}`);
4017
- logError("Custom Node Installation Failed");
4785
+ logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`);
4018
4786
  return false;
4019
4787
  }
4020
4788
  };
4021
- this.fetchPost = async (endpoint, body, validator) => {
4022
- const response = await this.host.fetch(endpoint, {
4789
+ this.waitFor = async (what, check) => {
4790
+ const deadline = Date.now() + this.timing.installTimeoutMs;
4791
+ for (;;) {
4792
+ const value = await check();
4793
+ if (value != null) return value;
4794
+ if (Date.now() >= deadline) throw new Error(`${what} still running after ${this.timing.installTimeoutMs} ms (manager.timing.installTimeoutMs)`);
4795
+ await new Promise((resolve) => setTimeout(resolve, this.timing.pollMs));
4796
+ }
4797
+ };
4798
+ this.post = async (route, body) => {
4799
+ const response = await this.host.fetch(route, {
4023
4800
  method: "POST",
4024
4801
  headers: { "Content-Type": "application/json" },
4025
- body: JSON.stringify(body)
4802
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4026
4803
  });
4027
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4028
- const status = await response.json();
4029
- if (validator) return softValidate(validator, status);
4030
- return status;
4031
- };
4032
- this.fetchGetJSON = async (endpoint, validator) => {
4033
- const response = await this.host.fetch(endpoint);
4034
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
4804
+ const text = await response.text();
4805
+ if (!response.ok) throw new Error(`POST ${route} → ${response.status} ${text}`.trim());
4806
+ if (text === "") return null;
4807
+ try {
4808
+ return JSON.parse(text);
4809
+ } catch {
4810
+ return text;
4811
+ }
4812
+ };
4813
+ this.getJSON = async (route, validator) => {
4814
+ const response = await this.host.fetch(route);
4815
+ if (!response.ok) throw new Error(`GET ${route} → ${response.status} ${await response.text()}`.trim());
4035
4816
  const jsonResult = await response.json();
4036
4817
  if (validator) return softValidate(validator, jsonResult);
4037
4818
  return jsonResult;
4038
4819
  };
4039
- this.fetchGetText = async (endopint) => {
4040
- return await (await this.host.fetch(endopint)).text();
4820
+ this.getValid = async (route, schema) => {
4821
+ const res = schema(await this.getJSON(route));
4822
+ if (res instanceof arktype.type.errors) throw new Error(`GET ${route}: ${res.summary}`);
4823
+ return res;
4041
4824
  };
4042
4825
  }
4043
4826
  get registry() {
@@ -6184,6 +6967,7 @@ var ComfyHost = class {
6184
6967
  this.onLogs = null;
6185
6968
  this.comfySessionId = "temp";
6186
6969
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
6970
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6187
6971
  this.status = null;
6188
6972
  this.lastWsMessageAt = null;
6189
6973
  this.base = parseHostBase(this.data);
@@ -6423,9 +7207,26 @@ var ComfyHost = class {
6423
7207
  }
6424
7208
  return;
6425
7209
  }
6426
- const msg_ = JSON.parse(String(e.data));
6427
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6428
- if (msg_.type === "crystools.monitor") return;
7210
+ let msg_ = JSON.parse(String(e.data));
7211
+ const rec = typeof msg_ === "object" && msg_ != null ? msg_ : null;
7212
+ const eventType = rec != null && "type" in rec && typeof rec.type === "string" ? rec.type : null;
7213
+ if (eventType != null && isIgnoredWsEventType(eventType)) return;
7214
+ if (eventType == null || !isRoutedWsEventType(eventType)) {
7215
+ const key = eventType ?? "<no type>";
7216
+ if (this._unknownWsEventTypes.has(key)) return;
7217
+ this._unknownWsEventTypes.add(key);
7218
+ console.error(`🔴 unknown ws event type ${JSON.stringify(key)} from host ${this.data.id}, ignored (reported once per connection)`);
7219
+ return;
7220
+ }
7221
+ if (eventType === "executing" && this.activePromptID != null && rec != null) {
7222
+ const data = Reflect.get(rec, "data");
7223
+ if (typeof data === "object" && data != null && !("prompt_id" in data)) msg_ = {
7224
+ type: eventType,
7225
+ data: {
7226
+ ...data,
7227
+ prompt_id: this.activePromptID
7228
+ }
7229
+ };
6429
7230
  }
6430
7231
  const res = WsMsg_ark(msg_);
6431
7232
  if (res instanceof arktype.type.errors) {
@@ -6439,7 +7240,11 @@ var ComfyHost = class {
6439
7240
  this.comfySessionId = msg.data.sid;
6440
7241
  this._sessionResolve?.();
6441
7242
  this._sessionResolve = null;
6442
- if (sidChanged) this.onSession?.(msg.data.sid);
7243
+ if (sidChanged) {
7244
+ this._unknownWsEventTypes.clear();
7245
+ this._unknownBinaryFrameTypes.clear();
7246
+ this.onSession?.(msg.data.sid);
7247
+ }
6443
7248
  }
6444
7249
  this.status = msg.data.status;
6445
7250
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6454,7 +7259,7 @@ var ComfyHost = class {
6454
7259
  this.routeOrBuffer(activePromptID, msg);
6455
7260
  return;
6456
7261
  }
6457
- 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") {
7262
+ 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") {
6458
7263
  this.routeOrBuffer(msg.data.prompt_id, msg);
6459
7264
  return;
6460
7265
  }
@@ -6466,8 +7271,6 @@ var ComfyHost = class {
6466
7271
  this.onLogs?.(msg.data);
6467
7272
  return;
6468
7273
  }
6469
- console.log("❌", "Unknown message:", msg);
6470
- logError("Unknown message type: " + JSON.stringify(msg.type));
6471
7274
  }
6472
7275
  };
6473
7276
  //#endregion
@@ -6796,6 +7599,7 @@ const _getKnownModels = (DB) => {
6796
7599
  }
6797
7600
  const knownModelList = canonical.concat(extraModels.models);
6798
7601
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7602
+ DB.modelRows = knownModelList;
6799
7603
  if (DB.opts.genTypes) {
6800
7604
  let out1 = "";
6801
7605
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6964,6 +7768,7 @@ var ComfyRegistry = class ComfyRegistry {
6964
7768
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6965
7769
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6966
7770
  this.knownModels = /* @__PURE__ */ new Map();
7771
+ this.modelRows = [];
6967
7772
  this.alterations = [];
6968
7773
  this.githubStats = /* @__PURE__ */ new Map();
6969
7774
  this.report = new ManagerParseReport();