comfy-ts 2.15.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 (76) hide show
  1. package/README.md +23 -0
  2. package/dist/{run-serve-B5PfIuhK.js → ServeApp-BSA5yzxZ.js} +28 -446
  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-C3UIWR-o.js → findDefinedWorkflow-0lG-VTEd.js} +201 -201
  9. package/dist/findDefinedWorkflow-0lG-VTEd.js.map +1 -0
  10. package/dist/index.cjs +202 -62
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +115 -14
  13. package/dist/index.d.ts +115 -14
  14. package/dist/index.js +202 -62
  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-D-N4_yyX.js → run-tui-B0AQWbad.js} +6 -37
  21. package/dist/run-tui-B0AQWbad.js.map +1 -0
  22. package/dist/{schemaDrift-BkN8rLiZ.js → schemaDrift-CbsABBuk.js} +59 -5
  23. package/dist/schemaDrift-CbsABBuk.js.map +1 -0
  24. package/dist/serve-web.js +48 -48
  25. package/dist/{state-CZsYJqB6.js → state-C2oDiQ26.js} +146 -60
  26. package/dist/state-C2oDiQ26.js.map +1 -0
  27. package/dist/web.d.ts +115 -14
  28. package/dist/web.js +202 -62
  29. package/dist/web.js.map +1 -1
  30. package/examples/README.md +2 -0
  31. package/examples/media/README.md +6 -5
  32. package/examples/media/voice_en_6s.flac +0 -0
  33. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +9 -1
  34. package/examples/rvion/10-anima-t2i.cflow.ts +8 -1
  35. package/examples/rvion/15-tts-voice-clone.cflow.ts +111 -0
  36. package/examples/rvion/16-tts-voice-design.cflow.ts +71 -0
  37. package/guide-for-agents.md +5 -1
  38. package/package.json +2 -2
  39. package/src/cli/comfy-ts-cli.ts +14 -1
  40. package/src/cli/run/findModules.ts +36 -0
  41. package/src/cli/run/flagValue.ts +61 -0
  42. package/src/cli/run/outputPaths.ts +41 -0
  43. package/src/cli/run/pickModule.ts +41 -0
  44. package/src/cli/run/run-run.ts +250 -0
  45. package/src/cli/run/runArgs.ts +61 -0
  46. package/src/cli/run/sidecar.ts +27 -0
  47. package/src/cli/serve/ServeApp.ts +28 -42
  48. package/src/cli/serve/web/components/DraftTabs.tsx +10 -3
  49. package/src/cli/serve/web/components/Gallery.tsx +2 -1
  50. package/src/cli/serve/web/components/HistoryPicker.tsx +5 -3
  51. package/src/cli/serve/web/components/MenuButton.tsx +2 -4
  52. package/src/cli/serve/web/components/Omnibox.tsx +2 -1
  53. package/src/cli/serve/web/components/PromptEnhancer.tsx +4 -3
  54. package/src/cli/serve/web/components/ShortcutsModal.tsx +2 -1
  55. package/src/cli/serve/web/components/SideMenu.tsx +2 -1
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +4 -3
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +2 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +2 -1
  59. package/src/cli/serve/web/components/controls/SizeControl.tsx +2 -1
  60. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  61. package/src/cli/serve/web/state/escape.ts +16 -0
  62. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  63. package/src/coreExports.ts +12 -1
  64. package/src/host/ComfyHost.ts +73 -40
  65. package/src/host/previewMethod.ts +29 -0
  66. package/src/runner/ComfyExecution.ts +45 -1
  67. package/src/runner/ComfyWorkflow.ts +6 -1
  68. package/src/runner/ComfyWsApi.ts +1 -1
  69. package/src/runner/wsBinaryFrame.ts +48 -25
  70. package/src/vars/ComfyVars.ts +86 -13
  71. package/src/vars/DefinedWorkflow.ts +36 -2
  72. package/dist/LogsSt-C3UIWR-o.js.map +0 -1
  73. package/dist/run-serve-B5PfIuhK.js.map +0 -1
  74. package/dist/run-tui-D-N4_yyX.js.map +0 -1
  75. package/dist/schemaDrift-BkN8rLiZ.js.map +0 -1
  76. package/dist/state-CZsYJqB6.js.map +0 -1
@@ -46,6 +46,7 @@ import {
46
46
  type LoraRecord,
47
47
  type LorasInput,
48
48
  } from 'src/vars/lanes.ts'
49
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
49
50
 
50
51
  /** one editable list of loras: the whole var, or one of its lanes (ix -1 = no lanes) */
51
52
  type Section = { ix: number; record: LoraRecord; lane: LoraLane | null }
@@ -125,7 +126,7 @@ const LoraLaneBar = observer(function LoraLaneBar(p: {
125
126
  write(patchLane(p.lanes, p.ix, { name: e.currentTarget.value.trim() || lane.name }))
126
127
  setRenaming(false)
127
128
  }
128
- if (e.key === 'Escape') setRenaming(false)
129
+ onEscape(e, () => setRenaming(false))
129
130
  }}
130
131
  onBlur={() => setRenaming(false)}
131
132
  />
@@ -404,7 +405,7 @@ export const LorasControl = observer(function LorasControl(p: {
404
405
  useEffect(() => {
405
406
  if (!open) return
406
407
  const onKey = (e: KeyboardEvent): void => {
407
- if (e.key === 'Escape') local.setOpen(false)
408
+ onEscape(e, () => local.setOpen(false))
408
409
  }
409
410
  window.addEventListener('keydown', onKey)
410
411
  return () => window.removeEventListener('keydown', onKey)
@@ -1095,7 +1096,7 @@ const LoraDetails = observer(function LoraDetails(p: {
1095
1096
  }, [host, name, local])
1096
1097
  useEffect(() => {
1097
1098
  const onKey = (e: KeyboardEvent): void => {
1098
- if (e.key === 'Escape') p.onClose()
1099
+ onEscape(e, () => p.onClose())
1099
1100
  }
1100
1101
  window.addEventListener('keydown', onKey)
1101
1102
  return () => window.removeEventListener('keydown', onKey)
@@ -5,6 +5,7 @@ import { useState } from 'react'
5
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
6
6
  import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
7
7
  import { activePresetLabel } from 'src/vars/presets.ts'
8
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
8
9
 
9
10
  /** one line of a preset's text, enough to tell two of them apart in the menu */
10
11
  function firstLine(text: string): string {
@@ -19,7 +20,7 @@ export const PresetPicker = observer(function PresetPicker(p: { v: VarSt }) {
19
20
  const value = typeof p.v.value === 'string' ? p.v.value : ''
20
21
  const active = activePresetLabel(presets, value)
21
22
  return (
22
- <div className="preset-box" onKeyDown={(e) => (e.key === 'Escape' ? setOpen(false) : undefined)}>
23
+ <div className="preset-box" onKeyDown={(e) => onEscape(e, () => setOpen(false))}>
23
24
  <button
24
25
  type="button"
25
26
  className="preset-btn mini"
@@ -19,6 +19,7 @@ import {
19
19
  toPromptLanes,
20
20
  type PromptLane,
21
21
  } from 'src/vars/lanes.ts'
22
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
22
23
 
23
24
  /** the words each active lora adds in front of the prompt. One line per lora, cut with an
24
25
  * ellipsis; clicking opens the full list with a checkbox per word and all / none */
@@ -143,7 +144,7 @@ const LaneBox = observer(function LaneBox(p: {
143
144
  write(patchLane(p.lanes, p.ix, { name: e.currentTarget.value.trim() || lane.name }))
144
145
  setRenaming(false)
145
146
  }
146
- if (e.key === 'Escape') setRenaming(false)
147
+ onEscape(e, () => setRenaming(false))
147
148
  }}
148
149
  onBlur={() => setRenaming(false)}
149
150
  />
@@ -7,6 +7,7 @@ import type { VarSt } from 'src/cli/serve/web/state/FormSt.ts'
7
7
  import { asSizeForm } from 'src/cli/serve/web/state/payload.ts'
8
8
  import { aspectBox, starredPresets, toggleStar } from 'src/cli/serve/web/state/sizeStars.ts'
9
9
  import type { WebSt } from 'src/cli/serve/web/state/WebSt.ts'
10
+ import { onEscape } from 'src/cli/serve/web/state/escape.ts'
10
11
 
11
12
  /** a tiny rectangle in the preset's own ratio, centred in a fixed square so a row lines up */
12
13
  function AspectIcon(p: { width: number; height: number; box?: number }): ReactNode {
@@ -66,7 +67,7 @@ export const SizeControl = observer(function SizeControl(p: { v: VarSt; st: WebS
66
67
  ))}
67
68
  </span>
68
69
  ) : null}
69
- <div className="preset-box" onKeyDown={(e) => (e.key === 'Escape' ? setOpen(false) : undefined)}>
70
+ <div className="preset-box" onKeyDown={(e) => onEscape(e, () => setOpen(false))}>
70
71
  <button type="button" className="preset-btn size-pick" aria-expanded={open} onClick={() => setOpen(!open)}>
71
72
  <AspectIcon width={size.width} height={size.height} /> {current?.label ?? 'custom'} ▾
72
73
  </button>
@@ -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 []
@@ -0,0 +1,16 @@
1
+ // esc is always CLAIMED by the page: a native window (sk gui's WKWebView) beeps on any key the
2
+ // page leaves unhandled, so a popup that closes on esc without preventDefault closes AND beeps.
3
+ // PURE, tests/serve-web-escape.test.ts guards that every esc handler of the panel goes through it
4
+
5
+ /** true when `e` was esc: claimed, then `close` ran */
6
+ export function onEscape(e: { key: string; preventDefault(): void }, close: () => void): boolean {
7
+ if (e.key !== 'Escape') return false
8
+ e.preventDefault()
9
+ close()
10
+ return true
11
+ }
12
+
13
+ /** the lines of a source that test for esc by hand instead of through onEscape */
14
+ export function rawEscapeChecks(source: string): string[] {
15
+ return source.split('\n').filter((line) => /\.key\s*[!=]==?\s*['"]Escape['"]/.test(line))
16
+ }
@@ -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'
@@ -122,6 +124,8 @@ export type {
122
124
  SizeValue,
123
125
  SizePreset,
124
126
  MediaVarOpts,
127
+ ModelVarOpts,
128
+ HostSlotSource,
125
129
  ImageVarOpts,
126
130
  AudioVarOpts,
127
131
  VideoVarOpts,
@@ -140,7 +144,14 @@ export type {
140
144
  LoraRecord,
141
145
  } from 'src/vars/lanes.ts'
142
146
  export type { LoraEntry } from 'src/vars/loraEntry.ts'
143
- export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
147
+ export {
148
+ DefinedWorkflow,
149
+ type DefineWorkflowSpec,
150
+ type BoundVars,
151
+ type LoraNameOf,
152
+ type SlotNameOf,
153
+ type SlotValueOf,
154
+ } from 'src/vars/DefinedWorkflow.ts'
144
155
  export {
145
156
  clearLoraKeywordOverride,
146
157
  getLoraKeyword,
@@ -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
  }