"""项目主页 LLM 调度:结构化计划、白名单执行与全流程交付。""" from __future__ import annotations import json import threading import time import pytest from app.models import AgentRun, ModelSpec, ReviewRecord, Task from app.providers import registry as model_registry from app.services import agent def _plan(steps: list[dict], *, reply: str = "可以执行", blockers: list[str] | None = None) -> dict: return { "intent": "full_delivery", "reply": reply, "summary": "测试执行计划", "steps": steps, "blockers": blockers or [], "warnings": [], } def test_agent_plan_and_execute_full_delivery( api, studio, script_text, make_image_png, install_llm ): install_llm(_plan([ {"action": "generate_shots", "reason": "生成视频和配音", "shot_ids": None}, {"action": "quality_check", "reason": "检查产物", "shot_ids": None}, {"action": "approve_passed", "reason": "用户已授权全自动通过质检合格镜头", "shot_ids": None}, {"action": "build_timeline", "reason": "排布已审核镜头", "shot_ids": None}, {"action": "compose", "reason": "导出最终成片", "shot_ids": None}, ])) pid = studio["project_id"] imported = api.post( f"/api/projects/{pid}/import", data={"script_text": script_text, "default_duration": 2}, files=[ ("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")), ("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png")), ], ) assert imported["ok"] is True planned = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "把现有分镜完整生成并交付,质检合格后自动放行", "auto_approve": True}, )["run"] assert planned["status"] == "planned" assert planned["provider"] == "fake" and planned["model"] == "orchestrator" # 身份素材(定妆图/三视图/场景母图/声线)由调度自动补排,不需要用户先手动准备 assert [step["action"] for step in planned["steps"]] == [ "generate_identity_assets", "generate_shots", "quality_check", "approve_passed", "build_timeline", "compose", ] assert planned["auto_approve"] is True and planned["can_execute"] is True executed = api.post( f"/api/projects/{pid}/agent/runs/{planned['id']}/execute", json={"wait": True, "timeout_seconds": 600}, )["run"] assert executed["status"] == "succeeded", executed assert all(step["status"] in ("succeeded", "skipped") for step in executed["steps"]) quality = next(step for step in executed["steps"] if step["action"] == "quality_check") assert quality["status"] == "succeeded" assert quality["result"]["already_checked"] is True assert "生成阶段完成自动质检" in quality["detail"] compose = next(step for step in executed["steps"] if step["action"] == "compose") assert compose["result"]["export_id"] exports = api.get(f"/api/projects/{pid}/exports")["exports"] assert len(exports) == 1 and exports[0]["status"] == "succeeded" assert api.get(f"/api/projects/{pid}")["summary"]["status"] == "delivered" agent_reviews = api.get(f"/api/projects/{pid}/reviews", params={"kind": "agent"})["reviews"] assert len(agent_reviews) == 2 assert all(row["reviewer"] == "agent:fake/orchestrator" for row in agent_reviews) assert all("不是人工审核" in row["notes"] for row in agent_reviews) def test_agent_refuses_mock_llm(api): pid = api.project(name="Mock 调度拒绝") response = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "继续项目", "auto_approve": False}, expect=409, ) assert "Mock LLM" in response["detail"] def test_agent_cancel_immediately_releases_run_and_active_tasks(api, db, studio): pid = studio["project_id"] run = AgentRun(project_id=pid, status="running", request_text="取消测试", steps_json=[{"action": "generate_shots", "status": "running"}]) task = Task(project_id=pid, kind="asset", name="取消中的任务", stage="asset", status="running") db.add_all([run, task]) db.commit() cancelled = api.post( f"/api/projects/{pid}/agent/runs/{run.id}/cancel", json={"reason": "导演停止本轮生成"}, )["run"] assert cancelled["status"] == "cancelled" and cancelled["cancel_requested"] is True db.expire_all() assert db.get(Task, task.id).status == "cancelled" assert db.get(AgentRun, run.id).error_code == "cancelled" def test_interrupted_agent_run_is_recovered_after_service_restart(db, studio): run = AgentRun(project_id=studio["project_id"], status="running", steps_json=[{"action": "compose", "status": "running"}]) db.add(run) db.commit() assert agent.recover_interrupted_runs(db) == 1 db.refresh(run) assert run.status == "failed" and run.error_code == "agent_interrupted" assert run.steps_json[0]["status"] == "failed" def test_agent_rejects_unlisted_action_without_touching_project(api, install_llm): pid = api.project(name="危险动作拒绝") install_llm(_plan([ {"action": "delete_project", "reason": "模型试图越权", "shot_ids": None}, ])) response = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "删除项目", "auto_approve": True}, expect=502, ) assert "字段不合法" in response["detail"] or "不合法" in response["detail"] assert api.get(f"/api/projects/{pid}")["result"]["id"] == pid assert api.get(f"/api/projects/{pid}/agent/runs")["count"] == 0 def test_agent_requires_explicit_auto_approval(api, install_llm): pid = api.project(name="审核门禁") install_llm(_plan([ {"action": "approve_passed", "reason": "越权放行", "shot_ids": None}, ])) response = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "自动通过审核", "auto_approve": False}, expect=502, ) assert "approve_passed" in response["detail"] def test_agent_returns_blockers_without_executable_steps(api, install_llm): pid = api.project(name="空项目诊断") install_llm(_plan([], reply="项目还没有分镜,请先导入脚本。", blockers=["尚未导入分镜与脚本"])) run = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "一键生成整个项目", "auto_approve": False}, )["run"] assert run["status"] == "blocked" assert run["steps"] == [] assert run["blockers"] == ["尚未导入分镜与脚本"] api.post( f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 60}, expect=409, ) def test_agent_treats_completed_project_as_success_not_blocker(api, install_llm): pid = api.project(name="已完成项目") install_llm({ "intent": "complete", "outcome": "complete", "reply": "项目已完成交付,无需重复生成。", "summary": "已交付", "steps": [], "blockers": [], "warnings": [], }) run = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "检查是否完成", "auto_approve": False}, )["run"] assert run["status"] == "succeeded" assert run["blockers"] == [] and run["steps"] == [] def test_agent_approval_is_auditable_as_agent_not_manual(api, db): """模型审核记录必须单独标记,不能污染 kind=manual 的人工审核审计。""" pid = api.project(name="审核审计") row = ReviewRecord(project_id=pid, kind="agent", verdict="pass", reviewer="agent:test") db.add(row) db.commit() manual = api.get(f"/api/projects/{pid}/reviews", params={"kind": "manual"})["reviews"] agent_rows = api.get(f"/api/projects/{pid}/reviews", params={"kind": "agent"})["reviews"] assert manual == [] assert [item["reviewer"] for item in agent_rows] == ["agent:test"] def _rewrite_plan(shots: list[dict], *, extra: list[dict] | None = None) -> dict: return { "intent": "rewrite", "outcome": "execute", "reply": "按新主题重写分镜并重新生成整片。", "summary": "改写分镜后重新生成", "steps": [{"action": "rewrite_shots", "reason": "主题变了", "storyboard": shots}] + (extra or []), "blockers": [], "warnings": [], } # 分镜里的人物/场景名一律用项目里已有的资产,验证「改写分镜会沿用既有资产」 REWRITE_SHOTS = [ {"code": "S01", "title": "启航警报", "description": "舰桥警报灯闪烁,林澈从休眠舱坐起", "duration": 2, "shot_size": "medium", "camera_movement": "push_in", "scene": "星舰舰桥", "characters": ["林澈"]}, {"code": "S02", "title": "呐喊", "description": "舷窗外星云中出现巨型怪兽轮廓,林澈瞪大双眼", "duration": 2, "shot_size": "close_up", "camera_movement": "static", "dialogue": "我的天啊,这是什么怪兽?", "speaker": "林澈", "scene": "星舰舰桥", "characters": ["林澈"]}, ] def test_agent_rewrite_shots_replaces_storyboard_and_purges_outputs( api, studio, script_text, make_image_png, install_llm, install_image, db ): """换主题必须是可执行动作:旧镜头与旧产物作废,新分镜沿用既有人物/场景。""" from app.models import Asset, Shot from app.services import storage install_llm(_plan([ {"action": "generate_shots", "reason": "先出一版", "shot_ids": None}, {"action": "quality_check", "reason": "质检", "shot_ids": None}, ])) pid = studio["project_id"] api.post(f"/api/projects/{pid}/import", data={"script_text": script_text, "default_duration": 2}, files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")), ("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))]) first = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "生成分镜", "auto_approve": False})["run"] api.post(f"/api/projects/{pid}/agent/runs/{first['id']}/execute", json={"wait": True, "timeout_seconds": 600}) old_shots = api.get(f"/api/projects/{pid}/shots")["shots"] assert all(row["output_path"] for row in old_shots), "旧镜头应已有产物" old_outputs = [row["output_path"] for row in old_shots] old_ids = {row["id"] for row in old_shots} install_image() install_llm(_rewrite_plan(REWRITE_SHOTS)) run = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "重新生成本项目,主题改为卧室看哥斯拉", "auto_approve": False})["run"] # 换主题后新人物/新场景缺定妆素材,调度必须紧跟一步 generate_identity_assets assert [step["action"] for step in run["steps"]] == ["rewrite_shots", "generate_identity_assets"] assert run["steps"][0]["storyboard"], "计划必须把新分镜落库,供用户审阅" executed = api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 600})["run"] assert executed["status"] == "succeeded", executed["error_message"] new_shots = api.get(f"/api/projects/{pid}/shots")["shots"] assert [row["code"] for row in new_shots] == ["S01", "S02"] assert new_shots[1]["dialogue"] == "我的天啊,这是什么怪兽?" assert new_shots[0]["camera_movement"] == "push_in" assert all(row["characters"] for row in new_shots), "新分镜要自动沿用项目人物" assert all(not row["output_path"] for row in new_shots) for path in old_outputs: assert not storage.exists(path), f"旧产物文件应被清理:{path}" stale = [row for row in db.query(Asset).filter(Asset.owner_type == "shot", Asset.owner_id.in_(old_ids)).all() if row.project_id == pid and not storage.exists(row.path)] assert not stale, "旧镜头素材不能变成孤儿记录" summary = api.get(f"/api/projects/{pid}")["summary"] assert summary["status"] != "delivered" by_key = {row["key"]: row for row in summary["workflow"]} assert by_key["export"]["state"] == "pending" assert summary["stats"]["latest_export"] is None def test_agent_rewrite_then_regenerate_delivers_new_film( api, studio, script_text, make_image_png, install_llm, install_image ): """换主题后的完整闭环:改写 → 自动补关键帧 → 生成 → 质检 → 放行 → 成片。""" install_llm(_plan([ {"action": "generate_shots", "reason": "先出一版", "shot_ids": None}, {"action": "quality_check", "reason": "质检", "shot_ids": None}, {"action": "approve_passed", "reason": "授权", "shot_ids": None}, {"action": "build_timeline", "reason": "排布", "shot_ids": None}, {"action": "compose", "reason": "导出", "shot_ids": None}, ])) pid = studio["project_id"] api.post(f"/api/projects/{pid}/import", data={"script_text": script_text, "default_duration": 2}, files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")), ("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))]) first = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "完整交付", "auto_approve": True})["run"] api.post(f"/api/projects/{pid}/agent/runs/{first['id']}/execute", json={"wait": True, "timeout_seconds": 600}) assert api.get(f"/api/projects/{pid}/exports")["exports"], "第一版应有成片" install_image() install_llm(_rewrite_plan(REWRITE_SHOTS, extra=[ {"action": "generate_shots", "reason": "重新生成", "shot_ids": None}, {"action": "quality_check", "reason": "质检", "shot_ids": None}, {"action": "approve_passed", "reason": "授权", "shot_ids": None}, {"action": "build_timeline", "reason": "排布", "shot_ids": None}, {"action": "compose", "reason": "导出", "shot_ids": None}, ])) run = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "主题换成哥斯拉,重新生成本项目", "auto_approve": True})["run"] executed = api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 900})["run"] assert executed["status"] == "succeeded", executed["error_message"] by_action = {step["action"]: step for step in executed["steps"]} assert by_action["rewrite_shots"]["status"] == "succeeded" # 新分镜没有关键帧,generate_shots 必须先自动补图,否则预检会把整步清空 assert by_action["generate_shots"]["result"].get("auto_keyframes") == 2 assert by_action["compose"]["result"].get("export_id") exports = api.get(f"/api/projects/{pid}/exports")["exports"] assert len(exports) == 2 and {row["status"] for row in exports} == {"succeeded"} summary = api.get(f"/api/projects/{pid}")["summary"] assert summary["status"] == "delivered" assert summary["stats"]["shots"] == 2 def test_agent_rewrite_creates_missing_scenes(api, studio, install_llm, install_image, db): """新主题必然带来新场景:rewrite_shots 要顺手建好,不能卡在「项目里没有卧室」。""" from app.models import Scene pid = studio["project_id"] install_image() install_llm({ "intent": "rewrite", "outcome": "execute", "reply": "改写为海边卧室主题", "summary": "改写", "steps": [{ "action": "rewrite_shots", "reason": "换主题", "storyboard": [ {"code": "S01", "description": "卧室晨光,女主从床上坐起", "duration": 2, "scene": "海边别墅卧室", "characters": ["林澈"]}, {"code": "S02", "description": "落地窗外海面浮出巨兽", "duration": 2, "scene": "落地窗前", "characters": ["林澈"]}, ], "new_scenes": [{"name": "海边别墅卧室", "description": "清晨阳光,白色床品", "lighting": "暖色晨光", "time_of_day": "清晨"}, {"name": "落地窗前", "description": "整面落地窗正对大海"}, {"name": "没人引用的场景", "description": "应被忽略"}], "new_characters": [{"name": "哥斯拉", "role": "怪兽", "appearance": "黑色鳞甲巨兽"}], }], "blockers": [], "warnings": [], }) run = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "改成海边卧室看哥斯拉", "auto_approve": False})["run"] executed = api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 600})["run"] assert executed["status"] == "succeeded", executed["error_message"] step = executed["steps"][0] assert step["result"]["created_assets"]["scenes"] == ["海边别墅卧室", "落地窗前"] names = {row.name for row in db.query(Scene).filter(Scene.project_id == pid).all()} assert {"海边别墅卧室", "落地窗前"} <= names assert "没人引用的场景" not in names, "只创建分镜真正引用的场景" shots = api.get(f"/api/projects/{pid}/shots")["shots"] assert [row["scenes"][0]["name"] for row in shots] == ["海边别墅卧室", "落地窗前"] def test_agent_rewrite_is_idempotent_on_repeat_execute(api, studio, install_llm, install_image, db): """同一个计划被重复确认执行时不能重复建场景或留下半套分镜。""" from app.models import Scene pid = studio["project_id"] install_image() install_llm({ "intent": "rewrite", "outcome": "execute", "reply": "改写", "summary": "改写", "steps": [{"action": "rewrite_shots", "reason": "换主题", "storyboard": [{"code": "S01", "description": "女主推开卧室门走向落地窗", "duration": 2, "scene": "卧室"}], "new_scenes": [{"name": "卧室", "description": "海边别墅卧室"}]}], "blockers": [], "warnings": [], }) run = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "换主题", "auto_approve": False})["run"] api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 600}) again = api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True, "timeout_seconds": 600}, expect=409) assert "succeeded" in again["detail"] assert db.query(Scene).filter(Scene.project_id == pid, Scene.name == "卧室").count() == 1 def test_agent_rewrite_plan_requires_storyboard(api, install_llm): pid = api.project(name="改写缺分镜") install_llm({"intent": "rewrite", "outcome": "execute", "reply": "改写", "summary": "改写", "steps": [{"action": "rewrite_shots", "reason": "换主题", "storyboard": []}], "blockers": [], "warnings": []}) response = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "换个主题", "auto_approve": False}, expect=502) assert "storyboard" in response["detail"] def test_agent_context_exposes_rewrite_action(api, studio, install_llm): """调度器必须知道 rewrite_shots 存在,否则会把「换主题」误判成无法完成。""" from app.db import SessionLocal from app.models import Project session = SessionLocal() try: project = session.get(Project, studio["project_id"]) context = agent.build_context(session, project, message="换个主题", auto_approve=False) finally: session.close() allowed = {row["action"]: row for row in context["policy"]["allowed_actions"]} assert "rewrite_shots" in allowed and allowed["rewrite_shots"]["allowed"] is True assert context["options"]["shot_size"] and context["video_model"]["min_duration"] > 0 assert "rewrite_shots" in agent._system_prompt() def test_background_execute_claims_the_run_before_responding(api, studio, install_llm): """后台执行必须在响应前把计划置为 running。 校验过去只发生在后台线程里:线程一失败就静默死掉,状态还停在 planned, 前端却已经收到 200「调度已启动」——用户看到的就是点了一次执行后项目毫无推进。 """ install_llm(_plan([{"action": "build_timeline", "reason": "排布已审核镜头", "shot_ids": None}])) pid = studio["project_id"] run = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "推进到时间线", "auto_approve": True}, )["run"] started = api.post( f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": False, "timeout_seconds": 60}, )["run"] assert started["status"] == "running", started assert started["steps"][0]["status"] in ("pending", "running") def test_start_run_is_the_single_claim_gate(db, studio): """同一项目只允许一条在跑的计划;空计划与已完成计划都必须明确报错。""" pid = studio["project_id"] busy = AgentRun(project_id=pid, status="running", steps_json=[{"action": "build_timeline", "reason": "排布", "shot_ids": None}]) queued = AgentRun(project_id=pid, status="planned", steps_json=[{"action": "build_timeline", "reason": "排布", "shot_ids": None}]) db.add_all([busy, queued]) db.commit() with pytest.raises(agent.AgentStateError, match="正在执行"): agent.start_run(db, queued, timeout_seconds=60) db.rollback() busy.status = "succeeded" db.commit() claimed = agent.start_run(db, queued, timeout_seconds=60) assert claimed.status == "running" and claimed.timeout_seconds == 60 assert claimed.started_at is not None db.commit() empty = AgentRun(project_id=pid, status="planned", steps_json=[]) db.add(empty) db.commit() with pytest.raises(agent.AgentStateError, match="没有可执行步骤"): agent.start_run(db, empty, timeout_seconds=60) db.rollback() def _await_run(api, project_id: int, run_id: int, *, timeout: float = 15.0) -> dict: """轮询后台线程推进的规划/执行状态,替代过去「一次 POST 等到底」。""" deadline = time.monotonic() + timeout row: dict = {} while time.monotonic() < deadline: row = api.get(f"/api/projects/{project_id}/agent/runs/{run_id}")["run"] if row["status"] != "planning": return row time.sleep(0.05) return row def test_async_plan_returns_a_planning_record_immediately(api, studio, install_llm, monkeypatch): """规划必须先在库里可见:LLM 还没答完时页面就有记录可看,也不会被二次点击插队。""" install_llm(_plan([{"action": "build_timeline", "reason": "排布已审核镜头", "shot_ids": None}])) pid = studio["project_id"] gate = threading.Event() original = model_registry.generate_asset def slow(db, request, *args, **kwargs): gate.wait(10) return original(db, request, *args, **kwargs) monkeypatch.setattr(model_registry, "generate_asset", slow) run = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "推进到时间线", "auto_approve": True, "wait": False}, )["run"] assert run["status"] == "planning" and run["is_planning"] is True assert run["can_execute"] is False and run["plan_stage"] == "queued" busy = api.post(f"/api/projects/{pid}/agent/plan", json={"message": "再下一句", "wait": False}, expect=409) assert "正在规划" in busy["detail"] too_early = api.post(f"/api/projects/{pid}/agent/runs/{run['id']}/execute", json={"wait": True}, expect=409) assert "还在盘点项目" in too_early["detail"] gate.set() finished = _await_run(api, pid, run["id"]) assert finished["status"] == "planned", finished assert [step["action"] for step in finished["steps"]] == ["build_timeline"] assert finished["can_execute"] is True def test_auto_execute_continues_on_the_server_without_a_second_click(api, studio, install_llm): """勾了「立即执行」就必须由服务端接手跑完整条链,浏览器关掉也不影响。""" install_llm(_plan([{"action": "build_timeline", "reason": "排布已审核镜头", "shot_ids": None}])) pid = studio["project_id"] run = api.post( f"/api/projects/{pid}/agent/plan", json={"message": "推进到时间线", "auto_approve": True, "wait": False, "auto_execute": True, "timeout_seconds": 120}, )["run"] deadline = time.monotonic() + 15 row = run while time.monotonic() < deadline: row = api.get(f"/api/projects/{pid}/agent/runs/{run['id']}")["run"] if row.get("started_at"): break time.sleep(0.05) assert row["started_at"], row assert row["status"] != "planning", row actions = [event["action"] for event in api.get(f"/api/projects/{pid}/events", params={"limit": 80})["events"]] assert "agent.plan_requested" in actions assert "agent.auto_execute" in actions or "agent.run_started" in actions def test_planning_record_is_released_after_service_restart(db, studio): """服务重启会带走规划线程:记录必须翻成失败,否则项目永远卡在「规划中」。""" run = AgentRun(project_id=studio["project_id"], status="planning", request_text="跑完整片") db.add(run) db.commit() assert agent.recover_interrupted_runs(db) == 1 db.refresh(run) assert run.status == "failed" and run.error_code == "agent_interrupted" assert "规划请求中断" in run.error_message def test_planning_record_can_be_cancelled(db, studio): """取消规划要立即生效,后台线程回来后不能再把记录复活。""" run = AgentRun(project_id=studio["project_id"], status="planning", request_text="跑完整片") db.add(run) db.commit() cancelled = agent.cancel_run(db, run, reason="换一种说法") assert cancelled.status == "cancelled" and cancelled.cancel_requested is True db.refresh(run) assert run.plan_json.get("stage") == "cancelled"