Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

fix(drama): 修复摘要与分集任务提交后返回500

yi29ff9c346798
diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.py
index 626e4a1..3ddfbd7 100644
--- a/backend/app/services/tasks/service.py
+++ b/backend/app/services/tasks/service.py
@@ -978,10 +978,15 @@ async def _validate_task_scope(db: AsyncSession, user: User, body: TaskCreateReq
raise ValueError("漫剧项目不存在或无权限")
# Hold project ownership through task insertion. A concurrent personal transfer
# must either observe this active task or finish before our scope is accepted.
- project = (await db.execute(select(DramaProject).where(DramaProject.id == pid).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()
- if project is None or project.team_id != actual_team_id:
+ # 只读取最新归属字段,避免刷新 ORM 对象使调用方已加载的剧本关系失效。
+ locked_project = (await db.execute(
+ select(DramaProject.id, DramaProject.user_id, DramaProject.team_id)
+ .where(DramaProject.id == pid)
+ .with_for_update()
+ )).one_or_none()
+ if locked_project is None or locked_project.team_id != actual_team_id:
raise ValueError("项目归属已变化,请刷新页面后重试")
- if actual_team_id is None and int(project.user_id) != int(user.id):
+ if actual_team_id is None and int(locked_project.user_id) != int(user.id):
raise ValueError("漫剧项目不存在或无权限")
body.drama_project_id = pid
if body.team_id is not None and body.team_id != actual_team_id:
diff --git a/backend/tests/test_drama_agent_submission.py b/backend/tests/test_drama_agent_submission.py
new file mode 100644
index 0000000..968cc33
--- /dev/null
+++ b/backend/tests/test_drama_agent_submission.py
@@ -0,0 +1,91 @@
+"""任务提交后仍能返回剧本快照,重复请求不重复启动模型。"""
+
+from unittest.mock import AsyncMock, Mock
+
+import httpx
+import pytest
+from fastapi import FastAPI
+from sqlalchemy import select
+
+from app.api.drama.agents import router
+from app.database import get_db
+from app.deps import get_current_user
+from app.models_drama import DramaProject, DramaScript
+from app.models_tasks import TaskRun
+from tests.conftest import make_user
+
+
+ "endpoint,extra,status_key",
+ [
+ ("script_summary", {"episode_count": 3}, "summary_status"),
+ ("episode_script", {}, "episode_content_status"),
+ (
+ "episode_script",
+ {"episode_number": 1, "draft": "曹操迎汉献帝迁都许昌,面对诸侯的挑战,逐渐确立自己的政治地位。"},
+ "episode_optimize_status",
+ ),
+ ],
+)
+async def test_submission_returns_script_and_repeated_request_does_not_launch_again(
+ db_session, monkeypatch, endpoint, extra, status_key
+):
+ """走真实任务创建、权限锁和提交链路,隔离外部模型调用。"""
+ launch = Mock()
+ monkeypatch.setattr("app.services.tasks.direct.launch_direct_task", launch)
+ monkeypatch.setattr(
+ "app.services.billing.settlement.estimate_task_fen", AsyncMock(return_value=100)
+ )
+ user = await make_user(db_session)
+ project = DramaProject(user_id=user.id, title="迁都许昌")
+ db_session.add(project)
+ await db_session.flush()
+ script = DramaScript(
+ project_id=project.id,
+ name="迁都许昌",
+ source="公元196年,曹操迎汉献帝迁都许昌,在动荡的时代中与各路诸侯展开博弈。",
+ summary={"episodeCount": 3},
+ params={},
+ )
+ db_session.add(script)
+ await db_session.commit()
+ project_id, script_id = project.id, script.id
+ # 请求从数据库加载关系,避免构造时的对象引用掩盖异步懒加载问题。
+ db_session.expunge(project)
+ db_session.expunge(script)
+
+ app = FastAPI()
+ app.include_router(router, prefix="/api/drama")
+
+ async def request_db():
+ yield db_session
+
+ app.dependency_overrides[get_db] = request_db
+ app.dependency_overrides[get_current_user] = lambda: user
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app, raise_app_exceptions=False),
+ base_url="http://test",
+ ) as client:
+ payload = {"project_id": project_id, **extra}
+ response = await client.post(f"/api/drama/agents/{endpoint}", json=payload)
+ assert response.status_code == 200, response.text
+ result = response.json()
+ assert result["ok"] is True
+ assert result["queued"] is True
+ assert result["status"] == "generating"
+ assert result["task_id"] > 0
+ assert result["script"]["id"] == script_id
+ assert result["script"]["params"][status_key] == "generating"
+
+ repeated = await client.post(f"/api/drama/agents/{endpoint}", json=payload)
+ assert repeated.status_code == 200, repeated.text
+ assert repeated.json()["task_id"] is None
+ assert repeated.json()["script"]["id"] == script_id
+
+ tasks = list((await db_session.scalars(
+ select(TaskRun).where(TaskRun.drama_project_id == project_id)
+ )).all())
+ assert [task.id for task in tasks] == [result["task_id"]]
+ launch.assert_called_once()
+ assert launch.call_args.args[0] == result["task_id"]
diff --git a/backend/tests/test_team_tasks.py b/backend/tests/test_team_tasks.py
index 3e6558f..4c35e21 100644
--- a/backend/tests/test_team_tasks.py
+++ b/backend/tests/test_team_tasks.py
@@ -32,6 +32,42 @@ async def test_task_derives_team_from_asset_and_rejects_mixed_scope(db_session):
await _validate_task_scope(db_session, member, TaskCreateRequest(task_type="asset_image", asset_id=asset.id, drama_project_id=personal.id))
+async def test_task_rejects_stale_cached_personal_owner(db_session):
+ """The locked database owner must override a stale personal-project identity."""
+ from sqlalchemy import update
+ from app.services.tasks.service import create_task
+ from conftest import make_user
+
+ owner = await make_user(db_session)
+ new_owner = await make_user(db_session)
+ stale_project = DramaProject(user_id=owner.id, team_id=None, title="Changed owner")
+ db_session.add(stale_project)
+ await db_session.flush()
+ await db_session.execute(
+ update(DramaProject)
+ .where(DramaProject.id == stale_project.id)
+ .values(user_id=new_owner.id)
+ .execution_options(synchronize_session=False)
+ )
+ assert stale_project.user_id == owner.id
+ assert stale_project.team_id is None
+ assert await db_session.scalar(
+ select(DramaProject.user_id).where(DramaProject.id == stale_project.id)
+ ) == new_owner.id
+
+ with pytest.raises(ValueError, match="漫剧项目不存在或无权限"):
+ await create_task(
+ db_session, owner,
+ TaskCreateRequest(task_type="script_summary", drama_project_id=stale_project.id),
+ commit=False,
+ )
+
+ assert await db_session.scalar(
+ select(TaskRun.id).where(TaskRun.drama_project_id == stale_project.id)
+ ) is None
+
+
@pytest.mark.asyncio
async def test_team_task_read_and_cancel_roles_and_personal_list(db_session, monkeypatch):
team, owner, member = await seed_team(db_session)