comfy-ts 2.16.0 → 2.17.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 (59) hide show
  1. package/README.md +23 -0
  2. package/dist/{run-serve-C78hD7t9.js → ServeApp-BSA5yzxZ.js} +17 -444
  3. package/dist/ServeApp-BSA5yzxZ.js.map +1 -0
  4. package/dist/cli.js +18 -5
  5. package/dist/cli.js.map +1 -1
  6. package/dist/exampleAssets-BfWzygoM.js +38 -0
  7. package/dist/exampleAssets-BfWzygoM.js.map +1 -0
  8. package/dist/{LogsSt-Ct7Le0S_.js → findDefinedWorkflow-0lG-VTEd.js} +201 -201
  9. package/dist/findDefinedWorkflow-0lG-VTEd.js.map +1 -0
  10. package/dist/index.cjs +146 -59
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +61 -8
  13. package/dist/index.d.ts +61 -8
  14. package/dist/index.js +146 -59
  15. package/dist/index.js.map +1 -1
  16. package/dist/run-run-DnaMLCFn.js +450 -0
  17. package/dist/run-run-DnaMLCFn.js.map +1 -0
  18. package/dist/run-serve-CbKxIu6i.js +418 -0
  19. package/dist/run-serve-CbKxIu6i.js.map +1 -0
  20. package/dist/{run-tui-nPETFRmk.js → run-tui-B0AQWbad.js} +6 -37
  21. package/dist/run-tui-B0AQWbad.js.map +1 -0
  22. package/dist/{schemaDrift-wb5XkrHV.js → schemaDrift-CbsABBuk.js} +3 -2
  23. package/dist/{schemaDrift-wb5XkrHV.js.map → schemaDrift-CbsABBuk.js.map} +1 -1
  24. package/dist/serve-web.js +37 -37
  25. package/dist/{state-BMW57_M0.js → state-C2oDiQ26.js} +146 -60
  26. package/dist/state-C2oDiQ26.js.map +1 -0
  27. package/dist/web.d.ts +61 -8
  28. package/dist/web.js +146 -59
  29. package/dist/web.js.map +1 -1
  30. package/examples/README.md +1 -0
  31. package/examples/rvion/15-tts-voice-clone.cflow.ts +8 -8
  32. package/examples/rvion/16-tts-voice-design.cflow.ts +71 -0
  33. package/guide-for-agents.md +3 -0
  34. package/package.json +1 -1
  35. package/src/cli/comfy-ts-cli.ts +14 -1
  36. package/src/cli/run/findModules.ts +36 -0
  37. package/src/cli/run/flagValue.ts +61 -0
  38. package/src/cli/run/outputPaths.ts +41 -0
  39. package/src/cli/run/pickModule.ts +41 -0
  40. package/src/cli/run/run-run.ts +250 -0
  41. package/src/cli/run/runArgs.ts +61 -0
  42. package/src/cli/run/sidecar.ts +27 -0
  43. package/src/cli/serve/ServeApp.ts +13 -39
  44. package/src/cli/serve/web/components/DraftTabs.tsx +8 -2
  45. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  46. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  47. package/src/coreExports.ts +2 -0
  48. package/src/host/ComfyHost.ts +73 -40
  49. package/src/host/previewMethod.ts +29 -0
  50. package/src/runner/ComfyExecution.ts +45 -1
  51. package/src/runner/ComfyWorkflow.ts +6 -1
  52. package/src/runner/ComfyWsApi.ts +1 -1
  53. package/src/runner/wsBinaryFrame.ts +48 -25
  54. package/src/vars/ComfyVars.ts +3 -0
  55. package/src/vars/DefinedWorkflow.ts +1 -0
  56. package/dist/LogsSt-Ct7Le0S_.js.map +0 -1
  57. package/dist/run-serve-C78hD7t9.js.map +0 -1
  58. package/dist/run-tui-nPETFRmk.js.map +0 -1
  59. package/dist/state-BMW57_M0.js.map +0 -1
@@ -0,0 +1,27 @@
1
+ // the text a media file carries beside it: a media var set from `clip.flac` whose declaration
2
+ // links a text var (`v.audio(path, { sidecarText })`) fills that var from `clip.txt`, unless the
3
+ // flags set it. The link is the workflow's, so run knows no var name
4
+ import type { AnyVar, MediaVar } from 'src/vars/ComfyVars.ts'
5
+ import { sidecarPath } from 'src/cli/run/outputPaths.ts'
6
+
7
+ const MEDIA = new Set(['image', 'audio', 'video'])
8
+
9
+ /** each var to fill, with the sidecar it comes from */
10
+ export function sidecarFills(
11
+ entries: readonly (readonly [string, AnyVar])[],
12
+ payload: Readonly<Record<string, unknown>>,
13
+ exists: (path: string) => boolean,
14
+ ): { name: string; from: string }[] {
15
+ const out: { name: string; from: string }[] = []
16
+ for (const [k, v] of entries) {
17
+ const path = payload[k]
18
+ // kind, never instanceof (agent/coding.md cast whitelist 6)
19
+ if (!MEDIA.has(v.kind) || typeof path !== 'string' || /^https?:\/\//.test(path)) continue
20
+ const linked = (v as MediaVar).opts.sidecarText
21
+ const name = linked == null ? null : entries.find(([, x]) => x === linked)?.[0]
22
+ if (name == null || name in payload || out.some((o) => o.name === name)) continue
23
+ const from = sidecarPath(path)
24
+ if (exists(from)) out.push({ name, from })
25
+ }
26
+ return out
27
+ }
@@ -111,7 +111,13 @@ export type ServeExecution = {
111
111
 
112
112
  export type ServeStarter = (
113
113
  mod: ServeModule,
114
- opts: { saveToDisk: boolean; savePrefix: string; host?: ComfyHost },
114
+ opts: {
115
+ saveToDisk: boolean
116
+ savePrefix: string
117
+ host?: ComfyHost
118
+ /** the run's live preview frames, feeding the /run/<module>/preview poll */
119
+ onPreview?: (p: { bytes: Uint8Array; mime: string }) => void
120
+ },
115
121
  ) => Promise<ServeExecution>
116
122
 
117
123
  export type ServeRequest = { method: string; url: string; accept?: string; body?: string }
@@ -231,7 +237,7 @@ const realStarter: ServeStarter = async (mod, opts) => {
231
237
  const wf = await mod.dw.build({ advance: true, host })
232
238
  // saving is a SETTING now (GET/PUT /settings): off keeps outputs in memory and the
233
239
  // reply points at /images/<promptId>/<ix> instead of a file url
234
- return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false })
240
+ return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false, onPreview: opts.onPreview })
235
241
  }
236
242
 
237
243
  const CONTENT_TYPES: Record<string, string> = {
@@ -1447,31 +1453,6 @@ export class ServeApp {
1447
1453
  /** seq counts frames so the poller refetches only on a NEW one, not every tick */
1448
1454
  private latentPreviews = new Map<string, { bytes: Uint8Array; mime: string; seq: number }>()
1449
1455
  private latentSeq = 0
1450
- /** promptId → module: `onLatentPreview` is ONE slot per host and two modules can share a
1451
- * host, so frames are routed by the prompt they belong to, never by "the last run started" */
1452
- private promptOwner = new Map<string, string>()
1453
- private latentHosts = new Set<ComfyHost>()
1454
-
1455
- private runningModules(): string[] {
1456
- return [...this.liveRuns.entries()]
1457
- .filter(([, e]) => e.status !== 'Success' && e.status !== 'Failure')
1458
- .map(([key]) => key)
1459
- }
1460
-
1461
- /** one dispatcher per host, installed once and left in place (idempotent) */
1462
- private wireLatents(host: ComfyHost): void {
1463
- if (this.latentHosts.has(host)) return
1464
- this.latentHosts.add(host)
1465
- host.onLatentPreview = (p) => {
1466
- const owner = p.promptID != null ? this.promptOwner.get(p.promptID) : undefined
1467
- // an unattributable frame (no promptID yet, e.g. before start() returned) is only
1468
- // safe to show when exactly ONE run is live; otherwise drop it rather than lie
1469
- const running = this.runningModules()
1470
- const key = owner ?? (running.length === 1 ? running[0] : undefined)
1471
- if (key == null) return
1472
- this.latentPreviews.set(key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq })
1473
- }
1474
- }
1475
1456
 
1476
1457
  private replyRunStatus(modKey: string): ServeReply {
1477
1458
  const mod = this.moduleByKey(modKey)
@@ -1635,13 +1616,8 @@ export class ServeApp {
1635
1616
 
1636
1617
  const execution = started.execution
1637
1618
  this.liveRuns.set(mod.key, execution)
1638
- this.promptOwner.set(execution.data.id, mod.key)
1639
1619
  console.log(`[serve] → ${mod.key}/${draft} (prompt ${execution.data.id})`)
1640
- try {
1641
- await execution.done
1642
- } finally {
1643
- this.promptOwner.delete(execution.data.id)
1644
- }
1620
+ await execution.done
1645
1621
  const durationMs = Date.now() - t0
1646
1622
 
1647
1623
  if (execution.status === 'Failure') {
@@ -1858,20 +1834,18 @@ export class ServeApp {
1858
1834
  }
1859
1835
 
1860
1836
  // 5. send (build + POST /prompt); the wait for outputs happens OUTSIDE the mutex.
1861
- // latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
1862
- // the previous run's preview must not linger over the new one
1837
+ // the run's own preview frames feed the web ui's /run/<module>/preview poll; the
1838
+ // previous run's preview must not linger over the new one
1863
1839
  this.latentPreviews.delete(mod.key)
1864
- // the host the run ACTUALLY goes to: onLatentPreview is one slot per ComfyHost, so
1865
- // wiring the defining host while running on an override left the override host with no
1866
- // dispatcher, the panel simply never saw a frame, with nothing to say why
1867
1840
  const runHost = this.runHostFor(mod)
1868
- this.wireLatents(runHost ?? mod.dw.host)
1869
1841
  try {
1870
1842
  return {
1871
1843
  execution: await this.starter(mod, {
1872
1844
  saveToDisk: this.settings.saveToDisk,
1873
1845
  savePrefix: this.savePrefixFor(mod.key),
1874
1846
  host: runHost ?? undefined,
1847
+ onPreview: (p) =>
1848
+ this.latentPreviews.set(mod.key, { bytes: p.bytes, mime: p.mime, seq: ++this.latentSeq }),
1875
1849
  }),
1876
1850
  }
1877
1851
  } catch (e) {
@@ -1,6 +1,6 @@
1
1
  // the open drafts as tabs over the work area: a click opens one (a click on the open one shows
2
2
  // its actions), × or a middle click closes it, ⌘1 to ⌘8 pick one, ⌘9 the last, ⌘PageUp and
3
- // ⌘PageDown step (ctrl elsewhere), from any focus
3
+ // ⌘PageDown step, ⌘W closes the open one unless it is the last (ctrl elsewhere), from any focus
4
4
  import {
5
5
  autoUpdate,
6
6
  flip,
@@ -15,7 +15,7 @@ import { observer } from 'mobx-react-lite'
15
15
  import { useEffect, useState } from 'react'
16
16
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
17
17
  import { MOD_KEY } from 'src/cli/serve/web/components/modKey.ts'
18
- import { tabForKey, tabStepForKey, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
18
+ import { tabForKey, tabStepForKey, tabToCloseForKey, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
19
19
  import { shortcutLabel } from 'src/cli/serve/web/state/shortcuts.ts'
20
20
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
21
21
  import { onEscape } from 'src/cli/serve/web/state/escape.ts'
@@ -23,6 +23,12 @@ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
23
23
  export function useTabShortcuts(st: WebSt): void {
24
24
  useEffect(() => {
25
25
  const onKey = (e: KeyboardEvent): void => {
26
+ const closing = tabToCloseForKey(st.tabs, st.activeTab, e)
27
+ if (closing != null) {
28
+ e.preventDefault()
29
+ st.closeTab(closing)
30
+ return
31
+ }
26
32
  const t = tabForKey(st.tabs, e) ?? tabStepForKey(st.tabs, st.activeTab, e)
27
33
  if (t == null) return
28
34
  e.preventDefault()
@@ -59,6 +59,18 @@ export function tabStepForKey(
59
59
  return tabs[(ix + dir + tabs.length) % tabs.length] ?? null
60
60
  }
61
61
 
62
+ /** ⌘W (ctrl elsewhere): the open tab, while another one is left. On the last tab it is null, so
63
+ * the key goes through and the desktop shell closes its window */
64
+ export function tabToCloseForKey(
65
+ tabs: readonly DraftTab[],
66
+ active: DraftTab | null,
67
+ e: { key: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean },
68
+ ): DraftTab | null {
69
+ if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return null
70
+ if (e.key.toLowerCase() !== 'w' || active == null || tabs.length < 2) return null
71
+ return tabs.find((x) => same(x, active)) ?? null
72
+ }
73
+
62
74
  /** a stored list, shape-checked, keeping only drafts that still exist */
63
75
  export function readTabs(raw: unknown, modules: readonly { module: string; drafts: readonly string[] }[]): DraftTab[] {
64
76
  if (!Array.isArray(raw)) return []
@@ -48,6 +48,7 @@ export function shortcutCatalog(mod: string = MOD_KEY): ShortcutGroup[] {
48
48
  { keys: [`${mod}1 … ${mod}8`], what: 'open tab 1 to 8' },
49
49
  { keys: [`${mod}9`], what: 'open the last tab' },
50
50
  { keys: [`${mod}PageUp`, `${mod}PageDown`], what: 'previous or next tab, wrapping' },
51
+ { keys: [`${mod}W`], what: 'close the tab; on the last one, close the window (desktop app)' },
51
52
  ...jumps,
52
53
  { keys: [`${mod}A`], what: 'select all in the field you are in' },
53
54
  { keys: ['Esc'], what: 'close the popup on top' },
@@ -16,6 +16,7 @@ export {
16
16
  type ComfyHostID,
17
17
  type ConnectOptions,
18
18
  } from 'src/host/ComfyHost.ts'
19
+ export type { PreviewMethod } from 'src/host/previewMethod.ts'
19
20
  export { type ParsedHostBase, parseHostBase, renderHttpBase, renderWsUrl } from 'src/host/hostUrl.ts'
20
21
  export { ComfyManager } from 'src/host/ComfyManager.ts'
21
22
  export { ComfyUploader, type ComfyUploadImageResult } from 'src/host/ComfyUploader.ts'
@@ -39,6 +40,7 @@ export {
39
40
  type ComfyVideoOutput,
40
41
  type ComfyExecutionData,
41
42
  type ComfyTextOutput,
43
+ type ExecutionPreview,
42
44
  type ExecutionProgress,
43
45
  } from 'src/runner/ComfyExecution.ts'
44
46
  export type { PromptID, WsMsg, PromptRelated_WsMsg } from 'src/runner/ComfyWsApi.ts'
@@ -6,7 +6,14 @@ import type { ComfyManagerPluginInfo } from 'src/manager/types/ComfyManagerPlugi
6
6
  import type { ComfyExecution } from 'src/runner/ComfyExecution.ts'
7
7
  import type { ComfyApiJson } from 'src/sdk-generator/comfy-api-json.ts'
8
8
  import { parseWorkflowJson } from 'src/litegraph/normalizeWorkflow.ts'
9
- import { parseBinaryWsFrame } from 'src/runner/wsBinaryFrame.ts'
9
+ import { type PreviewMethod, previewMethodFromSystemStats } from 'src/host/previewMethod.ts'
10
+ import {
11
+ binaryFrameType,
12
+ isPreviewFrameType,
13
+ type ParsedPreviewFrame,
14
+ parseBinaryWsFrame,
15
+ parsePreviewFrame,
16
+ } from 'src/runner/wsBinaryFrame.ts'
10
17
  import { convertLiteGraphToPrompt } from 'src/sdk-generator/litegraphToApiRequestPayload.ts'
11
18
  import { asComfyWorkflowID, ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
12
19
  import {
@@ -116,6 +123,8 @@ export class ComfyHostAuthError extends Error {
116
123
  }
117
124
  }
118
125
 
126
+ type LatentPreview = { promptID: Maybe<PromptID>; receivedAt: number_Timestamp; blob: Blob; url: string }
127
+
119
128
  export class ComfyHost<ID extends string = string> {
120
129
  // ----- misc paths where we'll store host-related files -----
121
130
  cacheFolder: AbsolutePath
@@ -665,6 +674,15 @@ export class ComfyHost<ID extends string = string> {
665
674
  // SERVER LOGS ----------------------------------------------------------------------
666
675
  // /internal routes are served bare (no /api prefix, no custom-node hijacks)
667
676
 
677
+ /** the `--preview-method` this host was launched with, read from `GET /system_stats`.
678
+ * `'none'` (ComfyUI's default) means no live preview frame will ever arrive; null = the host
679
+ * does not publish its launch flags (a cloud host), so only a run can tell */
680
+ fetchPreviewMethod = async (): Promise<PreviewMethod | null> => {
681
+ const res = await this.fetch('/system_stats', {})
682
+ if (!res.ok) throw new Error(`GET /system_stats failed: ${res.status}`)
683
+ return previewMethodFromSystemStats(await res.json())
684
+ }
685
+
668
686
  /** the server's recent console buffer (entries are write CHUNKS, not lines) */
669
687
  fetchRawLogs = async (): Promise<{ entries: LogEntry[] }> => {
670
688
  const res = await this.fetch('/internal/logs/raw', {}, { apiPrefix: false })
@@ -792,13 +810,24 @@ export class ComfyHost<ID extends string = string> {
792
810
  prompt.onPromptRelatedMessage(msg)
793
811
  }
794
812
 
795
- /** the latent image beeing generated, in case you want to display it */
796
- latentPreview: Maybe<{
797
- promptID: Maybe<PromptID>
798
- receivedAt: number_Timestamp
799
- blob: Blob
800
- url: string
801
- }> = null
813
+ /** the last raw preview frame; `latentPreview` decodes it only when read */
814
+ private _latentFrame: Maybe<{ data: ArrayBuffer; promptID: Maybe<PromptID>; receivedAt: number_Timestamp }> = null
815
+ private _latentPreview: Maybe<LatentPreview> = null
816
+
817
+ /** the latent image beeing generated, in case you want to display it. Built on read: a
818
+ * session that never reads it never decodes a frame nor holds an object url */
819
+ get latentPreview(): Maybe<LatentPreview> {
820
+ if (this._latentPreview != null || this._latentFrame == null) return this._latentPreview
821
+ const frame = parsePreviewFrame(this._latentFrame.data)
822
+ const blob = new Blob([frame.bytes], { type: frame.mime })
823
+ this._latentPreview = {
824
+ blob,
825
+ url: URL.createObjectURL(blob),
826
+ receivedAt: this._latentFrame.receivedAt,
827
+ promptID: this._latentFrame.promptID,
828
+ }
829
+ return this._latentPreview
830
+ }
802
831
 
803
832
  /** byte-level latent-preview hook (e.g. TUI live preview panel) */
804
833
  onLatentPreview: Maybe<(p: { bytes: Uint8Array; mime: string; promptID: Maybe<PromptID> }) => void> = null
@@ -831,43 +860,47 @@ export class ComfyHost<ID extends string = string> {
831
860
  * never revives one) */
832
861
  lastWsMessageAt: number | null = null
833
862
 
863
+ /** a type 1 or 4 frame. Parsed only when someone wants it, in this order (architecture.md,
864
+ * Live previews): the ws saver's output, the pre-registration buffer, the run's onPreview,
865
+ * the host hook. Nobody listening = the frame is kept by reference and never copied */
866
+ private onPreviewFrame(data: ArrayBuffer): void {
867
+ let parsed: ParsedPreviewFrame | null = null
868
+ const frame = (): ParsedPreviewFrame => (parsed ??= parsePreviewFrame(data))
869
+ const promptID = this.activePromptID
870
+ const activeExec = promptID != null ? this.executions.get(promptID) : null
871
+ // OUTPUT, not preview: while a SaveImageWebsocket node executes, each preview-kind
872
+ // frame IS one output image (frames follow their 'executing' message on the same
873
+ // socket, architecture.md item 14)
874
+ if (activeExec?.wsOutputNodeExecuting)
875
+ return activeExec.onWsImageOutput({ bytes: frame().bytes, mime: frame().mime })
876
+ // pre-registration window: ws messages can beat the POST /prompt response, and an
877
+ // ephemeral output frame in that window would be the ONLY copy of the image. Buffer it
878
+ // IN ORDER with the json messages; ComfyExecution.onCreate replays the queue and decides
879
+ // output-vs-preview from the state at replay time
880
+ const pending = promptID != null ? this._pendingMsgs.get(promptID) : undefined
881
+ if (pending != null)
882
+ pending.push({
883
+ type: 'binary_preview_frame',
884
+ bytes: frame().bytes,
885
+ mime: frame().mime,
886
+ metadata: frame().metadata,
887
+ })
888
+ // the object url REGISTRY holds a strong ref to its blob until revoked, and a sampler
889
+ // emits one frame per step: revoke the outgoing one or a long session retains every latent
890
+ if (this._latentPreview != null) URL.revokeObjectURL(this._latentPreview.url)
891
+ this._latentPreview = null
892
+ this._latentFrame = { data, promptID, receivedAt: Date.now() as number_Timestamp }
893
+ if (activeExec?.onPreview != null) activeExec.onPreviewFrame(frame())
894
+ if (this.onLatentPreview != null) this.onLatentPreview({ bytes: frame().bytes, mime: frame().mime, promptID })
895
+ }
896
+
834
897
  onMessage(e: WsMessageEvent): void {
835
898
  this.lastWsMessageAt = Date.now()
836
899
  if (this.data.onWsMessageAny) this.data.onWsMessageAny(e)
837
900
  if (e.data instanceof ArrayBuffer) {
901
+ if (isPreviewFrameType(binaryFrameType(e.data))) return this.onPreviewFrame(e.data)
838
902
  const frame = parseBinaryWsFrame(e.data)
839
- if (frame.kind === 'preview') {
840
- // OUTPUT, not preview: while a SaveImageWebsocket node executes,
841
- // each preview-kind frame IS one output image (frames follow their
842
- // 'executing' message on the same socket — architecture.md item 14)
843
- const activeExec = this.activePromptID != null ? this.executions.get(this.activePromptID) : null
844
- if (activeExec?.wsOutputNodeExecuting) {
845
- activeExec.onWsImageOutput({ bytes: frame.bytes, mime: frame.mime })
846
- return
847
- }
848
- // pre-registration window: ws messages
849
- // can beat the POST /prompt response, and an ephemeral output frame
850
- // in that window would be the ONLY copy of the image — buffer it IN
851
- // ORDER with the json messages; ComfyExecution.onCreate replays the
852
- // queue and decides output-vs-latent from the state at replay time
853
- if (this.activePromptID != null) {
854
- const pending = this._pendingMsgs.get(this.activePromptID)
855
- if (pending != null) pending.push({ type: 'binary_preview_frame', bytes: frame.bytes, mime: frame.mime })
856
- }
857
- // type 1 AND the cloud's type 4 (preview + metadata) feed the same hook.
858
- // The object url REGISTRY holds a strong ref to its blob until it is
859
- // revoked (node and browsers alike), and a sampler emits one frame per
860
- // step: revoke the outgoing one or a long session retains every latent
861
- if (this.latentPreview != null) URL.revokeObjectURL(this.latentPreview.url)
862
- const imageBlob = new Blob([frame.bytes], { type: frame.mime })
863
- this.latentPreview = {
864
- blob: imageBlob,
865
- url: URL.createObjectURL(imageBlob),
866
- receivedAt: Date.now() as number_Timestamp,
867
- promptID: this.activePromptID,
868
- }
869
- this.onLatentPreview?.({ bytes: frame.bytes, mime: frame.mime, promptID: this.activePromptID })
870
- } else if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
903
+ if (frame.kind === 'unknown' && !this._unknownBinaryFrameTypes.has(frame.eventType)) {
871
904
  // wire tolerance: log once per type, never throw (a throw per sampling
872
905
  // step is what the first live cloud run did on type 4)
873
906
  this._unknownBinaryFrameTypes.add(frame.eventType)
@@ -0,0 +1,29 @@
1
+ // ComfyUI sends live preview frames only when launched with `--preview-method` set to
2
+ // something other than its default `none`. The launch flags reach a client through
3
+ // `GET /system_stats` (`system.argv`), the one place a client can read them.
4
+
5
+ export type PreviewMethod = 'none' | 'auto' | 'latent2rgb' | 'taesd'
6
+
7
+ function isPreviewMethod(x: unknown): x is PreviewMethod {
8
+ return x === 'none' || x === 'auto' || x === 'latent2rgb' || x === 'taesd'
9
+ }
10
+
11
+ /** the preview method a host was launched with, from its /system_stats payload. `'none'` when
12
+ * the flag is absent (ComfyUI's default), null when the payload carries no argv to read (a cloud
13
+ * host) or the flag holds a value this parser does not know */
14
+ export function previewMethodFromSystemStats(stats: unknown): PreviewMethod | null {
15
+ if (stats == null || typeof stats !== 'object' || !('system' in stats)) return null
16
+ const system = stats.system
17
+ if (system == null || typeof system !== 'object' || !('argv' in system)) return null
18
+ const argv = system.argv
19
+ if (!Array.isArray(argv)) return null
20
+ for (let i = 0; i < argv.length; i++) {
21
+ const arg: unknown = argv[i]
22
+ if (typeof arg !== 'string') continue
23
+ const value =
24
+ arg === '--preview-method' ? argv[i + 1] : arg.startsWith('--preview-method=') ? arg.slice(17) : undefined
25
+ if (value === undefined) continue
26
+ return isPreviewMethod(value) ? value : null
27
+ }
28
+ return 'none'
29
+ }
@@ -22,6 +22,7 @@ import type {
22
22
  } from 'src/runner/ComfyWsApi.ts'
23
23
  import { MediaImage } from 'src/runner/MediaImage.ts'
24
24
  import { isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'
25
+ import { previewMetadataNodeId } from 'src/runner/wsBinaryFrame.ts'
25
26
 
26
27
  /** paths claimed by in-flight retrievals: two same-second runs on a
27
28
  * counter-resetting cloud host compute the same name before either writes.
@@ -71,6 +72,23 @@ export type ExecutionProgress = ProgressReport & {
71
72
  progressText: string | null
72
73
  }
73
74
 
75
+ /** one live preview frame of a run: the image a sampler is forming, once per step */
76
+ export type ExecutionPreview = {
77
+ promptId: PromptID
78
+ /** the image as ComfyUI encoded it, jpeg or png */
79
+ bytes: Uint8Array
80
+ mime: string
81
+ /** the node that sent the frame: the frame's own metadata when it names one (type 4 frames),
82
+ * else the node executing when it arrived. Null when neither is known */
83
+ nodeId: ComfyNodeId | null
84
+ /** that node's class name in the sent prompt (`KSampler`), null when unknown */
85
+ nodeName: string | null
86
+ /** that node's own counter when the frame arrived (sampler step of total), null when unknown */
87
+ step: { value: number; max: number } | null
88
+ /** the raw metadata json of a type 4 frame (`node_id`, `prompt_id`, …), null on a type 1 frame */
89
+ metadata: unknown
90
+ }
91
+
74
92
  export class ComfyExecution {
75
93
  get host(): ComfyHost {
76
94
  return this.workflow.host
@@ -85,6 +103,7 @@ export class ComfyExecution {
85
103
  scrubHistory?: boolean
86
104
  ephemeral?: boolean
87
105
  onProgress?: Maybe<(p: ExecutionProgress) => void>
106
+ onPreview?: Maybe<(p: ExecutionPreview) => void>
88
107
  logProgress?: boolean
89
108
  } = {},
90
109
  ) {
@@ -94,6 +113,7 @@ export class ComfyExecution {
94
113
  this.scrubHistory = init.scrubHistory ?? false
95
114
  this.ephemeral = init.ephemeral ?? false
96
115
  this.onProgress = init.onProgress ?? null
116
+ this.onPreview = init.onPreview ?? null
97
117
  this.logProgress = init.logProgress ?? false
98
118
  // register with the host so websocket messages route here,
99
119
  // then flush messages that arrived before we existed
@@ -114,6 +134,8 @@ export class ComfyExecution {
114
134
  // ---- progress ----------------------------------------------------------
115
135
  /** called on every progress-relevant websocket message */
116
136
  onProgress: Maybe<(p: ExecutionProgress) => void> = null
137
+ /** called on every live preview frame of this run. Null = frames are never decoded for it */
138
+ onPreview: Maybe<(p: ExecutionPreview) => void> = null
117
139
  /** render a live single-line progress report to the console */
118
140
  logProgress: boolean = false
119
141
  readonly startedAt: number = Date.now()
@@ -197,9 +219,10 @@ export class ComfyExecution {
197
219
  onPromptRelatedMessage = (msg: PendingWsItem): void => {
198
220
  const graph = this.workflow
199
221
  // replayed pre-registration binary frame: an OUTPUT only when the ws
200
- // saver was executing at this point of the stream; stale latents drop
222
+ // saver was executing at this point of the stream, else a preview
201
223
  if (msg.type === 'binary_preview_frame') {
202
224
  if (this.wsOutputNodeExecuting) this.onWsImageOutput({ bytes: msg.bytes, mime: msg.mime })
225
+ else this.onPreviewFrame(msg)
203
226
  return
204
227
  }
205
228
  if (msg.type === 'execution_start') return
@@ -448,6 +471,27 @@ export class ComfyExecution {
448
471
  return apiJson[uid]?.class_type === 'SaveImageWebsocket'
449
472
  }
450
473
 
474
+ /** @internal a live preview frame of this run; never an output (the host routes ws saver frames
475
+ * to onWsImageOutput before they get here) */
476
+ onPreviewFrame(p: { bytes: Uint8Array; mime: string; metadata: unknown }): void {
477
+ const listener = this.onPreview
478
+ if (listener == null) return
479
+ const current = this.workflow.currentExecutingNode
480
+ const named = previewMetadataNodeId(p.metadata)
481
+ const nodeId: ComfyNodeId | null = named ?? current?.uid ?? null
482
+ const apiJson = this.snapshot?.apiJson ?? this.workflow.apiJson
483
+ const counter = current != null && current.uid === nodeId ? current.progress : null
484
+ listener({
485
+ promptId: this.data.id,
486
+ bytes: p.bytes,
487
+ mime: p.mime,
488
+ nodeId,
489
+ nodeName: nodeId != null ? (apiJson[nodeId]?.class_type ?? null) : null,
490
+ step: counter != null ? { value: counter.value, max: counter.max } : null,
491
+ metadata: p.metadata,
492
+ })
493
+ }
494
+
451
495
  /** one binary ws frame = one output image of the executing SaveImageWebsocket
452
496
  * node (architecture.md item 14 — the zero-server-disk path) */
453
497
  onWsImageOutput = (p: { bytes: Uint8Array; mime: string }): void => {
@@ -8,7 +8,7 @@ import { convertFlowToLiteGraphJSON } from 'src/litegraph/convertFlowToLiteGraph
8
8
  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
- import { ComfyExecution, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
11
+ import { ComfyExecution, type ExecutionPreview, type ExecutionProgress } from 'src/runner/ComfyExecution.ts'
12
12
  import { rewriteSaveNodesToWebsocket } from 'src/runner/ephemeral.ts'
13
13
  import type { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
14
14
  import type { ComfyApiJson, ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
@@ -52,6 +52,10 @@ export type RunSettings = {
52
52
  log?: boolean
53
53
  /** called on every progress-relevant websocket message */
54
54
  onProgress?: (p: ExecutionProgress) => void
55
+ /** called on every live preview frame of this run (the image a sampler is forming). Opt in:
56
+ * without it no frame is decoded for the run. ComfyUI sends frames only when launched with
57
+ * `--preview-method`, see `host.fetchPreviewMethod()` */
58
+ onPreview?: (p: ExecutionPreview) => void
55
59
  }
56
60
 
57
61
  /** exactly what was sent to the host for one execution, frozen at send time */
@@ -427,6 +431,7 @@ export class ComfyWorkflow<ID extends string = string> {
427
431
  // ephemeral implies the scrub unless the caller explicitly opted out
428
432
  scrubHistory: p.scrubHistory ?? p.ephemeral ?? false,
429
433
  onProgress: p.onProgress,
434
+ onPreview: p.onPreview,
430
435
  logProgress: p.log ?? false,
431
436
  },
432
437
  )
@@ -152,7 +152,7 @@ export type PromptRelated_WsMsg = typeof types.PromptRelated_WsMsg.infer
152
152
  /** a binary preview-kind ws frame buffered IN ORDER with the json messages
153
153
  * during the pre-registration window (ComfyHost._pendingMsgs) — replayed by
154
154
  * ComfyExecution.onCreate, which decides output-vs-latent at replay time */
155
- export type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string }
155
+ export type PendingBinaryFrame = { type: 'binary_preview_frame'; bytes: Uint8Array; mime: string; metadata: unknown }
156
156
  export type PendingWsItem = PromptRelated_WsMsg | PendingBinaryFrame
157
157
  export type WsMsg = typeof types.WsMsg.infer
158
158
  export type ComfyStatusData = typeof types.ComfyStatusData.infer
@@ -6,43 +6,66 @@
6
6
  // Unknown types come back as 'unknown' — the CALLER logs, never throws: the
7
7
  // wire drifts faster than we do (type 4 appeared on the first live cloud run).
8
8
 
9
+ export const BINARY_FRAME_PREVIEW_IMAGE = 1
10
+ export const BINARY_FRAME_TEXT = 3
11
+ export const BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA = 4
12
+
13
+ export type ParsedPreviewFrame = { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }
14
+
9
15
  export type ParsedBinaryWsFrame =
10
- | { kind: 'preview'; bytes: Uint8Array<ArrayBuffer>; mime: string; metadata: unknown }
16
+ | ParsedPreviewFrame
11
17
  | { kind: 'text'; nodeId: string; text: string }
12
18
  | { kind: 'unknown'; eventType: number }
13
19
 
14
- export function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {
15
- const view = new DataView(data)
16
- const eventType = view.getUint32(0)
20
+ /** the frame's event type, read in place: deciding whether anyone wants a frame costs no copy */
21
+ export function binaryFrameType(data: ArrayBuffer): number {
22
+ if (data.byteLength < 4) return -1
23
+ return new DataView(data).getUint32(0)
24
+ }
17
25
 
18
- if (eventType === 1) {
19
- const imageType = view.getUint32(4)
20
- const bytes = new Uint8Array(data.slice(8))
21
- const mime = imageType === 2 ? 'image/png' : 'image/jpeg'
22
- return { kind: 'preview', bytes, mime, metadata: null }
23
- }
26
+ export function isPreviewFrameType(eventType: number): boolean {
27
+ return eventType === BINARY_FRAME_PREVIEW_IMAGE || eventType === BINARY_FRAME_PREVIEW_IMAGE_WITH_METADATA
28
+ }
29
+
30
+ export function parseBinaryWsFrame(data: ArrayBuffer): ParsedBinaryWsFrame {
31
+ const eventType = binaryFrameType(data)
32
+ if (isPreviewFrameType(eventType)) return parsePreviewFrame(data)
24
33
 
25
- if (eventType === 3) {
26
- const nodeIdLen = view.getUint32(4)
34
+ if (eventType === BINARY_FRAME_TEXT) {
35
+ const nodeIdLen = new DataView(data).getUint32(4)
27
36
  const decoder = new TextDecoder()
28
37
  const nodeId = decoder.decode(data.slice(8, 8 + nodeIdLen))
29
38
  const text = decoder.decode(data.slice(8 + nodeIdLen))
30
39
  return { kind: 'text', nodeId, text }
31
40
  }
32
41
 
33
- if (eventType === 4) {
34
- const metadataLen = view.getUint32(4)
35
- let metadata: unknown = null
36
- try {
37
- metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)))
38
- } catch {
39
- // tolerate broken metadata: the image bytes are the payload that matters
40
- }
41
- const bytes = new Uint8Array(data.slice(8 + metadataLen))
42
- // the docs say "raw JPEG/PNG bytes" with no format field — sniff the magic
43
- const mime = bytes[0] === 0x89 && bytes[1] === 0x50 ? 'image/png' : 'image/jpeg'
44
- return { kind: 'preview', bytes, mime, metadata }
42
+ return { kind: 'unknown', eventType }
43
+ }
44
+
45
+ /** a type 1 or type 4 frame; the caller checked the type with `isPreviewFrameType` */
46
+ export function parsePreviewFrame(data: ArrayBuffer): ParsedPreviewFrame {
47
+ const view = new DataView(data)
48
+ if (view.getUint32(0) === BINARY_FRAME_PREVIEW_IMAGE) {
49
+ const imageType = view.getUint32(4)
50
+ const bytes = new Uint8Array(data.slice(8))
51
+ const mime = imageType === 2 ? 'image/png' : 'image/jpeg'
52
+ return { kind: 'preview', bytes, mime, metadata: null }
45
53
  }
54
+ const metadataLen = view.getUint32(4)
55
+ let metadata: unknown = null
56
+ try {
57
+ metadata = JSON.parse(new TextDecoder().decode(data.slice(8, 8 + metadataLen)))
58
+ } catch {
59
+ // tolerate broken metadata: the image bytes are the payload that matters
60
+ }
61
+ const bytes = new Uint8Array(data.slice(8 + metadataLen))
62
+ // the docs say "raw JPEG/PNG bytes" with no format field — sniff the magic
63
+ const mime = bytes[0] === 0x89 && bytes[1] === 0x50 ? 'image/png' : 'image/jpeg'
64
+ return { kind: 'preview', bytes, mime, metadata }
65
+ }
46
66
 
47
- return { kind: 'unknown', eventType }
67
+ /** the node a type 4 frame names (`node_id` in its metadata), null when absent or malformed */
68
+ export function previewMetadataNodeId(metadata: unknown): string | null {
69
+ if (metadata == null || typeof metadata !== 'object' || !('node_id' in metadata)) return null
70
+ return typeof metadata.node_id === 'string' && metadata.node_id !== '' ? metadata.node_id : null
48
71
  }
@@ -906,6 +906,9 @@ export type MediaVarOpts = {
906
906
  * not what the api accepts) */
907
907
  extensions?: readonly string[]
908
908
  label?: string
909
+ /** the text var a file's `<name>.txt` sidecar fills, when a driver sets this var from a file
910
+ * and leaves that one unset: a voice clip's transcript (`comfy-ts run`) */
911
+ sidecarText?: TextVar
909
912
  }
910
913
  export type ImageVarOpts = MediaVarOpts
911
914
  export type AudioVarOpts = MediaVarOpts
@@ -185,6 +185,7 @@ export class DefinedWorkflow<ID extends string = string, V extends VarsSpec = Va
185
185
  idMode: settings.idMode,
186
186
  log: settings.log,
187
187
  onProgress: settings.onProgress,
188
+ onPreview: settings.onPreview,
188
189
  })
189
190
  this.lastExecution = execution
190
191
  return execution