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
@@ -22,7 +22,11 @@ import type {
22
22
  WsMsgExecutionSuccess,
23
23
  } from 'src/runner/ComfyWsApi.ts'
24
24
  import { MediaImage } from 'src/runner/MediaImage.ts'
25
- import { isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'
25
+ import { extensionOf, isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'
26
+ import { model3dMime } from 'src/runner/outputs3d.ts'
27
+ import { type HistoryReplay, historyReplay } from 'src/runner/historyReplay.ts'
28
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
29
+ import { logError, logInfo } from 'src/utils/log.ts'
26
30
  import { previewMetadataNodeId } from 'src/runner/wsBinaryFrame.ts'
27
31
 
28
32
  /** paths claimed by in-flight retrievals: two same-second runs on a
@@ -36,6 +40,8 @@ export type ComfyExecutionData = {
36
40
  graphID: ComfyWorkflowID
37
41
  executed: boolean
38
42
  error?: WsMsgExecutionError | WsMsgExecutionInterrupted | null
43
+ /** why comfy-ts failed the run itself, when no ComfyUI message says it (the host lost the prompt) */
44
+ reason?: string | null
39
45
  status?: ComfyExecutionStatus | null
40
46
  }
41
47
 
@@ -47,12 +53,18 @@ export type ComfyAudioOutput = {
47
53
  mime: string
48
54
  bytes: Uint8Array
49
55
  absPath: AbsolutePath | null
56
+ /** the `tag` / `tags` of the output node's metadata, as on images */
57
+ tags: string[]
50
58
  }
51
59
 
52
60
  /** one video file an output node published (SaveVideo, SaveWEBM, VHS_VideoCombine), same
53
61
  * shape and same retrieval as an audio file */
54
62
  export type ComfyVideoOutput = ComfyAudioOutput
55
63
 
64
+ /** one 3D file an output node published (SaveGLB, SaveGaussianSplat, SavePointCloud): a mesh, a point
65
+ * cloud or a splat, same retrieval as an audio file. `format` is the lowercase extension (glb, ply, spz…) */
66
+ export type Comfy3DOutput = ComfyAudioOutput & { format: string }
67
+
56
68
  /** one text output as an output node published it (`nodeKey` is null when the node left the snapshot) */
57
69
  export type ComfyTextOutput = {
58
70
  nodeId: ComfyNodeId
@@ -118,7 +130,7 @@ export class ComfyExecution {
118
130
  this.logProgress = init.logProgress ?? false
119
131
  // register with the host so websocket messages route here,
120
132
  // then flush messages that arrived before we existed
121
- this.host.executions.set(data.id, this)
133
+ this.host.trackExecution(this)
122
134
  this.onCreate()
123
135
  }
124
136
 
@@ -182,6 +194,7 @@ export class ComfyExecution {
182
194
  const outputs = [`${this.images.length} image(s)`]
183
195
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`)
184
196
  if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`)
197
+ if (this.models3d.length > 0) outputs.push(`${this.models3d.length} 3d model(s)`)
185
198
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`)
186
199
  const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${outputs.join(' · ')}`
187
200
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
@@ -218,6 +231,11 @@ export class ComfyExecution {
218
231
  }
219
232
 
220
233
  onPromptRelatedMessage = (msg: PendingWsItem): void => {
234
+ // a run reconciled from /history can still hear its own end late: one end only
235
+ if (this.ended) return
236
+ this.heard()
237
+ if (msg.type === 'execution_success' || msg.type === 'execution_error' || msg.type === 'execution_interrupted')
238
+ this.ended = true
221
239
  const graph = this.workflow
222
240
  // replayed pre-registration binary frame: an OUTPUT only when the ws
223
241
  // saver was executing at this point of the stream, else a preview
@@ -250,6 +268,7 @@ export class ComfyExecution {
250
268
  }
251
269
 
252
270
  private onExecutionSuccess = async (_msg: WsMsgExecutionSuccess): Promise<void> => {
271
+ if (this.mayHaveMissedEvents) await this.retrieveMissedOutputs()
253
272
  await Promise.all(this.pendingPromises)
254
273
  return this._finish({ status: 'Success' })
255
274
  }
@@ -263,6 +282,7 @@ export class ComfyExecution {
263
282
  /** update execution list */
264
283
  private onExecuted = (msg: WsMsgExecuted): void => {
265
284
  const promptNodeID = msg.data.node
285
+ this.heardExecuted.add(promptNodeID)
266
286
  // a STRING output reaches the client ONLY through an output node's ui
267
287
  // payload (PreviewAny), never through the prompt result
268
288
  for (const entry of msg.data.output?.text ?? []) {
@@ -279,10 +299,13 @@ export class ComfyExecution {
279
299
  )
280
300
  for (const video of listed.filter((f) => isVideoFilename(f.filename))) {
281
301
  this.pendingPromises.push(
282
- this.retrieveFile('video', video, promptNodeID).catch((e: unknown) => {
283
- console.error(`🔴 failed to retrieve ${video.filename}:`, e)
284
- this.videoErrors.push({ video, error: e })
285
- }),
302
+ this.retrieveFile(video, promptNodeID, mediaMime(video.filename)).then(
303
+ (o) => void this.videos.push(o),
304
+ (e: unknown) => {
305
+ console.error(`🔴 failed to retrieve ${video.filename}:`, e)
306
+ this.videoErrors.push({ video, error: e })
307
+ },
308
+ ),
286
309
  )
287
310
  }
288
311
  const images = listed.filter((f) => !isVideoFilename(f.filename))
@@ -299,15 +322,138 @@ export class ComfyExecution {
299
322
  }
300
323
  for (const audio of msg.data.output?.audio ?? []) {
301
324
  this.pendingPromises.push(
302
- this.retrieveFile('audio', audio, promptNodeID).catch((e: unknown) => {
303
- console.error(`🔴 failed to retrieve ${audio.filename}:`, e)
304
- this.audioErrors.push({ audio, error: e })
305
- }),
325
+ this.retrieveFile(audio, promptNodeID, mediaMime(audio.filename)).then(
326
+ (o) => void this.audios.push(o),
327
+ (e: unknown) => {
328
+ console.error(`🔴 failed to retrieve ${audio.filename}:`, e)
329
+ this.audioErrors.push({ audio, error: e })
330
+ },
331
+ ),
332
+ )
333
+ }
334
+ // a 3D loader echoes the file it READ, typed 'input', like LoadVideo
335
+ for (const model3d of (out?.['3d'] ?? []).filter((f) => f.type !== 'input')) {
336
+ this.pendingPromises.push(
337
+ this.retrieveFile(model3d, promptNodeID, model3dMime(model3d.filename)).then(
338
+ (o) => void this.models3d.push({ ...o, format: extensionOf(o.filename) }),
339
+ (e: unknown) => {
340
+ console.error(`🔴 failed to retrieve ${model3d.filename}:`, e)
341
+ this.models3dErrors.push({ model3d, error: e })
342
+ },
343
+ ),
306
344
  )
307
345
  }
308
346
  }
309
347
  private pendingPromises: Promise<void>[] = []
310
348
 
349
+ /** an end message arrived (or was replayed): every later message is ignored */
350
+ private ended: boolean = false
351
+ /** the output nodes whose `executed` reached us, so a /history replay never retrieves one twice */
352
+ private heardExecuted: Set<string> = new Set()
353
+
354
+ /** the run lived through a reconnect and may have lost events: its end reads /history for them */
355
+ private mayHaveMissedEvents: boolean = false
356
+
357
+ private replayUnheardOutputs(replay: HistoryReplay): void {
358
+ for (const msg of replay.executed)
359
+ if (msg.type === 'executed' && !this.heardExecuted.has(msg.data.node)) this.onExecuted(msg)
360
+ }
361
+
362
+ /** the history entry is written right after the end message is queued, so it may lag by a moment */
363
+ historyRetry: { tries: number; ms: number } = { tries: 5, ms: 400 }
364
+
365
+ /** a run that lived through a reconnect: an output node that ended in the gap is only in /history */
366
+ private retrieveMissedOutputs = async (): Promise<void> => {
367
+ const id = this.data.id
368
+ for (let i = 0; i < this.historyRetry.tries; i++) {
369
+ if (this.host.reconcileOff != null) return
370
+ if (i > 0) await new Promise((r) => setTimeout(r, this.historyRetry.ms))
371
+ try {
372
+ const replay = historyReplay(await this.host.fetchHistory(id), id)
373
+ if (replay == null) continue
374
+ return this.replayUnheardOutputs(replay)
375
+ } catch (e) {
376
+ if (this.host.noteReconcileFailure(e)) return
377
+ return logError(`run ${id}: its history did not answer (${extractErrorMessage(e)}); an output sent while the socket was down may be missing`)
378
+ }
379
+ }
380
+ logError(`run ${id}: no history entry after its end; an output sent while the socket was down may be missing`)
381
+ }
382
+
383
+ // ---- reconcile over http (architecture.md, ResilientWebsocket.ts) ------------------------
384
+ /** @internal the last event of this run: the watchdog checks only runs quiet for host.runSilenceMs */
385
+ lastHeardAt: number = Date.now()
386
+ /** @internal a check is in flight: never two at once */
387
+ reconciling: boolean = false
388
+ private loggedReconcileProblems: Set<string> = new Set()
389
+
390
+ private heard(): void {
391
+ this.lastHeardAt = Date.now()
392
+ }
393
+
394
+ private logReconcileOnce(msg: string): void {
395
+ if (this.loggedReconcileProblems.has(msg)) return
396
+ this.loggedReconcileProblems.add(msg)
397
+ logError(`run ${this.data.id}: ${msg}`)
398
+ }
399
+
400
+ /** @internal called before the host reads its queue. After a reconnect the run may have lost events,
401
+ * so its end reads /history for them; the flag is set before any await, so a live end that lands
402
+ * during the reads still looks. A check for silence alone does not set it: a quiet run lost nothing */
403
+ beginReconcile(why: 'reconnect' | 'silence'): void {
404
+ this.reconciling = true
405
+ if (why === 'reconnect') this.mayHaveMissedEvents = true
406
+ }
407
+
408
+ /** @internal ask the host where this run stands. `queued` is the host's queue read BEFORE this
409
+ * history read (the server moves a prompt from one to the other under one lock, so this order never
410
+ * misses a run that ended between the two reads); null when it did not answer, and then the run is
411
+ * never declared lost. A queued run needs no history read. Says how the check ended */
412
+ reconcile = async (queued: Set<string> | null): Promise<'history' | 'waiting' | 'lost'> => {
413
+ const id = this.data.id
414
+ const hostId = this.host.data.id
415
+ try {
416
+ if (this.ended || queued?.has(id) === true) return 'waiting'
417
+ let replay: HistoryReplay | null
418
+ try {
419
+ replay = historyReplay(await this.host.fetchHistory(id), id)
420
+ } catch (e) {
421
+ if (!this.host.noteReconcileFailure(e))
422
+ this.logReconcileOnce(`the history of host '${hostId}' did not answer (${extractErrorMessage(e)}); waiting for its events`)
423
+ return 'waiting'
424
+ }
425
+ if (this.ended) return 'waiting'
426
+ if (replay == null) {
427
+ if (queued == null) return 'waiting'
428
+ const reason = `host '${hostId}' has it neither in its queue nor in its history (cancelled, or the host restarted)`
429
+ logError(`run ${id}: ${reason}; the run fails`)
430
+ this.ended = true
431
+ await this._finish({ status: 'Failure', error: null, reason })
432
+ return 'lost'
433
+ }
434
+ // a SaveImageWebsocket frame in transit is silence too (the message event fires once the frame is
435
+ // whole) and /history never holds one: a quiet socket gets until runSilenceMaxMs to deliver it
436
+ const sinceHeard = Date.now() - this.lastHeardAt
437
+ if (!this.mayHaveMissedEvents && this.sendsWsFrames && sinceHeard < this.host.runSilenceMaxMs) return 'waiting'
438
+ logInfo(`run ${id}: ended on host '${hostId}' without its end reaching the socket, finishing from its history`)
439
+ for (const p of replay.problems) logError(`run ${id}: a history entry does not match the ws schemas, skipped: ${p}`)
440
+ this.replayUnheardOutputs(replay)
441
+ if (this.ephemeral)
442
+ logError(`run ${id}: SaveImageWebsocket frames sent while the socket did not hear are lost (they never reach the server disk)`)
443
+ if (replay.end != null) {
444
+ this.onPromptRelatedMessage(replay.end)
445
+ return 'history'
446
+ }
447
+ const reason = `its history entry on host '${hostId}' carries no end message`
448
+ logError(`run ${id}: ${reason}; the run fails`)
449
+ this.ended = true
450
+ await this._finish({ status: 'Failure', error: null, reason })
451
+ return 'history'
452
+ } finally {
453
+ this.reconciling = false
454
+ }
455
+ }
456
+
311
457
  /** audio retrievals that failed (their files are missing from `audios`) */
312
458
  audioErrors: { audio: ComfyImageInfo; error: unknown }[] = []
313
459
 
@@ -320,20 +466,23 @@ export class ComfyExecution {
320
466
  /** video files retrieved for this execution, in arrival order (final once `done` resolves) */
321
467
  videos: ComfyVideoOutput[] = []
322
468
 
469
+ /** 3D retrievals that failed (their files are missing from `models3d`) */
470
+ models3dErrors: { model3d: ComfyImageInfo; error: unknown }[] = []
471
+
472
+ /** 3D files retrieved for this execution, in arrival order (final once `done` resolves) */
473
+ models3d: Comfy3DOutput[] = []
474
+
475
+ /** one non-image file through /view, its bytes as the server wrote them; the caller files it */
323
476
  private retrieveFile = async (
324
- kind: 'audio' | 'video',
325
477
  info: ComfyImageInfo,
326
478
  promptNodeID: ComfyNodeId,
327
- ): Promise<void> => {
479
+ mime: string,
480
+ ): Promise<ComfyAudioOutput> => {
328
481
  const response = await this.host.fetchFile('/view?' + new URLSearchParams(info).toString())
329
482
  const bytes = new Uint8Array(await response.arrayBuffer())
330
- const mime = mediaMime(info.filename)
331
- const list = kind === 'audio' ? this.audios : this.videos
483
+ const tags = this.tagsOf(promptNodeID)
332
484
  const sf = this.save
333
- if (sf == null) {
334
- list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null })
335
- return
336
- }
485
+ if (sf == null) return { nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null, tags }
337
486
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs['filename_prefix']
338
487
  const written = await this.encodeAndWrite({
339
488
  bytes,
@@ -343,7 +492,7 @@ export class ComfyExecution {
343
492
  subfolder: info.subfolder,
344
493
  filename: info.filename,
345
494
  })
346
- list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path })
495
+ return { nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path, tags }
347
496
  }
348
497
 
349
498
  /** image retrievals that failed (their images are missing from `images`);
@@ -458,12 +607,22 @@ export class ComfyExecution {
458
607
 
459
608
  /** accumulate an output on the prompt; tags from node metadata ride along */
460
609
  private pushImage(img: MediaImage, promptNodeID: Maybe<string>): void {
461
- const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null
462
- if (promptMeta?.tag) img.tags.push(promptMeta.tag)
463
- if (promptMeta?.tags) img.tags.push(...promptMeta.tags)
610
+ img.tags.push(...this.tagsOf(promptNodeID))
464
611
  this.images.push(img)
465
612
  }
466
613
 
614
+ /** the tags an output node was built with (`{ tag }` / `{ tags }` metadata) */
615
+ private tagsOf(promptNodeID: Maybe<string>): string[] {
616
+ const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null
617
+ return [...(promptMeta?.tag ? [promptMeta.tag] : []), ...(promptMeta?.tags ?? [])]
618
+ }
619
+
620
+ /** the sent graph saves through SaveImageWebsocket: those outputs exist only as ws frames */
621
+ private get sendsWsFrames(): boolean {
622
+ const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson
623
+ return Object.values(apiJson).some((n) => n?.class_type === 'SaveImageWebsocket')
624
+ }
625
+
467
626
  /** true while the currently executing node is a SaveImageWebsocket in the
468
627
  * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
469
628
  * live graph may still say SaveImage) — binary frames are then OUTPUTS */
@@ -477,6 +636,7 @@ export class ComfyExecution {
477
636
  /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
478
637
  * to onWsImageOutput before they get here) */
479
638
  onPreviewFrame(p: { bytes: Uint8Array; mime: string; metadata: unknown }): void {
639
+ this.heard()
480
640
  const listener = this.onPreview
481
641
  if (listener == null) return
482
642
  const current = this.workflow.currentExecutingNode
@@ -498,6 +658,7 @@ export class ComfyExecution {
498
658
  /** one binary ws frame = one output image of the executing SaveImageWebsocket
499
659
  * node (architecture.md item 14 — the zero-server-disk path) */
500
660
  onWsImageOutput = (p: { bytes: Uint8Array; mime: string }): void => {
661
+ this.heard()
501
662
  const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null
502
663
  this.pendingPromises.push(
503
664
  this.storeWsImage(p, promptNodeID).catch((e: unknown) => {
@@ -545,6 +706,7 @@ export class ComfyExecution {
545
706
 
546
707
  /** @internal a live-text frame for one node */
547
708
  onProgressText(p: { nodeId: string; text: string }): void {
709
+ this.heard()
548
710
  this.progressTexts.set(p.nodeId, p.text)
549
711
  this.progressText = p.text
550
712
  this.emitProgress()
@@ -560,7 +722,7 @@ export class ComfyExecution {
560
722
  }
561
723
 
562
724
  private alreadyDone: boolean = false
563
- private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error'>): Promise<void> => {
725
+ private _finish = async (p: Pick<ComfyExecutionData, 'status' | 'error' | 'reason'>): Promise<void> => {
564
726
  if (this.alreadyDone) throw new Error(`❌ invariant violation: already finished`)
565
727
  this.alreadyDone = true
566
728
  this.update({ ...p, executed: true })
@@ -9,6 +9,12 @@ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
9
9
  import { ComfyNode } from 'src/graph/ComfyNode.ts'
10
10
  import type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
11
11
  import { ComfyExecution, type ExecutionPreview, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
12
+ import {
13
+ ComfyOrgApiKeyMissingError,
14
+ type ComfyOrgApiKeySource,
15
+ partnerApiNodes,
16
+ resolveComfyOrgApiKey,
17
+ } from 'src/runner/comfyOrgApiKey.ts'
12
18
  import { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'
13
19
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
14
20
  import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
@@ -56,8 +62,14 @@ export type RunSettings = {
56
62
  * without it no frame is decoded for the run. ComfyUI sends frames only when launched with
57
63
  * `--preview-method`, see `host.fetchPreviewMethod()` */
58
64
  onPreview?: (p: ExecutionPreview) => void
65
+ /** the Comfy account key for this run's paid partner API nodes; overrides the host's
66
+ * `comfyOrgApiKey`. Sent only when the prompt holds one, never saved */
67
+ comfyOrgApiKey?: ComfyOrgApiKeySource
59
68
  }
60
69
 
70
+ /** a Comfy Cloud host's X-API-Key is a platform.comfy.org key, the one partner nodes bill to */
71
+ const COMFY_CLOUD_HOST = 'cloud.comfy.org'
72
+
61
73
  /** exactly what was sent to the host for one execution, frozen at send time */
62
74
  export type ExecutionSnapshot = {
63
75
  apiJson: ComfyApiJson
@@ -385,6 +397,15 @@ export class ComfyWorkflow<ID extends string = string> {
385
397
  `🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`,
386
398
  )
387
399
  }
400
+ // the account key rides the posted body only, never the snapshot (architecture.md, Partner API nodes)
401
+ const partners = partnerApiNodes(snapshot.apiJson, this.schema)
402
+ let comfyOrgApiKey: string | undefined
403
+ if (partners.length > 0) {
404
+ const data = this.host.data
405
+ const cloudKey = data.apiKey != null && this.host.base.host === COMFY_CLOUD_HOST ? data.apiKey : undefined
406
+ comfyOrgApiKey = await resolveComfyOrgApiKey([p.comfyOrgApiKey, data.comfyOrgApiKey, cloudKey])
407
+ if (comfyOrgApiKey == null) throw new ComfyOrgApiKeyMissingError(data.id, partners)
408
+ }
388
409
  const out: ApiPromptInput = {
389
410
  client_id: this.host.comfySessionId,
390
411
  prompt: snapshot.apiJson,
@@ -395,6 +416,7 @@ export class ComfyWorkflow<ID extends string = string> {
395
416
  comfy_ts_workflow_id: this.id,
396
417
  comfy_ts_version: comfyts.version,
397
418
  },
419
+ ...(comfyOrgApiKey != null ? { api_key_comfy_org: comfyOrgApiKey } : {}),
398
420
  },
399
421
  }
400
422
 
@@ -14,7 +14,7 @@ const tempScope = scope({
14
14
 
15
15
  ApiPromptInput: {
16
16
  client_id: 'string',
17
- extra_data: { extra_pnginfo: 'unknown' },
17
+ extra_data: { extra_pnginfo: 'unknown', 'api_key_comfy_org?': 'string' },
18
18
  prompt: 'unknown',
19
19
  },
20
20
 
@@ -73,6 +73,8 @@ const tempScope = scope({
73
73
  // VideoHelperSuite's VHS_VideoCombine, and savers that name their list `video`
74
74
  'video?': 'ComfyImageInfo[]',
75
75
  'gifs?': 'ComfyImageInfo[]',
76
+ // native 3D savers (SaveGLB, SaveGaussianSplat, SavePointCloud): UI.Saved3DModels
77
+ '3d?': 'ComfyImageInfo[]',
76
78
  // ui payload of a text output node (PreviewAny, and how TextGenerate
77
79
  // results reach the client); entries are soft, non-strings are dropped
78
80
  'text?': 'unknown[]',
@@ -0,0 +1,44 @@
1
+ import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
2
+ import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
3
+
4
+ /** a Comfy account key, or a thunk read only when a run with a partner node starts */
5
+ export type ComfyOrgApiKeySource = string | (() => string | undefined | Promise<string | undefined>)
6
+
7
+ /** a partner API node of a prompt: what the error names */
8
+ export type PartnerApiNode = { id: string; classType: string }
9
+
10
+ /** the prompt holds a paid partner node and no Comfy account key was set */
11
+ export class ComfyOrgApiKeyMissingError extends Error {
12
+ /** name, not instanceof: the cli bundle and dist/index.js each define this class */
13
+ override readonly name = 'ComfyOrgApiKeyMissingError'
14
+ constructor(
15
+ public hostId: string,
16
+ public nodes: PartnerApiNode[],
17
+ ) {
18
+ const list = nodes.map((n) => `${n.classType} #${n.id}`).join(', ')
19
+ super(
20
+ `🔴 host '${hostId}': the prompt holds partner API node(s) ${list}, which bill a Comfy account, and no Comfy account key is set. ` +
21
+ `Set it with \`comfy.host({ id: '${hostId}', comfyOrgApiKey })\` or \`run({ comfyOrgApiKey })\` (a string or a thunk; the key comes from platform.comfy.org). Nothing was sent.`,
22
+ )
23
+ }
24
+ }
25
+
26
+ /** the nodes of a prompt whose schema says `api_node: true` */
27
+ export const partnerApiNodes = (apiJson: ComfyApiJson, schema: ComfySchema): PartnerApiNode[] => {
28
+ const out: PartnerApiNode[] = []
29
+ for (const [id, node] of Object.entries(apiJson))
30
+ if (schema.nodesByNameInComfy[node.class_type]?.raw.api_node === true) out.push({ id, classType: node.class_type })
31
+ return out
32
+ }
33
+
34
+ /** the first source set wins; an empty string counts as unset */
35
+ export const resolveComfyOrgApiKey = async (
36
+ sources: readonly (ComfyOrgApiKeySource | undefined)[],
37
+ ): Promise<string | undefined> => {
38
+ for (const src of sources) {
39
+ if (src == null) continue
40
+ const key = typeof src === 'string' ? src : await src()
41
+ if (key != null && key !== '') return key
42
+ }
43
+ return undefined
44
+ }
@@ -0,0 +1,53 @@
1
+ import { type } from 'arktype'
2
+ import { type PromptID, type PromptRelated_WsMsg, types } from 'src/runner/ComfyWsApi.ts'
3
+
4
+ const END_TYPES: ReadonlySet<string> = new Set(['execution_success', 'execution_error', 'execution_interrupted'])
5
+
6
+ export type HistoryReplay = {
7
+ /** one `executed` per output node the entry lists */
8
+ executed: PromptRelated_WsMsg[]
9
+ /** the end message: from `status.messages`, or a success when the entry says success (or, on an
10
+ * old server, says nothing). Null when the entry claims an end it does not carry */
11
+ end: PromptRelated_WsMsg | null
12
+ /** entries that did not pass the ws schemas, skipped */
13
+ problems: string[]
14
+ }
15
+
16
+ /** a prompt's `GET /history/<id>` reply as the ws messages a client missed. Null while the host has no
17
+ * entry for it: queued, running, or lost */
18
+ export function historyReplay(json: unknown, promptId: PromptID): HistoryReplay | null {
19
+ const entry = field(json, promptId)
20
+ if (entry == null) return null
21
+ const problems: string[] = []
22
+ const valid = (raw: unknown): PromptRelated_WsMsg | null => {
23
+ const res = types.PromptRelated_WsMsg(raw)
24
+ if (!(res instanceof type.errors)) return res
25
+ problems.push(`${JSON.stringify(raw).slice(0, 200)}: ${res.summary}`)
26
+ return null
27
+ }
28
+
29
+ const executed: PromptRelated_WsMsg[] = []
30
+ const outputs = field(entry, 'outputs')
31
+ if (typeof outputs === 'object' && outputs != null)
32
+ for (const [node, output] of Object.entries(outputs)) {
33
+ const msg = valid({ type: 'executed', data: { node, output, prompt_id: promptId } })
34
+ if (msg != null) executed.push(msg)
35
+ }
36
+
37
+ const status = field(entry, 'status')
38
+ const list = field(status, 'messages')
39
+ let end: PromptRelated_WsMsg | null = null
40
+ for (const m of Array.isArray(list) ? list : []) {
41
+ if (!Array.isArray(m) || typeof m[0] !== 'string' || !END_TYPES.has(m[0])) continue
42
+ end = valid({ type: m[0], data: m[1] })
43
+ }
44
+ const statusStr = field(status, 'status_str')
45
+ if (end == null && (status == null || statusStr === 'success'))
46
+ end = valid({ type: 'execution_success', data: { prompt_id: promptId, timestamp: Date.now() } })
47
+ return { executed, end, problems }
48
+ }
49
+
50
+ function field(x: unknown, key: string): unknown {
51
+ if (typeof x !== 'object' || x == null) return null
52
+ return Reflect.get(x, key) ?? null
53
+ }
@@ -0,0 +1,18 @@
1
+ // the 3D files an output node can publish (ui key `3d`), and their mimes. PURE + dependency-free.
2
+ // a sibling of mediaKinds.ts on purpose: MediaKind drives the media VARS, and a 3D output is no var kind
3
+
4
+ import { extensionOf } from 'src/runner/mediaKinds.ts'
5
+
6
+ /** ply and spz have no registered mime: the `x-` forms are what three.js and the splat viewers accept */
7
+ export const MODEL_3D_MIMES: Readonly<Record<string, string>> = {
8
+ glb: 'model/gltf-binary',
9
+ gltf: 'model/gltf+json',
10
+ ply: 'model/x-ply',
11
+ spz: 'model/x-spz',
12
+ obj: 'model/obj',
13
+ stl: 'model/stl',
14
+ }
15
+
16
+ export function model3dMime(filename: string): string {
17
+ return MODEL_3D_MIMES[extensionOf(filename)] ?? 'application/octet-stream'
18
+ }
@@ -27,6 +27,8 @@ export const ComfyUIObjectInfoScope = scope({
27
27
  // Stability Flags
28
28
  'deprecated?': 'boolean',
29
29
  'experimental?': 'boolean',
30
+ // a partner node: a paid service billed to a Comfy account, its key from extra_data.api_key_comfy_org
31
+ 'api_node?': 'boolean',
30
32
  },
31
33
  ComfyInputSpecAlt1: ['ComfyInputType', 'ComfyInputOpts'],
32
34
  ComfyInputSpecAlt2: ['ComfyInputType'],
@@ -318,10 +318,15 @@ export function codegenSDK(this: ComfySchema, opts: CodegenOptions): string {
318
318
  // 2/3
319
319
  p('')
320
320
  p('// named slot types: everything an input of that type accepts')
321
+ const slotTypeNames = new Set<string>(slotTypes.map((t) => t.comfyType))
321
322
  for (const t of slotTypes) {
322
- p(
323
- `${escapeJSKey(t.comfyType)}: ${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`,
323
+ const own = `${t.tsType} | HasSingle['${t.comfyType}'] | ((x: Producer['${t.comfyType}']) => Accepts['${t.comfyType}'])`
324
+ // `MESH,FILE_3D_GLB` takes an output of ANY listed type (SaveGLB's `mesh`)
325
+ const parts = t.comfyType.includes(',') ? t.comfyType.split(',').map((s) => s.trim()) : []
326
+ const anyOf = parts.map((part) =>
327
+ slotTypeNames.has(part) ? `Accepts['${part}']` : `ComfyNodeOutput<'${part}'>`,
324
328
  )
329
+ p(`${escapeJSKey(t.comfyType)}: ${[own, ...anyOf].join(' | ')}`)
325
330
  }
326
331
 
327
332
  // 3/3
package/src/state.ts CHANGED
@@ -75,6 +75,8 @@ export class ComfyTS {
75
75
  `host id '${data.id}' already registered ${cur == null ? 'with no address' : `at ${renderHttpBase(cur)}`}${authed(existing.data)} — refusing ${incoming == null ? 'the id alone' : renderHttpBase(incoming)}${authed(data)}`,
76
76
  )
77
77
  }
78
+ // a credential provider, not the address: a later registration hands it over, never drops it
79
+ if (data.comfyOrgApiKey != null) existing.data.comfyOrgApiKey = data.comfyOrgApiKey
78
80
  // cast: whitelist item 7 (agent/coding.md) — id equality checked just above
79
81
  return existing as ComfyHost<ID>
80
82
  }
@@ -204,6 +204,7 @@ export class DefinedWorkflow<ID extends string = string, V extends VarsSpec = Va
204
204
  log: settings.log,
205
205
  onProgress: settings.onProgress,
206
206
  onPreview: settings.onPreview,
207
+ comfyOrgApiKey: settings.comfyOrgApiKey,
207
208
  })
208
209
  this.lastExecution = execution
209
210
  return execution