comfy-ts 2.22.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 (54) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-DolRCMHj.js} +51 -17
  2. package/dist/ServeApp-DolRCMHj.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-Duneoq6r.js} +330 -28
  5. package/dist/exampleAssets-Duneoq6r.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-DjoJA8y7.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-DjoJA8y7.js.map} +1 -1
  8. package/dist/index.cjs +350 -34
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +131 -19
  11. package/dist/index.d.ts +131 -19
  12. package/dist/index.js +350 -34
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cr0L9lCK.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cr0L9lCK.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve---qA7o_m.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve---qA7o_m.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-DxXiWo5J.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-DxXiWo5J.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BTxdABHi.js} +16 -2
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BTxdABHi.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +131 -19
  24. package/dist/web.js +350 -34
  25. package/dist/web.js.map +1 -1
  26. package/examples/comfy-cloud/sdk.d.ts +102 -1
  27. package/examples/rvion/18-world.cflow.ts +101 -0
  28. package/examples/world-explorer/serve.ts +171 -0
  29. package/examples/world-explorer/web/index.html +14 -0
  30. package/examples/world-explorer/web/main.tsx +200 -0
  31. package/examples/world-explorer/web/state.ts +212 -0
  32. package/examples/world-explorer/web/styles.css +131 -0
  33. package/examples/world-explorer/web/thumb.ts +21 -0
  34. package/examples/world-explorer/web/tsconfig.json +11 -0
  35. package/examples/world-explorer/world-state.ts +40 -0
  36. package/package.json +5 -7
  37. package/src/cli/serve/ServeApp.ts +27 -2
  38. package/src/cli/serve/resultHistory.ts +22 -4
  39. package/src/cli/serve/thumbs.ts +19 -8
  40. package/src/cli/serve/web/api.ts +4 -0
  41. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  42. package/src/cli/serve/web/styles.ts +3 -0
  43. package/src/coreExports.ts +1 -0
  44. package/src/graph/ComfyNode.ts +12 -2
  45. package/src/host/ComfyHost.ts +153 -2
  46. package/src/host/ResilientWebsocket.ts +10 -0
  47. package/src/manager/script-update-manager.bun.ts +0 -7
  48. package/src/runner/ComfyExecution.ts +165 -20
  49. package/src/runner/ComfyWsApi.ts +2 -0
  50. package/src/runner/historyReplay.ts +53 -0
  51. package/src/runner/outputs3d.ts +18 -0
  52. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  53. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  54. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
package/dist/web.js CHANGED
@@ -101,7 +101,7 @@ function getComfyStorage() {
101
101
  }
102
102
  //#endregion
103
103
  //#region package.json
104
- var version = "2.22.0";
104
+ var version = "2.23.0";
105
105
  //#endregion
106
106
  //#region src/litegraph/LiteGraphLinkID.ts
107
107
  const asLiteGraphLinkID = (id) => id;
@@ -1856,13 +1856,14 @@ var ComfyNode = class ComfyNode {
1856
1856
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
1857
1857
  }
1858
1858
  _getOutputForTypeOrCrash(type) {
1859
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1859
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1860
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
1860
1861
  const val = this.outputs[i.outKey];
1861
1862
  if (val instanceof ComfyNodeOutput) return val;
1862
1863
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1863
1864
  }
1864
1865
  _getOutputForTypeOrNull(type) {
1865
- const i = this.$schema.outputs.find((i) => i.typeName === type);
1866
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
1866
1867
  if (i == null) return null;
1867
1868
  const val = this.outputs[i.outKey];
1868
1869
  if (val == null) return null;
@@ -1870,6 +1871,11 @@ var ComfyNode = class ComfyNode {
1870
1871
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
1871
1872
  }
1872
1873
  };
1874
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
1875
+ function slotTypeAccepts(inputType, outputType) {
1876
+ if (inputType === outputType) return true;
1877
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
1878
+ }
1873
1879
  //#endregion
1874
1880
  //#region src/host/ComfyWorkflowBuilder.ts
1875
1881
  var ComfyWorkflowBuilder = class {
@@ -2372,6 +2378,7 @@ const types$1 = scope({
2372
2378
  "audio?": "ComfyImageInfo[]",
2373
2379
  "video?": "ComfyImageInfo[]",
2374
2380
  "gifs?": "ComfyImageInfo[]",
2381
+ "3d?": "ComfyImageInfo[]",
2375
2382
  "text?": "unknown[]"
2376
2383
  },
2377
2384
  WsMsgExecuted: {
@@ -2733,6 +2740,88 @@ function mediaMime(filename) {
2733
2740
  return MIMES[extensionOf(filename)] ?? "application/octet-stream";
2734
2741
  }
2735
2742
  //#endregion
2743
+ //#region src/runner/outputs3d.ts
2744
+ /** ply and spz have no registered mime: the `x-` forms are what three.js and the splat viewers accept */
2745
+ const MODEL_3D_MIMES = {
2746
+ glb: "model/gltf-binary",
2747
+ gltf: "model/gltf+json",
2748
+ ply: "model/x-ply",
2749
+ spz: "model/x-spz",
2750
+ obj: "model/obj",
2751
+ stl: "model/stl"
2752
+ };
2753
+ function model3dMime(filename) {
2754
+ return MODEL_3D_MIMES[extensionOf(filename)] ?? "application/octet-stream";
2755
+ }
2756
+ //#endregion
2757
+ //#region src/runner/historyReplay.ts
2758
+ const END_TYPES = /* @__PURE__ */ new Set([
2759
+ "execution_success",
2760
+ "execution_error",
2761
+ "execution_interrupted"
2762
+ ]);
2763
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
2764
+ * entry for it: queued, running, or lost */
2765
+ function historyReplay(json, promptId) {
2766
+ const entry = field(json, promptId);
2767
+ if (entry == null) return null;
2768
+ const problems = [];
2769
+ const valid = (raw) => {
2770
+ const res = types$1.PromptRelated_WsMsg(raw);
2771
+ if (!(res instanceof type.errors)) return res;
2772
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
2773
+ return null;
2774
+ };
2775
+ const executed = [];
2776
+ const outputs = field(entry, "outputs");
2777
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
2778
+ const msg = valid({
2779
+ type: "executed",
2780
+ data: {
2781
+ node,
2782
+ output,
2783
+ prompt_id: promptId
2784
+ }
2785
+ });
2786
+ if (msg != null) executed.push(msg);
2787
+ }
2788
+ const status = field(entry, "status");
2789
+ const list = field(status, "messages");
2790
+ let end = null;
2791
+ for (const m of Array.isArray(list) ? list : []) {
2792
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
2793
+ end = valid({
2794
+ type: m[0],
2795
+ data: m[1]
2796
+ });
2797
+ }
2798
+ const statusStr = field(status, "status_str");
2799
+ if (end == null && (status == null || statusStr === "success")) end = valid({
2800
+ type: "execution_success",
2801
+ data: {
2802
+ prompt_id: promptId,
2803
+ timestamp: Date.now()
2804
+ }
2805
+ });
2806
+ return {
2807
+ executed,
2808
+ end,
2809
+ problems
2810
+ };
2811
+ }
2812
+ function field(x, key) {
2813
+ if (typeof x !== "object" || x == null) return null;
2814
+ return Reflect.get(x, key) ?? null;
2815
+ }
2816
+ //#endregion
2817
+ //#region src/utils/log.ts
2818
+ const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
2819
+ const logInfo = (msg) => {
2820
+ if (!isQuiet()) console.log(msg);
2821
+ };
2822
+ const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
2823
+ const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
2824
+ //#endregion
2736
2825
  //#region src/runner/ComfyExecution.ts
2737
2826
  /** paths claimed by in-flight retrievals: two same-second runs on a
2738
2827
  * counter-resetting cloud host compute the same name before either writes.
@@ -2759,6 +2848,9 @@ var ComfyExecution = class {
2759
2848
  this._resolve = resolve;
2760
2849
  });
2761
2850
  this.onPromptRelatedMessage = (msg) => {
2851
+ if (this.ended) return;
2852
+ this.heard();
2853
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
2762
2854
  const graph = this.workflow;
2763
2855
  if (msg.type === "binary_preview_frame") {
2764
2856
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -2789,6 +2881,7 @@ var ComfyExecution = class {
2789
2881
  this.workflow.onExecuting(msg);
2790
2882
  };
2791
2883
  this.onExecutionSuccess = async (_msg) => {
2884
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
2792
2885
  await Promise.all(this.pendingPromises);
2793
2886
  return this._finish({ status: "Success" });
2794
2887
  };
@@ -2802,6 +2895,7 @@ var ComfyExecution = class {
2802
2895
  };
2803
2896
  this.onExecuted = (msg) => {
2804
2897
  const promptNodeID = msg.data.node;
2898
+ this.heardExecuted.add(promptNodeID);
2805
2899
  for (const entry of msg.data.output?.text ?? []) {
2806
2900
  if (typeof entry !== "string") continue;
2807
2901
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -2817,7 +2911,7 @@ var ComfyExecution = class {
2817
2911
  ...out?.video ?? [],
2818
2912
  ...out?.gifs ?? []
2819
2913
  ].filter((f) => f.type !== "input");
2820
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
2914
+ 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) => {
2821
2915
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
2822
2916
  this.videoErrors.push({
2823
2917
  video,
@@ -2832,35 +2926,114 @@ var ComfyExecution = class {
2832
2926
  error: e
2833
2927
  });
2834
2928
  }));
2835
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
2929
+ 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) => {
2836
2930
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
2837
2931
  this.audioErrors.push({
2838
2932
  audio,
2839
2933
  error: e
2840
2934
  });
2841
2935
  }));
2936
+ 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({
2937
+ ...o,
2938
+ format: extensionOf(o.filename)
2939
+ }), (e) => {
2940
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
2941
+ this.models3dErrors.push({
2942
+ model3d,
2943
+ error: e
2944
+ });
2945
+ }));
2842
2946
  };
2843
2947
  this.pendingPromises = [];
2948
+ this.ended = false;
2949
+ this.heardExecuted = /* @__PURE__ */ new Set();
2950
+ this.mayHaveMissedEvents = false;
2951
+ this.historyRetry = {
2952
+ tries: 5,
2953
+ ms: 400
2954
+ };
2955
+ this.retrieveMissedOutputs = async () => {
2956
+ const id = this.data.id;
2957
+ for (let i = 0; i < this.historyRetry.tries; i++) {
2958
+ if (this.host.reconcileOff != null) return;
2959
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
2960
+ try {
2961
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
2962
+ if (replay == null) continue;
2963
+ return this.replayUnheardOutputs(replay);
2964
+ } catch (e) {
2965
+ if (this.host.noteReconcileFailure(e)) return;
2966
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
2967
+ }
2968
+ }
2969
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
2970
+ };
2971
+ this.lastHeardAt = Date.now();
2972
+ this.reconciling = false;
2973
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
2974
+ this.reconcile = async (queued) => {
2975
+ const id = this.data.id;
2976
+ const hostId = this.host.data.id;
2977
+ try {
2978
+ if (this.ended || queued?.has(id) === true) return "waiting";
2979
+ let replay;
2980
+ try {
2981
+ replay = historyReplay(await this.host.fetchHistory(id), id);
2982
+ } catch (e) {
2983
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
2984
+ return "waiting";
2985
+ }
2986
+ if (this.ended) return "waiting";
2987
+ if (replay == null) {
2988
+ if (queued == null) return "waiting";
2989
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
2990
+ logError(`run ${id}: ${reason}; the run fails`);
2991
+ this.ended = true;
2992
+ await this._finish({
2993
+ status: "Failure",
2994
+ error: null,
2995
+ reason
2996
+ });
2997
+ return "lost";
2998
+ }
2999
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3000
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3001
+ this.replayUnheardOutputs(replay);
3002
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3003
+ if (replay.end != null) {
3004
+ this.onPromptRelatedMessage(replay.end);
3005
+ return "history";
3006
+ }
3007
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3008
+ logError(`run ${id}: ${reason}; the run fails`);
3009
+ this.ended = true;
3010
+ await this._finish({
3011
+ status: "Failure",
3012
+ error: null,
3013
+ reason
3014
+ });
3015
+ return "history";
3016
+ } finally {
3017
+ this.reconciling = false;
3018
+ }
3019
+ };
2844
3020
  this.audioErrors = [];
2845
3021
  this.audios = [];
2846
3022
  this.videoErrors = [];
2847
3023
  this.videos = [];
2848
- this.retrieveFile = async (kind, info, promptNodeID) => {
3024
+ this.models3dErrors = [];
3025
+ this.models3d = [];
3026
+ this.retrieveFile = async (info, promptNodeID, mime) => {
2849
3027
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
2850
3028
  const bytes = new Uint8Array(await response.arrayBuffer());
2851
- const mime = mediaMime(info.filename);
2852
- const list = kind === "audio" ? this.audios : this.videos;
2853
3029
  const sf = this.save;
2854
- if (sf == null) {
2855
- list.push({
2856
- nodeId: promptNodeID,
2857
- filename: info.filename,
2858
- mime,
2859
- bytes,
2860
- absPath: null
2861
- });
2862
- return;
2863
- }
3030
+ if (sf == null) return {
3031
+ nodeId: promptNodeID,
3032
+ filename: info.filename,
3033
+ mime,
3034
+ bytes,
3035
+ absPath: null
3036
+ };
2864
3037
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
2865
3038
  const written = await this.encodeAndWrite({
2866
3039
  bytes,
@@ -2872,13 +3045,13 @@ var ComfyExecution = class {
2872
3045
  subfolder: info.subfolder,
2873
3046
  filename: info.filename
2874
3047
  });
2875
- list.push({
3048
+ return {
2876
3049
  nodeId: promptNodeID,
2877
3050
  filename: info.filename,
2878
3051
  mime,
2879
3052
  bytes,
2880
3053
  absPath: written.path
2881
- });
3054
+ };
2882
3055
  };
2883
3056
  this.imageErrors = [];
2884
3057
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -2956,6 +3129,7 @@ var ComfyExecution = class {
2956
3129
  };
2957
3130
  };
2958
3131
  this.onWsImageOutput = (p) => {
3132
+ this.heard();
2959
3133
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
2960
3134
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
2961
3135
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3018,7 +3192,7 @@ var ComfyExecution = class {
3018
3192
  this.onProgress = init.onProgress ?? null;
3019
3193
  this.onPreview = init.onPreview ?? null;
3020
3194
  this.logProgress = init.logProgress ?? false;
3021
- this.host.executions.set(data.id, this);
3195
+ this.host.trackExecution(this);
3022
3196
  this.onCreate();
3023
3197
  }
3024
3198
  get progress() {
@@ -3054,6 +3228,7 @@ var ComfyExecution = class {
3054
3228
  const outputs = [`${this.images.length} image(s)`];
3055
3229
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3056
3230
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3231
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3057
3232
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3058
3233
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3059
3234
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3082,6 +3257,24 @@ var ComfyExecution = class {
3082
3257
  get status() {
3083
3258
  return this.data.status ?? "New";
3084
3259
  }
3260
+ replayUnheardOutputs(replay) {
3261
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3262
+ }
3263
+ heard() {
3264
+ this.lastHeardAt = Date.now();
3265
+ }
3266
+ logReconcileOnce(msg) {
3267
+ if (this.loggedReconcileProblems.has(msg)) return;
3268
+ this.loggedReconcileProblems.add(msg);
3269
+ logError(`run ${this.data.id}: ${msg}`);
3270
+ }
3271
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3272
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3273
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3274
+ beginReconcile(why) {
3275
+ this.reconciling = true;
3276
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3277
+ }
3085
3278
  /** accumulate an output on the prompt; tags from node metadata ride along */
3086
3279
  pushImage(img, promptNodeID) {
3087
3280
  const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
@@ -3100,6 +3293,7 @@ var ComfyExecution = class {
3100
3293
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3101
3294
  * to onWsImageOutput before they get here) */
3102
3295
  onPreviewFrame(p) {
3296
+ this.heard();
3103
3297
  const listener = this.onPreview;
3104
3298
  if (listener == null) return;
3105
3299
  const current = this.workflow.currentExecutingNode;
@@ -3121,6 +3315,7 @@ var ComfyExecution = class {
3121
3315
  }
3122
3316
  /** @internal a live-text frame for one node */
3123
3317
  onProgressText(p) {
3318
+ this.heard();
3124
3319
  this.progressTexts.set(p.nodeId, p.text);
3125
3320
  this.progressText = p.text;
3126
3321
  this.emitProgress();
@@ -3181,14 +3376,6 @@ function styler(open = "", close = "") {
3181
3376
  }
3182
3377
  const ansi = styler();
3183
3378
  //#endregion
3184
- //#region src/utils/log.ts
3185
- const isQuiet = () => process.env.COMFY_TS_QUIET === "1";
3186
- const logInfo = (msg) => {
3187
- if (!isQuiet()) console.log(msg);
3188
- };
3189
- const logError = (msg) => console.error(`[comfy-ts] 🔴 ${msg}`);
3190
- const logSuccess = (msg) => console.log(`[comfy-ts] 🟢 ${msg}`);
3191
- //#endregion
3192
3379
  //#region src/utils/printArkResultInConsole.ts
3193
3380
  const MAX_PRINTED_ERRORS = 10;
3194
3381
  function printArkResultInConsole(res) {
@@ -3877,7 +4064,12 @@ function codegenSDK(opts) {
3877
4064
  p(`INVALID_null: any`);
3878
4065
  p("");
3879
4066
  p("// named slot types: everything an input of that type accepts");
3880
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
4067
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
4068
+ for (const t of slotTypes) {
4069
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
4070
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
4071
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
4072
+ }
3881
4073
  p("");
3882
4074
  p("// enum unions: literal values or an output carrying one");
3883
4075
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -5168,6 +5360,12 @@ var ResilientWebSocketClient = class {
5168
5360
  }
5169
5361
  }, ms);
5170
5362
  }
5363
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5364
+ reconnect() {
5365
+ if (this.permanentlyClosed || this.currentWS == null) return;
5366
+ this.addInfo("closing the socket to reconnect");
5367
+ this.currentWS.close();
5368
+ }
5171
5369
  /** close and stop reconnecting (lets a script exit cleanly) */
5172
5370
  disconnectPermanently() {
5173
5371
  this.permanentlyClosed = true;
@@ -5189,6 +5387,7 @@ var ResilientWebSocketClient = class {
5189
5387
  }
5190
5388
  async connect() {
5191
5389
  this.isOpen = false;
5390
+ this.url = this.options.url();
5192
5391
  const prevWS = this.currentWS;
5193
5392
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
5194
5393
  this.stopHeartbeat();
@@ -6820,10 +7019,17 @@ function diffSchemas(p) {
6820
7019
  }
6821
7020
  //#endregion
6822
7021
  //#region src/host/ComfyHost.ts
6823
- /** the host never came up within ConnectOptions.timeoutMs */
6824
- var ComfyHostUnreachableError = class extends Error {
7022
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
7023
+ var HostRouteUnusableError = class extends Error {
6825
7024
  constructor(..._args) {
6826
7025
  super(..._args);
7026
+ this.name = "HostRouteUnusableError";
7027
+ }
7028
+ };
7029
+ /** the host never came up within ConnectOptions.timeoutMs */
7030
+ var ComfyHostUnreachableError = class extends Error {
7031
+ constructor(..._args2) {
7032
+ super(..._args2);
6827
7033
  this.name = "ComfyHostUnreachableError";
6828
7034
  }
6829
7035
  };
@@ -6996,6 +7202,7 @@ var ComfyHost = class {
6996
7202
  this._connectTimer = null;
6997
7203
  this.disconnect = () => {
6998
7204
  this.clearConnectTimer();
7205
+ this.stopWatchdog();
6999
7206
  this.ws?.disconnectPermanently();
7000
7207
  this.ws = null;
7001
7208
  this._ready = null;
@@ -7015,6 +7222,50 @@ var ComfyHost = class {
7015
7222
  });
7016
7223
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
7017
7224
  };
7225
+ this.fetchReconcileJSON_ = async (route) => {
7226
+ const res = await this.fetch(route);
7227
+ const contentType = res.headers.get("content-type") ?? "";
7228
+ if (res.ok && contentType.includes("json")) return res.json();
7229
+ res.body?.cancel();
7230
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
7231
+ };
7232
+ this.fetchHistory = (promptId) => {
7233
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
7234
+ };
7235
+ this.fetchQueuedPromptIds = async () => {
7236
+ const json = await this.fetchReconcileJSON_("/queue");
7237
+ const ids = /* @__PURE__ */ new Set();
7238
+ for (const key of ["queue_running", "queue_pending"]) {
7239
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
7240
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
7241
+ for (const item of list) {
7242
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
7243
+ ids.add(item[1]);
7244
+ }
7245
+ }
7246
+ return ids;
7247
+ };
7248
+ this.reconcileOff = null;
7249
+ this.fetchQueuedPromptIdsOrNull = async () => {
7250
+ try {
7251
+ return await this.fetchQueuedPromptIds();
7252
+ } catch (e) {
7253
+ if (this.noteReconcileFailure(e)) return null;
7254
+ const msg = extractErrorMessage(e);
7255
+ if (!this._loggedQueueProblems.has(msg)) {
7256
+ this._loggedQueueProblems.add(msg);
7257
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
7258
+ }
7259
+ return null;
7260
+ }
7261
+ };
7262
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
7263
+ this.runSilenceMs = 1e3;
7264
+ this.runSilenceMaxMs = 3e4;
7265
+ this._silenceWaitMs = null;
7266
+ this._lastCheckAt = 0;
7267
+ this._checking = false;
7268
+ this._watchdog = null;
7018
7269
  this.clearQueue = () => {
7019
7270
  return this.postJSON_("/queue", { clear: true });
7020
7271
  };
@@ -7144,6 +7395,7 @@ var ComfyHost = class {
7144
7395
  this.comfySessionId = "temp";
7145
7396
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
7146
7397
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
7398
+ this._socketIsNew = false;
7147
7399
  this.status = null;
7148
7400
  this.lastWsMessageAt = null;
7149
7401
  /** folder where file related to the host config will be cached */
@@ -7249,6 +7501,8 @@ var ComfyHost = class {
7249
7501
  this.ws = new ResilientWebSocketClient({
7250
7502
  onConnectOrReconnect: async () => {
7251
7503
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
7504
+ this._socketIsNew = true;
7505
+ this.reconcileRuns([...this.executions.values()], "reconnect");
7252
7506
  if (this.shouldUseSchemaCache()) try {
7253
7507
  await this.loadSchemaFromCache();
7254
7508
  await this.waitForSession();
@@ -7262,7 +7516,7 @@ var ComfyHost = class {
7262
7516
  this.markReady();
7263
7517
  },
7264
7518
  onMessage: (e) => this.onMessage(e),
7265
- url: () => this.getWSUrl(),
7519
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
7266
7520
  headers: () => this.authHeaders(),
7267
7521
  onTransportDead: (e) => this.markFailed(e),
7268
7522
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -7304,6 +7558,65 @@ var ComfyHost = class {
7304
7558
  });
7305
7559
  return this._schemaFromCache;
7306
7560
  }
7561
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
7562
+ * stop for good, said once), false for a passing failure the caller reports */
7563
+ noteReconcileFailure(e) {
7564
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
7565
+ if (this.reconcileOff == null) {
7566
+ this.reconcileOff = e.message;
7567
+ this.stopWatchdog();
7568
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
7569
+ }
7570
+ return true;
7571
+ }
7572
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
7573
+ trackExecution(execution) {
7574
+ this.executions.set(execution.data.id, execution);
7575
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
7576
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
7577
+ this._watchdog.unref?.();
7578
+ }
7579
+ stopWatchdog() {
7580
+ if (this._watchdog != null) clearInterval(this._watchdog);
7581
+ this._watchdog = null;
7582
+ }
7583
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
7584
+ * quiet node: ask. A run queued behind a talking host is never asked about */
7585
+ watchdogTick() {
7586
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
7587
+ if (this._checking) return;
7588
+ const now = Date.now();
7589
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
7590
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
7591
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
7592
+ if (due.length === 0) return;
7593
+ this._checking = true;
7594
+ this.reconcileRuns(due, "silence").finally(() => {
7595
+ this._checking = false;
7596
+ this._lastCheckAt = Date.now();
7597
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
7598
+ });
7599
+ }
7600
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
7601
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
7602
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
7603
+ * the new socket of the same session. A clean close lets the server end that handler first */
7604
+ async reconcileRuns(runs, why) {
7605
+ if (this.reconcileOff != null) return;
7606
+ const todo = runs.filter((r) => !r.reconciling);
7607
+ if (todo.length === 0) return;
7608
+ for (const r of todo) r.beginReconcile(why);
7609
+ const queued = await this.fetchQueuedPromptIdsOrNull();
7610
+ if (this.reconcileOff != null) {
7611
+ for (const r of todo) r.reconciling = false;
7612
+ return;
7613
+ }
7614
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
7615
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
7616
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
7617
+ this.ws.reconnect();
7618
+ }
7619
+ }
7307
7620
  /** method to either execute or buffer the incoming message */
7308
7621
  routeOrBuffer(prompt_id, msg) {
7309
7622
  this.activePromptID = prompt_id;
@@ -7365,6 +7678,7 @@ var ComfyHost = class {
7365
7678
  }
7366
7679
  onMessage(e) {
7367
7680
  this.lastWsMessageAt = Date.now();
7681
+ this._silenceWaitMs = null;
7368
7682
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
7369
7683
  if (e.data instanceof ArrayBuffer) {
7370
7684
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -7416,10 +7730,12 @@ var ComfyHost = class {
7416
7730
  if (msg.type === "status") {
7417
7731
  if (msg.data.sid) {
7418
7732
  const sidChanged = msg.data.sid !== this.comfySessionId;
7733
+ const socketIsNew = this._socketIsNew;
7734
+ this._socketIsNew = false;
7419
7735
  this.comfySessionId = msg.data.sid;
7420
7736
  this._sessionResolve?.();
7421
7737
  this._sessionResolve = null;
7422
- if (sidChanged) {
7738
+ if (sidChanged || socketIsNew) {
7423
7739
  this._unknownWsEventTypes.clear();
7424
7740
  this._unknownBinaryFrameTypes.clear();
7425
7741
  this.onSession?.(msg.data.sid);