comfy-ts 1.4.0 → 2.0.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 (89) hide show
  1. package/README.md +80 -6
  2. package/dist/{DefinedWorkflow-C_QAxKr3.js → DefinedWorkflow-CqNE_kgR.js} +4 -2
  3. package/dist/{DefinedWorkflow-C_QAxKr3.js.map → DefinedWorkflow-CqNE_kgR.js.map} +1 -1
  4. package/dist/{DraftsSt-DcOTn0QR.js → DraftsSt-Da4DZUP7.js} +2 -2
  5. package/dist/{DraftsSt-DcOTn0QR.js.map → DraftsSt-Da4DZUP7.js.map} +1 -1
  6. package/dist/cli.js +3 -3
  7. package/dist/index.cjs +212 -66
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.cts +72 -77
  10. package/dist/index.d.ts +72 -77
  11. package/dist/index.js +212 -66
  12. package/dist/index.js.map +1 -1
  13. package/dist/{run-serve-CN0DhrsA.js → run-serve-BqeXtf8P.js} +9 -7
  14. package/dist/run-serve-BqeXtf8P.js.map +1 -0
  15. package/dist/{run-tui-bN2hSD5i.js → run-tui-CiB7TbYv.js} +12 -6
  16. package/dist/run-tui-CiB7TbYv.js.map +1 -0
  17. package/dist/{state-COlKYipO.js → state-C1g_B8zR.js} +211 -67
  18. package/dist/state-C1g_B8zR.js.map +1 -0
  19. package/dist/web.d.ts +72 -77
  20. package/dist/web.js +212 -66
  21. package/dist/web.js.map +1 -1
  22. package/examples/comfy-cloud/ace-step-t2a.cflow.ts +1 -0
  23. package/examples/comfy-cloud/anima-t2i.cflow.ts +2 -3
  24. package/examples/comfy-cloud/boogu-i2i.cflow.ts +2 -5
  25. package/examples/comfy-cloud/capybara-i2i.cflow.ts +2 -2
  26. package/examples/comfy-cloud/capybara-i2v.cflow.ts +1 -0
  27. package/examples/comfy-cloud/capybara-t2i.cflow.ts +2 -2
  28. package/examples/comfy-cloud/chatterbox-t2a.cflow.ts +1 -0
  29. package/examples/comfy-cloud/chroma-t2i.cflow.ts +2 -5
  30. package/examples/comfy-cloud/ernie-t2i.cflow.ts +2 -3
  31. package/examples/comfy-cloud/firered-i2i.cflow.ts +2 -2
  32. package/examples/comfy-cloud/flux1-i2i.cflow.ts +2 -2
  33. package/examples/comfy-cloud/flux1-t2i.cflow.ts +2 -2
  34. package/examples/comfy-cloud/flux2-i2i.cflow.ts +2 -5
  35. package/examples/comfy-cloud/flux2-t2i.cflow.ts +2 -5
  36. package/examples/comfy-cloud/hidream-i2i.cflow.ts +2 -5
  37. package/examples/comfy-cloud/hidream-t2i.cflow.ts +2 -2
  38. package/examples/comfy-cloud/hunyuan-video-i2v.cflow.ts +1 -0
  39. package/examples/comfy-cloud/hunyuan-video-t2v.cflow.ts +1 -0
  40. package/examples/comfy-cloud/ideogram4-t2i.cflow.ts +2 -3
  41. package/examples/comfy-cloud/kandinsky5-i2v.cflow.ts +1 -0
  42. package/examples/comfy-cloud/kandinsky5-t2i.cflow.ts +2 -2
  43. package/examples/comfy-cloud/kandinsky5-t2v.cflow.ts +1 -0
  44. package/examples/comfy-cloud/krea2-t2i.cflow.ts +2 -3
  45. package/examples/comfy-cloud/lens-t2i.cflow.ts +2 -3
  46. package/examples/comfy-cloud/longcat-i2i.cflow.ts +2 -2
  47. package/examples/comfy-cloud/longcat-t2i.cflow.ts +2 -5
  48. package/examples/comfy-cloud/ltxv-i2v.cflow.ts +1 -0
  49. package/examples/comfy-cloud/ltxv-t2v.cflow.ts +1 -0
  50. package/examples/comfy-cloud/newbie-t2i.cflow.ts +2 -5
  51. package/examples/comfy-cloud/omnigen2-i2i.cflow.ts +2 -5
  52. package/examples/comfy-cloud/omnigen2-t2i.cflow.ts +2 -5
  53. package/examples/comfy-cloud/ovis-t2i.cflow.ts +2 -5
  54. package/examples/comfy-cloud/pixeldit-t2i.cflow.ts +2 -5
  55. package/examples/comfy-cloud/qwen-image-i2i.cflow.ts +2 -2
  56. package/examples/comfy-cloud/qwen-image-t2i.cflow.ts +2 -2
  57. package/examples/comfy-cloud/sd35-t2i.cflow.ts +2 -2
  58. package/examples/comfy-cloud/sdk.d.ts +13251 -11458
  59. package/examples/comfy-cloud/sdxl-t2i.cflow.ts +2 -2
  60. package/examples/comfy-cloud/stable-audio-t2a.cflow.ts +1 -0
  61. package/examples/comfy-cloud/svd-i2v.cflow.ts +1 -0
  62. package/examples/comfy-cloud/wan21-i2v.cflow.ts +1 -0
  63. package/examples/comfy-cloud/wan21-t2v.cflow.ts +1 -0
  64. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +1 -0
  65. package/examples/comfy-cloud/wan22-i2v.cflow.ts +1 -0
  66. package/examples/comfy-cloud/wan22-t2v.cflow.ts +1 -0
  67. package/examples/comfy-cloud/z-image-t2i.cflow.ts +2 -5
  68. package/examples/rvion/01-txt2img.cflow.ts +5 -3
  69. package/examples/rvion/02-img2img-upload.cflow.ts +5 -4
  70. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +6 -7
  71. package/examples/rvion/05-comfy-cloud.cflow.ts +4 -2
  72. package/examples/rvion/06-qwen-image-edit.cflow.ts +2 -3
  73. package/examples/web/example.ts +8 -1
  74. package/package.json +1 -1
  75. package/src/cli/serve/ServeApp.ts +9 -6
  76. package/src/cli/tui/state/ExecSt.ts +14 -2
  77. package/src/host/ComfyHost.ts +33 -1
  78. package/src/runner/ComfyExecution.ts +162 -74
  79. package/src/runner/ComfyWorkflow.ts +25 -3
  80. package/src/runner/ComfyWsApi.ts +6 -0
  81. package/src/runner/MediaImage.ts +58 -11
  82. package/src/runner/ephemeral.ts +21 -0
  83. package/src/runner/outputPath.ts +2 -2
  84. package/src/sdk-generator/_pythonModuleToNamespace.ts +3 -0
  85. package/src/types/index.ts +6 -2
  86. package/src/vars/DefinedWorkflow.ts +3 -1
  87. package/dist/run-serve-CN0DhrsA.js.map +0 -1
  88. package/dist/run-tui-bN2hSD5i.js.map +0 -1
  89. package/dist/state-COlKYipO.js.map +0 -1
@@ -9,7 +9,8 @@ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
9
9
  import { importSharp } from 'src/utils/lazySharp.ts'
10
10
  import { getPngMetadataFromUint8Array } from 'src/image-utils/_getPngMetadata.ts'
11
11
  import type { ComfyNodeId } from 'src/graph/ComfyNodeID.ts'
12
- import { asAbsolutePath, type ImageSaveFormat, type Maybe } from 'src/types/index.ts'
12
+ import { type AbsolutePath, asAbsolutePath, type Maybe, type SaveOptions } from 'src/types/index.ts'
13
+ import { bang } from 'src/utils/bang.ts'
13
14
  import { exhaust } from 'src/utils/exhaust.ts'
14
15
  import type { ComfyExecutionStatus } from 'src/runner/ComfyExecutionStatus.ts'
15
16
  import type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport } from 'src/runner/ComfyWorkflow.ts'
@@ -17,7 +18,7 @@ import type { ComfyWorkflow, ComfyWorkflowID, ExecutionSnapshot, ProgressReport
17
18
  import type {
18
19
  ComfyImageInfo,
19
20
  PromptID,
20
- PromptRelated_WsMsg,
21
+ PendingWsItem,
21
22
  WsMsgExecuted,
22
23
  WsMsgExecuting,
23
24
  WsMsgExecutionError,
@@ -49,14 +50,18 @@ export class ComfyExecution {
49
50
  public data: ComfyExecutionData,
50
51
  init: {
51
52
  snapshot?: ExecutionSnapshot
52
- saveFormat?: Maybe<ImageSaveFormat>
53
+ save?: Maybe<boolean | SaveOptions>
54
+ scrubHistory?: boolean
55
+ ephemeral?: boolean
53
56
  onProgress?: Maybe<(p: ExecutionProgress) => void>
54
57
  logProgress?: boolean
55
58
  } = {},
56
59
  ) {
57
60
  // settings FIRST: onCreate flushes buffered ws messages whose handlers read them
58
61
  this.snapshot = init.snapshot ?? null
59
- this.saveFormat = init.saveFormat ?? null
62
+ this.save = init.save === true ? {} : init.save === false ? null : (init.save ?? null)
63
+ this.scrubHistory = init.scrubHistory ?? false
64
+ this.ephemeral = init.ephemeral ?? false
60
65
  this.onProgress = init.onProgress ?? null
61
66
  this.logProgress = init.logProgress ?? false
62
67
  // register with the host so websocket messages route here,
@@ -65,8 +70,12 @@ export class ComfyExecution {
65
70
  this.onCreate()
66
71
  }
67
72
 
68
- // post-process
69
- saveFormat: Maybe<ImageSaveFormat> = null
73
+ /** local disk saving, OPT-IN (architecture.md item 14); null = outputs stay in memory */
74
+ save: Maybe<SaveOptions> = null
75
+ /** delete this run's server history entry after `done` */
76
+ scrubHistory: boolean = false
77
+ /** this run's SaveImage nodes were rewritten to SaveImageWebsocket in the snapshot */
78
+ ephemeral: boolean = false
70
79
 
71
80
  /** exactly what was sent to the host, frozen at send time (replayable) */
72
81
  snapshot: Maybe<ExecutionSnapshot> = null
@@ -141,8 +150,14 @@ export class ComfyExecution {
141
150
  return this.data.status ?? 'New'
142
151
  }
143
152
 
144
- onPromptRelatedMessage = (msg: PromptRelated_WsMsg): void => {
153
+ onPromptRelatedMessage = (msg: PendingWsItem): void => {
145
154
  const graph = this.workflow
155
+ // replayed pre-registration binary frame: an OUTPUT only when the ws
156
+ // saver was executing at this point of the stream; stale latents drop
157
+ if (msg.type === 'binary_preview_frame') {
158
+ if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })
159
+ return
160
+ }
146
161
  if (msg.type === 'execution_start') return
147
162
  else if (msg.type === 'execution_cached') graph.onExecutionCached(msg)
148
163
  else if (msg.type === 'executing') this.onExecuting(msg)
@@ -193,8 +208,9 @@ export class ComfyExecution {
193
208
  }
194
209
  private pendingPromises: Promise<void>[] = []
195
210
 
196
- /** image retrievals that failed (their images are missing from `images`) */
197
- imageErrors: { image: ComfyImageInfo; error: unknown }[] = []
211
+ /** image retrievals that failed (their images are missing from `images`);
212
+ * `image` is null for SaveImageWebsocket frames (no server-side file info exists) */
213
+ imageErrors: { image: Maybe<ComfyImageInfo>; error: unknown }[] = []
198
214
 
199
215
  retrieveImage = async (
200
216
  //
@@ -203,101 +219,151 @@ export class ComfyExecution {
203
219
  ): Promise<void> => {
204
220
  // retrieve the node
205
221
  const promptNode = this.workflow.data.apiJson?.[promptNodeID]
206
- const promptMeta = this.workflow.data.metadata?.[promptNodeID]
207
222
  if (promptNode == null) throw new Error(`❌ invariant violation: promptNode is null`)
208
223
 
209
224
  // image route on the host (cloud answers a 302 signed url — fetchFile follows it unauthed)
210
225
  const imgRoute = '/view?' + new URLSearchParams(comfyImageInfo).toString()
226
+ const response = await this.host.fetchFile(imgRoute)
227
+ const bytes = new Uint8Array(await response.arrayBuffer())
228
+
229
+ const comfyUIInfos = { comfyImageInfo, comfyHostHttpURL: this.host.getServerHostHTTP() }
230
+
231
+ // local saving is OPT-IN (architecture.md item 14): no save → in-memory only
232
+ const sf = this.save
233
+ if (sf == null) {
234
+ return this.pushImage(
235
+ new MediaImage({ buffer: bytes, execution: this, promptNodeID: promptNodeID, comfyUIInfos }),
236
+ promptNodeID,
237
+ )
238
+ }
211
239
 
212
- // target path on disk: OUR naming, never the raw server filename — a
213
- // cloud host resets its _00001_ counter per run, so the server name
214
- // overwrote the same local file on every run (his repro 2026-07-31)
215
- const sf = this.saveFormat
216
240
  const promptPrefix = promptNode.inputs['filename_prefix']
217
- let absPath: string = comfyts.resolveFromOutput(
218
- localOutputPath({
219
- localDir: sf?.prefix,
220
- filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,
221
- subfolder: comfyImageInfo.subfolder,
222
- filename: comfyImageInfo.filename,
223
- timestamp: runTimestamp(new Date(this.startedAt)),
241
+ const written = await this.encodeAndWrite({
242
+ bytes,
243
+ sf,
244
+ filenamePrefix: typeof promptPrefix === 'string' ? promptPrefix : undefined,
245
+ subfolder: comfyImageInfo.subfolder,
246
+ filename: comfyImageInfo.filename,
247
+ })
248
+ this.pushImage(
249
+ new MediaImage({
250
+ path: written.path,
251
+ buffer: written.bytes,
252
+ execution: this,
253
+ promptNodeID: promptNodeID,
254
+ comfyUIInfos,
224
255
  }),
256
+ promptNodeID,
225
257
  )
226
- if (sf?.format && sf.format !== 'raw') {
227
- const extension = sf.format.split('/')[1]
228
- absPath += '.' + extension
229
- }
230
- // last-resort uniquifier: bump past files on disk AND paths claimed by
231
- // still-downloading retrievals — never overwrite
232
- const storage = getComfyStorage()
233
- absPath = uniquifyOutputPath({ path: absPath, exists: (p) => storage.exists(p), claimed: CLAIMED_OUTPUT_PATHS })
234
-
235
- // ref
236
- let img: MediaImage
258
+ }
237
259
 
238
- // RE-ENCODE (COMPRESSED)
239
- if (sf && sf.format !== 'raw') {
240
- const response = await this.host.fetchFile(imgRoute)
241
- const buff = await response.arrayBuffer()
260
+ /** re-encode when asked, then write under OUR local naming — never the raw
261
+ * server filename: a cloud host resets its _00001_ counter per run, so the
262
+ * server name overwrote the same local file on every run (his repro 2026-07-31) */
263
+ private encodeAndWrite = async (p: {
264
+ bytes: Uint8Array
265
+ sf: SaveOptions
266
+ filenamePrefix?: string
267
+ subfolder: string
268
+ filename: string
269
+ }): Promise<{ path: AbsolutePath; bytes: Uint8Array }> => {
270
+ let bytes = p.bytes
271
+ const reencode = p.sf.format != null && p.sf.format !== 'raw'
272
+ if (reencode) {
273
+ // PNG text chunk (workflow provenance) survives the re-encode as EXIF
242
274
  let textChunk = {}
243
275
  try {
244
- const res = getPngMetadataFromUint8Array(new Uint8Array(buff))
276
+ const res = getPngMetadataFromUint8Array(p.bytes)
245
277
  if (res.success) textChunk = res.value
246
278
  } catch {}
247
279
 
248
280
  const format = ((): keyof FormatEnum => {
249
- if (sf.format === 'image/jpeg') return 'jpeg'
250
- if (sf.format === 'image/png') return 'png'
251
- if (sf.format === 'image/webp') return 'webp'
281
+ if (p.sf.format === 'image/jpeg') return 'jpeg'
282
+ if (p.sf.format === 'image/webp') return 'webp'
252
283
  return 'png'
253
284
  })()
254
285
 
255
- // node-only branch: re-encoding needs sharp (saveFormat 'raw' is the web path)
256
- const sharp = await importSharp(`saveFormat '${sf.format}' re-encoding`)
257
- const encoded = await sharp(buff)
286
+ // node-only branch: re-encoding needs sharp (save 'raw' is the web path)
287
+ const sharp = await importSharp(`save format '${p.sf.format}' re-encoding`)
288
+ const encoded = await sharp(p.bytes)
258
289
  .withMetadata()
259
290
  .withExif({ IFD0: textChunk })
260
291
  // sharp expect quality between 1 and 100
261
- .toFormat(format, sf.quality ? { quality: Math.round(sf.quality * 100) } : undefined)
292
+ .toFormat(format, p.sf.quality ? { quality: Math.round(p.sf.quality * 100) } : undefined)
262
293
  .toBuffer()
263
- storage.writeBytes(asAbsolutePath(absPath), new Uint8Array(encoded))
264
-
265
- img = new MediaImage({
266
- path: asAbsolutePath(absPath),
267
- buffer: new Uint8Array(encoded),
268
- execution: this,
269
- promptNodeID: promptNodeID,
270
- comfyUIInfos: {
271
- comfyImageInfo: comfyImageInfo,
272
- comfyHostHttpURL: this.host.getServerHostHTTP(),
273
- },
274
- })
294
+ bytes = new Uint8Array(encoded)
275
295
  }
276
296
 
277
- // SAVE RAW ------------------------------------------------------------------------------------------
278
- else {
279
- const response = await this.host.fetchFile(imgRoute)
280
- const buff = await response.arrayBuffer()
281
- const uint8arr = new Uint8Array(buff)
282
- storage.writeBytes(asAbsolutePath(absPath), uint8arr)
283
- img = new MediaImage({
284
- path: asAbsolutePath(absPath),
285
- buffer: uint8arr,
286
- execution: this,
287
- promptNodeID: promptNodeID,
288
- comfyUIInfos: {
289
- comfyImageInfo: comfyImageInfo,
290
- comfyHostHttpURL: this.host.getServerHostHTTP(),
291
- },
292
- })
293
- }
297
+ let absPath: string = comfyts.resolveFromOutput(
298
+ localOutputPath({
299
+ localDir: p.sf.prefix,
300
+ filenamePrefix: p.filenamePrefix,
301
+ subfolder: p.subfolder,
302
+ filename: p.filename,
303
+ timestamp: runTimestamp(new Date(this.startedAt)),
304
+ }),
305
+ )
306
+ if (reencode) absPath += '.' + bang(p.sf.format).split('/')[1]
307
+ // last-resort uniquifier: bump past files on disk AND paths claimed by
308
+ // still-downloading retrievals — never overwrite
309
+ const storage = getComfyStorage()
310
+ absPath = uniquifyOutputPath({ path: absPath, exists: (x) => storage.exists(x), claimed: CLAIMED_OUTPUT_PATHS })
311
+ storage.writeBytes(asAbsolutePath(absPath), bytes)
312
+ return { path: asAbsolutePath(absPath), bytes }
313
+ }
294
314
 
295
- // accumulate outputs on the prompt; tags from node metadata ride along
315
+ /** accumulate an output on the prompt; tags from node metadata ride along */
316
+ private pushImage(img: MediaImage, promptNodeID: Maybe<string>): void {
317
+ const promptMeta = promptNodeID != null ? this.workflow.data.metadata?.[promptNodeID] : null
296
318
  if (promptMeta?.tag) img.tags.push(promptMeta.tag)
297
319
  if (promptMeta?.tags) img.tags.push(...promptMeta.tags)
298
320
  this.images.push(img)
299
321
  }
300
322
 
323
+ /** true while the currently executing node is a SaveImageWebsocket in the
324
+ * SENT snapshot (the ephemeral rewrite only touches the snapshot, so the
325
+ * live graph may still say SaveImage) — binary frames are then OUTPUTS */
326
+ get wsOutputNodeExecuting(): boolean {
327
+ const uid = this.workflow.currentExecutingNode?.uid
328
+ if (uid == null) return false
329
+ const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson
330
+ return apiJson[uid]?.class_type === 'SaveImageWebsocket'
331
+ }
332
+
333
+ /** one binary ws frame = one output image of the executing SaveImageWebsocket
334
+ * node (architecture.md item 14 — the zero-server-disk path) */
335
+ onWsImageOutput = (p: { bytes: Uint8Array; mime: string }): void => {
336
+ const promptNodeID = this.workflow.currentExecutingNode?.uid ?? null
337
+ this.pendingPromises.push(
338
+ this.storeWsImage(p, promptNodeID).catch((e: unknown) => {
339
+ console.error(`🔴 failed to store a SaveImageWebsocket output:`, e)
340
+ this.imageErrors.push({ image: null, error: e })
341
+ }),
342
+ )
343
+ }
344
+
345
+ private storeWsImage = async (
346
+ p: { bytes: Uint8Array; mime: string },
347
+ promptNodeID: Maybe<string>,
348
+ ): Promise<void> => {
349
+ const sf = this.save
350
+ if (sf == null) {
351
+ return this.pushImage(new MediaImage({ buffer: p.bytes, execution: this, promptNodeID }), promptNodeID)
352
+ }
353
+ const ext = p.mime === 'image/jpeg' ? 'jpg' : (p.mime.split('/')[1] ?? 'png')
354
+ const written = await this.encodeAndWrite({
355
+ bytes: p.bytes,
356
+ sf,
357
+ subfolder: '',
358
+ // ws frames carry no server filename — the workflow id is the stem
359
+ filename: `${this.workflow.id}.${ext}`,
360
+ })
361
+ this.pushImage(
362
+ new MediaImage({ path: written.path, buffer: written.bytes, execution: this, promptNodeID }),
363
+ promptNodeID,
364
+ )
365
+ }
366
+
301
367
  /** images retrieved for this execution, in arrival order (final once `done` resolves) */
302
368
  images: MediaImage[] = []
303
369
 
@@ -314,6 +380,28 @@ export class ComfyExecution {
314
380
  // finished executions receive no further messages — free the routing maps
315
381
  this.host.executions.delete(this.data.id)
316
382
  this.host._pendingMsgs.delete(this.data.id)
383
+
384
+ // the inputs gap, stated loud (item 14): ephemeral covers OUTPUTS only —
385
+ // uploaded inputs persist in the server's input/ dir, no upstream delete API
386
+ if (this.ephemeral) {
387
+ const classTypes = Object.values(this.snapshot?.apiJson ?? {}).map((n) => n.class_type)
388
+ if (classTypes.includes('LoadImage') || classTypes.includes('LoadImageMask')) {
389
+ console.warn(
390
+ `🟡 ephemeral run ${this.data.id}: outputs never touched the server disk, but the graph's ` +
391
+ `LoadImage nodes reference files in the host's input/ folder (uploads persist — ComfyUI has ` +
392
+ `no delete API). Use MediaImage.loadInWorkflow_viaBase64Node to keep inputs off the server too.`,
393
+ )
394
+ }
395
+ }
396
+
397
+ // history scrub AFTER retrievals: loud but never fatal — a privacy
398
+ // feature that crashes the run would push users to disable it
399
+ if (this.scrubHistory) {
400
+ await this.host.deleteHistory(this.data.id).catch((e: unknown) => {
401
+ console.error(`🔴 failed to scrub history entry ${this.data.id} on host ${this.host.data.id}:`, e)
402
+ })
403
+ }
404
+
317
405
  this.finishProgressLine()
318
406
  this._resolve(this)
319
407
  }
@@ -8,9 +8,10 @@ import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
8
8
  import { ComfyNode } from 'src/graph/ComfyNode.ts'
9
9
  import type { ComfyNodeId, ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
10
10
  import { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
11
+ import { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'
11
12
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
12
13
  import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
13
- import { type AbsolutePath, type ImageSaveFormat, type Maybe, type Tagged } from 'src/types/index.ts'
14
+ import { type AbsolutePath, type Maybe, type SaveOptions, type Tagged } from 'src/types/index.ts'
14
15
  import type { SdkForHost } from 'src/types/comfy-sdk.ts'
15
16
  import { bang } from 'src/utils/bang.ts'
16
17
  import { deepCopyNaive } from 'src/utils/deepCopyNaive.ts'
@@ -35,7 +36,16 @@ export type ProgressReport = {
35
36
  export type ComfyNodeIdMode = 'use_stringified_numbers_only' | 'use_class_name_and_number'
36
37
 
37
38
  export type RunSettings = {
38
- saveFormat?: ImageSaveFormat
39
+ /** local disk saving is OPT-IN: unset/false keeps outputs in memory only
40
+ * (`execution.images` buffers); `true` = raw save, an object re-encodes/relocates */
41
+ save?: boolean | SaveOptions
42
+ /** rewrite every SaveImage node to SaveImageWebsocket in the SENT prompt —
43
+ * outputs never touch the server disk. Implies `scrubHistory` unless that
44
+ * is explicitly false. (architecture.md item 14) */
45
+ ephemeral?: boolean
46
+ /** delete this run's server history entry (workflow JSON, prompts, filenames)
47
+ * after `done` — loud but non-fatal on failure */
48
+ scrubHistory?: boolean
39
49
  idMode?: ComfyNodeIdMode
40
50
  /** render a live single-line progress report to the console */
41
51
  log?: boolean
@@ -350,6 +360,15 @@ export class ComfyWorkflow<ID extends string = string> {
350
360
  apiJson: deepCopyNaive(this.toApiJson(p.idMode ?? 'use_stringified_numbers_only')),
351
361
  workflowJson: await this.toWorkflowJson(),
352
362
  }
363
+ // ephemeral: rewrite in the SNAPSHOT only — the live graph stays editable/exportable as authored
364
+ if (p.ephemeral) {
365
+ const rewritten = rewriteSaveNodesToWebsocket(snapshot.apiJson)
366
+ const hasWsSaver = Object.values(snapshot.apiJson).some((n) => n.class_type === 'SaveImageWebsocket')
367
+ if (rewritten === 0 && !hasWsSaver)
368
+ console.warn(
369
+ `🟡 ephemeral run: no SaveImage/SaveImageWebsocket node in workflow '${this.id}' — nothing streams back`,
370
+ )
371
+ }
353
372
  const out: ApiPromptInput = {
354
373
  client_id: this.host.comfySessionId,
355
374
  prompt: snapshot.apiJson,
@@ -385,7 +404,10 @@ export class ComfyWorkflow<ID extends string = string> {
385
404
  },
386
405
  {
387
406
  snapshot,
388
- saveFormat: p.saveFormat,
407
+ save: p.save,
408
+ ephemeral: p.ephemeral ?? false,
409
+ // ephemeral implies the scrub unless the caller explicitly opted out
410
+ scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
389
411
  onProgress: p.onProgress,
390
412
  logProgress: p.log ?? false,
391
413
  },
@@ -140,6 +140,12 @@ export type NodeProgress = typeof types.NodeProgress.infer
140
140
 
141
141
  // LIVE UPDATES ----------------------------------------------------
142
142
  export type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer
143
+
144
+ /** a binary preview-kind ws frame buffered IN ORDER with the json messages
145
+ * during the pre-registration window (ComfyHost._pendingMsgs) — replayed by
146
+ * ComfyExecution.onCreate, which decides output-vs-latent at replay time */
147
+ export type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string }
148
+ export type PendingWsItem = PromptRelated_WsMsg | PendingBinaryFrame
143
149
  export type WsMsg = typeof types.WsMsg.infer
144
150
  export type ComfyStatusData = typeof types.ComfyStatusData.infer
145
151
  export type WsMsgStatus = typeof types.WsMsgStatus.infer
@@ -7,7 +7,7 @@ import { importSharp } from 'src/utils/lazySharp.ts'
7
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
8
8
  import type { ComfyNodeMetadata } from 'src/graph/ComfyNodeID.ts'
9
9
  import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
10
- import type { AbsolutePath, Maybe } from 'src/types/index.ts'
10
+ import { type AbsolutePath, asAbsolutePath, type Maybe } from 'src/types/index.ts'
11
11
  import type { NodeOf } from 'src/types/comfy-sdk.ts'
12
12
  import type { ComfyImageName } from 'src/sdk-generator/comfyui-types.ts'
13
13
  import { bang } from 'src/utils/bang.ts'
@@ -15,9 +15,23 @@ import { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'
15
15
  import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
16
16
  import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
17
17
  import { type ComfyImageInfo, ComfyImageInfo_ark } from 'src/runner/ComfyWsApi.ts'
18
+ import { ComfyNode } from 'src/graph/ComfyNode.ts'
19
+
20
+ /** base64 image loader nodes we know how to wire, in preference order — each
21
+ * verified against a real object_info dump before entering the table */
22
+ export const BASE64_IMAGE_LOADERS: { nameInComfy: string; inputs: (b64: string) => ComfyApiNodeJson['inputs'] }[] = [
23
+ // comfyui-tooling-nodes: outputs IMAGE + MASK (alpha)
24
+ { nameInComfy: 'ETN_LoadImageBase64', inputs: (b64) => ({ image: b64 }) },
25
+ // ComfyUI-Easy-Use: image_output 'Hide' + empty prefix so the node itself saves nothing
26
+ {
27
+ nameInComfy: 'easy loadImageBase64',
28
+ inputs: (b64) => ({ base64_data: b64, image_output: 'Hide', save_prefix: '' }),
29
+ },
30
+ ]
18
31
 
19
32
  export type MediaImageData = {
20
- path: AbsolutePath
33
+ /** absent = in-memory image (ws output with local saving off) — the buffer is then required */
34
+ path?: Maybe<AbsolutePath>
21
35
 
22
36
  // to avoid having to read the file if we already have the buffer around
23
37
  buffer?: Uint8Array
@@ -40,7 +54,8 @@ export const ImageInfos_ComfyGenerated_ark = type({
40
54
  })
41
55
 
42
56
  export class MediaImage {
43
- absPath: AbsolutePath
57
+ /** null for in-memory images (local saving is opt-in — architecture.md item 14) */
58
+ absPath: AbsolutePath | null
44
59
 
45
60
  /** the execution this image came from (null when not generated via comfy-ts) */
46
61
  execution: Maybe<ComfyExecution>
@@ -53,9 +68,11 @@ export class MediaImage {
53
68
  promptNodeID: Maybe<string>
54
69
 
55
70
  constructor(data: MediaImageData) {
56
- this.absPath = data.path
71
+ this.absPath = data.path ?? null
57
72
  this.execution = data.execution
58
73
  this.promptNodeID = data.promptNodeID
74
+ if (data.path == null && data.buffer == null)
75
+ throw new Error('❌ MediaImage: an in-memory image (no path) requires a buffer')
59
76
  if (data.buffer != null) this.updateBuffer(data.buffer)
60
77
  }
61
78
 
@@ -67,9 +84,10 @@ export class MediaImage {
67
84
  return new Blob([this.buffer as Uint8Array<ArrayBuffer>], { type: `image/${this.metadata.type ?? 'png'}` })
68
85
  }
69
86
 
70
- /** return the image filename */
87
+ /** return the image filename (in-memory images get a stable hash-derived name) */
71
88
  get filename(): string {
72
- return basename(this.absPath)
89
+ if (this.absPath != null) return basename(this.absPath)
90
+ return `image-${this.hash.slice(0, 8)}.${this.metadata.type ?? 'png'}`
73
91
  }
74
92
 
75
93
  get baseNameWithoutExtension(): string {
@@ -125,6 +143,31 @@ export class MediaImage {
125
143
  return mask as NodeOf<WID, 'LoadImageMask'>
126
144
  }
127
145
 
146
+ /** load this image into the workflow WITHOUT any server-side file: the
147
+ * image rides base64 inside the prompt JSON (architecture.md item 14 —
148
+ * the prompt still enters server history; `scrubHistory` covers that).
149
+ * Feature-detected against the host schema; no supported node = loud throw. */
150
+ loadInWorkflow_viaBase64Node = <WID extends string>(workflow: ComfyWorkflow<WID>): NodeOf<WID, 'LoadImage'> => {
151
+ const schema = workflow.host.schema
152
+ const entry = BASE64_IMAGE_LOADERS.find((t) => schema.nodes.some((n) => n.nameInComfy === t.nameInComfy))
153
+ if (entry == null) {
154
+ throw new Error(
155
+ `❌ host '${workflow.host.data.id}' has no base64 image loader node ` +
156
+ `(looked for: ${BASE64_IMAGE_LOADERS.map((t) => `'${t.nameInComfy}'`).join(', ')}). ` +
157
+ `Install one (e.g. comfyui-tooling-nodes) or fall back to loadInWorkflow_viaLoadImageNode (uploads persist server-side).`,
158
+ )
159
+ }
160
+ const node = new ComfyNode(
161
+ workflow,
162
+ (workflow._uidNumber++).toString(),
163
+ { class_type: entry.nameInComfy, inputs: entry.inputs(this.getBase64Payload()) },
164
+ {},
165
+ )
166
+ // sanctioned cast (family 1, like the two sibling loaders): both table
167
+ // nodes output IMAGE+MASK, the LoadImage face is the shape consumers wire
168
+ return node as NodeOf<WID, 'LoadImage'>
169
+ }
170
+
128
171
  /** return the json of the ComfyNode that led to this image */
129
172
  get ComfyNode(): Maybe<ComfyApiNodeJson> {
130
173
  const nodeID = this.promptNodeID
@@ -184,10 +227,13 @@ export class MediaImage {
184
227
  private _buffer: Maybe<Uint8Array> = null
185
228
  get buffer(): Uint8Array {
186
229
  if (this._buffer != null) return this._buffer
187
- this._buffer = getComfyStorage().readBytes(this.absPath)
230
+ this._buffer = getComfyStorage().readBytes(bang(this.absPath, 'in-memory MediaImage lost its buffer'))
188
231
  return this._buffer
189
232
  }
190
- freeBuffer = (): void => void (this._buffer = null)
233
+ /** no-op on in-memory images: the buffer is the only copy */
234
+ freeBuffer = (): void => {
235
+ if (this.absPath != null) this._buffer = null
236
+ }
191
237
  updateBuffer = (buff: Uint8Array): void => {
192
238
  this._buffer = buff
193
239
  this._metadata = null // expire metadata
@@ -225,7 +271,7 @@ export class MediaImage {
225
271
  ): Promise<this> => {
226
272
  const sharp = await importSharp('processWithSharp_inplace')
227
273
  const buff = await fn(sharp(this.buffer)).toBuffer()
228
- getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))
274
+ if (this.absPath != null) getComfyStorage().writeBytes(this.absPath, new Uint8Array(buff))
229
275
  this.updateBuffer(new Uint8Array(buff))
230
276
  return this
231
277
  }
@@ -242,9 +288,10 @@ export class MediaImage {
242
288
  path?: AbsolutePath,
243
289
  ): Promise<MediaImage> => {
244
290
  const sharp = await importSharp('processWithSharp')
245
- path ??= this.absPath + `.processed-${Date.now()}` + this.extension
291
+ path ??=
292
+ this.absPath != null ? asAbsolutePath(this.absPath + `.processed-${Date.now()}` + this.extension) : undefined
246
293
  const buffer = new Uint8Array(await fn(sharp(this.buffer)).toBuffer())
247
- getComfyStorage().writeBytes(path, buffer)
294
+ if (path != null) getComfyStorage().writeBytes(path, buffer)
248
295
  return new MediaImage({ path, buffer })
249
296
  }
250
297
  }
@@ -0,0 +1,21 @@
1
+ import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
2
+
3
+ /**
4
+ * the `ephemeral: true` rewrite (architecture.md item 14): every SaveImage
5
+ * node in the SENT snapshot becomes a SaveImageWebsocket (core node, `images`
6
+ * input only), so outputs stream over the ws and never touch the server disk.
7
+ * Mutates the given apiJson IN PLACE — callers pass the run's deep-copied
8
+ * snapshot, never the live graph. Returns how many nodes were rewritten so
9
+ * callers can warn when a graph had nothing to rewrite.
10
+ */
11
+ export function rewriteSaveNodesToWebsocket(apiJson: ComfyApiJson): number {
12
+ let rewritten = 0
13
+ for (const node of Object.values(apiJson)) {
14
+ if (node.class_type !== 'SaveImage') continue
15
+ const images = node.inputs['images']
16
+ node.class_type = 'SaveImageWebsocket'
17
+ node.inputs = images == null ? {} : { images }
18
+ rewritten++
19
+ }
20
+ return rewritten
21
+ }
@@ -4,12 +4,12 @@
4
4
  * `_00001_` counter every run, so trusting it overwrote the same file — and
5
5
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
6
6
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
7
- * (or an explicit saveFormat.prefix override), then
7
+ * (or an explicit save.prefix override), then
8
8
  * `<stem>_<timestamp>_<counter><ext>` so every run sorts chronologically
9
9
  * per stem and nothing ever collides.
10
10
  */
11
11
  export const localOutputPath = (p: {
12
- /** explicit local dir override (ImageSaveFormat.prefix) — wins when set */
12
+ /** explicit local dir override (SaveOptions.prefix) — wins when set */
13
13
  localDir?: string
14
14
  /** the SaveImage node's own filename_prefix as sent in the prompt */
15
15
  filenamePrefix?: string
@@ -2,6 +2,9 @@ export function pythonModuleToPrefix(pythonModule: string): string {
2
2
  // if (pythonModule == null) console.error(`[🔴🔴🔴🔴🔴🔴] `, pythonModule)
3
3
  if (pythonModule === 'nodes') return ''
4
4
  if (pythonModule.startsWith('comfy_extras.')) return '' //''
5
+ // ships INSIDE the ComfyUI repo (upstream parks it under custom_nodes/):
6
+ // the ephemeral-outputs saver reads `b.SaveImageWebsocket` like the core node it is
7
+ if (pythonModule === 'custom_nodes.websocket_image_save') return ''
5
8
  if (pythonModule.startsWith('comfy_api_nodes.')) return pythonModule.replace('comfy_api_nodes.', 'api.')
6
9
  if (pythonModule.startsWith('custom_nodes.')) {
7
10
  // return `${pythonModuleToNamespace_(pythonModule.replace('custom_nodes.', ''))}.`
@@ -24,9 +24,13 @@ export const asRelativePath = (path: string): RelativePath => path as RelativePa
24
24
 
25
25
  // #region Image
26
26
  export type ConvertibleImageFormat = 'image/png' | 'image/jpeg' | 'image/webp' | 'raw'
27
- export type ImageSaveFormat = {
28
- format: ConvertibleImageFormat
27
+ /** local disk saving is OPT-IN per run: `save: true` = raw bytes, an object re-encodes/relocates */
28
+ export type SaveOptions = {
29
+ /** 'raw' (default) writes the bytes untouched; an image/* mime re-encodes through sharp */
30
+ format?: ConvertibleImageFormat
31
+ /** local dir under `.comfy-ts/outputs/` (wins over the prompt's own filename_prefix) */
29
32
  prefix?: string
33
+ /** 0..1, re-encode only */
30
34
  quality?: number
31
35
  }
32
36
 
@@ -119,7 +119,9 @@ export class DefinedWorkflow<ID extends string = string, V extends VarsSpec = Va
119
119
  await host.connect()
120
120
  const wf = await this.build({ advance: true, host })
121
121
  const execution = await wf.run({
122
- saveFormat: settings.saveFormat,
122
+ save: settings.save,
123
+ ephemeral: settings.ephemeral,
124
+ scrubHistory: settings.scrubHistory,
123
125
  idMode: settings.idMode,
124
126
  log: settings.log,
125
127
  onProgress: settings.onProgress,