comfy-ts 2.10.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 (110) hide show
  1. package/README.md +1 -0
  2. package/dist/{LogsSt-DFxzQfDc.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 +565 -62
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +210 -31
  8. package/dist/index.d.ts +210 -31
  9. package/dist/index.js +561 -63
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-_nrvJYyt.js → run-serve-BeAznay5.js} +549 -43
  12. package/dist/run-serve-BeAznay5.js.map +1 -0
  13. package/dist/{run-tui-Atvf9vb3.js → run-tui-BTGjvnKk.js} +75 -18
  14. package/dist/run-tui-BTGjvnKk.js.map +1 -0
  15. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-Cg39vs53.js} +644 -60
  16. package/dist/schemaDrift-Cg39vs53.js.map +1 -0
  17. package/dist/serve-web.js +523 -133
  18. package/dist/{state-6RFDIQwJ.js → state-C7REnHan.js} +18 -3
  19. package/dist/{state-6RFDIQwJ.js.map → state-C7REnHan.js.map} +1 -1
  20. package/dist/web.d.ts +210 -31
  21. package/dist/web.js +561 -63
  22. package/dist/web.js.map +1 -1
  23. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  24. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  26. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  27. package/examples/rvion/06-qwen-image-edit.cflow.ts +3 -2
  28. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  29. package/examples/rvion/10-anima-t2i.cflow.ts +229 -0
  30. package/extra/README.md +4 -0
  31. package/extra/comfyui-fresh-model-lists/README.md +25 -0
  32. package/extra/comfyui-fresh-model-lists/__init__.py +36 -0
  33. package/extra/comfyui-fresh-model-lists/test_fresh_model_lists.py +97 -0
  34. package/package.json +17 -7
  35. package/src/cli/draftMeta.ts +39 -0
  36. package/src/cli/serve/ServeApp.ts +242 -12
  37. package/src/cli/serve/applyVarPayload.ts +50 -22
  38. package/src/cli/serve/describeVar.ts +49 -6
  39. package/src/cli/serve/favicon.ts +3 -0
  40. package/src/cli/serve/llmConfigShape.ts +51 -0
  41. package/src/cli/serve/llmConfigs.ts +52 -0
  42. package/src/cli/serve/tagList.ts +92 -0
  43. package/src/cli/serve/tagSource.ts +69 -0
  44. package/src/cli/serve/web/api.ts +60 -0
  45. package/src/cli/serve/web/components/App.tsx +336 -44
  46. package/src/cli/serve/web/components/Gallery.tsx +105 -28
  47. package/src/cli/serve/web/components/HistoryPicker.tsx +149 -0
  48. package/src/cli/serve/web/components/Icon.tsx +18 -2
  49. package/src/cli/serve/web/components/MenuButton.tsx +53 -0
  50. package/src/cli/serve/web/components/Omnibox.tsx +85 -0
  51. package/src/cli/serve/web/components/PromptEnhancer.tsx +476 -180
  52. package/src/cli/serve/web/components/TooltipLayer.tsx +45 -0
  53. package/src/cli/serve/web/components/VarIcon.tsx +24 -0
  54. package/src/cli/serve/web/components/VarsForm.tsx +341 -177
  55. package/src/cli/serve/web/components/controls/BasicControls.tsx +57 -32
  56. package/src/cli/serve/web/components/controls/LorasControl.tsx +708 -285
  57. package/src/cli/serve/web/components/controls/PresetPicker.tsx +1 -1
  58. package/src/cli/serve/web/components/controls/PromptControl.tsx +279 -0
  59. package/src/cli/serve/web/components/controls/PromptEditor.tsx +113 -0
  60. package/src/cli/serve/web/components/controls/SeedControl.tsx +17 -10
  61. package/src/cli/serve/web/components/controls/SizeControl.tsx +111 -18
  62. package/src/cli/serve/web/components/modKey.ts +2 -0
  63. package/src/cli/serve/web/llm.ts +23 -12
  64. package/src/cli/serve/web/promptEditor/promptExtensions.ts +281 -0
  65. package/src/cli/serve/web/state/EnhancerSt.ts +415 -100
  66. package/src/cli/serve/web/state/FormSt.ts +193 -29
  67. package/src/cli/serve/web/state/OmniboxSt.ts +57 -0
  68. package/src/cli/serve/web/state/WebSt.ts +281 -57
  69. package/src/cli/serve/web/state/choiceButtons.ts +61 -0
  70. package/src/cli/serve/web/state/generateButton.ts +16 -0
  71. package/src/cli/serve/web/state/history.ts +54 -0
  72. package/src/cli/serve/web/state/host.ts +5 -2
  73. package/src/cli/serve/web/state/keptLines.ts +53 -0
  74. package/src/cli/serve/web/state/latentMode.ts +20 -0
  75. package/src/cli/serve/web/state/loraSort.ts +57 -0
  76. package/src/cli/serve/web/state/moduleTree.ts +2 -2
  77. package/src/cli/serve/web/state/omnibox.ts +69 -0
  78. package/src/cli/serve/web/state/payload.ts +38 -58
  79. package/src/cli/serve/web/state/shortcuts.ts +54 -0
  80. package/src/cli/serve/web/state/sizeStars.ts +31 -0
  81. package/src/cli/serve/web/state/stableSlots.ts +21 -0
  82. package/src/cli/serve/web/state/varGroups.ts +24 -0
  83. package/src/cli/serve/web/styles.ts +472 -118
  84. package/src/cli/serve/webBundle.ts +54 -10
  85. package/src/cli/tui/components/Header.tsx +2 -0
  86. package/src/cli/tui/components/PickerOverlays.tsx +9 -2
  87. package/src/cli/tui/imagePicker/ImagePickerSt.ts +1 -1
  88. package/src/cli/tui/state/DraftsSt.ts +18 -2
  89. package/src/cli/tui/state/EditorSt.ts +1 -1
  90. package/src/cli/tui/state/HostSt.ts +34 -0
  91. package/src/cli/tui/state/LorasSt.ts +1 -1
  92. package/src/cli/tui/state/PickerSt.ts +25 -7
  93. package/src/cli/tui/state/SettingsSt.ts +1 -1
  94. package/src/cli/tui/state/TuiSt.ts +10 -0
  95. package/src/coreExports.ts +20 -0
  96. package/src/host/ComfyHost.ts +15 -0
  97. package/src/host/loraInfoCache.ts +70 -0
  98. package/src/host/loraManagerApi.ts +27 -0
  99. package/src/host/schemaDrift.ts +87 -0
  100. package/src/state.ts +5 -0
  101. package/src/vars/ComfyVars.ts +337 -67
  102. package/src/vars/DefinedWorkflow.ts +40 -19
  103. package/src/vars/lanes.ts +238 -0
  104. package/src/vars/loraEntry.ts +101 -0
  105. package/src/vars/promptSyntax.ts +382 -0
  106. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  107. package/dist/LogsSt-DFxzQfDc.js.map +0 -1
  108. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  109. package/dist/run-tui-Atvf9vb3.js.map +0 -1
  110. package/src/cli/serve/web/components/Sidebar.tsx +0 -66
@@ -18,15 +18,26 @@ 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'
26
+ import { FAVICON_DATA_URI } from 'src/cli/serve/favicon.ts'
27
+ import { driftChanged, summarizeDrift } from 'src/host/schemaDrift.ts'
22
28
  import { validSavePrefix, validStoreName } from 'src/utils/safeName.ts'
23
29
  import { readServeSettings, writeServeSettings, type ServeSettings } from 'src/cli/serve/serveSettings.ts'
24
30
  import { assembleLogChunks } from 'src/cli/tui/state/LogsSt.ts'
25
31
  import { draftsDirForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.ts'
26
32
  import {
27
33
  buildLoraMirror,
34
+ getLoraAddedAt,
35
+ getLoraTriggers,
36
+ type LoraTriggers,
37
+ recordCivitaiMiss,
28
38
  getLoraDisplayName,
29
39
  getLoraInfo,
40
+ lorasMissingFromMirror,
30
41
  getLoraPreviewUrl,
31
42
  getLoraTriggerWords,
32
43
  refreshLoraInfoCacheIfChanged,
@@ -34,6 +45,7 @@ import {
34
45
  writeLoraMirror,
35
46
  } from 'src/host/loraInfoCache.ts'
36
47
  import {
48
+ fetchLoraCivitai,
37
49
  fetchLoraDescription,
38
50
  fetchLoraExampleImages,
39
51
  fetchLoraList,
@@ -153,6 +165,9 @@ class DownloadRefused extends Error {
153
165
 
154
166
  const INPUT_DOWNLOAD_CAP = 50_000_000
155
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
156
171
 
157
172
  /** read a reply STREAMING, aborting the moment it passes the cap. `arrayBuffer()` buffers the
158
173
  * whole body first, so a chunked reply with no content-length could exhaust the process before
@@ -250,15 +265,21 @@ const USAGE = [
250
265
  'GET /drafts/<module>/<draft> — one draft with its stored values',
251
266
  'POST /generate/<module>/<draft> with { ...vars } — run, blocking',
252
267
  'POST /generate/<draft> — unqualified, when unambiguous',
268
+ 'POST /preview/<module> with { ...draft values } — the workflow previews for those values, nothing is run',
253
269
  'PUT /drafts/<module>/<draft> with { ...vars } — save (or duplicate to a new name) a draft',
254
270
  'DELETE /drafts/<module>/<draft> — delete that draft file',
255
271
  'GET /run/<module> — live run status · /run/<module>/preview — latent preview bytes',
256
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`)',
274
+ 'GET /hosts/<hostId>/drift[?full=1] — what changed on the host since the schema was loaded (model files; node types with full=1)',
257
275
  'GET /lora-info/<hostId>/<lora> — display name + trigger words (local mirror)',
276
+ 'POST /hosts/<hostId>/lora-civitai/<lora> — fetch its civitai metadata (trigger words) through the lora manager, then re-sync the mirror',
258
277
  'GET /lora-preview/<hostId>/<lora> — preview image bytes',
259
278
  'GET /lora-about/<hostId>/<lora> — civitai description + example images (live from the extension)',
260
279
  'GET /prompt-enhancers — the web ui master prompts (.comfy-ts/prompt-enhancers/*.md)',
261
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>',
262
283
  'GET /settings — { saveToDisk } · PUT /settings with {"saveToDisk"} — write outputs to disk, or keep them in memory',
263
284
  'GET /hosts — every host this process knows · PUT /hosts/<module> with {"host"} — run that workflow elsewhere',
264
285
  'POST /hosts/<hostId>/<interrupt|clear-queue|restart|refresh-loras|refresh-schema> — act on a ComfyUI host',
@@ -284,6 +305,7 @@ const WEB_SHELL = `<!doctype html>
284
305
  <meta charset="utf-8">
285
306
  <meta name="viewport" content="width=device-width, initial-scale=1">
286
307
  <title>comfy-ts serve</title>
308
+ <link rel="icon" type="image/png" href="${FAVICON_DATA_URI}">
287
309
  <style>html{background:#101217;color:#e8eaf0}</style>
288
310
  </head>
289
311
  <body>
@@ -302,8 +324,6 @@ export class ServeApp {
302
324
  private seedState = new Map<string, { last: number; draftBase: number }>()
303
325
  /** per-module promise chain: vars are shared mutable state, apply→send is exclusive */
304
326
  private chains = new Map<string, Promise<unknown>>()
305
- /** the bundle is built at most once per process, first browser hit pays it */
306
- private webJsCache: Promise<string | null> | null = null
307
327
  /** saving + host overrides are live settings (the web ui flips them). LAZY: a ServeApp can
308
328
  * be constructed before a comfyts instance is registered, and reading the file then would
309
329
  * throw at construction time */
@@ -325,7 +345,8 @@ export class ServeApp {
325
345
  starter?: ServeStarter
326
346
  outputRoot?: string
327
347
  loadErrors?: Record<string, string>
328
- /** 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 */
329
350
  webJs?: () => Promise<string | null>
330
351
  } = {},
331
352
  ) {
@@ -354,8 +375,7 @@ export class ServeApp {
354
375
  // the bundle resolves BEFORE the shell ships: a shell whose /web/app.js 404s is
355
376
  // a blank dark page, the json index is a usable answer
356
377
  if (segs.length === 0 && this.opts.webJs != null && req.accept?.includes('text/html') === true) {
357
- this.webJsCache ??= this.opts.webJs()
358
- const js = await this.webJsCache
378
+ const js = await this.opts.webJs()
359
379
  if (js != null)
360
380
  return {
361
381
  status: 200,
@@ -378,12 +398,17 @@ export class ServeApp {
378
398
  if (segs[0] === 'lora-about' && segs.length === 3 && segs[1] != null && segs[2] != null)
379
399
  return await this.replyLoraAbout(segs[1], segs[2])
380
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)
381
404
  if (segs[0] === 'settings' && segs.length === 1) return this.replySettings()
382
405
  if (segs[0] === 'hosts' && segs.length === 1) return this.replyHosts()
383
406
  if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'logs')
384
407
  return await this.replyHostLogs(segs[1])
385
408
  if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'ping')
386
409
  return await this.replyHostPing(segs[1])
410
+ if (segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] === 'drift')
411
+ return await this.replyHostDrift(segs[1], req.url.includes('full=1'))
387
412
  if (segs[0] === 'images' && segs.length === 3 && segs[1] != null && segs[2] != null)
388
413
  return this.replyMemoryImage(`${segs[1]}/${segs[2]}`)
389
414
  if (segs[0] === 'outputs') return this.replyOutput(segs.slice(1))
@@ -394,6 +419,8 @@ export class ServeApp {
394
419
  if ('error' in target) return json(target.status, { error: target.error })
395
420
  return await this.generate(target.mod, target.draft, req)
396
421
  }
422
+ if (req.method === 'POST' && segs[0] === 'preview' && segs.length === 2 && segs[1] != null)
423
+ return await this.replyPreview(segs[1], req)
397
424
  if (req.method === 'POST' && segs[0] === 'upload' && segs.length === 1) return this.replyUpload(req)
398
425
  if (req.method === 'PUT' && segs[0] === 'drafts' && segs.length === 3 && segs[1] != null && segs[2] != null)
399
426
  return await this.replySaveDraft(segs[1], segs[2], req)
@@ -404,10 +431,23 @@ export class ServeApp {
404
431
  return this.replySetHost(segs[1], req)
405
432
  if (req.method === 'POST' && segs[0] === 'hosts' && segs.length === 3 && segs[1] != null && segs[2] != null)
406
433
  return await this.replyHostAction(segs[1], segs[2])
434
+ if (
435
+ req.method === 'POST' &&
436
+ segs[0] === 'hosts' &&
437
+ segs.length === 4 &&
438
+ segs[1] != null &&
439
+ segs[2] === 'lora-civitai' &&
440
+ segs[3] != null
441
+ )
442
+ return await this.replyLoraCivitaiFetch(segs[1], segs[3])
407
443
  if (req.method === 'PUT' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
408
444
  return this.replySavePromptEnhancer(segs[1], req)
409
445
  if (req.method === 'DELETE' && segs[0] === 'prompt-enhancers' && segs.length === 2 && segs[1] != null)
410
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])
411
451
  return json(404, { error: `no route: ${req.method} ${path}`, usage: USAGE })
412
452
  } catch (e) {
413
453
  console.error('[serve] request crashed:', e)
@@ -520,6 +560,18 @@ export class ServeApp {
520
560
  if (kw !== '') keywords[option] = kw
521
561
  }
522
562
  if (Object.keys(keywords).length > 0) desc.optionKeywords = keywords
563
+ const addedAt: Record<string, number> = {}
564
+ for (const option of desc.options) {
565
+ const t = getLoraAddedAt(option, hostId)
566
+ if (t != null) addedAt[option] = t
567
+ }
568
+ if (Object.keys(addedAt).length > 0) desc.optionAddedAt = addedAt
569
+ const triggers: Record<string, LoraTriggers> = {}
570
+ for (const option of desc.options) {
571
+ const t = getLoraTriggers(option, hostId)
572
+ if (t != null) triggers[option] = t
573
+ }
574
+ if (Object.keys(triggers).length > 0) desc.optionTriggers = triggers
523
575
  }
524
576
  vars[name] = desc
525
577
  }
@@ -544,6 +596,8 @@ export class ServeApp {
544
596
  (d) => `POST /generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`,
545
597
  ),
546
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 ?? {}),
547
601
  }
548
602
  }
549
603
 
@@ -568,6 +622,34 @@ export class ServeApp {
568
622
  return json(200, { ...this.describeModule(mod), draft, values: this.draftValues(mod, draft) })
569
623
  }
570
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
+
571
653
  /** stored values (toJSON shapes); 'default' without a file falls back to descriptor defaults */
572
654
  private draftValues(mod: ServeModule, draft: string): Record<string, unknown> {
573
655
  const path = this.draftPath(mod, draft)
@@ -591,8 +673,7 @@ export class ServeApp {
591
673
 
592
674
  private async replyWebJs(): Promise<ServeReply> {
593
675
  if (this.opts.webJs == null) return json(404, { error: 'web ui not enabled on this server' })
594
- this.webJsCache ??= this.opts.webJs()
595
- const js = await this.webJsCache
676
+ const js = await this.opts.webJs()
596
677
  if (js == null) return json(404, { error: 'web ui bundle unavailable — see the server log' })
597
678
  return { status: 200, contentType: 'text/javascript; charset=utf-8', body: js, headers: NO_STORE }
598
679
  }
@@ -637,7 +718,17 @@ export class ServeApp {
637
718
  return json(400, { error: 'body must be a json object: { "<var>": value, … }' })
638
719
  const values = parsed as Record<string, unknown>
639
720
  const known = new Set(mod.dw.entries().map(([k]) => k))
640
- 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))
641
732
  if (unknown.length > 0)
642
733
  return json(400, { error: `unknown var(s) ${unknown.join(', ')} — vars: ${[...known].join(', ')}` })
643
734
  // values are written VERBATIM (toJSON shapes, loadJSON re-validates on read) —
@@ -713,9 +804,18 @@ export class ServeApp {
713
804
  if (action === 'refresh-loras') return await this.refreshLoraMirror(hostId, host)
714
805
  if (action === 'refresh-schema') {
715
806
  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
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'
719
819
  const rebound = await this.rebindHostVars(hostId, host)
720
820
  const nodes = host.schema.nodes.length
721
821
  const loras = host.schema.getLoras().length
@@ -728,7 +828,7 @@ export class ServeApp {
728
828
  host: hostId,
729
829
  action,
730
830
  stale: rebound.stale,
731
- 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}`,
732
832
  })
733
833
  }
734
834
  if (action === 'restart') {
@@ -818,6 +918,67 @@ export class ServeApp {
818
918
  })
819
919
  }
820
920
 
921
+ /** fetch ONE lora's civitai metadata through the lora manager, then re-sync the mirror so its
922
+ * trigger words reach every surface. The extension keys the request by the file path ON THE
923
+ * HOST, which only the mirror knows, so a lora outside the mirror needs a sync first */
924
+ private async replyLoraCivitaiFetch(hostId: string, lora: string): Promise<ServeReply> {
925
+ const host = comfyts.hosts.get(hostId)
926
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` })
927
+ const info = getLoraInfo(lora, hostId)
928
+ const filePath = info == null ? null : lmFilePath(info)
929
+ if (filePath == null)
930
+ return json(404, { error: `'${lora}' is not in the lora manager mirror of ${hostId}: sync the mirror first` })
931
+ const fetched = await fetchLoraCivitai(host, filePath)
932
+ const sha256 = info == null ? null : lmSha256(info)
933
+ // civitai ANSWERED that it has no version for this hash: a definite result, kept so the
934
+ // card stops offering a fetch. Any other failure (network, the extension) stays an error
935
+ if (!fetched.ok && /no version data found/i.test(fetched.reason) && sha256 != null) {
936
+ recordCivitaiMiss({ hostId, sha256, miss: true })
937
+ return json(200, {
938
+ ok: true,
939
+ host: hostId,
940
+ lora,
941
+ triggers: { state: 'not-on-civitai' },
942
+ note: `civitai does not know '${lora}' (a private or local lora): no trigger words to fetch`,
943
+ })
944
+ }
945
+ if (!fetched.ok) return json(502, { error: `civitai fetch failed for '${lora}': ${fetched.reason}` })
946
+ if (sha256 != null) recordCivitaiMiss({ hostId, sha256, miss: false })
947
+ const synced = await this.refreshLoraMirror(hostId, host)
948
+ if (synced.status !== 200) return synced
949
+ const t = getLoraTriggers(lora, hostId)
950
+ const note =
951
+ t?.state === 'words'
952
+ ? `trigger words: ${t.words.join(', ')}`
953
+ : t?.state === 'none'
954
+ ? `civitai lists no trigger words for '${lora}'`
955
+ : `civitai has no metadata for '${lora}'`
956
+ return json(200, { ok: true, host: hostId, lora, triggers: t, note })
957
+ }
958
+
959
+ /** has the host changed since this process loaded its schema: new or removed model files (and
960
+ * node types on a full check). A host whose catalog is COMMITTED rather than live-synced
961
+ * (sdkAutoWrite: false, the cloud catalog) is not compared: its live list moves on purpose */
962
+ private async replyHostDrift(hostId: string, full: boolean): Promise<ServeReply> {
963
+ const host = comfyts.hosts.get(hostId)
964
+ if (host == null) return json(404, { error: `unknown host '${hostId}'` })
965
+ if (host.data.sdkAutoWrite === false)
966
+ return json(200, { host: hostId, checked: false, changed: false, summary: '' })
967
+ try {
968
+ const drift = await host.checkSchemaDrift({ full })
969
+ return json(200, {
970
+ host: hostId,
971
+ checked: true,
972
+ full,
973
+ changed: driftChanged(drift),
974
+ summary: summarizeDrift(drift),
975
+ drift,
976
+ })
977
+ } catch (e) {
978
+ return json(502, { error: `${hostId} unreachable: ${extractErrorMessage(e)}` })
979
+ }
980
+ }
981
+
821
982
  /** is the host answering RIGHT NOW: what the panel polls while a restart is in flight, so
822
983
  * "restarting…" ends on a fact rather than on a guess */
823
984
  private async replyHostPing(hostId: string): Promise<ServeReply> {
@@ -979,6 +1140,35 @@ export class ServeApp {
979
1140
 
980
1141
  // #region prompt enhancers (the web ui's master prompts, as .md files) ------
981
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
+
982
1172
  private replyPromptEnhancers(): ServeReply {
983
1173
  try {
984
1174
  return json(200, { enhancers: listPromptEnhancers() })
@@ -1021,6 +1211,46 @@ export class ServeApp {
1021
1211
  return json(200, { ok: true, name, enhancers: listPromptEnhancers() })
1022
1212
  }
1023
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
+
1024
1254
  // #region live run state (web ui polling: progress + latent preview) --------
1025
1255
  private liveRuns = new Map<string, ServeExecution>()
1026
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,8 +15,10 @@ 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'
21
+ import type { LoraTriggers } from 'src/host/loraInfoCache.ts'
19
22
 
20
23
  export type VarDescriptor = {
21
24
  kind: VarKind
@@ -23,6 +26,10 @@ export type VarDescriptor = {
23
26
  /** what a POST payload accepts for this var, human-readable */
24
27
  payload: string
25
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
26
33
  choices?: readonly string[]
27
34
  /** loras: the resolved option list */
28
35
  options?: readonly string[]
@@ -41,6 +48,17 @@ export type VarDescriptor = {
41
48
  * the picker with a warning, because a lora present on disk usually runs even when the
42
49
  * server has not rescanned its list, filled by ServeApp.describeModule */
43
50
  managerOnlyOptions?: readonly string[]
51
+ /** loras: when each file landed on the host (epoch seconds, the lora manager's date), entries
52
+ * only where the mirror has one. The popup's `date added` sort reads it */
53
+ optionAddedAt?: Record<string, number>
54
+ /** loras: trigger words per option as the mirror knows them (words, fetched and empty, or
55
+ * civitai never asked). An option ABSENT from this record is not in the mirror at all */
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
44
62
  /** text: this one wants a box, not a line (`v.text(…, { multiline: true })`) */
45
63
  multiline?: boolean
46
64
  /** text + prompt: named starting texts (`{ presets: { label: text } }`). NOT `presets`, which
@@ -49,6 +67,8 @@ export type VarDescriptor = {
49
67
  min?: number
50
68
  max?: number
51
69
  presets?: SizePreset[]
70
+ /** size: preset labels starred by default (quick buttons before the list) */
71
+ starredPresets?: string[]
52
72
  extensions?: readonly string[]
53
73
  }
54
74
 
@@ -63,7 +83,13 @@ function rangeText(opts: { min?: number; max?: number }): string {
63
83
  }
64
84
 
65
85
  export function describeVar(varDef: AnyVar): VarDescriptor {
66
- 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
+ }
67
93
  // kind, never instanceof: the cli bundle and the consumer's `comfy-ts` import hold
68
94
  // different copies of every class (VarKind owns the WHY). Casts are the sanctioned
69
95
  // kind-narrowing family (agent/coding.md cast whitelist 6)
@@ -72,8 +98,13 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
72
98
  const v = varDef as PromptVar
73
99
  return {
74
100
  ...base,
75
- payload: 'string ("//" lines = comments, "- " lines = negative)',
101
+ payload: 'string ("//" starts a comment, "- " lines = negative)',
76
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,
77
108
  }
78
109
  }
79
110
  case 'text': {
@@ -102,8 +133,15 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
102
133
  case 'toggle':
103
134
  return { ...base, payload: 'true or false' }
104
135
  case 'choice': {
105
- const v = varDef as ChoiceVar<string>
106
- 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 }
107
145
  }
108
146
  case 'loras': {
109
147
  const v = varDef as LorasVar<string>
@@ -117,7 +155,12 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
117
155
  }
118
156
  case 'size': {
119
157
  const v = varDef as SizeVar
120
- 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
+ }
121
164
  }
122
165
  case 'image': {
123
166
  const v = varDef as ImageVar