comfy-ts 2.12.0 → 2.14.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 (81) hide show
  1. package/dist/{LogsSt-U1H0mP1m.js → LogsSt-CUeo843w.js} +18 -4
  2. package/dist/LogsSt-CUeo843w.js.map +1 -0
  3. package/dist/cli.js +4 -4
  4. package/dist/index.cjs +123 -12
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +96 -16
  7. package/dist/index.d.ts +96 -16
  8. package/dist/index.js +123 -12
  9. package/dist/index.js.map +1 -1
  10. package/dist/{run-serve-BeAznay5.js → run-serve-DUqcn0h3.js} +477 -63
  11. package/dist/run-serve-DUqcn0h3.js.map +1 -0
  12. package/dist/{run-tui-BTGjvnKk.js → run-tui-D-LaSqgB.js} +4 -4
  13. package/dist/{run-tui-BTGjvnKk.js.map → run-tui-D-LaSqgB.js.map} +1 -1
  14. package/dist/{schemaDrift-Cg39vs53.js → schemaDrift-E95iTF7E.js} +4 -1
  15. package/dist/{schemaDrift-Cg39vs53.js.map → schemaDrift-E95iTF7E.js.map} +1 -1
  16. package/dist/serve-web.js +378 -141
  17. package/dist/{state-C7REnHan.js → state-BytbdZ8s.js} +122 -14
  18. package/dist/state-BytbdZ8s.js.map +1 -0
  19. package/dist/web.d.ts +96 -16
  20. package/dist/web.js +123 -12
  21. package/dist/web.js.map +1 -1
  22. package/examples/comfy-cloud/sdk.d.ts +163 -163
  23. package/examples/rvion/10-anima-t2i.cflow.ts +48 -25
  24. package/examples/rvion/11-yue2-t2a.cflow.ts +105 -0
  25. package/examples/rvion/12-stable-audio-3-t2a.cflow.ts +78 -0
  26. package/examples/rvion/13-ace-step-15-xl-t2a.cflow.ts +153 -0
  27. package/examples/rvion/stableAudio3Prompts.ts +19 -0
  28. package/package.json +2 -2
  29. package/src/cli/serve/ServeApp.ts +224 -77
  30. package/src/cli/serve/byteRange.ts +48 -0
  31. package/src/cli/serve/resultHistory.ts +125 -0
  32. package/src/cli/serve/run-serve.ts +12 -3
  33. package/src/cli/serve/runError.ts +23 -0
  34. package/src/cli/serve/serveSettings.ts +17 -1
  35. package/src/cli/serve/web/api.ts +53 -2
  36. package/src/cli/serve/web/components/App.tsx +311 -160
  37. package/src/cli/serve/web/components/DraftTabs.tsx +167 -0
  38. package/src/cli/serve/web/components/Gallery.tsx +75 -25
  39. package/src/cli/serve/web/components/Icon.tsx +44 -0
  40. package/src/cli/serve/web/components/MemoryBudget.tsx +98 -0
  41. package/src/cli/serve/web/components/Omnibox.tsx +70 -20
  42. package/src/cli/serve/web/components/RunError.tsx +19 -0
  43. package/src/cli/serve/web/components/ShortcutsModal.tsx +54 -0
  44. package/src/cli/serve/web/components/SideMenu.tsx +428 -0
  45. package/src/cli/serve/web/components/TooltipLayer.tsx +3 -2
  46. package/src/cli/serve/web/components/VarsForm.tsx +141 -404
  47. package/src/cli/serve/web/components/controls/BasicControls.tsx +8 -1
  48. package/src/cli/serve/web/components/controls/LorasControl.tsx +30 -25
  49. package/src/cli/serve/web/promptEditor/promptExtensions.ts +9 -4
  50. package/src/cli/serve/web/state/EnhancerSt.ts +17 -2
  51. package/src/cli/serve/web/state/FormSt.ts +22 -2
  52. package/src/cli/serve/web/state/OmniboxSt.ts +3 -1
  53. package/src/cli/serve/web/state/RunSt.ts +61 -3
  54. package/src/cli/serve/web/state/WebSt.ts +198 -35
  55. package/src/cli/serve/web/state/draftNames.ts +16 -0
  56. package/src/cli/serve/web/state/draftTabs.ts +75 -0
  57. package/src/cli/serve/web/state/formRows.ts +9 -0
  58. package/src/cli/serve/web/state/generateButton.ts +1 -1
  59. package/src/cli/serve/web/state/keptResults.ts +26 -0
  60. package/src/cli/serve/web/state/lightbox.ts +17 -0
  61. package/src/cli/serve/web/state/omnibox.ts +82 -18
  62. package/src/cli/serve/web/state/shortcutCatalog.ts +100 -0
  63. package/src/cli/serve/web/state/shortcuts.ts +66 -7
  64. package/src/cli/serve/web/styles.ts +327 -93
  65. package/src/cli/serve/workflowTags.ts +42 -0
  66. package/src/cli/serve/workspaceLabels.ts +23 -0
  67. package/src/cli/tui/state/DraftsSt.ts +10 -6
  68. package/src/coreExports.ts +1 -0
  69. package/src/host/ComfyHost.ts +17 -2
  70. package/src/host/ResilientWebsocket.ts +54 -4
  71. package/src/runner/ComfyExecution.ts +60 -0
  72. package/src/runner/ComfyWorkflow.ts +4 -0
  73. package/src/runner/ComfyWsApi.ts +2 -0
  74. package/src/runner/MediaImage.ts +2 -2
  75. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +5 -5
  76. package/src/sdk-generator/comfyui-sdk-codegen.ts +1 -1
  77. package/src/utils/copyName.ts +12 -0
  78. package/src/vars/DefinedWorkflow.ts +7 -1
  79. package/dist/LogsSt-U1H0mP1m.js.map +0 -1
  80. package/dist/run-serve-BeAznay5.js.map +0 -1
  81. package/dist/state-C7REnHan.js.map +0 -1
@@ -24,9 +24,19 @@ import { ENHANCE_KEY, isDraftMetaKey } from 'src/cli/draftMeta.ts'
24
24
  import { managerOnlyLoraOptions } from 'src/cli/serve/managerOnlyLoras.ts'
25
25
  import { resolveTagSource, TagSources } from 'src/cli/serve/tagSource.ts'
26
26
  import { FAVICON_DATA_URI } from 'src/cli/serve/favicon.ts'
27
+ import { type TagNode, workflowTags } from 'src/cli/serve/workflowTags.ts'
28
+ import { workspaceLabels } from 'src/cli/serve/workspaceLabels.ts'
27
29
  import { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'
28
30
  import { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'
29
- 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'
39
+ import { readTabs, SERVE_TABS_FILE, type DraftTab } from 'src/cli/serve/web/state/draftTabs.ts'
30
40
  import { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'
31
41
  import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
32
42
  import {
@@ -82,6 +92,8 @@ export type ServeExecution = {
82
92
  /** STRING outputs (PreviewAny, i.e. every llm graph). A text-only workflow has no images at
83
93
  * all, so without these its run reply is empty and the panel shows nothing */
84
94
  texts?: { nodeId: string; nodeKey: string | null; text: string }[]
95
+ /** audio files (SaveAudio*, PreviewAudio). absPath null = saving off, bytes the only copy */
96
+ audios?: { absPath: string | null; filename: string; mime: string; bytes: Uint8Array }[]
85
97
  data: { id: string; error?: unknown }
86
98
  /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
87
99
  progressGlobal?: { percent: number }
@@ -168,6 +180,7 @@ const INPUT_DOWNLOAD_TIMEOUT_MS = 60_000
168
180
  /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
169
181
  const TAG_LIST_CAP = 40_000_000
170
182
  const TAG_LIST_TIMEOUT_MS = 120_000
183
+ const MB = 1024 * 1024
171
184
 
172
185
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
173
186
  * whole body first, so a chunked reply with no content-length could exhaust the process before
@@ -228,6 +241,12 @@ const CONTENT_TYPES: Record<string, string> = {
228
241
  '.gif': 'image/gif',
229
242
  '.mp4': 'video/mp4',
230
243
  '.webm': 'video/webm',
244
+ '.flac': 'audio/flac',
245
+ '.mp3': 'audio/mpeg',
246
+ '.opus': 'audio/ogg',
247
+ '.ogg': 'audio/ogg',
248
+ '.wav': 'audio/wav',
249
+ '.m4a': 'audio/mp4',
231
250
  '.json': 'application/json',
232
251
  '.txt': 'text/plain',
233
252
  }
@@ -280,12 +299,14 @@ const USAGE = [
280
299
  'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
281
300
  'GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)',
282
301
  'PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>',
283
- 'GET /settings — { saveToDisk } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory',
302
+ 'GET /settings — { saveToDisk, memoryBudgetMb } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory; {"memoryBudgetMb"} caps what memory keeps',
284
303
  'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
285
304
  'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',
286
305
  'GET /hosts/<hostId>/ping — is that host answering right now (restart watch)',
287
306
  'GET /hosts/<hostId>/logs — the last lines of that host console',
288
307
  'GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives',
308
+ 'GET /audio/<promptId>/<ix> — the same for an in-memory audio output',
309
+ 'GET /results — the last runs this process kept, for a reload · DELETE /results[/<promptId>] — forget them, freeing their memory',
289
310
  'GET /outputs/<path> — generated files',
290
311
  ]
291
312
 
@@ -318,10 +339,10 @@ const WEB_SHELL = `<!doctype html>
318
339
  export class ServeApp {
319
340
  private starter: ServeStarter
320
341
  /** last SERVED seed per `module/draft/var` — '+'/'-' modes continue from it.
321
- * draftBase remembers which DRAFT value the continuation grew from: when the
322
- * draft's seed changes (the web form autosaves a typed value), the typed
323
- * value wins and the continuation restarts there */
324
- private seedState = new Map<string, { last: number; draftBase: number }>()
342
+ * draftBase remembers which DRAFT value the continuation grew from, served every seed
343
+ * the chain handed out: a draft holding one of them is the panel's write-back (it lags a
344
+ * queued run), anything else is a typed value, which wins and restarts the chain there */
345
+ private seedState = new Map<string, { last: number; draftBase: number; served: number[] }>()
325
346
  /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
326
347
  private chains = new Map<string, Promise<unknown>>()
327
348
  /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can
@@ -335,9 +356,13 @@ export class ServeApp {
335
356
  private set settings(next: ServeSettings) {
336
357
  this.settingsCache = next
337
358
  }
338
- /** in-memory outputs of runs made with saving OFF: the ONLY copy, so the gallery has
339
- * something to show. Capped and FIFO, a long session must not grow without bound */
340
- private memoryImages = new Map<string, { bytes: Uint8Array; contentType: string }>()
359
+ /** the last runs, for a reload, and the bytes of their unsaved outputs: the ONLY copy.
360
+ * LAZY for the same reason as settings: its budget is a setting */
361
+ private keptCache: ResultHistory | null = null
362
+ private get kept(): ResultHistory {
363
+ this.keptCache ??= new ResultHistory(this.settings.memoryBudgetMb * MB)
364
+ return this.keptCache
365
+ }
341
366
 
342
367
  constructor(
343
368
  public modules: ServeModule[],
@@ -345,6 +370,10 @@ export class ServeApp {
345
370
  starter?: ServeStarter
346
371
  outputRoot?: string
347
372
  loadErrors?: Record<string, string>
373
+ /** where `.comfy-ts/` lives and the folder serve scanned: the menu's read-only cards.
374
+ * absent = the index leaves both out */
375
+ workspace?: string
376
+ root?: string
348
377
  /** web ui bundle provider (run-serve wires loadOrBuildWebJs), called on every page load
349
378
  * and owning its own cache; absent = api only */
350
379
  webJs?: () => Promise<string | null>
@@ -384,7 +413,7 @@ export class ServeApp {
384
413
  headers: NO_STORE,
385
414
  }
386
415
  }
387
- if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
416
+ if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return await this.replyIndex()
388
417
  if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()
389
418
  if (segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
390
419
  return this.replyDraft(segs[1], segs[2])
@@ -402,6 +431,7 @@ export class ServeApp {
402
431
  if (segs[0] === 'tags' && segs.length === 3 && segs[1] != null && segs[2] != null)
403
432
  return await this.replyTags(segs[1], segs[2], req.url)
404
433
  if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()
434
+ if (segs[0] === 'tabs' && segs.length === 1) return this.replyTabs()
405
435
  if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()
406
436
  if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')
407
437
  return await this.replyHostLogs(segs[1])
@@ -411,6 +441,10 @@ export class ServeApp {
411
441
  return await this.replyHostDrift(segs[1], req.url.includes('full=1'))
412
442
  if (segs[0] === 'images' && segs.length === 3 && segs[1] != null && segs[2] != null)
413
443
  return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)
444
+ if (segs[0] === 'audio' && segs.length === 3 && segs[1] != null && segs[2] != null)
445
+ return this.replyMemoryImage(`audio/${segs[1]}/${segs[2]}`)
446
+ if (segs[0] === 'results' && segs.length === 1)
447
+ return json(200, { runs: this.kept.list(), memory: this.kept.usage() })
414
448
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
415
449
  return json(404, { error: `no route: GET ${path}`, usage: USAGE })
416
450
  }
@@ -427,6 +461,12 @@ export class ServeApp {
427
461
  if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
428
462
  return await this.replyDeleteDraft(segs[1], segs[2])
429
463
  if (req.method === 'PUT' && segs[0] === 'settings' && segs.length === 1) return this.replySaveSettings(req)
464
+ if (req.method === 'DELETE' && segs[0] === 'results' && segs.length <= 2) {
465
+ if (segs[1] == null) this.kept.clear()
466
+ else this.kept.remove(segs[1])
467
+ return json(200, { memory: this.kept.usage() })
468
+ }
469
+ if (req.method === 'PUT' && segs[0] === 'tabs' && segs.length === 1) return this.replySaveTabs(req)
430
470
  if (req.method === 'PUT' && segs[0] === 'hosts' && segs.length === 2 && segs[1] != null)
431
471
  return this.replySetHost(segs[1], req)
432
472
  if (req.method === 'POST' && segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] != null)
@@ -598,14 +638,52 @@ export class ServeApp {
598
638
  vars,
599
639
  // the names of the workflow's live previews: the panel asks POST /preview/<module>
600
640
  previews: Object.keys(mod.dw.spec.previews ?? {}),
641
+ tags: this.tagsByModule.get(mod.key) ?? mod.dw.spec.tags ?? [],
642
+ }
643
+ }
644
+
645
+ /** per module, read once from a dry build: the omnibox searches and shows them */
646
+ private tagsByModule = new Map<string, string[]>()
647
+
648
+ private async tagsFor(mod: ServeModule): Promise<string[]> {
649
+ const known = this.tagsByModule.get(mod.key)
650
+ if (known != null) return known
651
+ const extra = mod.dw.spec.tags ?? []
652
+ const varKinds = mod.dw.entries().map(([, varDef]) => varDef.kind)
653
+ let tags: string[]
654
+ try {
655
+ const wf = await mod.dw.build({ dry: true })
656
+ const nodes: TagNode[] = wf.nodes.map((n) => ({
657
+ id: n.uid,
658
+ classType: n.json.class_type,
659
+ outputNode: n.$schema.raw.output_node,
660
+ outputTypes: n.$schema.outputs.map((o) => o.typeName),
661
+ links: Object.values(n.json.inputs).flatMap((v): [string, number][] =>
662
+ Array.isArray(v) && v.length === 2 && typeof v[1] === 'number' ? [[String(v[0]), v[1]]] : [],
663
+ ),
664
+ }))
665
+ tags = workflowTags({ nodes, varKinds, extra })
666
+ } catch (e) {
667
+ console.error(`[serve] 🔴 tags for ${mod.key}: dry build failed, spec tags only: ${extractErrorMessage(e)}`)
668
+ tags = workflowTags({ nodes: [], varKinds, extra })
601
669
  }
670
+ this.tagsByModule.set(mod.key, tags)
671
+ return tags
602
672
  }
603
673
 
604
- private replyIndex(): ServeReply {
674
+ private async replyIndex(): Promise<ServeReply> {
675
+ for (const m of this.modules) await this.tagsFor(m)
605
676
  return json(200, {
606
677
  server: 'comfy-ts serve',
607
678
  usage: USAGE,
608
679
  workflows: this.modules.map((m) => this.describeModule(m)),
680
+ ...(this.opts.workspace == null
681
+ ? {}
682
+ : workspaceLabels({
683
+ workspace: this.opts.workspace,
684
+ root: this.opts.root ?? this.opts.workspace,
685
+ home: process.env.HOME ?? '',
686
+ })),
609
687
  ...(this.opts.loadErrors != null && Object.keys(this.opts.loadErrors).length > 0
610
688
  ? { loadErrors: this.opts.loadErrors }
611
689
  : {}),
@@ -1052,25 +1130,16 @@ export class ServeApp {
1052
1130
  }
1053
1131
 
1054
1132
  // #region settings + in-memory outputs --------------------------------------
1055
- /** the last N in-memory outputs stay reachable; older ones are dropped, because with
1056
- * saving off these buffers are the only copy and nothing else will free them */
1057
- private readonly MEMORY_IMAGE_CAP = 60
1058
-
1059
- private rememberMemoryImage(key: string, bytes: Uint8Array, filename: string): void {
1133
+ private memoryBlob(key: string, bytes: Uint8Array, filename: string): KeptBlob {
1060
1134
  const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)
1061
- this.memoryImages.set(key, { bytes, contentType })
1062
- while (this.memoryImages.size > this.MEMORY_IMAGE_CAP) {
1063
- const oldest = this.memoryImages.keys().next()
1064
- if (oldest.done === true) break
1065
- this.memoryImages.delete(oldest.value)
1066
- }
1135
+ return { key, bytes, contentType }
1067
1136
  }
1068
1137
 
1069
1138
  private replyMemoryImage(key: string): ServeReply {
1070
- const hit = this.memoryImages.get(key)
1139
+ const hit = this.kept.blob(key)
1071
1140
  if (hit == null)
1072
1141
  return json(404, {
1073
- error: `no in-memory image '${key}' — it expired (only the last ${this.MEMORY_IMAGE_CAP} are kept) or the server restarted. Turn saving on to keep outputs.`,
1142
+ 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.`,
1074
1143
  })
1075
1144
  return { status: 200, contentType: hit.contentType, body: hit.bytes }
1076
1145
  }
@@ -1091,9 +1160,9 @@ export class ServeApp {
1091
1160
  }
1092
1161
  if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
1093
1162
  return json(400, {
1094
- error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" } }',
1163
+ error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" }, "memoryBudgetMb"?: number }',
1095
1164
  })
1096
- const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown }
1165
+ const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown; memoryBudgetMb?: unknown }
1097
1166
  let next = this.settings
1098
1167
  if (wanted.saveToDisk != null) {
1099
1168
  if (typeof wanted.saveToDisk !== 'boolean') return json(400, { error: '"saveToDisk" must be true or false' })
@@ -1117,8 +1186,14 @@ export class ServeApp {
1117
1186
  }
1118
1187
  next = { ...next, savePrefix: prefixes }
1119
1188
  }
1189
+ if (wanted.memoryBudgetMb != null) {
1190
+ const mb = validMemoryBudgetMb(wanted.memoryBudgetMb)
1191
+ if (mb == null) return json(400, { error: '"memoryBudgetMb" must be a number of MB, 1 to 100000' })
1192
+ next = { ...next, memoryBudgetMb: mb }
1193
+ }
1120
1194
  const saveToDisk = next.saveToDisk
1121
1195
  this.settings = next
1196
+ this.kept.setBudget(next.memoryBudgetMb * MB)
1122
1197
  try {
1123
1198
  writeServeSettings(this.settings)
1124
1199
  } catch (e) {
@@ -1138,6 +1213,60 @@ export class ServeApp {
1138
1213
  })
1139
1214
  }
1140
1215
 
1216
+ // #region open draft tabs (the web ui's tab bar) ------------------------------
1217
+ /** held by the process, so every window and reload sees the same tabs, and mirrored to a file
1218
+ * under .comfy-ts/ (gitignored wholesale) so a restart keeps them. null = not read yet */
1219
+ private tabs: DraftTab[] | null = null
1220
+
1221
+ private tabsFile(): string {
1222
+ return join(comfyts.baseFolder, SERVE_TABS_FILE)
1223
+ }
1224
+
1225
+ /** only drafts that still exist: a tab whose file was deleted elsewhere is dropped on read */
1226
+ private liveTabs(raw: unknown): DraftTab[] {
1227
+ return readTabs(
1228
+ raw,
1229
+ this.modules.map((m) => ({ module: m.key, drafts: this.draftsFor(m) })),
1230
+ )
1231
+ }
1232
+
1233
+ private replyTabs(): ServeReply {
1234
+ if (this.tabs == null) {
1235
+ const path = this.tabsFile()
1236
+ let raw: unknown = []
1237
+ try {
1238
+ if (existsSync(path)) raw = JSON.parse(readFileSync(path, 'utf8'))
1239
+ } catch (e) {
1240
+ console.error(`[serve] 🔴 open tabs unreadable (${path}), starting with none:`, e)
1241
+ }
1242
+ this.tabs = this.liveTabs(raw)
1243
+ }
1244
+ this.tabs = this.liveTabs(this.tabs)
1245
+ return json(200, { tabs: this.tabs })
1246
+ }
1247
+
1248
+ private replySaveTabs(req: ServeRequest): ServeReply {
1249
+ let parsed: unknown
1250
+ try {
1251
+ parsed = JSON.parse(req.body ?? '')
1252
+ } catch (e) {
1253
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
1254
+ }
1255
+ const raw = parsed != null && typeof parsed === 'object' ? (parsed as { tabs?: unknown }).tabs : undefined
1256
+ if (!Array.isArray(raw) || raw.length > 100)
1257
+ return json(400, { error: 'expects { "tabs": [{ "module", "draft" }, …] }' })
1258
+ this.tabs = this.liveTabs(raw)
1259
+ try {
1260
+ mkdirSync(comfyts.baseFolder, { recursive: true })
1261
+ writeFileSync(this.tabsFile(), JSON.stringify(this.tabs, null, 2))
1262
+ } catch (e) {
1263
+ // kept for this process either way: only the restart loses them, and the reply says so
1264
+ console.error(`[serve] 🔴 open tabs not saved to ${this.tabsFile()}:`, e)
1265
+ return json(200, { tabs: this.tabs, warning: `not saved: ${extractErrorMessage(e)}` })
1266
+ }
1267
+ return json(200, { tabs: this.tabs })
1268
+ }
1269
+
1141
1270
  // #region prompt enhancers (the web ui's master prompts, as .md files) ------
1142
1271
  /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
1143
1272
  /** tag lists by source, loaded on the first query and kept for the process */
@@ -1454,30 +1583,70 @@ export class ServeApp {
1454
1583
  const durationMs = Date.now() - t0
1455
1584
 
1456
1585
  if (execution.status === 'Failure') {
1457
- console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms`)
1458
- return json(500, {
1459
- ok: false,
1460
- module: mod.key,
1461
- draft,
1462
- promptId: execution.data.id,
1463
- durationMs,
1464
- error: execution.data.error ?? 'execution failed',
1465
- })
1586
+ const error = describeRunError(execution.data.error)
1587
+ console.error(`[serve] 🔴 ${mod.key}/${draft} failed after ${durationMs}ms: ${error}`)
1588
+ return json(500, { ok: false, module: mod.key, draft, promptId: execution.data.id, durationMs, error })
1466
1589
  }
1467
1590
 
1468
1591
  const produced = [`${execution.images.length} image(s)`]
1592
+ const audios = execution.audios ?? []
1593
+ if (audios.length > 0) produced.push(`${audios.length} audio(s)`)
1469
1594
  if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)
1470
1595
  console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)
1471
1596
 
1472
1597
  // saving off → the buffer is the only copy: keep it addressable so the gallery (and
1473
1598
  // curl) still get an image instead of a null url
1474
- const memoryKeys = new Map<number, string>()
1475
- for (const [ix, img] of execution.images.entries()) {
1476
- if (img.absPath != null || img.buffer == null) continue
1599
+ const blobs: KeptBlob[] = []
1600
+ const imageKeys = execution.images.map((img, ix) => {
1601
+ if (img.absPath != null || img.buffer == null) return null
1477
1602
  const key = `${execution.data.id}/${ix}`
1478
- this.rememberMemoryImage(key, img.buffer, img.filename)
1479
- memoryKeys.set(ix, key)
1603
+ blobs.push(this.memoryBlob(key, img.buffer, img.filename))
1604
+ return key
1605
+ })
1606
+ // same store as the images, own key space: the audio route adds the `audio/` prefix
1607
+ const audioKeys = audios.map((a, ix) => {
1608
+ if (a.absPath != null) return null
1609
+ const key = `audio/${execution.data.id}/${ix}`
1610
+ blobs.push(this.memoryBlob(key, a.bytes, a.filename))
1611
+ return key
1612
+ })
1613
+ // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and handle() decodes
1614
+ // per segment, so the lookup gets the raw key back
1615
+ const memoryUrl = (route: string, key: string): string =>
1616
+ `/${route}/${key
1617
+ .split('/')
1618
+ .slice(route === 'audio' ? 1 : 0)
1619
+ .map((seg) => encodeURIComponent(seg))
1620
+ .join('/')}`
1621
+ const record: RunRecord = {
1622
+ ok: true,
1623
+ module: mod.key,
1624
+ draft,
1625
+ promptId: execution.data.id,
1626
+ durationMs,
1627
+ finishedAt: Date.now(),
1628
+ seeds,
1629
+ savedToDisk: this.settings.saveToDisk,
1630
+ texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
1631
+ images: execution.images.map((img, ix) => {
1632
+ const key = imageKeys[ix]
1633
+ return {
1634
+ filename: img.filename,
1635
+ url: img.absPath != null ? this.outputUrl(img.absPath) : key != null ? memoryUrl('images', key) : null,
1636
+ absPath: img.absPath,
1637
+ }
1638
+ }),
1639
+ audios: audios.map((a, ix) => {
1640
+ const key = audioKeys[ix]
1641
+ return {
1642
+ filename: a.filename,
1643
+ mime: a.mime,
1644
+ url: a.absPath != null ? this.outputUrl(a.absPath) : key != null ? memoryUrl('audio', key) : null,
1645
+ absPath: a.absPath,
1646
+ }
1647
+ }),
1480
1648
  }
1649
+ this.kept.add({ record, imageKeys, audioKeys, blobs })
1481
1650
 
1482
1651
  // Accept: image/* → first image's bytes directly (curl -o, <img src>)
1483
1652
  const first = execution.images[0]
@@ -1486,35 +1655,11 @@ export class ServeApp {
1486
1655
  const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
1487
1656
  return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
1488
1657
  }
1489
- const inMemory = this.memoryImages.get(memoryKeys.get(0) ?? '')
1658
+ const inMemory = this.kept.blob(imageKeys[0] ?? '')
1490
1659
  if (inMemory != null) return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes }
1491
1660
  }
1492
1661
 
1493
- return json(200, {
1494
- ok: true,
1495
- module: mod.key,
1496
- draft,
1497
- promptId: execution.data.id,
1498
- durationMs,
1499
- seeds,
1500
- savedToDisk: this.settings.saveToDisk,
1501
- texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
1502
- images: execution.images.map((img, ix) => ({
1503
- filename: img.filename,
1504
- url:
1505
- img.absPath != null
1506
- ? this.outputUrl(img.absPath)
1507
- : memoryKeys.has(ix)
1508
- ? // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and
1509
- // handle() decodes per segment, so the lookup gets the raw key back
1510
- `/images/${(memoryKeys.get(ix) ?? '')
1511
- .split('/')
1512
- .map((seg) => encodeURIComponent(seg))
1513
- .join('/')}`
1514
- : null,
1515
- absPath: img.absPath,
1516
- })),
1517
- })
1662
+ return json(200, record)
1518
1663
  }
1519
1664
 
1520
1665
  /** everything that touches the module's SHARED vars, under the module mutex */
@@ -1615,17 +1760,19 @@ export class ServeApp {
1615
1760
  const seedVar = varDef as SeedVar
1616
1761
  const stateKey = `${mod.key}/${draft}/${k}`
1617
1762
  const draftValue = draftSeedValues.get(k) ?? seedVar.value
1618
- if (!(k in payload)) {
1619
- if (seedVar.mode === '?') seedVar.randomize()
1620
- else if (seedVar.mode === '+' || seedVar.mode === '-') {
1621
- const prev = this.seedState.get(stateKey)
1622
- // the draft holding the value we last SERVED is our own write-back, not the
1623
- // human edit draftBase watches for
1624
- const ours = prev != null && (prev.draftBase === draftValue || prev.last === draftValue)
1625
- if (prev != null && ours) seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
1626
- }
1627
- }
1628
- this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue })
1763
+ const prev = this.seedState.get(stateKey)
1764
+ const continues =
1765
+ !(k in payload) &&
1766
+ (seedVar.mode === '+' || seedVar.mode === '-') &&
1767
+ prev != null &&
1768
+ (prev.draftBase === draftValue || prev.served.includes(draftValue))
1769
+ if (!(k in payload) && seedVar.mode === '?') seedVar.randomize()
1770
+ if (continues) {
1771
+ seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
1772
+ // bounded: a write-back never lags by more than the queue
1773
+ const served = [...prev.served, seedVar.value].slice(-256)
1774
+ this.seedState.set(stateKey, { last: seedVar.value, draftBase: prev.draftBase, served })
1775
+ } else this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue, served: [seedVar.value] })
1629
1776
  seeds[k] = seedVar.value
1630
1777
  }
1631
1778
 
@@ -0,0 +1,48 @@
1
+ // HTTP byte ranges on binary replies. WebKit (Safari, and a WKWebView app window) plays audio and
2
+ // video only from a server that answers `Range` with 206: without it a flac never starts there
3
+ import type { ServeReply } from 'src/cli/serve/ServeApp.ts'
4
+
5
+ /** one range, the only kind media players send: `bytes=a-b`, `bytes=a-`, `bytes=-n` */
6
+ function parseRange(header: string, size: number): { start: number; end: number } | 'unsatisfiable' | null {
7
+ const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim())
8
+ if (m == null) return null
9
+ const a = m[1] ?? ''
10
+ const b = m[2] ?? ''
11
+ if (a === '' && b === '') return null
12
+ if (a === '') {
13
+ const n = Number(b)
14
+ if (n === 0) return 'unsatisfiable'
15
+ return { start: Math.max(0, size - n), end: size - 1 }
16
+ }
17
+ const start = Number(a)
18
+ const end = b === '' ? size - 1 : Math.min(Number(b), size - 1)
19
+ if (start >= size || start > end) return 'unsatisfiable'
20
+ return { start, end }
21
+ }
22
+
23
+ /** a whole 200 binary reply gets its length and `accept-ranges`; a range request gets 206 with
24
+ * those bytes, or 416 past the end. Text replies and errors pass through untouched */
25
+ export function withByteRange(reply: ServeReply, req: { method: string; range?: string }): ServeReply {
26
+ if (req.method !== 'GET' || reply.status !== 200 || typeof reply.body === 'string') return reply
27
+ const size = reply.body.length
28
+ const base = { ...reply.headers, 'accept-ranges': 'bytes' }
29
+ const range = req.range == null ? null : parseRange(req.range, size)
30
+ if (range == null) return { ...reply, headers: { ...base, 'content-length': String(size) } }
31
+ if (range === 'unsatisfiable')
32
+ return {
33
+ status: 416,
34
+ contentType: reply.contentType,
35
+ body: new Uint8Array(0),
36
+ headers: { ...base, 'content-range': `bytes */${size}` },
37
+ }
38
+ return {
39
+ status: 206,
40
+ contentType: reply.contentType,
41
+ body: reply.body.subarray(range.start, range.end + 1),
42
+ headers: {
43
+ ...base,
44
+ 'content-range': `bytes ${range.start}-${range.end}/${size}`,
45
+ 'content-length': String(range.end - range.start + 1),
46
+ },
47
+ }
48
+ }
@@ -0,0 +1,125 @@
1
+ // the serve process's memory of its last runs: a page reload (or a second window) shows them
2
+ // again. Unsaved outputs keep their bytes here, the ONLY copy, under one byte budget, FIFO.
3
+ // Nothing is written to disk: a server restart forgets it all. PURE, headless-tested
4
+
5
+ export type RunOutput = { filename: string; url: string | null; absPath: string | null }
6
+ export type RunAudioOutput = RunOutput & { mime: string }
7
+
8
+ /** the run reply `POST /generate` answers, and what `GET /results` lists */
9
+ export type RunRecord = {
10
+ ok: true
11
+ module: string
12
+ draft: string
13
+ promptId: string
14
+ durationMs: number
15
+ /** epoch ms: the panel formats it, the server's clock is the one every window shares */
16
+ finishedAt: number
17
+ seeds: Record<string, number>
18
+ savedToDisk: boolean
19
+ texts: { nodeKey: string | null; text: string }[]
20
+ images: RunOutput[]
21
+ audios: RunAudioOutput[]
22
+ }
23
+
24
+ export type MemoryUsage = { usedBytes: number; budgetBytes: number; outputs: number; runs: number }
25
+
26
+ /** the bytes of one unsaved output, under the key its url names */
27
+ export type KeptBlob = { key: string; bytes: Uint8Array; contentType: string }
28
+
29
+ /** how many runs the list keeps, saved or not. The panel shows as many */
30
+ export const KEPT_RUNS = 50
31
+
32
+ export const DEFAULT_MEMORY_BUDGET_MB = 100
33
+
34
+ /** 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)[] }
36
+
37
+ export class ResultHistory {
38
+ /** newest first */
39
+ private runs: Kept[] = []
40
+ /** insertion order IS the eviction order */
41
+ private blobs = new Map<string, { bytes: Uint8Array; contentType: string }>()
42
+ private used = 0
43
+
44
+ constructor(private budgetBytes: number) {}
45
+
46
+ add(p: { record: RunRecord; imageKeys: (string | null)[]; audioKeys: (string | null)[]; blobs: KeptBlob[] }): void {
47
+ this.remove(p.record.promptId)
48
+ for (const b of p.blobs) {
49
+ this.blobs.set(b.key, { bytes: b.bytes, contentType: b.contentType })
50
+ this.used += b.bytes.byteLength
51
+ }
52
+ this.runs = [{ record: p.record, imageKeys: p.imageKeys, audioKeys: p.audioKeys }, ...this.runs]
53
+ for (const dropped of this.runs.slice(KEPT_RUNS)) this.freeRun(dropped)
54
+ this.runs = this.runs.slice(0, KEPT_RUNS)
55
+ this.evict()
56
+ }
57
+
58
+ blob(key: string): { bytes: Uint8Array; contentType: string } | null {
59
+ return this.blobs.get(key) ?? null
60
+ }
61
+
62
+ /** an output whose bytes were evicted lists with url null: the panel says it is gone */
63
+ list(): RunRecord[] {
64
+ return this.runs.map((k) => ({
65
+ ...k.record,
66
+ images: k.record.images.map((img, ix) => this.withLiveUrl(img, k.imageKeys[ix])),
67
+ audios: k.record.audios.map((a, ix) => this.withLiveUrl(a, k.audioKeys[ix])),
68
+ }))
69
+ }
70
+
71
+ remove(promptId: string): void {
72
+ const hit = this.runs.find((k) => k.record.promptId === promptId)
73
+ if (hit == null) return
74
+ this.freeRun(hit)
75
+ this.runs = this.runs.filter((k) => k !== hit)
76
+ }
77
+
78
+ clear(): void {
79
+ this.runs = []
80
+ this.blobs.clear()
81
+ this.used = 0
82
+ }
83
+
84
+ setBudget(bytes: number): void {
85
+ this.budgetBytes = bytes
86
+ this.evict()
87
+ }
88
+
89
+ usage(): MemoryUsage {
90
+ return { usedBytes: this.used, budgetBytes: this.budgetBytes, outputs: this.blobs.size, runs: this.runs.length }
91
+ }
92
+
93
+ private withLiveUrl<T extends RunOutput>(out: T, key: string | null | undefined): T {
94
+ if (key == null || this.blobs.has(key)) return out
95
+ return { ...out, url: null }
96
+ }
97
+
98
+ private freeRun(k: Kept): void {
99
+ for (const key of [...k.imageKeys, ...k.audioKeys]) {
100
+ if (key == null) continue
101
+ const b = this.blobs.get(key)
102
+ if (b == null) continue
103
+ this.used -= b.bytes.byteLength
104
+ this.blobs.delete(key)
105
+ }
106
+ }
107
+
108
+ /** the NEWEST output always stays, even alone over budget: the run that just finished must
109
+ * not reply with a url that already 404s */
110
+ private evict(): void {
111
+ while (this.used > this.budgetBytes && this.blobs.size > 1) {
112
+ const oldest = this.blobs.entries().next()
113
+ if (oldest.done === true) break
114
+ this.used -= oldest.value[1].bytes.byteLength
115
+ this.blobs.delete(oldest.value[0])
116
+ }
117
+ // a run with nothing left to show is noise in the list
118
+ this.runs = this.runs.filter((k) => {
119
+ const live = (keys: (string | null)[]): boolean => keys.some((key) => key == null || this.blobs.has(key))
120
+ 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)
123
+ })
124
+ }
125
+ }