comfyanonymous/ComfyUI
Top-level files
These aren't a package, but they hold the runtime entry points and the standard node library. They live at the repository root and import everything else.
Purpose
main.py boots the process. server.py is the HTTP/WebSocket layer. execution.py runs queued prompts. nodes.py is the standard node library that ships with ComfyUI. folder_paths.py is the model/path registry. The rest are small focused helpers.
Files
| File | Lines | Role |
|---|---|---|
main.py |
531 | Entry point. Parses args, sets device env vars, starts the prompt worker thread |
server.py |
1,288 | The aiohttp PromptServer — /prompt, /queue, /history, /view, the WebSocket |
execution.py |
1,355 | The PromptExecutor and validation: builds the DAG, traverses caches, runs nodes |
nodes.py |
2,513 | The standard node library: LoadCheckpoint, KSampler, VAEEncode, SaveImage, … |
folder_paths.py |
498 | folder_names_and_paths registry; get_folder_paths, add_model_folder_path |
latent_preview.py |
137 | TAESD/Latent2RGB preview rendering during sampling |
cuda_malloc.py |
101 | cudaMallocAsync detection and blacklist |
node_helpers.py |
91 | Small helpers used by built-in nodes (image loading, etc.) |
new_updater.py |
35 | Windows standalone build updater |
protocol.py |
7 | BinaryEventTypes constants for the WebSocket binary protocol |
hook_breaker_ac10a0.py |
17 | Save/restore monkey-patched core functions around node execution |
comfyui_version.py |
3 | The version constant; auto-generated from pyproject.toml |
main.py — startup sequence
main.py does, in order:
import comfy.options; comfy.options.enable_args_parsing()— must run before any module that importscomfy.cli_args.- Disable HF/Posthog telemetry env vars.
- Configure device env vars:
CUDA_VISIBLE_DEVICES,HIP_VISIBLE_DEVICES,ASCEND_RT_VISIBLE_DEVICES,MIMALLOC_PURGE_DELAY,OCL_SET_SVM_SIZE. These must be set before torch is imported. - Conditionally bring up
comfyui_managerif--enable-manageris set. - Apply custom paths from
extra_model_paths.yaml, register output directories. - Run
prestartup_script.pyfrom each custom node directory. - Import torch + the rest of
comfy/. If torch was already imported, log a warning. - Call
start_comfyui()which builds thePromptServer, initializes nodes, sets up the DB, and launches the prompt worker thread. - Run the asyncio loop.
The prompt_worker function is the per-request handler — see Prompt execution.
server.py — the aiohttp app
server.py defines PromptServer. Key endpoints:
| Path | Purpose |
|---|---|
POST /prompt |
Validate and enqueue a prompt |
GET /queue |
Inspect the queue |
GET /history, /history/<prompt_id> |
Past executions |
POST /interrupt |
Cancel the current execution |
GET /view?filename=... |
Read an output/input/temp file |
GET /system_stats |
Memory and device state |
GET /object_info |
Schema dump of every registered node |
GET /ws |
WebSocket for progress, status, executed events |
GET / and asset paths |
Serve the frontend bundle from web/ |
GET /internal/* |
Routes mounted from api_server/routes/internal/ |
Middleware stack (composable via flags):
cache_control— frommiddleware/cache_middleware.pycompress_body— gzips JSON when--enable-compress-response-bodyis setcors_middleware— when--enable-cors-header ORIGINis setorigin_only_middleware— blocks cross-site fetches when listening on loopback (default)block_external_middleware— sets a Content-Security-Policy headerdeprecation_warning— logs once when legacy/scripts/uipaths are hit
The WebSocket binary protocol is defined in protocol.py (BinaryEventTypes.UNENCODED_PREVIEW_IMAGE etc.).
execution.py
PromptExecutor.execute(prompt, prompt_id, extra_data, ...) is the main entry. Internally it:
- Validates the prompt via
validate_prompt. - Builds an
ExecutionListfromcomfy_execution.graph. - Walks output nodes backward, checking the
CacheSet(outputs,objects). - For each node, calls
_async_map_node_over_listwhich handles list-input batching, lazy inputs,IS_CHANGED, V3fingerprint_inputs, and node expansion viaDynamicPrompt. - Accumulates
history_resultand ships progress to the server.
See Prompt execution for the full flow.
nodes.py
The standard node library. Roughly 100 nodes covering text encoding, sampling, model loading, image I/O, latent ops, conditioning ops, model merging, ControlNet loading, and the LoRA/IP-Adapter family. nodes.NODE_CLASS_MAPPINGS is the global registry; init_extra_nodes populates it further from comfy_extras/ and custom_nodes/.
Notable classes:
CheckpointLoader,CheckpointLoaderSimple,UNETLoader— load model filesCLIPLoader,DualCLIPLoader,TripleCLIPLoader— load text encodersVAELoader,VAEEncode,VAEDecodeCLIPTextEncode— text → conditioningKSampler,KSamplerAdvanced— the canonical samplersLoraLoader,LoraLoaderModelOnly— apply a LoRALoadImage,SaveImage,PreviewImage— image I/OConditioningCombine,ConditioningSetArea,ConditioningSetMask— conditioning ops
folder_paths.py
The map from logical model categories to disk paths and accepted extensions. Used everywhere instead of hardcoded paths. Custom nodes call folder_paths.add_model_folder_path("checkpoints", "/some/path") to register additional locations. The default registry is set up at module import; extra_model_paths.yaml is layered on top by apply_custom_paths in main.py.
Supported model file extensions: {'.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'}.
latent_preview.py
Provides three preview methods: NoLatentPreviewer (off), Latent2RGBPreviewer (fast, low-quality, no extra weights), and TAESDPreviewer (loads small TAESD decoders from models/vae_approx/). Selected via --preview-method.
cuda_malloc.py
Detects whether the GPU supports cudaMallocAsync and maintains a blacklist of cards that crash with it (the warning is printed at startup if you have one). Imported early in main.py so the env var is set before torch initializes the CUDA allocator.
protocol.py
Tiny module:
class BinaryEventTypes:
UNENCODED_PREVIEW_IMAGE = 1
PREVIEW_IMAGE_WITH_METADATA = 2These are message-type bytes for the WebSocket binary frames the server sends to push preview images.
hook_breaker_ac10a0.py
Saves references to a small set of core functions before custom-node imports run, and restores them after each prompt execution. The cryptic suffix avoids name collisions with custom-node modules. See Debugging.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.