comfy-ts 2.17.1 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/index.cjs +944 -165
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1154 -408
  5. package/dist/index.d.ts +1154 -408
  6. package/dist/index.js +944 -165
  7. package/dist/index.js.map +1 -1
  8. package/dist/{run-run-tg82jUIk.js → run-run-Wn7H72Zg.js} +2 -2
  9. package/dist/{run-run-tg82jUIk.js.map → run-run-Wn7H72Zg.js.map} +1 -1
  10. package/dist/{run-tui-Bw7BA75d.js → run-tui-VWSj1D_j.js} +2 -2
  11. package/dist/{run-tui-Bw7BA75d.js.map → run-tui-VWSj1D_j.js.map} +1 -1
  12. package/dist/serve-web.js +47 -47
  13. package/dist/{state-zTow5ucI.js → state-DgwWhZWb.js} +945 -166
  14. package/dist/state-DgwWhZWb.js.map +1 -0
  15. package/dist/web.d.ts +1172 -426
  16. package/dist/web.js +944 -165
  17. package/dist/web.js.map +1 -1
  18. package/examples/comfy-cloud/ace-step15-t2a.cflow.ts +163 -0
  19. package/examples/comfy-cloud/anima-t2i-base.cflow.ts +57 -0
  20. package/examples/comfy-cloud/boogu-t2i.cflow.ts +55 -0
  21. package/examples/comfy-cloud/chronoedit-i2i.cflow.ts +95 -0
  22. package/examples/comfy-cloud/ernie-t2i-base.cflow.ts +81 -0
  23. package/examples/comfy-cloud/flux1-t2i-krea.cflow.ts +63 -0
  24. package/examples/comfy-cloud/flux2-i2i-dev.cflow.ts +83 -0
  25. package/examples/comfy-cloud/flux2-t2i-dev.cflow.ts +60 -0
  26. package/examples/comfy-cloud/hidream-o1-i2i.cflow.ts +71 -0
  27. package/examples/comfy-cloud/hidream-o1-t2i.cflow.ts +62 -0
  28. package/examples/comfy-cloud/krea2-i2i.cflow.ts +78 -0
  29. package/examples/comfy-cloud/ltx2-i2v.cflow.ts +175 -0
  30. package/examples/comfy-cloud/ltx2-t2v.cflow.ts +143 -0
  31. package/examples/comfy-cloud/ltx23-i2v.cflow.ts +189 -0
  32. package/examples/comfy-cloud/ltx23-t2v.cflow.ts +151 -0
  33. package/examples/comfy-cloud/mage-flow-i2i-turbo.cflow.ts +72 -0
  34. package/examples/comfy-cloud/mage-flow-i2i.cflow.ts +74 -0
  35. package/examples/comfy-cloud/mage-flow-t2i-turbo.cflow.ts +60 -0
  36. package/examples/comfy-cloud/mage-flow-t2i.cflow.ts +60 -0
  37. package/examples/comfy-cloud/minimax-h3-t2i.cflow.ts +64 -0
  38. package/examples/comfy-cloud/netayume-t2i.cflow.ts +60 -0
  39. package/examples/comfy-cloud/qwen-image-i2i-2509.cflow.ts +75 -0
  40. package/examples/comfy-cloud/qwen-image-t2i-2512.cflow.ts +63 -0
  41. package/examples/comfy-cloud/sdk.d.ts +21683 -13737
  42. package/examples/comfy-cloud/stable-audio3-t2a.cflow.ts +96 -0
  43. package/examples/comfy-cloud/z-image-t2i-base.cflow.ts +54 -0
  44. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +1 -1
  45. package/package.json +2 -2
  46. package/src/graph/ComfyNode.ts +93 -12
  47. package/src/host/ComfyHost.ts +31 -10
  48. package/src/host/ComfyManager.ts +448 -62
  49. package/src/litegraph/CanonicalWorkflow.ts +3 -0
  50. package/src/litegraph/LiteGraphJSON.ts +2 -2
  51. package/src/litegraph/LiteGraphNodeInput.ts +2 -2
  52. package/src/litegraph/LiteGraphNodeOutput.ts +2 -2
  53. package/src/litegraph/convertFlowToLiteGraphJSON.ts +112 -37
  54. package/src/litegraph/expandSubgraphs.ts +14 -0
  55. package/src/litegraph/normalizeWorkflow.ts +1 -0
  56. package/src/manager/ComfyRegistry.ts +2 -0
  57. package/src/manager/generated/KnownComfyCustomNodeName.ts +6354 -1680
  58. package/src/manager/generated/KnownComfyPluginTitle.ts +718 -356
  59. package/src/manager/generated/KnownComfyPluginURL.ts +357 -181
  60. package/src/manager/generated/KnownModel_Base.ts +9 -5
  61. package/src/manager/generated/KnownModel_FileName.ts +135 -0
  62. package/src/manager/generated/KnownModel_Name.ts +135 -0
  63. package/src/manager/generated/KnownModel_SavePath.ts +16 -14
  64. package/src/manager/generated/KnownModel_Type.ts +15 -13
  65. package/src/manager/installedView.ts +176 -0
  66. package/src/manager/json/custom-node-list.json +4018 -2248
  67. package/src/manager/json/extension-node-map.json +8903 -2964
  68. package/src/manager/json/github-stats.json +10796 -10036
  69. package/src/manager/json/model-list.json +298 -1
  70. package/src/manager/loaders/step4_model-list-loader.ts +1 -0
  71. package/src/manager/types/ComfyManagerAPIModelList.ts +3 -0
  72. package/src/manager/types/ComfyManagerAPIPluginList.ts +19 -0
  73. package/src/runner/ComfyExecution.ts +4 -1
  74. package/src/runner/ComfyWsApi.ts +82 -15
  75. package/src/sdk-generator/ComfySchema.ts +10 -1
  76. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +4 -1
  77. package/src/sdk-generator/comfyui-sdk-codegen.ts +61 -20
  78. package/src/sdk-generator/inputWidgetKind.ts +19 -4
  79. package/src/sdk-generator/litegraphToApiRequestPayload.ts +141 -33
  80. package/dist/state-zTow5ucI.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -134,7 +134,7 @@ function createNodeStorage() {
134
134
  }
135
135
  //#endregion
136
136
  //#region package.json
137
- var version = "2.17.1";
137
+ var version = "2.18.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,44 +1913,115 @@ const convertFlowToLiteGraphJSON = (graph) => {
1737
1913
  const convertNodeToLiteGraphNode = (ctx, node) => {
1738
1914
  const inputs = [];
1739
1915
  const widgets_values = [];
1740
- const pushLinked = (name, type, link, shape) => {
1916
+ const pushLinked = (name, type, link, extra = {}) => {
1741
1917
  const nodeUidNumber = bang(ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber, `link target node "${link[0]}" not found in graph`);
1742
- const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type);
1743
- inputs.push(shape == null ? {
1918
+ const input = {
1744
1919
  name,
1745
1920
  type,
1746
- link: linkId
1747
- } : {
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({
1748
2001
  name,
1749
- type,
1750
- shape,
1751
- link: linkId
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
1752
2013
  });
1753
2014
  };
1754
2015
  for (const ipt of node.$schema.inputs) {
1755
2016
  const kind = classifySchemaInput(ipt);
1756
- if (kind.kind === "dynamic-container") {
1757
- const type = containerInstanceSlotType(ipt.opts) ?? "*";
1758
- for (const instance of kind.instanceNames) {
1759
- const name = `${ipt.nameInComfy}.${instance}`;
1760
- const value = node.json.inputs[name];
1761
- if (value == null) continue;
1762
- const raw = node.serializeValue(name, value);
1763
- if (!_isLink(raw)) throw new Error(`🔴 [toWorkflowJson] ${node.$schema.nameInComfy}#${node.uid} "${name}" holds a literal; an autogrow instance is a link slot in the editor`);
1764
- pushLinked(name, type, raw, 7);
1765
- }
1766
- continue;
1767
- }
1768
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy]);
1769
- if (_isLink(raw)) pushLinked(ipt.nameInComfy, ipt.typeName, raw);
1770
- else if (kind.kind === "widget") {
1771
- widgets_values.push(...kind.prefixValues, raw);
1772
- const phantoms = kind.consumes - 1 - kind.prefixValues.length;
1773
- for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts));
1774
- } else inputs.push({
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({
1775
2020
  name: ipt.nameInComfy,
1776
- type: ipt.typeName,
1777
- link: null
2021
+ kind,
2022
+ typeName: ipt.typeName,
2023
+ opts: ipt.opts,
2024
+ value
1778
2025
  });
1779
2026
  }
1780
2027
  const outputs = node.$schema.outputs.map((i, ix) => ({
@@ -1960,11 +2207,6 @@ const getPngMetadataFromUint8Array = (pngData) => {
1960
2207
  return resultSuccess(txt_chunks);
1961
2208
  };
1962
2209
  //#endregion
1963
- //#region src/utils/exhaust.ts
1964
- function exhaust(x) {
1965
- return x;
1966
- }
1967
- //#endregion
1968
2210
  //#region src/utils/sha1.ts
1969
2211
  function sha1Hex(data) {
1970
2212
  const ml = data.length;
@@ -2102,16 +2344,17 @@ const types$1 = (0, arktype.scope)({
2102
2344
  },
2103
2345
  _WsMsgExecutedData: {
2104
2346
  node: "ComfyNodeID",
2105
- output: {
2106
- "previews?": [{ filepath: "string" }, "[]"],
2107
- "images?": "ComfyImageInfo[]",
2108
- "audio?": "ComfyImageInfo[]",
2109
- "video?": "ComfyImageInfo[]",
2110
- "gifs?": "ComfyImageInfo[]",
2111
- "text?": "unknown[]"
2112
- },
2347
+ output: "_WsMsgExecutedOutput | null",
2113
2348
  prompt_id: "PromptID"
2114
2349
  },
2350
+ _WsMsgExecutedOutput: {
2351
+ "previews?": [{ filepath: "string" }, "[]"],
2352
+ "images?": "ComfyImageInfo[]",
2353
+ "audio?": "ComfyImageInfo[]",
2354
+ "video?": "ComfyImageInfo[]",
2355
+ "gifs?": "ComfyImageInfo[]",
2356
+ "text?": "unknown[]"
2357
+ },
2115
2358
  WsMsgExecuted: {
2116
2359
  type: "'executed'",
2117
2360
  data: "_WsMsgExecutedData"
@@ -2133,12 +2376,22 @@ const types$1 = (0, arktype.scope)({
2133
2376
  exception_type: "string",
2134
2377
  traceback: "string[]",
2135
2378
  current_inputs: "Record<string, unknown>",
2136
- current_outputs: "Record<string, unknown>"
2379
+ current_outputs: "ComfyNodeID[]"
2137
2380
  },
2138
2381
  WsMsgExecutionError: {
2139
2382
  type: "'execution_error'",
2140
2383
  data: "_WsMsgExecutionErrorData"
2141
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
+ },
2142
2395
  WSMsgManagerFeedbackData: { data: "string" },
2143
2396
  WSMsgManagerFeedback: {
2144
2397
  type: "'manager-terminal-feedback'",
@@ -2168,11 +2421,51 @@ const types$1 = (0, arktype.scope)({
2168
2421
  type: "'progress_state'",
2169
2422
  data: "_WsMsgProgressStateData"
2170
2423
  },
2171
- PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionSuccess",
2424
+ PromptRelated_WsMsg: "WsMsgExecutionStart | WsMsgExecutionCached | WsMsgExecuting | WsMsgProgress | WsMsgProgressState | WsMsgExecuted | WsMsgExecutionError | WsMsgExecutionInterrupted | WsMsgExecutionSuccess",
2172
2425
  WsMsg: "WsMsgStatus | WSMsgManagerFeedback | WsMsgLogs | PromptRelated_WsMsg"
2173
2426
  }).export();
2174
2427
  const PromptInfo_ark = (0, arktype.type)({ prompt_id: types$1.PromptID }).as();
2175
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);
2176
2469
  const ComfyImageInfo_ark = types$1.ComfyImageInfo;
2177
2470
  const WsMsgLogsData_ark = types$1._WsMsgLogsData;
2178
2471
  //#endregion
@@ -2462,6 +2755,10 @@ var ComfyExecution = class {
2462
2755
  else if (msg.type === "progress") graph.onProgress(msg);
2463
2756
  else if (msg.type === "progress_state") {} else if (msg.type === "executed") this.onExecuted(msg);
2464
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
+ });
2465
2762
  else if (msg.type === "execution_success") return void this.onExecutionSuccess(msg);
2466
2763
  else {
2467
2764
  console.log(`🔴 UNEXPECTED MESSAGE:`, msg);
@@ -3375,6 +3672,15 @@ const dynamicComboUnion = (p) => {
3375
3672
  return `{ ${[`${p.nameEscaped}${p.keyOptional ? "?" : ""}: ${JSON.stringify(opt.key)}`, ...fields].join("; ")} }`;
3376
3673
  }).join(" | ")})`;
3377
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
+ };
3378
3684
  /**
3379
3685
  * convert a host id to the namespace name it gets inside the global `Comfy` namespace
3380
3686
  * e.g. 'windows-1' -> 'Windows1', 'my_cloud.instance' -> 'MyCloudInstance'
@@ -3423,6 +3729,8 @@ function codegenSDK(opts) {
3423
3729
  b.deindent();
3424
3730
  p(`// #endregion`);
3425
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 = [];
3426
3734
  p(`interface IN {`);
3427
3735
  b.indent();
3428
3736
  for (const n of nodes) {
@@ -3430,23 +3738,37 @@ function codegenSDK(opts) {
3430
3738
  const comboSuffixes = [];
3431
3739
  for (const i of n.inputs) {
3432
3740
  const kind = classifySchemaInput(i);
3433
- if (kind.kind === "dynamic-container") {
3434
- const instType = containerInstanceSlotType(i.opts);
3435
- if (instType != null) kind.instanceNames.forEach((instName, ix) => {
3436
- const opt = ix >= kind.requiredCount ? "?" : "";
3437
- p(` ${escapeJSKey(`${i.nameInComfy}.${instName}`)}${opt}: Accepts[${JSON.stringify(instType)}]`);
3438
- });
3439
- continue;
3440
- }
3441
- if (kind.kind === "dynamic-combo") {
3442
- const optsDyn = typeof i.opts === "string" ? null : i.opts;
3443
- comboSuffixes.push(dynamicComboUnion({
3444
- name: i.nameInComfy,
3445
- nameEscaped: i.nameInComfyEscaped,
3446
- options: kind.options,
3447
- keyOptional: optsDyn?.default !== void 0 || !i.required
3448
- }));
3449
- continue;
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:
3450
3772
  }
3451
3773
  const opts_ = typeof i.opts === "string" ? null : i.opts;
3452
3774
  let type = `Accepts[${JSON.stringify(i.typeName)}]`;
@@ -3469,6 +3791,15 @@ function codegenSDK(opts) {
3469
3791
  b.deindent();
3470
3792
  p("}");
3471
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
+ }
3472
3803
  p(`interface OUT {`);
3473
3804
  b.indent();
3474
3805
  for (const n of nodes) {
@@ -3781,9 +4112,13 @@ var ComfySchema = class {
3781
4112
  if (widgetKind?.kind === "dynamic-combo") {
3782
4113
  for (const opt of widgetKind.options) for (const entry of opt.inputs) if (typeof entry.type === "string") this.knownSlotTypes.add(asComfyNodeSlotTypeName(entry.type));
3783
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;
3784
4119
  node.inputs.push({
3785
4120
  slotName: inputSlotName,
3786
- required: ipt.required && !isAutogrowContainer,
4121
+ required,
3787
4122
  nameInComfy: inputNameInComfy,
3788
4123
  nameInComfyEscaped: escapeJSKey(inputNameInComfy),
3789
4124
  typeName: inputTypeName,
@@ -3859,7 +4194,12 @@ const types = (0, arktype.scope)({
3859
4194
  ComfyInputSpecAlt1: ["ComfyInputType", "ComfyInputOpts"],
3860
4195
  ComfyInputSpecAlt2: ["ComfyInputType"],
3861
4196
  ComfyInputSpecAlt3: (0, arktype.type)([arktype.type.null]),
3862
- ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3`,
4197
+ ComfyInputSpecAlt4: [
4198
+ "ComfyInputType",
4199
+ "ComfyInputOpts",
4200
+ "unknown"
4201
+ ],
4202
+ ComfyInputSpec: `ComfyInputSpecAlt1 | ComfyInputSpecAlt2 | ComfyInputSpecAlt3 | ComfyInputSpecAlt4`,
3863
4203
  ComfyInputType: `string | ComfyEnumDef`,
3864
4204
  ComfyInputHiddenEntry_broken1: "\"CHOOSE\"[][]",
3865
4205
  ComfyInputHiddenEntry_broken2: arktype.type.Record("string", arktype.type.unknown),
@@ -3925,10 +4265,163 @@ function readableStringify(obj, maxLevel = 3, level = 0) {
3925
4265
  return result;
3926
4266
  }
3927
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
3928
4418
  //#region src/manager/types/ComfyManagerAPIModelList.ts
3929
4419
  const ComfyManagerAPIModelList_ark = (0, arktype.type)({ models: (0, arktype.type)({
3930
4420
  name: arktype.type.string.as(),
3931
- installed: `'False' | 'True' | 'Update'`
4421
+ installed: `'False' | 'True' | 'Update'`,
4422
+ "filename?": "string",
4423
+ "save_path?": "string",
4424
+ "base?": "string"
3932
4425
  }).array() });
3933
4426
  //#endregion
3934
4427
  //#region src/manager/types/ComfyManagerAPIPluginList.ts
@@ -3939,28 +4432,155 @@ const ComfyManagerAPIPluginList_ark = (0, arktype.type)({
3939
4432
  }).array(),
3940
4433
  chanel: "string"
3941
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
+ });
3942
4448
  //#endregion
3943
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);
3944
4491
  var ComfyManager = class {
3945
- constructor(host) {
4492
+ constructor(host, timing = { ...MANAGER_TIMING }, mirror = () => comfyts.registry) {
3946
4493
  this.host = host;
3947
- this.fetchPluginsAndModels = async () => {
3948
- const [_pluginList, _modelList] = await Promise.all([this.fetchPlugins(), this.fetchModels()]);
3949
- this.pluginList = _pluginList;
3950
- this.modelList = _modelList;
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
+ }
3951
4563
  };
3952
- this.configureLogging = (mi) => {
3953
- 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;
3954
4571
  };
3955
4572
  this.getModelInfoFinalFilePath = (mi) => {
3956
4573
  return comfyts.registry.getModelInfoFinalFilePath(mi);
3957
4574
  };
3958
4575
  this.restartComfyUI = async () => {
4576
+ const api = await this.api();
4577
+ this._api = null;
4578
+ const route = this.route(api, "/manager/reboot");
3959
4579
  const refusals = [];
3960
4580
  for (const method of ["POST", "GET"]) {
3961
4581
  let response;
3962
4582
  try {
3963
- response = await this.host.fetch("/manager/reboot", { method });
4583
+ response = await this.host.fetch(route, { method });
3964
4584
  } catch {
3965
4585
  return;
3966
4586
  }
@@ -3968,31 +4588,42 @@ var ComfyManager = class {
3968
4588
  refusals.push(`${method} → ${response.status}`);
3969
4589
  if (response.status !== 404) break;
3970
4590
  }
3971
- 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;
3972
4597
  };
3973
4598
  this.modelList = null;
3974
- this.fetchModels = () => {
3975
- return this.fetchGetJSON("/externalmodel/getlist?mode=cache", ComfyManagerAPIModelList_ark);
4599
+ this.fetchModels = async () => {
4600
+ return this.strategy(await this.api()).fetchModels();
3976
4601
  };
3977
4602
  this.fetchLogs = () => {
3978
- return this.fetchGetJSON("/internal/logs");
4603
+ return this.getJSON("/internal/logs");
3979
4604
  };
3980
4605
  this.isModelInstalled = (name) => {
3981
4606
  return this.modelList?.models.some((x) => x.name === name && x.installed === "True") ?? false;
3982
4607
  };
3983
4608
  this.modelsBeeingInstalled = /* @__PURE__ */ new Set();
3984
4609
  this.installModel = async (model) => {
4610
+ this.modelsBeeingInstalled.add(model.name);
3985
4611
  try {
3986
- this.modelsBeeingInstalled.add(model.name);
3987
- await this.fetchPost("/model/install", model);
3988
- this.modelsBeeingInstalled.delete(model.name);
3989
- logSuccess("Model installed");
3990
- return true;
3991
- } catch (exception) {
3992
- console.error(`Install failed: / ${exception}`);
3993
- logError("Model Installation Failed");
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 {
3994
4626
  this.modelsBeeingInstalled.delete(model.name);
3995
- return false;
3996
4627
  }
3997
4628
  };
3998
4629
  this.getModelStatus = (modelName) => {
@@ -4023,47 +4654,173 @@ var ComfyManager = class {
4023
4654
  })();
4024
4655
  };
4025
4656
  this.fetchPlugins = async (mode = "cache", skipUpdate = true) => {
4026
- try {
4027
- const skip_update = skipUpdate ? "&skip_update=true" : "";
4028
- return await this.fetchGetJSON(`/customnode/getlist?mode=${mode}${skip_update}`, ComfyManagerAPIPluginList_ark);
4029
- } catch (exception) {
4030
- console.error(`node list retrieval failed: ${exception}`);
4031
- logError("node list retrieveal failed");
4032
- throw exception;
4033
- }
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
+ });
4034
4750
  };
4035
- 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) => {
4036
4775
  try {
4037
- await this.fetchPost("/customnode/install", model);
4038
- console.log("✅ Custom Node installed");
4039
- 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`);
4040
4783
  return true;
4041
4784
  } catch (exception) {
4042
- console.error(`Install failed: / ${exception}`);
4043
- logError("Custom Node Installation Failed");
4785
+ logError(`${what}: install failed on ${this.host.getServerHostHTTP()}: ${errorText(exception)}`);
4044
4786
  return false;
4045
4787
  }
4046
4788
  };
4047
- this.fetchPost = async (endpoint, body, validator) => {
4048
- 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, {
4049
4800
  method: "POST",
4050
4801
  headers: { "Content-Type": "application/json" },
4051
- body: JSON.stringify(body)
4802
+ body: body === void 0 ? void 0 : JSON.stringify(body)
4052
4803
  });
4053
- if (!response.ok) throw new Error(`POST ${endpoint} failed: ${response.status} ${response.statusText}`);
4054
- const status = await response.json();
4055
- if (validator) return softValidate(validator, status);
4056
- return status;
4057
- };
4058
- this.fetchGetJSON = async (endpoint, validator) => {
4059
- const response = await this.host.fetch(endpoint);
4060
- if (!response.ok) throw new Error(`GET ${endpoint} failed: ${response.status} ${response.statusText}`);
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());
4061
4816
  const jsonResult = await response.json();
4062
4817
  if (validator) return softValidate(validator, jsonResult);
4063
4818
  return jsonResult;
4064
4819
  };
4065
- this.fetchGetText = async (endopint) => {
4066
- 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;
4067
4824
  };
4068
4825
  }
4069
4826
  get registry() {
@@ -6210,6 +6967,7 @@ var ComfyHost = class {
6210
6967
  this.onLogs = null;
6211
6968
  this.comfySessionId = "temp";
6212
6969
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
6970
+ this._unknownWsEventTypes = /* @__PURE__ */ new Set();
6213
6971
  this.status = null;
6214
6972
  this.lastWsMessageAt = null;
6215
6973
  this.base = parseHostBase(this.data);
@@ -6449,9 +7207,26 @@ var ComfyHost = class {
6449
7207
  }
6450
7208
  return;
6451
7209
  }
6452
- const msg_ = JSON.parse(String(e.data));
6453
- if (typeof msg_ === "object" && msg_ != null && "type" in msg_) {
6454
- if (msg_.type === "crystools.monitor") return;
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
+ };
6455
7230
  }
6456
7231
  const res = WsMsg_ark(msg_);
6457
7232
  if (res instanceof arktype.type.errors) {
@@ -6465,7 +7240,11 @@ var ComfyHost = class {
6465
7240
  this.comfySessionId = msg.data.sid;
6466
7241
  this._sessionResolve?.();
6467
7242
  this._sessionResolve = null;
6468
- 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
+ }
6469
7248
  }
6470
7249
  this.status = msg.data.status;
6471
7250
  this.onStatus?.({ queueRemaining: msg.data.status?.exec_info?.queue_remaining ?? 0 });
@@ -6480,7 +7259,7 @@ var ComfyHost = class {
6480
7259
  this.routeOrBuffer(activePromptID, msg);
6481
7260
  return;
6482
7261
  }
6483
- if (msg.type === "execution_start" || msg.type === "execution_cached" || msg.type === "execution_error" || msg.type === "execution_success" || msg.type === "executing" || msg.type === "executed" || msg.type === "progress_state") {
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") {
6484
7263
  this.routeOrBuffer(msg.data.prompt_id, msg);
6485
7264
  return;
6486
7265
  }
@@ -6492,8 +7271,6 @@ var ComfyHost = class {
6492
7271
  this.onLogs?.(msg.data);
6493
7272
  return;
6494
7273
  }
6495
- console.log("❌", "Unknown message:", msg);
6496
- logError("Unknown message type: " + JSON.stringify(msg.type));
6497
7274
  }
6498
7275
  };
6499
7276
  //#endregion
@@ -6822,6 +7599,7 @@ const _getKnownModels = (DB) => {
6822
7599
  }
6823
7600
  const knownModelList = canonical.concat(extraModels.models);
6824
7601
  for (const modelInfo of knownModelList) DB.knownModels.set(modelInfo.name, modelInfo);
7602
+ DB.modelRows = knownModelList;
6825
7603
  if (DB.opts.genTypes) {
6826
7604
  let out1 = "";
6827
7605
  const uniqCategories = knownModelList.reduce((acc, cur) => {
@@ -6990,6 +7768,7 @@ var ComfyRegistry = class ComfyRegistry {
6990
7768
  this.plugins_byNodeKey = /* @__PURE__ */ new Map();
6991
7769
  this.customNodes_byPluginName = /* @__PURE__ */ new Map();
6992
7770
  this.knownModels = /* @__PURE__ */ new Map();
7771
+ this.modelRows = [];
6993
7772
  this.alterations = [];
6994
7773
  this.githubStats = /* @__PURE__ */ new Map();
6995
7774
  this.report = new ManagerParseReport();