comfy-ts 2.11.0 → 2.12.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 (99) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-qtFzOKpu.js → LogsSt-U1H0mP1m.js} +35 -5
  3. package/dist/LogsSt-U1H0mP1m.js.map +1 -0
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +473 -62
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +191 -31
  8. package/dist/index.d.ts +191 -31
  9. package/dist/index.js +469 -63
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-BK7BA2dn.js → run-serve-BeAznay5.js} +461 -43
  12. package/dist/run-serve-BeAznay5.js.map +1 -0
  13. package/dist/{run-tui-CQyvMf0N.js → run-tui-BTGjvnKk.js} +43 -18
  14. package/dist/run-tui-BTGjvnKk.js.map +1 -0
  15. package/dist/{schemaDrift-DjjEtwfx.js → schemaDrift-Cg39vs53.js} +470 -60
  16. package/dist/schemaDrift-Cg39vs53.js.map +1 -0
  17. package/dist/serve-web.js +508 -134
  18. package/dist/{state--wrz0BQc.js → state-C7REnHan.js} +7 -3
  19. package/dist/{state--wrz0BQc.js.map → state-C7REnHan.js.map} +1 -1
  20. package/dist/web.d.ts +191 -31
  21. package/dist/web.js +469 -63
  22. package/dist/web.js.map +1 -1
  23. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  24. package/examples/rvion/10-anima-t2i.cflow.ts +229 -0
  25. package/extra/README.md +4 -0
  26. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  27. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  28. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  29. package/package.json +15 -7
  30. package/src/cli/draftMeta.ts +39 -0
  31. package/src/cli/serve/ServeApp.ts +148 -12
  32. package/src/cli/serve/applyVarPayload.ts +50 -22
  33. package/src/cli/serve/describeVar.ts +42 -6
  34. package/src/cli/serve/llmConfigShape.ts +51 -0
  35. package/src/cli/serve/llmConfigs.ts +52 -0
  36. package/src/cli/serve/tagList.ts +92 -0
  37. package/src/cli/serve/tagSource.ts +69 -0
  38. package/src/cli/serve/web/api.ts +48 -0
  39. package/src/cli/serve/web/components/App.tsx +336 -44
  40. package/src/cli/serve/web/components/Gallery.tsx +105 -28
  41. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  42. package/src/cli/serve/web/components/Icon.tsx +18 -2
  43. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  44. package/src/cli/serve/web/components/Omnibox.tsx +85 -0
  45. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  46. package/src/cli/serve/web/components/TooltipLayer.tsx +45 -0
  47. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  48. package/src/cli/serve/web/components/VarsForm.tsx +341 -188
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  50. package/src/cli/serve/web/components/controls/LorasControl.tsx +644 -317
  51. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  52. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  53. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  54. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  55. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  56. package/src/cli/serve/web/components/modKey.ts +2 -0
  57. package/src/cli/serve/web/llm.ts +23 -12
  58. package/src/cli/serve/web/promptEditor/promptExtensions.ts +281 -0
  59. package/src/cli/serve/web/state/EnhancerSt.ts +415 -100
  60. package/src/cli/serve/web/state/FormSt.ts +193 -29
  61. package/src/cli/serve/web/state/OmniboxSt.ts +57 -0
  62. package/src/cli/serve/web/state/WebSt.ts +219 -74
  63. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  64. package/src/cli/serve/web/state/generateButton.ts +16 -0
  65. package/src/cli/serve/web/state/history.ts +54 -0
  66. package/src/cli/serve/web/state/host.ts +5 -2
  67. package/src/cli/serve/web/state/keptLines.ts +53 -0
  68. package/src/cli/serve/web/state/latentMode.ts +20 -0
  69. package/src/cli/serve/web/state/loraSort.ts +18 -0
  70. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  71. package/src/cli/serve/web/state/omnibox.ts +69 -0
  72. package/src/cli/serve/web/state/payload.ts +38 -58
  73. package/src/cli/serve/web/state/shortcuts.ts +54 -0
  74. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  75. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  76. package/src/cli/serve/web/state/varGroups.ts +24 -0
  77. package/src/cli/serve/web/styles.ts +457 -118
  78. package/src/cli/serve/webBundle.ts +54 -10
  79. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  80. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  81. package/src/cli/tui/state/DraftsSt.ts +18 -2
  82. package/src/cli/tui/state/EditorSt.ts +1 -1
  83. package/src/cli/tui/state/LorasSt.ts +1 -1
  84. package/src/cli/tui/state/PickerSt.ts +25 -7
  85. package/src/cli/tui/state/SettingsSt.ts +1 -1
  86. package/src/cli/tui/state/TuiSt.ts +10 -0
  87. package/src/coreExports.ts +20 -0
  88. package/src/host/loraInfoCache.ts +6 -0
  89. package/src/state.ts +5 -0
  90. package/src/vars/ComfyVars.ts +337 -67
  91. package/src/vars/DefinedWorkflow.ts +40 -19
  92. package/src/vars/lanes.ts +238 -0
  93. package/src/vars/loraEntry.ts +101 -0
  94. package/src/vars/promptSyntax.ts +382 -0
  95. package/dist/LogsSt-qtFzOKpu.js.map +0 -1
  96. package/dist/run-serve-BK7BA2dn.js.map +0 -1
  97. package/dist/run-tui-CQyvMf0N.js.map +0 -1
  98. package/dist/schemaDrift-DjjEtwfx.js.map +0 -1
  99. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -18,7 +18,11 @@ import { basename, dirname, extname, join, resolve } from 'pathe'
18
18
  import { applyVarPayload } from 'src/cli/serve/applyVarPayload.ts'
19
19
  import { describeVar, type VarDescriptor } from 'src/cli/serve/describeVar.ts'
20
20
  import { deletePromptEnhancer, listPromptEnhancers, writePromptEnhancer } from 'src/promptEnhancers.ts'
21
+ import { deleteLlmConfig, listLlmConfigs, writeLlmConfig } from 'src/cli/serve/llmConfigs.ts'
22
+ import { normalizeLlmConfig } from 'src/cli/serve/llmConfigShape.ts'
23
+ import { ENHANCE_KEY, isDraftMetaKey } from 'src/cli/draftMeta.ts'
21
24
  import { managerOnlyLoraOptions } from 'src/cli/serve/managerOnlyLoras.ts'
25
+ import { resolveTagSource, TagSources } from 'src/cli/serve/tagSource.ts'
22
26
  import { FAVICON_DATA_URI } from 'src/cli/serve/favicon.ts'
23
27
  import { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'
24
28
  import { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'
@@ -33,6 +37,7 @@ import {
33
37
  recordCivitaiMiss,
34
38
  getLoraDisplayName,
35
39
  getLoraInfo,
40
+ lorasMissingFromMirror,
36
41
  getLoraPreviewUrl,
37
42
  getLoraTriggerWords,
38
43
  refreshLoraInfoCacheIfChanged,
@@ -160,6 +165,9 @@ class DownloadRefused extends Error {
160
165
 
161
166
  const INPUT_DOWNLOAD_CAP = 50_000_000
162
167
  const INPUT_DOWNLOAD_TIMEOUT_MS = 60_000
168
+ /** the danbooru list is ~3.5 MB; ten times that is still a tag list, beyond is a wrong url */
169
+ const TAG_LIST_CAP = 40_000_000
170
+ const TAG_LIST_TIMEOUT_MS = 120_000
163
171
 
164
172
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
165
173
  * whole body first, so a chunked reply with no content-length could exhaust the process before
@@ -257,10 +265,12 @@ const USAGE = [
257
265
  'GET /drafts/<module>/<draft> — one draft with its stored values',
258
266
  'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
259
267
  'POST /generate/<draft> — unqualified, when unambiguous',
268
+ 'POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run',
260
269
  'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
261
270
  'DELETE /drafts/<module>/<draft> — delete that draft file',
262
271
  'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
263
272
  'POST /upload with {"name","dataBase64"} — store a browser file for an image var',
273
+ 'GET /tags/<module>/<var>?q=<text>&limit=<n> — tag completion from the list a prompt var declares (`tags`)',
264
274
  'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',
265
275
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
266
276
  'POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror',
@@ -268,6 +278,8 @@ const USAGE = [
268
278
  'GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)',
269
279
  'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',
270
280
  'PUT /prompt-enhancers/<name> with {"text"} — write one · DELETE /prompt-enhancers/<name> — remove it',
281
+ 'GET /llm-configs — the enhancer LLM configs (.comfy-ts/llm-configs/*.json)',
282
+ 'PUT /llm-configs/<name> with {provider, baseUrl, model, effort, thinkingOnly} · DELETE /llm-configs/<name>',
271
283
  'GET /settings — { saveToDisk } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory',
272
284
  'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
273
285
  'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',
@@ -312,8 +324,6 @@ export class ServeApp {
312
324
  private seedState = new Map<string, { last: number; draftBase: number }>()
313
325
  /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
314
326
  private chains = new Map<string, Promise<unknown>>()
315
- /** the bundle is built at most once per process, first browser hit pays it */
316
- private webJsCache: Promise<string | null> | null = null
317
327
  /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can
318
328
  * be constructed before a comfyts instance is registered, and reading the file then would
319
329
  * throw at construction time */
@@ -335,7 +345,8 @@ export class ServeApp {
335
345
  starter?: ServeStarter
336
346
  outputRoot?: string
337
347
  loadErrors?: Record<string, string>
338
- /** web ui bundle provider (run-serve wires loadOrBuildWebJs); absent = api only */
348
+ /** web ui bundle provider (run-serve wires loadOrBuildWebJs), called on every page load
349
+ * and owning its own cache; absent = api only */
339
350
  webJs?: () => Promise<string | null>
340
351
  } = {},
341
352
  ) {
@@ -364,8 +375,7 @@ export class ServeApp {
364
375
  // the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is
365
376
  // a blank dark page, the json index is a usable answer
366
377
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {
367
- this.webJsCache ??= this.opts.webJs()
368
- const js = await this.webJsCache
378
+ const js = await this.opts.webJs()
369
379
  if (js != null)
370
380
  return {
371
381
  status: 200,
@@ -388,6 +398,9 @@ export class ServeApp {
388
398
  if (segs[0] === 'lora-about' && segs.length === 3 && segs[1] != null && segs[2] != null)
389
399
  return await this.replyLoraAbout(segs[1], segs[2])
390
400
  if (segs[0] === 'prompt-enhancers' && segs.length === 1) return this.replyPromptEnhancers()
401
+ if (segs[0] === 'llm-configs' && segs.length === 1) return this.replyLlmConfigs()
402
+ if (segs[0] === 'tags' && segs.length === 3 && segs[1] != null && segs[2] != null)
403
+ return await this.replyTags(segs[1], segs[2], req.url)
391
404
  if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()
392
405
  if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()
393
406
  if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')
@@ -406,6 +419,8 @@ export class ServeApp {
406
419
  if ('error' in target) return json(target.status, { error: target.error })
407
420
  return await this.generate(target.mod, target.draft, req)
408
421
  }
422
+ if (req.method === 'POST' && segs[0] === 'preview' && segs.length === 2 && segs[1] != null)
423
+ return await this.replyPreview(segs[1], req)
409
424
  if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)
410
425
  if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
411
426
  return await this.replySaveDraft(segs[1], segs[2], req)
@@ -429,6 +444,10 @@ export class ServeApp {
429
444
  return this.replySavePromptEnhancer(segs[1], req)
430
445
  if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
431
446
  return this.replyDeletePromptEnhancer(segs[1])
447
+ if (req.method === 'PUT' && segs[0] === 'llm-configs' && segs.length === 2 && segs[1] != null)
448
+ return this.replySaveLlmConfig(segs[1], req)
449
+ if (req.method === 'DELETE' && segs[0] === 'llm-configs' && segs.length === 2 && segs[1] != null)
450
+ return this.replyDeleteLlmConfig(segs[1])
432
451
  return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
433
452
  } catch (e) {
434
453
  console.error('[serve] request crashed:', e)
@@ -577,6 +596,8 @@ export class ServeApp {
577
596
  (d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,
578
597
  ),
579
598
  vars,
599
+ // the names of the workflow's live previews: the panel asks POST /preview/<module>
600
+ previews: Object.keys(mod.dw.spec.previews ?? {}),
580
601
  }
581
602
  }
582
603
 
@@ -601,6 +622,34 @@ export class ServeApp {
601
622
  return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })
602
623
  }
603
624
 
625
+ /** the workflow's previews for the values the panel holds right now. The vars are SHARED
626
+ * state (a run reads them), so this runs under the module lock: load the values, compute,
627
+ * put the old values back. Nothing is queued, nothing is written */
628
+ private async replyPreview(key: string, req: ServeRequest): Promise<ServeReply> {
629
+ const mod = this.moduleByKey(key)
630
+ if (mod == null) return json(404, { error: `unknown workflow '${key}'` })
631
+ let values: unknown
632
+ try {
633
+ values = JSON.parse(req.body ?? '{}')
634
+ } catch (e) {
635
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
636
+ }
637
+ if (values == null || typeof values !== 'object' || Array.isArray(values))
638
+ return json(400, { error: 'expects { "<var>": value, … }' })
639
+ const incoming = values as Record<string, unknown>
640
+ const previews = await this.exclusive(mod.key, () => {
641
+ const saved = mod.dw.entries().map(([k, v]) => [k, v.toJSON()] as const)
642
+ try {
643
+ for (const [k, v] of mod.dw.entries()) if (k in incoming) v.loadJSON(incoming[k])
644
+ return Promise.resolve(mod.dw.computePreviews())
645
+ } finally {
646
+ const byName = new Map(mod.dw.entries())
647
+ for (const [k, json] of saved) byName.get(k)?.loadJSON(json)
648
+ }
649
+ })
650
+ return json(200, { previews })
651
+ }
652
+
604
653
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
605
654
  private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {
606
655
  const path = this.draftPath(mod, draft)
@@ -624,8 +673,7 @@ export class ServeApp {
624
673
 
625
674
  private async replyWebJs(): Promise<ServeReply> {
626
675
  if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })
627
- this.webJsCache ??= this.opts.webJs()
628
- const js = await this.webJsCache
676
+ const js = await this.opts.webJs()
629
677
  if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })
630
678
  return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }
631
679
  }
@@ -670,7 +718,17 @@ export class ServeApp {
670
718
  return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
671
719
  const values = parsed as Record<string, unknown>
672
720
  const known = new Set(mod.dw.entries().map(([k]) => k))
673
- const unknown = Object.keys(values).filter((k) => !known.has(k))
721
+ // `$enhance` rides beside the values (src/cli/draftMeta.ts): a string map, checked whole
722
+ if (ENHANCE_KEY in values) {
723
+ const raw = values[ENHANCE_KEY]
724
+ const ok =
725
+ raw != null &&
726
+ typeof raw === 'object' &&
727
+ !Array.isArray(raw) &&
728
+ Object.values(raw).every((v) => typeof v === 'string')
729
+ if (!ok) return json(400, { error: `${ENHANCE_KEY} must be { "<prompt var>": "<intent>" }` })
730
+ }
731
+ const unknown = Object.keys(values).filter((k) => !known.has(k) && !isDraftMetaKey(k))
674
732
  if (unknown.length > 0)
675
733
  return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })
676
734
  // values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —
@@ -746,9 +804,18 @@ export class ServeApp {
746
804
  if (action === 'refresh-loras') return await this.refreshLoraMirror(hostId, host)
747
805
  if (action === 'refresh-schema') {
748
806
  await host.fetchAndUpdateSchema()
749
- // a lora var resolves its regex against the schema ONCE, at define time, so a
750
- // refetch alone left every var on the list it was born with and the panel kept
751
- // warning about a lora the host had just learned. rebinding re-runs that resolve
807
+ // the ONE refresh re-reads the lora manager's list too, BEFORE the rebind reads it:
808
+ // a lora the host just learned gets its name, preview and trigger words in the same
809
+ // pass. A host without the extension, or one that fails the sweep, keeps its old
810
+ // list and the note says so; the schema refetch itself still stands
811
+ const unmirrored = lorasMissingFromMirror(host.schema.getLoras(), (n) => getLoraInfo(n, hostId) != null)
812
+ const synced = await this.refreshLoraMirror(hostId, host)
813
+ const lorasNote =
814
+ synced.status === 200
815
+ ? unmirrored.length > 0
816
+ ? `, lora list re-read (${unmirrored.length} new)`
817
+ : ', lora list re-read'
818
+ : ', the lora manager list could not be re-read'
752
819
  const rebound = await this.rebindHostVars(hostId, host)
753
820
  const nodes = host.schema.nodes.length
754
821
  const loras = host.schema.getLoras().length
@@ -761,7 +828,7 @@ export class ServeApp {
761
828
  host: hostId,
762
829
  action,
763
830
  stale: rebound.stale,
764
- note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}. no restart needed`,
831
+ note: `schema refetched: ${nodes} node types, ${loras} loras, ${rebound.widened} lora var(s) changed${dropped}${lorasNote}`,
765
832
  })
766
833
  }
767
834
  if (action === 'restart') {
@@ -1073,6 +1140,35 @@ export class ServeApp {
1073
1140
 
1074
1141
  // #region prompt enhancers (the web ui's master prompts, as .md files) ------
1075
1142
  /** the folder is seeded on the first read, so `refine-krea2-prompt.md` exists to be edited */
1143
+ /** tag lists by source, loaded on the first query and kept for the process */
1144
+ private tagSources = new TagSources({
1145
+ cacheDir: () => join(comfyts.baseFolder, 'cache', 'tags'),
1146
+ fetchText: async (url) => {
1147
+ const res = await fetch(url, { redirect: 'follow', signal: AbortSignal.timeout(TAG_LIST_TIMEOUT_MS) })
1148
+ if (!res.ok) throw new Error(`tag list download failed (http ${res.status}): ${url}`)
1149
+ return new TextDecoder().decode(await readCapped(res, TAG_LIST_CAP, url))
1150
+ },
1151
+ })
1152
+
1153
+ private async replyTags(modKey: string, varName: string, url: string): Promise<ServeReply> {
1154
+ const mod = this.moduleByKey(modKey)
1155
+ if (mod == null) return json(404, { error: `unknown workflow '${modKey}'` })
1156
+ const found = mod.dw.entries().find(([k]) => k === varName)?.[1]
1157
+ if (found == null) return json(404, { error: `workflow '${modKey}' has no var '${varName}'` })
1158
+ // cast: whitelist family 6, narrowed by kind
1159
+ const tags = found.kind === 'prompt' ? (found as PromptVar).tags : null
1160
+ if (tags == null) return json(404, { error: `var '${varName}' declares no tag list (v.prompt(…, { tags }))` })
1161
+ const params = new URLSearchParams(url.split('?')[1] ?? '')
1162
+ const limit = Math.min(100, Math.max(1, Number(params.get('limit') ?? '20') || 20))
1163
+ try {
1164
+ const list = await this.tagSources.load(resolveTagSource(tags.url, mod.file))
1165
+ return json(200, { hits: list.search(params.get('q') ?? '', limit) })
1166
+ } catch (e) {
1167
+ console.error(`[serve] 🔴 tag list for ${modKey}/${varName}: ${extractErrorMessage(e)}`)
1168
+ return json(502, { error: extractErrorMessage(e) })
1169
+ }
1170
+ }
1171
+
1076
1172
  private replyPromptEnhancers(): ServeReply {
1077
1173
  try {
1078
1174
  return json(200, { enhancers: listPromptEnhancers() })
@@ -1115,6 +1211,46 @@ export class ServeApp {
1115
1211
  return json(200, { ok: true, name, enhancers: listPromptEnhancers() })
1116
1212
  }
1117
1213
 
1214
+ private replyLlmConfigs(): ServeReply {
1215
+ try {
1216
+ return json(200, { configs: listLlmConfigs() })
1217
+ } catch (e) {
1218
+ return json(500, { error: `llm-configs folder unreadable: ${extractErrorMessage(e)}` })
1219
+ }
1220
+ }
1221
+
1222
+ private replySaveLlmConfig(rawName: string, req: ServeRequest): ServeReply {
1223
+ const name = validStoreName(rawName)
1224
+ if (name == null)
1225
+ return json(400, { error: `invalid config name '${rawName}' — letters/digits then letters, digits, ". -_"` })
1226
+ let parsed: unknown
1227
+ try {
1228
+ parsed = JSON.parse(req.body ?? '')
1229
+ } catch (e) {
1230
+ return json(400, { error: `body is not valid json: ${extractErrorMessage(e)}` })
1231
+ }
1232
+ if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed))
1233
+ return json(400, { error: 'body must be { provider, baseUrl, model, effort, thinkingOnly }' })
1234
+ try {
1235
+ writeLlmConfig(name, normalizeLlmConfig(parsed))
1236
+ } catch (e) {
1237
+ return json(500, { error: `could not write llm config '${name}': ${extractErrorMessage(e)}` })
1238
+ }
1239
+ return json(200, { ok: true, name, configs: listLlmConfigs() })
1240
+ }
1241
+
1242
+ private replyDeleteLlmConfig(rawName: string): ServeReply {
1243
+ const name = validStoreName(rawName)
1244
+ if (name == null) return json(400, { error: `invalid config name '${rawName}'` })
1245
+ try {
1246
+ deleteLlmConfig(name)
1247
+ } catch (e) {
1248
+ return json(500, { error: `could not delete llm config '${name}': ${extractErrorMessage(e)}` })
1249
+ }
1250
+ console.log(`[serve] llm config deleted: ${name}`)
1251
+ return json(200, { ok: true, name, configs: listLlmConfigs() })
1252
+ }
1253
+
1118
1254
  // #region live run state (web ui polling: progress + latent preview) --------
1119
1255
  private liveRuns = new Map<string, ServeExecution>()
1120
1256
  /** seq counts frames so the poller refetches only on a NEW one, not every tick */
@@ -9,11 +9,10 @@
9
9
  // below are the sanctioned kind-narrowing family (agent/coding.md cast whitelist 6).
10
10
  import type {
11
11
  AnyVar,
12
- ChoiceVar,
12
+ AnyChoiceVar,
13
13
  FloatVar,
14
14
  ImageVar,
15
15
  IntVar,
16
- LoraStrength,
17
16
  LorasVar,
18
17
  PromptVar,
19
18
  SeedVar,
@@ -21,17 +20,13 @@ import type {
21
20
  TextVar,
22
21
  ToggleVar,
23
22
  } from 'src/vars/ComfyVars.ts'
23
+ import { isLoraLanes, isLorasInput, isPromptInput } from 'src/vars/lanes.ts'
24
+ import { isLoraStrength } from 'src/vars/loraEntry.ts'
24
25
 
25
26
  function isFiniteNumber(x: unknown): x is number {
26
27
  return typeof x === 'number' && Number.isFinite(x)
27
28
  }
28
29
 
29
- function isLoraStrength(x: unknown): x is LoraStrength {
30
- if (typeof x === 'boolean') return true
31
- if (isFiniteNumber(x)) return true
32
- return Array.isArray(x) && x.length === 2 && isFiniteNumber(x[0]) && isFiniteNumber(x[1])
33
- }
34
-
35
30
  /** cap long option lists in error messages */
36
31
  function listSome(items: readonly string[], cap: number = 20): string {
37
32
  if (items.length <= cap) return items.join(', ')
@@ -49,10 +44,16 @@ export function applyVarPayload(
49
44
  const name = varDef.name ?? varDef.label ?? varDef.kind
50
45
 
51
46
  switch (varDef.kind) {
52
- case 'text':
53
- case 'prompt': {
47
+ case 'text': {
54
48
  if (typeof raw !== 'string') return `var '${name}' expects a string`
55
- ;(varDef as TextVar | PromptVar).set(raw)
49
+ ;(varDef as TextVar).set(raw)
50
+ return null
51
+ }
52
+
53
+ case 'prompt': {
54
+ if (!isPromptInput(raw))
55
+ return `var '${name}' expects a string or {"lanes": [{"name": string, "prompt": string, "active": boolean}]}`
56
+ ;(varDef as PromptVar).set(raw)
56
57
  return null
57
58
  }
58
59
 
@@ -97,23 +98,50 @@ export function applyVarPayload(
97
98
  }
98
99
 
99
100
  case 'choice': {
100
- const v = varDef as ChoiceVar<string>
101
- if (typeof raw === 'string' && v.parse(raw)) return null
101
+ const v = varDef as AnyChoiceVar<string>
102
+ const known = (x: unknown): x is string => typeof x === 'string' && v.choices.includes(x)
103
+ if (v.select === 'many') {
104
+ // one value is a list of one: a tab or a draft from when this was a single choice
105
+ if (known(raw)) {
106
+ v.set([raw])
107
+ return null
108
+ }
109
+ if (Array.isArray(raw) && raw.every(known)) {
110
+ v.set(v.choices.filter((c) => raw.includes(c)))
111
+ return null
112
+ }
113
+ return `var '${name}' expects a list of: ${listSome(v.choices)}`
114
+ }
115
+ if (v.select === 'zero-or-one') {
116
+ if (raw === null || known(raw)) {
117
+ v.set(raw)
118
+ return null
119
+ }
120
+ return `var '${name}' expects null or one of: ${listSome(v.choices)}`
121
+ }
122
+ if (known(raw)) {
123
+ v.set(raw)
124
+ return null
125
+ }
102
126
  return `var '${name}' expects one of: ${listSome(v.choices)}`
103
127
  }
104
128
 
105
129
  case 'loras': {
106
130
  const v = varDef as LorasVar<string>
107
- if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
108
- return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
109
- const record = raw as Record<string, unknown>
131
+ const SHAPE = `{"<lora name>": false | true | strength | [model, clip] | {strength, off?, mute?}} or {"lanes": [{"name", "active", "loras": {…}}]}`
132
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return `var '${name}' expects ${SHAPE}`
133
+ const records = isLoraLanes(raw) ? raw.lanes.map((l) => l.loras) : [raw as Record<string, unknown>]
110
134
  const known = new Set<string>([...v.options, ...(opts.extraLoraOptions ?? [])])
111
- const unknownNames = Object.keys(record).filter((k) => !known.has(k))
112
- if (unknownNames.length > 0)
113
- return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome([...known])}`
114
- for (const [k, st] of Object.entries(record))
115
- if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
116
- v.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
135
+ for (const record of records) {
136
+ const unknownNames = Object.keys(record).filter((k) => !known.has(k))
137
+ if (unknownNames.length > 0)
138
+ return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome([...known])}`
139
+ for (const [k, st] of Object.entries(record))
140
+ if (!isLoraStrength(st))
141
+ return `var '${name}': '${k}' must be false | true | number | [model, clip] | { strength: [model, clip], off?, mute? }`
142
+ }
143
+ if (!isLorasInput(raw)) return `var '${name}' expects ${SHAPE}`
144
+ v.set(raw) // every lane and entry validated just above
117
145
  return null
118
146
  }
119
147
 
@@ -3,7 +3,8 @@
3
3
  import { ansi } from 'src/utils/ansi.ts'
4
4
  import type {
5
5
  AnyVar,
6
- ChoiceVar,
6
+ AnyChoiceVar,
7
+ ChoiceSelect,
7
8
  FloatVar,
8
9
  ImageVar,
9
10
  IntVar,
@@ -14,6 +15,7 @@ import type {
14
15
  SizeVar,
15
16
  TextVar,
16
17
  VarKind,
18
+ VarUi,
17
19
  } from 'src/vars/ComfyVars.ts'
18
20
  import type { VarPreset } from 'src/vars/presets.ts'
19
21
  import type { LoraTriggers } from 'src/host/loraInfoCache.ts'
@@ -24,6 +26,10 @@ export type VarDescriptor = {
24
26
  /** what a POST payload accepts for this var, human-readable */
25
27
  payload: string
26
28
  default: unknown
29
+ /** choice vars: exactly one, one or none (value may be null), or many (value is a list) */
30
+ select?: ChoiceSelect
31
+ /** how the workflow wants this var to look (VarUi): icon, colors, description */
32
+ ui?: VarUi
27
33
  choices?: readonly string[]
28
34
  /** loras: the resolved option list */
29
35
  options?: readonly string[]
@@ -48,6 +54,11 @@ export type VarDescriptor = {
48
54
  /** loras: trigger words per option as the mirror knows them (words, fetched and empty, or
49
55
  * civitai never asked). An option ABSENT from this record is not in the mirror at all */
50
56
  optionTriggers?: Record<string, LoraTriggers>
57
+ /** prompt: tag completion is on (`v.prompt(…, { tags })`), with the insert rules. The list
58
+ * itself stays on the server: the editor asks `GET /tags/<module>/<var>?q=` */
59
+ tags?: { underscores: boolean; artistPrefix?: string }
60
+ /** prompt: false when the model ignores `(text:1.2)` weights */
61
+ weights?: false
51
62
  /** text: this one wants a box, not a line (`v.text(…, { multiline: true })`) */
52
63
  multiline?: boolean
53
64
  /** text + prompt: named starting texts (`{ presets: { label: text } }`). NOT `presets`, which
@@ -56,6 +67,8 @@ export type VarDescriptor = {
56
67
  min?: number
57
68
  max?: number
58
69
  presets?: SizePreset[]
70
+ /** size: preset labels starred by default (quick buttons before the list) */
71
+ starredPresets?: string[]
59
72
  extensions?: readonly string[]
60
73
  }
61
74
 
@@ -70,7 +83,13 @@ function rangeText(opts: { min?: number; max?: number }): string {
70
83
  }
71
84
 
72
85
  export function describeVar(varDef: AnyVar): VarDescriptor {
73
- const base = { kind: varDef.kind, label: varDef.label, default: varDef.defaultValue }
86
+ const base = {
87
+ kind: varDef.kind,
88
+ label: varDef.label,
89
+ default: varDef.defaultValue,
90
+ // absent unless the workflow set something: most vars carry no looks
91
+ ...(Object.keys(varDef.uiOpts).length > 0 ? { ui: varDef.uiOpts } : {}),
92
+ }
74
93
  // kind, never instanceof: the cli bundle and the consumer's `comfy-ts` import hold
75
94
  // different copies of every class (VarKind owns the WHY). Casts are the sanctioned
76
95
  // kind-narrowing family (agent/coding.md cast whitelist 6)
@@ -79,8 +98,13 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
79
98
  const v = varDef as PromptVar
80
99
  return {
81
100
  ...base,
82
- payload: 'string ("//" lines = comments, "- " lines = negative)',
101
+ payload: 'string ("//" starts a comment, "- " lines = negative)',
83
102
  textPresets: presetsOrUndefined(v.presets),
103
+ tags:
104
+ v.tags == null
105
+ ? undefined
106
+ : { underscores: v.tags.underscores === true, artistPrefix: v.tags.artistPrefix },
107
+ weights: v.promptOpts.weights === false ? false : undefined,
84
108
  }
85
109
  }
86
110
  case 'text': {
@@ -109,8 +133,15 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
109
133
  case 'toggle':
110
134
  return { ...base, payload: 'true or false' }
111
135
  case 'choice': {
112
- const v = varDef as ChoiceVar<string>
113
- return { ...base, payload: `one of: ${v.choices.join(' | ')}`, choices: v.choices }
136
+ const v = varDef as AnyChoiceVar<string>
137
+ const list = v.choices.join(' | ')
138
+ const payload =
139
+ v.select === 'many'
140
+ ? `a list of: ${list}`
141
+ : v.select === 'zero-or-one'
142
+ ? `null or one of: ${list}`
143
+ : `one of: ${list}`
144
+ return { ...base, payload, choices: v.choices, select: v.select }
114
145
  }
115
146
  case 'loras': {
116
147
  const v = varDef as LorasVar<string>
@@ -124,7 +155,12 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
124
155
  }
125
156
  case 'size': {
126
157
  const v = varDef as SizeVar
127
- return { ...base, payload: '{"width":W,"height":H} or "WxH" or a preset label', presets: v.presets }
158
+ return {
159
+ ...base,
160
+ payload: '{"width":W,"height":H} or "WxH" or a preset label',
161
+ presets: v.presets,
162
+ starredPresets: [...v.starred],
163
+ }
128
164
  }
129
165
  case 'image': {
130
166
  const v = varDef as ImageVar
@@ -0,0 +1,51 @@
1
+ // one LLM config of the prompt enhancer: where the model runs and how it is asked. PURE (the
2
+ // browser bundle and serve both read it), every field runtime-checked, since the file is
3
+ // hand-editable. No api key here: keys stay in the browser (architecture item 13)
4
+ import { defaultBaseUrl, type ProviderId, type ReasoningEffort } from 'src/cli/serve/web/llm.ts'
5
+
6
+ export type LlmConfig = {
7
+ provider: ProviderId
8
+ baseUrl: string
9
+ model: string
10
+ effort: ReasoningEffort
11
+ /** hide models that report no reasoning support */
12
+ thinkingOnly: boolean
13
+ }
14
+
15
+ export type LlmConfigEntry = { name: string; config: LlmConfig }
16
+
17
+ export function isProvider(raw: unknown): raw is ProviderId {
18
+ return raw === 'openrouter' || raw === 'openwebui' || raw === 'openai'
19
+ }
20
+
21
+ export function isEffort(raw: unknown): raw is ReasoningEffort {
22
+ return raw === 'off' || raw === 'low' || raw === 'medium' || raw === 'high'
23
+ }
24
+
25
+ /** explicit model ids, never an alias: behaviour and cost stay reproducible */
26
+ const DEFAULT_MODEL: Record<ProviderId, string> = {
27
+ openrouter: 'anthropic/claude-sonnet-5',
28
+ openwebui: '',
29
+ openai: '',
30
+ }
31
+
32
+ /** a stored file → a usable config: a half-written or hand-broken field degrades to its
33
+ * default, never breaks the modal */
34
+ export function normalizeLlmConfig(raw: unknown): LlmConfig {
35
+ const o = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {}
36
+ const provider = isProvider(o.provider) ? o.provider : 'openrouter'
37
+ return {
38
+ provider,
39
+ baseUrl: typeof o.baseUrl === 'string' && o.baseUrl.trim() !== '' ? o.baseUrl.trim() : defaultBaseUrl(provider),
40
+ model: typeof o.model === 'string' ? o.model : DEFAULT_MODEL[provider],
41
+ effort: isEffort(o.effort) ? o.effort : 'medium',
42
+ thinkingOnly: o.thinkingOnly !== false,
43
+ }
44
+ }
45
+
46
+ /** switching provider resets what belongs to the old one: an openrouter model id sent to a
47
+ * local box, or a local base url sent to openrouter, is never what anyone means */
48
+ export function withProvider(c: LlmConfig, provider: ProviderId): LlmConfig {
49
+ if (provider === c.provider) return c
50
+ return { ...c, provider, baseUrl: defaultBaseUrl(provider), model: DEFAULT_MODEL[provider] }
51
+ }
@@ -0,0 +1,52 @@
1
+ // the prompt enhancer's LLM configs as FILES: `.comfy-ts/llm-configs/<name>.json`, the drafts
2
+ // model. The FILENAME is the identity (a rename is a write plus a delete), validStoreName is the
3
+ // same gate the draft routes use. SERVE-ONLY: no workflow reads these
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
5
+ import { join } from 'pathe'
6
+ import { normalizeLlmConfig, type LlmConfig, type LlmConfigEntry } from 'src/cli/serve/llmConfigShape.ts'
7
+ import { validStoreName } from 'src/utils/safeName.ts'
8
+
9
+ const EXT = '.json'
10
+
11
+ export function llmConfigsDir(): string {
12
+ return comfyts.resolveFromLlmConfigs('')
13
+ }
14
+
15
+ function llmConfigPath(name: string): string | null {
16
+ const safe = validStoreName(name)
17
+ return safe == null ? null : join(llmConfigsDir(), `${safe}${EXT}`)
18
+ }
19
+
20
+ export function listLlmConfigs(): LlmConfigEntry[] {
21
+ const dir = llmConfigsDir()
22
+ if (!existsSync(dir)) return []
23
+ const out: LlmConfigEntry[] = []
24
+ for (const file of readdirSync(dir).sort()) {
25
+ if (!file.endsWith(EXT)) continue
26
+ const name = file.slice(0, -EXT.length)
27
+ if (validStoreName(name) == null) continue
28
+ // one broken file is skipped loudly, the rest still list
29
+ try {
30
+ out.push({ name, config: normalizeLlmConfig(JSON.parse(readFileSync(join(dir, file), 'utf8'))) })
31
+ } catch (e) {
32
+ console.error(`[serve] llm config '${name}' unreadable, skipped:`, e)
33
+ }
34
+ }
35
+ return out
36
+ }
37
+
38
+ export function writeLlmConfig(name: string, config: LlmConfig): string | null {
39
+ const path = llmConfigPath(name)
40
+ if (path == null) return null
41
+ mkdirSync(llmConfigsDir(), { recursive: true })
42
+ writeFileSync(path, `${JSON.stringify(normalizeLlmConfig(config), null, 3)}\n`)
43
+ return path
44
+ }
45
+
46
+ /** a missing file is still a success: the caller asked for it to be gone, and it is */
47
+ export function deleteLlmConfig(name: string): boolean {
48
+ const path = llmConfigPath(name)
49
+ if (path == null) return false
50
+ if (existsSync(path)) rmSync(path)
51
+ return true
52
+ }