---
name: comfyui-batch-runner
description: Automate local or cloud-GPU ComfyUI servers programmatically over HTTP and WebSocket—uploading keyframes via /upload/image, patching API JSON graphs deterministically, polling /history/{prompt_id}, and downloading finished MP4 or PNG outputs via /view.
---

# ComfyUI Headless API Batch Automation Protocol

Whenever writing Python or Node scripts to drive a local (`http://127.0.0.1:8188`) or remote cloud-GPU ComfyUI instance, follow this exact 5-step API lifecycle:

## 1. Health & Checkpoint Pre-Flight (`GET /object_info`)
Before queueing a 20-clip batch, verify the server is reachable and required node classes exist (`GET $COMFY_URL/system_stats` and `GET $COMFY_URL/object_info/SaveVideo`). Fail fast if the remote RunPod/local server is missing a checkpoint or node pack.

## 2. Upload Input Keyframes Cleanly (`POST /upload/image`)
Never assume local disk paths are visible to a remote RunPod/Modal ComfyUI container. Upload each opening PNG via multipart form-data:
```bash
curl -sS -X POST "$COMFY_URL/upload/image" \
  -F "image=@keyframes/shot01.png" \
  -F "overwrite=true"
```
Capture the returned `"name"` field and patch it into your `LoadImage` node's `inputs.image`.

## 3. Wrap Graph in `{"prompt": ..., "client_id": ...}` (`POST /prompt`)
ComfyUI rejects bare node maps unless wrapped inside `"prompt"`:
- Patch positive text, `LoadImage`, dimensions (divisible by `16` for Wan 2.2, `32` for LTX-2), frame count (`4n+1` for Wan 2.2, `8n+1` for LTX-2), and deterministic integer `noise_seed`.
- Verify the graph terminates in `SaveVideo` or `SaveImage` before POSTing.
- Parse returned `{"prompt_id": "..."}` and log it immediately to `comfy-manifest.json`.

## 4. Wait Cleanly via `/history/{prompt_id}` (or WebSocket)
Poll `GET $COMFY_URL/history/$PROMPT_ID` every `5–10s` (or subscribe to `ws://$HOST/ws?clientId=$CLIENT_ID`) until `history[prompt_id]["status"]["completed"] == true` or `status_str == "error"`. On CUDA OOM errors, stop immediately and surface the exact node ID + traceback instead of retrying endlessly.

## 5. Download Output Artifacts (`GET /view`)
Iterate over `history[prompt_id]["outputs"][node_id]` (`videos`, `gifs`, or `images`) and download each rendered artifact via:
```bash
curl -sS "$COMFY_URL/view?filename=$FILENAME&subfolder=$SUBFOLDER&type=$TYPE" \
  -o "renders/${SHOT_ID}_${SEED}_${FILENAME}"
```
Run `ffprobe` on downloaded MP4s and persist seed + output path inside `comfy-manifest.json` so any keeper take is 100% reproducible.
