comfy-ts 2.16.0 → 2.17.1

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 (71) hide show
  1. package/README.md +23 -0
  2. package/dist/{run-serve-C78hD7t9.js → ServeApp-qXcQfdgT.js} +18 -445
  3. package/dist/ServeApp-qXcQfdgT.js.map +1 -0
  4. package/dist/cli.js +72 -9
  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 +182 -69
  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 +182 -69
  15. package/dist/index.js.map +1 -1
  16. package/dist/run-run-tg82jUIk.js +450 -0
  17. package/dist/run-run-tg82jUIk.js.map +1 -0
  18. package/dist/run-serve-DaXzoVTS.js +464 -0
  19. package/dist/run-serve-DaXzoVTS.js.map +1 -0
  20. package/dist/{run-tui-nPETFRmk.js → run-tui-Bw7BA75d.js} +7 -38
  21. package/dist/run-tui-Bw7BA75d.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 +56 -48
  25. package/dist/{state-BMW57_M0.js → state-zTow5ucI.js} +182 -70
  26. package/dist/state-zTow5ucI.js.map +1 -0
  27. package/dist/web.d.ts +61 -8
  28. package/dist/web.js +182 -69
  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 +2 -2
  35. package/src/cli/bunHop.ts +49 -0
  36. package/src/cli/comfy-ts-cli.ts +18 -5
  37. package/src/cli/run/findModules.ts +36 -0
  38. package/src/cli/run/flagValue.ts +61 -0
  39. package/src/cli/run/outputPaths.ts +41 -0
  40. package/src/cli/run/pickModule.ts +41 -0
  41. package/src/cli/run/run-run.ts +250 -0
  42. package/src/cli/run/runArgs.ts +61 -0
  43. package/src/cli/run/sidecar.ts +27 -0
  44. package/src/cli/serve/ServeApp.ts +13 -39
  45. package/src/cli/serve/run-serve.ts +51 -13
  46. package/src/cli/serve/web/components/App.tsx +2 -0
  47. package/src/cli/serve/web/components/DialogLayer.tsx +55 -0
  48. package/src/cli/serve/web/components/DraftTabs.tsx +16 -5
  49. package/src/cli/serve/web/components/PromptEnhancer.tsx +15 -9
  50. package/src/cli/serve/web/components/SideMenu.tsx +16 -8
  51. package/src/cli/serve/web/state/WebSt.ts +10 -1
  52. package/src/cli/serve/web/state/dialog.ts +59 -0
  53. package/src/cli/serve/web/state/draftTabs.ts +12 -0
  54. package/src/cli/serve/web/state/keptLines.ts +1 -1
  55. package/src/cli/serve/web/state/shortcutCatalog.ts +1 -0
  56. package/src/cli/serve/web/styles.ts +8 -0
  57. package/src/coreExports.ts +2 -0
  58. package/src/host/ComfyHost.ts +73 -40
  59. package/src/host/previewMethod.ts +29 -0
  60. package/src/litegraph/convertFlowToLiteGraphJSON.ts +38 -20
  61. package/src/promptEnhancers.ts +1 -1
  62. package/src/runner/ComfyExecution.ts +45 -1
  63. package/src/runner/ComfyWorkflow.ts +6 -1
  64. package/src/runner/ComfyWsApi.ts +1 -1
  65. package/src/runner/wsBinaryFrame.ts +48 -25
  66. package/src/vars/ComfyVars.ts +3 -0
  67. package/src/vars/DefinedWorkflow.ts +1 -0
  68. package/dist/LogsSt-Ct7Le0S_.js.map +0 -1
  69. package/dist/run-serve-C78hD7t9.js.map +0 -1
  70. package/dist/run-tui-nPETFRmk.js.map +0 -1
  71. package/dist/state-BMW57_M0.js.map +0 -1
@@ -1,6 +1,7 @@
1
1
  // ✨ on a prompt row → the refine modal: the LLM configs and the master prompts as two lists of
2
2
  // vertical tabs on the left, the job (yours → rewrite) alone on the right. A tab's pen opens its
3
3
  // editor over the job. Nothing touches the var until APPLY.
4
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
4
5
  import { Icon } from 'src/cli/serve/web/components/Icon.tsx'
5
6
  import { observer } from 'mobx-react-lite'
6
7
  import { useEffect, useRef, type ReactNode } from 'react'
@@ -51,8 +52,8 @@ const TabList = observer(function TabList(p: {
51
52
  onSelect(name: string): void
52
53
  onCreate(name: string): void
53
54
  }) {
54
- const create = (): void => {
55
- const name = window.prompt(`name the new ${p.kind}`, p.newName)
55
+ const create = async (): Promise<void> => {
56
+ const name = await dialogs.prompt({ message: `name the new ${p.kind}`, value: p.newName })
56
57
  if (name != null) p.onCreate(name)
57
58
  }
58
59
  const dot = (name: string): ReactNode => {
@@ -96,7 +97,7 @@ const TabList = observer(function TabList(p: {
96
97
  ) : null}
97
98
  </div>
98
99
  ))}
99
- <button type="button" className="enh-tab-new" onClick={create}>
100
+ <button type="button" className="enh-tab-new" onClick={() => void create()}>
100
101
  <Icon name="plus" /> new {p.kind}
101
102
  </button>
102
103
  </div>
@@ -184,14 +185,19 @@ function EditPanel(p: {
184
185
  onClose(): void
185
186
  children: ReactNode
186
187
  }): ReactNode {
187
- const rename = (): void => {
188
+ const rename = async (): Promise<void> => {
188
189
  if (p.name == null) return
189
- const name = window.prompt(`rename this ${p.kind} (renames the file)`, p.name)
190
+ const name = await dialogs.prompt({ message: `rename this ${p.kind} (renames the file)`, value: p.name })
190
191
  if (name != null) p.onRename(name)
191
192
  }
192
- const remove = (): void => {
193
+ const remove = async (): Promise<void> => {
193
194
  if (p.name == null) return
194
- if (window.confirm(`delete ${p.kind} '${p.name}'? its file is removed.`)) p.onDelete()
195
+ const ok = await dialogs.confirm({
196
+ message: `delete ${p.kind} '${p.name}'? its file is removed.`,
197
+ ok: 'delete',
198
+ danger: true,
199
+ })
200
+ if (ok) p.onDelete()
195
201
  }
196
202
  return (
197
203
  <section className="enh-edit">
@@ -204,10 +210,10 @@ function EditPanel(p: {
204
210
  <button type="button" onClick={() => p.onDuplicate()}>
205
211
  duplicate
206
212
  </button>
207
- <button type="button" onClick={rename}>
213
+ <button type="button" onClick={() => void rename()}>
208
214
  rename
209
215
  </button>
210
- <button type="button" className="quiet-danger" onClick={remove}>
216
+ <button type="button" className="quiet-danger" onClick={() => void remove()}>
211
217
  <Icon name="trash" /> delete
212
218
  </button>
213
219
  </span>
@@ -1,5 +1,6 @@
1
1
  // the menu column: where you are, widest scope first (workspace, workflow, draft, host, preview).
2
2
  // a left Panel above 760px (collapsible to an icon rail), a drawer behind ☰ below
3
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
3
4
  import { observer, useLocalObservable } from 'mobx-react-lite'
4
5
  import type { ReactNode } from 'react'
5
6
  import { Icon, type IconName } from 'src/cli/serve/web/components/Icon.tsx'
@@ -96,11 +97,14 @@ const DraftSection = observer(function DraftSection(p: { st: WebSt; form: FormSt
96
97
  type="button"
97
98
  className="head-icon danger"
98
99
  data-tip="delete this draft's file (default resets to the workflow's own values)"
99
- onClick={() => {
100
- if (
101
- window.confirm(`delete draft '${p.form.draft}' of ${p.form.moduleKey}? the file is removed.`)
102
- )
103
- void p.st.deleteDraft({ module: p.form.moduleKey, draft: p.form.draft })
100
+ onClick={async () => {
101
+ const target = { module: p.form.moduleKey, draft: p.form.draft }
102
+ const ok = await dialogs.confirm({
103
+ message: `delete draft '${target.draft}' of ${target.module}? the file is removed.`,
104
+ ok: 'delete',
105
+ danger: true,
106
+ })
107
+ if (ok) void p.st.deleteDraft(target)
104
108
  }}
105
109
  >
106
110
  <Icon name="trash" />
@@ -277,9 +281,13 @@ export const MenuCards = observer(function MenuCards(p: { st: WebSt }) {
277
281
  type="button"
278
282
  className="head-icon danger"
279
283
  data-tip="restart ComfyUI on that host (manager reboot) — it reconnects when back"
280
- onClick={() => {
281
- if (window.confirm(`restart ComfyUI on '${p.st.hostFor(form.moduleKey)}'?`))
282
- void p.st.hostAction('restart')
284
+ onClick={async () => {
285
+ const ok = await dialogs.confirm({
286
+ message: `restart ComfyUI on '${p.st.hostFor(form.moduleKey)}'?`,
287
+ ok: 'restart',
288
+ danger: true,
289
+ })
290
+ if (ok) void p.st.hostAction('restart')
283
291
  }}
284
292
  >
285
293
  <Icon name="power" />
@@ -1,5 +1,6 @@
1
1
  // ROOT state tree of the serve web ui (app-state-tree doctrine: one root,
2
2
  // child stores hang off it, components read and call)
3
+ import { dialogs } from 'src/cli/serve/web/state/dialog.ts'
3
4
  import { makeAutoObservable, observableRef, observableShallow, runInAction } from 'mobx'
4
5
  import {
5
6
  deleteDraft,
@@ -1398,7 +1399,15 @@ export class WebSt {
1398
1399
  const name = rawName.trim()
1399
1400
  if (form == null || name === '') return
1400
1401
  const existing = this.moduleByKey(form.moduleKey)?.drafts.includes(name) === true
1401
- if (existing && !window.confirm(`draft '${name}' already exists — overwrite it?`)) return
1402
+ if (
1403
+ existing &&
1404
+ !(await dialogs.confirm({
1405
+ message: `draft '${name}' already exists: overwrite it?`,
1406
+ ok: 'overwrite',
1407
+ danger: true,
1408
+ }))
1409
+ )
1410
+ return
1402
1411
  try {
1403
1412
  const reply = await saveDraft({ module: form.moduleKey, draft: name, values })
1404
1413
  runInAction(() => {
@@ -0,0 +1,59 @@
1
+ // the panel's own confirm and text prompt, drawn in the page (DialogLayer). Never window.prompt /
2
+ // confirm / alert: sk gui's WKWebView implements no js panel, so there they return null / false
3
+ // at once and the button that asked does nothing; browsers also suppress them after a few.
4
+ // tests/serve-web-dialog.test.ts guards that no panel source calls the native ones
5
+ import { makeAutoObservable } from 'mobx'
6
+
7
+ export type DialogRequest =
8
+ | { kind: 'confirm'; message: string; ok: string; danger: boolean; resolve(ok: boolean): void }
9
+ | { kind: 'prompt'; message: string; value: string; resolve(value: string | null): void }
10
+
11
+ export class DialogSt {
12
+ current: DialogRequest | null = null
13
+
14
+ constructor() {
15
+ makeAutoObservable(this)
16
+ }
17
+
18
+ confirm(p: { message: string; ok?: string; danger?: boolean }): Promise<boolean> {
19
+ this.cancel()
20
+ return new Promise((resolve) => {
21
+ this.current = { kind: 'confirm', message: p.message, ok: p.ok ?? 'ok', danger: p.danger ?? false, resolve }
22
+ })
23
+ }
24
+
25
+ /** the typed text on ok, null on cancel */
26
+ prompt(p: { message: string; value: string }): Promise<string | null> {
27
+ this.cancel()
28
+ return new Promise((resolve) => {
29
+ this.current = { kind: 'prompt', message: p.message, value: p.value, resolve }
30
+ })
31
+ }
32
+
33
+ setValue(value: string): void {
34
+ if (this.current?.kind === 'prompt') this.current = { ...this.current, value }
35
+ }
36
+
37
+ accept(): void {
38
+ const c = this.current
39
+ if (c == null) return
40
+ this.current = null
41
+ if (c.kind === 'confirm') c.resolve(true)
42
+ else c.resolve(c.value)
43
+ }
44
+
45
+ cancel(): void {
46
+ const c = this.current
47
+ if (c == null) return
48
+ this.current = null
49
+ if (c.kind === 'confirm') c.resolve(false)
50
+ else c.resolve(null)
51
+ }
52
+ }
53
+
54
+ export const dialogs = new DialogSt()
55
+
56
+ /** the lines of a source that call a native browser dialog */
57
+ export function nativeDialogCalls(source: string): string[] {
58
+ return source.split('\n').filter((line) => /\b(window|globalThis)\.(prompt|confirm|alert)\s*\(/.test(line))
59
+ }
@@ -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 []
@@ -36,7 +36,7 @@ export function finishRewrite(model: string, kept: readonly string[]): string {
36
36
  const items = negativeItems(kept)
37
37
  const body = model
38
38
  .split('\n')
39
- .filter((l) => kept.length === 0 || !isKept(l))
39
+ .filter((l) => !isKept(l))
40
40
  .map((l) => {
41
41
  if (items.size === 0) return l
42
42
  let at = l.indexOf(' - ')
@@ -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' },
@@ -882,6 +882,14 @@ button.enh-big { font-size: 14px; padding: 8px 18px; }
882
882
  .modal-overlay.hist-overlay { z-index: 60; }
883
883
  .modal.hist-modal { width: min(1100px, 100%); height: min(76vh, 100%); max-height: none; }
884
884
  .hist-modal .modal-head { align-items: center; }
885
+ /* the panel's confirm and text prompt (DialogLayer): above every modal, the enhancer included */
886
+ .modal-overlay.dialog-overlay { z-index: 70; }
887
+ .modal.dialog-modal { width: min(420px, 100%); }
888
+ .dialog-body { display: flex; flex-direction: column; gap: 10px; }
889
+ .dialog-message { white-space: pre-line; }
890
+ .dialog-body input { width: 100%; }
891
+ .dialog-actions { display: flex; justify-content: flex-end; gap: 8px; padding: 0 10px 10px; }
892
+ .dialog-actions button.dialog-danger { color: var(--red); border-color: var(--red); }
885
893
  .hist-cols { flex: 1; min-height: 0; display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); }
886
894
  .hist-list { min-height: 0; overflow-y: auto; border-right: 1px solid var(--border); padding: 6px; display: flex; flex-direction: column; gap: 2px; }
887
895
  .hist-row {
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ComfyNode } from 'src/graph/ComfyNode.ts'
2
2
  import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
3
3
  import { bang } from 'src/utils/bang.ts'
4
- import { classifySchemaInput } from 'src/sdk-generator/inputWidgetKind.ts'
4
+ import { classifySchemaInput, containerInstanceSlotType } from 'src/sdk-generator/inputWidgetKind.ts'
5
5
  import type { LiteGraphJSON } from 'src/litegraph/LiteGraphJSON.ts'
6
6
  import type { LiteGraphLinkTuple } from 'src/litegraph/LiteGraphLink.ts'
7
7
  import { asLiteGraphLinkID, type LiteGraphLinkID } from 'src/litegraph/LiteGraphLinkID.ts'
@@ -40,27 +40,38 @@ export const convertFlowToLiteGraphJSON = (graph: ComfyWorkflow): LiteGraphJSON
40
40
  const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): LiteGraphNode => {
41
41
  const inputs: LiteGraphNodeInput[] = []
42
42
  const widgets_values: unknown[] = []
43
+ // target_slot = index within THIS node's litegraph inputs array,
44
+ // not the schema input index (widget inputs are not litegraph slots)
45
+ const pushLinked = (name: string, type: string, link: [string, number], shape?: number): void => {
46
+ const nodeUidNumber = bang(
47
+ ctx.graph.nodes.find((n) => n.uid === link[0])?.uidNumber,
48
+ `link target node "${link[0]}" not found in graph`,
49
+ )
50
+ const linkId = ctx.allocateLink(nodeUidNumber, link[1], node.uidNumber, asLiteGraphSlotIndex(inputs.length), type)
51
+ inputs.push(shape == null ? { name, type, link: linkId } : { name, type, shape, link: linkId })
52
+ }
43
53
  for (const ipt of node.$schema.inputs) {
44
- const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])
45
54
  const kind = classifySchemaInput(ipt)
55
+ if (kind.kind === 'dynamic-container') {
56
+ // the declaration is never a slot: each grown instance is its own
57
+ // optional slot `decl.<instance>` (shape 7), as the editor stores it
58
+ const type = containerInstanceSlotType(ipt.opts) ?? '*'
59
+ for (const instance of kind.instanceNames) {
60
+ const name = `${ipt.nameInComfy}.${instance}`
61
+ const value = node.json.inputs[name]
62
+ if (value == null) continue
63
+ const raw = node.serializeValue(name, value)
64
+ if (!_isLink(raw))
65
+ throw new Error(
66
+ `🔴 [toWorkflowJson] ${node.$schema.nameInComfy}#${node.uid} "${name}" holds a literal; an autogrow instance is a link slot in the editor`,
67
+ )
68
+ pushLinked(name, type, raw, 7)
69
+ }
70
+ continue
71
+ }
72
+ const raw = node.serializeValue(ipt.nameInComfy, node.json.inputs[ipt.nameInComfy])
46
73
  if (_isLink(raw)) {
47
- const nodeUidNumber = bang(
48
- ctx.graph.nodes.find((n) => n.uid === raw[0])?.uidNumber,
49
- `link target node "${raw[0]}" not found in graph`,
50
- )
51
- inputs.push({
52
- name: ipt.nameInComfy,
53
- type: ipt.typeName,
54
- // target_slot = index within THIS node's litegraph inputs array,
55
- // not the schema input index (widget inputs are not litegraph slots)
56
- link: ctx.allocateLink(
57
- nodeUidNumber,
58
- raw[1],
59
- node.uidNumber,
60
- asLiteGraphSlotIndex(inputs.length),
61
- ipt.typeName,
62
- ),
63
- })
74
+ pushLinked(ipt.nameInComfy, ipt.typeName, raw)
64
75
  } else if (kind.kind === 'widget') {
65
76
  // frontend button-widget values ride BEFORE the real value (LOAD_3D)
66
77
  widgets_values.push(...kind.prefixValues, raw)
@@ -69,7 +80,7 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
69
80
  // INT-named-seed heuristic lives inside controlConsumes), so export
70
81
  // and import can never disagree on the run length
71
82
  const phantoms = kind.consumes - 1 - kind.prefixValues.length
72
- for (let i = 0; i < phantoms; i++) widgets_values.push(false)
83
+ for (let i = 0; i < phantoms; i++) widgets_values.push(controlMode(ipt.opts))
73
84
  } else {
74
85
  // unconnected link-kind input: a litegraph slot with no link —
75
86
  // NEVER a widget value (that would misalign the round-trip import)
@@ -96,6 +107,13 @@ const convertNodeToLiteGraphNode = (ctx: LiteGraphCtx, node: ComfyNode<any>): Li
96
107
  }
97
108
  }
98
109
 
110
+ /** the editor's control widget is a combo (fixed, increment, decrement, randomize):
111
+ * a config naming a mode keeps it, anything else is `fixed`, the seed the code pinned */
112
+ const controlMode = (opts: unknown): string => {
113
+ const mode = typeof opts === 'object' && opts != null ? Reflect.get(opts, 'control_after_generate') : null
114
+ return typeof mode === 'string' ? mode : 'fixed'
115
+ }
116
+
99
117
  const _isLink = (v: unknown): v is [string, number] => {
100
118
  return Array.isArray(v) && v.length === 2 && typeof v[0] === 'string' && typeof v[1] === 'number'
101
119
  }
@@ -39,7 +39,7 @@ Rewrite it into ONE paragraph a reader could picture with their eyes closed:
39
39
  - plain descriptive english. Flowing sentences and comma separated descriptive clauses both read well; disconnected keyword soup does not. No praise words, never "masterpiece", "8k", "highly detailed", "award winning", "trending on". The model is steered by what you name, not by what you forbid.
40
40
  - text that must appear inside the image is spelled out in "quotes", exactly as it should be rendered.
41
41
  - roughly 60 to 150 words, one paragraph, no lists, no headings, no quotes around the result itself.
42
- - keep any "// " comment line and any "- " negative line from the input verbatim, each on its own line.
42
+ - never write a negative ("- ...") line or a comment ("// ...") line: the panel keeps the user's own and adds them back after your prompt.
43
43
 
44
44
  Answer with the rewritten prompt and nothing else: no preamble, no explanation.
45
45
  `,
@@ -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 => {