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
@@ -76,6 +76,7 @@ import {
76
76
  import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
77
77
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
78
78
  import { DEFAULT_MEDIA_EXTENSIONS, MEDIA_KINDS, type MediaKind } from 'src/runner/mediaKinds.ts'
79
+ import { MODEL_3D_MIMES } from 'src/runner/outputs3d.ts'
79
80
  import type {
80
81
  ChoiceOptionLook,
81
82
  ChoiceVar,
@@ -106,6 +107,8 @@ export type ServeExecution = {
106
107
  audios?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]
107
108
  /** video files (SaveVideo, SaveWEBM, VHS_VideoCombine), same shape as audios */
108
109
  videos?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]
110
+ /** 3D files (SaveGLB, SaveGaussianSplat, SavePointCloud), the same shape plus `format` */
111
+ models3d?: { absPath: string | null; filename: string; mime: string; format: string; bytes: Uint8Array }[]
109
112
  data: { id: string; error?: unknown }
110
113
  /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
111
114
  progressGlobal?: { percent: number }
@@ -271,6 +274,7 @@ const CONTENT_TYPES: Record<string, string> = {
271
274
  '.m4a': 'audio/mp4',
272
275
  '.json': 'application/json',
273
276
  '.txt': 'text/plain',
277
+ ...Object.fromEntries(Object.entries(MODEL_3D_MIMES).map(([ext, mime]) => [`.${ext}`, mime])),
274
278
  }
275
279
 
276
280
  /** magic-byte sniff for the preview proxy — fetchLoraPreviewBytes already guarantees an image */
@@ -352,7 +356,7 @@ const USAGE = [
352
356
  'DELETE /drafts/<module>/<draft> — delete that draft file',
353
357
  'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
354
358
  'POST /upload with {"name","dataBase64"} — store a browser file for an image, audio or video var',
355
- 'GET /images|audio|video/<promptId>/<ix> — an output kept in memory (saving off)',
359
+ 'GET /images|audio|video|model3d/<promptId>/<ix> — an output kept in memory (saving off)',
356
360
  'GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)',
357
361
  'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',
358
362
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
@@ -510,6 +514,8 @@ export class ServeApp {
510
514
  return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`)
511
515
  if (segs[0] === 'video' && segs.length === 3 && segs[1] != null && segs[2] != null)
512
516
  return this.replyMemoryImage(`video/${segs[1]}/${segs[2]}`)
517
+ if (segs[0] === 'model3d' && segs.length === 3 && segs[1] != null && segs[2] != null)
518
+ return this.replyMemoryImage(`model3d/${segs[1]}/${segs[2]}`)
513
519
  if (segs[0] === 'results' && segs.length === 1)
514
520
  return json(200, { runs: this.kept.list(), memory: this.kept.usage() })
515
521
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
@@ -1696,6 +1702,8 @@ export class ServeApp {
1696
1702
  if (audios.length > 0) produced.push(`${audios.length} audio(s)`)
1697
1703
  const videos = execution.videos ?? []
1698
1704
  if (videos.length > 0) produced.push(`${videos.length} video(s)`)
1705
+ const models3d = execution.models3d ?? []
1706
+ if (models3d.length > 0) produced.push(`${models3d.length} 3d model(s)`)
1699
1707
  if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)
1700
1708
  console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)
1701
1709
 
@@ -1721,6 +1729,12 @@ export class ServeApp {
1721
1729
  blobs.push(this.memoryBlob(key, a.bytes, a.filename))
1722
1730
  return key
1723
1731
  })
1732
+ const model3dKeys = models3d.map((m, ix) => {
1733
+ if (m.absPath != null) return null
1734
+ const key = `model3d/${execution.data.id}/${ix}`
1735
+ blobs.push(this.memoryBlob(key, m.bytes, m.filename))
1736
+ return key
1737
+ })
1724
1738
  // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and handle() decodes
1725
1739
  // per segment, so the lookup gets the raw key back
1726
1740
  const memoryUrl = (route: string, key: string): string =>
@@ -1766,9 +1780,20 @@ export class ServeApp {
1766
1780
  absPath: a.absPath,
1767
1781
  }
1768
1782
  }),
1783
+ models3d: models3d.map((m, ix) => {
1784
+ const key = model3dKeys[ix]
1785
+ return {
1786
+ filename: m.filename,
1787
+ mime: m.mime,
1788
+ format: m.format,
1789
+ size: m.bytes.byteLength,
1790
+ url: m.absPath != null ? this.outputUrl(m.absPath) : key != null ? memoryUrl('model3d', key) : null,
1791
+ absPath: m.absPath,
1792
+ }
1793
+ }),
1769
1794
  ...(mod.dw.spec.widgets != null && mod.dw.spec.widgets.length > 0 ? { widgets: mod.dw.spec.widgets } : {}),
1770
1795
  }
1771
- this.kept.add({ record, imageKeys, audioKeys, videoKeys, blobs })
1796
+ this.kept.add({ record, imageKeys, audioKeys, videoKeys, model3dKeys, blobs })
1772
1797
 
1773
1798
  // Accept: image/* → first image's bytes directly (curl -o, <img src>)
1774
1799
  const first = execution.images[0]
@@ -7,6 +7,8 @@ import type { OutputWidget } from 'src/vars/outputWidgets.ts'
7
7
  /** `tags`: the save node's metadata tags, which output widgets read (absent on older records) */
8
8
  export type RunOutput = { filename: string; url: string | null; absPath: string | null; tags?: string[] }
9
9
  export type RunAudioOutput = RunOutput & { mime: string }
10
+ /** a mesh, point cloud or splat: `format` the lowercase extension, `size` in bytes */
11
+ export type RunModel3DOutput = RunAudioOutput & { format: string; size: number }
10
12
 
11
13
  /** the run reply `POST /generate` answers, and what `GET /results` lists */
12
14
  export type RunRecord = {
@@ -24,6 +26,8 @@ export type RunRecord = {
24
26
  audios: RunAudioOutput[]
25
27
  /** absent on a record from an older server */
26
28
  videos?: RunAudioOutput[]
29
+ /** absent on a record from an older server */
30
+ models3d?: RunModel3DOutput[]
27
31
  /** the module's output widgets at run time, so a kept result draws them after a reload */
28
32
  widgets?: OutputWidget[]
29
33
  }
@@ -44,6 +48,7 @@ type Kept = {
44
48
  imageKeys: (string | null)[]
45
49
  audioKeys: (string | null)[]
46
50
  videoKeys: (string | null)[]
51
+ model3dKeys: (string | null)[]
47
52
  }
48
53
 
49
54
  export class ResultHistory {
@@ -60,6 +65,7 @@ export class ResultHistory {
60
65
  imageKeys: (string | null)[]
61
66
  audioKeys: (string | null)[]
62
67
  videoKeys?: (string | null)[]
68
+ model3dKeys?: (string | null)[]
63
69
  blobs: KeptBlob[]
64
70
  }): void {
65
71
  this.remove(p.record.promptId)
@@ -67,7 +73,13 @@ export class ResultHistory {
67
73
  this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType })
68
74
  this.used += b.bytes.byteLength
69
75
  }
70
- const kept = { record: p.record, imageKeys: p.imageKeys, audioKeys: p.audioKeys, videoKeys: p.videoKeys ?? [] }
76
+ const kept = {
77
+ record: p.record,
78
+ imageKeys: p.imageKeys,
79
+ audioKeys: p.audioKeys,
80
+ videoKeys: p.videoKeys ?? [],
81
+ model3dKeys: p.model3dKeys ?? [],
82
+ }
71
83
  this.runs = [kept, ...this.runs]
72
84
  for (const dropped of this.runs.slice(KEPT_RUNS)) this.freeRun(dropped)
73
85
  this.runs = this.runs.slice(0, KEPT_RUNS)
@@ -85,6 +97,7 @@ export class ResultHistory {
85
97
  images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
86
98
  audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
87
99
  videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),
100
+ models3d: (k.record.models3d ?? []).map((a, ix) => this.withLiveUrl(a, k.model3dKeys[ix])),
88
101
  }))
89
102
  }
90
103
 
@@ -116,7 +129,7 @@ export class ResultHistory {
116
129
  }
117
130
 
118
131
  private freeRun(k: Kept): void {
119
- for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys]) {
132
+ for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys, ...k.model3dKeys]) {
120
133
  if (key == null) continue
121
134
  const b = this.blobs.get(key)
122
135
  if (b == null) continue
@@ -139,8 +152,13 @@ export class ResultHistory {
139
152
  const live = (keys: (string | null)[]): boolean => keys.some((key) => key == null || this.blobs.has(key))
140
153
  const hasText = k.record.texts.length > 0
141
154
  const hasNothing =
142
- k.record.images.length === 0 && k.record.audios.length === 0 && (k.record.videos ?? []).length === 0
143
- return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys)
155
+ k.record.images.length === 0 &&
156
+ k.record.audios.length === 0 &&
157
+ (k.record.videos ?? []).length === 0 &&
158
+ (k.record.models3d ?? []).length === 0
159
+ return (
160
+ hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys) || live(k.model3dKeys)
161
+ )
144
162
  })
145
163
  }
146
164
  }
@@ -13,6 +13,24 @@ export function thumbUrl(abs: string, width = 160): string {
13
13
  return `/thumb?src=${encodeURIComponent(abs)}&w=${width}`
14
14
  }
15
15
 
16
+ /** Bun's own image pipeline when the server runs on Bun, sharp only under Node (the cli runs on
17
+ * both). Both read the EXIF orientation */
18
+ async function webpThumb(path: string, width: number): Promise<Uint8Array> {
19
+ if (typeof Bun !== 'undefined')
20
+ return new Bun.Image(path)
21
+ .resize(width, width, { fit: 'inside', withoutEnlargement: true })
22
+ .webp({ quality: 78 })
23
+ .bytes()
24
+ const sharp = await importSharp('a thumbnail')
25
+ return new Uint8Array(
26
+ await sharp(path)
27
+ .rotate()
28
+ .resize({ width, height: width, fit: 'inside', withoutEnlargement: true })
29
+ .webp({ quality: 78 })
30
+ .toBuffer(),
31
+ )
32
+ }
33
+
16
34
  const MAX_WIDTH = 640
17
35
  const MAX_CACHED = 400
18
36
 
@@ -48,14 +66,7 @@ export class ThumbStore {
48
66
  const key = `${p}|${statSync(p).mtimeMs}|${w}`
49
67
  const hit = this.cache.get(key)
50
68
  if (hit != null) return hit
51
- const sharp = await importSharp('a thumbnail')
52
- const bytes = new Uint8Array(
53
- await sharp(p)
54
- .rotate()
55
- .resize({ width: w, height: w, fit: 'inside', withoutEnlargement: true })
56
- .webp({ quality: 78 })
57
- .toBuffer(),
58
- )
69
+ const bytes = await webpThumb(p, w)
59
70
  if (this.cache.size >= MAX_CACHED) {
60
71
  const oldest = this.cache.keys().next().value
61
72
  if (oldest != null) this.cache.delete(oldest)
@@ -37,6 +37,9 @@ export type GeneratedAudio = { filename: string; mime: string; url: string | nul
37
37
  /** a video file (SaveVideo, SaveWEBM, VHS_VideoCombine): the panel plays it in a <video> player */
38
38
  export type GeneratedVideo = GeneratedAudio
39
39
 
40
+ /** a 3D file (SaveGLB, SaveGaussianSplat, SavePointCloud): the panel lists it as a download, `size` in bytes */
41
+ export type GeneratedModel3D = GeneratedAudio & { format: string; size: number }
42
+
40
43
  export type GenerateOk = {
41
44
  ok: true
42
45
  module: string
@@ -50,6 +53,7 @@ export type GenerateOk = {
50
53
  texts?: GeneratedText[]
51
54
  audios?: GeneratedAudio[]
52
55
  videos?: GeneratedVideo[]
56
+ models3d?: GeneratedModel3D[]
53
57
  /** the module's output widgets (`widget.relight(...)`), drawn over this run's tagged images */
54
58
  widgets?: OutputWidget[]
55
59
  }
@@ -17,6 +17,13 @@ import { SHORTCUT_KEYS } from 'src/cli/serve/web/state/shortcuts.ts'
17
17
  import { onEscape } from 'src/cli/serve/web/state/escape.ts'
18
18
  import { OutputWidgets } from 'src/cli/serve/web/widgets/OutputWidgets.tsx'
19
19
 
20
+ /** a 3D file is often tens of MB (a splat), sometimes a few KB (a small mesh) */
21
+ function formatSize(bytes: number): string {
22
+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
23
+ const mb = bytes / (1024 * 1024)
24
+ return `${mb < 10 ? mb.toFixed(1) : Math.round(mb)} MB`
25
+ }
26
+
20
27
  /** on an output only the serve process holds: a restart, or the memory budget, loses it */
21
28
  function EphemeralPill(p: { out: { url: string | null; absPath: string | null } }): ReactNode {
22
29
  if (!isEphemeral(p.out)) return null
@@ -643,10 +650,26 @@ export const Gallery = observer(function Gallery(p: { st: WebSt; compact?: boole
643
650
  </div>
644
651
  ),
645
652
  )}
653
+ {(r.models3d ?? []).map((m, ix) =>
654
+ m.url != null ? (
655
+ <div key={`${r.promptId}-model3d-${ix}`} className="model3d-cell">
656
+ <a href={m.url} download={m.filename} data-tip={`${m.format} 3D file, ${m.mime}`}>
657
+ <Icon name="save" /> {m.filename}
658
+ </a>
659
+ <span className="hint">{formatSize(m.size)}</span>
660
+ <EphemeralPill out={m} />
661
+ </div>
662
+ ) : (
663
+ <div key={`${r.promptId}-model3d-${ix}`} className="noimg">
664
+ {m.filename} (not saved, and no longer in memory)
665
+ </div>
666
+ ),
667
+ )}
646
668
  {r.images.length === 0 &&
647
669
  (r.texts ?? []).length === 0 &&
648
670
  (r.audios ?? []).length === 0 &&
649
- (r.videos ?? []).length === 0 ? (
671
+ (r.videos ?? []).length === 0 &&
672
+ (r.models3d ?? []).length === 0 ? (
650
673
  <div className="noimg">no outputs</div>
651
674
  ) : null}
652
675
  </div>
@@ -534,6 +534,9 @@ input[type='range'].setting-range:disabled { opacity: 0.3; }
534
534
  .gallery.by-cols .video-cell { width: 100%; }
535
535
  .video-cell video { width: 100%; max-height: 480px; border-radius: 6px; background: #000; }
536
536
  .img-cell[draggable='true'], .audio-cell[draggable='true'], .video-cell[draggable='true'] { cursor: grab; }
537
+ .model3d-cell { display: flex; align-items: center; gap: 8px; width: min(100%, 480px); }
538
+ .model3d-cell a { display: inline-flex; align-items: center; gap: 4px; }
539
+ .model3d-cell .ephemeral-pill { position: static; }
537
540
  .use-as { display: flex; flex-wrap: wrap; gap: 4px; }
538
541
  /* a media var takes desktop files and gallery outputs: the zone lights while one hovers it */
539
542
  .media-drop { border: 1px dashed var(--border); border-radius: 6px; padding: 6px; }
@@ -38,6 +38,7 @@ export {
38
38
  ComfyExecution,
39
39
  type ComfyAudioOutput,
40
40
  type ComfyVideoOutput,
41
+ type Comfy3DOutput,
41
42
  type ComfyExecutionData,
42
43
  type ComfyTextOutput,
43
44
  type ExecutionPreview,
@@ -542,7 +542,11 @@ export class ComfyNode<
542
542
  }
543
543
 
544
544
  private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {
545
- const i: NodeOutputExt = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)!
545
+ const i = this.$schema.outputs.find((i: NodeOutputExt) => slotTypeAccepts(type, i.typeName))
546
+ if (i == null)
547
+ throw new Error(
548
+ `🔴 ${this.$schema.nodeKey} has no output of type ${type}: link one of its outputs by name instead`,
549
+ )
546
550
  const val = (this.outputs as any)[i.outKey]
547
551
  // console.log(`this[i.name] = ${this.$schema.name}[${i.name}] = ${val}`)
548
552
  if (val instanceof ComfyNodeOutput) return val
@@ -550,7 +554,7 @@ export class ComfyNode<
550
554
  }
551
555
 
552
556
  private _getOutputForTypeOrNull(type: string): ComfyNodeOutput<any> | null {
553
- const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => i.typeName === type)
557
+ const i: Maybe<NodeOutputExt> = this.$schema.outputs.find((i: NodeOutputExt) => slotTypeAccepts(type, i.typeName))
554
558
  if (i == null) return null
555
559
  const val = (this.outputs as any)[i.outKey]
556
560
  if (val == null) return null
@@ -558,3 +562,9 @@ export class ComfyNode<
558
562
  throw new Error(`Expected ${i.outKey} to be a ComfyNodeOutput`)
559
563
  }
560
564
  }
565
+
566
+ /** an input typed `MESH,FILE_3D_GLB` takes an output of ANY listed type (ComfyUI's SaveGLB) */
567
+ export function slotTypeAccepts(inputType: string, outputType: string): boolean {
568
+ if (inputType === outputType) return true
569
+ return inputType.includes(',') && inputType.split(',').some((part) => part.trim() === outputType)
570
+ }
@@ -95,6 +95,12 @@ export type ConnectOptions = {
95
95
  timeoutMs?: number
96
96
  }
97
97
 
98
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
99
+ export class HostRouteUnusableError extends Error {
100
+ /** name, not instanceof: the cli bundle and dist/index.js each define this class */
101
+ override readonly name = 'HostRouteUnusableError'
102
+ }
103
+
98
104
  /** the host never came up within ConnectOptions.timeoutMs */
99
105
  export class ComfyHostUnreachableError extends Error {
100
106
  /** name, not instanceof: the cli bundle and dist/index.js each define this class */
@@ -460,6 +466,7 @@ export class ComfyHost<ID extends string = string> {
460
466
  /** close the websocket (e.g. to let a script exit) */
461
467
  disconnect = (): void => {
462
468
  this.clearConnectTimer()
469
+ this.stopWatchdog()
463
470
  this.ws?.disconnectPermanently()
464
471
  this.ws = null
465
472
  this._ready = null
@@ -543,6 +550,9 @@ export class ComfyHost<ID extends string = string> {
543
550
  this.ws = new ResilientWebSocketClient({
544
551
  onConnectOrReconnect: async (): Promise<void> => {
545
552
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)
553
+ this._socketIsNew = true
554
+ // events sent while the socket was down are lost for good: each run in flight asks
555
+ void this.reconcileRuns([...this.executions.values()], 'reconnect')
546
556
  if (this.shouldUseSchemaCache()) {
547
557
  try {
548
558
  await this.loadSchemaFromCache()
@@ -561,7 +571,12 @@ export class ComfyHost<ID extends string = string> {
561
571
  this.markReady()
562
572
  },
563
573
  onMessage: (e: WsMessageEvent): void => this.onMessage(e),
564
- url: () => this.getWSUrl(),
574
+ // a reconnect keeps the session: ComfyUI routes a prompt's events to the client_id it
575
+ // was posted with, and drops them when that session has no socket
576
+ url: () =>
577
+ this.comfySessionId === 'temp'
578
+ ? this.getWSUrl()
579
+ : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
565
580
  // auth rides the upgrade headers; headerless transports (browser)
566
581
  // remap X-API-Key to ?token= inside the ws client
567
582
  headers: () => this.authHeaders(),
@@ -634,6 +649,135 @@ export class ComfyHost<ID extends string = string> {
634
649
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)
635
650
  }
636
651
 
652
+ /** GET a json route for the run checks: an answer that is not json (a 404, a 405, a page) means the
653
+ * host has no such route, a HostRouteUnusableError; a network failure stays a plain error */
654
+ private fetchReconcileJSON_ = async (route: string): Promise<unknown> => {
655
+ const res = await this.fetch(route)
656
+ const contentType = res.headers.get('content-type') ?? ''
657
+ if (res.ok && contentType.includes('json')) return res.json()
658
+ void res.body?.cancel()
659
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || 'no content-type'}`)
660
+ }
661
+
662
+ /** one prompt's `GET /history/<id>` reply, `{}` while the host has no entry for it */
663
+ fetchHistory = (promptId: PromptID): Promise<unknown> => {
664
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`)
665
+ }
666
+
667
+ /** the ids of the prompts waiting or running on this host, every client counted (`GET /queue`) */
668
+ fetchQueuedPromptIds = async (): Promise<Set<string>> => {
669
+ const json = await this.fetchReconcileJSON_('/queue')
670
+ const ids = new Set<string>()
671
+ for (const key of ['queue_running', 'queue_pending']) {
672
+ const list: unknown = typeof json === 'object' && json != null ? Reflect.get(json, key) : null
673
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`)
674
+ // an item of another shape (a cloud host) could hide a run: refuse the whole answer
675
+ for (const item of list) {
676
+ if (!Array.isArray(item) || typeof item[1] !== 'string')
677
+ throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`)
678
+ ids.add(item[1])
679
+ }
680
+ }
681
+ return ids
682
+ }
683
+
684
+ /** why runs on this host are never checked over http: its /queue or /history is not ComfyUI's
685
+ * (a cloud host). Null while both answered as ComfyUI does, or were never asked */
686
+ reconcileOff: string | null = null
687
+
688
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
689
+ * stop for good, said once), false for a passing failure the caller reports */
690
+ noteReconcileFailure(e: unknown): boolean {
691
+ if (!(e instanceof Error) || e.name !== 'HostRouteUnusableError') return false
692
+ if (this.reconcileOff == null) {
693
+ this.reconcileOff = e.message
694
+ this.stopWatchdog()
695
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`)
696
+ }
697
+ return true
698
+ }
699
+
700
+ /** fetchQueuedPromptIds, null when the queue did not answer (logged once per message) or has another
701
+ * shape: a run is then never declared lost */
702
+ fetchQueuedPromptIdsOrNull = async (): Promise<Set<string> | null> => {
703
+ try {
704
+ return await this.fetchQueuedPromptIds()
705
+ } catch (e) {
706
+ if (this.noteReconcileFailure(e)) return null
707
+ const msg = extractErrorMessage(e)
708
+ if (!this._loggedQueueProblems.has(msg)) {
709
+ this._loggedQueueProblems.add(msg)
710
+ toastError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`)
711
+ }
712
+ return null
713
+ }
714
+ }
715
+ private _loggedQueueProblems = new Set<string>()
716
+
717
+ // RUN WATCHDOG (architecture.md, ResilientWebsocket.ts) -------------------------------
718
+ /** a check needs the WHOLE socket quiet this long, and the run itself too */
719
+ runSilenceMs: number = 1000
720
+ /** the wait doubles after each check that ends no run, up to this; any ws message resets it */
721
+ runSilenceMaxMs: number = 30_000
722
+ private _silenceWaitMs: number | null = null
723
+ private _lastCheckAt: number = 0
724
+ private _checking: boolean = false
725
+ private _watchdog: Maybe<ReturnType<typeof setInterval>> = null
726
+
727
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
728
+ trackExecution(execution: ComfyExecution): void {
729
+ this.executions.set(execution.data.id, execution)
730
+ // a run with no socket (tests that drive messages by hand) has nothing to watch
731
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return
732
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs))
733
+ this._watchdog.unref?.()
734
+ }
735
+
736
+ private stopWatchdog(): void {
737
+ if (this._watchdog != null) clearInterval(this._watchdog)
738
+ this._watchdog = null
739
+ }
740
+
741
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
742
+ * quiet node: ask. A run queued behind a talking host is never asked about */
743
+ private watchdogTick(): void {
744
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog()
745
+ if (this._checking) return
746
+ const now = Date.now()
747
+ const wait = this._silenceWaitMs ?? this.runSilenceMs
748
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return
749
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs)
750
+ if (due.length === 0) return
751
+ this._checking = true
752
+ void this.reconcileRuns(due, 'silence').finally(() => {
753
+ this._checking = false
754
+ this._lastCheckAt = Date.now()
755
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs)
756
+ })
757
+ }
758
+
759
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
760
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
761
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
762
+ * the new socket of the same session. A clean close lets the server end that handler first */
763
+ async reconcileRuns(runs: ComfyExecution[], why: 'reconnect' | 'silence'): Promise<void> {
764
+ if (this.reconcileOff != null) return
765
+ const todo = runs.filter((r) => !r.reconciling)
766
+ if (todo.length === 0) return
767
+ for (const r of todo) r.beginReconcile(why)
768
+ const queued = await this.fetchQueuedPromptIdsOrNull()
769
+ if (this.reconcileOff != null) {
770
+ for (const r of todo) r.reconciling = false
771
+ return
772
+ }
773
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)))
774
+ if (why === 'silence' && verdicts.includes('history') && this.ws?.isOpen === true) {
775
+ toastError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`)
776
+ this.ws.reconnect()
777
+ }
778
+ }
779
+
780
+
637
781
  /** drop every PENDING prompt from the server queue (the running one keeps going) */
638
782
  clearQueue = (): Promise<void> => {
639
783
  return this.postJSON_('/queue', { clear: true })
@@ -870,6 +1014,9 @@ export class ComfyHost<ID extends string = string> {
870
1014
  private _unknownBinaryFrameTypes = new Set<number>()
871
1015
  private _unknownWsEventTypes = new Set<string>()
872
1016
 
1017
+ /** the socket opened and its first 'status' has not come yet */
1018
+ private _socketIsNew: boolean = false
1019
+
873
1020
  /** handy to keep around */
874
1021
  status: ComfyStatusData['status'] | null = null
875
1022
 
@@ -915,6 +1062,7 @@ export class ComfyHost<ID extends string = string> {
915
1062
 
916
1063
  onMessage(e: WsMessageEvent): void {
917
1064
  this.lastWsMessageAt = Date.now()
1065
+ this._silenceWaitMs = null
918
1066
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
919
1067
  if (e.data instanceof ArrayBuffer) {
920
1068
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)
@@ -974,10 +1122,13 @@ export class ComfyHost<ID extends string = string> {
974
1122
  if (msg.type === 'status') {
975
1123
  if (msg.data.sid) {
976
1124
  const sidChanged = msg.data.sid !== this.comfySessionId
1125
+ const socketIsNew = this._socketIsNew
1126
+ this._socketIsNew = false
977
1127
  this.comfySessionId = msg.data.sid
978
1128
  this._sessionResolve?.()
979
1129
  this._sessionResolve = null
980
- if (sidChanged) {
1130
+ // a reconnect keeps its sid (?clientId=), and still starts a new connection
1131
+ if (sidChanged || socketIsNew) {
981
1132
  this._unknownWsEventTypes.clear()
982
1133
  this._unknownBinaryFrameTypes.clear()
983
1134
  this.onSession?.(msg.data.sid)
@@ -77,6 +77,7 @@ export class ResilientWebSocketClient {
77
77
 
78
78
  constructor(
79
79
  public options: {
80
+ /** re-read on every connect */
80
81
  url: () => string
81
82
  /** upgrade-request headers (auth: X-API-Key & co) — a thunk, re-read on every reconnect.
82
83
  * On a headerless transport (browser) X-API-Key rides `?token=` instead
@@ -149,6 +150,13 @@ export class ResilientWebSocketClient {
149
150
  }, ms)
150
151
  }
151
152
 
153
+ /** close the socket cleanly, then reconnect as after any close: the server ends its handler first */
154
+ reconnect(): void {
155
+ if (this.permanentlyClosed || this.currentWS == null) return
156
+ this.addInfo('closing the socket to reconnect')
157
+ this.currentWS.close()
158
+ }
159
+
152
160
  /** close and stop reconnecting (lets a script exit cleanly) */
153
161
  disconnectPermanently(): void {
154
162
  this.permanentlyClosed = true
@@ -175,6 +183,8 @@ export class ResilientWebSocketClient {
175
183
 
176
184
  private async connect(): Promise<void> {
177
185
  this.isOpen = false
186
+ // re-read: a reconnect asks the server for the session the socket had (?clientId=)
187
+ this.url = this.options.url()
178
188
  const prevWS = this.currentWS
179
189
 
180
190
  // cleanup a possible re-connection timeout for an other url
@@ -17,10 +17,3 @@ console.log(` custom node keys: ${registry.plugins_byNodeKey.size}`)
17
17
  console.log(` models: ${registry.knownModels.size}`)
18
18
  console.log(` alterations: ${registry.alterations.length}`)
19
19
  console.log(` github stats: ${registry.githubStats.size}`)
20
-
21
- // the generator aligns its own `// x N` comments and emits trailing blank
22
- // lines; oxfmt disagrees on both, so WITHOUT this the ci gate goes red right
23
- // after any regeneration. Runs here, not chained in package.json: a `&&` there
24
- // swallows this script's own flags (`--skip-download` landed on oxfmt).
25
- const fmt = Bun.spawnSync(['oxfmt', 'src/manager/generated'], { stdout: 'inherit', stderr: 'inherit' })
26
- if (fmt.exitCode !== 0) throw new Error(`🔴 oxfmt failed on src/manager/generated (exit ${fmt.exitCode})`)