comfy-ts 0.3.0 → 1.0.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 (73) hide show
  1. package/README.md +349 -255
  2. package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
  3. package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
  4. package/dist/cli.js +3969 -128
  5. package/dist/cli.js.map +1 -1
  6. package/dist/index.cjs +1208 -170
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.cts +449 -115
  9. package/dist/index.d.ts +449 -115
  10. package/dist/index.js +1200 -171
  11. package/dist/index.js.map +1 -1
  12. package/dist/{run-tui-Io8Xea0L.js → run-tui-BFhba_oG.js} +744 -665
  13. package/dist/run-tui-BFhba_oG.js.map +1 -0
  14. package/examples/01-txt2img.cflow.ts +50 -0
  15. package/examples/02-img2img-upload.cflow.ts +66 -0
  16. package/examples/03-export-workflow-json.cflow.ts +56 -0
  17. package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
  18. package/examples/05-comfy-cloud.cflow.ts +67 -0
  19. package/examples/comfy-cloud/sdk.d.ts +122674 -0
  20. package/guide-for-agents.md +166 -0
  21. package/package.json +7 -3
  22. package/src/cli/comfy-ts-cli.ts +19 -2
  23. package/src/cli/gen.ts +21 -12
  24. package/src/cli/tui/components/Header.tsx +5 -0
  25. package/src/cli/tui/components/LogsPanel.tsx +23 -0
  26. package/src/cli/tui/components/PreviewPanel.tsx +52 -7
  27. package/src/cli/tui/components/StatusBar.tsx +10 -4
  28. package/src/cli/tui/components/TreePanel.tsx +15 -2
  29. package/src/cli/tui/components/TuiApp.tsx +26 -3
  30. package/src/cli/tui/discoverWorkflows.ts +79 -0
  31. package/src/cli/tui/protocolImagePainter.ts +54 -18
  32. package/src/cli/tui/run-tui.tsx +55 -24
  33. package/src/cli/tui/state/ExecSt.ts +4 -1
  34. package/src/cli/tui/state/HostSt.ts +123 -1
  35. package/src/cli/tui/state/LogsSt.ts +107 -0
  36. package/src/cli/tui/state/PreviewSt.ts +173 -23
  37. package/src/cli/tui/state/SettingsSt.ts +48 -21
  38. package/src/cli/tui/state/TreeSt.ts +30 -6
  39. package/src/cli/tui/state/TuiSt.ts +27 -3
  40. package/src/cli/tui/state/WorkflowsSt.ts +16 -1
  41. package/src/host/ComfyHost.ts +241 -71
  42. package/src/host/ComfyManager.ts +10 -9
  43. package/src/host/ComfyUploader.ts +1 -2
  44. package/src/host/ResilientWebsocket.ts +3 -1
  45. package/src/host/hostUrl.ts +59 -0
  46. package/src/host/loraManagerApi.ts +5 -4
  47. package/src/index.ts +20 -1
  48. package/src/litegraph/CanonicalWorkflow.ts +77 -0
  49. package/src/litegraph/LiteGraphGroup.ts +9 -7
  50. package/src/litegraph/LiteGraphJSON.ts +34 -13
  51. package/src/litegraph/LiteGraphLink.ts +32 -2
  52. package/src/litegraph/LiteGraphNode.ts +18 -33
  53. package/src/litegraph/LiteGraphNodeInput.ts +10 -8
  54. package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
  55. package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
  56. package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
  57. package/src/litegraph/expandSubgraphs.ts +352 -0
  58. package/src/litegraph/normalizeWorkflow.ts +141 -0
  59. package/src/runner/ComfyExecution.ts +4 -5
  60. package/src/runner/ComfyWorkflow.ts +2 -2
  61. package/src/runner/ComfyWsApi.ts +12 -1
  62. package/src/runner/wsBinaryFrame.ts +48 -0
  63. package/src/sdk-generator/Primitives.ts +6 -24
  64. package/src/sdk-generator/comfy-api-json.ts +3 -1
  65. package/src/sdk-generator/inputWidgetKind.ts +179 -0
  66. package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
  67. package/src/ssh-host-manager/ssh-manager.ts +0 -15
  68. package/src/state.ts +13 -2
  69. package/src/utils/ansi.ts +7 -0
  70. package/src/utils/mojibake.ts +60 -0
  71. package/dist/log-CdfgILde.js +0 -10
  72. package/dist/log-CdfgILde.js.map +0 -1
  73. package/dist/run-tui-Io8Xea0L.js.map +0 -1
@@ -0,0 +1,166 @@
1
+ # comfy-ts, guide for coding agents
2
+
3
+ You are working in a project that uses `comfy-ts`, a type-safe ComfyUI
4
+ companion for TypeScript. It connects to one or more ComfyUI hosts, generates
5
+ one typed SDK per host (global `Comfy.<HostNs>.*` namespaces), builds
6
+ workflows in code with full autocomplete, executes them over websocket, and
7
+ downloads the output images. Include this file from the project's CLAUDE.md:
8
+ `@./node_modules/comfy-ts/guide-for-agents.md`.
9
+
10
+ ## Setup flow
11
+
12
+ 1. Install: `bun add comfy-ts` (npm/pnpm/yarn work too, node >= 20).
13
+ 2. Generate the per-host schema cache + typed SDK once per host:
14
+
15
+ ```bash
16
+ bunx comfy-ts gen --id my-gpu --host http://127.0.0.1:8188
17
+ # writes .comfy-ts/hosts/my-gpu/{object_info.json,embeddings.json,sdk.d.ts}
18
+ ```
19
+
20
+ Or skip the CLI: a first `await host.connect()` fetches the schema and
21
+ writes the same files.
22
+ 3. Activate the generated types in tsconfig:
23
+
24
+ ```jsonc
25
+ { "include": ["src", ".comfy-ts/hosts/**/sdk.d.ts"] }
26
+ ```
27
+
28
+ 4. Gitignore `.comfy-ts/` entirely. It is local state: host schema dumps
29
+ (often ~10MB, they describe that machine's models and paths), run outputs,
30
+ TUI drafts and settings, lora keywords, preview cache. Everything in it is
31
+ regenerable. (Exception: a private repo may commit `hosts/` to get typed CI.)
32
+
33
+ Before the first codegen the builder falls back to permissive base types, so
34
+ code compiles either way. Types sharpen once a generated sdk.d.ts is in scope.
35
+
36
+ ## The workflow pattern: defineWorkflow + vars + build
37
+
38
+ A workflow module is a `*.cflow.ts` file (that suffix is what the TUI scans
39
+ for). Minimal complete example:
40
+
41
+ ```ts
42
+ import { ComfyTS, v } from 'comfy-ts'
43
+
44
+ const comfy = ComfyTS.create()
45
+ const host = comfy.host({ id: 'my-gpu', host: '127.0.0.1', port: 8188 })
46
+ await host.loadSchemaFromCache() // offline import; run() connects lazily
47
+
48
+ export const txt2img = host.defineWorkflow({
49
+ id: 'txt2img',
50
+ vars: {
51
+ prompt: v.text('a cozy house in a snowy forest'),
52
+ seed: v.seed(42),
53
+ steps: v.int(20, { min: 1, max: 60 }),
54
+ size: v.size({ width: 512, height: 512 }),
55
+ },
56
+ build: (b, vars) => {
57
+ // b is Comfy.MyGpu.Builder: one typed factory per node of THIS host
58
+ const ckpt = b.CheckpointLoaderSimple({ ckpt_name: 'SD1.5\\v1-5-pruned-emaonly.ckpt' })
59
+ const samples = b.KSampler({
60
+ model: ckpt,
61
+ positive: b.CLIPTextEncode({ clip: ckpt, text: vars.prompt }),
62
+ negative: b.CLIPTextEncode({ clip: ckpt, text: 'blurry, low quality' }),
63
+ latent_image: b.EmptyLatentImage({ width: vars.size.width, height: vars.size.height, batch_size: 1 }),
64
+ seed: vars.seed,
65
+ steps: vars.steps,
66
+ cfg: 7,
67
+ sampler_name: 'euler',
68
+ scheduler: 'normal',
69
+ denoise: 1,
70
+ })
71
+ b.SaveImage({ images: b.VAEDecode({ samples, vae: ckpt }) })
72
+ },
73
+ })
74
+
75
+ export default txt2img
76
+
77
+ // standalone run, skipped when a driver (the TUI) imports this module
78
+ if (import.meta.main) {
79
+ const execution = await txt2img.run({ log: true })
80
+ for (const img of execution.images) console.log(img.absPath)
81
+ host.disconnect()
82
+ }
83
+ ```
84
+
85
+ Var kinds: `v.text`, `v.int`, `v.float`, `v.seed`, `v.toggle`, `v.choice`,
86
+ `v.size`, `v.loras`, `v.prompt`. Notes:
87
+
88
+ - `v.loras(/regex/)` resolves against the host's real lora list;
89
+ `activeLoras(vars.loras)` returns `{ lora_name, strength_model, strength_clip }[]`
90
+ for a standard `LoraLoader` chain.
91
+ - `v.prompt` is structured: `//` lines are comments (stripped), `- ` lines go
92
+ to the negative prompt, `{ loraKeywordsFrom: lorasVar }` prefixes lora
93
+ trigger keywords. The value is `{ positive, negative }`.
94
+ - `vars` may be a lambda `(v) => ({ ... })` so vars can reference each other.
95
+ - `build` may be async, for uploads: the third param `wf` feeds `MediaImage`
96
+ helpers (`new MediaImage({ path }).loadInWorkflow_viaLoadImageNode(wf)`).
97
+ Uploads are hash-named and deduped, nothing is re-sent.
98
+
99
+ ## Running and getting images
100
+
101
+ - `await workflow.run({ log: true })` connects (idempotent, one websocket per
102
+ host), builds a fresh graph from current var values, executes, streams
103
+ progress, and returns a `ComfyExecution`.
104
+ - `execution.images` are downloaded `MediaImage`s: `img.absPath`,
105
+ `img.width`, `img.height`.
106
+ - Tweak then re-run: `workflow.vars.seed.randomize()` or
107
+ `workflow.vars.prompt.set('...')`, then `run()` again.
108
+ - `run({ onProgress })` gives a progress callback instead of console logs.
109
+ - Call `host.disconnect()` at the end of a standalone script or the process
110
+ stays alive on the open websocket.
111
+
112
+ ## CLI
113
+
114
+ ```bash
115
+ bunx comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] # codegen
116
+ bunx comfy-ts outline [file] [--section Name] [--lines N] # inspect a sdk.d.ts
117
+ bunx comfy-ts tui [dir | module.cflow.ts] # interactive tweak & re-run
118
+ ```
119
+
120
+ The TUI scans `**/*.cflow.ts` (no arg: cwd PLUS the examples bundled with
121
+ the package, grouped apart in the tree; an explicit dir or file limits to
122
+ that scope), shows vars as editable knobs, runs with live progress and
123
+ previews, and saves named drafts under `.comfy-ts/drafts/`. It re-execs
124
+ through bun when launched under node (workflow modules are TypeScript, and
125
+ node cannot import .ts from node_modules). Point users at it; as an agent
126
+ you run modules with `bun path/to/module.cflow.ts`.
127
+
128
+ ## Import and export ComfyUI JSON
129
+
130
+ - `host.importApiJson(json)` turns an `api.json` (prompt format) into a
131
+ `ComfyWorkflow`.
132
+ - `host.importWorkflowJson(json)` does the same for a saved `workflow.json`
133
+ (litegraph format, handles muted nodes, Note/Reroute/PrimitiveNode).
134
+ - `wf.toApiJson()` exports the prompt format;
135
+ `await wf.toWorkflowJson()` exports an autolayouted `workflow.json` you can
136
+ drag into the ComfyUI editor. Both work fully offline:
137
+ `const wf = await workflow.build()` never needs a live server.
138
+
139
+ ## Gotchas
140
+
141
+ - **Offline cache vs live connect.** `host.loadSchemaFromCache()` reads
142
+ `.comfy-ts/hosts/<id>/` and never touches the network, so modules import
143
+ instantly and offline. `run()` connects lazily. If the cache is missing,
144
+ the import still works: you get the permissive base types plus a loud
145
+ console message; run the `gen` command or `connect()` once to fix it.
146
+ `connect()` reuses a cache
147
+ younger than 24h; `connect({ schema: 'refresh' })` forces a re-fetch.
148
+ - **Per-host namespaces.** Types come from `Comfy.<HostNs>` keyed by the host
149
+ `id` you pass to `comfy.host({ id })` (`my-gpu` becomes `Comfy.MyGpu`). A
150
+ new id has no generated sdk yet, so you silently get permissive base types:
151
+ model names widen to `string` and typos stop being caught. Keep the id
152
+ stable and regenerate after installing custom nodes on the host.
153
+ - **Registries.** `ComfyTS.create()` returns the existing global instance,
154
+ and `comfy.host({ id })` returns the already-registered host for that id.
155
+ Modules can import each other safely in one process.
156
+ - **Seeds.** `v.seed` carries a mode (`+` increment, `-` decrement, `=`
157
+ fixed, `?` reroll) and advances itself after every run, so a batch of runs
158
+ gets distinct seeds by default. When reproducibility matters, pin both the
159
+ mode and the value: `vars.seed.setMode('=')` then `vars.seed.set(N)`.
160
+ `set()` alone keeps the current mode, so a prior `?` would still reroll.
161
+ - **`auto<T>()` slots.** From `import { auto } from 'comfy-ts'`: leave an
162
+ input blank and comfy-ts wires the most recent node producing that type.
163
+ Handy, but implicit; prefer explicit wiring in code meant to be read.
164
+ - **Errors before the server.** Invalid graphs accumulate messages in
165
+ `workflow.problems` before ComfyUI ever sees them. Check it when a run
166
+ misbehaves.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "comfy-ts",
3
- "version": "0.3.0",
3
+ "version": "1.0.0",
4
4
  "description": "Type-safe generative AI pipeline creation and execution using ComfyUI",
5
5
  "keywords": [
6
6
  "comfyui",
@@ -42,8 +42,9 @@
42
42
  "files": [
43
43
  "dist",
44
44
  "src",
45
- "!src/__private__",
45
+ "examples",
46
46
  "README.md",
47
+ "guide-for-agents.md",
47
48
  "LICENSE"
48
49
  ],
49
50
  "scripts": {
@@ -64,14 +65,17 @@
64
65
  "ci:local": "bun run ci && bun run typecheck",
65
66
  "gen:manager": "bun src/manager/script-update-manager.bun.ts",
66
67
  "gen:sdk": "bun scripts/gen-sdk-from-cache.ts",
68
+ "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",
67
69
  "sdk:outline": "bun scripts/sdk-outline.ts",
70
+ "templates:fetch": "bun scripts/fetch-templates.ts",
71
+ "templates:check": "bun scripts/check-templates.ts",
68
72
  "hooks:install": "git config core.hooksPath .githooks",
69
73
  "prepublishOnly": "bun run ci && bun run build",
70
74
  "tui": "bun src/cli/comfy-ts-cli.ts tui"
71
75
  },
72
76
  "rvt": {
73
77
  "skip": [
74
- "src/__private__",
78
+ ".rv-private",
75
79
  "tmp",
76
80
  ".comfy-ts"
77
81
  ]
@@ -1,21 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  // sidekick CLI: `bunx comfy-ts <command>` — codegen without writing any code
3
+ import { spawnSync } from 'node:child_process'
4
+ import { fileURLToPath } from 'node:url'
3
5
  import { runGen } from 'src/cli/gen.ts'
4
6
  import { runOutline } from 'src/cli/outline.ts'
5
7
 
6
8
  const HELP = `comfy-ts — typed SDK codegen for ComfyUI
7
9
 
8
10
  Usage:
9
- comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188]
11
+ comfy-ts gen --id <host-id> [--host http://127.0.0.1:8188] [--api-key <key>] [--out <sdk-path>]
10
12
  fetch object_info + embeddings from a live ComfyUI host and write
11
13
  .comfy-ts/hosts/<host-id>/{object_info.json,embeddings.json,sdk.d.ts}
14
+ (--api-key or COMFY_CLOUD_API_KEY authenticates via X-API-Key;
15
+ --out relocates ONLY the sdk.d.ts, e.g. a committed cloud catalog)
12
16
 
13
17
  comfy-ts outline [file] [--lines N] [--section Name]
14
18
  outline a generated sdk.d.ts (defaults to the first one in .comfy-ts/hosts/)
15
19
 
16
20
  comfy-ts tui [dir | workflow-module.ts]
17
21
  interactive tweak & re-run over **/*.cflow.ts modules (exporting
18
- host.defineWorkflow(...)); no arg scans cwd, a file arg preselects it
22
+ host.defineWorkflow(...)); no arg scans cwd + the examples bundled
23
+ with comfy-ts, an explicit dir/file limits to it (file preselected)
19
24
 
20
25
  comfy-ts help
21
26
  `
@@ -25,6 +30,18 @@ async function main(): Promise<number> {
25
30
  if (cmd === 'gen') return runGen(rest)
26
31
  if (cmd === 'outline') return runOutline(rest)
27
32
  if (cmd === 'tui') {
33
+ // .cflow.ts workflow modules need bun: node refuses to strip types under
34
+ // node_modules, exactly where the packaged examples live — and the bin's
35
+ // node shebang means `bunx comfy-ts tui` lands here under NODE. Hop to
36
+ // bun when we are not already in it; without bun, runTui degrades loudly.
37
+ if (process.versions.bun == null) {
38
+ const self = fileURLToPath(import.meta.url)
39
+ const res = spawnSync('bun', [self, 'tui', ...rest], { stdio: 'inherit' })
40
+ if (res.error == null) return res.status ?? 1
41
+ console.error(
42
+ `[comfy-ts tui] bun not found (${res.error.message}) — continuing under node: the examples packaged in node_modules cannot load here, and your own .cflow.ts modules rely on node's type stripping`,
43
+ )
44
+ }
28
45
  // lazy import: keeps ink/react out of the codegen paths
29
46
  const { runTui } = await import('src/cli/tui/run-tui.tsx')
30
47
  return runTui(rest)
package/src/cli/gen.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  // fetch a live host's schema and generate its typed sdk
2
2
  import { mkdirSync, writeFileSync } from 'node:fs'
3
- import { join } from 'pathe'
3
+ import { dirname, join, resolve } from 'pathe'
4
4
  import { ComfySchema } from 'src/sdk-generator/ComfySchema.ts'
5
5
  import type { ComfySchemaJSON } from 'src/sdk-generator/ComfyUIObjectInfoTypes.ts'
6
+ import { ComfyTS } from 'src/state.ts'
6
7
  import { readableStringify } from 'src/utils/stringifyReadable.ts'
7
8
 
8
9
  export async function runGen(args: string[]): Promise<number> {
@@ -17,16 +18,18 @@ export async function runGen(args: string[]): Promise<number> {
17
18
  return 1
18
19
  }
19
20
 
20
- // prefer /api/* (canonical prefix; custom nodes like lora-manager hijack the bare routes)
21
+ // the lib's own authed host.fetch does the /api-first probing + X-API-Key
22
+ const comfy = ComfyTS.create()
23
+ const apiKey = getFlag('api-key') ?? process.env.COMFY_CLOUD_API_KEY
24
+ const host = comfy.host({ id, url: hostUrl, apiKey: apiKey ?? undefined })
25
+
21
26
  const fetchJSON = async <T>(route: string): Promise<T> => {
22
- for (const url of [`${hostUrl}/api${route}`, `${hostUrl}${route}`]) {
23
- console.log(`[comfy-ts gen] fetching ${url} …`)
24
- const res = await fetch(url)
25
- if (!res.ok) continue
26
- if (!(res.headers.get('content-type') ?? '').includes('json')) continue
27
- return (await res.json()) as T
28
- }
29
- throw new Error(`GET ${route} failed on ${hostUrl} (tried /api${route} and ${route})`)
27
+ console.log(`[comfy-ts gen] fetching ${hostUrl} ${route} …`)
28
+ const res = await host.fetch(route)
29
+ if (!res.ok) throw new Error(`GET ${route} failed on ${hostUrl}: ${res.status}`)
30
+ if (!(res.headers.get('content-type') ?? '').includes('json'))
31
+ throw new Error(`GET ${route} on ${hostUrl} did not answer json`)
32
+ return (await res.json()) as T
30
33
  }
31
34
 
32
35
  const spec = await fetchJSON<ComfySchemaJSON>('/object_info')
@@ -39,9 +42,15 @@ export async function runGen(args: string[]): Promise<number> {
39
42
 
40
43
  const parsed = new ComfySchema({ spec, embeddings })
41
44
  const dts = parsed.codegenDTS({ hostId: id })
42
- const outPath = join(dir, 'sdk.d.ts')
45
+ // --out: explicit sdk home (the committed cloud catalog) — the json dumps
46
+ // above still cache under .comfy-ts/hosts/<id>/, but the sdk must exist at
47
+ // ONE tsconfig-visible path only, so it skips the hosts dir entirely
48
+ const out = getFlag('out')
49
+ const outPath = out != null ? resolve(process.cwd(), out) : join(dir, 'sdk.d.ts')
50
+ if (out != null) mkdirSync(dirname(outPath), { recursive: true })
43
51
  writeFileSync(outPath, dts, 'utf8')
44
52
  console.log(`[comfy-ts gen] 🟢 ${outPath} (${parsed.nodes.length} nodes, ${(dts.length / 1024).toFixed(0)}kB)`)
45
- console.log(`[comfy-ts gen] add ".comfy-ts/hosts/**/sdk.d.ts" to your tsconfig "include" to activate the types`)
53
+ if (out == null)
54
+ console.log(`[comfy-ts gen] add ".comfy-ts/hosts/**/sdk.d.ts" to your tsconfig "include" to activate the types`)
46
55
  return 0
47
56
  }
@@ -37,6 +37,7 @@ export const Header = observer((p: { st: TuiSt }) => {
37
37
  </HeaderBox>
38
38
  <HeaderBox title="(h)ost">
39
39
  <Text>
40
+ <Text color={s.host.status === 'up' ? 'green' : s.host.status === 'down' ? 'red' : 'gray'}>● </Text>
40
41
  <Text bold color="green">
41
42
  {s.wf.host.data.id}
42
43
  </Text>
@@ -44,6 +45,10 @@ export const Header = observer((p: { st: TuiSt }) => {
44
45
  {' '}
45
46
  ({s.wf.host.data.host}:{s.wf.host.data.port})
46
47
  </Text>
48
+ {/* while down, show the probe loop living: spinner in flight, countdown between tries */}
49
+ {s.host.status === 'down' && (
50
+ <Text color="red"> {s.host.probing ? s.host.spinner : `↻ ${s.host.retryInS}s`}</Text>
51
+ )}
47
52
  </Text>
48
53
  </HeaderBox>
49
54
  </Box>
@@ -0,0 +1,23 @@
1
+ import { Box, Text } from 'ink'
2
+ import { observer } from 'mobx-react-lite'
3
+ import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
+
5
+ const ERROR_RE = /error|exception|traceback|failed/i
6
+
7
+ /** last server console lines (LogsSt), below the vars panel */
8
+ export const LogsPanel = observer((p: { st: TuiSt }) => {
9
+ const rows = p.st.logs.tail(p.st.termRows < 30 ? 4 : 8)
10
+ if (rows.length === 0) return null
11
+ return (
12
+ <Box borderStyle="round" borderColor="gray" paddingX={1} flexDirection="column" flexShrink={0}>
13
+ <Box marginTop={-1}>
14
+ <Text color="gray">comfy host logs</Text>
15
+ </Box>
16
+ {rows.map((line, ix) => (
17
+ <Text key={ix} color={ERROR_RE.test(line) ? 'red' : 'gray'} wrap="truncate-end">
18
+ {line}
19
+ </Text>
20
+ ))}
21
+ </Box>
22
+ )
23
+ })
@@ -2,23 +2,68 @@ import { Box, Text } from 'ink'
2
2
  import { observer } from 'mobx-react-lite'
3
3
  import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
4
4
 
5
- /** right-side panel: selected-lora preview in the loras overlay, live latent while running, last output after.
5
+ /** right-side panel: selected-lora preview in the loras overlay, live latent while running,
6
+ * last output after — plus the `p` settings menu (mode 'preview') rendered in place.
6
7
  * protocol terminals: the body is BLANK cells — useProtocolImage paints the real image over them */
7
8
  export const PreviewPanel = observer((p: { st: TuiSt }) => {
8
9
  const s = p.st
9
10
  const pv = s.preview
11
+
12
+ if (pv.menuOpen) {
13
+ return (
14
+ <Box borderStyle="double" paddingX={1} flexDirection="column" flexShrink={0} width={pv.width + 4}>
15
+ <Box marginTop={-1}>
16
+ <Text color="gray">(p)review · settings</Text>
17
+ </Box>
18
+ {pv.menuRows.map((row, ix) => {
19
+ const sel = ix === pv.menuIx
20
+ return (
21
+ <Text key={row.key} inverse={sel} wrap="truncate">
22
+ {sel ? '▸ ' : ' '}
23
+ {row.label.padEnd(14)}
24
+ <Text bold>{row.value}</Text>
25
+ </Text>
26
+ )
27
+ })}
28
+ <Text> </Text>
29
+ <Text color="gray" wrap="truncate">
30
+ ←→ change · ↑↓ move · ⏎/p/esc done
31
+ </Text>
32
+ </Box>
33
+ )
34
+ }
35
+
10
36
  const loraMode = s.mode === 'overlay-loras'
11
- const showLatent = !loraMode && s.exec.running && (pv.latentAnsi != null || pv.latentBytes != null)
12
- const label = loraMode ? `lora ${s.loras.previewName ?? 'lora'}` : showLatent ? 'latent' : 'output'
13
- const placeholder = loraMode ? (s.loras.previewNote ?? '(pick a lora)') : '(no image yet)'
14
- const content = pv.useNative ? null : loraMode ? s.loras.previewAnsi : showLatent ? pv.latentAnsi : pv.outputAnsi
15
- const reserveRect = pv.useNative && pv.protocolImage != null
37
+ const running = s.exec.running
38
+ const wantLatent = running && pv.duringRun !== 'last-output'
39
+ const showLatent = !loraMode && wantLatent && (pv.latentAnsi != null || pv.latentBytes != null)
40
+ const label = loraMode
41
+ ? `lora ${s.loras.previewName ?? 'lora'}`
42
+ : showLatent
43
+ ? pv.duringRun === 'latent-small'
44
+ ? 'latent small'
45
+ : 'latent'
46
+ : 'output'
47
+ const placeholder = loraMode
48
+ ? (s.loras.previewNote ?? '(pick a lora)')
49
+ : pv.latentsMissing
50
+ ? '(no latents from the server — launch comfy with --preview-method auto)'
51
+ : '(no image yet)'
52
+ const content = pv.useNative
53
+ ? null
54
+ : loraMode
55
+ ? s.loras.previewAnsi
56
+ : showLatent
57
+ ? (pv.latentAnsi ?? pv.outputAnsi)
58
+ : pv.outputAnsi
59
+ const reserveRect = pv.useNative && (pv.protocolImage != null || pv.protocolImageCorner != null)
16
60
  return (
17
61
  <Box borderStyle="round" paddingX={1} flexDirection="column" flexShrink={0} width={pv.width + 4}>
18
62
  {/* marginTop -1 lifts the label onto the border line: the panel key IS its title */}
19
63
  <Box marginTop={-1}>
20
64
  <Text color="gray" wrap="truncate">
21
- (p)review · {label}
65
+ (p)review · {label} · {pv.renderer}
66
+ {pv.latentsMissing ? <Text color="red"> · no latents!</Text> : null}
22
67
  </Text>
23
68
  </Box>
24
69
  {reserveRect ? (
@@ -125,6 +125,11 @@ const MODE_KEYS: Partial<Record<string, Hint[]>> = {
125
125
  ['↑↓', 'move'],
126
126
  ['h/esc', 'back'],
127
127
  ],
128
+ preview: [
129
+ ['←→', 'change'],
130
+ ['↑↓', 'move'],
131
+ ['⏎/p/esc', 'done'],
132
+ ],
128
133
  }
129
134
 
130
135
  /** persistent 2-line keybar: EVERYTHING available right now, always visible */
@@ -139,16 +144,17 @@ export const KeyBar = observer((p: { st: TuiSt }) => {
139
144
  // keys already advertised by a panel title (t/v/p) or a header box (w/d/h)
140
145
  // are NOT repeated here — one letter, one place
141
146
  const globalHints: Hint[] =
142
- s.mode === 'nav' || s.mode === 'tree' || s.mode === 'host'
147
+ s.mode === 'nav' || s.mode === 'tree' || s.mode === 'host' || s.mode === 'preview'
143
148
  ? [
144
149
  ['r', 'run'],
145
150
  ['s', 'reroll+run'],
146
151
  ...(s.mode === 'nav' ? ([['e', 'rename draft']] as Hint[]) : []),
147
152
  // the preview panel carries `p` in its title — unless it is hidden
148
- ...(s.preview.show ? [] : ([['p', 'preview off']] as Hint[])),
153
+ ...(s.preview.show || s.mode === 'preview' ? [] : ([['p', 'preview (off)']] as Hint[])),
149
154
  ['o', 'open image'],
150
- // c is duplicate inside the tree — don't advertise the copy pair there
151
- ...(s.mode === 'tree' ? [] : ([['c/C', 'copy wf/api']] as Hint[])),
155
+ // c is duplicate inside the tree — don't advertise the copy pair
156
+ // there; the preview menu doesn't forward it either
157
+ ...(s.mode === 'tree' || s.mode === 'preview' ? [] : ([['c/C', 'copy wf/api']] as Hint[])),
152
158
  ['q', 'quit'],
153
159
  ]
154
160
  : [
@@ -24,12 +24,25 @@ export const TreePanel = observer((p: { st: TuiSt }) => {
24
24
  </Box>
25
25
  {tree.rows.map((row, ix) => {
26
26
  const sel = focused && ix === tree.ix
27
+ if (row.kind === 'section') {
28
+ return (
29
+ <Text key={`section·${row.label}`} color="gray" dimColor wrap="truncate">
30
+ ─ {row.label}
31
+ </Text>
32
+ )
33
+ }
27
34
  if (row.kind === 'workflow') {
28
35
  const arrow = row.hasDrafts ? (row.expanded ? '▾' : '▸') : ' '
36
+ const marker = row.error != null ? '✗' : row.current ? '●' : ' '
29
37
  return (
30
- <Text key={row.file} inverse={sel} color={row.current ? 'green' : undefined} wrap="truncate">
38
+ <Text
39
+ key={row.file}
40
+ inverse={sel}
41
+ color={row.error != null ? 'red' : row.current ? 'green' : undefined}
42
+ wrap="truncate"
43
+ >
31
44
  {arrow}
32
- {row.current ? '●' : ' '} {row.name}
45
+ {marker} {row.name}
33
46
  </Text>
34
47
  )
35
48
  }
@@ -9,6 +9,7 @@ import { ChoiceOverlay, SizeOverlay } from 'src/cli/tui/components/PickerOverlay
9
9
  import { PreviewPanel } from 'src/cli/tui/components/PreviewPanel.tsx'
10
10
  import { PromptOverlay } from 'src/cli/tui/components/PromptOverlay.tsx'
11
11
  import { KeyBar, ProgressLine } from 'src/cli/tui/components/StatusBar.tsx'
12
+ import { LogsPanel } from 'src/cli/tui/components/LogsPanel.tsx'
12
13
  import { TextOverlay } from 'src/cli/tui/components/TextOverlay.tsx'
13
14
  import { TreePanel } from 'src/cli/tui/components/TreePanel.tsx'
14
15
  import { VarsPanel } from 'src/cli/tui/components/VarsPanel.tsx'
@@ -114,7 +115,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
114
115
  if (input === 's') return s.exec.randomizeSeedAndRun()
115
116
  if (input === 'd') return s.drafts.begin()
116
117
  if (input === 'h') return s.host.begin()
117
- if (input === 'p') return s.settings.cyclePreviewMode()
118
+ if (input === 'p') return s.preview.beginMenu()
118
119
  if (input === 'o') return s.exec.openLastOutput()
119
120
  if (input === 'q') {
120
121
  s.onExit()
@@ -134,6 +135,26 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
134
135
  }
135
136
  return
136
137
  }
138
+ if (s.mode === 'preview') {
139
+ const pv = s.preview
140
+ // ⏎ CONFIRMS (closes): ←→ already changed the value in place
141
+ if (key.escape || key.return || input === 'p' || input === 'v') return pv.blurMenu()
142
+ if (key.upArrow) return pv.menuMove(-1)
143
+ if (key.downArrow) return pv.menuMove(1)
144
+ if (key.leftArrow) return pv.menuCycle(-1)
145
+ if (key.rightArrow || input === ' ') return pv.menuCycle(1)
146
+ // global keys keep working from the menu (mirrors the tree)
147
+ if (input === 'r') return void s.exec.run()
148
+ if (input === 's') return s.exec.randomizeSeedAndRun()
149
+ if (input === 'd') return s.drafts.begin()
150
+ if (input === 'h') return s.host.begin()
151
+ if (input === 'o') return s.exec.openLastOutput()
152
+ if (input === 'q') {
153
+ s.onExit()
154
+ return app.exit()
155
+ }
156
+ return
157
+ }
137
158
  if (s.mode === 'overlay-drafts') {
138
159
  const d = s.drafts
139
160
  if (key.escape) return s.editor.cancel()
@@ -167,7 +188,7 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
167
188
  if (input === 't' || input === 'w') return s.tree.focus()
168
189
  if (input === 'h') return s.host.begin()
169
190
  if (input === 'd') return s.drafts.begin()
170
- if (input === 'p') return s.settings.cyclePreviewMode()
191
+ if (input === 'p') return s.preview.beginMenu()
171
192
  if (input === 'o') return s.exec.openLastOutput()
172
193
  if (input === 'c') return void s.exec.copyWorkflowJson()
173
194
  if (input === 'C') return void s.exec.copyApiJson()
@@ -214,8 +235,10 @@ export const TuiApp = observer((p: { st: TuiSt }) => {
214
235
  ))}
215
236
  </Box>
216
237
  )}
238
+ {/* hidden while an overlay owns the vars area: typing space > logs */}
239
+ {!s.mode.startsWith('overlay-') && !(s.mode === 'edit' && s.editor.isCustom) && <LogsPanel st={s} />}
217
240
  </Box>
218
- {s.preview.show && <PreviewPanel st={s} />}
241
+ {(s.preview.show || s.preview.menuOpen) && <PreviewPanel st={s} />}
219
242
  </Box>
220
243
  <KeyBar st={s} />
221
244
  </Box>
@@ -0,0 +1,79 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { fileURLToPath } from 'node:url'
3
+ import { dirname, join } from 'pathe'
4
+
5
+ /**
6
+ * recursive scan for the workflow-module naming convention. Entries BELOW a
7
+ * node_modules segment are skipped: packaged examples arrive via
8
+ * bundledExamplesDir (symlinked layouts like pnpm would otherwise list them
9
+ * twice, un-deduped, as the user's own files), and third-party packages
10
+ * shipping *.cflow.ts are not this project's workflows. A scan root that is
11
+ * ITSELF inside node_modules still works (the filter is relative to the root).
12
+ */
13
+ export function scanCflowFiles(dir: string): string[] {
14
+ const hits = readdirSync(dir, { recursive: true })
15
+ .map((f) => String(f))
16
+ .filter((f) => !f.split('/').includes('node_modules'))
17
+ .map((f) => join(dir, f))
18
+ .filter((f) => f.endsWith('.cflow.ts') || f.endsWith('.cflow.tsx'))
19
+ return hits.sort()
20
+ }
21
+
22
+ /**
23
+ * the examples/ folder shipped in the npm tarball, resolved from THIS module's
24
+ * own location (NEVER cwd): walking up to the nearest NAMED package.json finds
25
+ * <pkg>/examples both from a consumer's node_modules/comfy-ts/dist/cli.js and
26
+ * from this repo's src/cli/tui/. Returns null when the examples are absent
27
+ * (a consumer may prune the folder) or when the nearest named package is not
28
+ * comfy-ts (the lib was inlined into someone else's bundle — its examples are
29
+ * not on disk); no package.json all the way up is a broken install and throws.
30
+ */
31
+ export function bundledExamplesDir(moduleUrl: string = import.meta.url): string | null {
32
+ let dir = dirname(fileURLToPath(moduleUrl))
33
+ let prev = ''
34
+ while (dir !== prev) {
35
+ const pkgPath = join(dir, 'package.json')
36
+ if (existsSync(pkgPath)) {
37
+ let pkg: { name?: string } = {}
38
+ try {
39
+ pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
40
+ } catch {
41
+ // a malformed package.json on the walk (someone's broken fixture
42
+ // dir) must not take the whole TUI down; treat as unnamed
43
+ }
44
+ if (pkg.name === 'comfy-ts') {
45
+ const examples = join(dir, 'examples')
46
+ return existsSync(examples) ? examples : null
47
+ }
48
+ if (pkg.name != null) return null
49
+ }
50
+ prev = dir
51
+ dir = dirname(dir)
52
+ }
53
+ throw new Error(`[comfy-ts tui] no package.json found walking up from ${fileURLToPath(moduleUrl)}`)
54
+ }
55
+
56
+ export type WorkflowDiscovery = {
57
+ /** every module the tree lists, user files first, bundled examples last */
58
+ files: string[]
59
+ /** the subset that came from the PACKAGED examples (grouped apart in the tree) */
60
+ bundled: Set<string>
61
+ }
62
+
63
+ /**
64
+ * PURE merge of the scan with the packaged examples (headless-tested). An
65
+ * explicit target keeps its scope only. Bundled files ALWAYS group under the
66
+ * bundled section, also when the scan already found them (repo dev: ./examples
67
+ * is under cwd) — dedupe relies on the caller passing realpath-normalized
68
+ * strings on both sides.
69
+ */
70
+ export function mergeWorkflowSources(p: {
71
+ explicitTarget: boolean
72
+ scanned: string[]
73
+ bundledFiles: string[]
74
+ }): WorkflowDiscovery {
75
+ if (p.explicitTarget) return { files: p.scanned, bundled: new Set() }
76
+ const bundled = new Set(p.bundledFiles)
77
+ const userFiles = p.scanned.filter((f) => !bundled.has(f))
78
+ return { files: [...userFiles, ...p.bundledFiles], bundled }
79
+ }