Files
aigc-home/calliope-backend/src/calliope/routers/workbench.py
T
总工andmultica-agent 06b15dc3b6 feat: five-stage creation workbench (HEL-614)
- backend: project_stages/stage_runs tables; /api/workbench router
  (overview, run agent with confirmed-upstream context only, edit draft,
  confirm, restore, script import, in-flow image/video generation via the
  shared queue with source=workbench); project stats gain real
  stage_confirmed/stage_status/active_jobs
- frontend: /workbench picker + /workbench/[id] five-stage page (stepper,
  per-stage editors, style direction chooser, storyboard table, asset
  prompt cards with in-flow generation, shot video prompts with player,
  agent + task side rail); nav 创作工作台 now opens it; home entries go
  through the workbench (导入剧本 skips 剧本创作); project cards show
  real five-stage progress; i18n keys in all seven dictionaries
- tests: 9 backend workbench tests (flow handoff, edit/confirm/restore,
  import, generation, Chinese failure states)

Co-authored-by: multica-agent <github@multica.ai>
2026-09-28 13:30:19 +08:00

917 lines
37 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Five-stage creation workbench (HEL-614).
剧本创作 → 视觉设计 → 分镜设计 → 素材资产 → 镜头脚本 — one project, five
named agents in sequence. Each stage holds a working draft the user can edit
(``content_json``) and the last confirmed snapshot
(``confirmed_content_json``); only confirmed snapshots flow into the next
agent's context, so an unconfirmed draft is never treated as final.
Stage runs reuse the HEL-613 registry (persona + llm_role + skill bindings)
with a workbench-specific mode prompt and a per-stage JSON artifact schema.
In-flow generation reuses the HEL-612 shared queue: jobs are project-linked
with ``payload.source = "workbench"`` so tasks and results come back to the
project (and the tasks page) like every other job.
"""
from __future__ import annotations
import asyncio
import json
import re
from typing import Any, Literal
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from calliope import config
from calliope.agent.agents_registry import AGENTS, AGENT_KEYS
from calliope.agent.llm import LLMClient, extract_json
from calliope.agent.skills_store import effective_skill_dirs, list_skills
from calliope.comfyui.parser import parse_dynamic_inputs
from calliope.comfyui.smart_fill import smart_fill_inputs
from calliope.db import get_db, row_to_dict
from calliope.events.bus import event_bus
from calliope.queue.manager import queue_manager
router = APIRouter()
STAGE_KEYS: tuple[str, ...] = AGENT_KEYS # script, style, storyboard, assets, shot
StageKey = Literal["script", "style", "storyboard", "assets", "shot"]
WORKBENCH_SOURCE = "workbench"
class StagePatch(BaseModel):
content: dict[str, Any]
chosen_style_id: str | None = None
class StageRunRequest(BaseModel):
instruction: str | None = Field(default=None, max_length=8000)
class StageConfirmRequest(BaseModel):
chosen_style_id: str | None = None
class ScriptImportRequest(BaseModel):
text: str = Field(min_length=1, max_length=200_000)
class WorkbenchGenerateRequest(BaseModel):
kind: Literal["image", "video"]
stage_key: StageKey
target_id: str | None = Field(default=None, max_length=64)
prompt: str = Field(min_length=1, max_length=8000)
negative_prompt: str | None = Field(default=None, max_length=2000)
duration_sec: float | None = None
# ─────────────────────────────────────────────────────────────────────────
# Content normalization — one defensive normalizer per stage. Accepts mild
# LLM shape drift, fills defaults, rejects unusable output with a Chinese
# reason that surfaces on the run row.
# ─────────────────────────────────────────────────────────────────────────
class StageContentError(ValueError):
"""Unusable artifact content; str(err) is user-facing Chinese."""
def _text(value: Any) -> str:
return str(value if value is not None else "").strip()
def _num(value: Any, default: float) -> float:
try:
out = float(value)
except (TypeError, ValueError):
return default
return out if out > 0 else default
def _slug_id(prefix: str, index: int) -> str:
return f"{prefix}{index + 1}"
def _norm_script(data: dict[str, Any]) -> dict[str, Any]:
text = _text(data.get("text") or data.get("script") or data.get("content"))
if len(text) < 30:
raise StageContentError("剧本内容太短(不足 30 字),请重试或在下方手动补充。")
return {"text": text}
def _norm_style(data: dict[str, Any]) -> dict[str, Any]:
raw = data.get("directions") or data.get("styles") or []
if not isinstance(raw, list):
raise StageContentError("风格数据格式不正确,缺少风格方向列表。")
directions = []
used_ids: set[str] = set()
for i, item in enumerate(raw):
if not isinstance(item, dict):
continue
name = _text(item.get("name") or item.get("title"))
prompt = _text(item.get("prompt") or item.get("keywords"))
if not name or not prompt:
continue
sid = _text(item.get("id"))
if not sid or sid in used_ids:
sid = _slug_id("style", i)
n = 2
while sid in used_ids:
sid = f"style{i + 1}-{n}"
n += 1
used_ids.add(sid)
directions.append(
{
"id": sid,
"name": name,
"description": _text(item.get("description")),
"prompt": prompt,
"negative_prompt": _text(item.get("negative_prompt")),
}
)
if len(directions) < 2:
raise StageContentError("风格方向不足 2 套。请让智能体重试,或手动补充更多方向。")
return {"directions": directions}
def _norm_storyboard(data: dict[str, Any]) -> dict[str, Any]:
raw = data.get("shots") or data.get("storyboard") or []
if not isinstance(raw, list):
raise StageContentError("分镜数据格式不正确,缺少逐镜列表。")
shots = []
for i, item in enumerate(raw):
if not isinstance(item, dict):
continue
description = _text(item.get("description") or item.get("action") or item.get("content"))
if not description:
continue
shots.append(
{
"id": _text(item.get("id")) or _slug_id("shot", i),
"scene": _text(item.get("scene")) or f"{i + 1}",
"shot_size": _text(item.get("shot_size") or item.get("size")) or "中景",
"camera": _text(item.get("camera") or item.get("movement")) or "固定",
"description": description,
"dialog": _text(item.get("dialog") or item.get("dialogue")),
"duration_sec": _num(item.get("duration_sec") or item.get("duration"), 3.0),
}
)
if not shots:
raise StageContentError("分镜表为空。请让智能体重试,或手动添加镜头。")
return {"shots": shots}
def _norm_assets(data: dict[str, Any]) -> dict[str, Any]:
raw = data.get("assets") or data.get("items") or []
if not isinstance(raw, list):
raise StageContentError("素材数据格式不正确,缺少资产列表。")
assets = []
for i, item in enumerate(raw):
if not isinstance(item, dict):
continue
name = _text(item.get("name") or item.get("title"))
prompt = _text(item.get("prompt"))
if not name or not prompt:
continue
kind = _text(item.get("kind") or item.get("type"))
if kind not in ("character", "location", "prop"):
kind = "prop"
assets.append(
{
"id": _text(item.get("id")) or _slug_id("asset", i),
"kind": kind,
"name": name,
"description": _text(item.get("description")),
"prompt": prompt,
"negative_prompt": _text(item.get("negative_prompt")),
}
)
if not assets:
raise StageContentError("素材清单为空。请让智能体重试,或手动添加素材。")
return {"assets": assets}
def _norm_shot(data: dict[str, Any]) -> dict[str, Any]:
raw = data.get("shots") or []
if not isinstance(raw, list):
raise StageContentError("镜头脚本数据格式不正确,缺少逐镜列表。")
shots = []
for i, item in enumerate(raw):
if not isinstance(item, dict):
continue
prompt = _text(item.get("prompt") or item.get("video_prompt"))
if not prompt:
continue
shots.append(
{
"id": _text(item.get("id")) or _slug_id("vshot", i),
"shot_no": _text(item.get("shot_no") or item.get("shot")) or _slug_id("S", i),
"description": _text(item.get("description")),
"prompt": prompt,
"duration_sec": _num(item.get("duration_sec") or item.get("duration"), 5.0),
}
)
if not shots:
raise StageContentError("镜头脚本为空。请让智能体重试,或手动添加镜头。")
return {"shots": shots}
NORMALIZERS = {
"script": _norm_script,
"style": _norm_style,
"storyboard": _norm_storyboard,
"assets": _norm_assets,
"shot": _norm_shot,
}
# Short artifact brief embedded in each run prompt (Chinese; keeps the five
# agents' deliverables aligned with what the workbench UI renders).
STAGE_BRIEFS = {
"script": (
"产出完整可拍摄的短视频剧本:故事大纲、按场次展开的分场(场景/时间/地点/人物)、"
"人物小传要点、逐场台词与动作描述。直接输出剧本正文,不要写「好的」之类的客套话。"
),
"style": (
"给出至少 2 套(建议 3 套)差异化视觉风格方向,每套包含:风格名称、中文风格说明"
"(色调/光影/材质/线条)、可直接用于生图模型的英文正向提示词词组(逗号分隔)、"
"可选的英文负面提示词。提示词词组必须完整可复制。"
),
"storyboard": (
"把剧本拆成逐镜分镜表,每镜包含:场次、景别(远/全/中/近/特写)、运镜"
"(推/拉/摇/移/跟/固定)、画面内容描述、台词或音效起点、建议时长(秒)。"
"重要情绪点给特写,节奏有起伏。"
),
"assets": (
"结合剧本、已确认的视觉风格与分镜表,整理需要生图的资产清单(角色/场景/道具),"
"每项资产给出:类型、名称、中文说明、完整可直接复制的英文生图提示词"
"(主体外观细节+风格关键词+构图视角+画质词)、可选负面提示词。"
"同一角色要保持跨视角一致性。"
),
"shot": (
"把分镜表转化为视频生成模型(如 MiniMax H3)可用的逐镜脚本,每镜包含:镜号、"
"中文画面说明、完整可直接复制的英文视频提示词(主体与动作+运镜指令+镜头语言+"
"光影氛围)、建议时长(秒)。同一项目运镜与风格保持一致。"
),
}
def _stage_name(stage_key: str) -> str:
return AGENTS[stage_key]["name"] if stage_key in AGENTS else stage_key
# ─────────────────────────────────────────────────────────────────────────
# DB helpers
# ─────────────────────────────────────────────────────────────────────────
def _get_project(conn, project_id: int) -> dict[str, Any]:
row = conn.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
if not row or row["status"] == "system":
raise HTTPException(status_code=404, detail="项目不存在")
return row_to_dict(row)
def _ensure_stage_rows(conn, project_id: int) -> None:
for key in STAGE_KEYS:
conn.execute(
"INSERT OR IGNORE INTO project_stages (project_id, stage_key) VALUES (?, ?)",
(project_id, key),
)
conn.commit()
def _load_stage(conn, project_id: int, stage_key: str) -> dict[str, Any]:
row = conn.execute(
"SELECT * FROM project_stages WHERE project_id = ? AND stage_key = ?",
(project_id, stage_key),
).fetchone()
if not row:
raise HTTPException(status_code=404, detail="阶段不存在")
return row_to_dict(row)
def _stage_public(row: dict[str, Any]) -> dict[str, Any]:
return {
"stage_key": row["stage_key"],
"status": row["status"],
"content": json.loads(row["content_json"]) if row["content_json"] else None,
"confirmed_content": (
json.loads(row["confirmed_content_json"]) if row["confirmed_content_json"] else None
),
"chosen_style_id": row["chosen_style_id"],
"draft_edited": bool(row["draft_edited"]),
"error": row["error"],
"updated_at": row["updated_at"],
}
def _last_run(conn, project_id: int, stage_key: str) -> dict[str, Any] | None:
row = conn.execute(
"SELECT * FROM stage_runs WHERE project_id = ? AND stage_key = ? "
"ORDER BY id DESC LIMIT 1",
(project_id, stage_key),
).fetchone()
if not row:
return None
return {
"id": row["id"],
"status": row["status"],
"error": row["error"],
"instruction": row["instruction"],
"created_at": row["created_at"],
"completed_at": row["completed_at"],
}
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
def _workbench_job_outputs(conn, project_id: int) -> dict[str, dict[str, Any]]:
"""target_id → latest workbench job (any status) for asset/shot panels."""
rows = conn.execute(
"SELECT * FROM jobs WHERE project_id = ? ORDER BY id ASC",
(project_id,),
).fetchall()
out: dict[str, dict[str, Any]] = {}
for row in rows:
job = _job_public(row_to_dict(row))
payload = job.get("payload") or {}
if payload.get("source") != WORKBENCH_SOURCE:
continue
target = payload.get("target_id")
if not target:
continue
prev = out.get(target)
# later rows win; keep the newest per target
if prev is None or int(job["id"]) > int(prev["id"]):
out[target] = job
return out
def _enrich_stage(
stage: dict[str, Any], outputs: dict[str, dict[str, Any]]
) -> dict[str, Any]:
content = stage.get("content") or {}
if stage["stage_key"] == "assets" and isinstance(content.get("assets"), list):
for asset in content["assets"]:
job = outputs.get(asset.get("id"))
if job:
asset["job"] = _job_brief(job)
elif stage["stage_key"] == "shot" and isinstance(content.get("shots"), list):
for shot in content["shots"]:
job = outputs.get(shot.get("id"))
if job:
shot["job"] = _job_brief(job)
return stage
def _job_brief(job: dict[str, Any]) -> dict[str, Any]:
return {
"id": job["id"],
"status": job["status"],
"kind": job["kind"],
"output": (job.get("output_paths") or [None])[0],
"error": job.get("error"),
}
# ─────────────────────────────────────────────────────────────────────────
# Stage-run prompt assembly + background execution
# ─────────────────────────────────────────────────────────────────────────
_SKILL_BODY_MAX_CHARS = 1600
_SKILL_BODY_MAX_COUNT = 3
def _skills_context(agent_key: str) -> str:
try:
effective = effective_skill_dirs(agent_key)
skills = [s for s in list_skills(cap=None) if s["dir"] in effective]
except Exception:
return ""
if not skills:
return ""
lines = ["以下 Skill 已分配给该智能体(用户配置),生成时请吸收其要点:"]
shown = 0
for skill in skills:
lines.append(f"- {skill['name']}: {skill['description']}")
if shown >= _SKILL_BODY_MAX_COUNT:
continue
body = _skill_body(skill["dir"])
if body:
lines.append(f" {skill['name']} 内容摘要:\n{body}")
shown += 1
return "\n".join(lines)
def _skill_body(skill_dir: str) -> str:
from calliope.agent.skills_store import skills_root
path = skills_root() / skill_dir / "SKILL.md"
try:
text = path.read_text(encoding="utf-8")
except OSError:
return ""
text = re.sub(r"^---.*?---\s*", "", text, flags=re.S)
text = text.strip()
if len(text) > _SKILL_BODY_MAX_CHARS:
text = text[:_SKILL_BODY_MAX_CHARS] + "…"
return text
def _system_prompt(stage_key: str) -> str:
agent = AGENTS[stage_key]
idx = STAGE_KEYS.index(stage_key) + 1
parts = [
agent["persona"],
(
f"WORKBENCH MODE: 你正在「创作工作台」五段流程中负责第 {idx} 段「{agent['name']}」。"
"本次输出会被程序解析入库并在工作台展示给用户编辑、确认,因此:\n"
"- 只输出一个 JSON 对象,不要加 Markdown 代码围栏,不要输出 JSON 以外的任何文字。\n"
"- 严格遵守用户消息末尾给出的 JSON 结构与字段要求,中文内容用中文写,"
"提示词词组按各段惯例(英文逗号分隔)。\n"
"- 这是正式交付物:内容要完整、具体、可直接使用,不要输出占位符或「待补充」。"
),
f"本段任务:{STAGE_BRIEFS[stage_key]}",
]
skills_ctx = _skills_context(stage_key)
if skills_ctx:
parts.append(skills_ctx)
return "\n\n".join(parts)
def _stage_context(conn, project_id: int, stage_key: str) -> str:
"""Confirmed upstream artifacts only — drafts never leak downstream."""
project = _get_project(conn, project_id)
blocks: list[str] = [f"项目名称:{project['title']}"]
if project.get("idea") and stage_key != "script":
idea = _text(project["idea"])
if len(idea) <= 600:
blocks.append(f"用户创意:{idea}")
rows = conn.execute(
"SELECT * FROM project_stages WHERE project_id = ?",
(project_id,),
).fetchall()
stages = {r["stage_key"]: row_to_dict(r) for r in rows}
def confirmed(key: str) -> dict[str, Any] | None:
row = stages.get(key)
if not row or row["status"] != "confirmed" or not row["confirmed_content_json"]:
return None
return json.loads(row["confirmed_content_json"])
script = confirmed("script")
if script and stage_key in ("style", "storyboard", "assets", "shot"):
blocks.append(f"【已确认的剧本】\n{_text(script.get('text'))}")
style = confirmed("style")
if style and stage_key in ("storyboard", "assets", "shot"):
chosen_id = stages.get("style", {}).get("chosen_style_id")
directions = style.get("directions") or []
chosen = next(
(d for d in directions if d.get("id") == chosen_id), directions[0] if directions else None
)
if chosen:
blocks.append(
"【已确认的视觉风格】\n"
f"{chosen.get('name')}:{chosen.get('description') or ''}\n"
f"风格关键词:{chosen.get('prompt')}"
)
else:
names = "、".join(d.get("name", "") for d in directions)
blocks.append(f"【已确认的视觉风格】候选方向:{names}")
board = confirmed("storyboard")
if board and stage_key in ("assets", "shot"):
lines = []
for i, shot in enumerate(board.get("shots") or [], 1):
lines.append(
f"{i}. 场次{shot.get('scene')}|{shot.get('shot_size')}|{shot.get('camera')}|"
f"{shot.get('description')}"
+ (f"|台词:{shot.get('dialog')}" if shot.get("dialog") else "")
)
blocks.append("【已确认的分镜表】\n" + "\n".join(lines))
assets = confirmed("assets")
if assets and stage_key == "shot":
lines = [
f"- {a.get('kind')}|{a.get('name')}:{a.get('description') or a.get('prompt')}"
for a in assets.get("assets") or []
]
blocks.append("【已确认的素材清单】\n" + "\n".join(lines))
return "\n\n".join(blocks)
_JSON_SCHEMAS = {
"script": '{"text": "完整剧本正文(简体中文,含大纲/分场/台词)"}',
"style": (
'{"directions": [{"id": "style1", "name": "风格名称", '
'"description": "中文风格说明", "prompt": "english, style, keywords", '
'"negative_prompt": "optional english negative keywords"}]}(至少 2 套)'
),
"storyboard": (
'{"shots": [{"id": "shot1", "scene": "场次", "shot_size": "景别", '
'"camera": "运镜", "description": "画面内容", "dialog": "台词(可空)", '
'"duration_sec": 3}]}'
),
"assets": (
'{"assets": [{"id": "asset1", "kind": "character|location|prop", '
'"name": "名称", "description": "中文说明", '
'"prompt": "complete english image prompt", '
'"negative_prompt": "可空"}]}'
),
"shot": (
'{"shots": [{"id": "vshot1", "shot_no": "S1", '
'"description": "中文画面说明", "prompt": "complete english video prompt", '
'"duration_sec": 5}]}'
),
}
# Strong refs so in-flight runs are never garbage-collected mid-turn
# (same pattern as the harness runner).
_ACTIVE_RUNS: dict[int, asyncio.Task] = {}
async def _execute_run(project_id: int, stage_key: str, run_id: int, instruction: str | None) -> None:
db = config.settings.db_path
try:
conn = get_db(db)
try:
context = _stage_context(conn, project_id, stage_key)
finally:
conn.close()
user_parts = [context]
if instruction and instruction.strip():
user_parts.append(f"用户补充要求:{instruction.strip()}")
user_parts.append(
f"请产出本段({ _stage_name(stage_key)})的 JSON:{_JSON_SCHEMAS[stage_key]}"
)
messages = [
{"role": "system", "content": _system_prompt(stage_key)},
{"role": "user", "content": "\n\n".join(user_parts)},
]
role = AGENTS[stage_key]["llm_role"]
client = LLMClient.for_role(role, timeout=240.0)
try:
text = await client.chat(messages, temperature=0.7)
finally:
await client.close()
content = NORMALIZERS[stage_key](extract_json(text))
conn = get_db(db)
try:
conn.execute(
"UPDATE stage_runs SET status='done', output_json=?, completed_at=CURRENT_TIMESTAMP "
"WHERE id = ?",
(json.dumps(content, ensure_ascii=False), run_id),
)
conn.execute(
"UPDATE project_stages SET content_json=?, status='awaiting_confirm', "
"draft_edited=0, error=NULL, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ?",
(json.dumps(content, ensure_ascii=False), project_id, stage_key),
)
conn.execute(
"UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id = ?",
(project_id,),
)
conn.commit()
finally:
conn.close()
except Exception as exc: # noqa: BLE001 — any failure becomes a readable run row
reason = _friendly_error(exc)
try:
conn = get_db(db)
try:
conn.execute(
"UPDATE stage_runs SET status='failed', error=?, completed_at=CURRENT_TIMESTAMP "
"WHERE id = ?",
(reason, run_id),
)
conn.execute(
"UPDATE project_stages SET status=CASE "
"WHEN confirmed_content_json IS NOT NULL THEN 'confirmed' ELSE 'todo' END, "
"error=?, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ? AND status = 'running'",
(reason, project_id, stage_key),
)
conn.commit()
finally:
conn.close()
except Exception: # pragma: no cover — bookkeeping failure only
pass
def _friendly_error(exc: Exception) -> str:
text = str(exc)
lowered = text.lower()
if "connect" in lowered or "timeout" in lowered or "timed out" in lowered:
return (
"连接大模型服务失败:请到「模型设置」检查地址与密钥,或点「重新生成」再试一次。"
)
if "no json" in lowered or isinstance(exc, ValueError):
return "智能体没有返回可解析的结果,请点「重新生成」重试;多次失败可换一个模型。"
return f"生成失败:{text[:300]}"
# ─────────────────────────────────────────────────────────────────────────
# Endpoints
# ─────────────────────────────────────────────────────────────────────────
@router.get("/projects/{project_id}")
async def workbench_overview(project_id: int) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
project = _get_project(conn, project_id)
_ensure_stage_rows(conn, project_id)
rows = conn.execute(
"SELECT * FROM project_stages WHERE project_id = ? ORDER BY id ASC",
(project_id,),
).fetchall()
outputs = _workbench_job_outputs(conn, project_id)
stages = []
for row in rows:
stage = _stage_public(row_to_dict(row))
stages.append(_enrich_stage(stage, outputs))
runs = {key: _last_run(conn, project_id, key) for key in STAGE_KEYS}
for stage in stages:
stage["last_run"] = runs.get(stage["stage_key"])
return {
"project": {
"id": project["id"],
"title": project["title"],
"idea": project.get("idea"),
"status": project["status"],
"updated_at": project["updated_at"],
},
"stages": stages,
}
finally:
conn.close()
def _stage_or_404(conn, project_id: int, stage_key: str) -> dict[str, Any]:
if stage_key not in STAGE_KEYS:
raise HTTPException(status_code=404, detail="阶段不存在")
_ensure_stage_rows(conn, project_id)
return _load_stage(conn, project_id, stage_key)
@router.patch("/projects/{project_id}/stages/{stage_key}")
async def patch_stage(project_id: int, stage_key: str, payload: StagePatch) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
stage = _stage_or_404(conn, project_id, stage_key)
if stage["status"] == "running":
raise HTTPException(status_code=409, detail="本阶段正在生成中,请稍候再编辑。")
try:
content = NORMALIZERS[stage_key](payload.content)
except StageContentError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if content == (json.loads(stage["content_json"]) if stage["content_json"] else None):
return {"ok": True, "stage": _stage_public({**stage, "content_json": json.dumps(content, ensure_ascii=False)})}
# Editing a confirmed stage produces a new draft awaiting re-confirm;
# the confirmed snapshot stays intact for 恢复.
next_status = "awaiting_confirm" if stage["status"] == "confirmed" else stage["status"]
if stage["status"] == "todo":
next_status = "awaiting_confirm"
chosen = payload.chosen_style_id
if stage_key == "style" and chosen:
ids = [d.get("id") for d in content.get("directions", [])]
if chosen not in ids:
raise HTTPException(status_code=400, detail="所选风格方向不存在,请刷新后重试。")
conn.execute(
"UPDATE project_stages SET content_json=?, status=?, draft_edited=1, "
"chosen_style_id=COALESCE(?, chosen_style_id), updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ?",
(
json.dumps(content, ensure_ascii=False),
next_status,
chosen,
project_id,
stage_key,
),
)
conn.execute(
"UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id = ?", (project_id,)
)
conn.commit()
row = _load_stage(conn, project_id, stage_key)
return {"ok": True, "stage": _stage_public(row)}
finally:
conn.close()
@router.post("/projects/{project_id}/stages/{stage_key}/run")
async def run_stage(project_id: int, stage_key: str, payload: StageRunRequest | None = None) -> dict[str, Any]:
instruction = (payload.instruction if payload else None) or None
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
stage = _stage_or_404(conn, project_id, stage_key)
if stage["status"] == "running":
raise HTTPException(status_code=409, detail="本阶段正在生成中,请稍候。")
# Prerequisite: the previous stage must be confirmed (drafts never
# unlock the next agent).
idx = STAGE_KEYS.index(stage_key)
if idx > 0:
prev = _load_stage(conn, project_id, STAGE_KEYS[idx - 1])
if prev["status"] != "confirmed":
raise HTTPException(
status_code=409,
detail=f"请先完成并确认上一阶段「{_stage_name(STAGE_KEYS[idx - 1])}」。",
)
# LLM must be resolvable — fail fast with a fix-it message.
try:
profile = config.settings.resolve_llm_for_role(AGENTS[stage_key]["llm_role"])
except Exception: # pragma: no cover — defensive
profile = None
if not profile or not (profile.get("base_url") or "").strip():
raise HTTPException(
status_code=400,
detail="尚未配置可用的大模型:请到「模型设置」添加并测试通过后再生成。",
)
cur = conn.execute(
"INSERT INTO stage_runs (project_id, stage_key, instruction) VALUES (?, ?, ?)",
(project_id, stage_key, instruction),
)
run_id = int(cur.lastrowid)
conn.execute(
"UPDATE project_stages SET status='running', error=NULL, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ?",
(project_id, stage_key),
)
conn.commit()
finally:
conn.close()
task = asyncio.create_task(_execute_run(project_id, stage_key, run_id, instruction))
_ACTIVE_RUNS[run_id] = task
task.add_done_callback(lambda t: _ACTIVE_RUNS.pop(run_id, None))
return {"ok": True, "run_id": run_id}
@router.post("/projects/{project_id}/stages/{stage_key}/confirm")
async def confirm_stage(
project_id: int, stage_key: str, payload: StageConfirmRequest | None = None
) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
stage = _stage_or_404(conn, project_id, stage_key)
if stage["status"] == "running":
raise HTTPException(status_code=409, detail="本阶段正在生成中,请等待完成。")
if not stage["content_json"]:
raise HTTPException(status_code=400, detail="本阶段还没有内容,请先生成或手动填写。")
content = json.loads(stage["content_json"])
chosen = payload.chosen_style_id if payload else None
if stage_key == "style":
directions = content.get("directions") or []
ids = [d.get("id") for d in directions]
if chosen and chosen not in ids:
raise HTTPException(status_code=400, detail="所选风格方向不存在,请刷新后重试。")
if not chosen:
chosen = stage["chosen_style_id"] or (ids[0] if ids else None)
conn.execute(
"UPDATE project_stages SET status='confirmed', confirmed_content_json=?, "
"chosen_style_id=?, draft_edited=0, error=NULL, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ?",
(
json.dumps(content, ensure_ascii=False),
chosen if stage_key == "style" else stage["chosen_style_id"],
project_id,
stage_key,
),
)
conn.execute(
"UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id = ?", (project_id,)
)
conn.commit()
row = _load_stage(conn, project_id, stage_key)
return {"ok": True, "stage": _stage_public(row)}
finally:
conn.close()
@router.post("/projects/{project_id}/stages/{stage_key}/restore")
async def restore_stage(project_id: int, stage_key: str) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
stage = _stage_or_404(conn, project_id, stage_key)
if not stage["confirmed_content_json"]:
raise HTTPException(status_code=400, detail="本阶段还没有已确认版本,无需恢复。")
conn.execute(
"UPDATE project_stages SET content_json=confirmed_content_json, "
"status='confirmed', draft_edited=0, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = ?",
(project_id, stage_key),
)
conn.commit()
row = _load_stage(conn, project_id, stage_key)
return {"ok": True, "stage": _stage_public(row)}
finally:
conn.close()
@router.post("/projects/{project_id}/stages/script/import")
async def import_script(project_id: int, payload: ScriptImportRequest) -> dict[str, Any]:
"""导入现成剧本:直接确认为剧本阶段基线,从视觉设计继续。"""
text = payload.text.strip()
if len(text) < 30:
raise HTTPException(status_code=400, detail="剧本内容太短,请检查粘贴是否完整。")
content = {"text": text}
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
_stage_or_404(conn, project_id, "script")
conn.execute(
"UPDATE project_stages SET content_json=?, confirmed_content_json=?, "
"status='confirmed', draft_edited=0, error=NULL, updated_at=CURRENT_TIMESTAMP "
"WHERE project_id = ? AND stage_key = 'script'",
(
json.dumps(content, ensure_ascii=False),
json.dumps(content, ensure_ascii=False),
project_id,
),
)
conn.execute(
"UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id = ?", (project_id,)
)
conn.commit()
row = _load_stage(conn, project_id, "script")
return {"ok": True, "stage": _stage_public(row)}
finally:
conn.close()
@router.post("/projects/{project_id}/generate")
async def workbench_generate(project_id: int, payload: WorkbenchGenerateRequest) -> dict[str, Any]:
"""In-flow generation (HEL-612 shared queue): one image or video job,
project-linked, tagged workbench so results come back to the project."""
conn = get_db(config.settings.db_path)
try:
_get_project(conn, project_id)
_stage_or_404(conn, project_id, payload.stage_key)
wf = conn.execute(
"SELECT * FROM workflows WHERE kind = ? AND is_enabled = 1 ORDER BY id ASC LIMIT 1",
(payload.kind,),
).fetchone()
if not wf:
label = "生图" if payload.kind == "image" else "生视频"
raise HTTPException(
status_code=400,
detail=f"没有可用的{label}工作流:请先到「ComfyUI 连接」确认连接可用,"
"再到工作流管理导入并启用一个"
f"{label}工作流。",
)
workflow = row_to_dict(wf)
finally:
conn.close()
inputs = parse_dynamic_inputs(json.loads(workflow["workflow_json"] or "{}"))
duration = payload.duration_sec if payload.kind == "video" else None
input_values = smart_fill_inputs(
inputs,
prompt=payload.prompt,
negative_prompt=payload.negative_prompt or None,
duration=duration,
)
job = queue_manager.enqueue(
project_id=project_id,
kind=payload.kind,
workflow_id=int(workflow["id"]),
payload={
"input_values": input_values,
"prompt": payload.prompt,
"source": WORKBENCH_SOURCE,
"stage_key": payload.stage_key,
"target_id": payload.target_id,
},
)
await event_bus.publish(
"job.created",
{
"job_id": job["id"],
"kind": payload.kind,
"source": WORKBENCH_SOURCE,
"project_id": project_id,
},
)
return {"ok": True, "job": _job_public(job)}