Files
aigc-home/calliope-backend/src/calliope/routers/comfyui.py
T
施工员andmultica-agent 319c7b049b fix: nine review follow-ups for connections & workflow foundation (HEL-619)
1. .form-col border-box — 384px is the outer width (a6 spec)
2. import preview counts all analyzed inputs, matching inline/studio counts
3. SSRF guard also runs on endpoint save (create + patch)
4. schemeless/garbled URL is a 400 format error, not a DNS-classified probe failure
5. ComfyUI health probe timeout 120s → 5s (matches the test probe)
6. workflow delete refuses (409) while pending/running jobs use it; delete errors surfaced in the UI
7. agent_llm_assignments: per-role incremental merge server-side + single-role delta payloads
8. test_shell_tool now portable (interpreter on PATH; PYTHON+approval instead of ffprobe)
9. test_video_continue pauses the queue singleton via monkeypatch (no leak into test_workbench)

Co-authored-by: multica-agent <github@multica.ai>
2026-09-29 16:13:00 +08:00

370 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""ComfyUI multi-connection endpoints: CRUD + server-side connectivity test.
HEL-611 / HEL-601 §3. All probes run from the machine hosting this
workbench (the user's rule: connectivity is judged by the SERVER, not the
browser). Tokens are stored server-side only and never echoed back.
"""
from __future__ import annotations
import ipaddress
import socket
import time
from typing import Any
from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from calliope.config import settings
router = APIRouter()
_TEST_TIMEOUT_SEC = 5.0
_TEST_TIMEOUT_RANGE = (2.0, 15.0)
_AUTH_TYPES = ("none", "bearer", "header")
# SSRF guard (HEL-601 §3.4): http/https only; link-local (incl. cloud
# metadata 169.254.169.254) and unspecified/multicast/reserved targets are
# rejected. Loopback is EXPLICITLY allowed — a local ComfyUI is a
# legitimate target for this desktop tool.
_BLOCKED_NETWORKS = [
ipaddress.ip_network("169.254.0.0/16"),
ipaddress.ip_network("0.0.0.0/8"),
ipaddress.ip_network("224.0.0.0/4"),
ipaddress.ip_network("240.0.0.0/4"),
ipaddress.ip_network("255.255.255.255/32"),
ipaddress.ip_network("fe80::/10"),
ipaddress.ip_network("ff00::/8"),
]
class EndpointIn(BaseModel):
id: str | None = None
name: str | None = None
base_url: str
auth_type: str = "none"
# Blank/None on edit keeps the stored token (it is never echoed back).
auth_token: str | None = None
header_name: str | None = None
notes: str | None = None
class EndpointPatch(BaseModel):
name: str | None = None
base_url: str | None = None
auth_type: str | None = None
auth_token: str | None = None
header_name: str | None = None
notes: str | None = None
class EndpointTestIn(BaseModel):
endpoint_id: str | None = None
# Raw candidate values (unsaved form). Stored values fill the blanks
# when endpoint_id is given — the token never needs a round trip.
base_url: str | None = None
auth_type: str | None = None
auth_token: str | None = None
header_name: str | None = None
timeout_sec: float | None = Field(
None, ge=_TEST_TIMEOUT_RANGE[0], le=_TEST_TIMEOUT_RANGE[1]
)
def _parsed_url(base_url: str) -> tuple[str, str]:
url = (base_url or "").strip()
if not url:
raise HTTPException(status_code=400, detail="API 地址不能为空")
# HEL-619: the server validates format as strictly as the UI already
# does. A schemeless garbled string used to be silently prefixed with
# http:// and then reported as a DNS failure; it is a 400 format error.
if "://" not in url or any(ch.isspace() for ch in url):
raise HTTPException(status_code=400, detail="地址必须是 http:// 或 https:// 开头的有效 URL")
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.hostname:
raise HTTPException(status_code=400, detail="地址必须是 http:// 或 https:// 开头的有效 URL")
return url.rstrip("/"), parsed.hostname
def _assert_not_ssrf(hostname: str) -> None:
"""Reject link-local / metadata / reserved targets (loopback allowed)."""
try:
addr = ipaddress.ip_address(hostname)
except ValueError:
addr = None
candidates: list[str] = [str(addr)] if addr else _resolve_host(hostname)
for cand in candidates:
try:
ip = ipaddress.ip_address(cand)
except ValueError:
continue
if ip.is_loopback:
continue
for net in _BLOCKED_NETWORKS:
if ip in net:
raise HTTPException(
status_code=400,
detail="该地址位于被禁止的网段(链路本地/元数据/保留地址),不允许探测",
)
def _resolve_host(hostname: str) -> list[str]:
try:
infos = socket.getaddrinfo(hostname, None, proto=socket.IPPROTO_TCP)
except OSError:
return []
return sorted({info[4][0] for info in infos})
def _public_payload() -> dict[str, Any]:
data = settings.to_public_dict()
return {"endpoints": data["comfyui_endpoints"], "active_id": data["comfyui_active_id"]}
def _stored_endpoint(endpoint_id: str) -> dict[str, Any]:
settings.ensure_comfyui_endpoints()
for ep in settings.comfyui_endpoints:
if ep.get("id") == endpoint_id:
return ep
raise HTTPException(status_code=404, detail="连接不存在")
@router.get("/endpoints")
async def list_endpoints() -> dict[str, Any]:
return _public_payload()
@router.post("/endpoints")
async def create_endpoint(payload: EndpointIn) -> dict[str, Any]:
base_url, host = _parsed_url(payload.base_url)
# HEL-619: the same SSRF guard as the connectivity test applies on
# save — otherwise a blocked address can be stored and later probed by
# the worker path. Unresolvable hosts still pass (resolution happens
# again at probe time).
_assert_not_ssrf(host)
incoming = [ep for ep in settings.comfyui_endpoints or []]
incoming.append(payload.model_dump() | {"base_url": base_url})
try:
settings.replace_comfyui_endpoints(incoming)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
settings.save_config_file()
return _public_payload()
@router.patch("/endpoints/{endpoint_id}")
async def update_endpoint(endpoint_id: str, payload: EndpointPatch) -> dict[str, Any]:
_stored_endpoint(endpoint_id)
base_url = payload.base_url
if base_url is not None:
base_url, host = _parsed_url(base_url)
_assert_not_ssrf(host) # same save-time guard as create (HEL-619)
patch = payload.model_dump(exclude_unset=True)
if base_url is not None:
patch["base_url"] = base_url
incoming = [
{**ep, **patch} if ep.get("id") == endpoint_id else ep
for ep in settings.comfyui_endpoints
]
try:
settings.replace_comfyui_endpoints(incoming)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
settings.save_config_file()
return _public_payload()
@router.delete("/endpoints/{endpoint_id}")
async def delete_endpoint(endpoint_id: str) -> dict[str, Any]:
_stored_endpoint(endpoint_id)
remaining = [ep for ep in settings.comfyui_endpoints if ep.get("id") != endpoint_id]
if not remaining:
raise HTTPException(status_code=400, detail="至少保留一个连接;如需更换请先编辑现有连接")
settings.replace_comfyui_endpoints(remaining)
settings.save_config_file()
return _public_payload()
@router.post("/endpoints/{endpoint_id}/activate")
async def activate_endpoint(endpoint_id: str) -> dict[str, Any]:
_stored_endpoint(endpoint_id)
settings.comfyui_active_id = endpoint_id
settings.apply_active_comfyui()
settings.save_config_file()
return _public_payload()
def _classify_connect_error(exc: httpx.ConnectError) -> tuple[str, str]:
"""Map a connect failure onto (code, Chinese message).
httpx collapses socket errors to "All connection attempts failed" on
the outer exception — the distinguishing errno lives in the __cause__
chain, so classify over the whole chain.
"""
parts: list[str] = [f"{exc.__class__.__name__}: {exc}"]
node = exc.__cause__ or exc.__context__
seen = {id(exc)}
while node is not None and id(node) not in seen:
seen.add(id(node))
parts.append(f"{node.__class__.__name__}: {node}")
node = node.__cause__ or node.__context__
text = " | ".join(parts)
lowered = text.lower()
if (
"name or service not known" in lowered
or "getaddrinfo" in lowered
or "temporary failure in resolution" in lowered
or "nodename nor servname" in lowered
):
return "dns", "域名解析失败:请检查地址拼写或 DNS"
if (
"connection refused" in lowered
or "errno 111" in lowered
or "errno 10061" in lowered
or "winerror 10061" in lowered
):
return "refused", "连接被拒绝:目标端口没有服务在监听"
if "ssl" in lowered or "certificate" in lowered:
return "tls", "TLS/证书错误:检查 https 配置或改用 http"
if "unreachable" in lowered or "no route to host" in lowered:
return "refused", "网络不可达:本机无法路由到该地址"
return "connect", f"无法建立连接:{str(exc)[:300]}"
@router.post("/endpoints/test")
async def test_endpoint(payload: EndpointTestIn) -> dict[str, Any]:
"""Server-side ComfyUI probe: GET /system_stats with error classification."""
from calliope.comfyui.endpoints import build_auth_headers
base_url = (payload.base_url or "").strip()
auth_type = (payload.auth_type or "").strip() or None
auth_token = (payload.auth_token or "").strip() or None
header_name = (payload.header_name or "").strip() or None
if payload.endpoint_id:
stored = _stored_endpoint(payload.endpoint_id)
if not base_url:
base_url = str(stored.get("base_url") or "")
if auth_type is None:
auth_type = str(stored.get("auth_type") or "none")
if auth_token is None:
token = stored.get("auth_token")
auth_token = token if isinstance(token, str) and token.strip() else None
if header_name is None:
header_name = stored.get("header_name")
if not base_url:
raise HTTPException(status_code=400, detail="base_url 和 endpoint_id 至少提供一项")
url, hostname = _parsed_url(base_url)
_assert_not_ssrf(hostname)
headers = build_auth_headers(
{
"auth_type": auth_type or "none",
"auth_token": auth_token,
"header_name": header_name,
}
)
timeout_sec = (
payload.timeout_sec if payload.timeout_sec is not None else _TEST_TIMEOUT_SEC
)
timeout_sec = min(max(timeout_sec, _TEST_TIMEOUT_RANGE[0]), _TEST_TIMEOUT_RANGE[1])
started = time.perf_counter()
try:
async with httpx.AsyncClient(timeout=timeout_sec, follow_redirects=True) as client:
resp = await client.get(f"{url}/system_stats", headers=headers)
except httpx.TimeoutException:
return {
"ok": False,
"error": "timeout",
"message": f"超时:{timeout_sec:.0f} 秒内没有响应",
"timeout_sec": timeout_sec,
}
except httpx.ConnectError as exc:
code, message = _classify_connect_error(exc)
return {"ok": False, "error": code, "message": message, "detail": str(exc)[:300]}
except httpx.HTTPError as exc:
return {
"ok": False,
"error": "connect",
"message": "连接失败",
"detail": (str(exc) or exc.__class__.__name__)[:300],
}
elapsed_ms = int((time.perf_counter() - started) * 1000)
if resp.status_code in (401, 403):
return {
"ok": False,
"error": "auth",
"message": f"鉴权失败(HTTP {resp.status_code}):请检查访问令牌或鉴权方式",
}
if resp.status_code == 404:
# Reverse proxies sometimes strip /system_stats — probe "/" so the
# user learns "reachable, but not confirmed ComfyUI" (HEL-601 risk ①).
reachable = False
try:
async with httpx.AsyncClient(timeout=timeout_sec, follow_redirects=True) as client:
root = await client.get(f"{url}/", headers=headers)
reachable = root.status_code < 500
except httpx.HTTPError:
reachable = False
if reachable:
return {
"ok": False,
"error": "not_comfyui",
"message": "HTTP 可达但未确认是 ComfyUI(/system_stats 不存在)",
"elapsed_ms": elapsed_ms,
}
return {
"ok": False,
"error": "not_comfyui",
"message": "未找到 /system_stats,且根路径不可用",
}
if resp.status_code >= 500:
return {
"ok": False,
"error": "server",
"message": f"目标服务返回错误(HTTP {resp.status_code})",
"elapsed_ms": elapsed_ms,
}
if resp.status_code >= 400:
return {
"ok": False,
"error": "http",
"message": f"请求被拒绝(HTTP {resp.status_code})",
"detail": resp.text[:200].strip(),
}
try:
data = resp.json()
except ValueError:
return {
"ok": False,
"error": "not_comfyui",
"message": "地址连通,但响应不是 ComfyUI(/system_stats 返回非 JSON)",
"elapsed_ms": elapsed_ms,
}
system = data.get("system") if isinstance(data, dict) else None
version = None
if isinstance(system, dict):
version = system.get("comfyui_version")
if not version:
return {
"ok": False,
"error": "not_comfyui",
"message": "地址连通,但响应不像 ComfyUI(/system_stats 缺少版本字段)",
"elapsed_ms": elapsed_ms,
}
device_name = None
devices = data.get("devices") if isinstance(data, dict) else None
if isinstance(devices, list) and devices and isinstance(devices[0], dict):
device_name = devices[0].get("name") or devices[0].get("type")
return {
"ok": True,
"elapsed_ms": elapsed_ms,
"comfyui_version": str(version),
**({"device_name": str(device_name)} if device_name else {}),
}