CivArchive
    ← All articles
    Published November 21, 2026by lepetitprince716355

    Compiling ComfyUI API Graphs into Readable Canvases: What the Frontend Actually Stores

    26 views0 reactions0 comments on CivitAI0 collected
    open sourcepythonautomationworkflowcomfyuitool guide

    TL;DR

    • ComfyUI uses two JSON formats that do not round-trip by default: the flat API prompt graph (class_type + inputs) that scripts and coding agents write, and the LiteGraph UI canvas (nodes, links, groups, reroutes, widgets_values) that people load in the browser.

    • We built and open-sourced comfyui-workflow-compiler (cwc), a zero-dependency Python compiler (Apache 2.0) that turns an API graph into a grouped, routed UI canvas and checks that it exports the exact prompt it was compiled from.

    • Before writing the layout engine, we measured a live ComfyUI 0.45.0 / frontend 1.59.1 instance with an automated browser oracle. Five frontend behaviors broke our initial assumptions: socket reordering on load, positional pseudo-widgets (control_after_generate on 20 of 702 core node types), geometry-only group membership, Vue renderer box growth, and spline link clearances.

    • Below are the exact measurements from frontend 1.59.1 and how to use cwc to compile clean workflows or let a coding agent author readable canvases directly.

    The two-graph problem in ComfyUI

    Anyone who builds ComfyUI workflows in code—or asks an LLM / coding agent to assemble a pipeline—hits the same split:

    • The API format (graphToPrompt().output) is a dictionary keyed by node ID. Each node has a class_type and an inputs object where literals and [source_id, slot] links live together. It is declarative, compact, and easy to diff or generate.

    • The UI canvas format (app.graph.serialize()) is a visual scene graph. Every node needs [x, y] coordinates, [w, h] dimensions, split input/output socket arrays, a positional widgets_values array, integer link IDs in a top-level links table, and group bounding rectangles.

    If you drop a raw API prompt onto the ComfyUI canvas, it cannot render a layout. If you ask a language model to invent raw UI coordinates and widgets_values arrays directly, it miscounts hidden pseudo-widgets, overlaps nodes, tangles wires across the screen, and places nodes outside their visual groups.

    We built comfyui-workflow-compiler (cwc) so that humans and coding agents only ever author the clean API graph (with optional _meta hints), while the compiler handles instantiation, widget templates, group inference, five layout presets, native reroute wiring, and prompt-equivalence verification.

    git clone https://github.com/lepetitprince716-prog/comfyui-workflow-compiler
    cd comfyui-workflow-compiler
    python3 -m venv .venv && . .venv/bin/activate
    pip install .
    cwc compile docs/images/src/hires.json -o out
    cwc compile: ok; preset bento; 7 groups, 0 optional modules, 1 warning
    wrote out/hires.ui.json
    wrote out/hires.api.json
    wrote out/hires.report.json

    Drop out/hires.ui.json onto ComfyUI and it opens as a grouped, routed canvas.

    Five facts we measured on ComfyUI frontend 1.59.1

    All measurements below were taken on ComfyUI 0.45.0 with frontend 1.59.1 in headless Chrome at 1920x1080 (devicePixelRatio 1). Other frontend versions and custom node packs with custom DOM widgets are untested.

    1. Socket order and fixed-point serialization

    In a node definition (/object_info), link inputs and widget inputs can appear interleaved. When a widget is converted to a link input, you might expect its socket to sit at its declaration index.

    We tested six input-array layouts on a KSampler fed by a PrimitiveInt on steps and an EmptyLatentImage on latent_image:

    Fixture                Sampler inputs array as written
    ---------------------  ----------------------------------------------
    inputs_spec_order      All slots interleaved in declaration order
    inputs_frontend_order  Link sockets first, widget sockets second
    inputs_compressed      Connection sockets + linked widget socket only
    inputs_linked_only     Only the two linked sockets, renumbered
    inputs_no_widget_key   Linked sockets only, widget key omitted
    inputs_stale_slots     Linked sockets only, stale slot numbers (2, 8)

    What frontend 1.59.1 did on all six:

    • All six loaded with zero errors and produced the exact same graphToPrompt().output.

    • On load, the frontend matches links by input name, not by slot index: stale slot numbers 2 and 8 were automatically rewritten to 5 and 3.

    • app.graph.serialize() always writes connection sockets first, then widget sockets, each in declaration order (model, positive, negative, latent_image, seed, steps, cfg, sampler_name, scheduler, denoise).

    Takeaway: A workflow compiler should emit connection sockets first and widget sockets second so that the compiled .ui.json is already a fixed point of load and save.

    2. widgets_values vs. widgets_values_named and pseudo-widgets

    Frontend 1.59.1 writes both a positional widgets_values array and a widgets_values_named dictionary when saving a canvas. Which one wins on load?

    Case on load                 Default (NamedValuesRestore false)  Setting true
    ---------------------------  ----------------------------------  -------------------
    Named and positional differ  Positional array wins               Named table wins
    Named table missing a key    Positional array used               Widget default used
    Named table only (no array)  All widgets reset to defaults       Named table used

    Because Comfy.Workflow.NamedValuesRestore is false by default in 1.59.1, a generated canvas must emit an accurate positional widgets_values array.

    That means accounting for non-serialized pseudo-widgets that live inside widgets_values at runtime:

    • control_after_generate: a combo widget (fixed, increment, decrement, randomize) inserted right after a seed/number widget. Exactly 20 of 702 bundled core node types have one. It is never exported to the API prompt, but omitting it shifts every following widget in widgets_values (for example, putting steps into control_after_generate and cfg into steps on KSampler).

    • upload: an "image" button occupying slot 2 of widgets_values on image loaders (["example.png", "image"]).

    cwc bundles the exact widget templates for all 702 core node types and provides cwc learn to derive templates from custom node /object_info exports.

    3. Group membership is pure geometry (and includes the 30 px title band)

    A LiteGraph .ui.json file does not store which nodes belong to which group. Instead, LGraphGroup.recomputeInsideNodes computes membership on the fly when you drag a group header:

    • A node's pos [x, y] is the top-left corner of its body, below its title bar.

    • Its visual boundingRect includes the 30 px title band above y: [x, y - 30, w, h + 30].

    • A node belongs to a group if and only if the centre (cx, cy) of that boundingRect falls inside the group's half-open rectangle [gx, gy, gw, gh]: gx <= cx < gx + gw and gy <= cy < gy + gh.

    In our oracle tests, a collapsed node placed at pos.y = 100 inside a group starting at gy = 100 was not a member of that group: its collapsed boundingRect was the title band y = 70..100, putting its vertical centre at y = 85 (outside the group). cwc verifies group containment (G3) using the exact y - 30 bounding rectangle math.

    4. Classic vs. Vue renderer node dimensions

    ComfyUI supports both the classic canvas renderer and the Vue DOM renderer (Comfy.VueNodes.Enabled). We measured the exact live boxes of the same nodes under both renderers:

    Node type               State      Classic box (w x h)    Vue box (w x h)
    ----------------------  ---------  ---------------------  ---------------------
    CheckpointLoaderSimple  Expanded   315 x 128 (+30 title)  315 x 156 (+30 title)
    VAEDecode               Expanded   210 x 76 (+30 title)   225 x 84 (+30 title)
    VAEDecode               Collapsed  130.38 x 30            225 x 30 (DOM 28)
    Short title "P"         Collapsed  67.66 x 30             225 x 30 (DOM 28)

    Under Vue, every expanded or collapsed node is at least 225 px wide, and widget rows sit slightly taller. If a layout tool packs nodes tightly to classic 210 px widths, they collide when opened with Vue nodes enabled. cwc sizes and spaces nodes with margins that stay collision-free across both renderers.

    5. Separating the Controls cockpit from the pipeline

    When someone downloads a workflow from Civitai, they usually want to edit four or five things on every run—positive prompt, negative prompt, canvas size, seed, or step count—without hunting across 40 pipeline nodes.

    In cwc, prompts and empty latents automatically enter the Controls group on the far left. Any other parameter can be promoted to Controls by adding "ui_role": "cockpit" in _meta:

    {
      "steps": {
        "class_type": "PrimitiveInt",
        "inputs": {"value": 28},
        " _meta": {"title": "Steps", "ui_role": "cockpit"}
      },
      "lora": {
        "class_type": "LoraLoader",
        "inputs": {
          "model": ["ckpt", "MODEL"],
          "clip": ["ckpt", "CLIP"],
          "lora_name": "style_lora.safetensors",
          "strength_model": 0.8,
          "strength_clip": 0.8
        },
        "_meta": {"title": "Style LoRA", "ui_optional": true}
      }
    }

    Setting "ui_optional": true places a node (or connected sub-chain) into an Optional module group that ships bypassed (mode: 4), and cwc compile --all-enabled verifies both the default prompt and the prompt with every optional module switched on.

    Five layout presets

    You can pick a layout arrangement with --preset (or let --preset auto choose from graph size and branch count):

    Preset         Best for                          Layout structure
    -------------  --------------------------------  -------------------------------------------------------------------------------
    bento          General workflows (default)       Controls left; main pipeline top row; branches & optional modules below
    tower-preview  <= 16 nodes, no optional modules  Like bento, with an >= 880x680 output group so the preview fills the right side
    swimlanes      >= 3 ControlNet / mask branches   One column per data-flow stage, each control branch under the stage it steers
    cockpit-split  Large graphs (>= 60 nodes)        Splits core controls (prompts, size, seed) above secondary tuning controls
    stepped        Tutorials & teaching graphs       Columns titled Step 1, Step 2, Step 3 in execution order

    Using cwc with coding agents (Claude Code, Cursor, Gemini, Codex)

    Because cwc validates node types, input names, type compatibility, and widget ranges offline in milliseconds, it acts as a fast compiler loop for coding agents:

    1. cwc guide prints the complete one-page authoring specification (_meta roles, optional modules, and _workflow keys).

    2. cwc node --search <keyword> and cwc node <TYPE> inspect exact socket names, widget defaults, and combo options.

    3. cwc compile graph.json -o out reports typos with suggestions (exit codes 0..5) and writes .ui.json, .api.json, and .report.json.

    4. cwc render out/graph.ui.json -o preview.svg renders an SVG preview of the canvas without needing a browser or GPU.

    A ready-to-use agent skill file is included in `skills/comfyui-workflow-compiler/SKILL.md`.

    Links & open resources

    Archived from CivitAI · Updated November 21, 2026View source