diff --git a/calliope-backend/src/calliope/comfyui/client.py b/calliope-backend/src/calliope/comfyui/client.py index aa60c4a8..59b6021f 100644 --- a/calliope-backend/src/calliope/comfyui/client.py +++ b/calliope-backend/src/calliope/comfyui/client.py @@ -2,6 +2,7 @@ from __future__ import annotations import logging +import time import uuid from pathlib import Path from typing import Any @@ -18,6 +19,17 @@ logger = logging.getLogger("calliope.comfyui") # bad endpoint hangs every queued job for two minutes before failing. HEALTH_TIMEOUT_SEC = 5.0 +# /object_info fetch is a few MB on big instances; the preflight check +# (HEL-642/643) caches it per endpoint for this long. Manual refresh +# (`force_refresh=True`) bypasses the TTL. +OBJECT_INFO_TTL_SEC = 300.0 +_object_info_cache: dict[str, tuple[float, dict[str, Any]]] = {} + + +def clear_object_info_cache() -> None: + """Drop cached /object_info payloads (tests swap fake endpoints in).""" + _object_info_cache.clear() + def _surface_error(prefix: str, resp: httpx.Response) -> RuntimeError: """Raise with ComfyUI's own error body instead of an opaque status line. @@ -88,6 +100,33 @@ class ComfyUIClient: except Exception: return False + def _cache_key(self) -> str: + auth = self._headers.get("Authorization") or next( + (v for k, v in self._headers.items() if k.lower() not in ("authorization",)), "" + ) + return f"{self.base_url}|{auth}" + + async def object_info(self, force_refresh: bool = False) -> dict[str, Any]: + """The server's full ``/object_info`` node catalogue, cached per endpoint. + + Cached for OBJECT_INFO_TTL_SEC; ``force_refresh`` re-fetches (the + connections page "重新检查" button after the user installs nodes). + Raises on transport/HTTP errors so callers can report honestly. + """ + key = self._cache_key() + now = time.monotonic() + if not force_refresh: + hit = _object_info_cache.get(key) + if hit and now - hit[0] < OBJECT_INFO_TTL_SEC: + return hit[1] + resp = await self._http.get(f"{self.base_url}/object_info", timeout=30.0) + resp.raise_for_status() + data = resp.json() + if not isinstance(data, dict): + raise RuntimeError("ComfyUI 返回的 /object_info 不是对象") + _object_info_cache[key] = (now, data) + return data + async def upload_image(self, path: Path, subfolder: str = "calliope") -> str: data = path.read_bytes() files = {"image": (path.name, data, "application/octet-stream")} diff --git a/calliope-backend/src/calliope/comfyui/parser.py b/calliope-backend/src/calliope/comfyui/parser.py index 922f4723..be8416c7 100644 --- a/calliope-backend/src/calliope/comfyui/parser.py +++ b/calliope-backend/src/calliope/comfyui/parser.py @@ -281,17 +281,45 @@ def resolution_selector_size(aspect_ratio: str, megapixels: float, multiple: int ) -# ComfyUI Autogrow image inputs a studio form fills as one 1…max list. -# The workflow wires ``.N``; extra images are cloned LoadImage -# nodes added at patch time (patcher.py). This registry only beautifies known -# classes (label + real max from /object_info); detection itself is generic — -# any ``.N`` run of image-loader links folds into a group. -IMAGE_GROUPS: dict[str, dict[str, dict[str, Any]]] = { +# ComfyUI Autogrow media inputs a studio form fills as one 1…max list +# (HEL-643 generalizes the original image-only registry to three media +# kinds). The workflow wires ``.N``; extra items are cloned +# loader nodes added at patch time (patcher.py). This registry only +# beautifies known classes (label + real max + hint key); detection itself +# is generic — any ``.N`` run of same-family media-loader +# links folds into a group, image / video / audio alike. +MEDIA_GROUPS: dict[str, dict[str, dict[str, Any]]] = { "MiniMaxH3ReferenceToVideo": { - "ref_images": {"prefix": "ref_image_", "max": 9, "label": "参考图"}, + "ref_images": { + "prefix": "ref_image_", + "max": 9, + "label": "参考图", + "kind": "image", + }, + "ref_videos": { + "prefix": "ref_video_", + "max": 3, + "label": "参考视频", + "kind": "video", + }, + "ref_audios": { + "prefix": "ref_audio_", + "max": 3, + "label": "参考音频", + "kind": "audio", + }, }, } +# Backwards-compatible alias for the original image-only view. +IMAGE_GROUPS = MEDIA_GROUPS + +# Consuming-node classes whose groups carry official usage limits worth a +# hint in the UI. Purely cosmetic — detection never depends on it. +_MEDIA_HINTS: dict[str, str] = { + "MiniMaxH3ReferenceToVideo": "minimax_h3_ref2va", +} + # ``ref_images.ref_image_0`` / ``images.image_1`` style Autogrow input names. _GROUP_INPUT_RE = re.compile( r"^(?P[A-Za-z0-9_+-]+)\.(?P[A-Za-z0-9_+-]+?)(?P\d+)$" @@ -305,9 +333,27 @@ _FRAME_SLOT_ROLES: dict[str, tuple[str, str]] = { "end_image": ("last_frame", "尾帧"), } +# Group media kind → (schema kind, role, default label, default max). +_GROUP_KIND_META: dict[str, tuple[str, str, str, int]] = { + "image": ("image_list", "reference_image", "参考图", 9), + "video": ("video_list", "reference_video", "参考视频", 9), + "audio": ("audio_list", "reference_audio", "参考音频", 9), +} + +# Loader class family for each media kind (registry.py sets). +_GROUP_SOURCE_CLASSES: dict[str, frozenset[str]] = { + "image": IMAGE_CLASSES, + "video": VIDEO_CLASSES, + "audio": AUDIO_CLASSES, +} + + +def media_group_spec(class_type: str, group: str) -> dict[str, Any] | None: + return MEDIA_GROUPS.get(class_type, {}).get(group) + def image_group_spec(class_type: str, group: str) -> dict[str, Any] | None: - return IMAGE_GROUPS.get(class_type, {}).get(group) + return media_group_spec(class_type, group) def image_group_prefix(node: dict[str, Any], group: str) -> str | None: @@ -346,14 +392,14 @@ def image_group_slots( def _detected_group_runs( workflow: dict[str, Any], node: dict[str, Any] -) -> list[tuple[str, str, list[str]]]: - """``[(group, prefix, source LoadImage ids)]`` for generic Autogrow inputs. +) -> list[tuple[str, str, list[str], str]]: + """``[(group, prefix, source loader ids, media kind)]`` for Autogrow inputs. - A run qualifies when the numbers are consecutive, every slot links to an - image-loader class, and the run either starts at 0 (single-slot Autogrow - exports like H3's ``ref_image_0``) or has ≥2 slots. Single runs numbered - from 1 (e.g. TextEncodeQwenImage21's ``images.image_1``) stay ordinary - image slots. + A run qualifies when the numbers are consecutive, every slot links to a + loader of the SAME media family (image / video / audio), and the run + either starts at 0 (single-slot Autogrow exports like H3's + ``ref_image_0``) or has ≥2 slots. Single runs numbered from 1 (e.g. + TextEncodeQwenImage21's ``images.image_1``) stay ordinary image slots. """ runs: dict[tuple[str, str], dict[int, Any]] = {} for name, val in (node.get("inputs") or {}).items(): @@ -361,7 +407,7 @@ def _detected_group_runs( if not m or not (isinstance(val, list) and len(val) == 2): continue runs.setdefault((m.group("group"), m.group("rest")), {})[int(m.group("n"))] = val - out: list[tuple[str, str, list[str]]] = [] + out: list[tuple[str, str, list[str], str]] = [] for (group, prefix), slots in sorted(runs.items()): ns = sorted(slots) if any(b - a != 1 for a, b in zip(ns, ns[1:])): @@ -369,41 +415,57 @@ def _detected_group_runs( if not (ns[0] == 0 or len(ns) >= 2): continue sources: list[str] = [] + family: str | None = None for n in ns: link = slots[n] src = workflow.get(str(link[0])) - if not (isinstance(src, dict) and src.get("class_type") in IMAGE_CLASSES): - sources = [] + if not isinstance(src, dict): + family = None break + ct = str(src.get("class_type") or "") + kinds = [ + kind + for kind, classes in _GROUP_SOURCE_CLASSES.items() + if ct in classes + ] + if len(kinds) != 1 or (family is not None and kinds[0] != family): + family = None + break + family = kinds[0] sources.append(str(link[0])) - if sources: - out.append((group, prefix, sources)) + if family and sources: + out.append((group, prefix, sources, family)) return out -def _image_groups( +def _media_groups( workflow: dict[str, Any], ) -> tuple[list[dict[str, Any]], set[str]]: - """Group entries for Autogrow reference inputs + the LoadImage ids they absorb.""" + """Group entries for Autogrow reference inputs (image/video/audio) plus + the loader node ids they absorb.""" entries: list[dict[str, Any]] = [] absorbed: set[str] = set() for nid, node in sorted( ((str(k), v) for k, v in workflow.items() if isinstance(v, dict)), key=lambda kv: _node_sort_key(kv[0]), ): - for group, _prefix, sources in _detected_group_runs(workflow, node): - spec = image_group_spec(str(node.get("class_type") or ""), group) or {} + class_type = str(node.get("class_type") or "") + for group, _prefix, sources, media_kind in _detected_group_runs(workflow, node): + spec = media_group_spec(class_type, group) or {} + kind, role, default_label, default_max = _GROUP_KIND_META[media_kind] absorbed.update(sources) + hint = _MEDIA_HINTS.get(class_type) entries.append( _entry( f"{nid}{FIELD_KEY_SEP}{group}", - str(spec.get("label") or "参考图"), - "reference_image", - "image_list", + str(spec.get("label") or default_label), + role, + kind, None, True, min=1, - max=spec.get("max", 9), + max=spec.get("max", default_max), + media_hint=hint, ) ) return entries, absorbed @@ -449,7 +511,7 @@ def detect_untagged_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]: ) texts: list[tuple[str, dict[str, Any], str, bool]] = [] # (id, node, field, negative) - groups, grouped_images = _image_groups(workflow) + groups, grouped_loaders = _media_groups(workflow) media: list[dict[str, Any]] = [] numbers: list[dict[str, Any]] = [] taken_roles: set[str] = set() @@ -475,7 +537,7 @@ def detect_untagged_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]: lowered = title.lower() if ct in IMAGE_CLASSES or ct in _MASK_IMAGE_CLASSES: - if nid in grouped_images: + if nid in grouped_loaders: continue is_mask = ct in _MASK_IMAGE_CLASSES or "mask" in lowered or "遮罩" in lowered slot = _image_slot(nid, workflow, consumers) @@ -504,6 +566,10 @@ def detect_untagged_inputs(workflow: dict[str, Any]) -> list[dict[str, Any]]: ) continue if ct in VIDEO_CLASSES or ct in AUDIO_CLASSES: + if nid in grouped_loaders: + # Absorbed into an Autogrow media group (HEL-643) — the + # group entry owns its upload slots. + continue kind = "video" if ct in VIDEO_CLASSES else "audio" field = resolve_patch_field(node) has_default = isinstance(inputs.get(field), str) and bool(inputs.get(field)) diff --git a/calliope-backend/src/calliope/comfyui/patcher.py b/calliope-backend/src/calliope/comfyui/patcher.py index b83a7bf7..4fd1644a 100644 --- a/calliope-backend/src/calliope/comfyui/patcher.py +++ b/calliope-backend/src/calliope/comfyui/patcher.py @@ -5,12 +5,44 @@ from __future__ import annotations import copy from typing import Any -from calliope.comfyui.registry import IMAGE_CLASSES, class_to_patch_field +from calliope.comfyui.registry import ( + AUDIO_CLASSES, + IMAGE_CLASSES, + VIDEO_CLASSES, + VIDEO_FILE_CLASSES, + class_to_patch_field, +) # Input keys of the form "@" target one named widget on a # node (auto-detected inputs: KSampler seed/steps/cfg, latent width/height…). FIELD_KEY_SEP = "@" +# Media-loader families and the Chinese slot label used on cloned nodes. +_GROUP_LABELS: tuple[tuple[frozenset[str], str], ...] = ( + (IMAGE_CLASSES, "参考图"), + (VIDEO_CLASSES, "参考视频"), + (AUDIO_CLASSES, "参考音频"), +) + + +def _loader_label(class_type: str) -> str: + for classes, label in _GROUP_LABELS: + if class_type in classes: + return label + return "参考素材" + + +def _loader_field(class_type: str, inputs: dict[str, Any]) -> str: + """The widget a loader node of this class stores its file value in.""" + if class_type in IMAGE_CLASSES: + return "image" + if class_type in VIDEO_CLASSES: + return "file" if class_type in VIDEO_FILE_CLASSES else "video" + if class_type in AUDIO_CLASSES: + # VHS_LoadAudio names its widget "audio:" (with the colon). + return "audio" if "audio" in inputs else "audio:" + return "image" + def _resolve_field(field: str, inputs: dict[str, Any]) -> str: """Map the computed patch field onto a key that exists on this node. @@ -43,15 +75,16 @@ def _next_node_id(workflow: dict[str, Any]) -> str: return str(max(numeric, default=0) + 1) -def apply_image_group( +def apply_media_group( workflow: dict[str, Any], node_id: str, group: str, paths: list[str] ) -> None: - """Rewire an Autogrow image group to exactly ``paths``, in order. + """Rewire an Autogrow media group (image/video/audio) to exactly ``paths``. - ``.0 … N-1`` each get their own LoadImage: the workflow's - existing ones are reused in slot order, extra ones are clones of the - first, and slots/loaders left over from the export are removed so no - stale image reaches ComfyUI. + ``.0 … N-1`` each get their own loader node: the + workflow's existing ones are reused in slot order, extra ones are clones + of the first, and slots/loaders left over from the export are removed so + no stale media reaches ComfyUI. File values are local paths — + ``prepare_media_inputs`` uploads them right before queueing. """ from calliope.comfyui.parser import image_group_prefix, image_group_slots @@ -61,7 +94,6 @@ def apply_image_group( prefix = image_group_prefix(node, group) if prefix is None: return - label = "参考图" inputs = dict(node.get("inputs") or {}) slots = image_group_slots(node, group, prefix) loaders: list[str] = [] @@ -69,11 +101,14 @@ def apply_image_group( inputs.pop(name, None) if isinstance(link, list) and len(link) == 2: src = workflow.get(str(link[0])) - if isinstance(src, dict) and src.get("class_type") in IMAGE_CLASSES: + if isinstance(src, dict) and str(src.get("class_type") or "") in ( + IMAGE_CLASSES | VIDEO_CLASSES | AUDIO_CLASSES + ): loaders.append(str(link[0])) if not loaders: return template = copy.deepcopy(workflow[loaders[0]]) + label = _loader_label(str(template.get("class_type") or "")) still_used: set[str] = set() for nid, other in workflow.items(): @@ -94,7 +129,8 @@ def apply_image_group( nid = _next_node_id(workflow) loader = copy.deepcopy(template) loader_inputs = dict(loader.get("inputs") or {}) - loader_inputs["image"] = path + field = _loader_field(str(loader.get("class_type") or ""), loader_inputs) + loader_inputs[field] = path loader["inputs"] = loader_inputs loader["_meta"] = {**(loader.get("_meta") or {}), "title": f"{label} {i + 1}"} workflow[nid] = loader @@ -102,6 +138,10 @@ def apply_image_group( node["inputs"] = inputs +# Original name kept: image groups were the first (and most common) family. +apply_image_group = apply_media_group + + def patch_workflow( base: dict[str, Any], values_by_node_id: dict[str, Any], @@ -125,7 +165,7 @@ def patch_workflow( if isinstance(paths, list): clean = [p for p in paths if isinstance(p, str) and p.strip()] if clean: - apply_image_group(patched, key, field, clean) + apply_media_group(patched, key, field, clean) continue if field is None: field = resolve_patch_field(node) diff --git a/calliope-backend/src/calliope/comfyui/preflight.py b/calliope-backend/src/calliope/comfyui/preflight.py new file mode 100644 index 00000000..0f7da21e --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/preflight.py @@ -0,0 +1,137 @@ +"""L2 connection preflight: check a workflow against a live /object_info (HEL-642/643). + +Layer 1 (lint.py) judges the JSON on its own; this module judges the JSON +against what the target ComfyUI actually has installed. Two generic rules, +zero hard-coding for any specific workflow or model name: + +1. Node existence — every ``class_type`` in the JSON must exist as a key of + the server's /object_info catalogue; missing ones are custom nodes the + user has not installed. +2. Combo value legality — for every combo input the server declares (an + input whose spec carries a candidate list — unet_name/clip_name/ + sampler/scheduler/…), the JSON's current widget value must be one of the + candidates; a miss usually means a model file or component is missing. + +File-upload widgets (LoadImage.image and friends) are skipped: their combo +lists are the server's input directory at export time and the value is +replaced by an upload before every submit, so a miss there says nothing. +""" +from __future__ import annotations + +from typing import Any + +from calliope.comfyui.registry import AUDIO_CLASSES, IMAGE_CLASSES, VIDEO_CLASSES + +# Media-loader classes and the widget names that hold their file values — +# upload-backed combos that cannot be judged before an upload happens. +_MEDIA_LOADER_FIELDS: tuple[frozenset[str], frozenset[str]] = ( + (IMAGE_CLASSES, frozenset({"image"})), + (AUDIO_CLASSES, frozenset({"audio", "audio:"})), + (VIDEO_CLASSES, frozenset({"file", "video"})), +) + +# object_info widget-config keys that mark an input as file-upload backed. +_UPLOAD_CONFIG_KEYS = ("image_upload", "audio_upload", "video_upload", "upload") + +_MAX_CANDIDATES_SHOWN = 6 + + +def _node_title(node: dict[str, Any]) -> str: + title = (node.get("_meta") or {}).get("title") + return str(title).strip() if title else "" + + +def _is_upload_backed(class_type: str, input_name: str, config: Any) -> bool: + if isinstance(config, dict) and any(config.get(k) for k in _UPLOAD_CONFIG_KEYS): + return True + for classes, fields in _MEDIA_LOADER_FIELDS: + if class_type in classes and input_name in fields: + return True + return False + + +def _combo_candidates(spec: Any) -> list[str] | None: + """The candidate list when ``spec`` is a combo input, else None. + + A combo spec is ``[["a", "b"], {config}]`` — first element a list of + plain strings. Typed inputs (``["FLOAT", {…}]``) return None. + """ + if not (isinstance(spec, list) and len(spec) >= 1): + return None + values = spec[0] + if not isinstance(values, list) or not values: + return None + if not all(isinstance(v, str) for v in values): + return None + return values + + +def check_workflow_against( + object_info: dict[str, Any], workflow: dict[str, Any] +) -> list[dict[str, Any]]: + """Findings for every problem the target server's catalogue reveals. + + Each finding is ``{level, code, node_id, node_title, message, hint}`` + (``level`` is always ``"error"`` for now — both rules are hard misses). + """ + findings: list[dict[str, Any]] = [] + if not isinstance(object_info, dict) or not isinstance(workflow, dict): + return findings + for node_id, node in workflow.items(): + if not isinstance(node, dict): + continue + class_type = str(node.get("class_type") or "") + title = _node_title(node) + label = f"节点 {node_id}「{title}」" if title else f"节点 {node_id}" + spec = object_info.get(class_type) + if not isinstance(spec, dict): + findings.append( + { + "level": "error", + "code": "missing_node", + "node_id": str(node_id), + "node_title": title, + "message": ( + f"缺少自定义节点 {class_type or '(未知类名)'}({label})——" + "该 ComfyUI 未安装此节点,需先安装对应的节点包" + ), + "hint": "安装节点包后回到本页点「重新检查」即可复查,无需重新导入。", + } + ) + continue + declared = (spec.get("input") or {}) if isinstance(spec.get("input"), dict) else {} + inputs = node.get("inputs") or {} + for section in ("required", "optional"): + entries = declared.get(section) + if not isinstance(entries, dict): + continue + for input_name, in_spec in entries.items(): + value = inputs.get(input_name) + # Wired inputs (links) and absent widgets are not combos to judge. + if isinstance(value, (list, dict)) or value is None: + continue + config = in_spec[1] if isinstance(in_spec, list) and len(in_spec) > 1 else None + if _is_upload_backed(class_type, str(input_name), config): + continue + candidates = _combo_candidates(in_spec) + if candidates is None: + continue + if value in candidates: + continue + shown = "、".join(candidates[:_MAX_CANDIDATES_SHOWN]) + if len(candidates) > _MAX_CANDIDATES_SHOWN: + shown += f" 等 {len(candidates)} 项" + findings.append( + { + "level": "error", + "code": "value_not_in_list", + "node_id": str(node_id), + "node_title": title, + "message": ( + f"{label}:值「{value}」不在 ComfyUI 的可选列表" + f"(参数 {input_name})——多为对应的模型文件或组件未安装" + ), + "hint": f"该 ComfyUI 上可选:{shown}" if shown else None, + } + ) + return findings diff --git a/calliope-backend/src/calliope/comfyui/validate.py b/calliope-backend/src/calliope/comfyui/validate.py index bfcfa00d..a96a6657 100644 --- a/calliope-backend/src/calliope/comfyui/validate.py +++ b/calliope-backend/src/calliope/comfyui/validate.py @@ -63,20 +63,24 @@ def validate_input_values( errors.append(f"「{label}」不能大于 {_fmt(hi)}") continue clean[key] = value - elif kind == "image_list": + elif kind in ("image_list", "video_list", "audio_list"): paths = [raw] if isinstance(raw, str) else raw if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): errors.append(f"「{label}」的取值格式不对,请重新上传") continue paths = [p for p in paths if p.strip()] + unit = _LIST_UNITS[kind] + noun = _LIST_NOUNS[kind] hi = entry.get("max") if hi is not None and len(paths) > hi: - errors.append(f"{label}最多 {hi} 张(当前 {len(paths)} 张),请删除多余的图片") + errors.append( + f"{label}最多 {hi} {unit}(当前 {len(paths)} {unit}),请删除多余的{noun}" + ) continue bad = [ f"{label} {i}:{msg}" for i, p in enumerate(paths, 1) - if (msg := _image_file_problem(p)) + if (msg := _media_file_problem(p, kind)) ] if bad: errors.extend(bad) @@ -98,10 +102,11 @@ def validate_input_values( has_fallback = str(entry.get("defaultValue") or "").strip() != "" if key not in clean and not has_fallback: errors.append(f"请填写「{label}」") - elif required and entry.get("kind") == "image_list": + elif required and entry.get("kind") in ("image_list", "video_list", "audio_list"): lo = entry.get("min") or 1 + unit = _LIST_UNITS[entry.get("kind")] if len(clean.get(key) or []) < lo and not any(label in e for e in errors): - errors.append(f"需要至少 {lo} 张{label}") + errors.append(f"需要至少 {lo} {unit}{label}") elif required and entry.get("kind") == "image" and entry.get("role") != "mask": if key not in clean: errors.append(f"请上传{label}") @@ -109,19 +114,33 @@ def validate_input_values( _IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".webp"}) +_VIDEO_EXTS = frozenset({".mp4", ".webm", ".mov"}) +_AUDIO_EXTS = frozenset({".mp3", ".wav", ".m4a"}) +_LIST_UNITS = {"image_list": "张", "video_list": "段", "audio_list": "段"} +_LIST_NOUNS = {"image_list": "图片", "video_list": "视频", "audio_list": "音频"} +_LIST_EXTS = {"image_list": _IMAGE_EXTS, "video_list": _VIDEO_EXTS, "audio_list": _AUDIO_EXTS} +_LIST_FORMAT_HINT = { + "image_list": "格式不支持,请使用 PNG / JPG / WebP", + "video_list": "格式不支持,请使用 MP4 / WebM / MOV", + "audio_list": "格式不支持,请使用 MP3 / WAV / M4A", +} -def _image_file_problem(path: str) -> str | None: - """Why ``path`` cannot be a studio reference image (None = fine).""" +def _media_file_problem(path: str, kind: str) -> str | None: + """Why ``path`` cannot fill a media-list slot of this kind (None = fine).""" from calliope import config target = Path(path) - if target.suffix.lower() not in _IMAGE_EXTS: - return "格式不支持,请使用 PNG / JPG / WebP" + if target.suffix.lower() not in _LIST_EXTS[kind]: + return _LIST_FORMAT_HINT[kind] try: target.resolve().relative_to(config.settings.assets_dir.resolve()) except (ValueError, OSError): - return "只能使用在本页上传或从生成结果选入的图片" + return f"只能使用在本页上传或从生成结果选入的{_LIST_NOUNS[kind]}" if not target.is_file(): return "文件已不存在,请重新上传" return None + + +def _image_file_problem(path: str) -> str | None: + return _media_file_problem(path, "image_list") diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 1638155d..7f1cbad8 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -518,6 +518,11 @@ async def migrate_db(db_path: Path) -> None: conn.execute("ALTER TABLE jobs ADD COLUMN comfy_prompt_id TEXT") if "phase" not in job_cols: conn.execute("ALTER TABLE jobs ADD COLUMN phase TEXT") + # HEL-643: where a job came from — 'user' (every normal generation) or + # 'workflow_test' (L3 试运行). Existing rows default to 'user', semantics + # unchanged; test jobs get isolated artifacts and no entity write-back. + if "origin" not in job_cols: + conn.execute("ALTER TABLE jobs ADD COLUMN origin TEXT NOT NULL DEFAULT 'user'") # Build Scene's per-scene sessions: origin stamps WHERE a blind session was # born ('chat' = user-created in AI Canvas, 'scene' = auto-created by the # Build Scene rail). The session list excludes origin='scene' so scene diff --git a/calliope-backend/src/calliope/models/schemas.py b/calliope-backend/src/calliope/models/schemas.py index 4f69d66b..9af82ca7 100644 --- a/calliope-backend/src/calliope/models/schemas.py +++ b/calliope-backend/src/calliope/models/schemas.py @@ -247,6 +247,23 @@ class WorkflowUpdate(BaseModel): class WorkflowAnalyze(BaseModel): workflow_json: dict[str, Any] + # HEL-643: optional target connection — given, the analyze response also + # carries an L2 connection check (node/model availability via /object_info). + endpoint_id: str | None = None + # Bypass the /object_info cache (user re-checks after installing nodes). + refresh: bool = False + + +class WorkflowCheckRequest(BaseModel): + """L2 re-check of a saved workflow against a live ComfyUI (HEL-643).""" + endpoint_id: str | None = None + refresh: bool = False + + +class WorkflowTestRequest(BaseModel): + """Launch one real test run of a workflow (HEL-643 L3).""" + endpoint_id: str | None = None + input_values: dict[str, Any] = Field(default_factory=dict) class JobCreate(BaseModel): diff --git a/calliope-backend/src/calliope/queue/manager.py b/calliope-backend/src/calliope/queue/manager.py index 934f94b3..98f323af 100644 --- a/calliope-backend/src/calliope/queue/manager.py +++ b/calliope-backend/src/calliope/queue/manager.py @@ -36,16 +36,18 @@ class QueueManager: scene_id: int | None = None, clip_id: int | None = None, payload: dict[str, Any] | None = None, + origin: str = "user", ) -> 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', ?) + INSERT INTO jobs (project_id, scene_id, clip_id, kind, workflow_id, + status, payload_json, origin) + VALUES (?, ?, ?, ?, ?, 'pending', ?, ?) """, - (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload)), + (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload), origin), ) conn.commit() row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone() diff --git a/calliope-backend/src/calliope/queue/worker.py b/calliope-backend/src/calliope/queue/worker.py index 8d07745c..d8b7f44b 100644 --- a/calliope-backend/src/calliope/queue/worker.py +++ b/calliope-backend/src/calliope/queue/worker.py @@ -21,6 +21,11 @@ from calliope.db import get_db from calliope.events.bus import event_bus from calliope.export.runner import run_export from calliope.queue.manager import queue_manager +from calliope.queue.workflow_test import ( + TEST_ORIGIN, + prune_workflow_tests, + workflow_test_dir, +) logger = logging.getLogger("calliope.worker") @@ -164,6 +169,16 @@ class QueueWorker: "message": f"{self._job_label(job)} failed", }, ) + if str(job.get("origin") or "") == TEST_ORIGIN and job.get("workflow_id"): + # Retention: keep only the newest records (and their + # artifacts) per workflow (HEL-643). + try: + prune_workflow_tests(int(job["workflow_id"])) + except Exception: + logger.exception( + "Pruning workflow-test records for workflow %s failed", + job["workflow_id"], + ) except Exception: logger.exception("Worker loop error") await asyncio.sleep(config.settings.queue_poll_interval_sec) @@ -173,6 +188,7 @@ class QueueWorker: payload = json.loads(job["payload_json"] or "{}") project_id = job["project_id"] kind = job["kind"] + is_test = str(job.get("origin") or "") == TEST_ORIGIN use_dry = bool(config.settings.dry_run) if kind == "export": @@ -183,6 +199,13 @@ class QueueWorker: base_url, headers, endpoint_label = self._resolve_endpoint(payload) client = ComfyUIClient(base_url, headers=headers) try: + # A workflow test must be a REAL run — a dry-run placeholder that + # passes as "测试通过" is exactly the false positive HEL-643 bans. + if use_dry and is_test: + raise RuntimeError( + "测试工作流必须真实运行:当前设置开启了 Dry-run(占位模式)," + "请到「设置」关闭 Dry-run 后重新测试" + ) if use_dry: queue_manager.set_phase(job["id"], "dry_run") return await self._dry_run(job, payload) @@ -277,7 +300,12 @@ class QueueWorker: "请到「ComfyUI 连接」页修正该节点的媒体类型。" ) queue_manager.set_phase(job["id"], "saving") - dest_dir = config.settings.assets_dir / str(project_id) / kind + if is_test: + # Test artifacts live in a scratch dir, isolated from project + # media and never written back to entities (HEL-643). + dest_dir = workflow_test_dir(int(workflow_id)) + else: + dest_dir = config.settings.assets_dir / str(project_id) / kind dest_dir.mkdir(parents=True, exist_ok=True) paths: list[str] = [] for meta in outputs_meta: @@ -291,7 +319,8 @@ class QueueWorker: ) paths.append(str(dest)) - self._apply_outputs_to_entities(job, payload, paths) + if not is_test: + self._apply_outputs_to_entities(job, payload, paths) queue_manager.set_phase(job["id"], "finished") return paths finally: diff --git a/calliope-backend/src/calliope/queue/workflow_test.py b/calliope-backend/src/calliope/queue/workflow_test.py new file mode 100644 index 00000000..8ea81054 --- /dev/null +++ b/calliope-backend/src/calliope/queue/workflow_test.py @@ -0,0 +1,180 @@ +"""Workflow-test job helpers (HEL-643). + +A test job (jobs.origin = 'workflow_test') runs the FULL real pipeline — +queue → ComfyUI → outputs — but its artifacts are isolated from project +entities: files land under ``assets/_workflow_test/{workflow_id}/`` and are +never written back to characters/locations/scenes/clips. + +This module owns the artifact directory, the retention policy (keep the +newest N records per workflow) and the purge paths used by "清除测试记录" +and workflow deletion. +""" +from __future__ import annotations + +import json +import logging +import shutil +from pathlib import Path +from typing import Any + +from calliope import config +from calliope.db import get_db + +logger = logging.getLogger("calliope.queue") + +TEST_ORIGIN = "workflow_test" +TEST_SOURCE = "workflow_test" +# Records (and artifacts) kept per workflow before older ones are pruned. +TEST_KEEP = 5 + + +def workflow_test_dir(workflow_id: int) -> Path: + return config.settings.assets_dir / "_workflow_test" / str(workflow_id) + + +def _safe_unlink(path_str: str) -> bool: + """Delete a file if it resolves under assets_dir (missing = already gone).""" + try: + target = Path(path_str).resolve() + target.relative_to(config.settings.assets_dir.resolve()) + except (ValueError, OSError): + return False + if not target.is_file(): + return False + try: + target.unlink() + return True + except OSError: + return False + + +def _unlink_job_outputs(job: dict[str, Any]) -> None: + try: + paths = json.loads(job.get("output_paths_json") or "[]") + except (json.JSONDecodeError, TypeError): + return + if not isinstance(paths, list): + return + for p in paths: + if isinstance(p, str) and p.strip(): + _safe_unlink(p) + + +def _remove_test_dir_if_empty(workflow_id: int) -> None: + d = workflow_test_dir(workflow_id) + try: + if d.is_dir() and not any(d.iterdir()): + d.rmdir() + except OSError: + pass + + +def _test_job_public(job: dict[str, Any]) -> dict[str, Any]: + out = dict(job) + out["payload"] = json.loads(job.get("payload_json") or "{}") + out["output_paths"] = json.loads(job.get("output_paths_json") or "[]") + out.pop("payload_json", None) + out.pop("output_paths_json", None) + return out + + +def list_test_jobs(workflow_id: int, limit: int = 20) -> list[dict[str, Any]]: + conn = get_db(config.settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?" + " ORDER BY id DESC LIMIT ?", + (workflow_id, TEST_ORIGIN, limit), + ).fetchall() + return [_test_job_public(dict(r)) for r in rows] + finally: + conn.close() + + +def find_active_test_job(workflow_id: int, endpoint_id: str | None) -> dict[str, Any] | None: + """The unfinished test job for (workflow, endpoint), if one exists. + + Idempotency guard for the "测试工作流" button: a second click re-uses the + in-flight job instead of enqueuing a duplicate. + """ + conn = get_db(config.settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?" + " AND status IN ('pending', 'running') ORDER BY id DESC", + (workflow_id, TEST_ORIGIN), + ).fetchall() + finally: + conn.close() + for r in rows: + job = dict(r) + try: + payload = json.loads(job.get("payload_json") or "{}") + except (json.JSONDecodeError, TypeError): + payload = {} + snap = payload.get("endpoint") or {} + if not isinstance(snap, dict): + snap = {} + if (snap.get("id") or None) == (endpoint_id or None): + return _test_job_public(job) + return None + + +def prune_workflow_tests(workflow_id: int, keep: int = TEST_KEEP) -> int: + """Keep only the newest ``keep`` test records (older rows + files go).""" + conn = get_db(config.settings.db_path) + try: + rows = conn.execute( + "SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?" + " ORDER BY id DESC LIMIT -1 OFFSET ?", + (workflow_id, TEST_ORIGIN, max(keep, 0)), + ).fetchall() + removed = 0 + for r in rows: + job = dict(r) + if job.get("status") in ("pending", "running"): + continue + _unlink_job_outputs(job) + conn.execute("DELETE FROM jobs WHERE id = ?", (job["id"],)) + removed += 1 + conn.commit() + finally: + conn.close() + _remove_test_dir_if_empty(workflow_id) + if removed: + logger.info("Pruned %s old workflow-test records for workflow %s", removed, workflow_id) + return removed + + +def purge_workflow_tests(workflow_id: int, *, allow_active: bool = False) -> int: + """Delete EVERY test record and artifact for a workflow. + + Returns the removed row count; raises RuntimeError when an unfinished + test job is still in flight (unless ``allow_active``). + """ + conn = get_db(config.settings.db_path) + try: + if not allow_active: + active = conn.execute( + "SELECT COUNT(*) AS n FROM jobs WHERE workflow_id = ? AND origin = ?" + " AND status IN ('pending', 'running')", + (workflow_id, TEST_ORIGIN), + ).fetchone()["n"] + if active: + raise RuntimeError( + f"该工作流还有 {active} 个进行中的测试任务,请先等待完成或取消,再清除测试记录" + ) + rows = conn.execute( + "SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?", + (workflow_id, TEST_ORIGIN), + ).fetchall() + removed = 0 + for r in rows: + _unlink_job_outputs(dict(r)) + conn.execute("DELETE FROM jobs WHERE id = ?", (r["id"],)) + removed += 1 + conn.commit() + finally: + conn.close() + shutil.rmtree(workflow_test_dir(workflow_id), ignore_errors=True) + return removed diff --git a/calliope-backend/src/calliope/routers/playground.py b/calliope-backend/src/calliope/routers/playground.py index fa63dd6a..ce41aa7b 100644 --- a/calliope-backend/src/calliope/routers/playground.py +++ b/calliope-backend/src/calliope/routers/playground.py @@ -197,7 +197,14 @@ async def list_playground_jobs(limit: int = 50) -> list[dict[str, Any]]: pid = ensure_playground_project(conn) finally: conn.close() - return [_job_public(j) for j in queue_manager.list_jobs(pid, None, limit)] + # Workflow-test jobs (HEL-643) ride the same scratch project but must not + # surface in the studio windows' history — they carry their own dialog. + jobs = [ + j + for j in queue_manager.list_jobs(pid, None, limit) + if str(j.get("origin") or "user") != "workflow_test" + ] + return [_job_public(j) for j in jobs] @router.delete("/jobs/{job_id}") diff --git a/calliope-backend/src/calliope/routers/workflows.py b/calliope-backend/src/calliope/routers/workflows.py index 8d817151..dc2ded31 100644 --- a/calliope-backend/src/calliope/routers/workflows.py +++ b/calliope-backend/src/calliope/routers/workflows.py @@ -5,7 +5,8 @@ from typing import Any from fastapi import APIRouter, HTTPException -from calliope.comfyui.lint import workflow_warnings +from calliope.comfyui.endpoints import client_for, endpoint_snapshot +from calliope.comfyui.lint import blocking_problem, workflow_warnings from calliope.comfyui.output_map import ( auto_output_map, load_output_map, @@ -19,11 +20,27 @@ from calliope.comfyui.parser import ( parse_dynamic_inputs, parse_dynamic_outputs, ) +from calliope.comfyui.preflight import check_workflow_against from calliope.comfyui.profiles import detect_prompt_profile from calliope.comfyui.roles import usage_to_kind +from calliope.comfyui.validate import validate_input_values from calliope.config import settings from calliope.db import get_db, row_to_dict -from calliope.models.schemas import WorkflowAnalyze, WorkflowCreate, WorkflowUpdate +from calliope.events.bus import event_bus +from calliope.models.schemas import ( + WorkflowAnalyze, + WorkflowCheckRequest, + WorkflowCreate, + WorkflowTestRequest, + WorkflowUpdate, +) +from calliope.queue.manager import queue_manager +from calliope.queue.workflow_test import ( + TEST_SOURCE, + find_active_test_job, + list_test_jobs, + purge_workflow_tests, +) router = APIRouter() @@ -47,12 +64,53 @@ def _serialize_workflow(row: Any) -> dict[str, Any]: return data +async def _connection_check( + endpoint_id: str | None, workflow_json: dict[str, Any], refresh: bool = False +) -> dict[str, Any]: + """L2 preflight (HEL-643): workflow vs the target ComfyUI's /object_info. + + An unreachable connection degrades to ``reachable: False`` with an honest + 「无法核查」 message — it never blocks and never pretends to pass. + """ + endpoint = settings.resolve_comfyui_endpoint(endpoint_id) + if endpoint is None: + return { + "ok": False, + "reachable": False, + "endpoint_id": endpoint_id, + "endpoint_name": None, + "findings": [], + "message": "没有可用的 ComfyUI 连接,无法核查节点与模型", + } + base = { + "endpoint_id": endpoint.get("id"), + "endpoint_name": endpoint.get("name"), + "base_url": endpoint.get("base_url"), + } + client = client_for(endpoint) + try: + object_info = await client.object_info(force_refresh=refresh) + except Exception as exc: + return { + **base, + "ok": False, + "reachable": False, + "findings": [], + "message": f"无法核查(连不上该 ComfyUI):{type(exc).__name__}", + } + finally: + await client.close() + findings = check_workflow_against(object_info, workflow_json) + ok = not any(f.get("level") == "error" for f in findings) + return {**base, "ok": ok, "reachable": True, "findings": findings} + + @router.post("/analyze") async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]: inputs = parse_dynamic_inputs(payload.workflow_json) outputs = parse_dynamic_outputs(payload.workflow_json) judgment = classify_usage(payload.workflow_json) - return { + result: dict[str, Any] = { "inputs": inputs, "outputs": outputs, "suggested_profile": detect_prompt_profile(payload.workflow_json), @@ -64,6 +122,13 @@ async def analyze_workflow(payload: WorkflowAnalyze) -> dict[str, Any]: "usage_evidence": judgment["evidence"], "usable_usage": judgment["usable_usage"], } + # L2 (optional): with a target connection the analyze response also + # reports which nodes/models that ComfyUI actually has (HEL-643). + if payload.endpoint_id: + result["connection_check"] = await _connection_check( + payload.endpoint_id, payload.workflow_json, payload.refresh + ) + return result def _stored_schema(payload_schema: list[dict[str, Any]] | None, workflow: dict[str, Any]) -> str: @@ -133,16 +198,64 @@ async def reanalyze_workflow(workflow_id: int) -> dict[str, Any]: conn.close() +def _last_test_summary(job: dict[str, Any]) -> dict[str, Any]: + """Slim "上次测试" record for a workflow row (queried live, never stored).""" + try: + outputs = json.loads(job.get("output_paths_json") or "[]") + except (json.JSONDecodeError, TypeError): + outputs = [] + return { + "id": job["id"], + "status": job.get("status"), + "phase": job.get("phase"), + "error": job.get("error"), + "created_at": job.get("created_at"), + "completed_at": job.get("completed_at"), + "output_count": len(outputs) if isinstance(outputs, list) else 0, + } + + @router.get("") async def list_workflows() -> list[dict[str, Any]]: conn = get_db(settings.db_path) try: rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall() - return [_serialize_workflow(r) for r in rows] + out = [_serialize_workflow(r) for r in rows] + # 上次测试 state is read live from the newest test job per workflow — + # no cached column that could go stale (HEL-643). + latest: dict[int, dict[str, Any]] = {} + for jr in conn.execute( + "SELECT * FROM jobs WHERE origin = 'workflow_test' AND id IN" + " (SELECT MAX(id) FROM jobs WHERE origin = 'workflow_test' GROUP BY workflow_id)" + ).fetchall(): + latest[int(jr["workflow_id"])] = _last_test_summary(dict(jr)) + for data in out: + data["last_test"] = latest.get(int(data["id"])) + return out finally: conn.close() +@router.post("/{workflow_id}/check") +async def check_workflow(workflow_id: int, payload: WorkflowCheckRequest) -> dict[str, Any]: + """L2 re-check of a saved workflow against its (or a chosen) connection. + + The user installs missing nodes/models in ComfyUI, comes back here and + re-checks — no re-import needed. + """ + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT workflow_json, endpoint_id FROM workflows WHERE id = ?", (workflow_id,) + ).fetchone() + finally: + conn.close() + if not row: + raise HTTPException(status_code=404, detail="Workflow not found") + endpoint_id = payload.endpoint_id or row["endpoint_id"] + return await _connection_check(endpoint_id, json.loads(row["workflow_json"]), payload.refresh) + + @router.post("/dedupe") async def dedupe_workflows() -> dict[str, Any]: """Delete byte-identical duplicate workflows, keeping the lowest id. @@ -341,6 +454,119 @@ async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str conn.close() +def _job_public(job: dict[str, Any]) -> dict[str, Any]: + out = dict(job) + out["payload"] = json.loads(job.get("payload_json") or "{}") + out["output_paths"] = json.loads(job.get("output_paths_json") or "[]") + out.pop("payload_json", None) + out.pop("output_paths_json", None) + return out + + +@router.post("/{workflow_id}/test") +async def test_workflow(workflow_id: int, payload: WorkflowTestRequest) -> dict[str, Any]: + """Launch (or re-attach to) one REAL test run of a workflow (HEL-643 L3). + + The job goes through the ordinary queue → ComfyUI → outputs pipeline; + only its artifacts and bookkeeping are isolated (origin='workflow_test'). + A dry-run setting is refused outright — placeholder output must never + count as a test pass. Repeat clicks reuse the in-flight job. + """ + from calliope import config + + if config.settings.dry_run: + raise HTTPException( + status_code=400, + detail=( + "测试工作流必须真实运行:当前设置开启了 Dry-run(占位模式)," + "请到「设置」关闭 Dry-run 后再测试" + ), + ) + conn = get_db(settings.db_path) + try: + wf = conn.execute( + "SELECT id, kind, workflow_json, input_schema, output_map, output_map_source," + " endpoint_id FROM workflows WHERE id = ?", + (workflow_id,), + ).fetchone() + if not wf: + raise HTTPException(status_code=404, detail="Workflow not found") + workflow_json = json.loads(wf["workflow_json"]) + broken = blocking_problem(workflow_json) + if broken: + raise HTTPException(status_code=400, detail=broken) + map_problem = mapping_problem(workflow_json, wf["output_map"], wf["output_map_source"]) + if map_problem: + raise HTTPException(status_code=400, detail=map_problem) + schema = effective_input_schema( + json.loads(wf["input_schema"]) if wf["input_schema"] else [], workflow_json + ) + input_values, problems = validate_input_values(schema, payload.input_values) + if problems: + raise HTTPException(status_code=400, detail="参数有误:" + ";".join(problems)) + + endpoint_id = payload.endpoint_id or wf["endpoint_id"] or None + snapshot = endpoint_snapshot(endpoint_id) + active = find_active_test_job(workflow_id, (snapshot or {}).get("id")) + if active is not None: + return {"ok": True, "job": _job_public(active), "reused": True} + + from calliope.routers.playground import ensure_playground_project + + pid = ensure_playground_project(conn) + finally: + conn.close() + + job = queue_manager.enqueue( + project_id=pid, + kind=wf["kind"], + workflow_id=workflow_id, + scene_id=None, + payload={ + "input_values": input_values, + "source": TEST_SOURCE, + **({"endpoint_id": payload.endpoint_id} if payload.endpoint_id else {}), + }, + origin="workflow_test", + ) + await event_bus.publish( + "job.created", + {"job_id": job["id"], "kind": job["kind"], "source": TEST_SOURCE, + "project_id": job["project_id"], "workflow_test": True}, + ) + return {"ok": True, "job": _job_public(job), "reused": False} + + +@router.get("/{workflow_id}/tests") +async def list_workflow_tests(workflow_id: int) -> list[dict[str, Any]]: + conn = get_db(settings.db_path) + try: + row = conn.execute("SELECT id FROM workflows WHERE id = ?", (workflow_id,)).fetchone() + finally: + conn.close() + if not row: + raise HTTPException(status_code=404, detail="Workflow not found") + return list_test_jobs(workflow_id) + + +@router.post("/{workflow_id}/clear-tests") +async def clear_workflow_tests(workflow_id: int) -> dict[str, Any]: + """Delete every test record and artifact for this workflow.""" + conn = get_db(settings.db_path) + try: + row = conn.execute("SELECT id FROM workflows WHERE id = ?", (workflow_id,)).fetchone() + finally: + conn.close() + if not row: + raise HTTPException(status_code=404, detail="Workflow not found") + try: + removed = purge_workflow_tests(workflow_id) + except RuntimeError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc + await event_bus.publish("job.deleted", {"workflow_id": workflow_id, "source": TEST_SOURCE}) + return {"ok": True, "removed": removed} + + @router.delete("/{workflow_id}") async def delete_workflow(workflow_id: int) -> dict[str, bool]: conn = get_db(settings.db_path) @@ -366,6 +592,9 @@ async def delete_workflow(workflow_id: int) -> dict[str, bool]: "请先等任务完成或取消任务,再删除该工作流" ), ) + # Test records/artifacts belong to the workflow — cascade (HEL-643). + # The 409 above guarantees none are in flight here. + purge_workflow_tests(workflow_id, allow_active=True) conn.execute("DELETE FROM workflows WHERE id = ?", (workflow_id,)) conn.commit() return {"ok": True} diff --git a/calliope-backend/tests/test_media_groups.py b/calliope-backend/tests/test_media_groups.py new file mode 100644 index 00000000..009d38dd --- /dev/null +++ b/calliope-backend/tests/test_media_groups.py @@ -0,0 +1,266 @@ +"""媒体组泛化(HEL-643 批次 3):参考视频/参考音频按 JSON 实际连线进入 +input_schema 与提交流程;无连线则无入口;05_ref2va 只保留参考图。 + +视频/音频参考的真实 H3 JSON 暂无可执行样本(.15 无 ComfyUI),本套用 +自造 fixture + fake ComfyUI 验证解析/表单/回填/上传全链路(模拟链路)。 +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path + +import pytest + +from calliope.comfyui.parser import parse_dynamic_inputs +from calliope.comfyui.patcher import patch_workflow +from calliope.comfyui.validate import validate_input_values +from calliope.config import settings +from tests.test_studio_generation import PNG_1PX, _real_run + +FIXTURES = Path(__file__).parent / "fixtures" / "comfy_native" + + +@pytest.fixture +def uploads_dir(client): + d = settings.assets_dir / "uploads" + d.mkdir(parents=True, exist_ok=True) + return d + + +def _load_05() -> dict: + return json.loads((FIXTURES / "h3_ref2va_05_API.json").read_text(encoding="utf-8")) + + +def _ref2va_workflow(*, images=1, videos=1, audios=1) -> dict: + """H3 Ref2VA 形状的自造 JSON:图/视频/音频各一组 Autogrow 连线。""" + wf: dict = { + "1": { + "class_type": "PrimitiveStringMultiline", + "inputs": {"value": "提示词"}, + }, + "92": { + "class_type": "SaveVideo", + "inputs": {"video": ["131", 0]}, + }, + "131": { + "class_type": "MiniMaxH3ReferenceToVideo", + "inputs": {"prompt": ["1", 0]}, + }, + "901": {"class_type": "LoadImage", "inputs": {"image": "ref.png"}}, + "902": {"class_type": "LoadVideo", "inputs": {"file": "ref.mp4", "force_rate": 0}}, + "903": {"class_type": "LoadAudio", "inputs": {"audio": "ref.wav"}}, + } + ins = wf["131"]["inputs"] + for i in range(images): + ins[f"ref_images.ref_image_{i}"] = ["901", 0] + for i in range(videos): + ins[f"ref_videos.ref_video_{i}"] = ["902", 0] + for i in range(audios): + ins[f"ref_audios.ref_audio_{i}"] = ["903", 0] + return wf + + +def _entry(schema: list[dict], key_suffix: str) -> dict | None: + for e in schema: + if e["nodeId"].endswith("@" + key_suffix): + return e + return None + + +# --------------------------------------------------------------------------- +# Schema: 入口只由实际连线决定 +# --------------------------------------------------------------------------- + + +def test_ref2va_schema_exposes_three_media_groups(): + schema = parse_dynamic_inputs(_ref2va_workflow()) + img = _entry(schema, "ref_images") + vid = _entry(schema, "ref_videos") + aud = _entry(schema, "ref_audios") + assert img and img["kind"] == "image_list" and img["role"] == "reference_image" + assert img["max"] == 9 and img["label"] == "参考图" + assert vid and vid["kind"] == "video_list" and vid["role"] == "reference_video" + assert vid["max"] == 3 and vid["label"] == "参考视频" + assert aud and aud["kind"] == "audio_list" and aud["role"] == "reference_audio" + assert aud["max"] == 3 and aud["label"] == "参考音频" + # 官方限额提示按节点类名驱动(通用检测不携带 hint) + assert img["media_hint"] == vid["media_hint"] == aud["media_hint"] == "minimax_h3_ref2va" + # 被组吸收的 loader 不再单独出现 + assert not any(e["nodeId"] == "902" for e in schema) + assert not any(e["nodeId"] == "903" for e in schema) + + +def test_unwired_media_kinds_produce_no_entry(): + schema = parse_dynamic_inputs(_ref2va_workflow(videos=0, audios=0)) + assert _entry(schema, "ref_images") is not None + assert _entry(schema, "ref_videos") is None + assert _entry(schema, "ref_audios") is None + + +def test_generic_class_gets_group_without_hint(): + wf = _ref2va_workflow(videos=0, audios=0) + wf["20"] = {"class_type": "GenericRefNode", "inputs": {}} + wf["701"] = {"class_type": "VHS_LoadVideo", "inputs": {"video": "a.mp4"}} + wf["702"] = {"class_type": "VHS_LoadVideo", "inputs": {"video": "b.mp4"}} + wf["20"]["inputs"]["media.clip_0"] = ["701", 0] + wf["20"]["inputs"]["media.clip_1"] = ["702", 0] + schema = parse_dynamic_inputs(wf) + g = _entry(schema, "media") + assert g and g["kind"] == "video_list" and g["max"] == 9 + assert "media_hint" not in g + + +def test_05_ref2va_fixture_stays_image_only(): + schema = parse_dynamic_inputs(_load_05()) + lists = [e for e in schema if e["kind"].endswith("_list")] + assert len(lists) == 1 + assert lists[0]["kind"] == "image_list" and lists[0]["max"] == 9 + assert lists[0]["nodeId"] == "131@ref_images" + + +# --------------------------------------------------------------------------- +# Validation +# --------------------------------------------------------------------------- + + +def _media_file(path: str, data: bytes) -> str: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + p.write_bytes(data) + return str(p) + + +def test_validate_video_and_audio_lists(uploads_dir): + schema = parse_dynamic_inputs(_ref2va_workflow()) + img_key = _entry(schema, "ref_images")["nodeId"] + vid_key = _entry(schema, "ref_videos")["nodeId"] + aud_key = _entry(schema, "ref_audios")["nodeId"] + png = _media_file(str(uploads_dir / "ok.png"), PNG_1PX) + mp4 = _media_file(str(uploads_dir / "ok.mp4"), b"00") + mp3 = _media_file(str(uploads_dir / "ok.mp3"), b"00") + + clean, errs = validate_input_values( + schema, {"1": "p", img_key: [png], vid_key: [mp4], aud_key: [mp3]} + ) + assert errs == [] and clean[vid_key] == [mp4] and clean[aud_key] == [mp3] + + # 错误格式(图片文件填视频槽 / 视频文件填音频槽) + _, errs = validate_input_values( + schema, {"1": "p", img_key: [png], vid_key: [png], aud_key: [mp3]} + ) + assert errs == ["参考视频 1:格式不支持,请使用 MP4 / WebM / MOV"] + _, errs = validate_input_values( + schema, {"1": "p", img_key: [png], vid_key: [mp4], aud_key: [mp4]} + ) + assert errs == ["参考音频 1:格式不支持,请使用 MP3 / WAV / M4A"] + + # 上限(H3 官方 3 段)与最少 1 段 + four = [_media_file(str(uploads_dir / f"v{i}.mp4"), b"00") for i in range(4)] + _, errs = validate_input_values( + schema, {"1": "p", img_key: [png], vid_key: four, aud_key: [mp3]} + ) + assert errs == ["参考视频最多 3 段(当前 4 段),请删除多余的视频"] + _, errs = validate_input_values( + schema, {"1": "p", img_key: [png], aud_key: [mp3]} + ) + assert errs == ["需要至少 1 段参考视频"] + + +# --------------------------------------------------------------------------- +# Patcher + full chain against fake ComfyUI +# --------------------------------------------------------------------------- + + +def test_patcher_clones_and_backfills_each_media_kind(uploads_dir): + wf = _ref2va_workflow() + schema = parse_dynamic_inputs(wf) + pngs = [_media_file(str(uploads_dir / "r1.png"), PNG_1PX), + _media_file(str(uploads_dir / "r2.png"), PNG_1PX)] + mp4 = _media_file(str(uploads_dir / "v1.mp4"), b"00") + mp3 = _media_file(str(uploads_dir / "a1.mp3"), b"00") + patched = patch_workflow( + wf, + { + _entry(schema, "ref_images")["nodeId"]: pngs, + _entry(schema, "ref_videos")["nodeId"]: [mp4], + _entry(schema, "ref_audios")["nodeId"]: [mp3], + }, + ) + ins = patched["131"]["inputs"] + image_links = [v for k, v in ins.items() if k.startswith("ref_images.")] + video_links = [v for k, v in ins.items() if k.startswith("ref_videos.")] + audio_links = [v for k, v in ins.items() if k.startswith("ref_audios.")] + assert len(image_links) == 2 and len(video_links) == 1 and len(audio_links) == 1 + loaders = {nid: n for nid, n in patched.items() + if n.get("class_type") in ("LoadImage", "LoadVideo", "LoadAudio")} + imgs = [n for n in loaders.values() if n["class_type"] == "LoadImage"] + vids = [n for n in loaders.values() if n["class_type"] == "LoadVideo"] + auds = [n for n in loaders.values() if n["class_type"] == "LoadAudio"] + assert len(imgs) == 2 and all(n["inputs"]["image"] in pngs for n in imgs) + assert vids and vids[0]["inputs"]["file"] == mp4 + assert auds and auds[0]["inputs"]["audio"] == mp3 + # 克隆出的节点带中文槽位标题 + assert {n["_meta"]["title"] for n in imgs} == {"参考图 1", "参考图 2"} + assert vids[0]["_meta"]["title"] == "参考视频 1" + assert auds[0]["_meta"]["title"] == "参考音频 1" + + +def test_full_chain_uploads_and_backfills_media_groups(client, fake_comfy, uploads_dir): + """提交 → 上传 → 回填:fake ComfyUI 收到的 prompt 里每类 loader 都 + 指向已上传文件(模拟链路:fake 端点,非真机 H3)。""" + wf = _ref2va_workflow() + png = _media_file(str(uploads_dir / "ref.png"), PNG_1PX) + mp4 = _media_file(str(uploads_dir / "ref.mp4"), b"00") + mp3 = _media_file(str(uploads_dir / "ref.mp3"), b"00") + r = client.post( + "/api/workflows", + json={"name": "媒体组链路", "workflow_json": wf, "usage": "ref2video"}, + ) + assert r.status_code == 200, r.text + wf_id = r.json()["id"] + schema = r.json()["input_schema"] + + with _real_run(client, fake_comfy): + fake_comfy.out_name = "media_out.mp4" + r = client.post( + f"/api/workflows/{wf_id}/test", + json={ + "input_values": { + _entry(schema, "ref_images")["nodeId"]: [png], + _entry(schema, "ref_videos")["nodeId"]: [mp4], + _entry(schema, "ref_audios")["nodeId"]: [mp3], + } + }, + ) + assert r.status_code == 200, r.text + job_id = r.json()["job"]["id"] + + deadline = time.time() + 25 + job = {} + while time.time() < deadline: + job = client.get(f"/api/jobs/{job_id}").json() + if job["status"] not in ("pending", "running"): + break + time.sleep(0.4) + assert job["status"] == "done", job.get("error") + + assert len(fake_comfy.uploads) >= 3 # 图、视频、音频各一次 + queued = fake_comfy.prompts[-1]["prompt"] + loaders = [n for n in queued.values() + if n.get("class_type") in ("LoadImage", "LoadVideo", "LoadAudio")] + by_field = { + (n["class_type"], k): v + for n in loaders + for k, v in n["inputs"].items() + if isinstance(v, str) and "uploaded-input" in v + } + assert ("LoadImage", "image") in by_field + assert ("LoadVideo", "file") in by_field + assert ("LoadAudio", "audio") in by_field + # 组连线数与提交数一致 + ins = queued["131"]["inputs"] + assert len([k for k in ins if k.startswith("ref_images.")]) == 1 + assert len([k for k in ins if k.startswith("ref_videos.")]) == 1 + assert len([k for k in ins if k.startswith("ref_audios.")]) == 1 diff --git a/calliope-backend/tests/test_studio_generation.py b/calliope-backend/tests/test_studio_generation.py index 1b3114cd..f7e88845 100644 --- a/calliope-backend/tests/test_studio_generation.py +++ b/calliope-backend/tests/test_studio_generation.py @@ -50,6 +50,9 @@ class _FakeComfyHandler(BaseHTTPRequestHandler): }, ) return + if self.path == "/object_info": + self._json(200, dict(getattr(self.server, "object_info", None) or {})) + return if self.path.startswith("/history/"): pid = self.path[len("/history/") :] entry = self.server.history.get(pid) @@ -78,9 +81,13 @@ class _FakeComfyHandler(BaseHTTPRequestHandler): {"filename": self.server.out_name, "subfolder": "", "type": "output"} ] } + outputs = ( + {} if getattr(self.server, "drop_outputs", False) else + {self._output_node(body): out_entry} + ) self.server.history[prompt_id] = { "status": {"status_str": "success", "completed": True}, - "outputs": {self._output_node(body): out_entry}, + "outputs": outputs, "prompt": [], } self.server.prompts.append(json.loads(body.decode("utf-8") or "{}")) @@ -135,6 +142,8 @@ def fake_comfy(): server.out_name = "out-1.png" server.outputs_key = "images" server.forced_output_node = None + server.object_info = {} + server.drop_outputs = False thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: diff --git a/calliope-backend/tests/test_workflow_preflight.py b/calliope-backend/tests/test_workflow_preflight.py new file mode 100644 index 00000000..03586fe5 --- /dev/null +++ b/calliope-backend/tests/test_workflow_preflight.py @@ -0,0 +1,272 @@ +"""L2 连接核查(HEL-643 批次 1):导入/复查时用目标 ComfyUI 的 /object_info +预检节点与模型可用性。全部基于 fake ComfyUI 的脚本化 /object_info, +不针对任何固定 JSON 或模型名写死判定。""" + +from __future__ import annotations + +import json +import socket +from pathlib import Path + +import pytest + +from calliope.comfyui.client import clear_object_info_cache +from calliope.comfyui.preflight import check_workflow_against +from calliope.config import settings +from tests.test_studio_generation import _url + +FIXTURES = Path(__file__).parent / "fixtures" / "comfy_native" + + +def _load_05() -> dict: + return json.loads((FIXTURES / "h3_ref2va_05_API.json").read_text(encoding="utf-8")) + + +def build_object_info(workflow: dict) -> dict: + """A catalogue where every widget value the JSON carries is legal. + + String widgets become combos whose candidates include the workflow's own + value (merged across nodes of the same class); numbers/booleans are typed + inputs; wired inputs are link types — none of those can mismatch. + """ + info: dict = {} + for node in workflow.values(): + if not isinstance(node, dict): + continue + ct = str(node.get("class_type") or "") + if not ct: + continue + spec = info.setdefault(ct, {"input": {"required": {}}, "output": ["*"]}) + required = spec["input"]["required"] + for name, val in (node.get("inputs") or {}).items(): + if isinstance(val, str): + # Merge: two nodes of one class with different values → both legal. + if name in required and isinstance(required[name][0], list): + if val not in required[name][0]: + required[name][0] = [*required[name][0], val] + continue + required[name] = [[val], {}] + elif name in required: + continue + elif isinstance(val, list): + required[name] = ["*", {}] + elif isinstance(val, bool): + required[name] = ["BOOLEAN", {}] + elif isinstance(val, (int, float)): + required[name] = ["NUMBER", {}] + return info + + +@pytest.fixture(autouse=True) +def _fresh_cache(): + clear_object_info_cache() + yield + clear_object_info_cache() + + +@pytest.fixture +def endpoint_at(client, fake_comfy): # noqa: F811 + """Register a connection pointing at the fake server; yields its id.""" + prev_eps = [dict(ep) for ep in (settings.comfyui_endpoints or [])] + prev_active = settings.comfyui_active_id + r = client.post( + "/api/comfyui/endpoints", + json={"name": "预检桩", "base_url": _url(fake_comfy), "auth_type": "none"}, + ) + assert r.status_code == 200, r.text + endpoints = r.json()["endpoints"] + ep = next(e for e in endpoints if e["base_url"] == _url(fake_comfy)) + settings.comfyui_endpoints = [dict(e) for e in endpoints if e["base_url"] == _url(fake_comfy)] + settings.comfyui_active_id = ep["id"] + settings.apply_active_comfyui() + try: + yield ep["id"] + finally: + settings.comfyui_endpoints = prev_eps + settings.comfyui_active_id = prev_active + settings.apply_active_comfyui() + + +# --------------------------------------------------------------------------- +# Unit rules +# --------------------------------------------------------------------------- + + +def test_unit_missing_node_reported_with_node_context(): + wf = {"900": {"class_type": "H3SLAAttention", "inputs": {"enabled": True}, + "_meta": {"title": "H3 SLA Attention"}}} + findings = check_workflow_against({"OtherNode": {}}, wf) + assert len(findings) == 1 + f = findings[0] + assert f["code"] == "missing_node" and f["level"] == "error" + msg = f["message"] + assert "H3SLAAttention" in msg and "900" in msg and "H3 SLA Attention" in msg + assert "重新检查" in f["hint"] + + +def test_unit_combo_value_not_in_list(): + wf = {"127": {"class_type": "UNETLoader", + "inputs": {"unet_name": "missing_model.safetensors", "weight_dtype": "default"}}} + info = {"UNETLoader": {"input": {"required": { + "unet_name": [["installed_model.safetensors"], {}], + "weight_dtype": [["default", "fp8"], {"upload": False}], + }}, "output": ["MODEL"]}} + findings = check_workflow_against(info, wf) + assert len(findings) == 1 + f = findings[0] + assert f["code"] == "value_not_in_list" and f["node_id"] == "127" + assert "missing_model.safetensors" in f["message"] and "unet_name" in f["message"] + assert "模型文件" in f["message"] + assert "installed_model.safetensors" in f["hint"] + + +def test_unit_upload_backed_and_wired_inputs_skipped(): + wf = { + "1": {"class_type": "LoadImage", "inputs": {"image": "placeholder.png"}}, + "2": {"class_type": "LoadVideo", "inputs": {"file": "clip.mp4"}}, + "3": {"class_type": "LoadAudio", "inputs": {"audio": "voice.wav"}}, + "4": {"class_type": "KSampler", "inputs": {"seed": 7, "model": ["9", 0]}}, + } + info = { + "LoadImage": {"input": {"required": {"image": [["other.png"], {"image_upload": True}]}}, + "output": ["IMAGE"]}, + "LoadVideo": {"input": {"required": {"file": [[], {}]}}, "output": ["IMAGE"]}, + "LoadAudio": {"input": {"required": {"audio": [[], {}]}}, "output": ["AUDIO"]}, + "KSampler": {"input": {"required": {"seed": ["INT", {}], "model": ["MODEL", {}]}}, + "output": ["IMAGE"]}, + } + assert check_workflow_against(info, wf) == [] + + +# --------------------------------------------------------------------------- +# Analyze with a target connection +# --------------------------------------------------------------------------- + + +def test_analyze_all_green_against_fake_object_info(client, endpoint_at, fake_comfy): + fake_comfy.object_info = build_object_info(_load_05()) + r = client.post( + "/api/workflows/analyze", + json={"workflow_json": _load_05(), "endpoint_id": endpoint_at}, + ) + assert r.status_code == 200, r.text + check = r.json()["connection_check"] + assert check["reachable"] is True and check["ok"] is True + assert check["findings"] == [] + + +def test_analyze_reports_missing_custom_node(client, endpoint_at, fake_comfy): + info = build_object_info(_load_05()) + info.pop("H3SLAAttention") + fake_comfy.object_info = info + r = client.post( + "/api/workflows/analyze", + json={"workflow_json": _load_05(), "endpoint_id": endpoint_at}, + ) + check = r.json()["connection_check"] + assert check["ok"] is False + missing = [f for f in check["findings"] if f["code"] == "missing_node"] + assert missing and "H3SLAAttention" in missing[0]["message"] + assert "900" in missing[0]["message"] + + +def test_analyze_reports_missing_model_value(client, endpoint_at, fake_comfy): + info = build_object_info(_load_05()) + # The server has a DIFFERENT unet installed than the one the JSON names. + info["UNETLoader"]["input"]["required"]["unet_name"] = [["another_unet.safetensors"], {}] + fake_comfy.object_info = info + r = client.post( + "/api/workflows/analyze", + json={"workflow_json": _load_05(), "endpoint_id": endpoint_at}, + ) + check = r.json()["connection_check"] + assert check["ok"] is False + bad = [f for f in check["findings"] if f["code"] == "value_not_in_list"] + assert bad and bad[0]["node_id"] == "127" + assert "minimax_h3_fused_refdelta" in bad[0]["message"] + + +def test_unreachable_connection_degrades_to_unchecked(client): + # A port that nothing listens on: the endpoint resolves, the server doesn't. + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + prev_eps = [dict(ep) for ep in (settings.comfyui_endpoints or [])] + prev_active = settings.comfyui_active_id + r = client.post( + "/api/comfyui/endpoints", + json={"name": "断连桩", "base_url": f"http://127.0.0.1:{port}", "auth_type": "none"}, + ) + endpoints = r.json()["endpoints"] + ep = next(e for e in endpoints if e["base_url"] == f"http://127.0.0.1:{port}") + settings.comfyui_endpoints = [dict(e) for e in endpoints if e["id"] == ep["id"]] + settings.comfyui_active_id = ep["id"] + settings.apply_active_comfyui() + try: + r = client.post( + "/api/workflows/analyze", + json={"workflow_json": _load_05(), "endpoint_id": ep["id"]}, + ) + check = r.json()["connection_check"] + assert check["reachable"] is False and check["ok"] is False + assert "无法核查" in check["message"] + assert check["findings"] == [] + finally: + settings.comfyui_endpoints = prev_eps + settings.comfyui_active_id = prev_active + settings.apply_active_comfyui() + + +# --------------------------------------------------------------------------- +# Saved-workflow re-check + cache +# --------------------------------------------------------------------------- + + +def _create_workflow(client, workflow: dict, endpoint_id: str | None = None) -> int: + r = client.post( + "/api/workflows", + json={ + "name": "预检工作流", + "workflow_json": workflow, + "usage": "ref2video", + **({"endpoint_id": endpoint_id} if endpoint_id else {}), + }, + ) + assert r.status_code == 200, r.text + return r.json()["id"] + + +def test_saved_workflow_recheck_and_refresh(client, endpoint_at, fake_comfy): + wf_id = _create_workflow(client, _load_05(), endpoint_at) + info = build_object_info(_load_05()) + info.pop("UNETLoader") + fake_comfy.object_info = info + r = client.post(f"/api/workflows/{wf_id}/check", json={}) + assert r.status_code == 200, r.text + body = r.json() + assert body["ok"] is False and body["endpoint_id"] == endpoint_at + assert any(f["code"] == "missing_node" for f in body["findings"]) + + # User installs the node package, comes back and re-checks with refresh. + fake_comfy.object_info = build_object_info(_load_05()) + r = client.post(f"/api/workflows/{wf_id}/check", json={"refresh": True}) + body = r.json() + assert body["ok"] is True and body["findings"] == [] + + +def test_object_info_cached_within_ttl(client, endpoint_at, fake_comfy): + fake_comfy.object_info = build_object_info(_load_05()) + for _ in range(2): + r = client.post( + "/api/workflows/analyze", + json={"workflow_json": _load_05(), "endpoint_id": endpoint_at}, + ) + assert r.json()["connection_check"]["ok"] is True + hits = [p for p in fake_comfy.requests if p == "/object_info"] + assert len(hits) == 1 # second call served from the 5-minute cache + + wf_id = _create_workflow(client, _load_05()) + client.post(f"/api/workflows/{wf_id}/check", json={"refresh": True}) + hits = [p for p in fake_comfy.requests if p == "/object_info"] + assert len(hits) == 2 # manual refresh bypasses the TTL diff --git a/calliope-backend/tests/test_workflow_test.py b/calliope-backend/tests/test_workflow_test.py new file mode 100644 index 00000000..34bccfcf --- /dev/null +++ b/calliope-backend/tests/test_workflow_test.py @@ -0,0 +1,197 @@ +"""「测试工作流」(HEL-643 批次 2)端到端:真实队列 → fake ComfyUI → 产物隔离。 + +测试任务与普通任务区分(jobs.origin)、dry-run 拒绝、幂等复用、 +保留策略与级联清理,全部对着 fake ComfyUI 跑真实链路。 +""" + +from __future__ import annotations + +import time +from pathlib import Path + +from calliope.config import settings +from calliope.queue.workflow_test import workflow_test_dir +from tests.test_studio_generation import ( + IMAGE_WORKFLOW, + PNG_1PX, + _real_run, +) + + +def _wait_terminal(client, job_id: int, timeout: float = 25.0) -> dict: + deadline = time.time() + timeout + while time.time() < deadline: + r = client.get(f"/api/jobs/{job_id}") + assert r.status_code == 200, r.text + job = r.json() + if job["status"] not in ("pending", "running"): + return job + time.sleep(0.4) + raise AssertionError(f"test job {job_id} did not finish in {timeout}s") + + +def _create_workflow(client, workflow: dict, name: str = "可测工作流") -> int: + r = client.post( + "/api/workflows", + json={"name": name, "workflow_json": workflow, "usage": "text2image"}, + ) + assert r.status_code == 200, r.text + return r.json()["id"] + + +def test_passing_test_downloads_real_output_to_scratch_dir(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="通过用例") + r = client.post( + f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "测试提示词"}} + ) + assert r.status_code == 200, r.text + body = r.json() + assert body["reused"] is False + job = _wait_terminal(client, body["job"]["id"]) + assert job["status"] == "done", job.get("error") + assert job["origin"] == "workflow_test" + assert job["payload"]["source"] == "workflow_test" + assert job["phase"] == "finished" + # 真实拿到可下载输出才算通过:产物落在独立 scratch 目录 + assert len(job["output_paths"]) >= 1 + out = Path(job["output_paths"][0]) + assert out.is_file() and out.read_bytes() == PNG_1PX + assert workflow_test_dir(wf_id) in out.parents + # 提交给 fake ComfyUI 的是补丁后的真实提示词 + queued = fake_comfy.prompts[-1]["prompt"] + assert queued["1"]["inputs"]["text"] == "测试提示词" + + +def test_tasks_list_shows_origin_but_playground_history_hides_it(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="可见性用例") + r = client.post(f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}}) + job_id = r.json()["job"]["id"] + _wait_terminal(client, job_id) + + listed = client.get("/api/jobs?limit=50").json() + mine = [j for j in listed if j["id"] == job_id] + assert mine and mine[0]["origin"] == "workflow_test" + + pg = client.get("/api/playground/jobs").json() + assert all(j["id"] != job_id for j in pg), "test jobs must stay out of studio history" + + +def test_failed_prompt_reports_chinese_reason(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="排队被拒用例") + fake_comfy.fail_prompt = True + r = client.post(f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}}) + job = _wait_terminal(client, r.json()["job"]["id"]) + assert job["status"] == "failed" + assert "拒绝执行" in (job["error"] or "") + + +def test_no_output_does_not_pass(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="无输出用例") + fake_comfy.drop_outputs = True + r = client.post(f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}}) + job = _wait_terminal(client, r.json()["job"]["id"]) + assert job["status"] == "failed" + assert "没有返回任何图片或视频" in (job["error"] or "") + + +def test_dry_run_setting_refuses_real_test(client, fake_comfy): + with _real_run(client, fake_comfy): + settings.dry_run = True # conftest default; _real_run clears it — set again + try: + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="dry 拒绝用例") + r = client.post(f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}}) + assert r.status_code == 400 + assert "Dry-run" in r.json()["detail"] + finally: + settings.dry_run = False + + +def test_repeat_click_reuses_inflight_job(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="幂等用例") + assert client.post("/api/jobs/pause").status_code == 200 + try: + r1 = client.post( + f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "一次就好"}} + ) + assert r1.status_code == 200 and r1.json()["reused"] is False + r2 = client.post( + f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "重复点击"}} + ) + assert r2.status_code == 200 + assert r2.json()["reused"] is True + assert r2.json()["job"]["id"] == r1.json()["job"]["id"] + finally: + client.post("/api/jobs/resume") + client.post(f"/api/jobs/{r1.json()['job']['id']}/cancel") + _wait_terminal(client, r1.json()["job"]["id"]) + + +def test_retention_keeps_newest_records_and_prunes_artifacts(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="保留策略用例") + for i in range(7): + fake_comfy.out_name = f"t{i}.png" + r = client.post( + f"/api/workflows/{wf_id}/test", + json={"input_values": {"1": f"第{i}次"}}, + ) + _wait_terminal(client, r.json()["job"]["id"]) + rows = client.get(f"/api/workflows/{wf_id}/tests").json() + assert len(rows) <= 5 + kept_ids = {row["id"] for row in rows} + # 被清掉的旧记录其产物文件也一并删除 + leftovers = [p for p in workflow_test_dir(wf_id).iterdir() if p.suffix == ".png"] + assert all(p.stem.lstrip("t").isdigit() and int(p.stem[1:]) >= 2 for p in leftovers) + assert len(kept_ids) == 5 + + +def test_clear_tests_and_workflow_delete_cascade(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_id = _create_workflow(client, IMAGE_WORKFLOW, name="清理用例") + r = client.post(f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}}) + _wait_terminal(client, r.json()["job"]["id"]) + assert workflow_test_dir(wf_id).is_dir() + + r = client.post(f"/api/workflows/{wf_id}/clear-tests") + assert r.status_code == 200 and r.json()["removed"] >= 1 + assert not workflow_test_dir(wf_id).exists() + assert client.get(f"/api/workflows/{wf_id}/tests").json() == [] + + # 进行中的测试:先拒绝清除,取消后删除工作流级联清理 + assert client.post("/api/jobs/pause").status_code == 200 + try: + job_id = client.post( + f"/api/workflows/{wf_id}/test", json={"input_values": {"1": "p"}} + ).json()["job"]["id"] + r = client.post(f"/api/workflows/{wf_id}/clear-tests") + assert r.status_code == 409 + finally: + client.post("/api/jobs/resume") + client.post(f"/api/jobs/{job_id}/cancel") + _wait_terminal(client, job_id) + + # 工作流列表带出「上次测试」实时状态 + listed = client.get("/api/workflows").json() + mine = [w for w in listed if w["id"] == wf_id][0] + assert mine["last_test"]["id"] == job_id + + assert client.delete(f"/api/workflows/{wf_id}").status_code == 200 + assert not workflow_test_dir(wf_id).exists() + assert client.get(f"/api/workflows/{wf_id}/tests").status_code == 404 + + +def test_last_test_summary_live_on_list(client, fake_comfy): + with _real_run(client, fake_comfy): + wf_a = _create_workflow(client, IMAGE_WORKFLOW, name="A") + wf_b = _create_workflow(client, IMAGE_WORKFLOW, name="B") + r = client.post(f"/api/workflows/{wf_a}/test", json={"input_values": {"1": "p"}}) + done = _wait_terminal(client, r.json()["job"]["id"]) + listed = {w["id"]: w for w in client.get("/api/workflows").json()} + assert listed[wf_a]["last_test"]["status"] == "done" + assert listed[wf_a]["last_test"]["output_count"] == len(done["output_paths"]) + assert listed[wf_b]["last_test"] is None diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 0803c8d2..6f1706f1 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -138,6 +138,8 @@ import type { ComfyDynamicInput, ComfyDynamicOutput, WorkflowOutputMapEntry, + WorkflowConnectionCheck, + WorkflowLastTest, } from "./comfy/types"; export type { Job, @@ -150,6 +152,8 @@ export type { ComfyDynamicInput, ComfyDynamicOutput, WorkflowOutputMapEntry, + WorkflowConnectionCheck, + WorkflowLastTest, }; async function api(path: string, init?: RequestInit): Promise { @@ -458,13 +462,50 @@ export const comfy = { export const workflows = { list: () => api("/api/workflows"), - analyze: (workflow_json: Record) => + analyze: ( + workflow_json: Record, + endpoint_id?: string | null, + refresh = false, + ) => api("/api/workflows/analyze", { method: "POST", - body: JSON.stringify({ workflow_json }), + body: JSON.stringify({ + workflow_json, + ...(endpoint_id ? { endpoint_id } : {}), + ...(refresh ? { refresh } : {}), + }), }), reanalyze: (id: number) => api(`/api/workflows/${id}/reanalyze`, { method: "POST" }), + /** L2 re-check against a live ComfyUI (HEL-643): node/model availability. */ + check: ( + id: number, + payload?: { endpoint_id?: string | null; refresh?: boolean }, + ) => + api(`/api/workflows/${id}/check`, { + method: "POST", + body: JSON.stringify(payload ?? {}), + }), + /** Launch (or re-attach to) one REAL test run (HEL-643 L3). */ + test: ( + id: number, + payload: { + endpoint_id?: string | null; + input_values?: Record; + }, + ) => + api<{ ok: boolean; job: Job; reused: boolean }>( + `/api/workflows/${id}/test`, + { + method: "POST", + body: JSON.stringify(payload), + }, + ), + tests: (id: number) => api(`/api/workflows/${id}/tests`), + clearTests: (id: number) => + api<{ ok: boolean; removed: number }>(`/api/workflows/${id}/clear-tests`, { + method: "POST", + }), create: (payload: { name: string; workflow_json: Record; diff --git a/calliope-web/src/lib/comfy/imageFile.ts b/calliope-web/src/lib/comfy/imageFile.ts index d71f618c..d3d22817 100644 --- a/calliope-web/src/lib/comfy/imageFile.ts +++ b/calliope-web/src/lib/comfy/imageFile.ts @@ -1,26 +1,72 @@ -import { t } from '$lib/i18n.svelte'; +import { t } from "$lib/i18n.svelte"; /** Studio image slots (ref-upload-spec §3): PNG / JPG / WebP, ≤ 20MB each. */ -export const IMAGE_SLOT_ACCEPT = '.png,.jpg,.jpeg,.webp,image/png,image/jpeg,image/webp'; +export const IMAGE_SLOT_ACCEPT = + ".png,.jpg,.jpeg,.webp,image/png,image/jpeg,image/webp"; export const IMAGE_SLOT_MAX_BYTES = 20 * 1024 * 1024; -const IMAGE_EXTS = ['.png', '.jpg', '.jpeg', '.webp']; +const IMAGE_EXTS = [".png", ".jpg", ".jpeg", ".webp"]; + +/** Reference video slots (HEL-643): MP4 / WebM / MOV, ≤ 500MB (upload cap). */ +export const VIDEO_SLOT_ACCEPT = + "video/mp4,video/webm,video/quicktime,.mp4,.webm,.mov"; +export const VIDEO_SLOT_MAX_BYTES = 500 * 1024 * 1024; +const VIDEO_EXTS = [".mp4", ".webm", ".mov"]; + +/** Reference audio slots (HEL-643): MP3 / WAV / M4A, ≤ 100MB. */ +export const AUDIO_SLOT_ACCEPT = + "audio/mpeg,audio/wav,audio/mp4,.mp3,.wav,.m4a"; +export const AUDIO_SLOT_MAX_BYTES = 100 * 1024 * 1024; +const AUDIO_EXTS = [".mp3", ".wav", ".m4a"]; + +export type MediaSlotKind = "image" | "video" | "audio"; + +export function mediaSlotAccept(kind: MediaSlotKind): string { + if (kind === "video") return VIDEO_SLOT_ACCEPT; + if (kind === "audio") return AUDIO_SLOT_ACCEPT; + return IMAGE_SLOT_ACCEPT; +} + +/** Why this file cannot fill a media slot of this kind (null = fine). */ +export function mediaFileProblem( + kind: MediaSlotKind, + file: { name: string; size: number }, +): string | null { + const dot = file.name.lastIndexOf("."); + const ext = dot >= 0 ? file.name.slice(dot).toLowerCase() : ""; + const max = + kind === "video" + ? VIDEO_SLOT_MAX_BYTES + : kind === "audio" + ? AUDIO_SLOT_MAX_BYTES + : IMAGE_SLOT_MAX_BYTES; + if (kind === "video" && !VIDEO_EXTS.includes(ext)) + return t("studio.errVideoFormat", { name: file.name }); + if (kind === "audio" && !AUDIO_EXTS.includes(ext)) + return t("studio.errAudioFormat", { name: file.name }); + if (kind === "image" && !IMAGE_EXTS.includes(ext)) + return t("studio.errImageFormat", { name: file.name }); + if (file.size > max) + return kind === "image" + ? t("studio.errImageSize", { name: file.name }) + : t("studio.errMediaSize", { name: file.name }); + return null; +} /** Why this file cannot fill an image slot (null = fine). */ -export function imageFileProblem(file: { name: string; size: number }): string | null { - const dot = file.name.lastIndexOf('.'); - const ext = dot >= 0 ? file.name.slice(dot).toLowerCase() : ''; - if (!IMAGE_EXTS.includes(ext)) return t('studio.errImageFormat', { name: file.name }); - if (file.size > IMAGE_SLOT_MAX_BYTES) return t('studio.errImageSize', { name: file.name }); - return null; +export function imageFileProblem(file: { + name: string; + size: number; +}): string | null { + return mediaFileProblem("image", file); } export function formatBytes(bytes: number): string { - if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`; - return `${Math.max(1, Math.round(bytes / 1024))} KB`; + if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`; + return `${Math.max(1, Math.round(bytes / 1024))} KB`; } /** Display name of an uploaded path (strips the uuid8- prefix the upload endpoint writes). */ export function uploadBaseName(p: string): string { - const raw = p.split(/[/\\]/).pop() ?? p; - return /^[0-9a-f]{8}-/.test(raw) ? raw.slice(9) : raw; + const raw = p.split(/[/\\]/).pop() ?? p; + return /^[0-9a-f]{8}-/.test(raw) ? raw.slice(9) : raw; } diff --git a/calliope-web/src/lib/comfy/types.ts b/calliope-web/src/lib/comfy/types.ts index 48912c0d..10a2c155 100644 --- a/calliope-web/src/lib/comfy/types.ts +++ b/calliope-web/src/lib/comfy/types.ts @@ -8,7 +8,10 @@ export type ComfyInputKind = | 'audio' | 'video' /** Ordered list of images for one Autogrow input (e.g. H3 ref_images, min…max). */ - | 'image_list'; + | 'image_list' + /** Ordered lists of videos / audios for Autogrow inputs (HEL-643). */ + | 'video_list' + | 'audio_list'; export type ComfyOutputKind = 'image' | 'video' | 'other'; /** Structural finding on an imported workflow; `error` blocks generation. */ @@ -38,6 +41,8 @@ export interface ComfyDynamicInput { options?: string[]; /** On a ResolutionSelector aspect_ratio entry: its megapixels key and rounding multiple. */ resolution?: { megapixels: string; multiple: number }; + /** Official usage-limits hint key for known media groups (HEL-643, e.g. 'minimax_h3_ref2va'). */ + media_hint?: string; } export interface ComfyDynamicOutput { @@ -84,6 +89,40 @@ export const USAGE_BY_KIND: Record<'image' | 'video', WorkflowUsage[]> = { video: ['text2video', 'image2video', 'ref2video'], }; +/** One L2 connection-check finding against a live ComfyUI (HEL-643). */ +export interface PreflightFinding { + level: 'error' | 'warn' | 'info' | 'ok'; + code: string; + node_id?: string; + node_title?: string | null; + message: string; + hint?: string | null; +} + +/** Result of checking a workflow against a target connection's /object_info. */ +export interface WorkflowConnectionCheck { + endpoint_id: string | null; + endpoint_name: string | null; + base_url?: string | null; + /** False when any error-level finding exists (or the server was unreachable). */ + ok: boolean; + /** False → 无法核查 (server down): honest, non-blocking. */ + reachable: boolean; + findings: PreflightFinding[]; + message?: string | null; +} + +/** Slim live record of a workflow's latest test run (HEL-643). */ +export interface WorkflowLastTest { + id: number; + status: string; + phase: string | null; + error: string | null; + created_at: string; + completed_at: string | null; + output_count: number; +} + /** Result of POST /api/workflows/analyze (import confirm step 1). */ export interface WorkflowAnalyzeResult { inputs: ComfyDynamicInput[]; @@ -101,6 +140,8 @@ export interface WorkflowAnalyzeResult { summary: string[]; }; usable_usage: WorkflowUsage[]; + /** Present when analyze was called with a target endpoint (HEL-643 L2). */ + connection_check?: WorkflowConnectionCheck; } export interface WorkflowNode { @@ -130,6 +171,8 @@ export interface Workflow { output_map_source?: 'auto' | 'user' | null; /** True when the graph has unknown output nodes needing designation. */ needs_mapping?: boolean; + /** Latest test-run record, queried live (HEL-643); null = never tested. */ + last_test?: WorkflowLastTest | null; } export interface Job { @@ -152,6 +195,8 @@ export interface Job { comfy_prompt_id?: string | null; /** connecting · comfy_queued · comfy_running · saving · finished · dry_run */ phase?: string | null; + /** 'user' (normal generation) or 'workflow_test' (HEL-643 test run). */ + origin?: string; } export interface SceneVideoSettings { diff --git a/calliope-web/src/lib/components/WorkflowTestDialog.svelte b/calliope-web/src/lib/components/WorkflowTestDialog.svelte new file mode 100644 index 00000000..1e63049b --- /dev/null +++ b/calliope-web/src/lib/components/WorkflowTestDialog.svelte @@ -0,0 +1,579 @@ + + + + {#if wf} +
+

+ {wf.name} + #{wf.id} +

+ + + + {#if hasH3Hint} +
+ +

{t('wfMedia.h3Limits')}

+
+ {/if} + + {#if activeJob} + {@const info = jobStatusInfo(activeJob)} +
+
+ {t('wft.running')} + {info.detail} + +
+
+ {:else if finishedJob && finishedJob.status === 'done' && (finishedJob.output_paths?.length ?? 0) > 0} +
+

{t('wft.passed', { n: finishedJob.output_paths.length })}

+
+ {#each finishedJob.output_paths.slice(0, 4) as path (path)} + + + + {/each} +
+
+ {:else if finishedJob && finishedJob.status !== 'pending' && finishedJob.status !== 'running'} +
+

{t('wft.failed')}

+

{finishedJob.error === 'cancelled' ? t('wft.cancelledShort') : finishedJob.error}

+
+ {/if} + + {#if !queueBusy} +
+ {#each listEntries as entry (entry.nodeId)} + {@const kind = kindOf(entry)} + mediaAdd(entry, files)} + onReplace={(i, file) => mediaReplace(entry, i, file)} + onRemove={(i) => mediaRemove(entry, i)} + onDismissReject={(i) => + setRejects(entry.nodeId, (rejects[entry.nodeId] ?? []).filter((_, j) => j !== i))} + /> + {/each} + {#if formEntries.length} + + {/if} +
+ {#if submitError}{submitError}{/if} +
+ +
+ {/if} + +
+
+ {t('wft.history', { n: history.length })} + {#if history.length} + + {/if} +
+ {#if history.length === 0} +

{t('wft.never')}

+ {:else} +
    + {#each history as job (job.id)} +
  • + #{job.id} + {timeOf(job.created_at)} + 0}> + {resultLine(job)} + +
  • + {/each} +
+ {/if} +
+
+ {/if} +
+ + + + diff --git a/calliope-web/src/lib/components/studio/RefImageGrid.svelte b/calliope-web/src/lib/components/studio/RefImageGrid.svelte index 9164144c..d824183d 100644 --- a/calliope-web/src/lib/components/studio/RefImageGrid.svelte +++ b/calliope-web/src/lib/components/studio/RefImageGrid.svelte @@ -2,14 +2,21 @@ import Icon from '$lib/components/ui/Icon.svelte'; import Spinner from '$lib/components/ui/Spinner.svelte'; import { assetUrl } from '$lib/api'; - import { IMAGE_SLOT_ACCEPT, formatBytes, uploadBaseName } from '$lib/comfy/imageFile'; + import { + IMAGE_SLOT_ACCEPT, + formatBytes, + mediaSlotAccept, + uploadBaseName, + type MediaSlotKind, + } from '$lib/comfy/imageFile'; import { t } from '$lib/i18n.svelte'; /** - * Reference-image grid (ref-upload-spec §2 `.refgrid`): numbered cells - * 参考图 1…N in the order they reach the workflow, each with replace and - * ✕; a dashed add cell while below `max`; rejected files show as error - * cells that take no place in the list. + * Reference-media grid (ref-upload-spec §2 `.refgrid`, generalized to + * image/video/audio in HEL-643): numbered cells 参考图/参考视频/参考音频 + * 1…N in the order they reach the workflow, each with replace and ✕; a + * dashed add cell while below `max`; rejected files show as error cells + * that take no place in the list. */ interface Reject { name: string; @@ -19,6 +26,8 @@ label: string; paths: string[]; max: number; + /** Media family of the slots — drives thumbnails, accept and copy. */ + mediaKind?: MediaSlotKind; /** Byte sizes of files uploaded in this session, by server path. */ sizes?: Record; /** Name of the file being uploaded (add or replace), if any. */ @@ -39,6 +48,7 @@ label, paths, max, + mediaKind = 'image', sizes = {}, uploadingName, uploadingIndex = -1, @@ -57,9 +67,28 @@ let replaceIndex = $state(-1); let dragDepth = $state(0); let dims = $state>({}); + let durations = $state>({}); const uploading = $derived(!!uploadingName); const remaining = $derived(Math.max(0, max - paths.length)); + const accept = $derived(mediaKind === 'image' ? IMAGE_SLOT_ACCEPT : mediaSlotAccept(mediaKind)); + const isMedia = $derived(mediaKind !== 'image'); + const hintLabel = $derived( + isMedia + ? t('studio.refHintMedia', { n: paths.length, max }) + : t('studio.refHint', { n: paths.length, max }), + ); + function durationOf(path: string): string { + const d = durations[path]; + if (d == null || !Number.isFinite(d)) return ''; + return `${d.toFixed(1)}s`; + } + function noteDuration(path: string, e: Event): void { + const el = e.currentTarget as HTMLVideoElement | HTMLAudioElement | null; + if (el && Number.isFinite(el.duration)) { + durations = { ...durations, [path]: el.duration }; + } + } function pickAdd() { if (uploading || !addInput) return; @@ -88,14 +117,16 @@ } function metaOf(path: string): string { - return [dims[path], sizes[path] != null ? formatBytes(sizes[path]) : null].filter(Boolean).join(' · '); + return [dims[path], durationOf(path), sizes[path] != null ? formatBytes(sizes[path]) : null] + .filter(Boolean) + .join(' · '); }
{label}* - {t('studio.refHint', { n: paths.length, max })} + {hintLabel}
{ const files = Array.from(e.currentTarget.files ?? []); @@ -117,14 +148,14 @@ class="sr-file" tabindex="-1" aria-hidden="true" - accept={IMAGE_SLOT_ACCEPT} + accept={accept} onchange={(e) => { const f = e.currentTarget.files?.[0]; if (f && replaceIndex >= 0) onReplace(replaceIndex, f); }} /> -
+
{#each paths as path, i (path + i)}
{/if} @@ -208,7 +262,7 @@ {/if} {#if remaining === 0} - {t('studio.refFull', { max })} + {isMedia ? t('studio.refFullMedia', { max }) : t('studio.refFull', { max })} {/if} {#each rejects as rej, i (rej.name + i)} {rej.message} @@ -223,6 +277,30 @@ gap: 6px; min-width: 0; } + .refgrid.audio { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .refgrid.audio .ref-thumb { + aspect-ratio: auto; + min-height: 64px; + flex-direction: column; + gap: 2px; + padding: 8px 4px; + } + .refgrid.audio audio { + width: 90%; + height: 28px; + } + .refgrid video { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + } + .audio-glyph { + color: var(--text-3); + display: inline-flex; + } .slot-label { display: flex; align-items: baseline; diff --git a/calliope-web/src/lib/components/studio/StudioGenerate.svelte b/calliope-web/src/lib/components/studio/StudioGenerate.svelte index 680f1bf1..20a88601 100644 --- a/calliope-web/src/lib/components/studio/StudioGenerate.svelte +++ b/calliope-web/src/lib/components/studio/StudioGenerate.svelte @@ -7,7 +7,7 @@ import ImageLightbox from '$lib/components/ImageLightbox.svelte'; import MediaSlot from '$lib/components/studio/MediaSlot.svelte'; import RefImageGrid from '$lib/components/studio/RefImageGrid.svelte'; - import { imageFileProblem } from '$lib/comfy/imageFile'; + import { mediaFileProblem } from '$lib/comfy/imageFile'; import { toStore } from 'svelte/store'; import { tick } from 'svelte'; import AppShell from '$lib/components/shell/AppShell.svelte'; @@ -145,6 +145,7 @@ let fileSizes = $state>({}); /** Reference index being replaced while its upload runs. */ let replacingIndex = $state(-1); + let replacingKey = $state(''); let showErrors = $state(false); let submitting = $state(false); let lightboxOpen = $state(false); @@ -212,7 +213,9 @@ inp.kind === 'image_url' || inp.kind === 'video' || inp.kind === 'audio' || - inp.kind === 'image_list'; + inp.kind === 'image_list' || + inp.kind === 'video_list' || + inp.kind === 'audio_list'; // Auto-detected slots carry their role from the wiring; tagged (Input:…) // workflows still name frames only in the title. const isFirstFrame = (inp: ComfyDynamicInput) => @@ -220,14 +223,44 @@ const isLastFrame = (inp: ComfyDynamicInput) => role(inp) === 'last_frame' || (!inp.auto && kind === 'video' && /last|end|尾帧/.test(hay(inp))); + /** Autogrow media lists actually wired in this workflow (HEL-643: image / + * video / audio). No wiring → no entry, whatever the model could do. */ + const listGroups = $derived( + schema.filter( + (i) => i.kind === 'image_list' || i.kind === 'video_list' || i.kind === 'audio_list', + ), + ); + function listKind(entry: ComfyDynamicInput): 'image' | 'video' | 'audio' { + if (entry.kind === 'video_list') return 'video'; + if (entry.kind === 'audio_list') return 'audio'; + return 'image'; + } // ComfyUI Autogrow reference images (H3 ref_images): one ordered 1…max list. - const refGroup = $derived(schema.find((i) => i.kind === 'image_list') ?? null); + const refGroup = $derived(listGroups.find((i) => i.kind === 'image_list') ?? null); const refMax = $derived(refGroup?.max ?? 9); const refPaths = $derived.by(() => { const v = refGroup ? values[refGroup.nodeId] : undefined; if (Array.isArray(v)) return v; return typeof v === 'string' && v ? [v] : []; }); + function groupPaths(entry: ComfyDynamicInput): string[] { + const v = values[entry.nodeId]; + if (Array.isArray(v)) return v; + return typeof v === 'string' && v ? [v] : []; + } + // H3 Ref2VA official limits (soft hint, keyed off the node class only). + const hasH3Hint = $derived(listGroups.some((e) => e.media_hint === 'minimax_h3_ref2va')); + const h3SoftWarnings = $derived.by(() => { + if (!hasH3Hint) return []; + const warns: string[] = []; + const counts = { image: 0, video: 0, audio: 0 }; + for (const g of listGroups) counts[listKind(g)] += groupPaths(g).length; + const total = counts.image + counts.video + counts.audio; + if (total > 12) warns.push(t('wfMedia.h3TotalOver', { n: total })); + if (counts.audio > 0 && counts.image === 0 && counts.video === 0) + warns.push(t('wfMedia.h3AudioAlone')); + return warns; + }); const brokenReasons = $derived( (currentWorkflow?.warnings ?? []).filter((w) => w.level === 'error').map((w) => w.message), ); @@ -271,7 +304,10 @@ } const mediaSlots = $derived.by(() => { - const media = schema.filter((i) => isMedia(i) && i.kind !== 'image_list'); + const media = schema.filter( + (i) => + isMedia(i) && i.kind !== 'image_list' && i.kind !== 'video_list' && i.kind !== 'audio_list', + ); const plainImages = media.filter( (i) => i.kind === 'image' && role(i) !== 'mask' && !/mask|遮罩/.test(hay(i)) && !isFirstFrame(i) && !isLastFrame(i), ); @@ -424,10 +460,17 @@ errs[s.inp.nodeId] = s.missing || t('studio.errUpload', { label: s.label }); } } - if (refGroup) { - if (refPaths.length < (refGroup.min ?? 1)) errs[refGroup.nodeId] = t('studio.errNeedRef'); - else if (refPaths.length > refMax) - errs[refGroup.nodeId] = t('studio.errRefMax', { max: refMax, n: refPaths.length, k: refPaths.length - refMax }); + for (const g of listGroups) { + const n = groupPaths(g).length; + const max = g.max ?? 9; + if (n < (g.min ?? 1)) { + errs[g.nodeId] = + g.kind === 'image_list' + ? t('studio.errNeedRef') + : t('studio.errNeedRefMedia', { n: g.min ?? 1, label: g.label }); + } else if (n > max) { + errs[g.nodeId] = t('studio.errRefMax', { max, n, k: n - max }); + } } for (const inp of restInputs) { if (inp.required && !String(values[inp.nodeId] ?? '').trim()) { @@ -486,12 +529,10 @@ } async function slotFile(nodeId: string, file: File, mediaKind: 'image' | 'video' | 'audio' = 'image') { - if (mediaKind === 'image') { - const problem = imageFileProblem(file); - if (problem) { - setRejects(nodeId, [{ name: file.name, message: problem }]); - return; - } + const problem = mediaFileProblem(mediaKind, file); + if (problem) { + setRejects(nodeId, [{ name: file.name, message: problem }]); + return; } setRejects(nodeId, []); const path = await uploadImage(nodeId, file); @@ -499,46 +540,48 @@ } /** Add picked/dropped files in order; a batch that would pass `max` is refused whole. */ - async function refAdd(files: File[]) { - if (!refGroup) return; - const key = refGroup.nodeId; - const ok = files.filter((f) => !imageFileProblem(f)); + async function groupAdd(entry: ComfyDynamicInput, files: File[]) { + const key = entry.nodeId; + const mk = listKind(entry); + const max = entry.max ?? 9; + const paths = groupPaths(entry); + const ok = files.filter((f) => !mediaFileProblem(mk, f)); const rejected = files - .filter((f) => imageFileProblem(f)) - .map((f) => ({ name: f.name, message: imageFileProblem(f)! })); + .filter((f) => mediaFileProblem(mk, f)) + .map((f) => ({ name: f.name, message: mediaFileProblem(mk, f)! })); setRejects(key, rejected); - if (refPaths.length + ok.length > refMax) { - toast.error(t('studio.errRefMax', { max: refMax, n: refPaths.length, k: ok.length })); + if (paths.length + ok.length > max) { + toast.error(t('studio.errRefMax', { max, n: paths.length, k: ok.length })); return; } for (const f of ok) { const path = await uploadImage(key, f); if (!path) break; - setVal(key, [...refPaths, path]); + setVal(key, [...paths, path]); } } - async function refReplace(index: number, file: File) { - if (!refGroup) return; - const key = refGroup.nodeId; - const problem = imageFileProblem(file); + async function groupReplace(entry: ComfyDynamicInput, index: number, file: File) { + const key = entry.nodeId; + const problem = mediaFileProblem(listKind(entry), file); if (problem) { setRejects(key, [{ name: file.name, message: problem }]); return; } setRejects(key, []); + replacingKey = key; replacingIndex = index; try { const path = await uploadImage(key, file); - if (path) setVal(key, refPaths.map((p, i) => (i === index ? path : p))); + if (path) setVal(key, groupPaths(entry).map((p, i) => (i === index ? path : p))); } finally { + replacingKey = ''; replacingIndex = -1; } } - function refRemove(index: number) { - if (!refGroup) return; - setVal(refGroup.nodeId, refPaths.filter((_, i) => i !== index)); + function groupRemove(entry: ComfyDynamicInput, index: number) { + setVal(entry.nodeId, groupPaths(entry).filter((_, i) => i !== index)); } const imageResults = $derived( @@ -1066,25 +1109,36 @@ {/if} {/if} - {#if refGroup} -
- - setRejects(refGroup.nodeId, (slotRejects[refGroup.nodeId] ?? []).filter((_, j) => j !== i))} - onFromResults={() => openPicker(refGroup.nodeId)} - /> + {#if listGroups.length} +
+ {#each listGroups as entry (entry.nodeId)} + groupAdd(entry, files)} + onReplace={(i, file) => groupReplace(entry, i, file)} + onRemove={(i) => groupRemove(entry, i)} + onDismissReject={(i) => + setRejects(entry.nodeId, (slotRejects[entry.nodeId] ?? []).filter((_, j) => j !== i))} + onFromResults={entry.kind === 'image_list' ? () => openPicker(entry.nodeId) : undefined} + /> + {/each} + {#if hasH3Hint} +
+

{t('wfMedia.h3Limits')}

+ {#each h3SoftWarnings as w (w)} +

{w}

+ {/each} +
+ {/if}
{/if} @@ -1723,6 +1777,26 @@ />