comfy-ts 2.3.0 → 2.4.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 (53) hide show
  1. package/README.md +13 -0
  2. package/dist/{DefinedWorkflow-CwHInZgn.js → DefinedWorkflow-QrhT6V66.js} +441 -9
  3. package/dist/DefinedWorkflow-QrhT6V66.js.map +1 -0
  4. package/dist/{DraftsSt-omWuBSej.js → DraftsSt-D9Fhk4qR.js} +2 -2
  5. package/dist/{DraftsSt-omWuBSej.js.map → DraftsSt-D9Fhk4qR.js.map} +1 -1
  6. package/dist/cli.js +116 -8
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +260 -23
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +132 -9
  11. package/dist/index.d.ts +132 -9
  12. package/dist/index.js +249 -24
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-serve-CfzOH-AR.js → run-serve-C9E8dyLP.js} +3 -3
  15. package/dist/run-serve-C9E8dyLP.js.map +1 -0
  16. package/dist/{run-tui-_LD0DoGe.js → run-tui-cawSJuuh.js} +60 -121
  17. package/dist/run-tui-cawSJuuh.js.map +1 -0
  18. package/dist/{state-C-OOEcp3.js → state-BbKuSDCV.js} +7 -76
  19. package/dist/state-BbKuSDCV.js.map +1 -0
  20. package/dist/web.d.ts +132 -9
  21. package/dist/web.js +249 -24
  22. package/dist/web.js.map +1 -1
  23. package/guide-for-agents.md +3 -0
  24. package/package.json +2 -1
  25. package/src/cli/comfy-ts-cli.ts +16 -1
  26. package/src/cli/flags.ts +14 -0
  27. package/src/cli/gen.ts +2 -4
  28. package/src/cli/loras.ts +113 -0
  29. package/src/cli/serve/applyVarPayload.ts +1 -1
  30. package/src/cli/tui/components/LorasOverlay.tsx +18 -5
  31. package/src/cli/tui/components/StatusBar.tsx +1 -0
  32. package/src/cli/tui/components/TuiApp.tsx +1 -0
  33. package/src/cli/tui/imageClipboard.ts +3 -3
  34. package/src/cli/tui/protocolImagePainter.ts +1 -1
  35. package/src/cli/tui/run-tui.tsx +2 -2
  36. package/src/cli/tui/state/ExecSt.ts +2 -2
  37. package/src/cli/tui/state/HostSt.ts +1 -1
  38. package/src/cli/tui/state/LorasSt.ts +60 -15
  39. package/src/cli/tui/state/PreviewSt.ts +1 -1
  40. package/src/cli/tui/state/SettingsSt.ts +1 -1
  41. package/src/coreExports.ts +20 -1
  42. package/src/host/ComfyHost.ts +1 -1
  43. package/src/host/loraInfoCache.ts +216 -0
  44. package/src/host/loraManagerApi.ts +131 -27
  45. package/src/runner/ComfyExecution.ts +1 -1
  46. package/src/runner/outputPath.ts +3 -3
  47. package/src/utils/isRecord.ts +4 -0
  48. package/src/vars/ComfyVars.ts +13 -7
  49. package/src/vars/loraKeywords.ts +48 -5
  50. package/dist/DefinedWorkflow-CwHInZgn.js.map +0 -1
  51. package/dist/run-serve-CfzOH-AR.js.map +0 -1
  52. package/dist/run-tui-_LD0DoGe.js.map +0 -1
  53. package/dist/state-C-OOEcp3.js.map +0 -1
@@ -0,0 +1,216 @@
1
+ import { join } from 'pathe'
2
+ import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
3
+ import {
4
+ type LmLoraItem,
5
+ lmBaseModel,
6
+ lmItemKey,
7
+ lmModelName,
8
+ lmPreviewUrl,
9
+ lmTags,
10
+ lmTrainedWords,
11
+ loraBasename,
12
+ loraKey,
13
+ } from 'src/host/loraManagerApi.ts'
14
+ import type { AbsolutePath } from 'src/types/index.ts'
15
+ import { isRecord } from 'src/utils/isRecord.ts'
16
+ import { logError } from 'src/utils/log.ts'
17
+
18
+ /**
19
+ * the LOCAL MIRROR of what ComfyUI-Lora-Manager knows about a host's loras
20
+ * (agent/architecture.md item 8). A ComfyUI host only ever tells us a lora's
21
+ * file name; the model's real name, its trigger words and its tags live in the
22
+ * extension. We sweep them once (`comfy-ts loras`) into
23
+ * `.comfy-ts/hosts/<id>/loras.json` and every surface reads the mirror after.
24
+ */
25
+
26
+ export type LoraMirror = {
27
+ hostId: string
28
+ /** remembered so a later `comfy-ts loras` re-syncs with no flags. NEVER an api key. */
29
+ hostUrl: string
30
+ fetchedAt: string
31
+ count: number
32
+ /** `loraKey` → the RAW lm item */
33
+ loras: Record<string, LmLoraItem>
34
+ }
35
+
36
+ export function loraMirrorPath(hostId: string): AbsolutePath {
37
+ return comfyts.resolveFromHosts(join(hostId, 'loras.json'))
38
+ }
39
+
40
+ /** pure: the on-disk shape for a sweep. Items without a file_name are dropped (nothing to key them by). */
41
+ export function buildLoraMirror(p: {
42
+ hostId: string
43
+ hostUrl: string
44
+ fetchedAt: string
45
+ items: LmLoraItem[]
46
+ }): LoraMirror {
47
+ const loras: Record<string, LmLoraItem> = {}
48
+ for (const item of p.items) {
49
+ const key = lmItemKey(item)
50
+ if (key == null) continue
51
+ // `x.safetensors` and `x.pt` in one folder collapse here: one lora would
52
+ // silently inherit the other's trigger words, so say it out loud
53
+ if (loras[key] != null) logError(`[loraInfoCache] two loras share the key '${key}' — one of them is shadowed`)
54
+ loras[key] = item
55
+ }
56
+ return {
57
+ hostId: p.hostId,
58
+ hostUrl: p.hostUrl,
59
+ fetchedAt: p.fetchedAt,
60
+ count: Object.keys(loras).length,
61
+ loras,
62
+ }
63
+ }
64
+
65
+ export function writeLoraMirror(mirror: LoraMirror): AbsolutePath {
66
+ const path = loraMirrorPath(mirror.hostId)
67
+ getComfyStorage().writeText(path, JSON.stringify(mirror, null, 2))
68
+ return path
69
+ }
70
+
71
+ /** null = never synced (or unreadable, which is LOGGED) */
72
+ export function readLoraMirror(hostId: string): LoraMirror | null {
73
+ const path = loraMirrorPath(hostId)
74
+ const text = getComfyStorage().readTextIfExists(path)
75
+ if (text == null) return null
76
+ try {
77
+ const raw: unknown = JSON.parse(text)
78
+ if (!isRecord(raw)) return null
79
+ const rawLoras = raw['loras']
80
+ if (!isRecord(rawLoras)) return null
81
+ const loras: Record<string, LmLoraItem> = {}
82
+ for (const [key, item] of Object.entries(rawLoras)) if (isRecord(item)) loras[key] = item
83
+ const str = (key: string, fallback: string): string => {
84
+ const v = raw[key]
85
+ return typeof v === 'string' ? v : fallback
86
+ }
87
+ // count is RECOUNTED, never trusted: the file is hand-editable like every .comfy-ts json
88
+ return {
89
+ hostId: str('hostId', hostId),
90
+ hostUrl: str('hostUrl', ''),
91
+ fetchedAt: str('fetchedAt', ''),
92
+ count: Object.keys(loras).length,
93
+ loras,
94
+ }
95
+ } catch (e) {
96
+ logError(`[loraInfoCache] unreadable ${path}: ${String(e)}`)
97
+ return null
98
+ }
99
+ }
100
+
101
+ /**
102
+ * the read model: each registered host's mirror, kept PER HOST.
103
+ *
104
+ * Per host, not merged into one map, because the same file name on two hosts is
105
+ * routinely a different model. A merged map served whichever host loaded first,
106
+ * so on the other host the overlay showed the wrong model name and the prompt
107
+ * silently received the wrong trigger words — a bad generation with no error
108
+ * anywhere. Callers that know their host say so; the rest fall back to any host
109
+ * that has the lora, which is still better than nothing for a display name.
110
+ *
111
+ * Plain (non-observable) on purpose: the loras overlay reads this from inside a
112
+ * mobx render. The storage seam has no readdir, so the host set comes from
113
+ * `comfyts.hosts` — exactly the hosts this process can be asked about.
114
+ */
115
+ const byHost = new Map<string, Map<string, LmLoraItem>>()
116
+ /** hosts already looked for, INCLUDING the ones with no mirror (see reloadLoraInfoCache) */
117
+ const loadedHostIds = new Set<string>()
118
+
119
+ function ensureLoaded(): void {
120
+ for (const hostId of comfyts.hosts.keys()) {
121
+ if (loadedHostIds.has(hostId)) continue
122
+ loadedHostIds.add(hostId)
123
+ const mirror = readLoraMirror(hostId)
124
+ if (mirror == null) continue
125
+ byHost.set(hostId, new Map(Object.entries(mirror.loras)))
126
+ }
127
+ }
128
+
129
+ /**
130
+ * forget everything loaded, so the next read picks up a fresh `comfy-ts loras`.
131
+ * A long-lived process (the TUI, `comfy-ts serve`) has no other way to see a
132
+ * re-sync that happened in another terminal.
133
+ */
134
+ export function reloadLoraInfoCache(): void {
135
+ byHost.clear()
136
+ loadedHostIds.clear()
137
+ }
138
+
139
+ /**
140
+ * the lm item for a raw lora name (`styles\x.safetensors`).
141
+ * `hostId` picks the mirror that actually describes this host's file; without
142
+ * it, any host that knows the name answers. null when unsynced/unknown.
143
+ */
144
+ export function getLoraInfo(name: string, hostId?: string): LmLoraItem | null {
145
+ ensureLoaded()
146
+ const key = loraKey(name)
147
+ if (hostId != null) {
148
+ const own = byHost.get(hostId)
149
+ // a host WITH a mirror is authoritative about its own loras: never fall
150
+ // back to another host's entry for a lora it does not have
151
+ if (own != null) return own.get(key) ?? null
152
+ }
153
+ for (const mirror of byHost.values()) {
154
+ const hit = mirror.get(key)
155
+ if (hit != null) return hit
156
+ }
157
+ return null
158
+ }
159
+
160
+ /** civitai trigger words for this lora, in civitai's order */
161
+ export function getLoraTriggerWords(name: string, hostId?: string): string[] {
162
+ const info = getLoraInfo(name, hostId)
163
+ return info == null ? [] : lmTrainedWords(info)
164
+ }
165
+
166
+ /** the human name (`Aurora Ink Wash`), falling back to the file's own name */
167
+ export function getLoraDisplayName(name: string, hostId?: string): string {
168
+ const info = getLoraInfo(name, hostId)
169
+ return (info == null ? null : lmModelName(info)) ?? loraBasename(name)
170
+ }
171
+
172
+ /** server-relative preview url from the mirror, null when unsynced/unknown */
173
+ export function getLoraPreviewUrl(name: string, hostId?: string): string | null {
174
+ const info = getLoraInfo(name, hostId)
175
+ return info == null ? null : lmPreviewUrl(info)
176
+ }
177
+
178
+ /** the lora's NAMES: the file, and the model name a human would call it by */
179
+ export function loraSearchNames(name: string, hostId?: string): string[] {
180
+ const names = [loraBasename(name), name.replaceAll('\\', '/')]
181
+ const info = getLoraInfo(name, hostId)
182
+ const modelName = info == null ? null : lmModelName(info)
183
+ if (modelName != null) names.push(modelName)
184
+ return names
185
+ }
186
+
187
+ /** the lora's FREE TEXT: tags, base model, trigger words */
188
+ export function loraSearchText(name: string, hostId?: string): string[] {
189
+ const info = getLoraInfo(name, hostId)
190
+ if (info == null) return []
191
+ const text = [...lmTags(info), ...lmTrainedWords(info)]
192
+ const baseModel = lmBaseModel(info)
193
+ if (baseModel != null) text.push(baseModel)
194
+ return text
195
+ }
196
+
197
+ /**
198
+ * the loras overlay filter: find a lora by its human name, not only by the file
199
+ * name. EVERY whitespace-separated token must be a SUBSTRING of some field — order
200
+ * free, so `aurora ink`, `ink aurora` and `styles wash` all land on the same
201
+ * lora. NOT fuzzyMatch: a subsequence match over phrases this long matches
202
+ * nearly everything. Measured on a real collection, filtering by each lora's
203
+ * own file name: this rule peaks at 8 hits where fuzzyMatch matched a third of
204
+ * every lora present.
205
+ * Fields are matched one by one, never as a concatenated haystack, for the same
206
+ * reason. `tests/lora-corpus.private.test.ts` keeps that measurement runnable.
207
+ */
208
+ export function loraMatchesFilter(name: string, filter: string, hostId?: string): boolean {
209
+ const tokens = filter
210
+ .toLowerCase()
211
+ .split(/\s+/)
212
+ .filter((t) => t !== '')
213
+ if (tokens.length === 0) return true
214
+ const fields = [...loraSearchNames(name, hostId), ...loraSearchText(name, hostId)].map((f) => f.toLowerCase())
215
+ return tokens.every((token) => fields.some((field) => field.includes(token)))
216
+ }
@@ -1,5 +1,8 @@
1
1
  import { type } from 'arktype'
2
+ import { basename } from 'pathe'
2
3
  import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
4
+ import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
+ import { isRecord } from 'src/utils/isRecord.ts'
3
6
  import { sha1HexOfString } from 'src/utils/sha1.ts'
4
7
  import type { ComfyHost } from 'src/host/ComfyHost.ts'
5
8
  import { logError } from 'src/utils/log.ts'
@@ -9,52 +12,153 @@ import { logError } from 'src/utils/log.ts'
9
12
  * absent extension = normal condition: callers get null/empty and degrade.
10
13
  */
11
14
 
12
- const lmLoraItem = type({
13
- folder: 'string',
14
- file_name: 'string',
15
- preview_url: 'string',
16
- })
15
+ /**
16
+ * one lora exactly as lora-manager sent it. RAW on purpose (agent/architecture
17
+ * item 8): the mirror on disk keeps every field, including the ones we do not
18
+ * read yet, so adding `sha256` or `civitai.modelId` to a surface later is an
19
+ * accessor, not a re-sync. Reading goes through the checked lm* helpers below.
20
+ */
21
+ export type LmLoraItem = Record<string, unknown>
22
+
23
+ /** only the ENVELOPE is schema'd — items stay unknown so nothing can strip their fields */
17
24
  const lmLoraPage = type({
18
- items: lmLoraItem.array(),
19
- total: 'number',
25
+ items: 'unknown[]',
26
+ 'total?': 'number',
20
27
  })
21
28
 
22
- /** normalize an object_info lora name OR an lm folder/file pair to one key */
23
- export function loraPreviewKey(name: string): string {
29
+ function readString(item: LmLoraItem, key: string): string | null {
30
+ const v = item[key]
31
+ return typeof v === 'string' && v !== '' ? v : null
32
+ }
33
+
34
+ function readStringArray(item: LmLoraItem, key: string): string[] {
35
+ const v = item[key]
36
+ if (!Array.isArray(v)) return []
37
+ return v.filter((x): x is string => typeof x === 'string' && x !== '')
38
+ }
39
+
40
+ export function lmFileName(item: LmLoraItem): string | null {
41
+ return readString(item, 'file_name')
42
+ }
43
+ export function lmFolder(item: LmLoraItem): string {
44
+ return readString(item, 'folder') ?? ''
45
+ }
46
+ export function lmModelName(item: LmLoraItem): string | null {
47
+ return readString(item, 'model_name')
48
+ }
49
+ export function lmBaseModel(item: LmLoraItem): string | null {
50
+ return readString(item, 'base_model')
51
+ }
52
+ export function lmPreviewUrl(item: LmLoraItem): string | null {
53
+ return readString(item, 'preview_url')
54
+ }
55
+ export function lmTags(item: LmLoraItem): string[] {
56
+ return readStringArray(item, 'tags')
57
+ }
58
+
59
+ /** the trigger words: civitai's `trainedWords`, absent for a lora nobody published */
60
+ export function lmTrainedWords(item: LmLoraItem): string[] {
61
+ const civitai = item['civitai']
62
+ if (!isRecord(civitai)) return []
63
+ return readStringArray(civitai, 'trainedWords')
64
+ }
65
+
66
+ /** lm's own absolute path for the file, as it exists on the HOST's disk */
67
+ export function lmFilePath(item: LmLoraItem): string | null {
68
+ return readString(item, 'file_path')
69
+ }
70
+
71
+ /**
72
+ * the ONE key space where a host's object_info spelling of a lora meets
73
+ * lora-manager's: lowercase, forward slashes, no model extension.
74
+ * `styles\Aurora.safetensors` and lm's folder `styles` + file_name `aurora`
75
+ * both become `styles/aurora`.
76
+ */
77
+ export function loraKey(name: string): string {
24
78
  return name
25
79
  .replaceAll('\\', '/')
26
80
  .replace(/\.(safetensors|st|pt|ckpt)$/i, '')
27
81
  .toLowerCase()
28
82
  }
29
83
 
84
+ /** the file's own name, windows separators included (`styles\x.safetensors` → `x.safetensors`) */
85
+ export function loraBasename(name: string): string {
86
+ return basename(name.replaceAll('\\', '/'))
87
+ }
88
+
89
+ /** the mirror key for an lm item: its folder/file_name pair, normalized */
90
+ export function lmItemKey(item: LmLoraItem): string | null {
91
+ const file = lmFileName(item)
92
+ if (file == null) return null
93
+ const folder = lmFolder(item)
94
+ return loraKey(folder === '' ? file : `${folder}/${file}`)
95
+ }
96
+
97
+ /** runaway stop: 20 pages × the server's 100-per-page cap = 2000 loras */
98
+ const MAX_PAGES = 20
99
+
30
100
  /**
31
- * fetch every lora known to lora-manager, mapped `loraPreviewKey` → preview_url
32
- * (server-relative). Returns null when the extension is absent (404/network).
101
+ * the outcome of a sweep, DISCRIMINATED. A bare `null` for "no loras" conflated
102
+ * three very different situations, and callers then told the user the wrong one:
103
+ * a host that is merely DOWN was reported as "extension not detected", and a
104
+ * sweep cut short mid-collection was indistinguishable from a complete one, so
105
+ * a partial mirror could overwrite a good one and report success.
33
106
  */
34
- export async function fetchLoraPreviewMap(host: ComfyHost): Promise<Map<string, string> | null> {
35
- const map = new Map<string, string>()
36
- const pageSize = 500
37
- for (let page = 1; page <= 20; page++) {
107
+ export type LoraSweep =
108
+ | { status: 'ok'; items: LmLoraItem[] }
109
+ /** the extension answered, then stopped answering: `items` is INCOMPLETE, never write it over a good mirror */
110
+ | { status: 'partial'; items: LmLoraItem[]; reason: string }
111
+ /** no ComfyUI-Lora-Manager on this host (404 on the first page) */
112
+ | { status: 'absent' }
113
+ /** the host itself could not be reached (down, refused, auth) */
114
+ | { status: 'unreachable'; reason: string }
115
+
116
+ /**
117
+ * every lora lora-manager knows, RAW, in one paged sweep.
118
+ * page_size asks for 500; the server caps it at 100, so the loop follows `total`.
119
+ */
120
+ export async function fetchLoraList(host: ComfyHost): Promise<LoraSweep> {
121
+ const items: LmLoraItem[] = []
122
+ for (let page = 1; page <= MAX_PAGES; page++) {
38
123
  let res: Response
39
124
  try {
40
125
  // the extension registers under /api — already prefixed, skip the probe
41
- res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=${pageSize}`, {}, { apiPrefix: false })
42
- } catch {
43
- return null // host unreachable (or auth-refused): previews off, not an error
126
+ res = await host.fetch(`/api/lm/loras/list?page=${page}&page_size=500`, {}, { apiPrefix: false })
127
+ } catch (e) {
128
+ const reason = `host unreachable at page ${page}: ${extractErrorMessage(e)}`
129
+ return page === 1 ? { status: 'unreachable', reason } : partial(items, reason)
130
+ }
131
+ if (!res.ok) {
132
+ if (page === 1) return { status: 'absent' } // 404 on page 1 = extension absent
133
+ return partial(items, `page ${page} answered ${res.status}`)
44
134
  }
45
- if (!res.ok) return page === 1 ? null : map // 404 on page 1 = extension absent
46
135
  const json: unknown = await res.json()
47
136
  const parsed = lmLoraPage(json)
48
137
  if (parsed instanceof type.errors) {
49
- // wire tolerance (agent/coding.md): lm drifts faster than our schema — LOG then bail
50
- logError(`[loraManagerApi] /api/lm/loras/list page ${page} shape mismatch: ${parsed.summary}`)
51
- return map
52
- }
53
- for (const item of parsed.items) {
54
- const rel = item.folder === '' ? item.file_name : `${item.folder}/${item.file_name}`
55
- map.set(loraPreviewKey(rel), item.preview_url)
138
+ // wire tolerance (agent/coding.md): lm drifts faster than our schema
139
+ return partial(items, `page ${page} shape mismatch: ${parsed.summary}`)
56
140
  }
57
- if (map.size >= parsed.total || parsed.items.length === 0) break
141
+ const pageItems = parsed.items.filter(isRecord)
142
+ items.push(...pageItems)
143
+ const total = parsed.total
144
+ if (pageItems.length === 0 || (total != null && items.length >= total)) return { status: 'ok', items }
145
+ }
146
+ return partial(items, `stopped at the ${MAX_PAGES}-page runaway limit`)
147
+ }
148
+
149
+ /** a truncated sweep is LOUD at the source, whatever the caller then decides to do */
150
+ function partial(items: LmLoraItem[], reason: string): LoraSweep {
151
+ logError(`[loraManagerApi] lora sweep INCOMPLETE after ${items.length} loras — ${reason}`)
152
+ return { status: 'partial', items, reason }
153
+ }
154
+
155
+ /** `loraKey` → server-relative preview_url */
156
+ export function loraPreviewMapFrom(items: LmLoraItem[]): Map<string, string> {
157
+ const map = new Map<string, string>()
158
+ for (const item of items) {
159
+ const key = lmItemKey(item)
160
+ const url = lmPreviewUrl(item)
161
+ if (key != null && url != null) map.set(key, url)
58
162
  }
59
163
  return map
60
164
  }
@@ -261,7 +261,7 @@ export class ComfyExecution {
261
261
 
262
262
  /** re-encode when asked, then write under OUR local naming — never the raw
263
263
  * server filename: a cloud host resets its _00001_ counter per run, so the
264
- * server name overwrote the same local file on every run (his repro 2026-07-31) */
264
+ * server name overwrote the same local file on every run */
265
265
  private encodeAndWrite = async (p: {
266
266
  bytes: Uint8Array
267
267
  sf: SaveOptions
@@ -1,6 +1,6 @@
1
1
  /**
2
- * local output naming, relative to `.comfy-ts/outputs/` (his repro
3
- * 2026-07-31): the server filename is NOT unique — cloud hosts reset the
2
+ * local output naming, relative to `.comfy-ts/outputs/`:
3
+ * the server filename is NOT unique — cloud hosts reset the
4
4
  * `_00001_` counter every run, so trusting it overwrote the same file — and
5
5
  * a `foo/krea/` prefix means the DIRECTORY foo/krea/, not a `krea_` name
6
6
  * prefix. Local names are ours: dir from the prompt's own filename_prefix
@@ -60,7 +60,7 @@ export const withExtension = (path: string, ext: string): string => {
60
60
  /**
61
61
  * never-overwrite guard: bump `-2`, `-3`, … while the path exists on disk OR
62
62
  * was already CLAIMED by a still-downloading retrieval (two same-second runs
63
- * on a counter-resetting cloud host compute the same name — reviewer catch).
63
+ * on a counter-resetting cloud host compute the same name).
64
64
  * The chosen path is claimed before returning.
65
65
  */
66
66
  export const uniquifyOutputPath = (p: {
@@ -0,0 +1,4 @@
1
+ /** narrows unknown wire json to an indexable object (arrays and null excluded) */
2
+ export function isRecord(v: unknown): v is Record<string, unknown> {
3
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
4
+ }
@@ -11,8 +11,8 @@ import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
11
11
  * the var's CLASS, and the only safe way to discriminate one: `instanceof` compares class
12
12
  * OBJECTS, and the published package hands the same class out twice — a consumer's
13
13
  * `.cflow.ts` imports `comfy-ts` (dist/index.js) while `comfy-ts serve`/`tui` run from the
14
- * cli bundle, so every `instanceof XVar` across that boundary is false (his repro
15
- * 2026-07-31: "var 'prompt' has unsupported kind 'text'" for EVERY kind). A string tag
14
+ * cli bundle, so every `instanceof XVar` across that boundary is false (observed
15
+ * in a consumer app: "var 'prompt' has unsupported kind 'text'", for EVERY kind). A string tag
16
16
  * crosses bundles; a class identity does not.
17
17
  */
18
18
  export type VarKind = 'text' | 'prompt' | 'int' | 'float' | 'seed' | 'toggle' | 'choice' | 'loras' | 'size' | 'image'
@@ -92,8 +92,11 @@ export class TextVar extends ComfyVar<string> {
92
92
  const commentLineRe = /^\s*\/\//
93
93
  const negativeLineRe = /^\s*- (.*)$/
94
94
 
95
- /** what PromptVar needs from a loras var: covariant face, so LorasVar<'a'|'b'> fits */
96
- export type ActiveLoraSource = { activeNames(): string[] }
95
+ /** what PromptVar needs from a loras var: covariant face, so LorasVar<'a'|'b'> fits.
96
+ * `hostId` scopes the keyword lookup: the same file name on two hosts is often a
97
+ * different model, and injecting the other host's trigger words is a silently
98
+ * wrong generation. */
99
+ export type ActiveLoraSource = { activeNames(): string[]; hostId?: string }
97
100
 
98
101
  /** what a prompt CONTRIBUTES to build: `vars.prompt.positive` / `.negative` */
99
102
  export type PromptValue = { positive: string; negative: string }
@@ -134,7 +137,7 @@ export class PromptVar extends ComfyVarBase<string, PromptValue> {
134
137
  ...new Set(
135
138
  src
136
139
  .activeNames()
137
- .map(getLoraKeyword)
140
+ .map((name) => getLoraKeyword(name, src.hostId))
138
141
  .filter((k) => k !== ''),
139
142
  ),
140
143
  ]
@@ -329,7 +332,7 @@ export function activeLoras<T extends string>(loras: Partial<Record<T, LoraStren
329
332
  }
330
333
 
331
334
  /** what LorasVar.bindHost needs — structural, so ComfyVars never imports ComfyHost */
332
- export type LorasHost = { schema: { getLoras(filter?: RegExp): string[] } }
335
+ export type LorasHost = { data?: { id?: string }; schema: { getLoras(filter?: RegExp): string[] } }
333
336
 
334
337
  /**
335
338
  * multi-select lora stack over a DYNAMIC options list — a RegExp resolves
@@ -343,6 +346,8 @@ export class LorasVar<T extends string> extends ComfyVar<Partial<Record<T, LoraS
343
346
  private prev: Partial<Record<T, LoraStrength>> = {}
344
347
  /** a RegExp source resolves lazily (bindHost) — null until then */
345
348
  private resolvedOptions: readonly T[] | null = null
349
+ /** which host these loras live on, so their metadata is read from ITS mirror */
350
+ hostId: string | undefined = undefined
346
351
 
347
352
  constructor(
348
353
  private readonly optionsSource: readonly T[] | RegExp,
@@ -365,6 +370,7 @@ export class LorasVar<T extends string> extends ComfyVar<Partial<Record<T, LoraS
365
370
  * cast: whitelist family 1 (agent/coding.md) — getLoras() returns the runtime
366
371
  * values of the SAME object_info enum the generated E_LoraName union comes from */
367
372
  bindHost(host: LorasHost): void {
373
+ this.hostId = host.data?.id
368
374
  if (!(this.optionsSource instanceof RegExp)) return
369
375
  this.resolvedOptions = host.schema.getLoras(this.optionsSource) as T[]
370
376
  }
@@ -461,7 +467,7 @@ export const DEFAULT_SIZE_PRESETS: SizePreset[] = [
461
467
  ]
462
468
 
463
469
  /** width/height picker: presets + free `WxH` entry + optionally the LIVE
464
- * size of a linked image var (his ask 2026-07-30: the widget shows
470
+ * size of a linked image var (the widget shows
465
471
  * `WxH size of image '<name>'` as a pickable row) */
466
472
  export class SizeVar extends ComfyVar<SizeValue> {
467
473
  readonly kind = 'size' as const
@@ -1,5 +1,6 @@
1
1
  import { observable, runInAction } from 'mobx'
2
2
  import { join } from 'pathe'
3
+ import { getLoraTriggerWords } from 'src/host/loraInfoCache.ts'
3
4
  import { getComfyStorage } from 'src/storage/ComfyStorage.ts'
4
5
  import { logError } from 'src/utils/log.ts'
5
6
 
@@ -9,6 +10,12 @@ import { logError } from 'src/utils/log.ts'
9
10
  * `.comfy-ts/lora-keywords.json` (NOT under cache/: this is hand-entered data
10
11
  * and must survive a cache wipe). Observable map: overlay rows re-render on
11
12
  * assignment. Keys are the RAW lora names (folder/file.safetensors).
13
+ *
14
+ * This file is the OVERRIDE layer. Below it sits the lora-manager mirror's
15
+ * civitai trigger words (src/host/loraInfoCache.ts, refreshed by
16
+ * `comfy-ts loras`), so most loras carry a keyword without anyone typing one.
17
+ * The overlay renders a mirror-sourced keyword dim and a hand-typed one yellow,
18
+ * and ⌃D drops the override to fall back to the mirror again.
12
19
  */
13
20
  const keywords = observable.map<string, string>()
14
21
  let loaded = false
@@ -34,19 +41,55 @@ function loadOnce(): void {
34
41
  }
35
42
  }
36
43
 
37
- export function getLoraKeyword(name: string): string {
44
+ /** the hand keyword when this lora HAS an entry (`''` included), else the mirror's trigger words */
45
+ export function getLoraKeyword(name: string, hostId?: string): string {
38
46
  loadOnce()
39
- return keywords.get(name) ?? ''
47
+ const hand = keywords.get(name)
48
+ if (hand != null) return hand
49
+ return getLoraTriggerWords(name, hostId).join(', ')
40
50
  }
41
51
 
42
- /** empty keyword deletes the entry; every set writes the file (tiny, rare) */
43
- export function setLoraKeyword(name: string, keyword: string): void {
52
+ /** true when the keyword shown comes from the lora-manager mirror, not from ⌃K */
53
+ export function isLoraKeywordFromMirror(name: string, hostId?: string): boolean {
54
+ loadOnce()
55
+ return !keywords.has(name) && getLoraTriggerWords(name, hostId).length > 0
56
+ }
57
+
58
+ /** what `clearLoraKeywordOverride` would restore this lora to, `''` when nothing */
59
+ export function loraKeywordFromMirror(name: string, hostId?: string): string {
60
+ return getLoraTriggerWords(name, hostId).join(', ')
61
+ }
62
+
63
+ /**
64
+ * drop the hand entry entirely, so the mirror's trigger words apply again.
65
+ * The way BACK from an empty-string tombstone: without it, clearing a keyword on
66
+ * a lora that has trigger words was a one-way door only a text editor could undo.
67
+ */
68
+ export function clearLoraKeywordOverride(name: string): void {
69
+ loadOnce()
70
+ if (!keywords.has(name)) return
71
+ runInAction(() => void keywords.delete(name))
72
+ writeKeywords()
73
+ }
74
+
75
+ /**
76
+ * empty keyword deletes the entry — EXCEPT when the mirror has trigger words for
77
+ * this lora: there `''` is stored as an explicit tombstone, the only way to say
78
+ * "inject nothing" about a lora civitai gave words to. Every set writes the file
79
+ * (tiny, rare).
80
+ */
81
+ export function setLoraKeyword(name: string, keyword: string, hostId?: string): void {
44
82
  loadOnce()
45
83
  const trimmed = keyword.trim()
46
84
  runInAction(() => {
47
- if (trimmed === '') keywords.delete(name)
85
+ if (trimmed === '' && getLoraTriggerWords(name, hostId).length === 0) keywords.delete(name)
48
86
  else keywords.set(name, trimmed)
49
87
  })
88
+ writeKeywords()
89
+ }
90
+
91
+ /** every set writes the file: it is tiny and hand-edited rarely */
92
+ function writeKeywords(): void {
50
93
  const path = filePath()
51
94
  try {
52
95
  getComfyStorage().writeText(path, JSON.stringify(Object.fromEntries([...keywords.entries()].sort()), null, 2))