comfy-ts 2.7.0 → 2.9.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 (104) hide show
  1. package/README.md +20 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +7 -5
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +284 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +125 -7
  11. package/dist/index.d.ts +125 -7
  12. package/dist/index.js +282 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-JxlEbb_f.js → run-tui-BLEdTsOX.js} +106 -157
  17. package/dist/run-tui-BLEdTsOX.js.map +1 -0
  18. package/dist/serve-web.js +441 -72
  19. package/dist/{state-CaHeDL-0.js → state-BbgJeCe6.js} +180 -45
  20. package/dist/state-BbgJeCe6.js.map +1 -0
  21. package/dist/web.d.ts +185 -7
  22. package/dist/web.js +235 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +3 -0
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +3 -1
  35. package/src/cli/serve/ServeApp.ts +754 -40
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/hostProtocol.ts +68 -0
  39. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  40. package/src/cli/serve/run-serve.ts +35 -38
  41. package/src/cli/serve/serveSettings.ts +86 -0
  42. package/src/cli/serve/startupPrint.ts +111 -0
  43. package/src/cli/serve/web/api.ts +97 -1
  44. package/src/cli/serve/web/components/App.tsx +61 -22
  45. package/src/cli/serve/web/components/Gallery.tsx +306 -41
  46. package/src/cli/serve/web/components/Icon.tsx +160 -0
  47. package/src/cli/serve/web/components/PromptEnhancer.tsx +12 -9
  48. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  49. package/src/cli/serve/web/components/VarsForm.tsx +440 -91
  50. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  51. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  52. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  53. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  54. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  55. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  56. package/src/cli/serve/web/llm.ts +1 -1
  57. package/src/cli/serve/web/logWeb.ts +6 -0
  58. package/src/cli/serve/web/state/EnhancerSt.ts +8 -15
  59. package/src/cli/serve/web/state/FormSt.ts +74 -18
  60. package/src/cli/serve/web/state/RunSt.ts +22 -1
  61. package/src/cli/serve/web/state/WebSt.ts +814 -22
  62. package/src/cli/serve/web/state/host.ts +206 -0
  63. package/src/cli/serve/web/state/lightbox.ts +44 -0
  64. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  65. package/src/cli/serve/web/state/payload.ts +44 -2
  66. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  67. package/src/cli/serve/web/styles.ts +422 -57
  68. package/src/cli/serve/web/tsconfig.json +4 -0
  69. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  70. package/src/cli/tui/components/StatusBar.tsx +14 -1
  71. package/src/cli/tui/components/TuiApp.tsx +5 -2
  72. package/src/cli/tui/state/HostSt.ts +3 -2
  73. package/src/cli/tui/state/PickerSt.ts +48 -2
  74. package/src/cli/tui/state/TreeSt.ts +1 -1
  75. package/src/cli/tui/state/TuiSt.ts +2 -1
  76. package/src/coreExports.ts +8 -1
  77. package/src/graph/ComfyNode.ts +58 -1
  78. package/src/host/ComfyHost.ts +13 -2
  79. package/src/host/ComfyManager.ts +31 -13
  80. package/src/host/loraInfoCache.ts +35 -1
  81. package/src/host/loraManagerApi.ts +94 -0
  82. package/src/index.ts +2 -0
  83. package/src/promptEnhancers.ts +102 -0
  84. package/src/runner/ComfyExecution.ts +61 -6
  85. package/src/runner/ComfyWorkflow.ts +18 -4
  86. package/src/runner/ComfyWsApi.ts +3 -0
  87. package/src/runner/describePromptRejection.ts +34 -0
  88. package/src/sdk-generator/ComfySchema.ts +17 -4
  89. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  90. package/src/utils/ansi.ts +13 -0
  91. package/src/utils/matchesRegex.ts +13 -0
  92. package/src/utils/safeName.ts +29 -0
  93. package/src/utils/stringMap.ts +9 -0
  94. package/src/vars/ComfyVars.ts +61 -10
  95. package/src/vars/presets.ts +17 -0
  96. package/src/web.ts +12 -0
  97. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  98. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  99. package/dist/run-serve-D1Tsuru9.js +0 -1162
  100. package/dist/run-serve-D1Tsuru9.js.map +0 -1
  101. package/dist/run-tui-JxlEbb_f.js.map +0 -1
  102. package/dist/state-CaHeDL-0.js.map +0 -1
  103. package/src/cli/serve/promptEnhancers.ts +0 -69
  104. package/src/cli/serve/safeName.ts +0 -12
@@ -1,23 +1,58 @@
1
1
  // `comfy-ts serve` request handling, transport-free: run-serve owns node:http,
2
2
  // tests call handle() directly with an injected starter. Full contract:
3
3
  // agent/architecture.md item 12.
4
- import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
4
+ import {
5
+ closeSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readFileSync,
10
+ readSync,
11
+ realpathSync,
12
+ rmSync,
13
+ statSync,
14
+ writeFileSync,
15
+ } from 'node:fs'
5
16
  import { nanoid } from 'nanoid'
6
17
  import { basename, dirname, extname, join, resolve } from 'pathe'
7
18
  import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
8
19
  import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
9
- import { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/cli/serve/promptEnhancers.ts'
10
- import { validStoreName } from 'src/cli/serve/safeName.ts'
20
+ import { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/promptEnhancers.ts'
21
+ import { managerOnlyLoraOptions } from 'src/cli/serve/managerOnlyLoras.ts'
22
+ import { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'
23
+ import { readServeSettings, writeServeSettings, type ServeSettings } from 'src/cli/serve/serveSettings.ts'
24
+ import { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'
11
25
  import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
12
26
  import {
27
+ buildLoraMirror,
13
28
  getLoraDisplayName,
29
+ getLoraInfo,
14
30
  getLoraPreviewUrl,
15
31
  getLoraTriggerWords,
16
32
  refreshLoraInfoCacheIfChanged,
33
+ reloadLoraInfoCache,
34
+ writeLoraMirror,
17
35
  } from 'src/host/loraInfoCache.ts'
18
- import { fetchLoraList, fetchLoraPreviewBytes, loraKey, loraPreviewMapFrom } from 'src/host/loraManagerApi.ts'
36
+ import {
37
+ fetchLoraDescription,
38
+ fetchLoraExampleImages,
39
+ fetchLoraList,
40
+ fetchLoraPreviewBytes,
41
+ lmBaseModel,
42
+ lmCivitai,
43
+ lmFilePath,
44
+ lmFileSize,
45
+ lmSha256,
46
+ lmFolder,
47
+ lmNotes,
48
+ lmTags,
49
+ loraKey,
50
+ loraPreviewMapFrom,
51
+ } from 'src/host/loraManagerApi.ts'
52
+ import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
19
53
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
20
- import type { ImageVar, SeedVar } from 'src/vars/ComfyVars.ts'
54
+ import { DEFAULT_IMAGE_EXTENSIONS } from 'src/vars/ComfyVars.ts'
55
+ import type { ImageVar, LorasVar, PromptVar, SeedVar } from 'src/vars/ComfyVars.ts'
21
56
  import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
22
57
  import { bang } from 'src/utils/bang.ts'
23
58
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
@@ -29,24 +64,145 @@ export type ServeModule = { key: string; file: string; dw: DefinedWorkflow }
29
64
  export type ServeExecution = {
30
65
  done: Promise<unknown>
31
66
  status: string
32
- images: { absPath: string | null; filename: string }[]
67
+ /** buffer is the ONLY copy for an in-memory image (saving off); reading it on a
68
+ * SAVED image would hit the disk, so it is only touched when absPath is null */
69
+ images: { absPath: string | null; filename: string; buffer?: Uint8Array }[]
70
+ /** STRING outputs (PreviewAny, i.e. every llm graph). A text-only workflow has no images at
71
+ * all, so without these its run reply is empty and the panel shows nothing */
72
+ texts?: { nodeId: string; nodeKey: string | null; text: string }[]
33
73
  data: { id: string; error?: unknown }
34
74
  /** live global progress (ComfyExecution has it; fakes may omit) — the /run/<module> poll reads it */
35
75
  progressGlobal?: { percent: number }
76
+ /** the executing node and ITS counter, in its own unit (sampler steps, generated tokens).
77
+ * the only live signal a text node has: ComfyUI sends no partial text */
78
+ progress?: {
79
+ nodeName: string | null
80
+ nodeProgress: { value: number; max: number } | null
81
+ /** a node's live display text while it runs — a streaming generator's partial answer */
82
+ progressText?: string | null
83
+ }
36
84
  }
37
85
 
38
- export type ServeStarter = (mod: ServeModule) => Promise<ServeExecution>
86
+ export type ServeStarter = (
87
+ mod: ServeModule,
88
+ opts: { saveToDisk: boolean; savePrefix: string; host?: ComfyHost },
89
+ ) => Promise<ServeExecution>
39
90
 
40
91
  export type ServeRequest = { method: string; url: string; accept?: string; body?: string }
41
- export type ServeReply = { status: number; contentType: string; body: string | Uint8Array }
92
+ export type ServeReply = {
93
+ status: number
94
+ contentType: string
95
+ body: string | Uint8Array
96
+ /** extra response headers, lowercase keys — the transport writes them verbatim */
97
+ headers?: Record<string, string>
98
+ }
99
+
100
+ /** what serve will read off the disk and upload. Wider than the picker default: ComfyUI's
101
+ * LoadImage takes bmp and tiff too, and a var declaring one of those must not be refused */
102
+ const SERVE_IMAGE_FLOOR = new Set([
103
+ ...DEFAULT_IMAGE_EXTENSIONS.map((e) => e.toLowerCase()),
104
+ 'bmp',
105
+ 'tif',
106
+ 'tiff',
107
+ 'avif',
108
+ ])
109
+
110
+ /** the first bytes say what a file IS; the name only says what it claims. Cheap, and it stops
111
+ * a .png that holds a key or a script from being read and uploaded to the host.
112
+ * HONEST LIMIT: this is checked before the run, and the file is read again when the graph
113
+ * builds, so a local writer who can swap the path in between still wins. Closing that needs
114
+ * the upload to hold an fd, which is a bigger change than this gate. */
115
+ function looksLikeImage(path: string): boolean {
116
+ let fd: number | null = null
117
+ try {
118
+ fd = openSync(path, 'r')
119
+ const head = new Uint8Array(16)
120
+ const n = readSync(fd, head, 0, 16, 0)
121
+ return isImageMagic(head.subarray(0, n))
122
+ } catch {
123
+ return false
124
+ } finally {
125
+ if (fd != null) closeSync(fd)
126
+ }
127
+ }
128
+
129
+ /** what `POST /generate` will read off this machine and upload to a ComfyUI host. A var's own
130
+ * `extensions` is documented as a PICKER filter that never affects the value, so it cannot be
131
+ * the gate: a workflow author narrowing (or emptying) it for listing reasons must not be able
132
+ * to widen what an unauthenticated request can make the server read. The var may narrow this
133
+ * floor, never leave it. */
134
+ function serveAcceptsImageExt(declared: readonly string[], ext: string): boolean {
135
+ if (ext === '') return false
136
+ if (!SERVE_IMAGE_FLOOR.has(ext)) return false
137
+ // a declared list NARROWS the floor by its intersection. When that intersection is empty
138
+ // the declaration says nothing this bridge can honour (a picker filter for a format serve
139
+ // does not read), so the floor stands: narrowing to NOTHING would refuse every image,
140
+ // including the ones the var was declared for
141
+ const narrowed = declared.map((e) => e.toLowerCase().replace(/^\./, '')).filter((e) => SERVE_IMAGE_FLOOR.has(e))
142
+ return narrowed.length === 0 || narrowed.includes(ext)
143
+ }
144
+
145
+ /** an image var pointing at a url downloads it: capped, because the inbound BODY cap does not
146
+ * apply to what serve fetches on your behalf, and one url at a big file would OOM the process */
147
+ class DownloadRefused extends Error {
148
+ constructor(url: string) {
149
+ super(`could not fetch ${url}`)
150
+ this.name = 'DownloadRefused'
151
+ }
152
+ }
153
+
154
+ const INPUT_DOWNLOAD_CAP = 50_000_000
155
+ const INPUT_DOWNLOAD_TIMEOUT_MS = 60_000
156
+
157
+ /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
158
+ * whole body first, so a chunked reply with no content-length could exhaust the process before
159
+ * anything checked its size, the cap then reported a number nobody survived to read. */
160
+ export async function readCapped(res: Response, cap: number, what: string): Promise<Uint8Array> {
161
+ const body = res.body
162
+ if (body == null) return new Uint8Array(0)
163
+ const reader = body.getReader()
164
+ const chunks: Uint8Array[] = []
165
+ let total = 0
166
+ try {
167
+ for (;;) {
168
+ const step = await reader.read()
169
+ if (step.done) break
170
+ total += step.value.length
171
+ if (total > cap) {
172
+ await reader.cancel()
173
+ throw new Error(`download too large (over ${cap} bytes): ${what}`)
174
+ }
175
+ chunks.push(step.value)
176
+ }
177
+ } finally {
178
+ reader.releaseLock()
179
+ }
180
+ const out = new Uint8Array(total)
181
+ let at = 0
182
+ for (const c of chunks) {
183
+ out.set(c, at)
184
+ at += c.length
185
+ }
186
+ return out
187
+ }
188
+
189
+ /** the panel is REBUILT per serve process, so a cached copy is always the wrong one. With no
190
+ * cache header at all a browser applies heuristic freshness and reuses app.js across reloads,
191
+ * which makes every fix look like it never landed */
192
+ const NO_STORE = { 'cache-control': 'no-store, must-revalidate' }
42
193
 
43
194
  /** connect + fresh graph from current var values + send; done is awaited OUTSIDE the module mutex.
44
195
  * serve OPTS INTO local saving (library default is memory-only, architecture.md
45
196
  * item 14): the /outputs/ routes serve files, grouped per module */
46
- const realStarter: ServeStarter = async (mod) => {
47
- await mod.dw.host.connect()
48
- const wf = await mod.dw.build({ advance: true })
49
- return await wf.start({ save: { prefix: mod.key } })
197
+ const realStarter: ServeStarter = async (mod, opts) => {
198
+ // the override substitutes the host the graph is BUILT against too (DefinedWorkflow.build's
199
+ // own rule): a node missing there must surface as a workflow problem, not a silent run
200
+ const host = opts.host ?? mod.dw.host
201
+ await host.connect()
202
+ const wf = await mod.dw.build({ advance: true, host })
203
+ // saving is a SETTING now (GET/PUT /settings): off keeps outputs in memory and the
204
+ // reply points at /images/<promptId>/<ix> instead of a file url
205
+ return await wf.start({ save: opts.saveToDisk ? { prefix: opts.savePrefix } : false })
50
206
  }
51
207
 
52
208
  const CONTENT_TYPES: Record<string, string> = {
@@ -70,6 +226,20 @@ function sniffImageContentType(bytes: Uint8Array): string {
70
226
  return 'application/octet-stream'
71
227
  }
72
228
 
229
+ /** the FULL signature, not the first two bytes: `RI` alone matched a wav renamed .webp, and a
230
+ * two-byte file matched png. bmp/tiff/avif are here because the floor accepts them */
231
+ export function isImageMagic(b: Uint8Array): boolean {
232
+ const at = (i: number, ...want: number[]): boolean => want.every((w, k) => b[i + k] === w)
233
+ if (at(0, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)) return true // png
234
+ if (at(0, 0xff, 0xd8, 0xff)) return true // jpeg
235
+ if (at(0, 0x47, 0x49, 0x46, 0x38)) return true // gif87a/89a
236
+ if (at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) return true // riff....webp
237
+ if (at(0, 0x42, 0x4d)) return true // bmp
238
+ if (at(0, 0x49, 0x49, 0x2a, 0x00) || at(0, 0x4d, 0x4d, 0x00, 0x2a)) return true // tiff le/be
239
+ if (at(4, 0x66, 0x74, 0x79, 0x70)) return true // isobmff box: avif/heif
240
+ return false
241
+ }
242
+
73
243
  function json(status: number, payload: unknown): ServeReply {
74
244
  return { status, contentType: 'application/json', body: JSON.stringify(payload, null, 2) }
75
245
  }
@@ -86,11 +256,27 @@ const USAGE = [
86
256
  'POST /upload with {"name","dataBase64"} — store a browser file for an image var',
87
257
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
88
258
  'GET /lora-preview/<hostId>/<lora> — preview image bytes',
259
+ 'GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)',
89
260
  'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',
90
261
  'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
262
+ 'GET /settings — { saveToDisk } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory',
263
+ 'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
264
+ 'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',
265
+ 'GET /hosts/<hostId>/ping — is that host answering right now (restart watch)',
266
+ 'GET /hosts/<hostId>/logs — the last lines of that host console',
267
+ 'GET /images/<promptId>/<ix> — an in-memory output (saving off), while the process lives',
91
268
  'GET /outputs/<path> — generated files',
92
269
  ]
93
270
 
271
+ /** content hash of the bundle, so the script URL CHANGES whenever the code does. no-store
272
+ * alone does not help a browser that already has app.js cached under a plain url, and a panel
273
+ * running stale javascript is indistinguishable from a broken fix */
274
+ function buildId(js: string): string {
275
+ let h = 5381
276
+ for (let i = 0; i < js.length; i++) h = ((h << 5) + h + js.charCodeAt(i)) | 0
277
+ return (h >>> 0).toString(36)
278
+ }
279
+
94
280
  /** the html shell; the app itself is ONE bundle at /web/app.js */
95
281
  const WEB_SHELL = `<!doctype html>
96
282
  <html lang="en">
@@ -102,7 +288,7 @@ const WEB_SHELL = `<!doctype html>
102
288
  </head>
103
289
  <body>
104
290
  <div id="root"></div>
105
- <script type="module" src="/web/app.js"></script>
291
+ <script type="module" src="/web/app.js?v=__BUILD__"></script>
106
292
  </body>
107
293
  </html>
108
294
  `
@@ -118,6 +304,20 @@ export class ServeApp {
118
304
  private chains = new Map<string, Promise<unknown>>()
119
305
  /** the bundle is built at most once per process, first browser hit pays it */
120
306
  private webJsCache: Promise<string | null> | null = null
307
+ /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can
308
+ * be constructed before a comfyts instance is registered, and reading the file then would
309
+ * throw at construction time */
310
+ private settingsCache: ServeSettings | null = null
311
+ private get settings(): ServeSettings {
312
+ this.settingsCache ??= readServeSettings()
313
+ return this.settingsCache
314
+ }
315
+ private set settings(next: ServeSettings) {
316
+ this.settingsCache = next
317
+ }
318
+ /** in-memory outputs of runs made with saving OFF: the ONLY copy, so the gallery has
319
+ * something to show. Capped and FIFO, a long session must not grow without bound */
320
+ private memoryImages = new Map<string, { bytes: Uint8Array; contentType: string }>()
121
321
 
122
322
  constructor(
123
323
  public modules: ServeModule[],
@@ -155,8 +355,14 @@ export class ServeApp {
155
355
  // a blank dark page, the json index is a usable answer
156
356
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {
157
357
  this.webJsCache ??= this.opts.webJs()
158
- if ((await this.webJsCache) != null)
159
- return { status: 200, contentType: 'text/html; charset=utf-8', body: WEB_SHELL }
358
+ const js = await this.webJsCache
359
+ if (js != null)
360
+ return {
361
+ status: 200,
362
+ contentType: 'text/html; charset=utf-8',
363
+ body: WEB_SHELL.replace('__BUILD__', buildId(js)),
364
+ headers: NO_STORE,
365
+ }
160
366
  }
161
367
  if (segs.length === 0 || (segs[0] === 'drafts' && segs.length === 1)) return this.replyIndex()
162
368
  if (segs[0] === 'web' && segs[1] === 'app.js' && segs.length === 2) return await this.replyWebJs()
@@ -169,7 +375,17 @@ export class ServeApp {
169
375
  return this.replyLoraInfo(segs[1], segs[2])
170
376
  if (segs[0] === 'lora-preview' && segs.length === 3 && segs[1] != null && segs[2] != null)
171
377
  return await this.replyLoraPreview(segs[1], segs[2])
378
+ if (segs[0] === 'lora-about' && segs.length === 3 && segs[1] != null && segs[2] != null)
379
+ return await this.replyLoraAbout(segs[1], segs[2])
172
380
  if (segs[0] === 'prompt-enhancers' && segs.length === 1) return this.replyPromptEnhancers()
381
+ if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()
382
+ if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()
383
+ if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')
384
+ return await this.replyHostLogs(segs[1])
385
+ if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'ping')
386
+ return await this.replyHostPing(segs[1])
387
+ if (segs[0] === 'images' && segs.length === 3 && segs[1] != null && segs[2] != null)
388
+ return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)
173
389
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
174
390
  return json(404, { error: `no route: GET ${path}`, usage: USAGE })
175
391
  }
@@ -183,6 +399,11 @@ export class ServeApp {
183
399
  return await this.replySaveDraft(segs[1], segs[2], req)
184
400
  if (req.method === 'DELETE' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
185
401
  return await this.replyDeleteDraft(segs[1], segs[2])
402
+ if (req.method === 'PUT' && segs[0] === 'settings' && segs.length === 1) return this.replySaveSettings(req)
403
+ if (req.method === 'PUT' && segs[0] === 'hosts' && segs.length === 2 && segs[1] != null)
404
+ return this.replySetHost(segs[1], req)
405
+ if (req.method === 'POST' && segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] != null)
406
+ return await this.replyHostAction(segs[1], segs[2])
186
407
  if (req.method === 'PUT' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
187
408
  return this.replySavePromptEnhancer(segs[1], req)
188
409
  if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
@@ -205,7 +426,7 @@ export class ServeApp {
205
426
  }
206
427
 
207
428
  /** THE draft-name gate, shared by every route that turns a url segment into a path
208
- * (safeName.ts owns the rule — the prompt-enhancer routes call the same function) */
429
+ * (safeName.ts owns the rule, the prompt-enhancer routes call the same function) */
209
430
  private validDraftName(raw: string): string | null {
210
431
  return validStoreName(raw)
211
432
  }
@@ -274,9 +495,46 @@ export class ServeApp {
274
495
  if (label !== option) labels[option] = label
275
496
  }
276
497
  if (Object.keys(labels).length > 0) desc.optionLabels = labels
498
+ // the UNION: a lora the manager mirror knows but ComfyUI's enum does not. It is on
499
+ // disk, so it usually runs, the picker offers it, flagged, rather than hiding it
500
+ // by normalized key, never raw: an enum value keeps its case, extension and
501
+ // windows separators. the var's own regex narrows the mirror too
502
+ const extras = managerOnlyLoraOptions({
503
+ hostId,
504
+ options: desc.options,
505
+ filter: (varDef as LorasVar<string>).optionsFilter,
506
+ })
507
+ if (extras.length > 0) {
508
+ desc.managerOnlyOptions = extras
509
+ desc.options = [...desc.options, ...extras]
510
+ for (const extra of extras) {
511
+ const label = getLoraDisplayName(extra, hostId)
512
+ if (label !== extra) (desc.optionLabels ??= {})[extra] = label
513
+ }
514
+ }
515
+ // what a prompt with loraKeywordsFrom will PREPEND, per option: the panel shows
516
+ // the injection instead of leaving you to discover it in the generated image
517
+ const keywords: Record<string, string> = {}
518
+ for (const option of desc.options) {
519
+ const kw = getLoraKeyword(option, hostId)
520
+ if (kw !== '') keywords[option] = kw
521
+ }
522
+ if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords
277
523
  }
278
524
  vars[name] = desc
279
525
  }
526
+ // a prompt knows its lora SOURCE by identity only; naming it needs both vars, which is
527
+ // exactly what this loop has. Without it the panel cannot preview the keyword prefix
528
+ for (const [name, varDef] of mod.dw.entries()) {
529
+ if (varDef.kind !== 'prompt') continue
530
+ const source = (varDef as PromptVar).promptOpts.loraKeywordsFrom
531
+ if (source == null) continue
532
+ // identity across two unrelated faces (AnyVar vs ActiveLoraSource): compare as unknown,
533
+ // the LorasVar instance IS both
534
+ const sourceName = mod.dw.entries().find(([, other]) => (other as unknown) === (source as unknown))?.[0]
535
+ const desc = vars[name]
536
+ if (sourceName != null && desc != null) desc.keywordsFrom = sourceName
537
+ }
280
538
  return {
281
539
  module: mod.key,
282
540
  file: mod.file,
@@ -336,7 +594,7 @@ export class ServeApp {
336
594
  this.webJsCache ??= this.opts.webJs()
337
595
  const js = await this.webJsCache
338
596
  if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })
339
- return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js }
597
+ return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }
340
598
  }
341
599
 
342
600
  /** browser file → local file an image var can point at (downloadInput family) */
@@ -352,7 +610,9 @@ export class ServeApp {
352
610
  return json(400, { error: 'upload expects {"name":"<filename>","dataBase64":"<base64 bytes>"}' })
353
611
  const bytes = Buffer.from(o.dataBase64, 'base64')
354
612
  if (bytes.length === 0) return json(400, { error: 'dataBase64 decoded to zero bytes' })
355
- const safe = basename(o.name).replace(/[^\w.-]+/g, '_') || 'upload'
613
+ // the same 100-char cap validStoreName carries: without it a long name reached the fs and
614
+ // came back as a 500 quoting the absolute path
615
+ const safe = (basename(o.name).replace(/[^\w.-]+/g, '_') || 'upload').slice(0, 100)
356
616
  const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${safe}`)
357
617
  mkdirSync(dirname(abs), { recursive: true })
358
618
  writeFileSync(abs, bytes)
@@ -393,7 +653,7 @@ export class ServeApp {
393
653
 
394
654
  /** delete the draft FILE. `default` is deletable like any other: the implicit `default`
395
655
  * draft (spec values, no file) survives it, which is exactly the reset. Missing file is
396
- * still a 200 — the caller asked for it to be gone, and it is */
656
+ * still a 200, the caller asked for it to be gone, and it is */
397
657
  private async replyDeleteDraft(modKey: string, rawDraft: string): Promise<ServeReply> {
398
658
  const mod = this.moduleByKey(modKey)
399
659
  if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
@@ -407,6 +667,316 @@ export class ServeApp {
407
667
  return json(200, { ok: true, module: mod.key, draft: rawDraft.trim(), drafts: this.draftsFor(mod) })
408
668
  }
409
669
 
670
+ // #region hosts (run a workflow somewhere else, the TUI's host override) ----
671
+ /** every host this process registered: the modules' own, plus anything they created */
672
+ private knownHosts(): { id: string; url: string; httpUrl: string; modules: string[] }[] {
673
+ const byId = new Map<string, { id: string; url: string; httpUrl: string; modules: string[] }>()
674
+ for (const [id, host] of comfyts.hosts)
675
+ byId.set(id, {
676
+ id,
677
+ url: `${host.base.host}:${host.base.port}`,
678
+ // the browser needs the REAL base to open the host's own pages (lora manager)
679
+ httpUrl: host.getServerHostHTTP(),
680
+ modules: [],
681
+ })
682
+ for (const mod of this.modules) {
683
+ const entry = byId.get(mod.dw.host.data.id)
684
+ if (entry != null) entry.modules.push(mod.key)
685
+ }
686
+ return [...byId.values()].sort((a, b) => a.id.localeCompare(b.id))
687
+ }
688
+
689
+ /** the host a run goes to: the override if it still exists, else the module's own.
690
+ * A stale override (a host id that is gone) must never silently swallow the run */
691
+ private runHostFor(mod: ServeModule): ComfyHost | null {
692
+ const wanted = this.settings.hostOverride[mod.key]
693
+ if (wanted == null || wanted === mod.dw.host.data.id) return null
694
+ return comfyts.hosts.get(wanted) ?? null
695
+ }
696
+
697
+ /** the host actions the TUI's host panel has, minus re-codegen: regenerating the sdk
698
+ * rewrites a .d.ts for your EDITOR, while the running modules keep the builder they were
699
+ * imported with, a button that changes nothing in this process would be a lie */
700
+ private async replyHostAction(hostId: string, action: string): Promise<ServeReply> {
701
+ const host = comfyts.hosts.get(hostId)
702
+ if (host == null)
703
+ return json(404, { error: `unknown host '${hostId}' — known: ${[...comfyts.hosts.keys()].join(', ')}` })
704
+ try {
705
+ if (action === 'interrupt') {
706
+ await host.interrupt()
707
+ return json(200, { ok: true, host: hostId, action, note: 'interrupt requested' })
708
+ }
709
+ if (action === 'clear-queue') {
710
+ await host.clearQueue()
711
+ return json(200, { ok: true, host: hostId, action, note: 'pending prompts dropped' })
712
+ }
713
+ if (action === 'refresh-loras') return await this.refreshLoraMirror(hostId, host)
714
+ if (action === 'refresh-schema') {
715
+ await host.fetchAndUpdateSchema()
716
+ // a lora var resolves its regex against the schema ONCE, at define time, so a
717
+ // refetch alone left every var on the list it was born with and the panel kept
718
+ // warning about a lora the host had just learned. rebinding re-runs that resolve
719
+ const rebound = await this.rebindHostVars(hostId, host)
720
+ const nodes = host.schema.nodes.length
721
+ const loras = host.schema.getLoras().length
722
+ const dropped =
723
+ rebound.stale.length === 0
724
+ ? ''
725
+ : `. dropped ${rebound.stale.length} selection(s) this host no longer lists`
726
+ return json(200, {
727
+ ok: true,
728
+ host: hostId,
729
+ action,
730
+ stale: rebound.stale,
731
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`,
732
+ })
733
+ }
734
+ if (action === 'restart') {
735
+ // restartComfyUI already treats the mid-reboot disconnect as success, so what
736
+ // reaches here is a host that REFUSED, swallowing it reported a reboot that
737
+ // never happened, which is worse than saying nothing
738
+ await host.manager.restartComfyUI()
739
+ return json(200, { ok: true, host: hostId, action, note: 'reboot requested — it reconnects when back' })
740
+ }
741
+ return json(400, {
742
+ error: `unknown host action '${action}' — interrupt | clear-queue | restart | refresh-loras | refresh-schema`,
743
+ })
744
+ } catch (e) {
745
+ return json(502, { error: `host '${hostId}' refused '${action}': ${extractErrorMessage(e)}` })
746
+ }
747
+ }
748
+
749
+ /** re-sweep ComfyUI-Lora-Manager and rewrite the mirror — what `comfy-ts loras` does, with
750
+ * its refusals kept: a partial or unreachable sweep NEVER overwrites, because writing it
751
+ * would delete loras from the mirror that are alive on the host */
752
+ /** re-resolve the host-bound lora vars of the modules DEFINED on this host: LorasVar only
753
+ * resolves its RegExp inside bindHost, so nothing else picks up a widened enum.
754
+ *
755
+ * the defining host, not the override: rebinding an overridden module against another box
756
+ * rewrites its options AND its hostId (which picks the metadata mirror) with no way back,
757
+ * since dropping the override cannot un-resolve them.
758
+ *
759
+ * runs under each module's mutex, so it cannot swap the options out from under a generate
760
+ * that already validated its payload against the old list. */
761
+ private async rebindHostVars(hostId: string, host: ComfyHost): Promise<{ widened: number; stale: string[] }> {
762
+ let widened = 0
763
+ const stale: string[] = []
764
+ for (const mod of this.modules) {
765
+ if (mod.dw.host.data.id !== hostId) continue
766
+ await this.exclusive(mod.key, () => {
767
+ for (const [name, varDef] of mod.dw.entries()) {
768
+ if (varDef.kind !== 'loras') continue
769
+ const lorasVar = varDef as LorasVar<string>
770
+ if (lorasVar.optionsFilter == null) continue // a plain array never re-resolves
771
+ const before = lorasVar.options.length
772
+ lorasVar.bindHost(host)
773
+ if (lorasVar.options.length !== before) widened++
774
+ // a SELECTED lora the host no longer lists would still ride into the graph and
775
+ // be refused there: it leaves the record, and the reply says which
776
+ const known = new Set<string>(lorasVar.options)
777
+ const value = lorasVar.value as Record<string, unknown>
778
+ for (const picked of Object.keys(value)) {
779
+ if (known.has(picked)) continue
780
+ stale.push(`${mod.key}/${name}: ${picked}`)
781
+ delete value[picked]
782
+ }
783
+ }
784
+ return Promise.resolve()
785
+ })
786
+ }
787
+ return { widened, stale }
788
+ }
789
+
790
+ private async refreshLoraMirror(hostId: string, host: ComfyHost): Promise<ServeReply> {
791
+ const sweep = await fetchLoraList(host)
792
+ if (sweep.status === 'absent')
793
+ return json(400, {
794
+ error: `${hostId} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,
795
+ })
796
+ if (sweep.status === 'unreachable')
797
+ return json(502, { error: `${hostId} unreachable — ${sweep.reason}. Mirror left untouched.` })
798
+ if (sweep.status === 'partial')
799
+ return json(502, {
800
+ error: `the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched.`,
801
+ })
802
+ const mirror = buildLoraMirror({
803
+ hostId,
804
+ hostUrl: host.getServerHostHTTP(),
805
+ fetchedAt: new Date().toISOString(),
806
+ items: sweep.items,
807
+ })
808
+ writeLoraMirror(mirror)
809
+ // the in-process cache reads the file by mtime, so every surface sees the new names
810
+ reloadLoraInfoCache()
811
+ console.log(`[serve] lora mirror refreshed for ${hostId}: ${mirror.count} loras`)
812
+ return json(200, {
813
+ ok: true,
814
+ host: hostId,
815
+ action: 'refresh-loras',
816
+ count: mirror.count,
817
+ note: `${mirror.count} loras synced`,
818
+ })
819
+ }
820
+
821
+ /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
822
+ * "restarting…" ends on a fact rather than on a guess */
823
+ private async replyHostPing(hostId: string): Promise<ServeReply> {
824
+ const host = comfyts.hosts.get(hostId)
825
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` })
826
+ try {
827
+ const res = await host.fetch('/system_stats', {})
828
+ return json(200, { host: hostId, up: res.ok, status: res.status })
829
+ } catch (e) {
830
+ return json(200, { host: hostId, up: false, reason: extractErrorMessage(e) })
831
+ }
832
+ }
833
+
834
+ /** the ComfyUI console, the TUI's logs panel over http — through the SAME assembly the TUI
835
+ * uses (assembleLogChunks): entries are write CHUNKS, so lines are folded there, ANSI is
836
+ * stripped, tqdm redraws collapse to their last state, and the cp1252 mojibake a windows
837
+ * host emits is repaired. Re-implementing any of that here would drift from the TUI */
838
+ private async replyHostLogs(hostId: string): Promise<ServeReply> {
839
+ const host = comfyts.hosts.get(hostId)
840
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` })
841
+ try {
842
+ const raw = await host.fetchRawLogs()
843
+ const lines: string[] = []
844
+ const partial = assembleLogChunks({ lines, partial: '', entries: raw.entries })
845
+ // the tail has no newline yet (a live progress bar): show it, it is the current state
846
+ if (partial.trim() !== '') lines.push(partial)
847
+ return json(200, { host: hostId, lines: lines.slice(-200) })
848
+ } catch (e) {
849
+ return json(502, { error: `could not read the logs of '${hostId}': ${extractErrorMessage(e)}` })
850
+ }
851
+ }
852
+
853
+ private replyHosts(): ServeReply {
854
+ return json(200, {
855
+ hosts: this.knownHosts(),
856
+ defaults: Object.fromEntries(this.modules.map((m) => [m.key, m.dw.host.data.id])),
857
+ overrides: this.settings.hostOverride,
858
+ })
859
+ }
860
+
861
+ private replySetHost(modKey: string, req: ServeRequest): ServeReply {
862
+ const mod = this.moduleByKey(modKey)
863
+ if (mod == null) return json(404, { error: `unknown module '${modKey}'` })
864
+ let parsed: unknown
865
+ try {
866
+ parsed = JSON.parse(req.body ?? '')
867
+ } catch (e) {
868
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
869
+ }
870
+ const wanted = parsed != null && typeof parsed === 'object' ? (parsed as { host?: unknown }).host : null
871
+ if (wanted != null && typeof wanted !== 'string')
872
+ return json(400, { error: 'body must be { "host": "<host id>" } or { "host": null } to reset' })
873
+ const next = { ...this.settings.hostOverride }
874
+ if (wanted == null || wanted === mod.dw.host.data.id) delete next[mod.key]
875
+ else {
876
+ if (!comfyts.hosts.has(wanted))
877
+ return json(400, {
878
+ error: `unknown host '${wanted}' — known: ${[...comfyts.hosts.keys()].join(', ')}`,
879
+ })
880
+ next[mod.key] = wanted
881
+ }
882
+ this.settings = { ...this.settings, hostOverride: next }
883
+ try {
884
+ writeServeSettings(this.settings)
885
+ } catch (e) {
886
+ return json(500, { error: `host applied for this session but not saved: ${extractErrorMessage(e)}` })
887
+ }
888
+ const target = next[mod.key] ?? mod.dw.host.data.id
889
+ console.log(`[serve] ${mod.key} runs on ${target}${next[mod.key] != null ? ' (override)' : ''}`)
890
+ return json(200, { ok: true, module: mod.key, host: target, overrides: this.settings.hostOverride })
891
+ }
892
+
893
+ // #region settings + in-memory outputs --------------------------------------
894
+ /** the last N in-memory outputs stay reachable; older ones are dropped, because with
895
+ * saving off these buffers are the only copy and nothing else will free them */
896
+ private readonly MEMORY_IMAGE_CAP = 60
897
+
898
+ private rememberMemoryImage(key: string, bytes: Uint8Array, filename: string): void {
899
+ const contentType = CONTENT_TYPES[extname(filename).toLowerCase()] ?? sniffImageContentType(bytes)
900
+ this.memoryImages.set(key, { bytes, contentType })
901
+ while (this.memoryImages.size > this.MEMORY_IMAGE_CAP) {
902
+ const oldest = this.memoryImages.keys().next()
903
+ if (oldest.done === true) break
904
+ this.memoryImages.delete(oldest.value)
905
+ }
906
+ }
907
+
908
+ private replyMemoryImage(key: string): ServeReply {
909
+ const hit = this.memoryImages.get(key)
910
+ if (hit == null)
911
+ return json(404, {
912
+ 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.`,
913
+ })
914
+ return { status: 200, contentType: hit.contentType, body: hit.bytes }
915
+ }
916
+
917
+ /** the subfolder under outputs/ a module's images land in. Falls back to the module key,
918
+ * which is what every serve run used before the prefix was choosable */
919
+ private savePrefixFor(modKey: string): string {
920
+ const stored = this.settings.savePrefix[modKey]?.trim() ?? ''
921
+ return stored === '' ? modKey : stored
922
+ }
923
+
924
+ private replySaveSettings(req: ServeRequest): ServeReply {
925
+ let parsed: unknown
926
+ try {
927
+ parsed = JSON.parse(req.body ?? '')
928
+ } catch (e) {
929
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
930
+ }
931
+ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
932
+ return json(400, {
933
+ error: 'body must be { "saveToDisk"?: true | false, "savePrefix"?: { "<module>": "path" } }',
934
+ })
935
+ const wanted = parsed as { saveToDisk?: unknown; savePrefix?: unknown }
936
+ let next = this.settings
937
+ if (wanted.saveToDisk != null) {
938
+ if (typeof wanted.saveToDisk !== 'boolean') return json(400, { error: '"saveToDisk" must be true or false' })
939
+ next = { ...next, saveToDisk: wanted.saveToDisk }
940
+ }
941
+ if (wanted.savePrefix != null) {
942
+ if (typeof wanted.savePrefix !== 'object' || Array.isArray(wanted.savePrefix))
943
+ return json(400, { error: '"savePrefix" must be { "<module>": "path" }' })
944
+ const prefixes = { ...next.savePrefix }
945
+ for (const [modKey, raw] of Object.entries(wanted.savePrefix as Record<string, unknown>)) {
946
+ if (this.moduleByKey(modKey) == null) return json(404, { error: `unknown module '${modKey}'` })
947
+ if (typeof raw !== 'string') return json(400, { error: `prefix for '${modKey}' must be a string` })
948
+ const clean = validSavePrefix(raw)
949
+ if (clean == null)
950
+ return json(400, {
951
+ error: `invalid prefix '${raw}' — folder names only, "a/b" allowed, no ".." and no absolute path`,
952
+ })
953
+ // empty means "back to the default", so the stored map keeps only real choices
954
+ if (clean === '') delete prefixes[modKey]
955
+ else prefixes[modKey] = clean
956
+ }
957
+ next = { ...next, savePrefix: prefixes }
958
+ }
959
+ const saveToDisk = next.saveToDisk
960
+ this.settings = next
961
+ try {
962
+ writeServeSettings(this.settings)
963
+ } catch (e) {
964
+ // the live setting still applies; say the persistence failed rather than lying
965
+ return json(500, { error: `setting applied for this session but not saved: ${extractErrorMessage(e)}` })
966
+ }
967
+ console.log(`[serve] outputs ${saveToDisk ? 'SAVE to disk' : 'stay in MEMORY'}`)
968
+ return this.replySettings()
969
+ }
970
+
971
+ /** the stored settings PLUS the prefix each module actually uses, so the ui can show the
972
+ * effective folder without re-deriving the fallback rule */
973
+ private replySettings(): ServeReply {
974
+ return json(200, {
975
+ ...this.settings,
976
+ effectivePrefix: Object.fromEntries(this.modules.map((m) => [m.key, this.savePrefixFor(m.key)])),
977
+ })
978
+ }
979
+
410
980
  // #region prompt enhancers (the web ui's master prompts, as .md files) ------
411
981
  /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
412
982
  private replyPromptEnhancers(): ServeReply {
@@ -491,6 +1061,18 @@ export class ServeApp {
491
1061
  running,
492
1062
  status: exec?.status ?? 'idle',
493
1063
  percent: running ? (exec.progressGlobal?.percent ?? null) : null,
1064
+ // the node and ITS counter: on a text graph this is the ONLY thing that moves, since
1065
+ // ComfyUI publishes no partial text (probed: 90 progress messages, then one `executed`)
1066
+ node: running ? (exec.progress?.nodeName ?? null) : null,
1067
+ // value/max ONLY: the raw ws progress message also carries prompt_id and node, and
1068
+ // echoing a whole wire message into our own api makes its extra fields look like ours
1069
+ nodeProgress:
1070
+ running && exec.progress?.nodeProgress != null
1071
+ ? { value: exec.progress.nodeProgress.value, max: exec.progress.nodeProgress.max }
1072
+ : null,
1073
+ // live text a node publishes WHILE it runs (send_progress_text): the only channel
1074
+ // on which a generator's partial answer can reach a client at all
1075
+ progressText: running ? (exec.progress?.progressText ?? null) : null,
494
1076
  hasPreview: this.latentPreviews.has(mod.key),
495
1077
  previewSeq: this.latentPreviews.get(mod.key)?.seq ?? null,
496
1078
  })
@@ -522,10 +1104,46 @@ export class ServeApp {
522
1104
  if (this.hostById(hostId) == null)
523
1105
  return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
524
1106
  refreshLoraInfoCacheIfChanged()
1107
+ // everything the mirror holds that a human wants when they click a card. Read through the
1108
+ // lm* accessors, never off the raw json: the extension's field names are its business
1109
+ const item = getLoraInfo(lora, hostId)
1110
+ const civitai = item == null ? null : lmCivitai(item)
525
1111
  return json(200, {
526
1112
  name: lora,
527
1113
  displayName: getLoraDisplayName(lora, hostId),
528
1114
  triggerWords: getLoraTriggerWords(lora, hostId),
1115
+ known: item != null,
1116
+ baseModel: item == null ? null : lmBaseModel(item),
1117
+ folder: item == null ? null : lmFolder(item),
1118
+ filePath: item == null ? null : lmFilePath(item),
1119
+ fileSize: item == null ? null : lmFileSize(item),
1120
+ tags: item == null ? [] : lmTags(item),
1121
+ notes: item == null ? '' : lmNotes(item),
1122
+ civitaiUrl: civitai?.modelId == null ? null : `https://civitai.com/models/${civitai.modelId}`,
1123
+ civitaiVersion: civitai?.name ?? null,
1124
+ })
1125
+ }
1126
+
1127
+ /** what the mirror does NOT hold: civitai's description and the example images, both live
1128
+ * from the extension. A SEPARATE route from /lora-info on purpose, that one is mirror-only
1129
+ * and instant, this one talks to the host and is fetched when a details panel opens */
1130
+ private async replyLoraAbout(hostId: string, lora: string): Promise<ServeReply> {
1131
+ const host = this.hostById(hostId)
1132
+ if (host == null) return json(404, { error: `unknown host '${hostId}' — hosts: ${this.hostIds()}` })
1133
+ refreshLoraInfoCacheIfChanged()
1134
+ const item = getLoraInfo(lora, hostId)
1135
+ if (item == null) return json(200, { known: false, description: null, examples: [], examplesReason: null })
1136
+ const filePath = lmFilePath(item)
1137
+ const sha = lmSha256(item)
1138
+ const [description, examples] = await Promise.all([
1139
+ filePath == null ? Promise.resolve(null) : fetchLoraDescription(host, filePath),
1140
+ sha == null ? Promise.resolve({ files: [], reason: null }) : fetchLoraExampleImages(host, sha),
1141
+ ])
1142
+ return json(200, {
1143
+ known: true,
1144
+ description,
1145
+ examples: examples.files,
1146
+ examplesReason: examples.reason,
529
1147
  })
530
1148
  }
531
1149
 
@@ -617,15 +1235,29 @@ export class ServeApp {
617
1235
  })
618
1236
  }
619
1237
 
620
- console.log(
621
- `[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${execution.images.length} image(s)`,
622
- )
1238
+ const produced = [`${execution.images.length} image(s)`]
1239
+ if ((execution.texts ?? []).length > 0) produced.push(`${(execution.texts ?? []).length} text(s)`)
1240
+ console.log(`[serve] 🟢 ${mod.key}/${draft} done in ${(durationMs / 1000).toFixed(1)}s · ${produced.join(' · ')}`)
1241
+
1242
+ // saving off → the buffer is the only copy: keep it addressable so the gallery (and
1243
+ // curl) still get an image instead of a null url
1244
+ const memoryKeys = new Map<number, string>()
1245
+ for (const [ix, img] of execution.images.entries()) {
1246
+ if (img.absPath != null || img.buffer == null) continue
1247
+ const key = `${execution.data.id}/${ix}`
1248
+ this.rememberMemoryImage(key, img.buffer, img.filename)
1249
+ memoryKeys.set(ix, key)
1250
+ }
623
1251
 
624
1252
  // Accept: image/* → first image's bytes directly (curl -o, <img src>)
625
1253
  const first = execution.images[0]
626
- if (req.accept?.includes('image/') && first?.absPath != null) {
627
- const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
628
- return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
1254
+ if (req.accept?.includes('image/') && first != null) {
1255
+ if (first.absPath != null) {
1256
+ const contentType = CONTENT_TYPES[extname(first.absPath).toLowerCase()] ?? 'application/octet-stream'
1257
+ return { status: 200, contentType, body: new Uint8Array(readFileSync(first.absPath)) }
1258
+ }
1259
+ const inMemory = this.memoryImages.get(memoryKeys.get(0) ?? '')
1260
+ if (inMemory != null) return { status: 200, contentType: inMemory.contentType, body: inMemory.bytes }
629
1261
  }
630
1262
 
631
1263
  return json(200, {
@@ -635,9 +1267,21 @@ export class ServeApp {
635
1267
  promptId: execution.data.id,
636
1268
  durationMs,
637
1269
  seeds,
638
- images: execution.images.map((img) => ({
1270
+ savedToDisk: this.settings.saveToDisk,
1271
+ texts: (execution.texts ?? []).map((t) => ({ nodeKey: t.nodeKey, text: t.text })),
1272
+ images: execution.images.map((img, ix) => ({
639
1273
  filename: img.filename,
640
- url: img.absPath != null ? this.outputUrl(img.absPath) : null,
1274
+ url:
1275
+ img.absPath != null
1276
+ ? this.outputUrl(img.absPath)
1277
+ : memoryKeys.has(ix)
1278
+ ? // the KEY is raw (`<promptId>/<ix>`); the url encodes each segment, and
1279
+ // handle() decodes per segment, so the lookup gets the raw key back
1280
+ `/images/${(memoryKeys.get(ix) ?? '')
1281
+ .split('/')
1282
+ .map((seg) => encodeURIComponent(seg))
1283
+ .join('/')}`
1284
+ : null,
641
1285
  absPath: img.absPath,
642
1286
  })),
643
1287
  })
@@ -685,16 +1329,53 @@ export class ServeApp {
685
1329
  return { status: 400, error: `var '${k}': ${extractErrorMessage(e)}` }
686
1330
  }
687
1331
  }
688
- const err = applyVarPayload(varDef, value)
1332
+ // a lora the mirror knows but the enum does not is a legal choice here too, else the
1333
+ // picker would offer something the api then refuses
1334
+ const err = applyVarPayload(varDef, value, {
1335
+ // narrowed by the var's OWN filter, exactly like the picker: what the ui offers and
1336
+ // what the api accepts must be the same set, or one of them is lying
1337
+ // the SAME function the picker used: it derives the separator from this var's own
1338
+ // enum, so a backslash host cannot be offered `a/b` and then refused it
1339
+ extraLoraOptions:
1340
+ varDef.kind === 'loras'
1341
+ ? managerOnlyLoraOptions({
1342
+ hostId: mod.dw.host.data.id,
1343
+ options: (varDef as LorasVar<string>).options,
1344
+ filter: (varDef as LorasVar<string>).optionsFilter,
1345
+ })
1346
+ : undefined,
1347
+ })
689
1348
  if (err != null) return { status: 400, error: err }
690
1349
  }
691
1350
 
692
- // 3. image vars must point at real files BEFORE anything is queued
1351
+ // 3. image vars must point at a real FILE of a declared type BEFORE anything is queued.
1352
+ // the path a request hands us is read off this box and uploaded to the ComfyUI host, so
1353
+ // the extension list the descriptor advertises is enforced here, not merely advertised:
1354
+ // a var that accepts .png must not be talked into reading a key or a config file
693
1355
  for (const [k, varDef] of varMap) {
694
1356
  if (varDef.kind !== 'image') continue
695
1357
  const img = varDef as ImageVar
696
- if (img.isSet() && !existsSync(img.absPath()))
697
- return { status: 400, error: `image var '${k}': file not found: ${img.absPath()}` }
1358
+ if (!img.isSet()) continue
1359
+ const abs = img.absPath()
1360
+ // ONE message for every rejection below: distinct ones told an unauthenticated caller
1361
+ // whether any path exists, is a file, and what type it is
1362
+ const refuse = { status: 400, error: `image var '${k}': not a usable image file` }
1363
+ if (!existsSync(abs)) return refuse
1364
+ // the REAL path: statSync follows symlinks, so `pic.png -> id_rsa` passed a check made
1365
+ // on the link's name. Resolving first means the gate judges the file being read
1366
+ let real: string
1367
+ try {
1368
+ real = realpathSync(abs)
1369
+ } catch {
1370
+ return refuse
1371
+ }
1372
+ try {
1373
+ if (!statSync(real).isFile()) return refuse
1374
+ } catch {
1375
+ return refuse
1376
+ }
1377
+ if (!serveAcceptsImageExt(img.extensions, extname(real).toLowerCase().replace(/^\./, ''))) return refuse
1378
+ if (!looksLikeImage(real)) return refuse
698
1379
  }
699
1380
 
700
1381
  // 4. seed policy (architecture item 12): payload wins; '?' rerolls;
@@ -708,9 +1389,10 @@ export class ServeApp {
708
1389
  if (seedVar.mode === '?') seedVar.randomize()
709
1390
  else if (seedVar.mode === '+' || seedVar.mode === '-') {
710
1391
  const prev = this.seedState.get(stateKey)
711
- // continue only while the draft still holds the value the chain grew from
712
- if (prev != null && prev.draftBase === draftValue)
713
- seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
1392
+ // the draft holding the value we last SERVED is our own write-back, not the
1393
+ // human edit draftBase watches for
1394
+ const ours = prev != null && (prev.draftBase === draftValue || prev.last === draftValue)
1395
+ if (prev != null && ours) seedVar.set(prev.last + (seedVar.mode === '+' ? 1 : -1))
714
1396
  }
715
1397
  }
716
1398
  this.seedState.set(stateKey, { last: seedVar.value, draftBase: draftValue })
@@ -721,15 +1403,25 @@ export class ServeApp {
721
1403
  // latent frames feed the web ui's /run/<module>/preview poll (ExecSt's pattern);
722
1404
  // the previous run's preview must not linger over the new one
723
1405
  this.latentPreviews.delete(mod.key)
724
- this.wireLatents(mod.dw.host)
1406
+ // the host the run ACTUALLY goes to: onLatentPreview is one slot per ComfyHost, so
1407
+ // wiring the defining host while running on an override left the override host with no
1408
+ // dispatcher, the panel simply never saw a frame, with nothing to say why
1409
+ const runHost = this.runHostFor(mod)
1410
+ this.wireLatents(runHost ?? mod.dw.host)
725
1411
  try {
726
- return { execution: await this.starter(mod) }
1412
+ return {
1413
+ execution: await this.starter(mod, {
1414
+ saveToDisk: this.settings.saveToDisk,
1415
+ savePrefix: this.savePrefixFor(mod.key),
1416
+ host: runHost ?? undefined,
1417
+ }),
1418
+ }
727
1419
  } catch (e) {
728
1420
  // name, not instanceof: same two-copies problem as the var classes
729
1421
  if (e instanceof Error && e.name === 'ImageVarEmptyError') return { status: 400, error: e.message }
730
1422
  // the ComfyUI host is upstream of this bridge: 502, not "serve crashed".
731
1423
  // The connect deadline (ConnectOptions.timeoutMs) is what makes this
732
- // reachable at all — it used to hang here and block the module mutex
1424
+ // this runs inside the module mutex: a url that never answers would hold it
733
1425
  if (e instanceof Error && e.name === 'ComfyHostUnreachableError') return { status: 502, error: e.message }
734
1426
  return { status: 500, error: extractErrorMessage(e) }
735
1427
  }
@@ -748,9 +1440,31 @@ export class ServeApp {
748
1440
 
749
1441
  /** payload image urls land as local files under outputs/serve-inputs/ */
750
1442
  private async downloadInput(url: string): Promise<string> {
751
- const res = await fetch(url)
752
- if (!res.ok) throw new Error(`download failed (http ${res.status}): ${url}`)
753
- const bytes = new Uint8Array(await res.arrayBuffer())
1443
+ // every failure below answers the SAME thing. Refused, DNS miss, 403 and 200-of-the-wrong
1444
+ // -type were four distinguishable replies, which is a port and host scanner for anything
1445
+ // this box can reach. The reason goes to the server log
1446
+ try {
1447
+ return await this.fetchInput(url)
1448
+ } catch (e) {
1449
+ if (!(e instanceof DownloadRefused)) console.error(`[serve] input download failed: ${url}:`, e)
1450
+ throw new DownloadRefused(url)
1451
+ }
1452
+ }
1453
+
1454
+ private async fetchInput(url: string): Promise<string> {
1455
+ // a timeout, because this runs INSIDE the module mutex: a url that accepts the connection
1456
+ // and then trickles would wedge that workflow's queue for as long as it liked
1457
+ const res = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(INPUT_DOWNLOAD_TIMEOUT_MS) })
1458
+ // the upstream STATUS is not reported back: reflecting it turns an image var into a port
1459
+ // and route scanner for everything this box can reach (loopback, tailnet, metadata
1460
+ // endpoints). The caller learns the fetch failed, not what answered
1461
+ if (!res.ok) {
1462
+ console.error(`[serve] input download failed (http ${res.status}): ${url}`)
1463
+ throw new DownloadRefused(url)
1464
+ }
1465
+ const declared = Number(res.headers.get('content-length') ?? '0')
1466
+ if (declared > INPUT_DOWNLOAD_CAP) throw new Error(`download too large (${declared} bytes): ${url}`)
1467
+ const bytes = await readCapped(res, INPUT_DOWNLOAD_CAP, url)
754
1468
  const name = basename(new URL(url).pathname) || 'input'
755
1469
  const abs = join(this.outputRoot, 'serve-inputs', `${nanoid(6)}-${name}`)
756
1470
  mkdirSync(dirname(abs), { recursive: true })