comfy-ts 2.14.0 → 2.15.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 (57) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-CUeo843w.js → LogsSt-C3UIWR-o.js} +2 -2
  3. package/dist/{LogsSt-CUeo843w.js.map → LogsSt-C3UIWR-o.js.map} +1 -1
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +213 -53
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +123 -21
  8. package/dist/index.d.ts +123 -21
  9. package/dist/index.js +207 -54
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-DUqcn0h3.js → run-serve-B5PfIuhK.js} +108 -38
  12. package/dist/run-serve-B5PfIuhK.js.map +1 -0
  13. package/dist/{run-tui-D-LaSqgB.js → run-tui-D-N4_yyX.js} +15 -9
  14. package/dist/run-tui-D-N4_yyX.js.map +1 -0
  15. package/dist/{schemaDrift-E95iTF7E.js → schemaDrift-BkN8rLiZ.js} +163 -25
  16. package/dist/schemaDrift-BkN8rLiZ.js.map +1 -0
  17. package/dist/serve-web.js +62 -48
  18. package/dist/{state-BytbdZ8s.js → state-CZsYJqB6.js} +45 -35
  19. package/dist/state-CZsYJqB6.js.map +1 -0
  20. package/dist/web.d.ts +120 -21
  21. package/dist/web.js +196 -51
  22. package/dist/web.js.map +1 -1
  23. package/examples/media/README.md +8 -0
  24. package/examples/media/sine_440hz_3s.flac +0 -0
  25. package/examples/media/testsrc_256x256_3s.mp4 +0 -0
  26. package/examples/rvion/14-video-soundtrack.cflow.ts +47 -0
  27. package/guide-for-agents.md +2 -1
  28. package/package.json +2 -2
  29. package/src/cli/serve/ServeApp.ts +101 -30
  30. package/src/cli/serve/applyVarPayload.ts +5 -3
  31. package/src/cli/serve/describeVar.ts +5 -3
  32. package/src/cli/serve/resultHistory.ts +22 -6
  33. package/src/cli/serve/run-serve.ts +4 -1
  34. package/src/cli/serve/web/api.ts +4 -0
  35. package/src/cli/serve/web/components/Gallery.tsx +84 -4
  36. package/src/cli/serve/web/components/VarsForm.tsx +5 -3
  37. package/src/cli/serve/web/components/controls/MediaControl.tsx +111 -0
  38. package/src/cli/serve/web/state/FormSt.ts +70 -2
  39. package/src/cli/serve/web/state/host.ts +2 -0
  40. package/src/cli/serve/web/state/mediaDrop.ts +76 -0
  41. package/src/cli/serve/web/styles.ts +16 -2
  42. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +4 -1
  43. package/src/cli/tui/imagePicker/ImagePickerSt.ts +15 -6
  44. package/src/cli/tui/state/TuiSt.ts +1 -1
  45. package/src/coreExports.ts +10 -0
  46. package/src/exampleAssets.ts +13 -3
  47. package/src/host/ComfyUploader.ts +34 -27
  48. package/src/index.ts +1 -1
  49. package/src/runner/ComfyExecution.ts +38 -20
  50. package/src/runner/ComfyWsApi.ts +3 -0
  51. package/src/runner/mediaKinds.ts +51 -0
  52. package/src/vars/ComfyVars.ts +96 -22
  53. package/dist/run-serve-DUqcn0h3.js.map +0 -1
  54. package/dist/run-tui-D-LaSqgB.js.map +0 -1
  55. package/dist/schemaDrift-E95iTF7E.js.map +0 -1
  56. package/dist/state-BytbdZ8s.js.map +0 -1
  57. package/src/cli/serve/web/components/controls/ImageControl.tsx +0 -72
@@ -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[]',
@@ -0,0 +1,51 @@
1
+ // the three media a var can take and an output can be. PURE + dependency-free: the web bundle
2
+ // imports it to decide which var a dropped output may land on
3
+
4
+ export type MediaKind = 'image' | 'audio' | 'video'
5
+
6
+ export const MEDIA_KINDS: readonly MediaKind[] = ['image', 'audio', 'video']
7
+
8
+ /** picker defaults per kind, lowercase without dots */
9
+ export const DEFAULT_MEDIA_EXTENSIONS: Record<MediaKind, readonly string[]> = {
10
+ image: ['png', 'jpg', 'jpeg', 'webp', 'gif'],
11
+ audio: ['wav', 'flac', 'mp3', 'ogg', 'opus', 'm4a'],
12
+ video: ['mp4', 'webm', 'mov', 'mkv', 'm4v'],
13
+ }
14
+
15
+ const MIMES: Record<string, string> = {
16
+ png: 'image/png',
17
+ jpg: 'image/jpeg',
18
+ jpeg: 'image/jpeg',
19
+ webp: 'image/webp',
20
+ gif: 'image/gif',
21
+ flac: 'audio/flac',
22
+ mp3: 'audio/mpeg',
23
+ opus: 'audio/ogg',
24
+ ogg: 'audio/ogg',
25
+ wav: 'audio/wav',
26
+ m4a: 'audio/mp4',
27
+ aac: 'audio/aac',
28
+ mp4: 'video/mp4',
29
+ m4v: 'video/mp4',
30
+ webm: 'video/webm',
31
+ mov: 'video/quicktime',
32
+ mkv: 'video/x-matroska',
33
+ avi: 'video/x-msvideo',
34
+ }
35
+
36
+ /** video containers an output node can name. An animated webp or gif is an IMAGE: the
37
+ * extension decides, never the `animated` flag */
38
+ const VIDEO_EXTENSIONS = new Set(['mp4', 'm4v', 'webm', 'mov', 'mkv', 'avi'])
39
+
40
+ export function extensionOf(filename: string): string {
41
+ const dot = filename.lastIndexOf('.')
42
+ return dot < 0 ? '' : filename.slice(dot + 1).toLowerCase()
43
+ }
44
+
45
+ export function isVideoFilename(filename: string): boolean {
46
+ return VIDEO_EXTENSIONS.has(extensionOf(filename))
47
+ }
48
+
49
+ export function mediaMime(filename: string): string {
50
+ return MIMES[extensionOf(filename)] ?? 'application/octet-stream'
51
+ }
@@ -22,6 +22,10 @@ import { keptKeyword, loraIsOn, loraMuted, loraStrengths, withLora, type LoraStr
22
22
  import { logError } from 'src/utils/log.ts'
23
23
  import { COMMENT_LINE_RE, NEGATIVE_LINE_RE, parsePromptText } from 'src/vars/promptSyntax.ts'
24
24
  import { toPresetList, type VarPreset, type VarPresetSpec } from 'src/vars/presets.ts'
25
+ import { DEFAULT_MEDIA_EXTENSIONS, extensionOf, mediaMime, type MediaKind } from 'src/runner/mediaKinds.ts'
26
+ import { hashArrayBuffer } from 'src/utils/hashArrayBuffer.ts'
27
+ import type { ComfyWorkflow } from 'src/runner/ComfyWorkflow.ts'
28
+ import type { NodeOf } from 'src/types/comfy-sdk.ts'
25
29
 
26
30
  /**
27
31
  * the var's CLASS, and the only safe way to discriminate one: `instanceof` compares class
@@ -31,7 +35,7 @@ import { toPresetList, type VarPreset, type VarPresetSpec } from 'src/vars/prese
31
35
  * in a consumer app: "var 'prompt' has unsupported kind 'text'", for EVERY kind). A string tag
32
36
  * crosses bundles; a class identity does not.
33
37
  */
34
- export type VarKind = 'text' | 'prompt' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'
38
+ export type VarKind = 'text' | 'prompt' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | MediaKind
35
39
 
36
40
  /**
37
41
  * full base: T is what's STORED/edited, Out what the GRAPH consumes at build
@@ -825,52 +829,70 @@ export class SizeVar extends ComfyVar<SizeValue> {
825
829
  }
826
830
  }
827
831
 
828
- export type ImageVarOpts = {
832
+ export type MediaVarOpts = {
829
833
  /** where the TUI picker starts browsing AND what relative values resolve against (absPath) */
830
834
  folder?: string
831
835
  /** picker listing filter, lowercase without dots; never affects the value. NOT a security
832
- * boundary: `comfy-ts serve` keeps its own floor of image types it will read off the disk
836
+ * boundary: `comfy-ts serve` keeps its own floor of media types it will read off the disk
833
837
  * and upload, which this list may NARROW but never widen (emptying it changes the picker,
834
838
  * not what the api accepts) */
835
839
  extensions?: readonly string[]
836
840
  label?: string
837
841
  }
842
+ export type ImageVarOpts = MediaVarOpts
843
+ export type AudioVarOpts = MediaVarOpts
844
+ export type VideoVarOpts = MediaVarOpts
838
845
 
839
- export const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = ['png', 'jpg', 'jpeg', 'webp', 'gif']
846
+ export const DEFAULT_IMAGE_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.image
847
+ export const DEFAULT_AUDIO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.audio
848
+ export const DEFAULT_VIDEO_EXTENSIONS: readonly string[] = DEFAULT_MEDIA_EXTENSIONS.video
840
849
 
841
- /** empty image var consumed at build time — typed so drivers surface it apart from real crashes */
842
- export class ImageVarEmptyError extends Error {
850
+ /** empty media var consumed at build time — typed so drivers surface it apart from real crashes */
851
+ export class MediaVarEmptyError extends Error {
843
852
  /** name, not instanceof: the cli bundle and dist/index.js each define this class */
844
- override readonly name = 'ImageVarEmptyError'
845
- constructor(public readonly varName: string) {
846
- super(`image var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/image.png'))`)
853
+ override readonly name: string = 'MediaVarEmptyError'
854
+ constructor(
855
+ public readonly varName: string,
856
+ public readonly media: MediaKind = 'image',
857
+ ) {
858
+ super(`${media} var '${varName}' is empty — pick a file (TUI: activate the var; script: .set('/path/to/file'))`)
847
859
  }
848
860
  }
861
+ /** the image-only name this error had first; the same class */
862
+ export const ImageVarEmptyError = MediaVarEmptyError
863
+ export type ImageVarEmptyError = MediaVarEmptyError
849
864
 
850
- /** trim + expand a leading `~/` — every ImageVar write funnels through this */
865
+ /** trim + expand a leading `~/` — every media var write funnels through this */
851
866
  function expandUserPath(raw: string): string {
852
867
  const trimmed = raw.trim()
853
868
  return trimmed.startsWith('~/') ? join(getComfyStorage().homedir(), trimmed.slice(2)) : trimmed
854
869
  }
855
870
 
871
+ /** the loader node each medium goes through, and its file input */
872
+ const MEDIA_LOADERS: Record<MediaKind, { node: string; input: string }> = {
873
+ image: { node: 'LoadImage', input: 'image' },
874
+ audio: { node: 'LoadAudio', input: 'audio' },
875
+ video: { node: 'LoadVideo', input: 'file' },
876
+ }
877
+
856
878
  /**
857
- * a local image path. The VALUE is a PLAIN PATH STRING — text-encodable,
879
+ * a local media file path. The VALUE is a PLAIN PATH STRING — text-encodable,
858
880
  * drafts persist it verbatim (toJSON = the string), hand-editable in the
859
- * draft json. Empty = unset: outValue()/absPath() throw ImageVarEmptyError,
860
- * so a build never runs on a silent placeholder. The TUI opens the image
861
- * picker overlay for kind 'image'.
881
+ * draft json. Empty = unset: outValue()/absPath() throw MediaVarEmptyError,
882
+ * so a build never runs on a silent placeholder. The TUI opens the file
883
+ * picker overlay for every media kind.
862
884
  */
863
- export class ImageVar extends ComfyVar<string> {
864
- readonly kind = 'image' as const
885
+ export abstract class MediaVar extends ComfyVar<string> {
886
+ abstract override readonly kind: MediaKind
865
887
  constructor(
866
888
  defaultValue: string,
867
- public opts: ImageVarOpts = {},
889
+ public opts: MediaVarOpts = {},
868
890
  ) {
869
891
  super(expandUserPath(defaultValue), opts.label)
870
892
  }
871
893
  /** what the picker lists (lowercase, no dots) */
872
894
  get extensions(): readonly string[] {
873
- return this.opts.extensions ?? DEFAULT_IMAGE_EXTENSIONS
895
+ return this.opts.extensions ?? DEFAULT_MEDIA_EXTENSIONS[this.kind]
874
896
  }
875
897
  override set(value: string): this {
876
898
  return super.set(expandUserPath(value))
@@ -882,8 +904,8 @@ export class ImageVar extends ComfyVar<string> {
882
904
  isSet(): boolean {
883
905
  return this.value !== ''
884
906
  }
885
- private emptyError(): ImageVarEmptyError {
886
- return new ImageVarEmptyError(this.name ?? this.label ?? 'image')
907
+ private emptyError(): MediaVarEmptyError {
908
+ return new MediaVarEmptyError(this.name ?? this.label ?? this.kind, this.kind)
887
909
  }
888
910
  /** the ONE resolution helper: absolute kept as-is, relative resolved against opts.folder, else cwd */
889
911
  absPath(): string {
@@ -901,9 +923,59 @@ export class ImageVar extends ComfyVar<string> {
901
923
  const home = getComfyStorage().homedir()
902
924
  return this.value.startsWith(`${home}/`) ? `~${this.value.slice(home.length)}` : this.value
903
925
  }
926
+ /** upload the file hash-named (reruns dedupe) and add this medium's loader node. A dry
927
+ * build names the file by its hash and uploads nothing */
928
+ protected async loadVia(wf: ComfyWorkflow<string>): Promise<unknown> {
929
+ const loader = MEDIA_LOADERS[this.kind]
930
+ const factory = wf.builderBase[loader.node]
931
+ if (factory == null)
932
+ throw new Error(
933
+ `host '${wf.host.data.id}' has no ${loader.node} node: ${this.kind} var '${this.name ?? '?'}' cannot load`,
934
+ )
935
+ const abs = this.absPath()
936
+ const bytes = getComfyStorage().readBytes(abs)
937
+ const ext = extensionOf(abs)
938
+ const name = `${hashArrayBuffer(bytes)}${ext === '' ? '' : `.${ext}`}`
939
+ const onHost = wf.dry
940
+ ? name
941
+ : await wf.host.uploader.uploadInput({
942
+ blob: new Blob([bytes as Uint8Array<ArrayBuffer>], { type: mediaMime(abs) }),
943
+ name,
944
+ slot: `${loader.node}.${loader.input}`,
945
+ type: 'input',
946
+ })
947
+ return factory({ [loader.input]: onHost })
948
+ }
949
+ }
950
+
951
+ /** a local image path, loaded through LoadImage */
952
+ export class ImageVar extends MediaVar {
953
+ readonly kind = 'image' as const
954
+ async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadImage'>> {
955
+ // sanctioned cast (family 1): the node is the host's own LoadImage, built from object_info
956
+ return (await this.loadVia(wf)) as NodeOf<WID, 'LoadImage'>
957
+ }
958
+ }
959
+
960
+ /** a local audio path, loaded through LoadAudio */
961
+ export class AudioVar extends MediaVar {
962
+ readonly kind = 'audio' as const
963
+ async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadAudio'>> {
964
+ // sanctioned cast (family 1): same as ImageVar
965
+ return (await this.loadVia(wf)) as NodeOf<WID, 'LoadAudio'>
966
+ }
967
+ }
968
+
969
+ /** a local video path, loaded through LoadVideo */
970
+ export class VideoVar extends MediaVar {
971
+ readonly kind = 'video' as const
972
+ async loadInWorkflow<WID extends string>(wf: ComfyWorkflow<WID>): Promise<NodeOf<WID, 'LoadVideo'>> {
973
+ // sanctioned cast (family 1): same as ImageVar
974
+ return (await this.loadVia(wf)) as NodeOf<WID, 'LoadVideo'>
975
+ }
904
976
  }
905
977
 
906
- /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image */
978
+ /** the var constructors: v.text / v.prompt / v.int / v.float / v.seed / v.toggle / v.choice / v.loras / v.size / v.image / v.audio / v.video */
907
979
  export const v = {
908
980
  // the old `v.text(x, 'label')` form still works: a bare string IS the label
909
981
  text: (defaultValue: string, opts: TextVarOpts | string = {}): TextVar =>
@@ -936,7 +1008,9 @@ export const v = {
936
1008
  opts: { presets?: SizePreset[]; starred?: readonly string[]; label?: string; image?: ImageVar } = {},
937
1009
  ): SizeVar =>
938
1010
  new SizeVar(defaultValue, opts.presets ?? sizePresetsFor(defaultValue), opts.label, opts.image, opts.starred),
939
- image: (defaultValue: string, opts: ImageVarOpts = {}): ImageVar => new ImageVar(defaultValue, opts),
1011
+ image: (defaultValue: string, opts: MediaVarOpts = {}): ImageVar => new ImageVar(defaultValue, opts),
1012
+ audio: (defaultValue: string, opts: MediaVarOpts = {}): AudioVar => new AudioVar(defaultValue, opts),
1013
+ video: (defaultValue: string, opts: MediaVarOpts = {}): VideoVar => new VideoVar(defaultValue, opts),
940
1014
  }
941
1015
 
942
1016
  /**