comfyui-node 1.3.1 → 1.4.1
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.OLD.md +1395 -0
- package/README.md +112 -1223
- package/dist/.tsbuildinfo +1 -1
- package/dist/call-wrapper.d.ts +1 -0
- package/dist/call-wrapper.d.ts.map +1 -1
- package/dist/call-wrapper.js +136 -41
- package/dist/call-wrapper.js.map +1 -1
- package/dist/client.js +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/pool/WorkflowPool.d.ts +93 -0
- package/dist/pool/WorkflowPool.d.ts.map +1 -0
- package/dist/pool/WorkflowPool.js +438 -0
- package/dist/pool/WorkflowPool.js.map +1 -0
- package/dist/pool/client/ClientManager.d.ts +71 -0
- package/dist/pool/client/ClientManager.d.ts.map +1 -0
- package/dist/pool/client/ClientManager.js +167 -0
- package/dist/pool/client/ClientManager.js.map +1 -0
- package/dist/pool/failover/SmartFailoverStrategy.d.ts +18 -0
- package/dist/pool/failover/SmartFailoverStrategy.d.ts.map +1 -0
- package/dist/pool/failover/SmartFailoverStrategy.js +65 -0
- package/dist/pool/failover/SmartFailoverStrategy.js.map +1 -0
- package/dist/pool/failover/Strategy.d.ts +10 -0
- package/dist/pool/failover/Strategy.d.ts.map +1 -0
- package/dist/pool/failover/Strategy.js +2 -0
- package/dist/pool/failover/Strategy.js.map +1 -0
- package/dist/pool/index.d.ts +9 -0
- package/dist/pool/index.d.ts.map +1 -0
- package/dist/pool/index.js +4 -0
- package/dist/pool/index.js.map +1 -0
- package/dist/pool/queue/QueueAdapter.d.ts +31 -0
- package/dist/pool/queue/QueueAdapter.d.ts.map +1 -0
- package/dist/pool/queue/QueueAdapter.js +2 -0
- package/dist/pool/queue/QueueAdapter.js.map +1 -0
- package/dist/pool/queue/adapters/memory.d.ts +21 -0
- package/dist/pool/queue/adapters/memory.d.ts.map +1 -0
- package/dist/pool/queue/adapters/memory.js +96 -0
- package/dist/pool/queue/adapters/memory.js.map +1 -0
- package/dist/pool/types/events.d.ts +75 -0
- package/dist/pool/types/events.d.ts.map +1 -0
- package/dist/pool/types/events.js +2 -0
- package/dist/pool/types/events.js.map +1 -0
- package/dist/pool/types/job.d.ts +56 -0
- package/dist/pool/types/job.d.ts.map +1 -0
- package/dist/pool/types/job.js +2 -0
- package/dist/pool/types/job.js.map +1 -0
- package/dist/pool/utils/clone.d.ts +2 -0
- package/dist/pool/utils/clone.d.ts.map +1 -0
- package/dist/pool/utils/clone.js +7 -0
- package/dist/pool/utils/clone.js.map +1 -0
- package/dist/pool/utils/hash.d.ts +5 -0
- package/dist/pool/utils/hash.d.ts.map +1 -0
- package/dist/pool/utils/hash.js +19 -0
- package/dist/pool/utils/hash.js.map +1 -0
- package/dist/types/event.d.ts +3 -2
- package/dist/types/event.d.ts.map +1 -1
- package/dist/workflow.d.ts.map +1 -1
- package/dist/workflow.js +2 -1
- package/dist/workflow.js.map +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -6,1317 +6,206 @@
|
|
|
6
6
|

|
|
7
7
|

|
|
8
8
|
|
|
9
|
-
TypeScript SDK for interacting with the [ComfyUI](https://github.com/comfyanonymous/ComfyUI) API – focused on workflow construction, prompt execution orchestration, multi
|
|
10
|
-
|
|
11
|
-
> 1.0 is a complete redesign around modular feature namespaces (`api.ext.*`) and stronger typing. All legacy instance methods have been removed – see Migration section if upgrading.
|
|
12
|
-
|
|
13
|
-
## Contents
|
|
14
|
-
|
|
15
|
-
- [Features](#features)
|
|
16
|
-
- [Installation](#installation)
|
|
17
|
-
- [Cheat Sheet](#cheat-sheet)
|
|
18
|
-
- [Recent Enhancements (Ergonomics & Typing)](#recent-enhancements-ergonomics--typing)
|
|
19
|
-
- [High‑Level Workflow API (Experimental) – Quick Intro](#highlevel-workflow-api-experimental--quick-intro)
|
|
20
|
-
- [Choosing: Workflow vs PromptBuilder](#choosing-workflow-vs-promptbuilder)
|
|
21
|
-
- [Result Object Anatomy](#result-object-anatomy)
|
|
22
|
-
- [Multi-Instance Pool](#multi-instance-pool)
|
|
23
|
-
- [Authentication](#authentication)
|
|
24
|
-
- [Custom WebSocket](#custom-websocket)
|
|
25
|
-
- [Modular Features (`api.ext`)](#modular-features-apiext)
|
|
26
|
-
- [Events](#events)
|
|
27
|
-
- [Preview Metadata](#preview-metadata)
|
|
28
|
-
- [API Nodes (Comfy.org paid)](#api-nodes-comfyorg-paid)
|
|
29
|
-
- [Image Inputs: Attach Files (DX)](#image-inputs-attach-files-dx)
|
|
30
|
-
- [1.0 Migration](#10-migration)
|
|
31
|
-
- [Reference Overview](#reference-overview)
|
|
32
|
-
- [Examples](#examples)
|
|
33
|
-
- [Errors & Diagnostics](#errors--diagnostics)
|
|
34
|
-
- [Troubleshooting](#troubleshooting)
|
|
35
|
-
- [Published Smoke Test](#published-smoke-test)
|
|
36
|
-
- [Contributing](#contributing)
|
|
37
|
-
- [License](#license)
|
|
9
|
+
TypeScript SDK for interacting with the [ComfyUI](https://github.com/comfyanonymous/ComfyUI) API – focused on workflow construction, prompt execution orchestration, multi-instance scheduling and extension integration.
|
|
38
10
|
|
|
39
11
|
## Features
|
|
40
12
|
|
|
41
|
-
- Fully typed TypeScript surface
|
|
42
|
-
-
|
|
43
|
-
-
|
|
44
|
-
- WebSocket events
|
|
45
|
-
-
|
|
46
|
-
-
|
|
47
|
-
-
|
|
48
|
-
-
|
|
49
|
-
-
|
|
50
|
-
-
|
|
51
|
-
-
|
|
52
|
-
- JSON round‑trip support for builder state persistence
|
|
53
|
-
- High‑level `Workflow` abstraction (rapid parameter tweaking of existing JSON graphs)
|
|
54
|
-
- Input sugar helpers: `wf.input(...)`, `wf.batchInputs(...)`
|
|
55
|
-
- Soft autocomplete mode for sampler / scheduler (`Workflow.fromAugmented`)
|
|
56
|
-
- Progressive typed outputs inferred from `wf.output(...)` declarations
|
|
57
|
-
- Per‑node output shape heuristics (e.g. `SaveImage*`, `KSampler`)
|
|
58
|
-
- Automatic random seed substitution for `seed: -1` with `_autoSeeds` metadata
|
|
13
|
+
- Fully typed TypeScript surface with progressive output typing
|
|
14
|
+
- High-level `Workflow` API – tweak existing JSON workflows with minimal boilerplate
|
|
15
|
+
- Low-level `PromptBuilder` – programmatic graph construction with validation
|
|
16
|
+
- WebSocket events – progress, preview, output, completion with reconnection
|
|
17
|
+
- Multi-instance pooling – `WorkflowPool` with smart failover & health checks (v1.4.1+)
|
|
18
|
+
- Modular features – `api.ext.*` namespaces (queue, history, system, file, etc.)
|
|
19
|
+
- Authentication – basic, bearer token, custom headers
|
|
20
|
+
- Image attachments – upload files directly with workflow submissions
|
|
21
|
+
- Preview metadata – rich preview frames with metadata support
|
|
22
|
+
- Auto seed substitution – `seed: -1` randomized automatically
|
|
23
|
+
- API node support – compatible with custom/paid API nodes (Comfy.org)
|
|
59
24
|
|
|
60
25
|
## Installation
|
|
61
26
|
|
|
62
|
-
Requires Node.js >= 22
|
|
27
|
+
Requires Node.js >= 22. Works with Bun.
|
|
63
28
|
|
|
64
29
|
```bash
|
|
65
30
|
npm install comfyui-node
|
|
66
|
-
# or
|
|
67
|
-
pnpm add comfyui-node
|
|
68
|
-
# or
|
|
69
|
-
bun add comfyui-node
|
|
70
31
|
```
|
|
71
32
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
Minimal ESM usage example:
|
|
33
|
+
## Quick Start
|
|
75
34
|
|
|
76
35
|
```ts
|
|
77
36
|
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
78
37
|
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
79
38
|
|
|
80
|
-
async function main() {
|
|
81
|
-
const api = await new ComfyApi('http://127.0.0.1:8188').ready();
|
|
82
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
83
|
-
.set('6.inputs.text', 'Hello ComfyUI SDK')
|
|
84
|
-
.output('images:9');
|
|
85
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
86
|
-
const result = await job.done();
|
|
87
|
-
for (const img of (result.images?.images || [])) {
|
|
88
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
main();
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
## Cheat Sheet
|
|
95
|
-
|
|
96
|
-
Fast reference for common operations. See deeper sections for narrative explanations.
|
|
97
|
-
|
|
98
|
-
### Workflow (High-Level)
|
|
99
|
-
|
|
100
|
-
```ts
|
|
101
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
102
39
|
const api = await new ComfyApi('http://127.0.0.1:8188').ready();
|
|
103
|
-
const wf = Workflow.from(json)
|
|
104
|
-
.set('3.inputs.steps', 20) // dotted path set
|
|
105
|
-
.input('SAMPLER','cfg', 4) // input helper
|
|
106
|
-
.batchInputs('SAMPLER', { steps: 15, cfg: 3 })
|
|
107
|
-
.output('images:9'); // alias:nodeId
|
|
108
|
-
const job = await api.run(wf); // acceptance barrier
|
|
109
|
-
job.on('progress_pct', p => console.log(p,'%'));
|
|
110
|
-
const result = await job.done();
|
|
111
|
-
for (const img of (result.images?.images||[])) console.log(api.ext.file.getPathImage(img));
|
|
112
|
-
```
|
|
113
|
-
|
|
114
|
-
### PromptBuilder (Lower-Level)
|
|
115
|
-
|
|
116
|
-
```ts
|
|
117
|
-
import { PromptBuilder } from 'comfyui-node';
|
|
118
|
-
const builder = new PromptBuilder(base,[ 'positive','seed' ],[ 'images' ])
|
|
119
|
-
.setInputNode('positive','6.inputs.text')
|
|
120
|
-
.setInputNode('seed','3.inputs.seed')
|
|
121
|
-
.setOutputNode('images','9')
|
|
122
|
-
.input('positive','A misty forest')
|
|
123
|
-
.input('seed', 1234)
|
|
124
|
-
.validateOutputMappings();
|
|
125
|
-
```
|
|
126
|
-
|
|
127
|
-
### Running (Alternate APIs)
|
|
128
|
-
|
|
129
|
-
```ts
|
|
130
|
-
await api.run(wf); // high-level (Workflow)
|
|
131
|
-
await api.runWorkflow(wf); // alias
|
|
132
|
-
new CallWrapper(api, builder)
|
|
133
|
-
.onFinished(o => console.log(o.images?.images?.length))
|
|
134
|
-
.run(); // builder execution
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
### Declaring Outputs
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
wf.output('alias:NodeId');
|
|
141
|
-
wf.output('alias','NodeId');
|
|
142
|
-
wf.output('NodeId'); // key = id
|
|
143
|
-
// none declared -> auto collect SaveImage nodes
|
|
144
|
-
```
|
|
145
|
-
|
|
146
|
-
### Events (WorkflowJob)
|
|
147
|
-
|
|
148
|
-
```txt
|
|
149
|
-
pending -> start -> progress / progress_pct / preview -> output* -> finished (or failed)
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
| Event | Notes |
|
|
153
|
-
| ----- | ----- |
|
|
154
|
-
| pending | accepted into queue |
|
|
155
|
-
| start | first execution step began |
|
|
156
|
-
| progress_pct | integer 0-100 (deduped) |
|
|
157
|
-
| preview | live frame (Blob) |
|
|
158
|
-
| output | a declared / auto-detected node produced data |
|
|
159
|
-
| finished | all requested nodes resolved |
|
|
160
|
-
| failed | execution error / interruption |
|
|
161
|
-
|
|
162
|
-
### Seed Handling
|
|
163
|
-
|
|
164
|
-
```ts
|
|
165
|
-
// -1 sentinel => randomized & reported under _autoSeeds
|
|
166
|
-
wf.batchInputs('SAMPLER', { seed: -1 });
|
|
167
|
-
```
|
|
168
|
-
|
|
169
|
-
### Type Extraction
|
|
170
|
-
|
|
171
|
-
```ts
|
|
172
|
-
type Result = ReturnType<typeof wf.typedResult>;
|
|
173
|
-
```
|
|
174
|
-
|
|
175
|
-
### Pool Quick Start
|
|
176
|
-
|
|
177
|
-
```ts
|
|
178
|
-
const pool = new ComfyPool([
|
|
179
|
-
new ComfyApi('http://localhost:8188'),
|
|
180
|
-
new ComfyApi('http://localhost:8189')
|
|
181
|
-
]);
|
|
182
|
-
const job2 = await pool.clients[0].run(wf, { pool });
|
|
183
|
-
await job2.done();
|
|
184
|
-
```
|
|
185
|
-
|
|
186
|
-
### Selecting Workflow vs PromptBuilder
|
|
187
|
-
|
|
188
|
-
Use Workflow for 90% of: tweak existing JSON, few parameter edits, rapid prototyping. Use PromptBuilder when you must programmatically assemble / rewire node graphs or need validation utilities pre-submit.
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
### High‑Level Workflow API (Experimental) – Quick Intro
|
|
193
|
-
|
|
194
|
-
Skip manual `PromptBuilder` wiring with `Workflow` when you just want to tweak an existing graph JSON and run it. A full step‑by‑step tutorial is below; here is the 10‑second overview:
|
|
195
|
-
|
|
196
|
-
- Load JSON – `Workflow.from(json)`
|
|
197
|
-
- Mutate values – `.set('nodeId.inputs.field', value)`
|
|
198
|
-
- Declare outputs – `.output('alias:nodeId')` (or just `.output('nodeId')`; falls back to auto‑detecting `SaveImage` nodes)
|
|
199
|
-
- Execute – `await api.run(wf)` (or `api.runWorkflow(wf)` alias) returning a `WorkflowJob` (Promise‑like)
|
|
200
|
-
- Subscribe to events – `progress`, `progress_pct`, `preview`, `output`, `finished`, `failed`
|
|
201
|
-
- Await final object – either `await job` or `await job.done()`
|
|
202
|
-
|
|
203
|
-
See the dedicated tutorial section for a narrated example and option details.
|
|
204
|
-
|
|
205
|
-
### Recent Enhancements (Ergonomics & Typing)
|
|
206
|
-
|
|
207
|
-
The `Workflow` surface has gained several quality‑of‑life helpers and **progressive typing** features. All are additive (no breaking changes) and optional—fall back to raw `set()` / `output()` styles whenever you prefer.
|
|
208
|
-
|
|
209
|
-
| Feature | Purpose | Example | Type Effect |
|
|
210
|
-
| ------- | ------- | ------- | ----------- |
|
|
211
|
-
| `wf.input(nodeId, inputName, value)` | Concise single input mutation (vs dotted path) | `wf.input('SAMPLER','steps',30)` | none (runtime sugar) |
|
|
212
|
-
| `wf.batchInputs(nodeId, { ... })` | Set multiple inputs on one node | `wf.batchInputs('SAMPLER',{ steps:30, cfg:5 })` | none |
|
|
213
|
-
| `wf.batchInputs({ NODEA:{...} })` | Multi‑node batch mutation | `wf.batchInputs({ SAMPLER:{ cfg:6 } })` | none |
|
|
214
|
-
| `Workflow.fromAugmented(json)` | Soft autocomplete on sampler / scheduler but still accepts future values | `Workflow.fromAugmented(base)` | narrows fields to union \| (string & {}) |
|
|
215
|
-
| Typed output inference | `.output('alias:ID')` accumulates object keys | `wf.output('images:SAVE_IMAGE')` | widens result shape with `images` key |
|
|
216
|
-
| Per‑node output shape hints | Heuristic shapes for `SaveImage*`, `KSampler` | `result.images.images` | structural hints for nested fields |
|
|
217
|
-
| Multiple output syntaxes | Choose preferred style | `'alias:NodeId'` / `('alias','NodeId')` / `'NodeId'` | identical effect |
|
|
218
|
-
| `wf.typedResult()` | Get IDE type of final result | `type R = ReturnType<typeof wf.typedResult>` | captures accumulated generic |
|
|
219
|
-
| Auto seed substitution | `seed: -1` randomized before submit | `wf.input('SAMPLER','seed',-1)` | adds `_autoSeeds` map key |
|
|
220
|
-
| Acceptance barrier run | `await api.run(wf)` returns job handle pre-completion | `const job=await api.run(wf)` | result type unchanged |
|
|
221
|
-
|
|
222
|
-
> All typing is structural—no runtime validation. Unknown / future sampler names or new node classes continue to work.
|
|
223
|
-
|
|
224
|
-
#### Input Helpers
|
|
225
|
-
|
|
226
|
-
```ts
|
|
227
|
-
const wf = Workflow.fromAugmented(baseJson)
|
|
228
|
-
.input('LOADER','ckpt_name','model.safetensors')
|
|
229
|
-
.batchInputs('SAMPLER', {
|
|
230
|
-
steps: 30,
|
|
231
|
-
cfg: 4,
|
|
232
|
-
sampler_name: 'euler_ancestral', // autocomplete + accepts future strings
|
|
233
|
-
scheduler: 'karras', // autocomplete + forward compatible
|
|
234
|
-
seed: -1 // -1 -> auto randomized before submit
|
|
235
|
-
})
|
|
236
|
-
.batchInputs({
|
|
237
|
-
CLIP_TEXT_ENCODE_POSITIVE: { text: 'A moody cinematic landscape' },
|
|
238
|
-
LATENT_IMAGE: { width: 896, height: 1152 }
|
|
239
|
-
});
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
### Output Declaration & Typing
|
|
243
|
-
|
|
244
|
-
Each `output()` call accumulates inferred keys:
|
|
245
|
-
|
|
246
|
-
```ts
|
|
247
|
-
const wf2 = Workflow.fromAugmented(baseJson)
|
|
248
|
-
.output('gallery:SAVE_IMAGE') // key 'gallery'
|
|
249
|
-
.output('KSamplerNode') // key 'KSamplerNode'
|
|
250
|
-
.output('thumb','THUMBNAIL_NODE'); // key 'thumb'
|
|
251
|
-
|
|
252
|
-
// Type exploration (IDE only):
|
|
253
|
-
type Wf2Result = ReturnType<typeof wf2.typedResult>;
|
|
254
|
-
// Wf2Result ~ {
|
|
255
|
-
// gallery: { images?: any[] }; // SaveImage heuristic
|
|
256
|
-
// KSamplerNode: { samples?: any }; // KSampler heuristic
|
|
257
|
-
// thumb: any; // THUMBNAIL_NODE class not mapped yet
|
|
258
|
-
// _promptId?: string; _nodes?: string[]; _aliases?: Record<string,string>; _autoSeeds?: Record<string,number>;
|
|
259
|
-
// }
|
|
260
|
-
|
|
261
|
-
const job = await api.run(wf2);
|
|
262
|
-
const final = await job.done();
|
|
263
|
-
final.gallery.images?.forEach(img => console.log(api.ext.file.getPathImage(img)));
|
|
264
|
-
```
|
|
265
|
-
|
|
266
|
-
Supported output forms (all equivalent semantically; choose your style):
|
|
267
|
-
|
|
268
|
-
```ts
|
|
269
|
-
wf.output('alias:NodeId');
|
|
270
|
-
wf.output('alias','NodeId');
|
|
271
|
-
wf.output('NodeId'); // raw key = node id
|
|
272
|
-
```
|
|
273
|
-
|
|
274
|
-
If you declare *no* outputs the SDK still auto‑collects all `SaveImage` nodes.
|
|
275
|
-
|
|
276
|
-
#### Per‑Node Output Shapes (Heuristics)
|
|
277
|
-
|
|
278
|
-
Currently recognized:
|
|
279
|
-
|
|
280
|
-
| class_type match | Inferred shape fragment |
|
|
281
|
-
| ---------------- | ----------------------- |
|
|
282
|
-
| `SaveImage`, `SaveImageAdvanced` | `{ images?: any[] }` |
|
|
283
|
-
| `KSampler` | `{ samples?: any }` |
|
|
284
|
-
|
|
285
|
-
All others are typed as `any` (you still get alias key inference). This table will expand; explicit contributions welcome.
|
|
286
|
-
|
|
287
|
-
#### Combining With Result Metadata
|
|
288
|
-
|
|
289
|
-
The object from `job.done()` (and `runAndWait`) is always the intersection:
|
|
290
|
-
|
|
291
|
-
```ts
|
|
292
|
-
// final result shape (conceptual)
|
|
293
|
-
{ ...yourDeclaredOutputs, _promptId?: string, _nodes?: string[], _aliases?: Record<string,string>, _autoSeeds?: Record<string,number> }
|
|
294
|
-
```
|
|
295
|
-
|
|
296
|
-
#### When to Use `Workflow.fromAugmented`
|
|
297
|
-
|
|
298
|
-
Use it when you want IDE suggestions for sampler / scheduler *without* losing forward compatibility. The widened types are `TSamplerName | (string & {})` and `TSchedulerName | (string & {})` internally—any new upstream values are valid.
|
|
299
|
-
|
|
300
|
-
#### Extracting a Stable Result Type
|
|
301
|
-
|
|
302
|
-
If you want to export a type for downstream modules:
|
|
303
|
-
|
|
304
|
-
```ts
|
|
305
|
-
export type MyGenerationResult = ReturnType<typeof wf.typedResult>;
|
|
306
|
-
```
|
|
307
|
-
|
|
308
|
-
This stays accurate as long as all `output()` calls run before the type is captured.
|
|
309
|
-
|
|
310
|
-
#### Limitations & Future Work
|
|
311
|
-
|
|
312
|
-
- Output shapes are heuristic; not all node classes annotated yet.
|
|
313
|
-
- Dynamic node creation using non‑strict `input()` cannot update the generic shape (TypeScript limitation). You can re‑wrap with `Workflow.fromAugmented` after structural edits if needed.
|
|
314
|
-
- Potential future API: `wf.withOutputShapes({ MyCustomNode: { customField: string } })` for user overrides.
|
|
315
|
-
|
|
316
|
-
---
|
|
317
|
-
|
|
318
|
-
## Choosing: Workflow vs PromptBuilder
|
|
319
|
-
|
|
320
|
-
| Criterion | Prefer Workflow | Prefer PromptBuilder |
|
|
321
|
-
| --------- | --------------- | -------------------- |
|
|
322
|
-
| Starting point | You already have a working JSON graph | You need to assemble nodes programmatically |
|
|
323
|
-
| Change pattern | Tweak a handful of numeric/text inputs | Add/remove/re‑wire nodes dynamically |
|
|
324
|
-
| Output declaration | Simple image node aliases | Complex multi‑node mapping / conditional outputs |
|
|
325
|
-
| Validation needs | Light (auto collect `SaveImage`) | Strong: explicit mapping + cycle checks |
|
|
326
|
-
| Type ergonomics | Progressive result typing via `.output()` + heuristics | Fully explicit generic parameters on construction |
|
|
327
|
-
| Autocomplete | Sampler / scheduler (augmented mode) | Input & output alias keys / builder fluency |
|
|
328
|
-
| Serialization | Not needed / reuse same base JSON | Need to persist & replay builder state |
|
|
329
|
-
| Scheduling | Direct `api.run(wf)` | Usually wrapped in `CallWrapper` (or converted later) |
|
|
330
|
-
| Learning curve | Minimal (few fluent methods) | Slightly higher (need to map inputs / outputs) |
|
|
331
|
-
| Migration path | Can drop down later to builder if requirements grow | Can export to JSON & wrap with `Workflow.from(...)` for simpler tweaking |
|
|
332
|
-
|
|
333
|
-
Rule of thumb: start with `Workflow`. Move to `PromptBuilder` when you feel friction needing structural graph edits or stronger pre‑submit validation.
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
Pool variant (experimental):
|
|
337
|
-
|
|
338
|
-
```ts
|
|
339
|
-
import { ComfyApi, ComfyPool, Workflow } from 'comfyui-node';
|
|
340
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
341
|
-
|
|
342
|
-
const pool = new ComfyPool([
|
|
343
|
-
new ComfyApi('http://localhost:8188'),
|
|
344
|
-
new ComfyApi('http://localhost:8189')
|
|
345
|
-
]);
|
|
346
40
|
|
|
347
41
|
const wf = Workflow.from(BaseWorkflow)
|
|
348
|
-
.set('6.inputs.text', 'A
|
|
349
|
-
.output('9');
|
|
350
|
-
|
|
351
|
-
// Run using one specific API (pool provided for scheduling context)
|
|
352
|
-
const api2 = pool.clients[0];
|
|
353
|
-
const job2 = await api2.run(wf, { pool });
|
|
354
|
-
await job2.done();
|
|
355
|
-
```
|
|
42
|
+
.set('6.inputs.text', 'A dramatic cinematic landscape')
|
|
43
|
+
.output('images:9');
|
|
356
44
|
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
- Experimental surface: event names / helpers may refine before a stable minor release.
|
|
360
|
-
|
|
361
|
-
### PromptBuilder Validation & Serialization
|
|
362
|
-
|
|
363
|
-
`PromptBuilder` now includes optional robustness helpers you can invoke before submission:
|
|
364
|
-
|
|
365
|
-
```ts
|
|
366
|
-
builder
|
|
367
|
-
.validateOutputMappings() // Ensures every declared output key maps to an existing node id
|
|
368
|
-
.validateNoImmediateCycles(); // Guards against a node directly referencing itself in its input tuple
|
|
369
|
-
|
|
370
|
-
// Serialize to persist / send over IPC
|
|
371
|
-
const saved = builder.toJSON();
|
|
372
|
-
// Later restore (types must line up with original generic parameters when casting)
|
|
373
|
-
const restored = PromptBuilder.fromJSON(saved);
|
|
374
|
-
```
|
|
375
|
-
|
|
376
|
-
If validation fails an `Error` is thrown with a concise list of offending mappings, e.g.
|
|
377
|
-
|
|
378
|
-
```text
|
|
379
|
-
Error: Unmapped or missing output nodes: images:UNMAPPED
|
|
380
|
-
```
|
|
381
|
-
|
|
382
|
-
Cycle detection currently targets immediate self‑cycles (a node whose input tuple references itself). Broader multi‑hop cycle detection can be layered later without breaking this API.
|
|
383
|
-
|
|
384
|
-
### Common Validation Patterns
|
|
385
|
-
|
|
386
|
-
```ts
|
|
387
|
-
function safeBuild(wf: any) {
|
|
388
|
-
return new PromptBuilder(wf,["positive","seed"],["images"])
|
|
389
|
-
.setInputNode("positive","6.inputs.text")
|
|
390
|
-
.setInputNode("seed","3.inputs.seed")
|
|
391
|
-
.setOutputNode("images","9")
|
|
392
|
-
.input("positive","Hello world")
|
|
393
|
-
.input("seed", seed())
|
|
394
|
-
.validateOutputMappings()
|
|
395
|
-
.validateNoImmediateCycles();
|
|
396
|
-
}
|
|
397
|
-
```
|
|
398
|
-
|
|
399
|
-
## Result Object Anatomy
|
|
400
|
-
|
|
401
|
-
All high‑level executions (`api.run(wf)` / `runWorkflow` / `runAndWait`) ultimately resolve to an object merging:
|
|
402
|
-
|
|
403
|
-
1. Declared / inferred output aliases (each key value is the raw node output JSON for that node)
|
|
404
|
-
2. Heuristic shape hints (currently only augmenting `SaveImage*` & `KSampler` nodes with friendly nested fields)
|
|
405
|
-
3. Metadata fields: `_promptId`, `_nodes`, `_aliases`, `_autoSeeds`
|
|
406
|
-
|
|
407
|
-
Conceptual shape:
|
|
408
|
-
|
|
409
|
-
```ts
|
|
410
|
-
type WorkflowResult = {
|
|
411
|
-
// Your keys:
|
|
412
|
-
[aliasOrNodeId: string]: any; // each node's output blob (heuristically narrowed)
|
|
413
|
-
// Metadata:
|
|
414
|
-
_promptId?: string;
|
|
415
|
-
_nodes?: string[]; // collected node ids
|
|
416
|
-
_aliases?: Record<string,string>; // nodeId -> alias
|
|
417
|
-
_autoSeeds?: Record<string,number>; // nodeId -> randomized seed (when -1 sentinel used)
|
|
418
|
-
};
|
|
419
|
-
```
|
|
420
|
-
|
|
421
|
-
Example with heuristics:
|
|
422
|
-
|
|
423
|
-
```ts
|
|
424
|
-
const wf = Workflow.fromAugmented(json)
|
|
425
|
-
.output('gallery:SAVE_IMAGE')
|
|
426
|
-
.output('sampler:KSampler');
|
|
427
|
-
type R = ReturnType<typeof wf.typedResult>; // => { gallery: { images?: any[] }; sampler: { samples?: any }; _promptId?: ... }
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
Heuristics are intentionally shallow – they provide just enough structure for IDE discovery without locking you into specific upstream node versions. Missing shape? You still get the alias key with `any` type; open a PR to extend the mapping.
|
|
431
|
-
|
|
432
|
-
Access patterns:
|
|
45
|
+
const job = await api.run(wf, { autoDestroy: true });
|
|
46
|
+
job.on('progress_pct', p => console.log(`${p}%`));
|
|
433
47
|
|
|
434
|
-
|
|
435
|
-
const
|
|
436
|
-
job.on('output', id => console.log('node completed', id));
|
|
437
|
-
const res = await job.done();
|
|
438
|
-
console.log(res._promptId, Object.keys(res));
|
|
439
|
-
for (const img of (res.gallery?.images || [])) {
|
|
48
|
+
const result = await job.done();
|
|
49
|
+
for (const img of (result.images?.images || [])) {
|
|
440
50
|
console.log(api.ext.file.getPathImage(img));
|
|
441
51
|
}
|
|
442
52
|
```
|
|
443
53
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
```ts
|
|
447
|
-
export type GenerationResult = ReturnType<typeof wf.typedResult>;
|
|
448
|
-
```
|
|
449
|
-
|
|
450
|
-
Changing outputs later? Re‑generate the type after adding the new `.output()` call.
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
## Multi-Instance Pool
|
|
454
|
-
|
|
455
|
-
`ComfyPool` provides weighted job scheduling & automatic client selection across multiple ComfyUI instances. It is transport‑agnostic and only relies on the standard `ComfyApi` event surface.
|
|
456
|
-
|
|
457
|
-
### Modes
|
|
458
|
-
|
|
459
|
-
| Mode | Enum | Behavior | When to use |
|
|
460
|
-
| ---- | ---- | -------- | ----------- |
|
|
461
|
-
| Pick zero queue | `EQueueMode.PICK_ZERO` (default) | Choose any online client whose reported `queue_remaining` is 0 (prefers idle machines). Locks a client until it emits an execution event. | Co‑existence with the ComfyUI web UI where queue spikes are common. |
|
|
462
|
-
| Lowest queue | `EQueueMode.PICK_LOWEST` | Choose the online client with the smallest `queue_remaining` (may still be busy). | High throughput batch ingestion; keeps all nodes saturated. |
|
|
463
|
-
| Round‑robin | `EQueueMode.PICK_ROUTINE` | Simple rotation through available online clients irrespective of queue depth. | Latency balancing; predictable distribution. |
|
|
464
|
-
|
|
465
|
-
### Basic Example
|
|
466
|
-
|
|
467
|
-
```ts
|
|
468
|
-
import { ComfyApi, ComfyPool, EQueueMode, CallWrapper, PromptBuilder, seed } from "comfyui-node";
|
|
469
|
-
import ExampleTxt2ImgWorkflow from "./example-txt2img-workflow.json";
|
|
470
|
-
// ... pool basic example content (see earlier dedicated Workflow section for high-level abstraction)
|
|
471
|
-
```
|
|
472
|
-
|
|
473
|
-
Pool variant (experimental):
|
|
474
|
-
|
|
475
|
-
```ts
|
|
476
|
-
import { ComfyApi, ComfyPool, Workflow } from 'comfyui-node';
|
|
477
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
478
|
-
|
|
479
|
-
const pool = new ComfyPool([
|
|
480
|
-
new ComfyApi('http://localhost:8188'),
|
|
481
|
-
new ComfyApi('http://localhost:8189')
|
|
482
|
-
]);
|
|
483
|
-
|
|
484
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
485
|
-
.set('6.inputs.text', 'A macro photo of a dewdrop on a leaf')
|
|
486
|
-
.output('9');
|
|
487
|
-
|
|
488
|
-
// Run using one specific API (pool provided for scheduling context)
|
|
489
|
-
const api = pool.clients[0];
|
|
490
|
-
const job = await api.run(wf, { pool });
|
|
491
|
-
await job.done();
|
|
492
|
-
```
|
|
493
|
-
|
|
494
|
-
Notes:
|
|
495
|
-
|
|
496
|
-
- Experimental surface: event names / helpers may refine before a stable minor release.
|
|
497
|
-
- Falls back to `SaveImage` detection if you omit `output(...)`.
|
|
498
|
-
- For advanced validation, serialization, or complex key mapping prefer `PromptBuilder`.
|
|
499
|
-
|
|
500
|
-
---
|
|
501
|
-
|
|
502
|
-
## High‑Level Workflow Tutorial (New Users of This SDK)
|
|
503
|
-
|
|
504
|
-
Audience: You already understand ComfyUI graphs & node JSON, but are new to this TypeScript SDK.
|
|
505
|
-
|
|
506
|
-
Goals after this section you can: (a) clone a base workflow, (b) modify its parameters, (c) name your desired outputs, (d) track progress & previews, and (e) retrieve final image paths – with minimal boilerplate.
|
|
507
|
-
|
|
508
|
-
### 1. Prepare a Base Workflow JSON
|
|
509
|
-
|
|
510
|
-
Export or copy a working ComfyUI txt2img graph (e.g. the one in `test/example-txt2img-workflow.json`). Ensure you know the node ID of the final `SaveImage` (here we assume `9`).
|
|
511
|
-
|
|
512
|
-
### 2. Initialize the API
|
|
513
|
-
|
|
514
|
-
`api.ready()` handles connection & feature probing. It is idempotent (can be safely called multiple times). You can override the host using `COMFY_HOST`.
|
|
515
|
-
|
|
516
|
-
### 3. Mutate Parameters & Declare Outputs
|
|
517
|
-
|
|
518
|
-
Use `.set('<nodeId>.inputs.<field>', value)` to change values. Call `.output('alias:nodeId')` to collect that node's result under a friendly key (`alias`). If you omit alias (`.output('9')`) the key will be the node ID. If you omit all outputs the SDK tries to collect every `SaveImage` node automatically.
|
|
519
|
-
|
|
520
|
-
Auto seed: If any node has an input field literally named `seed` with value `-1`, the SDK will replace it with a random 32‑bit integer before submission and expose the mapping in the final result under `_autoSeeds` (object keyed by node id). This lets you keep templates with `-1` sentinel for “random every run”.
|
|
521
|
-
|
|
522
|
-
### 4. Run & Observe Progress
|
|
523
|
-
|
|
524
|
-
`api.run(workflow, { autoDestroy: true })` executes and (optionally) closes underlying sockets once finished/failed so the process can exit without manual cleanup. The returned `WorkflowJob` is an EventEmitter‑like object AND a Promise: `await job` works just like `await job.done()`.
|
|
525
|
-
|
|
526
|
-
### 5. Extract Image Paths
|
|
527
|
-
|
|
528
|
-
Final structure includes your alias keys plus `_promptId`, `_nodes` and `_aliases` metadata. Use `api.ext.file.getPathImage(imageInfo)` to build a fetchable URL.
|
|
529
|
-
|
|
530
|
-
### Complete Example
|
|
531
|
-
|
|
532
|
-
```ts
|
|
533
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
534
|
-
import BaseWorkflow from './example-txt2img-workflow.json';
|
|
535
|
-
|
|
536
|
-
async function main() {
|
|
537
|
-
const api = await new ComfyApi(process.env.COMFY_HOST || 'http://127.0.0.1:8188').ready();
|
|
538
|
-
|
|
539
|
-
const wf = Workflow.from(BaseWorkflow)
|
|
540
|
-
.set('4.inputs.ckpt_name', process.env.COMFY_MODEL || 'SDXL/realvisxlV40_v40LightningBakedvae.safetensors')
|
|
541
|
-
.set('6.inputs.text', 'A dramatic cinematic landscape, volumetric light')
|
|
542
|
-
.set('7.inputs.text', 'text, watermark')
|
|
543
|
-
.set('3.inputs.seed', Math.floor(Math.random() * 10_000_000))
|
|
544
|
-
.set('3.inputs.steps', 8)
|
|
545
|
-
.set('3.inputs.cfg', 2)
|
|
546
|
-
.set('3.inputs.sampler_name', 'dpmpp_sde')
|
|
547
|
-
.set('3.inputs.scheduler', 'sgm_uniform')
|
|
548
|
-
.set('5.inputs.width', 1024)
|
|
549
|
-
.set('5.inputs.height', 1024)
|
|
550
|
-
.output('images:9'); // alias 'images' -> node 9
|
|
551
|
-
|
|
552
|
-
const job = await api.runWorkflow(wf, { autoDestroy: true });
|
|
553
|
-
|
|
554
|
-
job
|
|
555
|
-
.on('pending', id => console.log('[queue]', id))
|
|
556
|
-
.on('start', id => console.log('[start]', id))
|
|
557
|
-
.on('progress_pct', pct => process.stdout.write(`\rprogress ${pct}% `))
|
|
558
|
-
.on('preview', blob => console.log('\npreview frame bytes=', blob.size))
|
|
559
|
-
.on('failed', err => console.error('\nerror', err));
|
|
560
|
-
|
|
561
|
-
const result = await job; // or await job.done();
|
|
562
|
-
console.log('\nPrompt ID:', result._promptId);
|
|
563
|
-
for (const img of (result.images?.images || [])) {
|
|
564
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
|
|
568
|
-
main().catch(e => { console.error(e); process.exit(1); });
|
|
569
|
-
```
|
|
570
|
-
|
|
571
|
-
### Key Options Recap
|
|
572
|
-
|
|
573
|
-
| Option | Where | Purpose |
|
|
574
|
-
| ------ | ----- | ------- |
|
|
575
|
-
| `autoDestroy` | `api.run(...)` | Automatically `destroy()` the client on finish/fail |
|
|
576
|
-
| `includeOutputs` | `api.run(wf,{ includeOutputs:['9'] })` | Force extra node IDs (in addition to `.output(...)`) |
|
|
577
|
-
| `pool` | (advanced) | Execute through a `ComfyPool` for multi‑instance scheduling |
|
|
578
|
-
|
|
579
|
-
### Event Cheat Sheet (WorkflowJob)
|
|
54
|
+
## Documentation
|
|
580
55
|
|
|
581
|
-
|
|
582
|
-
| ----- | ------- | ----------- |
|
|
583
|
-
| `pending` | promptId | Enqueued, waiting to start |
|
|
584
|
-
| `start` | promptId | Execution began |
|
|
585
|
-
| `progress` | raw `{ value,max }` | Low‑level progress data |
|
|
586
|
-
| `progress_pct` | number (0‑100) | Deduped integer percentage (fires on change) |
|
|
587
|
-
| `preview` | `Blob` | Live image preview frame |
|
|
588
|
-
| `output` | nodeId | Partial node output arrived |
|
|
589
|
-
| `finished` | final object | All requested outputs resolved |
|
|
590
|
-
| `failed` | `Error` | Execution failed / interrupted |
|
|
56
|
+
### Getting Started
|
|
591
57
|
|
|
592
|
-
|
|
58
|
+
- **[Getting Started Guide](./docs/getting-started.md)** – Installation, quick start, core concepts, cheat sheet
|
|
59
|
+
- **[Workflow Guide](./docs/workflow-guide.md)** – Complete high-level Workflow API tutorial with progressive typing
|
|
60
|
+
- **[PromptBuilder Guide](./docs/prompt-builder.md)** – Lower-level graph construction, validation, serialization
|
|
593
61
|
|
|
594
|
-
|
|
62
|
+
### Multi-Instance Pooling
|
|
595
63
|
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
job
|
|
599
|
-
.on('progress_pct', pct => console.log('progress', pct))
|
|
600
|
-
.on('preview', blob => console.log('preview frame', blob.size));
|
|
64
|
+
- **[WorkflowPool Documentation](./docs/workflow-pool.md)** – Production-ready pooling with health checks (v1.4.1+)
|
|
65
|
+
- **[Connection Stability Guide](./docs/websocket-idle-issue.md)** – WebSocket health check implementation details
|
|
601
66
|
|
|
602
|
-
|
|
603
|
-
```
|
|
67
|
+
### Advanced Features
|
|
604
68
|
|
|
605
|
-
|
|
69
|
+
- **[Advanced Usage](./docs/advanced-usage.md)** – Authentication, events, preview metadata, API nodes, image attachments
|
|
70
|
+
- **[API Features](./docs/api-features.md)** – Modular `api.ext.*` namespaces (queue, file, system, etc.)
|
|
606
71
|
|
|
607
|
-
|
|
72
|
+
### Help & Migration
|
|
608
73
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
| `_promptId` | Server prompt id assigned |
|
|
612
|
-
| `_nodes` | Array of collected node ids |
|
|
613
|
-
| `_aliases` | Mapping nodeId -> alias (where provided) |
|
|
614
|
-
| `_autoSeeds` | Mapping nodeId -> randomized seed (only when you used -1 sentinel) |
|
|
74
|
+
- **[Troubleshooting](./docs/troubleshooting.md)** – Common issues, error types, testing, diagnostics
|
|
75
|
+
- **[Migration Guide](./docs/migration-guide.md)** – Upgrading from <1.0 to 1.0+ with complete API mappings
|
|
615
76
|
|
|
616
|
-
|
|
77
|
+
## Key Concepts
|
|
617
78
|
|
|
618
|
-
###
|
|
79
|
+
### Workflow vs PromptBuilder
|
|
619
80
|
|
|
620
|
-
|
|
81
|
+
**Use `Workflow`** for tweaking existing JSON workflows:
|
|
621
82
|
|
|
622
83
|
```ts
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
]);
|
|
84
|
+
const wf = Workflow.from(baseJson)
|
|
85
|
+
.set('3.inputs.steps', 20)
|
|
86
|
+
.input('SAMPLER', 'cfg', 4)
|
|
87
|
+
.output('images:9');
|
|
628
88
|
```
|
|
629
89
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
Target or avoid specific client IDs:
|
|
90
|
+
**Use `PromptBuilder`** for programmatic graph construction:
|
|
633
91
|
|
|
634
92
|
```ts
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
### Failover & Retries
|
|
640
|
-
|
|
641
|
-
`run()` attempts transparent failover when a job throws. It excludes the failing client and retries another (up to `maxRetries`).
|
|
642
|
-
|
|
643
|
-
```ts
|
|
644
|
-
await pool.run(doGenerate, undefined, undefined, { maxRetries: 3, retryDelay: 1500 });
|
|
645
|
-
```
|
|
646
|
-
|
|
647
|
-
Disable failover:
|
|
648
|
-
|
|
649
|
-
```ts
|
|
650
|
-
await pool.run(doGenerate, undefined, undefined, { enableFailover: false });
|
|
93
|
+
const builder = new PromptBuilder(base, ['positive', 'seed'], ['images'])
|
|
94
|
+
.setInputNode('positive', '6.inputs.text')
|
|
95
|
+
.validateOutputMappings();
|
|
651
96
|
```
|
|
652
97
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
`ComfyPool` is an `EventTarget` emitting high‑level orchestration signals:
|
|
656
|
-
|
|
657
|
-
| Event | Detail Payload | When |
|
|
658
|
-
| ----- | -------------- | ---- |
|
|
659
|
-
| `init` | – | All clients added & initial processing pass done |
|
|
660
|
-
| `added` / `removed` | `{ client, clientIdx }` | Client lifecycle changes |
|
|
661
|
-
| `ready` | `{ client, clientIdx }` | Individual client fully initialized |
|
|
662
|
-
| `executing` / `executed` | `{ client, clientIdx }` | A job starts / finishes on a client |
|
|
663
|
-
| `execution_error` | `{ client, clientIdx, error, willRetry, attempt, maxRetries }` | A job threw; may retry |
|
|
664
|
-
| `execution_interrupted` | `{ client, clientIdx }` | Underlying API emitted interruption |
|
|
665
|
-
| `connected` / `disconnected` / `reconnected` | `{ client, clientIdx }` | WebSocket state relayed from `ComfyApi` |
|
|
666
|
-
| `terminal` | `{ clientIdx, line }` | Terminal log pass‑through |
|
|
667
|
-
| `system_monitor` | `{ clientIdx, data }` | Crystools monitor snapshot (when supported) |
|
|
668
|
-
| `add_job` | `{ jobIdx, weight }` | Job inserted into internal queue |
|
|
669
|
-
| `change_mode` | `{ mode }` | Queue selection mode altered |
|
|
670
|
-
| `have_job` | `{ client, remain }` | A client reports pending queue > 0 |
|
|
671
|
-
| `idle` | `{ client }` | A previously busy client reports queue 0 |
|
|
98
|
+
See [comparison guide](./docs/workflow-guide.md#choosing-workflow-vs-promptbuilder) for details.
|
|
672
99
|
|
|
673
|
-
###
|
|
100
|
+
### WorkflowPool (v1.4.1+)
|
|
674
101
|
|
|
675
|
-
|
|
102
|
+
Production-ready multi-instance scheduling with automatic health checks:
|
|
676
103
|
|
|
677
104
|
```ts
|
|
678
|
-
|
|
679
|
-
```
|
|
680
|
-
|
|
681
|
-
### Combined Orchestration Example (Auth + Pool + Validation + Retry)
|
|
682
|
-
|
|
683
|
-
```ts
|
|
684
|
-
import { ComfyApi, ComfyPool, EQueueMode, PromptBuilder, CallWrapper, seed } from "comfyui-node";
|
|
105
|
+
import { WorkflowPool, MemoryQueueAdapter } from "comfyui-node";
|
|
685
106
|
|
|
686
|
-
const pool = new
|
|
687
|
-
new ComfyApi(
|
|
688
|
-
new ComfyApi(
|
|
689
|
-
], {
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
const wf = /* load / clone a base workflow JSON */ {} as any;
|
|
693
|
-
const builder = new PromptBuilder(wf,["positive","seed"],["images"])
|
|
694
|
-
.setInputNode("positive","6.inputs.text")
|
|
695
|
-
.setInputNode("seed","3.inputs.seed")
|
|
696
|
-
.setOutputNode("images","9")
|
|
697
|
-
.input("positive", text)
|
|
698
|
-
.input("seed", seed())
|
|
699
|
-
.validateOutputMappings();
|
|
700
|
-
|
|
701
|
-
return await new Promise<string[]>((resolve, reject) => {
|
|
702
|
-
new CallWrapper(api, builder)
|
|
703
|
-
.onFinished(d => resolve((d.images?.images||[]).map((img:any)=> api.ext.file.getPathImage(img))))
|
|
704
|
-
.onFailed(err => reject(err))
|
|
705
|
-
.run();
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
// Weighted submission with retry semantics
|
|
710
|
-
const tasks = ["cat portrait","cyberpunk city","forest at dawn"].map(txt => (api: ComfyApi) => generate(api, txt));
|
|
711
|
-
const results = await Promise.all(tasks.map((fn,i)=> pool.run(fn, i))); // lower weight = earlier
|
|
712
|
-
console.log(results.flat());
|
|
713
|
-
pool.destroy();
|
|
714
|
-
```
|
|
715
|
-
|
|
716
|
-
### Choosing a Mode
|
|
717
|
-
|
|
718
|
-
| Goal | Suggested Mode |
|
|
719
|
-
| ---- | -------------- |
|
|
720
|
-
| Minimize latency spikes | `PICK_ZERO` |
|
|
721
|
-
| Maximize throughput | `PICK_LOWEST` |
|
|
722
|
-
| Deterministic striping | `PICK_ROUTINE` |
|
|
107
|
+
const pool = new WorkflowPool([
|
|
108
|
+
new ComfyApi("http://localhost:8188"),
|
|
109
|
+
new ComfyApi("http://localhost:8189")
|
|
110
|
+
], {
|
|
111
|
+
healthCheckIntervalMs: 30000 // keeps connections alive
|
|
112
|
+
});
|
|
723
113
|
|
|
724
|
-
|
|
114
|
+
pool.on("job:progress", ev => console.log(ev.detail.jobId, ev.detail.progress));
|
|
725
115
|
|
|
726
|
-
|
|
727
|
-
pool.changeMode(EQueueMode.PICK_LOWEST);
|
|
116
|
+
const jobId = await pool.enqueue(workflow, { priority: 10 });
|
|
728
117
|
```
|
|
729
118
|
|
|
730
|
-
|
|
119
|
+
**New in v1.4.1:** Automatic health checks prevent idle connection timeouts. See [WorkflowPool docs](./docs/workflow-pool.md).
|
|
731
120
|
|
|
732
|
-
|
|
121
|
+
## What's New in v1.4.1
|
|
733
122
|
|
|
734
|
-
|
|
123
|
+
- **Idle connection stability** – Automatic health checks keep WebSocket connections alive
|
|
124
|
+
- **Increased default timeout** – WebSocket inactivity timeout raised from 10s to 60s
|
|
125
|
+
- **Configurable health checks** – `healthCheckIntervalMs` option (default 30s, set to 0 to disable)
|
|
126
|
+
- **Better DX** – Comprehensive JSDoc comments and exported types for all pool options
|
|
735
127
|
|
|
736
|
-
|
|
128
|
+
See [CHANGELOG.md](./CHANGELOG.md) for complete release notes.
|
|
737
129
|
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
- Global circuit breaker (temporarily exclude flapping client)
|
|
741
|
-
- Adaptive weight assignment based on rolling execution duration
|
|
742
|
-
- Pluggable selection strategies via user callback
|
|
130
|
+
## Examples
|
|
743
131
|
|
|
744
|
-
|
|
132
|
+
Check the `scripts/` directory for comprehensive examples:
|
|
745
133
|
|
|
746
|
-
|
|
134
|
+
- **Basic workflows:** `workflow-tutorial-basic.ts`, `test-simple-txt2img.ts`
|
|
135
|
+
- **Image editing:** `qwen-image-edit-demo.ts`, `qwen-image-edit-queue.ts`
|
|
136
|
+
- **Pooling:** `workflow-pool-demo.ts`, `workflow-pool-debug.ts`
|
|
137
|
+
- **Node bypass:** `demo-node-bypass.ts`, `demo-workflow-bypass.ts`
|
|
138
|
+
- **API nodes:** `api-node-image-edit.ts` (Comfy.org paid nodes)
|
|
139
|
+
- **Image loading:** `image-loading-demo.ts`
|
|
747
140
|
|
|
748
|
-
|
|
749
|
-
import { ComfyApi, BasicCredentials, BearerTokenCredentials, CustomCredentials } from "comfyui-node";
|
|
141
|
+
Live demo: `demos/recursive-edit/` – recursive image editing server + web client.
|
|
750
142
|
|
|
751
|
-
|
|
752
|
-
const bearer = new ComfyApi("http://localhost:8189","id2", { credentials: { type: "bearer_token", token: "token" } as BearerTokenCredentials }).init();
|
|
753
|
-
const custom = new ComfyApi("http://localhost:8189","id3", { credentials: { type: "custom", headers: { "X-Api-Key": "abc" } } as CustomCredentials }).init();
|
|
754
|
-
```
|
|
143
|
+
## API Reference
|
|
755
144
|
|
|
756
|
-
|
|
145
|
+
### ComfyApi Client
|
|
757
146
|
|
|
758
147
|
```ts
|
|
759
|
-
|
|
760
|
-
|
|
148
|
+
const api = new ComfyApi('http://127.0.0.1:8188', 'optional-id', {
|
|
149
|
+
credentials: { type: 'basic', username: 'user', password: 'pass' },
|
|
150
|
+
wsTimeout: 60000,
|
|
151
|
+
comfyOrgApiKey: process.env.COMFY_ORG_API_KEY,
|
|
152
|
+
debug: true
|
|
153
|
+
});
|
|
761
154
|
|
|
762
|
-
|
|
155
|
+
await api.ready(); // Connection + feature probing
|
|
763
156
|
```
|
|
764
157
|
|
|
765
|
-
|
|
158
|
+
### Modular Features (`api.ext`)
|
|
766
159
|
|
|
767
160
|
```ts
|
|
768
|
-
await api.waitForReady();
|
|
769
161
|
await api.ext.queue.queuePrompt(null, workflow);
|
|
162
|
+
await api.ext.queue.interrupt();
|
|
770
163
|
const stats = await api.ext.system.getSystemStats();
|
|
771
164
|
const checkpoints = await api.ext.node.getCheckpoints();
|
|
772
|
-
|
|
773
|
-
const
|
|
774
|
-
```
|
|
775
|
-
|
|
776
|
-
| Namespace | Responsibility |
|
|
777
|
-
| --------- | -------------- |
|
|
778
|
-
| `queue` | Prompt submission, append & interrupt |
|
|
779
|
-
| `history` | Execution history retrieval |
|
|
780
|
-
| `system` | System stats & memory free |
|
|
781
|
-
| `node` | Node defs + sampler / checkpoint / lora helpers |
|
|
782
|
-
| `user` | User & settings CRUD |
|
|
783
|
-
| `file` | Uploads, image helpers, user data file ops |
|
|
784
|
-
| `model` | Experimental model browsing & previews |
|
|
785
|
-
| `terminal` | Terminal logs & subscription toggle |
|
|
786
|
-
| `misc` | Extensions list, embeddings (new + fallback) |
|
|
787
|
-
| `manager` | ComfyUI Manager extension integration |
|
|
788
|
-
| `monitor` | Crystools monitor events & snapshot |
|
|
789
|
-
| `featureFlags` | Server capabilities (`/features`) |
|
|
790
|
-
|
|
791
|
-
## Events
|
|
792
|
-
|
|
793
|
-
Both `ComfyApi` and `ComfyPool` expose strongly typed event maps. Import the key unions or event maps for generic helpers:
|
|
794
|
-
|
|
795
|
-
```ts
|
|
796
|
-
import { ComfyApi, ComfyApiEventKey, TComfyAPIEventMap } from 'comfyui-node';
|
|
797
|
-
|
|
798
|
-
const api = new ComfyApi('http://localhost:8188');
|
|
799
|
-
api.on('progress', (ev) => {
|
|
800
|
-
console.log(ev.detail.value, '/', ev.detail.max);
|
|
801
|
-
});
|
|
802
|
-
|
|
803
|
-
function handleApiEvent<K extends ComfyApiEventKey>(k: K, e: TComfyAPIEventMap[K]) {
|
|
804
|
-
if (k === 'executed') {
|
|
805
|
-
console.log('Node executed:', e.detail.node);
|
|
806
|
-
}
|
|
807
|
-
}
|
|
808
|
-
```
|
|
809
|
-
|
|
810
|
-
Pool usage:
|
|
811
|
-
|
|
812
|
-
```ts
|
|
813
|
-
import { ComfyPool, ComfyPoolEventKey } from 'comfyui-node';
|
|
814
|
-
|
|
815
|
-
pool.on('execution_error', (ev) => {
|
|
816
|
-
if (ev.detail.willRetry) console.warn('Transient failure, retrying...');
|
|
817
|
-
});
|
|
818
|
-
```
|
|
819
|
-
|
|
820
|
-
---
|
|
821
|
-
|
|
822
|
-
## Preview Metadata
|
|
823
|
-
|
|
824
|
-
When the server advertises the `supports_preview_metadata` feature flag, binary preview frames are sent using a richer protocol (`PREVIEW_IMAGE_WITH_METADATA`). The SDK decodes these frames and exposes both legacy and richer events.
|
|
825
|
-
|
|
826
|
-
What you get:
|
|
827
|
-
|
|
828
|
-
- Low-level API events on `ComfyApi`:
|
|
829
|
-
- `b_preview` – existing event with `Blob` image only (kept for backward compatibility)
|
|
830
|
-
- `b_preview_meta` – new event with `{ blob: Blob; metadata: any }`
|
|
831
|
-
|
|
832
|
-
- High-level `WorkflowJob` events:
|
|
833
|
-
- `preview` – existing event with `Blob`
|
|
834
|
-
- `preview_meta` – new event with `{ blob, metadata }`
|
|
835
|
-
|
|
836
|
-
Server protocol (per ComfyUI `protocol.py`):
|
|
837
|
-
|
|
838
|
-
- Binary event IDs:
|
|
839
|
-
- `1` = `PREVIEW_IMAGE` (legacy)
|
|
840
|
-
- `4` = `PREVIEW_IMAGE_WITH_METADATA`
|
|
841
|
-
- For type `4`, payload format after the 4-byte type header:
|
|
842
|
-
- 4 bytes: big-endian uint32 `metadata_length`
|
|
843
|
-
- N bytes: UTF-8 JSON metadata
|
|
844
|
-
- remaining: image bytes (PNG or JPEG)
|
|
845
|
-
|
|
846
|
-
The SDK reads `metadata.image_type` to set the Blob MIME type.
|
|
847
|
-
|
|
848
|
-
Example – low-level API usage:
|
|
849
|
-
|
|
850
|
-
```ts
|
|
851
|
-
api.on('b_preview_meta', (ev) => {
|
|
852
|
-
const { blob, metadata } = ev.detail;
|
|
853
|
-
console.log('[b_preview_meta]', metadata, 'bytes=', blob.size);
|
|
854
|
-
});
|
|
855
|
-
```
|
|
856
|
-
|
|
857
|
-
Example – high-level Workflow API usage:
|
|
858
|
-
|
|
859
|
-
```ts
|
|
860
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
861
|
-
|
|
862
|
-
job
|
|
863
|
-
.on('preview', (blob) => console.log('preview bytes=', blob.size))
|
|
864
|
-
.on('preview_meta', ({ blob, metadata }) => {
|
|
865
|
-
console.log('mime:', metadata?.image_type, 'size=', blob.size);
|
|
866
|
-
// other metadata fields depend on the server implementation
|
|
867
|
-
});
|
|
868
|
-
```
|
|
869
|
-
|
|
870
|
-
Backwards compatibility:
|
|
871
|
-
|
|
872
|
-
- If the server only emits legacy frames, you will still receive `preview` / `b_preview` events as before.
|
|
873
|
-
- When metadata frames are present, both are emitted: `b_preview` and `b_preview_meta` (and at the high level, `preview` and `preview_meta`).
|
|
874
|
-
|
|
875
|
-
Troubleshooting:
|
|
876
|
-
|
|
877
|
-
- Ensure your ComfyUI build supports `PREVIEW_IMAGE_WITH_METADATA` and that the feature flag is enabled. The SDK announces support via WebSocket on connect.
|
|
878
|
-
|
|
879
|
-
---
|
|
880
|
-
|
|
881
|
-
## API Nodes (Comfy.org paid)
|
|
882
|
-
|
|
883
|
-
Some workflows use paid API nodes (for example, Luma/Photon) that communicate progress and results via additional binary WebSocket frames. This SDK supports those nodes by:
|
|
884
|
-
|
|
885
|
-
- Allowing you to pass your Comfy.org API key to the server with each job
|
|
886
|
-
- Emitting low-level events for binary/text frames so you can surface progress and result URLs
|
|
887
|
-
|
|
888
|
-
### Enabling API-node runs
|
|
889
|
-
|
|
890
|
-
Provide your key through the `comfyOrgApiKey` client option (recommended to source it from an environment variable):
|
|
891
|
-
|
|
892
|
-
```ts
|
|
893
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
894
|
-
import LumaPhoton from './your-luma-photon-workflow.json';
|
|
895
|
-
|
|
896
|
-
const api = await new ComfyApi(
|
|
897
|
-
process.env.COMFY_HOST || 'http://127.0.0.1:8188',
|
|
898
|
-
undefined,
|
|
899
|
-
{
|
|
900
|
-
comfyOrgApiKey: process.env.COMFY_ORG_API_KEY,
|
|
901
|
-
wsTimeout: 30000, // API nodes may take longer; increase if needed
|
|
902
|
-
debug: true // optional: structured socket + polling logs
|
|
903
|
-
}
|
|
904
|
-
).ready();
|
|
905
|
-
|
|
906
|
-
// Minimal example: set prompt/seed, declare output, observe events
|
|
907
|
-
const wf = Workflow.fromAugmented(LumaPhoton)
|
|
908
|
-
.input('LUMA', 'prompt', 'Old photograph of the Guanabara Bay in Rio de Janeiro, aerial view')
|
|
909
|
-
.input('LUMA', 'seed', -1) // -1 => randomized; see _autoSeeds in result
|
|
910
|
-
.output('final_images', '2'); // alias, nodeId (auto-corrects if swapped)
|
|
911
|
-
|
|
912
|
-
// Low-level API-node events (binary channel text + raw preview bytes)
|
|
913
|
-
api.on('b_text', (ev) => {
|
|
914
|
-
const text = (ev as any).detail as string;
|
|
915
|
-
if (typeof text === 'string') console.log('[api-node text]', text.slice(0, 200));
|
|
916
|
-
});
|
|
917
|
-
api.on('b_text_meta', (ev) => {
|
|
918
|
-
// { channel: number, text: string }
|
|
919
|
-
console.log('[api-node text meta]', (ev as any).detail);
|
|
920
|
-
});
|
|
921
|
-
api.on('b_preview_raw', (ev) => {
|
|
922
|
-
const bytes = (ev as any).detail as Uint8Array;
|
|
923
|
-
console.log('[api-node preview raw bytes]', bytes?.byteLength);
|
|
924
|
-
});
|
|
925
|
-
|
|
926
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
927
|
-
|
|
928
|
-
job
|
|
929
|
-
.on('start', (id) => console.log('[start]', id))
|
|
930
|
-
.on('progress_pct', (p) => process.stdout.write(`\rprogress ${p}% `))
|
|
931
|
-
.on('preview', (blob) => console.log('\npreview bytes=', blob.size))
|
|
932
|
-
.on('failed', (e) => console.error('\nfailed', e));
|
|
933
|
-
|
|
934
|
-
const result = await job.done();
|
|
935
|
-
console.log('\nPrompt ID:', result._promptId);
|
|
936
|
-
for (const img of (result.final_images?.images || [])) {
|
|
937
|
-
console.log('image path:', api.ext.file.getPathImage(img));
|
|
938
|
-
}
|
|
939
|
-
```
|
|
940
|
-
|
|
941
|
-
Notes:
|
|
942
|
-
|
|
943
|
-
- API-node text frames often include human-readable progress and a final “Result URL:” line. The SDK exposes the raw text via `b_text` and `{ channel, text }` via `b_text_meta` so you can parse or display them as desired.
|
|
944
|
-
- For long-running API calls, increase `wsTimeout` and consider enabling `debug` or setting `COMFY_DEBUG=1` to troubleshoot reconnection/polling.
|
|
945
|
-
- Output declaration accepts any of: `'alias:NodeId'`, `('alias','NodeId')`, or `'NodeId'`. If you accidentally swap the alias/id parameters, the SDK will auto-correct and warn.
|
|
946
|
-
|
|
947
|
-
Security tip: Never print your API key. The built-in debug logger redacts common key/authorization fields automatically.
|
|
948
|
-
|
|
949
|
-
---
|
|
950
|
-
|
|
951
|
-
## Image Inputs: Attach Files (DX)
|
|
952
|
-
|
|
953
|
-
When a workflow references images (e.g., `LoadImage.image = "IMAGE_A.png"` or folder loaders such as `LoadImageSetFromFolderNode`), you can attach local buffers directly to the `Workflow` and let the SDK handle uploads before execution.
|
|
954
|
-
|
|
955
|
-
Helpers:
|
|
956
|
-
|
|
957
|
-
- `wf.attachImage(nodeId, inputName, data, fileName, opts?)`
|
|
958
|
-
- Uploads `data` (Blob/Buffer/ArrayBuffer/Uint8Array) and sets the node input to `fileName` automatically.
|
|
959
|
-
- Options: `{ subfolder?: string; override?: boolean }`.
|
|
960
|
-
- `wf.attachFolderFiles(subfolder, files[], opts?)`
|
|
961
|
-
- Upload multiple files into a server subfolder; ideal for folder‑based loaders.
|
|
962
|
-
|
|
963
|
-
Example (see `scripts/image-loading-demo.ts`):
|
|
964
|
-
|
|
965
|
-
```ts
|
|
966
|
-
import { ComfyApi, Workflow } from 'comfyui-node';
|
|
967
|
-
import Graph from './ImageLoading.json';
|
|
968
|
-
import * as fs from 'node:fs/promises';
|
|
969
|
-
import * as path from 'node:path';
|
|
970
|
-
|
|
971
|
-
const api = await new ComfyApi(process.env.COMFY_HOST || 'http://127.0.0.1:8188').ready();
|
|
972
|
-
const wf = Workflow.from(Graph);
|
|
973
|
-
|
|
974
|
-
// Attach two individual images for LoadImage nodes 2 and 4
|
|
975
|
-
const dir = path.resolve(process.cwd(), 'scripts', 'example_images');
|
|
976
|
-
const a = await fs.readFile(path.join(dir, 'IMAGE_A.png'));
|
|
977
|
-
const b = await fs.readFile(path.join(dir, 'IMAGE_B.png'));
|
|
978
|
-
wf.attachImage('2', 'image', a, 'IMAGE_A.png', { override: true })
|
|
979
|
-
.attachImage('4', 'image', b, 'IMAGE_B.png', { override: true });
|
|
980
|
-
|
|
981
|
-
// Attach an entire folder for node 5 (LoadImageSetFromFolderNode)
|
|
982
|
-
const files = (await fs.readdir(dir))
|
|
983
|
-
.filter(f => /\.(png|jpe?g|webp)$/i.test(f))
|
|
984
|
-
.map(async f => ({ fileName: f, data: await fs.readFile(path.join(dir, f)) }));
|
|
985
|
-
wf.attachFolderFiles('EXAMPLE_IMAGES', await Promise.all(files), { override: true });
|
|
986
|
-
wf.set('5.inputs.folder', 'EXAMPLE_IMAGES');
|
|
987
|
-
|
|
988
|
-
// Collect a simple output target for demonstration
|
|
989
|
-
wf.output('1');
|
|
990
|
-
|
|
991
|
-
const job = await api.run(wf, { autoDestroy: true });
|
|
992
|
-
job.on('progress_pct', p => process.stdout.write(`\rprogress ${p}% `));
|
|
993
|
-
await job.done();
|
|
994
|
-
```
|
|
995
|
-
|
|
996
|
-
Notes:
|
|
997
|
-
|
|
998
|
-
- The inputs are updated to point at the uploaded filenames; subfolders are handled server‑side.
|
|
999
|
-
- Use `override: true` to replace existing files with the same name if needed.
|
|
1000
|
-
|
|
1001
|
-
---
|
|
1002
|
-
|
|
1003
|
-
## 1.0 Migration
|
|
1004
|
-
|
|
1005
|
-
All legacy `ComfyApi` instance methods listed below were **removed in 1.0.0** after a deprecation window in 0.2.x. Migrate to the `api.ext.*` namespaces. If you're upgrading from <1.0, replace calls as shown. No runtime warnings remain (they were stripped with the removals).
|
|
1006
|
-
|
|
1007
|
-
| Deprecated | Replacement |
|
|
1008
|
-
| ---------- | ----------- |
|
|
1009
|
-
| `queuePrompt(...)` | `api.ext.queue.queuePrompt(...)` |
|
|
1010
|
-
| `appendPrompt(...)` | `api.ext.queue.appendPrompt(...)` |
|
|
1011
|
-
| `getHistories(...)` | `api.ext.history.getHistories(...)` |
|
|
1012
|
-
| `getHistory(id)` | `api.ext.history.getHistory(id)` |
|
|
1013
|
-
| `getSystemStats()` | `api.ext.system.getSystemStats()` |
|
|
1014
|
-
| `getCheckpoints()` | `api.ext.node.getCheckpoints()` |
|
|
1015
|
-
| `getLoras()` | `api.ext.node.getLoras()` |
|
|
1016
|
-
| `getSamplerInfo()` | `api.ext.node.getSamplerInfo()` |
|
|
1017
|
-
| `getNodeDefs(name?)` | `api.ext.node.getNodeDefs(name?)` |
|
|
1018
|
-
| `getExtensions()` | `api.ext.misc.getExtensions()` |
|
|
1019
|
-
| `getEmbeddings()` | `api.ext.misc.getEmbeddings()` |
|
|
1020
|
-
| `uploadImage(...)` | `api.ext.file.uploadImage(...)` |
|
|
1021
|
-
| `uploadMask(...)` | `api.ext.file.uploadMask(...)` |
|
|
1022
|
-
| `getPathImage(info)` | `api.ext.file.getPathImage(info)` |
|
|
1023
|
-
| `getImage(info)` | `api.ext.file.getImage(info)` |
|
|
1024
|
-
| `getUserData(file)` | `api.ext.file.getUserData(file)` |
|
|
1025
|
-
| `storeUserData(...)` | `api.ext.file.storeUserData(...)` |
|
|
1026
|
-
| `deleteUserData(file)` | `api.ext.file.deleteUserData(file)` |
|
|
1027
|
-
| `moveUserData(...)` | `api.ext.file.moveUserData(...)` |
|
|
1028
|
-
| `listUserData(...)` | `api.ext.file.listUserData(...)` |
|
|
1029
|
-
| `getUserConfig()` | `api.ext.user.getUserConfig()` |
|
|
1030
|
-
| `createUser(name)` | `api.ext.user.createUser(name)` |
|
|
1031
|
-
| `getSettings()` | `api.ext.user.getSettings()` |
|
|
1032
|
-
| `getSetting(id)` | `api.ext.user.getSetting(id)` |
|
|
1033
|
-
| `storeSettings(map)` | `api.ext.user.storeSettings(map)` |
|
|
1034
|
-
| `storeSetting(id,val)` | `api.ext.user.storeSetting(id,val)` |
|
|
1035
|
-
| `getTerminalLogs()` | `api.ext.terminal.getTerminalLogs()` |
|
|
1036
|
-
| `setTerminalSubscription()` | `api.ext.terminal.setTerminalSubscription()` |
|
|
1037
|
-
| `interrupt()` | `api.ext.queue.interrupt()` |
|
|
1038
|
-
|
|
1039
|
-
Quick grep-based migration (bash):
|
|
1040
|
-
|
|
1041
|
-
```bash
|
|
1042
|
-
grep -R "api\.getSystemStats" -n src | cut -d: -f1 | xargs sed -i '' 's/api\.getSystemStats()/api.ext.system.getSystemStats()/g'
|
|
1043
|
-
```
|
|
1044
|
-
|
|
1045
|
-
PowerShell example:
|
|
1046
|
-
|
|
1047
|
-
```powershell
|
|
1048
|
-
Get-ChildItem -Recurse -Include *.ts | ForEach-Object {
|
|
1049
|
-
(Get-Content $_.FullName) -replace 'api.getSystemStats\(\)', 'api.ext.system.getSystemStats()' | Set-Content $_.FullName
|
|
1050
|
-
}
|
|
1051
|
-
```
|
|
1052
|
-
|
|
1053
|
-
(Adjust the pattern per method; or use a codemod tool if you have many occurrences.)
|
|
1054
|
-
|
|
1055
|
-
Diff example:
|
|
1056
|
-
|
|
1057
|
-
Example migration:
|
|
1058
|
-
|
|
1059
|
-
```diff
|
|
1060
|
-
- const stats = await api.getSystemStats();
|
|
1061
|
-
+ const stats = await api.ext.system.getSystemStats();
|
|
1062
|
-
- await api.uploadImage(buf, 'a.png');
|
|
1063
|
-
+ await api.ext.file.uploadImage(buf, 'a.png');
|
|
165
|
+
await api.ext.file.uploadImage(buffer, 'image.png');
|
|
166
|
+
const history = await api.ext.history.getHistory('prompt-id');
|
|
1064
167
|
```
|
|
1065
168
|
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
Core (non‑deprecated) `ComfyApi` methods: `init`, `waitForReady`, event registration (`on`/`off`/`removeAllListeners`), `fetchApi`, `pollStatus`, `ping`, `reconnectWs`, `destroy`, and modular surface via `ext`.
|
|
1069
|
-
|
|
1070
|
-
Supporting classes:
|
|
1071
|
-
|
|
1072
|
-
- `PromptBuilder` – graph construction & value injection
|
|
1073
|
-
- `CallWrapper` – prompt execution lifecycle helpers
|
|
1074
|
-
- `ComfyPool` – multi‑instance scheduler
|
|
1075
|
-
|
|
1076
|
-
Enums & Types: `EQueueMode`, sampler / scheduler unions, `OSType`, plus exported response types found under `types/*`.
|
|
1077
|
-
|
|
1078
|
-
## Monitoring: System vs Job Progress
|
|
1079
|
-
|
|
1080
|
-
"Monitoring" in this SDK refers to two unrelated event domains:
|
|
1081
|
-
|
|
1082
|
-
| Type | Source | Requires Extension | Events | Usage |
|
|
1083
|
-
| ---- | ------ | ------------------ | ------ | ----- |
|
|
1084
|
-
| System Monitoring | Crystools extension | Yes (ComfyUI-Crystools) | `system_monitor` (pool) + feature internals | Host CPU/GPU/RAM telemetry |
|
|
1085
|
-
| Job Progress | Core ComfyUI | No | `executing`, `progress`, `executed`, `execution_success`, `execution_error`, `execution_interrupted`, `b_preview` | Per‑job progress %, live image previews |
|
|
1086
|
-
|
|
1087
|
-
System monitoring is toggled via env flags in the smoke script (`COMFY_MONITOR`, `COMFY_MONITOR_STRICT`, `COMFY_MONITOR_FORCE`) and is surfaced under `api.ext.monitor`.
|
|
1088
|
-
|
|
1089
|
-
Job progress monitoring is always active: subscribe directly (`api.on("progress", ...)`) or use higher‑level helpers:
|
|
1090
|
-
|
|
1091
|
-
```ts
|
|
1092
|
-
new CallWrapper(api, builder)
|
|
1093
|
-
.onProgress(p => console.log(p.value, '/', p.max))
|
|
1094
|
-
.onPreview(blob => /* show transient image */)
|
|
1095
|
-
.onFinished(out => /* final outputs */)
|
|
1096
|
-
.run();
|
|
1097
|
-
```
|
|
1098
|
-
|
|
1099
|
-
The published smoke test now logs job progress automatically and counts preview frames. Set `COMFY_PROGRESS_VERBOSE=1` to force log every step (not just percentage changes).
|
|
1100
|
-
|
|
1101
|
-
If you only need generation progress & previews you do NOT need the Crystools extension.
|
|
1102
|
-
|
|
1103
|
-
## Examples
|
|
1104
|
-
|
|
1105
|
-
See the `examples` directory for text‑to‑image, image‑to‑image, upscaling and pool orchestration patterns.
|
|
1106
|
-
|
|
1107
|
-
## Errors & Diagnostics
|
|
1108
|
-
|
|
1109
|
-
The SDK raises specialized subclasses of `Error` to improve debuggability during workflow submission and execution:
|
|
1110
|
-
|
|
1111
|
-
| Error | When | Key Extras |
|
|
1112
|
-
| ----- | ---- | ---------- |
|
|
1113
|
-
| `EnqueueFailedError` | HTTP `/prompt` (append/queue) failed | `status`, `statusText`, `url`, `method`, `bodyJSON`, `bodyTextSnippet`, `reason` |
|
|
1114
|
-
| `ExecutionFailedError` | Execution finished but not all mapped outputs arrived | missing outputs context |
|
|
1115
|
-
| `ExecutionInterruptedError` | Server emitted an interruption mid run | cause carries interruption detail |
|
|
1116
|
-
| `MissingNodeError` | A declared bypass or output node is absent | `cause` (optional) |
|
|
1117
|
-
| `WentMissingError` | Job disappeared from queue and no cached output | – |
|
|
1118
|
-
| `FailedCacheError` | Cached output retrieval failed | – |
|
|
1119
|
-
| `CustomEventError` | Server emitted execution error event | event payload in `cause` |
|
|
1120
|
-
| `DisconnectedError` | WebSocket disconnected mid‑execution | – |
|
|
1121
|
-
|
|
1122
|
-
### Error Codes
|
|
1123
|
-
|
|
1124
|
-
Every custom error exposes a stable `code` (enum) to enable branch logic without string matching message text:
|
|
1125
|
-
|
|
1126
|
-
```ts
|
|
1127
|
-
import { ErrorCode, EnqueueFailedError } from "comfyui-node";
|
|
1128
|
-
|
|
1129
|
-
try { /* run call wrapper */ } catch (e) {
|
|
1130
|
-
if ((e as any).code === ErrorCode.ENQUEUE_FAILED) {
|
|
1131
|
-
// inspect structured diagnostics
|
|
1132
|
-
}
|
|
1133
|
-
}
|
|
1134
|
-
```
|
|
1135
|
-
|
|
1136
|
-
### EnqueueFailedError Details
|
|
1137
|
-
|
|
1138
|
-
When the server rejects a workflow submission the SDK now attempts to surface the underlying cause:
|
|
1139
|
-
|
|
1140
|
-
```ts
|
|
1141
|
-
try {
|
|
1142
|
-
await new CallWrapper(api, workflow).run();
|
|
1143
|
-
} catch (e) {
|
|
1144
|
-
if (e instanceof EnqueueFailedError) {
|
|
1145
|
-
console.error('Status:', e.status, e.statusText);
|
|
1146
|
-
console.error('Reason:', e.reason);
|
|
1147
|
-
console.error('Body JSON:', e.bodyJSON);
|
|
1148
|
-
console.error('Snippet:', e.bodyTextSnippet);
|
|
1149
|
-
}
|
|
1150
|
-
}
|
|
1151
|
-
```
|
|
1152
|
-
|
|
1153
|
-
`reason` is resolved using (in order): `bodyJSON.error`, `bodyJSON.message`, falling back to a truncated textual body (first 500 chars). Raw JSON (if parseable) and a short text snippet are both retained to help rapidly identify mis‑shaped prompts, missing extensions, permission issues or model path problems.
|
|
1154
|
-
|
|
1155
|
-
If the response body is not JSON, `bodyTextSnippet` contains the first 500 characters of the returned text, which is also copied into `reason`.
|
|
169
|
+
See [API Features docs](./docs/api-features.md) for complete namespace reference.
|
|
1156
170
|
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
### Execution Failure vs Interruption
|
|
1160
|
-
|
|
1161
|
-
- `ExecutionFailedError`: The workflow ran but one or more declared output nodes never produced data (often due to an upstream node error not surfaced as a global event). Revisit your output mappings or inspect per‑node errors.
|
|
1162
|
-
- `ExecutionInterruptedError`: The server (or user action) actively interrupted execution; retrying may succeed if the interruption cause was transient.
|
|
1163
|
-
|
|
1164
|
-
### Persisting & Replaying Builder State
|
|
1165
|
-
|
|
1166
|
-
You can store builder state in a database / job queue:
|
|
171
|
+
### Events
|
|
1167
172
|
|
|
1168
173
|
```ts
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
.validateOutputMappings();
|
|
1173
|
-
```
|
|
1174
|
-
|
|
1175
|
-
This is useful for deferred execution, cross‑process scheduling, or audit logging of the exact prompt graph sent to the server.
|
|
174
|
+
api.on('progress', ev => console.log(ev.detail.value, '/', ev.detail.max));
|
|
175
|
+
api.on('b_preview', ev => console.log('Preview:', ev.detail.size));
|
|
176
|
+
api.on('executed', ev => console.log('Node:', ev.detail.node));
|
|
1176
177
|
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
```bash
|
|
1182
|
-
bun test # unit + lightweight integration tests
|
|
1183
|
-
bun run test:real # real server tests (COMFY_REAL=1)
|
|
1184
|
-
bun run test:full # comprehensive real server tests (COMFY_REAL=1 COMFY_FULL=1)
|
|
1185
|
-
bun run coverage # text coverage summary (lines/functions per file)
|
|
1186
|
-
bun run coverage:lcov # generate coverage/lcov.info (for badges or external services)
|
|
1187
|
-
bun run coverage:enforce # generate LCOV then enforce thresholds
|
|
178
|
+
job.on('progress_pct', pct => console.log(`${pct}%`));
|
|
179
|
+
job.on('preview', blob => console.log('Preview:', blob.size));
|
|
180
|
+
job.on('failed', err => console.error(err));
|
|
1188
181
|
```
|
|
1189
182
|
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
- `COMFY_REAL=1` enables `test/real.integration.spec.ts` (expects a running ComfyUI at `http://localhost:8188` unless overridden via `COMFY_HOST`).
|
|
1193
|
-
- `COMFY_FULL=1` additionally enables the extended `test/real.full.integration.spec.ts` suite.
|
|
1194
|
-
- `COMFY_HOST=http://host:port` to point at a non-default instance.
|
|
1195
|
-
|
|
1196
|
-
Coverage thresholds are enforced by `scripts/coverage-check.ts` (baseline intentionally modest to allow incremental improvement):
|
|
1197
|
-
|
|
1198
|
-
Default thresholds:
|
|
1199
|
-
|
|
1200
|
-
- Lines: `>= 25%`
|
|
1201
|
-
- Functions: `>= 60%`
|
|
1202
|
-
|
|
1203
|
-
Override thresholds ad hoc (CI example):
|
|
183
|
+
## Testing
|
|
1204
184
|
|
|
1205
185
|
```bash
|
|
1206
|
-
|
|
186
|
+
bun test # Unit + integration tests
|
|
187
|
+
bun run test:real # Real server tests (COMFY_REAL=1)
|
|
188
|
+
bun run test:full # Comprehensive tests (COMFY_FULL=1)
|
|
189
|
+
bun run coverage # Coverage report
|
|
1207
190
|
```
|
|
1208
191
|
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
```powershell
|
|
1212
|
-
$env:COVERAGE_MIN_LINES=30; $env:COVERAGE_MIN_FUNCTIONS=65; bun run coverage:enforce
|
|
1213
|
-
```
|
|
1214
|
-
|
|
1215
|
-
### Improving Coverage
|
|
1216
|
-
|
|
1217
|
-
Current low-coverage areas (see `bun test --coverage` output):
|
|
1218
|
-
|
|
1219
|
-
- `src/client.ts` – large surface; break out helpers & add unit tests for fetch error branches and WebSocket reconnect logic.
|
|
1220
|
-
- `src/call-wrapper.ts` – test error paths (enqueue failure, execution interruption, missing outputs) with mocked `fetch` & event streams.
|
|
1221
|
-
- Feature modules with toleration logic (`monitoring`, `manager`, `terminal`) – add mocks to simulate absent endpoints & successful responses.
|
|
192
|
+
See [Troubleshooting docs](./docs/troubleshooting.md#testing--coverage) for details.
|
|
1222
193
|
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
1. Extract pure helper functions from monolithic classes (e.g., parsing, polling backoff) into modules you can unit test in isolation.
|
|
1226
|
-
2. Add fine-grained tests for error branches (simulate non-200 responses & malformed JSON bodies) to raise line coverage quickly.
|
|
1227
|
-
3. Introduce deterministic mock WebSocket that replays scripted events (connection drop, progress, output) to cover reconnect & event translation.
|
|
1228
|
-
4. Gradually raise `COVERAGE_MIN_LINES` by 5% after each meaningful set of additions.
|
|
1229
|
-
|
|
1230
|
-
Skipping heavy real-image generation: full suite internally tolerates missing models & will skip or soften assertions rather than fail—use it sparingly in CI (nightly job) if runtime is a concern.
|
|
1231
|
-
|
|
1232
|
-
If contributing, please run at least:
|
|
1233
|
-
|
|
1234
|
-
```bash
|
|
1235
|
-
bun test && bun run coverage
|
|
1236
|
-
```
|
|
1237
|
-
|
|
1238
|
-
before opening a PR, and prefer adding tests alongside new feature code.
|
|
1239
|
-
|
|
1240
|
-
## Troubleshooting
|
|
1241
|
-
|
|
1242
|
-
| Symptom | Likely Cause | Fix |
|
|
1243
|
-
| ------- | ------------ | ---- |
|
|
1244
|
-
| `progress_pct` never fires | Only listening to raw `progress` (or run finished instantly) | Subscribe to `progress_pct`; ensure workflow isn't trivially cached / instant |
|
|
1245
|
-
| Empty `images` array | Wrong node id in `.output()` or no `SaveImage` nodes detected | Verify node id in base JSON; omit outputs to let auto-detect run |
|
|
1246
|
-
| `_autoSeeds` missing | No `seed: -1` inputs present | Set seed field explicitly to `-1` on nodes requiring randomization |
|
|
1247
|
-
| Autocomplete missing for sampler | Used `Workflow.from(...)` not `fromAugmented` | Switch to `Workflow.fromAugmented(json)` |
|
|
1248
|
-
| Type not updating after new `.output()` | Captured type alias before adding the call | Recompute `type R = ReturnType<typeof wf.typedResult>` after the last output declaration |
|
|
1249
|
-
| Execution error but no missing outputs | Underlying node error surfaced via `execution_error` event | Listen to `failed` + inspect error / server logs |
|
|
1250
|
-
| Job hangs waiting for output | Declared non-existent node id | Run with fewer outputs or validate JSON; inspect `_nodes` metadata |
|
|
1251
|
-
| Random seed not changing between runs | Provided explicit numeric seed | Use `-1` sentinel or generate a random seed before `.set()` |
|
|
1252
|
-
| Preview frames never appear | Workflow lacks preview-capable nodes (e.g. KSampler) | Confirm server emits `b_preview` events for your graph |
|
|
1253
|
-
| Pool never selects idle client | Mode set to `PICK_LOWEST` with constant queue depth | Switch to `PICK_ZERO` for latency focus |
|
|
1254
|
-
| High-level run returns immediately | Accessed `await api.run(wf)` only (acceptance barrier) | Await `job.done()` or events to completion |
|
|
1255
|
-
|
|
1256
|
-
Diagnostic tips:
|
|
1257
|
-
|
|
1258
|
-
- Enable verbose progress: set `COMFY_PROGRESS_VERBOSE=1` before running the smoke script.
|
|
1259
|
-
- For enqueue failures inspect `EnqueueFailedError` fields (`status`, `reason`, `bodyTextSnippet`).
|
|
1260
|
-
- Use `_aliases` metadata to confirm alias -> node id mapping at runtime.
|
|
1261
|
-
- Log `_autoSeeds` to verify sentinel replacement behavior in batch runs.
|
|
1262
|
-
- If types feel stale, close & reopen the file – TypeScript sometimes caches deep conditional expansions.
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
## Published Smoke Test
|
|
1266
|
-
|
|
1267
|
-
The script `scripts/published-e2e.ts` offers a zero‑config verification of the published npm artifact with **Bun auto‑install**. It dynamically imports `comfyui-node`, builds a small txt2img workflow (optionally an upscale branch), waits for completion and prints output image URLs.
|
|
1268
|
-
|
|
1269
|
-
### Quick Run (Auto‑Install)
|
|
1270
|
-
|
|
1271
|
-
```bash
|
|
1272
|
-
mkdir comfyui-node-smoke
|
|
1273
|
-
cd comfyui-node-smoke
|
|
1274
|
-
curl -o published-e2e.ts https://raw.githubusercontent.com/igorls/comfyui-node/main/scripts/published-e2e.ts
|
|
1275
|
-
COMFY_HOST=http://localhost:8188 bun run published-e2e.ts
|
|
1276
|
-
```
|
|
1277
|
-
|
|
1278
|
-
### Optional Explicit Install
|
|
1279
|
-
|
|
1280
|
-
```bash
|
|
1281
|
-
mkdir comfyui-node-smoke
|
|
1282
|
-
cd comfyui-node-smoke
|
|
1283
|
-
bun add comfyui-node
|
|
1284
|
-
curl -o published-e2e.ts https://raw.githubusercontent.com/igorls/comfyui-node/main/scripts/published-e2e.ts
|
|
1285
|
-
COMFY_HOST=http://localhost:8188 bun run published-e2e.ts
|
|
1286
|
-
```
|
|
1287
|
-
|
|
1288
|
-
### Environment Variables
|
|
1289
|
-
|
|
1290
|
-
| Var | Default | Purpose |
|
|
1291
|
-
| --- | ------- | ------- |
|
|
1292
|
-
| `COMFY_HOST` | `http://127.0.0.1:8188` | Base ComfyUI server |
|
|
1293
|
-
| `COMFY_MODEL` | `SDXL/sd_xl_base_1.0.safetensors` | Checkpoint file name (must exist) |
|
|
1294
|
-
| `COMFY_POSITIVE_PROMPT` | scenic base prompt | Positive text |
|
|
1295
|
-
| `COMFY_NEGATIVE_PROMPT` | `text, watermark` | Negative text |
|
|
1296
|
-
| `COMFY_SEED` | random | Deterministic seed override |
|
|
1297
|
-
| `COMFY_STEPS` | `8` | Sampling steps |
|
|
1298
|
-
| `COMFY_CFG` | `2` | CFG scale |
|
|
1299
|
-
| `COMFY_SAMPLER` | `dpmpp_sde` | Sampler name |
|
|
1300
|
-
| `COMFY_SCHEDULER` | `sgm_uniform` | Scheduler name |
|
|
1301
|
-
| `COMFY_TIMEOUT_MS` | `120000` | Overall timeout (ms) |
|
|
1302
|
-
| `COMFY_UPSCALE` | unset | If set, adds RealESRGAN upscale branch |
|
|
1303
|
-
| `COMFY_MONITOR` | unset | If set, attempt to enable Crystools system monitor & log first event |
|
|
1304
|
-
| `COMFY_MONITOR_STRICT` | unset | With monitor enabled, fail (exit 5) if no events received |
|
|
1305
|
-
|
|
1306
|
-
Exit codes: 0 success, 1 import failure, 2 timeout, 3 enqueue failure, 4 other error, 5 monitor strict failure.
|
|
1307
|
-
|
|
1308
|
-
### Rationale
|
|
1309
|
-
|
|
1310
|
-
Ensures the published `dist` is coherent and functional in a clean consumer environment; can later be wired into CI behind an opt‑in flag (e.g. `E2E_PUBLISHED=1`).
|
|
194
|
+
## Contributing
|
|
1311
195
|
|
|
1312
|
-
|
|
196
|
+
Issues and PRs welcome! Please:
|
|
1313
197
|
|
|
1314
|
-
|
|
198
|
+
- Include tests for new features
|
|
199
|
+
- Follow existing code style
|
|
200
|
+
- Keep feature surfaces minimal & cohesive
|
|
201
|
+
- Run `bun test && bun run coverage` before submitting
|
|
1315
202
|
|
|
1316
|
-
##
|
|
203
|
+
## License
|
|
1317
204
|
|
|
1318
|
-
|
|
205
|
+
MIT – see [LICENSE](./LICENSE)
|
|
1319
206
|
|
|
1320
|
-
##
|
|
207
|
+
## Links
|
|
1321
208
|
|
|
1322
|
-
|
|
209
|
+
- **npm:** [comfyui-node](https://www.npmjs.com/package/comfyui-node)
|
|
210
|
+
- **GitHub:** [igorls/comfyui-node](https://github.com/igorls/comfyui-node)
|
|
211
|
+
- **ComfyUI:** [comfyanonymous/ComfyUI](https://github.com/comfyanonymous/ComfyUI)
|