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
@@ -0,0 +1,8 @@
1
+ # Bundled example media
2
+
3
+ Default inputs for the examples that take an audio or a video file. They ship in the npm tarball, so these examples run out of the box. Both are synthetic (ffmpeg test sources), so no license question applies.
4
+
5
+ | file | what | made with |
6
+ | ------------------------ | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
7
+ | `testsrc_256x256_3s.mp4` | 3 s, 256×256, 12 fps, h264, no audio track | `ffmpeg -f lavfi -i "testsrc2=size=256x256:rate=12:duration=3" -c:v libx264 -pix_fmt yuv420p -crf 30 -movflags +faststart` |
8
+ | `sine_440hz_3s.flac` | 3 s, 440 Hz sine at 30% volume, 22.05 kHz | `ffmpeg -f lavfi -i "sine=frequency=440:duration=3:sample_rate=22050" -af "volume=0.3" -c:a flac` |
@@ -0,0 +1,47 @@
1
+ // a new soundtrack on a video, on windows-1: the frames of one file, the audio of another, muxed
2
+ // back into one video at the fps you pick (lower = slower). Core nodes only, no model
3
+ // shows the media vars: v.video and v.audio load through LoadVideo and LoadAudio, and the result
4
+ // comes back as a VIDEO output (execution.videos). In the serve panel, drop a file on either var,
5
+ // or drag a generated video or audio from the results onto it
6
+ // run directly: bun examples/rvion/14-video-soundtrack.cflow.ts [video.mp4] [audio.flac]
7
+ import { ComfyTS, exampleMediaPath, v } from 'comfy-ts'
8
+
9
+ const comfy = ComfyTS.create()
10
+ const host = comfy.host({ id: 'windows-1', host: 'desktop-im18794', port: 8085 })
11
+ await host.loadSchemaFromCache() // offline import; run() connects lazily
12
+
13
+ // bundled defaults (examples/media/, ship in the tarball)
14
+ const video = v.video(exampleMediaPath('testsrc_256x256_3s.mp4'))
15
+ const soundtrack = v.audio(exampleMediaPath('sine_440hz_3s.flac'))
16
+
17
+ export const videoSoundtrack = host.defineWorkflow({
18
+ id: 'video-soundtrack',
19
+ tags: ['soundtrack', 'mux'],
20
+ vars: {
21
+ video,
22
+ soundtrack,
23
+ fps: v.float(12, { min: 1, max: 60 }),
24
+ },
25
+ // async build: both files are uploaded (hash-named, deduped) per run
26
+ build: async (b, vars, wf) => {
27
+ const frames = b.GetVideoComponents({ video: await video.loadInWorkflow(wf) })
28
+ b.SaveVideo({
29
+ video: b.CreateVideo({ images: frames._IMAGE, fps: vars.fps, audio: await soundtrack.loadInWorkflow(wf) }),
30
+ filename_prefix: 'comfy-ts-example/video-soundtrack',
31
+ format: 'mp4',
32
+ codec: 'h264',
33
+ })
34
+ },
35
+ })
36
+
37
+ export default videoSoundtrack
38
+
39
+ // standalone run (skipped when another driver — e.g. the TUI — imports this module)
40
+ if (import.meta.main) {
41
+ if (process.argv[2]) videoSoundtrack.vars.video.set(process.argv[2])
42
+ if (process.argv[3]) videoSoundtrack.vars.soundtrack.set(process.argv[3])
43
+
44
+ const execution = await videoSoundtrack.run({ log: true, save: { prefix: 'comfy-ts-example/video-soundtrack' } })
45
+ for (const clip of execution.videos) console.log(`🟢 ${clip.absPath}`)
46
+ host.disconnect()
47
+ }
@@ -71,11 +71,12 @@ if (import.meta.main) {
71
71
  }
72
72
  ```
73
73
 
74
- Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`, `v.size`, `v.loras`, `v.prompt`, `v.image`. Notes:
74
+ Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`, `v.size`, `v.loras`, `v.prompt`, `v.image`, `v.audio`, `v.video`. Notes:
75
75
 
76
76
  - `v.loras(/regex/)` resolves against the host's real lora list; `activeLoras(vars.loras)` returns `{ lora_name, strength_model, strength_clip }[]` for a standard `LoraLoader` chain.
77
77
  - `v.prompt` is structured: `//` lines are comments (stripped), `- ` lines go to the negative prompt, `{ loraKeywordsFrom: lorasVar }` prefixes lora trigger keywords. The value is `{ positive, negative }`.
78
78
  - `v.image` holds a local image path as a plain string; an empty value throws at build time instead of running a silent placeholder. Capture the var in a const and call `image.absPath()` in `build`. Default it to a bundled sample with `exampleImagePath('bear_1024x1024.jpg')` (ships in the package). In the TUI it opens an image picker (browse, favorite folders, recents, preview).
79
+ - `v.audio` and `v.video` work the same way for audio and video files. In `build`, `await myVar.loadInWorkflow(wf)` uploads the file and returns the loader node (`LoadImage`, `LoadAudio`, `LoadVideo`). Default them with `exampleMediaPath('sine_440hz_3s.flac')` or `exampleMediaPath('testsrc_256x256_3s.mp4')`. Video results land in `execution.videos`.
79
80
  - `vars` may be a lambda `(v) => ({ ... })` so vars can reference each other.
80
81
  - `build` may be async, for uploads: the third param `wf` feeds `MediaImage` helpers (`new MediaImage({ path }).loadInWorkflow_viaLoadImageNode(wf)`). Uploads are hash-named and deduped, nothing is re-sent.
81
82
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.14.0",
3
+ "version": "2.15.0",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -140,7 +140,7 @@
140
140
  "oxfmt": "^0.60.0",
141
141
  "oxlint": "^1.75.0",
142
142
  "oxlint-tsgolint": "^7.0.2001",
143
- "rvlib-shipkit": "^1.5.0",
143
+ "rvlib-shipkit": "^1.6.0",
144
144
  "rvlib-ts-tools": "^0.3.3",
145
145
  "tsdown": "^0.22.14",
146
146
  "typescript": "^7.0.2"
@@ -73,8 +73,8 @@ import {
73
73
  } from 'src/host/loraManagerApi.ts'
74
74
  import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
75
75
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
76
- import { DEFAULT_IMAGE_EXTENSIONS } from 'src/vars/ComfyVars.ts'
77
- import type { ImageVar, LorasVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'
76
+ import { DEFAULT_MEDIA_EXTENSIONS, MEDIA_KINDS, type MediaKind } from 'src/runner/mediaKinds.ts'
77
+ import type { LorasVar, MediaVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'
78
78
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
79
79
  import { bang } from 'src/utils/bang.ts'
80
80
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
@@ -94,6 +94,8 @@ export type ServeExecution = {
94
94
  texts?: { nodeId: string; nodeKey: string | null; text: string }[]
95
95
  /** audio files (SaveAudio*, PreviewAudio). absPath null = saving off, bytes the only copy */
96
96
  audios?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]
97
+ /** video files (SaveVideo, SaveWEBM, VHS_VideoCombine), same shape as audios */
98
+ videos?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]
97
99
  data: { id: string; error?: unknown }
98
100
  /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
99
101
  progressGlobal?: { percent: number }
@@ -121,28 +123,26 @@ export type ServeReply = {
121
123
  headers?: Record<string, string>
122
124
  }
123
125
 
124
- /** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's
125
- * LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
126
- const SERVE_IMAGE_FLOOR = new Set([
127
- ...DEFAULT_IMAGE_EXTENSIONS.map((e) => e.toLowerCase()),
128
- 'bmp',
129
- 'tif',
130
- 'tiff',
131
- 'avif',
132
- ])
126
+ /** what serve will read off the disk and upload, per medium. Wider than the picker defaults:
127
+ * ComfyUI's LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
128
+ const SERVE_MEDIA_FLOOR: Record<MediaKind, Set<string>> = {
129
+ image: new Set([...DEFAULT_MEDIA_EXTENSIONS.image, 'bmp', 'tif', 'tiff', 'avif']),
130
+ audio: new Set([...DEFAULT_MEDIA_EXTENSIONS.audio, 'aac']),
131
+ video: new Set([...DEFAULT_MEDIA_EXTENSIONS.video, 'avi']),
132
+ }
133
133
 
134
134
  /** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops
135
135
  * a .png that holds a key or a script from being read and uploaded to the host.
136
136
  * HONEST LIMIT: this is checked before the run, and the file is read again when the graph
137
137
  * builds, so a local writer who can swap the path in between still wins. Closing that needs
138
138
  * the upload to hold an fd, which is a bigger change than this gate. */
139
- function looksLikeImage(path: string): boolean {
139
+ function looksLikeMedia(kind: MediaKind, path: string): boolean {
140
140
  let fd: number | null = null
141
141
  try {
142
142
  fd = openSync(path, 'r')
143
143
  const head = new Uint8Array(16)
144
144
  const n = readSync(fd, head, 0, 16, 0)
145
- return isImageMagic(head.subarray(0, n))
145
+ return isMediaMagic(kind, head.subarray(0, n))
146
146
  } catch {
147
147
  return false
148
148
  } finally {
@@ -155,14 +155,15 @@ function looksLikeImage(path: string): boolean {
155
155
  * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able
156
156
  * to widen what an unauthenticated request can make the server read. The var may narrow this
157
157
  * floor, never leave it. */
158
- function serveAcceptsImageExt(declared: readonly string[], ext: string): boolean {
158
+ function serveAcceptsMediaExt(kind: MediaKind, declared: readonly string[], ext: string): boolean {
159
+ const floor = SERVE_MEDIA_FLOOR[kind]
159
160
  if (ext === '') return false
160
- if (!SERVE_IMAGE_FLOOR.has(ext)) return false
161
+ if (!floor.has(ext)) return false
161
162
  // a declared list NARROWS the floor by its intersection. When that intersection is empty
162
163
  // the declaration says nothing this bridge can honour (a picker filter for a format serve
163
164
  // does not read), so the floor stands: narrowing to NOTHING would refuse every image,
164
165
  // including the ones the var was declared for
165
- const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, '')).filter((e) => SERVE_IMAGE_FLOOR.has(e))
166
+ const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, '')).filter((e) => floor.has(e))
166
167
  return narrowed.length === 0 || narrowed.includes(ext)
167
168
  }
168
169
 
@@ -241,6 +242,11 @@ const CONTENT_TYPES: Record<string, string> = {
241
242
  '.gif': 'image/gif',
242
243
  '.mp4': 'video/mp4',
243
244
  '.webm': 'video/webm',
245
+ '.m4v': 'video/mp4',
246
+ '.mov': 'video/quicktime',
247
+ '.mkv': 'video/x-matroska',
248
+ '.avi': 'video/x-msvideo',
249
+ '.aac': 'audio/aac',
244
250
  '.flac': 'audio/flac',
245
251
  '.mp3': 'audio/mpeg',
246
252
  '.opus': 'audio/ogg',
@@ -274,6 +280,47 @@ export function isImageMagic(b: Uint8Array): boolean {
274
280
  return false
275
281
  }
276
282
 
283
+ /** the same full-signature sniff for every medium: a var of one kind never reads a file of
284
+ * another. mp4, mov and m4a share the isobmff `ftyp` box, the extension floor tells them apart */
285
+ export function isMediaMagic(kind: MediaKind, b: Uint8Array): boolean {
286
+ const at = (i: number, ...want: number[]): boolean => want.every((w, k) => b[i + k] === w)
287
+ const isobmff = at(4, 0x66, 0x74, 0x79, 0x70)
288
+ if (kind === 'image') return isImageMagic(b)
289
+ if (kind === 'audio') {
290
+ if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x41, 0x56, 0x45)) return true // riff....wave
291
+ if (at(0, 0x66, 0x4c, 0x61, 0x43)) return true // flac
292
+ if (at(0, 0x4f, 0x67, 0x67, 0x53)) return true // ogg (vorbis, opus)
293
+ if (at(0, 0x49, 0x44, 0x33)) return true // mp3 with an id3 tag
294
+ // an mpeg frame sync: 11 set bits, a version and a layer that are not reserved, then a
295
+ // bitrate and a sample rate that are not the invalid 1111 and 11. FF FE is refused whole:
296
+ // it is the utf-16le BOM, and a layer I header is never what a real file starts with
297
+ const b0 = b[0]
298
+ const b1 = b[1]
299
+ const b2 = b[2]
300
+ if (
301
+ b0 === 0xff &&
302
+ b1 != null &&
303
+ b1 !== 0xfe &&
304
+ b2 != null &&
305
+ (b1 & 0xe0) === 0xe0 &&
306
+ (b1 & 0x18) !== 0x08 &&
307
+ (b1 & 0x06) !== 0 &&
308
+ b2 >> 4 !== 0xf &&
309
+ ((b2 >> 2) & 3) !== 3
310
+ )
311
+ return true
312
+ if (b0 === 0xff && b1 != null && (b1 & 0xf6) === 0xf0) return true // aac adts
313
+ return isobmff // m4a
314
+ }
315
+ if (at(0, 0x1a, 0x45, 0xdf, 0xa3)) return true // ebml: webm, mkv
316
+ if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x41, 0x56, 0x49, 0x20)) return true // riff....avi
317
+ return isobmff // mp4, mov, m4v
318
+ }
319
+
320
+ function isMediaKind(kind: string): kind is MediaKind {
321
+ return (MEDIA_KINDS as readonly string[]).includes(kind)
322
+ }
323
+
277
324
  function json(status: number, payload: unknown): ServeReply {
278
325
  return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
279
326
  }
@@ -288,7 +335,8 @@ const USAGE = [
288
335
  'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
289
336
  'DELETE /drafts/<module>/<draft> — delete that draft file',
290
337
  'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
291
- 'POST /upload with {"name","dataBase64"} — store a browser file for an image var',
338
+ 'POST /upload with {"name","dataBase64"} — store a browser file for an image, audio or video var',
339
+ 'GET /images|audio|video/<promptId>/<ix> — an output kept in memory (saving off)',
292
340
  'GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)',
293
341
  'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',
294
342
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
@@ -443,6 +491,8 @@ export class ServeApp {
443
491
  return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)
444
492
  if (segs[0] === 'audio' && segs.length === 3 && segs[1] != null && segs[2] != null)
445
493
  return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`)
494
+ if (segs[0] === 'video' && segs.length === 3 && segs[1] != null && segs[2] != null)
495
+ return this.replyMemoryImage(`video/${segs[1]}/${segs[2]}`)
446
496
  if (segs[0] === 'results' && segs.length === 1)
447
497
  return json(200, { runs: this.kept.list(), memory: this.kept.usage() })
448
498
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
@@ -756,7 +806,7 @@ export class ServeApp {
756
806
  return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }
757
807
  }
758
808
 
759
- /** browser file → local file an image var can point at (downloadInput family) */
809
+ /** browser file → local file a media var can point at (downloadInput family) */
760
810
  private replyUpload(req: ServeRequest): ServeReply {
761
811
  let parsed: unknown
762
812
  try {
@@ -1591,6 +1641,8 @@ export class ServeApp {
1591
1641
  const produced = [`${execution.images.length} image(s)`]
1592
1642
  const audios = execution.audios ?? []
1593
1643
  if (audios.length > 0) produced.push(`${audios.length} audio(s)`)
1644
+ const videos = execution.videos ?? []
1645
+ if (videos.length > 0) produced.push(`${videos.length} video(s)`)
1594
1646
  if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)
1595
1647
  console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)
1596
1648
 
@@ -1610,12 +1662,18 @@ export class ServeApp {
1610
1662
  blobs.push(this.memoryBlob(key, a.bytes, a.filename))
1611
1663
  return key
1612
1664
  })
1665
+ const videoKeys = videos.map((a, ix) => {
1666
+ if (a.absPath != null) return null
1667
+ const key = `video/${execution.data.id}/${ix}`
1668
+ blobs.push(this.memoryBlob(key, a.bytes, a.filename))
1669
+ return key
1670
+ })
1613
1671
  // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and handle() decodes
1614
1672
  // per segment, so the lookup gets the raw key back
1615
1673
  const memoryUrl = (route: string, key: string): string =>
1616
1674
  `/${route}/${key
1617
1675
  .split('/')
1618
- .slice(route === 'audio' ? 1 : 0)
1676
+ .slice(route === 'images' ? 0 : 1)
1619
1677
  .map((seg) => encodeURIComponent(seg))
1620
1678
  .join('/')}`
1621
1679
  const record: RunRecord = {
@@ -1645,8 +1703,17 @@ export class ServeApp {
1645
1703
  absPath: a.absPath,
1646
1704
  }
1647
1705
  }),
1706
+ videos: videos.map((a, ix) => {
1707
+ const key = videoKeys[ix]
1708
+ return {
1709
+ filename: a.filename,
1710
+ mime: a.mime,
1711
+ url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl('video', key) : null,
1712
+ absPath: a.absPath,
1713
+ }
1714
+ }),
1648
1715
  }
1649
- this.kept.add({ record, imageKeys, audioKeys, blobs })
1716
+ this.kept.add({ record, imageKeys, audioKeys, videoKeys, blobs })
1650
1717
 
1651
1718
  // Accept: image/* → first image's bytes directly (curl -o, <img src>)
1652
1719
  const first = execution.images[0]
@@ -1697,7 +1764,7 @@ export class ServeApp {
1697
1764
  let value = rawValue
1698
1765
  // kind, never instanceof: consumer and cli hold different class copies (VarKind
1699
1766
  // owns the WHY); casts are the kind-narrowing family, agent/coding.md whitelist 6
1700
- if (varDef.kind === 'image' && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
1767
+ if (isMediaKind(varDef.kind) && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
1701
1768
  try {
1702
1769
  value = await this.downloadInput(rawValue)
1703
1770
  } catch (e) {
@@ -1723,18 +1790,19 @@ export class ServeApp {
1723
1790
  if (err != null) return { status: 400, error: err }
1724
1791
  }
1725
1792
 
1726
- // 3. image vars must point at a real FILE of a declared type BEFORE anything is queued.
1793
+ // 3. media vars must point at a real FILE of a declared type BEFORE anything is queued.
1727
1794
  // the path a request hands us is read off this box and uploaded to the ComfyUI host, so
1728
1795
  // the extension list the descriptor advertises is enforced here, not merely advertised:
1729
1796
  // a var that accepts .png must not be talked into reading a key or a config file
1730
1797
  for (const [k, varDef] of varMap) {
1731
- if (varDef.kind !== 'image') continue
1732
- const img = varDef as ImageVar
1733
- if (!img.isSet()) continue
1734
- const abs = img.absPath()
1798
+ const kind = varDef.kind
1799
+ if (!isMediaKind(kind)) continue
1800
+ const media = varDef as MediaVar
1801
+ if (!media.isSet()) continue
1802
+ const abs = media.absPath()
1735
1803
  // ONE message for every rejection below: distinct ones told an unauthenticated caller
1736
1804
  // whether any path exists, is a file, and what type it is
1737
- const refuse = { status: 400, error: `image var '${k}': not a usable image file` }
1805
+ const refuse = { status: 400, error: `${kind} var '${k}': not a usable ${kind} file` }
1738
1806
  if (!existsSync(abs)) return refuse
1739
1807
  // the REAL path: statSync follows symlinks, so `pic.png -> id_rsa` passed a check made
1740
1808
  // on the link's name. Resolving first means the gate judges the file being read
@@ -1749,8 +1817,9 @@ export class ServeApp {
1749
1817
  } catch {
1750
1818
  return refuse
1751
1819
  }
1752
- if (!serveAcceptsImageExt(img.extensions, extname(real).toLowerCase().replace(/^\./, ''))) return refuse
1753
- if (!looksLikeImage(real)) return refuse
1820
+ if (!serveAcceptsMediaExt(kind, media.extensions, extname(real).toLowerCase().replace(/^\./, '')))
1821
+ return refuse
1822
+ if (!looksLikeMedia(kind, real)) return refuse
1754
1823
  }
1755
1824
 
1756
1825
  // 4. seed policy (architecture item 12): payload wins; '?' rerolls;
@@ -1795,7 +1864,9 @@ export class ServeApp {
1795
1864
  }
1796
1865
  } catch (e) {
1797
1866
  // name, not instanceof: same two-copies problem as the var classes
1798
- if (e instanceof Error && e.name === 'ImageVarEmptyError') return { status: 400, error: e.message }
1867
+ // both names: a project on an older comfy-ts still throws the image-only one
1868
+ if (e instanceof Error && (e.name === 'MediaVarEmptyError' || e.name === 'ImageVarEmptyError'))
1869
+ return { status: 400, error: e.message }
1799
1870
  // the ComfyUI host is upstream of this bridge: 502, not "serve crashed".
1800
1871
  // The connect deadline (ConnectOptions.timeoutMs) is what makes this
1801
1872
  // this runs inside the module mutex: a url that never answers would hold it
@@ -11,7 +11,7 @@ import type {
11
11
  AnyVar,
12
12
  AnyChoiceVar,
13
13
  FloatVar,
14
- ImageVar,
14
+ MediaVar,
15
15
  IntVar,
16
16
  LorasVar,
17
17
  PromptVar,
@@ -158,9 +158,11 @@ export function applyVarPayload(
158
158
  return `var '${name}' expects {"width":W,"height":H}, "WxH", or a preset label`
159
159
  }
160
160
 
161
- case 'image': {
161
+ case 'image':
162
+ case 'audio':
163
+ case 'video': {
162
164
  if (typeof raw !== 'string') return `var '${name}' expects a file path or http(s) url string`
163
- ;(varDef as ImageVar).set(raw)
165
+ ;(varDef as MediaVar).set(raw)
164
166
  return null
165
167
  }
166
168
 
@@ -6,7 +6,7 @@ import type {
6
6
  AnyChoiceVar,
7
7
  ChoiceSelect,
8
8
  FloatVar,
9
- ImageVar,
9
+ MediaVar,
10
10
  IntVar,
11
11
  LorasVar,
12
12
  PromptVar,
@@ -162,8 +162,10 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
162
162
  starredPresets: [...v.starred],
163
163
  }
164
164
  }
165
- case 'image': {
166
- const v = varDef as ImageVar
165
+ case 'image':
166
+ case 'audio':
167
+ case 'video': {
168
+ const v = varDef as MediaVar
167
169
  return { ...base, payload: 'local file path or http(s) url', extensions: v.extensions }
168
170
  }
169
171
  default: {
@@ -19,6 +19,8 @@ export type RunRecord = {
19
19
  texts: { nodeKey: string | null; text: string }[]
20
20
  images: RunOutput[]
21
21
  audios: RunAudioOutput[]
22
+ /** absent on a record from an older server */
23
+ videos?: RunAudioOutput[]
22
24
  }
23
25
 
24
26
  export type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }
@@ -32,7 +34,12 @@ export const KEPT_RUNS = 50
32
34
  export const DEFAULT_MEMORY_BUDGET_MB = 100
33
35
 
34
36
  /** a run and the memory key of each output (null = saved on disk, or never had bytes) */
35
- type Kept = { record: RunRecord; imageKeys: (string | null)[]; audioKeys: (string | null)[] }
37
+ type Kept = {
38
+ record: RunRecord
39
+ imageKeys: (string | null)[]
40
+ audioKeys: (string | null)[]
41
+ videoKeys: (string | null)[]
42
+ }
36
43
 
37
44
  export class ResultHistory {
38
45
  /** newest first */
@@ -43,13 +50,20 @@ export class ResultHistory {
43
50
 
44
51
  constructor(private budgetBytes: number) {}
45
52
 
46
- add(p: { record: RunRecord; imageKeys: (string | null)[]; audioKeys: (string | null)[]; blobs: KeptBlob[] }): void {
53
+ add(p: {
54
+ record: RunRecord
55
+ imageKeys: (string | null)[]
56
+ audioKeys: (string | null)[]
57
+ videoKeys?: (string | null)[]
58
+ blobs: KeptBlob[]
59
+ }): void {
47
60
  this.remove(p.record.promptId)
48
61
  for (const b of p.blobs) {
49
62
  this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType })
50
63
  this.used += b.bytes.byteLength
51
64
  }
52
- this.runs = [{ record: p.record, imageKeys: p.imageKeys, audioKeys: p.audioKeys }, ...this.runs]
65
+ const kept = { record: p.record, imageKeys: p.imageKeys, audioKeys: p.audioKeys, videoKeys: p.videoKeys ?? [] }
66
+ this.runs = [kept, ...this.runs]
53
67
  for (const dropped of this.runs.slice(KEPT_RUNS)) this.freeRun(dropped)
54
68
  this.runs = this.runs.slice(0, KEPT_RUNS)
55
69
  this.evict()
@@ -65,6 +79,7 @@ export class ResultHistory {
65
79
  ...k.record,
66
80
  images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
67
81
  audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
82
+ videos: (k.record.videos ?? []).map((a, ix) => this.withLiveUrl(a, k.videoKeys[ix])),
68
83
  }))
69
84
  }
70
85
 
@@ -96,7 +111,7 @@ export class ResultHistory {
96
111
  }
97
112
 
98
113
  private freeRun(k: Kept): void {
99
- for (const key of [...k.imageKeys, ...k.audioKeys]) {
114
+ for (const key of [...k.imageKeys, ...k.audioKeys, ...k.videoKeys]) {
100
115
  if (key == null) continue
101
116
  const b = this.blobs.get(key)
102
117
  if (b == null) continue
@@ -118,8 +133,9 @@ export class ResultHistory {
118
133
  this.runs = this.runs.filter((k) => {
119
134
  const live = (keys: (string | null)[]): boolean => keys.some((key) => key == null || this.blobs.has(key))
120
135
  const hasText = k.record.texts.length > 0
121
- const hasNothing = k.record.images.length === 0 && k.record.audios.length === 0
122
- return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys)
136
+ const hasNothing =
137
+ k.record.images.length === 0 && k.record.audios.length === 0 && (k.record.videos ?? []).length === 0
138
+ return hasText || hasNothing || live(k.imageKeys) || live(k.audioKeys) || live(k.videoKeys)
123
139
  })
124
140
  }
125
141
  }
@@ -18,6 +18,8 @@ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
18
18
 
19
19
  const DEFAULT_PORT = 8288
20
20
  const BODY_CAP = 10_000_000
21
+ /** a video dropped on a media var rides POST /upload as base64 json: ~200 MB of file */
22
+ export const UPLOAD_BODY_CAP = 280_000_000
21
23
 
22
24
  export function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
23
25
  let target: string | undefined
@@ -56,6 +58,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
56
58
  'access-control-allow-headers': 'content-type, accept',
57
59
  }
58
60
  return (req, res) => {
61
+ const cap = req.method === 'POST' && (req.url ?? '').split('?')[0] === '/upload' ? UPLOAD_BODY_CAP : BODY_CAP
59
62
  const chunks: Buffer[] = []
60
63
  let size = 0
61
64
  let overflow = false
@@ -63,7 +66,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
63
66
  req.on('data', (c: Buffer) => {
64
67
  if (overflow) return
65
68
  size += c.length
66
- if (size > BODY_CAP) {
69
+ if (size > cap) {
67
70
  // answer NOW: a destroyed request never emits 'end'
68
71
  overflow = true
69
72
  res.writeHead(413, { 'content-type': 'application/json', ...cors })
@@ -32,6 +32,9 @@ export type GeneratedText = { nodeKey: string | null; text: string }
32
32
  /** an audio file (SaveAudio*, PreviewAudio): the panel plays it in an <audio> player */
33
33
  export type GeneratedAudio = { filename: string; mime: string; url: string | null; absPath: string | null }
34
34
 
35
+ /** a video file (SaveVideo, SaveWEBM, VHS_VideoCombine): the panel plays it in a <video> player */
36
+ export type GeneratedVideo = GeneratedAudio
37
+
35
38
  export type GenerateOk = {
36
39
  ok: true
37
40
  module: string
@@ -44,6 +47,7 @@ export type GenerateOk = {
44
47
  images: GeneratedImage[]
45
48
  texts?: GeneratedText[]
46
49
  audios?: GeneratedAudio[]
50
+ videos?: GeneratedVideo[]
47
51
  }
48
52
 
49
53
  async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {