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:
@@ -218,10 +218,21 @@ class Generation:
|
||||
# -- the one frame that reaches a browser after a reply is over.
|
||||
drained: bool = False
|
||||
injected_ids: list[str] = field(default_factory=list)
|
||||
# Images this reply produced, waiting to be bound to its message row. The
|
||||
# runner writes the file and the `Attachment`; only `_persist` may say which
|
||||
# turn it belongs to, which is the same division of labour `canvas` above
|
||||
# follows and for the same reason.
|
||||
attachment_ids: list[str] = field(default_factory=list)
|
||||
# How many times *in a row* this reply has ended with plan tasks still open
|
||||
# and been told to carry on. Reset the moment it calls a tool again, so the
|
||||
# count is of consecutive stops rather than of stops in total.
|
||||
nudges: int = 0
|
||||
# A tool this reply must call, set by `/image` and by nothing else. It goes
|
||||
# into the *first* request only -- `_run` rebuilds the payload's messages
|
||||
# per round but keeps this body, and `tool_choice` left in place would make
|
||||
# every later round call the tool again, which is a loop rather than a
|
||||
# command. Cleared once the first round has gone out.
|
||||
force_tool: str = ""
|
||||
|
||||
def touch(self) -> None:
|
||||
self.version += 1
|
||||
@@ -362,7 +373,7 @@ def _prune() -> None:
|
||||
_TASKS.pop(message_id, None)
|
||||
|
||||
|
||||
def ensure(chat_id: str, message_id: str) -> Generation:
|
||||
def ensure(chat_id: str, message_id: str, *, force_tool: str = "") -> Generation:
|
||||
"""Start generating this reply if it is not already under way.
|
||||
|
||||
Idempotent, because more than one thing can ask for it: the route that
|
||||
@@ -377,7 +388,7 @@ def ensure(chat_id: str, message_id: str) -> Generation:
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
generation = Generation(chat_id=chat_id, message_id=message_id)
|
||||
generation = Generation(chat_id=chat_id, message_id=message_id, force_tool=force_tool)
|
||||
_RUNNING[message_id] = generation
|
||||
_TASKS[message_id] = asyncio.create_task(_run(generation))
|
||||
return generation
|
||||
@@ -471,7 +482,7 @@ async def _run(generation: Generation) -> None:
|
||||
toolset = tools_service.resolve_tools(db, chat, owner)
|
||||
offered = toolset.schemas
|
||||
payload = chat_service.build_request(
|
||||
db, chat, upto=message, tools=offered, user=owner
|
||||
db, chat, upto=message, tools=offered, user=owner, force_tool=generation.force_tool
|
||||
)
|
||||
question = _question_from(payload)
|
||||
needs_title = not chat.title_generated
|
||||
@@ -777,6 +788,12 @@ async def _run(generation: Generation) -> None:
|
||||
# somebody through all of them -- or away from a file they
|
||||
# are editing -- is what makes a panel like this unusable.
|
||||
canvas_service.open_tab(generation.canvas, opened, activate=False)
|
||||
if attachment_id := outcome.event.get("attachment_id"):
|
||||
# A generated image. The runner wrote the row and the bytes;
|
||||
# binding it to this reply is the loop's job for the reason
|
||||
# the canvas tab above is -- a runner cannot write the
|
||||
# message row, and `_persist` is the single writer.
|
||||
generation.attachment_ids.append(str(attachment_id))
|
||||
if outcome.event.get("plan"):
|
||||
generation.plan = outcome.event["plan"]
|
||||
# Only `plan_submit` sets this. `plan_update` writes the
|
||||
@@ -809,6 +826,10 @@ async def _run(generation: Generation) -> None:
|
||||
messages.append(added)
|
||||
|
||||
payload = {**payload, "messages": messages}
|
||||
# `/image` forces the first round to call the tool. Leaving it set
|
||||
# would force *every* round to, so the reply could never finish --
|
||||
# it would draw a picture, be asked again, and draw another.
|
||||
payload.pop("tool_choice", None)
|
||||
|
||||
# A plan ends the turn. One more request so the model can say what
|
||||
# it proposed and why -- a bubble containing only a card reads as
|
||||
@@ -1902,6 +1923,28 @@ def _inject(generation: Generation, chat_id: str, vision: bool) -> dict | None:
|
||||
return entry
|
||||
|
||||
|
||||
def _bind_attachments(db, chat, message, ids: list[str]) -> None:
|
||||
"""Bind images this reply produced to the bubble that produced them.
|
||||
|
||||
The narrowing is the point. The ids arrive on a tool event, and an event is
|
||||
a dict a runner built -- so the query names this chat and refuses a row that
|
||||
is already bound, exactly as `files.claim` does for an upload, and for the
|
||||
identical reason: without it a forged id would attach somebody else's file
|
||||
to this conversation.
|
||||
"""
|
||||
from lembas.db.models import Attachment
|
||||
|
||||
rows = db.scalars(
|
||||
select(Attachment).where(
|
||||
Attachment.id.in_(ids),
|
||||
Attachment.chat_id == chat.id,
|
||||
Attachment.message_id.is_(None),
|
||||
)
|
||||
)
|
||||
for attachment in rows:
|
||||
attachment.message_id = message.id
|
||||
|
||||
|
||||
def _persist(generation: Generation, title: str, elapsed: float) -> None:
|
||||
"""Write the finished reply, name the chat, and set the unread flag.
|
||||
|
||||
@@ -1944,6 +1987,12 @@ def _persist(generation: Generation, title: str, elapsed: float) -> None:
|
||||
# the snapshot above was seeded when the reply began, and
|
||||
# somebody may have opened a tab by hand since.
|
||||
chat.canvas_json = canvas_service.merge(chat.canvas_json, generation.canvas)
|
||||
if generation.attachment_ids:
|
||||
# Images this reply made, bound to it here because this is the
|
||||
# only writer. Scoped to rows this chat owns and still unbound,
|
||||
# for the reason `files.claim` is scoped: an id that came back
|
||||
# on an event must not be able to pull in somebody else's file.
|
||||
_bind_attachments(db, chat, message, generation.attachment_ids)
|
||||
if generation.plan:
|
||||
# This bubble now carries the plan in force, and the chat points
|
||||
# at it so the harness can find it with one primary-key lookup
|
||||
|
||||
Reference in New Issue
Block a user