diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5818d7d..2127fcc 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,21 +1,11 @@ { "name": "comfyui-readable-node", - "interface": { - "displayName": "Readable Node" - }, - "owner": { - "name": "nomadoor" - }, + "owner": { "name": "nomadoor" }, "plugins": [ { "name": "comfyui-readable-node", "source": "./", - "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node).", - "policy": { - "installation": "AVAILABLE", - "authentication": "ON_INSTALL" - }, - "category": "Productivity" + "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node)." } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 801194e..af73145 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "comfyui-readable-node", - "version": "0.0.4", + "version": "0.0.5", "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node).", "author": { "name": "nomadoor" diff --git a/CHANGELOG.md b/CHANGELOG.md index f4d42a7..802bbc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 0.0.5 (2026-11-08) + +Layout came out worse in 0.0.4: rules lost while untangling sentences, and the canvas telling the agent fixes it could not make. This puts them back and makes the canvas and the rules agree. + +- Rules restored: Load VAE stands above the sampler when only VAE Decode uses it; Load VAE or Load CLIP above the model loaders is Bad unless their nodes and wires cannot meet; a node put between columns that many wires pass through is Bad; ControlNet kinds are pale_blue. +- A ControlNet that changes the model (it takes a MODEL_PATCH) stands like Apply ControlNet, just left of the sampler, the text encoders left of it, its Load Model Patch below the encoders. `canvas core` drafts it. Other model nodes come before it. +- Stages: when no node taking the conditioning stands just left of the sampler, the nodes between two stages stand on the eye line and the wire from the previous stage is the level one. With SamplerCustomAdvanced, the latent from the previous stage comes last in the sources column. +- Columns: nodes stacked in one column align their right edges (`put … above/below` and `stack` align right by default); nodes whose widths differ by less than 60px take the wider width. +- The source heading a rail stands at the rail's height (not only loaders); a source whose wire into the node right of it is level may raise or lower the rail with a Reroute right after it. +- The canvas no longer widens a gap by itself: a gap where wires cross three times or more is named by the check, and the plan writes `gap wide`. "Only what you point at moves." +- New checks: a rail target reached without a lowering Reroute; a rail head away from its rail; an output node stepped down where the flow ends; uneven widths and right edges in a column; the wire from the previous stage slanting into the stage's chain. +- `canvas guide` prints every line uncut; `canvas core` lists the Layout examples for the nodes of its draft; the last line of `canvas layout` names what is left to fix. +- Review: a row answered `left` goes back to the reviewer, whose reply is written after the answer (`reviewer: not Bad`); `canvas review` stops without it or when the reviewer said Bad. +- A short one-line text in a field that is not a prompt (an expression, a regex) gets the frontend's smallest field. +- Widening a column or a loader to one width never eats the gap beside it: a loader placed left of a node widens to the left. +- A Reroute raising a wire to a rail stands on the left edge of the next column also across `gap wide`. +- A wire whose curve only bulges into a node in its target's column (a straight line would pass behind nothing) is not a wire behind a node. +- Load VAE or Load CLIP above a model loader: only meeting the model loader or its wires counts; crossing other wires does not. +- `set =@` stops when the file is missing (the path is read from the current folder). +- The conversation report at the end follows references/report.md (files and what each makes, what was changed that makes the result differ, other ways it could be built, other notes). +- Examples are marked "Exception ()" where a rule gives way. +- Tests: the fixes a check names are tested to work (tests/test_check_fixes.py). + ## 0.0.4 (2026-11-07) The rules were untangled into one set: sentences that contradicted each other were merged, and what stays undecided is shown as worked examples instead of rules. diff --git a/README.ja.md b/README.ja.md index a4f2def..4833b41 100644 --- a/README.ja.md +++ b/README.ja.md @@ -13,31 +13,20 @@ ComfyUI の workflow を、人が読みやすい形(**Readable Node**)に組 ## 導入 -使うエージェントごとに、下のどれか一つで入れる。Claude と ChatGPT(Codex)の両方で使うなら、それぞれに入れる。同じエージェントに二つの方法で入れると、skill が二重に並ぶ。 +下のどれか一つで入れてください。二つ入れると、skill が二重に並びます。 -### Claude デスクトップアプリ +### Claude Code -1. **プラグイン** の画面で **+追加 → マーケットプレイスを追加 → リポジトリから追加** を選ぶ -2. `nomadoor/comfyui-readable-node` を入力 -3. `comfyui-readable-node` の **+** をクリック +Claude Code のセッションの中で、次を実行してください。 -### Claude Code(CLI) - -ターミナルで次を実行する。 - -```bash -claude plugin install comfyui-readable-node --marketplace nomadoor/comfyui-readable-node +``` +/plugin marketplace add nomadoor/comfyui-readable-node +/plugin install comfyui-readable-node@comfyui-readable-node ``` -### ChatGPT デスクトップアプリ(Codex) - -1. **カスタマイズ → プラグイン** で **追加** を押す -2. ソースに `https://github.com/nomadoor/comfyui-readable-node.git` を入力。Git ref とスパースパスは空のまま -3. **個人用** のタブの `comfyui-readable-node` の **+** をクリック - -### Codex CLI +自動で更新したいときは、`/plugin` の Marketplaces で `comfyui-readable-node` を選び、Enable auto-update を選んでください。 -ターミナルで次を実行する。 +### Codex ```bash codex plugin marketplace add nomadoor/comfyui-readable-node @@ -46,15 +35,13 @@ codex plugin add comfyui-readable-node@comfyui-readable-node ### そのほかのエージェント(Gemini CLI、Cursor、GitHub Copilot など) -ターミナルで次を実行する。 - ```bash npx skills add nomadoor/comfyui-readable-node -g ``` -Node.js 22.20 以上が要る。 +Node.js 22.20 以上が必要です。 -scripts を動かすには Python 3 が要る(標準ライブラリだけを使う)。 +scripts を動かすには Python 3 が必要です(標準ライブラリだけを使います)。 ## モデル diff --git a/README.md b/README.md index 10e52d4..0d56ab8 100644 --- a/README.md +++ b/README.md @@ -13,31 +13,20 @@ An agent skill that rebuilds ComfyUI workflows into a form people can read: **Re ## Install -Install it once for each agent you use, with one of the ways below. To use it in both Claude and ChatGPT (Codex), install it in each. Installing it two ways for the same agent lists the skill twice. +Use one of the ways below. Installing two lists the skill twice. -### Claude desktop app +### Claude Code -1. In **Settings → Customize → Plugins**, choose **+ Add → Add marketplace → Add from a repository** -2. Enter `nomadoor/comfyui-readable-node` -3. Click **+** on `comfyui-readable-node` +In a Claude Code session, run: -### Claude Code (CLI) - -In a terminal, run: - -```bash -claude plugin install comfyui-readable-node --marketplace nomadoor/comfyui-readable-node +``` +/plugin marketplace add nomadoor/comfyui-readable-node +/plugin install comfyui-readable-node@comfyui-readable-node ``` -### ChatGPT desktop app (Codex) - -1. Open **Plugins** and press **Add** to open **Add plugin marketplace** -2. Enter `https://github.com/nomadoor/comfyui-readable-node.git` in **Source**. Leave **Git ref** and **Sparse paths** empty -3. On the **Personal** tab, click **+** on `comfyui-readable-node` - -### Codex CLI +To get updates automatically, open `/plugin`, go to Marketplaces, select `comfyui-readable-node` and choose Enable auto-update. -In a terminal, run: +### Codex ```bash codex plugin marketplace add nomadoor/comfyui-readable-node @@ -46,8 +35,6 @@ codex plugin add comfyui-readable-node@comfyui-readable-node ### Other agents (Gemini CLI, Cursor, GitHub Copilot and others) -In a terminal, run: - ```bash npx skills add nomadoor/comfyui-readable-node -g ``` diff --git a/skills/comfyui-readable-node/SKILL.md b/skills/comfyui-readable-node/SKILL.md index 10306cb..c45c9eb 100644 --- a/skills/comfyui-readable-node/SKILL.md +++ b/skills/comfyui-readable-node/SKILL.md @@ -3,7 +3,7 @@ name: comfyui-readable-node description: Builds a ComfyUI workflow (JSON) into a form people can read easily (Readable Node). Use it when the user mentions Readable Node, asks to make a ComfyUI workflow readable or tidy, takes an existing workflow apart to rebuild it, or builds a new workflow. Do not hide nodes, do not hide wires (turn wireless links back into wires), left to right, 1 task per workflow, fewer custom nodes, appropriate colouring. license: MIT metadata: - version: "0.0.4" + version: "0.0.5" --- # Readable Node @@ -47,7 +47,7 @@ The rules in the references serve these principles and goals; how to read a rule **What the canvas does (things with exactly one answer)**: node sizes, calculating positions, the default colours of loaders, LoRAs and Notes, group padding, checks (check), export. When reading the original (`canvas open`), it fixes what has exactly one way of fixing, such as turning wireless links back into wires, and applying the official node-replacement list and replacements that give the same calculation. It returns everything it did. **How to use the canvas** -- Do not write coordinate numbers. Point at things: "put it to the right of A", "make the wire horizontal", "align the top edges". The canvas does the calculation. +- Do not write coordinate numbers. Point at things: "put it to the right of A", "make the wire horizontal", "align the top edges". The canvas does the calculation. Only what you point at moves. - Every call of the tool takes time. Do in one call what can be done in one call (build with `run` on build.txt, arrange with `layout` on layout.txt). Read things side by side, at once. ## What not to do diff --git a/skills/comfyui-readable-node/references/examples.md b/skills/comfyui-readable-node/references/examples.md index 2f7ad4d..07ade33 100644 --- a/skills/comfyui-readable-node/references/examples.md +++ b/skills/comfyui-readable-node/references/examples.md @@ -1,6 +1,7 @@ # Examples How the rules applied in real workflows: "Layout" under the section headings of readable-form.md, then "Content" and "Notes" by topic. "Before" is a form an agent built, "After" the corrected form, "Layout" a layout arranged by hand. In the same situation, lean towards this form. +An example marked **Exception ()** is a correct counter-example: there that rule gives way. Every other example is a rule applied as written. ## Layout @@ -24,6 +25,24 @@ After: Save Image, which matters more, stands next to VAE Decode; Compare where After: a stage whose result is made by another node than VAE Decode (Merge List of Tiles to Image after redrawing tiles): Save Image next to that node ``` +**One latent node between two samplers (Hires.fix: KSampler → Upscale Latent By → KSampler)** +``` +Before: Upscale Latent By set lower so its wire into the second KSampler was level; the longer wire from the first KSampler slanted +After: Upscale Latent By on the eye line, its top edge on the KSamplers'; the longer wire from the first KSampler is level, the short one into the second KSampler slants +``` + +**A stage whose conditioning node stands just left of its sampler (MiniMax H3 hires fix, image to video)** +``` +Before: the chain (Separate AV Latent → Latent Upscaler → Concat AV Latent) at the height of the second KSampler's latent slot, the wire from the first KSampler slanting into it +After: MiniMax H3 Image to Video just left of the second KSampler, its positive level; the chain below that column (under Conditioning Zero Out) +``` + +**A stage with SamplerCustomAdvanced taking the previous stage's latent (KSampler → Upscale Latent By → SamplerCustomAdvanced)** +``` +Before: Upscale Latent By at the first KSampler's height, left of the sources column, its wire from the KSampler level +After: Upscale Latent By at the bottom of the sources column (the latent is the last input); both its wires slant +``` + **Stages in a row (t2i → tiled upscale, t2i → Hires.fix → upscale)** ``` Before: the upscale stage 500px below the first; the image lifted with Reroutes and lowered again @@ -78,9 +97,9 @@ After: WanImageToVideo top-aligned with CLIP Text Encode; the main flow continu ``` After: its sources in one column on its left, top to bottom in input order, right edges aligned (`inputs`) Before: the model row (… → Skip Layer Guidance → EasyCache) ending at the right edge of the text encoders, one column left of WanFunControlToVideo, the sampler's source column -After: the model row ending at WanFunControlToVideo's right edge; when the gap left of that column is widened, the model row moves with it (Wan 2.1 Fun Control) +After: the model row ending at WanFunControlToVideo's right edge; when the gap left of that column is wide, the model row ends there too (Wan 2.1 Fun Control) Before: WanSoundImageToVideo's 9 input slots in a row left 700px between it and the prompt column -After: Load Image and Load Audio pulled close to the node that receives them, even at the cost of some wire overlap +After: Load Image and Load Audio pulled close to the node that receives them ``` **The row of an image chain** @@ -107,9 +126,10 @@ Layout: the image Switches of all stages, the loader and the saver at one height ``` **Layers, same-shape chains** -- Nodes that stack layers (Add Layer → Create Layered Image) go from the bottom up, background at the bottom. Only these. +- **Exception (sources in the order of the inputs)**: nodes that stack layers (Add Layer → Create Layered Image) go from the bottom up, background at the bottom. Only these. - Two chains of the same shape (Wan 2.2 high and low noise; two AnimateDiff keyframe chains): the one for the later node on top, so their wires do not cross. -- Several large loading nodes (Load Image, Load Video) into one node: a staircase, the first at the upper left at its slot's height, the next lower right. Stacked in one column they make the workflow too tall. +- **Exception (sources in the order of the inputs)**: in Wan Animate, WanAnimateToVideo's face_video slot is above pose_video, yet the chain that cuts the face out with SDPose (SDPose Face Bounding Boxes → Crop By BBoxes) stands below the DWPose chain. +- **Exception (sources in one column)**: several large loading nodes (Load Image, Load Video) into one node: a staircase, the first at the upper left at its slot's height, the next lower right. Stacked in one column they make the workflow too tall. **Spacing** ``` @@ -122,6 +142,7 @@ After: no wider space to a wired neighbour without a reason ``` Layout: basic t2i: Load VAE above the KSampler (it is first used by VAE Decode) Layout: Load VAE next to the VAE Encode of the bottom row when it is first used there (Anima pose, Krea2 head swap, SeedVR2) +Layout: an edit (Flux.2 Klein, Anima with Klein): Load VAE below the text encoder; without a Reroute, between Conditioning Zero Out and Resize Image Before: a second Load Checkpoint used only from the third stage, at the far left with a long diagonal wire After: in the column left of its first user Before: Load Upscale Model at the far left, feeding one node @@ -147,10 +168,10 @@ Layout: a single stage: Load Checkpoint just left of the text encoders (its CLIP ### 7. Groups and colour -- A t2i with IPAdapter has no group. +- A two-stage LTX workflow has three groups (stage 1, stage 2, decode). A t2i with IPAdapter has no group. - A Detail pass whose every node was coloured green inside its group: the group already guides the eye. - Colour split finely (SCAIL 2): the core green; taking the person in the input video pale_blue; taking the person in the reference image cyan; CLIP Vision brown. -- In a two-stage LTX workflow, the decode of the Stage 1 result and the decode after upscaling are different outputs: they were split out of one "Decode" group. +- In that two-stage LTX workflow, when the Stage 1 result is decoded too, that decode belongs to the stage 1 group; only the decode after upscaling is in the decode group. ### 8. Names diff --git a/skills/comfyui-readable-node/references/glossary.md b/skills/comfyui-readable-node/references/glossary.md index c203af8..44ddc69 100644 --- a/skills/comfyui-readable-node/references/glossary.md +++ b/skills/comfyui-readable-node/references/glossary.md @@ -40,7 +40,7 @@ The meaning of the words used in the skill's documents. Each is defined here onc - **rail**: a value, or several side by side, carried far or to several places with Reroutes (`rail`). - **Reroute**: a small node that relays a wire. Used for rails. - **raising / lowering Reroute**: the Reroute that takes a rail from its source's output up or down to the height the rail runs at, and the one that takes it from the rail down or up into a target. -- **column gap / row gap**: the gap the canvas keeps between columns and between nodes stacked in a column (layout_params.json, H_GAP and V_GAP). A gap where wires cross several times is widened (GAP_WIDE). +- **column gap / row gap**: the gap the canvas keeps between columns and between nodes stacked in a column (layout_params.json, H_GAP and V_GAP). A gap where wires cross three times or more is made wide in the plan (`gap wide`, GAP_WIDE); the check names it. - **rail gap**: the vertical distance the canvas keeps between two rails (layout_params.json, RAIL_GAP). - **title band**: the strip at the top of a group frame where its title is written. - **step (staircase)**: a node placed just below the wire that passes it (`put right step`), so the wire runs on above it. diff --git a/skills/comfyui-readable-node/references/readable-form.md b/skills/comfyui-readable-node/references/readable-form.md index bbc48ef..7e6986c 100644 --- a/skills/comfyui-readable-node/references/readable-form.md +++ b/skills/comfyui-readable-node/references/readable-form.md @@ -8,10 +8,12 @@ How to read a rule: the bold line says what to do. **Why** names the principle o **Build the core in the usual form, so every workflow of the same kind reads the same.** Why: the whole picture at a glance. - Text to image with KSampler: the model chain (loader → LoRA → model patches) on a row above the encoders, or, when its last node also gives the encoders their CLIP (Load Checkpoint, a LoRA), just left of them (section 4); its wire into the KSampler may slant (the conditioning is the one made horizontal, not the model). The text encoders in the column left of the KSampler, positive above, negative below (Conditioning Zero Out stands where the negative would be). The positive conditioning enters the KSampler horizontally. VAE Decode right of the KSampler, level with it; Save Image right of VAE Decode. +- A ControlNet that changes the model (it takes and gives MODEL, with a Load Model Patch) is not part of the model row: like Apply ControlNet, it stands between the text encoders and the sampler, in the column just left of the sampler, its Load Model Patch below the text encoders (left of it and lower: never right below it, where its wire would go back). The other nodes of the model chain (LoRA, model sampling, caching) come before it. Change the order of model nodes only when their source shows they do not write the same setting (one that writes after another replaces it). - With SamplerCustomAdvanced: its sources in one column on its left in input order (noise, guider, sampler, sigmas, latent), the sampler at the vertical middle of that column (the guider's wire into it slants); the guider's conditioning enters the guider horizontally; the sigma nodes (scheduler → split) in that column, not on the model row. - The outputs: Save Image next to the node that makes the result. Compare and Preview need not be next to Save Image: they go where their wires need the fewest Reroutes (below Save Image is fine), but never between the node that makes the result and Save Image. When the flow goes on past an output node to a later node, the output node steps down so the wire passes above it (a staircase: `put right step` places it just below the wire; section 4). When the wire to Compare or Preview passes Save Image, one of them steps down; which one is chosen so fewer Reroutes are needed. +- Load VAE stands above the sampler (KSampler or SamplerCustomAdvanced) when only VAE Decode uses it. - The sampler stays where the eye line puts it; what enters it (its column of sources and the chains before them) moves up or down to it, never the sampler to them. -- A stage that takes the previous stage's result (an image, a latent): its sampler stands on the eye line first (section 4; a stage built as a block: `align top move ` aligns the sampler, not the block's frame); its conditioning enters horizontally from the column just left of it (Apply ControlNet, as the text encoder does in text to image), and the stage's own chain (upscale, resize, VAE Encode) stands on the row below, its latent slanting up into the sampler. When the conditioning cannot enter horizontally (it comes on a rail), the chain moves to the sampler instead: its latent enters horizontally. The wire bringing the previous stage's result into that chain is the one that slants (or runs on a rail). +- A stage that takes the previous stage's result (an image, a latent): its sampler stands on the eye line first (section 4; a stage built as a block: `align top move ` aligns the sampler, not the block's frame); its conditioning enters horizontally from the column just left of it (Apply ControlNet, as the text encoder does in text to image), and the stage's own chain (upscale, resize, VAE Encode) stands on the row below, its latent slanting up into the sampler. When no node taking the conditioning stands in the column just left of the sampler, the chain stands on the eye line instead, its top edges on the sampler's: the wire bringing the previous stage's result into the chain is horizontal, and the chain's latent into the sampler slants. ## 2. Nodes @@ -30,10 +32,11 @@ How to read a rule: the bold line says what to do. **Why** names the principle o - Fine: back by at most the target's width plus one column gap, into Conditioning Zero Out or from an empty latent into a scheduler. **A wire is drawn directly. Reroutes are used only when, without them, one could not see where the wire goes (a value carried far or to several places: a rail). When a direct wire would be hidden behind a node, move its source or its target so it shows, before bending it with Reroutes.** Why: Reroutes cut one wire into pieces, and the reader must trace them to see where a value comes from. -- A rail is one value, or several side by side, carried with Reroutes. Write a `rail` line; it runs at the height the line writes (`above `, `below `, `level .`) or, with none written, at its source's output height, and gives every target after its first lowering Reroute the value from the rail. Rails of model, vae, clip and conditioning run in that order from the top wherever their runs overlap. Place the source and the targets so the rail runs where it should. A loader heads its rail: stand it at its rail's height in that order; do not raise it with a Reroute. The one exception: a loader whose other output goes level into the node right of it (Load Checkpoint with a Load LoRA on its model) cannot avoid running this rail behind that node, so the rail goes down with a Reroute right after the loader. When the stages stand apart in groups of their own, the loaders' model and vae go to the later stages on rails; samplers that only stand next to each other (Wan 2.2 high and low noise) take them by direct wires. A conditioning rail runs above the samplers; the positive and the negative carried to a later stage run side by side, the positive on top, the negative just below it (not at two heights that cross); other rails are ordered so fewer wires cross. A rail for a side use (an image carried only to be shown or stitched for reference) runs below, written `below `: a rail above stands out on its own. +- A rail is one value, or several side by side, carried with Reroutes. Write a `rail` line; it runs at the height the line writes (`above `, `below `, `level .`) or, with none written, at its source's output height, and gives every target after its first lowering Reroute the value from the rail. Rails of model, vae, clip and conditioning run in that order from the top wherever their runs overlap. Place the source and the targets so the rail runs where it should. The source that heads a rail (a loader, a value node) stands at its rail's height, loaders in that order; do not raise or lower it with a Reroute. The one exception: a source whose wire into the node right of it is level (from this output or another: Load Checkpoint with a Load LoRA on its model, a Load Image whose image goes level into its neighbour and also on a rail below) cannot stand at the rail's height, so the rail goes up or down with a Reroute right after the source. When the stages stand apart in groups of their own, the loaders' model and vae go to the later stages on rails; samplers that only stand next to each other (Wan 2.2 high and low noise) take them by direct wires. A conditioning rail runs above the samplers; the positive and the negative carried to a later stage run side by side, the positive on top, the negative just below it (not at two heights that cross); other rails are ordered so fewer wires cross. A rail for a side use (an image carried only to be shown or stitched for reference) runs below, written `below `: a rail above stands out on its own. - Bad: a wire bent with Reroutes while neither its source nor its target was moved. One of a pair (positive and negative) on a rail and the other not. The same loader placed again for each stage. A rail that goes up and down. Two rails closer than the rail gap (a conditioning rail written just under the vae rail): the loaders heading the upper rails go up together, so the gap opens. A rail lifted off its source's output height by a Reroute where a line at that height would pass behind nothing (two values of Get Image Size raised to a height written in the rail line): the source stands at the height the rail runs, or the rail runs at the output height. - Fine: a rail inside or outside a group, off the group's title band. A rail of values (fps and so on) below the main flow. - Fine: wires passing behind a node that do not cross each other behind it (they come out in the order they went in). +- Fine: a wire running far down whose curve bulges into a node in its target's column (a Compare below a Save Image), where a straight line from its output to its input would pass behind nothing: the curve cannot avoid it. - Fine: in the staircase of several large loading nodes into one node (examples.md), a wire that would pass behind the next loading node is carried on with Reroutes: the staircase is kept even when it needs more Reroutes. ## 4. Flow and position @@ -69,12 +72,16 @@ How to read a rule: the bold line says what to do. **Why** names the principle o - Fine: preparation further left than the loaders. A preparation node next to the node it feeds that ends up above or below a column of the core. **Wires show and nothing is packed; no empty space is made by hand.** Why: do not hide wires; the whole picture at a glance. Place by relations (put, row, stack, align, level, inputs, rail); the canvas keeps the gaps, also around group frames. -- Bad: an empty band left between nodes. +- Bad: an empty band left between nodes. A node put between columns that many wires pass through, only because the space is free, so those wires run behind it. + +**Nodes stacked in one column align their right edges; nodes whose widths differ by less than 60px take the wider width.** Why: the whole picture at a glance (a column reads as one). +- Bad: a column of nodes with uneven right edges. Two stacked nodes whose widths differ by less than 60px. ## 5. Loaders **A loader stands in the column left of the node that first uses it.** Why: left to right; the wire from a loader is short and does not go back. -- Bad: other columns between a loader and its first user. A loader at the far left that feeds only a later stage. A loader of one node's model (Load Upscale Model) away from that node. +- Bad: other columns between a loader and its first user. A loader at the far left that feeds only a later stage. A loader of one node's model (Load Upscale Model) away from that node. Load VAE or Load CLIP above the model loaders. +- Fine: Load VAE or Load CLIP above a model loader where neither it nor its wires meet the model loader or the model loader's wires (no crossing, nothing passing behind it): then which is higher does not matter (Load VAE above the sampler). Its wires crossing other wires (CLIP, conditioning) on the way down do not count. ## 6. Value nodes @@ -89,7 +96,7 @@ How to read a rule: the bold line says what to do. **Why** names the principle o - Bad: stages that are clearly separate with no group. A group for each small piece of a stage: the stage's group holds them, and the frames of small groups leave the layout full of gaps. A group removed because a wire crossed its title band (move the wire or the group instead). A function switched with bypass whose nodes are not all in its group. Groups of stages operated in order not sharing their top and bottom edges (`group-align`). A wire over a group's title band. - Fine: no group for a bypass that switches what is in effect one node (a Canny with only a Preview of it, a VAE Decode Audio): the node itself is what is switched. -**Colour shows which function a node belongs to, on the few nodes that do one job.** Why: colour appropriately. Loaders, LoRAs and Notes have fixed colours (the canvas applies them; a Load CLIP whose CLIP reaches no text encoder, one that feeds only an LLM, has none). Five colours are left: brown, green, blue, pale_blue, cyan. The basic t2i / t2v form stays uncoloured; green is the part that makes this workflow differ from the basic form (the basic form is always the plain t2i / t2v of its model: in an edit, an i2i or an inpaint, the nodes that take the image in, and those that mask and stitch it, are green); each other added function gets one colour. A group already guides the eye: nodes inside a group get no colour but the fixed ones. +**Colour shows which function a node belongs to, on the few nodes that do one job.** Why: colour appropriately. Loaders, LoRAs and Notes have fixed colours (the canvas applies them; a Load CLIP whose CLIP reaches no text encoder, one that feeds only an LLM, has none). Five colours are left: brown, green, blue, pale_blue, cyan. The basic t2i / t2v form stays uncoloured; green is the part that makes this workflow differ from the basic form (the basic form is always the plain t2i / t2v of its model: in an edit, an i2i or an inpaint, the nodes that take the image in, and those that mask and stitch it, are green); ControlNet kinds are pale_blue; each other added function gets one colour. A group already guides the eye: nodes inside a group get no colour but the fixed ones. - Bad: a sixth colour. A node only for looking (a Preview) coloured. Every node of a group coloured the same. One node of a function coloured while the nodes that do that function with it stay uncoloured (Generate Text green, its Text (Multiline) and its Load CLIP not). A node that only makes the run faster (a cache, an attention backend) coloured: it belongs to the basic form. ## 8. Names diff --git a/skills/comfyui-readable-node/references/review.md b/skills/comfyui-readable-node/references/review.md index befca2e..ff3f8ed 100644 --- a/skills/comfyui-readable-node/references/review.md +++ b/skills/comfyui-readable-node/references/review.md @@ -11,6 +11,7 @@ Another agent reviews each exported workflow. You do not judge your own layout: 3. Fix the rows one at a time: change the plan (or the build) for that row, run `canvas layout`, and keep the change if the row's form is gone and the check list gained no new item; otherwise `canvas undo` and try another way. Then export again. When you think a row itself is wrong (the reviewer misread the picture), do not answer it yourself: send that row and why to the same reviewer, once. It withdraws the row (moves it under the table as "Withdrawn: — ") or keeps it. If the same reviewer cannot be reached, answer the row as below. Answer every row in the last column, once: `fixed`, or `left: `. A row is left only with a quoted line of readable-form.md or notes.md, written between quotes as it is in the file (the whole line or a part of it, eight characters or more, copied exactly): the Fine line that applies, or the bold line of the rule that fixing it would break. Each left row gives its own reason. `canvas review` stops on a left row without such a quote. Do not edit the reviewer's rows or its `Checked:` line. + Send every left row, with your answer, to the same reviewer. It looks only at whether the form in the picture is the Bad of that row's rule. If it is, the row is not left: fix it. Write its reply after your answer: `reviewer: not Bad`, or `reviewer: not reached` when the same reviewer cannot be reached (`left: "" — reviewer: not Bad`). `canvas review` stops on a left row without it, and on one where the reviewer said Bad. 4. `canvas use `, `canvas review $W/review_.md`, then `canvas report` again. The report page shows every row with your answer. `canvas finish` stops while a review is missing, a row is unanswered, or the canvas changed after its review was registered; `review` stops when a row says `fixed` but nothing changed since the picture the reviewer saw. Each canvas is reviewed once: after fixing the rows, do not start another review. ## The brief (give it as written) @@ -35,6 +36,7 @@ Write <$W/review_.md> in , keeping node names, rule Leave the answer column empty. If nothing breaks a rule, write "No findings." instead of the table. If the builder later sends you a row it thinks is wrong, look again once: withdraw it (move it under the table as "Withdrawn: — ", above the "Checked:" line) or keep it, and reply in one line. +If the builder sends you a row it answered "left", look only at whether the form in the picture is the Bad of that row's rule, and reply in one line: "Bad: fix it" or "not Bad: left stands". End the file with: "Checked: readable-form.md rules, notes.md rules". Reply with one line: the number of rows and the "Checked:" line. ``` diff --git a/skills/comfyui-readable-node/scripts/canvas.py b/skills/comfyui-readable-node/scripts/canvas.py index 61b5ee4..71b88c8 100644 --- a/skills/comfyui-readable-node/scripts/canvas.py +++ b/skills/comfyui-readable-node/scripts/canvas.py @@ -50,13 +50,13 @@ put origin top-left at (0, 0) There are no numbers in placing: the canvas keeps every gap (columns 60, rows 45, measured from hand-made layouts), plus the group padding where a group frame lies between two nodes (the gap is kept frame to node, frame to frame). - After the plan's lines, a gap between two columns where wires cross 3 times or more is widened to twice the column gap (the report - page lists each one); a node reaching over the gap whose right edge is the right edge of the column moved goes with it. Nothing else moves after the plan's lines: what the plan writes is where things stand. - Widths are the canvas's too: each node keeps its own, and loaders stacked in one column get the widest of them. + Nothing moves after the plan's lines: what the plan writes is where things stand. A gap between two columns where wires cross + 3 times or more is named by the check: write `gap wide` on the line that places the right column there. + Widths are the canvas's too: nodes stacked in one column whose widths differ by less than 60px get the wider width. put right [top|wire|bottom|middle|step] to the right of ref. Default: wire if a wire connects them, else top. step: one step down, just below the wire leaving ref (a staircase: an output node under a wire that passes on) put left [top|wire|bottom|middle|step] step: just below the wire entering ref (a side node under the image wire) - put below [left|right|center] below ref. Default: left edges aligned + put below [left|right|center] below ref. Default: right edges aligned put above [left|right|center] wire: at the height where the (first) wire between ref and unit is horizontal put right|left below|above beside A and below or above B (x from A, y from B; also written @@ -220,9 +220,9 @@ # the layout's own fixes after the plan (levelling, widening and closing gaps, clearing below growing nodes, pulling rails # together, railing wires along rails, separating groups, clearing frames). Off only to compare AUTO_FIX = False -# after the plan's lines the canvas moves nothing by itself: the one move kept is widening a gap -# between two columns where wires cross 3 times or more -WIDE_GAP = True +# after the plan's lines the canvas moves nothing by itself; a gap between two columns where wires cross 3 times or more +# is named by the check, and the plan writes `gap wide` there (the skill author) +WIDE_GAP = False # a Note goes where the plan writes it: the canvas does not try the other sides or turn below into above NOTE_SEARCH = False # level moves only the unit it names: the nodes wired level to it do not move along @@ -230,6 +230,7 @@ FRONTEND_MIN = json.loads((Path(__file__).resolve().parent / "frontend_min_sizes.json").read_text(encoding="utf-8"))["sizes"] PAD_L, PAD_T, PAD_R, PAD_B = P["GROUP_PAD_LEFT"], P["GROUP_PAD_TOP"], P["GROUP_PAD_RIGHT"], P["GROUP_PAD_BOTTOM"] GROUP_TITLE_H = 34 # height of the frontend's group title bar (font_size 24 x 1.4) +PROMPT_FIELDS = {"text", "prompt", "value", "string", "system_prompt", "positive", "negative"} TEXT_MIN_H = 100 # minimum height of a text area (a number set by the skill author) # a CLIP Text Encode that only names what SAM3 looks for holds one short sentence: the width of the SAM3 nodes, a text # area of a few lines (the skill author keeps these small; 17 in 10 hand-made layouts, 250-303 wide) @@ -238,6 +239,7 @@ IMAGE_AREA = {"save": P["IMAGE_AREA_SAVE"], "preview": P["IMAGE_AREA_PREVIEW"], "load": P["IMAGE_AREA_LOAD"]} IMAGE_UPLOAD_FLAGS = tuple(f for f in CS.UPLOAD_FLAGS if f in ("image_upload", "video_upload")) LOADER_MIN_W = 300 # minimum loader width (rounded from the median of 734 loaders in hand-made layouts, 301) +SAME_WIDTH_UNDER = 60 # nodes stacked in one column whose widths differ by less than this get one width (the skill author) REROUTE_W, REROUTE_H = 75, 26 COLORS = { "red": ("#322", "#533"), "brown": ("#332922", "#593930"), "green": ("#232", "#353"), "blue": ("#223", "#335"), @@ -252,7 +254,7 @@ # working keys from reading, dropped when copying from the source. orig_size is kept (used for the size of custom nodes that are not installed) WORK_KEYS = WW.NODE_WORK_KEYS - {"orig_size"} # marks only the canvas adds. Dropped on export -CANVAS_MARKS = {"size_min", "width_set", "loader_base", "loader_shift", "loader_x", "canvas_note", "layout_prev", "group_note", "note_ref"} +CANVAS_MARKS = {"size_min", "width_set", "loader_base", "loader_shift", "loader_x", "col_base", "col_shift", "col_x", "canvas_note", "layout_prev", "group_note", "note_ref"} class Stop(Exception): @@ -465,25 +467,115 @@ def same_loader_width(self): left = self.placed(n) and any(abs(G.rect(m)[2] - G.rect(n)[2]) < 1 and self.stacked(n, m) for m in self.s["nodes"] if m is not n and self.placed(m) and m.get("type") not in {"Reroute"} | NOTE_TYPES and "Loader" not in (m.get("type") or "") and not self.is_model_loader(m)) - # widest first; if that overlaps a neighbour, at least the minimum width; else leave it as it is + # widest first; if that overlaps a neighbour, at least the minimum width; else leave it as it is. A loader + # not kept on a right edge widens to the right, or to the left when widening to the right would eat the gap + # to the node right of it (a loader placed left of a node keeps its gap to that node) + before, done = G.rect(n) if self.placed(n) else None, False + # a loader on the left edge of a node stacked right below or above it keeps that edge: it never widens left + on_left_edge = self.placed(n) and any(abs(G.rect(m)[0] - G.rect(n)[0]) < 1 and self.stacked(n, m) + for m in self.s["nodes"] if m is not n and self.placed(m) + and m.get("type") not in {"Reroute"} | NOTE_TYPES) for cand in (w, max(base, LOADER_MIN_W)): - if cand == base: + if cand == base or done: break - n["size"][0] = cand - if left: - n["pos"][0] -= cand - base - if not (self.placed(n) and (any(rect_overlap(G.rect(n), G.rect(m)) for m in self.s["nodes"] - if m is not n and self.placed(m)) or self.sticks_out(n, base))): - n["loader_base"] = base - if left: - n["loader_shift"] = cand - base - n["loader_x"] = n["pos"][0] - self.changed.add(n["id"]) - break - n["size"][0] = base - if left: - n["pos"][0] += cand - base + for to_left in ((True,) if left else (False,) if on_left_edge else (False, True)): + n["size"][0] = cand + if to_left: + n["pos"][0] -= cand - base + if not (self.placed(n) and (any(rect_overlap(G.rect(n), G.rect(m)) + or self._gap_eaten(n, before, G.rect(n), m) + for m in self.s["nodes"] if m is not n and self.placed(m)) + or self.sticks_out(n, base))): + n["loader_base"] = base + if to_left: + n["loader_shift"] = cand - base + n["loader_x"] = n["pos"][0] + self.changed.add(n["id"]) + done = True + break + n["size"][0] = base + if to_left: + n["pos"][0] += cand - base self.same_column_loader_width() + self.same_column_width() + + def same_column_width(self): + """Nodes stacked in one column whose width is less than SAME_WIDTH_UNDER narrower than the widest of that column take + the widest width (readable-form.md, section 4: a column reads as one). A column whose right edges are aligned keeps + them aligned (it widens to the left); otherwise it widens to the right. Not widened when that would overlap another + node, or when its width was set with width.""" + skip = {"Reroute"} | NOTE_TYPES + for n in self.s["nodes"]: + if "col_base" in n: + n["size"][0] = n.pop("col_base") + shift, at = n.pop("col_shift", 0), n.pop("col_x", None) + if n.get("pos") is not None and shift and at is not None and abs(n["pos"][0] - at) < 1: + n["pos"][0] += shift + ns = [n for n in self.s["nodes"] if self.placed(n) and n.get("size") and n.get("type") not in skip] + ns.sort(key=lambda n: G.rect(n)[1]) + cols, seen = [], set() + for n in ns: + if n["id"] in seen: + continue + col, cur = [n], n + seen.add(n["id"]) + for m in ns: + if m["id"] in seen: + continue + r, q = G.rect(cur), G.rect(m) + if min(r[2], q[2]) > max(r[0], q[0]) and 0 <= q[1] - r[3] <= V_GAP + 1 \ + and (abs(r[2] - q[2]) < 1 or abs(r[0] - q[0]) < 1): + col.append(m) + seen.add(m["id"]) + cur = m + if len(col) > 1: + cols.append(col) + for col in cols: + right = len({round(G.rect(n)[2]) for n in col}) == 1 + widths = sorted({n["size"][0] for n in col}) + for n in col: + # the widest width less than SAME_WIDTH_UNDER wider than this node, stepping up through the widths + # in between (a Conditioning Zero Out takes the Empty Latent's width even when the column also holds a + # much wider text encoder) + w = n["size"][0] + for x in widths: + if w < x < w + SAME_WIDTH_UNDER: + w = x + d = w - n["size"][0] + if d <= 0 or n.get("width_set"): + continue + before = G.rect(n) + n["size"][0] = w + if right: + n["pos"][0] -= d + if any(rect_overlap(G.rect(n), G.rect(m)) or self._gap_eaten(n, before, G.rect(n), m) + for m in self.s["nodes"] if m is not n and self.placed(m)): + n["size"][0] -= d + if right: + n["pos"][0] += d + continue + n["col_base"] = n.get("col_base", w - d) + n["col_shift"] = n.get("col_shift", 0) + (d if right else 0) + if n["col_shift"]: + n["col_x"] = n["pos"][0] + self.changed.add(n["id"]) + + def _gap_eaten(self, n, before, after, mn): + """Widening node n from rect before to rect after brings it closer than H_GAP to node mn, beside it in the same + rows (closer than GAP_WIDE where the plan wrote `gap wide` between them): the gap between two columns stays the + gap the layout gave them. A gap already narrower is not made narrower.""" + m = G.rect(mn) + if min(after[3], m[3]) - max(after[1], m[1]) <= 0: + return False + if m[0] >= before[2]: + old, new = m[0] - before[2], m[0] - after[2] + elif m[2] <= before[0]: + old, new = before[0] - m[2], after[0] - m[2] + else: + return False + wide = any((n["id"] in a and mn["id"] in b) or (n["id"] in b and mn["id"] in a) + for a, b in self.s.get("wide_pairs", [])) + return new < old and new < min(old, GAP_WIDE if wide else H_GAP) def same_column_loader_width(self): """Loaders stacked in one column (any node whose type name contains Loader and that takes no wire: IPAdapter Model @@ -516,10 +608,12 @@ def same_column_loader_width(self): d = w - n["size"][0] if d <= 0: continue + before = G.rect(n) n["size"][0] = w if right: n["pos"][0] -= d - if any(rect_overlap(G.rect(n), G.rect(m)) for m in self.s["nodes"] if m is not n and self.placed(m)): + if any(rect_overlap(G.rect(n), G.rect(m)) or self._gap_eaten(n, before, G.rect(n), m) + for m in self.s["nodes"] if m is not n and self.placed(m)): n["size"][0] -= d if right: n["pos"][0] += d @@ -794,6 +888,9 @@ def size_node(self, n): if n.get("type") in NOTE_TYPES: return n.pop("loader_base", None) # the size is recomputed, so the loader width alignment is recomputed too + n.pop("col_base", None) + n.pop("col_shift", None) + n.pop("col_x", None) shift, at = n.pop("loader_shift", 0), n.pop("loader_x", None) if n.get("pos") is not None and shift and at is not None and abs(n["pos"][0] - at) < 1: n["pos"][0] += shift @@ -824,7 +921,12 @@ def size_node(self, n): rows = max(len(sock), len(n.get("outputs") or []), 1) start = rows * G.SLOT + 6 fixed = sum(G.WIDGET for x in names if x not in grow) - h = max(h, start + fixed + TEXT_MIN_H * len(grow)) + # a one-line text in a field that is not a prompt (an expression, a pattern) gets the smallest field the + # frontend makes (nodesize.MULTILINE_H); a longer line scrolls in it (the skill author: as small as its + # content needs, a field never larger than needed) + vals = dict(zip(names, n.get("widgets_values") or [])) if isinstance(n.get("widgets_values"), list) else {} + short = [x for x in grow if x not in PROMPT_FIELDS and isinstance(vals.get(x), str) and "\n" not in vals[x]] + h = max(h, start + fixed + TEXT_MIN_H * (len(grow) - len(short)) + nodesize.MULTILINE_H * len(short)) # Nodes 2.0 draws a node taller than the legacy renderer: one margin for every type (layout_params.json) if n.get("type") not in {"Reroute"} | NOTE_TYPES: h += P["VUE_MARGIN"] @@ -1153,15 +1255,13 @@ def about(f, b): continue out.append(f"\n## {v['shown']} ({t})" + (f" ×{v['count']}" if v["count"] > 1 else "")) seen = set() - for f, h, b in hits[:6]: + # every line, uncut: a cut line hid the half of an example that says where the node goes + for f, h, b in hits: key = (f, b) if key in seen: continue seen.add(key) - body = b if len(b) <= 600 else b[:600] + " …" - out.append(f"- {f} — {h}:\n " + body.replace("\n", "\n ")) - if len(hits) > 6: - out.append(f"- ({len(hits) - 6} more: grep references/ for {v['shown']})") + out.append(f"- {f} — {h}:\n " + b.replace("\n", "\n ")) if len(out) == 2: out.append("(no line of references/ names a node on this canvas)") return out @@ -1214,16 +1314,36 @@ def upstream(nid, typ): pos = src(cond_at, "positive") or src(cond_at, "conditioning") model_at = guider or sid mchain = upstream(model_at, "MODEL") + # a ControlNet that changes the model (it takes a MODEL_PATCH from Load Model Patch) is not part of the model row + # (readable-form.md, The usual form): it stands just left of the sampler, like Apply ControlNet + patch_cn = [x for x in mchain if any(i.get("type") == "MODEL_PATCH" for i in cv.node(x).get("inputs") or [])] + mchain = [x for x in mchain if x not in patch_cn] + + def decoders_from(nid, depth=3): + # the decoders a sampler's latent reaches, through nodes that are not samplers (an AV latent split, …) + found, todo, seen = [], [(nid, 0)], {nid} + while todo: + cur, d = todo.pop(0) + for n in outs_of(cur): + if n["id"] in seen or is_sampler(n): + continue + seen.add(n["id"]) + if any(i.get("type") == "VAE" for i in n.get("inputs") or []) \ + and "LATENT" not in {o.get("type") for o in n.get("outputs") or []}: + found.append(n) + elif d + 1 < depth: + todo.append((n["id"], d + 1)) + return found decodes = [n for n in outs_of(sid) if "LATENT" not in {o.get("type") for o in n.get("outputs") or []} and any(i.get("type") == "VAE" for i in n.get("inputs") or [])] dec = decodes[0]["id"] if decodes else None + far_decs = [] if dec else decoders_from(sid) outs = [n for n in outs_of(dec) if is_output_node(cv, n)] if dec else [] save = next((n["id"] for n in outs if "Compare" not in n.get("type", "")), None) compare = next((n["id"] for n in outs if "Compare" in n.get("type", "")), None) - vae = src(dec, "vae") if dec else None - vae_only_decode = vae and cv.is_loader(cv.node(vae)) and all( - any(i.get("type") == "VAE" and src(t["id"], i.get("name")) == vae for i in t.get("inputs") or []) and t["id"] == dec - for t in outs_of(vae)) + vae = src(dec, "vae") if dec else (src(far_decs[0]["id"], "vae") if far_decs else None) + dec_ids = {dec} if dec else {n["id"] for n in far_decs} + vae_only_decode = vae and cv.is_loader(cv.node(vae)) and all(t["id"] in dec_ids for t in outs_of(vae)) out = [f"# the usual form around {sid} (readable-form.md, \"The usual form\"); paste into the plan and adjust", f"put {sid} origin", f"inputs {sid}" + ("" if not guider else f" # {guider} is the guider: its conditioning enters it horizontally")] @@ -1270,7 +1390,37 @@ def upstream(nid, typ): out += [f"block model_{sid} {' '.join(mchain)}", f"row {' '.join(mchain)}", f"put model_{sid} above {anchor} right # the model row above the encoders; its wire may slant"] if vae and vae_only_decode and vae not in mchain: - out.append(f"put {vae} above {sid} # Load VAE used only by the decoder") + out.append(f"put {vae} above {sid} # Load VAE used only by the decoder: above the sampler") + for cn in patch_cn: + lp = next((l["origin_id"] for l in links if l["target_id"] == cn + and next((i for i in cv.node(cn).get("inputs") or [] if i.get("name") == l["target_input"]), {}).get("type") == "MODEL_PATCH"), None) + if guider: + out.append(f"# {cn} changes the model as a ControlNet: with a guider ({guider}) its place is not drafted here; " + f"place it by relations, like Apply ControlNet before the guider") + continue + if src(sid, "model") != cn: + out.append(f"# {cn} changes the model as a ControlNet: it goes last in the model chain, wired into {sid}.model " + f"(rewire in the build when the source shows the nodes after it do not write the same setting), " + f"then run core again") + continue + neg = src(sid, "negative") + lat = src(sid, "latent_image") + # like Apply ControlNet: just left of the sampler, the text encoders left of it, the positive level (it passes + # behind the ControlNet), its Load Model Patch below the encoders, the latent below the ControlNet + out = [x for x in out if not x.startswith(f"inputs {sid}")] + out.append(f"put {cn} left {sid} wire # {cn} changes the model as a ControlNet: just left of {sid}") + if lat: + out.append(f"put {lat} below {cn} right") + if pos: + pl = next(l for l in links if l["target_id"] == sid and l["target_input"] == "positive") + out += [f"put {pos} left {cn} top", f"level {pos}.{pl['origin_slot']} {sid}.positive move {pos}"] + if neg and neg != pos: + out.append(f"put {neg} below {pos} right") + if lp: + out.append(f"put {lp} below {neg if neg and neg != pos else pos or cn} right # its Load Model Patch") + # the model row is placed against the encoders: after them + mlines = [x for x in out if x.startswith(("block model_", "row ", "put model_"))] + out = [x for x in out if x not in mlines] + mlines if dec: out.append(f"put {dec} right {sid} wire") else: @@ -1285,12 +1435,27 @@ def upstream(nid, typ): if compare: out.append(f"# {compare} (Compare) is not placed here: where its wires need the fewest Reroutes, not between " f"the decoder and Save Image") + # the Layout examples that name a node of this draft, uncut, next to it: the draft is the usual form, the examples + # say how it was placed in real workflows (read them before adjusting the draft) + ids = {sid, *mchain, *patch_cn, *([vae] if vae else []), *([dec] if dec else []), *([save] if save else []), + *([pos] if pos else []), *([guider] if guider else [])} + types = {cv.node(i).get("type"): (cv.oi.get(cv.node(i).get("type")) or {}).get("display_name") or cv.node(i).get("type") + for i in ids if i in cv.nodes} + ex = [] + for h, b in _guide_pieces(REFS / "examples.md") if (REFS / "examples.md").is_file() else []: + if not h[:1].isdigit(): + continue # the Layout part of examples.md: its headings are the numbered sections of readable-form.md + if any(re.search(rf"(? 3): + ex.append(f"# examples.md — {h}:\n# " + b.replace("\n", "\n# ")) out.append("# not placed here: Load CLIP, " + (f"{vae} (Load VAE, used by more than the decoder: left of the node that first uses it), " if vae and cv.is_loader(cv.node(vae)) and not vae_only_decode and vae not in mchain else "") + "the size nodes, " + ("the scheduler → split chain (in the sources column), " if guider else "") + "and everything added to the core") + if ex: + out.append("# the Layout examples that name these nodes (examples.md): read them before adjusting the draft") + out += ex return out @@ -1461,11 +1626,25 @@ def _chk_narrow(cv, c): return out +def _only_the_curve_bulges(cv, l, nid): + """A wire whose curve bulges into a node standing in its target's column (a wire running far down into a Compare below + a Save Image), where the straight line from its output to its input passes behind nothing: the spline cannot avoid it, + so it is not a wire behind a node (readable-form.md, Wires).""" + t, n = cv.node(l["target_id"]), cv.node(nid) + if not (t and n and cv.placed(t) and cv.placed(n)): + return False + rt, rn = G.rect(t), G.rect(n) + if min(rt[2], rn[2]) - max(rt[0], rn[0]) <= 0: + return False + pts = cv.wire_pts(l) + return bool(pts) and not G.wire_hits([pts[0], pts[-1]], rn) + + @check_rule("wires behind nodes") def _chk_hidden(cv, c): out = [] nodes, ws = c.nodes, c.ws # noqa: F841 - allh = hidden_wires(cv) + allh = [(l, nid) for l, nid in hidden_wires(cv) if not _only_the_curve_bulges(cv, l, nid)] hw = [(l, nid) for l, nid in allh if crosses_behind(cv, l, nid, allh) or _behind_output_node(cv, f"wire behind a node: x ({l['type']}) passes behind {nid}")] c.count["wires behind nodes"] = len(hw) @@ -1697,6 +1876,10 @@ def _chk_sampler_inputs(cv, c): model = o["id"] else: srcs.append(o["id"]) + # a ControlNet that changes the model stands just left of the sampler (readable-form §1): the other sources stand + # around it (the text encoders left of it, the latent below it), not in one column + if model and any(i.get("type") == "MODEL_PATCH" for i in nodes[model].get("inputs") or []): + continue # a source that also feeds another of them (a VAE Encode whose latent goes into Reference Latent as well) stands # left of it: its wire into that node would go back from the column (not into Conditioning Zero Out and the like, # which a wire may go back into, BACKWARD_OK_TYPES) @@ -1796,6 +1979,18 @@ def _chk_width_and_value_tops(cv, c): if 0 <= gap_v <= V_GAP * 2 and 1 <= dw < H_GAP and cv.is_model_loader(a) and cv.is_model_loader(b): out.append(f"stacked loaders differ in width by {round(dw)}px: the canvas gives a column of loaders one width, but a node " f"next to one is in the way of widening it: {a['id']} and {b['id']}") + # nodes stacked in one column (readable-form.md, section 4): right edges aligned, one width when the widths + # differ by less than SAME_WIDTH_UNDER (the canvas gives it; this names where something was in the way) + # a column: stacked with an edge aligned (the canvas widens only such a column); two nodes of different + # rows that merely stand one above the other are not a column + aligned = abs(ra[2] - rb[2]) < 1 or abs(ra[0] - rb[0]) < 1 + if 0 <= gap_v <= V_GAP + 1 and not (cv.is_model_loader(a) and cv.is_model_loader(b)): + if aligned and 1 <= dw < SAME_WIDTH_UNDER: + out.append(f"stacked nodes differ in width by {round(dw)}px: the canvas gives a column one width, but a node " + f"next to one is in the way of widening it: {a['id']} and {b['id']}") + elif not aligned: + out.append(f"stacked nodes with right edges not aligned ({round(abs(ra[2] - rb[2]))}px): {a['id']} and {b['id']} " + f"(if they are one column, align their right edges; nodes of different rows need not)") # a model loader stacked right on a sampler stands in its column: the two get one width if 0 <= gap_v <= V_GAP + 1 and dw >= 1 and any(cv.is_model_loader(x) and is_sampler(y) for x, y in ((a, b), (b, a))): out.append(f"a loader stacked on a sampler differs from it in width by {round(dw)}px: place one with " @@ -1886,6 +2081,33 @@ def _chk_loader_order(cv, c): if same_stack(cv, m["id"], n["id"], col) and G.rect(n)[1] < G.rect(m)[1]: out.append(f"{k.lower()} loader {n['id']} is above the model loader {m['id']}: " f"the vae and clip loaders stacked in one column go below the model loader") + # in other columns too, a vae or clip loader above the model loader is Bad when their nodes or wires meet (a wire + # from it crosses one from the model loader, or passes behind the model loader). Where nothing meets, which is higher + # does not matter (readable-form.md, Loaders: Fine) + ws = c.ws + + def root(nid): + # the node a wire really comes from, through Reroutes (a rail) + seen = set() + while (c.nodes.get(nid) or {}).get("type") == "Reroute" and nid not in seen: + seen.add(nid) + up = next((x for x in cv.s["links"] if x["target_id"] == nid), None) + if not up: + break + nid = up["origin_id"] + return nid + for m in kinds.get("MODEL", []): + mw = [pts for l, pts in ws if root(l["origin_id"]) == m["id"]] + for k in ("VAE", "CLIP"): + for n in kinds.get(k, []): + if same_stack(cv, m["id"], n["id"], col) or G.rect(n)[1] >= G.rect(m)[1]: + continue + nw = [(l, pts) for l, pts in ws if root(l["origin_id"]) == n["id"]] + meets = any(poly_cross(pa, pb) for _, pa in nw for pb in mw) or \ + any(G.wire_hits(pts, G.rect(m)) for _, pts in nw) + if meets: + out.append(f"{k.lower()} loader {n['id']} is above the model loader {m['id']} and its wires meet the " + f"model loader's (they cross, or pass behind it): put it below the model loader") # vae and clip take either order: Load VAE may stand below the text encoders, below Load CLIP return out @@ -2208,12 +2430,12 @@ def _chk_wide_gap(cv, c): @check_rule("crossings in a gap between columns") def _chk_gap_crossings(cv, c): out = [] - # wires that still cross CROSS_WIDEN times or more inside a gap between columns: the canvas widens such a gap when - # it can; crossing there means the sources stand in another order than the inputs, or far above or below them - for x0, x1, n, oid, tid in column_gaps(cv, GAP_WIDE + 1): + # wires that cross CROSS_WIDEN times or more inside a gap between columns narrower than GAP_WIDE: the plan writes + # gap wide there (or puts the sources in the order of the inputs) + for x0, x1, n, oid, tid in column_gaps(cv): if n >= CROSS_WIDEN: - out.append(f"wires cross {n} times in the gap between {oid} and {tid} (look at the order and height of the " - f"sources: a node centred on its sources column keeps them from crossing)") + out.append(f"wires cross {n} times in the gap between {oid} and {tid}: write `gap wide` on the line that places " + f"{tid} right of {oid} (or put the sources in the order of the inputs so they do not cross)") return out @@ -2548,6 +2770,82 @@ def _chk_idle_reroute(cv, c): return out +@check_rule("rail targets off the rail") +def _chk_rail_target_off_rail(cv, c): + # a rail target wired straight from a rail Reroute far to its left, at another height: the rail ends in a long slanted + # wire instead of a lowering Reroute next to the target (readable-form.md, Wires: a rail gives its targets the value + # through a lowering Reroute) + out = [] + nodes = c.nodes + for l in cv.s["links"]: + o, t = nodes.get(l["origin_id"]), nodes.get(l["target_id"]) + if not o or not t or o.get("type") != "Reroute" or t.get("type") == "Reroute" or not cv.placed(o) or not cv.placed(t): + continue + a, b = cv.out_xy(o["id"], 0), cv.in_xy(t["id"], l["target_input"]) + ro, rt = G.rect(o), G.rect(t) + # a lowering Reroute stands in the column just left of its target: no node stands between them + between = any(cv.placed(m) and m.get("type") not in {"Reroute"} | NOTE_TYPES and m is not t + and G.rect(m)[0] >= ro[2] and G.rect(m)[2] <= rt[0] for m in cv.s["nodes"]) + if abs(a[1] - b[1]) >= 1 and between: + out.append(f"rail target without a lowering Reroute ({round(b[0] - a[0])}px across, {round(b[1] - a[1])}px down): " + f"{o['id']} → {lname(cv, l)}") + return out + + +@check_rule("rail heads away from their rail") +def _chk_rail_head_off_rail(cv, c): + # a node that takes no wire in (a loader, a value node, Load Image) heading a rail stands at the rail's height + # (readable-form.md, Wires): a Reroute raising or lowering its output to the rail means the node stands elsewhere + out = [] + nodes = c.nodes + wired_in = {l["target_id"] for l in cv.s["links"]} + for l in cv.s["links"]: + n, r = nodes.get(l["origin_id"]), nodes.get(l["target_id"]) + if not n or not r or n.get("type") == "Reroute" or r.get("type") != "Reroute" or n["id"] in wired_in \ + or cv.is_model_loader(n) or not cv.placed(n) or not cv.placed(r): + continue + dy = cv.out_xy(r["id"], 0)[1] - cv.out_xy(n["id"], l["origin_slot"])[1] + # the exception: the source's wire into a node right of it is level (it cannot also stand at the rail's height) + held = any(m["origin_id"] == n["id"] and nodes.get(m["target_id"], {}).get("type") != "Reroute" + and cv.placed(nodes.get(m["target_id"], {})) + and abs(cv.out_xy(n["id"], m["origin_slot"])[1] - cv.in_xy(m["target_id"], m["target_input"])[1]) < 1 + for m in cv.s["links"]) + if abs(dy) >= 1 and not held: + out.append(f"rail head away from its rail ({round(dy)}px): place {n['id']} at the height the rail runs, " + f"with no Reroute raising or lowering it: {n['id']}") + return out + + +@check_rule("output nodes stepped where the flow ends") +def _chk_output_stepped_at_end(cv, c): + # an output node stands on its source's line when the flow ends there; it steps down only when the flow goes on past + # it (readable-form.md, Flow and position) + out = [] + nodes = c.nodes + stepped = {i for u in cv.s.get("stepped") or [] for i in u} + for nid in stepped: + n = nodes.get(nid) + if not n or not is_output_node(cv, n) or not cv.placed(n): + continue + for l in cv.s["links"]: + if l["target_id"] != nid: + continue + def ends_on(tid, seen=()): + # the nodes a wire reaches, through Reroutes + t = nodes.get(tid) + if not t or tid in seen: + return [] + if t.get("type") != "Reroute": + return [t] + return [x for m in cv.s["links"] if m["origin_id"] == tid for x in ends_on(m["target_id"], seen + (tid,))] + others = [t for m in cv.s["links"] if m["origin_id"] == l["origin_id"] and m["target_id"] != nid + for t in ends_on(m["target_id"]) if not is_output_node(cv, t)] + if not others: + out.append(f"output node stepped down where the flow ends: put {nid} right of {l['origin_id']} on its wire " + f"(step only when the flow goes on past it): {nid}") + return out + + @check_rule("rails that can run at the output height") def _chk_rail_at_output(cv, c): out = [] @@ -2899,9 +3197,12 @@ def _chk_loader_raise(cv, c): # a loader whose other output goes level into the node right of it (a Load LoRA right of Load Checkpoint): at # its output height this rail would run behind that node, so it goes down with a Reroute right after the loader # (the skill author) - if any(l["origin_id"] == o["id"] and l["origin_slot"] != slot and cv.placed(nodes.get(l["target_id"]) or {}) + # (readable-form.md, Wires: the one exception) a source whose wire into a node right of it is level, from this + # output or another (a Load VAE beside the VAE Encode it feeds, its vae also carried on a rail) cannot stand at + # the rail's height either + if any(l["origin_id"] == o["id"] and (nodes.get(l["target_id"]) or {}).get("type") != "Reroute" + and cv.placed(nodes.get(l["target_id"]) or {}) and abs(cv.out_xy(o["id"], l["origin_slot"])[1] - cv.in_xy(l["target_id"], l["target_input"])[1]) < 1 - and G.rect(nodes[l["target_id"]])[1] <= ay <= G.rect(nodes[l["target_id"]])[3] for l in cv.s["links"]): continue rx, ox1 = G.rect(r)[0], G.rect(o)[2] @@ -3088,11 +3389,11 @@ def _stage_entry(cv, sid, nodes): return None -@check_rule("result wire level, latent into the sampler slants") +@check_rule("result wire slants into the stage's chain") def _chk_stage_entry_level(cv, c): - """readable-form §1: a stage taking the previous stage's result whose conditioning does not enter level: its own - chain moves to its sampler so the latent enters level, and the wire from the previous stage into that chain is the - one that slants.""" + """readable-form §1: a stage taking the previous stage's result with no node taking the conditioning just left of its + sampler (its conditioning does not enter level from there): the chain stands on the eye line, the wire from the + previous stage into the chain is horizontal, and the chain's latent into the sampler slants.""" out = [] for n in cv.s["nodes"]: # a sampler taking its sources in one column (SamplerCustomAdvanced: the latent last) has its own level wire @@ -3110,11 +3411,11 @@ def _chk_stage_entry_level(cv, c): continue a, b = cv.out_xy(lat["origin_id"], lat["origin_slot"]), cv.in_xy(n["id"], lat["target_input"]) ra, rb = cv.out_xy(lk["origin_id"], lk["origin_slot"]), cv.in_xy(lk["target_id"], lk["target_input"]) - if not (a and b and ra and rb) or abs(a[1] - b[1]) < 1 or abs(ra[1] - rb[1]) >= 1: + if not (a and b and ra and rb) or abs(ra[1] - rb[1]) < 1: continue - out.append(f"result wire level, latent into the sampler slants: {lname(cv, lk)} is horizontal while " - f"{lname(cv, lat)} ({round(b[1] - a[1])}px) slants; move the stage's chain to {n['id']} so its latent " - f"enters level, and let the wire from the previous stage slant") + out.append(f"result wire slants into the stage's chain: {lname(cv, lk)} ({round(rb[1] - ra[1])}px) slants; put the " + f"stage's chain on the eye line (top edges on {n['id']}'s) so that wire is horizontal, and let " + f"{lname(cv, lat)} slant into the sampler") return out @@ -3179,6 +3480,10 @@ def _chk_one_line_text(cv, c): # the sampler → decode → save wires. The skill author's LTX layouts set the decode midway between the video and # audio latents: a liking, not the form to write "main flow off its line": lambda cv, l: True, + "rail targets off the rail": lambda cv, l: True, + "crossings in a gap between columns": lambda cv, l: True, + "rail heads away from their rail": lambda cv, l: True, + "output nodes stepped where the flow ends": lambda cv, l: True, "core nodes the replacement list replaces": lambda cv, l: True, "custom nodes the replacement list turns into core": lambda cv, l: True, } @@ -3866,10 +4171,12 @@ def gap_opt(opt): """The spacing a plan may ask for: none (the standard gap) or `gap wide` (between columns with many wires).""" if "gap" not in opt: return None + if opt["gap"] == "wide": + return "wide" if HAND_PLACING_FOR_TESTS: - return "wide" if opt["gap"] == "wide" else num(opt["gap"], "gap") - raise Stop(f"there is no gap {opt['gap']}: the canvas keeps every gap, and widens the gap between two columns " - f"where wires cross in it") + return num(opt["gap"], "gap") + raise Stop(f"there is no gap {opt['gap']}: the canvas keeps every gap; between two columns where wires cross 3 " + f"times or more, write gap wide") def plan_groups(cv): @@ -3986,6 +4293,8 @@ def put_rel(cv, ids, how, ref_ids, align, gap): def _put_rel(cv, ids, how, ref_ids, align, gap): + # placed again: a step written before for these nodes no longer holds + cv.s["stepped"] = [u for u in cv.s.get("stepped") or [] if not set(u) & set(ids)] w, h = cv.unit_size(ids) rb = ref_box(cv, ref_ids) if how in ("right", "left"): @@ -4023,7 +4332,7 @@ def _put_rel(cv, ids, how, ref_ids, align, gap): elif how in ("below", "above"): g = side_gap(cv, ids, how, ref_ids, gap) y0 = rb[3] + g if how == "below" else rb[1] - g - h - align = align or "left" + align = align or "right" # a column reads as one by its right edges (readable-form.md, section 4) if align == "left": x0 = rb[0] elif align == "right": @@ -4930,7 +5239,7 @@ def _op_stack(cv, work, args): units = [cv.unit(t) for t in pos] if not units: raise Stop("stack ...") - al = "right" if "right" in opt else "left" + al = "left" if "left" in opt else "right" gap = gap_opt(opt) if gap == "wide": raise Stop("gap wide is only between columns (put right, row, inputs)") @@ -5493,6 +5802,13 @@ def _op_review(cv, work, args): raise Stop(f"\"{a}\": a row is left only with a quoted line of {', '.join(REVIEW_RULE_FILES)} (a Fine " f"line, or the bold line of the rule the fix would break), written as it is in the file " f"between quotes. If no such line applies, fix the row") + # every left row went back to the reviewer, who said whether the form is that row's Bad (references/review.md) + reply = re.search(r"reviewer:\s*(not bad|bad|not reached)", a, re.I) + if not reply: + raise Stop(f"\"{a}\": a left row goes back to the same reviewer first; add its reply after your answer as " + f"\"reviewer: not Bad\" (or \"reviewer: not reached\" when it cannot be reached)") + if reply.group(1).lower() == "bad": + raise Stop(f"\"{a}\": the reviewer says the form is that row's Bad: it is not left. Fix it") seen = (work.cfg.get("review_render") or {}).get(cv.name) if any(r["answer"].lower().startswith("fixed") for r in rows) and seen == now: raise Stop("rows say \"fixed\", but the workflow is the same as in the picture the reviewer saw: fix it, export again, then register") @@ -6204,6 +6520,11 @@ def do_layout(cv, work, args): if t != shown and not (may_say_what(cv, n) and t.startswith(shown + ":")): n.pop("title", None) cv.size_node(n) + if "col_base" in n: + # a width the column alignment gave is not the node's own: start again from its own width + n["size"][0] = n.pop("col_base") + n.pop("col_shift", None) + n.pop("col_x", None) widened = n.pop("size_min", None) is not None if n.pop("width_set", None) or widened or n.get("type") == "CLIPTextEncode" or cv.is_negative_prompt(n): # (a CLIP Text Encode is sized again too: whether it only feeds SAM3 is known once it is wired) @@ -6512,7 +6833,7 @@ def written(i): cv.same_loader_width() for n in cv.s["nodes"]: if n.get("size") and before_w.get(n["id"]) != n["size"][0]: - beyond.append(f" width {n['id']}: {before_w.get(n['id'])} -> {n['size'][0]} (loader widths aligned)") + beyond.append(f" width {n['id']}: {before_w.get(n['id'])} -> {n['size'][0]} (widths aligned)") cv.save() if beyond: cv.out.append("done by the canvas beyond the lines:") @@ -6524,6 +6845,11 @@ def written(i): soft = soft_problems(cv) if soft: cv.out += violations(soft) + # the last line names what is left, so a reply cut to its last line still says which nodes break which rule + left = [ln.strip() for ln in (hard or []) + (soft or [])] + if left: + names = [f"{ln.rsplit(': ', 1)[-1] if ': ' in ln else ''} ({ln.split(':')[0].split('(')[0].strip()})" for ln in left] + cv.out.append(f"left to fix ({len(left)}): " + "; ".join(names)) return cv.out @@ -6566,6 +6892,7 @@ def violations(lines, how="fix them in the plan"): (("groups overlap", "wire over the title", "node over the title", "node overlapping group"), "A group holds one large function"), (("loader is above the model loader",), "A loader stands in the column left"), + (("stacked nodes differ in width", "stacked nodes with right edges"), "Nodes stacked in one column"), (("rail order differs", "rail runs above the", "loader rail runs below", "stacked loaders differ"), "A wire is drawn directly"), # its rail line holds the order (("loader away from its first user", "vae loader"), "A loader stands in the column left"), @@ -6574,7 +6901,9 @@ def violations(lines, how="fix them in the plan"): (("overlap:", "is directly below"), "No node is hidden"), (("narrow gap", "empty band", "gap inside a column", "wide gap to a wired neighbour", "uneven spacing", "times in the gap"), "Wires show and nothing is packed"), - (("wire behind a node", "Reroute", "single value carried", "rail needs no raising", "rails too close"), + (("output node stepped down",), "An output node (Save, Preview"), + (("wire behind a node", "Reroute", "single value carried", "rail needs no raising", "rails too close", + "rail head away"), "A wire is drawn directly"), (("non-horizontal wire", "slanted wire", "reference wire level", "no wire level into"), "A wire is horizontal when it can be"), (("image into",), "Other chains have their own rows"), @@ -6665,7 +6994,7 @@ def finish(cv): cv.same_loader_width() for n in cv.s["nodes"]: if n.get("size") and before.get(n["id"]) != n["size"][0]: - cv.out.append(f"width {n['id']}: {before.get(n['id'])} → {n['size'][0]} (loader widths aligned)") + cv.out.append(f"width {n['id']}: {before.get(n['id'])} → {n['size'][0]} (widths aligned)") local_report(cv, cv.before) cv.save() return cv.out or ["nothing changed"] @@ -6972,9 +7301,10 @@ def lane_nodes(lanes): def rail_raise_x(cv, ox1): """x of a raising Reroute: its left edge on the left edge of the column right of the source (as in hand-made layouts), - or half the column gap right of the source when there is no such column.""" + or half the column gap right of the source when there is no such column. The column may stand up to a wide gap away + (`gap wide`), as for a lowering Reroute.""" lefts = [G.rect(m)[0] for m in cv.s["nodes"] if cv.placed(m) and m.get("type") != "Reroute" - and ox1 + H_GAP / 3 <= G.rect(m)[0] <= ox1 + H_GAP + REROUTE_W / 2] + and ox1 + H_GAP / 3 <= G.rect(m)[0] <= ox1 + GAP_WIDE + REROUTE_W / 2] return min(lefts) if lefts else ox1 + H_GAP / 2 diff --git a/skills/comfyui-readable-node/scripts/layout_params.json b/skills/comfyui-readable-node/scripts/layout_params.json index 0553fb0..86b2fa0 100644 --- a/skills/comfyui-readable-node/scripts/layout_params.json +++ b/skills/comfyui-readable-node/scripts/layout_params.json @@ -15,13 +15,13 @@ "GAP_WIDE": { "value": 120, "unit": "px", - "meaning": "Gap the canvas gives two columns when wires cross each other CROSS_WIDEN times or more in the gap between them (the agent does not choose it)", + "meaning": "Gap the plan writes (gap wide) between two columns where wires cross each other CROSS_WIDEN times or more; the check names such a gap", "source": "Twice H_GAP. The skill author (nomadoor): a crowded gap is about twice the usual" }, "CROSS_WIDEN": { "value": 3, "unit": "crossings", - "meaning": "Number of wire crossings inside the gap between two columns from which the canvas widens that gap to GAP_WIDE", + "meaning": "Number of wire crossings inside the gap between two columns from which the check names that gap (write gap wide)", "source": "The same measurement: gaps with 3 or more crossings are about 90 wide in hand-made layouts. Decided by the skill author (nomadoor)" }, "RAIL_GAP": { diff --git a/skills/comfyui-readable-node/scripts/report.py b/skills/comfyui-readable-node/scripts/report.py index 9b65f30..0c344ed 100644 --- a/skills/comfyui-readable-node/scripts/report.py +++ b/skills/comfyui-readable-node/scripts/report.py @@ -205,7 +205,7 @@ def _x_put(S, a, x, d): "wire": "間の線が水平になる高さで", "left": "左端をそろえて", "right": "右端をそろえて", "center": "左右の真ん中をそろえて"} if align is None: # put right|left without a word: the canvas made the wire horizontal when the two are wired, otherwise aligned the tops - align = ("wire" if x.get("wired") else "top") if how in ("right", "left") else "left" + align = ("wire" if x.get("wired") else "top") if how in ("right", "left") else "right" if S.ja: g = f"(間隔 {opt['gap']} px)" if "gap" in opt else "" return f"{u} を {r} {where_ja}に、{al_ja.get(align, '')}置きました{g}" @@ -230,7 +230,7 @@ def _x_row(S, a, x, d): def _x_stack(S, a, x, d): pos, opt = _opts(a, keyed=("below", "gap")) units = [p for p in pos if p not in ("left", "right")] - side = "right" if "right" in pos else "left" + side = "left" if "left" in pos else "right" start = S.L(f", starting below {S.unit(opt['below'])}", f"({S.unit(opt['below'])} の下から)") if "below" in opt else "" if S.ja: return f"{S.many(units, 4, d=d)} を上から下へ一列に積みました({'右端' if side == 'right' else '左端'}をそろえて){start}" diff --git a/tests/test_canvas.py b/tests/test_canvas.py index d99b584..abc1b2a 100644 --- a/tests/test_canvas.py +++ b/tests/test_canvas.py @@ -1047,11 +1047,124 @@ def test_loader_is_not_widened_past_the_node_below_it(self): self.assertLess(cv.node("10")["size"][0], C.LOADER_MIN_W) self.assertNotIn("loader_base", cv.node("10")) + def test_put_below_and_stack_align_right_edges_by_default(self): + # a column reads as one by its right edges: put above/below and stack align right edges unless told otherwise + self.do("put 13 origin") + self.do("put 27 above 13") + r, q = G.rect(self.cv().node("27")), G.rect(self.cv().node("13")) + self.assertEqual(r[2], q[2]) + self.do("stack 26 22 below 13") + a, b = G.rect(self.cv().node("26")), G.rect(self.cv().node("22")) + self.assertEqual((a[2], b[2]), (q[2], q[2])) + self.do("put 27 above 13 left") + self.assertEqual(G.rect(self.cv().node("27"))[0], q[0]) + + def test_a_column_takes_one_width_when_the_widths_differ_by_less_than_60(self): + # nodes stacked in one column, right edges aligned: the narrower takes the wider width (it widens to the left); + # a node 60px or more narrower keeps its own width + self.do("put 13 origin") + w13 = self.cv().node("13")["size"][0] + self.do("put 26 above 13") + cv = self.cv() + a, b = cv.node("26"), cv.node("13") + self.assertLess(abs(a["size"][0] - w13), 60) + self.assertEqual(a["size"][0], b["size"][0]) + self.assertEqual(G.rect(a)[2], G.rect(b)[2]) + self.do("put 9 below 13") + cv = self.cv() + self.assertGreaterEqual(cv.node("9")["size"][0] - cv.node("13")["size"][0], 60) + + def test_an_output_node_stepped_down_where_the_flow_ends_is_named(self): + # Save Image after VAE Decode, where nothing goes on: it stands on the wire, not a step below + self.do("put 13 origin") + self.do("put 8 right 13") + self.do("put 9 right 8 step") + self.assertTrue([x for x in C.full_check(self.cv())[0] if x.startswith("output node stepped down") and x.endswith(": 9")]) + self.do("put 9 right 8") + self.assertFalse([x for x in C.full_check(self.cv())[0] if x.startswith("output node stepped down")]) + + def test_a_value_node_heading_a_rail_away_from_it_is_named(self): + # a node that takes no wire in heads its rail at the rail's height, as a loader does + self.do("add PrimitiveFloat v") + self.do("link v.0 26.guidance") + plan = ["put 13 origin", "put 26 left 13", "put v left 26", "rail v.0 below 13 to 26.guidance"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + self.assertTrue([x for x in C.full_check(self.cv())[0] if x.startswith("rail head away from its rail") and x.endswith(": v")]) + + def test_a_short_text_in_a_field_that_is_not_a_prompt_gets_half_a_text_area(self): + # Extract Text's pattern: a one-line pattern gets the frontend's smallest field; several lines, a full text area + self.do("add RegexExtract r") + self.do('set r regex_pattern="x"') + short = self.cv().node("r")["size"][1] + f = self.dir / "two_lines.txt" + f.write_text("a\nb", encoding="utf-8") + self.do(f"set r regex_pattern=@{f}") + self.assertEqual(self.cv().node("r")["size"][1] - short, C.TEXT_MIN_H - C.nodesize.MULTILINE_H) + + def test_a_column_widens_a_node_to_the_next_wider_within_60_not_only_the_widest(self): + # a text encoder (400) above FluxGuidance (270) above BasicGuider (225): the guider takes 270, as a Conditioning + # Zero Out takes the Empty Latent's width; the encoder keeps its own + self.do("put 42 origin") + self.do("stack 42 26 22") + cv = self.cv() + self.assertEqual([cv.node(i)["size"][0] for i in ("42", "26", "22")], [400, 270, 270]) + + def test_widening_a_column_to_the_right_keeps_the_gap_to_the_next_column(self): + # a left-aligned column (BasicGuider 225 over FluxGuidance 270) with a node right of the narrower one: the + # narrower is not widened into the gap between the columns + plan = ["put 22 origin", "put 26 below 22 left", "put 13 right 22"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + cv = self.cv() + self.assertGreaterEqual(G.rect(cv.node("13"))[0] - G.rect(cv.node("22"))[2], C.H_GAP) + + def test_a_curve_bulging_into_the_node_above_its_target_is_not_a_wire_behind(self): + # VAE Decode's image into a Save Image far below another one in the next column: the straight line passes behind + # nothing, only the curve bulges into the upper Save Image + self.do("add SaveImage s2") + self.do("link 8.0 s2.images") + plan = ["put 8 origin", "put 9 right 8 top", "put s2 below 9 left gap 300"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + cv = self.cv() + l = next(x for x in cv.s["links"] if x["target_id"] == "s2") + self.assertIn((l["id"], "9"), [(x["id"], nid) for x, nid in C.hidden_wires(cv)]) + self.assertFalse([x for x in C.full_check(cv)[0] if "passes behind 9" in x]) + + def test_widening_a_column_keeps_a_wide_gap(self): + # as above, with `gap wide` between the columns: the gap stays wide + plan = ["put 22 origin", "put 26 below 22 left", "put 13 right 22 gap wide"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + cv = self.cv() + self.assertGreaterEqual(G.rect(cv.node("13"))[0] - G.rect(cv.node("22"))[2], C.GAP_WIDE) + + def test_a_loader_left_of_a_node_widens_to_the_left_and_keeps_its_gap(self): + # Load CLIP placed left of its text encoder, then the loaders' width grows (another loader is wider): widening the + # CLIP loader to the right would eat the gap to the encoder, so it widens to the left + plan = ["put 6 origin", "put 11 left 6", "put 12 above 6 right"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + cv = self.cv() + cv.node("12").pop("loader_base", None) + cv.node("12")["size"][0] = 360 + cv.node("12")["width_set"] = True + cv.same_loader_width() + clip, enc = cv.node("11"), cv.node("6") + self.assertEqual(clip["size"][0], 360) + self.assertGreaterEqual(G.rect(enc)[0] - G.rect(clip)[2], C.H_GAP) + + def test_a_raising_reroute_stands_on_the_left_edge_of_the_column_across_a_wide_gap(self): + # Load VAE left of the sampler with `gap wide`, its wire raised to a rail above the sampler: the Reroute stands on + # the sampler's left edge, not in the middle of the gap + plan = ["put 13 origin", "put 8 right 13 wire", "put 10 left 13 gap wide", "rail 10.0 above 13 to 8.vae"] + self.do(f"layout {self.write_plan(chr(10).join(plan))}") + cv = self.cv() + rr = [n for n in cv.s["nodes"] if n.get("type") == "Reroute" and G.rect(n)[0] < G.rect(cv.node("13"))[0] + 1] + self.assertTrue(rr) + self.assertEqual(min(G.rect(n)[0] for n in rr), G.rect(cv.node("13"))[0]) + def test_load_vae_above_the_sampler_keeps_its_left_edge_and_the_layout_is_stable(self): # Load VAE above the sampler, both 270 wide (narrower than the loader minimum): widening it to the left would put # its left edge off the sampler's, and to the right past the sampler, so it is not widened self.do("put 13 origin") - self.do("put 10 above 13") + self.do("put 10 above 13 left") cv = self.cv() for i in ("10", "13"): cv.node(i)["size"][0] = 270 @@ -1103,12 +1216,21 @@ def test_open_names_the_deprecated_nodes(self): out = C.run_cmd(C.Work(d), f"open {SUBJECT} {OI}") self.assertFalse([l for l in out if l.startswith("deprecated: ")]) + def test_gap_wide_is_written_in_a_plan(self): + # a gap where wires cross three times or more is named by the check and made wide in the plan + C.HAND_PLACING_FOR_TESTS = False + try: + self.do(f"layout {self.write_plan('put 12 origin' + chr(10) + 'put 30 right 12 gap wide' + chr(10), why=False)}") + cv = self.cv() + self.assertGreaterEqual(G.rect(cv.node("30"))[0] - G.rect(cv.node("12"))[2], C.GAP_WIDE) + finally: + C.HAND_PLACING_FOR_TESTS = True + def test_a_plan_places_without_numbers(self): C.HAND_PLACING_FOR_TESTS = False try: for plan, word in (("put 12 origin\nput 30 right 12\nmove 30 0 40\n", "there is no move"), ("put 12 origin\nput 30 right 12 gap 100\n", "there is no gap 100"), - ("put 12 origin\nput 30 right 12 gap wide\n", "there is no gap wide"), ("put 12 origin\nput 30 right 12\nwidth 12 30\n", "there is no width")): with self.assertRaises(C.Stop) as e: self.do(f"layout {self.write_plan(plan, why=False)}") @@ -1469,7 +1591,7 @@ def test_core_prints_the_usual_form(self): out = self.do("core 13") self.assertIn("inputs 13 # 22 is the guider: its conditioning enters it horizontally", out) self.assertIn("put 26 left 22 wire", out) - self.assertIn("put 10 above 13 # Load VAE used only by the decoder", out) + self.assertIn("put 10 above 13 # Load VAE used only by the decoder: above the sampler", out) self.assertIn("put 8 right 13 wire", out) self.do(f"layout {self.write_plan(chr(10).join(l for l in out if not l.startswith('#')))}") self.assertEqual(C.hard_problems(self.cv()), []) @@ -1901,7 +2023,8 @@ def test_a_load_clip_above_a_node_that_is_not_a_sampler_takes_the_loaders_width( cv = self.cv() cv.same_loader_width() widest = max(cv.node(i)["size"][0] for i in ("12", "10")) - self.assertGreater(widest, cv.node("t")["size"][0]) + # t stands in 11's column and is less than 60px narrower: the column takes one width + self.assertEqual(cv.node("t")["size"][0], widest) self.assertEqual(cv.node("11")["size"][0], widest) # written right-aligned with t: it widens to the left and keeps that edge self.assertEqual(G.rect(cv.node("11"))[2], G.rect(cv.node("t"))[2]) @@ -1911,21 +2034,20 @@ def test_a_load_clip_above_a_node_that_is_not_a_sampler_takes_the_loaders_width( cv.same_loader_width() self.assertEqual(cv.node("11")["size"][0], widest) - def test_a_stage_whose_result_wire_is_level_but_whose_latent_slants_is_fixed_in_the_plan(self): - # the previous stage's image (out of VAE Decode 8) enters the stage's VAE Encode level, while the latent into the - # stage's KSampler slants: the stage's chain is the one to move + def test_a_stage_whose_result_wire_slants_into_its_chain_is_named(self): + # no node taking the conditioning stands just left of the stage's KSampler: the chain stands on the eye line, the + # previous stage's image (out of VAE Decode 8) enters the stage's VAE Encode level, and the latent slants self.do("add VAEEncode e") self.do("add KSampler k") self.do("link 8.0 e.pixels 10.0 e.vae e.0 k.latent_image") self.do("put 8 origin") self.do("put e right 8") - self.do("level 8.IMAGE e.pixels move e") self.do("put k right e") - self.do("move k 0 80") - chk = next(f for n, f in C.CHECKS if n == "result wire level, latent into the sampler slants") + self.do("move e 0 60") + chk = next(f for n, f in C.CHECKS if n == "result wire slants into the stage's chain") cv = self.cv() - self.assertTrue(chk(cv, C._CheckCtx(cv)), "the latent slants while the result wire is level") - self.do("level e.LATENT k.latent_image move e") + self.assertTrue(chk(cv, C._CheckCtx(cv)), "the result wire slants") + self.do("level 8.IMAGE e.pixels move e") cv = self.cv() self.assertEqual(chk(cv, C._CheckCtx(cv)), []) diff --git a/tests/test_check_fixes.py b/tests/test_check_fixes.py new file mode 100644 index 0000000..67a7fca --- /dev/null +++ b/tests/test_check_fixes.py @@ -0,0 +1,94 @@ +"""Tests that what a check tells the agent to write can be written and makes that check line go away +(the check-fix tests). Python standard library only. + +Each test builds the form a check names, writes the plan line the check's own words give, runs the layout again, and +checks that the layout does not stop and that the line is gone. A check that names a plan line gets a test here when it +is added or changed. + +Usage: python3 -m unittest discover -s tests +""" +import re +import shutil +import tempfile +import unittest +from pathlib import Path + +import test_canvas as T + +C, G = T.C, T.G + + +class CheckFixTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.base = Path(tempfile.mkdtemp()) + C.run_cmd(C.Work(cls.base), f"open {T.SUBJECT} {T.OI}") + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.base) + + def setUp(self): + C.HAND_PLACING_FOR_TESTS = False # as the agent writes plans: no numbers, no move + self.dir = Path(tempfile.mkdtemp()) + for name in ("object_info.json", "src.flat.json", "canvas.config.json"): + shutil.copy(self.base / name, self.dir / name) + self.do("new t") + + def tearDown(self): + C.HAND_PLACING_FOR_TESTS = True + shutil.rmtree(self.dir) + + def do(self, line): + return C.run_cmd(C.Work(self.dir), line) + + def layout(self, lines): + f = self.dir / "plan.txt" + f.write_text("\n".join(lines) + "\n", encoding="utf-8") + return self.do(f"layout {f}") + + def cv(self): + return C.Work(self.dir).current() + + def check_lines(self, start): + return [x for x in C.full_check(self.cv())[0] if start in x] + + def test_write_level_from_one_move(self): + # "slanted wire that one move makes horizontal: … (write level A.out B.in [move X])" + self.do("copy 13 8 9 27 10") + self.do("link 13.0 8.samples 8.0 9.images 10.0 8.vae 27.0 13.latent_image") + plan = ["put 13 origin", "put 8 right 13 wire", "put 9 right 8 bottom"] + self.layout(plan) + named = self.check_lines("one move makes horizontal") + self.assertTrue(named, "the check names the slanted wire") + fix = re.search(r"write (level [^)]+)\)", named[0]).group(1) + self.layout(plan + [fix]) + self.assertFalse(self.check_lines("one move makes horizontal: 8.IMAGE")) + + def test_write_gap_wide_where_wires_cross(self): + # "wires cross N times in the gap between A and B: write `gap wide` on the line that places B right of A" + self.do("copy 25 22 16 17 27 13") + self.do("link 25.0 13.noise 22.0 13.guider 16.0 13.sampler 17.0 13.sigmas 27.0 13.latent_image") + plan = ["put 27 origin", "stack 27 17 16 22 25", "put 13 right 22 top"] + self.layout(plan) + named = self.check_lines("times in the gap between") + self.assertTrue(named, "the check names the gap") + m = re.search(r"between (\S+) and (\S+):", named[0]) + self.layout(plan[:-1] + [plan[-1] + " gap wide"]) + self.assertFalse(self.check_lines(f"times in the gap between {m.group(1)} and {m.group(2)}")) + + def test_write_rail_move_for_a_raised_loader(self): + # "raising Reroute right of a loader …: write rail … move to …" + self.do("copy 10 13 8 9 27") + self.do("link 13.0 8.samples 10.0 8.vae 8.0 9.images 27.0 13.latent_image") + plan = ["put 13 origin", "put 8 right 13 wire", "put 9 right 8 wire", "put 27 left 13 bottom", + "put 10 below 27", "rail 10.VAE above 13 to 8.vae"] + self.layout(plan) + named = self.check_lines("raising Reroute right of a loader") + self.assertTrue(named, "the check names the loader") + self.layout(plan[:-1] + ["rail 10.VAE above 13 move 10 to 8.vae"]) + self.assertFalse(self.check_lines("raising Reroute right of a loader")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_finish.py b/tests/test_finish.py index 526a41b..fc5c82d 100644 --- a/tests/test_finish.py +++ b/tests/test_finish.py @@ -117,7 +117,7 @@ def test_fixed_needs_a_change_since_the_review_picture(self): with self.assertRaises(C.Stop) as e: self.review(answer="fixed") self.assertIn("same as in the picture", str(e.exception)) - self.review(answer='left: "preparation further left than the loaders" applies') # leaving it needs no change + self.review(answer='left: "preparation further left than the loaders" applies — reviewer: not Bad') # leaving it needs no change def test_stale_review_stops_finish(self): self.do(f"export {self.out / 't.json'}") @@ -140,11 +140,11 @@ def test_review_row_with_the_answer_after_an_empty_cell(self): self.do(f"export {self.out / 't.json'}") f = self.w / "review_t.md" f.write_text("| rule | nodes | what to change | answer |\n|---|---|---|---|\n" - "| readable-form.md: Left to right. | 1 | swap them | | left: “preparation further left than the loaders” |\n", encoding="utf-8") + "| readable-form.md: Left to right. | 1 | swap them | | left: “preparation further left than the loaders” — reviewer: not Bad |\n", encoding="utf-8") self.do(f"review {f}") row = C.Work(self.w).current().s["review"]["rows"][0] self.assertEqual((row["rule"], row["nodes"], row["change"], row["answer"]), - ("readable-form.md: Left to right.", "1", "swap them", "left: “preparation further left than the loaders”")) + ("readable-form.md: Left to right.", "1", "swap them", "left: “preparation further left than the loaders” — reviewer: not Bad")) def test_review_rows_with_a_pipe_in_the_rule_and_a_missing_header(self): self.do(f"export {self.out / 't.json'}") @@ -154,7 +154,7 @@ def test_review_rows_with_a_pipe_in_the_rule_and_a_missing_header(self): self.do(f"review {f}") self.assertIn("no header row", str(e.exception)) f.write_text("| rule | nodes | what to change | answer |\n|---|---|---|---|\n" - "| readable-form: use `put … right|left` | 1 99 | put it right | left: 「preparation further left than the loaders」 |\n", encoding="utf-8") + "| readable-form: use `put … right|left` | 1 99 | put it right | left: 「preparation further left than the loaders」 — reviewer: not Bad |\n", encoding="utf-8") out = self.do(f"review {f}") self.assertTrue([x for x in out if "put … right|left" in x], out) self.assertTrue([x for x in out if "not a node of the exported workflow" in x and "99" in x], out) @@ -186,8 +186,10 @@ def test_left_needs_a_quoted_rule_line_of_its_own(self): head = "| rule | nodes | what to change | answer |\n|---|---|---|---|\n" for rows, word in (("| r | 1 | a | left: there is no room |\n", "quoted line"), ('| r | 1 | a | left: "a line that is in no rule file" |\n', "quoted line"), - ('| r | 1 | a | left: "preparation further left than the loaders" |\n| s | 1 | b | left: "preparation further left than the loaders" |\n', - "same words")): + ('| r | 1 | a | left: "preparation further left than the loaders" — reviewer: not Bad |\n| s | 1 | b | left: "preparation further left than the loaders" — reviewer: not Bad |\n', + "same words"), + ('| r | 1 | a | left: "preparation further left than the loaders" |\n', "same reviewer first"), + ('| r | 1 | a | left: "preparation further left than the loaders" — reviewer: Bad |\n', "Fix it")): f.write_text(head + rows, encoding="utf-8") with self.assertRaises(C.Stop) as e: self.do(f"review {f}")