comfy-ts 0.4.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.
- package/README.md +349 -255
- package/dist/DefinedWorkflow-O3ynII3Y.js +598 -0
- package/dist/DefinedWorkflow-O3ynII3Y.js.map +1 -0
- package/dist/cli.js +3969 -128
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1167 -172
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +401 -115
- package/dist/index.d.ts +401 -115
- package/dist/index.js +1159 -173
- package/dist/index.js.map +1 -1
- package/dist/{run-tui-SDSJo1Qf.js → run-tui-BFhba_oG.js} +132 -609
- package/dist/run-tui-BFhba_oG.js.map +1 -0
- package/examples/01-txt2img.cflow.ts +50 -0
- package/examples/02-img2img-upload.cflow.ts +66 -0
- package/examples/03-export-workflow-json.cflow.ts +56 -0
- package/examples/04-krea2-turbo-t2i.cflow.ts +125 -0
- package/examples/05-comfy-cloud.cflow.ts +67 -0
- package/examples/comfy-cloud/sdk.d.ts +122674 -0
- package/guide-for-agents.md +166 -0
- package/package.json +6 -1
- package/src/cli/comfy-ts-cli.ts +19 -2
- package/src/cli/gen.ts +21 -12
- package/src/cli/tui/components/TreePanel.tsx +15 -2
- package/src/cli/tui/discoverWorkflows.ts +79 -0
- package/src/cli/tui/run-tui.tsx +51 -23
- package/src/cli/tui/state/HostSt.ts +2 -3
- package/src/cli/tui/state/TreeSt.ts +30 -6
- package/src/cli/tui/state/TuiSt.ts +21 -3
- package/src/cli/tui/state/WorkflowsSt.ts +15 -1
- package/src/host/ComfyHost.ts +203 -77
- package/src/host/ComfyManager.ts +10 -9
- package/src/host/ComfyUploader.ts +1 -2
- package/src/host/ResilientWebsocket.ts +3 -1
- package/src/host/hostUrl.ts +59 -0
- package/src/host/loraManagerApi.ts +5 -4
- package/src/index.ts +20 -1
- package/src/litegraph/CanonicalWorkflow.ts +77 -0
- package/src/litegraph/LiteGraphGroup.ts +9 -7
- package/src/litegraph/LiteGraphJSON.ts +34 -13
- package/src/litegraph/LiteGraphLink.ts +32 -2
- package/src/litegraph/LiteGraphNode.ts +18 -33
- package/src/litegraph/LiteGraphNodeInput.ts +10 -8
- package/src/litegraph/LiteGraphNodeOutput.ts +2 -3
- package/src/litegraph/LiteGraphSubgraphDef.ts +74 -0
- package/src/litegraph/convertFlowToLiteGraphJSON.ts +4 -4
- package/src/litegraph/expandSubgraphs.ts +352 -0
- package/src/litegraph/normalizeWorkflow.ts +141 -0
- package/src/runner/ComfyExecution.ts +4 -5
- package/src/runner/ComfyWorkflow.ts +2 -2
- package/src/runner/wsBinaryFrame.ts +48 -0
- package/src/sdk-generator/Primitives.ts +6 -24
- package/src/sdk-generator/comfy-api-json.ts +3 -1
- package/src/sdk-generator/inputWidgetKind.ts +179 -0
- package/src/sdk-generator/litegraphToApiRequestPayload.ts +372 -96
- package/src/state.ts +13 -2
- package/dist/log-CdfgILde.js +0 -10
- package/dist/log-CdfgILde.js.map +0 -1
- package/dist/run-tui-SDSJo1Qf.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
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Type-safe generative AI pipeline creation and execution using ComfyUI",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"comfyui",
|
|
@@ -42,7 +42,9 @@
|
|
|
42
42
|
"files": [
|
|
43
43
|
"dist",
|
|
44
44
|
"src",
|
|
45
|
+
"examples",
|
|
45
46
|
"README.md",
|
|
47
|
+
"guide-for-agents.md",
|
|
46
48
|
"LICENSE"
|
|
47
49
|
],
|
|
48
50
|
"scripts": {
|
|
@@ -63,7 +65,10 @@
|
|
|
63
65
|
"ci:local": "bun run ci && bun run typecheck",
|
|
64
66
|
"gen:manager": "bun src/manager/script-update-manager.bun.ts",
|
|
65
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",
|
|
66
69
|
"sdk:outline": "bun scripts/sdk-outline.ts",
|
|
70
|
+
"templates:fetch": "bun scripts/fetch-templates.ts",
|
|
71
|
+
"templates:check": "bun scripts/check-templates.ts",
|
|
67
72
|
"hooks:install": "git config core.hooksPath .githooks",
|
|
68
73
|
"prepublishOnly": "bun run ci && bun run build",
|
|
69
74
|
"tui": "bun src/cli/comfy-ts-cli.ts tui"
|
package/src/cli/comfy-ts-cli.ts
CHANGED
|
@@ -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
|
|
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
|
-
//
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
|
@@ -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
|
|
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
|
-
{
|
|
45
|
+
{marker} {row.name}
|
|
33
46
|
</Text>
|
|
34
47
|
)
|
|
35
48
|
}
|
|
@@ -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
|
+
}
|
package/src/cli/tui/run-tui.tsx
CHANGED
|
@@ -1,50 +1,78 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { realpathSync, statSync } from 'node:fs'
|
|
2
2
|
import { pathToFileURL } from 'node:url'
|
|
3
3
|
import { render } from 'ink'
|
|
4
|
-
import { dirname,
|
|
4
|
+
import { dirname, resolve } from 'pathe'
|
|
5
5
|
import { COMFY_TS_TUI_ENV } from 'src/cli/tui-env.ts'
|
|
6
|
+
import { bundledExamplesDir, mergeWorkflowSources, scanCflowFiles } from 'src/cli/tui/discoverWorkflows.ts'
|
|
6
7
|
import { findDefinedWorkflow } from 'src/cli/tui/findDefinedWorkflow.ts'
|
|
7
8
|
import { installProtocolImagePainter } from 'src/cli/tui/protocolImagePainter.ts'
|
|
8
9
|
import { TuiApp } from 'src/cli/tui/components/TuiApp.tsx'
|
|
9
10
|
import { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const hits = readdirSync(dir, { recursive: true })
|
|
14
|
-
.map((f) => join(dir, String(f)))
|
|
15
|
-
.filter((f) => f.endsWith('.cflow.ts') || f.endsWith('.cflow.tsx'))
|
|
16
|
-
return hits.sort()
|
|
17
|
-
}
|
|
11
|
+
import { extractErrorMessage } from 'src/utils/extractErrorMessage.ts'
|
|
12
|
+
import { logError } from 'src/utils/log.ts'
|
|
13
|
+
import type { DefinedWorkflow } from 'src/vars/DefinedWorkflow.ts'
|
|
18
14
|
|
|
19
15
|
export async function runTui(args: string[]): Promise<number> {
|
|
20
|
-
// no arg =
|
|
21
|
-
|
|
16
|
+
// no arg = cwd scan MERGED with the examples packaged with comfy-ts; an
|
|
17
|
+
// explicit dir/file arg keeps that scope only (a file arg is preselected)
|
|
18
|
+
const target = args.find((a) => !a.startsWith('--'))
|
|
22
19
|
|
|
23
20
|
// the module contract: files check `import.meta.main` (false here) so their
|
|
24
21
|
// standalone run block is skipped; this env var covers in-run tweaks
|
|
25
22
|
process.env[COMFY_TS_TUI_ENV] = '1'
|
|
26
23
|
process.env.COMFY_TS_QUIET = '1' // info chatter off; the TUI owns the screen
|
|
27
24
|
|
|
28
|
-
|
|
25
|
+
// realpath both sides: scanned paths derive from cwd, bundled ones from
|
|
26
|
+
// import.meta — a symlinked cwd must not defeat the dedupe
|
|
27
|
+
const abs = realpathSync(resolve(target ?? '.'))
|
|
29
28
|
const isDir = statSync(abs).isDirectory()
|
|
30
29
|
const scanned = scanCflowFiles(isDir ? abs : dirname(abs))
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
const scannedPlusArg = isDir || scanned.includes(abs) ? scanned : [abs, ...scanned]
|
|
31
|
+
// no bun = no bundled examples: node refuses to import TypeScript under
|
|
32
|
+
// node_modules (the cli re-execs into bun when it can, comfy-ts-cli.ts)
|
|
33
|
+
const canImportBundled = process.versions.bun != null
|
|
34
|
+
const examplesDir = canImportBundled ? bundledExamplesDir() : null
|
|
35
|
+
if (!canImportBundled && target == null)
|
|
36
|
+
logError('packaged examples skipped: importing .cflow.ts from node_modules needs bun (bunx --bun comfy-ts tui)')
|
|
37
|
+
const discovery = mergeWorkflowSources({
|
|
38
|
+
explicitTarget: target != null,
|
|
39
|
+
scanned: scannedPlusArg,
|
|
40
|
+
bundledFiles: examplesDir == null ? [] : scanCflowFiles(realpathSync(examplesDir)),
|
|
41
|
+
})
|
|
42
|
+
const workflowFiles = discovery.files
|
|
43
|
+
if (workflowFiles.length === 0) {
|
|
34
44
|
console.error(`[comfy-ts tui] no **/*.cflow.ts found under ${abs}`)
|
|
35
45
|
return 1
|
|
36
46
|
}
|
|
37
47
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
48
|
+
// initial module = the file arg, else the first candidate that LOADS: a
|
|
49
|
+
// module whose import throws (missing schema cache, bad code) or that
|
|
50
|
+
// exports no DefinedWorkflow becomes a red row in the tree, never a crash
|
|
51
|
+
const candidates =
|
|
52
|
+
!isDir && workflowFiles.includes(abs) ? [abs, ...workflowFiles.filter((f) => f !== abs)] : workflowFiles
|
|
53
|
+
const loadErrors = new Map<string, string>()
|
|
54
|
+
let first: string | null = null
|
|
55
|
+
let wf: DefinedWorkflow | null = null
|
|
56
|
+
for (const file of candidates) {
|
|
57
|
+
try {
|
|
58
|
+
const mod: Record<string, unknown> = await import(pathToFileURL(file).href)
|
|
59
|
+
const found = findDefinedWorkflow(mod)
|
|
60
|
+
if (found == null)
|
|
61
|
+
throw new Error(`${file} exports no DefinedWorkflow — export the result of host.defineWorkflow(...)`)
|
|
62
|
+
first = file
|
|
63
|
+
wf = found
|
|
64
|
+
break
|
|
65
|
+
} catch (e) {
|
|
66
|
+
loadErrors.set(file, extractErrorMessage(e))
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (first == null || wf == null) {
|
|
70
|
+
console.error(`[comfy-ts tui] no loadable workflow module among ${candidates.length} file(s):`)
|
|
71
|
+
for (const [file, err] of loadErrors) console.error(` ${file}: ${err}`)
|
|
44
72
|
return 1
|
|
45
73
|
}
|
|
46
74
|
|
|
47
|
-
const st = new TuiSt(wf, { workflowFiles, currentFile: first })
|
|
75
|
+
const st = new TuiSt(wf, { workflowFiles, currentFile: first, bundledFiles: discovery.bundled, loadErrors })
|
|
48
76
|
// ALT SCREEN (TTY only): deterministic absolute coordinates for the protocol
|
|
49
77
|
// image painter + no scrollback pollution / clipped first row.
|
|
50
78
|
// modifyOtherKeys mode 1 rides along: vscode/xterm.js then ENCODES modified ⏎
|
|
@@ -104,9 +104,8 @@ export class HostSt {
|
|
|
104
104
|
this.spinTimer = spin
|
|
105
105
|
let ok = false
|
|
106
106
|
try {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
})
|
|
107
|
+
// host.fetch: /api preferred + auth header, so cloud hosts probe up too
|
|
108
|
+
const res = await host.fetch('/prompt', { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })
|
|
110
109
|
void res.body?.cancel()
|
|
111
110
|
ok = res.ok
|
|
112
111
|
} catch {
|
|
@@ -3,7 +3,16 @@ import { draftKeyForFile, listDraftsForFile } from 'src/cli/tui/state/DraftsSt.t
|
|
|
3
3
|
import type { TuiSt } from 'src/cli/tui/state/TuiSt.ts'
|
|
4
4
|
|
|
5
5
|
export type TreeRow =
|
|
6
|
-
| { kind: '
|
|
6
|
+
| { kind: 'section'; label: string } // dim group header (bundled examples), never selectable
|
|
7
|
+
| {
|
|
8
|
+
kind: 'workflow'
|
|
9
|
+
file: string
|
|
10
|
+
name: string
|
|
11
|
+
expanded: boolean
|
|
12
|
+
current: boolean
|
|
13
|
+
hasDrafts: boolean
|
|
14
|
+
error: string | null
|
|
15
|
+
}
|
|
7
16
|
| { kind: 'draft'; file: string; draft: string; active: boolean }
|
|
8
17
|
|
|
9
18
|
/** the left `(t)ree`: workflows with their drafts nested under them */
|
|
@@ -19,7 +28,13 @@ export class TreeSt {
|
|
|
19
28
|
void this.st.drafts.version // fs-derived: recompute when drafts change
|
|
20
29
|
const w = this.st.workflows
|
|
21
30
|
const rows: TreeRow[] = []
|
|
31
|
+
let sectionPushed = false
|
|
22
32
|
for (const file of w.files) {
|
|
33
|
+
// bundled examples come LAST in files: one section header before the first
|
|
34
|
+
if (!sectionPushed && w.bundled.has(file)) {
|
|
35
|
+
rows.push({ kind: 'section', label: 'comfy-ts examples' })
|
|
36
|
+
sectionPushed = true
|
|
37
|
+
}
|
|
23
38
|
const current = file === w.currentPath
|
|
24
39
|
const expanded = this.expandedFiles.has(file)
|
|
25
40
|
const drafts = listDraftsForFile(file)
|
|
@@ -30,6 +45,7 @@ export class TreeSt {
|
|
|
30
45
|
expanded,
|
|
31
46
|
current,
|
|
32
47
|
hasDrafts: drafts.length > 0,
|
|
48
|
+
error: w.loadErrors.get(file) ?? null,
|
|
33
49
|
})
|
|
34
50
|
if (!expanded) continue
|
|
35
51
|
for (const draft of drafts) {
|
|
@@ -64,16 +80,23 @@ export class TreeSt {
|
|
|
64
80
|
}
|
|
65
81
|
|
|
66
82
|
move(delta: number): void {
|
|
67
|
-
const
|
|
83
|
+
const rows = this.rows
|
|
84
|
+
const len = rows.length
|
|
68
85
|
if (len === 0) return
|
|
69
|
-
|
|
86
|
+
let ix = this.ix
|
|
87
|
+
// hop over section headers (never selectable); bounded: wraps at most once
|
|
88
|
+
for (let step = 0; step < len; step++) {
|
|
89
|
+
ix = (ix + delta + len) % len
|
|
90
|
+
if (rows[ix]?.kind !== 'section') break
|
|
91
|
+
}
|
|
92
|
+
this.ix = ix
|
|
70
93
|
}
|
|
71
94
|
|
|
72
95
|
/** →: unfold the workflow under the cursor; on a draft row there is nothing
|
|
73
96
|
* left to unfold, so → continues rightwards into the vars panel */
|
|
74
97
|
unfold(): void {
|
|
75
98
|
const row = this.selected
|
|
76
|
-
if (row == null) return
|
|
99
|
+
if (row == null || row.kind === 'section') return
|
|
77
100
|
if (row.kind === 'workflow') this.expandedFiles.add(row.file)
|
|
78
101
|
else this.blur()
|
|
79
102
|
}
|
|
@@ -81,7 +104,7 @@ export class TreeSt {
|
|
|
81
104
|
/** ←: fold the workflow under the cursor; on a draft row, jump to (and fold) its parent */
|
|
82
105
|
fold(): void {
|
|
83
106
|
const row = this.selected
|
|
84
|
-
if (row == null) return
|
|
107
|
+
if (row == null || row.kind === 'section') return
|
|
85
108
|
this.expandedFiles.delete(row.file)
|
|
86
109
|
if (row.kind === 'draft') {
|
|
87
110
|
const ix = this.rows.findIndex((r) => r.kind === 'workflow' && r.file === row.file)
|
|
@@ -92,7 +115,7 @@ export class TreeSt {
|
|
|
92
115
|
/** ⏎: load the workflow (into 'default'), or the exact draft under the cursor */
|
|
93
116
|
async commit(): Promise<void> {
|
|
94
117
|
const row = this.selected
|
|
95
|
-
if (row == null) return
|
|
118
|
+
if (row == null || row.kind === 'section') return
|
|
96
119
|
if (row.kind === 'workflow') return this.st.workflows.commit(row.file)
|
|
97
120
|
return this.st.workflows.commit(row.file, row.draft)
|
|
98
121
|
}
|
|
@@ -100,6 +123,7 @@ export class TreeSt {
|
|
|
100
123
|
/** n: new draft — current workflow only (a draft snapshots its LIVE var values) */
|
|
101
124
|
promptNewDraft(): void {
|
|
102
125
|
const row = this.selected
|
|
126
|
+
if (row?.kind === 'section') return
|
|
103
127
|
if (row != null && row.file !== this.st.workflows.currentPath) {
|
|
104
128
|
this.st.exec.notice = 'load that workflow first (⏎) — a new draft snapshots its live vars'
|
|
105
129
|
return
|
|
@@ -55,7 +55,17 @@ export class TuiSt {
|
|
|
55
55
|
disposers: (() => void)[] = []
|
|
56
56
|
onExit: () => void = () => {}
|
|
57
57
|
|
|
58
|
-
constructor(
|
|
58
|
+
constructor(
|
|
59
|
+
wf: DefinedWorkflow,
|
|
60
|
+
opts: {
|
|
61
|
+
workflowFiles?: string[]
|
|
62
|
+
currentFile?: string
|
|
63
|
+
/** files that came from the PACKAGED examples (grouped apart in the tree) */
|
|
64
|
+
bundledFiles?: Set<string>
|
|
65
|
+
/** modules that failed to load before mount (red rows in the tree) */
|
|
66
|
+
loadErrors?: Map<string, string>
|
|
67
|
+
} = {},
|
|
68
|
+
) {
|
|
59
69
|
this.wf = wf
|
|
60
70
|
// wf: observable.ref so switching workflows re-renders without proxying
|
|
61
71
|
// the foreign object; children manage their own observability
|
|
@@ -79,7 +89,13 @@ export class TuiSt {
|
|
|
79
89
|
this.editor = new EditorSt(this)
|
|
80
90
|
this.picker = new PickerSt(this)
|
|
81
91
|
this.loras = new LorasSt(this)
|
|
82
|
-
this.workflows = new WorkflowsSt(
|
|
92
|
+
this.workflows = new WorkflowsSt(
|
|
93
|
+
this,
|
|
94
|
+
opts.workflowFiles ?? [],
|
|
95
|
+
opts.currentFile ?? null,
|
|
96
|
+
opts.bundledFiles,
|
|
97
|
+
opts.loadErrors,
|
|
98
|
+
)
|
|
83
99
|
this.tree = new TreeSt(this)
|
|
84
100
|
this.drafts = new DraftsSt(this)
|
|
85
101
|
this.exec = new ExecSt(this)
|
|
@@ -122,7 +138,9 @@ export class TuiSt {
|
|
|
122
138
|
get treeWidth(): number {
|
|
123
139
|
const longest = Math.max(
|
|
124
140
|
8,
|
|
125
|
-
...this.tree.rows.map((r) =>
|
|
141
|
+
...this.tree.rows.map((r) =>
|
|
142
|
+
r.kind === 'workflow' ? r.name.length : r.kind === 'draft' ? r.draft.length + 3 : r.label.length,
|
|
143
|
+
),
|
|
126
144
|
)
|
|
127
145
|
return Math.min(32, longest + 7)
|
|
128
146
|
}
|