fix(HEL-627): 补齐真实工作流参数并修正虚假完成
- 解析 ResolutionSelector 比例/总像素、KSampler/BasicScheduler 降噪,附带 ComfyUI 取值范围 - 已导入的自动识别工作流读取时按最新规则重新解析,无需重导 - 提交前后端校验参数(中文原因),非法值 400 拒绝不入队 - 任务新增 phase / comfy_prompt_id:连接中→已接收(前方排队)→执行中→保存中→完成 - 空产出、队列与历史都丢失、执行中断均判失败;Dry-run 结果标为占位,不算完成 - ComfyUI 缺模型报错写明缺哪个文件 - 生图/生视频/任务页统一用 jobStatusInfo 展示真实状态,结果区支持复用参数 Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
co-authored by
Cursor
multica-agent
parent
0031a897d7
commit
60c043db7c
@@ -19,7 +19,8 @@ class QueueManager:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
cur = conn.execute(
|
||||
"UPDATE jobs SET status = 'pending', started_at = NULL WHERE status = 'running'"
|
||||
"UPDATE jobs SET status = 'pending', started_at = NULL, phase = NULL, "
|
||||
"comfy_prompt_id = NULL WHERE status = 'running'"
|
||||
)
|
||||
conn.commit()
|
||||
return cur.rowcount
|
||||
@@ -105,6 +106,20 @@ class QueueManager:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def set_phase(self, job_id: int, phase: str, comfy_prompt_id: str | None = None) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
if comfy_prompt_id:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET phase = ?, comfy_prompt_id = ? WHERE id = ?",
|
||||
(phase, comfy_prompt_id, job_id),
|
||||
)
|
||||
else:
|
||||
conn.execute("UPDATE jobs SET phase = ? WHERE id = ?", (phase, job_id))
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def mark_done(self, job_id: int, output_paths: list[str]) -> None:
|
||||
conn = get_db(config.settings.db_path)
|
||||
try:
|
||||
@@ -142,7 +157,7 @@ class QueueManager:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE jobs SET status = 'pending', error = NULL, started_at = NULL,
|
||||
completed_at = NULL WHERE id = ?
|
||||
completed_at = NULL, phase = NULL, comfy_prompt_id = NULL WHERE id = ?
|
||||
""",
|
||||
(job_id,),
|
||||
)
|
||||
|
||||
@@ -8,6 +8,8 @@ from typing import Any
|
||||
|
||||
from pathlib import Path as _fs_path
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope import config
|
||||
from calliope.comfyui.client import ComfyUIClient
|
||||
from calliope.comfyui.dry_run import write_placeholder_mp4, write_placeholder_png
|
||||
@@ -26,12 +28,22 @@ def _comfy_messages(messages: list[Any]) -> str:
|
||||
"""Pull the readable part out of ComfyUI's history status messages."""
|
||||
parts: list[str] = []
|
||||
for msg in messages:
|
||||
if isinstance(msg, (list, tuple)) and len(msg) == 2 and msg[0] == "execution_error":
|
||||
body = msg[1] if isinstance(msg[1], dict) else {}
|
||||
node = body.get("node_type") or body.get("node_id") or "?"
|
||||
if not (isinstance(msg, (list, tuple)) and len(msg) == 2):
|
||||
continue
|
||||
body = msg[1] if isinstance(msg[1], dict) else {}
|
||||
node = body.get("node_type") or body.get("node_id") or "?"
|
||||
if msg[0] == "execution_error":
|
||||
reason = body.get("exception_message") or body.get("exception_type") or "未知错误"
|
||||
parts.append(f"节点 {node}:{str(reason).strip()}")
|
||||
return ";".join(parts) or str(messages)[:500]
|
||||
elif msg[0] == "execution_interrupted":
|
||||
parts.append(f"任务在节点 {node} 处被中断(在 ComfyUI 端被取消,或 ComfyUI 已重启)")
|
||||
return ";".join(parts) or "ComfyUI 未给出原因"
|
||||
|
||||
|
||||
# /queue lookups that must agree before a prompt counts as lost, and /history
|
||||
# or /queue request failures in a row before the job gives up.
|
||||
_MISSING_POLLS_LIMIT = 3
|
||||
_POLL_ERRORS_LIMIT = 5
|
||||
|
||||
|
||||
class _CancelledByUser(RuntimeError):
|
||||
@@ -91,6 +103,7 @@ class QueueWorker:
|
||||
job_payload = json.loads(job["payload_json"] or "{}")
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
job_payload = {}
|
||||
row = queue_manager.get_job(job["id"]) or {}
|
||||
await event_bus.publish(
|
||||
"job.completed",
|
||||
{
|
||||
@@ -102,6 +115,9 @@ class QueueWorker:
|
||||
# Source stamp lets the UI attribute sandbox jobs
|
||||
# to their enqueuer without racing the jobs poll.
|
||||
"source": job_payload.get("source"),
|
||||
"comfy_prompt_id": row.get("comfy_prompt_id"),
|
||||
# Placeholder output — ComfyUI was never called.
|
||||
"dry_run": row.get("phase") == "dry_run",
|
||||
"message": f"{self._job_label(job)} · {len(outputs)} file(s)",
|
||||
},
|
||||
)
|
||||
@@ -167,8 +183,10 @@ class QueueWorker:
|
||||
client = ComfyUIClient(base_url, headers=headers)
|
||||
try:
|
||||
if use_dry:
|
||||
queue_manager.set_phase(job["id"], "dry_run")
|
||||
return await self._dry_run(job, payload)
|
||||
|
||||
queue_manager.set_phase(job["id"], "connecting")
|
||||
healthy = await client.health()
|
||||
if not healthy:
|
||||
raise RuntimeError(
|
||||
@@ -191,21 +209,42 @@ class QueueWorker:
|
||||
patched = patch_workflow(workflow, input_values)
|
||||
patched = await client.prepare_media_inputs(patched)
|
||||
prompt_id = await client.queue_prompt(patched)
|
||||
queue_manager.set_phase(job["id"], "comfy_queued", prompt_id)
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job["id"],
|
||||
"prompt_id": prompt_id,
|
||||
"phase": "comfy_queued",
|
||||
"message": f"ComfyUI 已接收任务(ID {prompt_id})",
|
||||
},
|
||||
)
|
||||
|
||||
history = await self._poll_history(client, prompt_id, job["id"])
|
||||
if not history:
|
||||
if queue_manager.is_cancelled(job["id"]):
|
||||
raise _CancelledByUser()
|
||||
raise RuntimeError(
|
||||
"等待 ComfyUI 出结果超时:可在「设置 → 队列」调大超时,或到 ComfyUI 检查该任务"
|
||||
f"等待 ComfyUI 出结果超时(任务 ID {prompt_id}):可在「设置 → 队列」调大超时,"
|
||||
"或到 ComfyUI 检查该任务"
|
||||
)
|
||||
|
||||
status = history.get("status") or {}
|
||||
if status.get("status_str") == "error" or status.get("completed") is False:
|
||||
messages = status.get("messages") or []
|
||||
raise RuntimeError(f"ComfyUI 执行出错:{_comfy_messages(messages)}")
|
||||
raise RuntimeError(
|
||||
f"ComfyUI 执行出错(任务 ID {prompt_id}):{_comfy_messages(messages)}"
|
||||
)
|
||||
|
||||
outputs_meta = client.extract_outputs(history)
|
||||
saved = [m for m in outputs_meta if m.get("type") == "output"]
|
||||
outputs_meta = saved or outputs_meta
|
||||
if not outputs_meta:
|
||||
raise RuntimeError(
|
||||
f"ComfyUI 显示任务已结束(任务 ID {prompt_id}),但没有返回任何图片或视频,"
|
||||
"不算生成完成。请确认工作流带有保存/预览节点,并到 ComfyUI 历史中核对该任务。"
|
||||
)
|
||||
queue_manager.set_phase(job["id"], "saving")
|
||||
dest_dir = config.settings.assets_dir / str(project_id) / kind
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
paths: list[str] = []
|
||||
@@ -221,6 +260,7 @@ class QueueWorker:
|
||||
paths.append(str(dest))
|
||||
|
||||
self._apply_outputs_to_entities(job, payload, paths)
|
||||
queue_manager.set_phase(job["id"], "finished")
|
||||
return paths
|
||||
finally:
|
||||
await client.close()
|
||||
@@ -360,6 +400,9 @@ class QueueWorker:
|
||||
# configurable (default 30 min) instead of a hardcoded 600 seconds.
|
||||
attempts = None if timeout <= 0 else int(timeout / interval)
|
||||
n = 0
|
||||
phase = "comfy_queued"
|
||||
missing = 0
|
||||
errors = 0
|
||||
while attempts is None or n < attempts:
|
||||
n += 1
|
||||
if self._stop.is_set():
|
||||
@@ -370,17 +413,51 @@ class QueueWorker:
|
||||
if queue_manager.is_cancelled(job_id):
|
||||
await client.interrupt()
|
||||
return None
|
||||
history = await client.get_history(prompt_id)
|
||||
if history:
|
||||
return history
|
||||
await asyncio.sleep(interval)
|
||||
try:
|
||||
history = await client.get_history(prompt_id)
|
||||
if history:
|
||||
return history
|
||||
where, ahead = await client.locate_prompt(prompt_id)
|
||||
except httpx.HTTPError as exc:
|
||||
errors += 1
|
||||
if errors >= _POLL_ERRORS_LIMIT:
|
||||
raise RuntimeError(
|
||||
f"连续 {errors} 次无法从 ComfyUI 查询任务状态(任务 ID {prompt_id}):"
|
||||
f"{exc or type(exc).__name__}"
|
||||
) from exc
|
||||
await asyncio.sleep(interval)
|
||||
continue
|
||||
errors = 0
|
||||
if where == "missing":
|
||||
missing += 1
|
||||
if missing >= _MISSING_POLLS_LIMIT:
|
||||
raise RuntimeError(
|
||||
f"ComfyUI 的队列和历史里都找不到该任务(任务 ID {prompt_id}),"
|
||||
"可能 ComfyUI 已重启或任务被清除,没有产出结果"
|
||||
)
|
||||
else:
|
||||
missing = 0
|
||||
if where == "running":
|
||||
phase = "comfy_running"
|
||||
message = f"ComfyUI 正在执行(任务 ID {prompt_id})"
|
||||
elif where == "pending":
|
||||
phase = "comfy_queued"
|
||||
message = f"ComfyUI 排队中,前面还有 {ahead} 个任务(任务 ID {prompt_id})"
|
||||
else:
|
||||
message = f"等待 ComfyUI 返回结果(任务 ID {prompt_id})"
|
||||
if job_id is not None:
|
||||
queue_manager.set_phase(job_id, phase)
|
||||
await event_bus.publish(
|
||||
"job.progress",
|
||||
{
|
||||
"job_id": job_id,
|
||||
"prompt_id": prompt_id,
|
||||
"message": f"Waiting on ComfyUI ({prompt_id[:8]}…)",
|
||||
"phase": phase,
|
||||
"queue_ahead": ahead if where == "pending" else None,
|
||||
"message": message,
|
||||
},
|
||||
)
|
||||
await asyncio.sleep(interval)
|
||||
return None
|
||||
|
||||
def _mark_project_completed(self, project_id: int) -> None:
|
||||
|
||||
Reference in New Issue
Block a user