From ba7af8c66bacfec34ee682f0d0a3c7ed54f5cc26 Mon Sep 17 00:00:00 2001 From: nomadoor <124905471+nomadoor@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:17:21 +0900 Subject: [PATCH 1/3] =?UTF-8?q?=E5=B0=8E=E5=85=A5=E3=81=AE=E6=89=8B?= =?UTF-8?q?=E9=A0=86:=20=E3=83=87=E3=82=B9=E3=82=AF=E3=83=88=E3=83=83?= =?UTF-8?q?=E3=83=97=E3=82=A2=E3=83=97=E3=83=AA=EF=BC=88Claude=E3=80=81Cha?= =?UTF-8?q?tGPT=EF=BC=89=E3=81=A8=E3=80=81Codex=20=E7=94=A8=E3=81=AE=20mar?= =?UTF-8?q?ketplace=20=E3=81=AE=E9=A0=85=E7=9B=AE=20(#8)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * marketplace.json: Codex アプリが読む policy、category、interface.displayName を足す * README: 導入に Claude デスクトップアプリと ChatGPT デスクトップアプリの手順。Claude Code は一行で入れる形に * README: 画面の名前を実際の表示に合わせる。入れるのは + ボタン * README: 使うエージェントごとに一つ入れる --- .claude-plugin/marketplace.json | 14 ++++++++++++-- README.ja.md | 33 +++++++++++++++++++++++---------- README.md | 29 +++++++++++++++++++++-------- 3 files changed, 56 insertions(+), 20 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 2127fcc..5818d7d 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,11 +1,21 @@ { "name": "comfyui-readable-node", - "owner": { "name": "nomadoor" }, + "interface": { + "displayName": "Readable Node" + }, + "owner": { + "name": "nomadoor" + }, "plugins": [ { "name": "comfyui-readable-node", "source": "./", - "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node)." + "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node).", + "policy": { + "installation": "AVAILABLE", + "authentication": "ON_INSTALL" + }, + "category": "Productivity" } ] } diff --git a/README.ja.md b/README.ja.md index 4833b41..a4f2def 100644 --- a/README.ja.md +++ b/README.ja.md @@ -13,20 +13,31 @@ ComfyUI の workflow を、人が読みやすい形(**Readable Node**)に組 ## 導入 -下のどれか一つで入れてください。二つ入れると、skill が二重に並びます。 +使うエージェントごとに、下のどれか一つで入れる。Claude と ChatGPT(Codex)の両方で使うなら、それぞれに入れる。同じエージェントに二つの方法で入れると、skill が二重に並ぶ。 -### Claude Code +### Claude デスクトップアプリ -Claude Code のセッションの中で、次を実行してください。 +1. **プラグイン** の画面で **+追加 → マーケットプレイスを追加 → リポジトリから追加** を選ぶ +2. `nomadoor/comfyui-readable-node` を入力 +3. `comfyui-readable-node` の **+** をクリック -``` -/plugin marketplace add nomadoor/comfyui-readable-node -/plugin install comfyui-readable-node@comfyui-readable-node +### Claude Code(CLI) + +ターミナルで次を実行する。 + +```bash +claude plugin install comfyui-readable-node --marketplace nomadoor/comfyui-readable-node ``` -自動で更新したいときは、`/plugin` の Marketplaces で `comfyui-readable-node` を選び、Enable auto-update を選んでください。 +### ChatGPT デスクトップアプリ(Codex) -### Codex +1. **カスタマイズ → プラグイン** で **追加** を押す +2. ソースに `https://github.com/nomadoor/comfyui-readable-node.git` を入力。Git ref とスパースパスは空のまま +3. **個人用** のタブの `comfyui-readable-node` の **+** をクリック + +### Codex CLI + +ターミナルで次を実行する。 ```bash codex plugin marketplace add nomadoor/comfyui-readable-node @@ -35,13 +46,15 @@ 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 0d56ab8..10e52d4 100644 --- a/README.md +++ b/README.md @@ -13,20 +13,31 @@ An agent skill that rebuilds ComfyUI workflows into a form people can read: **Re ## Install -Use one of the ways below. Installing two lists the skill twice. +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. -### Claude Code +### Claude desktop app -In a Claude Code session, run: +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` -``` -/plugin marketplace add nomadoor/comfyui-readable-node -/plugin install comfyui-readable-node@comfyui-readable-node +### Claude Code (CLI) + +In a terminal, run: + +```bash +claude plugin install comfyui-readable-node --marketplace nomadoor/comfyui-readable-node ``` -To get updates automatically, open `/plugin`, go to Marketplaces, select `comfyui-readable-node` and choose Enable auto-update. +### ChatGPT desktop app (Codex) -### 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 + +In a terminal, run: ```bash codex plugin marketplace add nomadoor/comfyui-readable-node @@ -35,6 +46,8 @@ 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 ``` From 7e0ece6a09b5b0b3fc90bf4e68bbff8b9d746650 Mon Sep 17 00:00:00 2001 From: nomadoor <124905471+nomadoor@users.noreply.github.com> Date: Sat, 7 Nov 2026 12:25:15 +0900 Subject: [PATCH 2/3] 0.0.4 --- .claude-plugin/marketplace.json | 14 +- .claude-plugin/plugin.json | 2 +- CHANGELOG.md | 25 + README.ja.md | 33 +- README.md | 29 +- skills/comfyui-readable-node/SKILL.md | 61 +- .../references/content.md | 33 +- .../references/examples.md | 63 +- .../references/glossary.md | 6 +- .../comfyui-readable-node/references/notes.md | 20 +- .../references/readable-form.md | 48 +- .../references/replacements.md | 13 +- .../references/report.md | 16 + .../references/review.md | 15 +- .../references/techniques.md | 33 +- .../references/understanding.md | 9 +- .../comfyui-readable-node/scripts/canvas.py | 1455 +++++++++++------ .../scripts/comfy_schema.py | 7 +- .../comfyui-readable-node/scripts/compare.py | 53 +- .../comfyui-readable-node/scripts/flatten.py | 37 +- skills/comfyui-readable-node/scripts/logo.svg | 1 + skills/comfyui-readable-node/scripts/notes.py | 13 + .../comfyui-readable-node/scripts/render.py | 18 + .../comfyui-readable-node/scripts/report.py | 433 +++-- tests/fixtures/object_info.json | 650 ++++++++ tests/test_canvas.py | 694 +++++++- tests/test_finish.py | 10 +- 27 files changed, 2857 insertions(+), 934 deletions(-) create mode 100644 skills/comfyui-readable-node/references/report.md create mode 100644 skills/comfyui-readable-node/scripts/logo.svg 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 650e348..801194e 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "comfyui-readable-node", - "version": "0.0.3", + "version": "0.0.4", "description": "Rebuilds ComfyUI workflows into a form people can read (Readable Node).", "author": { "name": "nomadoor" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8dbe0e7..f4d42a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # Changelog +## 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. + +- Fixed (values were changed silently): + - A text of several lines given to `set` had its line breaks written as the two characters `\n`. Give it as `=@` (the path from the current folder); a value holding `\n` stops, and so does a missing file. + - Inside a subgraph holding a custom node that is not installed, values from outside were not written in, and the old defaults ran. The widget order is now read from the node's inputs. + - `canvas diff` missed a changed value on a widget turned into an input (the old value stayed), and a seed changed from `fixed`. +- New: `rail . … move to …` moves the source's unit so its output is at the rail height, instead of a Reroute raising the wire. Rails above and below keep their order and clearance. +- `rail … below ` runs below the room the node grows into. A Reroute on a rail stays in its column; it no longer steps aside. +- Content: + - A node is replaced by core only when it is the same calculation. Ultimate SD Upscale becomes core's tiles (the seams and the size may differ a little; the report says so). A model of another size is another model: it is kept and the core way is suggested in a Caution Note. + - A value is fixed only when something written shows it is wrong (the author's words, or what the model or node asks for); the report names it. + - The decode of a picture still being drawn is removed; other previews and saves are kept. + - Color Transfer is used only when the original uses it. + - A speed-up node left with nothing to attach to gets its core counterpart, bypassed, with how to turn it on. +- The conversation report at the end is short (references/report.md): the folder and each file with what it makes, what was changed that makes the result differ (with the reason when needed), other ways it could be built when there are any, and a few other notes. Nothing is asked while working; what does not change the result is not told. +- The exported file is named `_readable.json`, and `_readable_.json` when the workflow was split. +- The overview and models Note stands at the upper left, its top edge on the topmost node or group frame. Notes never move the layout. +- Branch is written as the frontend writes it (named inputs, the chosen name and the list); a third input no longer loses the earlier names. +- Painter is not used; the mask editor of Load Image is. A save that only writes generation data into the image becomes core's Save Image. +- `canvas open` names deprecated nodes. `canvas models` drafts the list of custom nodes for the models Note. +- `canvas report` is faster (about two thirds of the time), and the report page was redesigned. +- Smaller fixes: autogrow inputs accept the short names shown on screen (`a`, `image_1`); a Note named like a block, or placed against the group it falls in, no longer stops the layout; the models tree no longer doubles a folder name. + ## 0.0.3 (2026-10-29) - Fixed: values of VideoHelperSuite nodes (`VHS_`) read from an API-format workflow, or added on the canvas, landed in the wrong widgets (for example `frame_load_cap` in `skip_first_frames`). They are now written by name, as VideoHelperSuite saves them. 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 58ce1a9..10306cb 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.3" + version: "0.0.4" --- # Readable Node @@ -30,7 +30,7 @@ There are three goals. - The whole picture of the processing can be grasped at a glance (the shape is clear without reading the details). - The workflow, as a tool, is easy to rearrange and easy to reuse. -The rules in the references serve these principles and goals; most rules name the one they serve ("Why"). When a case is not covered by a rule, decide by them. Where a rule says "Undecided", it is not decided yet: do not fill it with a rule or threshold of your own; report what you did and what you were unsure about. The words are defined in references/glossary.md. +The rules in the references serve these principles and goals; how to read a rule is at the top of references/readable-form.md. When a case is not covered by a rule, decide by them. The words are defined in references/glossary.md. ## Language @@ -47,7 +47,7 @@ The rules in the references serve these principles and goals; most rules name th **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. Only what you point at moves. +- 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. - 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 @@ -65,7 +65,7 @@ The rules in the references serve these principles and goals; most rules name th Moves marked "(when there is an original)" are only for rebuilding a given workflow. When building a new one, skip them. -When the user asks for it fast, skip steps 9 and 10 (the review and the report page), finish with `canvas finish fast`, and say in the report that it was not reviewed. +When the user asks for it fast, skip steps 9 and 10 (the review and the report page), finish with `canvas finish fast`. 1. **Read the original (when there is an original)** `canvas open ` @@ -75,59 +75,58 @@ When the user asks for it fast, skip steps 9 and 10 (the review and the report p 2. **Write the understanding document (`$W/understanding.md`)** The understanding of the workflow, written before building. Write the first version after reading, and revise it while building. Keep what you revised as well. - - Read references/content.md, references/techniques.md, and the "Content" and "Notes" parts of references/examples.md before writing (its "Layout" part comes in step 5). + - Read references/content.md, references/techniques.md, and the "Content" and "Notes" parts of references/examples.md before writing (its "Layout" part comes in step 5). readable-form.md, notes.md and review.md are read in steps 5, 7 and 9, not now. - What to write is in references/understanding.md. For every node, write what it does with its values here. - When the understanding document is written, tell the user once, without waiting for an answer: what the workflow does, how many workflows it will be split into, and what will be replaced. - 3. **Split** - Following the split in the understanding document, make one canvas per workflow (`canvas new `, `canvas use `). How many files there are after splitting is Undecided; how they are named is in content.md ("Split"). One canvas becomes one workflow JSON. + Following the split in the understanding document, make one canvas per workflow (`canvas new `, `canvas use `). How they are named is in step 8. One canvas becomes one workflow JSON. - Workflows of the same form that differ only in part (another input, an added stage): build one, then make the others with `canvas new from `, so the shared nodes keep their ids. Write what they share in one plan file, and in each canvas's plan only `include ` and the lines of the part that differs. A fix to the shared part is made once. 4. **Build (per canvas)** The core first, then the added techniques. - This skill has no per-model templates: for how to build the core, refer to a workflow for the same use on nomadoor's site (Comfy-with-ComfyUI). `canvas refs ` lists, newest first, the workflows whose path or article title contains the word (a model name such as "flux" or "wan", or a use such as "inpaint"). Old workflows are sometimes built wrongly, so for the same use, choose the newer one. Refer only to how the core is built; do not copy the layout. - - Write all the build moves in build.txt and run them once with `canvas run build.txt`. If it stops, fix that line and run the rest. Once the nodes are on the canvas, `canvas guide` prints the lines of techniques.md and replacements.md (and of the rules and examples) that name them: read the first two before going on. - - An original node is `copy …` (copies type, values and mode; does not copy wires). A new node is `add ` (a type in object_info). Values are `set`. Wires are `link . . …`; a wire into a widget (seed, text) gives that widget its input. `canvas node ` shows a node's input and output names: look before writing the lines. Connect only what is needed. - - When the build is done (when there is an original), compare with the original using `canvas diff` (values, inputs the user puts in, outputs, mode). One item at a time: if it is an intended difference, note the reason; if not, fix it. + - Write all the build moves in build.txt and run them once with `canvas run build.txt`. If it stops, fix that line and run the rest. + - An original node is `copy …` (copies type, values and mode; does not copy wires). A new node is `add ` (a type in object_info). Values are `set` (whether a value gets a value node: readable-form.md, section 6). Wires are `link . . …`; a wire into a widget (seed, text) gives that widget its input. `canvas node ` shows a node's input and output names: look before writing the lines. Connect only what is needed. - Fix the content yourself. Compare with the understanding document and look for what falls under references/content.md. Also look for mistakes born from replacement and for lost functions. + - When the build is done (when there is an original), compare with the original using `canvas diff` (values, inputs the user puts in, outputs, mode). Take each difference against what counts as the same workflow: + 1. Something the user could do is gone: put it back. + 2. A small numeric difference within the same method (a size rounded to the model's multiple): keep it, and write it in the report. + 3. A different model or a different method (another depth model, another speed-up): put the original back, and suggest the other in a Caution Note. + 4. File names, metadata written into the image, previews and the way of wiring are not part of it: a difference there is not undone. 5. **Arrange (per canvas)** - After reading references/readable-form.md. In this order: - 1. Run `canvas guide` again and read the lines of the rules and examples it prints for the nodes of this canvas. - 2. Paste the lines of `canvas core ` at the top of layout.txt. They are a draft of the core's block: adjust them to this workflow (a part the usual form lacks is named in a comment, to be placed by relations). + In this order: + 1. Run `canvas guide` for each canvas and read its whole output, uncut: the lines of references/ that name the nodes of this canvas. + 2. Read references/readable-form.md, references/glossary.md and the "Layout" part of references/examples.md, again here if you read them before. Then paste the lines of `canvas core ` at the top of layout.txt. They are a draft of the core's block: adjust them to this workflow (a part the usual form lacks is named in a comment, to be placed by relations). 3. For each grouping of the understanding document, write `block …` and the arrangement inside it. - 4. Run `canvas between layout.txt` to see the wires between blocks and the outputs handed out to several blocks. A value handed out to several stages is written as a `rail` (readable-form.md, "Wires"). + 4. Run `canvas between layout.txt` to see the wires between blocks and the outputs handed out to several blocks. Whether a value handed out to several stages needs a `rail`: readable-form.md, "Wires". 5. Write the arrangement between blocks: each block against the block it is wired to (`put left|right wire`). Groups, colours and the titles of value nodes and of nodes loading an image go in the same file (readable-form.md, "Groups and colour", "Names"); the canvas reads every group line before it places anything, so where in the file a group line stands does not change the layout. 6. Run `canvas layout layout.txt`. How to place: - - A node's column comes from the node it feeds (just left of it); its row comes from the rows in readable-form.md. Neither comes from a node that merely stands nearby. + - A node's column comes from the node it feeds (just left of it); its row from readable-form.md, section 4 ("Other chains have their own rows"). Neither comes from a node that merely stands nearby. - Place by relations only (put, row, stack, align, level, inputs, rail). No numbers: gaps and widths are the canvas's; where a rail runs is in readable-form.md, "Wires". A place one reference does not give takes two (`put right below `). - Copy a shape with `canvas shape`. Split workflows give the same function the same layout (`canvas new from `). 6. **Look, and fix** 1. Draw the picture with `canvas render $W/look.png` and look at it. Does it look as if a person arranged it? A node far from what it feeds, a wire running a long way, an empty area, a crowded area: fix the plan. - 2. Read what `canvas layout` returned, as it is: each line names a rule of this skill that a form breaks (its file and section). Fix each in the plan; look at it on the picture. It stops nothing. `canvas check` lists every notice. - 3. Rewrite the plan lines for everything to fix together and run `canvas layout` again (not item by item). `rail` stops when its line cannot be drawn (a target stands left of the source, or rails keep blocking each other's height); fix what it names. A rail that runs behind a node or has a Reroute that does nothing is drawn, and the check names it. + 2. Read what `canvas layout` returned, as it is, uncut by grep or head (the `rule:` lines too): each line names a rule of this skill that a form breaks (its file and section); read that section again there. Fix each in the plan; look at it on the picture. `canvas check` lists every notice. + 3. Rewrite the plan lines for everything to fix together and run `canvas layout` again (not item by item). `rail` stops when its line cannot be drawn (a target stands left of the source); fix what it names. A rail whose wires cross behind a node, or that has a Reroute doing nothing, is drawn, and the check names it. 4. Repeat 1–3 until nothing is left to fix. - Leaving something: - - Leave an item only after trying, with what was tried and what happened. - - When no relation gives a place, leave it and report which two nodes you could not relate. - - The check list finds only what can be counted; an empty list does not mean the layout is right. The review (step 9) checks the rest. + The check list finds only what can be counted; an empty list does not mean the layout is right. The review (step 9) checks the rest. 7. **Notes** - Read references/notes.md. Export the canvas (a draft for the Note writer; the final export is step 8), then start a separate agent (a subagent) and give it: the exported workflow (a node keeps its number from one export to the next; a node the canvas named, such as a Reroute it made, gets a number of its own), `$W/understanding.md` (E lists the candidates), and references/notes.md, with this request: "Write the Notes for this ComfyUI workflow following notes.md: the one or two sentences at the top of the overview Note, and the Notes on part of the processing, one Markdown file each in $W/notes/, in . Write from what happens to the user, not from the nodes. Write nothing that the graph shows. Point at nodes by their display names. Each file holds only the text: no heading for the title. In your final message, list each file with the id of the node it explains and its title (one of the three in notes.md)." If no separate agent can be started, write them yourself and say so in the report. - - Add the models list from `canvas models` under the overview sentence. - - Place each Note where notes.md, "Where to place", says, with `note ` in the plan (it takes what `put` takes: an alignment, a second reference), give it its title with `title "Markdown Note: …"` (the file holds only the text), and run `canvas layout`. When the place written is not clear, the canvas says what the Note lands on. + Read references/notes.md. Export the canvas (a draft for the Note writer; the final export is step 8), then start a separate agent (a subagent) and give it: the exported workflow (a node keeps its number from one export to the next; a node the canvas named, such as a Reroute it made, gets a number of its own), `$W/understanding.md` (E lists the candidates), and references/notes.md, with this request: "Write the Notes for this ComfyUI workflow following notes.md: the one or two sentences at the top of the overview Note, and the Notes on part of the processing, one Markdown file each in $W/notes/, in . Write from what happens to the user, not from the nodes. Write nothing that the graph shows. Point at nodes by their display names. Each file holds only the text: no heading for the title. In your final message, list each file with the id of the node it explains and its title (one of the three in notes.md; the overview Note has neither)." If no separate agent can be started, write them yourself. + - Add the models list and the custom nodes list from `canvas models` under the overview sentence. + - Place each Note where notes.md, "Where to place", says, with `note ` in the plan (it takes what `put` takes: an alignment, a second reference), give a Note on part of the processing its title with `title "Markdown Note: …"` (the file holds only the text; the overview Note has no title), and run `canvas layout`. When the place written is not clear, the canvas says what the Note lands on. - One Note at a time, check that the node on the 🔗 line and the topics are about the same node; a topic about another node moves to that node's Note. 8. **Export and compare** - For each canvas, `canvas export .json`. (When there is an original) run `canvas diff` again on every canvas, look at the differences one by one, and if one is not intended, fix it and export again. + For each canvas, `canvas export .json`. The name is the original's file name with `_readable` after it (`image_flux2_klein_text_to_image_readable.json`), so it stands beside the original without overwriting it; when the workflow was split, a few English words after that say what each one does (`…_readable_upscale.json`). (When there is an original) run `canvas diff` again on every canvas, take the differences one by one against the four items of step 4 and content.md, "What becomes of each part", fix what they say, and export again. 9. **Review (another agent)** - Read references/review.md and follow it: draw the picture for each canvas, give the brief to a new agent, fix the rows one at a time, answer every row, export again and register the review with `canvas review`. + Read references/review.md and follow it: draw the picture for each canvas (not for one that differs from another only in values), give the brief to a new agent, fix the rows one at a time, answer every row, export again and register the review with `canvas review`. 10. **Write the report page (`report.html`)** Write the page where the user checks the result, as one HTML file. The page has three views. The canvas makes Original (the original workflow) and Rebuilt (what was done on the canvases, one move at a time). You write only the Walkthrough. @@ -136,9 +135,8 @@ When the user asks for it fast, skip steps 9 and 10 (the review and the report p - Finally, write the page with `canvas report report.html ` (`ja`, `en`, `zh` and so on). 11. **Report in the conversation** - First, a few lines of summary: what was produced, what was changed, what the user should check. The path of the report page. - - Below that, the details: the understanding document, how it was split, what was changed and why (what was removed, what was replaced, the author's mistakes that were fixed), the diff differences and their reasons, what was left in check and why, the reviewer's one-line reply for each canvas (or that it was not reviewed), and the review rows that were left and why. - - `canvas finish` deletes the files of the working folder it knows, including the understanding document. Take what the report needs from it first, then run `canvas finish`, then give the report. While something is missing (an export, a review, an answer to a review row, an up-to-date report page) it stops, says what, and deletes nothing. When the environment keeps the working folder, it only lists the files: say so in the report. + Read references/report.md, and report as it says. + - `canvas finish` deletes the files of the working folder it knows, including the understanding document. Take what the report needs from it first, then run `canvas finish`, then give the report. While something is missing (an export, a review, an answer to a review row, an up-to-date report page) it stops, says what, and deletes nothing. ## References @@ -149,5 +147,6 @@ When the user asks for it fast, skip steps 9 and 10 (the review and the report p - references/replacements.md: the replacement dictionary (custom nodes and deprecated nodes, things that may be removed, things to keep) and how to find the source. - references/readable-form.md: the layout rules (nodes, wires, flow and position, groups and colour, names). - references/notes.md: how to write Notes and the Walkthrough, and where to place Notes. -- references/examples.md: examples (how the rules applied in real workflows), and the list of Undecided items. +- references/examples.md: examples (how the rules applied in real workflows). - references/review.md: the review after export (what you do, and the brief for the agent that reviews). +- references/report.md: what to tell the user in the conversation at the end. diff --git a/skills/comfyui-readable-node/references/content.md b/skills/comfyui-readable-node/references/content.md index 6f83d4f..29ec12a 100644 --- a/skills/comfyui-readable-node/references/content.md +++ b/skills/comfyui-readable-node/references/content.md @@ -1,6 +1,6 @@ # Rules about content -Two decisions for each part of the original: which workflow it goes into (Split), and what becomes of it (keep it, fix it, replace it with core, or remove it). Used when writing the understanding document (step 2) and when building (step 4); `canvas diff` compares the result with the original (step 8). Rules read as in readable-form.md (Why, Bad, Fine, Undecided). +Two decisions for each part of the original: which workflow it goes into (Split), and what becomes of it (keep it, fix it, replace it with core, or remove it). Used when writing the understanding document (step 2) and when building (step 4); `canvas diff` compares the result with the original against the four items of SKILL.md, step 4. Rules read as in readable-form.md (Why, Bad, Fine). ## Read before deciding @@ -10,29 +10,34 @@ Two decisions for each part of the original: which workflow it goes into (Split) ## Split **One workflow is one thing the user wants to do.** Many workflows are fine: the aim is the principles of SKILL.md, not fewer workflows. Why: 1 task = 1 workflow. -- One workflow: a generation whose stages pass conditioning or a latent on (base → refiner → Hires.fix; t2i → a redraw at a larger size with the same model). +- One workflow: a generation whose stages pass conditioning or a latent on (base → refiner → Hires.fix; t2i → a redraw at a larger size with the same model). Effects on the finished image (film grain, colour matching, frame interpolation, a 1x deblur) stay in it. - Split: what changes what can be done (t2i, i2i and edit; T2V and I2V); what changes the sampling setup (steps, sigmas, cfg, the sampler): models each with their own settings, a speed-up that changes steps or cfg. Tasks that are not connected (outputs sharing no upstream). -- Its own workflow: effects applied to the finished image (film grain, colour correction and the like). -- A bypassed branch in the one workflow: an optional guide (a depth or reference image the task can do without), a speed-up that only may make it faster, an addition that only may make it a little better (CFGZeroStar, a guidance adjustment). -- Bad: one workflow whose switch or bypass chooses between things that must be split. Workflows split for an optional guide or an on/off branch. Of several selectable sets (models with their settings), one built as nodes and the others left as a table in a Note. Effects on the finished image packed into the generation workflow. +- A bypassed branch in the one workflow: a speed-up that only may make it faster, an addition that only may make it a little better (CFGZeroStar, a guidance adjustment). +- An added function the user may want or not (a ControlNet, a guide image) is split: with it and without it. A few nodes that must be switched together can stay in the one workflow as a group switched with bypass. +- Bad: one workflow whose switch or bypass chooses between things that must be split. Of several selectable sets (models with their settings), one built as nodes and the others left as a table in a Note. -Name split workflows so the version shows, give the difference in one phrase in the report, and put the same function in the same layout across them. +Put the same function in the same layout across split workflows. ## What becomes of each part -**Keep what the author added on purpose** (processing, values, structure per stage: one seed handed across stages, a CLIP Text Encode per stage; bypassed or muted branches, the unselected side of a switch; a Compare). Merge ways of doing one step differently (Tiled VAE Decode and VAE Decode) into the one the author chose. Why: the rebuilt workflow keeps every function of the original. +**Keep what the user can do** (the functions they can choose, bypassed or muted branches, the selectable sides of a switch) and a Compare the author added; a seed handed across stages stays one seed. The way it is built (which nodes, how they are wired) is not among what is kept: what brings the same thing is rebuilt in its simplest form. Merge ways of doing one step differently that give the same result (Tiled VAE Decode and VAE Decode differ only in memory) into the one the author chose; candidates that give different results stay, switched with Branch (techniques.md). Why: the rebuilt workflow keeps every function of the original. - Bad: a function of the original gone from every rebuilt workflow (only debugging leftovers may go). -**Fix what does nothing for the result or harms it, and what narrows what the user can do for no gain; report it.** Examples: a sampler whose result the next one fully redraws (both start at step 0 with noise added); VAE Encode right after VAE Decode (pass the latent on); decoding and previewing the middle of generation (techniques.md shows the form); positive and negative swapped in one of two same-shaped stages; an intermediate result saved while the final one only previews; a value that breaks the model's required multiple; a fixed size where the user should choose one. Why: the workflow does what it seems to do. +**Fix what does nothing for the result or harms it, and what narrows what the user can do for no gain; report it.** Examples: a sampler whose result the next one fully redraws (both start at step 0 with noise added); VAE Encode right after VAE Decode (pass the latent on); decoding a picture that is still being drawn (techniques.md shows the form); positive and negative swapped in one of two same-shaped stages; an intermediate result saved while the final one only previews; a value that breaks what the model or the node itself asks for (a multiple, or sizes that must match, as its tooltip or source says). Why: the workflow does what it seems to do. - Bad: one of these left in the rebuilt workflow. -- Fine: a value the author may have chosen on purpose (a hand-made sigma list, a strength) is kept; if it looks strange, it is explained in a Caution Note (notes.md). This is for values only: a strange way of wiring (the positive and the negative encoded through different CLIP chains) is fixed. +- Fine: a value that changes the result (a hand-made sigma list, a strength) is kept even when it looks strange, and is explained in a Caution Note (notes.md). A stage or node that does nothing for the result, or whose result is redrawn later, is fixed even when the author seems to have put it there on purpose, and the report says so. A value that differs from what the author's own words (a node title, a Note) say it is is a slip, not a choice: it is set to what they say, and the report says so. A value is fixed only when something written shows it is wrong (the author's own words, or what the model or node asks for); the report names it. Without that, it is the author's choice. This is for values only: a strange way of wiring (the positive and the negative encoded through different CLIP chains) is fixed. -**Replace old nodes and custom nodes with core nodes when core can do the job.** Build it simpler and more robust than the author did when you can; read the source to know what the node does, but the core build need not be proven equivalent. Why: remove custom nodes as far as possible. +**Replace old nodes and custom nodes with core nodes only when core does the same thing the same way.** The same way: the same calculation. What may differ: settings that do not change the kind of what comes out (weight dtype, quality, encoding), the image size when it still fits the model's required multiple, and the file of the same model at the same size (a GGUF LLM to core's Generate Text; a newer version of the same model that core reads). A model of another size (27B to 9B) is another model: keep the node, and suggest the core way in a Caution Note. A core node made as core's form of that custom node's feature counts as the same way, even when some of its methods or its sampler differ (Transfer Color for KJNodes' Color Match, core's SUPIR patch for SUPIR, core's tiles for Ultimate SD Upscale: the seams blend differently and the size may differ by a few pixels); write what changes in the report. The core build may be a few core nodes making the same calculation; read the source to know what the node does. Why: remove custom nodes as far as possible, without changing what the workflow makes. - Look up replacements.md first and follow it exactly. Otherwise read the node's source (how to find it: top of replacements.md), write it in the understanding document's table, and rewire if copying values is not enough. A deprecated node goes to its successor. Readable forms of the same calculation are in techniques.md. -- Keep it when: the part core cannot do changes the shape of the output (image size, number of images or frames, length); it is a GGUF loader; it is a special sampler (ClownsharKSampler and the like); replacing it would take away an operation the user does by dragging on screen; core cannot take the same input by wire (a crop whose region comes in by wire); its source cannot be found. Report what was kept and why. -- Use core when only internal numbers change (weights, quality, encoding), when the image size changes but still fits the model's required multiple, or when only the model file changes and core has the function (a GGUF LLM to core's Generate Text). Prefer core nodes not marked `experimental`. -- Bad: a custom node kept although none of the reasons to keep it applies. A custom node kept without reading what it does with its values here. +- A different way is not the same thing, even when the core node does the job better (TeaCache and core's EasyCache speed up differently; MiDaS and core's Depth Anything 3 make different depth maps): keep the custom node, and suggest the core way in a Caution Note (notes.md). +- A node that only makes the run faster (a cache), left with nothing to attach to because the custom nodes it was attached to are replaced by core: its core counterpart is put in its place, bypassed, and the Caution Note says the speed-up works another way and how to turn it on. +- Keep it also when: it is a GGUF loader; it is a special sampler (ClownsharKSampler and the like); replacing it would take away an operation the user does by dragging on screen; core cannot take the same input by wire (a crop whose region comes in by wire); its source cannot be found (what it does cannot be told). +- Bad: a custom node kept although core does the same thing the same way and none of the reasons to keep it applies. A custom node replaced by a core node that does the job another way. A custom node kept without reading what it does with its values here. -**Remove what reaches no output or does nothing with its values, and report it**: pass-through nodes; a LoRA at strength 0; a text processor whose features the text does not use; resizing to its own size; resizes one after another (merge them); a save node chosen for a feature it does not use (saving with metadata when no metadata is used: core Save Image already writes the workflow into the image); nodes that do not change the result (playing a sound, freeing GPU memory); a Preview only for looking (an image that was only resized). +**Remove what does nothing with its values**: pass-through nodes; a LoRA at strength 0; a text processor whose features the text does not use; resizing to its own size; resizes one after another (merge them); a save node chosen for a feature it does not use; nodes that do not change the result (playing a sound, freeing GPU memory); a Preview only for looking (an image that was only resized). - Fine: a Preview that lets the user check something the result depends on (which person in the input video the reference image goes on). A Compare the author added (it stays; where it stands: readable-form.md). A step that does nothing but makes the flow clearer (a size match before a compare). - Bad: any of the above left in the rebuilt workflow. + +**A save node that only writes generation data into the image becomes core Save Image.** Why: core Save Image already writes the prompt and the workflow into the image; the extra data changes nothing in the result, and the values wired to it (seed, steps, cfg, sampler, size, model names) run across the whole workflow. +- Before: a metadata saver taking seed, steps, cfg, sampler and model names from value nodes, seven wires across the workflow to reach it. After: core Save Image on the image; the value nodes feed only the nodes that use them. +- Fine: a save node that writes something besides the image that the workflow is for (a caption text file next to each image for a dataset). It is part of what the workflow makes. diff --git a/skills/comfyui-readable-node/references/examples.md b/skills/comfyui-readable-node/references/examples.md index 6b2c378..2f7ad4d 100644 --- a/skills/comfyui-readable-node/references/examples.md +++ b/skills/comfyui-readable-node/references/examples.md @@ -16,12 +16,6 @@ Before: BasicScheduler → SplitSigmas aligned to the model row; the VAE run acr ``` - The wire that loads the model and the nodes that make sigmas have different roles; do not put them on one row because they are connected. -**A SamplerCustomAdvanced setup that is one KSampler (MiniMax reference to video)** -``` -Before: copied SamplerCustomAdvanced + BasicGuider + KSamplerSelect + BasicScheduler as they were -After: one KSampler (the same calculation) -``` - **The outputs (VAE Decode → Save Image → Compare)** ``` After: Save Image, which matters more, stands next to VAE Decode; Compare where its wires need the fewest Reroutes (right of Save Image or below it) @@ -39,21 +33,21 @@ After: the upscale stage's first node level with the first stage's VAE Decode; ### 2. Nodes -- Save Image and Load Image are for checking the output and the input: give them a size at which the preview can be seen. Shrinking Load Image to pack a small workflow makes it harder to read than the original. -- Two Preview Image of one node next to the sampler, stacked in the column left of KSampler: the lower one stood right below the upper. Undecided: side by side, stacked, or merged into one. +- Shrinking Load Image to pack a small workflow makes it harder to read than the original. +- Two Preview Image of the same image: one. A Preview and a Compare of one result: stacked in one column. ### 3. Wires **A single value going far** ``` Layout: in a single-stage workflow where the loader's VAE goes into both VAE Encode and VAE Decode, no rail; both wired directly - Relighting Text to Image: the VAE wire from Load Checkpoint to VAE Decode runs diagonally behind Load Diffusion Model (way in and way out plain to see) + Relighting Text to Image: the VAE wire from Load Checkpoint to VAE Decode runs diagonally behind Load Diffusion Model (no other wire crosses it behind the node) ``` **Reroutes that are not needed** ``` Before: two samplers side by side (KSamplerAdvanced ×2, Wan 2.2 high noise and low noise) took the same positive and negative from a rail -After: wired directly; without Reroutes it is still clear where the wires go +After: wired directly, passing behind the first sampler; without Reroutes it is still clear where the wires go Before: a Reroute right after the source lifting its output, then the rail (a seed, a Wildcard Processor, Load Image → Split Image into List of Tiles) After: the source moved to the height of the rail (or the rail kept at the source's output height) Before: the image from an upscaler to Save Image and Compare right after it, through Reroutes @@ -66,6 +60,8 @@ Before: Resize Image/Mask (match size) took the image it matches on a horizontal After: Load Image → Resize Image/Mask → Stitch Images on one horizontal line; the wire into match slants (Wan 2.1 Fun Control) Before: LTXV Conditioning set midway between the positive and negative encoders; the AV latent split's VAE Decode midway between its video and audio wires (LTX 2.5) After: the positive wire into LTXV Conditioning horizontal; the video latent into VAE Decode horizontal (midway is a liking, not needed) +Before: Detailer's Simple Detector and SEGS Filter side by side, the SEGS wire between them slanting +After: the SEGS wire horizontal (both slots are the first, so their top edges align) ``` ### 4. Flow and position @@ -76,8 +72,6 @@ Before (SeedVR2): Load Diffusion Model below the band After: KSampler where Apply SeedVR2 Conditioning's positive and negative enter horizontally; Load Diffusion Model above Before (Wan 2.2 I2V): the main flow below CLIP Text Encode (the band too low) After: WanImageToVideo top-aligned with CLIP Text Encode; the main flow continues right on that row -Before (i2i): Load Image → Resize → VAE Encode moved 300px below VAE Encode's sampler -After: Load Image → Resize → VAE Encode level, as part of the main flow ``` **Nodes with many inputs (WanAnimateToVideo, WanSoundImageToVideo, WanSCAILToVideo)** @@ -85,8 +79,6 @@ After: Load Image → Resize → VAE Encode level, as part of the main flow 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) -Before: the chain that cuts the face out of the DWPose output above DWPose, to match the slot order -After: below DWPose (match the flow of processing) 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 ``` @@ -97,6 +89,8 @@ Layout: an image chain from Load Image that also goes to Get Image Size → Empt wires go up from that row to other targets (ControlNet, background removal) Before: the Load Image for a depth map left of Load Depth Anything 3 (one more column) After: below Load Depth Anything 3 +Before: the mask chain raised from the bottom row to a middle row (SDXL inpaint) +After: on the bottom row, its wires level ``` **Preparation** @@ -106,10 +100,16 @@ After: the Switch nodes built a little away; only the result comes into the cor Layout: a background composite before a depth ControlNet: Load Image, background removal and layer stacking left of Load Checkpoint ``` +**Stages switched on and off in a row** +``` +Before (four post-processing stages, each a group with its own Boolean that switches two If/Else Switches, one for the image and one for the file name): the image Switches at a different height in each group; the Booleans and a long Note inside the groups, so every group, its top and bottom aligned with the others, grew to the tallest +Layout: the image Switches of all stages, the loader and the saver at one height, so the line that passes the stages is one horizontal line from the first node to the last; the file-name Switches at one lower height, a second line; the Booleans in a row above the groups, outside them, their Notes above them; the long Note below its group, outside it +``` + **Layers, same-shape chains** - 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. +- 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** ``` @@ -134,6 +134,9 @@ Before: Load VAE bottom-aligned with Load Image (height 424) After: much higher (no reason to align with it) Before: Load VAE at the top of the loader column, above two Unet Loaders (Wan 2.2 GGUF) After: below the model loaders +Before: the model row 400px above KSampler, an empty gap between it and the nodes below +After: the loaders placed in order from the top, with no empty gap +Layout: a single stage: Load Checkpoint just left of the text encoders (its CLIP goes there; its model reaches KSampler without a wire going back) ``` - VAE Decode and VAE Decode Audio (MiniMax H3, LTX) stand in the same column. @@ -144,10 +147,10 @@ After: below the model loaders ### 7. Groups and colour -- A two-stage LTX workflow has three groups (stage 1, stage 2, decode). A t2i with IPAdapter has none. +- 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 that 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 (a case, not a rule). +- 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. ### 8. Names @@ -163,9 +166,11 @@ After: ComfyUI's display name ### Split ``` -One: base → refiner → Hires.fix (conditioning passes on). The film grain and colour correction on the finished image: a workflow of its own +One: base → refiner → Hires.fix (conditioning passes on), with the film grain and colour correction on the finished image Split: nine models with their own sampler settings × t2i and i2i = eighteen workflows -One, bypassed: a depth image as an optional guide for an edit (not a second workflow) +Split: a prompt written by hand or by an MLLM from an image, one side bypassed in the author's workflow: two text-to-image workflows, one with the MLLM and one without +Before: an Anima LLLite guide, its nodes in no group, switched on and off with bypass in one workflow +After: two workflows, with LLLite and without ``` ### Fix @@ -175,6 +180,8 @@ Before: two KSampler (Advanced) in a row, both adding noise from step 0; the sec After: the first removed, reported Before: 30 steps split into three KSampler (Advanced) (0–10, 10–20, 20–end) with a different seed each After: one KSampler with 30 steps; the difference reported +Before: looping once and looping twice saved through two Create Video and Save Video +After: one Create Video and Save Video; bypassing Batch Images switches between once and twice ``` ### Sizes from what they are for @@ -190,18 +197,21 @@ After: from one place ### Unconnected parts and disabled branches -- Resolution samples the author prepared (26 Empty Latent Image connected to nothing): removed, the values kept as a table in the Note on Empty Latent Image. Undecided: that table, or the core Resolution Selector wired in. Either is fine. +- Resolution samples the author prepared (26 Empty Latent Image connected to nothing): removed, the values kept as a table in the Note on Empty Latent Image. - A finished stage not connected to the output, with the author's Note saying how to connect it: left unconnected, and how to connect it written in a Note. - A bypassed branch whose sources are all empty: it cannot work, so it is removed as debris and reported. - A switch between Tiled VAE Decode and VAE Decode: keep the one the author had enabled. +- A switch choosing the base image of an i2i among three generated patterns (random shapes, a binary pattern, a gradient; the author's choice enabled, the other two groups muted): all three kept, the switch replaced by Branch (inputs named for the patterns), the groups unmuted. Every function is kept first; then the workflow is split as Split says. ### Choosing a replacement ``` +Before: copied SamplerCustomAdvanced + BasicGuider + KSamplerSelect + BasicScheduler as they were (MiniMax reference to video) +After: one KSampler (the same calculation) Before: Compositor3 (stacks images by dragging) rebuilt from Image Composite Masked and scaling nodes After: core Create Layered Image and Add Layer (positions fixed by dragging in the editor) -After: tiles: Split Image into List of Tiles → redraw each → Color Transfer → Merge List of Tiles to Image (in place of Ultimate SD Upscale) - With Qwen Image 2.1, whose VAE outputs RGBA, Split Image with Alpha before Color Transfer +After: tiles: Split Image into List of Tiles → redraw each → Merge List of Tiles to Image (in place of Ultimate SD Upscale) + Color Transfer only when the original workflow uses it; with Qwen Image 2.1, whose VAE outputs RGBA, Split Image with Alpha before it Kept: a crop whose region comes in by wire (core Crop Image cannot take it by wire) ``` @@ -224,12 +234,3 @@ After: ### With cfg at 1.1, most of the Distill version's speed is lost ``` **Not written**: "16:9 is 1088, not 1080, to divide by 16" (rounding to the model's multiple is expected); "un-bypass the blue nodes" (point at nodes by name); "according to the author, swap in Unet Loader (GGUF)" (a checkable step is written plainly). - -## Undecided - -- **Workflows that are too complex**: nested subgraphs expanding to hundreds of nodes (chains of regular expressions that build text, and so on). Leaving them as a subgraph may be easier to read. -- **What to hand over when splitting**: if what the author's wireless nodes sent is turned into Save Image → Load Image, the later workflow may apply the same processing again. -- **A node that gathers inputs**: at the middle of its sources, or its top edge aligned with its neighbour (Detailer's Simple Detector and SEGS Filter side by side were corrected to align their tops). -- **How high a loader may stand above the sampler** (400px above KSampler was too high). -- **A backward wire into a lower row**: an upscale group on the row below the main flow takes VAE Decode's image going back down to the left; where to draw the line. -- **Simplifying an author's size calculation**: the author measured an upscale ratio with an empty 64×64 latent (6 nodes, works for any upscale model); Resolution Selector → Math "a / 2" does it in 3 nodes for a single x2 model, no longer equivalent. diff --git a/skills/comfyui-readable-node/references/glossary.md b/skills/comfyui-readable-node/references/glossary.md index 7185f02..c203af8 100644 --- a/skills/comfyui-readable-node/references/glossary.md +++ b/skills/comfyui-readable-node/references/glossary.md @@ -36,6 +36,7 @@ The meaning of the words used in the skill's documents. Each is defined here onc - **column**: a vertical band of nodes stacked up and down. The column of sources to the left of a sampler, and so on. - **eye line (band)**: the height every stage's sampler (KSampler, SamplerCustomAdvanced) stands at; a band with width through which the main flow passes. - **main flow**: the flow from the sampler towards the final output (sampler → decode → … → save). +- **output node**: a node that takes a result and passes nothing on (Save, Preview, Compare). - **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. @@ -43,7 +44,7 @@ The meaning of the words used in the skill's documents. Each is defined here onc - **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. -- **model chain**: the nodes the model passes through before the sampler: its loader, LoRAs, and nodes that patch the model (sampling settings, attention). +- **model chain**: the nodes the model passes through before the node that takes it to sample (a KSampler, or a scheduler or guider): its loader, LoRAs, and nodes that patch the model (sampling settings, attention). - **backward wire**: a wire that goes back from right to left. - **wireless links**: mechanisms that pass values without drawing wires (Set/Get, Anything Everywhere, hidden links). - **Nodes 2.0 and the legacy renderer**: the two ways ComfyUI's frontend draws nodes. @@ -58,7 +59,6 @@ The meaning of the words used in the skill's documents. Each is defined here onc - **check list**: the list of layout and content problems returned by the canvas's `check`. - **report**: what tells the user the result when the rebuild is finished. Separate from Notes. There are two. - **report page**: `report.html`. It has three views: Original (the original workflow), Rebuilt (what was done on the canvas, one move at a time), Walkthrough. - - **conversation report**: what is told in the conversation in step 11. + - **conversation report**: what is told in the conversation in step 11 (references/report.md). - **Walkthrough**: one of the views of the report page. It explains the finished workflow grouping by grouping, in processing order. -- **Undecided**: something not yet decided. - **hand-made layout**: a layout a person arranged by hand. diff --git a/skills/comfyui-readable-node/references/notes.md b/skills/comfyui-readable-node/references/notes.md index 401537b..fbf188c 100644 --- a/skills/comfyui-readable-node/references/notes.md +++ b/skills/comfyui-readable-node/references/notes.md @@ -1,13 +1,13 @@ # How to write Notes and the Walkthrough -Rules read as in readable-form.md (Why, Bad, Fine, Undecided). +Rules read as in readable-form.md (Why, Bad, Fine). **A Note says what the graph cannot show. What the graph shows is not written.** As with comments in code: write why something is there, the pitfalls a reader would fall into, and what could be done better; do not restate what can be read. Why: the reader follows the workflow without being made to read twice. - Write: the author's intent that cannot be seen (why this value, why this node); pitfalls and advice (a value that makes the image smaller, latent upscaling degrading the image, a setting that wastes a distilled model's speed); where using it is easy to get wrong (which Load Image takes what, when several take images). -- Do not write: node names and values read aloud; the nodes read in wire order; what everyone who uses ComfyUI knows (negative has no effect at cfg 1, Load Image takes the image to edit, a size rounded to the model's multiple); what using ComfyUI shows (a custom node must be installed to run; with a node taken out, its wires are connected directly); which way a value works when that is the usual way (smaller is faster, larger keeps more detail); nodes only for looking or only loading a model; a value the workflow is built not to use (the negative prompt at cfg 1: techniques.md, "With cfg 1.0, make the negative…", says what becomes of it). +- Do not write: node names and values read aloud; the nodes read in wire order; what everyone who uses ComfyUI knows (negative has no effect at cfg 1, Load Image takes the image to edit, a size rounded to the model's multiple); what using ComfyUI shows (a custom node must be installed to run; with a node taken out, its wires are connected directly); which way a value works when that is the usual way (smaller is faster, larger keeps more detail); nodes only for looking or only loading a model; a value the workflow is built not to use. - Bad: a sentence that only restates what the graph shows. -Differences from the original workflow (what was tidied, replaced or removed, and why) are reported in the conversation, not in Notes. A report is read once; a Note stays in the workflow. +Differences from the original workflow are not written in Notes. A report is read once; a Note stays in the workflow. There are two kinds of Notes: the overview and models Note (one in every workflow), and Notes on part of the processing (only when something above applies). Both are written in a Markdown file and placed with the canvas `note`. @@ -19,6 +19,7 @@ The text of the Notes on part of the processing, and the one or two sentences at **At the very top, what this workflow does, in one or two sentences: what goes in and what comes out. Below it, the list of models.** - The first heading says that in the user's language. The models heading is always `## models`, in every language (the canvas finds the model Note by it). +- It has no title: its place at the upper left and its colour say what it is, and its headings divide it. - The list of models is in exactly this form (the canvas `models` gives a draft): ````markdown @@ -43,16 +44,16 @@ Generates an image from a text prompt with Qwen Image 2.1. ``` ```` -- The download URL and size come from the original workflow (the node's information, or the author's Note). If it has none, search HuggingFace for the same file name and write only a URL where the file was confirmed to exist. Do not guess; if it is not found, do not write it. -- When the same file is in a Comfy-Org repository on HuggingFace (files repackaged for ComfyUI), link that one rather than another copy. Confirm it there as above. +- The download URL and size come from the original workflow (the node's information, or the author's Note), or from the model Note of the site workflow you referred to (`canvas refs`) when it lists the same file. Otherwise do not write it: do not search elsewhere, and do not guess. - Models that a node downloads by itself the first time it runs are written below the list: what, where it goes, and what it needs (found in the custom node's source). +- Below the models, the custom nodes the workflow keeps, under `## custom nodes`: one line per pack, `- [](): `. The pack and its URL come from the node's information (the canvas `models` drafts them from `cnr_id` or `aux_id`) or from where the source search (replacements.md) found it; a node whose source was not found says so in place of the link. A workflow that keeps no custom node has no such part. ## A Note on part of the processing **The title is one of three: "Markdown Note: Usage", "Markdown Note: Author's techniques", "Markdown Note: Caution"** (the part after the colon in the user's language; two in one Note are lined up with " / "). - **Usage**: where using it is easy to get wrong; the purpose of an author's technique that cannot be seen (in one phrase). - **Author's techniques**: what the author left in words (Notes, descriptions, titles), in the author's own words, only where the user needs it to choose a value or to avoid a trap; not everything the author wrote. A claim that cannot be checked (how good the results look) is quoted as the author's words; what can be checked (swapping in a GGUF loader) is written plainly, without "according to the author". -- **Caution**: puzzling processing that is kept, a trade-off the author may have chosen, and advice on what could be done better. When memory may run short, suggest a smaller form of the same model (fp8_scaled, int8) with its link, from Comfy-Org when it has one, rather than loading the model in a lower weight_dtype. The workflow keeps the model the author chose: another file changes the result and the download. +- **Caution**: puzzling processing that could not be fixed, a trade-off the author may have chosen, and advice on what could be done better. When memory may run short, suggest a smaller form of the same model (fp8_scaled, int8), with its link when the original, the site workflow or Comfy-Org's repackaged models give one, rather than loading the model in a lower weight_dtype. The workflow keeps the model the author chose: another file changes the result and the download. - Bad: a Note under none of the three. "According to the author" on something that can be checked, or in a Usage Note. **Check every statement before writing it** in the node's source, the official description or the model card. Before writing that a node is missing, check whether ComfyUI applies a default internally (without ModelSampling, the model's default shift is still used). Rules of thumb (techniques.md) are written as knowledge from experience. Do not write where you checked (file names, function names). What you could not find out is written as "could not find out". @@ -67,17 +68,18 @@ Generates an image from a text prompt with Qwen Image 2.1. ## Where to place -**The overview and models Note stands at the upper left of the whole workflow, its top edge on the top edge of the whole workflow.** In the plan: `note left all`, then `align top all ` (`all` is the whole workflow with its group frames; other Notes do not count). +**The overview and models Note stands at the upper left of the whole workflow, its top edge on the top edge of the topmost node or group frame.** Other Notes do not count: a Note never moves the layout. - Bad: the Note set left of everything while the empty space at the upper left of the workflow (above the first nodes, left of a group) holds it: the workflow grows wider for nothing. - Fine: the Note in that empty space, written next to the node below it (`note above `), then `align top all `. Left of everything only when no such space holds it. **A Note on part of the processing stands next to the node it explains, placed last, in free space.** Why: the Note is read where it is needed, and it does not move the workflow. - On the canvas, `note` lines run after every other line, rails included, so a Note goes into the space left; a Note on a node inside a group runs where its line stands (write it right after the lines that place that node; it moves with that node's block). The Note goes where its line writes it: when that place is not clear (on a node, too close to one, on a wire's path, below a node that grows), the canvas says what it lands on; write another side of the same node. -- Bad: a Note in another column or row than the node it explains, with other nodes between them. Nodes moved or rows widened to make room for a Note. A Note on a wire's path. A Note narrower or wider than the default width. A Note touching a node (closer than half a column gap), as a Note left-aligned below a narrower node reaches the next column. +- Bad: a Note in another column or row than the node it explains, with other nodes between them, while a place next to that node is clear. Nodes moved or rows widened to make room for a Note. A Note on a wire's path. A Note narrower or wider than the default width. A Note touching a node (closer than half a column gap), as a Note left-aligned below a narrower node reaches the next column. - Fine: a Note wider than the node it explains, aligned with either edge of it (right-aligned when left-aligned would reach the next column). - Fine: when there is no room next to the node, right above or right below it, with no other node between them (the 🔗 line names the node). Not in a gap between nodes, and not below a node that grows when run (a sampler, a node showing a video). +- Fine: when no place next to the node is clear either, the nearest clear space, away from it, with other nodes between if need be: the 🔗 line names the node. A Note never changes the shape of the workflow; standing away is better than squeezing in. - Fine: a Note on a node inside a group stands inside that group's frame, next to the node. It is placed with the group, not last, so the frame takes it in and what comes after keeps clear of it. -- Bad: a Note that makes its group's frame larger while there is room inside the frame next to a node of the group (below a short node, beside a column). Fine: the frame grows only when there is no such room. +- Bad: a Note that makes its group's frame larger while there is room inside the frame next to a node of the group (below a short node, beside a column). Fine: the frame grows only when there is no such room. Fine: when the Note would make the frame much larger (a long Note, or groups aligned with each other that would all grow), the Note stands outside the group, right next to its frame, nearest the node it explains. ## Walkthrough diff --git a/skills/comfyui-readable-node/references/readable-form.md b/skills/comfyui-readable-node/references/readable-form.md index 08290cd..bbc48ef 100644 --- a/skills/comfyui-readable-node/references/readable-form.md +++ b/skills/comfyui-readable-node/references/readable-form.md @@ -1,17 +1,17 @@ # The Readable Node form -What you decide when arranging a workflow, and what a finished workflow is checked against. The canvas does the rest (node sizes and widths, the fixed colours, rail heights and the room for rails, Reroute positions); its moves and checks are at the top of canvas.py. +What you decide when arranging a workflow, and what a finished workflow is checked against. The canvas does the rest (node sizes and widths, the fixed colours, rail heights, Reroute positions); its moves and checks are at the top of canvas.py. -How to read a rule: the bold line says what to do. **Why** names the principle or goal of SKILL.md it serves; when a case is not covered, decide by it. **Bad** is the form that breaks the rule, as seen in a finished workflow. **Fine** is a form that looks like Bad but is not; a rule without Fine has no exception. **Undecided** is not decided: do not fill it with your own rule. Cases are in examples.md, "Layout", under the same section headings. +How to read a rule: the bold line says what to do. **Why** names the principle or goal of SKILL.md it serves; when a case is not covered, decide by it. **Bad** is the form that breaks the rule, as seen in a finished workflow. **Fine** is a form that looks like Bad but is not; a rule without Fine has no exception. Cases are in examples.md, "Layout", under the same section headings. ## 1. The usual form **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; 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. Empty Latent in the same column as the encoders. Load VAE above the KSampler when only VAE Decode uses it. VAE Decode right of the KSampler, level with it; Save Image right of VAE Decode. -- With SamplerCustomAdvanced: its sources in one column on its left in input order (noise, guider, sampler, sigmas, latent), the guider level with the sampler (its wire horizontal); the guider's conditioning enters horizontally; the sigma nodes (scheduler → split) in that column, not on the model row. Load VAE above the sampler. -- 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 main flow's wire passes an output node on its way to a later node, one of them steps down so the wire passes above it (a staircase: `put right step` places it just below the wire). Which one steps down is chosen so fewer Reroutes are needed. +- 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. +- 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. - 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); 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, or its top edge is on the sampler's (either is fine). 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 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). ## 2. Nodes @@ -22,63 +22,75 @@ How to read a rule: the bold line says what to do. **Why** names the principle o ## 3. Wires **A wire is horizontal when it can be.** Horizontal means the output slot and the input slot are at one height. This matters most. Why: the reader follows the processing along a single line. -- Bad: a slanted wire that becomes horizontal by moving the node at one end, without slanting another wire. At a node with two or more wires coming in, a reference wire (a size to match, a mask, a model) made horizontal while the node's chain wire (what it takes in, works on and passes on) slants. A node taking two wires it works on together (positive and negative, a video and an audio latent) set midway between their sources so that neither is horizontal: its chain wire is the horizontal one. +- A horizontal wire comes before the alignment of a column (equal widths, aligned edges, equal gaps) and before aligned top edges. It does not move the main flow for a side value: the side node or the column takes the room. +- Bad: a slanted wire that becomes horizontal by moving the node at one end, without slanting another wire. At a node with two or more wires coming in, a reference wire (a size to match, a mask) made horizontal while the node's chain wire (what it takes in, works on and passes on) slants. A node taking two wires it works on together (positive and negative, a video and an audio latent) set midway between their sources so that neither is horizontal: its chain wire is the horizontal one. **No wire goes back from right to left.** Why: left to right. - Bad: a wire entering a node whose left edge is left of the source's right edge. - 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. The canvas does not look for a height or move nodes to make room: place the source and the targets so the rail runs where it should. A loader heads its rail. Rails of model, vae and clip from one loader or from loaders stacked in one column run in that order from the top; a conditioning rail runs above the samplers and below the model and vae rails; 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. 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. - 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. -- Undecided: when a wire may pass behind a node (a wire whose way in and way out are plain to see may). +- Fine: wires passing behind a node that do not cross each other behind it (they come out in the order they went in). +- 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 **Left to right in processing order. A node's sources stand from the top in the order of its inputs.** Why: left to right; follow along a single line. +- Exceptions: a source that another rule places follows that rule: the sampler's form (the positive horizontal, SamplerCustomAdvanced in the middle), the type order of loaders and rails, the rows by role (image chains, sizes, masks and preparation lower down), the staircase of output nodes, the stacking of layers, a source moved to save a Reroute, a source that would stand on the path of a rail or a wire (it goes below and left of the node it feeds even when the input order turns over: wires kept clear come first). Other sources stand in input order. It is not a strict rule: some nodes take their inputs in an unusual order, and then the order gives way. - Bad: two wires into one node cross because the sources stand in another order, and swapping them breaks no other rule. A chain folded back below or above itself. **The main flow (sampler → VAE Decode → … → save) runs along one band (the eye line), from the first stage to the last. Every stage's sampler stands on it: their top edges at one height.** Why: follow along a single line; one look along the eye line finds every stage. -- Bad: stages whose samplers stand at different heights. A slanted wire inside a stage along the main flow or into the sampler's positive input, where it could be horizontal. From VAE Decode to the save node, top edges not shared, unless an output node stepped down for a wire passing on. A Preview or Save above the node that feeds it. A main-flow wire hidden behind a save or preview node. +- Bad: stages whose samplers stand at different heights. A slanted wire inside a stage along the main flow or into the sampler's positive input, where it could be horizontal. A Preview or Save above the node that feeds it. A main-flow wire hidden behind a save or preview node. +- Fine: a workflow without a sampler (joining clips, interpolating frames): its main flow (load → process → save) is the band; the rules about samplers do not apply. - Fine: stages that do not take each other's result (parallel stages) each have their own band. What enters a sampler (conditioning, guider, latent) and what follows it (decode, save) stand around it as its form places them, so with SamplerCustomAdvanced the guider and VAE Decode are off the samplers' height. A wire from one stage to the next that slants, or runs on a rail, so the samplers stay on the eye line. -**Other chains have their own rows, by role, not lined up because they are connected.** Why: the whole picture at a glance. The model chain goes above the band. Helper chains (masks, detection) one row below the band, in the column left of the node that uses them. The image chain and the size nodes (Get Image Size, Empty Latent, width and height) on a row lower down; the image that goes into the sampler (the input image of an i2i, through Resize and VAE Encode) is part of the main flow, not of this row. +**An output node (Save, Preview, Compare: a node that passes nothing on) stands on the main flow's line when the flow ends there, and beside it, one step below, when the flow goes on past it.** Why: follow along a single line (the wire that goes on is the one kept horizontal). +- Bad: the wire going on to a later node slanting because an output node was kept on the line. An output node on the line with the flow going on behind it or around it. +- Fine: a node on the way that takes the main flow in a later input (Inpaint Stitch takes the image in its second input, after `stitcher`) stands where that wire is horizontal, its top edge off VAE Decode's. A wire into another output node (Compare, Preview) is not the flow going on: which of them steps down is in section 1, "The outputs". + +**Other chains have their own rows, by role, not lined up because they are connected.** Why: the whole picture at a glance. Helper chains (masks, detection) one row below the band, in the column left of the node that uses them. The image chain and the size nodes (Get Image Size, Empty Latent, width and height) on a row lower down. - Bad: such a chain inside the band, so that the main flow steps around it. A side node (a detector provider, a Preview of a stage's image) aligned to the bottom of the tall node beside it, far from the wire it hangs on. - Fine: a side node just below the image wire that passes it, as far down as keeps it off that wire (`step`). - Bad: the image wire into a VAE Encode that takes only the image (and the VAE) slants, also when the same image goes on to a text encoder as a reference: the image chain (Load Image, Resize) stands on VAE Encode's row, so that wire is level; the wire from VAE Encode on to the sampler may slant. - Fine: a node that takes conditioning as well as the image (InpaintModelConditioning, an image-taking text encoder) stands where its conditioning enters level; the image wire into it slants. **The sources wired straight into a sampler stand in one column, right edges aligned (`inputs`).** Why: follow along a single line. -- Bad: those sources spread over several columns, or not right-aligned. The model chain, on its row above, ending at another column's right edge than this one (its last node stands near the sampler it feeds). +- A side value (a size) wired into a node of the column is made level with `level`: the gap above that node takes the room the wire needs, the other gaps stay, and SamplerCustomAdvanced is centred on the column last. The room shows where the wire needs it. +- Bad: those sources spread over several columns, or not right-aligned. + +**The model chain ends in the column just left of the leftmost node its last node feeds; its last node's right edge is that column's right edge.** Why: left to right; follow along a single line (a node stands right before the node that next uses it, and no wire goes back). The model goes to the node that takes it to sample (glossary, model chain): with a KSampler that column is the column of the sampler's sources; when a scheduler or guider in that column takes the model (SamplerCustomAdvanced), it is the column left of them. When the last node also gives the text encoders their CLIP (Load Checkpoint, a LoRA), the text encoders are further left: it stands in the column just left of them, and its model wire slants. +- Bad: the model chain, on its row above, ending at another column's right edge. **Preparation stays out of the core.** Preparation (switching reference images, compositing a background, assembling text, and so on) is built outside the core's columns, and only its result comes into the core. Why: the whole picture at a glance (the core keeps its usual form). - Bad: a preparation node squeezed into the column of a loader, a text encoder or the sampler (between those nodes). - 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: a node squeezed into a gap so that wires run behind it. An empty band left between nodes. +- Bad: an empty band left between nodes. ## 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, when it is not on a rail. 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 above the model loaders (it stands below the model chain; below the text encoders is fine too). -- Fine: Load CLIP in the column of the text encoders. A Load VAE first used on the input side (VAE Encode, WanImageToVideo and so on), when it is not on a rail, stands there, apart from the other loaders. +- 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. ## 6. Value nodes **A value is put in a value node only when it is changed for each generation and reaches several nodes.** Otherwise it stays in the widget of the node that uses it. Why: the workflow is easy to rearrange and reuse. - Bad: a value node with a single target. A value node holding a value nobody changes. A PrimitiveNode (use Int, Float, String and so on). A value node standing between the positive and negative prompts. A text written in a text area where it was (a prompt, a negative prompt) handed out from String, a one-line input: it is handed out from Text (Multiline), the same kind of input. +- Fine: a value the author put on a custom slider node: the slider goes; the value follows this rule (back into the widget, or into a core Int or Float when it is changed for each generation and reaches several nodes). A node that computes values (Resolution Selector) is not a value node: it stays even with a single target. Candidates wired into a Branch or a Create List. - Fine: a value node titled "display name: what the value is" (`Float: fps`, `Int: pixel count for 720p`); the display name follows "Language" in SKILL.md. ## 7. Groups and colour **A group holds one large function: a clearly separate stage, one of parallel stages of the same form, or a function switched with bypass. A workflow that does one simple thing has none. Decide by function, not by counting samplers or nodes.** Why: the whole picture at a glance (a group guides the eye). The title is in the user's language, as a Note's title is: a common name stays as it is (Hires.fix, Upscale); otherwise a short noun phrase for what the group does (Mask for IPAdapter), not a sentence explaining it. A group holds its function's loaders; shared loaders go into the group of the first stage that uses them; values shared by parallel stages go into no group. -- Bad: stages that are clearly separate with no group. A group for each small piece of a stage (each ControlNet switched with bypass inside the first 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. +- 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; ControlNet kinds are pale_blue; each other added function gets one colour. A group already guides the eye; colour nodes inside a group only with a reason. +**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. - 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. -- Undecided: what reason is enough to colour nodes inside a group. ## 8. Names diff --git a/skills/comfyui-readable-node/references/replacements.md b/skills/comfyui-readable-node/references/replacements.md index 469dfaa..013e0b4 100644 --- a/skills/comfyui-readable-node/references/replacements.md +++ b/skills/comfyui-readable-node/references/replacements.md @@ -7,7 +7,7 @@ For a custom node that is not installed in ComfyUI, read only the files you need 2. Read `__init__.py` by its raw URL, and follow `NODE_CLASS_MAPPINGS` to the file that has the node's type name. 3. Read only that file. If `ver` is a commit, read the one at that commit. - Do not clone. Do not run code you fetched. Do not put it into ComfyUI's custom_nodes. -- If it is found nowhere, leave it unreplaced, and write in the report "the source was not found, so this could not be determined". +- If it is found nowhere, leave it unreplaced. Do not look further than these steps (no search across GitHub). For where replacement stops, see content.md. @@ -22,12 +22,12 @@ Each row's "Where verified" is which source it was verified in. When the node's | VHS_VideoCombine (output) | CreateVideo + SaveVideo (copy format, codec, crf) | Keep it only when it saves as GIF (core's Save Video is only mp4, mkv, webm) | Decided by nomadoor. comfy_extras/nodes_video.py | | Concatenate Text (StringConcatenate) | One Format Text (StringFormat). The texts to join as a, b, c…, the separators in f_string (`{a}, {b}\n{c}` and so on). Whether chained or only one (two inputs) | If an empty text goes in, the separator stays (`{a}, {b}` with a = "cat", b = "" gives "cat, "). Concatenate Text does the same, so nothing changes from the original. A `{` or `}` in a separator or in text written into f_string is doubled (`{{`, `}}`) | Decided by nomadoor. comfy_extras/nodes_string.py (StringConcatenate, StringFormat) | | easy fullLoader (easy-use) | Load Checkpoint + CLIP Set Last Layer (clip_skip) + CLIP Text Encode ×2 + Empty Latent Image. LoRA and ControlNet inside the loader are also brought out as core nodes | If the prompt weight interpretation (token_normalization, weight_interpretation) is not the default (none, comfy), how the weights act changes slightly. Write it in the report | py/nodes/loaders.py and py/libs/adv_encode.py of easy-use 130c1b5 | -| Power Lora Loader (rgthree) | One Load LoRA per enabled row, in order. How each LoRA's clip is handled is in the LoRA item of techniques.md | Delete rows that are off and rows set to None. Internally it only calls LoraLoader in order | rgthree source | +| Power Lora Loader (rgthree) | One Load LoRA per row, in order. How each LoRA's clip is handled is in the LoRA item of techniques.md | Delete rows set to None. Internally it only calls LoraLoader in order | rgthree source | | KSampler (Efficient), KSampler Adv. (Efficient) | KSampler / KSamplerAdvanced + VAE Decode | It displayed the image itself (an output node), so if a place to view it is needed, Preview Image | efficiency-nodes source | | HighRes-Fix Script (efficiency, both) | VAE Decode → Upscale Image (using Model) → Resize Image/Mask (scale by multiplier) → VAE Encode → KSampler | The Upscale Latent By at factor 1 inside does nothing, so do not include it | efficiency-nodes source | | easy controlnetStack | Load ControlNet Model + Apply ControlNet (vae too) | Rows after num_controlnet have no effect | easy-use source | | SDXLEmptyLatentSizePicker+ (essentials) | Empty Latent Image | Enter the size that is in effect with the width / height overrides | essentials source | -| ImageResize+ (essentials, keep proportion) | For a square frame, Resize Image/Mask's scale longer dimension (rounding is also the same). For a rectangular frame, rebuild it in the form of techniques.md "Build the resolution from what the resolution is for" (scale total pixels → round to the model's multiple → Get Image Size) | With a rectangular frame the output size differs from the original. Write it in the report | essentials source (execute of ImageResize in image.py). Decided by nomadoor (rectangular frame) | +| ImageResize+ (essentials, keep proportion) | For a square frame, Resize Image/Mask's scale longer dimension (rounding is also the same). For a rectangular frame, rebuild it in the form of techniques.md "Build the resolution from what the resolution is for" (scale total pixels → round to the model's multiple → Get Image Size) | With a rectangular frame the output size differs from the original. Write it in the report (SKILL.md, step 4, item 2) | essentials source (execute of ImageResize in image.py). Decided by nomadoor (rectangular frame) | | ImageResizeKJ (KJNodes, v1. keep_proportion on, width and height the same) | Resize Image/Mask with "scale longer dimension", followed by "scale to multiple" (multiple of 8). The size and the center crop come out the same | KJ crops first and then scales, while core scales to cover and then crops, so the pixels differ slightly. Does not apply when the box is a rectangle, or to ImageResizeKJv2 | scale_to_multiple_cover in comfy_extras/nodes_post_processing.py | | ImageResize+ (essentials, stretch) | Resize Image/Mask's match size (crop disabled) | | essentials source | | ImagePadKJ + AILab_ICLoRAConcat | Stitch Images (right, copy spacing and color). For the mask on the right, Stitch a black and a white Empty Image with the same spacing, then Convert Image to Mask | ImagePadKJ's color "1,1,1" is white in the 0 to 1 range | KJNodes and ComfyUI-RMBG source | @@ -39,7 +39,7 @@ Each row's "Where verified" is which source it was verified in. When the node's | LLM Text Processor (KingManiya, a GGUF LLM via llama.cpp) | Generate Text (TextGenerate). Load the LLM with CLIPLoader (Qwen3.5, Qwen3-VL and so on can generate text in core). To have it describe an image, use the image input | GGUF cannot be loaded, so the model file changes to safetensors | qwen35.py and qwen3vl.py in comfy/text_encoders | | SaveImageKJ (KJNodes) with no caption connected | Save Image | | nodes/image_nodes.py of KJNodes | | Image Comparer (rgthree) | Compare Images (ImageCompare). Connect image_a and image_b as they are (`canvas open` replaces it when reading the original) | core's Compare Images shows the side-by-side comparison only in Nodes 2.0 | py/image_comparer.py of rgthree, comfy_extras/nodes_image_compare.py | -| ImagesGridByColumns (all images the same size, gap 0) | Make Image Grid (ImageGrid). columns is max_columns, cell_width and cell_height are the image size, padding is 0 | Make Image Grid is experimental | src/utils/images_grid.py of images-grid-comfy-plugin, comfy_extras/nodes_dataset.py | +| ImagesGridByColumns (all images the same size, gap 0) | Make Image Grid (ImageGrid). columns is max_columns, cell_width and cell_height are the image size, padding is 0 | | src/utils/images_grid.py of images-grid-comfy-plugin, comfy_extras/nodes_dataset.py | | ShowText\|pysssss (a node that displays the value it receives and passes it straight on) | Take it out of the flow and connect before and after directly, then branch from the value you want to see into Preview as Text (PreviewAny). How to build is "Do not put a display node in the flow; put it on a branch" in techniques.md | | py/show_text.py of pysssss (displays the text it receives and returns it as the output as is), comfy_extras/nodes_preview_any.py | | MathExpression\|pysssss | Math Expression (the same expression) | Check with values that the expression is the same. If the pysssss expression uses the size of an image or latent (a.width, a.height), widget values of other nodes, randomint, randomchoice or iif, it cannot be written as is in core's Math Expression (core has only numbers and sum, min, max, abs, round, pow, sqrt, ceil, floor, log, sin, cos, tan, int, float) | py/math_expression.py of pysssss, comfy_extras/nodes_math.py | @@ -49,6 +49,7 @@ Each row's "Where verified" is which source it was verified in. When the node's |---|---|---|---| | Apply ControlNet (DEPRECATED) (ControlNetApply) | Apply ControlNet (ControlNetApplyAdvanced) | The old one receives one conditioning and also acts on the negative side. The new one receives positive and negative, so connect negative too | ControlNetApply and ControlNetApplyAdvanced in nodes.py (control_apply_to_uncond) | | Apply Controlnet with VAE (ControlNetApplySD3) | Apply ControlNet (ControlNetApplyAdvanced). `canvas open` replaces it when reading the original | Inputs and outputs have the same names. The calculation is the same (no successor is named) | comfy_extras/nodes_sd3.py and ControlNetApplyAdvanced in nodes.py | +| Painter (not deprecated, but not used: its drawing area shows only in Nodes 2.0) | Load Image, painted in its mask editor: the mask pen for the mask, the paint pen for colour. IMAGE is the image with the paint, MASK the masked area | Painter's image input becomes the image loaded in Load Image; whatever resized it before Painter now resizes Load Image's IMAGE and MASK both. Tell the user in the Note where to paint (right-click Load Image → Open in Mask Editor) | comfy_extras/nodes_painter.py; the mask editor of the frontend (paint layer, saves the painted image with the mask) | ## May be removed (no effect on the result) @@ -66,8 +67,8 @@ These too are kept only when that workflow uses a function core does not have. I |---|---|---| | ClownsharKSampler_Beta (RES4LYF) | Special samplers are kept as an exception to where replacement stops. eta (adds and removes noise each step), methods such as ralston, and bongmath are not in core. Core does have methods that evaluate twice (heun, dpmpp_2s_ancestral, seeds_2) and samplers with eta, but the sampler the author chose stays custom | beta/samplers.py of RES4LYF, object_info | | Crop Image TargetSize (JPS) | There is no core node that receives the crop area through number wires and crops (Crop Image (DEPRECATED) is deprecated. Crop Image [ImageCropV2]'s area is only a frame dragged on the node, and is not received through wires [socketless]) | comfy_extras/nodes_images.py | -| ImagesGridByColumns where the image sizes are not uniform or gap is not 0 | It lines images up at the size of the first image and fills the gaps (gap) with white. core's Make Image Grid (experimental) shrinks cells to cell_width × cell_height and fills the gaps (padding) with black | src/utils/images_grid.py of images-grid-comfy-plugin, comfy_extras/nodes_dataset.py | +| ImagesGridByColumns where the image sizes are not uniform or gap is not 0 | It lines images up at the size of the first image and fills the gaps (gap) with white. core's Make Image Grid shrinks cells to cell_width × cell_height and fills the gaps (padding) with black | src/utils/images_grid.py of images-grid-comfy-plugin, comfy_extras/nodes_dataset.py | | Patch Sage Attention KJ | core's Model Attention Backend cannot select sage. The only way to use sage in core is the launch option --use-sage-attention | comfy_extras/nodes_model_advanced.py, comfy/ldm/modules/attention.py | | UnetLoaderGGUF | core has no node that loads GGUF | | -| SaveImageKJ (KJNodes) with a caption connected | It saves the text together as a .txt. core's Save Image-Text (to Folder) can do this too, but it is experimental and does not put the workflow into the PNG (a node that writes out training data) | nodes/image_nodes.py of KJNodes, comfy_extras/nodes_dataset.py | +| SaveImageKJ (KJNodes) with a caption connected | It saves the text together as a .txt. core's Save Image-Text (to Folder) can do this too, but it does not put the workflow into the PNG (a node that writes out training data) | nodes/image_nodes.py of KJNodes, comfy_extras/nodes_dataset.py | | A resize that "shrinks only when large" (conditional ones such as ImageResize+) | Without the condition, small images are also enlarged (the output size changes). Write the core way to build it as a suggestion in the Caution of a Note | Decided by nomadoor | diff --git a/skills/comfyui-readable-node/references/report.md b/skills/comfyui-readable-node/references/report.md new file mode 100644 index 0000000..489f674 --- /dev/null +++ b/skills/comfyui-readable-node/references/report.md @@ -0,0 +1,16 @@ +# The conversation report + +**Short, only the points. Details are answered when the user asks.** Why: a long report is not read, and what the workflow and its Notes show need not be told again. +- In the user's language, in a polite register. The headings below are written in that language, with the same meaning. +- Ask nothing while working: build to the end, then report. + +1. When the workflow was split, the first line says so ("Split into two workflows."). When it was not, there is no such line. +2. The folder of the files, once. Under it, each file name as a bullet, with nested lines: + - What the workflow makes, from what. From the second workflow on, with how it differs ("The same video, with Turbo LoRA in 4 steps."). + - Only when split: how it differs from the others (a LoRA, the steps). + - For `report.html`: "Open it to compare with the original workflow and to read how the rebuilt workflow works." +3. **Changed from the original workflow**: each change that makes the result differ, one bullet each. Nested under it: the reason, when the change alone does not explain itself; what takes the place of something lost. Of what the references say to report, only these are said. +4. **What else could be changed**, only when there is something: another build with core only (also when a Caution Note already says it); a step that makes in core an input the user would make elsewhere (a depth map from a photo with Depth Anything 3), not added. Write it as "there is also a form that …", not as what you can do ("I can …", "… can also be made"). +5. **Other**, only when there is something: a model whose download link was not found; a custom node not installed, whose values were matched from its source. + +Do not write: what was removed or replaced without changing the result; why it was split; the steps taken; the check list; the review; that the workflow was not run in ComfyUI. diff --git a/skills/comfyui-readable-node/references/review.md b/skills/comfyui-readable-node/references/review.md index fa01e1b..befca2e 100644 --- a/skills/comfyui-readable-node/references/review.md +++ b/skills/comfyui-readable-node/references/review.md @@ -4,13 +4,14 @@ Another agent reviews each exported workflow. You do not judge your own layout: ## What you do -1. After `canvas export .json`, draw the picture for the reviewer: `canvas render $W/review_.png export` (the node numbers drawn are the canvas ids, kept in the exported workflow). Do not look at it yourself. +1. After `canvas export .json`, draw the picture for the reviewer: `canvas render $W/review_.png export`. It also writes `$W/review_.txt`, the titles and Note texts the picture cannot draw. Do not look at them yourself. 2. Start a separate agent (a subagent) for each canvas and give it the brief below as written, with the paths filled in (`` is the folder that holds SKILL.md). Add nothing: no hints, no summary, no reasons, nothing you already know is wrong. - - If no separate agent can be started, do not review it yourself: write `Not reviewed: ` in `$W/review_.md`, and say so in the conversation report. + - A canvas made with `canvas new from ` that differs from it only in values (the same nodes, wires and layout) is not reviewed again: write `Not reviewed: values only, the same layout as ` in `$W/review_.md`. + - If no separate agent can be started, do not review it yourself: write `Not reviewed: ` in `$W/review_.md`. 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. - Answer every row in the last column, once: `fixed`, or `left: `. A row is left only with a quoted line of readable-form.md, content.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 or Undecided 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. + 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. 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. -5. In the conversation report, quote the reviewer's one-line reply, and list the rows you left with why. ## The brief (give it as written) @@ -18,10 +19,11 @@ Another agent reviews each exported workflow. You do not judge your own layout: You look at a ComfyUI workflow that another agent rebuilt to be easy to read, and say where it does not look easy to read. Do not grade it. Assume it has real problems. Read only these files; open nothing else and do not search the disk: -- the picture of the rebuilt workflow: (the numbers on the nodes are node ids; thick white lines are wires passing behind nodes; the picture cannot draw letters other than Latin ones, so a title in another script shows only its Latin part or the node's type: do not report a title from the picture) +- the picture of the rebuilt workflow: (the numbers on the nodes are node ids; thick white lines are wires passing behind nodes) +- what the picture cannot draw: (each node's number and its title as ComfyUI shows it, and the text of every Note; the picture's font has Latin letters only and draws no Note text) - the rules: /references/readable-form.md and notes.md, and the words they use: glossary.md -Judge from the picture only, as a person opening the workflow would see it. Do not read the workflow JSON and do not compute anything: what can be measured (overlaps, wires behind nodes, slanted wires, gaps) the tool that built it already checked. First look at the whole: does it look like a person laid it out? Far-off nodes, long wires, empty areas, crowded places, wires crossing, a Note away from what it explains. Then go through the rules of the two files. The tool already checks these forms and names them to the builder, so do not report them: overlapping nodes; a node or Reroute right below a node that grows; a Preview or Save above its source; backward wires; a wire or node over a group's title; group frames overlapping; model, vae and clip rails out of order, or in another order than their loaders; Reroutes doing nothing or carrying a single value that a direct wire could carry; a wire into Compare or another output hidden behind a node that saves; a slanted wire that moving the node at one end makes horizontal; a wire running along the rails but not on one. Report a place only when it has the rule's Bad form and does not match its Fine form. Do not report Undecided items. One row per cause, listing all its nodes. +Judge from the picture and that text, as a person opening the workflow would see it. Do not read the workflow JSON and do not compute anything: what can be measured (overlaps, wires behind nodes, slanted wires, gaps) the tool that built it already checked. First look at the whole: does it look like a person laid it out? Far-off nodes, long wires, empty areas, crowded places, wires crossing, a Note away from what it explains. Then go through the rules of the two files. The tool already checks these forms and names them to the builder, so do not report them: overlapping nodes; a node or Reroute right below a node that grows; a Preview or Save above its source; a wire or node over a group's title; group frames overlapping; model, vae and clip rails out of order, or in another order than their loaders; Reroutes doing nothing or carrying a single value that a direct wire could carry; a wire into Compare or another output hidden behind a node that saves. Report a place only when it has the rule's Bad form and does not match its Fine form. In a workflow without a sampler, the rules about samplers do not apply. One row per cause, listing all its nodes. Write <$W/review_.md> in , keeping node names, rule names and ComfyUI terms as they are: @@ -32,6 +34,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. 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/references/techniques.md b/skills/comfyui-readable-node/references/techniques.md index 9481976..87d8374 100644 --- a/skills/comfyui-readable-node/references/techniques.md +++ b/skills/comfyui-readable-node/references/techniques.md @@ -102,8 +102,7 @@ After: positive conditioning → ConditioningZeroOut → negative - With cfg 1.0 the sampler does not use the negative in its calculation. The negative input only needs a conditioning connected; there is no need to encode a text. - This holds when the author wrote a negative text too (it has no effect at cfg 1.0). Replace it the same way. - - When raising cfg is an ordinary choice: write the author's negative text in the Caution of a Note (it is needed if cfg is raised). - - When a Lightning or turbo LoRA fixes cfg at 1: do not put it in a Note; remove it and say so in the conversation report. + - Do not put the author's negative text in a Note; remove it. - Does not apply: cfg is higher than 1.0 (encoding an empty text and a zeroed conditioning then give different results). - Where verified: comfy/samplers.py (with cfg 1.0 the negative is not calculated), nodes.py ConditioningZeroOut (only sets the conditioning it receives to zero). @@ -116,7 +115,7 @@ Before: the original workflow connects the LoRA's clip, so LoraLoader is used After: read only the safetensors header of the LoRA file; if there are text encoder keys, LoraLoader, otherwise LoraLoaderModelOnly ``` -- If the file is not at hand, read the header of the one on HuggingFace or similar. If you cannot check, write in the report what you did. +- If the file is not at hand, read the header of the one on HuggingFace or similar. If you cannot read it, keep the original's wiring: connecting the clip of a LoRA that has no text encoder keys changes nothing. ## String processing @@ -129,7 +128,7 @@ After: text → Replace Text (Regex)(pattern: image|photo|picture, replace: X) - Replace Text (StringReplace), Replace Text (Regex) (RegexReplace). - When it does not apply: each word is replaced with a different target (image → A, photo → B). -- Watch out: Replace Text is case-sensitive and does not look at word boundaries. Replace Text (Regex)'s case_insensitive is on by default, so to keep it the same as the original, turn it off. Adding `\b` to the pattern drops words like "images", and the result changes from the original. Which to choose is decided by meaning. +- Watch out: Replace Text is case-sensitive and does not look at word boundaries. Replace Text (Regex)'s case_insensitive is on by default, so to keep it the same as the original, turn it off. Adding `\b` to the pattern drops words like "images", and the result changes from the original. - Where verified: comfy_extras/nodes_string.py (StringReplace, RegexReplace). ### If an instruction and the body text are joined and fed into Generate Text, put the instruction in system_prompt @@ -158,15 +157,15 @@ After: A → B - Watch out: Preview as Text also has a STRING output, but do not connect anything onward from it (that would put it back in the flow). - Where verified: comfy_extras/nodes_preview_any.py (the input `source` accepts anything). -### Remove outputs that only decode and show the result of an intermediate stage +### Remove the decode of a picture that is still being drawn ``` -Before: KSampler(stage 1) → VAE Decode → Save Image / Preview Image (an intermediate picture before it has finished drawing) - KSampler(stage 1) → … → KSampler(stage 2) → … -After: KSampler(stage 1) → … → KSampler(stage 2) → … +Before: KSamplerAdvanced(steps 0–10 of 20) → VAE Decode → Preview Image + KSamplerAdvanced(steps 0–10 of 20) → KSamplerAdvanced(steps 10–20 of 20) → … +After: KSamplerAdvanced(steps 0–10 of 20) → KSamplerAdvanced(steps 10–20 of 20) → … ``` -- It has nothing to do with the final result and only makes things heavier by the decode. Remove it and write it in the report. +- The picture still has noise left in it, so there is nothing to see; the decode only makes the run heavier. Remove it. ## Reusing the latent @@ -184,17 +183,19 @@ After: reference image → VAE Encode → (edit conditioning), sampler.latent_i ## Branches and options -### A switch that chooses one from candidate values (resolutions, prompts, and so on) is kept with Get Item From List or Create List +### A switch that chooses one of the author's candidates is kept with Branch ``` -Before: candidate values A, B, C (resolutions, prompts, and so on) → (a switch that chooses one of several) → … -After: candidates A, B, C → Create List → Get Item From List(index) → … (choose by number) - candidates A, B, C → Create List → … (run them all at once) +Before: candidates A, B, C (resolutions, prompts, generated images, and so on) → (a switch that chooses one of several) → … +After: candidates A, B, C → Branch (type BranchNode; each input renamed for what it is; choose by name) → … (only the chosen one runs) + candidates A, B, C → Create List → … (run them all at once) ``` +- First decide whether the candidates are things to split (content.md, Split): Branch is for a choice inside one task. - Keep the ability to choose as a whole. Do not keep only the one that is currently chosen. -- A switch that chooses between ways of doing it is merged into the one the workflow's author chose, as in "Split" in content.md. -- Where verified: comfy_extras/nodes_toolkit.py (Create List, Get Item From List). Whether the type of the chosen value matches where it plugs in is `canvas check`. +- Its type in object_info is `BranchNode` (`add BranchNode`). In a ComfyUI that has no BranchNode, use Create List → Get Item From List(index) (it runs every candidate). +- Value nodes wired into a Branch or a Create List as candidates are not value nodes with a single target. +- Where verified: comfy_extras/nodes_logic.py (Branch: only the chosen input is evaluated; inputs renamed by double-clicking them), comfy_extras/nodes_toolkit.py (Create List, Get Item From List). Whether the type of the chosen value matches where it plugs in is `canvas check`. ### Return a build that restricts the output's resolution or shape for no reason to the standard form @@ -204,7 +205,7 @@ After: Empty Latent Image → sampler.latent_image ``` - Write in the report that it was returned. -- When it does not apply: values or builds the author chose on purpose (hand-arranged sigmas, and so on). +- When it does not apply: values the author chose on purpose (hand-arranged sigmas, and so on). - How to verify: in the node's source, how that output is decided (in this example, the latent's resolution). ## Turning custom nodes into core diff --git a/skills/comfyui-readable-node/references/understanding.md b/skills/comfyui-readable-node/references/understanding.md index 04ac929..b46ed55 100644 --- a/skills/comfyui-readable-node/references/understanding.md +++ b/skills/comfyui-readable-node/references/understanding.md @@ -15,9 +15,9 @@ The understanding of the workflow, written before building (`$W/understanding.md - What it does (from what comes out at the end and what the user wants to do; do not mistake an intermediate means for the goal). What the user puts in and gets out. - The core, and the base form (t2i / i2i / t2v …, the kind of sampler, CFG, how the model is loaded). Pre- and post-processing added to the base. Disabled functions. - Values (values changed on each generation and values that do not change once decided; which are handed out from one). Models. -- The table of custom nodes (one by one. For each function: "the value in this workflow, the default value, whether core can do it". Whether the part core cannot do changes the shape of the output. Whether to keep it or use core). +- The table of custom nodes (one by one. For each function: "the value in this workflow, the default value, whether core can do it". Whether core does the same thing the same way. Whether to keep it or use core). - For ones in replacements.md, copy that row. - - For ones not there, always look at the "core nodes with similar names" that `canvas open` gives, and check in the source. + - For ones not there, always look at the "core nodes with names close to" that `canvas open` gives, and check in the source. - Groupings (which nodes form one grouping; units of work, and units of role such as loader, text encoder, sampler). - For every node: what it does with its values here (content.md, "Read before deciding"). Then: things that look like the author's mistakes, processing that does nothing, candidates to remove and candidates to replace, and why. @@ -30,10 +30,11 @@ Read the author's Notes, group names and titles (`canvas src words`) after writi ## D. What you do not know -If there is someone to ask, ask. If you cannot ask, lean towards keeping, and report it. +The way it is built is not kept for this reason. ## E. Candidates for Notes - Explanations the user needs. - The author's techniques (ones with the author's words). -- Warnings about puzzling processing that was kept. +- What the lines of techniques.md and replacements.md say to write in a Note. +- Puzzling processing that could not be fixed, and why. diff --git a/skills/comfyui-readable-node/scripts/canvas.py b/skills/comfyui-readable-node/scripts/canvas.py index 8cdedb0..ad426ac 100644 --- a/skills/comfyui-readable-node/scripts/canvas.py +++ b/skills/comfyui-readable-node/scripts/canvas.py @@ -20,7 +20,7 @@ src node inputs/outputs, values and mode of a source node src up everything upstream of that node src words the author's words (Notes, group names, titles) - models list of models and a draft of the model Note text (from all canvases if any exist, otherwise from the source) + models list of models and a draft of the model Note text, with the custom nodes kept (from all canvases if any exist, otherwise from the source) ■ Making canvases new [from ] makes a new canvas and makes it current (one canvas per workflow). @@ -36,14 +36,17 @@ copy ... copies source nodes with their type, values and mode (no wires; ids stay the same as the source) add [] adds a new node with the object_info defaults set = ... sets values (a value that is not valid JSON is taken as a string). For a node whose type is not in object_info: = + A text of several lines: write it in a file and give =@, the path from the current folder (\\n in a line stays two characters) link . . [. . ...] connects (in pairs, any number of pairs). Output by name or index, input by name. If B. already has a wire, it is replaced. Connecting to an autogrow input (values.c etc.) adds the slot + A Branch's input is named for what it carries: link .0 . (the next input, labelled); set + branch= chooses it (the first by default) unlink . ... rm ... removes nodes (and their wires) mode ... - title sets the title (e.g. a value node's "source node name: what the value is"). The node name is not changed + title <id> <title> sets the title (e.g. a value node's "display name: what the value is"). The node name is not changed -■ Laying out (<unit> is a node id or a block name. A block moves all its nodes together) +■ Laying out (<unit> is a node id, a block name or a group's title. A block moves all its nodes together) put <unit> 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). @@ -64,34 +67,40 @@ Default: wire between neighbours that are wired, top between those that are not stack <unit> ... [below <ref>] [left|right] one column from top to bottom align <top|bottom|left|right|middle|center> <unit|all> <unit> ... aligns to the first unit (the first does not move) + align <how> <unit|all> <B> move <unit> aligns B to the first unit, moving the unit that holds B with it (a later + stage's sampler on the eye line: align top <sampler 1> <sampler 2> move <stage 2 block>) core <sampler id> prints the plan lines of the usual form around that sampler (readable-form.md, "The usual form"): sources column, model row, Load VAE, decoder, Save (Compare is left to the plan: where its wires need the fewest Reroutes). Paste them into the plan and adjust. Only for the first stage. The sampler and its sources column always; a part the usual shape lacks (a positive conditioning, a decoder) is named in a comment, to be placed by relations guide prints the lines of references/ (rules, techniques, the replacement list, examples) that name a - node on the current canvas, by node type. Run it once the nodes are built, and again before writing the plan + node on the current canvas, by node type. Run it once, after the nodes are built and before writing the plan inputs <id> puts the sources wired directly into that node in one right-aligned column on its left (in input order, top to bottom). Only the sources move; a source an earlier stage's sampler also takes stays with that stage. Column height: the source that carries the conditioning enters at the node's height (KSampler: the positive wire - horizontal; SamplerCustomAdvanced: the guider's wire horizontal); a node that takes neither is centred on the column + horizontal); SamplerCustomAdvanced is centred on the column; any other node has its chain wire (else its first wired input) horizontal shape <laid-out block> <block to lay out> [right|below|left|above <ref>] places the nodes of the second block in the same shape as the first (nodes of the same type are matched in order). For laying out similar stages, or giving split workflows the same layout level <A>.<output> <B>.<input> [move <unit>] moves so that this wire is horizontal (default: moves B) + B in an `inputs` column (a side value made level into it): the gap above B takes the room + (the other gaps stay), the side value is set level, a centred sampler is centred last block <name> <id> ... makes a block (making it again replaces it). unblock <name> group <title> <unit> ... [color <color>] makes a group. The frame is recomputed from its nodes every time (padding measured from hand-made layouts) ungroup <title> group-align <title> ... aligns the top and bottom edges of these groups color <color|none> <id> ... color (red brown green blue pale_blue cyan purple yellow black) - rail <A>.<output> [above <unit>|below <unit>|level <X>.<output>] to <B>.<input> ... + rail <A>.<output> [above <unit>|below <unit>|level <X>.<output>] [move <unit>] to <B>.<input> ... Rail: carries A's output to many targets along a straight path of Reroutes. What you need to know: 1. Write all targets on one line. The rail runs at the height written (above X / below X / level X.output) or, - with none written, at the source's output height. The canvas does not look for a height, move the source or - move nodes to make room: place the source and the targets so the rail runs where the rules want it (model, - vae, clip from the top; conditioning above the samplers and below those). + with none written, at the source's output height. Where their runs overlap, model, vae, clip and conditioning + rails run in that order from the top: the canvas raises a rail that would run below one of a later type + (a raising Reroute then stands by its source; with `move <unit>` the unit holding the source moves up or down + so its output is at the rail's height, and no Reroute is needed). Place the source + and the targets so the rail runs where the rules want it (conditioning above the samplers). 2. The rail is drawn as written, with its Reroutes, even where a direct wire would pass behind nothing (the check then names a Reroute that does nothing). Where a wire is better direct, do not write it on the rail. - 3. A rail that runs behind a node is drawn anyway and named in the check: place the source or the targets differently. + 3. A rail whose wires cross behind a node is drawn anyway and named in the check: place the source or the targets differently. note <md file> <right|left|below|above> <ref> ... places a MarkdownNote (default width 400, height from the text), as put places (alignment, a second reference, all). In a layout, note lines and lines naming a Note run last, after the rails, in the order written; those that use all after the others. A @@ -104,7 +113,7 @@ Stops on an unknown id, block or group, on a Note or Reroute id, on a node in two parts, and on a part without text; names the nodes in no part review <md file> registers the review of the current canvas's exported workflow (references/review.md): the table - | rule | nodes | what to change | answer |, "No findings." or "Not reviewed: <why>". Node numbers are those of the exported + | rule | nodes | what to change | answer |, "No findings." or "Not reviewed: <why>" (a canvas that differs from another only in values). Node numbers are those of the exported workflow; they are shown with the canvas ids. The report page shows every row; finish stops while a canvas has no review or a row has no answer @@ -150,12 +159,14 @@ horizontal, samplers off the eye line, a main flow wire that is not horizontal, a side-use image rail above, a Reroute raising a loader's rail, a loader away from its first user, a wire into Compare or another output hidden behind a node that saves, sampler sources not right-aligned, - the model Note off the top edge, a Note away from the node it explains, nodes the replacement list replaces); then the ones that weigh less + the model Note off the top edge, a Note away from the node it explains, nodes the replacement list replaces); then more (single values on Reroutes, an image or latent wire hidden behind a preview node, a title the author - gave, other slanted wires one move makes horizontal). They are reported, and stop nothing + gave, other slanted wires one move makes horizontal). All are fixed in the plan; only the export stops stop export diff compares the source with all canvases (values, inputs the user fills in, outputs, mode, model Note) - render <png> [export] picture (for the review: with export, the node numbers of the exported workflow) - export <json> writes a workflow that ComfyUI can open + render <png> [export] picture (for the review: with export, the node numbers of the exported workflow, and a .txt of the + same name with each node's title and every Note's text, which the picture cannot draw) + export <json> writes a workflow that ComfyUI can open. Not while the check names a positive slanting into the + sampler, overlapping groups or a Reroute raising a loader's rail: it stops, writes nothing and lists those lines; change the plan report <html> [<language code>] writes the report page: it steps through every command on every canvas (for the user to see what was done). Give the user's language code (en, ja, zh, fr, ...; en by default). The page's @@ -173,6 +184,7 @@ import copy import hashlib import json +import math import re import os import shlex @@ -211,9 +223,6 @@ # 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 -# rails without a written height run at their source's output height: the canvas does not look for a height, move nodes -# to open a lane, or swap heights. The plan places the sources -PLAN_RAILS = True # 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 @@ -243,7 +252,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", "canvas_note", "layout_prev", "group_note", "note_ref"} +CANVAS_MARKS = {"size_min", "width_set", "loader_base", "loader_shift", "loader_x", "canvas_note", "layout_prev", "group_note", "note_ref"} class Stop(Exception): @@ -275,6 +284,10 @@ def display_title(n, oi): "VHS_LoadImages", "VHS_LoadImagesPath", "VHS_LoadImagePath"} +# widgets that draw the image themselves (the widgetType of an input, or the type of a socketless input) +OWN_IMAGE_WIDGETS = {"PAINTER", "IMAGECOMPARE"} + + def image_kind(t, oi): """Whether a node type shows an image, recognised from object_info (by type name only for LOADS_WITH_PREVIEW): "save" for an output node that takes an IMAGE or VIDEO input and saves files ("save" in its category or name, or a @@ -286,6 +299,10 @@ def image_kind(t, oi): if t in LOADS_WITH_PREVIEW: return "load" specs = [(nm, CS._spec_type_and_opts(sp)) for nm, sp, _ in CS.ordered_input_specs(info) if isinstance(sp, (list, tuple)) and sp] + # a node that shows the image in a widget of its own (Painter's drawing area, Compare Images' comparison view): the + # size the frontend makes it (FRONTEND_MIN) already holds that widget, so no image area goes below it + if any(opts.get("widgetType") in OWN_IMAGE_WIDGETS or typ in OWN_IMAGE_WIDGETS for _, (typ, opts) in specs): + return None if any(any(opts.get(f) for f in IMAGE_UPLOAD_FLAGS) for _, (_, opts) in specs): return "load" if not info.get("output_node") or not any(typ in ("IMAGE", "VIDEO") for _, (typ, _) in specs): @@ -430,8 +447,11 @@ def same_loader_width(self): for n in self.s["nodes"]: if "loader_base" in n: n["size"][0] = max(n.pop("loader_base"), (n.get("size_min") or [0, 0])[0]) - if n.get("pos") is not None: - n["pos"][0] += n.pop("loader_shift", 0) + # undo the shift only where the node still stands where widening put it: a layout that placed it again + # wrote its x anew (shifting that x back left the loader off the edge it was placed on) + 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 ls = [n for n in self.s["nodes"] if self.is_model_loader(n) and n.get("size")] if not ls: return @@ -457,6 +477,7 @@ def same_loader_width(self): 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 @@ -505,6 +526,8 @@ def same_column_loader_width(self): continue n["loader_base"] = n.get("loader_base", w - d) n["loader_shift"] = n.get("loader_shift", 0) + (d if right else 0) + if n["loader_shift"]: + n["loader_x"] = n["pos"][0] # where widening left it: the shift is undone only while it stands there self.changed.add(n["id"]) def stacked(self, n, m): @@ -513,9 +536,10 @@ def stacked(self, n, m): return min(r[2], q[2]) > max(r[0], q[0]) and (0 <= q[1] - r[3] <= V_GAP + 1 or 0 <= r[1] - q[3] <= V_GAP + 1) def sticks_out(self, n, base): - """Whether loader n, widened from base, sticks out past the right edge of a sampler stacked right above or below - it in its column (a Load VAE above a KSampler made wider than the KSampler). Above another node (a Load CLIP above - Format Text) it is widened like the other loaders.""" + """Whether loader n, widened from base, sticks out past the right edge or the left edge of a sampler stacked + right above or below it in its column (a Load VAE above a KSampler made wider than the KSampler, or widened to the + left off the KSampler's left edge). Above another node (a Load CLIP above Format Text) it is widened like the + other loaders.""" r = G.rect(n) for m in self.s["nodes"]: if m is n or not self.placed(m) or m.get("type") in {"Reroute"} | NOTE_TYPES or self.is_model_loader(m): @@ -524,7 +548,7 @@ def sticks_out(self, n, base): if not is_sampler(m): continue stacked = min(r[2], q[2]) > max(r[0], q[0]) and (0 <= q[1] - r[3] <= V_GAP + 1 or 0 <= r[1] - q[3] <= V_GAP + 1) - if stacked and r[2] > q[2] and n["size"][0] > base: + if stacked and (r[2] > q[2] or r[0] < q[0] - 0.5) and n["size"][0] > base: return True return False @@ -537,7 +561,16 @@ def save(self): # ---- lookup @property def nodes(self): - return {n["id"]: n for n in self.s["nodes"]} + # asked millions of times by the checks: the map is built again only when the node list changes (another list, + # another length, or other nodes at its ends; the list itself is held, so its id cannot be reused) + ns = self.s["nodes"] + c = getattr(self, "_nodes_cache", None) + if (c and c[0] is ns and c[1] == len(ns) and (not ns or (c[2] is ns[0] and c[3] is ns[-1])) + and all(c[4].get(n["id"]) is n for n in (ns[:1] + ns[-1:]))): + return c[4] + m = {n["id"]: n for n in ns} + self._nodes_cache = (ns, len(ns), ns[0] if ns else None, ns[-1] if ns else None, m) + return m def node(self, nid): n = self.nodes.get(nid) @@ -618,10 +651,38 @@ def port_in(self, tok): for i in n.get("inputs") or []: if i["name"].lower() == p.lower(): return nid, i["name"] - if self.grow_input(n, p) or self.widget_input(n, p): + if self.grow_input(n, p) or self.widget_input(n, p) or self.added_input(n, p): return nid, p + if n.get("type") == "BranchNode" and "." not in p: + return nid, self.branch_input(n, p) + if "." not in p: + # an autogrow input written by its short name (image_1 for images.image_1, a for values.a), as the frontend + # shows it: taken when it names one input, or one that the autogrow group can add + full = [i["name"] for i in n.get("inputs") or [] if i["name"].lower().endswith("." + p.lower())] + if len(full) == 1: + return nid, full[0] + groups = sorted({i["name"].split(".")[0] for i in n.get("inputs") or [] if "." in i["name"]}) + added = [g for g in groups if self.grow_input(n, f"{g}.{p}")] + if len(added) == 1: + return nid, f"{added[0]}.{p}" raise Stop(f"{nid} has no input {p} ({', '.join(i['name'] for i in n.get('inputs') or [])})") + def branch_input(self, n, label): + """A Branch input named for what it carries: the input with that label, or the next autogrow.branchN, labelled + (the frontend shows the label and chooses by it).""" + for i in n.get("inputs") or []: + if i.get("label") == label: + return i["name"] + grow = [i for i in n.get("inputs") or [] if i["name"].startswith("autogrow.")] + free = next((i for i in grow if not i.get("link") and not i.get("label")), None) + if free is None: + name = f"autogrow.branch{len(grow)}" + if not self.grow_input(n, name): + raise Stop(f"{n['id']} cannot take another input") + free = next(i for i in n["inputs"] if i["name"] == name) + free["label"] = label + return free["name"] + def widget_input(self, n, name): """Gives a widget its input slot (seed, text, ...), as the frontend does when a wire is dropped on the widget. True if the node has such a widget.""" @@ -648,10 +709,31 @@ def grow_input(self, n, name): saved = names + [name] if name not in [x for x, _ in CS.input_slots(info, n["widgets_values"], saved)]: return False - keep = {i["name"]: i.get("link") for i in n.get("inputs") or []} + return self.rebuild_inputs(n, info, saved, name) + + def added_input(self, n, name): + """An input the current definition has and the saved node lacks (saved by an older version): the frontend builds + the node from the current definition, so it shows the input. True if it was added.""" + info = self.oi.get(n.get("type")) + if not info or not isinstance(n.get("widgets_values"), list): + return False + names = [i["name"] for i in n.get("inputs") or []] + current = [x for x, _ in CS.input_slots(info, n["widgets_values"], names)] + # only when every saved input is still there (otherwise rebuilding would drop one) + if name not in current or not set(names) <= set(current): + return False + return self.rebuild_inputs(n, info, names, name) + + def rebuild_inputs(self, n, info, saved, name): + """The node's inputs in the frontend's order for the current definition. The inputs the node has keep their + wires and their labels (a Branch's names).""" + keep = {i["name"]: i for i in n.get("inputs") or []} ins, _ = CS.new_node_slots(info, n["widgets_values"], saved) for i in ins: - i["link"] = keep.get(i["name"]) + old = keep.get(i["name"], {}) + i["link"] = old.get("link") + if old.get("label"): + i["label"] = old["label"] n["inputs"] = ins self.out.append(f"added input: {n['id']}.{name}") return True @@ -688,6 +770,9 @@ def relink(self): outs = o.get("outputs") or [] if l["origin_slot"] < len(outs): outs[l["origin_slot"]]["links"].append(l["id"]) + for n in nodes.values(): + if n.get("type") == "BranchNode": + branch_values(n) def add_link(self, oid, slot, tid, tin): self.s["links"] = [l for l in self.s["links"] if not (l["target_id"] == tid and l["target_input"] == tin)] @@ -709,8 +794,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 - if n.get("pos") is not None: - n["pos"][0] += n.pop("loader_shift", 0) + 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 title = display_title(n, self.oi) size = nodesize.default_size(n, self.oi, title=title) if size is None: @@ -747,12 +833,26 @@ def size_node(self, n): w, h = max(w, P["PREVIEW_TEXT_SIZE"][0]), max(h, P["PREVIEW_TEXT_SIZE"][1]) if self.is_sam3_prompt(n): w, h = SAM3_PROMPT_SIZE + elif self.is_negative_prompt(n): + # a negative prompt is short (a long negative is rare, and often it is a Conditioning Zero Out instead): half + # the height the node is made with (the skill author), even below TEXT_MIN_H + h = round(h / 2) old = n.get("size") n["size"] = [round(w), round(h)] if old and old != n["size"]: self.out.append(f"size {n['id']}: {old} → {n['size']}") self.changed.add(n["id"]) + def is_negative_prompt(self, n): + """A node with a text area whose conditioning goes only into negative inputs (followed through Reroutes).""" + if "CONDITIONING" not in [o.get("type") for o in n.get("outputs") or []]: + return False + names, grow = RD.widget_info(n, self.oi) + if not any(x in grow for x in names): + return False + ends = ends_through_reroutes(self, n["id"]) + return bool(ends) and all(l.get("target_input") == "negative" for l in ends) + def is_sam3_prompt(self, n): """A CLIP Text Encode whose conditioning goes only into SAM3 nodes (followed through Reroutes).""" if n.get("type") != "CLIPTextEncode": @@ -898,6 +998,44 @@ def workflow(self): return wf, ids +def picture_text(wf, oi): + """The words of an exported workflow that its picture does not draw: each node's number and title as ComfyUI shows + it, each group's title (the picture draws only its ASCII letters), and the text of every Note.""" + lines, notes = ["# Node titles", ""], ["", "# Note texts"] + groups = [g.get("title") or "" for g in wf.get("groups") or []] + for n in sorted(wf["nodes"], key=lambda n: n["id"]): + if n.get("type") == "Reroute": + continue + lines.append(f"{n['id']}: {display_title(n, oi)}") + if n.get("type") in NOTE_TYPES: + notes += ["", f"## {n['id']}: {display_title(n, oi)}", "", str((n.get("widgets_values") or [""])[0]).rstrip()] + gl = (["", "# Group titles", ""] + [f"- {t}" for t in groups]) if groups else [] + return "\n".join(lines + gl + notes) + "\n" + + +def branch_values(n): + """A Branch's values as the frontend saves them: the chosen name, then the names of the connected inputs (their + labels, or branch0, branch1 …). The choice stays when it is still one of them, otherwise the first.""" + names = [i.get("label") or i["name"].split(".", 1)[1] for i in n.get("inputs") or [] + if i["name"].startswith("autogrow.") and i.get("link")] + wv = n.get("widgets_values") if isinstance(n.get("widgets_values"), list) else [] + # the choice is kept even while its input is not wired yet (wires come one at a time); the check says when it is + # not one of the connected inputs + chosen = wv[0] if wv and wv[0] else (names[0] if names else "") + n["widgets_values"] = [chosen, names] + + +def branch_problems(cv): + out = [] + for n in cv.s["nodes"]: + if n.get("type") == "BranchNode" and isinstance(n.get("widgets_values"), list) and len(n["widgets_values"]) == 2: + chosen, names = n["widgets_values"] + if chosen not in names: + out.append(f"Branch {n['id']} chooses {chosen!r}, which is none of its connected inputs ({', '.join(names) or 'none'}): " + f"set {n['id']} branch=<one of them>") + return out + + # ---------------------------------------------------------------- checks def wires_of(cv): @@ -1099,8 +1237,36 @@ def upstream(nid, typ): for nid in reversed(cchain): out.append(f"put {nid} left {prev} wire") prev = nid - anchor = cchain[0] if cchain else guider - if mchain: + # the model chain ends in the column just left of the guider (readable-form §4): the node put left of it + anchor = cchain[-1] if cchain else guider + # the chain's last node stands just left of the leftmost node it feeds (readable-form §4): when it also gives the + # text encoders their CLIP (Load Checkpoint, a LoRA), left of them, so that wire does not go back + # the encoder's CLIP traced up (through CLIP Set Last Layer and the like) to the end of the model chain + cchain_clip = upstream(anchor, "CLIP") if mchain and anchor else [] + if mchain and mchain[-1] in cchain_clip: + between = cchain_clip[cchain_clip.index(mchain[-1]) + 1:] + prev = anchor + for nid in reversed(between): + out.append(f"put {nid} left {prev} wire") + prev = nid + out += [f"block model_{sid} {' '.join(mchain)}", f"row {' '.join(mchain)}", + f"put model_{sid} left {prev} top # {mchain[-1]} also gives the text encoders their CLIP: left of them; its model wire may slant"] + elif mchain and any(x in cchain_clip for x in mchain): + # a node inside the chain gives the encoders their CLIP (Load Checkpoint → LoRA → a model patch): it stands just + # left of the encoders, so that wire does not go back; the rest of the chain ends on a row above the encoders + gi = max(i for i, x in enumerate(mchain) if x in cchain_clip) + between = cchain_clip[cchain_clip.index(mchain[gi]) + 1:] + prev = anchor + for nid in reversed(between): + out.append(f"put {nid} left {prev} wire") + prev = nid + head, rest = mchain[:gi + 1], mchain[gi + 1:] + out += [f"block model_{sid} {' '.join(head)}", f"row {' '.join(head)}", + f"put model_{sid} left {prev} top # {mchain[gi]} gives the text encoders their CLIP: left of them"] + if rest: + out += [f"block model_rest_{sid} {' '.join(rest)}", f"row {' '.join(rest)}", + f"put model_rest_{sid} above {anchor} right # the rest of the model chain ends above the encoders"] + elif mchain: 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: @@ -1112,11 +1278,17 @@ def upstream(nid, typ): out.append(f"# no decoder takes {sid}'s latent: place what follows by relations" + (f", the next sampler level with it (put {nxt[0]} right {sid} wire)" if nxt else "")) if save: - out.append(f"put {save} right {dec} wire") + # the flow goes on past the decoder to a later node: Save steps down so that wire passes above it (a staircase) + goes_on = any(not is_output_node(cv, n) for n in outs_of(dec)) + out.append(f"put {save} right {dec} step # the flow goes on past {dec}: Save steps down" if goes_on + else f"put {save} right {dec} wire") 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") - out.append("# not placed here: Load CLIP (the column of the text encoders), the size nodes, " + 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") return out @@ -1293,13 +1465,37 @@ def _chk_narrow(cv, c): def _chk_hidden(cv, c): out = [] nodes, ws = c.nodes, c.ws # noqa: F841 - hw = hidden_wires(cv) + allh = hidden_wires(cv) + 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) for l, nid in hw: out.append(f"wire behind a node: {lname(cv, l)} ({l['type']}) passes behind {nid}") return out +def _entry_exit(cv, l, nid): + """The heights where a wire goes in behind a node and comes out (its first and last points inside the node).""" + r = G.rect(cv.nodes[nid]) + ys = [y for x, y in cv.wire_pts(l) or [] if r[0] <= x <= r[2] and r[1] <= y <= r[3]] + return (ys[0], ys[-1]) if ys else None + + +def crosses_behind(cv, l, nid, allh=None): + """readable-form §3 (Fine): wires passing behind a node may, when they do not cross each other behind it (they come + out in the order they went in). True when this wire crosses another wire behind the same node.""" + a = _entry_exit(cv, l, nid) + if not a: + return False + for l2, n2 in (allh if allh is not None else hidden_wires(cv, only={nid})): + if n2 != nid or l2 is l: + continue + b = _entry_exit(cv, l2, nid) + if b and (a[0] - b[0]) * (a[1] - b[1]) < 0: + return True + return False + + @check_rule("crossings") def _chk_cross(cv, c): out = [] @@ -1379,8 +1575,8 @@ def one_move_levels(cv): dy = b[1] - a[1] if abs(dy) < 1: continue - if t.get("type") == "SamplerCustomAdvanced" and l["target_input"] in SCA_SIDE_INPUTS: - continue + if t.get("type") == "SamplerCustomAdvanced": + continue # it stands in the vertical middle of its sources column (its form): its inputs may slant, latent_image too if (is_output_node(cv, t) or any(t["id"] in u for u in cv.s.get("stepped") or [])) and dy > 0: continue # a staircase: the plan stepped it down below the wire passing on if cv.is_loader(o): @@ -1390,12 +1586,6 @@ def one_move_levels(cv): for start, other, d in ((t["id"], o["id"], -dy), (o["id"], t["id"], dy)): # a node stacked with another source of a node it feeds stands in that node's sources column (`inputs`): # moving it alone breaks the column - fed = {m["target_id"] for m in cv.s["links"] if m["origin_id"] == start} - sib = {m["origin_id"] for m in cv.s["links"] if m["target_id"] in fed and m["origin_id"] != start} - r = G.rect(nodes[start]) - if any(min(r[2], q[2]) > max(r[0], q[0]) and (0 <= q[1] - r[3] <= V_GAP + 1 or 0 <= r[1] - q[3] <= V_GAP + 1) - for q in (G.rect(m) for m in solid if m["id"] in sib)): - continue mv = move_closure(cv, solid, {start}, d, {other}, pairs) if mv and not any(is_sampler(nodes[i]) for i in mv) and not lands_on_reroute(cv, mv, d): # the sampler fixes the band: it does not move for a side wire; and the move makes no other Bad form @@ -1524,14 +1714,56 @@ def _chk_sampler_inputs(cv, c): and all(is_sampler(nodes.get(m["target_id"], {})) for m in cv.s["links"] if m["origin_id"] == model)): out.append(f"model chain end {model} {nodes[model]['type']}: its right edge ({round(G.rect(nodes[model])[2])}) is not " f"the right edge of the column of {n['id']}'s sources ({max(rights.values())})") + # a scheduler or guider in that column takes the model (SamplerCustomAdvanced): the chain ends in the column left + # of them, so that its wire into them goes forward + elif rights and not model: + end = _model_chain_end_left_of(cv, nodes, n["id"], srcs) + if end: + m, r, (target, by) = end + out.append(f"model chain end {m} {nodes[m]['type']}: its right edge ({round(G.rect(nodes[m])[2])}) is not " + f"the right edge of the column left of {r} {nodes[r]['type']} ({target}, {by} {nodes[by]['type']})") return out +def _model_chain_end_left_of(cv, nodes, sid, srcs): + """The last node of a model chain whose model goes into a node of the sampler's column of sources, when its right + edge is not that of the column just left of the column: (its id, the node it feeds, (that column's right edge, the + node giving it)).""" + col_left = min(G.rect(nodes[i])[0] for i in srcs) + # the column just left is made of this stage's nodes: what feeds this sampler, not what feeds an earlier stage's + mine = upstream(cv.s, sid) + for p in [i for i in mine if is_sampler(nodes.get(i, {}))]: + mine -= upstream(cv.s, p) | {p} + for r in srcs: + for l in cv.s["links"]: + if l["target_id"] != r or (l.get("type") or "") != "MODEL": + continue + m = nodes.get(l["origin_id"]) + if not m or not cv.placed(m) or m.get("type") in {"Reroute"} | NOTE_TYPES or m["id"] in srcs: + continue + # it feeds only that column or samplers (a node that also feeds others stays where those wires go forward) + if not all(m2["target_id"] in srcs or is_sampler(nodes.get(m2["target_id"], {})) + for m2 in cv.s["links"] if m2["origin_id"] == m["id"]): + continue + rm = G.rect(m) + if rm[2] > G.rect(nodes[r])[0]: + continue # a wire going back: the backward-wire check says it + # the column just left: the nodes between the chain's row and the bottom of the column of sources + bottom = max(G.rect(nodes[i])[3] for i in srcs) + edges = [(round(G.rect(o)[2]), o["id"]) for o in cv.s["nodes"] + if o["id"] in mine and cv.placed(o) and o["id"] != m["id"] and o["id"] not in srcs + and o.get("type") not in {"Reroute"} | NOTE_TYPES + and G.rect(o)[2] <= col_left and G.rect(o)[3] > rm[1] and G.rect(o)[1] < bottom] + if edges and abs(round(rm[2]) - max(edges)[0]) > 2: + return m["id"], r, max(edges) + return None + + @check_rule("empty band across everything") def _chk_empty_band(cv, c): out = [] nodes, ws = c.nodes, c.ws # noqa: F841 - # an empty band running across the whole canvas is wider than the minimum gap (space left without a reason) + # an empty band running across the whole canvas is wider than the minimum gap # Notes and Reroutes do not count (a band that only rails cross is still empty) rs = sorted(G.rect(n) for n in cv.s["nodes"] if cv.placed(n) and n.get("type") not in {"Reroute"} | NOTE_TYPES) if rs: @@ -1539,7 +1771,7 @@ def _chk_empty_band(cv, c): cur = spans[0][1] for y0, y1 in spans[1:]: if y0 - cur > V_GAP: - out.append(f"empty band across everything ({round(y0 - cur)}px tall, min {V_GAP}): y {round(cur)}-{round(y0)}. Is it empty without a reason?") + out.append(f"empty band across everything ({round(y0 - cur)}px tall, min {V_GAP}): y {round(cur)}-{round(y0)}: close it") cur = max(cur, y1) return out @@ -1564,6 +1796,10 @@ 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']}") + # 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 " + f"put … above/below the other, and the canvas gives them one width: {a['id']} and {b['id']}") if ov_y and not ov_x and a.get("type") in VALUE_TYPES and b.get("type") in VALUE_TYPES: gap_h = max(rb[0] - ra[2], ra[0] - rb[2]) if 0 <= gap_h <= H_GAP * 2 and abs(ra[1] - rb[1]) >= 1: @@ -1636,7 +1872,7 @@ def is_decode(n): def _chk_loader_order(cv, c): out = [] nodes, ws = c.nodes, c.ws # noqa: F841 - # loaders stacked in one column go from the top: model, vae, clip (checkpoint loaders are not counted) + # loaders stacked in one column: the vae and clip loaders below the model loader (checkpoint loaders are not counted) kinds = {} for n in cv.s["nodes"]: k = single_loader_kind(cv, n) if cv.placed(n) else None @@ -1649,12 +1885,8 @@ def _chk_loader_order(cv, c): for n in kinds.get(k, []): 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"loaders stacked in one column go model, vae, clip from the top") - for v in kinds.get("VAE", []): - for n in kinds.get("CLIP", []): - if same_stack(cv, v["id"], n["id"], col) and G.rect(n)[1] < G.rect(v)[1]: - out.append(f"clip loader {n['id']} is above the vae loader {v['id']}: loaders stacked in one column go " - f"model, vae, clip from the top") + f"the vae and clip loaders stacked in one column go below the model loader") + # vae and clip take either order: Load VAE may stand below the text encoders, below Load CLIP return out @@ -1912,7 +2144,7 @@ def _chk_below_growing(cv, c): best = b if best: out.append(f"{best['id']} is directly below {a['id']} ({why}), which grows in ComfyUI: " - f"move it out from below (staircase, another column)") + f"leave the room it grows below it (for a sampler {SAMPLER_GROW}px; a rail written `below` that node runs below that room), or wire it directly") return out @@ -2107,7 +2339,8 @@ def _nearest_points(r1, r2): @check_rule("Note away from its node") def _chk_note_away(cv, c): """notes.md, Where to place: a Note on part of the processing stands next to the node it explains (the node its 🔗 line - names). Bad: other nodes between them.""" + names). Bad: other nodes between them while a place next to that node is clear. With no clear place next to it, the + Note stands away (a Note does not move the workflow to make room) and the line says it is allowed.""" out = [] placed = [n for n in cv.s["nodes"] if cv.placed(n)] for n in placed: @@ -2130,11 +2363,40 @@ def _chk_note_away(cv, c): if best is None or len(between) < len(best[1]): best = (t["id"], between) if best and best[1]: - out.append(f"Note {n['id']} explains {best[0]}, but other nodes stand between them: {' '.join(best[1])} " - f"(place it right, left, above or below {best[0]})") + spot = _note_spot_next_to(cv, n, best[0]) + if spot: + out.append(f"Note {n['id']} explains {best[0]}, but other nodes stand between them: {' '.join(best[1])} " + f"(there is room next to it: write note <its file> {spot})") + else: + out.append(f"Note {n['id']} explains {best[0]} from away: no room next to {best[0]} " + f"(allowed: its 🔗 line names it; nodes are not moved for a Note)") return out +def _note_spot_next_to(cv, n, tid): + """A clear place for Note n next to node tid, as a note line's place ("right 12 top"), or None.""" + keep, out_len = list(n["pos"]), len(cv.out) + moved, changed = dict(cv.moved), set(cv.changed) + try: + for side, align in (("right", "top"), ("right", "bottom"), ("below", "left"), ("below", "right"), + ("left", "top"), ("left", "bottom"), ("above", "left"), ("above", "right")): + try: + _put_rel(cv, [n["id"]], side, [tid], align, None) + except Stop: + continue + if not note_trouble(cv, n["id"], away=False): + return f"{side} {tid} {align}" + return None + finally: + # trying places leaves nothing behind: not the place, not the record of what moved + n["pos"] = keep + del cv.out[out_len:] + cv.moved.clear() + cv.moved.update(moved) + cv.changed.clear() + cv.changed.update(changed) + + def note_room_in_frame(cv, n): """For a Note placed as part of a group: (how many px it widens the frame, a note line that keeps it inside the frame next to a node of the group, or None when there is no such room). None when it widens nothing.""" @@ -2233,7 +2495,7 @@ def _chk_model_note_top(cv, c): if m.get("type") in NOTE_TYPES and cv.placed(m) and "## models" in str((m.get("widgets_values") or [""])[0]): tops = [G.rect(o)[1] for o in cv.s["nodes"] if cv.placed(o) and o.get("type") not in NOTE_TYPES] + frames if tops and abs(G.rect(m)[1] - min(tops)) >= 1: - out.append(f"model Note top edge is not aligned with the top of the whole workflow ({round(min(tops))}): {m['id']}") + out.append(f"model Note top edge is not aligned with the top of the topmost node or group frame ({round(min(tops))}): {m['id']}") return out @@ -2332,8 +2594,17 @@ def _chk_rail_at_output(cv, c): if m["origin_id"] == n["id"] and m["origin_slot"] != l["origin_slot"] and nodes.get(m["target_id"], {}).get("type") == "Reroute"] if not blocked and not any(abs(sy - a0[1]) < P["RAIL_GAP"] for sy in near): + # a model, vae, clip or conditioning rail that the rail order raised: at the output height it would run + # below a rail of a later type, so only placing its source helps + t = rail_type(cv, n["id"], l["origin_slot"]) + raised = t in RAIL_STACK_ORDER and any( + rail_type(cv, *root) in RAIL_STACK_ORDER and RAIL_STACK_ORDER.index(rail_type(cv, *root)) > RAIL_STACK_ORDER.index(t) + and sy < a0[1] and min(sx1, xmax) > max(sx0, a0[0]) for sy, sx0, sx1, root in rail_spans(cv)) + how = (f"the rail order (model, vae, clip, conditioning from the top) puts the rail there: place {n['id']} so its " + f"output is at the rail height (rail ... move <its unit> to ...)" if raised else + f"leave the height out of the rail line, or place {n['id']} at the height the rail should run") out.append(f"rail needs no raising Reroute ({r['id']}, {abs(round(ry - a0[1]))}px off) if drawn at the output height: output of {n['id']}" - f" (leave the height out of the rail line, or place {n['id']} at the height the rail should run)") + f" ({how})") return out @@ -2475,7 +2746,7 @@ def _chk_rail_type_order(cv, c): other = tb if ta == "CONDITIONING" else ta cy, oy = (ya, yb) if ta == "CONDITIONING" else (yb, ya) if other in ("MODEL", "VAE") and cy < oy: - out.append(f"CONDITIONING rail runs above the {other} rail (conditioning below model and vae): " + out.append(f"CONDITIONING rail runs above the {other} rail (model, vae, clip, conditioning from the top): " f"rail of {ra if ta == 'CONDITIONING' else rb} and rail of {rb if ta == 'CONDITIONING' else ra}") continue # a model rail headed by the model chain (a LoRA after Load Checkpoint) still runs above the vae and clip rails of @@ -2530,7 +2801,9 @@ def _chk_author_titles(cv, c): t = n.get("title") if not t or n.get("type") in {"Reroute"} | NOTE_TYPES or not cv.placed(n): continue - shown = (cv.oi.get(n.get("type")) or {}).get("display_name") or n.get("type") + if n.get("type") not in cv.oi: + continue # not installed: its display name is in its source, which the canvas cannot read + shown = cv.oi[n["type"]].get("display_name") or n["type"] if t == shown or (may_say_what(cv, n) and t.startswith(shown + ":")): continue out.append(f"title the author gave left on a node (names go back to the display name \"{shown}\"): {n['id']}") @@ -2623,11 +2896,19 @@ def _chk_loader_raise(cv, c): if any(o2["id"] == o["id"] and s2 != slot for o2, s2, _ in starts): continue # a loader with several rails (a checkpoint): only one can run at its output height ay, ry = cv.out_xy(o["id"], slot)[1], cv.out_xy(r["id"], 0)[1] + # 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 {}) + 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] if abs(ay - ry) < 1 or not (ox1 <= rx <= ox1 + H_GAP): continue out.append(f"raising Reroute right of a loader or the node heading a rail ({r['id']}): place {o['id']} so its output is at the " - f"rail height (it heads the rail; leave the rail's height out), and the Reroute is not needed: {o['id']}") + f"rail height (it heads the rail: leave the rail's height out, or write rail ... move <its unit> to ...), and the Reroute is not needed: {o['id']}") return out @@ -2698,7 +2979,7 @@ def _chk_validate(cv, c): n["mode"] = 0 # a node's mode is the author's choice, not a problem; the mode is compared by diff for p in VD.check(flat, cv.oi): out.append(p) - return out + return out + branch_problems(cv) def _behind_output_node(cv, line): @@ -2743,8 +3024,7 @@ def passes_on(t): def _chain_link_line(cv, line): """Whether the wire of a 'one move makes horizontal' line is a link of a chain: its source sends out only this wire - and its target takes in only this wire. Hand-made layouts leave other wires slanted on purpose (dev measure: 219 such - wires in 34 of 35 hand-made layouts, 12 chain links).""" + and its target takes in only this wire.""" m = re.search(r": (\S+?)\.\S+ → (\S+?)\.(\S+?) \(write level", line) if not m: return False @@ -2772,8 +3052,7 @@ def _chk_positive_level(cv, c): if not (x0 - GAP_WIDE - 1 <= G.rect(o)[2] <= x0 - H_GAP / 3): continue a, b = cv.out_xy(o["id"], lp["origin_slot"]), cv.in_xy(n["id"], "positive") - # its top on the sampler's top is the same form: the output stands one slot (20px) above the input - if a and b and abs(a[1] - b[1]) > 20 and abs(G.rect(o)[1] - G.rect(n)[1]) > 20: + if a and b and abs(a[1] - b[1]) >= 1: out.append(f"positive into the sampler slants: {lname(cv, lp)} ({round(b[1] - a[1])}px); place {o['id']} so it " f"enters {n['id']} level, and what else stands in that column (upscale, VAE Encode) on the row below") return out @@ -2811,9 +3090,9 @@ def _stage_entry(cv, sid, nodes): @check_rule("result wire level, latent into the sampler slants") def _chk_stage_entry_level(cv, c): - """readable-form §1: a stage taking the previous stage's result: its own chain stands with its sampler (the latent - level, or the top edges aligned), and the wire from the previous stage into that chain is the one that slants. A - notice: which of the two is the skill author's choice either way.""" + """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.""" out = [] for n in cv.s["nodes"]: # a sampler taking its sources in one column (SamplerCustomAdvanced: the latent last) has its own level wire @@ -2825,7 +3104,7 @@ def _chk_stage_entry_level(cv, c): lk, lat = e lp = next((l for l in cv.s["links"] if l["target_id"] == n["id"] and l["target_input"] == "positive"), None) pa, pb = (cv.out_xy(lp["origin_id"], lp["origin_slot"]), cv.in_xy(n["id"], "positive")) if lp else (None, None) - if pa and pb and abs(pa[1] - pb[1]) <= 20: + if pa and pb and abs(pa[1] - pb[1]) < 1: continue # the conditioning enters level: the chain stands on the row below and its latent slants if not all(cv.placed(c.nodes.get(x["origin_id"], {})) for x in (lk, lat)): continue @@ -2833,12 +3112,9 @@ def _chk_stage_entry_level(cv, c): 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: continue - # the chain standing with the sampler, top edges aligned, is as good (the conditioning does not enter level either) - if abs(G.rect(c.nodes[lat["origin_id"]])[1] - G.rect(n)[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']} (its latent " - f"level, or its top on {n['id']}'s top), and let the wire from the previous stage slant") + 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") return out @@ -2864,7 +3140,7 @@ def _chk_one_line_text(cv, c): return out -# check lines that match a Bad line of the rules exactly, with no Fine or Undecided around them: they cannot be kept. +# check lines that match a Bad line of the rules exactly, with no Fine around them: they cannot be kept. # {check name: which of its lines} HARD_CHECKS = { "overlaps": lambda cv, l: l.startswith("overlap"), @@ -2880,8 +3156,7 @@ def _chk_one_line_text(cv, c): "one-line text into a text area": lambda cv, l: True, "narrow gaps": lambda cv, l: "a Note too close to a node" in l, "positive into the sampler slants": lambda cv, l: True, - # a Reroute lifting a rail off its source's output height where a line at that height passes behind nothing (the skill - # author lays rails at their output height; a second eye line for a loop is the one exception they make) + # a Reroute lifting a rail off its source's output height where a line at that height passes behind nothing "rails that can run at the output height": lambda cv, l: True, "Reroutes doing nothing": lambda cv, l: l.startswith(("Reroute doing nothing", "Reroute connected to nothing")), "consecutive Reroutes": lambda cv, l: True, @@ -2894,12 +3169,11 @@ def _chk_one_line_text(cv, c): # a rail lifted by a Reroute right after the node heading it "raising Reroutes right of a loader": lambda cv, l: True, "loaders away from their first user": lambda cv, l: True, - # a loader stacked above the model loader; clip above vae is not one (the skill author's - # Qwen layouts stack clip above vae, 10 of 10) + # a loader stacked above the model loader "loader order": lambda cv, l: "above the model loader" in l, "right edges of sampler inputs": lambda cv, l: not l.startswith("model chain end"), "model Note top edge": lambda cv, l: True, - "Note away from its node": lambda cv, l: True, + "Note away from its node": lambda cv, l: "stand between them" in l, "Note widening its group": lambda cv, l: True, "reference wire level, chain wire slanted": lambda cv, l: True, # the sampler → decode → save wires. The skill author's LTX layouts set the decode midway between the video and @@ -2909,10 +3183,9 @@ def _chk_one_line_text(cv, c): "custom nodes the replacement list turns into core": lambda cv, l: True, } -# forms the rules call Bad that weigh less: reported after the others, to fix when it costs nothing else +# more forms the rules call Bad: reported after the others, fixed in the plan the same way SOFT_CHECKS = { - # a node set midway between two wires it merges is a liking of the skill author's (their LTX layouts), so it weighs - # less; the form to write levels the chain wire + # a node set midway between two wires it merges: the form to write levels the chain wire "no wire level into a merging node": lambda cv, l: True, "image into VAE Encode slanted": lambda cv, l: True, "right edges of sampler inputs": lambda cv, l: l.startswith("model chain end"), @@ -2940,6 +3213,28 @@ def full_check(cv): return [ln for _, ln in lines], count +# check lines that stop export: the workflow is not written while one is left. Each is a form the plan can change +EXPORT_STOPS = { + "positive into the sampler slants": lambda cv, l: True, + "group titles, overhangs and overlaps": lambda cv, l: l.startswith("groups overlap"), + # only a loader of a model, clip or vae; the last node of a model chain heading a rail is still only said + "raising Reroutes right of a loader": lambda cv, l: cv.is_model_loader(cv.nodes.get(l.rsplit(": ", 1)[-1].strip()) or {}), +} + + +def export_stops(cv): + """The check lines that stop export (EXPORT_STOPS), each with what to change in the plan.""" + lines, _ = checked(cv) + out = [] + for name, ln in lines: + if name in EXPORT_STOPS and EXPORT_STOPS[name](cv, ln): + if ln.startswith("groups overlap"): + ln += (" (place the nodes of one group as a block, apart from the other group's nodes: a frame is drawn" + " around its nodes, so moving the whole group moves its frame)") + out.append(ln) + return out + + def hard_problems(cv): """The check lines that cannot be kept (HARD_CHECKS).""" lines, _ = checked(cv) @@ -2947,7 +3242,7 @@ def hard_problems(cv): def soft_problems(cv): - """The check lines of Bad forms that weigh less (SOFT_CHECKS).""" + """The check lines of the Bad forms in SOFT_CHECKS (listed after the others).""" lines, _ = checked(cv) return [ln for name, ln in lines if name in SOFT_CHECKS and SOFT_CHECKS[name](cv, ln)] @@ -3095,7 +3390,7 @@ def do_open(work, args): wf_path = str(work.dir / "source.ui.json") jdump(wf_path, ui) out.append(f"API format: {len(ui['nodes'])} nodes. There were no positions, sizes, groups, Notes or bypassed nodes; " - f"placed as ComfyUI places them when it opens an API-format file (source.ui.json). Say so in the report") + f"placed as ComfyUI places them when it opens an API-format file (source.ui.json)") out += [f"warning: {w}" for w in warns] flat, warns = load_source(wf_path, oi) out.append(f"read: {len(flat['nodes'])} nodes, {len(flat['links'])} wires") @@ -3132,6 +3427,11 @@ def do_open(work, args): flat["links"] = [l for l in flat["links"] if l["origin_id"] not in drop and l["target_id"] not in drop] for i, why in gone: out.append(f"removed: {i} {nodes[i]['type']} ({why})") + # deprecated nodes the replacement list did not replace (deprecated: true in object_info; the display name does not + # always say so): content.md sends them to their successor, which the agent finds in the source + for n in flat["nodes"]: + if (oi.get(n["type"]) or {}).get("deprecated"): + out.append(f"deprecated: {n['id']} {n['type']} ({display_title(n, oi)}). Find its successor in the source") flat["source"] = str(Path(wf_path).resolve()) jdump(work.dir / "src.flat.json", flat) work.cfg["source"] = flat["source"] @@ -3214,9 +3514,16 @@ def src_summary(flat, oi): stopped = [n for n in flat["nodes"] if n.get("mode") in (2, 4)] if stopped: out.append(f"disabled nodes {len(stopped)}: " + ", ".join(f"{n['id']} {n['type']} ({'mute' if n['mode'] == 2 else 'bypass'})" for n in stopped)) - sw = [n for n in flat["nodes"] if "switch" in n["type"].lower()] + sw = [n for n in flat["nodes"] if "switch" in n["type"].lower() or n["type"] == "BranchNode"] if sw: - out.append("switch: " + ", ".join(f"{n['id']} {n['type']}" for n in sw)) + def what(n): + if n["type"] != "BranchNode": + return f"{n['id']} {n['type']}" + wv = n.get("widgets_values") if isinstance(n.get("widgets_values"), list) else [] + names = [i.get("label") or i["name"].split(".", 1)[1] for i in n.get("inputs") or [] + if i["name"].startswith("autogrow.") and i.get("link")] + return f"{n['id']} Branch (inputs {', '.join(names) or 'none'}; chosen {wv[0] if wv else '?'})" + out.append("switch: " + ", ".join(what(n) for n in sw)) cust = {} for n in flat["nodes"]: if n["type"] not in NOTE_TYPES and is_custom(n["type"], oi): @@ -3489,9 +3796,45 @@ def do_models(work): + (" (file name too generic to look up)" if m.get("too_generic") else "")) out.append("draft of the model Note text (fill in unknown folders and URLs from the author's Notes, or search for the file):") out.append(NT.model_note_text(list(found.values()))) + packs = custom_packs(work, flat["nodes"]) + if packs: + out.append("") + out.append(NT.custom_nodes_text(packs)) return out +def custom_packs(work, nodes): + """The custom node packs the nodes need, as {(label, url, type): [display names]}. The pack comes from the node's + cnr_id (Registry) or aux_id (GitHub), or from a node of the same type in the source; ("?", None) when neither is + known (one line per type: the source search fills each in, or says it was not found).""" + src_props = {} + for n in work.src()["nodes"]: + p = n.get("properties") or {} + if p.get("cnr_id") or p.get("aux_id"): + src_props.setdefault(n["type"], p) + packs = {} + for n in nodes: + t = n.get("type") + if CS.pack_of(t, work.oi) in ("core", "frontend"): + continue + p = n.get("properties") or {} + if not (p.get("cnr_id") or p.get("aux_id")): + p = src_props.get(t, p) + cnr, aux = p.get("cnr_id"), p.get("aux_id") + if cnr == "comfy-core": + continue + if cnr: + key = (cnr, f"https://registry.comfy.org/nodes/{cnr}", "") + elif aux and "/" in aux: + key = (aux, f"https://github.com/{aux}", "") + else: + key = ("?", None, t) + name = (work.oi.get(t) or {}).get("display_name") or t + if name not in packs.setdefault(key, []): + packs[key].append(name) + return packs + + # ---------------------------------------------------------------- commands def parse_opts(args, flags=(), keyed=()): @@ -4213,7 +4556,7 @@ def _run_cmd(work, line): if hard: out += violations(hard) if soft: - out += violations(soft, "weigh less: fix them when it breaks nothing above") + out += violations(soft) if rest: out += [f"notices ({len(rest)}):"] + [" " + ln for ln in rest] return out if len(out) > 1 else [head, "no problems"] @@ -4232,10 +4575,20 @@ def _run_cmd(work, line): # first picture until the review is registered counts (a picture drawn again after fixing is not a new review) work.cfg.setdefault("review_render", {}).setdefault(cv.name, workflow_hash(wf)) work.save_cfg() + # what the picture cannot draw (its font has Latin letters only, and no Note text), for the reviewer + txt = str(Path(args[0]).with_suffix(".txt")) + Path(txt).write_text(picture_text(wf, cv.oi), encoding="utf-8") + work.consume(txt) + return [f"picture: {args[0]}", f"names and Note texts: {txt}"] return [f"picture: {args[0]}"] if cmd == "export": if not args: raise Stop("export <json>") + stops = export_stops(cv) + if stops: + raise Stop(f"not exported ({len(stops)} line{'s' if len(stops) > 1 else ''} below). The workflow is written only " + "when none is left; each is removed by changing the plan and running layout again:\n" + + "\n".join(f" {ln}" for ln in stops)) wf, ids = cv.workflow() Path(args[0]).parent.mkdir(parents=True, exist_ok=True) jdump(args[0], wf) @@ -4341,6 +4694,26 @@ def _op_add(cv, work, args): cv.out.append(f"added: {nid} {t}") +def set_value(v): + """The value of a set line: <file> after @ is read as it is (a text of several lines), and a missing file stops; a valid JSON value is read as + JSON; anything else is a string. A string holding the two characters backslash and n stops: in a plan line they do + not become a line break, so a text of several lines is written in a file and given as @<file>.""" + if v.startswith("@"): + f = Path(v[1:]) + if not f.is_file(): + raise Stop(f"{v}: no file {f.resolve()} (the path is read from the current folder, not from --dir). " + f"A string that begins with @ is given as JSON in single quotes: '\"{v}\"'") + return f.read_text(encoding="utf-8").rstrip("\n") + try: + return json.loads(v) + except json.JSONDecodeError: + pass + if "\\n" in v: + raise Stop("a value holds \\n, which stays two characters in a plan line, not a line break: write the text in a file " + "and give it as <widget>=@<file>") + return v + + def _op_set(cv, work, args): if len(args) < 2: raise Stop("set <id> <widget>=<value> ...") @@ -4356,16 +4729,20 @@ def _op_set(cv, work, args): k, sep, v = kv.partition("=") if not sep or k not in vals: raise Stop(f"write the values of {n['id']} by name ({', '.join(x for x in vals if not isinstance(vals[x], dict))})") - try: - v = json.loads(v) - except json.JSONDecodeError: - pass + v = set_value(v) cv.out.append(f"value {n['id']}.{k}: {json.dumps(vals[k], ensure_ascii=False)[:60]} → {json.dumps(v, ensure_ascii=False)[:60]}") vals[k] = v cv.changed.add(n["id"]) return if not isinstance(vals, list): raise Stop(f"cannot read the value list of {n['id']}") + if n.get("type") == "BranchNode": + names = vals[1] if len(vals) == 2 and isinstance(vals[1], list) else [] + for kv in args[1:]: + k, _, v = kv.partition("=") + if k == "branch" and v not in names: + raise Stop(f"{n['id']} has no connected input named {v!r} ({', '.join(names) or 'none'}): link it first, " + f"or choose one of them") if not info: # type not in object_info (custom node not installed): write by index in the value list for kv in args[1:]: @@ -4373,10 +4750,7 @@ def _op_set(cv, work, args): if not k.isdigit() or int(k) >= len(vals): raise Stop(f"the type of {n['id']} is not in object_info. Write by index in the value list (0-{len(vals) - 1}): " + ", ".join(f"{i}={json.dumps(x, ensure_ascii=False)[:30]}" for i, x in enumerate(vals))) - try: - v = json.loads(v) - except json.JSONDecodeError: - pass + v = set_value(v) cv.out.append(f"value {n['id']}[{k}]: {json.dumps(vals[int(k)], ensure_ascii=False)[:60]} → {json.dumps(v, ensure_ascii=False)[:60]}") vals[int(k)] = v cv.changed.add(n["id"]) @@ -4385,10 +4759,7 @@ def _op_set(cv, work, args): if "=" not in kv: raise Stop(f"{kv}: write <widget>=<value>") k, v = kv.split("=", 1) - try: - v = json.loads(v) - except json.JSONDecodeError: - pass + v = set_value(v) names = CS.widget_names(info, vals) dyn = CS.widget_spec(info, k, dict(zip(names, vals))) if k in names and dyn is not None and CS._spec_type_and_opts(dyn)[0] == "COMFY_DYNAMICCOMBO_V3": @@ -4568,10 +4939,19 @@ def _op_stack(cv, work, args): def _op_align(cv, work, args): + args, opt = parse_opts(args, keyed=("move",)) if len(args) < 3: - raise Stop("align <top|bottom|left|right|middle|center> <unit> ...") + raise Stop("align <top|bottom|left|right|middle|center> <unit> ... [move <unit>]") how, units = args[0], [cv.unit(args[1], allow_all=True)] + [cv.unit(t) for t in args[2:]] - units[0] = without(units[0], [i for u in units[1:] for i in u]) + # B is aligned, the unit holding it moves (as level ... move <unit>) + moving = None + if "move" in opt: + if len(units) != 2: + raise Stop("align <how> <unit> <B> move <unit>: one B, the node the move is measured on") + moving = cv.unit(opt["move"]) + if not set(units[1]) <= set(moving): + raise Stop(f"{opt['move']} does not hold {args[2]}: move the unit that holds it") + units[0] = without(units[0], [i for u in units[1:] for i in u] + (moving or [])) rb = ref_box(cv, units[0]) for u in units[1:]: b = cv.bbox(u) @@ -4590,7 +4970,7 @@ def _op_align(cv, work, args): dx = (rb[0] + rb[2]) / 2 - (b[0] + b[2]) / 2 else: raise Stop(f"unknown alignment {how} (top bottom middle left right center)") - cv.translate(u, dx, dy) + cv.translate(moving or u, dx, dy) def _op_inputs(cv, work, args): @@ -4621,30 +5001,36 @@ def _op_inputs(cv, work, args): rt = G.rect(t) right = rt[0] - gap y = 0 - for sid in srcs: + for k, sid in enumerate(srcs): n = cv.node(sid) h = n["size"][1] + G.title_height(n) + # a group frame between two sources keeps its padding, as put below does + y += frame_pad(cv, [sid], [srcs[k - 1]], "below") if k else 0 cv.set_rect_xy(sid, right - n["size"][0], y) y += h + V_GAP # column height: the node stays (it stands on the eye line) and the column moves to it. The source that carries the - # conditioning enters at the node's height: for KSampler etc. the positive wire is horizontal, for - # SamplerCustomAdvanced the guider's wire is (the sampler was centred on its column, and the column - # had nowhere to go). A node that takes neither is centred on the column + # conditioning enters at the node's height: for KSampler etc. the positive wire is horizontal. A node that takes no + # conditioning (SamplerCustomAdvanced: its conditioning enters the guider) is centred on the column; the guider's + # wire into it slants pos_l = next((l for l in cv.s["links"] if l["target_id"] == tid and l.get("type") == "CONDITIONING" and l["target_input"] in ("positive", "conditioning") and l["origin_id"] in srcs), None) - gd_l = next((l for l in cv.s["links"] if l["target_id"] == tid and l.get("type") == "GUIDER" - and l["origin_id"] in srcs), None) + # any other node (two latents into a concat): its chain wire is horizontal, else its first wired input + # (readable-form §3: level, not set midway between its sources) + ci = chain_input(cv, t) + first_l = next((l for name in ([ci] if ci else []) + order for l in cv.s["links"] + if l["target_id"] == tid and l["target_input"] == name and l["origin_id"] in srcs), None) if pos_l: dy = cv.in_xy(tid, pos_l["target_input"])[1] - cv.out_xy(pos_l["origin_id"], pos_l["origin_slot"])[1] how = "positive wire horizontal" - elif gd_l: - dy = cv.in_xy(tid, gd_l["target_input"])[1] - cv.out_xy(gd_l["origin_id"], gd_l["origin_slot"])[1] - how = "guider wire horizontal" + elif t.get("type") != "SamplerCustomAdvanced" and first_l: + dy = cv.in_xy(tid, first_l["target_input"])[1] - cv.out_xy(first_l["origin_id"], first_l["origin_slot"])[1] + how = f"{first_l['target_input']} wire horizontal" else: col = cv.bbox(srcs) dy = (rt[1] + rt[3]) / 2 - (col[1] + col[3]) / 2 how = "node centred on the column" cv.translate(srcs, 0, dy) + cv.s.setdefault("inputs_cols", {})[tid] = {"srcs": list(srcs), "centre": how == "node centred on the column"} cv.out.append(f"sources of {tid} in one right-aligned column on its left ({how}): {' '.join(srcs)}") @@ -4712,6 +5098,99 @@ def _op_level(cv, work, args): cv.translate(moved, 0, dy) if mv and set(mv) - set(ids): cv.out.append(f"moved along to keep their wires level: {' '.join(sorted(set(mv) - set(ids)))}") + for col_t, col in (cv.s.get("inputs_cols") or {}).items(): + if set(moved) & set(col["srcs"]) and col_t not in moved: + respace_inputs_column(cv, col_t, col) + + +def respace_inputs_column(cv, tid, col): + """A `level` moved a node of tid's sources column (a side value made level into it). The column stays as it is + except where the side value needs room: 1. nodes below that now come closer than the row gap move down; 2. the nodes + that were wired level into a column node from outside it (the side value, the positive encoder) are set level to it + again. A node going down carries what it pushes; a node going up moves with what is level to it and goes no further + than it stays clear (the main flow is not pushed for a side value): if it cannot reach, the gap above its target + takes the rest (the target and the nodes below it go down), and the others keep the row gap (the skill author: the + room shows where the wire needs it); 3. last, a node centred on its column (SamplerCustomAdvanced) is centred + again, with what is wired level to it and what is stacked on it.""" + srcs = [i for i in col["srcs"] if i in cv.nodes and cv.placed(cv.node(i))] + if len(srcs) < 2: + return + srcs.sort(key=lambda i: G.rect(cv.node(i))[1]) + in_col = set(srcs) + level_in = [l for l in cv.s["links"] if l["target_id"] in in_col and l["origin_id"] not in in_col | {tid} + and cv.placed(cv.node(l["origin_id"])) and cv.node(l["origin_id"]).get("type") != "Reroute" + and abs(cv.out_xy(l["origin_id"], l["origin_slot"])[1] - cv.in_xy(l["target_id"], l["target_input"])[1]) < 1] + level_in.sort(key=lambda l: G.rect(cv.node(l["target_id"]))[1]) + # the pairs wired level outside the column as they stand now: they stay level whatever the rounds move + pairs0 = [(a, b) for a, b in horizontal_pairs(cv) if not ({a, b} & (in_col | {tid}))] + for k in range(1, len(srcs)): + a, b = G.rect(cv.node(srcs[k - 1])), G.rect(cv.node(srcs[k])) + if b[1] - a[3] < V_GAP: + cv.translate(srcs[k:], 0, V_GAP - (b[1] - a[3])) + + def clear_at(ids, d): + """Whether ids moved by d stand clear of every other node by the row gap above and below.""" + others = [G.rect(m) for m in cv.s["nodes"] if cv.placed(m) and m["id"] not in ids + and m.get("type") != "Reroute" and m.get("type") not in NOTE_TYPES] + for i in ids: + r = G.rect(cv.node(i)) + box = (r[0], r[1] + d - V_GAP - 1, r[2], r[3] + d + V_GAP + 1) + if any(rect_overlap(box, q) for q in others): + return False + return True + + def clear_up(ids, u): + """How far ids can go up (u < 0) and stay clear, in eighths of u.""" + best, step = 0, -abs(u) / 8 + for k in range(1, 9): + if clear_at(ids, step * k): + best = step * k + else: + break + return best + + # repeated until every side value reaches (moving one target can move another's) + for _ in range(20): + solid = [m for m in cv.s["nodes"] if cv.placed(m) and m.get("type") != "Reroute" and m.get("type") not in NOTE_TYPES] + short = None + for l in level_in: + d = cv.in_xy(l["target_id"], l["target_input"])[1] - cv.out_xy(l["origin_id"], l["origin_slot"])[1] + if abs(d) < 0.5: + continue + # the node and what is wired level to it outside the column (a Load CLIP level with the positive encoder) + grp, todo = set(), [l["origin_id"]] + while todo: + x = todo.pop() + if x not in grp: + grp.add(x) + todo += [b for a, b in pairs0 if a == x] + [a for a, b in pairs0 if b == x] + if d > 0 and not clear_at(grp, d): + pairs = pairs0 + mv = move_closure(cv, solid, {l["origin_id"]}, d, in_col | {tid}, pairs) + cv.translate(sorted(mv) if mv else [], 0, d) + continue + ids = grp + u = d if clear_at(ids, d) else clear_up(ids, d) + cv.translate(sorted(ids), 0, u) + if u - d >= 0.5: + short = (l["target_id"], u - d) + break + if not short: + break + # the gap above the target takes the rest: the target and what is below it go down + k = srcs.index(short[0]) + cv.translate(srcs[k:], 0, math.ceil(short[1])) + if col.get("centre"): + solid = [m for m in cv.s["nodes"] if cv.placed(m) and m.get("type") != "Reroute" and m.get("type") not in NOTE_TYPES] + t, box = cv.node(tid), cv.bbox(srcs) + rt = G.rect(t) + d = round((box[1] + box[3]) / 2 - (rt[1] + rt[3]) / 2) + if abs(d) >= 0.5: + stacked = {m["id"] for m in solid if m["id"] != tid and m["id"] not in in_col and cv.stacked(t, m)} + pairs = [(a, b) for a, b in horizontal_pairs(cv) if not ({a, b} & in_col)] + mv = move_closure(cv, solid, {tid} | stacked, d, in_col, pairs) + cv.translate(sorted(mv) if mv else sorted({tid} | stacked), 0, d) + cv.out.append(f"sources of {tid} given room for the level" + (f", {tid} centred on them again" if col.get("centre") else "")) def _op_width(cv, work, args): @@ -4727,6 +5206,7 @@ def _op_width(cv, work, args): for n in ns: n.pop("loader_base", None) # so the loader width alignment does not undo a width set by hand n.pop("loader_shift", None) + n.pop("loader_x", None) n["width_set"] = True if n["size"][0] != w: n["size_min"] = [w, 0] @@ -4841,6 +5321,9 @@ def _op_note(cv, work, args): # every Note has the default width (a Note as narrow as the node it sat on grew tall and was pushed into gaps) w = NT.NOTE_W h = max(NT.NOTE_MIN[1], NT.note_height(text, w)) + if Path(pos[0]).stem in (cv.s.get("blocks") or {}): + # the Note's id is its file name; a block of that name would make every later line naming it ambiguous + raise Stop(f"the Note file {pos[0]} has the name of a block ({Path(pos[0]).stem}): rename the file") nid = Path(pos[0]).stem if Path(pos[0]).stem not in cv.nodes else f"{Path(pos[0]).stem}_{cv.s['next_id']}" cv.s["next_id"] += 1 n = {"id": nid, "type": "MarkdownNote", "mode": 0, "inputs": [], "outputs": [], "properties": {}, @@ -4875,6 +5358,25 @@ def _op_note(cv, work, args): grow = any(cv.placed(cv.node(i)) and grows(cv, cv.node(i)) for i in unit) tries += [[side, ref] for side in ("right", "left", "above", "below") if side != where[0] and not (side == "below" and grow)] + # above or below a node with no edge written: the Note (wider than most nodes) sticks out to the side where nothing + # stands. A node right of the ref: right edges aligned (it sticks out left); a node left: left edges aligned; none or + # both: centred. The other two are tried after, and the first that is clear is kept (notes.md: a Note touching a node) + if where[0] in ("above", "below") and len(where) == 2 and where[1] != "all": + try: + rb = cv.bbox(cv.unit(where[1])) + except Stop: + rb = None + if rb: + # a neighbour beside the ref or beside where the Note goes + y0, y1 = (rb[1], rb[3] + V_GAP + h) if where[0] == "below" else (rb[1] - V_GAP - h, rb[3]) + others = [G.rect(o) for o in cv.s["nodes"] if o["id"] != nid and cv.placed(o) and o["id"] not in cv.unit(where[1])] + near = [r for r in others if r[1] < y1 and r[3] > y0] + right = any(rb[2] < r[0] < rb[2] + w for r in near) + left = any(rb[0] - w < r[2] < rb[0] for r in near) + first = "right" if right and not left else "left" if left and not right else "center" + order = [first] + [a for a in ("center", "right", "left") if a != first] + tries = [[where[0], where[1], a] for a in order] + tries[1:] + where = tries[0] best = None for k, wh in enumerate(tries): n["pos"] = None @@ -4900,14 +5402,16 @@ def _op_note(cv, work, args): cv.out.append(f"Note {nid}: width {w}, height {round(h)}") -def note_trouble(cv, nid): +def note_trouble(cv, nid, away=True): """What is wrong with where a Note stands: it overlaps something, stands too close to a node, a wire passes behind - it, it stands right below a node that grows, or other nodes stand between it and the node it explains.""" + it, it stands right below a node that grows, or (away) other nodes stand between it and the node it explains while + a place next to that node is clear.""" only = {nid} return ([f"overlap {a} {b}" for a, b in overlaps(cv, only)] + [f"narrow {a} {b}" for a, b, *_ in narrow(cv, only)] + [f"wire behind {lname(cv, l)}" for l, _ in hidden_wires(cv, only) if _ == nid] + [x for x in _chk_below_growing(cv, _CheckCtx(cv)) if nid in x.split()] - + [x for x in _chk_note_away(cv, None) if x.startswith(f"Note {nid} ")]) + + ([x for x in _chk_note_away(cv, None) if x.startswith(f"Note {nid} ") and "stand between them" in x] + if away else [])) def _review_cells(line): @@ -4927,12 +5431,12 @@ def _review_cells(line): REFS = Path(__file__).resolve().parent.parent / "references" -REVIEW_RULE_FILES = ("readable-form.md", "content.md", "notes.md") +REVIEW_RULE_FILES = ("readable-form.md", "notes.md") def _op_review(cv, work, args): """Registers the review of the exported workflow (references/review.md): a table | rule | nodes | what to change | answer |, - "No findings.", or "Not reviewed: <why>", and the reviewer's last line "Checked: …". + "No findings.", or "Not reviewed: <why>" (a canvas that differs from another only in values), and the reviewer's last line "Checked: …". The node numbers are those of the exported workflow; they are shown with the canvas ids.""" if not args: raise Stop("review <md file>") @@ -4947,9 +5451,11 @@ def _op_review(cv, work, args): not_reviewed = next((ln for ln in lines if ln.lower().startswith("not reviewed:")), None) no_findings = any(ln.lower() == "no findings." for ln in lines) checked = next((ln for ln in lines if ln.lower().startswith("checked:")), None) - if not body and not not_reviewed and not no_findings: + # rows the reviewer withdrew after the builder sent them back once (references/review.md) + withdrawn = [ln[len("withdrawn:"):].strip() for ln in lines if ln.lower().startswith("withdrawn:")] + if not body and not not_reviewed and not no_findings and not withdrawn: raise Stop("the review has no rows. Write the table | rule | nodes | what to change | answer |, the line " - "\"No findings.\" when the reviewer found nothing, or \"Not reviewed: <why>\" when no other agent could review it") + "\"No findings.\" when the reviewer found nothing, or \"Not reviewed: <why>\" for a canvas that differs from another only in values") wf, ids = cv.workflow() now = workflow_hash(wf) to_canvas = {str(v): k for k, v in ids.items()} @@ -4965,7 +5471,7 @@ def _op_review(cv, work, args): unknown += [t for t in nums if t not in to_canvas] rows.append({"rule": cells[0], "nodes": cells[1], "ids": [to_canvas[t] for t in nums if t in to_canvas], "change": cells[2], "answer": answer}) - # a row is left only with a reason the rules give: a quoted line of a rule file (a Fine or Undecided line, or the + # a row is left only with a reason the rules give: a quoted line of a rule file (a Fine line, or the # bold line of the rule the fix would break), each row its own reason rules_text = " ".join(" ".join((REFS / f).read_text(encoding="utf-8").split()) for f in REVIEW_RULE_FILES if (REFS / f).is_file()) lefts = {} @@ -4980,8 +5486,8 @@ def _op_review(cv, work, args): lefts[why] = r["rule"] quotes = [" ".join(q.split()) for q in re.findall(r'"([^"]+)"|“([^”]+)”|「([^」]+)」', a) for q in q if q] if not any(len(q) >= 8 and q in rules_text for q in quotes): - raise Stop(f"\"{a}\": a row is left only with a quoted line of {', '.join(REVIEW_RULE_FILES)} (a Fine or " - f"Undecided line, or the bold line of the rule the fix would break), written as it is in the file " + 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") seen = (work.cfg.get("review_render") or {}).get(cv.name) if any(r["answer"].lower().startswith("fixed") for r in rows) and seen == now: @@ -4989,9 +5495,9 @@ def _op_review(cv, work, args): (work.cfg.get("review_render") or {}).pop(cv.name, None) # the next picture is for a new review work.save_cfg() cv.s["review"] = {"rows": rows, "not_reviewed": not_reviewed if not rows else None, - "no_findings": no_findings and not rows, "checked": checked, "hash": now} + "no_findings": no_findings and not rows, "checked": checked, "hash": now, "withdrawn": withdrawn} if not_reviewed and not rows: - cv.out.append(f"review of {cv.name}: {not_reviewed} (the report page says so; say it in the conversation report too)") + cv.out.append(f"review of {cv.name}: {not_reviewed} (the report page says so)") return open_rows = [r for r in rows if not r["answer"]] cv.out.append(f"review of {cv.name}: {len(rows)} rows" + (f", {len(open_rows)} without an answer" if open_rows else "") @@ -5000,6 +5506,8 @@ def _op_review(cv, work, args): cv.out.append(f" not a node of the exported workflow (check the reviewer's ids): {' '.join(dict.fromkeys(unknown))}") for r in rows: cv.out.append(f" {r['rule']} — {' '.join(r['ids']) or r['nodes']} — {r['answer'] or '(no answer yet)'}") + for w in withdrawn: + cv.out.append(f" withdrawn by the reviewer: {w}") cv.out.append(" run `report` again after this, so that the report page shows the review") @@ -5291,6 +5799,7 @@ def stacked(ids, ref, how): if prev and u: stacked(u, prev, "below") elif op == "align" and args and args[0] in ("top", "bottom", "middle") and len(args) > 2: + args = parse_opts(args, keyed=("move",))[0] ref = unit(args[1]) if ref: a = _bottom_node(cv, ref) if args[0] == "bottom" else _top_node(cv, ref) @@ -5456,9 +5965,8 @@ def apart(a, b, ya, yb): if eyes and typ == "CONDITIONING": cut = min(cut, min(eyes)) # a conditioning rail runs above the samplers even from below them (rail_side) geo.append([x0, x1, run, out_y, typ, cut, spec]) - # the order of overlapping rails: model, vae, clip from one loader or one stacked column; conditioning below the - # model and vae rails; the others by their cuts. Cuts are made to follow the fixed order first, so no cycle forms - col = stacks(cv) + # the order of overlapping rails: model, vae, clip, conditioning from the top; the others by their cuts. Cuts are + # made to follow the fixed order first, so no cycle forms must = [] for i in range(len(rails)): for j in range(len(rails)): @@ -5466,10 +5974,8 @@ def apart(a, b, ya, yb): if i == j or min(gi[1], gj[1]) <= max(gi[0], gj[0]): continue ti, tj = gi[4], gj[4] - if ti in RAIL_TYPE_ORDER and tj in RAIL_TYPE_ORDER and same_stack(cv, rails[i][3], rails[j][3], col) \ - and RAIL_TYPE_ORDER.index(ti) < RAIL_TYPE_ORDER.index(tj): - must.append((i, j)) - elif ti in ("MODEL", "VAE") and tj == "CONDITIONING": + # model, vae, clip, conditioning from the top, whatever their sources (as order_rails_by_type) + if ti in RAIL_STACK_ORDER and tj in RAIL_STACK_ORDER and RAIL_STACK_ORDER.index(ti) < RAIL_STACK_ORDER.index(tj): must.append((i, j)) for _ in range(len(rails) + 1): changed = False @@ -5695,7 +6201,7 @@ def do_layout(cv, work, args): n.pop("title", None) cv.size_node(n) widened = n.pop("size_min", None) is not None - if n.pop("width_set", None) or widened or n.get("type") == "CLIPTextEncode": + 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) # also clear widths widened by the plan's width and start again from the initial size (a leftover width would not go back when the plan is edited) cv.size_node(n) @@ -5715,6 +6221,7 @@ def do_layout(cv, work, args): cv.wide_gaps = [] cv.s["wide_pairs"] = [] cv.plan_rels, cv.inputs_columns = [], set() + cv.s["inputs_cols"] = {} cv.s["stepped"] = [] cv.clip_loader_role_color() cv.plan_group_lines = [] @@ -5733,6 +6240,35 @@ def do_layout(cv, work, args): mark = len(cv.out) _op_title(cv, work, toks[1:]) del cv.out[mark:] + # a model loader put right above or below a sampler stands in the sampler's column: the two get one width, the wider + # one's (a loader never narrower than LOADER_MIN_W), set before anything is placed so the columns beside are placed + # for it. width_set keeps the loader width alignment off them; the next layout sizes them again from the start + for raw in lines: + try: + toks = shlex.split(raw, comments=True) + except ValueError: + continue + pairs = [] + if len(toks) >= 4 and toks[0] == "put" and toks[1] in cv.nodes: + # put X above|below Y, also as the second reference (put X right A above Y) + pairs += [(toks[1], toks[k + 1]) for k in range(2, len(toks) - 1) + if toks[k] in ("above", "below") and toks[k + 1] in cv.nodes] + elif len(toks) >= 3 and toks[0] == "stack": + ids = [t for t in toks[1:] if t in cv.nodes] + pairs += list(zip(ids, ids[1:])) + for x_id, y_id in pairs: + a, b = cv.node(x_id), cv.node(y_id) + if any(cv.is_model_loader(x) and is_sampler(y) for x, y in ((a, b), (b, a))) and a.get("size") and b.get("size"): + for n in (a, b): + if "loader_base" in n: # the width the loader width alignment gave is not its own + n["size"][0] = max(n.pop("loader_base"), (n.get("size_min") or [0, 0])[0]) + n.pop("loader_shift", None) + n.pop("loader_x", None) + w = max(a["size"][0], b["size"][0], LOADER_MIN_W) + for n in (a, b): + n["width_set"] = True + n["size_min"] = [w, 0] + n["size"][0] = w later = [] note_ids = set() for raw in lines: @@ -5747,6 +6283,8 @@ def in_group_note(toks): """The title of the group holding every node the Note line is placed against, once those nodes stand; else None.""" if len(toks) < 4 or toks[3] == "all" or Path(toks[1]).stem in cv.nodes: return None + if toks[3] not in cv.nodes and toks[3] not in cv.s["blocks"]: + return None # placed against a whole group: the Note stands outside it, not in it try: ref = set(cv.unit(toks[3])) except Stop: @@ -5829,13 +6367,19 @@ def run_line(k, raw, toks): for m in (clear_below_growing(cv) if AUTO_FIX else []): notes.append(f" {m}") hand.append({"line": 0, "plan": "", "why": m}) - # rails without a written height, after every other line: first each one's height (moving nodes where needed; a later - # move carries the heights already chosen along when it moves their source and targets), then their Reroutes. + # rails without a written height, after every other line: each runs at its source's output height (no node moves), + # raised only by the rail order; then their Reroutes. # The order does not follow the plan: loaders of model, clip and vae first (they head their rails), then from the left # and from the top, so the same rails give the same result whatever order the plan writes them in rails = [] + rail_move = {} for k, raw, args in drawn_later: + args, mv = split_rail_move(args) + if mv: + rail_move[k] = mv try: + if mv: + cv.unit(mv[1]) oid, slot = cv.port_out(args[0]) if not cv.placed(cv.node(oid)): raise Stop(f"the rail source {oid} is not placed yet") @@ -5882,14 +6426,11 @@ def written(i): continue a = cv.out_xy(oid, slot) tins = [cv.port_in(t) for t in args[args.index("to") + 1:]] - if not PLAN_RAILS and all(wire_clear(cv, a, cv.in_xy(tid, tin), {oid, tid}) for tid, tin in tins): - notes.append(f" line {k}: every target is reached directly; the written height ({spec} {args[2]}) is not used") - continue try: if spec == "above": y = cv.bbox(cv.unit(args[2]))[1] - V_GAP elif spec == "below": - y = cv.bbox(cv.unit(args[2]))[3] + V_GAP + y = rail_below_y(cv, cv.unit(args[2])) else: y = cv.out_xy(*cv.port_out(args[2]))[1] except Stop as e: @@ -5907,61 +6448,26 @@ def written(i): lanes[i] = [y, oid, slot, targets] fixed.add(i) - def choose(i): - k, raw, args, oid, slot, targets = rails[i] - try: - y, msgs = open_lane(cv, oid, slot, targets, [ln for ln in lanes if ln is not None and ln[1:3] != [oid, slot]]) - except Stop as e: - raise Stop(f"stopped at line {k} \"{raw.strip()}\" (nothing changed): {e}") - if lanes[i] is None: - lanes[i] = [y, oid, slot, targets] - else: - lanes[i][0] = y - notes.extend(f" line {k}: {m}" for m in msgs) for i in order: if i in fixed: continue - if PLAN_RAILS: - k, raw, args, oid, slot, targets = rails[i] - lanes[i] = [cv.out_xy(oid, slot)[1], oid, slot, targets] - notes.append(f" line {k}: rail height {round(lanes[i][0])}: the output height of its source") - else: - choose(i) - # a later move may have put a node on a height chosen earlier: choose that one again from where things are now. - # A rail chosen again twice means two rails keep pushing each other: stop and name them - again = {} - for _ in (range(0) if PLAN_RAILS else range(2 * len(rails) + 1)): - bad = None - for i in order: - if i in fixed: - continue # the plan wrote that height - y, oid, slot, targets = lanes[i] - x0, x1, last = rail_extent(cv, oid, targets) - near = [j for j in order if j != i and abs(lanes[j][0] - y) < P["RAIL_GAP"] - and min(rail_extent(cv, lanes[j][1], lanes[j][3])[1], x1) > max(rail_extent(cv, lanes[j][1], lanes[j][3])[0], x0)] - if lane_blockers(cv, y, x0, x1, {oid} | last, rail_clear_above(cv, targets)) or near: - bad = (i, near) - break - if bad is None: - break - i, near = bad - again[i] = again.get(i, 0) + 1 - if again[i] > 1: - others = " ".join(f"line {rails[j][0]}" for j in near) or "the nodes moved for another rail" - raise Stop(f"stopped at line {rails[i][0]} \"{rails[i][1].strip()}\" (nothing changed): its height keeps being " - f"blocked by {others}. Place the sources or targets of these rails apart, or give one of them above <unit> or below <unit>") - choose(i) - for i, j in ([] if PLAN_RAILS else swap_by_crossings(cv, lanes)): - notes.append(f" line {rails[i][0]}: rail height {round(lanes[i][0])}: swapped with the rail of line {rails[j][0]}, " - f"so fewer wires cross") + k, raw, args, oid, slot, targets = rails[i] + lanes[i] = [cv.out_xy(oid, slot)[1], oid, slot, targets] + notes.append(f" line {k}: rail height {round(lanes[i][0])}: the output height of its source") + # model, vae, clip and conditioning rails run in that order from the top wherever their runs overlap: a rail + # that would run below a rail of a later type is raised (its height only; no node moves) + for i, y0 in order_rails_by_type(cv, rails, lanes): + notes.append(f" line {rails[i][0]}: rail height {round(lanes[i][0])} instead of {round(y0)}: model, vae, clip " + f"and conditioning rails run in that order from the top") cv.fixed_lanes = {i for i in fixed} for m in (pull_rails(cv, lanes) if AUTO_FIX else []): notes.append(f" {m}") + settle_rail_moves(cv, rails, lanes, rail_move, notes) cv.layout_lanes = lanes for (k, raw, args, oid, slot, _), (y, *_rest) in zip(rails, lanes): mark = len(cv.out) try: - do_rail(cv, [args[0], "at", str(y), str(k)] + args[args.index("to"):]) + do_rail(cv, [args[0], "at", str(y), str(k)] + rail_move.get(k, []) + args[args.index("to"):]) except Stop as e: raise Stop(f"stopped at line {k} \"{raw.strip()}\" (nothing changed): {e}") except Exception as e: @@ -6013,13 +6519,13 @@ def choose(i): cv.out += violations(hard) if hard else ["no form the rules call Bad (all notices: check)"] soft = soft_problems(cv) if soft: - cv.out += violations(soft, "weigh less: fix them when it breaks nothing above") + cv.out += violations(soft) return cv.out # what the canvas did that the plan's lines did not say (reported back after a layout) BEYOND_THE_LINES = ("with its group", "lowering Reroute stands", "no fixed yellow", "not clear there", "was not clear", - "gap widened", "was not placed", "stepped down") + "gap widened", "was not placed", "stepped down", "in that order from the top") def violations(lines, how="fix them in the plan"): @@ -6034,7 +6540,7 @@ def violations(lines, how="fix them in the plan"): elif body.startswith("Note ") and ("explains" in body or "widens the frame" in body): ref, rule = "notes.md Where to place", "A Note on part of the processing stands next to the node it explains, placed last, in free space." elif "model Note top edge" in body: - ref, rule = "notes.md Where to place", "The overview and models Note stands at the upper left of the whole workflow, its top edge on the top edge of the whole workflow." + ref, rule = "notes.md Where to place", "The overview and models Note stands at the upper left of the whole workflow, its top edge on the top edge of the topmost node or group frame." else: for keys, start in CHECK_RULES: if any(k in body for k in keys): @@ -6055,11 +6561,12 @@ def violations(lines, how="fix them in the plan"): # the more particular first: a line takes the first rule whose words it contains (("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", "loader is above the vae loader", "clip loader"), "A loader stands in the column left"), + (("loader is above the model loader",), "A loader stands in the column left"), (("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"), - (("right edges of the sources", "model chain end"), "The sources wired straight into a sampler"), + (("model chain end",), "The model chain ends in the column"), + (("right edges of the sources",), "The sources wired straight into a sampler"), (("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"), @@ -6073,7 +6580,7 @@ def violations(lines, how="fix them in the plan"): (("crossing",), "Left to right in processing order"), (("samplers of stages in a row", "main flow wire"), "The main flow"), (("side-use image rail",), "A wire is drawn directly"), - (("is above its source",), "Build the core in the usual form"), + (("is above its source",), "The main flow (sampler"), (("wire over the title", "node over the title", "node overlapping group", "groups overlap"), "A group holds one large function"), (("value nodes side by side",), "A value is put in a value node"), @@ -6160,7 +6667,7 @@ def finish(cv): return cv.out or ["nothing changed"] -RAIL_USAGE = "rail <A>.<output> [above <unit>|below <unit>|level <X>.<output>] to <B>.<input> ..." +RAIL_USAGE = "rail <A>.<output> [above <unit>|below <unit>|level <X>.<output>] [move <unit>] to <B>.<input> ..." # rails of what the sampler uses run above the eye line (the top of the samplers along the rail); other rails run below it. # Measured on the skill author's hand-made layouts (35 workflows, every rail of these types on the measured side) TOOL_RAIL_TYPES = {"MODEL", "VAE", "NOISE", "CLIP", "CONDITIONING"} @@ -6206,40 +6713,39 @@ def rail_type(cv, oid, slot): return ((cv.node(oid).get("outputs") or [])[slot] or {}).get("type") -def type_bounds(cv, oid, slot, targets, lanes): - """Bounds (lo, hi) on a rail's height from the rails of MODEL, VAE and CLIP already given a height whose runs overlap - it and whose source is the same node or stands in the same stacked column: a rail of a type earlier in - RAIL_TYPE_ORDER stays above, a later one below, RAIL_GAP apart. (A Load VAE placed by its first user elsewhere, - not stacked with the other loaders, is not ordered with them.)""" - t = rail_type(cv, oid, slot) - if t == "CONDITIONING": - # a conditioning rail runs below the model and vae rails whose runs overlap it (the skill author: by default) - x0, x1, _ = rail_extent(cv, oid, targets) - lo = float("-inf") - for y, o, sl, tg in lanes: - if rail_type(cv, o, sl) in ("MODEL", "VAE"): - a0, a1, _ = rail_extent(cv, o, tg) - if min(a1, x1) > max(a0, x0): - lo = max(lo, y + P["RAIL_GAP"]) - return lo, float("inf") - if t not in RAIL_TYPE_ORDER: - return float("-inf"), float("inf") - r = RAIL_TYPE_ORDER.index(t) - x0, x1, _ = rail_extent(cv, oid, targets) - lo, hi = float("-inf"), float("inf") - col = stacks(cv) - for y, o, sl, tg in lanes: - u = rail_type(cv, o, sl) - if u not in RAIL_TYPE_ORDER or (o, sl) == (oid, slot) or not same_stack(cv, o, oid, col): - continue - a0, a1, _ = rail_extent(cv, o, tg) - if min(a1, x1) <= max(a0, x0): - continue - if RAIL_TYPE_ORDER.index(u) < r: - lo = max(lo, y + P["RAIL_GAP"]) - elif RAIL_TYPE_ORDER.index(u) > r: - hi = min(hi, y - P["RAIL_GAP"]) - return lo, hi +# rails of these types run top to bottom in this order wherever their runs overlap, whatever their sources are (one +# node's outputs, loaders in one column or apart, the model chain): the canvas sets their heights so +RAIL_STACK_ORDER = RAIL_TYPE_ORDER + ("CONDITIONING",) + + +def order_rails_by_type(cv, rails, lanes): + """Sets the heights of the model, vae, clip and conditioning rails so they run in RAIL_STACK_ORDER from the top + wherever their runs overlap, RAIL_GAP apart. Only rails are raised, never lowered: from the bottom of the order up, + a rail is raised above every overlapping rail of a later type (and, when that moved it, above a rail of its own type + it came too close to). Nodes do not move; a rail that leaves its source's output height gets a raising Reroute. + rails: [(line, raw, args, source, output, targets)]; lanes: [[height, source, output, targets]] (changed in place). + Returns [(rail index, height before)] for the rails raised.""" + gap = P["RAIL_GAP"] + idx = [i for i, ln in enumerate(lanes) if ln is not None and rail_type(cv, ln[1], ln[2]) in RAIL_STACK_ORDER] + rank = {i: RAIL_STACK_ORDER.index(rail_type(cv, lanes[i][1], lanes[i][2])) for i in idx} + ext = {i: rail_extent(cv, lanes[i][1], lanes[i][3])[:2] for i in idx} + before = {i: lanes[i][0] for i in idx} + seq = sorted(idx, key=lambda i: (rank[i], lanes[i][0], lanes[i][2], rails[i][0])) + + def overlap(i, j): + return min(ext[i][1], ext[j][1]) > max(ext[i][0], ext[j][0]) + for a in range(len(seq) - 2, -1, -1): + i = seq[a] + y = lanes[i][0] + for j in seq[a + 1:]: + if overlap(i, j) and rank[i] < rank[j]: + y = min(y, lanes[j][0] - gap) + moved = abs(y - before[i]) >= 1 + for j in seq[a + 1:]: + if overlap(i, j) and rank[i] == rank[j] and (moved or abs(lanes[j][0] - before[j]) >= 1) and y > lanes[j][0] - gap: + y = lanes[j][0] - gap + lanes[i][0] = y + return [(i, before[i]) for i in idx if abs(lanes[i][0] - before[i]) >= 1] def is_output_node(cv, n): @@ -6356,34 +6862,6 @@ def lands_on_reroute(cv, moving, dy): return False -def lane_moving(cv, solid, run, pairs, c, down, oid, out_y): - """The nodes that move down by `down` to open a lane at height c, or None if that cannot be done cleanly. - Starts from the nodes along the run whose centre is below c, and adds, until nothing changes, the nodes joined to a - moving node by a horizontal wire and the nodes a moving node would land on or come within V_GAP of. If that reaches a node along the run whose - centre is above c, or the source while the lane is not above its output, the lane is not opened there.""" - if not down: - return set() - by_id = {m["id"]: m for m in solid} - in_run = {m["id"] for m in run} - moving = {m["id"] for m in run if (G.rect(m)[1] + G.rect(m)[3]) / 2 > c} - while True: - # a node that only saves or shows steps down from the wire it is level with (a staircase): the wire through wins - add = ({q for p, q in pairs if p in moving} - | {p for p, q in pairs if q in moving and not (q in in_run and is_output_node(cv, by_id[q]))}) - for i in moving: - r = G.rect(by_id[i]) - # where it lands, and the V_GAP below it: a node it would come closer to than V_GAP moves too (the column keeps its gap) - moved = (r[0], r[1] + down, r[2], r[3] + down + V_GAP) - add |= {m["id"] for m in solid if m["id"] not in moving and rect_overlap(G.rect(m), moved)} - add -= moving - if not add: - return None if lands_on_reroute(cv, moving, down) else moving - if (oid in add and c >= out_y) or any((G.rect(by_id[i])[1] + G.rect(by_id[i])[3]) / 2 <= c - for i in add if i in in_run): - return None - moving |= {i for i in add if i in by_id} - - def move_closure(cv, solid, start, dy, forbid, pairs): """The nodes that move by dy (up or down) when the nodes in start move, or None if that reaches a node in forbid. Adds, until nothing changes: the nodes joined to a moving node by a horizontal wire (it stays horizontal), the nodes a @@ -6488,230 +6966,6 @@ def lane_nodes(lanes): return {i for ln in lanes for i in [ln[1]] + list(ln[3])} -def level_single(cv, oid, slot, tid, solid, pairs, lanes): - """A rail with one target whose direct wire passes behind a node: moves the target, or the source, so that the wire is - horizontal and passes behind nothing; the one moving fewer nodes. Returns (moved ids, dy, what moved) or None.""" - tin = next(l["target_input"] for l in cv.s["links"] if l["origin_id"] == oid and l["origin_slot"] == slot and l["target_id"] == tid) - fixed = lane_nodes(lanes) - best = None - for start, other in ((tid, oid), (oid, tid)): - if start in fixed: - continue - a, b = cv.out_xy(oid, slot), cv.in_xy(tid, tin) - dy = (a[1] - b[1]) if start == tid else (b[1] - a[1]) - if abs(dy) < 1: - continue - moving = move_closure(cv, solid, {start}, dy, {other} | fixed, pairs) - if moving is None: - continue - if _try_move(cv, moving, dy, lambda: wire_clear(cv, cv.out_xy(oid, slot), cv.in_xy(tid, tin), {oid, tid})): - if best is None or len(moving) < len(best[0]): - best = (moving, dy, start) - return best - - -def lane_at(cv, solid, run, pairs, c, oid, out_y, above, others): - """Opening a lane at height c along the run: (down, moving) or None (see lane_moving).""" - if any(abs(sy - c) < P["RAIL_GAP"] for sy in others): - return None - if any((G.rect(m)[1] + G.rect(m)[3]) / 2 <= c < G.rect(m)[3] + above for m in run): - return None # a node above the lane reaches too close to it - down = max([c + LANE_CLEAR_BELOW - G.rect(m)[1] for m in run if (G.rect(m)[1] + G.rect(m)[3]) / 2 > c] + [0]) - moving = lane_moving(cv, solid, run, pairs, c, down, oid, out_y) - return None if moving is None else (down, moving) - - -def source_move(cv, oid, slot, targets, solid, run, pairs, lanes, lo, hi, others, above): - """Moving the source (with what it drags along, move_closure) so that the rail runs clear at its output height: - (height, moving, dy) for the nearest such height, or None. Not farther than RAIL_SHIFT_MAX (as far as a rail leaves its - output height in hand-made layouts), and not if the move reaches a node along the run, a target, or - a node of a rail already given its height.""" - a = cv.out_xy(oid, slot) - x0, x1, last = rail_extent(cv, oid, targets) - forbid = {m["id"] for m in run} | set(targets) | lane_nodes(lanes) - cands = {lo, hi} | {sy + g for sy in others for g in (-P["RAIL_GAP"], P["RAIL_GAP"])} - for m in run: - r = G.rect(m) - cands |= {r[1] - LANE_CLEAR_BELOW, r[3] + above} - for c in sorted((c for c in cands if abs(c) != float("inf") and lo <= c <= hi and 1 <= abs(c - a[1]) <= RAIL_SHIFT_MAX), - key=lambda c: (abs(c - a[1]), c)): - if any(abs(sy - c) < P["RAIL_GAP"] for sy in others): - continue - dy = c - a[1] - moving = move_closure(cv, solid, {oid}, dy, forbid, pairs) - if moving is None: - continue - if _try_move(cv, moving, dy, lambda: not lane_blockers(cv, c, x0, x1, {oid} | last, above)): - return c, moving, dy - return None - - -def open_lane(cv, oid, slot, targets, lanes): - """Layout: the height of a rail without a written height, moving nodes rather than bending the wire. Returns (height, - report lines). lanes: the rails of this layout given a height so far, [[height, source, output, targets]]; opening a - lane moves them with the nodes. - 1. The output height, if the run there is clear (and on the rail's side of the eye line). - 2. A rail with one target: the target or the source moves so that a direct horizontal wire passes behind nothing. - 3. At the output height, by moving nodes: either a lane is opened (the nodes along the run whose centre is below it - move down, lane_moving) or the source moves to a clear height (source_move). The one moving fewer nodes. - 4. Not for a loader of a model, clip or vae (it heads its rail): a raising Reroute to the nearest clear height within - RAIL_SHIFT_MAX, then a lane opened near the output height. - Otherwise it stops and says what is in the way.""" - a = cv.out_xy(oid, slot) - extra = [(y, *rail_extent(cv, o, tg)[:2], (o, sl)) for y, o, sl, tg in lanes] - x0, x1, last = rail_extent(cv, oid, targets) - above = rail_clear_above(cv, targets) - lo, hi = rail_side(cv, oid, slot, x0, x1) - tlo, thi = type_bounds(cv, oid, slot, targets, lanes) - lo, hi = max(lo, tlo), min(hi, thi) - others = [sy for sy, sx0, sx1, root in rail_spans(cv) + extra if root != (oid, slot) and min(sx1, x1) > max(sx0, x0)] - if lo <= a[1] <= hi and not lane_blockers(cv, a[1], x0, x1, {oid} | last, above) and not any(abs(sy - a[1]) < P["RAIL_GAP"] for sy in others): - return a[1], [f"rail height {round(a[1])}: at the output height"] - solid = [m for m in cv.s["nodes"] if cv.placed(m) and m.get("type") != "Reroute"] - run = [m for m in solid if m["id"] not in {oid} | last and G.rect(m)[0] < x1 and G.rect(m)[2] > x0] - pairs = horizontal_pairs(cv) - - def apply(ids, dy): - cv.translate(sorted(ids), 0, dy) - for ln in lanes: - if ln[1] in ids and all(t in ids for t in ln[3]): - ln[0] += dy - if len(targets) == 1: - tid = targets[0] - tin = next((l["target_input"] for l in cv.s["links"] if l["origin_id"] == oid and l["origin_slot"] == slot - and l["target_id"] == tid), None) - if tin is not None and wire_clear(cv, a, cv.in_xy(tid, tin), {oid, tid}): - return a[1], [f"rail height {round(a[1])}: wired directly (the direct wire passes behind nothing)"] - lv = level_single(cv, oid, slot, tid, solid, pairs, lanes) - if lv: - moving, dy, start = lv - apply(moving, dy) - y = cv.out_xy(oid, slot)[1] - return y, [f"rail height {round(y)}: wired directly, made horizontal by moving the {'target' if start == tid else 'source'} " - f"{round(abs(dy))}px {'up' if dy < 0 else 'down'}: {' '.join(sorted(moving))}"] - opts = [] - if lo <= a[1] <= hi: - ln = lane_at(cv, solid, run, pairs, a[1], oid, a[1], above, others) - if ln: - opts.append((len(ln[1]), 0, "lane", ln)) - sm = source_move(cv, oid, slot, targets, solid, run, pairs, lanes, lo, hi, others, above) - if sm: - opts.append((len(sm[1]), 1, "source", sm)) - if opts: - # fewer nodes moved first, then the shorter move (a lane opened far below moves the band away) - dist = lambda o: o[3][0] if o[2] == "lane" else abs(o[3][2]) - _, _, kind, v = min(opts, key=lambda o: (o[0], dist(o), o[1])) - if kind == "lane": - down, moving = v - out = [f"rail height {round(a[1])}: at the output height, opening a lane there"] - if down: - apply(moving, down) - out.append(f"moved {round(down)}px down to open the lane: {' '.join(sorted(moving))}") - return a[1], out - c, moving, dy = v - apply(moving, dy) - return c, [f"rail height {round(c)}: at the output height, moving the source {round(abs(dy))}px " - f"{'up' if dy < 0 else 'down'}: {' '.join(sorted(moving))}"] - in_way = " ".join(m["id"] for m in lane_blockers(cv, a[1], x0, x1, {oid} | last, above)) - if cv.is_model_loader(cv.node(oid)) and not any(ln[1] == oid for ln in lanes) and not tlo <= a[1] <= thi: - t = rail_type(cv, oid, slot) - rk = RAIL_TYPE_ORDER.index(t) if t in RAIL_TYPE_ORDER else len(RAIL_TYPE_ORDER) - down = a[1] < tlo - other = next((ln[1] for ln in lanes if cv.is_model_loader(cv.node(ln[1])) and rail_type(cv, ln[1], ln[2]) in RAIL_TYPE_ORDER - and (RAIL_TYPE_ORDER.index(rail_type(cv, ln[1], ln[2])) < rk) == down), None) - hint = (f": e.g. put {oid} {'below' if down else 'above'} {other}" + (f", or stack {other} {oid}" if down else f", or stack {oid} {other}")) if other else "" - raise Stop(f"the {t} rail of {oid} must run {'below' if down else 'above'} the other loaders' rails " - f"(rails go model, vae, clip from the top), but its output is on the other side: stack the loaders " - f"model, vae, clip from the top{hint}") - if cv.is_model_loader(cv.node(oid)) and not any(ln[1] == oid for ln in lanes): - raise Stop(f"no room for the rail of {oid} at its output height: in the way {in_way or '(other rails)'}; no lane " - f"opens there without cutting a horizontal wire, and {oid} cannot move without reaching the run or " - f"a target. A loader heads its rail: place it where its output height is clear along the run " - f"(a rail of model, clip or vae runs above the samplers' top)" - + (f", e.g. put {oid} above {in_way.split()[0]}" if in_way else "")) - try: - y, how = rail_height(cv, oid, slot, targets, extra, (tlo, thi)) - except Stop: - y, how = None, "" - # a conditioning rail lifted from below the samplers to above them may go farther than RAIL_SHIFT_MAX - # (620px in a layout of a Z-Image Turbo workflow the skill author arranged) - cap = float("inf") if rail_type(cv, oid, slot) == "CONDITIONING" and a[1] > hi else RAIL_SHIFT_MAX - if y is not None and abs(y - a[1]) <= cap: - return y, [f"rail height {round(y)}: {how}"] - best = None - cands = {G.rect(m)[3] + above for m in run} | {sy + g for sy in others for g in (-P["RAIL_GAP"], P["RAIL_GAP"])} - for c in sorted(cands, key=lambda c: (abs(c - a[1]), c)): - if abs(c - a[1]) > RAIL_SHIFT_MAX or not lo <= c <= hi: - continue - ln = lane_at(cv, solid, run, pairs, c, oid, a[1], above, others) - if ln and (best is None or (ln[0], len(ln[1])) < (best[0], len(best[2]))): - best = (ln[0], c, ln[1]) - if best is None: - raise Stop(f"no room for the rail of {oid} near its output height: in the way {in_way or '(other rails)'}; " - f"the nearest clear height is {'none' if y is None else str(round(abs(y - a[1]))) + 'px away'}, and no lane " - f"can be opened within {RAIL_SHIFT_MAX}px without cutting a horizontal wire or moving a node above the rail. " - f"Place the source or the targets so the run is shorter") - down, c, moving = best - out = [f"rail height {round(c)}: opened a lane {round(abs(c - a[1]))}px {'above' if c < a[1] else 'below'} the output height, " - f"since the nearest clear height is {'none' if y is None else str(round(abs(y - a[1]))) + 'px away'}"] - if down: - apply(moving, down) - out.append(f"moved {round(down)}px down to open the lane: {' '.join(sorted(moving))}") - return c, out - - -def lane_crossings(cv, upper, lower): - """How many wires of two rails cross when `upper` runs above `lower` ([height, source, output, targets] each): - the rise from each source and the drop to each target, crossing the other rail's run.""" - n = 0 - for a, b in ((upper, lower), (lower, upper)): - bx0, bx1, _ = rail_extent(cv, b[1], b[3]) - legs = [(G.rect(cv.node(a[1]))[2], cv.out_xy(a[1], a[2])[1])] - for t in a[3]: - tin = next((l["target_input"] for l in cv.s["links"] if l["target_id"] == t and l["origin_id"] == a[1] - and l["origin_slot"] == a[2]), None) - legs.append((G.rect(cv.node(t))[0], cv.in_xy(t, tin)[1] if tin is not None else G.rect(cv.node(t))[1])) - for x, y in legs: - if bx0 < x < bx1 and min(a[0], y) < b[0] < max(a[0], y): - n += 1 - return n - - -def swap_by_crossings(cv, lanes): - """Rails other than MODEL, VAE and CLIP: two rails whose runs overlap swap heights when fewer wires cross that way - and both heights stay clear for the rail that takes them. Returns the pairs swapped.""" - done = [] - free = [i for i, ln in enumerate(lanes) if rail_type(cv, ln[1], ln[2]) not in RAIL_TYPE_ORDER] - for _ in range(len(free)): - changed = False - for i in free: - for j in free: - a, b = lanes[i], lanes[j] - if i == j or a[0] >= b[0]: - continue - ax0, ax1, alast = rail_extent(cv, a[1], a[3]) - bx0, bx1, blast = rail_extent(cv, b[1], b[3]) - if min(ax1, bx1) <= max(ax0, bx0): - continue - now = lane_crossings(cv, a, b) - if not now or lane_crossings(cv, [a[0]] + b[1:], [b[0]] + a[1:]) >= now: - continue - ya, yb = a[0], b[0] - lo_a, hi_a = rail_side(cv, a[1], a[2], ax0, ax1) - lo_b, hi_b = rail_side(cv, b[1], b[2], bx0, bx1) - if not (lo_a <= yb <= hi_a and lo_b <= ya <= hi_b): - continue - if lane_blockers(cv, yb, ax0, ax1, {a[1]} | alast, rail_clear_above(cv, a[3])) or \ - lane_blockers(cv, ya, bx0, bx1, {b[1]} | blast, rail_clear_above(cv, b[3])): - continue - a[0], b[0] = yb, ya - done.append((i, j)) - changed = True - if not changed: - break - return done - - 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.""" @@ -6729,19 +6983,6 @@ def rail_lower_x(cv, x0, tid): return (max(rights) if rights else x0 - H_GAP) - REROUTE_W -def rail_free_x(cv, x, y, step): - """x for a Reroute at height y, moved (right for step 1, left for -1) out from below a node that grows in ComfyUI - (a sampler, a video): a Reroute there would be hidden when it grows.""" - for _ in range(20): - box = (x, y - REROUTE_H / 2, x + REROUTE_W, y + REROUTE_H / 2) - over = [G.rect(m) for m in cv.s["nodes"] if cv.placed(m) and m.get("type") != "Reroute" and grows(cv, m) - and in_grow_room(cv, m, box)] - if not over: - return x - x = (max(r[2] for r in over) + 1) if step > 0 else (min(r[0] for r in over) - REROUTE_W - 1) - return x - - def _frame_would_hit_another(cv, g, rect): """Whether widening group g's frame to take in rect would make it overlap another group's frame.""" b = g.get("bounding") @@ -6779,9 +7020,162 @@ def one_target_height(cv, oid, slot, tins, spec, y, notes, k): return ty +def settle_rail_moves(cv, rails, lanes, rail_move, notes): + """Rails written with `move <unit>`: the unit goes up or down with its rail, so it must not stand on a rail below it. + Such a rail goes up until the unit clears the rail below by the rail gap; a rail above it that it then comes too + close to (or passes) goes up too, and so on upwards, so the rails keep their order from the top. A rail pushed up + that ran at its source's output height, or that a loader heads, takes its source (with its block) along, so no + Reroute lifts it. Then the units move, once each, and a rail of a moved source that ran at its output height moves + with it. Changes lanes and rail_move; moves nodes.""" + gap = P["RAIL_GAP"] + idx = {rails[i][0]: i for i in range(len(rails))} + + def block_of(oid): + for name, ids in (cv.s.get("blocks") or {}).items(): + if oid in ids: + return cv.unit(name) + return [oid] + + movers = {} + for k, mv in rail_move.items(): + i = idx.get(k) + if i is None: + continue + unit = cv.unit(mv[1]) + if rails[i][3] not in unit: + raise Stop(f"stopped at line {k} \"{rails[i][1].strip()}\" (nothing changed): move {mv[1]} does not hold the rail source {rails[i][3]}") + movers[i] = unit + for a in movers: + for b in movers: + if a < b and set(movers[a]) & set(movers[b]): + raise Stop(f"stopped at line {rails[b][0]} \"{rails[b][1].strip()}\" (nothing changed): a unit moves with one " + f"rail only (line {rails[a][0]} already moves it): write move on one of its rails") + out_y0 = {i: cv.out_xy(lanes[i][1], lanes[i][2])[1] for i in range(len(lanes)) if lanes[i] is not None} + # the order from the top the rails had before anything moved: it stays + order0 = {i: (lanes[i][0], i) for i in out_y0} + # a unit moves with all the rails of the nodes in it (a checkpoint's model, clip and vae keep their places to it) + units = [] # [lead rail, node ids, rails of those nodes, bbox before moving] + unit_of = {} + + def add_unit(lead, ids): + members = [m for m in out_y0 if lanes[m][1] in ids] + u = [lead, list(ids), members, cv.bbox(list(ids))] + units.append(u) + for m in members: + unit_of[m] = u + return u + + for i, ids in movers.items(): + add_unit(i, ids) + + def shift(u): # how far unit u has moved so far + return lanes[u[0]][0] - out_y0[u[0]] + + def span(i): + _, oid, slot, targets = lanes[i] + x0, x1 = rail_extent(cv, oid, targets)[:2] + u = unit_of.get(i) + if u: + x0 = min(x0, u[3][0]) + return x0, x1 + + def raise_by(i, d): + u = unit_of.get(i) + for m in (u[2] if u else [i]): + lanes[m][0] += d + + active = set(unit_of) + for _ in range(200): + changed = False + for lo in out_y0: + for up in out_y0: + if up == lo or order0[up] > order0[lo]: + continue + u = unit_of.get(up) + if u is not None and unit_of.get(lo) is u: + continue + if lo not in active and u is None: + continue + (a0, a1), (b0, b1) = span(up), span(lo) + if min(a1, b1) <= max(a0, b0): + continue + if u is not None: + if any(order0[m] > order0[lo] for m in u[2]): + continue # a rail running between the unit's own rails: nothing to do here + # the unit's body clears the rail below by the rail gap + d = lanes[lo][0] - P["RAIL_GAP"] - (u[3][3] + shift(u)) + else: + d = lanes[lo][0] - gap - lanes[up][0] + if d >= -0.5: + continue + _, oid, slot, _t = lanes[up] + ids = block_of(oid) if u is None else None + # a block holding a sampler or a node a rail goes into stays: moving it would move the main flow + # (the rail is lifted by a Reroute instead, and the check names it) + if ids and any(is_sampler(cv.node(x)) or any(x in lanes[m][3] for m in out_y0) for x in ids): + ids = None + if ids and (abs(lanes[up][0] - out_y0[up]) < 1 or cv.is_model_loader(cv.node(oid))): + joined = next((v for v in units if set(v[1]) & set(ids)), None) + if joined is not None: + # its block already moves with another rail: it goes with that unit, its rail where the unit puts it + joined[1] = list(dict.fromkeys(joined[1] + ids)) + joined[3] = cv.bbox(joined[1]) + for m in out_y0: + if lanes[m][1] in ids and unit_of.get(m) is not joined: + lanes[m][0] = out_y0[m] + shift(joined) + joined[2].append(m) + unit_of[m] = joined + active |= set(joined[2]) + notes.append(f" line {rails[up][0]}: {oid} goes with line {rails[joined[0]][0]}'s move (same block)") + changed = True + continue + u = add_unit(up, ids) + rail_move[rails[up][0]] = ["move", oid] + notes.append(f" line {rails[up][0]}: {oid} goes up with its rail: the rail below it went up") + active |= set(u[2]) + d = min(d, lanes[lo][0] - gap - (u[3][3] + shift(u))) + raise_by(up, d) + notes.append(f" line {rails[up][0]}: rail height {round(lanes[up][0])}: clear of the rail below it by the rail gap") + active.add(up) + changed = True + if not changed: + break + for u in units: + dy = round(shift(u)) + if not dy: + continue + cv.translate(u[1], 0, dy) + notes.append(f" line {rails[u[0]][0]}: moved {len(u[1])} node(s) {abs(dy)}px {'down' if dy > 0 else 'up'}: " + f"{lanes[u[0]][1]}'s output at the rail's height") + for k in list(rail_move): + rail_move.pop(k) + + +def rail_below_y(cv, unit): + """Height of a rail written `below <unit>`: the gap below the unit, or below the room a node of the unit grows into + in ComfyUI (a sampler's preview) when that is lower: a rail there would be hidden when the node grows.""" + y = cv.bbox(unit)[3] + V_GAP + for i in unit: + n = cv.node(i) + if cv.placed(n) and grow_room(cv, n): + y = max(y, math.ceil(G.rect(n)[3] + grow_room(cv, n) + REROUTE_H / 2) + 1) + return y + + +def split_rail_move(args): + """A rail line's `move <unit>` (before `to`) taken out: (the other words, ["move", unit] or []).""" + if "move" in args and "to" in args and args.index("move") < args.index("to"): + i = args.index("move") + if i + 1 >= args.index("to"): + raise Stop(f"write rail ... move <unit> to ...: {RAIL_USAGE}") + return args[:i] + args[i + 2:], args[i:i + 2] + return args, [] + + def do_rail(cv, args): if "to" not in args: raise Stop(RAIL_USAGE) + args, mv = split_rail_move(args) k = args.index("to") head, targets = args[:k], args[k + 1:] if not head or not targets: @@ -6802,28 +7196,53 @@ def do_rail(cv, args): tid, tin = cv.port_in(t) tg.append((cv.bbox([tid])[0], tid, tin)) tg.sort() - if spec in ("above", "below", "level") and not PLAN_RAILS and all(wire_clear(cv, a, cv.in_xy(tid, tin), {oid, tid}) for _, tid, tin in tg): - # a written height where every target is reached directly, behind nothing: the rail is drawn as one without a - # height (it wires them directly), not down and back up to that height - cv.out.append(f"rail {head[0]}: every target is reached directly; the written height ({spec} {head[2]}) is not used") - spec = "auto" if spec == "auto": y, how = rail_height(cv, oid, slot, [t for _, t, _ in tg]) cv.out.append(f"rail height {round(y)}: {how}") elif spec == "at": - # layout: the height open_lane chose (the layout checked it is still clear after every rail was given its height) + # layout: the height the layout gave the rail (written, the source's output height, or raised by the rail order) if not getattr(cv, "in_layout", False): raise Stop(f"unknown rail height at (above below level)") y = float(head[2]) elif spec == "above": y = cv.bbox(cv.unit(head[2]))[1] - V_GAP elif spec == "below": - y = cv.bbox(cv.unit(head[2]))[3] + V_GAP + y = rail_below_y(cv, cv.unit(head[2])) elif spec == "level": x_id, x_slot = cv.port_out(head[2]) y = cv.out_xy(x_id, x_slot)[1] else: raise Stop(f"unknown rail height {spec} (above below level; or leave it out)") + if mv: + # move <unit>: the unit holding the source moves up or down so the source's output stands at the rail's height + # (the rail's height set from what comes after it; no Reroute lifts or lowers the source's output) + unit = cv.unit(mv[1]) + if oid not in unit: + raise Stop(f"rail ... move {mv[1]}: the unit does not hold the rail source {oid}") + drawn = [l for l in cv.s["links"] if l["origin_id"] in unit and (l["origin_id"], l["origin_slot"]) != (oid, slot)] + if any(cv.node(l["target_id"]).get("type") == "Reroute" for l in drawn): + raise Stop(f"rail ... move {mv[1]}: a rail from {mv[1]} is already drawn and would be left behind: " + f"write move on the first rail drawn from it") + # the unit stands above the rails below this one, clear of them by the rail gap (a rail behind the loader that + # heads the rail above it: both go up until it clears) + bb0 = cv.bbox(unit) + below_out = bb0[3] - a[1] + if getattr(cv, "in_layout", False) and getattr(cv, "layout_lanes", None): + others = [(ly, *rail_extent(cv, lo, lt)[:2]) for ly, lo, ls, lt in cv.layout_lanes if (lo, ls) != (oid, slot)] + else: + others = [(sy, sx0, sx1) for sy, sx0, sx1, root in rail_spans(cv) if root != (oid, slot)] + for _ in range(20): + hit = [ly for ly, lx0, lx1 in others if y < ly < y + below_out + P["RAIL_GAP"] + and min(lx1, bb0[2]) > max(lx0, bb0[0])] + if not hit: + break + y = min(hit) - below_out - P["RAIL_GAP"] + cv.out.append(f"rail of {oid} raised to {round(y)}: {mv[1]} would stand on the rail at {round(min(hit))} below it") + dy = round(y - a[1]) + if dy: + cv.translate(unit, 0, dy) + cv.out.append(f"moved {mv[1]} {abs(dy)}px {'down' if dy > 0 else 'up'}: {oid}'s output at the rail's height") + a = cv.out_xy(oid, slot) o = cv.node(oid) ox1 = G.rect(o)[2] made = [] @@ -6839,21 +7258,6 @@ def do_rail(cv, args): y = (min(near) - P["RAIL_GAP"]) if step < 0 else (max(near) + P["RAIL_GAP"]) cv.out.append(f"too close to another rail; height shifted to {round(y)}") - if spec in ("above", "below") and abs(y - a[1]) >= 1 and not PLAN_RAILS: - # if a horizontal line at the output height up to just before the rightmost target hits nothing and is not close - # to another rail, no raising or lowering Reroute is needed, so the rail is drawn at the output height - x1 = max(x for x, _, _ in tg) - band = (ox1 + 1, a[1] - REROUTE_H / 2, x1 - H_GAP / 2, a[1] + REROUTE_H / 2) - # a target standing between the source and a later target is in the way too (the rail would run on behind it); - # only the rightmost targets, which the band stops short of, are left out - last = {t for x, t, _ in tg if x == x1} - blocked = any(rect_overlap(G.rect(m), band) for m in cv.s["nodes"] - if cv.placed(m) and m["id"] != oid and m["id"] not in last and m.get("type") != "Reroute") - near = [sy for sy, sx0, sx1, root in rail_spans(cv) if root != (oid, slot) - and min(sx1, x1) > max(sx0, ox1) and abs(sy - a[1]) < P["RAIL_GAP"]] - if not blocked and not near: - cv.out.append(f"drawn at the output height {round(a[1])} instead of {spec}, since nothing is in the way") - y = a[1] if spec in ("above", "below"): y = one_target_height(cv, oid, slot, [(t, i) for _, t, i in tg], spec, y, cv.out, None) @@ -6875,9 +7279,6 @@ def reroute(x): last_x = ox1 if abs(y - a[1]) >= 1: x_r0 = rail_raise_x(cv, ox1) - fx = rail_free_x(cv, x_r0, y, 1) - if fx + REROUTE_W <= min(x for x, _, _ in tg) - H_GAP / 3: - x_r0 = fx r0 = reroute(x_r0) cv.add_link(oid, slot, r0, "") prev = (r0, 0) @@ -6903,9 +7304,6 @@ def direct_ok(tid, tin, src=None): f"place {tid} right of {oid}, or wire it directly") # a target the source reaches directly is wired directly only when the canvas chooses the rails; a rail the plan # writes is drawn as written (wiring it directly drew one wire across the whole workflow) - if not lowered and not getattr(cv, "rail_no_direct", False) and not PLAN_RAILS and direct_ok(tid, tin): - cv.add_link(oid, slot, tid, tin) - continue if prev[0] != oid and abs(cv.in_xy(tid, tin)[1] - y) < 1 and direct_ok(tid, tin, prev[0]): cv.add_link(prev[0], prev[1], tid, tin) continue @@ -6915,18 +7313,9 @@ def direct_ok(tid, tin, src=None): and not any(t2 == tid for _, t2, _ in tg[:-1])): cv.add_link(prev[0], prev[1], tid, tin) continue + # the lowering Reroute stays in the column left of the target (same column), also below a node that grows: it is + # not moved sideways; the check says so, and the plan gives the rail the room the node grows rx = rail_lower_x(cv, x0, tid) - rx0 = rx - # not below a node that grows: to its left if that stays right of the rail's last Reroute, else to its right if - # that stays left of the target, else where it is - for step in (-1, 1): - fx = rail_free_x(cv, rx, y, step) - if fx == rx or (last_x < fx and fx + REROUTE_W <= x0 - H_GAP / 3): - rx = fx - break - if rx != rx0: - cv.out.append(f"rail into {tid}: its lowering Reroute stands {abs(round(rx - rx0))}px {'left' if rx < rx0 else 'right'} " - f"of where it would, out from below a node that grows; the wire from it to {tid} slants") # rails from one node's outputs run 20px apart: their lowering Reroutes into one target would overlap, so a later # one steps left of the Reroute already there (a staircase), as long as it stays right of the rail's last Reroute def hits_reroute(x): @@ -7340,6 +7729,12 @@ def problem_refs(cv, lines): prev_sig, before_cv = sig, cv if pending: _flush(steps, pending, problem_refs) + # the page starts at the first drawing with nodes on it: the steps before it (building the graph, nothing placed) + # become one line of that step's details + while len(steps) > 1 and not nodes_t.items[steps[0]["v"][0]]: + first = steps.pop(0) + steps[0]["pre"] = first.get("pre", ([], [])) + steps[0]["pre"] = (steps[0]["pre"][0] + first["c"], steps[0]["pre"][1] + first["x"]) canvases.append({"name": name, "tab": (work.cfg.get("tab_group") or {}).get(name), "defs": defs.items, "nodes": nodes_t.items, "wires": wires_t.items, "groups": groups_t.items, "problems": probs.items, "steps": steps, "walk": walk_view(final), "review": _review_names(final, final.s.get("review")), "hand": final.s.get("hand_placed") or []}) diff --git a/skills/comfyui-readable-node/scripts/comfy_schema.py b/skills/comfyui-readable-node/scripts/comfy_schema.py index c541901..66f4dd5 100644 --- a/skills/comfyui-readable-node/scripts/comfy_schema.py +++ b/skills/comfyui-readable-node/scripts/comfy_schema.py @@ -23,6 +23,8 @@ WIDGET_TYPES = { "INT", "FLOAT", "BOOLEAN", "STRING", "COMBO", "MARKDOWN", "COLOR", "COMFY_DYNAMICCOMBO_V3", "IMAGEUPLOAD", "CURVE", + # Branch: the combo choosing an input by name, and the hidden list of the connected inputs' names + "COMFY_BRANCH_SELECTOR", "COMFY_BRANCH_INPUT_NAMES", } UPLOAD_FLAGS = ("image_upload", "video_upload", "audio_upload", "animated_image_upload", "file_upload") SEED_NAMES = ("seed", "noise_seed") @@ -156,6 +158,8 @@ def add(name, spec, j): if raw_t == "COMFY_AUTOGROW_V3": sockets.extend(_autogrow(name, opts, saved_names)) return 0 + if t == "COMFY_BRANCH_INPUT_NAMES": + return 1 # Branch's list of names: a hidden widget with no input slot (other socketless widgets keep one) if t in WIDGET_TYPES and not opts.get("forceInput"): used = 1 children = [] @@ -215,7 +219,8 @@ def default_value(spec): if t == "COMFY_DYNAMICCOMBO_V3": o = opts.get("options") or [] return o[0].get("key") if o else None - return {"INT": 0, "FLOAT": 0.0, "BOOLEAN": False, "STRING": ""}.get(t) + return {"INT": 0, "FLOAT": 0.0, "BOOLEAN": False, "STRING": "", "COMFY_BRANCH_SELECTOR": "", + "COMFY_BRANCH_INPUT_NAMES": []}.get(t) def map_widget_values(node_type, widgets_values, object_info, named=None): diff --git a/skills/comfyui-readable-node/scripts/compare.py b/skills/comfyui-readable-node/scripts/compare.py index 0573e95..5415dfd 100644 --- a/skills/comfyui-readable-node/scripts/compare.py +++ b/skills/comfyui-readable-node/scripts/compare.py @@ -8,6 +8,9 @@ output appears somewhere in the rebuilt workflows (all versions are passed). A string that survives as part of another string is reported as "partly". Setting names from turning a custom node into core nodes, and things removed on purpose (saving metadata, etc.), show up too. + A widget driven by a wire keeps a stored value that is not used: it is left out on both sides. A PrimitiveNode (the + frontend's value node) is compared: its value is the one the widgets it drives use. +- Seed controls: a version with fewer seeds kept fixed than the source, and some left to change (randomize, ...). - User inputs: the number of nodes where the user supplies a file, like Load Image / Load Video / Load Audio (inputs with *_upload in object_info, or types whose name starts with Load(Image|Video|Audio), VHS_LoadVideo, etc.). The same file in separate source nodes counts as separate inputs. Counts are compared per version. @@ -129,27 +132,59 @@ def model_note(flat): return None +def linked_widgets(flat): + """{node id: names of its widgets a wire drives}: their stored values are not used (the wire's value is).""" + out = {} + for l in flat["links"]: + out.setdefault(l["target_id"], set()).add(l["target_input"]) + return out + + +CONTROLS = ("fixed", "increment", "decrement", "randomize") + + +def controls(flat, live=None): + """{control value: how many} over the active nodes (those reaching an output, if live): fixed, randomize, ... of + seeds, read by name where the node is known and from the value list where it is not (a custom node not installed).""" + out = {} + for n in flat["nodes"]: + if n["type"] in SKIP_TYPES or n.get("mode", 0) != 0 or (live is not None and n["id"] not in live): + continue + w = n.get("widgets") + vals = ([v for k, v in w.items() if k == "control_after_generate" or k.endswith(".control_after_generate")] + if isinstance(w, dict) else n.get("widgets_values") if isinstance(n.get("widgets_values"), list) else []) + for v in vals: + if isinstance(v, str) and v in CONTROLS: + out[v] = out.get(v, 0) + 1 + return out + + def compare(src, outs, oi): """src: the source flat graph. outs: [(name, flat graph)]. Returns a list of fact lines.""" lines = [] live = reaching(src, oi) - # values + # values (a widget a wire drives keeps a value that is not used: it is left out on both sides) have, texts = set(), [] for _, f in outs: + driven = linked_widgets(f) for n in f["nodes"]: - if n["type"] in SKIP_TYPES: + if n["type"] in SKIP_TYPES and n["type"] != "PrimitiveNode": continue - for _, v in values_of(n): + for k, v in values_of(n): + if k in driven.get(n["id"], ()): + continue if keep(v): have.add(norm(v)) if isinstance(v, str): texts.append(v) + src_driven = linked_widgets(src) for n in src["nodes"]: - if n["type"] in SKIP_TYPES or n.get("mode", 0) != 0 or n["id"] not in live: + # a PrimitiveNode (the frontend's value node) holds the value the widgets it drives use: it is compared + if (n["type"] in SKIP_TYPES and n["type"] != "PrimitiveNode") or n.get("mode", 0) != 0 or n["id"] not in live: continue for k, v in values_of(n): - if not keep(v) or norm(v) in have: + if k in src_driven.get(n["id"], ()) or not keep(v) or norm(v) in have: continue s = json.dumps(v, ensure_ascii=False) if isinstance(v, str) and any(v.strip() in t for t in texts): @@ -157,6 +192,14 @@ def compare(src, outs, oi): else: lines.append(f"value not found: source {n['id']} {n['type']}.{k} = {s[:120]}") + # seed controls: a seed the source kept fixed that a version lets change (fewer fixed, more of the others) + c0 = controls(src, live) + for name, f in outs: + c1 = controls(f) + if c1.get("fixed", 0) < c0.get("fixed", 0) and sum(c1.values()) > c1.get("fixed", 0): + fmt = lambda c: ", ".join(f"{k} ×{c[k]}" for k in CONTROLS if c.get(k)) or "none" + lines.append(f"seed control changed: {name} has {fmt(c1)} (source: {fmt(c0)})") + # user inputs before = user_inputs(src, oi, only=live) after = {name: user_inputs(f, oi) for name, f in outs} diff --git a/skills/comfyui-readable-node/scripts/flatten.py b/skills/comfyui-readable-node/scripts/flatten.py index 380392e..82ed776 100644 --- a/skills/comfyui-readable-node/scripts/flatten.py +++ b/skills/comfyui-readable-node/scripts/flatten.py @@ -63,6 +63,28 @@ UE_TYPES = {"Prompts Everywhere", "Seed Everywhere"} +CONTROL_VALUES = {"fixed", "increment", "decrement", "randomize"} + + +def widget_names_from_inputs(node): + """Names for the positions of a node's widgets_values, from the widget inputs the workflow lists (in order), a + control_after_generate value counted after the widget it follows. None when that does not account for every value.""" + wv = node.get("widgets_values") + order = [i["name"] for i in node.get("inputs") or [] if isinstance(i.get("widget"), dict)] + if not isinstance(wv, list) or not order: + return None + names, k = [], 0 + for nm in order: + if k >= len(wv): + return None + names.append(nm) + k += 1 + if k < len(wv) and isinstance(wv[k], str) and wv[k] in CONTROL_VALUES and not isinstance(wv[k - 1], str): + names.append("control_after_generate") + k += 1 + return names if k == len(wv) else None + + class Flattener: def __init__(self, wf, object_info): self.wf = wf @@ -251,8 +273,18 @@ def set_widget(self, nid, name, value): wv[name] = value return True info = self.oi.get(node.get("type")) + if info is None and isinstance(wv, list): + # a custom node that is not installed: the order of its widgets is read from the inputs the workflow lists + # for them (each widget is an input with "widget"), a control_after_generate value standing after the widget + # it controls. Used only when that accounts for every value + names = widget_names_from_inputs(node) + if names and name in names: + wv[names.index(name)] = value + return True if info is None or not isinstance(wv, list): - self.warn(f"{nid} {node.get('type')}: cannot write a value to widget {name} (type unknown)") + self.warn(f"{nid} {node.get('type')}: the value {json.dumps(value, ensure_ascii=False)[:60]} given from outside the " + f"subgraph could not be written to widget {name} (type unknown): the node keeps an old value. Set it " + f"by hand on the canvas (set {nid} <index>=<value>) and say so in the report") return False names = comfy_schema.widget_names(info, wv) if name not in names or names.index(name) >= len(wv): @@ -601,6 +633,9 @@ def run(self): n.pop(key, None) for slot in (n.get("inputs") or []) + (n.get("outputs") or []): for key in SLOT_LAYOUT_KEYS: + # a Branch chooses by its inputs' labels: there a label is meaning, not layout + if key == "label" and n.get("type") == "BranchNode" and str(slot.get("name", "")).startswith("autogrow."): + continue slot.pop(key, None) return { "nodes": [self.nodes[n] for n in self.order], diff --git a/skills/comfyui-readable-node/scripts/logo.svg b/skills/comfyui-readable-node/scripts/logo.svg new file mode 100644 index 0000000..574e83f --- /dev/null +++ b/skills/comfyui-readable-node/scripts/logo.svg @@ -0,0 +1 @@ +<svg class="logo" viewBox="0 0 1032 173" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="ComfyUI Readable Node" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5"><g transform="matrix(1,0,0,1,-2298.08885,-226.017229)"><g transform="matrix(0.536983,0,0,0.159583,2298.08885,226.017229)"><g transform="matrix(2.152071,0,0,5.686505,-899.636939,-10786.262187)"><path d="M791.653,2071.988L791.653,2045.504C791.653,2033.545 799.277,2023.836 808.668,2023.836C818.059,2023.836 825.683,2033.545 825.683,2045.504L825.683,2071.988" style="fill:none;stroke:currentColor;stroke-width:11.12px;"/></g><g transform="matrix(1.76253,0,0,6.013963,-1118.346099,-12005.944433)"><path d="M791.653,2074.254L791.653,2045.504C791.653,2036.243 799.277,2028.724 808.668,2028.724C818.059,2028.724 825.683,2036.243 825.683,2045.504L825.683,2074.254" style="fill:none;stroke:currentColor;stroke-width:12.12px;"/></g><g transform="matrix(1.76253,0,0,6.013963,-1058.367894,-12005.944433)"><path d="M791.653,2045.504C791.653,2036.243 799.277,2028.724 808.668,2028.724C818.059,2028.724 825.683,2036.243 825.683,2045.504L825.683,2074.254" style="fill:none;stroke:currentColor;stroke-width:12.12px;"/></g><g transform="matrix(1.76253,0,0,5.573782,-1271.618364,-10565.359148)"><path d="M825.683,2045.504L825.683,2074.254" style="fill:none;stroke:currentColor;stroke-width:12.58px;"/></g><g transform="matrix(2.822273,0,0,9.496698,-1819.64861,-18641.490677)"><circle cx="709.825" cy="2039.01" r="3.813" style="fill:currentColor;"/></g><g transform="matrix(2.152071,0,-0,-5.686505,-1674.162473,12504.635064)"><path d="M791.653,2071.988L791.653,2045.504C791.653,2033.545 799.277,2023.836 808.668,2023.836C818.059,2023.836 825.683,2033.545 825.683,2045.504L825.683,2071.988" style="fill:none;stroke:currentColor;stroke-width:11.12px;"/></g><g transform="matrix(0.993203,0,0,1,0,0)"><g transform="matrix(2.1668,0,0,5.686505,-502.695902,-11313.765122)"><path d="M825.683,2047.904L825.683,2071.988" style="fill:none;stroke:currentColor;stroke-width:11.12px;"/></g><g transform="matrix(3.782835,0,0,12.642381,-1837.028658,-25498.455192)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g></g><g transform="matrix(0.993203,0,0,1,-8.499724,0)"><g transform="matrix(2.1668,0,0,5.686505,-221.421409,-11313.765122)"><path d="M825.683,2047.904L825.683,2071.988" style="fill:none;stroke:currentColor;stroke-width:11.12px;"/></g><g transform="matrix(3.782835,0,0,12.642381,-1555.754165,-25498.455192)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g></g><g transform="matrix(0.993203,0,0,1,-11.588114,0)"><g transform="matrix(2.1668,0,0,6.217732,-280.934836,-12551.370427)"><path d="M791.653,2071.988L791.653,2029.883" style="fill:none;stroke:currentColor;stroke-width:10.73px;"/></g><g transform="matrix(3.782835,0,0,12.642381,-1689.002938,-25498.412341)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g></g><g transform="matrix(2.152071,0,0,6.217732,-564.274314,-12023.807343)"><path d="M791.653,2071.988L791.653,2029.883" style="fill:none;stroke:currentColor;stroke-width:10.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-1962.771381,-24970.849257)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(0.993203,0,0,1,-2.766307,0)"><g transform="matrix(-2.1668,0,0,6.217732,3331.701633,-12551.370427)"><path d="M791.653,2071.988L791.653,2029.883" style="fill:none;stroke:currentColor;stroke-width:10.73px;"/></g><g transform="matrix(-3.782835,0,0,12.642381,4739.769734,-25498.412341)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g></g><g transform="matrix(-2.152071,0,0,9.468308,3441.720247,-19149.675433)"><path d="M782.203,2071.988C787.419,2071.988 791.653,2068.749 791.653,2064.76L791.653,2029.883" style="fill:none;stroke:currentColor;stroke-width:8.59px;"/></g><g transform="matrix(-2.152071,0,0,-9.468308,2169.281795,19688.101788)"><path d="M782.203,2071.988C787.419,2071.988 791.653,2068.749 791.653,2064.76L791.653,2029.883" style="fill:none;stroke:currentColor;stroke-width:8.59px;"/></g><g transform="matrix(2.152071,0,0,7.241527,-1787.729399,-14517.18965)"><path d="M1039.1,2034.176L1054.992,2034.176" style="fill:none;stroke:currentColor;stroke-width:10px;"/></g><g transform="matrix(2.152071,0,0,5.686505,-751.997459,-11313.825271)"><path d="M791.653,2071.988L791.653,2045.504C791.653,2033.545 800.626,2023.836 811.679,2023.836" style="fill:none;stroke:currentColor;stroke-width:11.12px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-2876.790032,-25498.429638)"><path d="M825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-2998.987784,-25498.429638)"><path d="M822.429,2050.871C820.476,2052.783 817.803,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C818.011,2032.31 820.851,2033.662 822.831,2035.817" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-2090.865843,-24970.892108)"><path d="M804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136C825.683,2049.111 820.832,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136Z" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-1824.541858,-24970.849257)"><path d="M822.193,2051.095C820.263,2052.875 817.686,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136L804.031,2043.136" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-1208.395907,-25498.412341)"><path d="M822.193,2051.095C820.263,2052.875 817.686,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136L804.031,2043.136" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(3.757122,0,0,12.642381,-1962.771381,-25498.412341)"><path d="M822.193,2051.095C820.263,2052.875 817.686,2053.962 814.857,2053.962C808.882,2053.962 804.031,2049.111 804.031,2043.136C804.031,2037.161 808.882,2032.31 814.857,2032.31C820.832,2032.31 825.683,2037.161 825.683,2043.136L804.031,2043.136" style="fill:none;stroke:currentColor;stroke-width:5.73px;"/></g><g transform="matrix(1.866685,0,0,8.027184,528.156897,-182.667229)"><path d="M39.03,47.015L39.03,67.812C39.03,75.16 31.406,81.126 22.015,81.126C12.624,81.126 5,75.16 5,67.812L5,47.015" style="fill:none;fill-rule:nonzero;stroke:currentColor;stroke-width:10.05px;stroke-miterlimit:10;"/></g><g transform="matrix(0,-7.241527,-2.152071,0,675.291064,718.483107)"><path d="M9.515,51.53C9.515,42.139 17.139,34.515 26.53,34.515L49.273,34.515" style="fill:none;fill-rule:nonzero;stroke:currentColor;stroke-width:10px;stroke-miterlimit:10;"/></g></g></g><path class="lw" pathLength="1" d="M176.44 137.12L377.73 137.12Q381.39 137.12 381.39 133.45L381.39 56.59Q381.39 52.93 385.05 52.93L443.74 52.93" style="fill:none;stroke:var(--accent);stroke-width:11.66px"/><circle class="ld ld1" cx="148.72" cy="137.12" r="5.85" style="fill:var(--accent)"/><circle class="ld ld2" cx="471.09" cy="52.94" r="5.85" style="fill:var(--accent)"/></svg> diff --git a/skills/comfyui-readable-node/scripts/notes.py b/skills/comfyui-readable-node/scripts/notes.py index 932094a..d7aa17a 100644 --- a/skills/comfyui-readable-node/scripts/notes.py +++ b/skills/comfyui-readable-node/scripts/notes.py @@ -182,9 +182,14 @@ def model_note_text(models): top = tree for x in _parts(d) or [d]: # a "/" in the folder name ("ultralytics/bbox") nests too top = top.setdefault(x + "/", {}) + dp = _parts(d) for m in ms: t = top *sub, base = _parts(m["name"]) + # a name that starts with the folder's last parts ("bbox/face.pt" in "ultralytics/bbox"): those parts are + # the folder itself, not one more level + k = next((k for k in range(min(len(sub), len(dp)), 0, -1) if dp[-k:] == sub[:k]), 0) + sub = sub[k:] for x in sub: t = t.setdefault(x + "/", {}) t[base] = None @@ -194,6 +199,14 @@ def model_note_text(models): return "\n".join(lines) +def custom_nodes_text(packs): + """The custom nodes part of the model Note, below the models: one line per pack, linked when its place is known.""" + lines = ["## custom nodes", ""] + for (label, url, _), names in packs.items(): + lines.append(f"- [{label}]({url}): {', '.join(names)}" if url else f"- {label} : {', '.join(names)}") + return "\n".join(lines) + + # ---- MarkdownNote height estimate ---- # Matches the frontend's legacy rendering (tiptap, 10px Inter body, line-height normal; a 400-wide node has a # 380-wide body). Height at which the body fits without scrolling = body height + 22 (DOM widget top/bottom margin). diff --git a/skills/comfyui-readable-node/scripts/render.py b/skills/comfyui-readable-node/scripts/render.py index 04750b2..ea7a1d6 100644 --- a/skills/comfyui-readable-node/scripts/render.py +++ b/skills/comfyui-readable-node/scripts/render.py @@ -150,10 +150,28 @@ def chunk(t, d): + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")) +_WIDGET_INFO = {} + + def widget_info(n, oi): info = oi.get(n.get("type")) if not info: return [], set() + # the same node type with the same values gives the same names: computed once (the checks ask millions of times) + try: + key = (id(info), repr(n.get("widgets_values"))) + except Exception: + key = None + hit = _WIDGET_INFO.get(key) if key else None + if hit is not None and hit[0] is info: + return list(hit[1]), set(hit[2]) + names, grow = _widget_info(info, n) + if key: + _WIDGET_INFO[key] = (info, list(names), set(grow)) + return names, grow + + +def _widget_info(info, n): names = comfy_schema.widget_names(info, n.get("widgets_values")) grow = set() for nm, spec, _ in comfy_schema.ordered_input_specs(info): diff --git a/skills/comfyui-readable-node/scripts/report.py b/skills/comfyui-readable-node/scripts/report.py index be542eb..9b65f30 100644 --- a/skills/comfyui-readable-node/scripts/report.py +++ b/skills/comfyui-readable-node/scripts/report.py @@ -6,8 +6,8 @@ (Japanese for ja, English for every other language code) and the page: the nodes drawn on one <canvas> as the ComfyUI canvas draws them (title, slots, widgets, wires, groups), a timeline on which the nodes move smoothly from one step to the next, a switch to the original workflow, and a panel that says what each step did and which problems it made or solved. -No external scripts: everything is inline. The Latin font is inside the page; Japanese text uses Zen Kaku Gothic New -from Google Fonts when online, and the machine's font otherwise. +No external scripts: everything is inline, the logo (logo.svg next to this file) too. The Latin font is inside the page; +Japanese text uses Zen Kaku Gothic New from Google Fonts when online, and the machine's font otherwise. ``build(canvases, original, lang)`` returns the HTML text. """ @@ -31,15 +31,15 @@ # the page's parts: always English CHROME = { - "title": "Readable Node report", "brand": "ComfyUI Readable Node", "theme": {"system": "System", "light": "Light", "dark": "Dark"}, - "original": "Original", "rebuilt": "Rebuilt", "compare": "Compare with the original workflow (O)", - "walk": "Walkthrough", "walk_title": "Walk through the finished workflow part by part (W)", + "title": "Readable Node report", "repo": "ComfyUI Readable Node on GitHub", "theme": {"system": "System", "light": "Light", "dark": "Dark"}, + "original": "Original", "rebuilt": "Rebuilt", + "walk": "Walkthrough", "prev_part": "Previous part", "next_part": "Next part", "walk_whole": "The whole workflow (no part chosen)", "prev": "Previous step", "play": "Play", "pause": "Pause", "next": "Next step", "speed": "Speed", "step": "Step", "zoom_in": "Zoom in", "zoom_out": "Zoom out", "fit": "Fit", "follow": "Follow changes", "problems": "problems", "moved": "moved", "added": "added", "changed": "changed", "removed": "removed", - "legend": "rebuilt / original", "legend_one": "rebuilt", "unplaced_title": "Nodes not placed yet", + "legend": "rebuilt / original", "legend_one": "rebuilt", "legend_orig": "original", "legend_orig_all": "original (all the workflows together)", "unplaced_title": "Nodes not placed yet", "help_title": "Keys and mouse", "help": [["← →", "previous / next step"], ["Space", "play / pause"], ["Home End", "first / last step"], ["O", "original / rebuilt"], ["W", "walkthrough on / off (← → move by part, Esc the whole workflow)"], ["drag the bar", "go to a step"], ["drag", "move the view"], ["wheel, pinch", "zoom"], ["0 F", "fit"], @@ -61,9 +61,9 @@ "units": {"moved": "moved", "added": "placed", "changed": "changed", "removed": "removed", "behind": "behind"}, "show_all": "Show all", "show_less": "Show less", "empty": "Nothing is placed on the canvas yet.", - "review": "Review by another agent", "review_none": "The review file says: No findings.", + "review": "Review by another agent", "review_none": "The review file says: No findings.", "review_withdrawn": "Withdrawn by the reviewer after the builder replied", "review_unchecked": "The review file has no line saying what the reviewer checked.", - "review_fixed": "Fixed", "review_left": "Left as it is", "review_open": "Not answered yet", "walk_toc": "Parts", + "review_fixed": "Fixed", "review_left": "Left as it is", "review_open": "Not answered yet", "walk_toc": "Parts", "walk_whole": "All", "hand": "Wide gaps (gap wide) and the wires between", "counts": CHROME["counts"], }, @@ -76,9 +76,9 @@ "units": {"moved": "動かした", "added": "置いた", "changed": "変えた", "removed": "消した", "behind": "裏を通る"}, "show_all": "すべて見る", "show_less": "たたむ", "empty": "キャンバスにはまだ何も置かれていません。", - "review": "別のエージェントによるレビュー", "review_none": "レビューのファイルには「No findings.」(何も見つからなかった)とあります。", + "review": "別のエージェントによるレビュー", "review_none": "レビューのファイルには「No findings.」(何も見つからなかった)とあります。", "review_withdrawn": "作った側の返事を受けて、レビュー役が取り下げた", "review_unchecked": "レビューのファイルに、レビュー役が何を確かめたかの一行がありません。", - "review_fixed": "直した", "review_left": "残した", "review_open": "まだ答えていない", "walk_toc": "部分", + "review_fixed": "直した", "review_left": "残した", "review_open": "まだ答えていない", "walk_toc": "部分", "walk_whole": "全体", "hand": "広い間(gap wide)と、その間の線の数", "counts": {"overlaps": "重なり", "wires behind nodes": "ノードの裏を通る線", "crossings": "交差", "non-horizontal wires": "水平でない線", "unplaced": "未配置", @@ -433,8 +433,9 @@ def _x_new(S, a, x, d): "title": ("named {n} nodes", "ノード {n} 個に題名を付け"), "mode": ("changed the mode of {n} nodes", "ノード {n} 個の mode を変え")} -def build_summary(xs, lang): - """One sentence for several commands that did not change the drawing (building the graph before it is placed).""" +def build_summary(xs, lang, before_placing=False): + """One sentence for several commands that did not change the drawing (building the graph before it is placed). + before_placing: the sentence is a detail of the first step with nodes on the drawing (the graph built before it).""" S = Say(lang) count = {} for x in xs: @@ -449,9 +450,11 @@ def build_summary(xs, lang): parts.append((ja if S.ja else en).format(n=count[c])) other = sum(v for c, v in count.items() if c not in BUILD_CMDS) if S.ja: - head = f"{len(xs)} 個の命令でノードと線を組み立てました(絵の上ではまだ何も動いていません)" + head = (f"置く前に、{len(xs)} 個の命令でノードと線を組み立てました" if before_placing else + f"{len(xs)} 個の命令でノードと線を組み立てました(絵の上ではまだ何も動いていません)") return head + ("。" + "、".join(parts) + "ました" if parts else "") + (f"。ほかの命令 {other} 個" if other else "") - head = f"Built nodes and wires with {len(xs)} commands (nothing moved on the drawing yet)" + head = (f"Before placing, built nodes and wires with {len(xs)} commands" if before_placing else + f"Built nodes and wires with {len(xs)} commands (nothing moved on the drawing yet)") return head + (": " + ", ".join(parts) if parts else "") + (f"; {other} other commands" if other else "") @@ -504,11 +507,8 @@ def _ids(S, s, limit=6): lambda S, m: S.L(f"The value nodes {S.node(m.group(2))} and {S.node(m.group(3))} side by side have tops {m.group(1)} px apart", f"横に並んだ値のノード {S.node(m.group(2))} と {S.node(m.group(3))} の上端が {m.group(1)} px ずれています")), ("order", r"^(vae|clip) loader (\S+) is above the model loader (\S+):", - lambda S, m: S.L(f"{S.node(m.group(2))} sits above the model loader {S.node(m.group(3))} (loaders go model, vae, clip from the top)", - f"{S.node(m.group(2))} が model の loader {S.node(m.group(3))} より上にあります(loader は上から model、vae、clip)")), - ("order", r"^clip loader (\S+) is above the vae loader (\S+):", - lambda S, m: S.L(f"{S.node(m.group(1))} sits above the vae loader {S.node(m.group(2))} (loaders go model, vae, clip from the top)", - f"{S.node(m.group(1))} が vae の loader {S.node(m.group(2))} より上にあります(loader は上から model、vae、clip)")), + lambda S, m: S.L(f"{S.node(m.group(2))} sits above the model loader {S.node(m.group(3))} (the vae and clip loaders go below the model loader)", + f"{S.node(m.group(2))} が model の loader {S.node(m.group(3))} より上にあります(vae と clip の loader は model の下)")), ("order", r"^(MODEL|VAE|CLIP|CONDITIONING) rail runs above the (MODEL|VAE|CLIP) rail .*: rail of (\S+) and rail of (\S+)$", lambda S, m: S.L(f"The {m.group(1)} rail of {S.node(m.group(3))} runs above the {m.group(2)} rail of {S.node(m.group(4))} (model, vae, clip from the top)", f"{S.node(m.group(3))} の {m.group(1)} のレールが、{S.node(m.group(4))} の {m.group(2)} のレールより上を通っています(上から model、vae、clip)")), @@ -694,7 +694,7 @@ def _review_view(rev): if not rev: return None return {"rows": rev.get("rows") or [], "not_reviewed": rev.get("not_reviewed"), "no_findings": rev.get("no_findings"), - "checked": rev.get("checked")} + "checked": rev.get("checked"), "withdrawn": rev.get("withdrawn") or []} def build(canvases, original, lang="en"): @@ -713,6 +713,9 @@ def build(canvases, original, lang="en"): say, det = build_summary(st["x"], lang), [e["s"] for e in ex] else: say, det = ex[0]["s"], ex[0]["d"] + [e["s"] for e in ex[1:]] + if st.get("pre") and st["pre"][1]: + # the graph built before anything was placed, in one line + det = [build_summary(st["pre"][1], lang, before_placing=True)] + det steps.append({"kind": st["kind"], "c": st["c"], "s": say, "d": det, "v": st["v"], "p": st["p"], "counts": st["counts"]}) probs = [] @@ -724,7 +727,8 @@ def build(canvases, original, lang="en"): data = json.dumps({"lang": lang, "ui": UI[lang], "chrome": CHROME, "colors": LINK_COLORS, "canvases": out, "original": original}, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/") title = html.escape(CHROME["title"]) - return (PAGE.replace("%LANG%", html.escape(code, quote=True)).replace("%TITLE%", title).replace("%STYLE%", _font_face() + STYLE) + return (PAGE.replace("%LANG%", html.escape(code, quote=True)).replace("%TITLE%", title).replace("%FAVICON%", FAVICON) + .replace("%LOGO%", _logo()).replace("%REPO%", REPO).replace("%STYLE%", _font_face() + STYLE) .replace("%DATA%", data).replace("%SCRIPT%", SCRIPT)) @@ -740,18 +744,31 @@ def _font_face(): f"src:url(data:font/woff2;base64,{data}) format('woff2');unicode-range:U+0000-00FF,U+2000-206F,U+2190-2193,U+2212}}\n") +# Icons: Tabler's outline icons (MIT, tabler.io/icons) drawn with a 1.75 stroke, except "rebuilt", which is the wire of +# the logo (a dot, a wire stepping down, a dot). class "draw" marks the strokes that draw themselves when chosen. ICONS = { - "prev": '<path d="M15 5l-8 7 8 7"/>', - "play": '<path d="M8 5v14l11-7z" class="fill"/>', - "next": '<path d="M9 5l8 7-8 7"/>', - "minus": '<path d="M5 12h14"/>', "plus": '<path d="M12 5v14M5 12h14"/>', - "fit": '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>', - "map": '<path d="M3 7l6-3 6 3 6-3v13l-6 3-6-3-6 3z"/><path d="M9 4v13M15 7v13"/>', - "follow": '<circle cx="12" cy="12" r="3"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/>', - "sun": '<circle cx="12" cy="12" r="4"/><path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.3 5.3l1.4 1.4M17.3 17.3l1.4 1.4M5.3 18.7l1.4-1.4M17.3 6.7l1.4-1.4"/>', - "moon": '<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>', - "system": '<rect x="3" y="4.5" width="18" height="12" rx="2"/><path d="M9 20h6M12 16.5V20"/>', - "help": '<path d="M8.5 8.8a3.6 3.6 0 1 1 4.6 3.4c-.7.3-1.1.9-1.1 1.6v.9"/><circle cx="12" cy="18.6" r="1.1" class="fill"/>', + "prev": '<path d="M15 6l-6 6l6 6"/>', + "next": '<path d="M9 6l6 6l-6 6"/>', + "play": '<path d="M7 4v16l13 -8z" class="fill"/>', + "pause": '<path d="M6 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" class="fill"/>' + '<path d="M14 6a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v12a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" class="fill"/>', + "minus": '<path d="M5 12l14 0"/>', "plus": '<path d="M12 5l0 14"/><path d="M5 12l14 0"/>', + "fit": '<path d="M4 8v-2a2 2 0 0 1 2 -2h2"/><path d="M4 16v2a2 2 0 0 0 2 2h2"/><path d="M16 4h2a2 2 0 0 1 2 2v2"/><path d="M16 20h2a2 2 0 0 0 2 -2v-2"/>', + "map": '<path d="M3 7l6 -3l6 3l6 -3v13l-6 3l-6 -3l-6 3v-13"/><path d="M9 4v13"/><path d="M15 7v13"/>', + "follow": '<path d="M12 12m-.5 0a.5 .5 0 1 0 1 0a.5 .5 0 1 0 -1 0"/><path d="M12 12m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"/>' + '<path d="M12 3l0 2"/><path d="M3 12l2 0"/><path d="M12 19l0 2"/><path d="M19 12l2 0"/>', + "sun": '<path d="M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0 -8 0"/><path d="M3 12h1m8 -9v1m8 8h1m-9 8v1m-6.4 -15.4l.7 .7m12.1 -.7l-.7 .7m0 11.4l.7 .7m-12.1 -.7l-.7 .7"/>', + "moon": '<path d="M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454z"/>', + "system": '<path d="M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10z"/><path d="M7 20h10"/><path d="M9 16v4"/><path d="M15 16v4"/>', + "help": '<path d="M8 8a3.5 3 0 0 1 3.5 -3h1a3.5 3 0 0 1 3.5 3a3 3 0 0 1 -2 3a3 4 0 0 0 -2 4"/><path d="M12 19l0 .01"/>', + # the workflow as its author saved it: a tangle (Tabler "scribble") + "original": '<path class="draw" pathLength="1" d="M3 15c2 3 4 4 7 4s7 -3 7 -7s-3 -7 -6 -7s-5 1.5 -5 4s2 5 6 5s8.408 -2.453 10 -5"/>', + # the rebuilt workflow: the logo's wire + "rebuilt": '<circle cx="3.5" cy="17" r="1.75" class="fill"/><path class="draw" pathLength="1" d="M6.8 17h4.7a1.5 1.5 0 0 0 1.5 -1.5v-7a1.5 1.5 0 0 1 1.5 -1.5h2.7"/>' + '<circle cx="20.5" cy="7" r="1.75" class="fill dot2"/>', + # the walkthrough: Tabler "book" + "github": '<path d="M9 19c-4.3 1.4 -4.3 -2.5 -6 -3m12 5v-3.5c0 -1 .1 -1.4 -.5 -2c2.8 -.3 5.5 -1.4 5.5 -6a4.6 4.6 0 0 0 -1.3 -3.2a4.2 4.2 0 0 0 -.1 -3.2s-1.1 -.3 -3.5 1.3a12.3 12.3 0 0 0 -6.2 0c-2.4 -1.6 -3.5 -1.3 -3.5 -1.3a4.2 4.2 0 0 0 -.1 3.2a4.6 4.6 0 0 0 -1.3 3.2c0 4.6 2.7 5.7 5.5 6c-.6 .6 -.6 1.2 -.5 2v3.5"/>', + "walk": '<path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"/><path d="M3 6l0 13"/><path d="M12 6l0 13"/><path d="M21 6l0 13"/>', } @@ -759,105 +776,140 @@ def _icon(name): return f'<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">{ICONS[name]}</svg>' -ACCENT = "#ff5a1f" # the one colour that marks "now" (the needle, the current step, the moved nodes) +ACCENT = "#ff5a1f" # the one colour that marks "now" (the needle, the current step, the moved nodes); the logo's wire +LOGO_FILE = Path(__file__).with_name("logo.svg") +REPO = "https://github.com/nomadoor/comfyui-readable-node" +# the browser tab's icon: the logo's wire on a dark rounded square +FAVICON = ("data:image/svg+xml," + "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%23121314'/%3E" + "%3Cpath d='M10 21h4.5a2 2 0 0 0 2 -2v-6a2 2 0 0 1 2 -2H22' fill='none' stroke='%23ff5a1f' stroke-width='2.6' stroke-linecap='round'/%3E" + "%3Ccircle cx='6.5' cy='21' r='2' fill='%23ff5a1f'/%3E%3Ccircle cx='25.5' cy='11' r='2' fill='%23ff5a1f'/%3E%3C/svg%3E") + +def _logo(): + return LOGO_FILE.read_text(encoding="utf-8").strip() if LOGO_FILE.is_file() else '<span class="name">ComfyUI Readable Node</span>' + + +# Colour only where it means something: the accent for "now", green for solved or added, red for problems, yellow for +# changed. A button's name floats just above it (or below, at the top of the page); nothing moves when the system asks +# for less motion. STYLE = """ -:root{--bg:#000;--tile:#1c1c1e;--tile2:#2c2c2e;--text:#d1d1d6;--muted:#7c7c80;--faint:#48484a;--head:#f5f5f7; +:root{--bg:#000;--tile:#1c1c1e;--tile2:#2c2c2e;--text:#b4b4b9;--muted:#7c7c80;--faint:#48484a;--head:#dcdce0; --accent:%ACCENT%;--good:#5fbf7a;--bad:#ff6b5f;--warn:#e0b25c; --cv-bg:#121214;--cv-dot:#2a2a2d;--node-bg:#353535;--node-title:#2c2c2c;--node-text:#c8c8c8;--slot-text:#a8a8a8; --w-bg:#222;--w-text:#dddddd;--w-label:#999;--casing:rgba(0,0,0,.6);--shadow:rgba(0,0,0,.45);--mix:100;--wmix:100;--gop:.2; --font:"Plus Jakarta Sans","Zen Kaku Gothic New","Hiragino Sans","Hiragino Kaku Gothic ProN","Noto Sans CJK JP","Yu Gothic UI",system-ui,sans-serif; ---mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace;--code:var(--mono),"Zen Kaku Gothic New","Hiragino Sans","Noto Sans CJK JP";--r-lg:22px;--r-md:16px;--ease:cubic-bezier(.2,.8,.2,1);color-scheme:dark} -@media (prefers-color-scheme:light){:root:not([data-theme=dark]){--bg:#e2dfe5;--tile:#f4f2f6;--tile2:#e8e6eb;--text:#3a3a3c; ---muted:#7c7a80;--faint:#c7c6cb;--head:#1d1d1f;--good:#1f7a3e;--bad:#c4321f;--warn:#a8670f; ---cv-bg:#f6f5f8;--cv-dot:#d4d2d8;--node-bg:#ffffff;--node-title:#e9e9ec;--node-text:#222;--slot-text:#4a4a52; ---w-bg:#f0f0f2;--w-text:#1a1a1a;--w-label:#6a6a72;--casing:rgba(255,255,255,.9);--shadow:rgba(0,0,0,.12);--mix:30;--wmix:70;--gop:.1;color-scheme:light}} +--mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace;--code:var(--mono),"Zen Kaku Gothic New","Hiragino Sans","Noto Sans CJK JP"; +--chev:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M4.5 2.5L8 6l-3.5 3.5' fill='none' stroke='%23000' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");--r-box:12px;--r-field:6px;--inset:12px;--t-hover:120ms;--t-seg:160ms;--ease:cubic-bezier(.2,.8,.2,1);--ease-out:cubic-bezier(.25,1,.5,1);color-scheme:dark} :root[data-theme=light]{--bg:#e2dfe5;--tile:#f4f2f6;--tile2:#e8e6eb;--text:#3a3a3c;--muted:#7c7a80;--faint:#c7c6cb;--head:#1d1d1f; --good:#1f7a3e;--bad:#c4321f;--warn:#a8670f;--cv-bg:#f6f5f8;--cv-dot:#d4d2d8;--node-bg:#fff;--node-title:#e9e9ec;--node-text:#222; --slot-text:#4a4a52;--w-bg:#f0f0f2;--w-text:#1a1a1a;--w-label:#6a6a72;--casing:rgba(255,255,255,.9);--shadow:rgba(0,0,0,.12); --mix:30;--wmix:70;--gop:.1;color-scheme:light} *{box-sizing:border-box} html,body{height:100%;margin:0} -body{background:var(--bg);color:var(--text);font:14px/1.55 var(--font);overflow:hidden} -button{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer} +body{background:var(--bg);color:var(--text);font:14px/1.55 var(--font);overflow:hidden;-webkit-font-smoothing:antialiased} +button,a{font:inherit;color:inherit;border:0;background:none;padding:0;cursor:pointer} +:focus-visible{outline:none} [hidden]{display:none!important} -.icon{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} +.icon{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.75;stroke-linecap:round;stroke-linejoin:round} .icon .fill{fill:currentColor;stroke:none} .app{height:100%;display:grid;grid-template-columns:minmax(0,1fr) 372px;grid-template-rows:auto minmax(0,1fr);gap:0 10px;padding:0 10px 10px} -/* header: the name and the tabs over the canvas column, the theme switch over the side panel; no space above it */ -.top{grid-column:1/-1;display:grid;grid-template-columns:subgrid;height:48px} -.top .lead{display:flex;align-items:stretch;gap:12px;min-width:0} -.top .name{flex:none;align-self:center;font-size:13px;font-weight:700;color:var(--head);padding-left:6px;white-space:nowrap} -.seg.theme{justify-self:end;align-self:center;padding:2px} + +/* header: the logo and the tabs over the canvas column, GitHub and the theme switch over the side panel; no space above it */ +.top{grid-column:1/-1;display:grid;grid-template-columns:subgrid;grid-template-rows:56px;height:56px} +.top .lead{display:flex;align-items:stretch;gap:14px;min-width:0} +.brand{flex:none;align-self:center;display:block;color:var(--head);line-height:0;padding-left:6px;cursor:default} +.brand .logo{height:30px;width:auto;display:block;overflow:visible} +.top .name{font-size:14px;font-weight:700;white-space:nowrap} +.tr{justify-self:end;align-self:center;display:flex;align-items:center;gap:8px} +.tr .ext{display:grid;place-items:center;width:32px;height:32px;border-radius:999px;color:var(--muted);transition:color var(--t-hover) ease} +.tr .ext:hover{color:var(--head)} +.seg.theme{padding:2px} .seg.theme .knob{top:2px;bottom:2px} .seg.theme button{display:grid;place-items:center;width:28px;height:24px;padding:0} .seg.theme .icon{width:15px;height:15px} +/* the logo's wire runs from the left dot to the right one; nothing else in the logo moves */ +.brand.play .lw{animation:rn-draw .75s cubic-bezier(.65,0,.35,1) backwards} +@keyframes rn-draw{from{stroke-dasharray:1 1;stroke-dashoffset:1}to{stroke-dasharray:1 1;stroke-dashoffset:0}} +@keyframes rn-fade{from{opacity:0}to{opacity:1}} + .stage{display:flex;flex-direction:column;gap:10px;min-width:0;min-height:0} /* segmented switch: a dark capsule with a light capsule on the chosen item */ -.seg{position:relative;display:inline-flex;padding:4px;border-radius:999px;background:var(--tile2);gap:2px;max-width:100%;overflow-x:auto;scrollbar-width:none} +.seg{position:relative;display:inline-flex;align-items:center;padding:4px;border-radius:999px;background:var(--tile2);gap:2px;max-width:100%;overflow-x:auto;scrollbar-width:none} .seg::-webkit-scrollbar{display:none} -.seg button{height:32px;padding:0 16px;border-radius:999px;font-size:13px;font-weight:600;color:var(--muted);white-space:nowrap;transition:background .15s var(--ease),color .15s} +.seg button{position:relative;z-index:1;display:inline-flex;align-items:center;gap:7px;height:32px;padding:0 16px;border-radius:999px;font-size:14px;font-weight:600;color:var(--muted);white-space:nowrap;transition:color var(--t-seg) ease-out} .seg button:hover{color:var(--head)} -.seg button{position:relative;z-index:1} .seg button[aria-pressed=true]{color:var(--bg)} .seg .knob{position:absolute;top:4px;bottom:4px;left:0;border-radius:999px;background:var(--head);pointer-events:none;transition:transform .25s var(--ease),width .25s var(--ease)} +.seg button .icon{width:16px;height:16px} +.seg button[aria-pressed=true] .draw{animation:rn-draw .45s cubic-bezier(.65,0,.35,1) backwards} +.seg button[aria-pressed=true] .dot2{animation:rn-fade .22s .36s ease-out backwards} /* workflow tabs, like a browser's: the chosen tab has the canvas colour and runs into the canvas below */ .tabs{display:flex;align-items:flex-end;gap:2px;min-width:0;padding:0 10px;overflow-x:auto;overflow-y:hidden;scrollbar-width:none} .tabs::-webkit-scrollbar{display:none} -.tabs button{position:relative;flex:none;height:40px;padding:0 16px 8px;border-radius:9px 9px 0 0;font-size:12px;font-weight:600;color:var(--muted);white-space:nowrap} +.tabs button{position:relative;flex:none;height:40px;padding:0 16px 8px;border-radius:9px 9px 0 0;font-size:14px;font-weight:600;color:var(--muted);white-space:nowrap;transition:color var(--t-hover) ease} .tabs button:hover{color:var(--text)} -.tabs button[aria-pressed=true]{background:var(--cv-bg);color:var(--head)} -.tabs button[aria-pressed=true]::before,.tabs button[aria-pressed=true]::after{content:"";position:absolute;bottom:0;width:9px;height:9px} -.tabs button[aria-pressed=true]::before{left:-9px;background:radial-gradient(circle at 0 0,transparent 9px,var(--cv-bg) 9.5px)} -.tabs button[aria-pressed=true]::after{right:-9px;background:radial-gradient(circle at 100% 0,transparent 9px,var(--cv-bg) 9.5px)} -#view{position:relative;flex:1;min-height:0;overflow:hidden;background:var(--cv-bg);border-radius:var(--r-lg);cursor:grab;touch-action:none;user-select:none} +.tabs button[aria-selected=true]{background:var(--cv-bg);color:var(--head)} +.tabs button[aria-selected=true]::before,.tabs button[aria-selected=true]::after{content:"";position:absolute;bottom:0;width:9px;height:9px} +.tabs button[aria-selected=true]::before{left:-9px;background:radial-gradient(circle at 0 0,transparent 9px,var(--cv-bg) 9.5px)} +.tabs button[aria-selected=true]::after{right:-9px;background:radial-gradient(circle at 100% 0,transparent 9px,var(--cv-bg) 9.5px)} +#view{position:relative;flex:1;min-height:0;overflow:hidden;background:var(--cv-bg);border-radius:var(--r-box);cursor:grab;touch-action:none;user-select:none} #view.drag{cursor:grabbing} #cv{position:absolute;inset:0;width:100%;height:100%;display:block} -#seg{position:absolute;left:12px;bottom:12px;z-index:2} +.float{position:absolute;z-index:2} +#seg{left:var(--inset);bottom:var(--inset)} +#seg button{padding:0 16px 0 13px} /* the workflows of one tab that differ only in values (one per model): a switch at the top of the canvas */ -#variants{position:absolute;left:12px;top:12px;z-index:2} -#variants button{height:28px;padding:0 12px;font-size:12px} -.tools{position:absolute;right:12px;bottom:12px;display:flex;gap:2px;padding:4px;border-radius:999px;background:var(--tile2);z-index:2} +#variants{left:var(--inset);top:var(--inset)} +#variants button{height:28px;padding:0 12px;font-size:13px} +.tools{right:var(--inset);bottom:var(--inset);display:flex;align-items:center;gap:2px;padding:4px;border-radius:999px;background:var(--tile2)} +.tools .sep{width:1px;height:18px;margin:0 4px;background:var(--faint);flex:none} .tool{display:grid;place-items:center;width:32px;height:32px;border-radius:999px;color:var(--text)} .tool:hover{background:var(--faint);color:var(--head)} .tool[aria-pressed=true]{background:var(--head);color:var(--bg)} .tool.off{opacity:.35;pointer-events:none} -.empty{position:absolute;inset:0;display:grid;place-items:center;color:var(--muted);pointer-events:none;font-size:13px;padding:24px;text-align:center} -.ntip{position:absolute;pointer-events:none;padding:4px 10px;border-radius:999px;font-size:12px;background:var(--tile2);color:var(--head);white-space:nowrap;z-index:3} +.empty{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;color:var(--muted);pointer-events:none;font-size:14px;padding:24px;text-align:center} +.empty .mark{width:120px;height:auto;color:var(--faint)} +.empty .mark .draw{animation:rn-draw 1.1s .2s cubic-bezier(.65,0,.35,1) backwards} +.ntip{position:absolute;pointer-events:none;padding:4px 8px;border-radius:var(--r-field);font-size:13px;background:var(--tile2);color:var(--head);white-space:nowrap;z-index:3;animation:rn-fade var(--t-hover) ease-out} .ntip small{color:var(--muted);margin-left:6px} -.help{position:absolute;right:12px;bottom:56px;max-width:300px;padding:12px 16px;border-radius:var(--r-md);font-size:12px;line-height:1.75; +.bubble{position:fixed;z-index:20;width:max-content;max-width:280px;padding:4px 8px;border-radius:var(--r-field); +background:var(--head);color:var(--bg);font-size:13px;font-weight:500;line-height:16px;pointer-events:none;visibility:hidden;opacity:0} +.bubble.on{visibility:visible;opacity:1;transition:opacity var(--t-hover) ease-out} +.help{position:absolute;right:var(--inset);bottom:60px;width:320px;padding:10px 16px;border-radius:var(--r-box);font-size:13px;line-height:1.5; background:var(--tile2);color:var(--text);z-index:3} -.help b{color:var(--head);font-weight:600;font-family:var(--mono);font-size:11.5px;margin-right:6px} +.help div{display:flex;gap:12px;align-items:baseline;padding:3px 0} +.help b{flex:none;width:96px;color:var(--head);font-weight:600} +.help .t{color:var(--text)} /* the deck: play, step, and the timeline, all one height */ -.deckwrap{position:relative;flex:none} -.deck{display:flex;align-items:center;gap:6px;flex:none;height:32px} +.deckwrap{position:relative;flex:none;background:var(--tile);border-radius:var(--r-box);padding:4px} +.deck,.walkbar{display:flex;align-items:center;gap:6px;flex:none;height:40px} .deck.off{opacity:.35;pointer-events:none} -.round{display:grid;place-items:center;width:32px;height:32px;border-radius:8px;background:var(--tile);color:var(--text);flex:none} +.round{display:grid;place-items:center;width:40px;height:40px;border-radius:999px;color:var(--text);flex:none} .round:hover{background:var(--tile2);color:var(--head)} -.round .icon{width:16px;height:16px;display:block} +.round .icon{width:18px;height:18px;display:block} #playicon{display:grid;place-items:center} -.speed{height:32px;width:44px;padding:0;text-align:center;border-radius:8px;background:var(--tile);font-size:12px;font-weight:600;color:var(--text);font-variant-numeric:tabular-nums;flex:none} +.speed{height:40px;min-width:48px;padding:0 12px;text-align:center;border-radius:999px;font-size:13px;font-weight:600;color:var(--text);font-variant-numeric:tabular-nums;flex:none} .speed:hover{background:var(--tile2);color:var(--head)} -.bar{position:relative;flex:1;min-width:0;height:32px;border-radius:8px;background:var(--tile);cursor:pointer;touch-action:none;user-select:none} -.bar .in{position:absolute;top:0;bottom:0;left:10px;right:10px} -.spark{position:absolute;left:0;bottom:5px;width:100%;height:20px;overflow:visible} -.spark path{fill:var(--faint);fill-opacity:.55;stroke:none} +.bar{position:relative;flex:1;min-width:0;height:40px;margin:0 4px;border-radius:var(--r-field);background:var(--tile2);cursor:pointer;touch-action:none;user-select:none} +.bar .in{position:absolute;top:0;bottom:0;left:12px;right:12px} +.spark{position:absolute;left:0;bottom:6px;width:100%;height:26px;overflow:visible} +.spark path{fill:var(--faint);fill-opacity:.7;stroke:none} .tk{position:absolute;bottom:0;width:1px;height:4px;background:var(--faint)} -.ph{position:absolute;top:5px;bottom:5px;width:2px;margin-left:-1px;border-radius:1px;background:var(--accent);pointer-events:none} -.tip{position:absolute;bottom:40px;transform:translateX(-50%);padding:5px 10px;border-radius:8px;font-size:12px; -background:var(--tile2);color:var(--text);pointer-events:none;white-space:nowrap;z-index:5} +.ph{position:absolute;top:7px;bottom:5px;width:2px;margin-left:-1px;border-radius:1px;background:var(--accent);pointer-events:none} +.ph::before{content:"";position:absolute;left:50%;top:-2px;width:8px;height:8px;margin-left:-4px;border-radius:50%;background:var(--accent)} +.tip{position:absolute;bottom:54px;transform:translateX(-50%);padding:4px 8px;border-radius:var(--r-field);font-size:13px; +background:var(--tile2);color:var(--text);pointer-events:none;white-space:nowrap;z-index:5;animation:rn-fade var(--t-hover) ease-out} .tip b{color:var(--head);font-weight:700;margin-right:6px} /* the walkthrough: the parts in processing order instead of the timeline (same height as the deck) */ -.walkbar{display:flex;align-items:center;gap:6px;height:32px} -.wparts{flex:1;min-width:0;height:32px;display:flex;gap:4px;overflow:hidden} -.wpart{min-width:0;height:32px;padding:0 10px;border-radius:8px;background:var(--tile);font-size:12px;font-weight:600;color:var(--muted); -white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background .15s var(--ease),color .15s} -.wpart:hover{color:var(--head)} +.wparts{flex:1;min-width:0;height:40px;display:flex;gap:2px;overflow:hidden;margin:0 4px} +.wpart{min-width:0;height:40px;padding:0 14px;border-radius:999px;font-size:13px;font-weight:600;color:var(--muted); +white-space:nowrap;overflow:hidden;text-overflow:ellipsis;transition:background-color var(--t-hover) ease,color var(--t-hover) ease} +.wpart:hover{color:var(--head);background:var(--tile2)} .wpart[aria-current=true]{background:var(--head);color:var(--bg)} .wwhole[aria-pressed=true]{background:var(--head);color:var(--bg)} -.wtitle{font-size:19px;font-weight:600;line-height:1.35;color:var(--head);margin:2px 8px 6px} -.wbody{margin:0 8px;font-size:13.5px;line-height:1.7;color:var(--text)} +.wtitle{font-size:20px;font-weight:700;line-height:1.35;letter-spacing:-.005em;color:var(--head);margin:4px 8px 10px} +.wbody{margin:0 8px;font-size:14px;line-height:1.7;color:var(--text)} .wbody p{margin:0 0 6px} /* bullets: the walkthrough text and the lists of the side panel */ .wbody ul,ul.plain{list-style:none;margin:0;padding:0} @@ -865,69 +917,68 @@ def _icon(name): .wbody li::before,ul.plain li::before{content:"";position:absolute;left:2px;top:12px;width:4px;height:4px;border-radius:50%;background:var(--muted)} .wbody ul ul{padding-left:14px} .wbody ul ul li::before{background:none;border:1px solid var(--muted);width:3px;height:3px} -.wbody code{font:12px var(--code);background:var(--tile);border-radius:4px;padding:1px 5px;color:var(--head)} +.wbody code{font:13px var(--code);background:var(--tile);border-radius:5px;padding:1px 5px;color:var(--head)} .wbody b{color:var(--head);font-weight:600} .wanswer{color:var(--muted);margin-top:2px} /* the whole workflow in the walkthrough: the parts as links, then the review, folded */ .wtoc{list-style:none;margin:0 0 14px;padding:0;counter-reset:wtoc} -.wtoc li{counter-increment:wtoc;padding:4px 0 4px 22px;position:relative} -.wtoc li::before{content:counter(wtoc);position:absolute;left:0;top:4px;color:var(--muted);font-variant-numeric:tabular-nums} +.wtoc li{counter-increment:wtoc;padding:4px 0 4px 26px;position:relative} +.wtoc li::before{content:counter(wtoc);position:absolute;left:0;top:4px;width:16px;text-align:right;color:var(--muted);font-weight:600;font-variant-numeric:tabular-nums} .wtoc a{color:var(--head);text-decoration:none;font-weight:600} .wtoc a:hover,.wtoc a:focus-visible{text-decoration:underline} .wtoc .wtocs{color:var(--muted);margin-top:2px} -details.wreview{border-top:1px solid var(--line);padding-top:8px} -details.wreview summary{cursor:pointer;color:var(--muted)} +details.wreview{border-top:1px solid var(--tile2);padding-top:8px} /* the side panel */ aside{display:flex;flex-direction:column;min-height:0;gap:10px} .phead{display:flex;flex-direction:column;gap:10px;flex:none} .ptop{display:flex;align-items:flex-end;justify-content:flex-end;gap:12px;padding:6px 6px 0;height:40px} .stepno{font-size:13px;font-weight:600;color:var(--muted);font-variant-numeric:tabular-nums;white-space:nowrap} -.stepno b{display:inline-block;text-align:right;font-size:22px;font-weight:600;color:var(--head)} -.lab{font-size:11px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -.legend{font-size:10.5px;font-weight:500;letter-spacing:.02em;color:var(--faint);text-align:right;padding:0 8px;height:17px;line-height:17px;white-space:nowrap;overflow:hidden} -.grid{display:grid;grid-template-columns:1fr 1fr;gap:12px 8px} -.pill-tile{display:flex;align-items:center;justify-content:space-between;gap:8px;min-width:0;padding:13px 18px 13px 22px;border-radius:999px;background:var(--tile)} +.stepno b{display:inline-block;text-align:right;font-size:22px;font-weight:600;color:var(--head);margin-right:2px} +.lab{font-size:12px;font-weight:500;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.legend{font-size:12px;font-weight:500;color:var(--muted);text-align:right;padding:0 8px;height:16px;line-height:16px;white-space:nowrap;overflow:hidden} +.grid{display:grid;grid-template-columns:1fr 1fr;gap:6px} +.pill-tile{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;min-width:0;padding:12px 12px 11px 14px;border-radius:var(--r-box);background:var(--tile)} .pt{min-width:0} -.pill-tile .v{font-size:22px;font-weight:300;line-height:1.15;color:var(--head);font-variant-numeric:tabular-nums;white-space:nowrap} -.pill-tile .was{font-size:15px;color:var(--muted)} -.pill-tile .lab{font-size:9.5px;letter-spacing:.03em;color:var(--muted);margin-top:2px} -.pill-tile svg{flex:none;width:18px;height:18px;fill:none;stroke:var(--muted);stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round} -.pill-tile svg .f{fill:var(--muted);fill-opacity:.3} -.keys{display:grid;grid-template-columns:auto auto 1fr;align-items:center;gap:7px 10px;padding:4px 8px 2px;font-size:11.5px} +.pill-tile .v{font-size:22px;font-weight:600;letter-spacing:-.01em;line-height:1.15;color:var(--head);font-variant-numeric:tabular-nums;white-space:nowrap} +.pill-tile .was{font-size:14px;font-weight:500;color:var(--muted)} +.pill-tile .lab{margin-top:3px} +.pill-tile svg{flex:none;width:18px;height:18px;margin-top:2px;fill:none;stroke:var(--muted);stroke-width:1.75;stroke-linecap:round;stroke-linejoin:round} +.pill-tile svg .f{fill:var(--muted);fill-opacity:.25} +.keys{display:grid;grid-template-columns:auto auto 1fr;align-items:center;gap:6px 10px;padding:2px 8px;font-size:13px} .keys>span{cursor:default} .keys .sw{width:14px;height:10px;border-radius:3px;border:2px solid} .keys .sw.removed{border:0;background:var(--faint);opacity:.45} .keys .sw.behind{border:1.5px dashed var(--bad)} .keys .d{line-height:1.45} -.keys .k{color:var(--text)}.keys .d{color:var(--muted)} -.pbody{flex:1;min-height:0;overflow-y:scroll;scrollbar-gutter:stable;scrollbar-width:thin;scrollbar-color:var(--tile2) transparent;padding:4px 4px 24px 6px} -.pbody::-webkit-scrollbar{width:8px}.pbody::-webkit-scrollbar-thumb{background:var(--tile2);border-radius:4px}.pbody::-webkit-scrollbar-track{background:transparent} -.say{font-size:13.5px;line-height:1.6;color:var(--text);margin:4px 0 10px} -h3{font-size:11px;font-weight:600;color:var(--muted);margin:16px 0 4px;padding:0 8px;display:flex;gap:6px} -h3 .c{color:var(--text)} +.keys .k{color:var(--head);font-weight:600}.keys .d{color:var(--muted)} +.pbody{flex:1;min-height:0;overflow-y:scroll;scrollbar-gutter:stable;scrollbar-width:thin;scrollbar-color:var(--tile2) transparent;padding:6px 2px 24px 0;border-top:1px solid var(--tile)} +.pbody::-webkit-scrollbar{width:6px}.pbody::-webkit-scrollbar-thumb{background:var(--tile2);border-radius:4px}.pbody::-webkit-scrollbar-track{background:transparent} +.say{font-size:14px;line-height:1.65;color:var(--head);margin:8px 8px 12px} ul.plain li{padding:3px 0 3px 14px;font-size:13px} -.more{color:var(--head);padding:4px 0;font-size:12px;font-weight:600} -.quiet{color:var(--muted);font-size:13px;margin:6px 0} +.more{color:var(--head);padding:4px 0;font-size:13px;font-weight:600} +.quiet{color:var(--muted);font-size:14px;margin:8px} .probs{list-style:none;margin:0;padding:0;display:flex;flex-direction:column} -.probs button{display:flex;align-items:baseline;gap:8px;width:100%;text-align:left;border-radius:8px;padding:3px 8px;font-size:11.5px;line-height:1.55;color:var(--muted)} +.probs button{display:flex;align-items:baseline;gap:8px;width:100%;text-align:left;border-radius:var(--r-field);padding:3px 8px;font-size:13px;line-height:1.55;color:var(--muted);transition:background-color var(--t-hover) ease,color var(--t-hover) ease} .probs button>span:last-child{min-width:0} .probs button:hover,.probs button[aria-pressed=true]{color:var(--text)} .probs button:hover{background:var(--tile)} .probs button[aria-pressed=true]{background:var(--tile2)} -.probs .dot{flex:none;width:5px;height:5px;border-radius:50%;transform:translateY(-1px);background:var(--bad);opacity:.7} +.probs .dot{flex:none;width:6px;height:6px;border-radius:50%;transform:translateY(-1px);background:var(--bad)} .probs .good .dot{background:var(--good)} -details{margin-top:10px} -details{padding:0 8px}details>summary{cursor:pointer;color:var(--muted);font-size:11px;font-weight:600;list-style:none;display:flex;align-items:center;gap:8px} -details>summary::before{content:"";width:6px;height:6px;border-right:1.5px solid currentColor;border-bottom:1.5px solid currentColor;transform:rotate(-45deg);transition:transform .15s} -details[open]>summary::before{transform:rotate(45deg)} +details{margin-top:10px;padding:0 8px} +details>summary{cursor:pointer;color:var(--muted);font-size:13px;font-weight:600;list-style:none;display:flex;align-items:center;gap:8px;height:24px;transition:color var(--t-hover) ease} +details>summary:hover{color:var(--head)} +details>summary::before{content:"";flex:none;width:12px;height:12px;background:currentColor;-webkit-mask:var(--chev) center/12px no-repeat;mask:var(--chev) center/12px no-repeat;transition:transform .15s} +details[open]>summary::before{transform:rotate(90deg)} +details>summary .n{color:var(--head);margin-left:4px;font-variant-numeric:tabular-nums} details>summary::-webkit-details-marker{display:none} -pre.cmd{font:12px/1.6 var(--code);color:var(--text);background:var(--tile);border-radius:12px;padding:10px 12px;margin:8px 0 0; +pre.cmd{font:12px/1.6 var(--code);color:var(--text);background:var(--tile);border-radius:var(--r-field);padding:10px 12px;margin:6px 0 0; white-space:pre-wrap;word-break:break-word;max-height:260px;overflow:auto} .ref{color:inherit;cursor:pointer} .ref:hover{color:var(--head);text-decoration:underline;text-decoration-color:var(--faint);text-underline-offset:3px} -.ref small{color:var(--faint);font-weight:400;margin-left:3px;font-size:.85em} -.say .ref{color:var(--head)} -@media (prefers-reduced-motion:reduce){*{transition:none!important}} +.ref small{color:var(--muted);opacity:.75;font-weight:500;margin-left:3px;font-size:.85em} +.say .ref{color:var(--head);font-weight:600} +@media (prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}} @media (max-width:900px){ body{overflow:auto;height:auto} .app{display:flex;flex-direction:column;height:auto} @@ -938,31 +989,38 @@ def _icon(name): } """.replace("%ACCENT%", ACCENT) +# the small wire of the logo, large and faint, where the canvas is empty +EMPTY_MARK = ('<svg class="mark icon" viewBox="0 0 24 24" aria-hidden="true" style="stroke-width:1.2">' + '<circle cx="3.5" cy="17" r="1.3" class="fill"/><path class="draw" pathLength="1" d="M6.5 17h5a1.5 1.5 0 0 0 1.5 -1.5v-7a1.5 1.5 0 0 1 1.5 -1.5h3"/>' + '<circle cx="20.5" cy="7" r="1.3" class="fill"/></svg>') + PAGE = """<!doctype html> <html lang="%LANG%"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> <title>%TITLE% + - + +
-
-
+
%LOGO%
+
""" + _icon("github") + """
-
- -
- +
+ +
+
- +
-
+