Draw a picture, on a ComfyUI you are running

The last unbuilt capability, and built the way CLAUDE.md said it had to be: a
ToolDef reaching resolve_tools plus a permission and a capability flag, not a new
code path. The only genuinely new UI is one branch in the transcript.

services/images/ is three modules. comfy.py speaks HTTP -- submit, poll /history,
fetch the PNG, /free, and an /object_info discovery for the admin page only.
Polled and not socketed, because holding a connection open for the length of a
generation is the live-connection state the whole ssh.py design forbids, and the
thing being waited for takes tens of seconds anyway. The base URL is exempt from
the SSRF guard by construction, exactly as Connection.base_url and the audio
endpoints are -- said out loud in the docstring, because a default of
127.0.0.1:8188 is precisely the shape that guard exists to refuse and therefore
reads as a hole rather than a decision.

workflow.py fills a template, and the one thing that matters is that it walks the
parsed JSON rather than the text of it. A value that is exactly "{{steps}}"
becomes the number 20; ComfyUI validates types and refuses the string. A
placeholder inside a longer string is still text, which is what makes
"{{prompt}}, masterpiece" work -- and text substitution would additionally mean a
prompt containing a quotation mark produced a document that no longer parses, on
the one input guaranteed to hold arbitrary text. Which node holds the prompt is
the administrator's statement rather than a guess from node types: sniffing for
the first CLIPTextEncode works on the shipped workflow and on nothing else, and
swaps positive for negative the first time somebody reorders them. seed has no
fixed default, because one would make every unspecified generation identical and
make the retry loop redraw the same rejected picture four times.

tool.py is one call, one finished image. Returning every attempt to the
conversation would cost a round each, make the ceiling advisory rather than
enforced, and walk the reader past every reject -- so the reviewer lives inside
the tool and is asked about *bytes*: an attempt about to be discarded should not
leave an Attachment behind, so it sees a downscaled preview built in memory and
only the kept image is written. Anything that goes wrong in review is a keep;
losing a picture because a judging request timed out would be the check
destroying the thing it was checking. The last attempt is kept whatever the
verdict, so a request always produces something. Rejects are recorded, not
stored.

Preserve VRAM unloads the chat's own connection and nothing else, because the
memory being freed belongs to one machine: local llama-swap answers GET /unload,
and a box on the network has no reason to be unloaded when ComfyUI wants memory
here. The swap goes round the review rather than round the tool, which costs two
model loads per retry -- so the two settings are independent and the page warns
when both are on. Nothing loads the LLM back: the reply's next request does, and
that step exists in the description and not in the code, so the code says so.

Two rules elsewhere had to be drawn for the first time. message_payload sends
images only on user turns -- no assistant message had ever carried one, and the
moment one does the multimodal list form on an assistant turn is rejected by
OpenAI and most local runners, breaking every later turn in the chat. And
files.store gained keep_original, because _process_image turns anything without
alpha into JPEG q85 at 1400px: right for a phone photo, a visible loss on the one
output this feature exists to produce.

/image sends the ordinary message with force_tool, which becomes tool_choice for
the first round only -- left in place the reply would draw a picture, be asked
again, and draw another. FORCEABLE_TOOLS is an allow list because the name is
read off a form.

ToolContext gained chat_id, and that fixed a tool nobody had ever successfully
run: _run_scratch_write read context.chat_id on a dataclass with no such field,
so every call raised AttributeError, swallowed by run_tool's blanket except into
"the scratch_write tool failed" -- indistinguishable from a model calling it
wrongly. The test that existed asserted the family and the risk, which are
properties of the declaration rather than of the code.

Verified against the real ComfyUI 0.27.0 on this machine rather than against
documentation: every endpoint shape here was read off it, a generation ran end to
end through the client, the reviewer was shown a matching and a mismatched prompt
and answered KEEP and RETRY correctly, and the unload hook fired for the local
llama-swap and not for the remote box.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-05 14:13:19 +02:00
parent 9f5ff72e32
commit 47d1ddbc3c
38 changed files with 3958 additions and 18 deletions
+122
View File
@@ -0,0 +1,122 @@
"""Filling a ComfyUI template.
The thing worth pinning here is types. ComfyUI validates its inputs, so a
workflow whose `steps` arrives as the string "20" is refused -- and the refusal
happens on somebody's machine a minute later rather than in a test.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
import lembas
from lembas.services.images import workflow as wf
BASE = json.loads(
(Path(lembas.__file__).parent / "services/images/base_workflow.json").read_text(
encoding="utf-8"
)
)
def _filled(**given):
return wf.fill(BASE, wf.resolve({"prompt": "a bicycle", **given}))
# --- Substitution --------------------------------------------------------------
def test_a_whole_placeholder_keeps_its_type():
"""`"steps": "{{steps}}"` has to become the number 20, not the text "20".
Substituting textually is the obvious implementation and produces a document
ComfyUI refuses."""
sampler = _filled(steps=25, cfg=7.5, seed=42)["3"]["inputs"]
assert sampler["steps"] == 25
assert isinstance(sampler["steps"], int)
assert sampler["cfg"] == 7.5
assert isinstance(sampler["cfg"], float)
assert sampler["seed"] == 42
assert isinstance(sampler["seed"], int)
def test_a_placeholder_inside_a_string_is_text():
"""Which is what makes `"{{prompt}}, masterpiece"` a usable template."""
filled = wf.fill(
{"n": {"inputs": {"text": "{{prompt}}, masterpiece"}}}, wf.resolve({"prompt": "a cat"})
)
assert filled["n"]["inputs"]["text"] == "a cat, masterpiece"
def test_the_prompt_and_the_negative_go_to_different_nodes():
filled = _filled(negative="blurry")
assert filled["6"]["inputs"]["text"] == "a bicycle"
assert filled["7"]["inputs"]["text"] == "blurry"
def test_the_links_between_nodes_survive():
"""A workflow is a graph, and `["4", 0]` is an edge rather than a value. A
filler that walked only dicts would flatten every one of them."""
filled = _filled()
assert filled["3"]["inputs"]["model"] == ["4", 0]
assert filled["8"]["inputs"]["vae"] == ["4", 2]
assert filled["5"]["inputs"]["batch_size"] == 1
def test_an_unknown_placeholder_is_left_alone():
"""`prompts.substitute`'s rule. A literal `{{x}}` is not a feature, but
silently deleting one is worse than leaving it where somebody can see it."""
filled = wf.fill({"n": {"inputs": {"lora": "{{lora_name}}"}}}, wf.resolve({"prompt": "x"}))
assert filled["n"]["inputs"]["lora"] == "{{lora_name}}"
def test_the_shipped_template_uses_every_placeholder_it_should():
assert wf.placeholders_in(BASE) == set(wf.PLACEHOLDERS)
# --- Resolution ----------------------------------------------------------------
def test_what_is_not_asked_for_takes_its_default():
values = wf.resolve({"prompt": "a bicycle"})
assert values["steps"] == 20
assert values["cfg"] == 8.0
assert values["width"] == 512
assert values["negative"] == "text, watermark"
assert values["sampler"] == "euler"
def test_the_seed_is_random_when_nobody_names_one():
"""A fixed default would make every unspecified generation identical -- and
would make the retry loop produce the same rejected image four times."""
seeds = {wf.resolve({"prompt": "x"})["seed"] for _ in range(8)}
assert len(seeds) == 8
def test_a_named_seed_is_kept():
assert wf.resolve({"prompt": "x", "seed": 1234})["seed"] == 1234
@pytest.mark.parametrize("empty", [None, ""])
def test_null_and_empty_mean_no_opinion(empty):
"""A model that emits `"steps": null` rather than omitting the key is common
enough that reading it as a request for zero steps would be a bug nobody
could see."""
assert wf.resolve({"prompt": "x", "steps": empty})["steps"] == 20
def test_out_of_range_numbers_are_clamped_rather_than_refused():
"""A model asking for 300 steps has misjudged rather than misbehaved, and a
clarifying round costs more than doing the sensible thing."""
values = wf.resolve({"prompt": "x", "steps": 5000, "cfg": -4, "denoise": 12})
assert values["steps"] == 150
assert values["cfg"] == 0.0
assert values["denoise"] == 1.0
def test_nonsense_falls_back_instead_of_raising():
"""Arguments come from a model, so "twenty" is a thing that will arrive."""
assert wf.resolve({"prompt": "x", "steps": "twenty"})["steps"] == 20
def test_a_seed_larger_than_comfyui_allows_is_wrapped():
assert 0 <= wf.resolve({"prompt": "x", "seed": wf.MAX_SEED + 5})["seed"] <= wf.MAX_SEED