comfy-ts 2.9.0 → 2.11.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 (55) hide show
  1. package/README.md +6 -4
  2. package/dist/{LogsSt-DFxzQfDc.js → LogsSt-qtFzOKpu.js} +2 -2
  3. package/dist/{LogsSt-DFxzQfDc.js.map → LogsSt-qtFzOKpu.js.map} +1 -1
  4. package/dist/cli.js +4 -4
  5. package/dist/index.cjs +102 -3
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +19 -0
  8. package/dist/index.d.ts +19 -0
  9. package/dist/index.js +102 -3
  10. package/dist/index.js.map +1 -1
  11. package/dist/{run-serve-_nrvJYyt.js → run-serve-BK7BA2dn.js} +91 -3
  12. package/dist/run-serve-BK7BA2dn.js.map +1 -0
  13. package/dist/{run-tui-BLEdTsOX.js → run-tui-CQyvMf0N.js} +36 -4
  14. package/dist/run-tui-CQyvMf0N.js.map +1 -0
  15. package/dist/{DefinedWorkflow-BatWaZO1.js → schemaDrift-DjjEtwfx.js} +176 -2
  16. package/dist/schemaDrift-DjjEtwfx.js.map +1 -0
  17. package/dist/serve-web.js +32 -16
  18. package/dist/{state-BbgJeCe6.js → state--wrz0BQc.js} +23 -5
  19. package/dist/state--wrz0BQc.js.map +1 -0
  20. package/dist/web.d.ts +19 -0
  21. package/dist/web.js +102 -3
  22. package/dist/web.js.map +1 -1
  23. package/examples/README.md +1 -0
  24. package/examples/comfy-cloud/capybara-i2v.cflow.ts +2 -0
  25. package/examples/comfy-cloud/ltx25-i2v.cflow.ts +152 -0
  26. package/examples/comfy-cloud/ltx25-t2v.cflow.ts +126 -0
  27. package/examples/comfy-cloud/minimax-music3-t2a.cflow.ts +95 -0
  28. package/examples/comfy-cloud/sdk.d.ts +30724 -24404
  29. package/examples/comfy-cloud/wan22-5b-t2v.cflow.ts +2 -0
  30. package/examples/comfy-cloud/wan22-i2v.cflow.ts +2 -0
  31. package/examples/comfy-cloud/wan22-t2v.cflow.ts +2 -0
  32. package/examples/rvion/07-local-llm-text-gen.cflow.ts +2 -2
  33. package/examples/rvion/08-qwen-image-21-t2i.cflow.ts +64 -0
  34. package/examples/rvion/09-qwen-image-21-edit.cflow.ts +83 -0
  35. package/package.json +4 -2
  36. package/src/cli/serve/ServeApp.ts +94 -0
  37. package/src/cli/serve/describeVar.ts +7 -0
  38. package/src/cli/serve/favicon.ts +3 -0
  39. package/src/cli/serve/web/api.ts +12 -0
  40. package/src/cli/serve/web/components/VarsForm.tsx +18 -7
  41. package/src/cli/serve/web/components/controls/LorasControl.tsx +102 -6
  42. package/src/cli/serve/web/state/WebSt.ts +79 -0
  43. package/src/cli/serve/web/state/loraSort.ts +39 -0
  44. package/src/cli/serve/web/styles.ts +15 -0
  45. package/src/cli/tui/components/Header.tsx +2 -0
  46. package/src/cli/tui/state/HostSt.ts +34 -0
  47. package/src/graph/ComfyNode.ts +19 -3
  48. package/src/host/ComfyHost.ts +15 -0
  49. package/src/host/loraInfoCache.ts +64 -0
  50. package/src/host/loraManagerApi.ts +27 -0
  51. package/src/host/schemaDrift.ts +87 -0
  52. package/dist/DefinedWorkflow-BatWaZO1.js.map +0 -1
  53. package/dist/run-serve-_nrvJYyt.js.map +0 -1
  54. package/dist/run-tui-BLEdTsOX.js.map +0 -1
  55. package/dist/state-BbgJeCe6.js.map +0 -1
@@ -10,6 +10,8 @@ import {
10
10
  fetchSettings,
11
11
  pingHost,
12
12
  postHostAction,
13
+ postLoraCivitai,
14
+ fetchHostDrift,
13
15
  saveDraft,
14
16
  saveSettings,
15
17
  setModuleHost,
@@ -24,6 +26,7 @@ import { logWebError } from 'src/cli/serve/web/logWeb.ts'
24
26
  import { asSeedForm } from 'src/cli/serve/web/state/payload.ts'
25
27
  import { readUrlSelection, resolveSelection, writeUrlSelection } from 'src/cli/serve/web/state/urlSelection.ts'
26
28
  import { RunSt } from 'src/cli/serve/web/state/RunSt.ts'
29
+ import { asLoraSort, type LoraSort } from 'src/cli/serve/web/state/loraSort.ts'
27
30
  import {
28
31
  coerceHostValue,
29
32
  isEmbedded,
@@ -73,6 +76,7 @@ type StoredSelection = {
73
76
  loraTitles?: boolean
74
77
  /** lora previews fill their card (cover) instead of fitting inside it (contain) */
75
78
  loraFill?: boolean
79
+ loraSort?: string
76
80
  /** how many lora cards the popup draws before it stops */
77
81
  loraCap?: number
78
82
  /** the one-shot 60 → 200 default bump already happened for this browser */
@@ -134,6 +138,7 @@ export class WebSt {
134
138
  showLoraTitles: boolean
135
139
  /** cover vs contain for every lora preview: art crops well, a character sheet does not */
136
140
  loraFill: boolean
141
+ loraSort: LoraSort
137
142
  /** how many lora cards the popup draws. A cap exists because each card is an image
138
143
  * request; how many is a MACHINE question (your box, your collection), so it is yours */
139
144
  loraCap: number
@@ -210,6 +215,7 @@ export class WebSt {
210
215
  this.showLoraImages = stored.loraImages ?? true
211
216
  this.showLoraTitles = stored.loraTitles ?? true
212
217
  this.loraFill = stored.loraFill ?? true
218
+ this.loraSort = asLoraSort(stored.loraSort)
213
219
  // marked in the blob, so the bump happens once and a deliberate 60 sticks after it
214
220
  this.loraCap = clampLoraCap(
215
221
  stored.loraCapMigrated !== true && stored.loraCap === LEGACY_LORA_CAP ? DEFAULT_LORA_CAP : stored.loraCap,
@@ -255,6 +261,11 @@ export class WebSt {
255
261
  this.persist()
256
262
  }
257
263
 
264
+ setLoraSort(mode: LoraSort): void {
265
+ this.loraSort = mode
266
+ this.persist()
267
+ }
268
+
258
269
  toggleLoraFill(): void {
259
270
  this.loraFill = !this.loraFill
260
271
  this.persist()
@@ -319,6 +330,7 @@ export class WebSt {
319
330
  loraImages: this.showLoraImages,
320
331
  loraTitles: this.showLoraTitles,
321
332
  loraFill: this.loraFill,
333
+ loraSort: this.loraSort,
322
334
  loraCap: this.loraCap,
323
335
  loraCapMigrated: true,
324
336
  layout: this.layout,
@@ -374,6 +386,7 @@ export class WebSt {
374
386
  if (urlPrompt != null) this.setPromptText(urlPrompt)
375
387
  // last: the host replies with its buttons + its prompt, and both need a form
376
388
  this.postHost({ comfyTs: 'ready' })
389
+ this.startDriftWatch()
377
390
  } catch (e) {
378
391
  const message = e instanceof Error ? e.message : String(e)
379
392
  runInAction(() => {
@@ -765,6 +778,70 @@ export class WebSt {
765
778
  await this.trackSwitch(this.reloadIndexAndForm())
766
779
  }
767
780
 
781
+ /** what changed on a host since the server loaded its schema, shown on the refetch button of
782
+ * that host only. A light check (the loaders, a few KB) runs every minute while the tab is
783
+ * visible; a full one (node types too) at boot, after a refetch or a restart, and when a host
784
+ * that stopped answering answers again, which is how a restart nobody announced is noticed */
785
+ drift: { host: string; summary: string } | null = null
786
+ driftDown = false
787
+
788
+ private startDriftWatch(): void {
789
+ void this.checkDrift(true)
790
+ setInterval(() => {
791
+ if (document.visibilityState === 'visible') void this.checkDrift(false)
792
+ }, 60_000)
793
+ }
794
+
795
+ async checkDrift(full: boolean): Promise<void> {
796
+ const host = this.form == null ? null : this.hostFor(this.form.moduleKey)
797
+ if (host == null || host === '') return
798
+ try {
799
+ const r = await fetchHostDrift({ host, full })
800
+ const cameBack = this.driftDown
801
+ runInAction(() => {
802
+ this.driftDown = false
803
+ // a clean LIGHT check cannot clear what a full one found (node types it does not see)
804
+ if (r.changed) this.drift = { host, summary: r.summary }
805
+ else if (full || this.drift?.host !== host) this.drift = null
806
+ })
807
+ if (cameBack && !full) await this.checkDrift(true)
808
+ } catch {
809
+ runInAction(() => {
810
+ this.driftDown = true
811
+ })
812
+ }
813
+ }
814
+
815
+ /** loras whose civitai fetch is in flight: their card says so instead of offering it twice */
816
+ loraFetching = new Set<string>()
817
+
818
+ /** one lora's trigger words, fetched from civitai by the lora manager, then the mirror and
819
+ * the descriptors re-read so the card shows what came back (words, or a definite none) */
820
+ async fetchLoraTriggers(lora: string): Promise<void> {
821
+ const host = this.form == null ? null : this.hostFor(this.form.moduleKey)
822
+ if (host == null || host === '' || this.loraFetching.has(lora)) return
823
+ runInAction(() => {
824
+ this.loraFetching.add(lora)
825
+ this.hostError = null
826
+ this.hostNote = null
827
+ })
828
+ try {
829
+ const reply = await postLoraCivitai({ host, lora })
830
+ runInAction(() => {
831
+ this.hostNote = reply.note
832
+ })
833
+ await this.trackSwitch(this.reloadIndexAndForm())
834
+ } catch (e) {
835
+ runInAction(() => {
836
+ this.hostError = e instanceof Error ? e.message : String(e)
837
+ })
838
+ } finally {
839
+ runInAction(() => {
840
+ this.loraFetching.delete(lora)
841
+ })
842
+ }
843
+ }
844
+
768
845
  private async reloadIndexAndForm(): Promise<void> {
769
846
  // the option lists (and the manager-only union) live in the descriptors: re-read them,
770
847
  // then re-select the same draft so the form is rebuilt against the new options
@@ -823,6 +900,7 @@ export class WebSt {
823
900
  this.hostWatch = 'back'
824
901
  this.hostNote = `${host} is back up`
825
902
  })
903
+ void this.checkDrift(true)
826
904
  setTimeout(() => runInAction(() => (this.hostWatch = 'idle')), 4000)
827
905
  return
828
906
  }
@@ -843,6 +921,7 @@ export class WebSt {
843
921
  })
844
922
  // a reboot is the one action whose result arrives LATER: watch for it
845
923
  if (action === 'restart') void this.watchHostComeBack()
924
+ if (action === 'refresh-schema') await this.checkDrift(true)
846
925
  } catch (e) {
847
926
  runInAction(() => {
848
927
  this.hostError = e instanceof Error ? e.message : String(e)
@@ -0,0 +1,39 @@
1
+ /** how the loras popup orders the cards the filter matched. `folder` keeps the host's own order
2
+ * and groups by folder, the other modes list flat. The sort runs BEFORE the card cap, so a
3
+ * lora the host listed last still makes the cut when it sorts first */
4
+ export type LoraSort = 'folder' | 'name' | 'added'
5
+
6
+ export const LORA_SORTS: readonly { mode: LoraSort; label: string; tip: string }[] = [
7
+ { mode: 'folder', label: 'folder', tip: 'grouped by folder, in the order the host lists them' },
8
+ { mode: 'name', label: 'name', tip: 'by display name, A to Z' },
9
+ {
10
+ mode: 'added',
11
+ label: 'date added',
12
+ tip: 'newest file first (the lora manager date). loras it has no date for come last',
13
+ },
14
+ ]
15
+
16
+ export function asLoraSort(raw: unknown): LoraSort {
17
+ return raw === 'name' || raw === 'added' ? raw : 'folder'
18
+ }
19
+
20
+ export function sortLoraMatches(p: {
21
+ names: readonly string[]
22
+ mode: LoraSort
23
+ label: (name: string) => string
24
+ /** option → epoch seconds, entries only where the mirror has a date */
25
+ addedAt: Record<string, number>
26
+ }): string[] {
27
+ const out = [...p.names]
28
+ if (p.mode === 'name')
29
+ return out.sort((a, b) => p.label(a).localeCompare(p.label(b), undefined, { sensitivity: 'base', numeric: true }))
30
+ if (p.mode === 'added')
31
+ return out.sort((a, b) => {
32
+ const ta = p.addedAt[a]
33
+ const tb = p.addedAt[b]
34
+ if (ta == null) return tb == null ? 0 : 1
35
+ if (tb == null) return -1
36
+ return tb - ta
37
+ })
38
+ return out
39
+ }
@@ -100,6 +100,8 @@ body {
100
100
  }
101
101
  .head-value.as-link:hover { color: var(--accent); text-decoration: underline; }
102
102
  button.danger { color: var(--dim); }
103
+ /* a button that asks to be pressed: the host changed under the panel */
104
+ button.attention { color: var(--accent); border-color: var(--accent); background: var(--accent-dim); font-size: 11px; white-space: nowrap; }
103
105
  button.danger:hover { color: var(--red); border-color: var(--red); }
104
106
 
105
107
  /* the sidebar is a tree: folder → workflows → drafts, the branch line makes the nesting readable */
@@ -279,6 +281,16 @@ button.mode.sel { background: var(--accent-dim); border-color: var(--accent); co
279
281
  .lora-chip:not(.card) .lora-toggle { flex-direction: row; align-items: center; gap: 6px; }
280
282
  .lora-toggle:hover .chip-title { color: var(--accent); }
281
283
  .chip-controls { display: flex; flex-direction: column; gap: 3px; }
284
+ /* trigger words under a row card: the words wrap, a missing state carries its fix */
285
+ .chip-triggers { font-size: 11px; line-height: 1.35; color: var(--text); overflow-wrap: anywhere; user-select: text; }
286
+ .chip-triggers.none, .chip-triggers.missing { color: var(--dim); font-style: italic; }
287
+ .chip-triggers.missing { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
288
+ .lora-chip .chip-triggers .trigger-fetch {
289
+ font-style: normal; font-size: 11px; padding: 1px 8px; border-radius: 6px;
290
+ border: 1px solid var(--border); background: var(--panel); color: var(--accent);
291
+ }
292
+ .lora-chip .chip-triggers .trigger-fetch:hover { color: var(--accent); border-color: var(--accent); }
293
+ .lora-chip .chip-triggers .trigger-fetch:disabled { color: var(--dim); cursor: default; }
282
294
  /* a line: label button, slider, number. The label toggles m+c ↔ m / c */
283
295
  .st-line { display: flex; gap: 5px; align-items: center; }
284
296
  .st-line .st-label {
@@ -358,6 +370,9 @@ button.mode.sel { background: var(--accent-dim); border-color: var(--accent); co
358
370
  .lora-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
359
371
 
360
372
  .lora-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; }
373
+ .lora-sort-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 6px; }
374
+ .lora-sort { display: inline-flex; align-items: center; gap: 4px; text-transform: none; letter-spacing: 0; }
375
+ .lora-sort .mode { font-size: 11px; padding: 2px 8px; }
361
376
  .lora-card {
362
377
  display: flex; flex-direction: column; gap: 6px; padding: 6px; text-align: left;
363
378
  background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; cursor: pointer; min-width: 0;
@@ -50,6 +50,8 @@ export const Header = observer((p: { st: TuiSt }) => {
50
50
  {s.hostOverride != null && s.hostOverride !== s.wf.host && (
51
51
  <Text color="yellow"> ⇄ overrides {s.wf.host.data.id}</Text>
52
52
  )}
53
+ {/* the host changed under the loaded schema: say what, and where the fix is */}
54
+ {s.host.drift !== '' && <Text color="yellow"> ⚠ changed: {s.host.drift} · a → re-codegen</Text>}
53
55
  {/* while down, show the probe loop living: spinner in flight, countdown between tries */}
54
56
  {s.host.status === 'down' && (
55
57
  <Text color="red"> {s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`}</Text>
@@ -2,12 +2,15 @@ import { makeAutoObservable, reaction, runInAction } from 'mobx'
2
2
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
3
3
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
4
4
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
5
+ import { summarizeDrift } from 'src/host/schemaDrift.ts'
5
6
 
6
7
  type HostAction = { key: 'refresh' | 'restart' | 'clear-queue' | 'interrupt'; label: string }
7
8
 
8
9
  export type HostStatus = 'unknown' | 'up' | 'down'
9
10
 
10
11
  const PROBE_EVERY_MS = 5000
12
+ /** a light drift check (the loaders only) at most this often while the host is up */
13
+ const DRIFT_EVERY_MS = 60_000
11
14
  const PROBE_TIMEOUT_MS = 3000
12
15
  /** ws message younger than this = the host is alive, whatever http says */
13
16
  export const WS_ALIVE_MS = 10_000
@@ -55,6 +58,7 @@ export class HostSt {
55
58
  this.status = 'unknown'
56
59
  this.statusVia = null
57
60
  this.lastProbeError = null // the previous host's failure must not show under the new one
61
+ this.drift = ''
58
62
  })
59
63
  this.probeGen++
60
64
  if (this.loopTimer != null) clearTimeout(this.loopTimer)
@@ -148,6 +152,7 @@ export class HostSt {
148
152
  }
149
153
  }
150
154
  if (this.host !== host) return // workflow switched mid-flight: stale verdict
155
+ const before = this.status
151
156
  const verdict = probeVerdict({
152
157
  httpOk: ok,
153
158
  wsOpen: host.isConnected,
@@ -159,6 +164,34 @@ export class HostSt {
159
164
  this.statusVia = verdict.via
160
165
  this.lastProbeError = probeError
161
166
  })
167
+ // first seen up, or back from down (a restart nobody announced): a full check. Otherwise a
168
+ // light one now and then, so a lora added under a running TUI still shows
169
+ if (verdict.status === 'up') {
170
+ if (before !== 'up') void this.checkDrift(true)
171
+ else if (Date.now() - this.driftAt > DRIFT_EVERY_MS) void this.checkDrift(false)
172
+ }
173
+ }
174
+
175
+ /** what changed on the host since its schema was loaded (`+5 loras`), '' when nothing is known
176
+ * to have changed. A committed catalog (sdkAutoWrite: false, the cloud) is never compared */
177
+ drift = ''
178
+ driftAt = 0
179
+
180
+ private async checkDrift(full: boolean): Promise<void> {
181
+ const host = this.host
182
+ if (host.data.sdkAutoWrite === false) return
183
+ this.driftAt = Date.now()
184
+ try {
185
+ const summary = summarizeDrift(await host.checkSchemaDrift({ full }))
186
+ if (this.host !== host) return
187
+ runInAction(() => {
188
+ // a clean LIGHT check cannot clear what a full one found (node types it does not see)
189
+ if (summary !== '') this.drift = summary
190
+ else if (full) this.drift = ''
191
+ })
192
+ } catch {
193
+ // reachability is the probe loop's job, and it already says so: a failed check just waits
194
+ }
162
195
  }
163
196
 
164
197
  ix: number = 0
@@ -278,6 +311,7 @@ export class HostSt {
278
311
  runInAction(() => {
279
312
  const schema = this.host.schema
280
313
  this.st.exec.notice = `SDK regenerated: ${schema.nodes.length} node types, ${schema.getLoras().length} loras`
314
+ this.drift = ''
281
315
  })
282
316
  } catch (e) {
283
317
  runInAction(() => {
@@ -4,7 +4,11 @@ import type { ComfyNodeSchema } from 'src/sdk-generator/ComfyNodeSchema.ts'
4
4
  import type { ComfyApiNodeJson } from 'src/sdk-generator/comfy-api-json.ts'
5
5
  import type { NodeInputExt, NodeOutputExt } from 'src/sdk-generator/comfyui-types.ts'
6
6
  import { ComfyDefaultNodeWhenUnknown_Name } from 'src/sdk-generator/Primitives.ts'
7
- import { classifySchemaInput, defaultValueForWidget } from 'src/sdk-generator/inputWidgetKind.ts'
7
+ import {
8
+ classifySchemaInput,
9
+ containerInstanceSlotType,
10
+ defaultValueForWidget,
11
+ } from 'src/sdk-generator/inputWidgetKind.ts'
8
12
  import type { DynamicComboOption } from 'src/sdk-generator/inputWidgetKind.ts'
9
13
  import type { Maybe } from 'src/types/index.ts'
10
14
  import { comfyColors } from 'src/utils/ComfyColors.ts'
@@ -440,8 +444,20 @@ export class ComfyNode<
440
444
 
441
445
  private _getExpectedTypeForField(name: string): string {
442
446
  const input = this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name)
443
- if (input == null) throw new Error('🔴 input not found asdf')
444
- return input.typeName
447
+ if (input != null) return input.typeName
448
+ // autogrow instance key `decl.<instance>`: the container template carries the slot type
449
+ const dot = name.indexOf('.')
450
+ const decl =
451
+ dot > 0 ? this.$schema.inputs.find((i: NodeInputExt) => i.nameInComfy === name.slice(0, dot)) : undefined
452
+ if (decl != null) {
453
+ const kind = classifySchemaInput(decl)
454
+ const slotType = containerInstanceSlotType(decl.opts)
455
+ if (kind.kind === 'dynamic-container' && kind.instanceNames.includes(name.slice(dot + 1)) && slotType != null)
456
+ return slotType
457
+ }
458
+ throw new Error(
459
+ `🔴 no input "${name}" on ${this.$schema.nodeKey}: cannot tell which output of the linked node to use`,
460
+ )
445
461
  }
446
462
 
447
463
  private _getOutputForTypeOrCrash(type: string): ComfyNodeOutput<any> {
@@ -36,6 +36,7 @@ import type { Requirements } from 'src/host/Requirements.ts'
36
36
  import { ResilientWebSocketClient, type WsMessageEvent } from 'src/host/ResilientWebsocket.ts'
37
37
  import { DefinedWorkflow, type DefineWorkflowSpec } from 'src/vars/DefinedWorkflow.ts'
38
38
  import type { VarsSpec } from 'src/vars/ComfyVars.ts'
39
+ import { diffSchemas, MODEL_LISTS, type SchemaDrift } from 'src/host/schemaDrift.ts'
39
40
 
40
41
  export type ComfyHostID = Tagged<string, { HostID: true }>
41
42
  export type ComfyHostData = {
@@ -678,6 +679,20 @@ export class ComfyHost<ID extends string = string> {
678
679
  if (!res.ok) throw new Error(`PATCH /internal/logs/subscribe failed: ${res.status}`)
679
680
  }
680
681
 
682
+ /** what changed on the host since this schema was loaded (src/host/schemaDrift.ts). `full: false`
683
+ * asks only the loaders the schema has, a few KB, so it can run on a timer. Throws when the host
684
+ * cannot be reached, which is itself the signal a caller watches for a restart */
685
+ checkSchemaDrift = async (p: { full: boolean }): Promise<SchemaDrift> => {
686
+ const loaded: Record<string, unknown> = this.schema.data.spec
687
+ const live: Record<string, unknown> = {}
688
+ if (p.full) Object.assign(live, await this.fetchJSON_<Record<string, unknown>>('/object_info'))
689
+ else
690
+ for (const m of MODEL_LISTS)
691
+ if (loaded[m.node] != null)
692
+ Object.assign(live, await this.fetchJSON_<Record<string, unknown>>(`/object_info/${m.node}`))
693
+ return diffSchemas({ loaded, live, full: p.full })
694
+ }
695
+
681
696
  /** GET a JSON route through host.fetch (/api preferred, bare fallback) */
682
697
  private fetchJSON_ = async <T>(route: string): Promise<T> => {
683
698
  const base = this.getServerHostHTTP()
@@ -8,7 +8,9 @@ import {
8
8
  lmFolder,
9
9
  lmItemKey,
10
10
  lmModelName,
11
+ lmModified,
11
12
  lmPreviewUrl,
13
+ lmSha256,
12
14
  lmTags,
13
15
  lmTrainedWords,
14
16
  loraBasename,
@@ -193,6 +195,68 @@ export function getLoraDisplayName(name: string, hostId?: string): string {
193
195
  return (info == null ? null : lmModelName(info)) ?? loraBasename(name)
194
196
  }
195
197
 
198
+ /** what the mirror knows about a lora's trigger words. The extension drops an EMPTY
199
+ * `trainedWords` when it slims the civitai block (model_scanner.py `if trained_words:`), so a
200
+ * block linked to civitai (an `id`) with no words means fetched and empty, while no block at
201
+ * all means civitai was never asked. null = the lora is not in the mirror */
202
+ export type LoraTriggers =
203
+ | { state: 'words'; words: string[] }
204
+ | { state: 'none' }
205
+ | { state: 'unfetched' }
206
+ /** civitai was asked and has no version for this file (a private or local lora) */
207
+ | { state: 'not-on-civitai' }
208
+
209
+ export function loraTriggersOf(item: LmLoraItem, p: { civitaiMiss?: boolean } = {}): LoraTriggers {
210
+ const words = lmTrainedWords(item)
211
+ if (words.length > 0) return { state: 'words', words }
212
+ const civitai = item['civitai']
213
+ if (isRecord(civitai) && (typeof civitai['id'] === 'number' || typeof civitai['modelId'] === 'number'))
214
+ return { state: 'none' }
215
+ return p.civitaiMiss === true ? { state: 'not-on-civitai' } : { state: 'unfetched' }
216
+ }
217
+
218
+ export function getLoraTriggers(name: string, hostId?: string): LoraTriggers | null {
219
+ const info = getLoraInfo(name, hostId)
220
+ if (info == null) return null
221
+ const sha = lmSha256(info)
222
+ return loraTriggersOf(info, { civitaiMiss: hostId != null && sha != null && readCivitaiMisses(hostId)[sha] != null })
223
+ }
224
+
225
+ // the lora manager records nothing when civitai has no version for a file, so the answer is kept
226
+ // here, keyed by content hash (a rename keeps it): without it such a lora would offer a fetch
227
+ // that fails the same way forever
228
+ function civitaiMissesPath(hostId: string): AbsolutePath {
229
+ return comfyts.resolveFromHosts(join(hostId, 'lora-civitai-misses.json'))
230
+ }
231
+
232
+ /** sha256 → when civitai said it has no version for that file */
233
+ export function readCivitaiMisses(hostId: string): Record<string, string> {
234
+ const text = getComfyStorage().readTextIfExists(civitaiMissesPath(hostId))
235
+ if (text == null) return {}
236
+ try {
237
+ const raw: unknown = JSON.parse(text)
238
+ const out: Record<string, string> = {}
239
+ if (isRecord(raw)) for (const [sha, at] of Object.entries(raw)) if (typeof at === 'string') out[sha] = at
240
+ return out
241
+ } catch (e) {
242
+ logError(`[loraInfoCache] unreadable ${civitaiMissesPath(hostId)}: ${String(e)}`)
243
+ return {}
244
+ }
245
+ }
246
+
247
+ export function recordCivitaiMiss(p: { hostId: string; sha256: string; miss: boolean }): void {
248
+ const misses = readCivitaiMisses(p.hostId)
249
+ if (p.miss) misses[p.sha256] = new Date().toISOString()
250
+ else delete misses[p.sha256]
251
+ getComfyStorage().writeText(civitaiMissesPath(p.hostId), JSON.stringify(misses, null, 2))
252
+ }
253
+
254
+ /** when the lora file landed on the host (epoch seconds), null when unsynced/unknown */
255
+ export function getLoraAddedAt(name: string, hostId?: string): number | null {
256
+ const info = getLoraInfo(name, hostId)
257
+ return info == null ? null : lmModified(info)
258
+ }
259
+
196
260
  /** server-relative preview url from the mirror, null when unsynced/unknown */
197
261
  export function getLoraPreviewUrl(name: string, hostId?: string): string | null {
198
262
  const info = getLoraInfo(name, hostId)
@@ -58,6 +58,12 @@ export function lmSha256(item: LmLoraItem): string | null {
58
58
  return readString(item, 'sha256')
59
59
  }
60
60
 
61
+ /** when the file landed on the host (epoch seconds): the lora manager's own "date added" sort reads it */
62
+ export function lmModified(item: LmLoraItem): number | null {
63
+ const raw = item['modified']
64
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : null
65
+ }
66
+
61
67
  export function lmFileSize(item: LmLoraItem): number | null {
62
68
  const raw = item['file_size']
63
69
  return typeof raw === 'number' && Number.isFinite(raw) ? raw : null
@@ -140,6 +146,27 @@ export type LoraSweep =
140
146
  /** the host itself could not be reached (down, refused, auth) */
141
147
  | { status: 'unreachable'; reason: string }
142
148
 
149
+ /** asks the extension to (re)fetch civitai metadata for ONE lora file, trigger words included.
150
+ * The reply says why when civitai has nothing for it (a private or deleted model) */
151
+ export async function fetchLoraCivitai(
152
+ host: ComfyHost,
153
+ filePath: string,
154
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
155
+ try {
156
+ const res = await host.fetch('/lm/loras/fetch-civitai', {
157
+ method: 'POST',
158
+ headers: { 'content-type': 'application/json' },
159
+ body: JSON.stringify({ file_path: filePath }),
160
+ })
161
+ const raw: unknown = await res.json().catch(() => null)
162
+ const error = isRecord(raw) && typeof raw['error'] === 'string' ? raw['error'] : null
163
+ if (res.ok && isRecord(raw) && raw['success'] !== false) return { ok: true }
164
+ return { ok: false, reason: error ?? `the lora manager answered ${res.status}` }
165
+ } catch (e) {
166
+ return { ok: false, reason: extractErrorMessage(e) }
167
+ }
168
+ }
169
+
143
170
  /** civitai's model description for ONE lora, as PLAIN TEXT. The extension answers html, and
144
171
  * html from a third party is never rendered: tags are stripped here, at the seam.
145
172
  * null = the extension has no description for it (or does not expose the route) */
@@ -0,0 +1,87 @@
1
+ import { isRecord } from 'src/utils/isRecord.ts'
2
+
3
+ /**
4
+ * what changed on a host since a schema was loaded: node types, and the model files each loader
5
+ * lists. ComfyUI exposes no boot time, so staleness is decided by CONTENT: a restart that changed
6
+ * nothing stays quiet, a new lora shows even when nobody knows when the box rebooted.
7
+ * A light check asks only the loaders (`/object_info/<node>`, a few KB); a full one compares every
8
+ * node type (`/object_info`, megabytes).
9
+ */
10
+
11
+ /** the loader inputs whose combo IS a model folder listing */
12
+ export const MODEL_LISTS = [
13
+ { noun: 'lora', node: 'LoraLoader', input: 'lora_name' },
14
+ { noun: 'checkpoint', node: 'CheckpointLoaderSimple', input: 'ckpt_name' },
15
+ { noun: 'unet', node: 'UNETLoader', input: 'unet_name' },
16
+ { noun: 'text encoder', node: 'CLIPLoader', input: 'clip_name' },
17
+ { noun: 'vae', node: 'VAELoader', input: 'vae_name' },
18
+ ] as const
19
+
20
+ type Spec = Record<string, unknown>
21
+ type Delta = { added: string[]; removed: string[] }
22
+
23
+ export type SchemaDrift = {
24
+ /** null on a light check: node types are only compared by a full one */
25
+ nodes: Delta | null
26
+ models: ({ noun: string } & Delta)[]
27
+ }
28
+
29
+ /** a combo's options in both object_info spellings: `[[...options]]` and `['COMBO', { options }]` */
30
+ export function comboOptions(spec: Spec, node: string, input: string): string[] | null {
31
+ const def = spec[node]
32
+ if (!isRecord(def) || !isRecord(def['input'])) return null
33
+ const sections = def['input']
34
+ for (const section of ['required', 'optional']) {
35
+ const sec = sections[section]
36
+ if (!isRecord(sec)) continue
37
+ const slot = sec[input]
38
+ if (!Array.isArray(slot)) continue
39
+ const first: unknown = slot[0]
40
+ if (Array.isArray(first)) return first.filter((x): x is string => typeof x === 'string')
41
+ const opts: unknown = slot[1]
42
+ if (first === 'COMBO' && isRecord(opts) && Array.isArray(opts['options']))
43
+ return opts['options'].filter((x): x is string => typeof x === 'string')
44
+ }
45
+ return null
46
+ }
47
+
48
+ function delta(before: readonly string[], after: readonly string[]): Delta {
49
+ const was = new Set(before)
50
+ const now = new Set(after)
51
+ return { added: after.filter((x) => !was.has(x)), removed: before.filter((x) => !now.has(x)) }
52
+ }
53
+
54
+ /** `live` may be PARTIAL (a light check holds only the loaders): a list is compared only where both
55
+ * sides have the loader, and node types only when `full` */
56
+ export function diffSchemas(p: { loaded: Spec; live: Spec; full: boolean }): SchemaDrift {
57
+ const models: SchemaDrift['models'] = []
58
+ for (const m of MODEL_LISTS) {
59
+ const before = comboOptions(p.loaded, m.node, m.input)
60
+ const after = comboOptions(p.live, m.node, m.input)
61
+ if (before == null || after == null) continue
62
+ const d = delta(before, after)
63
+ if (d.added.length > 0 || d.removed.length > 0) models.push({ noun: m.noun, ...d })
64
+ }
65
+ return { nodes: p.full ? delta(Object.keys(p.loaded), Object.keys(p.live)) : null, models }
66
+ }
67
+
68
+ export function driftChanged(d: SchemaDrift): boolean {
69
+ return d.models.length > 0 || (d.nodes != null && (d.nodes.added.length > 0 || d.nodes.removed.length > 0))
70
+ }
71
+
72
+ /** `+5 loras, -1 unet, +4 node types`, '' when nothing changed */
73
+ export function summarizeDrift(d: SchemaDrift): string {
74
+ const parts: string[] = []
75
+ const say = (n: number, sign: string, noun: string): void => {
76
+ if (n > 0) parts.push(`${sign}${n} ${noun}${n === 1 ? '' : 's'}`)
77
+ }
78
+ for (const m of d.models) {
79
+ say(m.added.length, '+', m.noun)
80
+ say(m.removed.length, '-', m.noun)
81
+ }
82
+ if (d.nodes != null) {
83
+ say(d.nodes.added.length, '+', 'node type')
84
+ say(d.nodes.removed.length, '-', 'node type')
85
+ }
86
+ return parts.join(', ')
87
+ }