comfy-ts 2.6.0 → 2.8.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 (101) hide show
  1. package/README.md +22 -13
  2. package/dist/{DefinedWorkflow-BJgt5t0x.js → DefinedWorkflow-BatWaZO1.js} +199 -16
  3. package/dist/DefinedWorkflow-BatWaZO1.js.map +1 -0
  4. package/dist/{DraftsSt-dizp3VcC.js → LogsSt-DFxzQfDc.js} +152 -4
  5. package/dist/LogsSt-DFxzQfDc.js.map +1 -0
  6. package/dist/cli.js +8 -6
  7. package/dist/cli.js.map +1 -1
  8. package/dist/index.cjs +288 -35
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +128 -7
  11. package/dist/index.d.ts +128 -7
  12. package/dist/index.js +286 -37
  13. package/dist/index.js.map +1 -1
  14. package/dist/run-serve-_nrvJYyt.js +1948 -0
  15. package/dist/run-serve-_nrvJYyt.js.map +1 -0
  16. package/dist/{run-tui-idFhdO4f.js → run-tui-BPw-SZYW.js} +107 -158
  17. package/dist/run-tui-BPw-SZYW.js.map +1 -0
  18. package/dist/serve-web.js +434 -81
  19. package/dist/{state-C90kdjtB.js → state-B-boDz-Z.js} +184 -45
  20. package/dist/state-B-boDz-Z.js.map +1 -0
  21. package/dist/web.d.ts +112 -7
  22. package/dist/web.js +239 -36
  23. package/dist/web.js.map +1 -1
  24. package/examples/README.md +1 -0
  25. package/examples/comfy-cloud/sdk.d.ts +4066 -321
  26. package/examples/rvion/04-krea2-turbo-t2i.cflow.ts +18 -2
  27. package/examples/rvion/07-local-llm-text-gen.cflow.ts +220 -0
  28. package/examples/web/tsconfig.json +7 -1
  29. package/extra/README.md +32 -0
  30. package/extra/comfyui-textgen-stream/README.md +35 -0
  31. package/extra/comfyui-textgen-stream/__init__.py +166 -0
  32. package/extra/scripts/fetch_text_encoder.py +137 -0
  33. package/package.json +6 -3
  34. package/src/cli/comfy-ts-cli.ts +4 -2
  35. package/src/cli/serve/ServeApp.ts +825 -43
  36. package/src/cli/serve/applyVarPayload.ts +10 -3
  37. package/src/cli/serve/describeVar.ts +47 -7
  38. package/src/cli/serve/managerOnlyLoras.ts +27 -0
  39. package/src/cli/serve/run-serve.ts +58 -29
  40. package/src/cli/serve/serveSettings.ts +86 -0
  41. package/src/cli/serve/startupPrint.ts +111 -0
  42. package/src/cli/serve/web/api.ts +120 -1
  43. package/src/cli/serve/web/components/App.tsx +61 -22
  44. package/src/cli/serve/web/components/Gallery.tsx +243 -30
  45. package/src/cli/serve/web/components/Icon.tsx +160 -0
  46. package/src/cli/serve/web/components/PromptEnhancer.tsx +85 -38
  47. package/src/cli/serve/web/components/Sidebar.tsx +43 -19
  48. package/src/cli/serve/web/components/VarsForm.tsx +440 -80
  49. package/src/cli/serve/web/components/controls/BasicControls.tsx +38 -5
  50. package/src/cli/serve/web/components/controls/ImageControl.tsx +3 -2
  51. package/src/cli/serve/web/components/controls/LorasControl.tsx +498 -81
  52. package/src/cli/serve/web/components/controls/PresetPicker.tsx +60 -0
  53. package/src/cli/serve/web/components/controls/SeedControl.tsx +38 -20
  54. package/src/cli/serve/web/components/controls/SizeControl.tsx +3 -2
  55. package/src/cli/serve/web/llm.ts +254 -0
  56. package/src/cli/serve/web/logWeb.ts +6 -0
  57. package/src/cli/serve/web/state/EnhancerSt.ts +261 -157
  58. package/src/cli/serve/web/state/FormSt.ts +70 -18
  59. package/src/cli/serve/web/state/RunSt.ts +22 -1
  60. package/src/cli/serve/web/state/WebSt.ts +542 -13
  61. package/src/cli/serve/web/state/lightbox.ts +44 -0
  62. package/src/cli/serve/web/state/moduleTree.ts +52 -0
  63. package/src/cli/serve/web/state/payload.ts +44 -2
  64. package/src/cli/serve/web/state/urlSelection.ts +53 -0
  65. package/src/cli/serve/web/styles.ts +415 -57
  66. package/src/cli/serve/web/tsconfig.json +4 -0
  67. package/src/cli/tui/components/PickerOverlays.tsx +37 -0
  68. package/src/cli/tui/components/StatusBar.tsx +14 -1
  69. package/src/cli/tui/components/TuiApp.tsx +5 -2
  70. package/src/cli/tui/state/HostSt.ts +3 -2
  71. package/src/cli/tui/state/PickerSt.ts +48 -2
  72. package/src/cli/tui/state/TreeSt.ts +1 -1
  73. package/src/cli/tui/state/TuiSt.ts +2 -1
  74. package/src/coreExports.ts +8 -1
  75. package/src/graph/ComfyNode.ts +58 -1
  76. package/src/host/ComfyHost.ts +13 -2
  77. package/src/host/ComfyManager.ts +31 -13
  78. package/src/host/loraInfoCache.ts +35 -1
  79. package/src/host/loraManagerApi.ts +94 -0
  80. package/src/index.ts +2 -0
  81. package/src/promptEnhancers.ts +102 -0
  82. package/src/runner/ComfyExecution.ts +61 -6
  83. package/src/runner/ComfyWorkflow.ts +18 -4
  84. package/src/runner/ComfyWsApi.ts +3 -0
  85. package/src/runner/describePromptRejection.ts +34 -0
  86. package/src/sdk-generator/ComfySchema.ts +17 -4
  87. package/src/sdk-generator/comfyui-sdk-codegen.ts +56 -2
  88. package/src/state.ts +6 -0
  89. package/src/utils/ansi.ts +13 -0
  90. package/src/utils/matchesRegex.ts +13 -0
  91. package/src/utils/safeName.ts +29 -0
  92. package/src/utils/stringMap.ts +9 -0
  93. package/src/vars/ComfyVars.ts +61 -10
  94. package/src/vars/presets.ts +17 -0
  95. package/dist/DefinedWorkflow-BJgt5t0x.js.map +0 -1
  96. package/dist/DraftsSt-dizp3VcC.js.map +0 -1
  97. package/dist/run-serve-CVu39RNd.js +0 -1002
  98. package/dist/run-serve-CVu39RNd.js.map +0 -1
  99. package/dist/run-tui-idFhdO4f.js.map +0 -1
  100. package/dist/state-C90kdjtB.js.map +0 -1
  101. package/src/cli/serve/web/openrouter.ts +0 -142
@@ -38,7 +38,14 @@ function listSome(items: readonly string[], cap: number = 20): string {
38
38
  return `${items.slice(0, cap).join(', ')} … +${items.length - cap} more`
39
39
  }
40
40
 
41
- export function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {
41
+ /** `extraLoraOptions`: names the lora-manager mirror knows that ComfyUI's enum does not.
42
+ * they are accepted like any option, the file is on disk, so the run usually works, but
43
+ * ONLY those: an arbitrary name still fails, so a typo cannot reach the host */
44
+ export function applyVarPayload(
45
+ varDef: AnyVar,
46
+ raw: unknown,
47
+ opts: { extraLoraOptions?: readonly string[] } = {},
48
+ ): string | null {
42
49
  const name = varDef.name ?? varDef.label ?? varDef.kind
43
50
 
44
51
  switch (varDef.kind) {
@@ -100,10 +107,10 @@ export function applyVarPayload(varDef: AnyVar, raw: unknown): string | null {
100
107
  if (raw == null || typeof raw !== 'object' || Array.isArray(raw))
101
108
  return `var '${name}' expects {"<lora name>": false | true | strength | [model, clip]}`
102
109
  const record = raw as Record<string, unknown>
103
- const known = new Set<string>(v.options)
110
+ const known = new Set<string>([...v.options, ...(opts.extraLoraOptions ?? [])])
104
111
  const unknownNames = Object.keys(record).filter((k) => !known.has(k))
105
112
  if (unknownNames.length > 0)
106
- return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome(v.options)}`
113
+ return `var '${name}': unknown lora(s) ${unknownNames.join(', ')} — available: ${listSome([...known])}`
107
114
  for (const [k, st] of Object.entries(record))
108
115
  if (!isLoraStrength(st)) return `var '${name}': '${k}' must be false | true | number | [model, clip]`
109
116
  v.set(record as Partial<Record<string, LoraStrength>>) // every entry validated just above
@@ -1,5 +1,6 @@
1
1
  // PURE var → descriptor: ONE introspection pass feeds GET /drafts (json) AND
2
2
  // the startup print (renderDescriptorLine)
3
+ import { ansi } from 'src/utils/ansi.ts'
3
4
  import type {
4
5
  AnyVar,
5
6
  ChoiceVar,
@@ -7,11 +8,14 @@ import type {
7
8
  ImageVar,
8
9
  IntVar,
9
10
  LorasVar,
11
+ PromptVar,
10
12
  SeedVar,
11
13
  SizePreset,
12
14
  SizeVar,
15
+ TextVar,
13
16
  VarKind,
14
17
  } from 'src/vars/ComfyVars.ts'
18
+ import type { VarPreset } from 'src/vars/presets.ts'
15
19
 
16
20
  export type VarDescriptor = {
17
21
  kind: VarKind
@@ -24,12 +28,35 @@ export type VarDescriptor = {
24
28
  options?: readonly string[]
25
29
  /** loras: human display names from the lora-manager mirror, keyed by option — entries only where the label differs (filled by ServeApp.describeModule, which knows the host) */
26
30
  optionLabels?: Record<string, string>
31
+ /** prompt: the name of the loras var whose ACTIVE keywords prefix this prompt
32
+ * (`v.prompt(…, { loraKeywordsFrom })`), filled by ServeApp.describeModule, which is the
33
+ * only place that knows both vars by name. The panel previews the injection from it */
34
+ keywordsFrom?: string
35
+ /** loras: the regex the workflow narrowed the list with (`/krea-?2/i`), when it did */
36
+ optionsFilter?: string
37
+ /** loras: hand-assigned keyword (or trigger words) per option, entries only where one
38
+ * exists, what a prompt with `loraKeywordsFrom` will prepend */
39
+ optionKeywords?: Record<string, string>
40
+ /** loras: names the lora-manager mirror knows and ComfyUI's enum does NOT (yet). Offered in
41
+ * the picker with a warning, because a lora present on disk usually runs even when the
42
+ * server has not rescanned its list, filled by ServeApp.describeModule */
43
+ managerOnlyOptions?: readonly string[]
44
+ /** text: this one wants a box, not a line (`v.text(…, { multiline: true })`) */
45
+ multiline?: boolean
46
+ /** text + prompt: named starting texts (`{ presets: { label: text } }`). NOT `presets`, which
47
+ * a size var already owns with a different shape — one flat descriptor type, two kinds */
48
+ textPresets?: VarPreset[]
27
49
  min?: number
28
50
  max?: number
29
51
  presets?: SizePreset[]
30
52
  extensions?: readonly string[]
31
53
  }
32
54
 
55
+ /** an empty list is absent from the json: every var without presets would otherwise carry `[]` */
56
+ function presetsOrUndefined(presets: VarPreset[]): VarPreset[] | undefined {
57
+ return presets.length === 0 ? undefined : presets
58
+ }
59
+
33
60
  function rangeText(opts: { min?: number; max?: number }): string {
34
61
  if (opts.min == null && opts.max == null) return ''
35
62
  return ` (${opts.min ?? '-∞'}..${opts.max ?? '∞'})`
@@ -41,10 +68,18 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
41
68
  // different copies of every class (VarKind owns the WHY). Casts are the sanctioned
42
69
  // kind-narrowing family (agent/coding.md cast whitelist 6)
43
70
  switch (varDef.kind) {
44
- case 'prompt':
45
- return { ...base, payload: 'string ("//" lines = comments, "- " lines = negative)' }
46
- case 'text':
47
- return { ...base, payload: 'string' }
71
+ case 'prompt': {
72
+ const v = varDef as PromptVar
73
+ return {
74
+ ...base,
75
+ payload: 'string ("//" lines = comments, "- " lines = negative)',
76
+ textPresets: presetsOrUndefined(v.presets),
77
+ }
78
+ }
79
+ case 'text': {
80
+ const v = varDef as TextVar
81
+ return { ...base, payload: 'string', multiline: v.opts.multiline, textPresets: presetsOrUndefined(v.presets) }
82
+ }
48
83
  case 'int': {
49
84
  const v = varDef as IntVar
50
85
  return { ...base, payload: `integer${rangeText(v.opts)}`, min: v.opts.min, max: v.opts.max }
@@ -76,6 +111,8 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
76
111
  ...base,
77
112
  payload: '{"<lora name>": false | true | strength | [model, clip]}',
78
113
  options: v.options,
114
+ // the workflow's own narrowing, shown in the picker so the list is explainable
115
+ optionsFilter: v.optionsFilter == null ? undefined : String(v.optionsFilter),
79
116
  }
80
117
  }
81
118
  case 'size': {
@@ -97,10 +134,13 @@ export function describeVar(varDef: AnyVar): VarDescriptor {
97
134
  }
98
135
  }
99
136
 
100
- /** one aligned console line per var (startup print) */
101
- export function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number): string {
137
+ /** one aligned console line per var (startup print). Padding happens on the PLAIN text: colors are wrapped around the
138
+ * already-padded cells, so a colored and an uncolored print line up identically */
139
+ export function renderDescriptorLine(name: string, d: VarDescriptor, nameWidth: number, color = false): string {
102
140
  const def = typeof d.default === 'string' ? JSON.stringify(truncate(d.default, 40)) : JSON.stringify(d.default)
103
- return ` ${name.padEnd(nameWidth)} ${d.kind.padEnd(6)} ${d.payload} · default: ${truncate(def ?? 'null', 60)}`
141
+ const cells = { name: name.padEnd(nameWidth), kind: d.kind.padEnd(6), value: truncate(def ?? 'null', 60) }
142
+ if (!color) return ` ${cells.name} ${cells.kind} ${d.payload} · default: ${cells.value}`
143
+ return ` ${ansi.bold(cells.name)} ${ansi.yellow(cells.kind)} ${ansi.gray(d.payload)} ${ansi.gray('· default:')} ${cells.value}`
104
144
  }
105
145
 
106
146
  function truncate(s: string, n: number): string {
@@ -0,0 +1,27 @@
1
+ // the loras a host's lora-manager knows but its object_info enum does not yet list.
2
+ // ONE function, because the picker and the payload validator must agree exactly: whatever
3
+ // the ui offers, `applyVarPayload` compares by RAW STRING, so a name built with the wrong
4
+ // separator is offered and then refused as an unknown lora.
5
+ import { loraMirrorEntries } from 'src/host/loraInfoCache.ts'
6
+ import { loraKey } from 'src/host/loraManagerApi.ts'
7
+ import { statelessRegex } from 'src/utils/matchesRegex.ts'
8
+
9
+ /**
10
+ * `options` is the host enum for this var: it decides both what counts as already-known
11
+ * (compared by normalized key, never raw, the enum keeps case, extension and separators)
12
+ * and which separator the rebuilt names must use.
13
+ */
14
+ export function managerOnlyLoraOptions(p: {
15
+ hostId: string
16
+ options: readonly string[]
17
+ /** the var's own narrowing, `v.loras(/krea-?2/i)`: it applies to the mirror too */
18
+ filter?: RegExp | null
19
+ }): string[] {
20
+ const filter = p.filter == null ? null : statelessRegex(p.filter)
21
+ const known = new Set(p.options.map((o) => loraKey(o)))
22
+ const separator = p.options.some((o) => o.includes('\\')) ? '\\' : '/'
23
+ return loraMirrorEntries(p.hostId, { separator })
24
+ .filter((e) => !known.has(e.key))
25
+ .map((e) => e.serverName)
26
+ .filter((n) => filter == null || filter.test(n))
27
+ }
@@ -1,7 +1,8 @@
1
- // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--bind ADDR]`
1
+ // `comfy-ts serve [dir | module.cflow.ts] [--port N] [--host ADDR]`
2
2
  // drafts as a local HTTP generation API — agent/architecture.md item 12
3
3
  import { statSync } from 'node:fs'
4
4
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
5
+ import { networkInterfaces } from 'node:os'
5
6
  import { pathToFileURL } from 'node:url'
6
7
  import { resolve } from 'pathe'
7
8
  import { scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
@@ -9,13 +10,15 @@ import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
9
10
  import { draftKeyForFile } from 'src/cli/tui/state/DraftsSt.ts'
10
11
  import { describeVar, renderDescriptorLine } from 'src/cli/serve/describeVar.ts'
11
12
  import { ServeApp, type ServeModule } from 'src/cli/serve/ServeApp.ts'
13
+ import { renderStartupLines } from 'src/cli/serve/startupPrint.ts'
12
14
  import { loadOrBuildWebJs } from 'src/cli/serve/webBundle.ts'
15
+ import { colorsAvailable } from 'src/utils/ansi.ts'
13
16
  import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
14
17
 
15
18
  const DEFAULT_PORT = 8288
16
19
  const BODY_CAP = 10_000_000
17
20
 
18
- function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
21
+ export function parseArgs(args: string[]): { target?: string; port: number; bind: string } | { error: string } {
19
22
  let target: string | undefined
20
23
  let port = DEFAULT_PORT
21
24
  let bind = '127.0.0.1'
@@ -25,9 +28,10 @@ function parseArgs(args: string[]): { target?: string; port: number; bind: strin
25
28
  const n = Number(args[++i])
26
29
  if (!Number.isInteger(n) || n <= 0 || n > 65535) return { error: `--port expects 1..65535, got '${args[i]}'` }
27
30
  port = n
28
- } else if (a === '--bind') {
31
+ } else if (a === '--host' || a === '--bind') {
32
+ // --host is the spelling; --bind stays an alias so an old command line keeps working
29
33
  const b = args[++i]
30
- if (b == null) return { error: '--bind expects an address' }
34
+ if (b == null) return { error: `${a} expects an address (0.0.0.0 to reach it from another machine)` }
31
35
  bind = b
32
36
  } else if (a != null && a.startsWith('--')) return { error: `unknown flag '${a}'` }
33
37
  else if (a != null) {
@@ -39,14 +43,18 @@ function parseArgs(args: string[]): { target?: string; port: number; bind: strin
39
43
  }
40
44
 
41
45
  /** node:http glue around ServeApp.handle — exported so tests can drive a real socket */
46
+ /** open CORS, because a browser page IS a first-class client here: the web entry runs the
47
+ * library in a tab and rides serve as its bridge to hosts that send no CORS headers
48
+ * (examples/web is on another port by construction). The cost is real and stated at launch:
49
+ * with no auth, any page you visit can drive this api. That is the same trade as the port
50
+ * being open at all, so it is said out loud rather than hidden behind a flag. */
42
51
  export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res: ServerResponse) => void {
52
+ const cors = {
53
+ 'access-control-allow-origin': '*',
54
+ 'access-control-allow-methods': 'GET, POST, PUT, DELETE, OPTIONS',
55
+ 'access-control-allow-headers': 'content-type, accept',
56
+ }
43
57
  return (req, res) => {
44
- // local bridge, no auth by design: open CORS so browser frontends can call it
45
- const cors = {
46
- 'access-control-allow-origin': '*',
47
- 'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
48
- 'access-control-allow-headers': 'content-type, accept',
49
- }
50
58
  const chunks: Buffer[] = []
51
59
  let size = 0
52
60
  let overflow = false
@@ -75,7 +83,7 @@ export function makeRequestListener(app: ServeApp): (req: IncomingMessage, res:
75
83
  body: Buffer.concat(chunks).toString('utf8'),
76
84
  })
77
85
  .then((reply) => {
78
- res.writeHead(reply.status, { 'content-type': reply.contentType, ...cors })
86
+ res.writeHead(reply.status, { 'content-type': reply.contentType, ...reply.headers, ...cors })
79
87
  res.end(reply.body)
80
88
  })
81
89
  .catch((e: unknown) => {
@@ -148,24 +156,45 @@ export async function runServe(args: string[]): Promise<number> {
148
156
  })
149
157
  }
150
158
 
159
+ export type Nic = { address: string; family: string | number; internal: boolean }
160
+
161
+ /** the addresses this bind actually answers on. `0.0.0.0` means every interface, so printing
162
+ * only that back is useless: the LAN ip and the tailnet 100.x are the urls a phone can open */
163
+ export function reachableAddresses(bind: string, nics: Record<string, Nic[] | undefined>): string[] {
164
+ if (bind !== '0.0.0.0' && bind !== '::') return [bind]
165
+ const found: string[] = []
166
+ for (const list of Object.values(nics)) {
167
+ for (const nic of list ?? []) {
168
+ // node reports family as 'IPv4' or 4 depending on the version
169
+ if (nic.internal || (nic.family !== 'IPv4' && nic.family !== 4)) continue
170
+ found.push(nic.address)
171
+ }
172
+ }
173
+ return ['127.0.0.1', ...found]
174
+ }
175
+
151
176
  function printStartup(app: ServeApp, bind: string, port: number): void {
152
177
  const base = `http://${bind}:${port}`
153
- console.log(`comfy-ts serve · ${app.modules.length} workflow(s) · ${base}/`)
154
- if (bind !== '127.0.0.1' && bind !== 'localhost')
155
- console.log(`⚠️ bound to ${bind} — this API has NO AUTH and runs workflows on your ComfyUI host`)
156
- for (const mod of app.modules) {
157
- console.log(`\n${mod.key} (host: ${mod.dw.host.data.id})`)
158
- for (const draft of app.draftsFor(mod))
159
- console.log(` POST ${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(draft)}`)
160
- const entries = mod.dw.entries()
161
- const nameWidth = Math.max(...entries.map(([n]) => n.length), 4)
162
- for (const [name, varDef] of entries) console.log(renderDescriptorLine(name, describeVar(varDef), nameWidth))
163
- }
164
- const firstMod = app.modules[0]
165
- if (firstMod != null)
166
- console.log(
167
- `\ntry: curl -X POST ${base}/generate/${encodeURIComponent(firstMod.key)}/default -H 'content-type: application/json' -d '{}'`,
168
- )
169
- console.log(`docs: GET ${base}/drafts (json index of everything above)`)
170
- console.log(`ui: open ${base}/ in a browser (every var as a form control)`)
178
+ const color = colorsAvailable()
179
+ const lines = renderStartupLines({
180
+ bind,
181
+ port,
182
+ urls: reachableAddresses(bind, networkInterfaces()),
183
+ color,
184
+ modules: app.modules.map((mod) => {
185
+ const entries = mod.dw.entries()
186
+ const nameWidth = Math.max(...entries.map(([n]) => n.length), 4)
187
+ return {
188
+ key: mod.key,
189
+ hostId: mod.dw.host.data.id,
190
+ routes: app
191
+ .draftsFor(mod)
192
+ .map((d) => `${base}/generate/${encodeURIComponent(mod.key)}/${encodeURIComponent(d)}`),
193
+ varLines: entries.map(([name, varDef]) =>
194
+ renderDescriptorLine(name, describeVar(varDef), nameWidth, color),
195
+ ),
196
+ }
197
+ }),
198
+ })
199
+ for (const line of lines) console.log(line)
171
200
  }
@@ -0,0 +1,86 @@
1
+ // serve's own slice of `.comfy-ts/settings.json`, under a `serve` key.
2
+ // MERGE, never rewrite: the TUI owns the rest of that file and a whole-blob write
3
+ // from here would silently drop its preview mode, last draft and lora prefixes.
4
+ // deliberately NOT the TUI's `saveToDisk`: that one governs TUI runs, this one
5
+ // governs the api's, so the two surfaces cannot fight over one value.
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
7
+ import { stringMap } from 'src/utils/stringMap.ts'
8
+ import { validSavePrefix } from 'src/utils/safeName.ts'
9
+ import { dirname } from 'pathe'
10
+
11
+ export type ServeSettings = {
12
+ /** false = generations stay in memory, streamed to the client, nothing written to outputs/ */
13
+ saveToDisk: boolean
14
+ /** module key → host id the runs go to, when it is not the one the module defined
15
+ * (the TUI's host override, per module because serve holds many workflows at once) */
16
+ hostOverride: Record<string, string>
17
+ /** module key → subfolder under outputs/ its images land in. Empty/absent = the module key,
18
+ * which is what serve always used before it was choosable */
19
+ savePrefix: Record<string, string>
20
+ }
21
+
22
+ const DEFAULT_SERVE_SETTINGS: ServeSettings = { saveToDisk: true, hostOverride: {}, savePrefix: {} }
23
+
24
+ /** null when no comfyts is registered yet: a ServeApp can be constructed before the global
25
+ * exists (tests do), and reading a setting must degrade to defaults, never throw */
26
+ function settingsPath(): string | null {
27
+ const g = globalThis as { comfyts?: { settingsPath?: string } }
28
+ const path = g.comfyts?.settingsPath
29
+ return typeof path === 'string' ? path : null
30
+ }
31
+
32
+ /** `readable: false` says the file EXISTS but could not be parsed — the one case where a write
33
+ * must refuse. Merging onto `{}` there would rewrite the file from nothing and take the TUI's
34
+ * keys with it, and these files are documented as hand-editable, so the user would lose the
35
+ * chance to repair it. */
36
+ function readBlob(): { blob: Record<string, unknown>; readable: boolean } {
37
+ const path = settingsPath()
38
+ if (path == null || !existsSync(path)) return { blob: {}, readable: true }
39
+ try {
40
+ const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
41
+ const ok = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
42
+ if (!ok) console.error(`[serve] settings is not an object (${path}), using defaults`)
43
+ return { blob: ok ? (parsed as Record<string, unknown>) : {}, readable: ok }
44
+ } catch (e) {
45
+ // reading must not take the server down: log loud, use defaults, and refuse to WRITE
46
+ console.error(`[serve] settings unreadable (${path}), using defaults:`, e)
47
+ return { blob: {}, readable: false }
48
+ }
49
+ }
50
+
51
+ /** keeps the CLEANED value, not the raw one: storing the raw form let the same input mean two
52
+ * different directories depending on whether it arrived by PUT or by hand */
53
+ function cleanValues(map: Record<string, string>, clean: (v: string) => string | null): Record<string, string> {
54
+ const out: Record<string, string> = {}
55
+ for (const [k, v] of Object.entries(map)) {
56
+ const ok = clean(v)
57
+ if (ok != null) out[k] = ok
58
+ }
59
+ return out
60
+ }
61
+
62
+ export function readServeSettings(): ServeSettings {
63
+ const serve = readBlob().blob.serve
64
+ const o = typeof serve === 'object' && serve !== null ? (serve as Record<string, unknown>) : {}
65
+ return {
66
+ saveToDisk: typeof o.saveToDisk === 'boolean' ? o.saveToDisk : DEFAULT_SERVE_SETTINGS.saveToDisk,
67
+ hostOverride: stringMap(o.hostOverride),
68
+ // validated on the way IN as well as on the way out: PUT /settings gates it, but a
69
+ // hand-written file did not go through that route, and this value becomes an output
70
+ // directory. One gate on one side is not a gate
71
+ savePrefix: cleanValues(stringMap(o.savePrefix), validSavePrefix),
72
+ }
73
+ }
74
+
75
+ export function writeServeSettings(next: ServeSettings): void {
76
+ const path = settingsPath()
77
+ // loud: the caller reports "applied for this session but not saved" rather than pretending
78
+ if (path == null) throw new Error('no comfyts instance registered — cannot persist serve settings')
79
+ const current = readBlob()
80
+ if (!current.readable)
81
+ throw new Error(
82
+ `serve settings not saved: ${path} is not readable json. Fix or delete it — overwriting would drop the keys it still holds`,
83
+ )
84
+ mkdirSync(dirname(path), { recursive: true })
85
+ writeFileSync(path, JSON.stringify({ ...current.blob, serve: next }, null, 2))
86
+ }
@@ -0,0 +1,111 @@
1
+ // what `comfy-ts serve` prints on launch. PURE: takes the already-described
2
+ // modules and gives back lines, so tests read the layout without a server and
3
+ // without a tty. Colors are a parameter, never a probe done in here.
4
+ import { ansi, stripAnsi } from 'src/utils/ansi.ts'
5
+
6
+ export type StartupModule = {
7
+ key: string
8
+ hostId: string
9
+ /** the POST routes, ready to print */
10
+ routes: string[]
11
+ /** one line per var (renderDescriptorLine) */
12
+ varLines: string[]
13
+ }
14
+
15
+ export type StartupInput = {
16
+ modules: StartupModule[]
17
+ bind: string
18
+ port: number
19
+ /** every address this bind answers on (reachableAddresses) */
20
+ urls: string[]
21
+ color: boolean
22
+ }
23
+
24
+ const RULE_WIDTH = 64
25
+
26
+ /** 100.64.0.0/10 is the CGNAT range tailscale hands out — worth naming, it is the one
27
+ * you want when the phone is not on the same wifi */
28
+ export function addressNote(addr: string): string {
29
+ const octets = addr.split('.').map(Number)
30
+ const second = octets[1] ?? 0
31
+ if (octets[0] === 100 && second >= 64 && second <= 127) return 'tailnet'
32
+ if (addr === '127.0.0.1' || addr === 'localhost') return 'this machine'
33
+ return ''
34
+ }
35
+
36
+ function paint(color: boolean): {
37
+ title: (s: string) => string
38
+ name: (s: string) => string
39
+ dim: (s: string) => string
40
+ url: (s: string) => string
41
+ warn: (s: string) => string
42
+ } {
43
+ const id = (s: string): string => s
44
+ if (!color) return { title: id, name: id, dim: id, url: id, warn: id }
45
+ return {
46
+ title: (s) => ansi.bold(s),
47
+ name: (s) => ansi.bold.cyan(s),
48
+ dim: (s) => ansi.gray(s),
49
+ url: (s) => ansi.green(s),
50
+ warn: (s) => ansi.yellow(s),
51
+ }
52
+ }
53
+
54
+ /** a box that stays square whatever the colors do: padding measures the VISIBLE text */
55
+ export function boxed(lines: string[], p: { color: boolean } = { color: false }): string[] {
56
+ const width = Math.max(...lines.map((l) => stripAnsi(l).length), 0)
57
+ const edge = (l: string, r: string): string => `${l}${'─'.repeat(width + 2)}${r}`
58
+ const border = (s: string): string => (p.color ? ansi.gray(s) : s)
59
+ return [
60
+ border(edge('┌', '┐')),
61
+ ...lines.map((l) => `${border('│')} ${l}${' '.repeat(width - stripAnsi(l).length)} ${border('│')}`),
62
+ border(edge('└', '┘')),
63
+ ]
64
+ }
65
+
66
+ export function renderStartupLines(p: StartupInput): string[] {
67
+ const c = paint(p.color)
68
+ const loopback = p.bind === '127.0.0.1' || p.bind === 'localhost' || p.bind === '::1'
69
+ const primary = `http://${p.urls[0] ?? p.bind}:${p.port}/`
70
+ const out: string[] = []
71
+
72
+ const count = `${p.modules.length} workflow${p.modules.length === 1 ? '' : 's'}`
73
+ out.push(c.title(`comfy-ts serve · ${count} · ${primary}`))
74
+ // said on EVERY launch, loopback included: cross-origin is open, so the exposure is not
75
+ // limited to who can reach the port. any page in your browser can reach 127.0.0.1 too
76
+ out.push(
77
+ c.warn(
78
+ loopback
79
+ ? '⚠️ no auth: this API runs workflows, and any page open in your browser can call it'
80
+ : `⚠️ bound to ${p.bind}, no auth: anyone on this network can run workflows on your ComfyUI host`,
81
+ ),
82
+ )
83
+
84
+ for (const mod of p.modules) {
85
+ out.push('', c.dim('─'.repeat(RULE_WIDTH)))
86
+ out.push(`${c.name(mod.key)} ${c.dim(`host: ${mod.hostId}`)}`)
87
+ for (const route of mod.routes) out.push(c.dim(` POST ${route}`))
88
+ out.push(...mod.varLines)
89
+ }
90
+ out.push(c.dim('─'.repeat(RULE_WIDTH)), '')
91
+
92
+ // the box is the last thing on screen: where the ui is, and how to reach it elsewhere
93
+ const box: string[] = [
94
+ `${c.title('web ui')} ${c.url(primary)}`,
95
+ `${c.dim('json api')} ${c.dim(`${primary}drafts`)}`,
96
+ ]
97
+ if (p.urls.length > 1) {
98
+ box.push('', c.dim('also reachable at:'))
99
+ for (const url of p.urls.slice(1)) {
100
+ const note = addressNote(url)
101
+ box.push(` ${c.url(`http://${url}:${p.port}/`)}${note === '' ? '' : c.dim(` (${note})`)}`)
102
+ }
103
+ }
104
+ if (loopback) {
105
+ box.push('', c.dim('to open it from your phone or another machine:'))
106
+ box.push(c.dim(` comfy-ts serve --host 0.0.0.0 (--bind is the same flag)`))
107
+ box.push(c.dim(' every reachable url gets printed here, tailnet included'))
108
+ }
109
+ out.push(...boxed(box, { color: p.color }))
110
+ return out
111
+ }
@@ -16,6 +16,9 @@ export type IndexPayload = {
16
16
 
17
17
  export type GeneratedImage = { filename: string; url: string | null; absPath: string | null }
18
18
 
19
+ /** a STRING output (PreviewAny). An llm graph produces these and no images at all */
20
+ export type GeneratedText = { nodeKey: string | null; text: string }
21
+
19
22
  export type GenerateOk = {
20
23
  ok: true
21
24
  module: string
@@ -24,6 +27,7 @@ export type GenerateOk = {
24
27
  durationMs: number
25
28
  seeds: Record<string, number>
26
29
  images: GeneratedImage[]
30
+ texts?: GeneratedText[]
27
31
  }
28
32
 
29
33
  async function jsonFetch<T>(url: string, init?: RequestInit): Promise<T> {
@@ -66,10 +70,20 @@ export function saveDraft(
66
70
  })
67
71
  }
68
72
 
73
+ export function deleteDraft(p: { module: string; draft: string }): Promise<{ ok: true; drafts: string[] }> {
74
+ return jsonFetch(`/drafts/${encodeURIComponent(p.module)}/${encodeURIComponent(p.draft)}`, { method: 'DELETE' })
75
+ }
76
+
69
77
  export type RunStatus = {
70
78
  running: boolean
71
79
  status: string
72
80
  percent: number | null
81
+ /** the executing node and its OWN counter: generated tokens on a text node, sampler steps
82
+ * on a KSampler. The only live signal a text graph has */
83
+ node?: string | null
84
+ nodeProgress?: { value: number; max: number } | null
85
+ /** a node's live display text while it runs — a streaming generator's partial answer */
86
+ progressText?: string | null
73
87
  hasPreview: boolean
74
88
  previewSeq: number | null
75
89
  }
@@ -83,16 +97,121 @@ export function runPreviewSrc(p: { module: string; tick: number }): string {
83
97
  return `/run/${encodeURIComponent(p.module)}/preview?t=${p.tick}`
84
98
  }
85
99
 
86
- export type LoraInfo = { name: string; displayName: string; triggerWords: string[] }
100
+ export type LoraInfo = {
101
+ name: string
102
+ displayName: string
103
+ triggerWords: string[]
104
+ /** false when the lora manager mirror has never heard of this file */
105
+ known?: boolean
106
+ baseModel?: string | null
107
+ folder?: string | null
108
+ filePath?: string | null
109
+ fileSize?: number | null
110
+ tags?: string[]
111
+ notes?: string
112
+ civitaiUrl?: string | null
113
+ civitaiVersion?: string | null
114
+ }
87
115
 
88
116
  export function fetchLoraInfo(p: { host: string; name: string }): Promise<LoraInfo> {
89
117
  return jsonFetch(`/lora-info/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`)
90
118
  }
91
119
 
120
+ /** the live half of a lora's story: civitai's description and the example images the
121
+ * extension keeps. Separate from fetchLoraInfo because this one talks to the host */
122
+ export type LoraAbout = {
123
+ known: boolean
124
+ description: string | null
125
+ examples: string[]
126
+ examplesReason: string | null
127
+ }
128
+
129
+ export function fetchLoraAbout(p: { host: string; name: string }): Promise<LoraAbout> {
130
+ return jsonFetch(`/lora-about/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`)
131
+ }
132
+
92
133
  export function loraPreviewSrc(p: { host: string; name: string }): string {
93
134
  return `/lora-preview/${encodeURIComponent(p.host)}/${encodeURIComponent(p.name)}`
94
135
  }
95
136
 
137
+ /** server-side settings the panel can flip (they apply to every client, curl included).
138
+ * effectivePrefix is derived server-side: the stored folder, or the module key by default */
139
+ export type ServeSettings = {
140
+ saveToDisk: boolean
141
+ hostOverride: Record<string, string>
142
+ savePrefix: Record<string, string>
143
+ effectivePrefix: Record<string, string>
144
+ }
145
+
146
+ export function fetchSettings(): Promise<ServeSettings> {
147
+ return jsonFetch('/settings')
148
+ }
149
+
150
+ export function saveSettings(p: { saveToDisk?: boolean; savePrefix?: Record<string, string> }): Promise<ServeSettings> {
151
+ return jsonFetch('/settings', {
152
+ method: 'PUT',
153
+ headers: { 'content-type': 'application/json' },
154
+ body: JSON.stringify(p),
155
+ })
156
+ }
157
+
158
+ /** every host the serve process knows, and where each module currently runs */
159
+ export type HostsPayload = {
160
+ hosts: { id: string; url: string; httpUrl: string; modules: string[] }[]
161
+ defaults: Record<string, string>
162
+ overrides: Record<string, string>
163
+ }
164
+
165
+ export function fetchHosts(): Promise<HostsPayload> {
166
+ return jsonFetch('/hosts')
167
+ }
168
+
169
+ export type HostAction = 'interrupt' | 'clear-queue' | 'restart' | 'refresh-loras' | 'refresh-schema'
170
+
171
+ export function pingHost(p: { host: string }): Promise<{ up: boolean }> {
172
+ return jsonFetch(`/hosts/${encodeURIComponent(p.host)}/ping`)
173
+ }
174
+
175
+ export function postHostAction(p: { host: string; action: HostAction }): Promise<{ ok: true; note: string }> {
176
+ return jsonFetch(`/hosts/${encodeURIComponent(p.host)}/${p.action}`, { method: 'POST' })
177
+ }
178
+
179
+ export function fetchHostLogs(p: { host: string }): Promise<{ lines: string[] }> {
180
+ return jsonFetch(`/hosts/${encodeURIComponent(p.host)}/logs`)
181
+ }
182
+
183
+ export function setModuleHost(p: { module: string; host: string | null }): Promise<{
184
+ ok: true
185
+ module: string
186
+ host: string
187
+ overrides: Record<string, string>
188
+ }> {
189
+ return jsonFetch(`/hosts/${encodeURIComponent(p.module)}`, {
190
+ method: 'PUT',
191
+ headers: { 'content-type': 'application/json' },
192
+ body: JSON.stringify({ host: p.host }),
193
+ })
194
+ }
195
+
196
+ /** master prompts of the enhancer, files under `.comfy-ts/prompt-enhancers/` (server-owned) */
197
+ export type PromptEnhancer = { name: string; text: string }
198
+
199
+ export function fetchPromptEnhancers(): Promise<{ enhancers: PromptEnhancer[] }> {
200
+ return jsonFetch('/prompt-enhancers')
201
+ }
202
+
203
+ export function savePromptEnhancer(p: PromptEnhancer): Promise<{ ok: true; enhancers: PromptEnhancer[] }> {
204
+ return jsonFetch(`/prompt-enhancers/${encodeURIComponent(p.name)}`, {
205
+ method: 'PUT',
206
+ headers: { 'content-type': 'application/json' },
207
+ body: JSON.stringify({ text: p.text }),
208
+ })
209
+ }
210
+
211
+ export function deletePromptEnhancer(p: { name: string }): Promise<{ ok: true; enhancers: PromptEnhancer[] }> {
212
+ return jsonFetch(`/prompt-enhancers/${encodeURIComponent(p.name)}`, { method: 'DELETE' })
213
+ }
214
+
96
215
  export async function uploadFile(p: { file: File }): Promise<{ path: string; url: string | null }> {
97
216
  const bytes = new Uint8Array(await p.file.arrayBuffer())
98
217
  let bin = ''