feat: multi-ComfyUI connections + workflow foundation (HEL-611)

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
shigongyuan-agent
2026-09-28 00:03:05 +08:00
co-authored by multica-agent
parent 25d1e05a30
commit 1cf9188955
27 changed files with 3736 additions and 44 deletions
@@ -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}
@@ -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()
@@ -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),
)
+176
View File
@@ -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,
+5
View File
@@ -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")
+2
View File
@@ -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"])
@@ -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):
+31 -1
View File
@@ -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
+35 -3
View File
@@ -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],
@@ -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 {}),
}
+12 -2
View File
@@ -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:
@@ -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",
@@ -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()
@@ -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
@@ -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, "<html><body>hi</body></html>")
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, "<html></html>")
return
if self.server.mode == "system_stats_404":
# reverse-proxy style: /system_stats stripped
self._send_html(404, "<html>404</html>")
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)
+60
View File
@@ -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<ComfyEndpoint> & { 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<ComfyEndpoint> & { 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<Workflow[]>('/api/workflows'),
analyze: (workflow_json: Record<string, unknown>) =>
@@ -307,6 +365,7 @@ export const workflows = {
workflow_json: Record<string, unknown>;
description?: string;
prompt_profile?: string;
endpoint_id?: string | null;
}) => api<Workflow>('/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<Workflow>(`/api/workflows/${id}`, { method: 'PATCH', body: JSON.stringify(payload) }),
delete: (id: number) => api<{ ok: boolean }>(`/api/workflows/${id}`, { method: 'DELETE' }),
+2
View File
@@ -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 {
@@ -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 @@
</nav>
<div class="side-foot">
<a class="comfy-row" href="/settings" title={t('shell.comfyManage')}>
<a class="comfy-row" href="/connections" title={t('shell.comfyManage')}>
<span class="dot" aria-hidden="true"></span>
<span class="comfy-text">
{#if comfyUrl}
@@ -294,8 +303,8 @@
color: var(--text);
}
/* Untested by default — the connections page (a6) is not built yet, so
no green "connected" claim is made (honesty rule on HEL-608). */
/* Neutral until a real server-side probe says otherwise — the
connections page (a6) owns the tested/failed states (HEL-611). */
.dot {
width: 7px;
height: 7px;
+83
View File
@@ -1282,4 +1282,87 @@ export const de: Dict = {
'home.jobRequeued': 'Auftrag erneut eingereiht',
'home.jobRetryFailed': 'Erneutes Einreihen fehlgeschlagen',
'home.jobProject': 'Projekt #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'settings.comfyMultiHint': 'ComfyUI-Adressen unterstützen jetzt mehrere Verbindungen (lokal / LAN / Cloud), je Workflow bindbar.',
'settings.comfyGoto': 'In „ComfyUI-Verbindungen“ verwalten →',
'conn.title': 'ComfyUI-Verbindungen',
'conn.subtitle': 'Lokale, LAN- oder Cloud-ComfyUI-API-Adressen registrieren · Erreichbarkeit wird vom Server dieses Workbenches geprüft',
'conn.statusCount': '{n} Verbindungen · {m} bestanden',
'conn.add': 'Verbindung hinzufügen',
'conn.loading': 'Verbindungen werden geladen…',
'conn.loadFailed': 'Verbindungen konnten nicht geladen werden',
'conn.empty': 'Noch keine ComfyUI-Verbindung — die erste Adresse über „Verbindung hinzufügen“ eintragen.',
'conn.defaultBadge': 'Standard',
'conn.test': 'Verbindung testen',
'conn.testing': 'Teste…',
'conn.edit': 'Bearbeiten',
'conn.delete': 'Löschen',
'conn.setDefault': 'Als Standard festlegen',
'conn.delDefaultHint': 'Die Standardverbindung kann nicht gelöscht werden; erst anderen Standard wählen',
'conn.delTitle': 'Verbindung löschen',
'conn.delConfirmUsed': 'An diese Verbindung gebundene Workflows fallen auf die Standardverbindung zurück. Bestehende Job-Snapshots bleiben. „{name}“ löschen?',
'conn.delConfirmFree': 'Verbindung „{name}“ löschen?',
'conn.statusUntested': 'Ungetestet',
'conn.statusConnected': 'Test bestanden',
'conn.statusFailed': 'Test fehlgeschlagen',
'conn.latency': '{ms} ms Latenz',
'conn.version': 'Version {v}',
'conn.lastTestAt': 'zuletzt getestet {time}',
'conn.boundWorkflows': '{n} Workflows gebunden',
'conn.tokenSaved': 'Token gespeichert — leer lassen zum Behalten',
'conn.saved': 'Verbindung gespeichert',
'conn.deleted': 'Verbindung gelöscht',
'conn.saveFailed': 'Speichern fehlgeschlagen: {detail}',
'conn.defaultSetToast': 'Als Standardverbindung festgelegt',
'conn.formTitleAdd': 'ComfyUI-Verbindung hinzufügen',
'conn.formTitleEdit': 'ComfyUI-Verbindung bearbeiten',
'conn.formClose': 'Schließen',
'conn.fName': 'Name',
'conn.fNamePh': 'z. B. Lokales ComfyUI / Renderbox',
'conn.fBaseUrl': 'API-Adresse',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'HTTP-API-Adresse von ComfyUI (Standardport 8188); gleiches Format für lokal, LAN und Cloud.',
'conn.fAuth': 'Authentifizierung',
'conn.authNone': 'Ohne',
'conn.authBearer': 'Bearer-Token',
'conn.authHeader': 'Eigener Header',
'conn.authHelp': 'Nur nötig, wenn der Endpunkt hinter Auth liegt (Reverse-Proxy-Key usw.).',
'conn.fToken': 'Zugriffstoken',
'conn.fHeaderName': 'Header-Name',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': 'nur serverseitig gespeichert, nie zurückgespiegelt',
'conn.keyHelp': 'Der Token liegt in der Serverkonfiguration des Workbenches und erreicht nie den Browser.',
'conn.fNotes': 'Notizen',
'conn.fNotesPh': 'optional: was die Maschine läuft, VRAM…',
'conn.errName': 'Name ist erforderlich',
'conn.errUrl': 'Adresse muss eine gültige http://- oder https://-URL sein',
'conn.errHeaderName': 'Eigener Header braucht einen Headernamen',
'conn.testOk': '✓ Test bestanden · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': 'Vor dem Speichern muss der Test bestehen',
'conn.testBtn': 'Testen',
'conn.save': 'Speichern',
'conn.noticeStrong': 'Der Server entscheidet über Erreichbarkeit: ',
'conn.noticeBody': 'Eine im Browser öffnende Adresse heißt nicht, dass Generierung funktioniert; Tests wie Generierungsanfragen stellt der Server dieses Workbenches. Tokens bleiben serverseitig.',
'conn.wfTitle': 'Workflow-Bibliothek',
'conn.wfHint': 'ComfyUI-JSON im API-Format importieren, als Bild/Video klassifizieren, mit einer Verbindung verknüpfen',
'conn.wfEmpty': 'Noch keine Workflows importiert. In ComfyUI den Entwicklermodus aktivieren, als „API-Format“ exportieren und hier einfügen.',
'conn.wfCount': '{n} Workflows · {m} Bild · {k} Video',
'conn.wfKindImage': 'Bild',
'conn.wfKindVideo': 'Video',
'conn.wfConnection': 'Verknüpfte Verbindung',
'conn.wfConnectionActive': 'Folgt der Standardverbindung',
'conn.wfParams': '{n} ausfüllbare Parameter',
'conn.wfImport': 'Workflow importieren',
'conn.wfImporting': 'Importiere…',
'conn.wfImported': 'Workflow importiert',
'conn.wfImportFailed': 'Import fehlgeschlagen: {detail}',
'conn.wfImportTitle': 'ComfyUI-Workflow importieren (API-Format-JSON)',
'conn.wfImportHint': 'Einfügen oder Datei wählen; Name ist Pflicht, die Art entscheidet über Bild- oder Video-Fenster.',
'conn.wfJsonInvalid': 'Kein gültiges API-Format-JSON (erwartet: Objekt aus Knoten-ID → {{…class_type…}})',
'conn.wfJsonPh': 'ComfyUI-API-JSON hier einfügen oder rechts eine Datei wählen',
'conn.wfDeleted': 'Workflow gelöscht',
'conn.missingMaterial': 'Ein dediziertes Qwen Image 2.1-Workflow-JSON fehlt noch im Repo: aus ComfyUI exportieren und hier importieren — der generische Importweg steht bereit.',
};
+83
View File
@@ -1020,6 +1020,8 @@ export const en = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'Where ComfyUI runs.',
'settings.comfyHint': 'Must be reachable from this machine.',
'settings.comfyMultiHint': 'ComfyUI addresses now support multiple connections (local / LAN / cloud), bindable per imported workflow.',
'settings.comfyGoto': 'Manage in “ComfyUI Connections” →',
'settings.storageSection': 'System Paths',
'settings.storageLead': 'Where files live on disk, and where the agent may work.',
'settings.storageCalloutStrong': 'Changing data directory',
@@ -1282,5 +1284,86 @@ export const en = {
'home.jobRequeued': 'Job requeued',
'home.jobRetryFailed': 'Could not requeue the job',
'home.jobProject': 'Project #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'conn.title': 'ComfyUI Connections',
'conn.subtitle': 'Register local, LAN or cloud ComfyUI API addresses · connectivity is probed by the server running this workbench',
'conn.statusCount': '{n} connections · {m} passing',
'conn.add': 'Add connection',
'conn.loading': 'Loading connections…',
'conn.loadFailed': 'Failed to load connections',
'conn.empty': 'No ComfyUI connections yet — add your first address with “Add connection”.',
'conn.defaultBadge': 'Default',
'conn.test': 'Test connection',
'conn.testing': 'Testing…',
'conn.edit': 'Edit',
'conn.delete': 'Delete',
'conn.setDefault': 'Set as default',
'conn.delDefaultHint': 'The default connection cannot be deleted; set another default first',
'conn.delTitle': 'Delete connection',
'conn.delConfirmUsed': 'Workflows bound to this connection will fall back to the default. Existing job snapshots are kept. Delete “{name}”?',
'conn.delConfirmFree': 'Delete connection “{name}”?',
'conn.statusUntested': 'Untested',
'conn.statusConnected': 'Test passed',
'conn.statusFailed': 'Test failed',
'conn.latency': '{ms} ms latency',
'conn.version': 'version {v}',
'conn.lastTestAt': 'last tested {time}',
'conn.boundWorkflows': '{n} workflows bound',
'conn.tokenSaved': 'Token saved — leave blank to keep it',
'conn.saved': 'Connection saved',
'conn.deleted': 'Connection deleted',
'conn.saveFailed': 'Save failed: {detail}',
'conn.defaultSetToast': 'Set as default connection',
'conn.formTitleAdd': 'Add ComfyUI connection',
'conn.formTitleEdit': 'Edit ComfyUI connection',
'conn.formClose': 'Close',
'conn.fName': 'Name',
'conn.fNamePh': 'e.g. Local ComfyUI / render box',
'conn.fBaseUrl': 'API address',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'HTTP API address of ComfyUI (default port 8188); same format for local, LAN and cloud.',
'conn.fAuth': 'Authentication',
'conn.authNone': 'None',
'conn.authBearer': 'Bearer token',
'conn.authHeader': 'Custom header',
'conn.authHelp': 'Only needed when the endpoint sits behind auth (reverse proxy key, etc.).',
'conn.fToken': 'Access token',
'conn.fHeaderName': 'Header name',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': 'stored server-side only, never echoed',
'conn.keyHelp': 'The token lives in the workbench server config file and never reaches the browser.',
'conn.fNotes': 'Notes',
'conn.fNotesPh': 'optional: what this box runs, VRAM…',
'conn.errName': 'Name is required',
'conn.errUrl': 'Address must be a valid http:// or https:// URL',
'conn.errHeaderName': 'Custom header needs a header name',
'conn.testOk': '✓ Test passed · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': 'Pass the test before saving',
'conn.testBtn': 'Test',
'conn.save': 'Save',
'conn.noticeStrong': 'The server decides connectivity: ',
'conn.noticeBody': 'an address opening in your browser does not mean generation works; both tests and generation requests are made by the server running this workbench. Tokens stay server-side.',
'conn.wfTitle': 'Workflow library',
'conn.wfHint': 'Import ComfyUI API-format JSON, classify as image / video, bind to a connection',
'conn.wfEmpty': 'No workflows imported yet. In ComfyUI enable developer mode, export as “API format” JSON, then paste it here.',
'conn.wfCount': '{n} workflows · {m} image · {k} video',
'conn.wfKindImage': 'Image',
'conn.wfKindVideo': 'Video',
'conn.wfConnection': 'Bound connection',
'conn.wfConnectionActive': 'Follows the default connection',
'conn.wfParams': '{n} fillable parameters',
'conn.wfImport': 'Import workflow',
'conn.wfImporting': 'Importing…',
'conn.wfImported': 'Workflow imported',
'conn.wfImportFailed': 'Import failed: {detail}',
'conn.wfImportTitle': 'Import ComfyUI workflow (API-format JSON)',
'conn.wfImportHint': 'Paste or pick a file; name is required, the kind decides whether it shows in the image or video window.',
'conn.wfJsonInvalid': 'Not valid API-format JSON (expected an object of node id to class_type)',
'conn.wfJsonPh': 'Paste the ComfyUI API-format JSON here, or pick a file',
'conn.wfDeleted': 'Workflow deleted',
'conn.missingMaterial': 'A dedicated Qwen Image 2.1 workflow JSON is not in the repo yet: export it from ComfyUI and import it here — the generic import path is ready.',
};
export type Dict = typeof en;
+83
View File
@@ -1282,4 +1282,87 @@ export const es: Dict = {
'home.jobRequeued': 'Tarea reencolada',
'home.jobRetryFailed': 'No se pudo reencolar la tarea',
'home.jobProject': 'Proyecto #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'settings.comfyMultiHint': 'Las direcciones ComfyUI ahora admiten varias conexiones (local / LAN / nube), vinculables por flujo de trabajo.',
'settings.comfyGoto': 'Gestionar en «Conexiones ComfyUI» →',
'conn.title': 'Conexiones ComfyUI',
'conn.subtitle': 'Registra direcciones API de ComfyUI locales, de LAN o de nube · la conectividad la prueba el servidor',
'conn.statusCount': '{n} conexiones · {m} correctas',
'conn.add': 'Añadir conexión',
'conn.loading': 'Cargando conexiones…',
'conn.loadFailed': 'Error al cargar las conexiones',
'conn.empty': 'Aún no hay conexiones ComfyUI; añade la primera dirección con «Añadir conexión».',
'conn.defaultBadge': 'Predeterminada',
'conn.test': 'Probar conexión',
'conn.testing': 'Probando…',
'conn.edit': 'Editar',
'conn.delete': 'Eliminar',
'conn.setDefault': 'Establecer como predeterminada',
'conn.delDefaultHint': 'La conexión predeterminada no se puede eliminar; elige otra primero',
'conn.delTitle': 'Eliminar conexión',
'conn.delConfirmUsed': 'Los flujos vinculados a esta conexión volverán a la predeterminada. Las instantáneas existentes se conservan. ¿Eliminar «{name}»?',
'conn.delConfirmFree': '¿Eliminar la conexión «{name}»?',
'conn.statusUntested': 'Sin probar',
'conn.statusConnected': 'Prueba superada',
'conn.statusFailed': 'Prueba fallida',
'conn.latency': '{ms} ms de latencia',
'conn.version': 'versión {v}',
'conn.lastTestAt': 'última prueba {time}',
'conn.boundWorkflows': '{n} flujos vinculados',
'conn.tokenSaved': 'Token guardado; deja vacío para conservarlo',
'conn.saved': 'Conexión guardada',
'conn.deleted': 'Conexión eliminada',
'conn.saveFailed': 'Error al guardar: {detail}',
'conn.defaultSetToast': 'Establecida como predeterminada',
'conn.formTitleAdd': 'Añadir conexión ComfyUI',
'conn.formTitleEdit': 'Editar conexión ComfyUI',
'conn.formClose': 'Cerrar',
'conn.fName': 'Nombre',
'conn.fNamePh': 'p. ej. ComfyUI local / equipo de render',
'conn.fBaseUrl': 'Dirección API',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'Dirección HTTP de la API de ComfyUI (puerto 8188 por defecto); mismo formato para local, LAN y nube.',
'conn.fAuth': 'Autenticación',
'conn.authNone': 'Ninguna',
'conn.authBearer': 'Token Bearer',
'conn.authHeader': 'Cabecera personalizada',
'conn.authHelp': 'Solo necesario si el extremo está tras autenticación (clave de proxy inverso, etc.).',
'conn.fToken': 'Token de acceso',
'conn.fHeaderName': 'Nombre de cabecera',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': 'se guarda solo en el servidor, nunca se muestra',
'conn.keyHelp': 'El token vive en el archivo de configuración del servidor y nunca llega al navegador.',
'conn.fNotes': 'Notas',
'conn.fNotesPh': 'opcional: qué ejecuta, VRAM…',
'conn.errName': 'El nombre es obligatorio',
'conn.errUrl': 'La dirección debe ser una URL http:// o https:// válida',
'conn.errHeaderName': 'La cabecera personalizada necesita un nombre',
'conn.testOk': '✓ Prueba superada · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': 'Supera la prueba antes de guardar',
'conn.testBtn': 'Probar',
'conn.save': 'Guardar',
'conn.noticeStrong': 'El servidor decide la conectividad: ',
'conn.noticeBody': 'Que una dirección abra en el navegador no significa que la generación funcione; las pruebas y las peticiones las hace el servidor. Los tokens permanecen en el servidor.',
'conn.wfTitle': 'Biblioteca de flujos',
'conn.wfHint': 'Importa JSON en formato API de ComfyUI, clasifícalo como imagen/vídeo y vincúlalo a una conexión',
'conn.wfEmpty': 'Aún no hay flujos importados. Activa el modo desarrollador en ComfyUI, exporta en «formato API» y pégalo aquí.',
'conn.wfCount': '{n} flujos · {m} imagen · {k} vídeo',
'conn.wfKindImage': 'Imagen',
'conn.wfKindVideo': 'Vídeo',
'conn.wfConnection': 'Conexión vinculada',
'conn.wfConnectionActive': 'Sigue la conexión predeterminada',
'conn.wfParams': '{n} parámetros rellenables',
'conn.wfImport': 'Importar flujo',
'conn.wfImporting': 'Importando…',
'conn.wfImported': 'Flujo importado',
'conn.wfImportFailed': 'Error al importar: {detail}',
'conn.wfImportTitle': 'Importar flujo de ComfyUI (JSON en formato API)',
'conn.wfImportHint': 'Pega o elige un archivo; el nombre es obligatorio y el tipo decide si aparece en la ventana de imagen o vídeo.',
'conn.wfJsonInvalid': 'JSON no válido en formato API (se esperaba un objeto id de nodo → {{…class_type…}})',
'conn.wfJsonPh': 'Pega aquí el JSON en formato API de ComfyUI o elige un archivo',
'conn.wfDeleted': 'Flujo eliminado',
'conn.missingMaterial': 'Aún falta en el repo un JSON dedicado de Qwen Image 2.1: expórtalo desde ComfyUI e impórtalo aquí; la vía genérica ya está lista.',
};
+83
View File
@@ -1282,4 +1282,87 @@ export const fr: Dict = {
'home.jobRequeued': 'Tâche remise en file',
'home.jobRetryFailed': 'Impossible de remettre la tâche en file',
'home.jobProject': 'Projet #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'settings.comfyMultiHint': 'Les adresses ComfyUI prennent désormais en charge plusieurs connexions (local / LAN / cloud), associables par workflow.',
'settings.comfyGoto': 'Gérer dans « Connexions ComfyUI » →',
'conn.title': 'Connexions ComfyUI',
'conn.subtitle': 'Enregistrez des adresses API ComfyUI locales, LAN ou cloud · la connectivité est testée par le serveur',
'conn.statusCount': '{n} connexions · {m} réussies',
'conn.add': 'Ajouter une connexion',
'conn.loading': 'Chargement des connexions…',
'conn.loadFailed': 'Échec du chargement des connexions',
'conn.empty': 'Aucune connexion ComfyUI pour l\'instant — ajoutez la première adresse via « Ajouter une connexion ».',
'conn.defaultBadge': 'Par défaut',
'conn.test': 'Tester la connexion',
'conn.testing': 'Test…',
'conn.edit': 'Modifier',
'conn.delete': 'Supprimer',
'conn.setDefault': 'Définir par défaut',
'conn.delDefaultHint': 'La connexion par défaut ne peut pas être supprimée ; choisissez-en une autre d\'abord',
'conn.delTitle': 'Supprimer la connexion',
'conn.delConfirmUsed': 'Les workflows liés à cette connexion reviendront à la connexion par défaut. Les instantanés existants sont conservés. Supprimer « {name} » ?',
'conn.delConfirmFree': 'Supprimer la connexion « {name} » ?',
'conn.statusUntested': 'Non testée',
'conn.statusConnected': 'Test réussi',
'conn.statusFailed': 'Échec du test',
'conn.latency': '{ms} ms de latence',
'conn.version': 'version {v}',
'conn.lastTestAt': 'dernier test {time}',
'conn.boundWorkflows': '{n} workflows liés',
'conn.tokenSaved': 'Jeton enregistré — laissez vide pour le conserver',
'conn.saved': 'Connexion enregistrée',
'conn.deleted': 'Connexion supprimée',
'conn.saveFailed': 'Échec de l\'enregistrement : {detail}',
'conn.defaultSetToast': 'Définie comme connexion par défaut',
'conn.formTitleAdd': 'Ajouter une connexion ComfyUI',
'conn.formTitleEdit': 'Modifier la connexion ComfyUI',
'conn.formClose': 'Fermer',
'conn.fName': 'Nom',
'conn.fNamePh': 'ex. ComfyUI local / machine de rendu',
'conn.fBaseUrl': 'Adresse API',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'Adresse HTTP de l\'API ComfyUI (port 8188 par défaut) ; même format pour local, LAN et cloud.',
'conn.fAuth': 'Authentification',
'conn.authNone': 'Aucune',
'conn.authBearer': 'Jeton Bearer',
'conn.authHeader': 'En-tête personnalisé',
'conn.authHelp': 'Nécessaire seulement si le point de terminaison est derrière une auth (clé de reverse proxy, etc.).',
'conn.fToken': 'Jeton d\'accès',
'conn.fHeaderName': 'Nom d\'en-tête',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': 'stocké côté serveur uniquement, jamais renvoyé',
'conn.keyHelp': 'Le jeton reste dans le fichier de configuration du serveur et n\'atteint jamais le navigateur.',
'conn.fNotes': 'Notes',
'conn.fNotesPh': 'facultatif : ce que fait la machine, VRAM…',
'conn.errName': 'Le nom est requis',
'conn.errUrl': 'L\'adresse doit être une URL http:// ou https:// valide',
'conn.errHeaderName': 'L\'en-tête personnalisé exige un nom',
'conn.testOk': '✓ Test réussi · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': 'Réussissez le test avant d\'enregistrer',
'conn.testBtn': 'Tester',
'conn.save': 'Enregistrer',
'conn.noticeStrong': 'C\'est le serveur qui décide de la connectivité : ',
'conn.noticeBody': 'Une adresse qui s\'ouvre dans le navigateur ne garantit pas que la génération fonctionne ; tests et requêtes sont faits par le serveur. Les jetons restent côté serveur.',
'conn.wfTitle': 'Bibliothèque de workflows',
'conn.wfHint': 'Importez le JSON au format API ComfyUI, classez-le image/vidéo, liez-le à une connexion',
'conn.wfEmpty': 'Aucun workflow importé. Activez le mode développeur dans ComfyUI, exportez en « format API » puis collez-le ici.',
'conn.wfCount': '{n} workflows · {m} image · {k} vidéo',
'conn.wfKindImage': 'Image',
'conn.wfKindVideo': 'Vidéo',
'conn.wfConnection': 'Connexion liée',
'conn.wfConnectionActive': 'Suit la connexion par défaut',
'conn.wfParams': '{n} paramètres remplissables',
'conn.wfImport': 'Importer le workflow',
'conn.wfImporting': 'Import…',
'conn.wfImported': 'Workflow importé',
'conn.wfImportFailed': 'Échec de l\'import : {detail}',
'conn.wfImportTitle': 'Importer un workflow ComfyUI (JSON format API)',
'conn.wfImportHint': 'Collez ou choisissez un fichier ; le nom est requis, le type décide de la fenêtre image ou vidéo.',
'conn.wfJsonInvalid': 'JSON invalide au format API (attendu : objet id de nœud → {{…class_type…}})',
'conn.wfJsonPh': 'Collez ici le JSON format API ComfyUI ou choisissez un fichier',
'conn.wfDeleted': 'Workflow supprimé',
'conn.missingMaterial': 'Un JSON de workflow Qwen Image 2.1 dédié manque encore au dépôt : exportez-le depuis ComfyUI et importez-le ici — le chemin d\'import générique est prêt.',
};
+83
View File
@@ -1282,4 +1282,87 @@ export const ja: Dict = {
'home.jobRequeued': 'タスクを再び待機列に入れました',
'home.jobRetryFailed': 'タスクを再待機できませんでした',
'home.jobProject': 'プロジェクト #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'settings.comfyMultiHint': 'ComfyUI アドレスは複数接続(ローカル / LAN / クラウド)に対応し、ワークフローごとに紐付けできます。',
'settings.comfyGoto': '「ComfyUI 接続」ページで管理 →',
'conn.title': 'ComfyUI 接続',
'conn.subtitle': 'ローカル / LAN / クラウドの ComfyUI API アドレスを登録 · 接続性はサーバーが実測します',
'conn.statusCount': '{n} 件の接続 · {m} 件成功',
'conn.add': '接続を追加',
'conn.loading': '接続を読み込み中…',
'conn.loadFailed': '接続情報の読み込みに失敗しました',
'conn.empty': 'ComfyUI 接続がまだありません。右上の「接続を追加」で最初のアドレスを登録してください。',
'conn.defaultBadge': 'デフォルト',
'conn.test': '接続テスト',
'conn.testing': 'テスト中…',
'conn.edit': '編集',
'conn.delete': '削除',
'conn.setDefault': 'デフォルトに設定',
'conn.delDefaultHint': 'デフォルト接続は削除できません。先に他の接続をデフォルトにしてください',
'conn.delTitle': '接続を削除',
'conn.delConfirmUsed': 'この接続に紐付いたワークフローはデフォルト接続に戻ります。既存ジョブのスナップショットは保持されます。「{name}」を削除しますか?',
'conn.delConfirmFree': '接続「{name}」を削除しますか?',
'conn.statusUntested': '未テスト',
'conn.statusConnected': 'テスト成功',
'conn.statusFailed': 'テスト失敗',
'conn.latency': 'レイテンシ {ms} ms',
'conn.version': 'バージョン {v}',
'conn.lastTestAt': '前回テスト {time}',
'conn.boundWorkflows': '{n} 件のワークフローに紐付け',
'conn.tokenSaved': 'トークン保存済み。空欄で変更なし',
'conn.saved': '接続を保存しました',
'conn.deleted': '接続を削除しました',
'conn.saveFailed': '保存に失敗しました:{detail}',
'conn.defaultSetToast': 'デフォルト接続に設定しました',
'conn.formTitleAdd': 'ComfyUI 接続を追加',
'conn.formTitleEdit': 'ComfyUI 接続を編集',
'conn.formClose': '閉じる',
'conn.fName': '名前',
'conn.fNamePh': '例:ローカル ComfyUI / レンダーマシン',
'conn.fBaseUrl': 'API アドレス',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'ComfyUI の HTTP API アドレス(既定ポート 8188)。ローカル / LAN / クラウドで書式は同じです。',
'conn.fAuth': '認証',
'conn.authNone': 'なし',
'conn.authBearer': 'Bearer トークン',
'conn.authHeader': 'カスタムヘッダー',
'conn.authHelp': 'エンドポイントが認証の背後にある場合(リバースプロキシのキーなど)のみ必要です。',
'conn.fToken': 'アクセストークン',
'conn.fHeaderName': 'ヘッダー名',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': 'サーバー側のみに保存され、画面には表示されません',
'conn.keyHelp': 'トークンはワークベンチ サーバーの設定ファイルに保存され、ブラウザには渡りません。',
'conn.fNotes': 'メモ',
'conn.fNotesPh': '任意:このマシンのモデル・VRAMなど',
'conn.errName': '名前を入力してください',
'conn.errUrl': 'アドレスは http:// または https:// で始まる有効な URL である必要があります',
'conn.errHeaderName': 'カスタムヘッダーにはヘッダー名が必要です',
'conn.testOk': '✓ テスト成功 · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': '保存前にテストを通過してください',
'conn.testBtn': 'テスト',
'conn.save': '保存',
'conn.noticeStrong': '接続性の判定はサーバーが行います:',
'conn.noticeBody': 'ブラウザで開けるアドレス=生成可能ではありません。テストも生成リクエストもサーバーが行い、トークンはサーバー側に保存されます。',
'conn.wfTitle': 'ワークフローライブラリ',
'conn.wfHint': 'ComfyUI の API 形式 JSON を取り込み、画像 / 動画に分類して接続に紐付けます',
'conn.wfEmpty': 'まだワークフローがありません。ComfyUI の開発者モードで「API 形式」を書き出し、ここに貼り付けてください。',
'conn.wfCount': 'ワークフロー {n} 件 · 画像 {m} · 動画 {k}',
'conn.wfKindImage': '画像',
'conn.wfKindVideo': '動画',
'conn.wfConnection': '紐付ける接続',
'conn.wfConnectionActive': 'デフォルト接続に従う',
'conn.wfParams': '記入可能パラメータ {n} 件',
'conn.wfImport': 'ワークフローを取り込む',
'conn.wfImporting': '取り込み中…',
'conn.wfImported': 'ワークフローを取り込みました',
'conn.wfImportFailed': '取り込みに失敗しました:{detail}',
'conn.wfImportTitle': 'ComfyUI ワークフローを取り込む(API 形式 JSON)',
'conn.wfImportHint': '貼り付けまたはファイル選択。名前は必須で、種類が画像 / 動画ウィンドウのどちらに表示されるかを決めます。',
'conn.wfJsonInvalid': '有効な API 形式 JSON ではありません(ノード ID → {{…class_type…}} のオブジェクトが必要)',
'conn.wfJsonPh': 'ここに ComfyUI の API 形式 JSON を貼り付けるか、右のボタンでファイルを選択',
'conn.wfDeleted': 'ワークフローを削除しました',
'conn.missingMaterial': 'Qwen Image 2.1 専用のワークフロー JSON はまだリポジトリにありません。ComfyUI から書き出してここで取り込んでください。汎用の取り込み経路は用意済みです。',
};
+83
View File
@@ -1282,4 +1282,87 @@ export const ko: Dict = {
'home.jobRequeued': '작업이 다시 대기열에 추가되었습니다',
'home.jobRetryFailed': '작업을 다시 대기열에 넣지 못했습니다',
'home.jobProject': '프로젝트 #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'settings.comfyMultiHint': 'ComfyUI 주소는 이제 다중 연결(로컬 / LAN / 클라우드)을 지원하며 워크플로별로 바인딩할 수 있습니다.',
'settings.comfyGoto': '\'ComfyUI 연결\' 페이지에서 관리 →',
'conn.title': 'ComfyUI 연결',
'conn.subtitle': '로컬·LAN·클라우드 ComfyUI API 주소를 등록하세요 · 연결성은 서버가 실측합니다',
'conn.statusCount': '연결 {n}개 · 통과 {m}개',
'conn.add': '연결 추가',
'conn.loading': '연결 불러오는 중…',
'conn.loadFailed': '연결 정보를 불러오지 못했습니다',
'conn.empty': '아직 ComfyUI 연결이 없습니다. 우측 상단 \'연결 추가\'로 첫 주소를 등록하세요.',
'conn.defaultBadge': '기본',
'conn.test': '연결 테스트',
'conn.testing': '테스트 중…',
'conn.edit': '편집',
'conn.delete': '삭제',
'conn.setDefault': '기본으로 설정',
'conn.delDefaultHint': '기본 연결은 삭제할 수 없습니다. 다른 연결을 먼저 기본으로 지정하세요',
'conn.delTitle': '연결 삭제',
'conn.delConfirmUsed': '이 연결에 바인딩된 워크플로는 기본 연결로 되돌아갑니다. 기존 작업 스냅샷은 유지됩니다. \'{name}\'을(를) 삭제할까요?',
'conn.delConfirmFree': '연결 \'{name}\'을(를) 삭제할까요?',
'conn.statusUntested': '미테스트',
'conn.statusConnected': '테스트 통과',
'conn.statusFailed': '테스트 실패',
'conn.latency': '지연 {ms} ms',
'conn.version': '버전 {v}',
'conn.lastTestAt': '마지막 테스트 {time}',
'conn.boundWorkflows': '워크플로 {n}개 바인딩',
'conn.tokenSaved': '토큰 저장됨 — 비워 두면 유지',
'conn.saved': '연결이 저장되었습니다',
'conn.deleted': '연결이 삭제되었습니다',
'conn.saveFailed': '저장 실패: {detail}',
'conn.defaultSetToast': '기본 연결로 설정되었습니다',
'conn.formTitleAdd': 'ComfyUI 연결 추가',
'conn.formTitleEdit': 'ComfyUI 연결 편집',
'conn.formClose': '닫기',
'conn.fName': '이름',
'conn.fNamePh': '예: 로컬 ComfyUI / 렌더 머신',
'conn.fBaseUrl': 'API 주소',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'ComfyUI의 HTTP API 주소(기본 포트 8188). 로컬·LAN·클라우드 모두 같은 형식입니다.',
'conn.fAuth': '인증',
'conn.authNone': '없음',
'conn.authBearer': 'Bearer 토큰',
'conn.authHeader': '사용자 지정 헤더',
'conn.authHelp': '엔드포인트가 인증 뒤에 있을 때만 필요합니다(리버스 프록시 키 등).',
'conn.fToken': '액세스 토큰',
'conn.fHeaderName': '헤더 이름',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': '서버에만 저장되며 표시되지 않습니다',
'conn.keyHelp': '토큰은 워크벤치 서버의 설정 파일에 저장되며 브라우저로 전송되지 않습니다.',
'conn.fNotes': '메모',
'conn.fNotesPh': '선택: 이 머신이 실행하는 것, VRAM 등',
'conn.errName': '이름이 필요합니다',
'conn.errUrl': '주소는 유효한 http:// 또는 https:// URL이어야 합니다',
'conn.errHeaderName': '사용자 지정 헤더에는 헤더 이름이 필요합니다',
'conn.testOk': '✓ 테스트 통과 · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': '저장 전 테스트를 통과해야 합니다',
'conn.testBtn': '테스트',
'conn.save': '저장',
'conn.noticeStrong': '연결성 판정은 서버가 합니다: ',
'conn.noticeBody': '브라우저에서 열리는 주소가 생성 가능을 뜻하지 않습니다. 테스트와 생성 요청은 모두 서버가 수행하며 토큰은 서버에만 저장됩니다.',
'conn.wfTitle': '워크플로 라이브러리',
'conn.wfHint': 'ComfyUI API 형식 JSON을 가져와 이미지/동영상으로 분류하고 연결에 바인딩합니다',
'conn.wfEmpty': '아직 가져온 워크플로가 없습니다. ComfyUI 개발자 모드에서 \'API 형식\'으로 내보낸 뒤 여기에 붙여넣으세요.',
'conn.wfCount': '워크플로 {n}개 · 이미지 {m} · 동영상 {k}',
'conn.wfKindImage': '이미지',
'conn.wfKindVideo': '동영상',
'conn.wfConnection': '바인딩할 연결',
'conn.wfConnectionActive': '기본 연결을 따름',
'conn.wfParams': '채울 수 있는 매개변수 {n}개',
'conn.wfImport': '워크플로 가져오기',
'conn.wfImporting': '가져오는 중…',
'conn.wfImported': '워크플로를 가져왔습니다',
'conn.wfImportFailed': '가져오기 실패: {detail}',
'conn.wfImportTitle': 'ComfyUI 워크플로 가져오기(API 형식 JSON)',
'conn.wfImportHint': '붙여넣기 또는 파일 선택. 이름은 필수이며 종류가 이미지/동영상 창 표시를 결정합니다.',
'conn.wfJsonInvalid': '유효한 API 형식 JSON이 아닙니다(노드 ID → {{…class_type…}} 객체 필요)',
'conn.wfJsonPh': '여기에 ComfyUI API 형식 JSON을 붙여넣거나 오른쪽 버튼으로 파일을 선택하세요',
'conn.wfDeleted': '워크플로가 삭제되었습니다',
'conn.missingMaterial': 'Qwen Image 2.1 전용 워크플로 JSON이 아직 저장소에 없습니다. ComfyUI에서 내보내 여기서 가져오세요. 범용 가져오기 경로는 준비되어 있습니다.',
};
+83 -1
View File
@@ -1020,6 +1020,8 @@ export const zh: Dict = {
'settings.comfySection': 'ComfyUI',
'settings.comfyLead': 'ComfyUI 的运行位置。',
'settings.comfyHint': '必须能从本机访问。',
'settings.comfyMultiHint': 'ComfyUI 地址已支持多连接管理(本机 / 局域网 / 云端),并可在导入工作流时绑定。',
'settings.comfyGoto': '前往「ComfyUI 连接」页管理 →',
'settings.storageSection': '系统路径',
'settings.storageLead': '文件在磁盘上的位置,以及 AI 代理可以工作的位置。',
'settings.storageCalloutStrong': '更改数据目录',
@@ -1240,7 +1242,7 @@ export const zh: Dict = {
'shell.wipHint': '该页面正在开发中,稍后开放',
'shell.comfyAt': 'ComfyUI · {host}',
'shell.comfyUnset': 'ComfyUI · 未配置',
'shell.comfyManage': '在「设置」中配置 ComfyUI 地址',
'shell.comfyManage': '管理 ComfyUI 连接',
'shell.mobileNotice': '请用桌面浏览器(宽 768px 以上)打开影工坊,手机端暂不适配。',
'home.title': '项目总览',
'home.subtitle': '管理创作项目,从一个创意或一份现成剧本开始。',
@@ -1282,4 +1284,84 @@ export const zh: Dict = {
'home.jobRequeued': '任务已重新排队',
'home.jobRetryFailed': '重新排队失败',
'home.jobProject': '项目 #{id}',
// --- ComfyUI connections page (a6, HEL-611) ---
'conn.title': 'ComfyUI 连接',
'conn.subtitle': '登记本机、局域网或云端的 ComfyUI API 地址 · 连通性由运行本工作台的服务器实测',
'conn.statusCount': '{n} 个连接 · {m} 个测试通过',
'conn.add': '添加连接',
'conn.loading': '正在加载连接…',
'conn.loadFailed': '连接信息加载失败',
'conn.empty': '还没有 ComfyUI 连接,点右上角「添加连接」登记第一个地址。',
'conn.defaultBadge': '默认',
'conn.test': '测试连接',
'conn.testing': '测试中…',
'conn.edit': '编辑',
'conn.delete': '删除',
'conn.setDefault': '设为默认',
'conn.delDefaultHint': '默认连接不能删除,请先把其他连接设为默认',
'conn.delTitle': '删除连接',
'conn.delConfirmUsed': '删除后绑定此连接的工作流将回退到默认连接;已生成任务的快照不受影响。确定删除「{name}」?',
'conn.delConfirmFree': '确定删除连接「{name}」?',
'conn.statusUntested': '未测试',
'conn.statusConnected': '测试通过',
'conn.statusFailed': '测试失败',
'conn.latency': '延迟 {ms} ms',
'conn.version': '版本 {v}',
'conn.lastTestAt': '上次测试 {time}',
'conn.boundWorkflows': '{n} 个工作流绑定',
'conn.tokenSaved': '已保存密钥,留空表示不修改',
'conn.saved': '连接已保存',
'conn.deleted': '连接已删除',
'conn.saveFailed': '保存失败:{detail}',
'conn.defaultSetToast': '已设为默认连接',
'conn.formTitleAdd': '添加 ComfyUI 连接',
'conn.formTitleEdit': '编辑 ComfyUI 连接',
'conn.formClose': '关闭',
'conn.fName': '名称',
'conn.fNamePh': '例如:本机 ComfyUI / 机房渲染机',
'conn.fBaseUrl': 'API 地址',
'conn.fBaseUrlPh': 'http://192.168.200.18:8188',
'conn.baseUrlHelp': 'ComfyUI 的 HTTP API 地址(默认端口 8188);本机、局域网、云端写法相同。',
'conn.fAuth': '鉴权方式',
'conn.authNone': '无鉴权',
'conn.authBearer': 'Bearer Token',
'conn.authHeader': '自定义 Header',
'conn.authHelp': '仅当服务端启用了鉴权(反代加的 Key 等)才需要填写。',
'conn.fToken': '访问令牌',
'conn.fHeaderName': 'Header 名称',
'conn.fHeaderNamePh': 'X-Api-Key',
'conn.keyNoEcho': '密钥仅保存在服务器,不回显',
'conn.keyHelp': '令牌保存在工作台服务器的配置文件里,不会出现在浏览器中。',
'conn.fNotes': '备注',
'conn.fNotesPh': '选填:这台机器跑什么模型、显存等',
'conn.errName': '请填写名称',
'conn.errUrl': '地址必须是 http:// 或 https:// 开头的有效 URL',
'conn.errHeaderName': '自定义 Header 需要填写 Header 名称',
'conn.testOk': '✓ 测试通过 · {ms} ms · ComfyUI {v}',
'conn.testFail': '✕ {reason}',
'conn.needTest': '保存前需测试通过',
'conn.testBtn': '测试',
'conn.save': '保存',
'conn.noticeStrong': '连通性以服务器为准:',
'conn.noticeBody': '地址在浏览器能打开不代表生成可用;测试与生成请求都由运行影工坊的服务器发起。令牌仅存服务端。',
'conn.wfTitle': '工作流库',
'conn.wfHint': '导入 ComfyUI 的 API 格式 JSON,分类为图片 / 视频,并绑定到某个连接',
'conn.wfEmpty': '还没有导入工作流。在 ComfyUI 里启用开发者模式,用「导出(API 格式)」得到 JSON 后粘贴导入。',
'conn.wfCount': '{n} 个工作流 · {m} 图片 · {k} 视频',
'conn.wfKindImage': '图片',
'conn.wfKindVideo': '视频',
'conn.wfConnection': '绑定连接',
'conn.wfConnectionActive': '跟随默认连接',
'conn.wfParams': '{n} 个可填参数',
'conn.wfImport': '导入工作流',
'conn.wfImporting': '导入中…',
'conn.wfImported': '工作流已导入',
'conn.wfImportFailed': '导入失败:{detail}',
'conn.wfImportTitle': '导入 ComfyUI 工作流(API 格式 JSON)',
'conn.wfImportHint': '粘贴或选择文件;名称必填,分类决定它出现在生图还是生视频窗口。',
'conn.wfJsonInvalid': '不是有效的 API 格式 JSON(应为节点 id 到 class_type 的对象)',
'conn.wfJsonPh': '在此粘贴 ComfyUI 导出的 API 格式 JSON,或点右侧按钮选择文件',
'conn.wfDeleted': '工作流已删除',
'conn.missingMaterial': 'Qwen Image 2.1 的专用工作流 JSON 仓库中暂缺:请从 ComfyUI 导出后在此导入,通用导入通道已就绪。',
};
File diff suppressed because it is too large Load Diff
+40 -22
View File
@@ -542,28 +542,25 @@
{/each}
</div>
</section>
{:else if tab === 'comfy'}
<section class="panel">
<h1>{t('settings.comfySection')}</h1>
<p class="lead">{t('settings.comfyLead')}</p>
<label class="field">
<span class="field-label">{t('settings.baseUrl')}</span>
<input
class="field-input"
value={String(fieldValue('comfyui_base_url', s.comfyui_base_url))}
oninput={(e) => (draft.comfyui_base_url = e.currentTarget.value)}
/>
<p class="field-hint">{t('settings.comfyHint')}</p>
</label>
<label class="check">
<input
type="checkbox"
checked={dryRunChecked(s)}
onchange={(e) => (draft.dry_run = e.currentTarget.checked)}
/>
{t('settings.dryRunLabel')}
</label>
</section>
{:else if tab === 'comfy'}
<section class="panel">
<h1>{t('settings.comfySection')}</h1>
<p class="lead">{t('settings.comfyLead')}</p>
<div class="comfy-redirect">
<p class="field-hint">{t('settings.comfyMultiHint')}</p>
<a class="comfy-link" href="/connections">
{t('settings.comfyGoto')}
</a>
</div>
<label class="check">
<input
type="checkbox"
checked={dryRunChecked(s)}
onchange={(e) => (draft.dry_run = e.currentTarget.checked)}
/>
{t('settings.dryRunLabel')}
</label>
</section>
{:else if tab === 'queue'}
<section class="panel">
<h1>{t('settings.queueSection')}</h1>
@@ -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;