comfy-ts 2.14.0 → 2.16.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 (75) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-CUeo843w.js → LogsSt-Ct7Le0S_.js} +2 -2
  3. package/dist/{LogsSt-CUeo843w.js.map → LogsSt-Ct7Le0S_.js.map} +1 -1
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +268 -55
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +176 -26
  8. package/dist/index.d.ts +176 -26
  9. package/dist/index.js +262 -56
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-DUqcn0h3.js → run-serve-C78hD7t9.js} +119 -40
  12. package/dist/run-serve-C78hD7t9.js.map +1 -0
  13. package/dist/{run-tui-D-LaSqgB.js → run-tui-nPETFRmk.js} +15 -9
  14. package/dist/run-tui-nPETFRmk.js.map +1 -0
  15. package/dist/{schemaDrift-E95iTF7E.js → schemaDrift-wb5XkrHV.js} +218 -27
  16. package/dist/schemaDrift-wb5XkrHV.js.map +1 -0
  17. package/dist/serve-web.js +64 -50
  18. package/dist/{state-BytbdZ8s.js → state-BMW57_M0.js} +45 -35
  19. package/dist/state-BMW57_M0.js.map +1 -0
  20. package/dist/web.d.ts +173 -26
  21. package/dist/web.js +251 -53
  22. package/dist/web.js.map +1 -1
  23. package/examples/README.md +1 -0
  24. package/examples/media/README.md +9 -0
  25. package/examples/media/sine_440hz_3s.flac +0 -0
  26. package/examples/media/testsrc_256x256_3s.mp4 +0 -0
  27. package/examples/media/voice_en_6s.flac +0 -0
  28. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +9 -1
  29. package/examples/rvion/10-anima-t2i.cflow.ts +8 -1
  30. package/examples/rvion/14-video-soundtrack.cflow.ts +47 -0
  31. package/examples/rvion/15-tts-voice-clone.cflow.ts +111 -0
  32. package/guide-for-agents.md +3 -1
  33. package/package.json +2 -2
  34. package/src/cli/serve/ServeApp.ts +115 -32
  35. package/src/cli/serve/applyVarPayload.ts +5 -3
  36. package/src/cli/serve/describeVar.ts +5 -3
  37. package/src/cli/serve/resultHistory.ts +22 -6
  38. package/src/cli/serve/run-serve.ts +4 -1
  39. package/src/cli/serve/web/api.ts +4 -0
  40. package/src/cli/serve/web/components/DraftTabs.tsx +2 -1
  41. package/src/cli/serve/web/components/Gallery.tsx +86 -5
  42. package/src/cli/serve/web/components/HistoryPicker.tsx +5 -3
  43. package/src/cli/serve/web/components/MenuButton.tsx +2 -4
  44. package/src/cli/serve/web/components/Omnibox.tsx +2 -1
  45. package/src/cli/serve/web/components/PromptEnhancer.tsx +4 -3
  46. package/src/cli/serve/web/components/ShortcutsModal.tsx +2 -1
  47. package/src/cli/serve/web/components/SideMenu.tsx +2 -1
  48. package/src/cli/serve/web/components/VarsForm.tsx +5 -3
  49. package/src/cli/serve/web/components/controls/LorasControl.tsx +4 -3
  50. package/src/cli/serve/web/components/controls/MediaControl.tsx +111 -0
  51. package/src/cli/serve/web/components/controls/PresetPicker.tsx +2 -1
  52. package/src/cli/serve/web/components/controls/PromptControl.tsx +2 -1
  53. package/src/cli/serve/web/components/controls/SizeControl.tsx +2 -1
  54. package/src/cli/serve/web/state/FormSt.ts +70 -2
  55. package/src/cli/serve/web/state/escape.ts +16 -0
  56. package/src/cli/serve/web/state/host.ts +2 -0
  57. package/src/cli/serve/web/state/mediaDrop.ts +76 -0
  58. package/src/cli/serve/web/styles.ts +16 -2
  59. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +4 -1
  60. package/src/cli/tui/imagePicker/ImagePickerSt.ts +15 -6
  61. package/src/cli/tui/state/TuiSt.ts +1 -1
  62. package/src/coreExports.ts +20 -1
  63. package/src/exampleAssets.ts +13 -3
  64. package/src/host/ComfyUploader.ts +34 -27
  65. package/src/index.ts +1 -1
  66. package/src/runner/ComfyExecution.ts +38 -20
  67. package/src/runner/ComfyWsApi.ts +3 -0
  68. package/src/runner/mediaKinds.ts +51 -0
  69. package/src/vars/ComfyVars.ts +178 -34
  70. package/src/vars/DefinedWorkflow.ts +35 -2
  71. package/dist/run-serve-DUqcn0h3.js.map +0 -1
  72. package/dist/run-tui-D-LaSqgB.js.map +0 -1
  73. package/dist/schemaDrift-E95iTF7E.js.map +0 -1
  74. package/dist/state-BytbdZ8s.js.map +0 -1
  75. package/src/cli/serve/web/components/controls/ImageControl.tsx +0 -72
@@ -3,7 +3,16 @@
3
3
  // reaction is owned here). DRAFTS ARE LIVE (the TUI model): edits autosave
4
4
  // through PUT /drafts, generate posts {} — the draft is the one source of truth
5
5
  import { makeAutoObservable, observableRef, reaction, runInAction, type IReactionDisposer } from 'mobx'
6
- import { fetchPreviews, saveDraft, type ModuleDescription } from 'src/cli/serve/web/api.ts'
6
+ import { fetchPreviews, saveDraft, uploadFile, type ModuleDescription } from 'src/cli/serve/web/api.ts'
7
+ import {
8
+ isMediaKind,
9
+ mediaKindOfFile,
10
+ refuseDrop,
11
+ valueForOutput,
12
+ type DraggedOutput,
13
+ } from 'src/cli/serve/web/state/mediaDrop.ts'
14
+ import type { MediaKind } from 'src/runner/mediaKinds.ts'
15
+ import { logWebError } from 'src/cli/serve/web/logWeb.ts'
7
16
  import type { VarDescriptor } from 'src/cli/serve/describeVar.ts'
8
17
  import { normalizeInitial, payloadSnapshot } from 'src/cli/serve/web/state/payload.ts'
9
18
  import {
@@ -23,8 +32,12 @@ export class VarSt {
23
32
  value: unknown
24
33
  /** changed since the draft loaded — drives the revert affordance, not the payload */
25
34
  dirty = false
26
- /** image vars only: a browser-visible url for the current value (upload response or http value) */
35
+ /** media vars only: a browser-visible url for the current value (upload response or http value) */
27
36
  uploadedUrl: string | null = null
37
+ /** media vars only: why the last drop or upload did not land, shown on the row */
38
+ mediaError: string | null = null
39
+ /** media vars only: an upload is on its way */
40
+ mediaBusy = false
28
41
 
29
42
  constructor(
30
43
  public readonly name: string,
@@ -52,6 +65,60 @@ export class VarSt {
52
65
  this.uploadedUrl = url
53
66
  }
54
67
 
68
+ /** the medium this row takes, null for a non-media var */
69
+ get mediaKind(): MediaKind | null {
70
+ return isMediaKind(this.desc.kind) ? this.desc.kind : null
71
+ }
72
+
73
+ setMediaError(message: string | null): void {
74
+ this.mediaError = message
75
+ }
76
+
77
+ /** a desktop file (picked or dropped): uploaded, the var points at the local copy */
78
+ async takeFile(file: File): Promise<void> {
79
+ const kind = this.mediaKind
80
+ if (kind == null) return
81
+ const refused = refuseDrop(kind, mediaKindOfFile(file), file.name)
82
+ if (refused != null) return this.setMediaError(refused)
83
+ await this.landMedia(file.name, () => uploadFile({ file }))
84
+ }
85
+
86
+ /** a gallery output (dragged, or its `→ var` button) */
87
+ async takeOutput(o: DraggedOutput): Promise<void> {
88
+ const kind = this.mediaKind
89
+ if (kind == null) return
90
+ const refused = refuseDrop(kind, o.kind, o.filename)
91
+ if (refused != null) return this.setMediaError(refused)
92
+ await this.landMedia(o.filename, () =>
93
+ valueForOutput(o, {
94
+ fetchBlob: async (url) => {
95
+ const res = await fetch(url)
96
+ if (!res.ok) throw new Error(`http ${res.status} on ${url}`)
97
+ return res.blob()
98
+ },
99
+ upload: (file) => uploadFile({ file }),
100
+ }),
101
+ )
102
+ }
103
+
104
+ private async landMedia(what: string, get: () => Promise<{ path: string; url: string | null }>): Promise<void> {
105
+ this.mediaBusy = true
106
+ this.mediaError = null
107
+ try {
108
+ const value = await get()
109
+ runInAction(() => {
110
+ this.set(value.path)
111
+ this.uploadedUrl = value.url
112
+ })
113
+ } catch (e) {
114
+ const message = `${what}: ${e instanceof Error ? e.message : String(e)}`
115
+ logWebError('media input did not land', e)
116
+ runInAction(() => (this.mediaError = message))
117
+ } finally {
118
+ runInAction(() => (this.mediaBusy = false))
119
+ }
120
+ }
121
+
55
122
  /** the workflow's declared default, in the shape the controls hold */
56
123
  get defaultValue(): unknown {
57
124
  return normalizeInitial(this.desc, this.desc.default)
@@ -71,6 +138,7 @@ export class VarSt {
71
138
  this.value = this.initial
72
139
  this.dirty = false
73
140
  this.uploadedUrl = null
141
+ this.mediaError = null
74
142
  }
75
143
 
76
144
  snapshot(): { name: string; value: unknown } {
@@ -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
+ }
@@ -95,6 +95,8 @@ export function coerceHostValue(desc: VarDescriptor, raw: unknown, current: unkn
95
95
  case 'prompt':
96
96
  case 'text':
97
97
  case 'image':
98
+ case 'audio':
99
+ case 'video':
98
100
  return typeof raw === 'string' ? { ok: true, value: raw } : REJECT
99
101
  case 'int':
100
102
  return isFiniteNumber(raw) ? { ok: true, value: Math.trunc(raw) } : REJECT
@@ -0,0 +1,76 @@
1
+ // what lands on a media var: a desktop file or a gallery output. PURE (the fetch and the upload
2
+ // are injected), tests/serve-web-media-drop.test.ts. The var must end on a LOCAL PATH, because
3
+ // that is the only value /generate accepts without a download
4
+ import { DEFAULT_MEDIA_EXTENSIONS, extensionOf, MEDIA_KINDS, type MediaKind } from 'src/runner/mediaKinds.ts'
5
+
6
+ /** the dataTransfer type a gallery output drags under */
7
+ export const OUTPUT_DRAG_MIME = 'application/x-comfy-output'
8
+
9
+ export type DraggedOutput = { kind: MediaKind; url: string | null; absPath: string | null; filename: string }
10
+
11
+ export function encodeDraggedOutput(o: DraggedOutput): string {
12
+ return JSON.stringify(o)
13
+ }
14
+
15
+ /** null on anything that is not one of ours: a drop can come from any page */
16
+ export function decodeDraggedOutput(raw: string): DraggedOutput | null {
17
+ let parsed: unknown
18
+ try {
19
+ parsed = JSON.parse(raw)
20
+ } catch {
21
+ return null
22
+ }
23
+ if (parsed == null || typeof parsed !== 'object') return null
24
+ // family 10: every field is checked right below before the object is claimed
25
+ const o = parsed as Record<string, unknown>
26
+ const kind = o.kind
27
+ if (typeof kind !== 'string' || !isMediaKind(kind)) return null
28
+ if (typeof o.filename !== 'string') return null
29
+ // any page can put this type on a drag: only a same-origin url and an absolute path are ours
30
+ const url = typeof o.url === 'string' && /^\/(?!\/)/.test(o.url) ? o.url : null
31
+ const absPath = typeof o.absPath === 'string' && /^(\/|[A-Za-z]:[\\/])/.test(o.absPath) ? o.absPath : null
32
+ if (o.url != null && url == null) return null
33
+ if (o.absPath != null && absPath == null) return null
34
+ if (url == null && absPath == null) return null
35
+ return { kind, url, absPath, filename: o.filename }
36
+ }
37
+
38
+ export function isMediaKind(kind: string): kind is MediaKind {
39
+ return (MEDIA_KINDS as readonly string[]).includes(kind)
40
+ }
41
+
42
+ /** a desktop file's medium: its mime first, its extension when the browser gave no mime */
43
+ export function mediaKindOfFile(file: { name: string; type: string }): MediaKind | null {
44
+ const top = file.type.split('/')[0] ?? ''
45
+ if (isMediaKind(top)) return top
46
+ const ext = extensionOf(file.name)
47
+ return MEDIA_KINDS.find((k) => DEFAULT_MEDIA_EXTENSIONS[k].includes(ext)) ?? null
48
+ }
49
+
50
+ /** null when the var takes it, else the reason it does not, said to the user */
51
+ export function refuseDrop(varKind: MediaKind, dropped: MediaKind | null, what: string): string | null {
52
+ if (dropped === varKind) return null
53
+ return `this is ${article(varKind)} input: ${what} is ${dropped == null ? 'not a known media file' : article(dropped)}`
54
+ }
55
+
56
+ function article(kind: MediaKind): string {
57
+ return kind === 'video' ? `a ${kind}` : `an ${kind}`
58
+ }
59
+
60
+ export type MediaValue = { path: string; url: string | null }
61
+
62
+ /** a saved output is already a local path. An unsaved one lives in the server memory only, so
63
+ * its bytes are fetched and uploaded, and the var points at the uploaded copy */
64
+ export async function valueForOutput(
65
+ o: DraggedOutput,
66
+ deps: {
67
+ fetchBlob: (url: string) => Promise<Blob>
68
+ upload: (file: File) => Promise<{ path: string; url: string | null }>
69
+ },
70
+ ): Promise<MediaValue> {
71
+ if (o.absPath != null) return { path: o.absPath, url: o.url }
72
+ if (o.url == null) throw new Error(`${o.filename} is no longer in memory: nothing to use`)
73
+ const blob = await deps.fetchBlob(o.url)
74
+ const reply = await deps.upload(new File([blob], o.filename, { type: blob.type }))
75
+ return { path: reply.path, url: reply.url }
76
+ }
@@ -528,6 +528,17 @@ input[type='range'].setting-range:disabled { opacity: 0.3; }
528
528
  .run-card .noimg { color: var(--dim); font-style: italic; }
529
529
  .audio-cell { display: flex; flex-direction: column; gap: 4px; width: min(100%, 480px); }
530
530
  .audio-cell audio { width: 100%; }
531
+ .video-cell { display: flex; flex-direction: column; gap: 4px; width: min(100%, 480px); }
532
+ .gallery.by-cols .video-cell { width: 100%; }
533
+ .video-cell video { width: 100%; max-height: 480px; border-radius: 6px; background: #000; }
534
+ .img-cell[draggable='true'], .audio-cell[draggable='true'], .video-cell[draggable='true'] { cursor: grab; }
535
+ .use-as { display: flex; flex-wrap: wrap; gap: 4px; }
536
+ /* a media var takes desktop files and gallery outputs: the zone lights while one hovers it */
537
+ .media-drop { border: 1px dashed var(--border); border-radius: 6px; padding: 6px; }
538
+ .media-drop.over { border-color: var(--accent); background: var(--accent-dim); }
539
+ .media-drop .error { color: var(--red); font-size: 12px; margin-top: 4px; white-space: pre-wrap; }
540
+ .media-preview-audio audio { width: min(100%, 360px); }
541
+ .media-preview-video video { max-width: 320px; max-height: 220px; border-radius: 6px; border: 1px solid var(--border); background: #000; }
531
542
  .run-card.running { border-color: var(--accent-dim); }
532
543
  /* what the host is on, in the node's own unit — the live signal of a text run, which has
533
544
  neither a latent frame nor an image to show */
@@ -907,6 +918,9 @@ button.enh-big { font-size: 14px; padding: 8px 18px; }
907
918
  /* blur mode: every result, the latent frame included, stays blurred until the pointer is on it */
908
919
  .gallery.blur img { filter: blur(22px); transition: filter 0.12s, transform 0.12s; }
909
920
  .gallery.blur img:hover, .gallery.blur .img-cell:hover img, .gallery.blur button:hover img { filter: none; }
921
+ /* a video is a picture too: the same privacy blur, lifted while you hover it */
922
+ .gallery.blur .video-cell video { filter: blur(22px); transition: filter 0.12s; }
923
+ .gallery.blur .video-cell:hover video { filter: none; }
910
924
  /* the blur stays inside the image: clipped by its button, and the image scaled up a little while
911
925
  blurred, else the clip shows the blur fading to transparent along every edge */
912
926
  .gallery.blur .img-button { position: relative; overflow: hidden; border-radius: 6px; }
@@ -918,13 +932,13 @@ button.enh-big { font-size: 14px; padding: 8px 18px; }
918
932
  }
919
933
  .img-button:hover .blur-hint { display: none; }
920
934
  /* an unsaved output: only the serve process holds it, so it says so where the eye lands */
921
- .gallery .img-button, .audio-cell { position: relative; }
935
+ .gallery .img-button, .audio-cell, .video-cell { position: relative; }
922
936
  .ephemeral-pill {
923
937
  position: absolute; left: 6px; bottom: 6px; pointer-events: auto; display: inline-flex; align-items: center; gap: 4px;
924
938
  font-size: 11px; font-weight: 600; padding: 1px 7px; border-radius: 999px;
925
939
  color: #1a1400; background: var(--amber); opacity: 0.92;
926
940
  }
927
- .audio-cell .ephemeral-pill { position: static; align-self: flex-start; }
941
+ .audio-cell .ephemeral-pill, .video-cell .ephemeral-pill { position: static; align-self: flex-start; }
928
942
  .memory-menu { max-width: 300px; }
929
943
  .memory-note { margin: 0; padding: 2px 4px; font-size: 12px; line-height: 1.4; }
930
944
  .memory-note.error { color: var(--red); }
@@ -64,7 +64,10 @@ export const ImagePickerOverlay = observer((p: { st: TuiSt }) => {
64
64
  })}
65
65
  footer={
66
66
  rows.length === 0 ? (
67
- <Text color="red">{ip.listingError ?? (ip.filter !== '' ? 'no match' : 'no images here')}</Text>
67
+ <Text color="red">
68
+ {ip.listingError ??
69
+ (ip.filter !== '' ? 'no match' : `no ${ip.selectedVar?.kind ?? 'image'} files here`)}
70
+ </Text>
68
71
  ) : undefined
69
72
  }
70
73
  />
@@ -8,7 +8,8 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
8
8
  import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
9
9
  import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
10
10
  import { protocolReadyBytes } from 'src/cli/tui/protocolImage.ts'
11
- import type { ImageVar } from 'src/vars/ComfyVars.ts'
11
+ import type { MediaVar } from 'src/vars/ComfyVars.ts'
12
+ import { extensionOf } from 'src/runner/mediaKinds.ts'
12
13
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
13
14
 
14
15
  export type PickerPane = 'browse' | 'favorites' | 'recents'
@@ -50,9 +51,9 @@ export class ImagePickerSt {
50
51
  filter: string = ''
51
52
 
52
53
  /** kind-narrowing cast sanctioned (agent/coding.md), `kind` is the tag */
53
- get selectedVar(): ImageVar | null {
54
+ get selectedVar(): MediaVar | null {
54
55
  const sel = this.st.selected?.[1]
55
- return sel?.kind === 'image' ? (sel as ImageVar) : null
56
+ return sel?.kind === 'image' || sel?.kind === 'audio' || sel?.kind === 'video' ? (sel as MediaVar) : null
56
57
  }
57
58
 
58
59
  get folderDisplay(): string {
@@ -60,7 +61,7 @@ export class ImagePickerSt {
60
61
  }
61
62
 
62
63
  /** begin() open order: dirname(value) → persisted lastFolder → opts.folder → cwd */
63
- private initialFolder(iv: ImageVar): string {
64
+ private initialFolder(iv: MediaVar): string {
64
65
  const candidates: (string | null)[] = [
65
66
  iv.isSet() ? dirname(iv.absPath()) : null,
66
67
  pickerPrefs().lastFolder,
@@ -104,7 +105,8 @@ export class ImagePickerSt {
104
105
  }
105
106
  if (this.pane === 'recents')
106
107
  return {
107
- rows: pickerPrefs().recents.map((img) => ({
108
+ // one recents list for every medium: an audio var lists only what it could take
109
+ rows: this.recentsForVar().map((img) => ({
108
110
  kind: 'image',
109
111
  name: contractHome(img),
110
112
  path: img,
@@ -130,6 +132,11 @@ export class ImagePickerSt {
130
132
  }
131
133
  }
132
134
 
135
+ private recentsForVar(): string[] {
136
+ const exts = this.selectedVar?.extensions ?? []
137
+ return pickerPrefs().recents.filter((f) => exts.includes(extensionOf(f)))
138
+ }
139
+
133
140
  get listingError(): string | null {
134
141
  return this.paneListing.error
135
142
  }
@@ -145,8 +152,10 @@ export class ImagePickerSt {
145
152
  return this.rows[this.ix] ?? null
146
153
  }
147
154
 
148
- /** feeds the preview reaction: only a real, present image highlights */
155
+ /** feeds the preview reaction: only a real, present image highlights (an audio or video
156
+ * row has nothing to paint) */
149
157
  get highlightedImage(): string | null {
158
+ if (this.selectedVar?.kind !== 'image') return null
150
159
  const row = this.current
151
160
  return row?.kind === 'image' && !row.missing ? row.path : null
152
161
  }
@@ -317,7 +317,7 @@ export class TuiSt {
317
317
  else if (sel.kind === 'choice') this.picker.beginChoice()
318
318
  else if (sel.kind === 'size') this.picker.beginSize()
319
319
  else if (sel.kind === 'loras') this.loras.begin()
320
- else if (sel.kind === 'image') this.imagePicker.begin()
320
+ else if (sel.kind === 'image' || sel.kind === 'audio' || sel.kind === 'video') this.imagePicker.begin()
321
321
  else this.editor.beginInline() // int / float / seed: type the number
322
322
  }
323
323
 
@@ -36,6 +36,7 @@ export {
36
36
  export {
37
37
  ComfyExecution,
38
38
  type ComfyAudioOutput,
39
+ type ComfyVideoOutput,
39
40
  type ComfyExecutionData,
40
41
  type ComfyTextOutput,
41
42
  type ExecutionProgress,
@@ -90,13 +91,19 @@ export {
90
91
  MultiChoiceVar,
91
92
  LorasVar,
92
93
  SizeVar,
94
+ MediaVar,
93
95
  ImageVar,
96
+ AudioVar,
97
+ VideoVar,
98
+ MediaVarEmptyError,
94
99
  ImageVarEmptyError,
95
100
  DEFAULT_SIZE_PRESETS,
96
101
  SD15_SIZE_PRESETS,
97
102
  DEFAULT_STARRED_SIZES,
98
103
  sizePresetsFor,
99
104
  DEFAULT_IMAGE_EXTENSIONS,
105
+ DEFAULT_AUDIO_EXTENSIONS,
106
+ DEFAULT_VIDEO_EXTENSIONS,
100
107
  activeLoras,
101
108
  } from 'src/vars/ComfyVars.ts'
102
109
  export type {
@@ -114,7 +121,12 @@ export type {
114
121
  ActiveLora,
115
122
  SizeValue,
116
123
  SizePreset,
124
+ MediaVarOpts,
125
+ ModelVarOpts,
126
+ HostSlotSource,
117
127
  ImageVarOpts,
128
+ AudioVarOpts,
129
+ VideoVarOpts,
118
130
  TextVarOpts,
119
131
  PromptVarOpts,
120
132
  PromptTagsOpts,
@@ -130,7 +142,14 @@ export type {
130
142
  LoraRecord,
131
143
  } from 'src/vars/lanes.ts'
132
144
  export type { LoraEntry } from 'src/vars/loraEntry.ts'
133
- export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
145
+ export {
146
+ DefinedWorkflow,
147
+ type DefineWorkflowSpec,
148
+ type BoundVars,
149
+ type LoraNameOf,
150
+ type SlotNameOf,
151
+ type SlotValueOf,
152
+ } from 'src/vars/DefinedWorkflow.ts'
134
153
  export {
135
154
  clearLoraKeywordOverride,
136
155
  getLoraKeyword,
@@ -44,13 +44,23 @@ export function bundledExamplesDir(moduleUrl: string = import.meta.url): string
44
44
  * or the package's examples/ folder was pruned.
45
45
  */
46
46
  export function exampleImagePath(name: string): string {
47
+ return bundledExampleFile('images', name)
48
+ }
49
+
50
+ /** the same for a bundled `examples/media/` audio or video file, e.g.
51
+ * `exampleMediaPath('sine_440hz_3s.flac')` — the default of audio and video example vars */
52
+ export function exampleMediaPath(name: string): string {
53
+ return bundledExampleFile('media', name)
54
+ }
55
+
56
+ function bundledExampleFile(folder: 'images' | 'media', name: string): string {
47
57
  const examples = bundledExamplesDir()
48
58
  if (examples == null) {
49
59
  throw new Error(
50
- `[comfy-ts] cannot resolve bundled example image '${name}': the package's examples/ folder is not on disk`,
60
+ `[comfy-ts] cannot resolve bundled example file '${name}': the package's examples/ folder is not on disk`,
51
61
  )
52
62
  }
53
- const abs = join(examples, 'images', name)
54
- if (!existsSync(abs)) throw new Error(`[comfy-ts] bundled example image not found: ${abs}`)
63
+ const abs = join(examples, folder, name)
64
+ if (!existsSync(abs)) throw new Error(`[comfy-ts] bundled example file not found: ${abs}`)
55
65
  return abs
56
66
  }
@@ -21,7 +21,11 @@ export const ComfyUploadImageResult_ark = type({
21
21
  export class ComfyUploader {
22
22
  constructor(public host: ComfyHost) {}
23
23
 
24
- /** upload a blob */
24
+ /** names this process already uploaded to this host: a LoadAudio or LoadVideo list is not
25
+ * reloaded after an upload, so without it every run re-sent the same file */
26
+ private uploaded = new Set<string>()
27
+
28
+ /** upload an image (hash-named, deduped against the host's LoadImage list) */
25
29
  uploadImage = async (
26
30
  //
27
31
  img: MediaImage,
@@ -31,46 +35,49 @@ export class ComfyUploader {
31
35
  subfolder?: string
32
36
  },
33
37
  ): Promise<ComfyImageName> => {
34
- const uniqFileName = img.enumName as ComfyImageName
35
- // console.warn(`[🌁] UPLOAD: ${img.relPath} required as "${uniqFileName}"...`)
38
+ const name = await this.uploadInput({ blob: img.getAsBlob(), name: img.enumName, ...p, slot: 'LoadImage.image' })
39
+ return name as ComfyImageName
40
+ }
36
41
 
37
- const expectedFinalName = p.subfolder //
38
- ? `${p.subfolder}/${uniqFileName}`
39
- : uniqFileName
40
- // 2. if image already exists, return it
41
- if (this.host.schema.hasImage(expectedFinalName)) {
42
- console.log(`[🌁] UPLOAD: 🩶 "${img.absPath}" already exists on current ComfyUI instance`)
43
- return expectedFinalName as ComfyImageName
42
+ /**
43
+ * THE upload path: any file a loader node reads from the host's input folder. ComfyUI routes
44
+ * audio and video through `/upload/image` too. `slot` is the loader input whose value list
45
+ * says the file is already there (`LoadImage.image`, `LoadAudio.audio`, `LoadVideo.file`)
46
+ */
47
+ uploadInput = async (p: {
48
+ blob: Blob
49
+ /** the name the file should get on the host, hash-derived by callers so reruns dedupe */
50
+ name: string
51
+ slot: string
52
+ type?: Maybe<'input' | 'temp' | 'output'>
53
+ override?: Maybe<boolean>
54
+ subfolder?: string
55
+ }): Promise<string> => {
56
+ const expectedFinalName = p.subfolder ? `${p.subfolder}/${p.name}` : p.name
57
+ if (this.uploaded.has(expectedFinalName) || this.host.schema.stringValues(p.slot).includes(expectedFinalName)) {
58
+ console.log(`[🌁] UPLOAD: 🩶 "${expectedFinalName}" already exists on current ComfyUI instance`)
59
+ return expectedFinalName
44
60
  }
45
61
 
46
- // 3. upload
47
62
  const form = new FormData()
48
- form.set('image', img.getAsBlob(), uniqFileName)
63
+ form.set('image', p.blob, p.name)
49
64
  if (p.type) form.set('type', p.type)
50
65
  if (p.override ?? true) form.set('override', 'true')
51
- // const subfolder = p.subfolder ?? 'comfyts-upload'
52
66
  if (p.subfolder) form.set('subfolder', p.subfolder)
53
67
  const resp = await this.host.fetch('/upload/image', { method: 'POST', body: form })
54
68
  const result: ComfyUploadImageResult = softValidate(ComfyUploadImageResult_ark, await resp.json())
55
69
 
56
- // 4. check upload is successfull
57
70
  console.log('[🌁] UPLOAD: ✅ got', result)
58
- if (result.name == null) throw new Error('upload failed')
59
-
60
- const finalName = result.subfolder //
61
- ? (`${result.subfolder}/${result.name}` as ComfyImageName)
62
- : result.name
71
+ if (result.name == null) throw new Error(`upload of '${p.name}' failed: the host answered no name`)
63
72
 
64
- if (finalName !== expectedFinalName) {
73
+ const finalName = result.subfolder ? `${result.subfolder}/${result.name}` : result.name
74
+ if (finalName !== expectedFinalName)
65
75
  console.warn(`[🌁] UPLOAD: ⚠️ expected "${expectedFinalName}" but got "${finalName}"`)
66
- } else {
67
- console.log(`[🌁] UPLOAD: ✅ finalName is "${finalName}"`)
68
- }
69
-
70
- // 5. patch the local ComfyUI schema locally
71
- this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName)
72
76
 
73
- // 6. return the image
77
+ // the image list IS a known union: patch it so the next LoadImage typechecks against it
78
+ if (p.slot === 'LoadImage.image')
79
+ this.host.schema.unsafely_addImageInSchemaWithoutReloading(finalName as ComfyImageName)
80
+ this.uploaded.add(finalName)
74
81
  return finalName
75
82
  }
76
83
 
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@ setDefaultComfyStorage(createNodeStorage())
12
12
  export * from 'src/coreExports.ts'
13
13
 
14
14
  // node-only surface: fs-backed example assets + the TUI env contract
15
- export { exampleImagePath } from 'src/exampleAssets.ts'
15
+ export { exampleImagePath, exampleMediaPath } from 'src/exampleAssets.ts'
16
16
  // the prompt-enhancer library on disk, offered as var presets (fs, so never in the web entry)
17
17
  export { promptEnhancerPresets, readPromptEnhancers, type PromptEnhancer } from 'src/promptEnhancers.ts'
18
18
  export { isTuiActive } from 'src/cli/tui-env.ts'
@@ -21,6 +21,7 @@ import type {
21
21
  WsMsgExecutionSuccess,
22
22
  } from 'src/runner/ComfyWsApi.ts'
23
23
  import { MediaImage } from 'src/runner/MediaImage.ts'
24
+ import { isVideoFilename, mediaMime } from 'src/runner/mediaKinds.ts'
24
25
 
25
26
  /** paths claimed by in-flight retrievals: two same-second runs on a
26
27
  * counter-resetting cloud host compute the same name before either writes.
@@ -46,19 +47,9 @@ export type ComfyAudioOutput = {
46
47
  absPath: AbsolutePath | null
47
48
  }
48
49
 
49
- const AUDIO_MIMES: Record<string, string> = {
50
- flac: 'audio/flac',
51
- mp3: 'audio/mpeg',
52
- opus: 'audio/ogg',
53
- ogg: 'audio/ogg',
54
- wav: 'audio/wav',
55
- m4a: 'audio/mp4',
56
- }
57
-
58
- export function audioMime(filename: string): string {
59
- const ext = filename.split('.').pop()?.toLowerCase() ?? ''
60
- return AUDIO_MIMES[ext] ?? 'application/octet-stream'
61
- }
50
+ /** one video file an output node published (SaveVideo, SaveWEBM, VHS_VideoCombine), same
51
+ * shape and same retrieval as an audio file */
52
+ export type ComfyVideoOutput = ComfyAudioOutput
62
53
 
63
54
  /** one text output as an output node published it (`nodeKey` is null when the node left the snapshot) */
64
55
  export type ComfyTextOutput = {
@@ -167,6 +158,7 @@ export class ComfyExecution {
167
158
  const p = this.progress
168
159
  const outputs = [`${this.images.length} image(s)`]
169
160
  if (this.audios.length > 0) outputs.push(`${this.audios.length} audio(s)`)
161
+ if (this.videos.length > 0) outputs.push(`${this.videos.length} video(s)`)
170
162
  if (this.texts.length > 0) outputs.push(`${this.texts.length} text(s)`)
171
163
  const line = `${this.status === 'Failure' ? '🔴' : '🟢'} ${this.status.toLowerCase()} in ${(p.elapsedMs / 1000).toFixed(1)}s · ${outputs.join(' · ')}`
172
164
  if (globalThis.process?.stdout?.isTTY) process.stdout.write(`\r\x1b[2K${line}\n`)
@@ -252,8 +244,23 @@ export class ComfyExecution {
252
244
  const nodeKey = this.workflow.data.apiJson?.[promptNodeID]?.class_type ?? null
253
245
  this.texts.push({ nodeId: promptNodeID, nodeKey, text: entry })
254
246
  }
255
- const images = msg.data.output?.images
256
- if (images) {
247
+ // a video file rides `images` (SaveVideo), `video` or `gifs` (VideoHelperSuite): the
248
+ // extension decides, so an animated webp or gif stays an image
249
+ const out = msg.data.output
250
+ // a loader (LoadVideo) echoes the file it READ, typed 'input': a preview, never an output
251
+ const listed = [...(out?.images ?? []), ...(out?.video ?? []), ...(out?.gifs ?? [])].filter(
252
+ (f) => f.type !== 'input',
253
+ )
254
+ for (const video of listed.filter((f) => isVideoFilename(f.filename))) {
255
+ this.pendingPromises.push(
256
+ this.retrieveFile('video', video, promptNodeID).catch((e: unknown) => {
257
+ console.error(`🔴 failed to retrieve ${video.filename}:`, e)
258
+ this.videoErrors.push({ video, error: e })
259
+ }),
260
+ )
261
+ }
262
+ const images = listed.filter((f) => !isVideoFilename(f.filename))
263
+ if (images.length > 0) {
257
264
  for (const img of images) {
258
265
  // guard every retrieval: one failed download must not hang `done`
259
266
  this.pendingPromises.push(
@@ -266,7 +273,7 @@ export class ComfyExecution {
266
273
  }
267
274
  for (const audio of msg.data.output?.audio ?? []) {
268
275
  this.pendingPromises.push(
269
- this.retrieveAudio(audio, promptNodeID).catch((e: unknown) => {
276
+ this.retrieveFile('audio', audio, promptNodeID).catch((e: unknown) => {
270
277
  console.error(`🔴 failed to retrieve ${audio.filename}:`, e)
271
278
  this.audioErrors.push({ audio, error: e })
272
279
  }),
@@ -281,13 +288,24 @@ export class ComfyExecution {
281
288
  /** audio files retrieved for this execution, in arrival order (final once `done` resolves) */
282
289
  audios: ComfyAudioOutput[] = []
283
290
 
284
- private retrieveAudio = async (info: ComfyImageInfo, promptNodeID: ComfyNodeId): Promise<void> => {
291
+ /** video retrievals that failed (their files are missing from `videos`) */
292
+ videoErrors: { video: ComfyImageInfo; error: unknown }[] = []
293
+
294
+ /** video files retrieved for this execution, in arrival order (final once `done` resolves) */
295
+ videos: ComfyVideoOutput[] = []
296
+
297
+ private retrieveFile = async (
298
+ kind: 'audio' | 'video',
299
+ info: ComfyImageInfo,
300
+ promptNodeID: ComfyNodeId,
301
+ ): Promise<void> => {
285
302
  const response = await this.host.fetchFile('/view?' + new URLSearchParams(info).toString())
286
303
  const bytes = new Uint8Array(await response.arrayBuffer())
287
- const mime = audioMime(info.filename)
304
+ const mime = mediaMime(info.filename)
305
+ const list = kind === 'audio' ? this.audios : this.videos
288
306
  const sf = this.save
289
307
  if (sf == null) {
290
- this.audios.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null })
308
+ list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: null })
291
309
  return
292
310
  }
293
311
  const promptPrefix = this.workflow.data.apiJson?.[promptNodeID]?.inputs['filename_prefix']
@@ -299,7 +317,7 @@ export class ComfyExecution {
299
317
  subfolder: info.subfolder,
300
318
  filename: info.filename,
301
319
  })
302
- this.audios.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path })
320
+ list.push({ nodeId: promptNodeID, filename: info.filename, mime, bytes, absPath: written.path })
303
321
  }
304
322
 
305
323
  /** image retrievals that failed (their images are missing from `images`);
@@ -66,6 +66,9 @@ const tempScope = scope({
66
66
  'images?': 'ComfyImageInfo[]',
67
67
  // SaveAudio*, PreviewAudio: same file triple as an image
68
68
  'audio?': 'ComfyImageInfo[]',
69
+ // VideoHelperSuite's VHS_VideoCombine, and savers that name their list `video`
70
+ 'video?': 'ComfyImageInfo[]',
71
+ 'gifs?': 'ComfyImageInfo[]',
69
72
  // ui payload of a text output node (PreviewAny, and how TextGenerate
70
73
  // results reach the client); entries are soft, non-strings are dropped
71
74
  'text?': 'unknown[]',