Changelog
1.12.0
Added
- ComfyUI V3 node schema (
COMBO) support –extractComboOptions()(exported from the main entry point) and all node, model, and MCP schema readers (NodeFeature.getSamplerInfo(),getCheckpoints(),getLoras(),getUnets(),getClips(),getVaes(),McpGenerationSession, andWorkflowCatalog.validateWorkflow()) now parse V3["COMBO", { options: [...], multiselect? }]definitions alongside legacy V1[string[], config]tuples. ExpandedNodeDefandNodeInputConfigwith V3 metadata fields. - State-agnostic Jobs cancellation & v0.44 Jobs alignment (
api.ext.jobs) – AddedcancelJob(jobId)(POST /api/jobs/{job_id}/cancel),cancelJobs(jobIds)(POST /api/jobs/cancel), andlistJobs(options)(alias forgetJobs), falling back automatically toPOST /api/queue{ delete }on older servers (404/405). NormalizedlistJobs({ sort_by })(created_at/execution_durationwith legacy alias mapping) and expandedJob/JobOutputPreviewtypes (previewable_outputs_count,execution_meta, text and 3D previews). - Queue submission options (
api.ext.queue) –queuePrompt(number, workflow, options?)andappendPrompt(workflow, options?)acceptQueuePromptOptions(promptId,partialExecutionTargets,workflowMetadata,extraData). - History pagination & management (
api.ext.history) –getHistories(maxItems?, offset?)now acceptsoffset, and newdeleteHistory(promptIds)/clearHistory()methods wrapPOST /history. - Assets API v0.44 alignment & helpers (
api.ext.assets) –listAssets()supports keyset pagination viaafter(withcursorretained as a fallback alias) andtags_all/tags_any/tags_nonefilters, and omits the removedmetadata_filterquery parameter that returns HTTP400 UNSUPPORTED_PARAMon ComfyUI v0.44+. UpdatedAsset,AssetUploadResponse, andTagsModificationResponseschemas, and addeddownloadAsset(),getAssetContentUrl(),assetExistsByHash(),listTags(),refineTags(),seedAssets(),getSeedStatus(),cancelSeed(), andpruneAssets(). - Core Model, Metadata & Userdata v2 helpers (
api.ext.model,api.ext.file) – AddedModelFeature.getModelTypes()(GET /models),getModelsInFolder(folder)(GET /models/{folder}), andgetModelMetadata(folder, filename)(GET /view_metadata/{folder}), plusFileFeature.listUserDataV2(path?)(GET /v2/userdata),fullInfooptions on userdata helpers, andpreview/channeloptions ongetPathImage()/getImage(). - Graph discovery & i18n endpoints (
api.ext.node,api.ext.misc) – AddedNodeFeature.getNodeReplacements()(GET /api/node_replacements),MiscFeature.getGlobalSubgraphs(),getGlobalSubgraph(id),getWorkflowTemplates(),getWorkflowTemplateUrl(), andgetI18n(). - Samplers, WebSocket events &
SystemStatsupdates – Addedexp_heun_2_x0,exp_heun_2_x0_sde, andcfgpp_ud10_abtoTSamplerName; addedfeature_flagsandasset_exportWebSocket events, execution eventtimestamps, richerprogress_statenode metadata, andcomfy_package_versions/deploy_environmentonSystemStatsResponse. - Bounded retention in
WorkflowPool& MCP – AddedWorkflowPoolOpts.completedJobRetention(default1000,0keeps everything) andMcpServerOptions.maxRetainedRuns(default200,0keeps everything) to prevent unbounded in-memory growth in long-running processes.
Fixed
- WebSocket reconnection race conditions (
reconnectionManager) – Sockets still inCONNECTING(readyState === 0) are no longer treated as connected, the final reconnect attempt now waits out its handshake window before emittingreconnection_failed, andabort()properly clears numeric timeout handles. feature_flagsWebSocket handshake ordering – On socket open, the client now sends itsfeature_flagscapability frame before dispatchingconnected/reconnectedevents (matching ComfyUI's first-message protocol) and guardssocket.send()withreadyState === WebSocket.OPEN.OSType& path separator encoding inPromptBuilder–OSTypeandPromptBuilder.input(..., api.osType)now handlesys.platformvalues ("win32","linux","darwin") returned by/system_statsin addition to"nt"and"posix".NodeFeature.getNodeDefs()encoding, HTTP error passthrough & auth headers – Single-node lookups encodenodeNameonce safely, HTTP 4xx/5xx responses are returned directly instead of retrying overnode:http, and thenode:httpstreaming fallback forwards client auth and custom headers.MonitoringFeature.off()listener filter – Fixed an inverted boolean filter that dropped unrelated listeners when detaching a single handler.- Structured ComfyUI error parsing & model incompatibility detection –
extractReason()and pool failure analyzers unwrap structured{ error: { type, code, message, details }, node_errors }envelopes cleanly and recognizeunet_name/clip_nameand.gguf/.sft/.onnxvalidation failures. Workflow&WorkflowPoolmedia output inference andnoise_seed: -1–Workflow.from(json)without explicit.output()now auto-detectsPreviewImage,SaveVideo,VHS_VideoCombine,SaveAnimated*,SaveWEBM,SaveAudio*,SaveGLTF/SaveGLB/Save3D, andSaveTextin addition toSaveImage;WorkflowPoolpreserves inferred outputs whenWorkflowhas no explicit.output()calls; and bothWorkflowandMultiWorkflowPoolauto-randomizenoise_seed: -1(RandomNoise) alongsideseed: -1.FileFeature.listUserData()root directory &{ fullInfo }normalization – Normalizesdir=""to"."so root listings do not fail with HTTP400 Directory not provided, and accepts{ fullInfo: true }consistently withstoreUserData()/moveUserData().- MCP session state, timer cleanup & model discovery –
comfy_infonow reportsclient.apiHost,comfy_generateandWorkflow.run()clear/unref their timeout handles on early completion so processes exit immediately without lingering timers,wait: falseruns update their session state upon background completion, and model queries deduplicate overlapping loader lookups.
Changed
- Zero-copy binary WebSocket frame decoding & lazy CLI startup – Binary preview and text frames slice buffers via
Uint8Array.subarray()with a sharedTextDecoder, and thecomfyui-nodeCLI lazy-imports the MCP server andsharpafter handling--help/--version. - TypeScript 7 & dependency upgrades – Upgraded the build toolchain to TypeScript 7 (
^7.0.2) and updated@modelcontextprotocol/sdk,sharp,ws, andzod.
1.11.1
Fixed
- MCP server lingered after its host exited – When an MCP host (Claude Code, Codex, Cursor, …) closed the server's stdin, the open ComfyUI WebSocket kept the process alive, so every host restart left an orphaned
comfyui-nodeprocess behind.startComfyMcpStdioServernow closes the server and destroys the ComfyUI client it created when stdin ends (a client passed in viaoptions.clientis left to its owner), and the CLI exits shortly after as a safety net. The shutdown wiring is exported ascloseWhenInputEnds()for embedders. - Wrong version in the MCP handshake and
--version– Both reported1.10.0; they now read the installed package version. - Release builds depended on the local build cache – Incremental builds could order union members in generated
.d.tsfiles differently from a clean build, sodist:freshfailed on fresh clones.dist:fresh(and soprepublishOnly) now does a forced clean build (build:clean).
1.11.0
Added
- Bundled MCP server –
npx -y comfyui-node/bunx comfyui-nodestarts a local stdio Model Context Protocol server so coding agents can discover, build, validate, run and review ComfyUI workflows. Nine tools:comfy_info,comfy_nodes,comfy_recipes,comfy_validate,comfy_workflows,comfy_generate,comfy_inspect,comfy_reviseandcomfy_job. Generation uses the existing WebSocket connection,comfy_inspectreturns bounded contact sheets, crops and comparisons, andcomfy_reviserecords parent/child lineage with a seed policy. Workflows are read from--workflow-dirfolders, with optional.sidecar.jsonmetadata. See docs/agent-workflow-guide.md. comfyui-node/mcpexport – Embed the MCP server programmatically. The maincomfyui-nodeentry point stays side-effect free.NodeFeature.getUnets(),getClips(),getVaes()– List installed diffusion models, text encoders and VAEs.
Fixed
CallWrapperreacted to other prompts' completion – With concurrent jobs sharing one client, another prompt'sexecution_successcould mark a job as finished while its outputs were still pending. The wrapper now only reacts to its ownprompt_id.- History-recovered outputs had a different shape – When outputs were recovered from
/history, each node stored only its first value (for example the bare image array) instead of the full node output that the WebSocket path stores. Both paths now store the same object. getNodeDefs()on very large/object_inforesponses – Iffetchfails to read the payload (seen with Bun on Windows), it retries over streamingnode:http/node:https.getSamplerInfo()– Tolerates both nested and flat sampler/scheduler option lists.
Changed
fetchApi()sendsConnection: closeand lets per-calloptions.headersoverride the client defaults.
1.10.1
Fixed
- Event socket never recovered after a second server restart – A socket created by a reconnect returned early from its
closehandler even after it had opened, so once the reconnect loop had finished, the next drop left the client without execution events for good (HTTP calls kept working, which hid it). Only a reconnect attempt that never opened now defers to the reconnect loop; a reconnected socket that drops reconnects like any other. - Dead sockets were never detected – The heartbeat marked the socket active as soon as it sent a ping, and HTTP requests also refreshed the same timestamp, so a socket whose peer vanished without a close frame (server restart behind a proxy or NAT, half-open TCP) stayed
OPENandconnectedforever. Liveness now tracks socket traffic only (open, message, ping, pong): afterwsTimeoutof silence the client pings, and if nothing comes back within anotherwsTimeoutit discards the socket, emitsstatus/disconnected, and reconnects. - A leftover socket blocked reconnection –
createSocketskipped creation whenever any socket was still referenced, including a closed or dead one. ACLOSING/CLOSEDleftover is now discarded, and reconnect attempts always start from a fresh socket. - Discarded sockets could start a second reconnect loop – The reconnect loop terminated the previous socket without detaching its handlers, so its late
closeevent could tear down the replacement. Sockets are now released throughComfyApi.releaseSocket(), which detaches handlers first (keeping a no-operrorlistener, sincewsthrows on an unhandlederror).destroy()also aborts any in-flight reconnect loop.
1.10.0
Added
MultiWorkflowPool.submitToVariants(variants, options)– Submit one logical render that has a distinct workflow variant per host capability (e.g. the same image compiled for different GPUs / model quantizations, where each host can only run its own variant). Routes to the variant whose host is idle now, or enqueues a capable variant to run when a host frees. See the heterogeneous-cluster section of the README.SubmitJobOptions.maxAttempts– Per-job override of the retry limit (default 3).MultiWorkflowPoolOptions.completedJobRetention– Bounds how many terminal job states are retained (default 1000; 0 keeps everything).
Fixed
CallWrapperdebug logging – ~30[CallWrapper]/[debug]lines were logged unconditionally; they are now gated behind the client's debug flag via a new publicComfyApi.isDebuggetter.- General-queue liveness (
MultiWorkflowPool) – When a client went idle the pool only re-triggered that client's affinity queues, never the shared"general"queue. General-queue jobs (and any job on a client added without affinity) could stall forever after the initial drain. Idle now re-triggers affinity queues ∪ general. - Double-dispatch race (
MultiWorkflowPool) – A client is now reserved synchronously at selection, so concurrently-processed queues can't dispatch two jobs to the same idle host. - Transient failures – Now retried up to
maxAttempts(on another eligible client, or the same one later) instead of being failed on first occurrence. General-queue jobs count any client as eligible for retry. - Unbounded job-state growth – Terminal job states are now evicted beyond
completedJobRetention.
Changed
- Structural workflow hash (behavioral) –
hashWorkflow/Workflow.structureHashnow honors its documented contract: it hashes topology + nodeclass_type+ model/resource references (checkpoints, LoRAs, VAEs), and excludes prompts, seeds, dimensions, cfg, steps and node_meta. Previously it hashed the entire workflow JSON, so affinity only matched byte-identical submissions and per-workflow failover blocked a single prompt rather than a whole workflow. The same graph with a different prompt/seed/size now shares a hash; a different model is a different hash. This changesstructureHashvalues — a runtime routing/failover key (not persisted), so only code that hard-codes hash values is affected.
1.9.0
Added
- Cloud Assets API helpers – Added
AssetsFeatureatapi.ext.assetswith helpers for listing, fetching, uploading, updating, deleting, and tagging assets. - Queue and Jobs management helpers – Added pending prompt/job cancellation, queue clearing, running job interruption,
getJobStatus(), andoutput_typefiltering for Jobs API queries. - Richer ComfyUI protocol typing – Added asset/output media types, extended node definition fields, progress state and notification events, execution interruption typing, richer error payloads, and binary text frame node metadata.
Updated
- File helpers – Upload and duplicate helpers now preserve server-returned
filename,subfolder, andtype, support uploadtype, and encode image view URLs withURLSearchParams. - Job duration calculation –
getExecutionDuration()now supports zero-valued start or end timestamps.
1.8.5
Updated
- ComfyUI v0.18.2 Compatibility – Added
JobStatus.CANCELLEDto match ComfyUI's Jobs API- ComfyUI returns
cancelledstatus when a job is interrupted rather thanfailed JobStatusenum now includes all five statuses:PENDING,IN_PROGRESS,COMPLETED,FAILED,CANCELLED- No other changes required - all existing APIs remain compatible with latest ComfyUI
- ComfyUI returns
1.8.0
Added
- ComfyUI v0.6.0 Compatibility – Full support for the new unified Jobs API
- New
JobsFeatureaccessible viaapi.ext.jobs getJobs(options?)– List all jobs with filtering, sorting, and paginationgetJob(jobId)– Get single job details with full outputs- Convenience methods:
getRunningJobs(),getPendingJobs(),getCompletedJobs(),getFailedJobs() getExecutionDuration(job)– Calculate job execution time
- New
New Types:
JobStatusenum –PENDING,IN_PROGRESS,COMPLETED,FAILEDJobinterface – Unified job representation with status, timing, outputs, and workflow dataJobsListResponse– Paginated job list responseJobsListOptions– Query options for filtering and paginationJobOutputPreview– Preview output metadata for list viewsJobExecutionError– Error details for failed jobsJobWorkflow– Workflow data in detailed job responses
Example Usage:
import { ComfyApi, JobStatus } from "comfyui-node";
const api = new ComfyApi("http://localhost:8188");
await api.init();
// Check if Jobs API is supported (requires ComfyUI v0.6.0+)
const supported = await api.ext.jobs.checkSupported();
if (supported) {
// List recent completed jobs
const { jobs, pagination } = await api.ext.jobs.getJobs({
status: JobStatus.COMPLETED,
limit: 10,
sort_order: "desc"
});
// Get specific job with full details
const job = await api.ext.jobs.getJob("prompt-id-here");
if (job && job.status === JobStatus.COMPLETED) {
console.log(`Duration: ${api.ext.jobs.getExecutionDuration(job)}ms`);
}
}Files Changed:
src/types/api.ts– Added Jobs API type definitionssrc/features/jobs.ts– New JobsFeature modulesrc/client.ts– Registered JobsFeature in ext namespacesrc/index.ts– Exported Jobs API types and feature
Backward Compatibility:
- All existing APIs remain unchanged
- Legacy
/queueand/historyendpoints still work - Jobs API is optional and gracefully degrades on older ComfyUI versions
1.7.0
Added
- Per-Job Priority Overrides for MultiWorkflowPool – Dynamic client selection based on workflow type
submitJob(workflow, options?)now accepts optionalSubmitJobOptionswithpriorityOverrides- Priority overrides are a
Map<string, number>orRecord<string, number>mapping client URLs to priorities - Higher priority values = more preferred for job assignment
- Overrides take precedence over static priorities set at
addClient()time - Enables workflow-specific routing (e.g., route
qwen-*workflows to GPU-rich hosts,t2i-*to dedicated inference servers)
Usage:
const pool = new MultiWorkflowPool();
pool.addClient("http://server1:8188", { priority: 50 });
pool.addClient("http://server2:8188", { priority: 50 });
// Route this specific T2I workflow to server2 with higher priority
await pool.submitJob(workflow, {
priorityOverrides: {
"http://server1:8188": 10, // Lower priority for this job
"http://server2:8188": 100 // Preferred for this job
}
});New Types:
SubmitJobOptions– Options interface forsubmitJob()priorityOverrides?: Map<string, number> | Record<string, number>
Files Changed:
src/multipool/interfaces.ts– AddedSubmitJobOptionsinterface, updatedQueueJobtypesrc/multipool/multi-workflow-pool.ts– UpdatedsubmitJob()signaturesrc/multipool/job-queue-processor.ts– Pass overrides to client selectionsrc/multipool/client-registry.ts– Use overrides in sorting logicsrc/index.ts– ExportSubmitJobOptionstype
1.6.7
Changed
- Event-Based Logging System – Replaced direct console logging with a structured event-based system
- Refactored
MultiWorkflowPool,JobQueueProcessor, andClientRegistryto emit log events - Removed internal
Loggerclass implementation (src/multipool/logger.ts) - Improved integration capability by allowing consumers to handle log events programmatically
- Refactored
1.6.6
Updated
- ComfyUI v0.3.68 Compatibility – Updated
SystemStatsResponseinterface to include new template version fields- Added
installed_templates_versionfield to system stats - Added
required_templates_versionfield to system stats - Tested and verified full compatibility with ComfyUI v0.3.68
- All existing functionality remains unchanged
- Added
1.6.5
Added
Integration Test Infrastructure
Real Process-Based Reconnection Testing – New comprehensive integration test infrastructure that spawns actual mock server processes to test reconnection behavior
- Mock servers run in separate OS processes that can be killed/restarted to simulate real server crashes
- 13 integration tests covering manual reconnection, auto-reconnection, connection state transitions, and multiple restart cycles
- All tests passing with real WebSocket connections (no mocks)
Mock Server (
test/integration/mock-server.ts) – Standalone ComfyUI-compatible server- HTTP endpoints:
/queue,/prompt,/system_stats,/history - WebSocket server at
/wswith periodic status messages - Graceful shutdown handling via SIGTERM/SIGINT
- IPC messaging to signal readiness
- Can be run standalone:
bun test/integration/mock-server.ts [port]
- HTTP endpoints:
Server Manager (
test/integration/server-manager.ts) – Process lifecycle managementstartServer(port)– Spawn server and wait for ready signalkillServer(port)– Gracefully terminate server processrestartServer(port, delay)– Kill and restart with optional delaykillAll()– Cleanup all running servers- Configurable timeouts and automatic error handling
Test Helpers (
test/integration/test-helpers.ts) – Reusable utilitiesinitializeClient(api)– Initialize ComfyApi and wait for readywaitForConnection(api, timeout)– Poll until client is connectedwaitForDisconnection(api, timeout)– Poll until client disconnectspollUntil(condition, timeout, interval)– Generic polling utilitytrackEvent(api, eventName)– Track whether specific events firedsleep(ms)– Simple delay utility
Integration Tests (
test/integration/reconnection.integration.spec.ts) – 10 comprehensive test cases- Manual reconnection after server restart
- Multiple reconnection attempts with abort
- Automatic reconnection with
autoReconnect: true reconnectedevent emission verification- Connection state transitions (connecting → connected → disconnected → reconnecting → connected)
- Connection validation with
validateConnection()andisConnected() - Reconnection failure handling and callbacks
- Multiple server restart cycles (3+ consecutive restarts)
- WebSocket message handling after reconnection
Simple Examples (
test/integration/reconnection-simple.example.spec.ts) – 3 well-documented examples- Basic reconnection flow with step-by-step logging
- Auto-reconnection example with event tracking
- Multiple restart cycles demonstration
Validation Script (
test/integration/validate-mock-server.ts)- Standalone script to verify entire integration test infrastructure
- Tests server startup, HTTP endpoints, WebSocket connection, reconnection, and cleanup
- Run with:
bun test/integration/validate-mock-server.ts
Documentation – Comprehensive guides for integration testing
test/integration/README.md– Full documentation (276 lines)test/integration/SUMMARY.md– Architecture overview (253 lines)test/integration/QUICKSTART.md– Developer quick-start guide (405 lines)
NPM Scripts – Easy access to integration tests
test:integration– Run all integration teststest:integration:simple– Run simple examplestest:integration:reconnection– Run comprehensive reconnection tests
Benefits
- Real Process Testing – Tests actual process spawning, killing, and restarting (not mocked)
- True Network Behavior – Real WebSocket connections and HTTP requests
- Timing Accuracy – Tests actual connection timing and retry logic
- Production Confidence – Simulates real-world server failures and recoveries
- CI/CD Ready – Proper cleanup, timeout handling, and isolated execution
- Developer-Friendly – Helper functions, examples, and 900+ lines of documentation
Files Added
9 new files (~2,350 lines):
test/integration/mock-server.ts(262 lines)test/integration/server-manager.ts(289 lines)test/integration/test-helpers.ts(177 lines)test/integration/reconnection.integration.spec.ts(375 lines)test/integration/reconnection-simple.example.spec.ts(158 lines)test/integration/validate-mock-server.ts(154 lines)test/integration/README.md(276 lines)test/integration/SUMMARY.md(253 lines)test/integration/QUICKSTART.md(405 lines)
1.6.2
What's New:
- MultiWorkflowPool – Event-driven heterogeneous cluster management for ComfyUI workers
- Manage pools of ComfyUI servers with different workflow capabilities (e.g., SDXL servers, Flux servers, ControlNet servers)
- Workflow Affinity Routing – Automatically route jobs to servers with matching workflow capabilities based on workflow hash
- Zero Polling Architecture – Fully event-driven design with no polling loops for maximum responsiveness and scalability
- Per-Workflow Queues – Separate job queues per workflow type with intelligent fallback to general queue
- Client Priority System – Configure server priority for workflow assignments
- Structured Logging – Built-in logger with configurable log levels (
debug,info,warn,error,silent) - Integrated Profiling – Optional per-node execution profiling adapted from WorkflowPool
- Progress & Preview Events – Real-time job progress tracking and preview image streaming
- Smart Client Management – Automatic idle/busy state tracking and failover handling
Architecture:
const pool = new MultiWorkflowPool({
logLevel: "info", // Structured logging
enableProfiling: true, // Per-node timing stats
enableMonitoring: true, // Periodic status summaries
connectionTimeoutMs: 10000 // Connection timeout per client
});
// Add clients with workflow affinity
pool.addClient("http://server1:8188", {
workflowAffinity: [sdxlWorkflow], // Routes SDXL jobs here
priority: 1
});
pool.addClient("http://server2:8188", {
workflowAffinity: [fluxWorkflow], // Routes Flux jobs here
priority: 2
});
await pool.init();
// Submit jobs - automatic routing to appropriate server
const jobId = await pool.submitJob(sdxlWorkflow);
// Track progress and get results
pool.attachJobProgressListener(jobId, ({ value, max }) => {
console.log(`Progress: ${Math.round(value/max*100)}%`);
});
const result = await pool.waitForJobCompletion(jobId);
console.log('Profile Stats:', result.profileStats);Key Features:
- ClientRegistry – Manages client connections, states (idle/busy/offline), and workflow affinity matching
- JobQueueProcessor – Per-workflow queue processing with event-driven job assignment
- JobStateRegistry – Centralized job lifecycle management with profiling integration
- PoolEventManager – Extensible event system for custom monitoring and integration
- Public Client Registry API – Safe access to client information and pool statistics
getClients()– Get all registered clients with their current stategetClient(url)– Get specific client information by URLgetClientsForWorkflow(workflow)– Find clients with affinity for a workflowgetIdleClients()– Get all currently available workershasClientsForWorkflow(workflow)– Check if workflow can be executedgetPoolStats()– Comprehensive pool statistics (client counts, queue depths)
Events Supported:
- Job lifecycle:
job:queued,job:started,job:completed,job:failed,job:cancelled - Progress tracking: Real-time progress updates with node execution tracking
- Preview streaming:
b_preview_metaevents with blob and metadata - Client state: Automatic idle/busy transitions, offline detection
- All ComfyUI Events: Every WebSocket event from clients is forwarded with
client:prefix- Examples:
client:status,client:progress,client:executing,client:execution_cached,client:executed,client:execution_success - Use
pool.attachEventHook(eventType, listener)to subscribe to any client event - Event payload includes
clientUrl,clientName,eventType, and originaleventData
- Examples:
Performance:
- Event-driven architecture eliminates polling overhead
- O(1) workflow hash lookup for client routing
- Separate queues prevent head-of-line blocking
- Profiling shows cache hit rates, node timing, and execution bottlenecks
Documentation:
docs/multipool-profiling.md– Profiling guide for MultiWorkflowPoolsrc/multipool/tests/profiling-demo.ts– Complete profiling demonstrationsrc/multipool/tests/event-forwarding-demo.ts– Event system demonstrationsrc/multipool/tests/client-registry-api-demo.ts– Client registry API examplessrc/multipool/tests/two-stage-edit-simulation.ts– Multi-user workflow simulation
New Exports:
MultiWorkflowPool– Main pool classJobProfiler– Per-job execution profiling (MultiWorkflowPool variant)Logger/createLogger– Structured logging infrastructure- Types:
MultiWorkflowPoolOptions,JobResults,JobState,JobProfileStats,PoolEvent,ClientEventPayload
Use Cases:
- Multi-tenant SaaS platforms with heterogeneous server capabilities
- Workflow-specific server pools (image generation, video, upscaling, etc.)
- Development/testing with mixed local and cloud ComfyUI instances
- Load balancing across geographically distributed servers
1.5.0
What's New:
WorkflowPool Profiling – Enable automatic per-node performance tracking
- Set
enableProfiling: trueto get detailed execution stats on every job - Stats include node timing, progress events, cache hits, and slowest bottlenecks
- Access via
job.profileStatsinjob:completedevents - Example:
"KSampler: 4328ms (50% of execution)"– instantly see where time is spent - Zero overhead when disabled (default)
- Set
Timeout Protection – Prevent jobs from hanging on stuck servers
- Execution Start Timeout (default: 5s) – Auto-retry if server hangs before starting
- Node Execution Timeout (default: 5 min) – Handle slow model loading or stuck nodes
- Works with SmartFailoverStrategy to automatically route jobs to healthy servers
- Configure:
new WorkflowPool(clients, { executionStartTimeoutMs: 5000, nodeExecutionTimeoutMs: 600000 })
Configuration:
const pool = new WorkflowPool(clients, {
enableProfiling: true, // Get per-node timing stats
executionStartTimeoutMs: 5000, // 5s - retry if execution doesn't start
nodeExecutionTimeoutMs: 600000 // 10 min - for slow model loading
});
pool.on('job:completed', (event) => {
const stats = event.detail.job.profileStats;
if (stats) {
console.log(`Total: ${stats.totalDuration}ms`);
console.log('Slowest nodes:', stats.summary.slowestNodes);
}
});Documentation:
docs/profiling.md– Profiling guide with examples and best practicesdocs/execution-timeout.md– Timeout tuning and troubleshootingscripts/demo-pool-profiling.ts– See profiling in action
New Types:
JobProfileStats– Complete execution statistics with summary and per-node breakdownNodeExecutionProfile– Individual node metrics (duration, progress, status)
Fixes:
- Improved TypeScript compatibility (removed
Array.at(), fixed Map iteration for ES2022)
1.4.3
Features:
- Hash-Based Workflow Routing with SmartFailoverStrategy
- Introduced deterministic SHA-256 hashing of workflow content to enable fine-grained failure tracking and intelligent routing
- Failures are now tracked per (client, workflow-hash) pair instead of per-client, enabling per-workflow blocking
- Jobs with the same workflow content automatically route around previously failed clients during the cooldown period (default: 60 seconds, configurable)
- Duplicate workflows detected via hash are routed to the same server when possible, improving cache hit rates and resource efficiency
- SmartFailoverStrategy integrated into WorkflowPool by default – no configuration needed
- Configuration:
new WorkflowPool(clients, { blockDuration: 60000, maxFailuresBeforeBlock: 1 }) - Multi-tenant safe: Each tenant's workflows are independently tracked and blocked, preventing cross-tenant interference
Developer Experience:
- Added comprehensive demo scripts showcasing hash-based routing:
scripts/pool-hash-routing-demo.ts– Educational demo with 4 complete scenarios (normal execution, failures, blocking, recovery) using mock clientsscripts/pool-hash-routing-advanced.ts– Integration patterns with multi-tenant routing, workflow affinity, and real server supportscripts/pool-multitenant-example.ts– Production-ready multi-tenant service templatescripts/pool-real-demo.ts– Intelligent server capability discovery with real workflow execution and hash-routing demonstration
- Added comprehensive documentation:
docs/hash-routing-guide.md– Practical configuration guide with usage patterns and best practicesdocs/hash-routing-architecture.md– System diagrams, data structures, job lifecycle flows, and performance analysisHASH_ROUTING_INDEX.md– Getting started guide with learning paths (5-min quickstart to production integration)DEMO_PACKAGE.md– Complete package overview of all resourcesdocs/hash-routing-quickstart.sh– Command reference for running demos
- Updated README with hash-routing section and documentation links
- All demos tested with real ComfyUI servers and verified working with multi-server deployments
Technical Details:
- Hash algorithm: Deterministic SHA-256 of JSON-normalized workflow content (order-independent)
- Event system: New
client:blocked_workflowandclient:unblocked_workflowevents for monitoring - Blocking lifecycle: Automatic unblocking after cooldown period – self-healing with no manual intervention required
- Performance: O(1) lookup for blocked workflows, minimal memory overhead per client
- Backward compatible: Existing WorkflowPool code works without changes; hash routing is automatic
1.4.1
Fixes:
- Resolved WorkflowPool idle connection stability issue
- Increased default WebSocket inactivity timeout from 10s to 60s to prevent false disconnections during normal idle periods
- ComfyUI servers don't send heartbeat messages when idle, causing the old 10s timeout to trigger unnecessary reconnection cycles
- Implemented automatic health check mechanism in
WorkflowPoolthat pings idle clients every 30 seconds (configurable viahealthCheckIntervalMsoption) - Health checks use lightweight
getQueue()calls to keep WebSocket connections alive without interfering with active jobs - Added proper cleanup with
ClientManager.destroy()to stop health checks on shutdown - Configuration:
new WorkflowPool(clients, { healthCheckIntervalMs: 30000 })(default: 30s, set to 0 to disable) - Test results: 120+ seconds of stable idle connection with zero disconnections, all WebSocket events (previews, progress, execution) received properly after long idle periods
- Backward compatible - existing code works automatically with improvements
Developer Experience:
- Added comprehensive test scripts for connection stability:
scripts/debug-idle-connections.ts- Monitor connection cycles and detect reconnection patternsscripts/debug-websocket-activity.ts- Track WebSocket message patterns and timingscripts/test-long-idle-then-execute.ts- Verify connection functionality after extended idle periodsscripts/test-long-idle-txt2img.ts- Test with actual image generation including preview eventsscripts/test-health-check.ts- Validate health check mechanism effectiveness
- Updated documentation in
docs/websocket-idle-issue.mdwith root cause analysis, solution details, and migration guide
1.4.0
Features:
- Introduced
WorkflowPool, a new event-driven pooling API with pluggable queue adapters and smarter failover heuristics. Jobs receive stable ids, WebSocket events carry the id, and backends such as Redis/BullMQ/RabbitMQ can be integrated by implementingQueueAdapter. - Added
SmartFailoverStrategyandMemoryQueueAdapterreference implementations plus a typed event map coveringjob:*andclient:*lifecycle notifications. - Published
docs/workflow-pool.mdwith architecture overview, adapter contract, and event reference. Updated README multi-instance section to compareWorkflowPoolwith the legacyComfyPool.
Breaking:
- None –
ComfyPoolremains unchanged and continues to be exported for existing consumers.
1.3.1
Features:
- Added
.bypass()and.reinstate()methods to theWorkflowclass for high-level node bypassing.workflow.bypass('NODE_NAME')– marks a node to be bypassed during executionworkflow.bypass(['NODE_1', 'NODE_2'])– bypass multiple nodes at onceworkflow.reinstate('NODE_NAME')– removes a node from the bypass list- Methods are immutable (return new Workflow instance) and chainable
- Bypassed nodes are automatically removed and connections rewired when
.run()is called - Leverages existing
PromptBuilder.bypass()andCallWrapper.bypassWorkflowNodes()implementation - Fully type-safe with compile-time validation of node names
Notes:
- This brings the high-level
WorkflowAPI to feature parity withPromptBuilderfor node bypassing. - Bypass functionality was already available in
PromptBuilder(since earlier versions); this release extends it toWorkflow. - This is additive and backward-compatible.
1.3.0
Features (API Nodes / Paid Nodes):
- Added first‑class support for custom/paid API nodes via
comfyOrgApiKey.- Pass it when constructing
ComfyApi(host, id?, { comfyOrgApiKey })and it will be included in/promptsubmissions underextra_data.api_key_comfy_org.
- Pass it when constructing
- Implemented full handling of ComfyUI binary WebSocket frames:
- 1 PREVIEW_IMAGE →
b_preview(Blob) - 2 UNENCODED_PREVIEW_IMAGE →
b_preview_raw(Uint8Array) - 3 TEXT →
b_text(string) andb_text_meta({ channel, text }) - 4 PREVIEW_IMAGE_WITH_METADATA →
b_preview+b_preview_meta({ blob, metadata })
- 1 PREVIEW_IMAGE →
- Added a normalized high‑level event
node_text_updatefor TEXT frames emitted by API nodes (e.g. comfy_api_nodes PollingOperation):detail = { channel, text, cleanText?, kind: 'progress' | 'result' | 'message', progressSeconds?, resultUrl?, nodeHint?, executingNode?, promptIdHint? }- Added
cleanText(prefix‑stripped message). Normalization now simply starts from the first known phrase ("Task in progress:" | "Result URL:"), removing any preceding node label (e.g. numeric id or "NODE_LABEL"). Falls back to the lastexecutingnode when a hint isn't present in text.
DX & Diagnostics:
- New optional
debugflag (orCOMFY_DEBUG=1) prints structured logs for socket lifecycle and messages; sensitive headers are redacted. - More resilient output mapping in
Workflow.output(...): calls likeoutput('2','images')are auto‑corrected to('images','2')with a console warning. - New high‑level helpers to simplify image inputs:
Workflow.attachImage(nodeId, inputName, data, fileName, opts?)– uploads a single image buffer/blob before run() and sets the input to the filename.Workflow.attachFolderFiles(subfolder, files[], opts?)– uploads multiple files into a server subfolder (useful forLoadImageSetFromFolderNode).- Example script added:
scripts/image-loading-demo.ts– demonstrates mixed loaders (single images + folder import) powered by the new helpers.
Notes:
node_text_updateis best‑effort normalization based on upstream conventions; for full fidelity keep listening tob_text/b_text_meta.- This is additive and backward‑compatible.
1.2.0
Features:
- Configurable announced feature flags on the WebSocket connection via a new
ComfyApioptionannounceFeatureFlags.supports_preview_metadata?: boolean(defaulttrue)max_upload_size?: number(bytes; default50 * 1024 * 1024)- Values are merged with defaults and sent to the server on socket open (and after reconnects).
Notes:
- This is additive and backward‑compatible. Existing behavior remains the same if you do not pass the option.
1.0.0
Breaking:
- Removed all previously deprecated
ComfyApiinstance wrappers in favor of modular feature namespaces (api.ext.*).- Removed methods:
queuePrompt,appendPrompt,getHistories,getHistory,getSystemStats,getTerminalLogs,setTerminalSubscription,getExtensions,getEmbeddings,getCheckpoints,getLoras,getSamplerInfo,getNodeDefs,getUserConfig,createUser,getSettings,getSetting,storeSettings,storeSetting,uploadImage,uploadMask,getPathImage,getImage,getUserData,storeUserData,deleteUserData,moveUserData,listUserData,interrupt. - Also removed the internal deprecation warning helper.
- Removed methods:
Migration:
- Replace direct calls with their namespaced equivalents, e.g.
api.getSystemStats()->api.ext.system.getSystemStats(). - See README "1.0 Migration" section for a diff table.
Other:
- Expanded branch test coverage for
CallWrapper(execution success, cached output, error branches, interruption, went missing). - Pruned dead code paths and improved internal consistency of feature namespace usage to avoid deprecated shims.
- Added support for metadata-enhanced preview frames (
PREVIEW_IMAGE_WITH_METADATA):- Low-level: new
b_preview_metaevent with{ blob, metadata }while keepingb_previewfor backward compatibility. - High-level:
WorkflowJobnow emitspreview_metaalongside existingpreview. - See README "Preview Metadata" for usage examples.
- Low-level: new
SemVer rationale: First major release locks in modular ext surface as the canonical public API; removed legacy wrappers to reduce bundle size and ambiguity.