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/index.js CHANGED
@@ -110,7 +110,7 @@ function createNodeStorage() {
110
110
  }
111
111
  //#endregion
112
112
  //#region package.json
113
- var version = "2.21.0";
113
+ var version = "2.23.0";
114
114
  //#endregion
115
115
  //#region src/litegraph/LiteGraphLinkID.ts
116
116
  const asLiteGraphLinkID = (id) => id;
@@ -1865,13 +1865,14 @@ var ComfyNode = class ComfyNode {
1865
1865
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1866
1866
  }
1867
1867
  _getOutputForTypeOrCrash(type) {
1868
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1868
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1869
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
1869
1870
  const val = this.outputs[i.outKey];
1870
1871
  if (val instanceof ComfyNodeOutput) return val;
1871
1872
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1872
1873
  }
1873
1874
  _getOutputForTypeOrNull(type) {
1874
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1875
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1875
1876
  if (i == null) return null;
1876
1877
  const val = this.outputs[i.outKey];
1877
1878
  if (val == null) return null;
@@ -1879,6 +1880,11 @@ var ComfyNode = class ComfyNode {
1879
1880
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1880
1881
  }
1881
1882
  };
1883
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
1884
+ function slotTypeAccepts(inputType, outputType) {
1885
+ if (inputType === outputType) return true;
1886
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
1887
+ }
1882
1888
  //#endregion
1883
1889
  //#region src/host/ComfyWorkflowBuilder.ts
1884
1890
  var ComfyWorkflowBuilder = class {
@@ -2381,6 +2387,7 @@ const types$1 = scope({
2381
2387
  "audio?": "ComfyImageInfo[]",
2382
2388
  "video?": "ComfyImageInfo[]",
2383
2389
  "gifs?": "ComfyImageInfo[]",
2390
+ "3d?": "ComfyImageInfo[]",
2384
2391
  "text?": "unknown[]"
2385
2392
  },
2386
2393
  WsMsgExecuted: {
@@ -2742,6 +2749,88 @@ function mediaMime(filename) {
2742
2749
  return MIMES[extensionOf(filename)] ?? "application/octet-stream";
2743
2750
  }
2744
2751
  //#endregion
2752
+ //#region src/runner/outputs3d.ts
2753
+ /** ply and spz have no registered mime: the `x-` forms are what three.js and the splat viewers accept */
2754
+ const MODEL_3D_MIMES = {
2755
+ glb: "model/gltf-binary",
2756
+ gltf: "model/gltf+json",
2757
+ ply: "model/x-ply",
2758
+ spz: "model/x-spz",
2759
+ obj: "model/obj",
2760
+ stl: "model/stl"
2761
+ };
2762
+ function model3dMime(filename) {
2763
+ return MODEL_3D_MIMES[extensionOf(filename)] ?? "application/octet-stream";
2764
+ }
2765
+ //#endregion
2766
+ //#region src/runner/historyReplay.ts
2767
+ const END_TYPES = /* @__PURE__ */ new Set([
2768
+ "execution_success",
2769
+ "execution_error",
2770
+ "execution_interrupted"
2771
+ ]);
2772
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
2773
+ * entry for it: queued, running, or lost */
2774
+ function historyReplay(json, promptId) {
2775
+ const entry = field(json, promptId);
2776
+ if (entry == null) return null;
2777
+ const problems = [];
2778
+ const valid = (raw) => {
2779
+ const res = types$1.PromptRelated_WsMsg(raw);
2780
+ if (!(res instanceof type.errors)) return res;
2781
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
2782
+ return null;
2783
+ };
2784
+ const executed = [];
2785
+ const outputs = field(entry, "outputs");
2786
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
2787
+ const msg = valid({
2788
+ type: "executed",
2789
+ data: {
2790
+ node,
2791
+ output,
2792
+ prompt_id: promptId
2793
+ }
2794
+ });
2795
+ if (msg != null) executed.push(msg);
2796
+ }
2797
+ const status = field(entry, "status");
2798
+ const list = field(status, "messages");
2799
+ let end = null;
2800
+ for (const m of Array.isArray(list) ? list : []) {
2801
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
2802
+ end = valid({
2803
+ type: m[0],
2804
+ data: m[1]
2805
+ });
2806
+ }
2807
+ const statusStr = field(status, "status_str");
2808
+ if (end == null && (status == null || statusStr === "success")) end = valid({
2809
+ type: "execution_success",
2810
+ data: {
2811
+ prompt_id: promptId,
2812
+ timestamp: Date.now()
2813
+ }
2814
+ });
2815
+ return {
2816
+ executed,
2817
+ end,
2818
+ problems
2819
+ };
2820
+ }
2821
+ function field(x, key) {
2822
+ if (typeof x !== "object" || x == null) return null;
2823
+ return Reflect.get(x, key) ?? null;
2824
+ }
2825
+ //#endregion
2826
+ //#region src/utils/log.ts
2827
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
2828
+ const logInfo = (msg) => {
2829
+ if (!isQuiet()) console.log(msg);
2830
+ };
2831
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
2832
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
2833
+ //#endregion
2745
2834
  //#region src/runner/ComfyExecution.ts
2746
2835
  /** paths claimed by in-flight retrievals: two same-second runs on a
2747
2836
  * counter-resetting cloud host compute the same name before either writes.
@@ -2768,6 +2857,9 @@ var ComfyExecution = class {
2768
2857
  this._resolve = resolve;
2769
2858
  });
2770
2859
  this.onPromptRelatedMessage = (msg) => {
2860
+ if (this.ended) return;
2861
+ this.heard();
2862
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
2771
2863
  const graph = this.workflow;
2772
2864
  if (msg.type === "binary_preview_frame") {
2773
2865
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -2798,6 +2890,7 @@ var ComfyExecution = class {
2798
2890
  this.workflow.onExecuting(msg);
2799
2891
  };
2800
2892
  this.onExecutionSuccess = async (_msg) => {
2893
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
2801
2894
  await Promise.all(this.pendingPromises);
2802
2895
  return this._finish({ status: "Success" });
2803
2896
  };
@@ -2811,6 +2904,7 @@ var ComfyExecution = class {
2811
2904
  };
2812
2905
  this.onExecuted = (msg) => {
2813
2906
  const promptNodeID = msg.data.node;
2907
+ this.heardExecuted.add(promptNodeID);
2814
2908
  for (const entry of msg.data.output?.text ?? []) {
2815
2909
  if (typeof entry !== "string") continue;
2816
2910
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -2826,7 +2920,7 @@ var ComfyExecution = class {
2826
2920
  ...out?.video ?? [],
2827
2921
  ...out?.gifs ?? []
2828
2922
  ].filter((f) => f.type !== "input");
2829
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
2923
+ 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) => {
2830
2924
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
2831
2925
  this.videoErrors.push({
2832
2926
  video,
@@ -2841,35 +2935,114 @@ var ComfyExecution = class {
2841
2935
  error: e
2842
2936
  });
2843
2937
  }));
2844
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
2938
+ 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) => {
2845
2939
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
2846
2940
  this.audioErrors.push({
2847
2941
  audio,
2848
2942
  error: e
2849
2943
  });
2850
2944
  }));
2945
+ 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({
2946
+ ...o,
2947
+ format: extensionOf(o.filename)
2948
+ }), (e) => {
2949
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
2950
+ this.models3dErrors.push({
2951
+ model3d,
2952
+ error: e
2953
+ });
2954
+ }));
2851
2955
  };
2852
2956
  this.pendingPromises = [];
2957
+ this.ended = false;
2958
+ this.heardExecuted = /* @__PURE__ */ new Set();
2959
+ this.mayHaveMissedEvents = false;
2960
+ this.historyRetry = {
2961
+ tries: 5,
2962
+ ms: 400
2963
+ };
2964
+ this.retrieveMissedOutputs = async () => {
2965
+ const id = this.data.id;
2966
+ for (let i = 0; i < this.historyRetry.tries; i++) {
2967
+ if (this.host.reconcileOff != null) return;
2968
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
2969
+ try {
2970
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
2971
+ if (replay == null) continue;
2972
+ return this.replayUnheardOutputs(replay);
2973
+ } catch (e) {
2974
+ if (this.host.noteReconcileFailure(e)) return;
2975
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
2976
+ }
2977
+ }
2978
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
2979
+ };
2980
+ this.lastHeardAt = Date.now();
2981
+ this.reconciling = false;
2982
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
2983
+ this.reconcile = async (queued) => {
2984
+ const id = this.data.id;
2985
+ const hostId = this.host.data.id;
2986
+ try {
2987
+ if (this.ended || queued?.has(id) === true) return "waiting";
2988
+ let replay;
2989
+ try {
2990
+ replay = historyReplay(await this.host.fetchHistory(id), id);
2991
+ } catch (e) {
2992
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
2993
+ return "waiting";
2994
+ }
2995
+ if (this.ended) return "waiting";
2996
+ if (replay == null) {
2997
+ if (queued == null) return "waiting";
2998
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
2999
+ logError(`run ${id}: ${reason}; the run fails`);
3000
+ this.ended = true;
3001
+ await this._finish({
3002
+ status: "Failure",
3003
+ error: null,
3004
+ reason
3005
+ });
3006
+ return "lost";
3007
+ }
3008
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3009
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3010
+ this.replayUnheardOutputs(replay);
3011
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3012
+ if (replay.end != null) {
3013
+ this.onPromptRelatedMessage(replay.end);
3014
+ return "history";
3015
+ }
3016
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3017
+ logError(`run ${id}: ${reason}; the run fails`);
3018
+ this.ended = true;
3019
+ await this._finish({
3020
+ status: "Failure",
3021
+ error: null,
3022
+ reason
3023
+ });
3024
+ return "history";
3025
+ } finally {
3026
+ this.reconciling = false;
3027
+ }
3028
+ };
2853
3029
  this.audioErrors = [];
2854
3030
  this.audios = [];
2855
3031
  this.videoErrors = [];
2856
3032
  this.videos = [];
2857
- this.retrieveFile = async (kind, info, promptNodeID) => {
3033
+ this.models3dErrors = [];
3034
+ this.models3d = [];
3035
+ this.retrieveFile = async (info, promptNodeID, mime) => {
2858
3036
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
2859
3037
  const bytes = new Uint8Array(await response.arrayBuffer());
2860
- const mime = mediaMime(info.filename);
2861
- const list = kind === "audio" ? this.audios : this.videos;
2862
3038
  const sf = this.save;
2863
- if (sf == null) {
2864
- list.push({
2865
- nodeId: promptNodeID,
2866
- filename: info.filename,
2867
- mime,
2868
- bytes,
2869
- absPath: null
2870
- });
2871
- return;
2872
- }
3039
+ if (sf == null) return {
3040
+ nodeId: promptNodeID,
3041
+ filename: info.filename,
3042
+ mime,
3043
+ bytes,
3044
+ absPath: null
3045
+ };
2873
3046
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
2874
3047
  const written = await this.encodeAndWrite({
2875
3048
  bytes,
@@ -2881,13 +3054,13 @@ var ComfyExecution = class {
2881
3054
  subfolder: info.subfolder,
2882
3055
  filename: info.filename
2883
3056
  });
2884
- list.push({
3057
+ return {
2885
3058
  nodeId: promptNodeID,
2886
3059
  filename: info.filename,
2887
3060
  mime,
2888
3061
  bytes,
2889
3062
  absPath: written.path
2890
- });
3063
+ };
2891
3064
  };
2892
3065
  this.imageErrors = [];
2893
3066
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -2965,6 +3138,7 @@ var ComfyExecution = class {
2965
3138
  };
2966
3139
  };
2967
3140
  this.onWsImageOutput = (p) => {
3141
+ this.heard();
2968
3142
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
2969
3143
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
2970
3144
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3027,7 +3201,7 @@ var ComfyExecution = class {
3027
3201
  this.onProgress = init.onProgress ?? null;
3028
3202
  this.onPreview = init.onPreview ?? null;
3029
3203
  this.logProgress = init.logProgress ?? false;
3030
- this.host.executions.set(data.id, this);
3204
+ this.host.trackExecution(this);
3031
3205
  this.onCreate();
3032
3206
  }
3033
3207
  get progress() {
@@ -3063,6 +3237,7 @@ var ComfyExecution = class {
3063
3237
  const outputs = [`${this.images.length} image(s)`];
3064
3238
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3065
3239
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3240
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3066
3241
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3067
3242
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3068
3243
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3091,6 +3266,24 @@ var ComfyExecution = class {
3091
3266
  get status() {
3092
3267
  return this.data.status ?? "New";
3093
3268
  }
3269
+ replayUnheardOutputs(replay) {
3270
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3271
+ }
3272
+ heard() {
3273
+ this.lastHeardAt = Date.now();
3274
+ }
3275
+ logReconcileOnce(msg) {
3276
+ if (this.loggedReconcileProblems.has(msg)) return;
3277
+ this.loggedReconcileProblems.add(msg);
3278
+ logError(`run ${this.data.id}: ${msg}`);
3279
+ }
3280
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3281
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3282
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3283
+ beginReconcile(why) {
3284
+ this.reconciling = true;
3285
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3286
+ }
3094
3287
  /** accumulate an output on the prompt; tags from node metadata ride along */
3095
3288
  pushImage(img, promptNodeID) {
3096
3289
  const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
@@ -3109,6 +3302,7 @@ var ComfyExecution = class {
3109
3302
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3110
3303
  * to onWsImageOutput before they get here) */
3111
3304
  onPreviewFrame(p) {
3305
+ this.heard();
3112
3306
  const listener = this.onPreview;
3113
3307
  if (listener == null) return;
3114
3308
  const current = this.workflow.currentExecutingNode;
@@ -3130,6 +3324,7 @@ var ComfyExecution = class {
3130
3324
  }
3131
3325
  /** @internal a live-text frame for one node */
3132
3326
  onProgressText(p) {
3327
+ this.heard();
3133
3328
  this.progressTexts.set(p.nodeId, p.text);
3134
3329
  this.progressText = p.text;
3135
3330
  this.emitProgress();
@@ -3190,14 +3385,6 @@ function styler(open = "", close = "") {
3190
3385
  }
3191
3386
  const ansi = styler();
3192
3387
  //#endregion
3193
- //#region src/utils/log.ts
3194
- const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
3195
- const logInfo = (msg) => {
3196
- if (!isQuiet()) console.log(msg);
3197
- };
3198
- const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
3199
- const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
3200
- //#endregion
3201
3388
  //#region src/utils/printArkResultInConsole.ts
3202
3389
  const MAX_PRINTED_ERRORS = 10;
3203
3390
  function printArkResultInConsole(res) {
@@ -3886,7 +4073,12 @@ function codegenSDK(opts) {
3886
4073
  p(`INVALID_null: any`);
3887
4074
  p("");
3888
4075
  p("// named slot types: everything an input of that type accepts");
3889
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
4076
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
4077
+ for (const t of slotTypes) {
4078
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
4079
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
4080
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
4081
+ }
3890
4082
  p("");
3891
4083
  p("// enum unions: literal values or an output carrying one");
3892
4084
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -5177,6 +5369,12 @@ var ResilientWebSocketClient = class {
5177
5369
  }
5178
5370
  }, ms);
5179
5371
  }
5372
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5373
+ reconnect() {
5374
+ if (this.permanentlyClosed || this.currentWS == null) return;
5375
+ this.addInfo("closing the socket to reconnect");
5376
+ this.currentWS.close();
5377
+ }
5180
5378
  /** close and stop reconnecting (lets a script exit cleanly) */
5181
5379
  disconnectPermanently() {
5182
5380
  this.permanentlyClosed = true;
@@ -5198,6 +5396,7 @@ var ResilientWebSocketClient = class {
5198
5396
  }
5199
5397
  async connect() {
5200
5398
  this.isOpen = false;
5399
+ this.url = this.options.url();
5201
5400
  const prevWS = this.currentWS;
5202
5401
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
5203
5402
  this.stopHeartbeat();
@@ -6531,6 +6730,13 @@ var MediaVar = class extends ComfyVar {
6531
6730
  get extensions() {
6532
6731
  return this.opts.extensions ?? DEFAULT_MEDIA_EXTENSIONS[this.kind];
6533
6732
  }
6733
+ /** the one-click starting files, `~/` expanded, in their declared order */
6734
+ get presets() {
6735
+ return Object.entries(this.opts.presets ?? {}).map(([label, value]) => ({
6736
+ label,
6737
+ value: expandUserPath(value)
6738
+ }));
6739
+ }
6534
6740
  set(value) {
6535
6741
  return super.set(expandUserPath(value));
6536
6742
  }
@@ -6822,10 +7028,17 @@ function diffSchemas(p) {
6822
7028
  }
6823
7029
  //#endregion
6824
7030
  //#region src/host/ComfyHost.ts
6825
- /** the host never came up within ConnectOptions.timeoutMs */
6826
- var ComfyHostUnreachableError = class extends Error {
7031
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
7032
+ var HostRouteUnusableError = class extends Error {
6827
7033
  constructor(..._args) {
6828
7034
  super(..._args);
7035
+ this.name = "HostRouteUnusableError";
7036
+ }
7037
+ };
7038
+ /** the host never came up within ConnectOptions.timeoutMs */
7039
+ var ComfyHostUnreachableError = class extends Error {
7040
+ constructor(..._args2) {
7041
+ super(..._args2);
6829
7042
  this.name = "ComfyHostUnreachableError";
6830
7043
  }
6831
7044
  };
@@ -6998,6 +7211,7 @@ var ComfyHost = class {
6998
7211
  this._connectTimer = null;
6999
7212
  this.disconnect = () => {
7000
7213
  this.clearConnectTimer();
7214
+ this.stopWatchdog();
7001
7215
  this.ws?.disconnectPermanently();
7002
7216
  this.ws = null;
7003
7217
  this._ready = null;
@@ -7017,6 +7231,50 @@ var ComfyHost = class {
7017
7231
  });
7018
7232
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
7019
7233
  };
7234
+ this.fetchReconcileJSON_ = async (route) => {
7235
+ const res = await this.fetch(route);
7236
+ const contentType = res.headers.get("content-type") ?? "";
7237
+ if (res.ok && contentType.includes("json")) return res.json();
7238
+ res.body?.cancel();
7239
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
7240
+ };
7241
+ this.fetchHistory = (promptId) => {
7242
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
7243
+ };
7244
+ this.fetchQueuedPromptIds = async () => {
7245
+ const json = await this.fetchReconcileJSON_("/queue");
7246
+ const ids = /* @__PURE__ */ new Set();
7247
+ for (const key of ["queue_running", "queue_pending"]) {
7248
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
7249
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
7250
+ for (const item of list) {
7251
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
7252
+ ids.add(item[1]);
7253
+ }
7254
+ }
7255
+ return ids;
7256
+ };
7257
+ this.reconcileOff = null;
7258
+ this.fetchQueuedPromptIdsOrNull = async () => {
7259
+ try {
7260
+ return await this.fetchQueuedPromptIds();
7261
+ } catch (e) {
7262
+ if (this.noteReconcileFailure(e)) return null;
7263
+ const msg = extractErrorMessage(e);
7264
+ if (!this._loggedQueueProblems.has(msg)) {
7265
+ this._loggedQueueProblems.add(msg);
7266
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
7267
+ }
7268
+ return null;
7269
+ }
7270
+ };
7271
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
7272
+ this.runSilenceMs = 1e3;
7273
+ this.runSilenceMaxMs = 3e4;
7274
+ this._silenceWaitMs = null;
7275
+ this._lastCheckAt = 0;
7276
+ this._checking = false;
7277
+ this._watchdog = null;
7020
7278
  this.clearQueue = () => {
7021
7279
  return this.postJSON_("/queue", { clear: true });
7022
7280
  };
@@ -7146,6 +7404,7 @@ var ComfyHost = class {
7146
7404
  this.comfySessionId = "temp";
7147
7405
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7148
7406
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
7407
+ this._socketIsNew = false;
7149
7408
  this.status = null;
7150
7409
  this.lastWsMessageAt = null;
7151
7410
  /** folder where file related to the host config will be cached */
@@ -7251,6 +7510,8 @@ var ComfyHost = class {
7251
7510
  this.ws = new ResilientWebSocketClient({
7252
7511
  onConnectOrReconnect: async () => {
7253
7512
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
7513
+ this._socketIsNew = true;
7514
+ this.reconcileRuns([...this.executions.values()], "reconnect");
7254
7515
  if (this.shouldUseSchemaCache()) try {
7255
7516
  await this.loadSchemaFromCache();
7256
7517
  await this.waitForSession();
@@ -7264,7 +7525,7 @@ var ComfyHost = class {
7264
7525
  this.markReady();
7265
7526
  },
7266
7527
  onMessage: (e) => this.onMessage(e),
7267
- url: () => this.getWSUrl(),
7528
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
7268
7529
  headers: () => this.authHeaders(),
7269
7530
  onTransportDead: (e) => this.markFailed(e),
7270
7531
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -7306,6 +7567,65 @@ var ComfyHost = class {
7306
7567
  });
7307
7568
  return this._schemaFromCache;
7308
7569
  }
7570
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
7571
+ * stop for good, said once), false for a passing failure the caller reports */
7572
+ noteReconcileFailure(e) {
7573
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
7574
+ if (this.reconcileOff == null) {
7575
+ this.reconcileOff = e.message;
7576
+ this.stopWatchdog();
7577
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
7578
+ }
7579
+ return true;
7580
+ }
7581
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
7582
+ trackExecution(execution) {
7583
+ this.executions.set(execution.data.id, execution);
7584
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
7585
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
7586
+ this._watchdog.unref?.();
7587
+ }
7588
+ stopWatchdog() {
7589
+ if (this._watchdog != null) clearInterval(this._watchdog);
7590
+ this._watchdog = null;
7591
+ }
7592
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
7593
+ * quiet node: ask. A run queued behind a talking host is never asked about */
7594
+ watchdogTick() {
7595
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
7596
+ if (this._checking) return;
7597
+ const now = Date.now();
7598
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
7599
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
7600
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
7601
+ if (due.length === 0) return;
7602
+ this._checking = true;
7603
+ this.reconcileRuns(due, "silence").finally(() => {
7604
+ this._checking = false;
7605
+ this._lastCheckAt = Date.now();
7606
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
7607
+ });
7608
+ }
7609
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
7610
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
7611
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
7612
+ * the new socket of the same session. A clean close lets the server end that handler first */
7613
+ async reconcileRuns(runs, why) {
7614
+ if (this.reconcileOff != null) return;
7615
+ const todo = runs.filter((r) => !r.reconciling);
7616
+ if (todo.length === 0) return;
7617
+ for (const r of todo) r.beginReconcile(why);
7618
+ const queued = await this.fetchQueuedPromptIdsOrNull();
7619
+ if (this.reconcileOff != null) {
7620
+ for (const r of todo) r.reconciling = false;
7621
+ return;
7622
+ }
7623
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
7624
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
7625
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
7626
+ this.ws.reconnect();
7627
+ }
7628
+ }
7309
7629
  /** method to either execute or buffer the incoming message */
7310
7630
  routeOrBuffer(prompt_id, msg) {
7311
7631
  this.activePromptID = prompt_id;
@@ -7367,6 +7687,7 @@ var ComfyHost = class {
7367
7687
  }
7368
7688
  onMessage(e) {
7369
7689
  this.lastWsMessageAt = Date.now();
7690
+ this._silenceWaitMs = null;
7370
7691
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
7371
7692
  if (e.data instanceof ArrayBuffer) {
7372
7693
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -7418,10 +7739,12 @@ var ComfyHost = class {
7418
7739
  if (msg.type === "status") {
7419
7740
  if (msg.data.sid) {
7420
7741
  const sidChanged = msg.data.sid !== this.comfySessionId;
7742
+ const socketIsNew = this._socketIsNew;
7743
+ this._socketIsNew = false;
7421
7744
  this.comfySessionId = msg.data.sid;
7422
7745
  this._sessionResolve?.();
7423
7746
  this._sessionResolve = null;
7424
- if (sidChanged) {
7747
+ if (sidChanged || socketIsNew) {
7425
7748
  this._unknownWsEventTypes.clear();
7426
7749
  this._unknownBinaryFrameTypes.clear();
7427
7750
  this.onSession?.(msg.data.sid);
@@ -8159,6 +8482,28 @@ var ComfyTS = class ComfyTS {
8159
8482
  }
8160
8483
  };
8161
8484
  //#endregion
8485
+ //#region src/vars/outputWidgets.ts
8486
+ const widget = {
8487
+ /** a point light moved over the image in 3D: left/right, up/down, nearer/farther */
8488
+ relight(roles, opts = {}) {
8489
+ if (roles.depth == null && roles.normal == null) throw new Error("widget.relight needs a `depth` or a `normal` role: without either there is no surface to light");
8490
+ return {
8491
+ kind: "relight",
8492
+ roles,
8493
+ ...opts.title != null ? { title: opts.title } : {}
8494
+ };
8495
+ } };
8496
+ /** the roles of a widget whose tag one of the images carries, as role → index in `images` */
8497
+ function resolveWidgetRoles(w, images) {
8498
+ const out = /* @__PURE__ */ new Map();
8499
+ for (const [role, tag] of Object.entries(w.roles)) {
8500
+ if (typeof tag !== "string") continue;
8501
+ const ix = images.findIndex((img) => img.tags?.includes(tag) === true);
8502
+ if (ix >= 0) out.set(role, ix);
8503
+ }
8504
+ return out;
8505
+ }
8506
+ //#endregion
8162
8507
  //#region src/utils/loraTag.ts
8163
8508
  /**
8164
8509
  * build a LoraManager-style lora tag: `<lora:name:strength>` or
@@ -8289,6 +8634,6 @@ function isTuiActive() {
8289
8634
  */
8290
8635
  setDefaultComfyStorage(createNodeStorage());
8291
8636
  //#endregion
8292
- export { AudioVar, ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyHostUnreachableError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_AUDIO_EXTENSIONS, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DEFAULT_STARRED_SIZES, DEFAULT_VIDEO_EXTENSIONS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, MediaVar, MediaVarEmptyError, MultiChoiceVar, OptionalChoiceVar, PromptVar, ResilientWebSocketClient, SD15_SIZE_PRESETS, SeedVar, SizeVar, TextVar, ToggleVar, VideoVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, activePresetLabel, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, clearLoraKeywordOverride, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, exampleMediaPath, getComfyStorage, getLoraDisplayName, getLoraInfo, getLoraKeyword, getLoraPreviewUrl, getLoraTriggerWords, hostIdToNamespace, isLoraKeywordFromMirror, isTuiActive, loraKey, loraKeywordFromMirror, loraMatchesFilter, loraSearchNames, loraSearchText, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, promptEnhancerPresets, readPromptEnhancers, refreshLoraInfoCacheIfChanged, reloadLoraInfoCache, renderHttpBase, renderWsUrl, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, sizePresetsFor, toPresetList, v };
8637
+ export { AudioVar, ChoiceVar, ComfyExecution, ComfyHost, ComfyHostAuthError, ComfyHostUnreachableError, ComfyManager, ComfyNode, ComfyNodeOutput, ComfySchema, ComfyTS, ComfyUploader, ComfyVar, ComfyVarBase, ComfyWorkflow, ComfyWorkflowBuilder, DEFAULT_AUDIO_EXTENSIONS, DEFAULT_IMAGE_EXTENSIONS, DEFAULT_SIZE_PRESETS, DEFAULT_STARRED_SIZES, DEFAULT_VIDEO_EXTENSIONS, DefinedWorkflow, FloatVar, ImageVar, ImageVarEmptyError, IntVar, InvalidPromptError, LorasVar, MediaImage, MediaVar, MediaVarEmptyError, MultiChoiceVar, OptionalChoiceVar, PromptVar, ResilientWebSocketClient, SD15_SIZE_PRESETS, SeedVar, SizeVar, TextVar, ToggleVar, VideoVar, WorkflowConvertError, WorkflowNormalizeError, __FAIL, __OK, activeLoras, activePresetLabel, asAbsolutePath, asHTMLContent, asMDContent, asRelativePath, auto, auto_, clearLoraKeywordOverride, codegenSDK, convertFlowToLiteGraphJSON, convertLiteGraphToPrompt, createMemoryStorage, exampleImagePath, exampleMediaPath, getComfyStorage, getLoraDisplayName, getLoraInfo, getLoraKeyword, getLoraPreviewUrl, getLoraTriggerWords, hostIdToNamespace, isLoraKeywordFromMirror, isTuiActive, loraKey, loraKeywordFromMirror, loraMatchesFilter, loraSearchNames, loraSearchText, loraTag, normalizeWorkflow, parseHostBase, parseWorkflowJson, promptEnhancerPresets, readPromptEnhancers, refreshLoraInfoCacheIfChanged, reloadLoraInfoCache, renderHttpBase, renderWsUrl, resolveWidgetRoles, resultFailure, resultSuccess, setDefaultComfyStorage, setLoraKeyword, sizePresetsFor, toPresetList, v, widget };
8293
8638
 
8294
8639
  //# sourceMappingURL=index.js.map