comfy-ts 2.13.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 (75) 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-DlRBv_Nk.js → run-serve-B5PfIuhK.js} +310 -88
  12. package/dist/run-serve-B5PfIuhK.js.map +1 -0
  13. package/dist/{run-tui-B5uxm2_l.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 +160 -71
  18. package/dist/{state-CUp2J1Zy.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 +189 -110
  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 +141 -0
  33. package/src/cli/serve/run-serve.ts +4 -1
  34. package/src/cli/serve/runError.ts +23 -0
  35. package/src/cli/serve/serveSettings.ts +17 -1
  36. package/src/cli/serve/web/api.ts +33 -2
  37. package/src/cli/serve/web/components/App.tsx +6 -4
  38. package/src/cli/serve/web/components/Gallery.tsx +116 -11
  39. package/src/cli/serve/web/components/Icon.tsx +4 -0
  40. package/src/cli/serve/web/components/MemoryBudget.tsx +98 -0
  41. package/src/cli/serve/web/components/RunError.tsx +19 -0
  42. package/src/cli/serve/web/components/ShortcutsModal.tsx +54 -0
  43. package/src/cli/serve/web/components/SideMenu.tsx +14 -0
  44. package/src/cli/serve/web/components/VarsForm.tsx +75 -55
  45. package/src/cli/serve/web/components/controls/BasicControls.tsx +8 -1
  46. package/src/cli/serve/web/components/controls/LorasControl.tsx +6 -3
  47. package/src/cli/serve/web/components/controls/MediaControl.tsx +111 -0
  48. package/src/cli/serve/web/promptEditor/promptExtensions.ts +3 -1
  49. package/src/cli/serve/web/state/FormSt.ts +70 -2
  50. package/src/cli/serve/web/state/RunSt.ts +61 -3
  51. package/src/cli/serve/web/state/WebSt.ts +26 -2
  52. package/src/cli/serve/web/state/formRows.ts +9 -0
  53. package/src/cli/serve/web/state/host.ts +2 -0
  54. package/src/cli/serve/web/state/keptResults.ts +26 -0
  55. package/src/cli/serve/web/state/lightbox.ts +17 -0
  56. package/src/cli/serve/web/state/mediaDrop.ts +76 -0
  57. package/src/cli/serve/web/state/shortcutCatalog.ts +100 -0
  58. package/src/cli/serve/web/state/shortcuts.ts +10 -0
  59. package/src/cli/serve/web/styles.ts +112 -24
  60. package/src/cli/tui/imagePicker/ImagePickerOverlay.tsx +4 -1
  61. package/src/cli/tui/imagePicker/ImagePickerSt.ts +15 -6
  62. package/src/cli/tui/state/TuiSt.ts +1 -1
  63. package/src/coreExports.ts +10 -0
  64. package/src/exampleAssets.ts +13 -3
  65. package/src/host/ComfyUploader.ts +34 -27
  66. package/src/index.ts +1 -1
  67. package/src/runner/ComfyExecution.ts +38 -20
  68. package/src/runner/ComfyWsApi.ts +3 -0
  69. package/src/runner/mediaKinds.ts +51 -0
  70. package/src/vars/ComfyVars.ts +96 -22
  71. package/dist/run-serve-DlRBv_Nk.js.map +0 -1
  72. package/dist/run-tui-B5uxm2_l.js.map +0 -1
  73. package/dist/schemaDrift-E95iTF7E.js.map +0 -1
  74. package/dist/state-CUp2J1Zy.js.map +0 -1
  75. 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.13.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"
@@ -28,7 +28,14 @@ import { type TagNode, workflowTags } from 'src/cli/serve/workflowTags.ts'
28
28
  import { workspaceLabels } from 'src/cli/serve/workspaceLabels.ts'
29
29
  import { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'
30
30
  import { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'
31
- import { readServeSettings, writeServeSettings, type ServeSettings } from 'src/cli/serve/serveSettings.ts'
31
+ import {
32
+ readServeSettings,
33
+ validMemoryBudgetMb,
34
+ writeServeSettings,
35
+ type ServeSettings,
36
+ } from 'src/cli/serve/serveSettings.ts'
37
+ import { describeRunError } from 'src/cli/serve/runError.ts'
38
+ import { ResultHistory, type KeptBlob, type RunRecord } from 'src/cli/serve/resultHistory.ts'
32
39
  import { readTabs, SERVE_TABS_FILE, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
33
40
  import { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'
34
41
  import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
@@ -66,8 +73,8 @@ import {
66
73
  } from 'src/host/loraManagerApi.ts'
67
74
  import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
68
75
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
69
- import { DEFAULT_IMAGE_EXTENSIONS } from 'src/vars/ComfyVars.ts'
70
- 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'
71
78
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
72
79
  import { bang } from 'src/utils/bang.ts'
73
80
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
@@ -87,6 +94,8 @@ export type ServeExecution = {
87
94
  texts?: { nodeId: string; nodeKey: string | null; text: string }[]
88
95
  /** audio files (SaveAudio*, PreviewAudio). absPath null = saving off, bytes the only copy */
89
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 }[]
90
99
  data: { id: string; error?: unknown }
91
100
  /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
92
101
  progressGlobal?: { percent: number }
@@ -114,28 +123,26 @@ export type ServeReply = {
114
123
  headers?: Record<string, string>
115
124
  }
116
125
 
117
- /** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's
118
- * LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
119
- const SERVE_IMAGE_FLOOR = new Set([
120
- ...DEFAULT_IMAGE_EXTENSIONS.map((e) => e.toLowerCase()),
121
- 'bmp',
122
- 'tif',
123
- 'tiff',
124
- 'avif',
125
- ])
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
+ }
126
133
 
127
134
  /** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops
128
135
  * a .png that holds a key or a script from being read and uploaded to the host.
129
136
  * HONEST LIMIT: this is checked before the run, and the file is read again when the graph
130
137
  * builds, so a local writer who can swap the path in between still wins. Closing that needs
131
138
  * the upload to hold an fd, which is a bigger change than this gate. */
132
- function looksLikeImage(path: string): boolean {
139
+ function looksLikeMedia(kind: MediaKind, path: string): boolean {
133
140
  let fd: number | null = null
134
141
  try {
135
142
  fd = openSync(path, 'r')
136
143
  const head = new Uint8Array(16)
137
144
  const n = readSync(fd, head, 0, 16, 0)
138
- return isImageMagic(head.subarray(0, n))
145
+ return isMediaMagic(kind, head.subarray(0, n))
139
146
  } catch {
140
147
  return false
141
148
  } finally {
@@ -148,14 +155,15 @@ function looksLikeImage(path: string): boolean {
148
155
  * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able
149
156
  * to widen what an unauthenticated request can make the server read. The var may narrow this
150
157
  * floor, never leave it. */
151
- 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]
152
160
  if (ext === '') return false
153
- if (!SERVE_IMAGE_FLOOR.has(ext)) return false
161
+ if (!floor.has(ext)) return false
154
162
  // a declared list NARROWS the floor by its intersection. When that intersection is empty
155
163
  // the declaration says nothing this bridge can honour (a picker filter for a format serve
156
164
  // does not read), so the floor stands: narrowing to NOTHING would refuse every image,
157
165
  // including the ones the var was declared for
158
- 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))
159
167
  return narrowed.length === 0 || narrowed.includes(ext)
160
168
  }
161
169
 
@@ -173,6 +181,7 @@ const INPUT_DOWNLOAD_TIMEOUT_MS = 60_000
173
181
  /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
174
182
  const TAG_LIST_CAP = 40_000_000
175
183
  const TAG_LIST_TIMEOUT_MS = 120_000
184
+ const MB = 1024 * 1024
176
185
 
177
186
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
178
187
  * whole body first, so a chunked reply with no content-length could exhaust the process before
@@ -233,6 +242,11 @@ const CONTENT_TYPES: Record<string, string> = {
233
242
  '.gif': 'image/gif',
234
243
  '.mp4': 'video/mp4',
235
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',
236
250
  '.flac': 'audio/flac',
237
251
  '.mp3': 'audio/mpeg',
238
252
  '.opus': 'audio/ogg',
@@ -266,6 +280,47 @@ export function isImageMagic(b: Uint8Array): boolean {
266
280
  return false
267
281
  }
268
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
+
269
324
  function json(status: number, payload: unknown): ServeReply {
270
325
  return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
271
326
  }
@@ -280,7 +335,8 @@ const USAGE = [
280
335
  'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
281
336
  'DELETE /drafts/<module>/<draft> — delete that draft file',
282
337
  'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
283
- '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)',
284
340
  'GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)',
285
341
  'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',
286
342
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
@@ -291,13 +347,14 @@ const USAGE = [
291
347
  'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
292
348
  'GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)',
293
349
  'PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>',
294
- 'GET /settings — { saveToDisk } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory',
350
+ 'GET /settings — { saveToDisk, memoryBudgetMb } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory; {"memoryBudgetMb"} caps what memory keeps',
295
351
  'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
296
352
  'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',
297
353
  'GET /hosts/<hostId>/ping — is that host answering right now (restart watch)',
298
354
  'GET /hosts/<hostId>/logs — the last lines of that host console',
299
355
  'GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives',
300
356
  'GET /audio/<promptId>/<ix> — the same for an in-memory audio output',
357
+ 'GET /results — the last runs this process kept, for a reload · DELETE /results[/<promptId>] — forget them, freeing their memory',
301
358
  'GET /outputs/<path> — generated files',
302
359
  ]
303
360
 
@@ -347,9 +404,13 @@ export class ServeApp {
347
404
  private set settings(next: ServeSettings) {
348
405
  this.settingsCache = next
349
406
  }
350
- /** in-memory outputs of runs made with saving OFF: the ONLY copy, so the gallery has
351
- * something to show. Capped and FIFO, a long session must not grow without bound */
352
- private memoryImages = new Map<string, { bytes: Uint8Array; contentType: string }>()
407
+ /** the last runs, for a reload, and the bytes of their unsaved outputs: the ONLY copy.
408
+ * LAZY for the same reason as settings: its budget is a setting */
409
+ private keptCache: ResultHistory | null = null
410
+ private get kept(): ResultHistory {
411
+ this.keptCache ??= new ResultHistory(this.settings.memoryBudgetMb * MB)
412
+ return this.keptCache
413
+ }
353
414
 
354
415
  constructor(
355
416
  public modules: ServeModule[],
@@ -430,6 +491,10 @@ export class ServeApp {
430
491
  return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)
431
492
  if (segs[0] === 'audio' && segs.length === 3 && segs[1] != null && segs[2] != null)
432
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]}`)
496
+ if (segs[0] === 'results' && segs.length === 1)
497
+ return json(200, { runs: this.kept.list(), memory: this.kept.usage() })
433
498
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
434
499
  return json(404, { error: `no route: GET ${path}`, usage: USAGE })
435
500
  }
@@ -446,6 +511,11 @@ export class ServeApp {
446
511
  if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
447
512
  return await this.replyDeleteDraft(segs[1], segs[2])
448
513
  if (req.method === 'PUT' && segs[0] === 'settings' && segs.length === 1) return this.replySaveSettings(req)
514
+ if (req.method === 'DELETE' && segs[0] === 'results' && segs.length <= 2) {
515
+ if (segs[1] == null) this.kept.clear()
516
+ else this.kept.remove(segs[1])
517
+ return json(200, { memory: this.kept.usage() })
518
+ }
449
519
  if (req.method === 'PUT' && segs[0] === 'tabs' && segs.length === 1) return this.replySaveTabs(req)
450
520
  if (req.method === 'PUT' && segs[0] === 'hosts' && segs.length === 2 && segs[1] != null)
451
521
  return this.replySetHost(segs[1], req)
@@ -736,7 +806,7 @@ export class ServeApp {
736
806
  return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }
737
807
  }
738
808
 
739
- /** 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) */
740
810
  private replyUpload(req: ServeRequest): ServeReply {
741
811
  let parsed: unknown
742
812
  try {
@@ -1110,25 +1180,16 @@ export class ServeApp {
1110
1180
  }
1111
1181
 
1112
1182
  // #region settings + in-memory outputs --------------------------------------
1113
- /** the last N in-memory outputs stay reachable; older ones are dropped, because with
1114
- * saving off these buffers are the only copy and nothing else will free them */
1115
- private readonly MEMORY_IMAGE_CAP = 60
1116
-
1117
- private rememberMemoryImage(key: string, bytes: Uint8Array, filename: string): void {
1183
+ private memoryBlob(key: string, bytes: Uint8Array, filename: string): KeptBlob {
1118
1184
  const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)
1119
- this.memoryImages.set(key, { bytes, contentType })
1120
- while (this.memoryImages.size > this.MEMORY_IMAGE_CAP) {
1121
- const oldest = this.memoryImages.keys().next()
1122
- if (oldest.done === true) break
1123
- this.memoryImages.delete(oldest.value)
1124
- }
1185
+ return { key, bytes, contentType }
1125
1186
  }
1126
1187
 
1127
1188
  private replyMemoryImage(key: string): ServeReply {
1128
- const hit = this.memoryImages.get(key)
1189
+ const hit = this.kept.blob(key)
1129
1190
  if (hit == null)
1130
1191
  return json(404, {
1131
- error: `no in-memory output '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.`,
1192
+ error: `no in-memory output '${key}' — it was deleted, dropped past the ${this.settings.memoryBudgetMb} MB memory budget, or the server restarted. Turn saving on to keep outputs.`,
1132
1193
  })
1133
1194
  return { status: 200, contentType: hit.contentType, body: hit.bytes }
1134
1195
  }
@@ -1149,9 +1210,9 @@ export class ServeApp {
1149
1210
  }
1150
1211
  if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
1151
1212
  return json(400, {
1152
- error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" } }',
1213
+ error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" }, "memoryBudgetMb"?: number }',
1153
1214
  })
1154
- const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown }
1215
+ const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown; memoryBudgetMb?: unknown }
1155
1216
  let next = this.settings
1156
1217
  if (wanted.saveToDisk != null) {
1157
1218
  if (typeof wanted.saveToDisk !== 'boolean') return json(400, { error: '"saveToDisk" must be true or false' })
@@ -1175,8 +1236,14 @@ export class ServeApp {
1175
1236
  }
1176
1237
  next = { ...next, savePrefix: prefixes }
1177
1238
  }
1239
+ if (wanted.memoryBudgetMb != null) {
1240
+ const mb = validMemoryBudgetMb(wanted.memoryBudgetMb)
1241
+ if (mb == null) return json(400, { error: '"memoryBudgetMb" must be a number of MB, 1 to 100000' })
1242
+ next = { ...next, memoryBudgetMb: mb }
1243
+ }
1178
1244
  const saveToDisk = next.saveToDisk
1179
1245
  this.settings = next
1246
+ this.kept.setBudget(next.memoryBudgetMb * MB)
1180
1247
  try {
1181
1248
  writeServeSettings(this.settings)
1182
1249
  } catch (e) {
@@ -1566,41 +1633,87 @@ export class ServeApp {
1566
1633
  const durationMs = Date.now() - t0
1567
1634
 
1568
1635
  if (execution.status === 'Failure') {
1569
- console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)
1570
- return json(500, {
1571
- ok: false,
1572
- module: mod.key,
1573
- draft,
1574
- promptId: execution.data.id,
1575
- durationMs,
1576
- error: execution.data.error ?? 'execution failed',
1577
- })
1636
+ const error = describeRunError(execution.data.error)
1637
+ console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms: ${error}`)
1638
+ return json(500, { ok: false, module: mod.key, draft, promptId: execution.data.id, durationMs, error })
1578
1639
  }
1579
1640
 
1580
1641
  const produced = [`${execution.images.length} image(s)`]
1581
1642
  const audios = execution.audios ?? []
1582
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)`)
1583
1646
  if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)
1584
1647
  console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)
1585
1648
 
1586
1649
  // saving off → the buffer is the only copy: keep it addressable so the gallery (and
1587
1650
  // curl) still get an image instead of a null url
1588
- const memoryKeys = new Map<number, string>()
1589
- for (const [ix, img] of execution.images.entries()) {
1590
- if (img.absPath != null || img.buffer == null) continue
1651
+ const blobs: KeptBlob[] = []
1652
+ const imageKeys = execution.images.map((img, ix) => {
1653
+ if (img.absPath != null || img.buffer == null) return null
1591
1654
  const key = `${execution.data.id}/${ix}`
1592
- this.rememberMemoryImage(key, img.buffer, img.filename)
1593
- memoryKeys.set(ix, key)
1594
- }
1595
-
1655
+ blobs.push(this.memoryBlob(key, img.buffer, img.filename))
1656
+ return key
1657
+ })
1596
1658
  // same store as the images, own key space: the audio route adds the `audio/` prefix
1597
- const audioKeys = new Map<number, string>()
1598
- for (const [ix, a] of audios.entries()) {
1599
- if (a.absPath != null) continue
1600
- const key = `${execution.data.id}/${ix}`
1601
- this.rememberMemoryImage(`audio/${key}`, a.bytes, a.filename)
1602
- audioKeys.set(ix, key)
1659
+ const audioKeys = audios.map((a, ix) => {
1660
+ if (a.absPath != null) return null
1661
+ const key = `audio/${execution.data.id}/${ix}`
1662
+ blobs.push(this.memoryBlob(key, a.bytes, a.filename))
1663
+ return key
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
+ })
1671
+ // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and handle() decodes
1672
+ // per segment, so the lookup gets the raw key back
1673
+ const memoryUrl = (route: string, key: string): string =>
1674
+ `/${route}/${key
1675
+ .split('/')
1676
+ .slice(route === 'images' ? 0 : 1)
1677
+ .map((seg) => encodeURIComponent(seg))
1678
+ .join('/')}`
1679
+ const record: RunRecord = {
1680
+ ok: true,
1681
+ module: mod.key,
1682
+ draft,
1683
+ promptId: execution.data.id,
1684
+ durationMs,
1685
+ finishedAt: Date.now(),
1686
+ seeds,
1687
+ savedToDisk: this.settings.saveToDisk,
1688
+ texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
1689
+ images: execution.images.map((img, ix) => {
1690
+ const key = imageKeys[ix]
1691
+ return {
1692
+ filename: img.filename,
1693
+ url: img.absPath != null ? this.outputUrl(img.absPath) : key != null ? memoryUrl('images', key) : null,
1694
+ absPath: img.absPath,
1695
+ }
1696
+ }),
1697
+ audios: audios.map((a, ix) => {
1698
+ const key = audioKeys[ix]
1699
+ return {
1700
+ filename: a.filename,
1701
+ mime: a.mime,
1702
+ url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl('audio', key) : null,
1703
+ absPath: a.absPath,
1704
+ }
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
+ }),
1603
1715
  }
1716
+ this.kept.add({ record, imageKeys, audioKeys, videoKeys, blobs })
1604
1717
 
1605
1718
  // Accept: image/* → first image's bytes directly (curl -o, <img src>)
1606
1719
  const first = execution.images[0]
@@ -1609,49 +1722,11 @@ export class ServeApp {
1609
1722
  const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
1610
1723
  return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
1611
1724
  }
1612
- const inMemory = this.memoryImages.get(memoryKeys.get(0) ?? '')
1725
+ const inMemory = this.kept.blob(imageKeys[0] ?? '')
1613
1726
  if (inMemory != null) return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes }
1614
1727
  }
1615
1728
 
1616
- return json(200, {
1617
- ok: true,
1618
- module: mod.key,
1619
- draft,
1620
- promptId: execution.data.id,
1621
- durationMs,
1622
- seeds,
1623
- savedToDisk: this.settings.saveToDisk,
1624
- texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
1625
- images: execution.images.map((img, ix) => ({
1626
- filename: img.filename,
1627
- url:
1628
- img.absPath != null
1629
- ? this.outputUrl(img.absPath)
1630
- : memoryKeys.has(ix)
1631
- ? // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and
1632
- // handle() decodes per segment, so the lookup gets the raw key back
1633
- `/images/${(memoryKeys.get(ix) ?? '')
1634
- .split('/')
1635
- .map((seg) => encodeURIComponent(seg))
1636
- .join('/')}`
1637
- : null,
1638
- absPath: img.absPath,
1639
- })),
1640
- audios: audios.map((a, ix) => ({
1641
- filename: a.filename,
1642
- mime: a.mime,
1643
- url:
1644
- a.absPath != null
1645
- ? this.outputUrl(a.absPath)
1646
- : audioKeys.has(ix)
1647
- ? `/audio/${(audioKeys.get(ix) ?? '')
1648
- .split('/')
1649
- .map((seg) => encodeURIComponent(seg))
1650
- .join('/')}`
1651
- : null,
1652
- absPath: a.absPath,
1653
- })),
1654
- })
1729
+ return json(200, record)
1655
1730
  }
1656
1731
 
1657
1732
  /** everything that touches the module's SHARED vars, under the module mutex */
@@ -1689,7 +1764,7 @@ export class ServeApp {
1689
1764
  let value = rawValue
1690
1765
  // kind, never instanceof: consumer and cli hold different class copies (VarKind
1691
1766
  // owns the WHY); casts are the kind-narrowing family, agent/coding.md whitelist 6
1692
- if (varDef.kind === 'image' && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
1767
+ if (isMediaKind(varDef.kind) && typeof rawValue === 'string' && /^https?:\/\//.test(rawValue)) {
1693
1768
  try {
1694
1769
  value = await this.downloadInput(rawValue)
1695
1770
  } catch (e) {
@@ -1715,18 +1790,19 @@ export class ServeApp {
1715
1790
  if (err != null) return { status: 400, error: err }
1716
1791
  }
1717
1792
 
1718
- // 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.
1719
1794
  // the path a request hands us is read off this box and uploaded to the ComfyUI host, so
1720
1795
  // the extension list the descriptor advertises is enforced here, not merely advertised:
1721
1796
  // a var that accepts .png must not be talked into reading a key or a config file
1722
1797
  for (const [k, varDef] of varMap) {
1723
- if (varDef.kind !== 'image') continue
1724
- const img = varDef as ImageVar
1725
- if (!img.isSet()) continue
1726
- 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()
1727
1803
  // ONE message for every rejection below: distinct ones told an unauthenticated caller
1728
1804
  // whether any path exists, is a file, and what type it is
1729
- 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` }
1730
1806
  if (!existsSync(abs)) return refuse
1731
1807
  // the REAL path: statSync follows symlinks, so `pic.png -> id_rsa` passed a check made
1732
1808
  // on the link's name. Resolving first means the gate judges the file being read
@@ -1741,8 +1817,9 @@ export class ServeApp {
1741
1817
  } catch {
1742
1818
  return refuse
1743
1819
  }
1744
- if (!serveAcceptsImageExt(img.extensions, extname(real).toLowerCase().replace(/^\./, ''))) return refuse
1745
- 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
1746
1823
  }
1747
1824
 
1748
1825
  // 4. seed policy (architecture item 12): payload wins; '?' rerolls;
@@ -1787,7 +1864,9 @@ export class ServeApp {
1787
1864
  }
1788
1865
  } catch (e) {
1789
1866
  // name, not instanceof: same two-copies problem as the var classes
1790
- 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 }
1791
1870
  // the ComfyUI host is upstream of this bridge: 502, not "serve crashed".
1792
1871
  // The connect deadline (ConnectOptions.timeoutMs) is what makes this
1793
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: {