feat(recipes): opt-in workflow embedding for widget recipe saves

Add a "Save Recipe with Workflow" action next to "Save Recipe" in the LoRA
widget context menu. It posts the current UI-format graph alongside the save
request so the stored preview embeds it and the recipe can send the graph back
to ComfyUI. Embedding stays opt-in rather than folded into "Save Recipe": the
workflow is by far the largest metadata field and its widget values may carry
sensitive data.

- web/comfyui: new menu entry; saveRecipeDirectly({ embedWorkflow }) posts the
  UI graph and reports the outcome (embedded / skipped) via toasts.
- save_recipe_from_widget handler: reads an optional JSON workflow field so the
  long-standing body-less POST keeps working, including from cached clients.
- RecipePersistenceService.save_recipe_from_widget: embeds the graph through
  the existing optimize_image workflow path, derives has_workflow by detection,
  and skips graphs above MAX_WORKFLOW_EMBED_BYTES with workflow_skipped.
This commit is contained in:
Will Miao
2026-09-29 09:03:26 +08:00
parent 69691b17a1
commit faeb66a23d
10 changed files with 607 additions and 25 deletions
+52 -3
View File
@@ -208,6 +208,11 @@ class StubAnalysisService:
self.remote_calls: List[Optional[str]] = []
self.local_calls: List[Optional[str]] = []
self.local_ignore_recipe_metadata_calls: List[bool] = []
self.widget_analysis_calls: List[Any] = []
self.widget_result = SimpleNamespace(
payload={"metadata": {"loras": ""}, "image_bytes": b"widget-image"},
status=200,
)
self.result = SimpleNamespace(payload={"loras": []}, status=200)
self._recipe_parser_factory: Any = None
StubAnalysisService.instances.append(self)
@@ -242,7 +247,8 @@ class StubAnalysisService:
return self.result
async def analyze_widget_metadata(self, *, recipe_scanner) -> SimpleNamespace:
return SimpleNamespace(payload={"metadata": {}, "image_bytes": b""}, status=200)
self.widget_analysis_calls.append(recipe_scanner)
return self.widget_result
class StubPersistenceService:
@@ -252,6 +258,7 @@ class StubPersistenceService:
def __init__(self, **_: Any) -> None:
self.save_calls: List[Dict[str, Any]] = []
self.widget_calls: List[Dict[str, Any]] = []
self.delete_calls: List[str] = []
self.move_calls: List[Dict[str, str]] = []
self.update_calls: List[Dict[str, Any]] = []
@@ -359,9 +366,24 @@ class StubPersistenceService:
)
async def save_recipe_from_widget(
self, *, recipe_scanner, metadata: Dict[str, Any], image_bytes: bytes
self,
*,
recipe_scanner,
metadata: Dict[str, Any],
image_bytes: bytes,
workflow: Any = None,
) -> SimpleNamespace: # pragma: no cover
return SimpleNamespace(payload={"success": True}, status=200)
self.widget_calls.append(
{
"recipe_scanner": recipe_scanner,
"metadata": metadata,
"image_bytes": image_bytes,
"workflow": workflow,
}
)
return SimpleNamespace(
payload={"success": True, "has_workflow": workflow is not None}, status=200
)
class StubSharingService:
@@ -481,6 +503,33 @@ async def recipe_harness(
StubSharingService.instances.clear()
async def test_save_from_widget_forwards_workflow_body(monkeypatch, tmp_path: Path) -> None:
"""The opt-in workflow arrives through a real JSON body and is handed to
the persistence layer; the response reports whether it was embedded."""
async with recipe_harness(monkeypatch, tmp_path) as harness:
workflow = {"nodes": [{"id": 1}], "last_node_id": 1}
response = await harness.client.post(
"/api/lm/recipes/save-from-widget", json={"workflow": workflow}
)
payload = await response.json()
assert response.status == 200
assert payload["has_workflow"] is True
assert harness.persistence.widget_calls[0]["workflow"] == workflow
async def test_save_from_widget_without_body_still_saves(monkeypatch, tmp_path: Path) -> None:
"""The long-standing body-less POST must keep working unchanged."""
async with recipe_harness(monkeypatch, tmp_path) as harness:
response = await harness.client.post("/api/lm/recipes/save-from-widget")
payload = await response.json()
assert response.status == 200
assert payload["has_workflow"] is False
assert harness.persistence.widget_calls[0]["workflow"] is None
async def test_list_recipes_provides_file_urls(monkeypatch, tmp_path: Path) -> None:
async with recipe_harness(monkeypatch, tmp_path) as harness:
recipe_path = harness.tmp_dir / "recipes" / "demo.png"
+129
View File
@@ -0,0 +1,129 @@
"""Handler tests for the widget "Save Recipe" endpoint.
Covers the opt-in workflow body: the endpoint historically received no body at
all, so a missing, empty or malformed body must degrade to "no workflow"
rather than failing the save.
"""
from __future__ import annotations
import json
import logging
from types import SimpleNamespace
from typing import Any
import pytest
from py.routes.handlers.recipe_handlers import RecipeManagementHandler
async def _noop_ensure() -> None:
return None
class FakeRequest:
"""Minimal request double exposing the optional-body contract."""
def __init__(
self,
*,
body: Any = None,
can_read_body: bool = True,
json_raises: bool = False,
) -> None:
self._body = body
self.can_read_body = can_read_body
self._json_raises = json_raises
async def json(self) -> Any:
if self._json_raises or self._body is None:
raise ValueError("no JSON body")
return self._body
class CapturingPersistence:
def __init__(self) -> None:
self.calls: list[dict[str, Any]] = []
async def save_recipe_from_widget(self, **kwargs: Any) -> SimpleNamespace:
self.calls.append(kwargs)
return SimpleNamespace(
payload={"success": True, "has_workflow": bool(kwargs.get("workflow"))},
status=200,
)
def _make_handler(persistence: CapturingPersistence) -> RecipeManagementHandler:
analysis_service = SimpleNamespace(
analyze_widget_metadata=lambda **kwargs: _analysis_result()
)
return RecipeManagementHandler(
ensure_dependencies_ready=_noop_ensure,
recipe_scanner_getter=lambda: object(),
logger=logging.getLogger(__name__),
persistence_service=persistence, # pyright: ignore[reportArgumentType]
analysis_service=analysis_service, # pyright: ignore[reportArgumentType]
downloader_factory=lambda: None,
civitai_client_getter=lambda: None,
)
async def _analysis_result() -> SimpleNamespace:
return SimpleNamespace(
payload={"metadata": {"loras": ""}, "image_bytes": b"image"}
)
@pytest.mark.asyncio
async def test_widget_save_forwards_workflow_from_json_body():
persistence = CapturingPersistence()
handler = _make_handler(persistence)
workflow = {"nodes": [{"id": 1}]}
response = await handler.save_recipe_from_widget(
FakeRequest(body={"workflow": workflow}) # type: ignore[arg-type]
)
assert response.status == 200
assert persistence.calls[0]["workflow"] == workflow
@pytest.mark.asyncio
async def test_widget_save_without_body_passes_no_workflow():
persistence = CapturingPersistence()
handler = _make_handler(persistence)
response = await handler.save_recipe_from_widget(
FakeRequest(can_read_body=False) # type: ignore[arg-type]
)
assert response.status == 200
assert persistence.calls[0]["workflow"] is None
@pytest.mark.asyncio
async def test_widget_save_tolerates_malformed_body():
persistence = CapturingPersistence()
handler = _make_handler(persistence)
await handler.save_recipe_from_widget(
FakeRequest(json_raises=True) # type: ignore[arg-type]
)
await handler.save_recipe_from_widget(
FakeRequest(body=["not", "an", "object"]) # type: ignore[arg-type]
)
assert [call["workflow"] for call in persistence.calls] == [None, None]
@pytest.mark.asyncio
async def test_widget_save_reports_embedded_workflow_in_response():
persistence = CapturingPersistence()
handler = _make_handler(persistence)
response = await handler.save_recipe_from_widget(
FakeRequest(body={"workflow": {"nodes": []}}) # type: ignore[arg-type]
)
assert json.loads(response.text)["has_workflow"] is True