412 lines
17 KiB
Python
412 lines
17 KiB
Python
"""HEL-627: the two workflows the user runs (Qwen Image 2.1 文生图 and
|
||
MiniMax H3 reference 文生视频) expose every widget they really have, the
|
||
values land in the /prompt payload, and a job is only "done" once ComfyUI
|
||
returned real files — empty, failed, lost and placeholder runs never are."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import threading
|
||
import time
|
||
from http.server import ThreadingHTTPServer
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
from calliope.comfyui.parser import (
|
||
RESOLUTION_ASPECT_RATIOS,
|
||
effective_input_schema,
|
||
parse_dynamic_inputs,
|
||
resolution_selector_size,
|
||
)
|
||
from calliope.comfyui.validate import validate_input_values
|
||
from calliope.config import settings
|
||
from calliope.db import get_db
|
||
from tests.test_studio_generation import (
|
||
_FakeComfyHandler,
|
||
_import_workflow,
|
||
_real_run,
|
||
)
|
||
|
||
FIXTURES = Path(__file__).parent / "fixtures" / "comfy_native"
|
||
T2I = "wen_sheng_tu_API.json" # image_qwen_image_2_1_t2i (2).json
|
||
T2V = "wen_sheng_shipin_API.json" # 01_reference_4step_sla (1).json
|
||
|
||
|
||
def _load(name: str) -> dict:
|
||
return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
|
||
|
||
|
||
def _by_role(inputs: list[dict]) -> dict[str, dict]:
|
||
return {i["role"]: i for i in inputs if i.get("role")}
|
||
|
||
|
||
class _StatusHandler(_FakeComfyHandler):
|
||
"""Fake ComfyUI with /queue and scriptable history outcomes."""
|
||
|
||
def do_GET(self):
|
||
srv = self.server
|
||
if self.path == "/queue":
|
||
if srv.queue_mode is None:
|
||
self._json(404, {"error": "not found"})
|
||
return
|
||
self.server.requests.append(self.path)
|
||
items = [[i, pid, {}, {}, []] for i, pid in enumerate(srv.history)]
|
||
if srv.queue_mode == "running":
|
||
self._json(200, {"queue_running": items, "queue_pending": []})
|
||
elif srv.queue_mode == "pending":
|
||
blocker = [[-1, "someone-else", {}, {}, []]]
|
||
self._json(200, {"queue_running": blocker, "queue_pending": items})
|
||
else:
|
||
self._json(200, {"queue_running": [], "queue_pending": []})
|
||
return
|
||
if self.path.startswith("/history/"):
|
||
if srv.lose_history or srv.hidden_history_polls > 0:
|
||
srv.hidden_history_polls = max(0, srv.hidden_history_polls - 1)
|
||
self.server.requests.append(self.path)
|
||
self._json(200, {})
|
||
return
|
||
super().do_GET()
|
||
|
||
def do_POST(self):
|
||
super().do_POST()
|
||
if self.path == "/prompt" and self.server.history_patch:
|
||
for entry in self.server.history.values():
|
||
entry.update(self.server.history_patch)
|
||
|
||
|
||
@pytest.fixture
|
||
def status_comfy():
|
||
server = ThreadingHTTPServer(("127.0.0.1", 0), _StatusHandler)
|
||
server.requests = []
|
||
server.prompts = []
|
||
server.uploads = []
|
||
server.history = {}
|
||
server.fail_prompt = False
|
||
server.out_name = "out-1.png"
|
||
server.outputs_key = "images"
|
||
server.queue_mode = None
|
||
server.lose_history = False
|
||
server.hidden_history_polls = 0
|
||
server.history_patch = None
|
||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||
thread.start()
|
||
try:
|
||
yield server
|
||
finally:
|
||
server.shutdown()
|
||
server.server_close()
|
||
|
||
|
||
def _wait_final(client, job_id: int, timeout: float = 25.0) -> dict:
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
for j in client.get("/api/playground/jobs").json():
|
||
if j["id"] == job_id and j["status"] in ("done", "failed"):
|
||
return j
|
||
time.sleep(0.2)
|
||
raise AssertionError(f"job {job_id} did not finish")
|
||
|
||
|
||
def _generate(client, wf_id: int, values: dict, source: str = "studio-image"):
|
||
return client.post(
|
||
"/api/playground/generate",
|
||
json={
|
||
"workflow_id": wf_id,
|
||
"input_values": values,
|
||
"source": source,
|
||
"endpoint_id": settings.comfyui_active_id,
|
||
},
|
||
)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Parameter detection on the two real workflows
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_real_t2i_exposes_ratio_megapixels_steps_denoise():
|
||
roles = _by_role(parse_dynamic_inputs(_load(T2I)))
|
||
assert set(roles) == {
|
||
"prompt", "negative", "aspect_ratio", "megapixels", "batch",
|
||
"seed", "steps", "cfg", "denoise",
|
||
}
|
||
ratio = roles["aspect_ratio"]
|
||
assert ratio["nodeId"] == "13@aspect_ratio"
|
||
assert ratio["kind"] == "select"
|
||
assert ratio["defaultValue"] == "1:1 (Square)"
|
||
assert ratio["options"] == list(RESOLUTION_ASPECT_RATIOS)
|
||
assert ratio["resolution"] == {"megapixels": "13@megapixels", "multiple": 8}
|
||
assert roles["megapixels"]["defaultValue"] == 1
|
||
assert roles["steps"]["nodeId"] == "459:458@steps"
|
||
assert roles["steps"]["defaultValue"] == 25 and roles["steps"]["integer"] is True
|
||
assert roles["denoise"]["nodeId"] == "459:458@denoise"
|
||
assert (roles["denoise"]["min"], roles["denoise"]["max"]) == (0.0, 1.0)
|
||
# Width/height are wired from ResolutionSelector; they are not faked as
|
||
# free inputs, and the encoder's reference-image `resolution` is not exposed.
|
||
assert "width" not in roles and "height" not in roles
|
||
assert all("resolution" not in i["nodeId"] for i in parse_dynamic_inputs(_load(T2I)))
|
||
|
||
|
||
def test_real_t2v_exposes_ratio_steps_denoise_seed_duration():
|
||
inputs = parse_dynamic_inputs(_load(T2V))
|
||
roles = _by_role(inputs)
|
||
assert set(roles) == {
|
||
"prompt", "aspect_ratio", "megapixels", "steps", "denoise", "seed", "duration",
|
||
}
|
||
assert roles["aspect_ratio"]["defaultValue"] == "16:9 (Widescreen)"
|
||
assert roles["aspect_ratio"]["resolution"]["multiple"] == 32
|
||
assert roles["megapixels"]["defaultValue"] == 0.7
|
||
assert roles["steps"]["nodeId"] == "124@steps" and roles["steps"]["defaultValue"] == 4
|
||
assert roles["seed"]["nodeId"] == "129@noise_seed"
|
||
assert roles["duration"]["nodeId"] == "133" and roles["duration"]["defaultValue"] == 10
|
||
# BasicGuider has no CFG; the frame expression hard-codes 24 fps, so no fps field.
|
||
assert "cfg" not in roles and "fps" not in roles
|
||
|
||
|
||
def test_resolution_matches_comfyui_resolution_selector():
|
||
# The H3 workflow's own title documents 1152x640 for 16:9 · 0.7 MP · ×32.
|
||
assert resolution_selector_size("16:9 (Widescreen)", 0.7, 32) == (1152, 640)
|
||
assert resolution_selector_size("1:1 (Square)", 1, 8) == (1024, 1024)
|
||
assert resolution_selector_size("9:16 (Portrait Widescreen)", 1, 8) == (768, 1368)
|
||
|
||
|
||
def test_validation_rejects_bad_values_in_chinese():
|
||
schema = parse_dynamic_inputs(_load(T2I))
|
||
clean, errors = validate_input_values(
|
||
schema,
|
||
{
|
||
"459:452@prompt": "猫",
|
||
"13@aspect_ratio": "5:4",
|
||
"459:458@steps": 12.5,
|
||
"459:458@denoise": 1.5,
|
||
"13@megapixels": "abc",
|
||
},
|
||
)
|
||
assert any("画面比例" in e and "5:4" in e for e in errors)
|
||
assert any("采样步数" in e and "整数" in e for e in errors)
|
||
assert any("降噪强度" in e and "不能大于 1" in e for e in errors)
|
||
assert any("总像素" in e and "数字" in e for e in errors)
|
||
clean, errors = validate_input_values(schema, {"459:458@steps": "30", "13@megapixels": 2})
|
||
assert errors == [] # an omitted prompt falls back to the workflow's own text
|
||
assert clean["459:458@steps"] == 30 and isinstance(clean["459:458@steps"], int)
|
||
|
||
blank = [dict(e, defaultValue="") if e.get("role") == "prompt" else e for e in schema]
|
||
_, errors = validate_input_values(blank, {"459:452@prompt": " "})
|
||
assert errors == ["请填写「正向提示词」"]
|
||
|
||
|
||
def test_stale_auto_schema_is_refreshed_without_reimport(client):
|
||
wf = _load(T2I)
|
||
stale = [
|
||
{"nodeId": "459:452@prompt", "label": "正向提示词", "role": "prompt",
|
||
"kind": "textarea", "defaultValue": "x", "required": True, "auto": True},
|
||
]
|
||
conn = get_db(settings.db_path)
|
||
try:
|
||
cur = conn.execute(
|
||
"INSERT INTO workflows"
|
||
" (name, kind, workflow_json, input_schema, output_schema, is_enabled)"
|
||
" VALUES (?, 'image', ?, ?, '[]', 1)",
|
||
("旧导入·Qwen2.1", json.dumps(wf), json.dumps(stale)),
|
||
)
|
||
conn.commit()
|
||
wf_id = cur.lastrowid
|
||
finally:
|
||
conn.close()
|
||
roles = _by_role(client.get(f"/api/workflows/{wf_id}").json()["input_schema"])
|
||
assert {"aspect_ratio", "megapixels", "steps", "denoise"} <= set(roles)
|
||
|
||
|
||
def test_tagged_schema_is_kept_as_stored():
|
||
stored = [{"nodeId": "6", "label": "P", "role": "prompt", "kind": "textarea",
|
||
"required": True}]
|
||
assert effective_input_schema(stored, _load(T2I)) == stored
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Submit payload + job status against a fake ComfyUI
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
def test_t2i_values_reach_the_prompt_payload(client, status_comfy):
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(参数)", "image", _load(T2I))
|
||
r = _generate(
|
||
client,
|
||
wf_id,
|
||
{
|
||
"459:452@prompt": "雨夜霓虹街道",
|
||
"459:452@negative_prompt": "模糊",
|
||
"13@aspect_ratio": "16:9 (Widescreen)",
|
||
"13@megapixels": 2,
|
||
"459:458@steps": "30",
|
||
"459:458@cfg": 2.5,
|
||
"459:458@denoise": 0.8,
|
||
"459:458@seed": 7,
|
||
},
|
||
)
|
||
assert r.status_code == 200, r.text
|
||
job = _wait_final(client, r.json()["job"]["id"])
|
||
assert job["status"] == "done", job.get("error")
|
||
queued = status_comfy.prompts[-1]["prompt"]
|
||
assert queued["13"]["inputs"]["aspect_ratio"] == "16:9 (Widescreen)"
|
||
assert queued["13"]["inputs"]["megapixels"] == 2
|
||
assert queued["459:458"]["inputs"]["steps"] == 30
|
||
assert queued["459:458"]["inputs"]["cfg"] == 2.5
|
||
assert queued["459:458"]["inputs"]["denoise"] == 0.8
|
||
assert queued["459:458"]["inputs"]["seed"] == 7
|
||
assert queued["459:452"]["inputs"]["prompt"] == "雨夜霓虹街道"
|
||
# Wiring intact: the latent still takes its size from the selector.
|
||
assert queued["459:456"]["inputs"]["width"] == ["13", 0]
|
||
assert queued["459:456"]["inputs"]["height"] == ["13", 1]
|
||
assert job["comfy_prompt_id"] in status_comfy.history
|
||
assert job["phase"] == "finished"
|
||
assert job["output_paths"] and Path(job["output_paths"][0]).stat().st_size > 0
|
||
|
||
|
||
def test_t2v_values_reach_the_prompt_payload(client, status_comfy):
|
||
status_comfy.outputs_key = "images" # SaveVideo reports under "images" + animated
|
||
status_comfy.out_name = "clip.mp4"
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·H3 参考生视频", "video", _load(T2V))
|
||
r = _generate(
|
||
client,
|
||
wf_id,
|
||
{
|
||
"1": "地铁车厢里的长镜头",
|
||
"115@aspect_ratio": "9:16 (Portrait Widescreen)",
|
||
"115@megapixels": 0.5,
|
||
"124@steps": 6,
|
||
"124@denoise": 1,
|
||
"129@noise_seed": 1234,
|
||
"133": 5,
|
||
},
|
||
source="studio-video",
|
||
)
|
||
assert r.status_code == 200, r.text
|
||
job = _wait_final(client, r.json()["job"]["id"])
|
||
assert job["status"] == "done", job.get("error")
|
||
queued = status_comfy.prompts[-1]["prompt"]
|
||
assert queued["1"]["inputs"]["value"] == "地铁车厢里的长镜头"
|
||
assert queued["115"]["inputs"]["aspect_ratio"] == "9:16 (Portrait Widescreen)"
|
||
assert queued["115"]["inputs"]["megapixels"] == 0.5
|
||
assert queued["124"]["inputs"]["steps"] == 6
|
||
assert queued["129"]["inputs"]["noise_seed"] == 1234
|
||
assert queued["133"]["inputs"]["value"] == 5
|
||
assert queued["132"]["inputs"]["values.a"] == ["133", 0]
|
||
|
||
|
||
def test_invalid_values_are_rejected_before_queueing(client, status_comfy):
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(校验)", "image", _load(T2I))
|
||
r = _generate(client, wf_id, {"459:452@prompt": "猫", "459:458@steps": 0})
|
||
assert r.status_code == 400
|
||
assert "采样步数" in r.json()["detail"] and "不能小于 1" in r.json()["detail"]
|
||
r = _generate(client, wf_id, {"459:452@prompt": "猫", "13@megapixels": 99})
|
||
assert r.status_code == 400 and "总像素" in r.json()["detail"]
|
||
assert "/prompt" not in status_comfy.requests
|
||
|
||
|
||
def test_empty_outputs_never_count_as_done(client, status_comfy):
|
||
status_comfy.history_patch = {"outputs": {}}
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(空结果)", "image", _load(T2I))
|
||
job = _wait_final(client, _generate(client, wf_id, {"459:452@prompt": "猫"}).json()["job"]["id"])
|
||
assert job["status"] == "failed"
|
||
assert "没有返回任何图片、视频、音频或文件" in job["error"]
|
||
assert job["comfy_prompt_id"] and job["comfy_prompt_id"] in job["error"]
|
||
assert job["output_paths"] == []
|
||
|
||
|
||
def test_comfy_execution_error_is_failed_with_reason(client, status_comfy):
|
||
status_comfy.history_patch = {
|
||
"status": {
|
||
"status_str": "error",
|
||
"completed": False,
|
||
"messages": [
|
||
["execution_start", {}],
|
||
["execution_error", {"node_type": "UNETLoader",
|
||
"exception_message": "模型文件不存在"}],
|
||
],
|
||
},
|
||
"outputs": {},
|
||
}
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(执行错)", "image", _load(T2I))
|
||
job = _wait_final(client, _generate(client, wf_id, {"459:452@prompt": "猫"}).json()["job"]["id"])
|
||
assert job["status"] == "failed"
|
||
assert "ComfyUI 执行出错" in job["error"] and "UNETLoader" in job["error"]
|
||
assert "模型文件不存在" in job["error"]
|
||
|
||
|
||
def test_prompt_lost_from_queue_and_history_fails(client, status_comfy):
|
||
status_comfy.lose_history = True
|
||
status_comfy.queue_mode = "missing"
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(丢失)", "image", _load(T2I))
|
||
job = _wait_final(client, _generate(client, wf_id, {"459:452@prompt": "猫"}).json()["job"]["id"])
|
||
assert job["status"] == "failed"
|
||
assert "队列和历史里都找不到该任务" in job["error"]
|
||
|
||
|
||
def test_running_then_finished_reports_real_phase(client, status_comfy):
|
||
status_comfy.queue_mode = "running"
|
||
status_comfy.hidden_history_polls = 3
|
||
with _real_run(client, status_comfy):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(执行中)", "image", _load(T2I))
|
||
job_id = _generate(client, wf_id, {"459:452@prompt": "猫"}).json()["job"]["id"]
|
||
seen: set[str] = set()
|
||
deadline = time.time() + 20
|
||
while time.time() < deadline:
|
||
row = next(j for j in client.get("/api/playground/jobs").json() if j["id"] == job_id)
|
||
if row.get("phase"):
|
||
seen.add(row["phase"])
|
||
if row["status"] in ("done", "failed"):
|
||
break
|
||
time.sleep(0.1)
|
||
assert row["status"] == "done", row.get("error")
|
||
assert "comfy_running" in seen
|
||
assert "/queue" in status_comfy.requests
|
||
|
||
|
||
def test_missing_model_rejection_names_the_file():
|
||
"""Body captured from the user's ComfyUI 0.37.4 when Qwen 2.1 models are absent."""
|
||
import httpx
|
||
|
||
from calliope.comfyui.client import _surface_error
|
||
|
||
body = {
|
||
"error": {"type": "prompt_outputs_failed_validation"},
|
||
"node_errors": {
|
||
"459:451": {
|
||
"errors": [{
|
||
"type": "value_not_in_list",
|
||
"message": "Value not in list",
|
||
"details": "unet_name: 'qwen_image_2.1_int8_convrot.safetensors' not in [...]",
|
||
"extra_info": {
|
||
"input_name": "unet_name",
|
||
"received_value": "qwen_image_2.1_int8_convrot.safetensors",
|
||
},
|
||
}],
|
||
"class_type": "UNETLoader",
|
||
}
|
||
},
|
||
}
|
||
msg = str(_surface_error("ComfyUI 拒绝执行该工作流", httpx.Response(400, json=body)))
|
||
assert "节点 459:451(UNETLoader)" in msg
|
||
assert "qwen_image_2.1_int8_convrot.safetensors" in msg and "模型文件未安装" in msg
|
||
|
||
|
||
def test_dry_run_result_is_marked_placeholder(client):
|
||
wf_id = _import_workflow(client, "真实·Qwen2.1(dry)", "image", _load(T2I))
|
||
prev = settings.dry_run
|
||
settings.dry_run = True
|
||
try:
|
||
job = _wait_final(client, _generate(client, wf_id, {"459:452@prompt": "猫"}).json()["job"]["id"])
|
||
finally:
|
||
settings.dry_run = prev
|
||
assert job["status"] == "done"
|
||
assert job["phase"] == "dry_run"
|
||
assert job["comfy_prompt_id"] is None
|