comfy-ts 2.22.0 → 2.24.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 (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. 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,
@@ -47,6 +48,11 @@ export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi
47
48
  export { MediaImage, type MediaImageData } from 'src/runner/MediaImage.ts'
48
49
  export type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
49
50
  export { InvalidPromptError } from 'src/errors/InvalidPromptError.ts'
51
+ export {
52
+ ComfyOrgApiKeyMissingError,
53
+ type ComfyOrgApiKeySource,
54
+ type PartnerApiNode,
55
+ } from 'src/runner/comfyOrgApiKey.ts'
50
56
 
51
57
  // graph (programmatic node graph)
52
58
  export { ComfyNode } from 'src/graph/ComfyNode.ts'
@@ -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
+ }
@@ -47,6 +47,7 @@ import { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/Resilien
47
47
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
48
48
  import type { VarsSpec } from 'src/vars/ComfyVars.ts'
49
49
  import { diffSchemas, MODEL_LISTS, type SchemaDrift } from 'src/host/schemaDrift.ts'
50
+ import type { ComfyOrgApiKeySource } from 'src/runner/comfyOrgApiKey.ts'
50
51
 
51
52
  export type ComfyHostID = Tagged<string, { HostID: true }>
52
53
  export type ComfyHostData = {
@@ -63,6 +64,11 @@ export type ComfyHostData = {
63
64
  /** sent as X-API-Key on every request AND the ws upgrade.
64
65
  * NEVER persist the value: read it from an env var (e.g. COMFY_CLOUD_API_KEY) */
65
66
  apiKey?: string
67
+ /** the Comfy account key (platform.comfy.org) that paid partner API nodes bill to, sent as
68
+ * `extra_data.api_key_comfy_org` with a prompt that holds one. A thunk is read only when such
69
+ * a run starts. `RunSettings.comfyOrgApiKey` overrides it for one run; a cloud.comfy.org host
70
+ * falls back to its apiKey. NEVER persist the value (architecture.md, Partner API nodes) */
71
+ comfyOrgApiKey?: ComfyOrgApiKeySource
66
72
  /** default true. false = never write sdk.d.ts to .comfy-ts/hosts/<id>/ —
67
73
  * schema updates stay in-memory. The comfy-cloud example sets false: its sdk
68
74
  * home is the COMMITTED examples/comfy-cloud/sdk.d.ts (gen:sdk:cloud), and a
@@ -95,6 +101,12 @@ export type ConnectOptions = {
95
101
  timeoutMs?: number
96
102
  }
97
103
 
104
+ /** the host answered a run check route, but not as ComfyUI does (no such route, another shape) */
105
+ export class HostRouteUnusableError extends Error {
106
+ /** name, not instanceof: the cli bundle and dist/index.js each define this class */
107
+ override readonly name = 'HostRouteUnusableError'
108
+ }
109
+
98
110
  /** the host never came up within ConnectOptions.timeoutMs */
99
111
  export class ComfyHostUnreachableError extends Error {
100
112
  /** name, not instanceof: the cli bundle and dist/index.js each define this class */
@@ -460,6 +472,7 @@ export class ComfyHost<ID extends string = string> {
460
472
  /** close the websocket (e.g. to let a script exit) */
461
473
  disconnect = (): void => {
462
474
  this.clearConnectTimer()
475
+ this.stopWatchdog()
463
476
  this.ws?.disconnectPermanently()
464
477
  this.ws = null
465
478
  this._ready = null
@@ -543,6 +556,9 @@ export class ComfyHost<ID extends string = string> {
543
556
  this.ws = new ResilientWebSocketClient({
544
557
  onConnectOrReconnect: async (): Promise<void> => {
545
558
  logInfo(`[👢] WEBSOCKET: connected to ComfyUI host ${this.data.id}`)
559
+ this._socketIsNew = true
560
+ // events sent while the socket was down are lost for good: each run in flight asks
561
+ void this.reconcileRuns([...this.executions.values()], 'reconnect')
546
562
  if (this.shouldUseSchemaCache()) {
547
563
  try {
548
564
  await this.loadSchemaFromCache()
@@ -561,7 +577,12 @@ export class ComfyHost<ID extends string = string> {
561
577
  this.markReady()
562
578
  },
563
579
  onMessage: (e: WsMessageEvent): void => this.onMessage(e),
564
- url: () => this.getWSUrl(),
580
+ // a reconnect keeps the session: ComfyUI routes a prompt's events to the client_id it
581
+ // was posted with, and drops them when that session has no socket
582
+ url: () =>
583
+ this.comfySessionId === 'temp'
584
+ ? this.getWSUrl()
585
+ : `${this.getWSUrl()}?clientId=${encodeURIComponent(this.comfySessionId)}`,
565
586
  // auth rides the upgrade headers; headerless transports (browser)
566
587
  // remap X-API-Key to ?token= inside the ws client
567
588
  headers: () => this.authHeaders(),
@@ -634,6 +655,135 @@ export class ComfyHost<ID extends string = string> {
634
655
  if (!res.ok) throw new Error(`POST ${route} failed on ${this.getServerHostHTTP()}: ${res.status}`)
635
656
  }
636
657
 
658
+ /** GET a json route for the run checks: an answer that is not json (a 404, a 405, a page) means the
659
+ * host has no such route, a HostRouteUnusableError; a network failure stays a plain error */
660
+ private fetchReconcileJSON_ = async (route: string): Promise<unknown> => {
661
+ const res = await this.fetch(route)
662
+ const contentType = res.headers.get('content-type') ?? ''
663
+ if (res.ok && contentType.includes('json')) return res.json()
664
+ void res.body?.cancel()
665
+ throw new HostRouteUnusableError(`GET ${route} answered ${res.status} ${contentType || 'no content-type'}`)
666
+ }
667
+
668
+ /** one prompt's `GET /history/<id>` reply, `{}` while the host has no entry for it */
669
+ fetchHistory = (promptId: PromptID): Promise<unknown> => {
670
+ return this.fetchReconcileJSON_(`/history/${encodeURIComponent(promptId)}`)
671
+ }
672
+
673
+ /** the ids of the prompts waiting or running on this host, every client counted (`GET /queue`) */
674
+ fetchQueuedPromptIds = async (): Promise<Set<string>> => {
675
+ const json = await this.fetchReconcileJSON_('/queue')
676
+ const ids = new Set<string>()
677
+ for (const key of ['queue_running', 'queue_pending']) {
678
+ const list: unknown = typeof json === 'object' && json != null ? Reflect.get(json, key) : null
679
+ if (!Array.isArray(list)) throw new HostRouteUnusableError(`GET /queue has no ${key} list`)
680
+ // an item of another shape (a cloud host) could hide a run: refuse the whole answer
681
+ for (const item of list) {
682
+ if (!Array.isArray(item) || typeof item[1] !== 'string')
683
+ throw new HostRouteUnusableError(`GET /queue: an item of ${key} is not [number, prompt_id, …]`)
684
+ ids.add(item[1])
685
+ }
686
+ }
687
+ return ids
688
+ }
689
+
690
+ /** why runs on this host are never checked over http: its /queue or /history is not ComfyUI's
691
+ * (a cloud host). Null while both answered as ComfyUI does, or were never asked */
692
+ reconcileOff: string | null = null
693
+
694
+ /** @internal a failed run check: true when it proved the host has no usable route (the checks then
695
+ * stop for good, said once), false for a passing failure the caller reports */
696
+ noteReconcileFailure(e: unknown): boolean {
697
+ if (!(e instanceof Error) || e.name !== 'HostRouteUnusableError') return false
698
+ if (this.reconcileOff == null) {
699
+ this.reconcileOff = e.message
700
+ this.stopWatchdog()
701
+ logInfo(`host '${this.data.id}': ${e.message}, not the ComfyUI shape: runs here are not checked over http, they wait for their events`)
702
+ }
703
+ return true
704
+ }
705
+
706
+ /** fetchQueuedPromptIds, null when the queue did not answer (logged once per message) or has another
707
+ * shape: a run is then never declared lost */
708
+ fetchQueuedPromptIdsOrNull = async (): Promise<Set<string> | null> => {
709
+ try {
710
+ return await this.fetchQueuedPromptIds()
711
+ } catch (e) {
712
+ if (this.noteReconcileFailure(e)) return null
713
+ const msg = extractErrorMessage(e)
714
+ if (!this._loggedQueueProblems.has(msg)) {
715
+ this._loggedQueueProblems.add(msg)
716
+ toastError(`host '${this.data.id}': its queue did not answer (${msg}); no run is failed as lost until it does`)
717
+ }
718
+ return null
719
+ }
720
+ }
721
+ private _loggedQueueProblems = new Set<string>()
722
+
723
+ // RUN WATCHDOG (architecture.md, ResilientWebsocket.ts) -------------------------------
724
+ /** a check needs the WHOLE socket quiet this long, and the run itself too */
725
+ runSilenceMs: number = 1000
726
+ /** the wait doubles after each check that ends no run, up to this; any ws message resets it */
727
+ runSilenceMaxMs: number = 30_000
728
+ private _silenceWaitMs: number | null = null
729
+ private _lastCheckAt: number = 0
730
+ private _checking: boolean = false
731
+ private _watchdog: Maybe<ReturnType<typeof setInterval>> = null
732
+
733
+ /** @internal a new run routes its ws messages here, and the watchdog watches it */
734
+ trackExecution(execution: ComfyExecution): void {
735
+ this.executions.set(execution.data.id, execution)
736
+ // a run with no socket (tests that drive messages by hand) has nothing to watch
737
+ if (this.ws == null || this._watchdog != null || this.reconcileOff != null) return
738
+ this._watchdog = setInterval(() => this.watchdogTick(), Math.min(250, this.runSilenceMs))
739
+ this._watchdog.unref?.()
740
+ }
741
+
742
+ private stopWatchdog(): void {
743
+ if (this._watchdog != null) clearInterval(this._watchdog)
744
+ this._watchdog = null
745
+ }
746
+
747
+ /** a socket that hears no broadcast and no event for a while is deaf, or the host runs one long
748
+ * quiet node: ask. A run queued behind a talking host is never asked about */
749
+ private watchdogTick(): void {
750
+ if (this.executions.size === 0 || this.ws == null) return this.stopWatchdog()
751
+ if (this._checking) return
752
+ const now = Date.now()
753
+ const wait = this._silenceWaitMs ?? this.runSilenceMs
754
+ if (now - Math.max(this.lastWsMessageAt ?? 0, this._lastCheckAt) < wait) return
755
+ const due = [...this.executions.values()].filter((e) => !e.reconciling && now - e.lastHeardAt >= this.runSilenceMs)
756
+ if (due.length === 0) return
757
+ this._checking = true
758
+ void this.reconcileRuns(due, 'silence').finally(() => {
759
+ this._checking = false
760
+ this._lastCheckAt = Date.now()
761
+ this._silenceWaitMs = Math.min(wait * 2, this.runSilenceMaxMs)
762
+ })
763
+ }
764
+
765
+ /** @internal one queue read for all the runs, then the history of each run not in it. A run that
766
+ * ends from its history while the socket looked fine means the socket hears nothing: ComfyUI removes
767
+ * a session BY KEY when a socket's handler ends, so an old handler that ends after a reconnect evicts
768
+ * the new socket of the same session. A clean close lets the server end that handler first */
769
+ async reconcileRuns(runs: ComfyExecution[], why: 'reconnect' | 'silence'): Promise<void> {
770
+ if (this.reconcileOff != null) return
771
+ const todo = runs.filter((r) => !r.reconciling)
772
+ if (todo.length === 0) return
773
+ for (const r of todo) r.beginReconcile(why)
774
+ const queued = await this.fetchQueuedPromptIdsOrNull()
775
+ if (this.reconcileOff != null) {
776
+ for (const r of todo) r.reconciling = false
777
+ return
778
+ }
779
+ const verdicts = await Promise.all(todo.map((r) => r.reconcile(queued)))
780
+ if (why === 'silence' && verdicts.includes('history') && this.ws?.isOpen === true) {
781
+ toastError(`host '${this.data.id}': a run ended without its end reaching the socket, which hears nothing; reconnecting`)
782
+ this.ws.reconnect()
783
+ }
784
+ }
785
+
786
+
637
787
  /** drop every PENDING prompt from the server queue (the running one keeps going) */
638
788
  clearQueue = (): Promise<void> => {
639
789
  return this.postJSON_('/queue', { clear: true })
@@ -870,6 +1020,9 @@ export class ComfyHost<ID extends string = string> {
870
1020
  private _unknownBinaryFrameTypes = new Set<number>()
871
1021
  private _unknownWsEventTypes = new Set<string>()
872
1022
 
1023
+ /** the socket opened and its first 'status' has not come yet */
1024
+ private _socketIsNew: boolean = false
1025
+
873
1026
  /** handy to keep around */
874
1027
  status: ComfyStatusData['status'] | null = null
875
1028
 
@@ -915,6 +1068,7 @@ export class ComfyHost<ID extends string = string> {
915
1068
 
916
1069
  onMessage(e: WsMessageEvent): void {
917
1070
  this.lastWsMessageAt = Date.now()
1071
+ this._silenceWaitMs = null
918
1072
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
919
1073
  if (e.data instanceof ArrayBuffer) {
920
1074
  if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)
@@ -974,10 +1128,13 @@ export class ComfyHost<ID extends string = string> {
974
1128
  if (msg.type === 'status') {
975
1129
  if (msg.data.sid) {
976
1130
  const sidChanged = msg.data.sid !== this.comfySessionId
1131
+ const socketIsNew = this._socketIsNew
1132
+ this._socketIsNew = false
977
1133
  this.comfySessionId = msg.data.sid
978
1134
  this._sessionResolve?.()
979
1135
  this._sessionResolve = null
980
- if (sidChanged) {
1136
+ // a reconnect keeps its sid (?clientId=), and still starts a new connection
1137
+ if (sidChanged || socketIsNew) {
981
1138
  this._unknownWsEventTypes.clear()
982
1139
  this._unknownBinaryFrameTypes.clear()
983
1140
  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})`)