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.cjs CHANGED
@@ -134,7 +134,7 @@ function createNodeStorage() {
134
134
  }
135
135
  //#endregion
136
136
  //#region package.json
137
- var version = "2.21.0";
137
+ var version = "2.23.0";
138
138
  //#endregion
139
139
  //#region src/litegraph/LiteGraphLinkID.ts
140
140
  const asLiteGraphLinkID = (id) => id;
@@ -1889,13 +1889,14 @@ var ComfyNode = class ComfyNode {
1889
1889
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1890
1890
  }
1891
1891
  _getOutputForTypeOrCrash(type) {
1892
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1892
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1893
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
1893
1894
  const val = this.outputs[i.outKey];
1894
1895
  if (val instanceof ComfyNodeOutput) return val;
1895
1896
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1896
1897
  }
1897
1898
  _getOutputForTypeOrNull(type) {
1898
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1899
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1899
1900
  if (i == null) return null;
1900
1901
  const val = this.outputs[i.outKey];
1901
1902
  if (val == null) return null;
@@ -1903,6 +1904,11 @@ var ComfyNode = class ComfyNode {
1903
1904
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1904
1905
  }
1905
1906
  };
1907
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
1908
+ function slotTypeAccepts(inputType, outputType) {
1909
+ if (inputType === outputType) return true;
1910
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
1911
+ }
1906
1912
  //#endregion
1907
1913
  //#region src/host/ComfyWorkflowBuilder.ts
1908
1914
  var ComfyWorkflowBuilder = class {
@@ -2408,6 +2414,7 @@ const types$1 = (0, arktype.scope)({
2408
2414
  "audio?": "ComfyImageInfo[]",
2409
2415
  "video?": "ComfyImageInfo[]",
2410
2416
  "gifs?": "ComfyImageInfo[]",
2417
+ "3d?": "ComfyImageInfo[]",
2411
2418
  "text?": "unknown[]"
2412
2419
  },
2413
2420
  WsMsgExecuted: {
@@ -2769,6 +2776,88 @@ function mediaMime(filename) {
2769
2776
  return MIMES[extensionOf(filename)] ?? "application/octet-stream";
2770
2777
  }
2771
2778
  //#endregion
2779
+ //#region src/runner/outputs3d.ts
2780
+ /** ply and spz have no registered mime: the `x-` forms are what three.js and the splat viewers accept */
2781
+ const MODEL_3D_MIMES = {
2782
+ glb: "model/gltf-binary",
2783
+ gltf: "model/gltf+json",
2784
+ ply: "model/x-ply",
2785
+ spz: "model/x-spz",
2786
+ obj: "model/obj",
2787
+ stl: "model/stl"
2788
+ };
2789
+ function model3dMime(filename) {
2790
+ return MODEL_3D_MIMES[extensionOf(filename)] ?? "application/octet-stream";
2791
+ }
2792
+ //#endregion
2793
+ //#region src/runner/historyReplay.ts
2794
+ const END_TYPES = /* @__PURE__ */ new Set([
2795
+ "execution_success",
2796
+ "execution_error",
2797
+ "execution_interrupted"
2798
+ ]);
2799
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
2800
+ * entry for it: queued, running, or lost */
2801
+ function historyReplay(json, promptId) {
2802
+ const entry = field(json, promptId);
2803
+ if (entry == null) return null;
2804
+ const problems = [];
2805
+ const valid = (raw) => {
2806
+ const res = types$1.PromptRelated_WsMsg(raw);
2807
+ if (!(res instanceof arktype.type.errors)) return res;
2808
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
2809
+ return null;
2810
+ };
2811
+ const executed = [];
2812
+ const outputs = field(entry, "outputs");
2813
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
2814
+ const msg = valid({
2815
+ type: "executed",
2816
+ data: {
2817
+ node,
2818
+ output,
2819
+ prompt_id: promptId
2820
+ }
2821
+ });
2822
+ if (msg != null) executed.push(msg);
2823
+ }
2824
+ const status = field(entry, "status");
2825
+ const list = field(status, "messages");
2826
+ let end = null;
2827
+ for (const m of Array.isArray(list) ? list : []) {
2828
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
2829
+ end = valid({
2830
+ type: m[0],
2831
+ data: m[1]
2832
+ });
2833
+ }
2834
+ const statusStr = field(status, "status_str");
2835
+ if (end == null && (status == null || statusStr === "success")) end = valid({
2836
+ type: "execution_success",
2837
+ data: {
2838
+ prompt_id: promptId,
2839
+ timestamp: Date.now()
2840
+ }
2841
+ });
2842
+ return {
2843
+ executed,
2844
+ end,
2845
+ problems
2846
+ };
2847
+ }
2848
+ function field(x, key) {
2849
+ if (typeof x !== "object" || x == null) return null;
2850
+ return Reflect.get(x, key) ?? null;
2851
+ }
2852
+ //#endregion
2853
+ //#region src/utils/log.ts
2854
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
2855
+ const logInfo = (msg) => {
2856
+ if (!isQuiet()) console.log(msg);
2857
+ };
2858
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
2859
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
2860
+ //#endregion
2772
2861
  //#region src/runner/ComfyExecution.ts
2773
2862
  /** paths claimed by in-flight retrievals: two same-second runs on a
2774
2863
  * counter-resetting cloud host compute the same name before either writes.
@@ -2795,6 +2884,9 @@ var ComfyExecution = class {
2795
2884
  this._resolve = resolve;
2796
2885
  });
2797
2886
  this.onPromptRelatedMessage = (msg) => {
2887
+ if (this.ended) return;
2888
+ this.heard();
2889
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
2798
2890
  const graph = this.workflow;
2799
2891
  if (msg.type === "binary_preview_frame") {
2800
2892
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -2825,6 +2917,7 @@ var ComfyExecution = class {
2825
2917
  this.workflow.onExecuting(msg);
2826
2918
  };
2827
2919
  this.onExecutionSuccess = async (_msg) => {
2920
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
2828
2921
  await Promise.all(this.pendingPromises);
2829
2922
  return this._finish({ status: "Success" });
2830
2923
  };
@@ -2838,6 +2931,7 @@ var ComfyExecution = class {
2838
2931
  };
2839
2932
  this.onExecuted = (msg) => {
2840
2933
  const promptNodeID = msg.data.node;
2934
+ this.heardExecuted.add(promptNodeID);
2841
2935
  for (const entry of msg.data.output?.text ?? []) {
2842
2936
  if (typeof entry !== "string") continue;
2843
2937
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -2853,7 +2947,7 @@ var ComfyExecution = class {
2853
2947
  ...out?.video ?? [],
2854
2948
  ...out?.gifs ?? []
2855
2949
  ].filter((f) => f.type !== "input");
2856
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
2950
+ 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) => {
2857
2951
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
2858
2952
  this.videoErrors.push({
2859
2953
  video,
@@ -2868,35 +2962,114 @@ var ComfyExecution = class {
2868
2962
  error: e
2869
2963
  });
2870
2964
  }));
2871
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
2965
+ 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) => {
2872
2966
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
2873
2967
  this.audioErrors.push({
2874
2968
  audio,
2875
2969
  error: e
2876
2970
  });
2877
2971
  }));
2972
+ 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({
2973
+ ...o,
2974
+ format: extensionOf(o.filename)
2975
+ }), (e) => {
2976
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
2977
+ this.models3dErrors.push({
2978
+ model3d,
2979
+ error: e
2980
+ });
2981
+ }));
2878
2982
  };
2879
2983
  this.pendingPromises = [];
2984
+ this.ended = false;
2985
+ this.heardExecuted = /* @__PURE__ */ new Set();
2986
+ this.mayHaveMissedEvents = false;
2987
+ this.historyRetry = {
2988
+ tries: 5,
2989
+ ms: 400
2990
+ };
2991
+ this.retrieveMissedOutputs = async () => {
2992
+ const id = this.data.id;
2993
+ for (let i = 0; i < this.historyRetry.tries; i++) {
2994
+ if (this.host.reconcileOff != null) return;
2995
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
2996
+ try {
2997
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
2998
+ if (replay == null) continue;
2999
+ return this.replayUnheardOutputs(replay);
3000
+ } catch (e) {
3001
+ if (this.host.noteReconcileFailure(e)) return;
3002
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
3003
+ }
3004
+ }
3005
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
3006
+ };
3007
+ this.lastHeardAt = Date.now();
3008
+ this.reconciling = false;
3009
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
3010
+ this.reconcile = async (queued) => {
3011
+ const id = this.data.id;
3012
+ const hostId = this.host.data.id;
3013
+ try {
3014
+ if (this.ended || queued?.has(id) === true) return "waiting";
3015
+ let replay;
3016
+ try {
3017
+ replay = historyReplay(await this.host.fetchHistory(id), id);
3018
+ } catch (e) {
3019
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
3020
+ return "waiting";
3021
+ }
3022
+ if (this.ended) return "waiting";
3023
+ if (replay == null) {
3024
+ if (queued == null) return "waiting";
3025
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
3026
+ logError(`run ${id}: ${reason}; the run fails`);
3027
+ this.ended = true;
3028
+ await this._finish({
3029
+ status: "Failure",
3030
+ error: null,
3031
+ reason
3032
+ });
3033
+ return "lost";
3034
+ }
3035
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3036
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3037
+ this.replayUnheardOutputs(replay);
3038
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3039
+ if (replay.end != null) {
3040
+ this.onPromptRelatedMessage(replay.end);
3041
+ return "history";
3042
+ }
3043
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3044
+ logError(`run ${id}: ${reason}; the run fails`);
3045
+ this.ended = true;
3046
+ await this._finish({
3047
+ status: "Failure",
3048
+ error: null,
3049
+ reason
3050
+ });
3051
+ return "history";
3052
+ } finally {
3053
+ this.reconciling = false;
3054
+ }
3055
+ };
2880
3056
  this.audioErrors = [];
2881
3057
  this.audios = [];
2882
3058
  this.videoErrors = [];
2883
3059
  this.videos = [];
2884
- this.retrieveFile = async (kind, info, promptNodeID) => {
3060
+ this.models3dErrors = [];
3061
+ this.models3d = [];
3062
+ this.retrieveFile = async (info, promptNodeID, mime) => {
2885
3063
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
2886
3064
  const bytes = new Uint8Array(await response.arrayBuffer());
2887
- const mime = mediaMime(info.filename);
2888
- const list = kind === "audio" ? this.audios : this.videos;
2889
3065
  const sf = this.save;
2890
- if (sf == null) {
2891
- list.push({
2892
- nodeId: promptNodeID,
2893
- filename: info.filename,
2894
- mime,
2895
- bytes,
2896
- absPath: null
2897
- });
2898
- return;
2899
- }
3066
+ if (sf == null) return {
3067
+ nodeId: promptNodeID,
3068
+ filename: info.filename,
3069
+ mime,
3070
+ bytes,
3071
+ absPath: null
3072
+ };
2900
3073
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
2901
3074
  const written = await this.encodeAndWrite({
2902
3075
  bytes,
@@ -2908,13 +3081,13 @@ var ComfyExecution = class {
2908
3081
  subfolder: info.subfolder,
2909
3082
  filename: info.filename
2910
3083
  });
2911
- list.push({
3084
+ return {
2912
3085
  nodeId: promptNodeID,
2913
3086
  filename: info.filename,
2914
3087
  mime,
2915
3088
  bytes,
2916
3089
  absPath: written.path
2917
- });
3090
+ };
2918
3091
  };
2919
3092
  this.imageErrors = [];
2920
3093
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -2992,6 +3165,7 @@ var ComfyExecution = class {
2992
3165
  };
2993
3166
  };
2994
3167
  this.onWsImageOutput = (p) => {
3168
+ this.heard();
2995
3169
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
2996
3170
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
2997
3171
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3054,7 +3228,7 @@ var ComfyExecution = class {
3054
3228
  this.onProgress = init.onProgress ?? null;
3055
3229
  this.onPreview = init.onPreview ?? null;
3056
3230
  this.logProgress = init.logProgress ?? false;
3057
- this.host.executions.set(data.id, this);
3231
+ this.host.trackExecution(this);
3058
3232
  this.onCreate();
3059
3233
  }
3060
3234
  get progress() {
@@ -3090,6 +3264,7 @@ var ComfyExecution = class {
3090
3264
  const outputs = [`${this.images.length} image(s)`];
3091
3265
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3092
3266
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3267
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3093
3268
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3094
3269
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3095
3270
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3118,6 +3293,24 @@ var ComfyExecution = class {
3118
3293
  get status() {
3119
3294
  return this.data.status ?? "New";
3120
3295
  }
3296
+ replayUnheardOutputs(replay) {
3297
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3298
+ }
3299
+ heard() {
3300
+ this.lastHeardAt = Date.now();
3301
+ }
3302
+ logReconcileOnce(msg) {
3303
+ if (this.loggedReconcileProblems.has(msg)) return;
3304
+ this.loggedReconcileProblems.add(msg);
3305
+ logError(`run ${this.data.id}: ${msg}`);
3306
+ }
3307
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3308
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3309
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3310
+ beginReconcile(why) {
3311
+ this.reconciling = true;
3312
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3313
+ }
3121
3314
  /** accumulate an output on the prompt; tags from node metadata ride along */
3122
3315
  pushImage(img, promptNodeID) {
3123
3316
  const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
@@ -3136,6 +3329,7 @@ var ComfyExecution = class {
3136
3329
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3137
3330
  * to onWsImageOutput before they get here) */
3138
3331
  onPreviewFrame(p) {
3332
+ this.heard();
3139
3333
  const listener = this.onPreview;
3140
3334
  if (listener == null) return;
3141
3335
  const current = this.workflow.currentExecutingNode;
@@ -3157,6 +3351,7 @@ var ComfyExecution = class {
3157
3351
  }
3158
3352
  /** @internal a live-text frame for one node */
3159
3353
  onProgressText(p) {
3354
+ this.heard();
3160
3355
  this.progressTexts.set(p.nodeId, p.text);
3161
3356
  this.progressText = p.text;
3162
3357
  this.emitProgress();
@@ -3217,14 +3412,6 @@ function styler(open = "", close = "") {
3217
3412
  }
3218
3413
  const ansi = styler();
3219
3414
  //#endregion
3220
- //#region src/utils/log.ts
3221
- const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
3222
- const logInfo = (msg) => {
3223
- if (!isQuiet()) console.log(msg);
3224
- };
3225
- const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
3226
- const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
3227
- //#endregion
3228
3415
  //#region src/utils/printArkResultInConsole.ts
3229
3416
  const MAX_PRINTED_ERRORS = 10;
3230
3417
  function printArkResultInConsole(res) {
@@ -3913,7 +4100,12 @@ function codegenSDK(opts) {
3913
4100
  p(`INVALID_null: any`);
3914
4101
  p("");
3915
4102
  p("// named slot types: everything an input of that type accepts");
3916
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
4103
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
4104
+ for (const t of slotTypes) {
4105
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
4106
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
4107
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
4108
+ }
3917
4109
  p("");
3918
4110
  p("// enum unions: literal values or an output carrying one");
3919
4111
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -5204,6 +5396,12 @@ var ResilientWebSocketClient = class {
5204
5396
  }
5205
5397
  }, ms);
5206
5398
  }
5399
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5400
+ reconnect() {
5401
+ if (this.permanentlyClosed || this.currentWS == null) return;
5402
+ this.addInfo("closing the socket to reconnect");
5403
+ this.currentWS.close();
5404
+ }
5207
5405
  /** close and stop reconnecting (lets a script exit cleanly) */
5208
5406
  disconnectPermanently() {
5209
5407
  this.permanentlyClosed = true;
@@ -5225,6 +5423,7 @@ var ResilientWebSocketClient = class {
5225
5423
  }
5226
5424
  async connect() {
5227
5425
  this.isOpen = false;
5426
+ this.url = this.options.url();
5228
5427
  const prevWS = this.currentWS;
5229
5428
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
5230
5429
  this.stopHeartbeat();
@@ -6558,6 +6757,13 @@ var MediaVar = class extends ComfyVar {
6558
6757
  get extensions() {
6559
6758
  return this.opts.extensions ?? DEFAULT_MEDIA_EXTENSIONS[this.kind];
6560
6759
  }
6760
+ /** the one-click starting files, `~/` expanded, in their declared order */
6761
+ get presets() {
6762
+ return Object.entries(this.opts.presets ?? {}).map(([label, value]) => ({
6763
+ label,
6764
+ value: expandUserPath(value)
6765
+ }));
6766
+ }
6561
6767
  set(value) {
6562
6768
  return super.set(expandUserPath(value));
6563
6769
  }
@@ -6849,10 +7055,17 @@ function diffSchemas(p) {
6849
7055
  }
6850
7056
  //#endregion
6851
7057
  //#region src/host/ComfyHost.ts
6852
- /** the host never came up within ConnectOptions.timeoutMs */
6853
- var ComfyHostUnreachableError = class extends Error {
7058
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
7059
+ var HostRouteUnusableError = class extends Error {
6854
7060
  constructor(..._args) {
6855
7061
  super(..._args);
7062
+ this.name = "HostRouteUnusableError";
7063
+ }
7064
+ };
7065
+ /** the host never came up within ConnectOptions.timeoutMs */
7066
+ var ComfyHostUnreachableError = class extends Error {
7067
+ constructor(..._args2) {
7068
+ super(..._args2);
6856
7069
  this.name = "ComfyHostUnreachableError";
6857
7070
  }
6858
7071
  };
@@ -7025,6 +7238,7 @@ var ComfyHost = class {
7025
7238
  this._connectTimer = null;
7026
7239
  this.disconnect = () => {
7027
7240
  this.clearConnectTimer();
7241
+ this.stopWatchdog();
7028
7242
  this.ws?.disconnectPermanently();
7029
7243
  this.ws = null;
7030
7244
  this._ready = null;
@@ -7044,6 +7258,50 @@ var ComfyHost = class {
7044
7258
  });
7045
7259
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
7046
7260
  };
7261
+ this.fetchReconcileJSON_ = async (route) => {
7262
+ const res = await this.fetch(route);
7263
+ const contentType = res.headers.get("content-type") ?? "";
7264
+ if (res.ok && contentType.includes("json")) return res.json();
7265
+ res.body?.cancel();
7266
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
7267
+ };
7268
+ this.fetchHistory = (promptId) => {
7269
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
7270
+ };
7271
+ this.fetchQueuedPromptIds = async () => {
7272
+ const json = await this.fetchReconcileJSON_("/queue");
7273
+ const ids = /* @__PURE__ */ new Set();
7274
+ for (const key of ["queue_running", "queue_pending"]) {
7275
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
7276
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
7277
+ for (const item of list) {
7278
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
7279
+ ids.add(item[1]);
7280
+ }
7281
+ }
7282
+ return ids;
7283
+ };
7284
+ this.reconcileOff = null;
7285
+ this.fetchQueuedPromptIdsOrNull = async () => {
7286
+ try {
7287
+ return await this.fetchQueuedPromptIds();
7288
+ } catch (e) {
7289
+ if (this.noteReconcileFailure(e)) return null;
7290
+ const msg = extractErrorMessage(e);
7291
+ if (!this._loggedQueueProblems.has(msg)) {
7292
+ this._loggedQueueProblems.add(msg);
7293
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
7294
+ }
7295
+ return null;
7296
+ }
7297
+ };
7298
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
7299
+ this.runSilenceMs = 1e3;
7300
+ this.runSilenceMaxMs = 3e4;
7301
+ this._silenceWaitMs = null;
7302
+ this._lastCheckAt = 0;
7303
+ this._checking = false;
7304
+ this._watchdog = null;
7047
7305
  this.clearQueue = () => {
7048
7306
  return this.postJSON_("/queue", { clear: true });
7049
7307
  };
@@ -7173,6 +7431,7 @@ var ComfyHost = class {
7173
7431
  this.comfySessionId = "temp";
7174
7432
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7175
7433
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
7434
+ this._socketIsNew = false;
7176
7435
  this.status = null;
7177
7436
  this.lastWsMessageAt = null;
7178
7437
  /** folder where file related to the host config will be cached */
@@ -7278,6 +7537,8 @@ var ComfyHost = class {
7278
7537
  this.ws = new ResilientWebSocketClient({
7279
7538
  onConnectOrReconnect: async () => {
7280
7539
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
7540
+ this._socketIsNew = true;
7541
+ this.reconcileRuns([...this.executions.values()], "reconnect");
7281
7542
  if (this.shouldUseSchemaCache()) try {
7282
7543
  await this.loadSchemaFromCache();
7283
7544
  await this.waitForSession();
@@ -7291,7 +7552,7 @@ var ComfyHost = class {
7291
7552
  this.markReady();
7292
7553
  },
7293
7554
  onMessage: (e) => this.onMessage(e),
7294
- url: () => this.getWSUrl(),
7555
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
7295
7556
  headers: () => this.authHeaders(),
7296
7557
  onTransportDead: (e) => this.markFailed(e),
7297
7558
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -7333,6 +7594,65 @@ var ComfyHost = class {
7333
7594
  });
7334
7595
  return this._schemaFromCache;
7335
7596
  }
7597
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
7598
+ * stop for good, said once), false for a passing failure the caller reports */
7599
+ noteReconcileFailure(e) {
7600
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
7601
+ if (this.reconcileOff == null) {
7602
+ this.reconcileOff = e.message;
7603
+ this.stopWatchdog();
7604
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
7605
+ }
7606
+ return true;
7607
+ }
7608
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
7609
+ trackExecution(execution) {
7610
+ this.executions.set(execution.data.id, execution);
7611
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
7612
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
7613
+ this._watchdog.unref?.();
7614
+ }
7615
+ stopWatchdog() {
7616
+ if (this._watchdog != null) clearInterval(this._watchdog);
7617
+ this._watchdog = null;
7618
+ }
7619
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
7620
+ * quiet node: ask. A run queued behind a talking host is never asked about */
7621
+ watchdogTick() {
7622
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
7623
+ if (this._checking) return;
7624
+ const now = Date.now();
7625
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
7626
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
7627
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
7628
+ if (due.length === 0) return;
7629
+ this._checking = true;
7630
+ this.reconcileRuns(due, "silence").finally(() => {
7631
+ this._checking = false;
7632
+ this._lastCheckAt = Date.now();
7633
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
7634
+ });
7635
+ }
7636
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
7637
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
7638
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
7639
+ * the new socket of the same session. A clean close lets the server end that handler first */
7640
+ async reconcileRuns(runs, why) {
7641
+ if (this.reconcileOff != null) return;
7642
+ const todo = runs.filter((r) => !r.reconciling);
7643
+ if (todo.length === 0) return;
7644
+ for (const r of todo) r.beginReconcile(why);
7645
+ const queued = await this.fetchQueuedPromptIdsOrNull();
7646
+ if (this.reconcileOff != null) {
7647
+ for (const r of todo) r.reconciling = false;
7648
+ return;
7649
+ }
7650
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
7651
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
7652
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
7653
+ this.ws.reconnect();
7654
+ }
7655
+ }
7336
7656
  /** method to either execute or buffer the incoming message */
7337
7657
  routeOrBuffer(prompt_id, msg) {
7338
7658
  this.activePromptID = prompt_id;
@@ -7394,6 +7714,7 @@ var ComfyHost = class {
7394
7714
  }
7395
7715
  onMessage(e) {
7396
7716
  this.lastWsMessageAt = Date.now();
7717
+ this._silenceWaitMs = null;
7397
7718
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
7398
7719
  if (e.data instanceof ArrayBuffer) {
7399
7720
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -7445,10 +7766,12 @@ var ComfyHost = class {
7445
7766
  if (msg.type === "status") {
7446
7767
  if (msg.data.sid) {
7447
7768
  const sidChanged = msg.data.sid !== this.comfySessionId;
7769
+ const socketIsNew = this._socketIsNew;
7770
+ this._socketIsNew = false;
7448
7771
  this.comfySessionId = msg.data.sid;
7449
7772
  this._sessionResolve?.();
7450
7773
  this._sessionResolve = null;
7451
- if (sidChanged) {
7774
+ if (sidChanged || socketIsNew) {
7452
7775
  this._unknownWsEventTypes.clear();
7453
7776
  this._unknownBinaryFrameTypes.clear();
7454
7777
  this.onSession?.(msg.data.sid);
@@ -8186,6 +8509,28 @@ var ComfyTS = class ComfyTS {
8186
8509
  }
8187
8510
  };
8188
8511
  //#endregion
8512
+ //#region src/vars/outputWidgets.ts
8513
+ const widget = {
8514
+ /** a point light moved over the image in 3D: left/right, up/down, nearer/farther */
8515
+ relight(roles, opts = {}) {
8516
+ 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");
8517
+ return {
8518
+ kind: "relight",
8519
+ roles,
8520
+ ...opts.title != null ? { title: opts.title } : {}
8521
+ };
8522
+ } };
8523
+ /** the roles of a widget whose tag one of the images carries, as role → index in `images` */
8524
+ function resolveWidgetRoles(w, images) {
8525
+ const out = /* @__PURE__ */ new Map();
8526
+ for (const [role, tag] of Object.entries(w.roles)) {
8527
+ if (typeof tag !== "string") continue;
8528
+ const ix = images.findIndex((img) => img.tags?.includes(tag) === true);
8529
+ if (ix >= 0) out.set(role, ix);
8530
+ }
8531
+ return out;
8532
+ }
8533
+ //#endregion
8189
8534
  //#region src/utils/loraTag.ts
8190
8535
  /**
8191
8536
  * build a LoraManager-style lora tag: `<lora:name:strength>` or
@@ -8400,6 +8745,7 @@ exports.refreshLoraInfoCacheIfChanged = refreshLoraInfoCacheIfChanged;
8400
8745
  exports.reloadLoraInfoCache = reloadLoraInfoCache;
8401
8746
  exports.renderHttpBase = renderHttpBase;
8402
8747
  exports.renderWsUrl = renderWsUrl;
8748
+ exports.resolveWidgetRoles = resolveWidgetRoles;
8403
8749
  exports.resultFailure = resultFailure;
8404
8750
  exports.resultSuccess = resultSuccess;
8405
8751
  exports.setDefaultComfyStorage = setDefaultComfyStorage;
@@ -8407,5 +8753,6 @@ exports.setLoraKeyword = setLoraKeyword;
8407
8753
  exports.sizePresetsFor = sizePresetsFor;
8408
8754
  exports.toPresetList = toPresetList;
8409
8755
  exports.v = v;
8756
+ exports.widget = widget;
8410
8757
 
8411
8758
  //# sourceMappingURL=index.cjs.map