PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(tasks): 隐藏文字任务并补全短视频生图记录
yic0648edd7c25
diff --git a/backend/app/services/tasks/generation_history.py b/backend/app/services/tasks/generation_history.pyindex 40eed30..229d500 100644--- a/backend/app/services/tasks/generation_history.py+++ b/backend/app/services/tasks/generation_history.py@@ -15,7 +15,7 @@ from sqlalchemy import String, and_, case, cast, exists, func, literal, or_, selfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlalchemy.orm import selectinload-from app.models import Project, Shot, ToolRun, User+from app.models import Project, Shot, ToolRun, UsageEvent, Userfrom app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProjectfrom app.models_tasks import TaskEvent, TaskRunfrom app.schemas_generation_history import GenerationListOut, GenerationRecordOut@@ -41,14 +41,43 @@ def _public_status(status: str) -> str:return "queued" if status in {"pending", "leased", "queued"} else "running"-def _kind_expression():+def _image_usage_clause():+ return or_(UsageEvent.capability == "image",+ and_(UsageEvent.capability.is_(None), UsageEvent.billing_key == "seedream"))+++def _kepu_usage_matches_task():+ return and_(TaskRun.domain == "kepu", UsageEvent.task_run_id == TaskRun.id,+ UsageEvent.user_id == TaskRun.requested_by,+ UsageEvent.team_id.is_not_distinct_from(TaskRun.team_id),+ UsageEvent.project_id.is_not_distinct_from(TaskRun.project_id),+ or_(UsageEvent.domain == "kepu", UsageEvent.domain.is_(None)),+ or_(TaskRun.shot_id.is_(None), UsageEvent.shot_id == TaskRun.shot_id))+++def _kind_expression(*, resolve_legacy: bool = True):phase = TaskRun.payload["phase"].as_string()+ legacy_pipeline = and_(TaskRun.task_type == "project_pipeline", or_(phase.is_(None), phase == "produce"))+ # Older resume tasks used "produce" for any stage. Use actual calls instead+ # of treating an image-only batch (often with an empty video snapshot) as video.+ used_video = exists(select(UsageEvent.id).where(_kepu_usage_matches_task(), UsageEvent.capability == "video"))+ used_image = exists(select(UsageEvent.id).where(_kepu_usage_matches_task(), _image_usage_clause()))+ used_audio = exists(select(UsageEvent.id).where(_kepu_usage_matches_task(), UsageEvent.billing_key == "tts"))+ used_text = exists(select(UsageEvent.id).where(_kepu_usage_matches_task(), UsageEvent.billing_key == "llm_chat"))+ saved_kind = TaskRun.result_payload["kind"].as_string()+ saved_output = or_(TaskRun.result_payload["urls"][0].as_string().is_not(None),+ TaskRun.result_payload["url"].as_string().is_not(None))return case((TaskRun.task_type.in_(_AUDIO_TYPES), "audio"),(TaskRun.task_type.in_(_TEXT_TYPES), "text"),(and_(TaskRun.task_type == "project_pipeline", phase == "assets"), "image"),(and_(TaskRun.task_type == "project_pipeline", phase == "audio"), "audio"),(and_(TaskRun.task_type == "project_pipeline", phase.in_(("script", "text", "plan", "storyboard"))), "text"),+ (legacy_pipeline, case((and_(saved_kind.in_(("image", "video", "audio")), saved_output), saved_kind),+ (used_video, "video"), (used_image, "image"),+ (used_audio, "audio"), (used_text, "text"),+ (saved_kind.in_(("image", "video", "audio", "text")), saved_kind), else_="video")+ if resolve_legacy else "video"),(TaskRun.task_type.in_(("project_pipeline", "episode_compose", "project_compose_only")), "video"),(TaskRun.task_type.contains("video"), "video"),(TaskRun.task_type.contains("image"), "image"),@@ -69,6 +98,9 @@ def _generation_kind(task) -> str:return "image"if phase == "audio":return "audio"+ result = task.result_payload if isinstance(task.result_payload, dict) else {}+ if phase in {None, "produce"} and result.get("kind") in ("image", "video", "audio", "text"):+ return result["kind"]return "text" if phase in {"script", "text", "plan", "storyboard"} else "video"if name in {"episode_compose", "project_compose_only"} or "video" in name:return "video"@@ -84,7 +116,8 @@ def _tool_link():task_id == reference,ToolRun.task_id == literal("task-") + task_id,and_(TaskRun.provider_task_id.is_not(None), TaskRun.domain.in_(("studio", "tools")),- ToolRun.kind == _kind_expression(), ToolRun.task_id == TaskRun.provider_task_id),+ # This provider link cannot match kepu; omit its legacy usage lookups.+ ToolRun.kind == _kind_expression(resolve_legacy=False), ToolRun.task_id == TaskRun.provider_task_id),))@@ -109,6 +142,8 @@ def _safe_params(data) -> dict:def _result_urls(result, kind: str) -> list[str]:if not isinstance(result, dict) or kind == "text":return []+ if result.get("kind") in ("image", "video", "audio", "text") and result["kind"] != kind:+ return []values = []for field in ("urls", f"{kind}_urls"):if isinstance(result.get(field), list):@@ -139,16 +174,16 @@ def _text_output(result) -> str:def project_generation(task, *, viewer_id: int, owner_user_id: int | None = None,linked_tool: ToolRun | None = None, fallback: dict | None = None,- submitted_params: dict | None = None) -> GenerationRecordOut:+ submitted_params: dict | None = None, kind_override: str | None = None) -> GenerationRecordOut:"""Project only safe public fields from already persisted task data."""- kind = _generation_kind(task)+ kind = kind_override or _generation_kind(task)result = task.result_payload if isinstance(task.result_payload, dict) else {}outputs = [result, *(step.output_payload for step in getattr(task, "steps", [])if isinstance(step.output_payload, dict))]urls = next((values for output in outputs if (values := _result_urls(output, kind))), [])if not urls and linked_tool is not None:urls = [url for value in (linked_tool.urls or []) if (url := _safe_url(value))]- if not urls and fallback and task.status == "succeeded":+ if not urls and fallback and (task.status == "succeeded" or fallback.get("delivered")):urls = _result_urls(fallback, kind)preview = next((url for output in outputs if (url := _safe_url(output.get("preview_url")))), None)if linked_tool is not None and not preview:@@ -238,15 +273,19 @@ async def _latest_target_tasks(db, tasks, target_name: str) -> set[int]:.group_by(target, kind))).all())-async def _legacy_entity_outputs(db, tasks) -> dict[int, dict]:+async def _legacy_entity_outputs(db, tasks, kinds) -> dict[int, dict]:"""Recover legacy artifacts only from the latest matching owned entity.New work stores immutable URLs on the task itself. Older tasks did not, soonly the latest successful generation may use an entity's current value;previous attempts stay visible without being assigned a later result."""- candidates = [task for task in tasks if task.status == "succeeded" and _generation_kind(task) != "text"- and not any(_result_urls(value, _generation_kind(task)) for value in [task.result_payload,+ def kind(task):+ return kinds.get(task.id) or _generation_kind(task)++ candidates = [task for task in tasks if task.status == "succeeded" and kind(task) != "text"+ and not (task.domain == "kepu" and kind(task) == "image")+ and not any(_result_urls(value, kind(task)) for value in [task.result_payload,*(step.output_payload for step in task.steps)])]outputs = {}asset_tasks = [task for task in candidates if task.asset_id and task.task_type in {"asset_image", "asset_video"}]@@ -257,7 +296,7 @@ async def _legacy_entity_outputs(db, tasks) -> dict[int, dict]:entities = {asset.id: (asset, project) for asset, project in rows}for task in asset_tasks:asset, project = entities.get(task.asset_id, (None, None))- if (asset is not None and task.id in latest and asset.asset_type == _generation_kind(task)+ if (asset is not None and task.id in latest and asset.asset_type == kind(task)and _entity_matches_task(task, project, drama=True) and _entity_is_current(asset, task)):outputs[task.id] = {"urls": [asset.url]}fragment_tasks = [task for task in candidates if task.fragment_id and task.task_type == "fragment_video"]@@ -282,7 +321,7 @@ async def _legacy_entity_outputs(db, tasks) -> dict[int, dict]:for task in shot_tasks:shot, project = entities.get(task.shot_id, (None, None))if shot is not None and task.id in latest and _entity_matches_task(task, project, drama=False):- outputs[task.id] = {"urls": [getattr(shot, f"{_generation_kind(task)}_url", None)]}+ outputs[task.id] = {"urls": [getattr(shot, f"{kind(task)}_url", None)]}project_tasks = [task for task in candidates if task.project_id and task.task_type in {"project_pipeline", "project_compose_only", "project_regen_audio"}]if project_tasks:@@ -296,14 +335,60 @@ async def _legacy_entity_outputs(db, tasks) -> dict[int, dict]:or not _entity_is_current(project, task)):continuephase = (task.payload or {}).get("phase")- kind = _generation_kind(task)- if kind == "video" and (task.task_type == "project_compose_only" or phase in {None, "compose", "produce"}):+ media_kind = kind(task)+ if media_kind == "video" and (task.task_type == "project_compose_only" or phase in {None, "compose", "produce"}):outputs[task.id] = {"urls": [project.final_video_url]}else:- outputs[task.id] = {"urls": [getattr(shot, f"{kind}_url", None) for shot in shots if shot.project_id == project.id]}+ outputs[task.id] = {"urls": [getattr(shot, f"{media_kind}_url", None) for shot in shots if shot.project_id == project.id]}return outputs+async def _kepu_image_outputs(db, tasks, kinds) -> dict[int, dict]:+ """Recover recorded deliveries, or the current image of an unchanged legacy shot.++ Project timestamps also change during video/compose, so they cannot establish+ whether an old image is still current. Legacy recovery requires the last image+ usage for that shot, an owned project and the AI remote marker (uploads clear it).+ """+ candidates = {task.id: task for task in tasks if task.domain == "kepu"+ and kinds.get(task.id, _generation_kind(task)) == "image"+ and not any(_result_urls(value, "image") for value in [task.result_payload,+ *(step.output_payload for step in task.steps)])}+ if not candidates:+ return {}+ events = list((await db.scalars(select(UsageEvent).join(TaskRun, _kepu_usage_matches_task())+ .where(TaskRun.id.in_(candidates), _image_usage_clause()).order_by(UsageEvent.id))).all())+ shot_ids = {event.shot_id for event in events if event.shot_id is not None}+ entities = {shot.id: (shot, project) for shot, project in (await db.execute(+ select(Shot, Project).join(Project, Shot.project_id == Project.id).where(Shot.id.in_(shot_ids)))).all()} if shot_ids else {}+ # Include later tasks outside this page, and other members redrawing a team shot.+ project_ids = {event.project_id for event in events if event.project_id is not None}+ latest = dict((await db.execute(select(UsageEvent.shot_id, func.max(UsageEvent.id))+ .where(UsageEvent.project_id.in_(project_ids), UsageEvent.shot_id.in_(shot_ids), _image_usage_clause())+ .group_by(UsageEvent.shot_id))).all()) if shot_ids and project_ids else {}+ urls = {}+ for event in events:+ try:+ raw = json.loads(event.raw_usage_json or "{}")+ except (ValueError, TypeError):+ continue+ if not isinstance(raw, dict):+ continue+ detail = event.billing_detail or {}+ if detail.get("mode") == "fixed_media" and detail.get("delivered") is not True:+ continue+ url = _safe_url(raw.get("delivery_id"))+ if "delivery_id" not in raw:+ shot, project = entities.get(event.shot_id, (None, None))+ task = candidates[event.task_run_id]+ if (task.status == "succeeded" and shot is not None and latest.get(shot.id) == event.id and shot.image_ark_url+ and shot.project_id == task.project_id and _entity_matches_task(task, project, drama=False)):+ url = _safe_url(shot.image_url)+ if url:+ urls.setdefault(event.task_run_id, []).append(url)+ return {task_id: {"urls": list(dict.fromkeys(values)), "delivered": True} for task_id, values in urls.items()}++async def _submitted_parameters(db, tasks) -> dict[int, dict]:"""Recover only accepted matching requests, never current editable project/fragment fields."""candidates = {task.id: task for task in tasks@@ -352,11 +437,13 @@ async def _load_records(db, user, references, owner_user_id):linked_by_task = {}for task_id, tool in linked:linked_by_task.setdefault(task_id, tool)- fallback = await _legacy_entity_outputs(db, tasks)+ kinds = {row.id: row.kind for row in references if row.source == "task"}+ fallback = await _legacy_entity_outputs(db, tasks, kinds)+ fallback.update(await _kepu_image_outputs(db, tasks, kinds))submitted = await _submitted_parameters(db, tasks)records = {f"task:{task.id}": project_generation(task, viewer_id=user.id, owner_user_id=owner_user_id,linked_tool=linked_by_task.get(task.id), fallback=fallback.get(task.id),- submitted_params=submitted.get(task.id)) for task in tasks}+ submitted_params=submitted.get(task.id), kind_override=kinds.get(task.id)) for task in tasks}records.update({f"tool:{tool.id}": _legacy_projection(tool) for tool in tools})return [records[f"{row.source}:{row.id}"] for row in references]@@ -383,7 +470,8 @@ async def list_generations(db: AsyncSession, user: User, *, page: int = 1, page_ToolRun.params["provider_task_id"].as_string() == value))history = union_all(task_query, tool_query).subquery()bucket = case((history.c.status.in_(_TERMINAL_STATUSES), history.c.status), else_="processing")- filters = []+ # Exclude internal writing work before counts and pagination, including legacy tools.+ filters = [history.c.kind.in_(("image", "video", "audio"))]if kind:filters.append(history.c.kind == kind)if created_from:@@ -397,7 +485,7 @@ async def list_generations(db: AsyncSession, user: User, *, page: int = 1, page_total = counts[status] if status else counts["all"]if status:filters.append(bucket == status)- rows = (await db.execute(select(history.c.source, history.c.id).where(*filters)+ rows = (await db.execute(select(history.c.source, history.c.id, history.c.kind).where(*filters).order_by(history.c.created_at.desc(), history.c.id.desc(), history.c.source.desc()).offset((page - 1) * page_size).limit(page_size))).all()return GenerationListOut(items=await _load_records(db, user, rows, owner_user_id),@@ -406,7 +494,7 @@ async def list_generations(db: AsyncSession, user: User, *, page: int = 1, page_async def get_generation(db: AsyncSession, user: User, task_id: int, *, team_id: int | None = None) -> GenerationRecordOut:scope, owner_user_id = await _workspace(db, user, team_id, {})- row = (await db.execute(select(literal("task").label("source"), TaskRun.id.label("id"))+ row = (await db.execute(select(literal("task").label("source"), TaskRun.id.label("id"), _kind_expression().label("kind")).where(*scope, TaskRun.id == task_id, TaskRun.task_type != "mock_delay"))).first()if row is None:raise LookupError("任务不存在")diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex 87db59b..654e054 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -210,18 +210,36 @@ async def _run_kepu_project_pipeline(task: TaskRun) -> dict[str, Any] | None:from app.services.pipeline import clear_pipeline_cancellation, run_pipelinepayload = task.payload if isinstance(task.payload, dict) else {}- phase = payload.get("phase")if task.cancel_requested:return {"cancelled": True, "project_id": task.project_id}+ project_id = _require_int(task.project_id, "project_id")+ raw_phase = payload.get("phase")+ phase = str(raw_phase).strip().lower() if raw_phase is not None else None+ if phase not in {"script", "assets", "videos", "compose"}:+ from sqlalchemy import select+ from sqlalchemy.orm import selectinload+ from app.database import AsyncSessionLocal+ from app.models import Project+ from app.services.kepu_stages import normalize_kepu_pipeline_phase++ async with AsyncSessionLocal() as db:+ project = (await db.execute(+ select(Project).where(Project.id == project_id).options(selectinload(Project.shots))+ )).scalar_one_or_none()+ if project is not None:+ # Resolve legacy auto/produce before generation changes readiness.+ # Use the pipeline's shared rules for both execution and its saved output.+ phase = normalize_kepu_pipeline_phase(phase, project)+ # The read transaction is closed before awaiting external generation.# The previous task can have been cancelled before its pipeline ever ran,# leaving a process-local marker. Clear it in the executing worker only for# this fresh task; persistent CANCELLED checks still catch a new cancellation.- clear_pipeline_cancellation(_require_int(task.project_id, "project_id"))+ clear_pipeline_cancellation(project_id)return await _await_kepu(task,run_pipeline(- _require_int(task.project_id, "project_id"),- phase=str(phase) if phase is not None else None,+ project_id,+ phase=phase,),phase=phase,)diff --git a/backend/tests/test_generation_history.py b/backend/tests/test_generation_history.pyindex 1642883..9667804 100644--- a/backend/tests/test_generation_history.py+++ b/backend/tests/test_generation_history.py@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_enginefrom app.database import Base, get_dbfrom app.deps import get_current_user-from app.models import Project, Shot, Template, ToolRun, User+from app.models import Project, Shot, Template, ToolRun, UsageEvent, Userfrom app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProjectfrom app.models_tasks import TaskEvent, TaskRunfrom app.models_teams import Team, TeamMember@@ -74,13 +74,13 @@ async def test_history_merges_all_domains_and_legacy_without_duplicates(history)response = await client.get("/api/tasks/generations?page_size=2")assert response.status_code == 200result = response.json()- assert result["total"] == 5- assert result["counts"] == {"all": 5, "processing": 1, "succeeded": 3, "failed": 1, "cancelled": 0}+ assert result["total"] == 4+ assert result["counts"] == {"all": 4, "processing": 1, "succeeded": 2, "failed": 1, "cancelled": 0}assert len(result["items"]) == 2all_rows = (await client.get("/api/tasks/generations?page_size=50")).json()["items"]linked = next(row for row in all_rows if row["record_key"] == f"task:{rows[0].id}")assert linked["prompt"] == "linked prompt"- assert {row["kind"] for row in all_rows} == {"image", "video", "audio", "text"}+ assert {row["kind"] for row in all_rows} == {"image", "video", "audio"}assert len([row for row in all_rows if row["source"] == "tool"]) == 1filtered = (await client.get("/api/tasks/generations?kind=video&status=processing")).json()assert filtered["total"] == 1 and filtered["counts"]["all"] == 2@@ -101,10 +101,48 @@ async def test_pipeline_phase_kind_matches_sql_filter_and_projection(history):async with await client_for(sessions, user) as client:for kind in {"image", "audio", "text", "video"}:result = (await client.get(f"/api/tasks/generations?kind={kind}")).json()- assert result["total"] == sum(value == kind for value in expected.values())+ assert result["total"] == (sum(value == kind for value in expected.values()) if kind != "text" else 0)assert all(row["kind"] == kind and expected[row["params"]["phase"]] == kind for row in result["items"])+async def test_text_tasks_are_excluded_before_counting_search_and_pagination(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ image = task(user)+ text = task(user, "episode_script")+ text.status = "failed"+ db.add_all([image, text, ToolRun(user_id=user.id, tool_id="text", kind="text", status="queued")])+ await db.commit()+ async with await client_for(sessions, user) as client:+ result = (await client.get("/api/tasks/generations?page_size=1")).json()+ assert result["total"] == result["counts"]["all"] == 1+ assert result["counts"]["failed"] == result["counts"]["processing"] == 0+ assert result["items"][0]["id"] == image.id+ assert (await client.get(f"/api/tasks/generations?task_id={text.id}")).json()["total"] == 0+ assert (await client.get("/api/tasks/generations?kind=text")).json()["total"] == 0+ # Hiding list entries must not remove durable task/detail compatibility.+ assert (await client.get(f"/api/tasks/generations/{text.id}")).json()["kind"] == "text"+ async with sessions() as db:+ assert (await db.get(TaskRun, text.id)).status == "failed"+++async def test_legacy_auto_script_is_hidden_despite_incorrect_empty_video_snapshot(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ row = TaskRun(domain="kepu", task_type="project_pipeline", queue_type="video", requested_by=user.id,+ status="succeeded", payload={"phase": "produce"}, result_payload={"kind": "video", "urls": []})+ db.add(row)+ await db.flush()+ db.add(UsageEvent(user_id=user.id, task_run_id=row.id, billing_key="llm_chat", capability="llm", domain="kepu"))+ await db.commit()+ async with await client_for(sessions, user) as client:+ listing = (await client.get("/api/tasks/generations")).json()+ assert listing["total"] == listing["counts"]["all"] == 0+ assert (await client.get(f"/api/tasks/generations/{row.id}")).json()["kind"] == "text"++@pytest.mark.asyncioasync def test_provider_id_links_require_matching_tool_domain_and_media_kind(history):sessions, (user, _, _), _team = historydiff --git a/backend/tests/test_generation_task_registration.py b/backend/tests/test_generation_task_registration.pyindex 0792755..b057346 100644--- a/backend/tests/test_generation_task_registration.py+++ b/backend/tests/test_generation_task_registration.py@@ -223,3 +223,92 @@ async def test_kepu_output_snapshot_freezes_only_matching_media(db_session, monkassert result == {"kind": kind, "urls": [url]}shot.image_url = "/static/replaced.png"assert result["urls"] == [url]++[email protected]("phase,ready,mode,expected_phase,kind,url", [+ (None, "empty", "full", "script", "text", None),+ ("produce", "empty", "full", "script", "text", None),+ (None, "script", "full", "assets", "image", "/static/generated.png"),+ ("produce", "script", "full", "assets", "image", "/static/generated.png"),+ (None, "assets", "full", "videos", "video", "/static/generated.mp4"),+ ("produce", "assets", "full", "videos", "video", "/static/generated.mp4"),+ (None, "videos", "full", "compose", "video", "/static/generated-final.mp4"),+ ("produce", "videos", "full", "compose", "video", "/static/generated-final.mp4"),+ (None, "assets", "image_text", "compose", "video", "/static/generated-final.mp4"),+ ("script", "assets", "full", "script", "text", None),+ ("assets", "script", "full", "assets", "image", "/static/generated.png"),+ ("videos", "assets", "full", "videos", "video", "/static/generated.mp4"),+ ("compose", "videos", "full", "compose", "video", "/static/generated-final.mp4"),+])+async def test_pipeline_legacy_phase_runs_and_snapshots_the_same_resolved_stage(+ monkeypatch, phase, ready, mode, expected_phase, kind, url,+):+ from app.services import pipeline+ from app.services.tasks import handlers++ shots = [] if ready == "empty" else [SimpleNamespace(+ image_url="/static/image.png" if ready in {"assets", "videos"} else None,+ video_url="/static/video.mp4" if ready == "videos" else None,+ narration="完整脚本", segment_script=None,+ )]+ project = SimpleNamespace(id=3, shots=shots, pipeline_mode=mode, cover_url=None, final_video_url=None)+ monkeypatch.setattr("app.services.kepu_stages.project_audio_ready", lambda _project: True)+ result_rows = SimpleNamespace(scalar_one_or_none=lambda: project, scalars=lambda: SimpleNamespace(all=lambda: shots))+ db = SimpleNamespace(get=AsyncMock(return_value=project), execute=AsyncMock(return_value=result_rows))+ opened = 0++ @asynccontextmanager+ async def session_factory():+ nonlocal opened+ opened += 1+ try:+ yield db+ finally:+ opened -= 1++ monkeypatch.setattr("app.database.AsyncSessionLocal", session_factory)++ async def run(project_id, *, phase):+ # Stage selection must return its read connection before any provider wait.+ assert opened == 0+ assert project_id == project.id and phase == expected_phase+ if phase == "script" and not shots:+ shots.append(SimpleNamespace(narration="完整脚本", segment_script=None))+ elif phase == "assets":+ shots[0].image_url = url+ elif phase == "videos":+ shots[0].video_url = url+ elif phase == "compose":+ project.final_video_url = url++ stage = AsyncMock(side_effect=run)+ monkeypatch.setattr(pipeline, "run_pipeline", stage)+ task = TaskRun(task_type="project_pipeline", project_id=project.id, cancel_requested=False,+ payload={} if phase is None else {"phase": phase})+ original_payload = dict(task.payload)+ result = await handlers._run_kepu_project_pipeline(task)+ stage.assert_awaited_once()+ assert result["phase"] == expected_phase+ assert result["kind"] == kind+ if kind == "text":+ assert result["text_content"] == "完整脚本"+ else:+ assert result["urls"] == [url]+ assert task.payload == original_payload # No new task or billing dimensions are introduced.+ assert opened == 0+++async def test_cancelled_legacy_pipeline_does_not_resolve_or_run_another_stage(monkeypatch):+ from app.services import pipeline+ from app.services.tasks import handlers++ session_factory = AsyncMock(side_effect=AssertionError("cancelled tasks must not query their next stage"))+ monkeypatch.setattr("app.database.AsyncSessionLocal", session_factory)+ stage = AsyncMock()+ monkeypatch.setattr(pipeline, "run_pipeline", stage)+ task = TaskRun(task_type="project_pipeline", project_id=3, cancel_requested=True, payload={"phase": "produce"})+ assert await handlers._run_kepu_project_pipeline(task) == {"cancelled": True, "project_id": 3}+ session_factory.assert_not_called()+ stage.assert_not_awaited()diff --git a/backend/tests/test_kepu_image_history.py b/backend/tests/test_kepu_image_history.pynew file mode 100644index 0000000..ba6ffe9--- /dev/null+++ b/backend/tests/test_kepu_image_history.py@@ -0,0 +1,274 @@+"""Recover AI short-video images from durable task evidence without inventing old outputs."""++from __future__ import annotations++import json+import uuid+from datetime import UTC, datetime, timedelta++import pytest++from app.models import Project, ProjectStatus, Shot, Template, UsageEvent+from app.models_tasks import TaskRun+from tests.test_generation_history import client_for, history, task # noqa: F401+++async def _project(db, user, *, count=1):+ template = Template(id=f"kepu-history-{uuid.uuid4().hex}", name="History", style_prefix="")+ db.add(template)+ await db.flush()+ now = datetime.now(UTC)+ project = Project(+ user_id=user.id, template_id=template.id, title="AI short video", source_text="A story",+ status=ProjectStatus.DONE, final_video_url="https://output.test/final.mp4",+ updated_at=now + timedelta(minutes=5),+ )+ db.add(project)+ await db.flush()+ shots = [Shot(+ project_id=project.id, shot_no=index,+ image_url=f"https://output.test/project-{project.id}-shot-{index}.png",+ image_ark_url=f"https://provider.test/project-{project.id}-shot-{index}.png",+ ) for index in range(1, count + 1)]+ db.add_all(shots)+ await db.flush()+ return project, shots+++async def _image_task(db, user, project, *, phase="assets", shot=None, result=None,+ status="succeeded", created_at=None):+ at = created_at or datetime.now(UTC)+ row = TaskRun(+ domain="kepu", task_type="shot_regen_image" if shot else "project_pipeline",+ requested_by=user.id, queue_type="image" if phase == "assets" or shot else "video",+ status=status, project_id=project.id, shot_id=shot.id if shot else None,+ payload={"phase": phase} if phase is not None else {}, result_payload=result,+ created_at=at, finished_at=at + timedelta(seconds=1),+ )+ db.add(row)+ await db.flush()+ return row+++async def _image_event(db, row, shot, *, raw=None, detail=None, **overrides):+ fields = {+ "user_id": row.requested_by, "team_id": row.team_id,+ "task_run_id": row.id, "project_id": row.project_id, "shot_id": shot.id,+ "domain": "kepu", "capability": "image", "billing_key": "seedream",+ "raw_usage_json": json.dumps({"usage": {"total_tokens": 1}}) if raw is None else raw,+ "billing_detail": detail,+ }+ event = UsageEvent(**{**fields, **overrides})+ db.add(event)+ await db.flush()+ return event+++ ("phase", "result"),+ [(None, None), ("produce", None), ("produce", {"kind": "video", "urls": []})],+ ids=["old-automatic-stage", "produce-without-snapshot", "produce-with-empty-video-snapshot"],+)+async def test_legacy_image_stage_is_classified_and_restored_after_later_compose(history, phase, result):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ image = await _image_task(db, user, project, phase=phase, result=result)+ await _image_event(db, image, shot)+ compose = TaskRun(+ domain="kepu", task_type="project_compose_only", queue_type="video", status="succeeded",+ requested_by=user.id, project_id=project.id, payload={"phase": "compose"},+ result_payload={"kind": "video", "urls": [project.final_video_url]},+ created_at=image.created_at + timedelta(minutes=1),+ )+ db.add(compose)+ await db.commit()+ async with await client_for(sessions, user) as client:+ response = await client.get("/api/tasks/generations?kind=image")+ assert response.status_code == 200+ listing = response.json()+ assert listing["total"] == 1+ record = listing["items"][0]+ assert record["platform_task_id"] == image.id+ assert record["kind"] == "image"+ assert record["urls"] == [shot.image_url]+ detail = await client.get(f"/api/tasks/generations/{image.id}")+ assert detail.status_code == 200+ assert detail.json()["kind"] == "image"+ assert detail.json()["urls"] == [shot.image_url]+ async with sessions() as db:+ persisted = await db.get(TaskRun, image.id)+ assert persisted.result_payload == result++[email protected]("later_is_other_member", [False, True], ids=["outside-page", "other-member"])+async def test_later_redraw_outside_candidate_page_never_becomes_an_old_tasks_output(+ history, later_is_other_member,+):+ sessions, (user, member, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ old = await _image_task(db, user, project, created_at=datetime.now(UTC) - timedelta(minutes=2))+ await _image_event(db, old, shot)+ newer = await _image_task(db, member if later_is_other_member else user, project, shot=shot)+ await _image_event(db, newer, shot)+ await db.commit()+ async with await client_for(sessions, user) as client:+ # Date filtering leaves only the old task in the page. The newer usage+ # must still prevent the current image being assigned to that task.+ response = await client.get("/api/tasks/generations", params={+ "kind": "image", "page_size": 1,+ "created_to": (old.created_at + timedelta(seconds=30)).isoformat(),+ })+ assert response.status_code == 200+ listing = response.json()+ assert listing["total"] == 1+ assert listing["items"][0]["platform_task_id"] == old.id+ assert listing["items"][0]["urls"] == []+++async def test_manual_upload_is_not_recovered_as_an_old_ai_generation(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ row = await _image_task(db, user, project)+ await _image_event(db, row, shot)+ shot.image_url = "/static/manual-upload.png"+ shot.image_ark_url = None+ await db.commit()+ async with await client_for(sessions, user) as client:+ record = (await client.get(f"/api/tasks/generations/{row.id}")).json()+ assert record["urls"] == []+ assert record["preview_url"] is None++[email protected]("mismatch", ["user", "team", "project", "shot"])+async def test_mismatched_usage_cannot_supply_an_image_or_private_delivery(history, mismatch):+ sessions, (user, member, _), team = history+ async with sessions() as db:+ project, shots = await _project(db, user, count=2)+ other_project, _ = await _project(db, user)+ row = await _image_task(db, user, project, shot=shots[0])+ overrides = {+ "user": {"user_id": member.id}, "team": {"team_id": team.id},+ "project": {"project_id": other_project.id}, "shot": {"shot_id": shots[1].id},+ }[mismatch]+ await _image_event(db, row, shots[0],+ raw=json.dumps({"delivery_id": "https://private.test/wrong-output.png"}),+ **overrides)+ await db.commit()+ async with await client_for(sessions, user) as client:+ response = await client.get(f"/api/tasks/generations/{row.id}")+ assert response.status_code == 200+ assert response.json()["urls"] == []+ assert "private.test" not in response.text+++async def test_batch_images_are_preserved_once_even_with_duplicate_usage_rows(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, shots = await _project(db, user, count=2)+ row = await _image_task(db, user, project)+ for shot in shots:+ await _image_event(db, row, shot)+ await _image_event(db, row, shots[0])+ await db.commit()+ async with await client_for(sessions, user) as client:+ record = (await client.get(f"/api/tasks/generations/{row.id}")).json()+ assert set(record["urls"]) == {shot.image_url for shot in shots}+ assert len(record["urls"]) == 2+ assert record["preview_url"] in record["urls"]+++async def test_explicit_delivery_keeps_the_old_image_after_later_redraw(history):+ sessions, (user, _, _), _team = history+ old_url = "https://output.test/immutable-old-image.png"+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ old = await _image_task(db, user, project)+ await _image_event(db, old, shot, raw=json.dumps({"delivery_id": old_url}))+ newer = await _image_task(db, user, project, shot=shot)+ await _image_event(db, newer, shot)+ await db.commit()+ async with await client_for(sessions, user) as client:+ record = (await client.get(f"/api/tasks/generations/{old.id}")).json()+ assert record["urls"] == [old_url]+ assert shot.image_url not in record["urls"]+++async def test_nonempty_final_video_snapshot_is_not_projected_as_an_image(history):+ """An old automatic image-text pipeline may generate images and compose a video."""+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ project.pipeline_mode = "image_text"+ row = await _image_task(db, user, project, phase="produce", result={+ "kind": "video", "urls": [project.final_video_url],+ })+ await _image_event(db, row, shot)+ await db.commit()+ async with await client_for(sessions, user) as client:+ record = (await client.get(f"/api/tasks/generations/{row.id}")).json()+ assert record["kind"] == "video"+ assert record["urls"] == [project.final_video_url]+ videos = (await client.get("/api/tasks/generations?kind=video")).json()+ assert videos["total"] == 1+ images = (await client.get("/api/tasks/generations?kind=image")).json()+ assert images["total"] == 0++[email protected]("status", ["failed", "cancelled"])+async def test_unsuccessful_redraw_without_delivery_cannot_borrow_the_previous_image(history, status):+ """A billed attempt may finish without applying its result to the existing shot."""+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ old = await _image_task(db, user, project, result={"kind": "image", "urls": [shot.image_url]})+ await _image_event(db, old, shot)+ redraw = await _image_task(db, user, project, shot=shot, status=status)+ await _image_event(db, redraw, shot, raw=json.dumps({"usage": {"cost_fen": 30}}))+ await db.commit()+ async with await client_for(sessions, user) as client:+ record = (await client.get(f"/api/tasks/generations/{redraw.id}")).json()+ assert record["status"] == status+ assert record["urls"] == []+ previous = (await client.get(f"/api/tasks/generations/{old.id}")).json()+ assert previous["urls"] == [shot.image_url]+++async def test_partially_failed_image_batch_keeps_its_successful_delivery(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ row = await _image_task(db, user, project, status="failed")+ row.error_message = "The next image failed"+ await _image_event(db, row, shot, raw=json.dumps({"delivery_id": shot.image_url}),+ detail={"mode": "fixed_media", "delivered": True})+ await db.commit()+ async with await client_for(sessions, user) as client:+ result = (await client.get("/api/tasks/generations?kind=image&status=failed")).json()+ assert result["total"] == 1+ record = result["items"][0]+ assert record["status"] == "failed"+ assert record["urls"] == [shot.image_url]+ assert record["error"] == "The next image failed"+++ ("raw", "detail"),+ [("{truncated", None), ("[]", None),+ (json.dumps({"delivery_id": "https://private.test/not-delivered.png"}),+ {"mode": "fixed_media", "delivered": False})],+ ids=["truncated-json", "non-object-json", "no-delivery"],+)+async def test_invalid_or_undelivered_usage_is_ignored_without_breaking_history(history, raw, detail):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ project, (shot,) = await _project(db, user)+ row = await _image_task(db, user, project)+ await _image_event(db, row, shot, raw=raw, detail=detail)+ await db.commit()+ async with await client_for(sessions, user) as client:+ response = await client.get(f"/api/tasks/generations/{row.id}")+ assert response.status_code == 200+ assert response.json()["urls"] == []diff --git a/frontend/src/api/generationTasks.ts b/frontend/src/api/generationTasks.tsindex 7a0f30b..8a8ab01 100644--- a/frontend/src/api/generationTasks.ts+++ b/frontend/src/api/generationTasks.ts@@ -1,18 +1,16 @@import { createJsonRequester } from './client'import { apiErrorMessage } from './http'import type { ToolRunFilters, ToolRunList, ToolRunRecord } from './tools'-import { generationDetailPath } from '../lib/generationTaskHistory'+import { generationDetailPath, generationTaskListPath } from '../lib/generationTaskHistory'const request = createJsonRequester((response, detail) => {if (response.status === 401) throw new Error('未登录')throw new Error(apiErrorMessage(detail, '加载任务失败'))})-/** 当前创作空间的全部生成记录;不传 kind 时包含文字、图片、音频和视频。 */+/** 当前创作空间的图片、音频和视频记录;旧文字筛选兼容为全部媒体。 */export function listGenerationTasks(page = 1, pageSize = 8, filters: ToolRunFilters = {}): Promise<ToolRunList> {- const query = new URLSearchParams({ page: String(page), page_size: String(pageSize) })- for (const [key, value] of Object.entries(filters)) if (value) query.set(key, value)- return request(`/api/tasks/generations?${query}`)+ return request(generationTaskListPath(page, pageSize, filters))}export function getGenerationTaskDetail(record: Pick<ToolRunRecord, 'id' | 'source'>): Promise<ToolRunRecord> {diff --git a/frontend/src/lib/generationTaskHistory.ts b/frontend/src/lib/generationTaskHistory.tsindex 8333962..2610e36 100644--- a/frontend/src/lib/generationTaskHistory.ts+++ b/frontend/src/lib/generationTaskHistory.ts@@ -1,4 +1,20 @@-import type { ToolRunRecord } from '../api/tools.ts'+import type { ToolRunFilters, ToolRunRecord } from '../api/tools.ts'++export const generationTaskKinds = ['all', 'video', 'image', 'audio'] as const+export type GenerationTaskKind = typeof generationTaskKinds[number]++/** 我的任务仅展示媒体;兼容以前的 kind=text 收藏链接。 */+export function generationTaskKind(kind?: string | null): GenerationTaskKind {+ return generationTaskKinds.includes(kind as GenerationTaskKind) ? kind as GenerationTaskKind : 'all'+}++export function generationTaskListPath(page: number, pageSize: number, filters: ToolRunFilters = {}): string {+ const query = new URLSearchParams({ page: String(page), page_size: String(pageSize) })+ for (const [key, value] of Object.entries(filters)) if (key !== 'kind' && value) query.set(key, value)+ const kind = generationTaskKind(filters.kind)+ if (kind !== 'all') query.set('kind', kind)+ return `/api/tasks/generations?${query}`+}/** TaskRun 与旧工具记录的数字 ID 独立,列表、下载和轮询必须带来源。 */export function generationRecordKey(record: ToolRunRecord): string {diff --git a/frontend/src/pages/GenerationTasksPage.tsx b/frontend/src/pages/GenerationTasksPage.tsxindex 49af6eb..9ad1824 100644--- a/frontend/src/pages/GenerationTasksPage.tsx+++ b/frontend/src/pages/GenerationTasksPage.tsx@@ -9,13 +9,11 @@ import GenerationSelect from '../components/tools/GenerationSelect'import { AssetDetailDialog } from '../components/assets/AssetDetailDialog'import { useToolRunDetail } from '../hooks/useToolRunDetail'import { mediaIcons, useGenerationText } from '../lib/generationMedia'-import { generationBillingState, generationRecordKey } from '../lib/generationTaskHistory'+import { generationBillingState, generationRecordKey, generationTaskKind, generationTaskKinds as taskKinds, type GenerationTaskKind as TaskKind } from '../lib/generationTaskHistory'import { subscribeWorkspace, workspaceScope } from '../features/teams/workspaceScope'import Pagination from '../components/ui/Pagination'import { fetchMediaBlob, triggerBlobDownload } from '../lib/clientDownload'-const taskKinds = ['all', 'video', 'image', 'audio', 'text'] as const-type TaskKind = typeof taskKinds[number]const taskIcons = { ...mediaIcons, all: ListChecks, text: FileText }const workspaceSnapshot = () => workspaceScope.epoch@@ -32,7 +30,7 @@ function TaskHistory() {function TaskHistoryContent() {const text = useGenerationText()const [params, setParams] = useSearchParams()- const kind = taskKinds.includes(params.get('kind') as TaskKind) ? params.get('kind') as TaskKind : 'all'+ const kind = generationTaskKind(params.get('kind'))const status = ['processing', 'succeeded', 'failed', 'cancelled'].includes(params.get('status') || '') ? params.get('status')! : ''const taskId = params.get('task_id') || ''const [query, setQuery] = useState(taskId)@@ -49,14 +47,14 @@ function TaskHistoryContent() {const { detail, asset: detailAsset, error: detailError, resultIndex, selectResult, openDetail, closeDetail } = useToolRunDetail()const [downloading, setDownloading] = useState<string | null>(null)const Icon = taskIcons[kind]- const createPath = kind === 'all' ? '/' : kind === 'text' ? '/studio/new' : `/tools/${kind}`+ const createPath = kind === 'all' ? '/' : `/tools/${kind}`const labels: Record<string, string> = {all: text('全部', 'All'), processing: text('处理中', 'Processing'), succeeded: text('已完成', 'Completed'),failed: text('失败', 'Failed'), cancelled: text('已取消', 'Cancelled'), queued: text('排队中', 'Queued'), running: text('处理中', 'Processing'),}const kindLabels: Record<TaskKind, string> = {all: text('全部任务', 'All tasks'), video: text('视频任务', 'Video tasks'), image: text('图片任务', 'Image tasks'),- audio: text('音频任务', 'Audio tasks'), text: text('文字任务', 'Text tasks'),+ audio: text('音频任务', 'Audio tasks'),}const billingLabels = {hidden: text('费用不可见', 'Cost hidden'), pending: text('待结算', 'Pending charge'), settled: text('已结算', 'Charged'),@@ -67,6 +65,13 @@ function TaskHistoryContent() {if (value) next.set(key, value); else next.delete(key)setParams(next); setPage(1)}+ useEffect(() => {+ const requestedKind = params.get('kind')+ if (!requestedKind || requestedKind === kind) return+ const next = new URLSearchParams(params)+ next.delete('kind')+ setParams(next, { replace: true })+ }, [params, setParams, kind])useEffect(() => { setQuery(taskId) }, [taskId])useEffect(() => {let disposed = false@@ -157,13 +162,15 @@ function TaskHistoryContent() {const recordKey = generationRecordKey(item)const billingState = generationBillingState(item)const ratio = typeof (item.params?.aspect_ratio ?? item.params?.ratio) === 'string' ? String(item.params?.aspect_ratio ?? item.params?.ratio) : ''+ const shortVideoImage = item.domain === 'kepu' && item.kind === 'image'+ const title = item.prompt || (shortVideoImage ? text('AI短视频生图', 'AI short video images') : text('生成任务', 'Generation task'))const formatLabel = item.kind === 'video' ? 'MP4' : item.kind === 'audio' ? 'MP3' : item.kind === 'text' ? text('文字', 'Text') : text('图片', 'Image')return <article className={`gen-task-row ${item.status === 'failed' ? 'has-error' : ''}`} key={recordKey}><button className="gen-task-cover" type="button" onClick={() => openDetail(item)} aria-label={text('查看生成结果', 'View result')}>{item.kind === 'image' && (item.preview_url || item.urls[0]) ? <img src={resolveToolMediaUrl(item.preview_url || item.urls[0])} alt="" /> : item.kind === 'video' && item.preview_url ? <img src={resolveToolMediaUrl(item.preview_url)} alt="" /> : item.kind === 'video' && item.urls[0] ? <video src={resolveToolMediaUrl(item.urls[0])} preload="metadata" muted /> : <RowIcon size={28} />}<span className="gen-cover-overlay"><Eye size={18} /></span></button>- <div className="gen-task-description"><button type="button" className="gen-task-title" onClick={() => openDetail(item)} title={item.prompt}>{item.prompt || text('生成任务', 'Generation task')}</button><div className="gen-task-metadata"><span className="gen-task-tag">{kindLabels[item.kind as TaskKind] || 'AI'}</span>{ratio && <span className="gen-task-tag">{ratio}</span>}</div>{item.error && <button type="button" className="gen-task-error" onClick={() => openDetail(item)} title={item.error}><AlertCircle size={12} /><span>{errorSummary(item.error)}</span><ArrowUpRight size={12} /></button>}</div>+ <div className="gen-task-description"><button type="button" className="gen-task-title" onClick={() => openDetail(item)} title={title}>{title}</button><div className="gen-task-metadata"><span className="gen-task-tag">{kindLabels[item.kind as TaskKind] || 'AI'}</span>{shortVideoImage && <span className="gen-task-tag">{text('AI短视频', 'AI short video')}</span>}{item.kind === 'image' && item.urls.length > 1 && <span className="gen-task-tag">{text(`${item.urls.length} 张图片`, `${item.urls.length} images`)}</span>}{ratio && <span className="gen-task-tag">{ratio}</span>}</div>{item.error && <button type="button" className="gen-task-error" onClick={() => openDetail(item)} title={item.error}><AlertCircle size={12} /><span>{errorSummary(item.error)}</span><ArrowUpRight size={12} /></button>}</div><div className="gen-task-state"><span className={`gen-state is-${item.status}`}><RowStatusIcon size={13} />{labels[item.status] || item.status}</span><small>{formatLabel}</small></div><div className="gen-task-cost"><strong>{billingState === 'hidden' ? '—' : `¥${((item.billing_charged_fen || 0) / 100).toFixed(2)}`}</strong><small>{billingLabels[billingState]}</small></div><div className="gen-task-time"><span>{when(item.created_at)}</span><small>{text('耗时', 'Duration')} {elapsed(item)}</small></div>diff --git a/frontend/tests/generation-task-history.test.mjs b/frontend/tests/generation-task-history.test.mjsindex cd62927..0070d54 100644--- a/frontend/tests/generation-task-history.test.mjs+++ b/frontend/tests/generation-task-history.test.mjs@@ -1,12 +1,37 @@import test from 'node:test'import assert from 'node:assert/strict'-import { generationRecordKey, generationDetailPath, generationBillingState } from '../src/lib/generationTaskHistory.ts'+import { generationRecordKey, generationDetailPath, generationBillingState, generationTaskKinds, generationTaskKind, generationTaskListPath } from '../src/lib/generationTaskHistory.ts'import { toolRunDetailAsset } from '../src/lib/toolRunDetails.ts'import { assetDetailInfo } from '../src/lib/assetDetails.ts'import { scopedRequestInit, setWorkspaceTeam } from '../src/features/teams/workspaceScope.ts'const record = { id: 42, tool_id: 'image', kind: 'image', status: 'succeeded', prompt: 'A portrait', urls: [], created_at: '2026-10-26T10:00:00Z' }+test('我的任务只提供全部、视频、图片和音频筛选', () => {+ assert.deepEqual(generationTaskKinds, ['all', 'video', 'image', 'audio'])+ for (const kind of generationTaskKinds) assert.equal(generationTaskKind(kind), kind)+})++test('旧文字任务链接和未知类型回到全部媒体任务', () => {+ for (const kind of ['text', 'unknown', '', null, undefined]) assert.equal(generationTaskKind(kind), 'all')+})++test('旧文字筛选不再传给列表 API,并保留其他筛选和分页', () => {+ const path = generationTaskListPath(2, 16, { kind: 'text', status: 'succeeded', task_id: 'task-42', created_from: '2026-10-26T00:00:00Z' })+ const url = new URL(path, 'https://printfilm.example')+ assert.equal(url.pathname, '/api/tasks/generations')+ assert.equal(url.searchParams.has('kind'), false)+ assert.equal(url.searchParams.get('page'), '2')+ assert.equal(url.searchParams.get('page_size'), '16')+ assert.equal(url.searchParams.get('status'), 'succeeded')+ assert.equal(url.searchParams.get('task_id'), 'task-42')+ assert.equal(url.searchParams.get('created_from'), '2026-10-26T00:00:00Z')+ for (const kind of ['video', 'image', 'audio']) {+ assert.equal(new URL(generationTaskListPath(1, 8, { kind }), url).searchParams.get('kind'), kind)+ }+ assert.equal(new URL(generationTaskListPath(1, 8, { kind: 'all' }), url).searchParams.has('kind'), false)+})+test('同数字 ID 的任务和旧工具记录使用独立标识及详情地址', () => {const task = { ...record, source: 'task' }assert.equal(generationRecordKey(task), 'task:42')