diff --git a/calliope-backend/src/calliope/agent/harness/plugins/render.py b/calliope-backend/src/calliope/agent/harness/plugins/render.py
index 28322141..202595bd 100644
--- a/calliope-backend/src/calliope/agent/harness/plugins/render.py
+++ b/calliope-backend/src/calliope/agent/harness/plugins/render.py
@@ -1305,9 +1305,10 @@ async def t_list_workflows(ctx: ToolContext, args: dict[str, Any]) -> list[dict[
async def t_comfy_server_info(ctx: ToolContext, args: dict[str, Any]) -> dict[str, Any]:
- from calliope.comfyui.client import ComfyUIClient
+ from calliope.comfyui.endpoints import client_for
- client = ComfyUIClient()
+ # Active connection (with its auth headers) — HEL-611 multi-endpoint.
+ client = client_for(None)
try:
info = await client.health()
return {"ok": True, "comfyui": info}
diff --git a/calliope-backend/src/calliope/comfyui/client.py b/calliope-backend/src/calliope/comfyui/client.py
index 72c5398a..362f4951 100644
--- a/calliope-backend/src/calliope/comfyui/client.py
+++ b/calliope-backend/src/calliope/comfyui/client.py
@@ -53,10 +53,11 @@ def _surface_error(prefix: str, resp: httpx.Response) -> RuntimeError:
class ComfyUIClient:
- def __init__(self, base_url: str | None = None) -> None:
+ def __init__(self, base_url: str | None = None, headers: dict[str, str] | None = None) -> None:
self.base_url = (base_url or settings.comfyui_base_url).rstrip("/")
self.client_id = str(uuid.uuid4())
- self._http = httpx.AsyncClient(timeout=120.0)
+ self._headers = dict(headers or {})
+ self._http = httpx.AsyncClient(timeout=120.0, headers=self._headers)
async def close(self) -> None:
await self._http.aclose()
diff --git a/calliope-backend/src/calliope/comfyui/endpoints.py b/calliope-backend/src/calliope/comfyui/endpoints.py
new file mode 100644
index 00000000..95dbe983
--- /dev/null
+++ b/calliope-backend/src/calliope/comfyui/endpoints.py
@@ -0,0 +1,67 @@
+"""Shared helpers for ComfyUI multi-connection endpoints (HEL-611).
+
+Every generation path (flow-internal video/asset jobs, playground, agent
+tool calls) funnels through ``queue_manager.enqueue``, which stamps an
+endpoint SNAPSHOT ``{id, name, base_url}`` into the job payload. The
+worker resolves that snapshot at run time: a still-configured endpoint id
+wins (fresh URL + token), a dangling id falls back to the snapshot URL,
+and no snapshot at all falls back to the active endpoint.
+"""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any
+
+from calliope.config import settings
+
+if TYPE_CHECKING:
+ from calliope.comfyui.client import ComfyUIClient
+
+
+def endpoint_snapshot(endpoint_id: str | None) -> dict[str, Any] | None:
+ """Connection snapshot for the job payload — never includes the token.
+
+ Dangling ids fall back to the active endpoint (mirrors
+ ``resolve_comfyui_endpoint``'s leniency) so an enqueue never hard-fails
+ because a connection was deleted between submit and stamp.
+ """
+ endpoint = settings.resolve_comfyui_endpoint(endpoint_id)
+ if not endpoint:
+ return None
+ return {
+ "id": endpoint.get("id"),
+ "name": endpoint.get("name"),
+ "base_url": endpoint.get("base_url"),
+ }
+
+
+def build_auth_headers(endpoint: dict[str, Any]) -> dict[str, str]:
+ """Authorization headers for a stored endpoint (server-side only)."""
+ auth_type = endpoint.get("auth_type") or "none"
+ token = endpoint.get("auth_token") if isinstance(endpoint.get("auth_token"), str) else None
+ token = (token or "").strip()
+ if not token:
+ return {}
+ if auth_type == "bearer":
+ return {"Authorization": f"Bearer {token}"}
+ if auth_type == "header":
+ header = (endpoint.get("header_name") or "X-Api-Key").strip() or "X-Api-Key"
+ return {header: token}
+ return {}
+
+
+def client_for(endpoint: dict[str, Any] | None) -> ComfyUIClient:
+ """Build a ComfyUIClient for a stored endpoint (auth headers included).
+
+ ``None`` falls back to the active endpoint, so legacy call sites keep
+ their behaviour but gain auth support.
+ """
+ from calliope.comfyui.client import ComfyUIClient
+
+ if endpoint is None:
+ endpoint = settings.resolve_comfyui_endpoint(None)
+ if endpoint is None:
+ return ComfyUIClient()
+ return ComfyUIClient(
+ str(endpoint.get("base_url") or ""),
+ headers=build_auth_headers(endpoint),
+ )
diff --git a/calliope-backend/src/calliope/config.py b/calliope-backend/src/calliope/config.py
index efd82cc9..66c84038 100644
--- a/calliope-backend/src/calliope/config.py
+++ b/calliope-backend/src/calliope/config.py
@@ -132,6 +132,13 @@ class Settings(BaseSettings):
comfyui_base_url: str = "http://127.0.0.1:8188"
# Comfy is HTTP-only (upload / prompt / history / view). No local input/output dirs.
+ # Named ComfyUI endpoints (multi-connection, HEL-611). `comfyui_base_url`
+ # above keeps mirroring the ACTIVE endpoint so legacy readers (worker
+ # fallback, tests) keep working — same pattern as llm_* vs llm_profiles.
+ # Each endpoint: {id, name, base_url, auth_type: none|bearer|header,
+ # auth_token, header_name, notes}. auth_token stays server-side only.
+ comfyui_endpoints: list[dict[str, Any]] = Field(default_factory=list)
+ comfyui_active_id: str | None = None
queue_concurrency: int = 1
queue_poll_interval_sec: float = 2.0
@@ -317,6 +324,167 @@ class Settings(BaseSettings):
break
self.apply_active_llm()
+ # ------------------------------------------------------------------
+ # ComfyUI multi-connection endpoints (HEL-611). Mirrors the LLM profile
+ # pattern: list + active id + secret-preserving replace + masked public
+ # view. `comfyui_base_url` always mirrors the active endpoint so legacy
+ # single-address readers keep working.
+ # ------------------------------------------------------------------
+ @staticmethod
+ def _normalize_comfy_endpoint(raw: dict[str, Any]) -> dict[str, Any] | None:
+ if not isinstance(raw, dict):
+ return None
+ base_url = str(raw.get("base_url") or "").strip().rstrip("/")
+ if not base_url:
+ return None
+ auth_type = str(raw.get("auth_type") or "none")
+ if auth_type not in ("none", "bearer", "header"):
+ auth_type = "none"
+ token = raw.get("auth_token")
+ if not isinstance(token, str) or not token.strip():
+ token = None
+ header_name = str(raw.get("header_name") or "").strip() or None
+ return {
+ "id": str(raw.get("id") or uuid.uuid4()),
+ "name": str(raw.get("name") or "").strip() or base_url,
+ "base_url": base_url,
+ "auth_type": auth_type,
+ "auth_token": token,
+ "header_name": header_name,
+ "notes": str(raw.get("notes") or "").strip() or None,
+ }
+
+ def ensure_comfyui_endpoints(self) -> bool:
+ """Guarantee at least one endpoint and base_url mirroring the active.
+
+ Returns True when the list was created or repaired (caller persists).
+ Existing configs with only comfyui_base_url migrate into one endpoint.
+ """
+ migrated = False
+ raw_list = self.comfyui_endpoints if isinstance(self.comfyui_endpoints, list) else []
+ normalized: list[dict[str, Any]] = []
+ for item in raw_list:
+ ep = self._normalize_comfy_endpoint(item)
+ if ep is not None:
+ normalized.append(ep)
+ if not normalized:
+ legacy = (self.comfyui_base_url or "http://127.0.0.1:8188").strip().rstrip("/")
+ pid = str(uuid.uuid4())
+ self.comfyui_endpoints = [
+ {
+ "id": pid,
+ "name": "本机 ComfyUI" if self._is_local_url(legacy) else legacy,
+ "base_url": legacy,
+ "auth_type": "none",
+ "auth_token": None,
+ "header_name": None,
+ "notes": None,
+ }
+ ]
+ self.comfyui_active_id = pid
+ migrated = True
+ else:
+ self.comfyui_endpoints = normalized
+ ids = {ep["id"] for ep in normalized}
+ if self.comfyui_active_id not in ids:
+ self.comfyui_active_id = normalized[0]["id"]
+ migrated = True
+ self.apply_active_comfyui()
+ return migrated
+
+ @staticmethod
+ def _is_local_url(url: str) -> bool:
+ host = url.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0].lower()
+ return host in ("localhost", "127.0.0.1", "::1")
+
+ def apply_active_comfyui(self) -> None:
+ """Mirror the active endpoint onto comfyui_base_url (legacy field)."""
+ endpoints = self.comfyui_endpoints if isinstance(self.comfyui_endpoints, list) else []
+ endpoint = next(
+ (ep for ep in endpoints if ep.get("id") == self.comfyui_active_id), None
+ )
+ if endpoint is None and endpoints:
+ endpoint = endpoints[0]
+ self.comfyui_active_id = str(endpoint.get("id") or "")
+ if endpoint is None:
+ return
+ if endpoint.get("base_url"):
+ self.comfyui_base_url = str(endpoint["base_url"])
+
+ def replace_comfyui_endpoints(self, incoming: list[dict[str, Any]]) -> None:
+ """Replace the endpoint list, preserving tokens unless a new one is sent."""
+ existing = {
+ str(ep["id"]): ep
+ for ep in (self.comfyui_endpoints or [])
+ if isinstance(ep, dict) and ep.get("id")
+ }
+ new_list: list[dict[str, Any]] = []
+ for raw in incoming:
+ if not isinstance(raw, dict):
+ continue
+ pid = str(raw["id"]) if raw.get("id") else str(uuid.uuid4())
+ old = existing.get(pid, {})
+ merged = {**old, **raw, "id": pid}
+ # Blank token on edit = keep the stored one (never echoed back).
+ incoming_token = raw.get("auth_token")
+ if not (isinstance(incoming_token, str) and incoming_token.strip()):
+ merged["auth_token"] = old.get("auth_token")
+ ep = self._normalize_comfy_endpoint(merged)
+ if ep is not None:
+ new_list.append(ep)
+ if not new_list:
+ raise ValueError("至少需要一个 ComfyUI 连接")
+ self.comfyui_endpoints = new_list
+ ids = {ep["id"] for ep in new_list}
+ if self.comfyui_active_id not in ids:
+ self.comfyui_active_id = new_list[0]["id"]
+ self.apply_active_comfyui()
+
+ def sync_legacy_comfyui_into_active(self) -> None:
+ """Write a legacy comfyui_base_url PATCH onto the active endpoint."""
+ base_url = (self.comfyui_base_url or "").strip().rstrip("/")
+ self.ensure_comfyui_endpoints()
+ for ep in self.comfyui_endpoints:
+ if ep.get("id") == self.comfyui_active_id:
+ if base_url:
+ ep["base_url"] = base_url
+ if not str(ep.get("name") or "").strip():
+ ep["name"] = base_url
+ break
+ self.apply_active_comfyui()
+
+ def resolve_comfyui_endpoint(self, endpoint_id: str | None = None) -> dict[str, Any] | None:
+ """Full endpoint dict (token included) for an id; None id or a dangling
+ id falls back to the active endpoint. Server-side use only."""
+ self.ensure_comfyui_endpoints()
+ endpoints = self.comfyui_endpoints
+ if endpoint_id:
+ for ep in endpoints:
+ if ep.get("id") == endpoint_id:
+ return ep
+ return next((ep for ep in endpoints if ep.get("id") == self.comfyui_active_id), None) or (
+ endpoints[0] if endpoints else None
+ )
+
+ def _public_comfyui_endpoints(self) -> list[dict[str, Any]]:
+ self.ensure_comfyui_endpoints()
+ out: list[dict[str, Any]] = []
+ for ep in self.comfyui_endpoints:
+ token = ep.get("auth_token") if isinstance(ep.get("auth_token"), str) else None
+ out.append(
+ {
+ "id": ep["id"],
+ "name": ep["name"],
+ "base_url": ep["base_url"],
+ "auth_type": ep.get("auth_type") or "none",
+ "header_name": ep.get("header_name"),
+ "notes": ep.get("notes"),
+ "has_token": bool(token),
+ "token_tail": (token or "")[-4:] or None,
+ }
+ )
+ return out
+
def _public_llm_profiles(self) -> list[dict[str, Any]]:
self.ensure_llm_profiles()
return [
@@ -350,6 +518,8 @@ class Settings(BaseSettings):
"llm_active_id": self.llm_active_id,
"agent_llm_assignments": dict(self.agent_llm_assignments or {}),
"comfyui_base_url": self.comfyui_base_url,
+ "comfyui_endpoints": self._public_comfyui_endpoints(),
+ "comfyui_active_id": self.comfyui_active_id,
"queue_concurrency": self.queue_concurrency,
"queue_poll_interval_sec": self.queue_poll_interval_sec,
"queue_poll_timeout_sec": self.queue_poll_timeout_sec,
@@ -408,6 +578,10 @@ class Settings(BaseSettings):
self.dry_run = bool(data.get("dry_run", False))
self.ensure_storage_dirs()
profiles_migrated = self.ensure_llm_profiles()
+ comfy_migrated = self.ensure_comfyui_endpoints()
+ if comfy_migrated:
+ # Legacy single-address config: persist the migrated endpoint list.
+ self.save_config_file()
# Auto-heal poisoned config (temp paths / quoted dirs / legacy comfy dirs) back to disk
needs_rewrite = is_ephemeral_path(normalize_path(data.get("data_dir"))) or any(
@@ -445,6 +619,8 @@ class Settings(BaseSettings):
"llm_active_id": self.llm_active_id,
"agent_llm_assignments": dict(self.agent_llm_assignments or {}),
"comfyui_base_url": self.comfyui_base_url,
+ "comfyui_endpoints": self.comfyui_endpoints,
+ "comfyui_active_id": self.comfyui_active_id,
"queue_concurrency": self.queue_concurrency,
"queue_poll_interval_sec": self.queue_poll_interval_sec,
"queue_poll_timeout_sec": self.queue_poll_timeout_sec,
diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py
index 43978324..56dbe8ec 100644
--- a/calliope-backend/src/calliope/db.py
+++ b/calliope-backend/src/calliope/db.py
@@ -319,6 +319,11 @@ async def migrate_db(db_path: Path) -> None:
conn.execute(
"ALTER TABLE workflows ADD COLUMN prompt_profile TEXT NOT NULL DEFAULT 'prose'"
)
+ if "endpoint_id" not in cols:
+ # HEL-611: optional binding to a ComfyUI connection (settings'
+ # comfyui_endpoints id). Dangling ids are tolerated — enqueue falls
+ # back to the active connection.
+ conn.execute("ALTER TABLE workflows ADD COLUMN endpoint_id TEXT")
scene_cols = {r[1] for r in conn.execute("PRAGMA table_info(scenes)").fetchall()}
if "location_id" not in scene_cols:
conn.execute("ALTER TABLE scenes ADD COLUMN location_id INTEGER")
diff --git a/calliope-backend/src/calliope/main.py b/calliope-backend/src/calliope/main.py
index fa0fdee3..b569df0f 100644
--- a/calliope-backend/src/calliope/main.py
+++ b/calliope-backend/src/calliope/main.py
@@ -20,6 +20,7 @@ from calliope.routers import (
agent,
assets,
canvas,
+ comfyui as comfy,
events,
jobs,
library,
@@ -135,6 +136,7 @@ def create_app(static_dir: Path | None = None) -> FastAPI:
app.include_router(workflows.router, prefix="/api/workflows", tags=["workflows"])
app.include_router(jobs.router, prefix="/api/jobs", tags=["jobs"])
app.include_router(playground.router, prefix="/api/playground", tags=["playground"])
+ app.include_router(comfy.router, prefix="/api/comfyui", tags=["comfyui"])
app.include_router(library.router, prefix="/api/library", tags=["library"])
app.include_router(canvas.router, prefix="/api/canvas", tags=["canvas"])
app.include_router(shots.router, prefix="/api/shots", tags=["shots"])
diff --git a/calliope-backend/src/calliope/models/schemas.py b/calliope-backend/src/calliope/models/schemas.py
index ec85e371..dc96dfe1 100644
--- a/calliope-backend/src/calliope/models/schemas.py
+++ b/calliope-backend/src/calliope/models/schemas.py
@@ -200,6 +200,8 @@ class WorkflowCreate(BaseModel):
workflow_json: dict[str, Any]
description: str | None = None
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
+ # Optional binding to a ComfyUI connection id (settings.comfyui_endpoints).
+ endpoint_id: str | None = None
class WorkflowUpdate(BaseModel):
@@ -208,6 +210,7 @@ class WorkflowUpdate(BaseModel):
description: str | None = None
prompt_profile: Literal["prose", "minimax_h3_ref"] | None = None
is_enabled: bool | None = None
+ endpoint_id: str | None = None
class WorkflowAnalyze(BaseModel):
diff --git a/calliope-backend/src/calliope/queue/manager.py b/calliope-backend/src/calliope/queue/manager.py
index eea7d645..1d0eb4b7 100644
--- a/calliope-backend/src/calliope/queue/manager.py
+++ b/calliope-backend/src/calliope/queue/manager.py
@@ -38,12 +38,13 @@ class QueueManager:
) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
+ payload = self._stamp_endpoint(conn, workflow_id, dict(payload or {}))
cur = conn.execute(
"""
INSERT INTO jobs (project_id, scene_id, clip_id, kind, workflow_id, status, payload_json)
VALUES (?, ?, ?, ?, ?, 'pending', ?)
""",
- (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload or {})),
+ (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload)),
)
conn.commit()
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone()
@@ -51,6 +52,35 @@ class QueueManager:
finally:
conn.close()
+ @staticmethod
+ def _stamp_endpoint(
+ conn, workflow_id: int | None, payload: dict[str, Any]
+ ) -> dict[str, Any]:
+ """Snapshot the target ComfyUI connection into the job payload (HEL-611).
+
+ Every generation path (flow video/assets, playground, agent tools)
+ funnels through here, so they all share one execution route.
+ Priority: an explicit payload ``endpoint_id`` → the workflow's
+ bound connection → the active connection. The snapshot carries
+ id/name/base_url only — the token is resolved server-side by
+ the worker at run time.
+ """
+ from calliope.comfyui.endpoints import endpoint_snapshot
+
+ if payload.get("endpoint"):
+ return payload
+ endpoint_id = payload.get("endpoint_id")
+ if not endpoint_id and workflow_id:
+ try:
+ row = conn.execute(
+ "SELECT endpoint_id FROM workflows WHERE id = ?", (workflow_id,)
+ ).fetchone()
+ endpoint_id = row["endpoint_id"] if row else None
+ except Exception:
+ endpoint_id = None # pre-migration DB: column may be missing
+ payload["endpoint"] = endpoint_snapshot(endpoint_id)
+ return payload
+
def claim_next(self) -> dict[str, Any] | None:
if self.paused:
return None
diff --git a/calliope-backend/src/calliope/queue/worker.py b/calliope-backend/src/calliope/queue/worker.py
index f5a1e672..746c0f29 100644
--- a/calliope-backend/src/calliope/queue/worker.py
+++ b/calliope-backend/src/calliope/queue/worker.py
@@ -151,7 +151,8 @@ class QueueWorker:
# and dry-run writes an mp4 placeholder (not the default PNG).
return await run_export(job, payload, event_bus, dry_run=use_dry)
- client = ComfyUIClient(config.settings.comfyui_base_url)
+ base_url, headers, endpoint_label = self._resolve_endpoint(payload)
+ client = ComfyUIClient(base_url, headers=headers)
try:
if use_dry:
return await self._dry_run(job, payload)
@@ -159,8 +160,8 @@ class QueueWorker:
healthy = await client.health()
if not healthy:
raise RuntimeError(
- f"ComfyUI unreachable at {config.settings.comfyui_base_url}. "
- "Start ComfyUI, or enable Dry-run in Settings only for placeholder testing."
+ f"ComfyUI 不可达({endpoint_label})。请在「ComfyUI 连接」页测试并修正该连接,"
+ "或在设置中开启 Dry-run 做占位测试。"
)
workflow_id = job.get("workflow_id") or payload.get("workflow_id")
@@ -208,6 +209,37 @@ class QueueWorker:
finally:
await client.close()
+ @staticmethod
+ def _resolve_endpoint(payload: dict[str, Any]) -> tuple[str, dict[str, str], str]:
+ """Pick the ComfyUI address for THIS job (HEL-611).
+
+ Priority: the payload's endpoint snapshot id, still present in
+ config (fresh URL + token win) → the snapshot's URL when the id was
+ deleted (token lost — history still explains the address) → the
+ active connection (snapshots from before multi-connection, or jobs
+ enqueued without one).
+ """
+ from calliope.comfyui.endpoints import build_auth_headers
+
+ snapshot = payload.get("endpoint") or {}
+ if isinstance(snapshot, dict) and snapshot.get("id"):
+ endpoint = config.settings.resolve_comfyui_endpoint(str(snapshot["id"]))
+ if endpoint is not None and endpoint.get("id") == snapshot.get("id"):
+ base_url = str(endpoint.get("base_url") or "")
+ label = f"{endpoint.get('name') or '连接'} · {base_url}"
+ return base_url, build_auth_headers(endpoint), label
+ if isinstance(snapshot, dict) and snapshot.get("base_url"):
+ # Dangling id: run against the snapshotted address, no token.
+ base_url = str(snapshot["base_url"])
+ label = f"{snapshot.get('name') or '已删除连接'} · {base_url}"
+ return base_url, {}, label
+ endpoint = config.settings.resolve_comfyui_endpoint(None)
+ if endpoint is None:
+ raise RuntimeError("没有可用的 ComfyUI 连接:请到「ComfyUI 连接」页添加。")
+ base_url = str(endpoint.get("base_url") or "")
+ label = f"{endpoint.get('name') or '默认连接'} · {base_url}"
+ return base_url, build_auth_headers(endpoint), label
+
async def _resolve_continue_source(
self,
job: dict[str, Any],
diff --git a/calliope-backend/src/calliope/routers/comfyui.py b/calliope-backend/src/calliope/routers/comfyui.py
new file mode 100644
index 00000000..21e0727c
--- /dev/null
+++ b/calliope-backend/src/calliope/routers/comfyui.py
@@ -0,0 +1,360 @@
+"""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 地址不能为空")
+ if "://" not in url:
+ url = f"http://{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)
+ 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)
+ 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 {}),
+ }
diff --git a/calliope-backend/src/calliope/routers/jobs.py b/calliope-backend/src/calliope/routers/jobs.py
index 646a01a3..dea85b16 100644
--- a/calliope-backend/src/calliope/routers/jobs.py
+++ b/calliope-backend/src/calliope/routers/jobs.py
@@ -6,7 +6,6 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query
from calliope.agent.video_agent import enqueue_video_jobs, preview_clip_prompt
-from calliope.comfyui.client import ComfyUIClient
from calliope.config import settings
from calliope.db import get_db
from calliope.events.bus import event_bus
@@ -191,7 +190,18 @@ async def cancel_job(job_id: int) -> dict[str, Any]:
# Export runs local ffmpeg, not Comfy — kill the process instead.
kill_running(job_id)
else:
- client = ComfyUIClient()
+ # Interrupt on the endpoint this job actually runs against (payload
+ # snapshot; falls back to the active connection).
+ from calliope.comfyui.endpoints import client_for
+
+ try:
+ snapshot = (json.loads(job.get("payload_json") or "{}") or {}).get("endpoint")
+ except json.JSONDecodeError:
+ snapshot = None
+ endpoint = None
+ if isinstance(snapshot, dict) and snapshot.get("id"):
+ endpoint = settings.resolve_comfyui_endpoint(str(snapshot["id"]))
+ client = client_for(endpoint)
try:
await client.interrupt()
finally:
diff --git a/calliope-backend/src/calliope/routers/playground.py b/calliope-backend/src/calliope/routers/playground.py
index be9ae971..4276a282 100644
--- a/calliope-backend/src/calliope/routers/playground.py
+++ b/calliope-backend/src/calliope/routers/playground.py
@@ -26,6 +26,9 @@ PLAYGROUND_TITLE = "Playground Scratch"
class PlaygroundGenerate(BaseModel):
workflow_id: int
input_values: dict[str, Any] = Field(default_factory=dict)
+ # Optional target connection; omitted → the workflow's bound connection,
+ # then the active one (resolved in queue_manager.enqueue).
+ endpoint_id: str | None = None
class PlaygroundAttach(BaseModel):
@@ -339,7 +342,11 @@ async def generate(payload: PlaygroundGenerate) -> dict[str, Any]:
kind=kind,
workflow_id=payload.workflow_id,
scene_id=None,
- payload={"input_values": payload.input_values, "source": "playground"},
+ payload={
+ "input_values": payload.input_values,
+ "source": "playground",
+ **({"endpoint_id": payload.endpoint_id} if payload.endpoint_id else {}),
+ },
)
await event_bus.publish(
"job.created",
diff --git a/calliope-backend/src/calliope/routers/settings.py b/calliope-backend/src/calliope/routers/settings.py
index 242faded..6a892ec2 100644
--- a/calliope-backend/src/calliope/routers/settings.py
+++ b/calliope-backend/src/calliope/routers/settings.py
@@ -45,6 +45,7 @@ class SettingsUpdate(BaseModel):
llm_active_id: str | None = None
agent_llm_assignments: dict[str, str | None] | None = None
comfyui_base_url: str | None = None
+ comfyui_active_id: str | None = None
data_dir: str | None = None
assets_dir: str | None = None
agent_workspace_dir: str | None = None
@@ -72,6 +73,8 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
active_in = data.pop("llm_active_id", None)
assignments_in = data.pop("agent_llm_assignments", None)
legacy_llm = {k: data.pop(k) for k in list(data) if k in _LEGACY_LLM_KEYS}
+ active_comfy_in = data.pop("comfyui_active_id", None)
+ legacy_comfy_url = data.pop("comfyui_base_url", None)
for key, value in data.items():
if key in {"data_dir", "assets_dir", "agent_workspace_dir"}:
@@ -121,6 +124,20 @@ async def update_settings(payload: SettingsUpdate) -> dict[str, Any]:
setattr(settings, key, value)
settings.sync_legacy_llm_into_active()
+ if active_comfy_in is not None:
+ settings.ensure_comfyui_endpoints()
+ ids = {ep["id"] for ep in settings.comfyui_endpoints}
+ if active_comfy_in not in ids:
+ raise HTTPException(status_code=400, detail="Unknown ComfyUI endpoint")
+ settings.comfyui_active_id = active_comfy_in
+ settings.apply_active_comfyui()
+
+ if legacy_comfy_url is not None:
+ # Legacy single-address PATCH (old Settings page): write it onto the
+ # active endpoint so the two views never diverge (HEL-611).
+ setattr(settings, "comfyui_base_url", legacy_comfy_url)
+ settings.sync_legacy_comfyui_into_active()
+
settings.save_config_file()
return settings.to_public_dict()
diff --git a/calliope-backend/src/calliope/routers/workflows.py b/calliope-backend/src/calliope/routers/workflows.py
index 2b61cf31..f05c3a1c 100644
--- a/calliope-backend/src/calliope/routers/workflows.py
+++ b/calliope-backend/src/calliope/routers/workflows.py
@@ -129,8 +129,9 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema,
- output_schema, description, prompt_profile, is_enabled)
- VALUES (?, ?, ?, ?, ?, ?, ?, 1)
+ output_schema, description, prompt_profile,
+ endpoint_id, is_enabled)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
""",
(
payload.name,
@@ -140,6 +141,7 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
json.dumps(outputs),
payload.description,
profile,
+ payload.endpoint_id,
),
)
conn.commit()
@@ -171,7 +173,9 @@ async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str
data = payload.model_dump(exclude_unset=True)
if "is_enabled" in data and data["is_enabled"] is not None:
data["is_enabled"] = 1 if data["is_enabled"] else 0
- data = {k: v for k, v in data.items() if v is not None}
+ # endpoint_id: explicit null clears the binding; other Nones are skips.
+ explicit_null = {"endpoint_id"} & {k for k, v in data.items() if v is None}
+ data = {k: v for k, v in data.items() if v is not None or k in explicit_null}
if data:
fields = ", ".join(f"{k} = :{k}" for k in data)
data["id"] = workflow_id
diff --git a/calliope-backend/tests/test_comfyui_endpoints.py b/calliope-backend/tests/test_comfyui_endpoints.py
new file mode 100644
index 00000000..14a4d9b7
--- /dev/null
+++ b/calliope-backend/tests/test_comfyui_endpoints.py
@@ -0,0 +1,558 @@
+"""ComfyUI multi-connection endpoints (HEL-611): CRUD, masking, migration,
+server-side connectivity test classification, workflow binding and job
+endpoint snapshots."""
+
+from __future__ import annotations
+
+import json
+import socket
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+import pytest
+
+from calliope.config import settings
+
+
+class _FakeComfyHandler(BaseHTTPRequestHandler):
+ server_version = "FakeComfy/1.0"
+
+ def do_GET(self):
+ self.server.requests.append({"path": self.path, "headers": dict(self.headers)})
+ if self.path == "/system_stats":
+ if self.server.require_auth and not self._auth_ok():
+ self._send(401, {"error": "unauthorized"})
+ return
+ if self.server.mode == "not_comfyui_json":
+ self._send(200, {"hello": "world"})
+ return
+ if self.server.mode == "html":
+ self._send_html(200, "
hi")
+ return
+ self._send(
+ 200,
+ {
+ "system": {"comfyui_version": "0.3.55-test", "os": "linux"},
+ "devices": [{"name": "FakeGPU RTX 5090", "type": "cuda"}],
+ },
+ )
+ return
+ if self.path == "/":
+ self._send_html(200, "")
+ return
+ if self.server.mode == "system_stats_404":
+ # reverse-proxy style: /system_stats stripped
+ self._send_html(404, "404")
+ return
+ self._send(404, {"error": "not found"})
+
+ def _auth_ok(self) -> bool:
+ auth = self.headers.get("Authorization") or ""
+ if auth == f"Bearer {self.server.token}":
+ return True
+ if self.headers.get(self.server.header_name or "X-Api-Key") == self.server.token:
+ return True
+ return False
+
+ def _send(self, status: int, payload: dict) -> None:
+ data = json.dumps(payload).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def _send_html(self, status: int, text: str) -> None:
+ data = text.encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "text/html")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def log_message(self, format, *args):
+ pass
+
+
+@pytest.fixture
+def fake_comfy():
+ server = ThreadingHTTPServer(("127.0.0.1", 0), _FakeComfyHandler)
+ server.requests = []
+ server.require_auth = False
+ server.token = "tok-1234"
+ server.header_name = "X-Api-Key"
+ server.mode = "ok"
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield server
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def _url(server) -> str:
+ return f"http://127.0.0.1:{server.server_address[1]}"
+
+
+def _snapshot_settings():
+ return {
+ "comfyui_endpoints": [dict(ep) for ep in (settings.comfyui_endpoints or [])],
+ "comfyui_active_id": settings.comfyui_active_id,
+ "comfyui_base_url": settings.comfyui_base_url,
+ }
+
+
+def _clear_endpoints() -> None:
+ """Start from an empty endpoint list (settings is a process singleton)."""
+ settings.comfyui_endpoints = []
+ settings.comfyui_active_id = None
+
+
+def _reset_endpoints(**kw) -> dict:
+ """Point settings at one fresh endpoint and return it."""
+ base = {
+ "id": "ep-11111111-1111-1111-1111-111111111111",
+ "name": "测试连接",
+ "base_url": "http://127.0.0.1:8188",
+ "auth_type": "none",
+ "auth_token": None,
+ "header_name": None,
+ "notes": None,
+ }
+ base.update(kw)
+ settings.comfyui_endpoints = [base]
+ settings.comfyui_active_id = base["id"]
+ settings.apply_active_comfyui()
+ return base
+
+
+# ----------------------------------------------------------------------
+# CRUD + masking
+# ----------------------------------------------------------------------
+
+
+def test_endpoints_crud_and_masking(client):
+ prev = _snapshot_settings()
+ try:
+ _clear_endpoints()
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={
+ "name": "本机",
+ "base_url": "http://127.0.0.1:8188",
+ "auth_type": "bearer",
+ "auth_token": "secret-tok-9999",
+ },
+ )
+ assert r.status_code == 200
+ body = r.json()
+ assert len(body["endpoints"]) == 1
+ ep = body["endpoints"][0]
+ assert ep["has_token"] is True
+ assert ep["token_tail"] == "9999"
+ assert "secret" not in r.text # token never echoed
+ eid = ep["id"]
+
+ # edit: blank token keeps the stored one
+ r = client.patch(
+ f"/api/comfyui/endpoints/{eid}",
+ json={"name": "本机改名", "base_url": "http://127.0.0.1:8189"},
+ )
+ assert r.status_code == 200
+ ep = r.json()["endpoints"][0]
+ assert ep["name"] == "本机改名"
+ assert ep["base_url"].endswith("8189")
+ assert ep["has_token"] is True
+
+ # comfyui_base_url mirrors the ACTIVE endpoint
+ assert settings.comfyui_base_url.endswith("8189")
+
+ # delete last endpoint is refused
+ r = client.delete(f"/api/comfyui/endpoints/{eid}")
+ assert r.status_code == 400
+
+ # add a second, delete the first: allowed, active falls back
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={"name": "局域网", "base_url": "http://192.168.200.15:8188"},
+ )
+ assert r.status_code == 200
+ second_id = r.json()["endpoints"][-1]["id"]
+ r = client.delete(f"/api/comfyui/endpoints/{eid}")
+ assert r.status_code == 200
+ assert r.json()["active_id"] == second_id
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_activate_endpoint(client):
+ prev = _snapshot_settings()
+ try:
+ _clear_endpoints()
+ r = client.post("/api/comfyui/endpoints", json={"name": "A", "base_url": "http://a.test:8188"})
+ assert r.status_code == 200
+ r = client.post("/api/comfyui/endpoints", json={"name": "B", "base_url": "http://b.test:8188"})
+ assert r.status_code == 200
+ id_b = r.json()["endpoints"][-1]["id"]
+
+ r = client.post(f"/api/comfyui/endpoints/{id_b}/activate")
+ assert r.status_code == 200
+ assert r.json()["active_id"] == id_b
+ assert settings.comfyui_base_url == "http://b.test:8188"
+
+ # legacy single-address PATCH writes onto the ACTIVE endpoint
+ r = client.post("/api/settings", json={"comfyui_base_url": "http://b2.test:8188"})
+ assert r.status_code == 200
+ assert settings.comfyui_base_url == "http://b2.test:8188"
+ stored_b = next(ep for ep in settings.comfyui_endpoints if ep["id"] == id_b)
+ assert stored_b["base_url"] == "http://b2.test:8188"
+
+ r = client.post("/api/comfyui/endpoints/does-not-exist/activate")
+ assert r.status_code == 404
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_legacy_base_url_migrates_into_endpoint():
+ prev = _snapshot_settings()
+ try:
+ settings.comfyui_endpoints = []
+ settings.comfyui_active_id = None
+ settings.comfyui_base_url = "http://192.168.200.15:8188"
+ migrated = settings.ensure_comfyui_endpoints()
+ assert migrated is True
+ assert len(settings.comfyui_endpoints) == 1
+ ep = settings.comfyui_endpoints[0]
+ assert ep["base_url"] == "http://192.168.200.15:8188"
+ assert settings.comfyui_active_id == ep["id"]
+ # idempotent
+ assert settings.ensure_comfyui_endpoints() is False
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+# ----------------------------------------------------------------------
+# server-side connectivity test
+# ----------------------------------------------------------------------
+
+
+def test_comfy_test_success_with_version_and_latency(client, fake_comfy):
+ r = client.post("/api/comfyui/endpoints/test", json={"base_url": _url(fake_comfy)})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["ok"] is True
+ assert body["comfyui_version"] == "0.3.55-test"
+ assert "FakeGPU" in body["device_name"]
+ assert isinstance(body["elapsed_ms"], int)
+ assert fake_comfy.requests[0]["path"] == "/system_stats"
+
+
+def test_comfy_test_bearer_auth_from_stored_endpoint(client, fake_comfy):
+ prev = _snapshot_settings()
+ fake_comfy.require_auth = True
+ try:
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={
+ "name": "带鉴权",
+ "base_url": _url(fake_comfy),
+ "auth_type": "bearer",
+ "auth_token": "tok-1234",
+ },
+ )
+ eid = r.json()["endpoints"][-1]["id"]
+ # test by id: stored token used server-side, never needs echo
+ r = client.post("/api/comfyui/endpoints/test", json={"endpoint_id": eid})
+ assert r.json()["ok"] is True
+ assert fake_comfy.requests[-1]["headers"].get("Authorization") == "Bearer tok-1234"
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_comfy_test_header_auth(client, fake_comfy):
+ fake_comfy.require_auth = True
+ r = client.post(
+ "/api/comfyui/endpoints/test",
+ json={
+ "base_url": _url(fake_comfy),
+ "auth_type": "header",
+ "header_name": "X-Api-Key",
+ "auth_token": "tok-1234",
+ },
+ )
+ assert r.json()["ok"] is True
+ assert fake_comfy.requests[-1]["headers"].get("X-Api-Key") == "tok-1234"
+
+
+def test_comfy_test_auth_rejected(client, fake_comfy):
+ fake_comfy.require_auth = True
+ r = client.post("/api/comfyui/endpoints/test", json={"base_url": _url(fake_comfy)})
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "auth"
+ assert "鉴权" in body["message"]
+
+
+def test_comfy_test_connection_refused(client):
+ sock = socket.socket()
+ sock.bind(("127.0.0.1", 0))
+ port = sock.getsockname()[1]
+ sock.close()
+ r = client.post("/api/comfyui/endpoints/test", json={"base_url": f"http://127.0.0.1:{port}"})
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "refused"
+ assert "拒绝" in body["message"]
+
+
+def test_comfy_test_timeout(client):
+ # 10.255.255.1 is unroutable on this LAN → connect timeout (2s floor)
+ r = client.post(
+ "/api/comfyui/endpoints/test",
+ json={"base_url": "http://10.255.255.1:8188", "timeout_sec": 2},
+ )
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "timeout"
+ assert "超时" in body["message"]
+
+
+def test_comfy_test_dns_failure(client):
+ r = client.post(
+ "/api/comfyui/endpoints/test",
+ json={"base_url": "http://nonexistent-host-xyz.invalid:8188"},
+ )
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "dns"
+ assert "解析" in body["message"]
+
+
+def test_comfy_test_reachable_but_not_comfyui(client, fake_comfy):
+ fake_comfy.mode = "not_comfyui_json"
+ r = client.post("/api/comfyui/endpoints/test", json={"base_url": _url(fake_comfy)})
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "not_comfyui"
+ assert "不是 ComfyUI" in body["message"] or "不像 ComfyUI" in body["message"]
+
+
+def test_comfy_test_html_response_is_not_comfyui(client, fake_comfy):
+ fake_comfy.mode = "html"
+ r = client.post("/api/comfyui/endpoints/test", json={"base_url": _url(fake_comfy)})
+ body = r.json()
+ assert body["ok"] is False
+ assert body["error"] == "not_comfyui"
+
+
+def test_comfy_test_ssrf_guard(client):
+ r = client.post(
+ "/api/comfyui/endpoints/test",
+ json={"base_url": "http://169.254.169.254/latest/meta-data"},
+ )
+ assert r.status_code == 400
+ assert "禁止" in r.json()["detail"]
+ # loopback IS allowed (local ComfyUI is a legitimate target)
+ r = client.post(
+ "/api/comfyui/endpoints/test",
+ json={"base_url": "http://127.0.0.1:1", "timeout_sec": 2},
+ )
+ assert r.status_code == 200 # runs the probe (refused), not blocked
+
+
+def test_comfy_test_requires_url(client):
+ r = client.post("/api/comfyui/endpoints/test", json={})
+ assert r.status_code == 400
+ r = client.post(
+ "/api/comfyui/endpoints/test", json={"base_url": "ftp://x/", "timeout_sec": 2}
+ )
+ assert r.status_code == 400
+
+
+# ----------------------------------------------------------------------
+# workflow binding + job snapshots
+# ----------------------------------------------------------------------
+
+
+def _import_workflow(client, name="H3 视频", kind="video", endpoint_id=None):
+ wf_json = {
+ "6": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {"text": "placeholder prompt", "clip": ["4", 1]},
+ },
+ }
+ payload = {"name": name, "kind": kind, "workflow_json": wf_json}
+ if endpoint_id is not None:
+ payload["endpoint_id"] = endpoint_id
+ return client.post("/api/workflows", json=payload)
+
+
+def test_workflow_endpoint_binding_roundtrip(client):
+ prev = _snapshot_settings()
+ try:
+ r = client.post(
+ "/api/comfyui/endpoints", json={"name": "局域网机", "base_url": "http://192.168.200.15:8188"}
+ )
+ eid = r.json()["endpoints"][-1]["id"]
+
+ r = _import_workflow(client, endpoint_id=eid)
+ assert r.status_code == 200
+ wf = r.json()
+ assert wf["endpoint_id"] == eid
+
+ # clear binding with explicit null
+ r = client.patch(f"/api/workflows/{wf['id']}", json={"endpoint_id": None})
+ assert r.json()["endpoint_id"] is None
+
+ # rebind
+ r = client.patch(f"/api/workflows/{wf['id']}", json={"endpoint_id": eid})
+ assert r.json()["endpoint_id"] == eid
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_playground_generate_stamps_endpoint_snapshot(client):
+ prev = _snapshot_settings()
+ try:
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={"name": "目标A", "base_url": "http://192.168.200.15:8188"},
+ )
+ target = r.json()["endpoints"][-1]
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={"name": "默认B", "base_url": "http://192.168.200.16:8188"},
+ )
+ default_ep = r.json()["endpoints"][-1]
+ client.post(f"/api/comfyui/endpoints/{default_ep['id']}/activate")
+
+ wf = _import_workflow(client).json()
+
+ # explicit endpoint_id wins
+ r = client.post(
+ "/api/playground/generate",
+ json={"workflow_id": wf["id"], "endpoint_id": target["id"]},
+ )
+ assert r.status_code == 200
+ snap = r.json()["job"]["payload"]["endpoint"]
+ assert snap["id"] == target["id"]
+ assert snap["name"] == "目标A"
+ assert snap["base_url"] == "http://192.168.200.15:8188"
+ assert "auth_token" not in snap # token never snapshots into payloads
+
+ # no explicit id + no binding → active endpoint
+ r = client.post("/api/playground/generate", json={"workflow_id": wf["id"]})
+ snap = r.json()["job"]["payload"]["endpoint"]
+ assert snap["id"] == default_ep["id"]
+
+ # workflow binding wins when no explicit id
+ r = client.patch(f"/api/workflows/{wf['id']}", json={"endpoint_id": target["id"]})
+ r = client.post("/api/playground/generate", json={"workflow_id": wf["id"]})
+ snap = r.json()["job"]["payload"]["endpoint"]
+ assert snap["id"] == target["id"]
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_worker_resolves_endpoint_from_snapshot():
+ from calliope.queue.worker import QueueWorker
+
+ prev = _snapshot_settings()
+ try:
+ ep = _reset_endpoints(
+ id="ep-22222222-2222-2222-2222-222222222222",
+ name="快照机",
+ base_url="http://192.168.200.15:8188",
+ )
+ # snapshot id still configured → current values (fresh URL/token)
+ url, headers, label = QueueWorker._resolve_endpoint(
+ {"endpoint": {"id": ep["id"], "name": "旧名", "base_url": "http://old:1"}}
+ )
+ assert url == "http://192.168.200.15:8188"
+ assert "快照机" in label
+
+ # dangling id → snapshot URL without token
+ url, headers, label = QueueWorker._resolve_endpoint(
+ {"endpoint": {"id": "gone-id", "name": "已删", "base_url": "http://kept:8188"}}
+ )
+ assert url == "http://kept:8188"
+ assert headers == {}
+ assert "已删" in label
+
+ # no snapshot → active endpoint
+ url, _h, label = QueueWorker._resolve_endpoint({})
+ assert url == "http://192.168.200.15:8188"
+
+ # bearer headers built for the active endpoint
+ _reset_endpoints(
+ id="ep-33333333-3333-3333-3333-333333333333",
+ base_url="http://auth.test:8188",
+ auth_type="bearer",
+ auth_token="tok-xyz",
+ )
+ _url2, headers, _label = QueueWorker._resolve_endpoint({})
+ assert headers == {"Authorization": "Bearer tok-xyz"}
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_queue_enqueue_stamps_all_paths(client):
+ """Flow-internal video enqueue also carries the snapshot (same path)."""
+ prev = _snapshot_settings()
+ try:
+ r = client.post(
+ "/api/comfyui/endpoints", json={"name": "流程机", "base_url": "http://192.168.200.15:8188"}
+ )
+ eid = r.json()["endpoints"][-1]["id"]
+ wf = _import_workflow(client, endpoint_id=eid).json()
+
+ # enqueue via queue_manager directly (what enqueue_video_jobs calls)
+ from calliope.queue.manager import queue_manager
+
+ project = client.post(
+ "/api/projects", json={"title": "连接快照测试", "idea": "x"}
+ ).json()
+ job = queue_manager.enqueue(
+ project_id=project["id"], kind="video", workflow_id=wf["id"], payload={}
+ )
+ payload = json.loads(job["payload_json"])
+ assert payload["endpoint"]["id"] == eid
+ assert payload["endpoint"]["base_url"] == "http://192.168.200.15:8188"
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
+
+
+def test_settings_public_dict_masks_endpoint_tokens(client):
+ prev = _snapshot_settings()
+ try:
+ r = client.post(
+ "/api/comfyui/endpoints",
+ json={
+ "name": "云端",
+ "base_url": "https://comfy.example.com",
+ "auth_type": "header",
+ "header_name": "X-Key",
+ "auth_token": "cloud-secret-7777",
+ },
+ )
+ assert r.status_code == 200
+ r = client.get("/api/settings")
+ text = r.text
+ assert "cloud-secret" not in text
+ ep = next(
+ ep for ep in r.json()["comfyui_endpoints"] if ep["name"] == "云端"
+ )
+ assert ep["has_token"] is True
+ assert ep["token_tail"] == "7777"
+ finally:
+ for key, value in prev.items():
+ setattr(settings, key, value)
diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts
index 18458552..40999e9c 100644
--- a/calliope-web/src/lib/api.ts
+++ b/calliope-web/src/lib/api.ts
@@ -85,6 +85,17 @@ export interface LlmProfile {
api_key_tail?: string | null;
}
+export interface ComfyEndpoint {
+ id: string;
+ name: string;
+ base_url: string;
+ auth_type: 'none' | 'bearer' | 'header';
+ header_name: string | null;
+ notes: string | null;
+ has_token: boolean;
+ token_tail?: string | null;
+}
+
export interface Settings {
host: string;
port: number;
@@ -98,6 +109,8 @@ export interface Settings {
llm_profiles: LlmProfile[];
llm_active_id: string | null;
comfyui_base_url: string;
+ comfyui_endpoints: ComfyEndpoint[];
+ comfyui_active_id: string | null;
queue_concurrency: number;
queue_poll_interval_sec: number;
queue_poll_timeout_sec: number;
@@ -288,6 +301,51 @@ export const settings = {
}),
};
+export const comfy = {
+ listEndpoints: () =>
+ api<{ endpoints: ComfyEndpoint[]; active_id: string | null }>('/api/comfyui/endpoints'),
+ createEndpoint: (payload: Partial & { base_url: string; auth_token?: string }) =>
+ api<{ endpoints: ComfyEndpoint[]; active_id: string | null }>('/api/comfyui/endpoints', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
+ updateEndpoint: (id: string, payload: Partial & { auth_token?: string }) =>
+ api<{ endpoints: ComfyEndpoint[]; active_id: string | null }>(`/api/comfyui/endpoints/${id}`, {
+ method: 'PATCH',
+ body: JSON.stringify(payload),
+ }),
+ deleteEndpoint: (id: string) =>
+ api<{ endpoints: ComfyEndpoint[]; active_id: string | null }>(`/api/comfyui/endpoints/${id}`, {
+ method: 'DELETE',
+ }),
+ activateEndpoint: (id: string) =>
+ api<{ endpoints: ComfyEndpoint[]; active_id: string | null }>(
+ `/api/comfyui/endpoints/${id}/activate`,
+ { method: 'POST' },
+ ),
+ testEndpoint: (payload: {
+ endpoint_id?: string;
+ base_url?: string;
+ auth_type?: string;
+ auth_token?: string;
+ header_name?: string;
+ timeout_sec?: number;
+ }) =>
+ api<{
+ ok: boolean;
+ elapsed_ms?: number;
+ comfyui_version?: string;
+ device_name?: string;
+ error?: string;
+ message?: string;
+ detail?: string;
+ timeout_sec?: number;
+ }>('/api/comfyui/endpoints/test', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
+};
+
export const workflows = {
list: () => api('/api/workflows'),
analyze: (workflow_json: Record) =>
@@ -307,6 +365,7 @@ export const workflows = {
workflow_json: Record;
description?: string;
prompt_profile?: string;
+ endpoint_id?: string | null;
}) => api('/api/workflows', { method: 'POST', body: JSON.stringify(payload) }),
update: (
id: number,
@@ -316,6 +375,7 @@ export const workflows = {
is_enabled: boolean;
description: string;
prompt_profile: string;
+ endpoint_id: string | null;
}>,
) => api(`/api/workflows/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
delete: (id: number) => api<{ ok: boolean }>(`/api/workflows/${id}`, { method: 'DELETE' }),
diff --git a/calliope-web/src/lib/comfy/types.ts b/calliope-web/src/lib/comfy/types.ts
index 5518e91c..a8ef557d 100644
--- a/calliope-web/src/lib/comfy/types.ts
+++ b/calliope-web/src/lib/comfy/types.ts
@@ -35,6 +35,8 @@ export interface Workflow {
description: string | null;
prompt_profile: string;
is_enabled: boolean;
+ /** Bound ComfyUI connection id (settings.comfyui_endpoints); null = active. */
+ endpoint_id?: string | null;
}
export interface Job {
diff --git a/calliope-web/src/lib/components/shell/AppShell.svelte b/calliope-web/src/lib/components/shell/AppShell.svelte
index 0337dc67..b8ab4613 100644
--- a/calliope-web/src/lib/components/shell/AppShell.svelte
+++ b/calliope-web/src/lib/components/shell/AppShell.svelte
@@ -43,7 +43,7 @@
{ id: 'video', labelKey: 'shell.navVideo', icon: 'film', wip: true },
{ id: 'tasks', labelKey: 'shell.navTasks', icon: 'queue', wip: true },
{ id: 'agents', labelKey: 'shell.navAgents', icon: 'sparkle', href: '/agents' },
- { id: 'connections', labelKey: 'shell.navConnections', icon: 'link', wip: true },
+ { id: 'connections', labelKey: 'shell.navConnections', icon: 'link', href: '/connections' },
{ id: 'models', labelKey: 'shell.navModels', icon: 'assets', href: '/models' },
{ id: 'settings', labelKey: 'shell.navSettings', icon: 'settings', href: '/settings' },
];
@@ -59,16 +59,25 @@
let { active, title, subtitle, actions, children }: Props = $props();
- // Real ComfyUI address from settings — shown honestly without a fake
- // "connected" claim; the standalone connections page is not built yet.
+ // Real ComfyUI connections from settings — shown honestly without a
+ // fake "connected" claim; tested state lives on /connections (a6).
const settingsQuery = createQuery({
queryKey: ['settings'],
queryFn: settings.get,
staleTime: 60_000,
});
+ // The ACTIVE ComfyUI connection from settings (HEL-611). The dot stays
+ // neutral — a passing test is only claimed on the connections page,
+ // where it comes from a real server-side probe.
+ const activeEndpoint = $derived.by(() => {
+ const s = $settingsQuery.data;
+ if (!s) return null;
+ return s.comfyui_endpoints?.find((ep) => ep.id === s.comfyui_active_id) ?? null;
+ });
+
const comfyUrl = $derived.by(() => {
- const raw = ($settingsQuery.data?.comfyui_base_url ?? '').trim();
+ const raw = (activeEndpoint?.base_url ?? $settingsQuery.data?.comfyui_base_url ?? '').trim();
if (!raw) return '';
try {
const u = new URL(raw.includes('://') ? raw : `http://${raw}`);
@@ -120,7 +129,7 @@
- {:else if tab === 'comfy'}
-
+ {:else if tab === 'comfy'}
+
{:else if tab === 'queue'}
{t('settings.queueSection')}
@@ -890,6 +887,27 @@
.check input {
width: auto;
}
+ .comfy-redirect {
+ border: 1px dashed var(--border);
+ border-radius: var(--radius-md, 8px);
+ padding: 14px 16px;
+ margin-bottom: var(--space-lg, 20px);
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ align-items: flex-start;
+ }
+ .comfy-link {
+ color: var(--accent, #e8a33d);
+ font-size: 13.5px;
+ font-weight: 600;
+ text-decoration: none;
+ border-bottom: 1px solid currentColor;
+ padding-bottom: 1px;
+ }
+ .comfy-link:hover {
+ opacity: 0.85;
+ }
.preset-chips {
display: flex;
gap: 8px;