comfy-ts 2.21.0 → 2.23.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 (104) hide show
  1. package/dist/{ServeApp-ByMobrWW.js → ServeApp-DolRCMHj.js} +183 -14
  2. package/dist/ServeApp-DolRCMHj.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-B5sMqNia.js → exampleAssets-Duneoq6r.js} +331 -42
  5. package/dist/exampleAssets-Duneoq6r.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-BNZgYIww.js → findDefinedWorkflow-DjoJA8y7.js} +2 -2
  7. package/dist/{findDefinedWorkflow-BNZgYIww.js.map → findDefinedWorkflow-DjoJA8y7.js.map} +1 -1
  8. package/dist/index.cjs +381 -34
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +201 -24
  11. package/dist/index.d.ts +201 -24
  12. package/dist/index.js +380 -35
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-CuBSygku.js → run-run-Cr0L9lCK.js} +5 -5
  15. package/dist/{run-run-CuBSygku.js.map → run-run-Cr0L9lCK.js.map} +1 -1
  16. package/dist/{run-serve-COk_G0Qz.js → run-serve---qA7o_m.js} +4 -4
  17. package/dist/{run-serve-COk_G0Qz.js.map → run-serve---qA7o_m.js.map} +1 -1
  18. package/dist/{run-tui-CB6i_x2y.js → run-tui-DxXiWo5J.js} +4 -4
  19. package/dist/{run-tui-CB6i_x2y.js.map → run-tui-DxXiWo5J.js.map} +1 -1
  20. package/dist/{schemaDrift-CHDVYlaj.js → schemaDrift-BTxdABHi.js} +36 -2
  21. package/dist/schemaDrift-BTxdABHi.js.map +1 -0
  22. package/dist/serve-web.js +207 -47
  23. package/dist/web.d.ts +201 -24
  24. package/dist/web.js +380 -35
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +2 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +722 -0
  29. package/examples/depth-explorer/serve.ts +140 -0
  30. package/examples/depth-explorer/thumbs/bae.webp +0 -0
  31. package/examples/depth-explorer/thumbs/da3-mono-large.webp +0 -0
  32. package/examples/depth-explorer/thumbs/dav1-vitl.webp +0 -0
  33. package/examples/depth-explorer/thumbs/dav2-vitl.webp +0 -0
  34. package/examples/depth-explorer/thumbs/dsine.webp +0 -0
  35. package/examples/depth-explorer/thumbs/iid-albedo.webp +0 -0
  36. package/examples/depth-explorer/thumbs/iid-metalness.webp +0 -0
  37. package/examples/depth-explorer/thumbs/iid-roughness.webp +0 -0
  38. package/examples/depth-explorer/thumbs/iid-shading.webp +0 -0
  39. package/examples/depth-explorer/thumbs/iid-specular.webp +0 -0
  40. package/examples/depth-explorer/thumbs/leres.webp +0 -0
  41. package/examples/depth-explorer/thumbs/lotus-depth.webp +0 -0
  42. package/examples/depth-explorer/thumbs/marigold2-albedo.webp +0 -0
  43. package/examples/depth-explorer/thumbs/marigold2-depth.webp +0 -0
  44. package/examples/depth-explorer/thumbs/marigold2-normal.webp +0 -0
  45. package/examples/depth-explorer/thumbs/metric3d-depth.webp +0 -0
  46. package/examples/depth-explorer/thumbs/metric3d-normal.webp +0 -0
  47. package/examples/depth-explorer/thumbs/midas-normal.webp +0 -0
  48. package/examples/depth-explorer/thumbs/midas.webp +0 -0
  49. package/examples/depth-explorer/thumbs/moge2-depth.webp +0 -0
  50. package/examples/depth-explorer/thumbs/moge2-normal.webp +0 -0
  51. package/examples/depth-explorer/thumbs/zoe-da.webp +0 -0
  52. package/examples/depth-explorer/thumbs/zoe.webp +0 -0
  53. package/examples/depth-explorer/web/App.tsx +457 -0
  54. package/examples/depth-explorer/web/gl.ts +202 -0
  55. package/examples/depth-explorer/web/index.html +14 -0
  56. package/examples/depth-explorer/web/main.tsx +19 -0
  57. package/examples/depth-explorer/web/pixels.ts +86 -0
  58. package/examples/depth-explorer/web/state.ts +329 -0
  59. package/examples/depth-explorer/web/styles.css +366 -0
  60. package/examples/depth-explorer/web/tsconfig.json +16 -0
  61. package/examples/rvion/17-relight.cflow.ts +110 -0
  62. package/examples/rvion/18-world.cflow.ts +101 -0
  63. package/examples/world-explorer/serve.ts +171 -0
  64. package/examples/world-explorer/web/index.html +14 -0
  65. package/examples/world-explorer/web/main.tsx +200 -0
  66. package/examples/world-explorer/web/state.ts +212 -0
  67. package/examples/world-explorer/web/styles.css +131 -0
  68. package/examples/world-explorer/web/thumb.ts +21 -0
  69. package/examples/world-explorer/web/tsconfig.json +11 -0
  70. package/examples/world-explorer/world-state.ts +40 -0
  71. package/package.json +6 -7
  72. package/src/cli/serve/ServeApp.ts +106 -6
  73. package/src/cli/serve/describeVar.ts +12 -1
  74. package/src/cli/serve/resultHistory.ts +28 -5
  75. package/src/cli/serve/thumbs.ts +77 -0
  76. package/src/cli/serve/web/api.ts +9 -1
  77. package/src/cli/serve/web/components/Gallery.tsx +26 -1
  78. package/src/cli/serve/web/components/controls/BasicControls.tsx +14 -17
  79. package/src/cli/serve/web/components/controls/MediaControl.tsx +62 -9
  80. package/src/cli/serve/web/components/controls/RichSelect.tsx +262 -0
  81. package/src/cli/serve/web/state/RunSt.poll.test.ts +4 -1
  82. package/src/cli/serve/web/state/choiceButtons.ts +26 -2
  83. package/src/cli/serve/web/styles.ts +42 -0
  84. package/src/cli/serve/web/widgets/OutputWidgets.tsx +19 -0
  85. package/src/cli/serve/web/widgets/RelightSt.ts +113 -0
  86. package/src/cli/serve/web/widgets/RelightWidget.tsx +305 -0
  87. package/src/cli/serve/web/widgets/relightGl.ts +305 -0
  88. package/src/cli/serve/web/widgets/widgetStyles.ts +19 -0
  89. package/src/coreExports.ts +10 -0
  90. package/src/graph/ComfyNode.ts +12 -2
  91. package/src/host/ComfyHost.ts +153 -2
  92. package/src/host/ResilientWebsocket.ts +10 -0
  93. package/src/manager/script-update-manager.bun.ts +0 -7
  94. package/src/runner/ComfyExecution.ts +165 -20
  95. package/src/runner/ComfyWsApi.ts +2 -0
  96. package/src/runner/historyReplay.ts +53 -0
  97. package/src/runner/outputs3d.ts +18 -0
  98. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  99. package/src/vars/ComfyVars.ts +32 -2
  100. package/src/vars/DefinedWorkflow.ts +4 -0
  101. package/src/vars/outputWidgets.ts +47 -0
  102. package/dist/ServeApp-ByMobrWW.js.map +0 -1
  103. package/dist/exampleAssets-B5sMqNia.js.map +0 -1
  104. package/dist/schemaDrift-CHDVYlaj.js.map +0 -1
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { a as readableStringify, c as writeHostFile, l as renderHttpBase, n as comfyTsPackageDir, r as ComfyTS, s as ComfySchema } from "./exampleAssets-B5sMqNia.js";
3
- import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-CHDVYlaj.js";
2
+ import { a as readableStringify, c as renderHttpBase, n as comfyTsPackageDir, o as ComfySchema, r as ComfyTS, s as writeHostFile } from "./exampleAssets-Duneoq6r.js";
3
+ import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-BTxdABHi.js";
4
4
  import { spawn } from "node:child_process";
5
5
  import { constants, homedir } from "node:os";
6
6
  import { fileURLToPath } from "node:url";
@@ -554,14 +554,14 @@ async function main() {
554
554
  }
555
555
  armHopChild();
556
556
  if (cmd === "run") {
557
- const { runRun } = await import("./run-run-CuBSygku.js");
557
+ const { runRun } = await import("./run-run-Cr0L9lCK.js");
558
558
  return runRun(rest);
559
559
  }
560
560
  if (cmd === "serve") {
561
- const { runServe } = await import("./run-serve-COk_G0Qz.js");
561
+ const { runServe } = await import("./run-serve---qA7o_m.js");
562
562
  return runServe(rest);
563
563
  }
564
- const { runTui } = await import("./run-tui-CB6i_x2y.js");
564
+ const { runTui } = await import("./run-tui-DxXiWo5J.js");
565
565
  return runTui(rest);
566
566
  }
567
567
  console.log(HELP);
@@ -1,4 +1,4 @@
1
- import { X as ansi, a as DefinedWorkflow, at as isRecord$1, ct as resolveComfyStorage, dt as logInfo, ft as logSuccess, ht as extractErrorMessage, it as hashArrayBuffer, lt as isQuiet, mt as sha1HexOfString, n as diffSchemas, nt as isVideoFilename, ot as bang, pt as statelessRegex, rt as mediaMime, st as getComfyStorage, t as MODEL_LISTS, ut as logError } from "./schemaDrift-CHDVYlaj.js";
1
+ import { X as ansi, _t as sha1HexOfString, a as DefinedWorkflow, at as mediaMime, ct as isRecord$1, dt as resolveComfyStorage, et as model3dMime, ft as isQuiet, gt as statelessRegex, ht as logSuccess, it as isVideoFilename, lt as bang, mt as logInfo, n as diffSchemas, ot as hashArrayBuffer, pt as logError, rt as extensionOf, st as importSharp, t as MODEL_LISTS, ut as getComfyStorage, vt as extractErrorMessage } from "./schemaDrift-BTxdABHi.js";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { basename, dirname, join } from "pathe";
@@ -695,7 +695,12 @@ function codegenSDK(opts) {
695
695
  p(`INVALID_null: any`);
696
696
  p("");
697
697
  p("// named slot types: everything an input of that type accepts");
698
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
698
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
699
+ for (const t of slotTypes) {
700
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
701
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
702
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
703
+ }
699
704
  p("");
700
705
  p("// enum unions: literal values or an output carrying one");
701
706
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -1003,7 +1008,7 @@ var ComfySchema = class {
1003
1008
  };
1004
1009
  //#endregion
1005
1010
  //#region package.json
1006
- var version = "2.21.0";
1011
+ var version = "2.23.0";
1007
1012
  //#endregion
1008
1013
  //#region src/litegraph/LiteGraphLinkID.ts
1009
1014
  const asLiteGraphLinkID = (id) => id;
@@ -2495,13 +2500,14 @@ var ComfyNode = class ComfyNode {
2495
2500
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
2496
2501
  }
2497
2502
  _getOutputForTypeOrCrash(type) {
2498
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2503
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2504
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
2499
2505
  const val = this.outputs[i.outKey];
2500
2506
  if (val instanceof ComfyNodeOutput) return val;
2501
2507
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2502
2508
  }
2503
2509
  _getOutputForTypeOrNull(type) {
2504
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2510
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2505
2511
  if (i == null) return null;
2506
2512
  const val = this.outputs[i.outKey];
2507
2513
  if (val == null) return null;
@@ -2509,6 +2515,11 @@ var ComfyNode = class ComfyNode {
2509
2515
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2510
2516
  }
2511
2517
  };
2518
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
2519
+ function slotTypeAccepts(inputType, outputType) {
2520
+ if (inputType === outputType) return true;
2521
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
2522
+ }
2512
2523
  //#endregion
2513
2524
  //#region src/host/ComfyWorkflowBuilder.ts
2514
2525
  var ComfyWorkflowBuilder = class {
@@ -2798,19 +2809,6 @@ const runTimestamp = (d) => {
2798
2809
  return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
2799
2810
  };
2800
2811
  //#endregion
2801
- //#region src/utils/lazySharp.ts
2802
- let cached = null;
2803
- async function importSharp(reason) {
2804
- if (cached != null) return cached;
2805
- const specifier = "sharp";
2806
- try {
2807
- cached = (await import(specifier)).default;
2808
- return cached;
2809
- } catch (e) {
2810
- throw new Error(`sharp is unavailable — ${reason} is node-only (browser builds get raw bytes instead): ${extractErrorMessage(e)}`, { cause: e });
2811
- }
2812
- }
2813
- //#endregion
2814
2812
  //#region src/types/index.ts
2815
2813
  const asAbsolutePath = (path) => path;
2816
2814
  const resultSuccess = (value) => ({
@@ -2911,6 +2909,7 @@ const types$1 = scope({
2911
2909
  "audio?": "ComfyImageInfo[]",
2912
2910
  "video?": "ComfyImageInfo[]",
2913
2911
  "gifs?": "ComfyImageInfo[]",
2912
+ "3d?": "ComfyImageInfo[]",
2914
2913
  "text?": "unknown[]"
2915
2914
  },
2916
2915
  WsMsgExecuted: {
@@ -3205,6 +3204,66 @@ var MediaImage = class MediaImage {
3205
3204
  }
3206
3205
  };
3207
3206
  //#endregion
3207
+ //#region src/runner/historyReplay.ts
3208
+ const END_TYPES = /* @__PURE__ */ new Set([
3209
+ "execution_success",
3210
+ "execution_error",
3211
+ "execution_interrupted"
3212
+ ]);
3213
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
3214
+ * entry for it: queued, running, or lost */
3215
+ function historyReplay(json, promptId) {
3216
+ const entry = field(json, promptId);
3217
+ if (entry == null) return null;
3218
+ const problems = [];
3219
+ const valid = (raw) => {
3220
+ const res = types$1.PromptRelated_WsMsg(raw);
3221
+ if (!(res instanceof type.errors)) return res;
3222
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
3223
+ return null;
3224
+ };
3225
+ const executed = [];
3226
+ const outputs = field(entry, "outputs");
3227
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
3228
+ const msg = valid({
3229
+ type: "executed",
3230
+ data: {
3231
+ node,
3232
+ output,
3233
+ prompt_id: promptId
3234
+ }
3235
+ });
3236
+ if (msg != null) executed.push(msg);
3237
+ }
3238
+ const status = field(entry, "status");
3239
+ const list = field(status, "messages");
3240
+ let end = null;
3241
+ for (const m of Array.isArray(list) ? list : []) {
3242
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
3243
+ end = valid({
3244
+ type: m[0],
3245
+ data: m[1]
3246
+ });
3247
+ }
3248
+ const statusStr = field(status, "status_str");
3249
+ if (end == null && (status == null || statusStr === "success")) end = valid({
3250
+ type: "execution_success",
3251
+ data: {
3252
+ prompt_id: promptId,
3253
+ timestamp: Date.now()
3254
+ }
3255
+ });
3256
+ return {
3257
+ executed,
3258
+ end,
3259
+ problems
3260
+ };
3261
+ }
3262
+ function field(x, key) {
3263
+ if (typeof x !== "object" || x == null) return null;
3264
+ return Reflect.get(x, key) ?? null;
3265
+ }
3266
+ //#endregion
3208
3267
  //#region src/runner/ComfyExecution.ts
3209
3268
  /** paths claimed by in-flight retrievals: two same-second runs on a
3210
3269
  * counter-resetting cloud host compute the same name before either writes.
@@ -3231,6 +3290,9 @@ var ComfyExecution = class {
3231
3290
  this._resolve = resolve;
3232
3291
  });
3233
3292
  this.onPromptRelatedMessage = (msg) => {
3293
+ if (this.ended) return;
3294
+ this.heard();
3295
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
3234
3296
  const graph = this.workflow;
3235
3297
  if (msg.type === "binary_preview_frame") {
3236
3298
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -3261,6 +3323,7 @@ var ComfyExecution = class {
3261
3323
  this.workflow.onExecuting(msg);
3262
3324
  };
3263
3325
  this.onExecutionSuccess = async (_msg) => {
3326
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
3264
3327
  await Promise.all(this.pendingPromises);
3265
3328
  return this._finish({ status: "Success" });
3266
3329
  };
@@ -3274,6 +3337,7 @@ var ComfyExecution = class {
3274
3337
  };
3275
3338
  this.onExecuted = (msg) => {
3276
3339
  const promptNodeID = msg.data.node;
3340
+ this.heardExecuted.add(promptNodeID);
3277
3341
  for (const entry of msg.data.output?.text ?? []) {
3278
3342
  if (typeof entry !== "string") continue;
3279
3343
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -3289,7 +3353,7 @@ var ComfyExecution = class {
3289
3353
  ...out?.video ?? [],
3290
3354
  ...out?.gifs ?? []
3291
3355
  ].filter((f) => f.type !== "input");
3292
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
3356
+ for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile(video, promptNodeID, mediaMime(video.filename)).then((o) => void this.videos.push(o), (e) => {
3293
3357
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
3294
3358
  this.videoErrors.push({
3295
3359
  video,
@@ -3304,35 +3368,114 @@ var ComfyExecution = class {
3304
3368
  error: e
3305
3369
  });
3306
3370
  }));
3307
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
3371
+ for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile(audio, promptNodeID, mediaMime(audio.filename)).then((o) => void this.audios.push(o), (e) => {
3308
3372
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
3309
3373
  this.audioErrors.push({
3310
3374
  audio,
3311
3375
  error: e
3312
3376
  });
3313
3377
  }));
3378
+ for (const model3d of (out?.["3d"] ?? []).filter((f) => f.type !== "input")) this.pendingPromises.push(this.retrieveFile(model3d, promptNodeID, model3dMime(model3d.filename)).then((o) => void this.models3d.push({
3379
+ ...o,
3380
+ format: extensionOf(o.filename)
3381
+ }), (e) => {
3382
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
3383
+ this.models3dErrors.push({
3384
+ model3d,
3385
+ error: e
3386
+ });
3387
+ }));
3314
3388
  };
3315
3389
  this.pendingPromises = [];
3390
+ this.ended = false;
3391
+ this.heardExecuted = /* @__PURE__ */ new Set();
3392
+ this.mayHaveMissedEvents = false;
3393
+ this.historyRetry = {
3394
+ tries: 5,
3395
+ ms: 400
3396
+ };
3397
+ this.retrieveMissedOutputs = async () => {
3398
+ const id = this.data.id;
3399
+ for (let i = 0; i < this.historyRetry.tries; i++) {
3400
+ if (this.host.reconcileOff != null) return;
3401
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
3402
+ try {
3403
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
3404
+ if (replay == null) continue;
3405
+ return this.replayUnheardOutputs(replay);
3406
+ } catch (e) {
3407
+ if (this.host.noteReconcileFailure(e)) return;
3408
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
3409
+ }
3410
+ }
3411
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
3412
+ };
3413
+ this.lastHeardAt = Date.now();
3414
+ this.reconciling = false;
3415
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
3416
+ this.reconcile = async (queued) => {
3417
+ const id = this.data.id;
3418
+ const hostId = this.host.data.id;
3419
+ try {
3420
+ if (this.ended || queued?.has(id) === true) return "waiting";
3421
+ let replay;
3422
+ try {
3423
+ replay = historyReplay(await this.host.fetchHistory(id), id);
3424
+ } catch (e) {
3425
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
3426
+ return "waiting";
3427
+ }
3428
+ if (this.ended) return "waiting";
3429
+ if (replay == null) {
3430
+ if (queued == null) return "waiting";
3431
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
3432
+ logError(`run ${id}: ${reason}; the run fails`);
3433
+ this.ended = true;
3434
+ await this._finish({
3435
+ status: "Failure",
3436
+ error: null,
3437
+ reason
3438
+ });
3439
+ return "lost";
3440
+ }
3441
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3442
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3443
+ this.replayUnheardOutputs(replay);
3444
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3445
+ if (replay.end != null) {
3446
+ this.onPromptRelatedMessage(replay.end);
3447
+ return "history";
3448
+ }
3449
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3450
+ logError(`run ${id}: ${reason}; the run fails`);
3451
+ this.ended = true;
3452
+ await this._finish({
3453
+ status: "Failure",
3454
+ error: null,
3455
+ reason
3456
+ });
3457
+ return "history";
3458
+ } finally {
3459
+ this.reconciling = false;
3460
+ }
3461
+ };
3316
3462
  this.audioErrors = [];
3317
3463
  this.audios = [];
3318
3464
  this.videoErrors = [];
3319
3465
  this.videos = [];
3320
- this.retrieveFile = async (kind, info, promptNodeID) => {
3466
+ this.models3dErrors = [];
3467
+ this.models3d = [];
3468
+ this.retrieveFile = async (info, promptNodeID, mime) => {
3321
3469
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
3322
3470
  const bytes = new Uint8Array(await response.arrayBuffer());
3323
- const mime = mediaMime(info.filename);
3324
- const list = kind === "audio" ? this.audios : this.videos;
3325
3471
  const sf = this.save;
3326
- if (sf == null) {
3327
- list.push({
3328
- nodeId: promptNodeID,
3329
- filename: info.filename,
3330
- mime,
3331
- bytes,
3332
- absPath: null
3333
- });
3334
- return;
3335
- }
3472
+ if (sf == null) return {
3473
+ nodeId: promptNodeID,
3474
+ filename: info.filename,
3475
+ mime,
3476
+ bytes,
3477
+ absPath: null
3478
+ };
3336
3479
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
3337
3480
  const written = await this.encodeAndWrite({
3338
3481
  bytes,
@@ -3344,13 +3487,13 @@ var ComfyExecution = class {
3344
3487
  subfolder: info.subfolder,
3345
3488
  filename: info.filename
3346
3489
  });
3347
- list.push({
3490
+ return {
3348
3491
  nodeId: promptNodeID,
3349
3492
  filename: info.filename,
3350
3493
  mime,
3351
3494
  bytes,
3352
3495
  absPath: written.path
3353
- });
3496
+ };
3354
3497
  };
3355
3498
  this.imageErrors = [];
3356
3499
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -3428,6 +3571,7 @@ var ComfyExecution = class {
3428
3571
  };
3429
3572
  };
3430
3573
  this.onWsImageOutput = (p) => {
3574
+ this.heard();
3431
3575
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
3432
3576
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
3433
3577
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3490,7 +3634,7 @@ var ComfyExecution = class {
3490
3634
  this.onProgress = init.onProgress ?? null;
3491
3635
  this.onPreview = init.onPreview ?? null;
3492
3636
  this.logProgress = init.logProgress ?? false;
3493
- this.host.executions.set(data.id, this);
3637
+ this.host.trackExecution(this);
3494
3638
  this.onCreate();
3495
3639
  }
3496
3640
  get progress() {
@@ -3526,6 +3670,7 @@ var ComfyExecution = class {
3526
3670
  const outputs = [`${this.images.length} image(s)`];
3527
3671
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3528
3672
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3673
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3529
3674
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3530
3675
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3531
3676
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3554,6 +3699,24 @@ var ComfyExecution = class {
3554
3699
  get status() {
3555
3700
  return this.data.status ?? "New";
3556
3701
  }
3702
+ replayUnheardOutputs(replay) {
3703
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3704
+ }
3705
+ heard() {
3706
+ this.lastHeardAt = Date.now();
3707
+ }
3708
+ logReconcileOnce(msg) {
3709
+ if (this.loggedReconcileProblems.has(msg)) return;
3710
+ this.loggedReconcileProblems.add(msg);
3711
+ logError(`run ${this.data.id}: ${msg}`);
3712
+ }
3713
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3714
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3715
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3716
+ beginReconcile(why) {
3717
+ this.reconciling = true;
3718
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3719
+ }
3557
3720
  /** accumulate an output on the prompt; tags from node metadata ride along */
3558
3721
  pushImage(img, promptNodeID) {
3559
3722
  const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
@@ -3572,6 +3735,7 @@ var ComfyExecution = class {
3572
3735
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3573
3736
  * to onWsImageOutput before they get here) */
3574
3737
  onPreviewFrame(p) {
3738
+ this.heard();
3575
3739
  const listener = this.onPreview;
3576
3740
  if (listener == null) return;
3577
3741
  const current = this.workflow.currentExecutingNode;
@@ -3593,6 +3757,7 @@ var ComfyExecution = class {
3593
3757
  }
3594
3758
  /** @internal a live-text frame for one node */
3595
3759
  onProgressText(p) {
3760
+ this.heard();
3596
3761
  this.progressTexts.set(p.nodeId, p.text);
3597
3762
  this.progressText = p.text;
3598
3763
  this.emitProgress();
@@ -4852,6 +5017,12 @@ var ResilientWebSocketClient = class {
4852
5017
  }
4853
5018
  }, ms);
4854
5019
  }
5020
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5021
+ reconnect() {
5022
+ if (this.permanentlyClosed || this.currentWS == null) return;
5023
+ this.addInfo("closing the socket to reconnect");
5024
+ this.currentWS.close();
5025
+ }
4855
5026
  /** close and stop reconnecting (lets a script exit cleanly) */
4856
5027
  disconnectPermanently() {
4857
5028
  this.permanentlyClosed = true;
@@ -4873,6 +5044,7 @@ var ResilientWebSocketClient = class {
4873
5044
  }
4874
5045
  async connect() {
4875
5046
  this.isOpen = false;
5047
+ this.url = this.options.url();
4876
5048
  const prevWS = this.currentWS;
4877
5049
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
4878
5050
  this.stopHeartbeat();
@@ -4942,10 +5114,17 @@ var ResilientWebSocketClient = class {
4942
5114
  };
4943
5115
  //#endregion
4944
5116
  //#region src/host/ComfyHost.ts
4945
- /** the host never came up within ConnectOptions.timeoutMs */
4946
- var ComfyHostUnreachableError = class extends Error {
5117
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
5118
+ var HostRouteUnusableError = class extends Error {
4947
5119
  constructor(..._args) {
4948
5120
  super(..._args);
5121
+ this.name = "HostRouteUnusableError";
5122
+ }
5123
+ };
5124
+ /** the host never came up within ConnectOptions.timeoutMs */
5125
+ var ComfyHostUnreachableError = class extends Error {
5126
+ constructor(..._args2) {
5127
+ super(..._args2);
4949
5128
  this.name = "ComfyHostUnreachableError";
4950
5129
  }
4951
5130
  };
@@ -5118,6 +5297,7 @@ var ComfyHost = class {
5118
5297
  this._connectTimer = null;
5119
5298
  this.disconnect = () => {
5120
5299
  this.clearConnectTimer();
5300
+ this.stopWatchdog();
5121
5301
  this.ws?.disconnectPermanently();
5122
5302
  this.ws = null;
5123
5303
  this._ready = null;
@@ -5137,6 +5317,50 @@ var ComfyHost = class {
5137
5317
  });
5138
5318
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
5139
5319
  };
5320
+ this.fetchReconcileJSON_ = async (route) => {
5321
+ const res = await this.fetch(route);
5322
+ const contentType = res.headers.get("content-type") ?? "";
5323
+ if (res.ok && contentType.includes("json")) return res.json();
5324
+ res.body?.cancel();
5325
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
5326
+ };
5327
+ this.fetchHistory = (promptId) => {
5328
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
5329
+ };
5330
+ this.fetchQueuedPromptIds = async () => {
5331
+ const json = await this.fetchReconcileJSON_("/queue");
5332
+ const ids = /* @__PURE__ */ new Set();
5333
+ for (const key of ["queue_running", "queue_pending"]) {
5334
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
5335
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
5336
+ for (const item of list) {
5337
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
5338
+ ids.add(item[1]);
5339
+ }
5340
+ }
5341
+ return ids;
5342
+ };
5343
+ this.reconcileOff = null;
5344
+ this.fetchQueuedPromptIdsOrNull = async () => {
5345
+ try {
5346
+ return await this.fetchQueuedPromptIds();
5347
+ } catch (e) {
5348
+ if (this.noteReconcileFailure(e)) return null;
5349
+ const msg = extractErrorMessage(e);
5350
+ if (!this._loggedQueueProblems.has(msg)) {
5351
+ this._loggedQueueProblems.add(msg);
5352
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
5353
+ }
5354
+ return null;
5355
+ }
5356
+ };
5357
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
5358
+ this.runSilenceMs = 1e3;
5359
+ this.runSilenceMaxMs = 3e4;
5360
+ this._silenceWaitMs = null;
5361
+ this._lastCheckAt = 0;
5362
+ this._checking = false;
5363
+ this._watchdog = null;
5140
5364
  this.clearQueue = () => {
5141
5365
  return this.postJSON_("/queue", { clear: true });
5142
5366
  };
@@ -5266,6 +5490,7 @@ var ComfyHost = class {
5266
5490
  this.comfySessionId = "temp";
5267
5491
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
5268
5492
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
5493
+ this._socketIsNew = false;
5269
5494
  this.status = null;
5270
5495
  this.lastWsMessageAt = null;
5271
5496
  /** folder where file related to the host config will be cached */
@@ -5371,6 +5596,8 @@ var ComfyHost = class {
5371
5596
  this.ws = new ResilientWebSocketClient({
5372
5597
  onConnectOrReconnect: async () => {
5373
5598
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
5599
+ this._socketIsNew = true;
5600
+ this.reconcileRuns([...this.executions.values()], "reconnect");
5374
5601
  if (this.shouldUseSchemaCache()) try {
5375
5602
  await this.loadSchemaFromCache();
5376
5603
  await this.waitForSession();
@@ -5384,7 +5611,7 @@ var ComfyHost = class {
5384
5611
  this.markReady();
5385
5612
  },
5386
5613
  onMessage: (e) => this.onMessage(e),
5387
- url: () => this.getWSUrl(),
5614
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
5388
5615
  headers: () => this.authHeaders(),
5389
5616
  onTransportDead: (e) => this.markFailed(e),
5390
5617
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -5426,6 +5653,65 @@ var ComfyHost = class {
5426
5653
  });
5427
5654
  return this._schemaFromCache;
5428
5655
  }
5656
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
5657
+ * stop for good, said once), false for a passing failure the caller reports */
5658
+ noteReconcileFailure(e) {
5659
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
5660
+ if (this.reconcileOff == null) {
5661
+ this.reconcileOff = e.message;
5662
+ this.stopWatchdog();
5663
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
5664
+ }
5665
+ return true;
5666
+ }
5667
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
5668
+ trackExecution(execution) {
5669
+ this.executions.set(execution.data.id, execution);
5670
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
5671
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
5672
+ this._watchdog.unref?.();
5673
+ }
5674
+ stopWatchdog() {
5675
+ if (this._watchdog != null) clearInterval(this._watchdog);
5676
+ this._watchdog = null;
5677
+ }
5678
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
5679
+ * quiet node: ask. A run queued behind a talking host is never asked about */
5680
+ watchdogTick() {
5681
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
5682
+ if (this._checking) return;
5683
+ const now = Date.now();
5684
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
5685
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
5686
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
5687
+ if (due.length === 0) return;
5688
+ this._checking = true;
5689
+ this.reconcileRuns(due, "silence").finally(() => {
5690
+ this._checking = false;
5691
+ this._lastCheckAt = Date.now();
5692
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
5693
+ });
5694
+ }
5695
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
5696
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
5697
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
5698
+ * the new socket of the same session. A clean close lets the server end that handler first */
5699
+ async reconcileRuns(runs, why) {
5700
+ if (this.reconcileOff != null) return;
5701
+ const todo = runs.filter((r) => !r.reconciling);
5702
+ if (todo.length === 0) return;
5703
+ for (const r of todo) r.beginReconcile(why);
5704
+ const queued = await this.fetchQueuedPromptIdsOrNull();
5705
+ if (this.reconcileOff != null) {
5706
+ for (const r of todo) r.reconciling = false;
5707
+ return;
5708
+ }
5709
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
5710
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
5711
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
5712
+ this.ws.reconnect();
5713
+ }
5714
+ }
5429
5715
  /** method to either execute or buffer the incoming message */
5430
5716
  routeOrBuffer(prompt_id, msg) {
5431
5717
  this.activePromptID = prompt_id;
@@ -5487,6 +5773,7 @@ var ComfyHost = class {
5487
5773
  }
5488
5774
  onMessage(e) {
5489
5775
  this.lastWsMessageAt = Date.now();
5776
+ this._silenceWaitMs = null;
5490
5777
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
5491
5778
  if (e.data instanceof ArrayBuffer) {
5492
5779
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -5538,10 +5825,12 @@ var ComfyHost = class {
5538
5825
  if (msg.type === "status") {
5539
5826
  if (msg.data.sid) {
5540
5827
  const sidChanged = msg.data.sid !== this.comfySessionId;
5828
+ const socketIsNew = this._socketIsNew;
5829
+ this._socketIsNew = false;
5541
5830
  this.comfySessionId = msg.data.sid;
5542
5831
  this._sessionResolve?.();
5543
5832
  this._sessionResolve = null;
5544
- if (sidChanged) {
5833
+ if (sidChanged || socketIsNew) {
5545
5834
  this._unknownWsEventTypes.clear();
5546
5835
  this._unknownBinaryFrameTypes.clear();
5547
5836
  this.onSession?.(msg.data.sid);
@@ -6316,6 +6605,6 @@ function comfyTsPackageDir(moduleUrl = import.meta.url) {
6316
6605
  throw new Error(`[comfy-ts] no package.json found walking up from ${fileURLToPath(moduleUrl)}`);
6317
6606
  }
6318
6607
  //#endregion
6319
- export { readableStringify as a, writeHostFile as c, settingsPathFor as i, renderHttpBase as l, comfyTsPackageDir as n, importSharp as o, ComfyTS as r, ComfySchema as s, bundledExamplesDir as t };
6608
+ export { readableStringify as a, renderHttpBase as c, settingsPathFor as i, comfyTsPackageDir as n, ComfySchema as o, ComfyTS as r, writeHostFile as s, bundledExamplesDir as t };
6320
6609
 
6321
- //# sourceMappingURL=exampleAssets-B5sMqNia.js.map
6610
+ //# sourceMappingURL=exampleAssets-Duneoq6r.js.map