comfyui-node

Acc. R-01 · v1.12.0

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, and WorkflowCatalog.validateWorkflow()) now parse V3 ["COMBO", { options: [...], multiselect? }] definitions alongside legacy V1 [string[], config] tuples. Expanded NodeDef and NodeInputConfig with V3 metadata fields.
  • State-agnostic Jobs cancellation & v0.44 Jobs alignment (api.ext.jobs) – Added cancelJob(jobId) (POST /api/jobs/{job_id}/cancel), cancelJobs(jobIds) (POST /api/jobs/cancel), and listJobs(options) (alias for getJobs), falling back automatically to POST /api/queue { delete } on older servers (404/405). Normalized listJobs({ sort_by }) (created_at / execution_duration with legacy alias mapping) and expanded Job / JobOutputPreview types (previewable_outputs_count, execution_meta, text and 3D previews).
  • Queue submission options (api.ext.queue) – queuePrompt(number, workflow, options?) and appendPrompt(workflow, options?) accept QueuePromptOptions (promptId, partialExecutionTargets, workflowMetadata, extraData).
  • History pagination & management (api.ext.history) – getHistories(maxItems?, offset?) now accepts offset, and new deleteHistory(promptIds) / clearHistory() methods wrap POST /history.
  • Assets API v0.44 alignment & helpers (api.ext.assets) – listAssets() supports keyset pagination via after (with cursor retained as a fallback alias) and tags_all / tags_any / tags_none filters, and omits the removed metadata_filter query parameter that returns HTTP 400 UNSUPPORTED_PARAM on ComfyUI v0.44+. Updated Asset, AssetUploadResponse, and TagsModificationResponse schemas, and added downloadAsset(), getAssetContentUrl(), assetExistsByHash(), listTags(), refineTags(), seedAssets(), getSeedStatus(), cancelSeed(), and pruneAssets().
  • Core Model, Metadata & Userdata v2 helpers (api.ext.model, api.ext.file) – Added ModelFeature.getModelTypes() (GET /models), getModelsInFolder(folder) (GET /models/{folder}), and getModelMetadata(folder, filename) (GET /view_metadata/{folder}), plus FileFeature.listUserDataV2(path?) (GET /v2/userdata), fullInfo options on userdata helpers, and preview / channel options on getPathImage() / getImage().
  • Graph discovery & i18n endpoints (api.ext.node, api.ext.misc) – Added NodeFeature.getNodeReplacements() (GET /api/node_replacements), MiscFeature.getGlobalSubgraphs(), getGlobalSubgraph(id), getWorkflowTemplates(), getWorkflowTemplateUrl(), and getI18n().
  • Samplers, WebSocket events & SystemStats updates – Added exp_heun_2_x0, exp_heun_2_x0_sde, and cfgpp_ud10_ab to TSamplerName; added feature_flags and asset_export WebSocket events, execution event timestamps, richer progress_state node metadata, and comfy_package_versions / deploy_environment on SystemStatsResponse.
  • Bounded retention in WorkflowPool & MCP – Added WorkflowPoolOpts.completedJobRetention (default 1000, 0 keeps everything) and McpServerOptions.maxRetainedRuns (default 200, 0 keeps everything) to prevent unbounded in-memory growth in long-running processes.

Fixed

  • WebSocket reconnection race conditions (reconnectionManager) – Sockets still in CONNECTING (readyState === 0) are no longer treated as connected, the final reconnect attempt now waits out its handshake window before emitting reconnection_failed, and abort() properly clears numeric timeout handles.
  • feature_flags WebSocket handshake ordering – On socket open, the client now sends its feature_flags capability frame before dispatching connected / reconnected events (matching ComfyUI's first-message protocol) and guards socket.send() with readyState === WebSocket.OPEN.
  • OSType & path separator encoding in PromptBuilder – OSType and PromptBuilder.input(..., api.osType) now handle sys.platform values ("win32", "linux", "darwin") returned by /system_stats in addition to "nt" and "posix".
  • NodeFeature.getNodeDefs() encoding, HTTP error passthrough & auth headers – Single-node lookups encode nodeName once safely, HTTP 4xx/5xx responses are returned directly instead of retrying over node:http, and the node:http streaming 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 recognize unet_name / clip_name and .gguf / .sft / .onnx validation failures.
  • Workflow & WorkflowPool media output inference and noise_seed: -1 – Workflow.from(json) without explicit .output() now auto-detects PreviewImage, SaveVideo, VHS_VideoCombine, SaveAnimated*, SaveWEBM, SaveAudio*, SaveGLTF/SaveGLB/Save3D, and SaveText in addition to SaveImage; WorkflowPool preserves inferred outputs when Workflow has no explicit .output() calls; and both Workflow and MultiWorkflowPool auto-randomize noise_seed: -1 (RandomNoise) alongside seed: -1.
  • FileFeature.listUserData() root directory & { fullInfo } normalization – Normalizes dir="" to "." so root listings do not fail with HTTP 400 Directory not provided, and accepts { fullInfo: true } consistently with storeUserData() / moveUserData().
  • MCP session state, timer cleanup & model discovery – comfy_info now reports client.apiHost, comfy_generate and Workflow.run() clear/unref their timeout handles on early completion so processes exit immediately without lingering timers, wait: false runs 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 shared TextDecoder, and the comfyui-node CLI lazy-imports the MCP server and sharp after handling --help / --version.
  • TypeScript 7 & dependency upgrades – Upgraded the build toolchain to TypeScript 7 (^7.0.2) and updated @modelcontextprotocol/sdk, sharp, ws, and zod.

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-node process behind. startComfyMcpStdioServer now closes the server and destroys the ComfyUI client it created when stdin ends (a client passed in via options.client is left to its owner), and the CLI exits shortly after as a safety net. The shutdown wiring is exported as closeWhenInputEnds() for embedders.
  • Wrong version in the MCP handshake and --version – Both reported 1.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.ts files differently from a clean build, so dist:fresh failed on fresh clones. dist:fresh (and so prepublishOnly) now does a forced clean build (build:clean).

1.11.0

Added

  • Bundled MCP server – npx -y comfyui-node / bunx comfyui-node starts 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_revise and comfy_job. Generation uses the existing WebSocket connection, comfy_inspect returns bounded contact sheets, crops and comparisons, and comfy_revise records parent/child lineage with a seed policy. Workflows are read from --workflow-dir folders, with optional .sidecar.json metadata. See docs/agent-workflow-guide.md.
  • comfyui-node/mcp export – Embed the MCP server programmatically. The main comfyui-node entry point stays side-effect free.
  • NodeFeature.getUnets(), getClips(), getVaes() – List installed diffusion models, text encoders and VAEs.

Fixed

  • CallWrapper reacted to other prompts' completion – With concurrent jobs sharing one client, another prompt's execution_success could mark a job as finished while its outputs were still pending. The wrapper now only reacts to its own prompt_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_info responses – If fetch fails to read the payload (seen with Bun on Windows), it retries over streaming node:http/node:https.
  • getSamplerInfo() – Tolerates both nested and flat sampler/scheduler option lists.

Changed

  • fetchApi() sends Connection: close and lets per-call options.headers override 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 close handler 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 OPEN and connected forever. Liveness now tracks socket traffic only (open, message, ping, pong): after wsTimeout of silence the client pings, and if nothing comes back within another wsTimeout it discards the socket, emits status/disconnected, and reconnects.
  • A leftover socket blocked reconnection – createSocket skipped creation whenever any socket was still referenced, including a closed or dead one. A CLOSING/CLOSED leftover 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 close event could tear down the replacement. Sockets are now released through ComfyApi.releaseSocket(), which detaches handlers first (keeping a no-op error listener, since ws throws on an unhandled error). 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

  • CallWrapper debug logging – ~30 [CallWrapper]/[debug] lines were logged unconditionally; they are now gated behind the client's debug flag via a new public ComfyApi.isDebug getter.
  • 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.structureHash now honors its documented contract: it hashes topology + node class_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 changes structureHash values — 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 AssetsFeature at api.ext.assets with 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(), and output_type filtering 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, and type, support upload type, and encode image view URLs with URLSearchParams.
  • Job duration calculation – getExecutionDuration() now supports zero-valued start or end timestamps.

1.8.5

Updated

  • ComfyUI v0.18.2 Compatibility – Added JobStatus.CANCELLED to match ComfyUI's Jobs API
    • ComfyUI returns cancelled status when a job is interrupted rather than failed
    • JobStatus enum now includes all five statuses: PENDING, IN_PROGRESS, COMPLETED, FAILED, CANCELLED
    • No other changes required - all existing APIs remain compatible with latest ComfyUI

1.8.0

Added

  • ComfyUI v0.6.0 Compatibility – Full support for the new unified Jobs API
    • New JobsFeature accessible via api.ext.jobs
    • getJobs(options?) – List all jobs with filtering, sorting, and pagination
    • getJob(jobId) – Get single job details with full outputs
    • Convenience methods: getRunningJobs(), getPendingJobs(), getCompletedJobs(), getFailedJobs()
    • getExecutionDuration(job) – Calculate job execution time

New Types:

  • JobStatus enum – PENDING, IN_PROGRESS, COMPLETED, FAILED
  • Job interface – Unified job representation with status, timing, outputs, and workflow data
  • JobsListResponse – Paginated job list response
  • JobsListOptions – Query options for filtering and pagination
  • JobOutputPreview – Preview output metadata for list views
  • JobExecutionError – Error details for failed jobs
  • JobWorkflow – Workflow data in detailed job responses

Example Usage:

typescript
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 definitions
  • src/features/jobs.ts – New JobsFeature module
  • src/client.ts – Registered JobsFeature in ext namespace
  • src/index.ts – Exported Jobs API types and feature

Backward Compatibility:

  • All existing APIs remain unchanged
  • Legacy /queue and /history endpoints 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 optional SubmitJobOptions with priorityOverrides
    • Priority overrides are a Map<string, number> or Record<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:

typescript
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 for submitJob()
    • priorityOverrides?: Map<string, number> | Record<string, number>

Files Changed:

  • src/multipool/interfaces.ts – Added SubmitJobOptions interface, updated QueueJob type
  • src/multipool/multi-workflow-pool.ts – Updated submitJob() signature
  • src/multipool/job-queue-processor.ts – Pass overrides to client selection
  • src/multipool/client-registry.ts – Use overrides in sorting logic
  • src/index.ts – Export SubmitJobOptions type

1.6.7

Changed

  • Event-Based Logging System – Replaced direct console logging with a structured event-based system
    • Refactored MultiWorkflowPool, JobQueueProcessor, and ClientRegistry to emit log events
    • Removed internal Logger class implementation (src/multipool/logger.ts)
    • Improved integration capability by allowing consumers to handle log events programmatically

1.6.6

Updated

  • ComfyUI v0.3.68 Compatibility – Updated SystemStatsResponse interface to include new template version fields
    • Added installed_templates_version field to system stats
    • Added required_templates_version field to system stats
    • Tested and verified full compatibility with ComfyUI v0.3.68
    • All existing functionality remains unchanged

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 /ws with 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]
  • Server Manager (test/integration/server-manager.ts) – Process lifecycle management

    • startServer(port) – Spawn server and wait for ready signal
    • killServer(port) – Gracefully terminate server process
    • restartServer(port, delay) – Kill and restart with optional delay
    • killAll() – Cleanup all running servers
    • Configurable timeouts and automatic error handling
  • Test Helpers (test/integration/test-helpers.ts) – Reusable utilities

    • initializeClient(api) – Initialize ComfyApi and wait for ready
    • waitForConnection(api, timeout) – Poll until client is connected
    • waitForDisconnection(api, timeout) – Poll until client disconnects
    • pollUntil(condition, timeout, interval) – Generic polling utility
    • trackEvent(api, eventName) – Track whether specific events fired
    • sleep(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
    • reconnected event emission verification
    • Connection state transitions (connecting → connected → disconnected → reconnecting → connected)
    • Connection validation with validateConnection() and isConnected()
    • 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 tests
    • test:integration:simple – Run simple examples
    • test: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:

typescript
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 state
    • getClient(url) – Get specific client information by URL
    • getClientsForWorkflow(workflow) – Find clients with affinity for a workflow
    • getIdleClients() – Get all currently available workers
    • hasClientsForWorkflow(workflow) – Check if workflow can be executed
    • getPoolStats() – 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_meta events 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 original eventData

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 MultiWorkflowPool
  • src/multipool/tests/profiling-demo.ts – Complete profiling demonstration
  • src/multipool/tests/event-forwarding-demo.ts – Event system demonstration
  • src/multipool/tests/client-registry-api-demo.ts – Client registry API examples
  • src/multipool/tests/two-stage-edit-simulation.ts – Multi-user workflow simulation

New Exports:

  • MultiWorkflowPool – Main pool class
  • JobProfiler – 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: true to get detailed execution stats on every job
    • Stats include node timing, progress events, cache hits, and slowest bottlenecks
    • Access via job.profileStats in job:completed events
    • Example: "KSampler: 4328ms (50% of execution)" – instantly see where time is spent
    • Zero overhead when disabled (default)
  • 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:

typescript
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 practices
  • docs/execution-timeout.md – Timeout tuning and troubleshooting
  • scripts/demo-pool-profiling.ts – See profiling in action

New Types:

  • JobProfileStats – Complete execution statistics with summary and per-node breakdown
  • NodeExecutionProfile – 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 clients
    • scripts/pool-hash-routing-advanced.ts – Integration patterns with multi-tenant routing, workflow affinity, and real server support
    • scripts/pool-multitenant-example.ts – Production-ready multi-tenant service template
    • scripts/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 practices
    • docs/hash-routing-architecture.md – System diagrams, data structures, job lifecycle flows, and performance analysis
    • HASH_ROUTING_INDEX.md – Getting started guide with learning paths (5-min quickstart to production integration)
    • DEMO_PACKAGE.md – Complete package overview of all resources
    • docs/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_workflow and client:unblocked_workflow events 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 WorkflowPool that pings idle clients every 30 seconds (configurable via healthCheckIntervalMs option)
    • 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 patterns
    • scripts/debug-websocket-activity.ts - Track WebSocket message patterns and timing
    • scripts/test-long-idle-then-execute.ts - Verify connection functionality after extended idle periods
    • scripts/test-long-idle-txt2img.ts - Test with actual image generation including preview events
    • scripts/test-health-check.ts - Validate health check mechanism effectiveness
  • Updated documentation in docs/websocket-idle-issue.md with 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 implementing QueueAdapter.
  • Added SmartFailoverStrategy and MemoryQueueAdapter reference implementations plus a typed event map covering job:* and client:* lifecycle notifications.
  • Published docs/workflow-pool.md with architecture overview, adapter contract, and event reference. Updated README multi-instance section to compare WorkflowPool with the legacy ComfyPool.

Breaking:

  • None – ComfyPool remains unchanged and continues to be exported for existing consumers.

1.3.1

Features:

  • Added .bypass() and .reinstate() methods to the Workflow class for high-level node bypassing.
    • workflow.bypass('NODE_NAME') – marks a node to be bypassed during execution
    • workflow.bypass(['NODE_1', 'NODE_2']) – bypass multiple nodes at once
    • workflow.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() and CallWrapper.bypassWorkflowNodes() implementation
    • Fully type-safe with compile-time validation of node names

Notes:

  • This brings the high-level Workflow API to feature parity with PromptBuilder for node bypassing.
  • Bypass functionality was already available in PromptBuilder (since earlier versions); this release extends it to Workflow.
  • 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 /prompt submissions under extra_data.api_key_comfy_org.
  • 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) and b_text_meta ({ channel, text })
    • 4 PREVIEW_IMAGE_WITH_METADATA → b_preview + b_preview_meta ({ blob, metadata })
  • Added a normalized high‑level event node_text_update for 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 last executing node when a hint isn't present in text.

DX & Diagnostics:

  • New optional debug flag (or COMFY_DEBUG=1) prints structured logs for socket lifecycle and messages; sensitive headers are redacted.
  • More resilient output mapping in Workflow.output(...): calls like output('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 for LoadImageSetFromFolderNode).
    • Example script added: scripts/image-loading-demo.ts – demonstrates mixed loaders (single images + folder import) powered by the new helpers.

Notes:

  • node_text_update is best‑effort normalization based on upstream conventions; for full fidelity keep listening to b_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 ComfyApi option announceFeatureFlags.
    • supports_preview_metadata?: boolean (default true)
    • max_upload_size?: number (bytes; default 50 * 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 ComfyApi instance 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.

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_meta event with { blob, metadata } while keeping b_preview for backward compatibility.
    • High-level: WorkflowJob now emits preview_meta alongside existing preview.
    • See README "Preview Metadata" for usage examples.

SemVer rationale: First major release locks in modular ext surface as the canonical public API; removed legacy wrappers to reduce bundle size and ambiguity.

Acc. R-01 · Edit CHANGELOG.md on GitHub