comfy-ts 2.2.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 (54) 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 +292 -24
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -9
  11. package/dist/index.d.ts +147 -9
  12. package/dist/index.js +280 -25
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-serve-C1oo5ilG.js → run-serve-C9E8dyLP.js} +7 -3
  15. package/dist/run-serve-C9E8dyLP.js.map +1 -0
  16. package/dist/{run-tui-CuVst-nc.js → run-tui-cawSJuuh.js} +60 -121
  17. package/dist/run-tui-cawSJuuh.js.map +1 -0
  18. package/dist/{state-CvMt0W1-.js → state-BbKuSDCV.js} +38 -77
  19. package/dist/state-BbKuSDCV.js.map +1 -0
  20. package/dist/web.d.ts +147 -9
  21. package/dist/web.js +280 -25
  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/ServeApp.ts +4 -0
  30. package/src/cli/serve/applyVarPayload.ts +1 -1
  31. package/src/cli/tui/components/LorasOverlay.tsx +18 -5
  32. package/src/cli/tui/components/StatusBar.tsx +1 -0
  33. package/src/cli/tui/components/TuiApp.tsx +1 -0
  34. package/src/cli/tui/imageClipboard.ts +3 -3
  35. package/src/cli/tui/protocolImagePainter.ts +1 -1
  36. package/src/cli/tui/run-tui.tsx +2 -2
  37. package/src/cli/tui/state/ExecSt.ts +2 -2
  38. package/src/cli/tui/state/HostSt.ts +1 -1
  39. package/src/cli/tui/state/LorasSt.ts +60 -15
  40. package/src/cli/tui/state/PreviewSt.ts +1 -1
  41. package/src/cli/tui/state/SettingsSt.ts +1 -1
  42. package/src/coreExports.ts +21 -1
  43. package/src/host/ComfyHost.ts +51 -3
  44. package/src/host/loraInfoCache.ts +216 -0
  45. package/src/host/loraManagerApi.ts +131 -27
  46. package/src/runner/ComfyExecution.ts +1 -1
  47. package/src/runner/outputPath.ts +3 -3
  48. package/src/utils/isRecord.ts +4 -0
  49. package/src/vars/ComfyVars.ts +13 -7
  50. package/src/vars/loraKeywords.ts +48 -5
  51. package/dist/DefinedWorkflow-CwHInZgn.js.map +0 -1
  52. package/dist/run-serve-C1oo5ilG.js.map +0 -1
  53. package/dist/run-tui-CuVst-nc.js.map +0 -1
  54. package/dist/state-CvMt0W1-.js.map +0 -1
@@ -92,9 +92,12 @@ Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`, `v.si
92
92
  ```bash
93
93
  bunx comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] # codegen
94
94
  bunx comfy-ts outline [file] [--section Name] [--lines N] # inspect a sdk.d.ts
95
+ bunx comfy-ts loras [--id <host-id>] [--host http://…] # mirror lora metadata (optional ComfyUI-Lora-Manager extension)
95
96
  bunx comfy-ts tui [dir | module.cflow.ts] # interactive tweak & re-run
96
97
  ```
97
98
 
99
+ `comfy-ts loras` writes `.comfy-ts/hosts/<id>/loras.json`: per lora, the model's real name, its civitai trigger words, tags, base model and preview url, stored raw. It is what makes `v.prompt(text, { loraKeywordsFrom: lorasVar })` inject a lora's trigger words with nothing typed by hand, and what lets the TUI find a lora by its human name. Read it yourself (`getLoraInfo`, `getLoraTriggerWords`, `getLoraDisplayName`) when a user asks which lora to pick. Absent extension or no sync yet: every getter answers empty, nothing breaks.
100
+
98
101
  The TUI scans `**/*.cflow.ts` (no arg: cwd PLUS the examples bundled with the package, grouped apart in the tree; an explicit dir or file limits to that scope), shows vars as editable knobs, runs with live progress and previews, and saves named drafts under `.comfy-ts/drafts/`. It re-execs through bun when launched under node (workflow modules are TypeScript, and node cannot import .ts from node_modules). Point users at it; as an agent you run modules with `bun path/to/module.cflow.ts`.
99
102
 
100
103
  ## Import and export ComfyUI JSON
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "description": "The complete TypeScript toolkit for ComfyUI and generative AI. Fully type-safe SDK with autocomplete on every node, companion CLI, TUI, agentic docs, and 50+ examples. Design, run and deploy creative pipelines for image, video, audio, 3d and text on any ComfyUI, local, cloud or hosted.",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -84,6 +84,7 @@
84
84
  "gen:sdk": "bun scripts/gen-sdk-from-cache.ts",
85
85
  "gen:sdk:cloud": "bun src/cli/comfy-ts-cli.ts gen --id comfy-cloud --host https://cloud.comfy.org --out examples/comfy-cloud/sdk.d.ts && oxfmt examples/comfy-cloud/sdk.d.ts",
86
86
  "sdk:outline": "bun scripts/sdk-outline.ts",
87
+ "loras": "bun src/cli/comfy-ts-cli.ts loras",
87
88
  "examples:images": "bun scripts/fetch-example-images.ts",
88
89
  "templates:fetch": "bun scripts/fetch-templates.ts",
89
90
  "templates:check": "bun scripts/check-templates.ts",
@@ -3,6 +3,7 @@
3
3
  import { spawnSync } from 'node:child_process'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import { runGen } from 'src/cli/gen.ts'
6
+ import { runLoras } from 'src/cli/loras.ts'
6
7
  import { runOutline } from 'src/cli/outline.ts'
7
8
 
8
9
  const HELP = `comfy-ts — typed SDK codegen for ComfyUI
@@ -17,6 +18,14 @@ Usage:
17
18
  comfy-ts outline [file] [--lines N] [--section Name]
18
19
  outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)
19
20
 
21
+ comfy-ts loras [--id <host-id>] [--host http://…] [--api-key <key>]
22
+ mirror what the optional ComfyUI-Lora-Manager extension knows about
23
+ every lora into .comfy-ts/hosts/<id>/loras.json: real model names,
24
+ civitai trigger words, tags, base model, preview urls. The TUI then
25
+ fuzzy-matches loras by their human name and auto-injects their trigger
26
+ words into v.prompt (⌃K still overrides, per lora). --id defaults to
27
+ the only host folder on disk, --host to the url the last sync used
28
+
20
29
  comfy-ts tui [dir | workflow-module.ts]
21
30
  interactive tweak & re-run over **/*.cflow.ts modules (exporting
22
31
  host.defineWorkflow(...)); no arg scans cwd + the examples bundled
@@ -35,6 +44,7 @@ async function main(): Promise<number> {
35
44
  const [cmd, ...rest] = process.argv.slice(2)
36
45
  if (cmd === 'gen') return runGen(rest)
37
46
  if (cmd === 'outline') return runOutline(rest)
47
+ if (cmd === 'loras') return runLoras(rest)
38
48
  if (cmd === 'tui' || cmd === 'serve') {
39
49
  // .cflow.ts workflow modules need bun: node refuses to strip types under
40
50
  // node_modules, exactly where the packaged examples live — and the bin's
@@ -60,4 +70,9 @@ async function main(): Promise<number> {
60
70
  return cmd == null || cmd === 'help' ? 0 : 1
61
71
  }
62
72
 
63
- process.exitCode = await main()
73
+ // a thrown command (a flag with no value, an unreadable path) must print ONE
74
+ // clear line and exit non-zero, never a raw unhandled-rejection stack
75
+ process.exitCode = await main().catch((e: unknown) => {
76
+ console.error(`[comfy-ts] 🔴 ${e instanceof Error ? e.message : String(e)}`)
77
+ return 1
78
+ })
@@ -0,0 +1,14 @@
1
+ /**
2
+ * the CLI's one flag reader: `--name value`.
3
+ * A flag written with no value after it is a TYPO, never a request for the
4
+ * default — silently falling back would run against the wrong host.
5
+ */
6
+ export function flagReader(args: string[]): (name: string) => string | null {
7
+ return (name: string): string | null => {
8
+ const ix = args.indexOf(`--${name}`)
9
+ if (ix < 0) return null
10
+ const value = args[ix + 1]
11
+ if (value == null || value.startsWith('--')) throw new Error(`--${name} needs a value`)
12
+ return value
13
+ }
14
+ }
package/src/cli/gen.ts CHANGED
@@ -1,16 +1,14 @@
1
1
  // fetch a live host's schema and generate its typed sdk
2
2
  import { mkdirSync, writeFileSync } from 'node:fs'
3
3
  import { dirname, join, resolve } from 'pathe'
4
+ import { flagReader } from 'src/cli/flags.ts'
4
5
  import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
5
6
  import type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
6
7
  import { ComfyTS } from 'src/state.ts'
7
8
  import { readableStringify } from 'src/utils/stringifyReadable.ts'
8
9
 
9
10
  export async function runGen(args: string[]): Promise<number> {
10
- const getFlag = (name: string): string | null => {
11
- const ix = args.indexOf(`--${name}`)
12
- return ix >= 0 ? (args[ix + 1] ?? null) : null
13
- }
11
+ const getFlag = flagReader(args)
14
12
  const hostUrl = getFlag('host') ?? 'http://127.0.0.1:8188'
15
13
  const id = getFlag('id')
16
14
  if (id == null) {
@@ -0,0 +1,113 @@
1
+ // refresh the local mirror of what ComfyUI-Lora-Manager knows about a host's loras
2
+ import { readdirSync } from 'node:fs'
3
+ import { join } from 'pathe'
4
+ import { flagReader } from 'src/cli/flags.ts'
5
+ import { buildLoraMirror, readLoraMirror, writeLoraMirror } from 'src/host/loraInfoCache.ts'
6
+ import { fetchLoraList, lmModelName, lmTrainedWords } from 'src/host/loraManagerApi.ts'
7
+ import { ComfyTS } from 'src/state.ts'
8
+
9
+ const DEFAULT_HOST_URL = 'http://127.0.0.1:8188'
10
+
11
+ /** host ids already known on disk — `.comfy-ts/hosts/<id>/` is created by `comfy-ts gen` */
12
+ function knownHostIds(): string[] {
13
+ try {
14
+ return readdirSync(join(process.cwd(), '.comfy-ts', 'hosts'), { withFileTypes: true })
15
+ .filter((e) => e.isDirectory())
16
+ .map((e) => e.name)
17
+ .sort()
18
+ } catch {
19
+ return []
20
+ }
21
+ }
22
+
23
+ export async function runLoras(args: string[]): Promise<number> {
24
+ const getFlag = flagReader(args)
25
+
26
+ // --id: explicit, else the only host folder on disk (unambiguous), else loud
27
+ const known = knownHostIds()
28
+ const explicitId = getFlag('id')
29
+ const id = explicitId ?? (known.length === 1 ? known[0] : null)
30
+ if (id == null) {
31
+ const hint =
32
+ known.length === 0 ? 'none yet — run `comfy-ts gen --id <host-id> --host <url>` first' : known.join(', ')
33
+ console.error(`[comfy-ts loras] 🔴 --id <host-id> is required (known: ${hint})`)
34
+ return 1
35
+ }
36
+ // a typo'd id used to be CREATED as a side effect of registering the host, and
37
+ // the junk folder then broke the `--id` default (and outline's) for good
38
+ if (explicitId != null && known.length > 0 && !known.includes(explicitId)) {
39
+ console.error(
40
+ `[comfy-ts loras] 🔴 unknown host id '${explicitId}' (known: ${known.join(', ')}). Run \`comfy-ts gen --id ${explicitId} --host <url>\` first if it is new.`,
41
+ )
42
+ return 1
43
+ }
44
+
45
+ // ComfyTS FIRST: every .comfy-ts path, the mirror's included, resolves through the global
46
+ const comfy = ComfyTS.create()
47
+
48
+ // --host: explicit, else the url the last sync remembered for this id
49
+ const previous = readLoraMirror(id)
50
+ const hostUrl = getFlag('host') ?? (previous?.hostUrl !== '' ? previous?.hostUrl : null) ?? DEFAULT_HOST_URL
51
+
52
+ const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY
53
+ const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })
54
+
55
+ console.log(`[comfy-ts loras] sweeping ${hostUrl} /api/lm/loras/list …`)
56
+ const sweep = await fetchLoraList(host)
57
+ if (sweep.status === 'absent') {
58
+ console.error(
59
+ `[comfy-ts loras] 🔴 ${hostUrl} has no ComfyUI-Lora-Manager: the extension is not installed there. Mirror left untouched.`,
60
+ )
61
+ return 1
62
+ }
63
+ if (sweep.status === 'unreachable') {
64
+ console.error(`[comfy-ts loras] 🔴 ${hostUrl} unreachable — ${sweep.reason}. Mirror left untouched.`)
65
+ return 1
66
+ }
67
+ if (sweep.status === 'partial') {
68
+ // writing this would DELETE loras from the mirror that are alive on the
69
+ // host, and every surface would then quietly not know them
70
+ console.error(
71
+ `[comfy-ts loras] 🔴 the sweep broke off after ${sweep.items.length} loras (${sweep.reason}). Writing that would drop every lora past it, so the mirror is left untouched. Re-run when the host is healthy.`,
72
+ )
73
+ return 1
74
+ }
75
+
76
+ const mirror = buildLoraMirror({ hostId: id, hostUrl, fetchedAt: new Date().toISOString(), items: sweep.items })
77
+ const path = writeLoraMirror(mirror)
78
+
79
+ // what actually moved since the last sync — the whole point of running it again
80
+ const before = previous?.loras ?? {}
81
+ const added: string[] = []
82
+ const changed: string[] = []
83
+ let withWords = 0
84
+ for (const [key, item] of Object.entries(mirror.loras)) {
85
+ const words = lmTrainedWords(item)
86
+ if (words.length > 0) withWords++
87
+ const old = before[key]
88
+ if (old == null) {
89
+ if (words.length > 0) added.push(`${key} → ${words.join(', ')}`)
90
+ else added.push(key)
91
+ } else if (lmTrainedWords(old).join('\0') !== words.join('\0')) {
92
+ changed.push(`${key} → ${words.length === 0 ? '(cleared)' : words.join(', ')}`)
93
+ }
94
+ }
95
+ const removed = Object.keys(before).filter((k) => mirror.loras[k] == null)
96
+
97
+ const sample = (label: string, lines: string[]): void => {
98
+ if (lines.length === 0) return
99
+ console.log(`[comfy-ts loras] ${label} (${lines.length}):`)
100
+ for (const line of lines.slice(0, 10)) console.log(` ${line}`)
101
+ if (lines.length > 10) console.log(` … +${lines.length - 10} more`)
102
+ }
103
+ sample('added', added)
104
+ sample('trigger words changed', changed)
105
+ sample('gone from the host', removed)
106
+
107
+ const named = Object.values(mirror.loras).filter((i) => lmModelName(i) != null).length
108
+ console.log(
109
+ `[comfy-ts loras] 🟢 ${path} — ${mirror.count} loras, ${withWords} with trigger words, ${named} with a model name`,
110
+ )
111
+ if (previous == null) console.log(`[comfy-ts loras] next time: \`comfy-ts loras --id ${id}\` (url remembered)`)
112
+ return 0
113
+ }
@@ -358,6 +358,10 @@ export class ServeApp {
358
358
  } catch (e) {
359
359
  // name, not instanceof: same two-copies problem as the var classes
360
360
  if (e instanceof Error && e.name === 'ImageVarEmptyError') return { status: 400, error: e.message }
361
+ // the ComfyUI host is upstream of this bridge: 502, not "serve crashed".
362
+ // The connect deadline (ConnectOptions.timeoutMs) is what makes this
363
+ // reachable at all — it used to hang here and block the module mutex
364
+ if (e instanceof Error && e.name === 'ComfyHostUnreachableError') return { status: 502, error: e.message }
361
365
  return { status: 500, error: extractErrorMessage(e) }
362
366
  }
363
367
  }
@@ -5,7 +5,7 @@
5
5
  // Discrimination is by `kind`, NEVER instanceof: a consumer's `.cflow.ts` imports
6
6
  // `comfy-ts` (dist/index.js) while `comfy-ts serve` runs from the cli bundle, and the
7
7
  // two hold different copies of every class, so instanceof was false for EVERY var and
8
- // every payload override answered "unsupported kind" (his repro 2026-07-31). The casts
8
+ // every payload override answered "unsupported kind". The casts
9
9
  // below are the sanctioned kind-narrowing family (agent/coding.md cast whitelist 6).
10
10
  import type {
11
11
  AnyVar,
@@ -1,8 +1,9 @@
1
1
  import { Text } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
- import { basename } from 'pathe'
4
3
  import { OverlayList } from 'src/cli/tui/components/OverlayList.tsx'
5
- import { getLoraKeyword } from 'src/vars/loraKeywords.ts'
4
+ import { getLoraDisplayName } from 'src/host/loraInfoCache.ts'
5
+ import { loraBasename } from 'src/host/loraManagerApi.ts'
6
+ import { getLoraKeyword, isLoraKeywordFromMirror } from 'src/vars/loraKeywords.ts'
6
7
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
7
8
 
8
9
  /** modal multi-select: tick/untick loras, filter, bulk ops, step strengths */
@@ -24,17 +25,29 @@ export const LorasOverlay = observer((p: { st: TuiSt }) => {
24
25
  lines={s.overlayLines}
25
26
  rows={names.map((name, ix) => {
26
27
  const on = lv.isOn(name)
27
- const keyword = getLoraKeyword(name)
28
+ const keyword = getLoraKeyword(name, lo.hostId)
29
+ // a keyword NOBODY typed reads as magic unless it looks different from
30
+ // one you set yourself: mirror-sourced is dim, hand-typed is not
31
+ const fromMirror = isLoraKeywordFromMirror(name, lo.hostId)
32
+ const file = loraBasename(name)
33
+ // the human name from the lora-manager mirror, shown only when it adds something
34
+ const display = getLoraDisplayName(name, lo.hostId)
28
35
  return {
29
36
  key: name,
30
37
  node: (
31
38
  // checked = whole row green with a bold checkmark (emoji checkboxes read identical at cell size)
32
39
  <Text key={name} inverse={ix === lo.ix} bold={on} color={on ? 'green' : 'gray'}>
33
40
  {ix === lo.ix ? '▸ ' : ' '}
34
- {on ? '✔' : '·'} {basename(name.replaceAll('\\', '/'))}
41
+ {on ? '✔' : '·'} {file}
35
42
  {on ? ` ${lv.strengthLabel(name)}` : ''}
43
+ {display !== file && (
44
+ <Text color="cyan" dimColor bold={false}>
45
+ {' '}
46
+ {display}
47
+ </Text>
48
+ )}
36
49
  {keyword !== '' && (
37
- <Text color="gray" dimColor bold={false}>
50
+ <Text color={fromMirror ? 'gray' : 'yellow'} dimColor={fromMirror} bold={false}>
38
51
  {' kw: '}
39
52
  {keyword}
40
53
  </Text>
@@ -116,6 +116,7 @@ const MODE_KEYS: Partial<Record<string, Hint[]>> = {
116
116
  ['←→', 'strength ±0.05'],
117
117
  ['type', 'filter'],
118
118
  ['⌃K', 'keyword'],
119
+ ['⌃D', 'reset keyword'],
119
120
  ['⌃A', 'all'],
120
121
  ['⌃N', 'none'],
121
122
  ['esc', 'done'],
@@ -89,6 +89,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
89
89
  if (key.ctrl && input === 'a') return lo.setAll(true)
90
90
  if (key.ctrl && input === 'n') return lo.setAll(false)
91
91
  if (key.ctrl && input === 'k') return lo.beginKeyword()
92
+ if (key.ctrl && input === 'd') return lo.resetKeyword()
92
93
  if (key.return || input === ' ') return lo.toggle()
93
94
  if (key.upArrow) return lo.move(-1)
94
95
  if (key.downArrow) return lo.move(1)
@@ -8,7 +8,7 @@ const extOf = (path: string): string => {
8
8
  }
9
9
 
10
10
  /** platform command that puts PNG bytes on the clipboard from STDIN — no
11
- * file ever touches disk (his ask 2026-07-31). The caller pipes `stdin`
11
+ * file ever touches disk. The caller pipes `stdin`
12
12
  * into the spawned process and closes it. */
13
13
  export type ImageClipboardStdinCommand = { cmd: string; args: string[]; stdin: Uint8Array }
14
14
 
@@ -52,7 +52,7 @@ export const imageClipboardCommand = (platform: NodeJS.Platform, path: string):
52
52
  if (platform === 'darwin') {
53
53
  // osascript TAGS bytes with the class, it never transcodes: PNGf on a
54
54
  // webp would paste garbage under a green popup — only png/jpeg pass;
55
- // the caller transcodes anything else to png first (reviewer catch)
55
+ // the caller transcodes anything else to png first
56
56
  if (ext !== 'png' && ext !== 'jpg' && ext !== 'jpeg') return null
57
57
  const cls = ext === 'png' ? '«class PNGf»' : 'JPEG picture'
58
58
  return {
@@ -62,7 +62,7 @@ export const imageClipboardCommand = (platform: NodeJS.Platform, path: string):
62
62
  }
63
63
  if (platform === 'win32') {
64
64
  // single-quoted PS string, inner quotes doubled: a double-quoted string
65
- // would interpolate $ and ` from user-controlled paths (reviewer catch)
65
+ // would interpolate $ and ` from user-controlled paths
66
66
  const psQuoted = `'${path.replaceAll("'", "''")}'`
67
67
  return {
68
68
  cmd: 'powershell',
@@ -16,7 +16,7 @@ const MIN_FRAME_BYTES = 64
16
16
  * re-paints SYNCHRONOUSLY within the same flush, the whole batch wrapped in
17
17
  * DEC 2026 synchronized-update markers: the terminal never presents the
18
18
  * erased-frame intermediate state. (The previous deferred setImmediate
19
- * repaint WAS the native-mode flicker — his repro.) A mobx reaction covers
19
+ * repaint WAS the native-mode flicker.) A mobx reaction covers
20
20
  * byte-only changes (fresh latent/output/lora bytes with no frame write).
21
21
  * NOT React: effects only fire for the component that re-rendered, which is
22
22
  * why a useEffect painter missed frames (his report: image waited for input).
@@ -116,7 +116,7 @@ export async function runTui(args: string[]): Promise<number> {
116
116
  // RAW MODE BEFORE RENDER: ink's kittyKeyboard auto-detect sends its `CSI ? u`
117
117
  // query from the Ink constructor, but raw mode only turns on later when
118
118
  // useInput mounts. In that window the terminal's `CSI ? 0 u` reply is echoed
119
- // by termios (ECHOCTL) as literal `^[[?0u` into the first frame (his repro).
119
+ // by termios (ECHOCTL) as literal `^[[?0u` into the first frame.
120
120
  // Raw mode off = echo on, so flip it ourselves first (inside the try so the
121
121
  // finally always restores); ink owns it afterwards and restores cooked mode
122
122
  // on exit.
@@ -138,7 +138,7 @@ export async function runTui(args: string[]): Promise<number> {
138
138
  uninstallPainter()
139
139
  // reset colors + erase WHILE STILL in the alt screen: ED deletes iTerm
140
140
  // inline images too — without this the last protocol image and stray
141
- // background colors survive into the shell (his repro)
141
+ // background colors survive into the shell
142
142
  if (altScreen) process.stdout.write('\u001b[0m\u001b[2J\u001b[H\u001b[>4;0m\u001b[?1049l')
143
143
  }
144
144
  return 0
@@ -182,7 +182,7 @@ export class ExecSt {
182
182
  // ---- clipboard ----
183
183
 
184
184
  /** `c`/`C` end HERE, success or failure — a copy must never be silent
185
- * (his repro: 'c does nothing', the notice line was too quiet) */
185
+ * (a silent copy reads as 'c does nothing': the notice line was too quiet) */
186
186
  copyPopup: { title: string; ok: boolean; lines: string[] } | null = null
187
187
 
188
188
  /** a copy build can hang on a stalled-host upload: guard double-presses */
@@ -210,7 +210,7 @@ export class ExecSt {
210
210
  }
211
211
  /** 'i': the LAST generated image's pixels → clipboard (paste anywhere).
212
212
  * The primary route pipes png bytes over stdin — no disk write at all
213
- * (his ask 2026-07-31); only when that tool fails does it fall back to
213
+ * ; only when that tool fails does it fall back to
214
214
  * the materialized-file command, and the popup says which route ran. */
215
215
  async copyLastImage(): Promise<void> {
216
216
  const lastImg = this.outputImages[this.outputImages.length - 1]
@@ -18,7 +18,7 @@ const SPIN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '
18
18
  * PURE probe verdict (headless-tested). http ok is proof enough; on http
19
19
  * failure a RECENTLY TALKING open ws still means up — ComfyUI is
20
20
  * single-threaded and stalls new connects mid-generation while established
21
- * sockets stream (his repro 2026-07-30: 'windows-1 offline' in the header
21
+ * sockets stream (observed: a host shown 'offline' in the header
22
22
  * while the browser tab generated fine). A half-open socket receives
23
23
  * nothing, so the recency window never revives one.
24
24
  */
@@ -1,13 +1,19 @@
1
1
  import { makeAutoObservable, reaction } from 'mobx'
2
- import { fetchLoraPreviewBytes, fetchLoraPreviewMap, loraPreviewKey } from 'src/host/loraManagerApi.ts'
2
+ import { getLoraPreviewUrl, loraMatchesFilter } from 'src/host/loraInfoCache.ts'
3
+ import { fetchLoraList, fetchLoraPreviewBytes, loraKey, loraPreviewMapFrom } from 'src/host/loraManagerApi.ts'
3
4
  import { imageBufferToAnsi } from 'src/utils/ansiImage.ts'
4
5
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
5
- import { fuzzyMatch } from 'src/utils/fuzzyMatch.ts'
6
6
  import { LorasVar } from 'src/vars/ComfyVars.ts'
7
- import { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
7
+ import {
8
+ clearLoraKeywordOverride,
9
+ getLoraKeyword,
10
+ isLoraKeywordFromMirror,
11
+ loraKeywordFromMirror,
12
+ setLoraKeyword,
13
+ } from 'src/vars/loraKeywords.ts'
8
14
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
9
15
 
10
- /** loras overlay: fuzzy filter + tick/untick + strengths + bulk ops + lora-manager preview */
16
+ /** loras overlay: filter + tick/untick + strengths + bulk ops + lora-manager metadata & preview */
11
17
  export class LorasSt {
12
18
  constructor(private st: TuiSt) {
13
19
  makeAutoObservable<LorasSt, 'st'>(this, { st: false })
@@ -30,12 +36,21 @@ export class LorasSt {
30
36
  return sel?.kind === 'loras' ? (sel as LorasVar<string>) : null
31
37
  }
32
38
 
33
- /** options surviving the fuzzy filter (bulk ops apply to exactly these) */
39
+ /** the host these loras live on: its mirror is the one that describes them */
40
+ get hostId(): string {
41
+ return this.st.wf.host.data.id
42
+ }
43
+
44
+ /**
45
+ * options surviving the filter (bulk ops apply to exactly these).
46
+ * The filter matches the file name OR anything the lora-manager mirror knows:
47
+ * model name, tags, base model, trigger words.
48
+ */
34
49
  get filteredNames(): string[] {
35
50
  const lv = this.selectedVar
36
51
  if (lv == null) return []
37
52
  if (this.filter === '') return lv.names
38
- return lv.names.filter((n) => fuzzyMatch(this.filter, n))
53
+ return lv.names.filter((n) => loraMatchesFilter(n, this.filter, this.hostId))
39
54
  }
40
55
 
41
56
  begin(): void {
@@ -92,17 +107,34 @@ export class LorasSt {
92
107
  beginKeyword(): void {
93
108
  const name = this.selectedName
94
109
  if (name == null) return
110
+ // the title must be honest about BOTH directions: on a lora the mirror gave
111
+ // trigger words to, empty does not "clear", it stores "inject nothing", and
112
+ // ⌃D is the only way back to the mirror value
113
+ const fromMirror = loraKeywordFromMirror(name, this.hostId)
114
+ const hint =
115
+ fromMirror === ''
116
+ ? 'empty clears'
117
+ : isLoraKeywordFromMirror(name, this.hostId)
118
+ ? 'from lora-manager · empty = inject nothing'
119
+ : `overrides lora-manager · ⌃D restores "${fromMirror}"`
95
120
  this.st.editor.beginCustom({
96
- title: `keyword for ${LorasVar.shortName(name)} (empty clears)`,
97
- initial: getLoraKeyword(name),
121
+ title: `keyword for ${LorasVar.shortName(name)} (${hint})`,
122
+ initial: getLoraKeyword(name, this.hostId),
98
123
  onCommit: (raw) => {
99
- setLoraKeyword(name, raw)
124
+ setLoraKeyword(name, raw, this.hostId)
100
125
  return true
101
126
  },
102
127
  returnMode: 'overlay-loras',
103
128
  })
104
129
  }
105
130
 
131
+ /** ⌃D: drop the hand keyword, so this lora falls back to lora-manager's trigger words */
132
+ resetKeyword(): void {
133
+ const name = this.selectedName
134
+ if (name == null) return
135
+ clearLoraKeywordOverride(name)
136
+ }
137
+
106
138
  // ---- lora-manager previews (optional extension, quiet degrade) ----
107
139
  get selectedName(): string | null {
108
140
  return this.filteredNames[this.ix] ?? null
@@ -111,6 +143,7 @@ export class LorasSt {
111
143
  /** undefined = not fetched yet · null = extension absent */
112
144
  private previewMap: Map<string, string> | null | undefined = undefined
113
145
  private previewMapHostId: string | null = null
146
+ private previewSweepStatus: 'ok' | 'partial' | 'absent' | 'unreachable' | null = null
114
147
  private _busy: boolean = false
115
148
 
116
149
  /** preview goes through PreviewSt's shared overlay slot (one code path with the image picker) */
@@ -125,13 +158,25 @@ export class LorasSt {
125
158
  this._busy = true
126
159
  try {
127
160
  const host = this.st.wf.host
128
- if (this.previewMap === undefined || this.previewMapHostId !== host.data.id) {
129
- this.previewMap = await fetchLoraPreviewMap(host)
130
- this.previewMapHostId = host.data.id
161
+ // the local mirror answers first (`comfy-ts loras`) — no request at all
162
+ let url = getLoraPreviewUrl(name, host.data.id)
163
+ let miss = 'no preview available'
164
+ if (url == null) {
165
+ // unsynced (or a lora the mirror never saw): ask the live host
166
+ if (this.previewMap === undefined || this.previewMapHostId !== host.data.id) {
167
+ const sweep = await fetchLoraList(host)
168
+ this.previewMap =
169
+ sweep.status === 'absent' || sweep.status === 'unreachable' ? null : loraPreviewMapFrom(sweep.items)
170
+ this.previewSweepStatus = sweep.status
171
+ this.previewMapHostId = host.data.id
172
+ }
173
+ url = this.previewMap?.get(loraKey(name)) ?? null
174
+ // each miss has its OWN cause, and naming the wrong one sends the user hunting
175
+ if (this.previewSweepStatus === 'absent') miss = 'lora-manager extension not detected'
176
+ else if (this.previewSweepStatus === 'unreachable') miss = 'host unreachable'
177
+ else if (this.previewSweepStatus === 'partial') miss = 'lora-manager answered only part of its list'
131
178
  }
132
- const map = this.previewMap
133
- const url = map?.get(loraPreviewKey(name))
134
- const note = map == null ? 'lora-manager extension not detected' : url == null ? 'no preview available' : null
179
+ const note = url != null ? null : miss
135
180
  if (url == null) {
136
181
  this.st.preview.setOverlayImage({ bytes: null, ansi: null, name: `lora ${name}`, note })
137
182
  return
@@ -202,7 +202,7 @@ export class PreviewSt {
202
202
  }
203
203
 
204
204
  /** corner cell box matched to the latent's REAL aspect (a mismatched box
205
- * letterboxes in iTerm — his repro: "some vertical rectangle"). Cells are
205
+ * letterboxes in iTerm, showing a tall rectangle). Cells are
206
206
  * ~1:2 (w:h), hence the ×2 when converting image aspect to cells. */
207
207
  get cornerBox(): { w: number; h: number } {
208
208
  let w = Math.max(8, Math.floor(this.width * CORNER_FRACTION))
@@ -70,7 +70,7 @@ export class SettingsSt {
70
70
  previewDuringRun: PreviewDuringRun = 'latent'
71
71
  /** module basename → the draft that was active last time (reopened on load) */
72
72
  lastDraft: Record<string, string> = {}
73
- /** path of the last OPEN workflow module — a no-arg `tui` reopens it (his ask 2026-07-30) */
73
+ /** path of the last OPEN workflow module — a no-arg `tui` reopens it */
74
74
  lastWorkflow: string | null = null
75
75
  /** the `h` host override, by host id (re-resolved once that host registers) */
76
76
  hostOverrideId: string | null = null
@@ -11,6 +11,7 @@ export { ComfyTS } from 'src/state.ts'
11
11
  export {
12
12
  ComfyHost,
13
13
  ComfyHostAuthError,
14
+ ComfyHostUnreachableError,
14
15
  type ComfyHostData,
15
16
  type ComfyHostID,
16
17
  type ConnectOptions,
@@ -102,7 +103,26 @@ export type {
102
103
  ImageVarOpts,
103
104
  } from 'src/vars/ComfyVars.ts'
104
105
  export { DefinedWorkflow, type DefineWorkflowSpec, type BoundVars, type LoraNameOf } from 'src/vars/DefinedWorkflow.ts'
105
- export { getLoraKeyword, setLoraKeyword } from 'src/vars/loraKeywords.ts'
106
+ export {
107
+ clearLoraKeywordOverride,
108
+ getLoraKeyword,
109
+ isLoraKeywordFromMirror,
110
+ loraKeywordFromMirror,
111
+ setLoraKeyword,
112
+ } from 'src/vars/loraKeywords.ts'
113
+ // the lora-manager mirror read model (refreshed by `comfy-ts loras`)
114
+ export { type LmLoraItem, type LoraSweep, loraKey } from 'src/host/loraManagerApi.ts'
115
+ export {
116
+ type LoraMirror,
117
+ getLoraDisplayName,
118
+ getLoraInfo,
119
+ getLoraPreviewUrl,
120
+ getLoraTriggerWords,
121
+ loraMatchesFilter,
122
+ loraSearchNames,
123
+ loraSearchText,
124
+ reloadLoraInfoCache,
125
+ } from 'src/host/loraInfoCache.ts'
106
126
  export { loraTag } from 'src/utils/loraTag.ts'
107
127
 
108
128
  // shared types