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/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { a as readableStringify, c as renderHttpBase, n as comfyTsPackageDir, o as ComfySchema, r as ComfyTS, s as writeHostFile } from "./exampleAssets-1NHndnNB.js";
3
- import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-CzjaIwZX.js";
2
+ import { a as readableStringify, c as renderHttpBase, n as comfyTsPackageDir, o as ComfySchema, r as ComfyTS, s as writeHostFile } from "./exampleAssets-Duneoq6r.js";
3
+ import { D as readLoraMirror, F as fetchLoraList, H as lmModelName, K as lmTrainedWords, _ as buildLoraMirror, j as writeLoraMirror } from "./schemaDrift-BTxdABHi.js";
4
4
  import { spawn } from "node:child_process";
5
5
  import { constants, homedir } from "node:os";
6
6
  import { fileURLToPath } from "node:url";
@@ -554,14 +554,14 @@ async function main() {
554
554
  }
555
555
  armHopChild();
556
556
  if (cmd === "run") {
557
- const { runRun } = await import("./run-run-Y5ZI48vV.js");
557
+ const { runRun } = await import("./run-run-Cr0L9lCK.js");
558
558
  return runRun(rest);
559
559
  }
560
560
  if (cmd === "serve") {
561
- const { runServe } = await import("./run-serve-CICU_wTL.js");
561
+ const { runServe } = await import("./run-serve---qA7o_m.js");
562
562
  return runServe(rest);
563
563
  }
564
- const { runTui } = await import("./run-tui-CViJXsHL.js");
564
+ const { runTui } = await import("./run-tui-DxXiWo5J.js");
565
565
  return runTui(rest);
566
566
  }
567
567
  console.log(HELP);
@@ -1,4 +1,4 @@
1
- import { X as ansi, a as DefinedWorkflow, at as importSharp, ct as getComfyStorage, dt as logError, ft as logInfo, gt as extractErrorMessage, ht as sha1HexOfString, it as hashArrayBuffer, lt as resolveComfyStorage, mt as statelessRegex, n as diffSchemas, nt as isVideoFilename, ot as isRecord$1, pt as logSuccess, rt as mediaMime, st as bang, t as MODEL_LISTS, ut as isQuiet } from "./schemaDrift-CzjaIwZX.js";
1
+ import { X as ansi, _t as sha1HexOfString, a as DefinedWorkflow, at as mediaMime, ct as isRecord$1, dt as resolveComfyStorage, et as model3dMime, ft as isQuiet, gt as statelessRegex, ht as logSuccess, it as isVideoFilename, lt as bang, mt as logInfo, n as diffSchemas, ot as hashArrayBuffer, pt as logError, rt as extensionOf, st as importSharp, t as MODEL_LISTS, ut as getComfyStorage, vt as extractErrorMessage } from "./schemaDrift-BTxdABHi.js";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { basename, dirname, join } from "pathe";
@@ -695,7 +695,12 @@ function codegenSDK(opts) {
695
695
  p(`INVALID_null: any`);
696
696
  p("");
697
697
  p("// named slot types: everything an input of that type accepts");
698
- for (const t of slotTypes) p(`${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`);
698
+ const slotTypeNames = new Set(slotTypes.map((t) => t.comfyType));
699
+ for (const t of slotTypes) {
700
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`;
701
+ const anyOf = (t.comfyType.includes(",") ? t.comfyType.split(",").map((s) => s.trim()) : []).map((part) => slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`);
702
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(" | ")}`);
703
+ }
699
704
  p("");
700
705
  p("// enum unions: literal values or an output carrying one");
701
706
  for (const t of this.knownUnionByHash.values()) p(`${escapeJSKey(t.unionName)}: Union['${t.unionName}'] | ComfyNodeOutput<'${t.unionName}'>`);
@@ -1003,7 +1008,7 @@ var ComfySchema = class {
1003
1008
  };
1004
1009
  //#endregion
1005
1010
  //#region package.json
1006
- var version = "2.22.0";
1011
+ var version = "2.23.0";
1007
1012
  //#endregion
1008
1013
  //#region src/litegraph/LiteGraphLinkID.ts
1009
1014
  const asLiteGraphLinkID = (id) => id;
@@ -2495,13 +2500,14 @@ var ComfyNode = class ComfyNode {
2495
2500
  throw new Error(`🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`);
2496
2501
  }
2497
2502
  _getOutputForTypeOrCrash(type) {
2498
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2503
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2504
+ if (i == null) throw new Error(`🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`);
2499
2505
  const val = this.outputs[i.outKey];
2500
2506
  if (val instanceof ComfyNodeOutput) return val;
2501
2507
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2502
2508
  }
2503
2509
  _getOutputForTypeOrNull(type) {
2504
- const i = this.$schema.outputs.find((i) => i.typeName === type);
2510
+ const i = this.$schema.outputs.find((i) => slotTypeAccepts(type, i.typeName));
2505
2511
  if (i == null) return null;
2506
2512
  const val = this.outputs[i.outKey];
2507
2513
  if (val == null) return null;
@@ -2509,6 +2515,11 @@ var ComfyNode = class ComfyNode {
2509
2515
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`);
2510
2516
  }
2511
2517
  };
2518
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
2519
+ function slotTypeAccepts(inputType, outputType) {
2520
+ if (inputType === outputType) return true;
2521
+ return inputType.includes(",") && inputType.split(",").some((part) => part.trim() === outputType);
2522
+ }
2512
2523
  //#endregion
2513
2524
  //#region src/host/ComfyWorkflowBuilder.ts
2514
2525
  var ComfyWorkflowBuilder = class {
@@ -2898,6 +2909,7 @@ const types$1 = scope({
2898
2909
  "audio?": "ComfyImageInfo[]",
2899
2910
  "video?": "ComfyImageInfo[]",
2900
2911
  "gifs?": "ComfyImageInfo[]",
2912
+ "3d?": "ComfyImageInfo[]",
2901
2913
  "text?": "unknown[]"
2902
2914
  },
2903
2915
  WsMsgExecuted: {
@@ -3192,6 +3204,66 @@ var MediaImage = class MediaImage {
3192
3204
  }
3193
3205
  };
3194
3206
  //#endregion
3207
+ //#region src/runner/historyReplay.ts
3208
+ const END_TYPES = /* @__PURE__ */ new Set([
3209
+ "execution_success",
3210
+ "execution_error",
3211
+ "execution_interrupted"
3212
+ ]);
3213
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
3214
+ * entry for it: queued, running, or lost */
3215
+ function historyReplay(json, promptId) {
3216
+ const entry = field(json, promptId);
3217
+ if (entry == null) return null;
3218
+ const problems = [];
3219
+ const valid = (raw) => {
3220
+ const res = types$1.PromptRelated_WsMsg(raw);
3221
+ if (!(res instanceof type.errors)) return res;
3222
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`);
3223
+ return null;
3224
+ };
3225
+ const executed = [];
3226
+ const outputs = field(entry, "outputs");
3227
+ if (typeof outputs === "object" && outputs != null) for (const [node, output] of Object.entries(outputs)) {
3228
+ const msg = valid({
3229
+ type: "executed",
3230
+ data: {
3231
+ node,
3232
+ output,
3233
+ prompt_id: promptId
3234
+ }
3235
+ });
3236
+ if (msg != null) executed.push(msg);
3237
+ }
3238
+ const status = field(entry, "status");
3239
+ const list = field(status, "messages");
3240
+ let end = null;
3241
+ for (const m of Array.isArray(list) ? list : []) {
3242
+ if (!Array.isArray(m) || typeof m[0] !== "string" || !END_TYPES.has(m[0])) continue;
3243
+ end = valid({
3244
+ type: m[0],
3245
+ data: m[1]
3246
+ });
3247
+ }
3248
+ const statusStr = field(status, "status_str");
3249
+ if (end == null && (status == null || statusStr === "success")) end = valid({
3250
+ type: "execution_success",
3251
+ data: {
3252
+ prompt_id: promptId,
3253
+ timestamp: Date.now()
3254
+ }
3255
+ });
3256
+ return {
3257
+ executed,
3258
+ end,
3259
+ problems
3260
+ };
3261
+ }
3262
+ function field(x, key) {
3263
+ if (typeof x !== "object" || x == null) return null;
3264
+ return Reflect.get(x, key) ?? null;
3265
+ }
3266
+ //#endregion
3195
3267
  //#region src/runner/ComfyExecution.ts
3196
3268
  /** paths claimed by in-flight retrievals: two same-second runs on a
3197
3269
  * counter-resetting cloud host compute the same name before either writes.
@@ -3218,6 +3290,9 @@ var ComfyExecution = class {
3218
3290
  this._resolve = resolve;
3219
3291
  });
3220
3292
  this.onPromptRelatedMessage = (msg) => {
3293
+ if (this.ended) return;
3294
+ this.heard();
3295
+ if (msg.type === "execution_success" || msg.type === "execution_error" || msg.type === "execution_interrupted") this.ended = true;
3221
3296
  const graph = this.workflow;
3222
3297
  if (msg.type === "binary_preview_frame") {
3223
3298
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({
@@ -3248,6 +3323,7 @@ var ComfyExecution = class {
3248
3323
  this.workflow.onExecuting(msg);
3249
3324
  };
3250
3325
  this.onExecutionSuccess = async (_msg) => {
3326
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs();
3251
3327
  await Promise.all(this.pendingPromises);
3252
3328
  return this._finish({ status: "Success" });
3253
3329
  };
@@ -3261,6 +3337,7 @@ var ComfyExecution = class {
3261
3337
  };
3262
3338
  this.onExecuted = (msg) => {
3263
3339
  const promptNodeID = msg.data.node;
3340
+ this.heardExecuted.add(promptNodeID);
3264
3341
  for (const entry of msg.data.output?.text ?? []) {
3265
3342
  if (typeof entry !== "string") continue;
3266
3343
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null;
@@ -3276,7 +3353,7 @@ var ComfyExecution = class {
3276
3353
  ...out?.video ?? [],
3277
3354
  ...out?.gifs ?? []
3278
3355
  ].filter((f) => f.type !== "input");
3279
- for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile("video", video, promptNodeID).catch((e) => {
3356
+ for (const video of listed.filter((f) => isVideoFilename(f.filename))) this.pendingPromises.push(this.retrieveFile(video, promptNodeID, mediaMime(video.filename)).then((o) => void this.videos.push(o), (e) => {
3280
3357
  console.error(`🔴 failed to retrieve ${video.filename}:`, e);
3281
3358
  this.videoErrors.push({
3282
3359
  video,
@@ -3291,35 +3368,114 @@ var ComfyExecution = class {
3291
3368
  error: e
3292
3369
  });
3293
3370
  }));
3294
- for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile("audio", audio, promptNodeID).catch((e) => {
3371
+ for (const audio of msg.data.output?.audio ?? []) this.pendingPromises.push(this.retrieveFile(audio, promptNodeID, mediaMime(audio.filename)).then((o) => void this.audios.push(o), (e) => {
3295
3372
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e);
3296
3373
  this.audioErrors.push({
3297
3374
  audio,
3298
3375
  error: e
3299
3376
  });
3300
3377
  }));
3378
+ for (const model3d of (out?.["3d"] ?? []).filter((f) => f.type !== "input")) this.pendingPromises.push(this.retrieveFile(model3d, promptNodeID, model3dMime(model3d.filename)).then((o) => void this.models3d.push({
3379
+ ...o,
3380
+ format: extensionOf(o.filename)
3381
+ }), (e) => {
3382
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e);
3383
+ this.models3dErrors.push({
3384
+ model3d,
3385
+ error: e
3386
+ });
3387
+ }));
3301
3388
  };
3302
3389
  this.pendingPromises = [];
3390
+ this.ended = false;
3391
+ this.heardExecuted = /* @__PURE__ */ new Set();
3392
+ this.mayHaveMissedEvents = false;
3393
+ this.historyRetry = {
3394
+ tries: 5,
3395
+ ms: 400
3396
+ };
3397
+ this.retrieveMissedOutputs = async () => {
3398
+ const id = this.data.id;
3399
+ for (let i = 0; i < this.historyRetry.tries; i++) {
3400
+ if (this.host.reconcileOff != null) return;
3401
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms));
3402
+ try {
3403
+ const replay = historyReplay(await this.host.fetchHistory(id), id);
3404
+ if (replay == null) continue;
3405
+ return this.replayUnheardOutputs(replay);
3406
+ } catch (e) {
3407
+ if (this.host.noteReconcileFailure(e)) return;
3408
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`);
3409
+ }
3410
+ }
3411
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`);
3412
+ };
3413
+ this.lastHeardAt = Date.now();
3414
+ this.reconciling = false;
3415
+ this.loggedReconcileProblems = /* @__PURE__ */ new Set();
3416
+ this.reconcile = async (queued) => {
3417
+ const id = this.data.id;
3418
+ const hostId = this.host.data.id;
3419
+ try {
3420
+ if (this.ended || queued?.has(id) === true) return "waiting";
3421
+ let replay;
3422
+ try {
3423
+ replay = historyReplay(await this.host.fetchHistory(id), id);
3424
+ } catch (e) {
3425
+ if (!this.host.noteReconcileFailure(e)) this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`);
3426
+ return "waiting";
3427
+ }
3428
+ if (this.ended) return "waiting";
3429
+ if (replay == null) {
3430
+ if (queued == null) return "waiting";
3431
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`;
3432
+ logError(`run ${id}: ${reason}; the run fails`);
3433
+ this.ended = true;
3434
+ await this._finish({
3435
+ status: "Failure",
3436
+ error: null,
3437
+ reason
3438
+ });
3439
+ return "lost";
3440
+ }
3441
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`);
3442
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`);
3443
+ this.replayUnheardOutputs(replay);
3444
+ if (this.ephemeral) logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`);
3445
+ if (replay.end != null) {
3446
+ this.onPromptRelatedMessage(replay.end);
3447
+ return "history";
3448
+ }
3449
+ const reason = `its history entry on host '${hostId}' carries no end message`;
3450
+ logError(`run ${id}: ${reason}; the run fails`);
3451
+ this.ended = true;
3452
+ await this._finish({
3453
+ status: "Failure",
3454
+ error: null,
3455
+ reason
3456
+ });
3457
+ return "history";
3458
+ } finally {
3459
+ this.reconciling = false;
3460
+ }
3461
+ };
3303
3462
  this.audioErrors = [];
3304
3463
  this.audios = [];
3305
3464
  this.videoErrors = [];
3306
3465
  this.videos = [];
3307
- this.retrieveFile = async (kind, info, promptNodeID) => {
3466
+ this.models3dErrors = [];
3467
+ this.models3d = [];
3468
+ this.retrieveFile = async (info, promptNodeID, mime) => {
3308
3469
  const response = await this.host.fetchFile("/view?" + new URLSearchParams(info).toString());
3309
3470
  const bytes = new Uint8Array(await response.arrayBuffer());
3310
- const mime = mediaMime(info.filename);
3311
- const list = kind === "audio" ? this.audios : this.videos;
3312
3471
  const sf = this.save;
3313
- if (sf == null) {
3314
- list.push({
3315
- nodeId: promptNodeID,
3316
- filename: info.filename,
3317
- mime,
3318
- bytes,
3319
- absPath: null
3320
- });
3321
- return;
3322
- }
3472
+ if (sf == null) return {
3473
+ nodeId: promptNodeID,
3474
+ filename: info.filename,
3475
+ mime,
3476
+ bytes,
3477
+ absPath: null
3478
+ };
3323
3479
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs["filename_prefix"];
3324
3480
  const written = await this.encodeAndWrite({
3325
3481
  bytes,
@@ -3331,13 +3487,13 @@ var ComfyExecution = class {
3331
3487
  subfolder: info.subfolder,
3332
3488
  filename: info.filename
3333
3489
  });
3334
- list.push({
3490
+ return {
3335
3491
  nodeId: promptNodeID,
3336
3492
  filename: info.filename,
3337
3493
  mime,
3338
3494
  bytes,
3339
3495
  absPath: written.path
3340
- });
3496
+ };
3341
3497
  };
3342
3498
  this.imageErrors = [];
3343
3499
  this.retrieveImage = async (comfyImageInfo, promptNodeID) => {
@@ -3415,6 +3571,7 @@ var ComfyExecution = class {
3415
3571
  };
3416
3572
  };
3417
3573
  this.onWsImageOutput = (p) => {
3574
+ this.heard();
3418
3575
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null;
3419
3576
  this.pendingPromises.push(this.storeWsImage(p, promptNodeID).catch((e) => {
3420
3577
  console.error(`🔴 failed to store a SaveImageWebsocket output:`, e);
@@ -3477,7 +3634,7 @@ var ComfyExecution = class {
3477
3634
  this.onProgress = init.onProgress ?? null;
3478
3635
  this.onPreview = init.onPreview ?? null;
3479
3636
  this.logProgress = init.logProgress ?? false;
3480
- this.host.executions.set(data.id, this);
3637
+ this.host.trackExecution(this);
3481
3638
  this.onCreate();
3482
3639
  }
3483
3640
  get progress() {
@@ -3513,6 +3670,7 @@ var ComfyExecution = class {
3513
3670
  const outputs = [`${this.images.length} image(s)`];
3514
3671
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`);
3515
3672
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`);
3673
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`);
3516
3674
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`);
3517
3675
  const line = `${this.status === "Failure" ? "🔴" : "🟢"} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1e3).toFixed(1)}s · ${outputs.join(" · ")}`;
3518
3676
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`);
@@ -3541,6 +3699,24 @@ var ComfyExecution = class {
3541
3699
  get status() {
3542
3700
  return this.data.status ?? "New";
3543
3701
  }
3702
+ replayUnheardOutputs(replay) {
3703
+ for (const msg of replay.executed) if (msg.type === "executed" && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg);
3704
+ }
3705
+ heard() {
3706
+ this.lastHeardAt = Date.now();
3707
+ }
3708
+ logReconcileOnce(msg) {
3709
+ if (this.loggedReconcileProblems.has(msg)) return;
3710
+ this.loggedReconcileProblems.add(msg);
3711
+ logError(`run ${this.data.id}: ${msg}`);
3712
+ }
3713
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
3714
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
3715
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
3716
+ beginReconcile(why) {
3717
+ this.reconciling = true;
3718
+ if (why === "reconnect") this.mayHaveMissedEvents = true;
3719
+ }
3544
3720
  /** accumulate an output on the prompt; tags from node metadata ride along */
3545
3721
  pushImage(img, promptNodeID) {
3546
3722
  const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null;
@@ -3559,6 +3735,7 @@ var ComfyExecution = class {
3559
3735
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
3560
3736
  * to onWsImageOutput before they get here) */
3561
3737
  onPreviewFrame(p) {
3738
+ this.heard();
3562
3739
  const listener = this.onPreview;
3563
3740
  if (listener == null) return;
3564
3741
  const current = this.workflow.currentExecutingNode;
@@ -3580,6 +3757,7 @@ var ComfyExecution = class {
3580
3757
  }
3581
3758
  /** @internal a live-text frame for one node */
3582
3759
  onProgressText(p) {
3760
+ this.heard();
3583
3761
  this.progressTexts.set(p.nodeId, p.text);
3584
3762
  this.progressText = p.text;
3585
3763
  this.emitProgress();
@@ -4839,6 +5017,12 @@ var ResilientWebSocketClient = class {
4839
5017
  }
4840
5018
  }, ms);
4841
5019
  }
5020
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
5021
+ reconnect() {
5022
+ if (this.permanentlyClosed || this.currentWS == null) return;
5023
+ this.addInfo("closing the socket to reconnect");
5024
+ this.currentWS.close();
5025
+ }
4842
5026
  /** close and stop reconnecting (lets a script exit cleanly) */
4843
5027
  disconnectPermanently() {
4844
5028
  this.permanentlyClosed = true;
@@ -4860,6 +5044,7 @@ var ResilientWebSocketClient = class {
4860
5044
  }
4861
5045
  async connect() {
4862
5046
  this.isOpen = false;
5047
+ this.url = this.options.url();
4863
5048
  const prevWS = this.currentWS;
4864
5049
  if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
4865
5050
  this.stopHeartbeat();
@@ -4929,10 +5114,17 @@ var ResilientWebSocketClient = class {
4929
5114
  };
4930
5115
  //#endregion
4931
5116
  //#region src/host/ComfyHost.ts
4932
- /** the host never came up within ConnectOptions.timeoutMs */
4933
- var ComfyHostUnreachableError = class extends Error {
5117
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
5118
+ var HostRouteUnusableError = class extends Error {
4934
5119
  constructor(..._args) {
4935
5120
  super(..._args);
5121
+ this.name = "HostRouteUnusableError";
5122
+ }
5123
+ };
5124
+ /** the host never came up within ConnectOptions.timeoutMs */
5125
+ var ComfyHostUnreachableError = class extends Error {
5126
+ constructor(..._args2) {
5127
+ super(..._args2);
4936
5128
  this.name = "ComfyHostUnreachableError";
4937
5129
  }
4938
5130
  };
@@ -5105,6 +5297,7 @@ var ComfyHost = class {
5105
5297
  this._connectTimer = null;
5106
5298
  this.disconnect = () => {
5107
5299
  this.clearConnectTimer();
5300
+ this.stopWatchdog();
5108
5301
  this.ws?.disconnectPermanently();
5109
5302
  this.ws = null;
5110
5303
  this._ready = null;
@@ -5124,6 +5317,50 @@ var ComfyHost = class {
5124
5317
  });
5125
5318
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`);
5126
5319
  };
5320
+ this.fetchReconcileJSON_ = async (route) => {
5321
+ const res = await this.fetch(route);
5322
+ const contentType = res.headers.get("content-type") ?? "";
5323
+ if (res.ok && contentType.includes("json")) return res.json();
5324
+ res.body?.cancel();
5325
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || "no content-type"}`);
5326
+ };
5327
+ this.fetchHistory = (promptId) => {
5328
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`);
5329
+ };
5330
+ this.fetchQueuedPromptIds = async () => {
5331
+ const json = await this.fetchReconcileJSON_("/queue");
5332
+ const ids = /* @__PURE__ */ new Set();
5333
+ for (const key of ["queue_running", "queue_pending"]) {
5334
+ const list = typeof json === "object" && json != null ? Reflect.get(json, key) : null;
5335
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`);
5336
+ for (const item of list) {
5337
+ if (!Array.isArray(item) || typeof item[1] !== "string") throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`);
5338
+ ids.add(item[1]);
5339
+ }
5340
+ }
5341
+ return ids;
5342
+ };
5343
+ this.reconcileOff = null;
5344
+ this.fetchQueuedPromptIdsOrNull = async () => {
5345
+ try {
5346
+ return await this.fetchQueuedPromptIds();
5347
+ } catch (e) {
5348
+ if (this.noteReconcileFailure(e)) return null;
5349
+ const msg = extractErrorMessage(e);
5350
+ if (!this._loggedQueueProblems.has(msg)) {
5351
+ this._loggedQueueProblems.add(msg);
5352
+ logError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`);
5353
+ }
5354
+ return null;
5355
+ }
5356
+ };
5357
+ this._loggedQueueProblems = /* @__PURE__ */ new Set();
5358
+ this.runSilenceMs = 1e3;
5359
+ this.runSilenceMaxMs = 3e4;
5360
+ this._silenceWaitMs = null;
5361
+ this._lastCheckAt = 0;
5362
+ this._checking = false;
5363
+ this._watchdog = null;
5127
5364
  this.clearQueue = () => {
5128
5365
  return this.postJSON_("/queue", { clear: true });
5129
5366
  };
@@ -5253,6 +5490,7 @@ var ComfyHost = class {
5253
5490
  this.comfySessionId = "temp";
5254
5491
  this._unknownBinaryFrameTypes = /* @__PURE__ */ new Set();
5255
5492
  this._unknownWsEventTypes = /* @__PURE__ */ new Set();
5493
+ this._socketIsNew = false;
5256
5494
  this.status = null;
5257
5495
  this.lastWsMessageAt = null;
5258
5496
  /** folder where file related to the host config will be cached */
@@ -5358,6 +5596,8 @@ var ComfyHost = class {
5358
5596
  this.ws = new ResilientWebSocketClient({
5359
5597
  onConnectOrReconnect: async () => {
5360
5598
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`);
5599
+ this._socketIsNew = true;
5600
+ this.reconcileRuns([...this.executions.values()], "reconnect");
5361
5601
  if (this.shouldUseSchemaCache()) try {
5362
5602
  await this.loadSchemaFromCache();
5363
5603
  await this.waitForSession();
@@ -5371,7 +5611,7 @@ var ComfyHost = class {
5371
5611
  this.markReady();
5372
5612
  },
5373
5613
  onMessage: (e) => this.onMessage(e),
5374
- url: () => this.getWSUrl(),
5614
+ url: () => this.comfySessionId === "temp" ? this.getWSUrl() : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
5375
5615
  headers: () => this.authHeaders(),
5376
5616
  onTransportDead: (e) => this.markFailed(e),
5377
5617
  onFirstConnectFailed: (e) => this.markFailed(new ComfyHostUnreachableError(`host '${this.data.id}' is not reachable at ${this.getWSUrl()} — ${extractErrorMessage(e)}. Is ComfyUI running there ?`)),
@@ -5413,6 +5653,65 @@ var ComfyHost = class {
5413
5653
  });
5414
5654
  return this._schemaFromCache;
5415
5655
  }
5656
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
5657
+ * stop for good, said once), false for a passing failure the caller reports */
5658
+ noteReconcileFailure(e) {
5659
+ if (!(e instanceof Error) || e.name !== "HostRouteUnusableError") return false;
5660
+ if (this.reconcileOff == null) {
5661
+ this.reconcileOff = e.message;
5662
+ this.stopWatchdog();
5663
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`);
5664
+ }
5665
+ return true;
5666
+ }
5667
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
5668
+ trackExecution(execution) {
5669
+ this.executions.set(execution.data.id, execution);
5670
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return;
5671
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs));
5672
+ this._watchdog.unref?.();
5673
+ }
5674
+ stopWatchdog() {
5675
+ if (this._watchdog != null) clearInterval(this._watchdog);
5676
+ this._watchdog = null;
5677
+ }
5678
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
5679
+ * quiet node: ask. A run queued behind a talking host is never asked about */
5680
+ watchdogTick() {
5681
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog();
5682
+ if (this._checking) return;
5683
+ const now = Date.now();
5684
+ const wait = this._silenceWaitMs ?? this.runSilenceMs;
5685
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return;
5686
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs);
5687
+ if (due.length === 0) return;
5688
+ this._checking = true;
5689
+ this.reconcileRuns(due, "silence").finally(() => {
5690
+ this._checking = false;
5691
+ this._lastCheckAt = Date.now();
5692
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs);
5693
+ });
5694
+ }
5695
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
5696
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
5697
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
5698
+ * the new socket of the same session. A clean close lets the server end that handler first */
5699
+ async reconcileRuns(runs, why) {
5700
+ if (this.reconcileOff != null) return;
5701
+ const todo = runs.filter((r) => !r.reconciling);
5702
+ if (todo.length === 0) return;
5703
+ for (const r of todo) r.beginReconcile(why);
5704
+ const queued = await this.fetchQueuedPromptIdsOrNull();
5705
+ if (this.reconcileOff != null) {
5706
+ for (const r of todo) r.reconciling = false;
5707
+ return;
5708
+ }
5709
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)));
5710
+ if (why === "silence" && verdicts.includes("history") && this.ws?.isOpen === true) {
5711
+ logError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`);
5712
+ this.ws.reconnect();
5713
+ }
5714
+ }
5416
5715
  /** method to either execute or buffer the incoming message */
5417
5716
  routeOrBuffer(prompt_id, msg) {
5418
5717
  this.activePromptID = prompt_id;
@@ -5474,6 +5773,7 @@ var ComfyHost = class {
5474
5773
  }
5475
5774
  onMessage(e) {
5476
5775
  this.lastWsMessageAt = Date.now();
5776
+ this._silenceWaitMs = null;
5477
5777
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e);
5478
5778
  if (e.data instanceof ArrayBuffer) {
5479
5779
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data);
@@ -5525,10 +5825,12 @@ var ComfyHost = class {
5525
5825
  if (msg.type === "status") {
5526
5826
  if (msg.data.sid) {
5527
5827
  const sidChanged = msg.data.sid !== this.comfySessionId;
5828
+ const socketIsNew = this._socketIsNew;
5829
+ this._socketIsNew = false;
5528
5830
  this.comfySessionId = msg.data.sid;
5529
5831
  this._sessionResolve?.();
5530
5832
  this._sessionResolve = null;
5531
- if (sidChanged) {
5833
+ if (sidChanged || socketIsNew) {
5532
5834
  this._unknownWsEventTypes.clear();
5533
5835
  this._unknownBinaryFrameTypes.clear();
5534
5836
  this.onSession?.(msg.data.sid);
@@ -6305,4 +6607,4 @@ function comfyTsPackageDir(moduleUrl = import.meta.url) {
6305
6607
  //#endregion
6306
6608
  export { readableStringify as a, renderHttpBase as c, settingsPathFor as i, comfyTsPackageDir as n, ComfySchema as o, ComfyTS as r, writeHostFile as s, bundledExamplesDir as t };
6307
6609
 
6308
- //# sourceMappingURL=exampleAssets-1NHndnNB.js.map
6610
+ //# sourceMappingURL=exampleAssets-Duneoq6r.js.map