PRINTFILM: AI short-video marketing and AI short-drama creation platform
feat(tasks): 汇总全部生成记录并持久化任务状态和结果
yie032b5378343
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.pyindex d10a934..0a4a142 100644--- a/backend/app/api/drama/episodes.py+++ b/backend/app/api/drama/episodes.py@@ -891,11 +891,13 @@ async def compose_episode("""只合成本次受理的分集,系统占用持续到文件完成。"""return await compose_episode_video(db, episode=episode, project=project, fragment_ids=req.fragment_ids)- if project.team_id is not None:- _, url = await run_billed_ephemeral(db, user, domain="drama", task_type="episode_compose", executor=compose_current_episode,- drama_project_id=project.id, episode_id=episode.id)- else:- url = await compose_current_episode()+ _, url = await run_billed_ephemeral(+ db, user, domain="drama", task_type="episode_compose", executor=compose_current_episode,+ drama_project_id=project.id, episode_id=episode.id,+ payload={"fragment_ids": req.fragment_ids},+ billable=project.team_id is not None,+ result_payload_factory=lambda result: {"kind": "video", "urls": [result] if result else []},+ )except RuntimeError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excexcept Exception as exc: # noqa: BLE001diff --git a/backend/app/api/drama/generation.py b/backend/app/api/drama/generation.pyindex dd872aa..8e2dded 100644--- a/backend/app/api/drama/generation.py+++ b/backend/app/api/drama/generation.py@@ -203,6 +203,10 @@ async def suggest_voice_prompt(drama_project_id=project.id,asset_id=asset.id,commit=True,+ result_payload_factory=lambda result: {+ "kind": "text", "text_content": result[0],+ "speaker": result[1], "sample_text": result[2],+ },)except ValueError as exc:raise http_exception_for_value_error(exc) from exc@@ -293,19 +297,20 @@ async def generate_voice()try:- if team_mode:- _, updated = await run_billed_ephemeral(- db,- user,- domain="drama",- task_type="voice_synthesis",- executor=_synthesize,- drama_project_id=project.id,- asset_id=asset.id,- payload={"asset_id": asset.id},- )- else:- updated = await _synthesize()+ _, updated = await run_billed_ephemeral(+ db,+ user,+ domain="drama",+ task_type="voice_synthesis",+ executor=_synthesize,+ drama_project_id=project.id,+ asset_id=asset.id,+ payload={"asset_id": asset.id, "prompt": prompt, "sample_text": body.sample_text},+ billable=team_mode,+ result_payload_factory=lambda result: {+ "kind": "audio", "urls": [result.url] if result.url else [], "asset_id": result.id,+ },+ )except Exception as exc: # noqa: BLE001project_id, asset_id = project.id, asset.idif team_mode and not started:diff --git a/backend/app/api/projects.py b/backend/app/api/projects.pyindex 2012c68..97fc11a 100644--- a/backend/app/api/projects.py+++ b/backend/app/api/projects.py@@ -93,12 +93,17 @@ async def get_media_models(db: AsyncSession = Depends(get_db)) -> dict:@router.post("/voices/preview", response_model=VoicePreviewOut)async def preview_voice(body: VoicePreviewRequest,+ db: AsyncSession = Depends(get_db),user: User = Depends(get_current_user),) -> VoicePreviewOut:"""Generate a short cached TTS sample for audition."""- _ = usertry:- url = await ensure_voice_preview(body.voice_id)+ _, url = await run_billed_ephemeral(+ db, user, domain="kepu", task_type="voice_preview",+ executor=lambda: ensure_voice_preview(body.voice_id),+ payload={"voice_id": body.voice_id}, billable=False,+ result_payload_factory=lambda result: {"kind": "audio", "urls": [result] if result else []},+ )except Exception as exc: # noqa: BLE001raise HTTPException(status_code=502, detail=f"试听生成失败:{exc}") from excreturn VoicePreviewOut(url=url, voice_id=body.voice_id)diff --git a/backend/app/api/tasks.py b/backend/app/api/tasks.pyindex e1149ee..29449d9 100644--- a/backend/app/api/tasks.py+++ b/backend/app/api/tasks.py@@ -3,6 +3,7 @@from __future__ import annotationsimport asyncioimport re+from datetime import datetimefrom app.config import get_settingsfrom fastapi import APIRouter, Depends, Header, HTTPException, Query@@ -12,6 +13,8 @@ from app.database import get_dbfrom app.deps import get_current_userfrom app.models import Userfrom app.schemas_tasks import MockDelayTaskRequest, TaskCreateRequest, TaskListOut, TaskRunOut+from app.schemas_generation_history import GenerationListOut, GenerationRecordOut+from app.services.tasks.generation_history import get_generation, list_generationsfrom app.services.billing.http import http_exception_for_value_errorfrom app.services.tasks.service import (TaskAccessContext,@@ -115,6 +118,46 @@ async def create_mock_delay_task(return public_task(task, viewer=user)+def _generation_workspace(team_id: int | None, workspace_team_id: int | None) -> int | None:+ if team_id is not None and workspace_team_id is not None and team_id != workspace_team_id:+ raise HTTPException(status_code=422, detail="团队空间参数不一致")+ return team_id if team_id is not None else workspace_team_id++[email protected]("/generations", response_model=GenerationListOut)+async def list_generation_history(+ page: int = Query(1, ge=1), page_size: int = Query(20, ge=1, le=100),+ kind: str | None = Query(None, pattern="^(video|image|audio|text)$"),+ status: str | None = Query(None, pattern="^(processing|succeeded|failed|cancelled)$"),+ task_id: str | None = Query(None, max_length=128),+ created_from: datetime | None = None, created_to: datetime | None = None,+ team_id: int | None = Query(None, ge=1),+ workspace_team_id: int | None = Header(None, alias="X-Team-Id", ge=1),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> GenerationListOut:+ if created_from and created_to:+ from datetime import UTC+ start = created_from.replace(tzinfo=UTC) if created_from.tzinfo is None else created_from+ end = created_to.replace(tzinfo=UTC) if created_to.tzinfo is None else created_to+ if start > end:+ raise HTTPException(status_code=400, detail="开始时间不能晚于结束时间")+ return await list_generations(db, user, page=page, page_size=page_size, kind=kind, status=status,+ task_id=task_id, created_from=created_from, created_to=created_to,+ team_id=_generation_workspace(team_id, workspace_team_id))++[email protected]("/generations/{task_id}", response_model=GenerationRecordOut)+async def get_generation_history(+ task_id: int, team_id: int | None = Query(None, ge=1),+ workspace_team_id: int | None = Header(None, alias="X-Team-Id", ge=1),+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user),+) -> GenerationRecordOut:+ try:+ return await get_generation(db, user, task_id, team_id=_generation_workspace(team_id, workspace_team_id))+ except LookupError as exc:+ raise HTTPException(status_code=404, detail="任务不存在") from exc++# 查询单个任务详情(含 steps/targets/events)@router.get("/{task_id}", response_model=TaskRunOut)async def get_task_run(diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.pyindex 8a391c6..32448db 100644--- a/backend/app/api/v1/generation.py+++ b/backend/app/api/v1/generation.py@@ -227,6 +227,7 @@ async def get_task(owned_task = await db.get(TaskRun, owned)async with billing_scope(owned, snapshot=owned_task.billing_snapshot):data = await poll_video_task(user, tid)+ owned_task.result_payload = {"kind": "video", **data}await settle_deferred_video_poll(db,user,diff --git a/backend/app/schemas_generation_history.py b/backend/app/schemas_generation_history.pynew file mode 100644index 0000000..3dc51e7--- /dev/null+++ b/backend/app/schemas_generation_history.py@@ -0,0 +1,42 @@+"""Public, provider-independent generation history records."""++from datetime import datetime+from typing import Literal++from pydantic import BaseModel, Field+++class GenerationRecordOut(BaseModel):+ id: int+ source: Literal["task", "tool"]+ record_key: str+ tool_id: str+ kind: Literal["video", "image", "audio", "text"]+ status: str+ domain: str | None = None+ task_type: str | None = None+ prompt: str = ""+ preview_url: str | None = None+ urls: list[str] = Field(default_factory=list)+ text_content: str = ""+ task_id: str | None = None+ params: dict = Field(default_factory=dict)+ error: str | None = None+ created_at: str = ""+ platform_task_id: int | None = None+ provider_task_id: str | None = None+ provider_name: str | None = None+ provider_status: str | None = None+ queue_type: str | None = None+ started_at: datetime | None = None+ finished_at: datetime | None = None+ billing_status: str = "none"+ billing_charged_fen: int | None = 0+++class GenerationListOut(BaseModel):+ items: list[GenerationRecordOut] = Field(default_factory=list)+ total: int = 0+ page: int = 1+ page_size: int = 20+ counts: dict[str, int] = Field(default_factory=dict)diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex 6abf30f..afdfcbe 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -2,6 +2,7 @@"""轻量 TaskRun:同步执行并计费(聊天、API、工具)。"""from __future__ import annotations+import asynciofrom collections.abc import Awaitable, Callablefrom datetime import UTC, datetimefrom typing import Any, TypeVar@@ -17,6 +18,7 @@ from app.config import get_settingsfrom app.services.billing.context import billing_scopefrom app.services.billing.settlement import freeze_for_task, settle_taskfrom app.services.tasks.handlers import get_task_handler+from app.services.tasks.inline import hold_inline_lease, start_inline_leasefrom app.services.tasks.queues import task_queuefrom app.services.tasks.service import append_task_event, build_task_event, build_task_stepfrom app.services.tasks.upstream import upstream_event_session@@ -114,6 +116,8 @@ async def run_billed_ephemeral(asset_id: int | None = None,episode_id: int | None = None,commit: bool = True,+ billable: bool = True,+ result_payload_factory: Callable[[T], dict[str, Any]] | None = None,) -> tuple[TaskRun, T]:"""创建轻量 TaskRun → 预扣 → 在 billing_scope 内执行 → 结算。@@ -133,7 +137,13 @@ async def run_billed_ephemeral(episode_id=episode_id,)try:- await freeze_for_task(db, task)+ if billable:+ await freeze_for_task(db, task)+ else:+ # Auditions and personal legacy synthesis remain free. They still+ # share the durable task lifecycle without creating a new charge.+ task.billing_status = "skipped"+ task.billing_enabled_snapshot = Falseexcept ValueError:task.status = "failed"task.error_code = "insufficient_balance"@@ -146,6 +156,7 @@ async def run_billed_ephemeral(now = datetime.now(UTC)task.status = "running"task.started_at = now+ start_inline_lease(task, now)await append_task_event(db,task.id,@@ -155,20 +166,20 @@ async def run_billed_ephemeral()await db.flush()- if task.team_id is not None or task.billing_snapshot is not None:- # Accepted team work is durable before network I/O; release the shared- # team/member/project/wallet admission locks even for commit=False callers.- await db.commit()+ # Accepted work must be visible while the provider is still generating.+ # commit=False controls the caller's final success transaction only; task+ # admission is durable before any external I/O, as for team/media tasks.+ await db.commit()result: Ttry:- async with billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):+ async with hold_inline_lease(task), billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):result = await executor()task.status = "succeeded"task.progress_percent = 100task.finished_at = datetime.now(UTC)- task.result_payload = {**(task.result_payload or {}), "ok": True,- **({"result": str(type(result))} if result is not None else {})}+ output = result_payload_factory(result) if result_payload_factory else _inline_result_payload(result)+ task.result_payload = {**(task.result_payload or {}), "ok": True, **output}await append_task_event(db,task.id,@@ -176,6 +187,9 @@ async def run_billed_ephemeral(status=task.status,message="轻量任务完成",)+ except asyncio.CancelledError:+ await _cancel_inline_task(db, task, billable=billable)+ raiseexcept Exception as exc:task.status = "failed"task.error_code = "ephemeral_failed"@@ -188,18 +202,47 @@ async def run_billed_ephemeral(status=task.status,message=str(exc)[:200],)- await settle_task(db, task.id)- if commit or task.team_id is not None:- await db.commit()+ if billable:+ await settle_task(db, task.id)+ # An outer request rollback must not erase an accepted failed task.+ await db.commit()raise- await settle_task(db, task.id)+ if billable:+ await settle_task(db, task.id)if commit or task.team_id is not None:await db.commit()await db.refresh(task)return task, result+def _inline_result_payload(result: Any) -> dict[str, Any]:+ """Keep generated text rather than only Python's return type."""+ if isinstance(result, str):+ return {"kind": "text", "text_content": result}+ if isinstance(result, dict):+ text = result.get("content") or result.get("reply") or result.get("text_content")+ if isinstance(text, str):+ return {"kind": "text", "text_content": text, "data": result}+ return {}+++async def _cancel_inline_task(db: AsyncSession, task: TaskRun, *, billable: bool = True) -> None:+ await db.refresh(task)+ if task.status in {"succeeded", "failed", "cancelled"}:+ return+ task.status = "cancelled"+ task.finished_at = datetime.now(UTC)+ task.next_action_at = None+ task.lease_token = None+ task.lease_until = None+ await append_task_event(db, task.id, event_type="task.cancelled", status=task.status,+ message="生成已取消")+ if billable:+ await settle_task(db, task.id)+ await db.commit()++def _extract_provider_task_id(result: Any) -> str:"""从 executor 返回值解析上游 task_id。"""if isinstance(result, dict):@@ -254,6 +297,7 @@ async def run_billed_ephemeral_deferred(now = datetime.now(UTC)task.status = "running"task.started_at = now+ start_inline_lease(task, now)await append_task_event(db,task.id,@@ -263,12 +307,11 @@ async def run_billed_ephemeral_deferred()await db.flush()- if task.team_id is not None or task.billing_snapshot is not None:- await db.commit()+ await db.commit()result: Ttry:- async with billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):+ async with hold_inline_lease(task), billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):result = await executor()provider_id = _extract_provider_task_id(result)if not provider_id:@@ -286,6 +329,9 @@ async def run_billed_ephemeral_deferred(message="已提交上游,等待轮询",payload={"provider_task_id": provider_id},)+ except asyncio.CancelledError:+ await _cancel_inline_task(db, task)+ raiseexcept Exception as exc:task.status = "failed"task.error_code = "ephemeral_failed"@@ -299,8 +345,7 @@ async def run_billed_ephemeral_deferred(message=str(exc)[:200],)await settle_task(db, task.id)- if commit or task.team_id is not None:- await db.commit()+ await db.commit()raiseif commit or task.team_id is not None:diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex 9725353..18490cb 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -350,6 +350,8 @@ async def run_script_summary_job(project_id: int) -> dict[str, Any]:"project_id": project_id,"assets": assets_result,"episode_script_task_id": episodes_task_id,+ "kind": "text",+ "text_content": format_summary_text(summary),}@@ -649,6 +651,8 @@ async def run_episode_scripts_job("project_id": project_id,"total": total,"post_pipeline": pipeline,+ "kind": "text",+ "episodes": existing,}except Exception as exc: # noqa: BLE001params = dict(script.params or {})@@ -923,6 +927,8 @@ async def _run_single_episode_script_job("assets_created_count": assets_created,"assets_reused_count": assets_reused,"post_pipeline": pipeline,+ "kind": "text",+ "episodes": batch,}except Exception as exc: # noqa: BLE001await db.rollback()@@ -1172,6 +1178,8 @@ async def run_episode_fragment_plan_job("mode": mode_used,"count": len(protected_frags) + len(drafts),"preserved": len(protected_frags),+ "kind": "text",+ "fragments": drafts,}@@ -1441,7 +1449,11 @@ async def _recover_complete_fragment_video(await db.refresh(locked, attribute_names=["steps"])# 先 complete(commit 后锁释放),再激活后续;避免 activate 提前 commit 导致并发双 completelocked.progress_percent = 100- result_payload: dict[str, Any] = {"ok": True, "fragment_id": int(fragment_id)}+ fragment = await db.get(DramaEpisodeFragment, int(fragment_id))+ result_payload: dict[str, Any] = {+ "ok": True, "fragment_id": int(fragment_id), "kind": "video",+ "urls": [fragment.video] if fragment and fragment.video else [],+ }if recovered:result_payload["recovered"] = Trueawait _complete_task(db, locked, result_payload)@@ -1825,7 +1837,8 @@ async def run_asset_image_job(asset.id,(asset.url or asset.cover or "")[:80],)- return {"ok": True, "asset_id": asset.id}+ url = asset.url or asset.cover+ return {"ok": True, "asset_id": asset.id, "kind": "image", "urls": [url] if url else []}except Exception as exc: # noqa: BLE001from app.services.exc_format import format_exception_message@@ -1973,7 +1986,8 @@ async def run_asset_video_job(asset.id,(asset.url or "")[:80],)- return {"ok": True, "asset_id": asset.id}+ return {"ok": True, "asset_id": asset.id, "kind": "video", "urls": [asset.url] if asset.url else [],+ "preview_url": asset.cover or None}except Exception as exc: # noqa: BLE001from app.services.drama.asset_video import DOWNLOAD_RETRY_MESSAGEfrom app.services.exc_format import format_exception_messagediff --git a/backend/app/services/tasks/generation_history.py b/backend/app/services/tasks/generation_history.pynew file mode 100644index 0000000..bbbc785--- /dev/null+++ b/backend/app/services/tasks/generation_history.py@@ -0,0 +1,378 @@+"""Read-only generation history across every task domain and legacy tool runs.++The SQL union performs filtering, counts and pagination before loading payloads.+Only explicit public result fields are projected; provider traces and generation+inputs never become downloadable outputs.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime, timedelta+from urllib.parse import urlsplit++from sqlalchemy import String, and_, case, cast, exists, func, literal, or_, select, union_all+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import selectinload++from app.models import Project, Shot, ToolRun, User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject+from app.models_tasks import TaskRun+from app.schemas_generation_history import GenerationListOut, GenerationRecordOut+from app.services.tasks.service import TaskAccessContext, _task_team_access++_AUDIO_TYPES = ("voice_synthesis", "voice_preview", "tool_audio", "shot_regen_audio", "project_regen_audio")+_TEXT_TYPES = ("script_summary", "episode_script", "fragment_plan", "seed_assets", "agent_chat",+ "skill_optimize", "voice_prompt", "content_expand", "creation_turn")+_SAFE_PARAMS = frozenset({"prompt", "negative", "model_id", "model", "ratio", "aspect_ratio", "resolution",+ "duration", "duration_sec", "voice", "voice_id", "phase", "video_mode", "mode",+ "strength", "motion", "pack", "image_style_id", "episode_number"})+_TEXT_FIELDS = ("text_content", "text", "content", "summary", "script", "body", "answer")+_TEXT_OBJECT_FIELDS = frozenset({*_TEXT_FIELDS, "title", "name", "description", "prompt", "narration",+ "number", "episode_number", "sort_order", "duration_sec", "kind", "type"})+_TEXT_COLLECTIONS = ("episodes", "fragments", "assets", "shots", "messages")+_TERMINAL_STATUSES = ("succeeded", "failed", "cancelled")+_TASK_LABELS = {+ "script_summary": "生成剧本摘要", "episode_script": "生成分集剧本", "fragment_plan": "规划分镜",+ "seed_assets": "提取剧本资产", "asset_image": "生成资产图片", "asset_video": "生成资产视频",+ "fragment_video": "生成分镜视频", "agent_chat": "创作助手对话", "skill_optimize": "优化创作提示词",+ "voice_prompt": "生成配音提示词", "voice_synthesis": "生成角色配音", "episode_compose": "合成分集视频",+ "content_expand": "扩写创作内容", "creation_turn": "创作对话", "voice_preview": "配音试听",+ "shot_regen_image": "重新生成分镜图片", "shot_regen_video": "重新生成分镜视频",+ "shot_regen_audio": "重新生成分镜配音", "project_regen_audio": "重新生成全片配音",+ "project_compose_only": "合成短视频", "v1_image": "API 图片生成", "v1_video": "API 视频生成",+ "v1_seedance": "API 视频生成", "tool_image": "生成图片", "tool_video": "生成视频", "tool_audio": "生成音频",+}+_PIPELINE_LABELS = {"script": "生成短视频剧本", "storyboard": "规划短视频分镜", "assets": "生成分镜图片",+ "videos": "生成分镜视频", "audio": "生成短视频配音", "compose": "合成短视频", "produce": "生成短视频"}+++def _public_status(status: str) -> str:+ if status in _TERMINAL_STATUSES:+ return status+ return "queued" if status in {"pending", "leased", "queued"} else "running"+++def _kind_expression():+ phase = TaskRun.payload["phase"].as_string()+ 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"),+ (TaskRun.task_type.in_(("project_pipeline", "episode_compose", "project_compose_only", "v1_seedance")), "video"),+ (TaskRun.task_type.contains("video"), "video"),+ (TaskRun.task_type.contains("image"), "image"),+ (TaskRun.queue_type.in_(("image", "video")), TaskRun.queue_type),+ else_="text",+ )+++def _generation_kind(task) -> str:+ name = task.task_type+ if name in _AUDIO_TYPES:+ return "audio"+ if name in _TEXT_TYPES:+ return "text"+ if name == "project_pipeline":+ phase = (task.payload or {}).get("phase")+ if phase == "assets":+ return "image"+ if phase == "audio":+ return "audio"+ return "text" if phase in {"script", "text", "plan", "storyboard"} else "video"+ if name in {"episode_compose", "project_compose_only", "v1_seedance"} or "video" in name:+ return "video"+ if "image" in name:+ return "image"+ return task.queue_type if task.queue_type in {"image", "video"} else "text"+++def _tool_link():+ task_id = cast(TaskRun.id, String)+ reference = func.coalesce(ToolRun.params["platform_task_id"].as_string(), ToolRun.params["billing_task_id"].as_string())+ return and_(TaskRun.requested_by == ToolRun.user_id, TaskRun.task_type != "mock_delay", or_(+ 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),+ ))+++def _safe_url(value) -> str | None:+ if not isinstance(value, str) or not value or len(value) > 8192 or "\\" in value:+ return None+ try:+ parts = urlsplit(value)+ except ValueError:+ return None+ if parts.scheme in {"http", "https"} and parts.hostname and not parts.username and not parts.password:+ return value+ if not parts.scheme and not parts.netloc and value.startswith(("/media/", "/static/", "/uploads/")) and ".." not in parts.path.split("/"):+ return value+ return None+++def _safe_params(data) -> dict:+ return {key: value for key, value in (data.items() if isinstance(data, dict) else [])+ if key in _SAFE_PARAMS and isinstance(value, (str, int, float, bool)) and len(str(value)) <= 7000}+++def _result_urls(result, kind: str) -> list[str]:+ if not isinstance(result, dict) or kind == "text":+ return []+ values = []+ for field in ("urls", f"{kind}_urls"):+ if isinstance(result.get(field), list):+ values.extend(result[field])+ values.extend(result.get(field) for field in ("url", f"{kind}_url", "output_url"))+ # OpenAI-compatible image results have data:[{url:...}]. Do not recurse into+ # arbitrary provider/request objects, which can contain reference media.+ if kind == "image" and isinstance(result.get("data"), list):+ values.extend(item.get("url") for item in result["data"] if isinstance(item, dict))+ return list(dict.fromkeys(url for item in values if (url := _safe_url(item))))+++def _text_output(result) -> str:+ if not isinstance(result, dict):+ return ""+ for field in _TEXT_FIELDS:+ if isinstance(result.get(field), str):+ return result[field][:50000]+ for field in _TEXT_COLLECTIONS:+ if isinstance(result.get(field), list):+ records = [{key: value for key, value in item.items()+ if key in _TEXT_OBJECT_FIELDS and isinstance(value, (str, int, float, bool))}+ for item in result[field][:200] if isinstance(item, dict)]+ if any(records):+ return json.dumps(records, ensure_ascii=False, indent=2)[:50000]+ return ""+++def project_generation(task, *, viewer_id: int, owner_user_id: int | None = None,+ linked_tool: ToolRun | None = None, fallback: dict | None = None) -> GenerationRecordOut:+ """Project only safe public fields from already persisted task data."""+ kind = _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":+ 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:+ preview = _safe_url(linked_tool.preview_url)+ if not preview and kind == "image" and urls:+ preview = urls[0]+ params = {**_safe_params(linked_tool.params if linked_tool is not None else {}), **_safe_params(task.payload)}+ prompt = str(params.get("prompt") or (linked_tool.prompt if linked_tool is not None else "") or "")+ if not prompt:+ prompt = next((str((task.payload or {}).get(key) or "") for key in ("text", "instruction", "draft", "name")+ if isinstance((task.payload or {}).get(key), str) and (task.payload or {}).get(key)), "")+ if not prompt:+ prompt = (_PIPELINE_LABELS.get((task.payload or {}).get("phase"), "生成 AI 短视频")+ if task.task_type == "project_pipeline" else _TASK_LABELS.get(task.task_type, "生成任务"))+ can_view_money = task.team_id is None or viewer_id in {task.requested_by, owner_user_id}+ created_at = getattr(task, "created_at", None)+ return GenerationRecordOut(+ id=task.id, source="task", record_key=f"task:{task.id}",+ tool_id=linked_tool.tool_id if linked_tool is not None else str((task.payload or {}).get("tool_id") or task.task_type),+ kind=kind, status=_public_status(task.status),+ domain=task.domain, task_type=task.task_type, prompt=prompt[:7000], urls=urls, preview_url=preview,+ text_content=next((text for output in outputs if (text := _text_output(output))), "") if kind == "text" else "",+ task_id=f"task-{task.id}", params=params, error=getattr(task, "error_message", None),+ created_at=created_at.isoformat() if created_at else "", platform_task_id=task.id,+ provider_task_id=getattr(task, "provider_task_id", None), provider_name=getattr(task, "provider_name", None),+ provider_status=getattr(task, "provider_status", None), queue_type=task.queue_type,+ started_at=getattr(task, "started_at", None), finished_at=getattr(task, "finished_at", None),+ billing_status=getattr(task, "billing_status", None) or "none",+ billing_charged_fen=int(getattr(task, "billing_charged_fen", 0) or 0) if can_view_money else None,+ )+++def _legacy_projection(row: ToolRun) -> GenerationRecordOut:+ params = _safe_params(row.params)+ return GenerationRecordOut(+ id=row.id, source="tool", record_key=f"tool:{row.id}", tool_id=row.tool_id,+ kind=row.kind if row.kind in {"video", "image", "audio"} else "text", status=_public_status(row.status),+ domain="studio", prompt=row.prompt or "", urls=[url for value in (row.urls or []) if (url := _safe_url(value))],+ preview_url=_safe_url(row.preview_url), params=params, task_id=row.task_id,+ provider_task_id=str((row.params or {}).get("provider_task_id") or row.task_id or "") or None,+ error=row.error, created_at=row.created_at.isoformat() if row.created_at else "",+ )+++async def _workspace(db, user: User, team_id: int | None, context: TaskAccessContext):+ if team_id is not None:+ team, _ = await _task_team_access(db, team_id, int(user.id), context=context)+ return [TaskRun.team_id == team_id], int(team.owner_user_id)+ return [TaskRun.requested_by == user.id, TaskRun.team_id.is_(None)], None+++def _entity_matches_task(task, project, *, drama: bool) -> bool:+ expected_project_id = task.drama_project_id if drama else task.project_id+ if project.id != expected_project_id or getattr(project, "team_id", None) != task.team_id:+ return False+ return task.team_id is not None or project.user_id == task.requested_by+++def _entity_is_current(entity, task) -> bool:+ """An entity edited after completion is no longer evidence of this output."""+ updated = getattr(entity, "updated_at", None)+ finished = task.finished_at+ if updated is None:+ return True+ if finished is None:+ return False+ updated = updated.replace(tzinfo=UTC) if updated.tzinfo is None else updated+ finished = finished.replace(tzinfo=UTC) if finished.tzinfo is None else finished+ return updated <= finished + timedelta(seconds=2)+++async def _latest_target_tasks(db, tasks, target_name: str) -> set[int]:+ target = getattr(TaskRun, target_name)+ ids = {getattr(task, target_name) for task in tasks if getattr(task, target_name) is not None}+ if not ids:+ return set()+ kind = _kind_expression()+ return set((await db.scalars(select(func.max(TaskRun.id)).where(target.in_(ids), TaskRun.status == "succeeded")+ .group_by(target, kind))).all())+++async def _legacy_entity_outputs(db, tasks) -> 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, so+ only 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,+ *(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"}]+ if asset_tasks:+ latest = await _latest_target_tasks(db, asset_tasks, "asset_id")+ rows = (await db.execute(select(DramaAsset, DramaProject).join(DramaProject, DramaAsset.project_id == DramaProject.id)+ .where(DramaAsset.id.in_({task.asset_id for task in asset_tasks})))).all()+ 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)+ 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"]+ if fragment_tasks:+ latest = await _latest_target_tasks(db, fragment_tasks, "fragment_id")+ rows = (await db.execute(select(DramaEpisodeFragment, DramaEpisode, DramaProject)+ .join(DramaEpisode, DramaEpisodeFragment.episode_id == DramaEpisode.id)+ .join(DramaProject, DramaEpisode.project_id == DramaProject.id)+ .where(DramaEpisodeFragment.id.in_({task.fragment_id for task in fragment_tasks})))).all()+ entities = {fragment.id: (fragment, episode, project) for fragment, episode, project in rows}+ for task in fragment_tasks:+ fragment, episode, project = entities.get(task.fragment_id, (None, None, None))+ if (fragment is not None and task.id in latest and (task.episode_id is None or task.episode_id == episode.id)+ and _entity_matches_task(task, project, drama=True) and _entity_is_current(fragment, task)):+ outputs[task.id] = {"urls": [fragment.video]}+ shot_tasks = [task for task in candidates if task.shot_id and task.task_type.startswith("shot_regen_")]+ if shot_tasks:+ latest = await _latest_target_tasks(db, shot_tasks, "shot_id")+ rows = (await db.execute(select(Shot, Project).join(Project, Shot.project_id == Project.id)+ .where(Shot.id.in_({task.shot_id for task in shot_tasks})))).all()+ entities = {shot.id: (shot, project) for shot, project in rows}+ 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)]}+ 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:+ latest = await _latest_target_tasks(db, project_tasks, "project_id")+ ids = {task.project_id for task in project_tasks}+ projects = {project.id: project for project in (await db.scalars(select(Project).where(Project.id.in_(ids)))).all()}+ shots = (await db.scalars(select(Shot).where(Shot.project_id.in_(ids)).order_by(Shot.shot_no))).all()+ for task in project_tasks:+ project = projects.get(task.project_id)+ if (project is None or task.id not in latest or not _entity_matches_task(task, project, drama=False)+ or not _entity_is_current(project, task)):+ continue+ phase = (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"}):+ 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]}+ return outputs+++async def _load_records(db, user, references, owner_user_id):+ task_ids = [row.id for row in references if row.source == "task"]+ tool_ids = [row.id for row in references if row.source == "tool"]+ tasks = list((await db.scalars(select(TaskRun).where(TaskRun.id.in_(task_ids))+ .options(selectinload(TaskRun.steps)))).all()) if task_ids else []+ tools = list((await db.scalars(select(ToolRun).where(ToolRun.id.in_(tool_ids)))).all()) if tool_ids else []+ linked = (await db.execute(select(TaskRun.id, ToolRun).join(ToolRun, _tool_link())+ .where(TaskRun.id.in_(task_ids)).order_by(ToolRun.id.desc()))).all() if task_ids else []+ linked_by_task = {}+ for task_id, tool in linked:+ linked_by_task.setdefault(task_id, tool)+ fallback = await _legacy_entity_outputs(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)) 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]+++async def list_generations(db: AsyncSession, user: User, *, page: int = 1, page_size: int = 20,+ kind: str | None = None, status: str | None = None, task_id: str | None = None,+ created_from: datetime | None = None, created_to: datetime | None = None,+ team_id: int | None = None) -> GenerationListOut:+ scope, owner_user_id = await _workspace(db, user, team_id, {})+ task_query = select(literal("task").label("source"), TaskRun.id.label("id"),+ TaskRun.created_at.label("created_at"), TaskRun.status.label("status"),+ _kind_expression().label("kind")).where(*scope, TaskRun.task_type != "mock_delay")+ tool_query = select(literal("tool").label("source"), ToolRun.id.label("id"),+ ToolRun.created_at.label("created_at"), ToolRun.status.label("status"),+ ToolRun.kind.label("kind")).where(ToolRun.user_id == user.id,+ ~exists(select(TaskRun.id).where(_tool_link())))+ if team_id is not None:+ tool_query = tool_query.where(literal(False))+ if task_id and (value := task_id.strip()):+ linked_id = exists(select(ToolRun.id).where(_tool_link(), or_(cast(ToolRun.id, String) == value, ToolRun.task_id == value)))+ task_query = task_query.where(or_(cast(TaskRun.id, String) == value, TaskRun.provider_task_id == value,+ literal("task-") + cast(TaskRun.id, String) == value, linked_id))+ tool_query = tool_query.where(or_(cast(ToolRun.id, String) == value, ToolRun.task_id == value,+ 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 = []+ if kind:+ filters.append(history.c.kind == kind)+ if created_from:+ filters.append(history.c.created_at >= created_from)+ if created_to:+ filters.append(history.c.created_at <= created_to)+ counts = {name: 0 for name in ("processing", "succeeded", "failed", "cancelled")}+ counts.update(dict((await db.execute(select(bucket, func.count()).select_from(history)+ .where(*filters).group_by(bucket))).all()))+ counts["all"] = sum(counts.values())+ 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)+ .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),+ total=total, page=page, page_size=page_size, counts=counts)+++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"))+ .where(*scope, TaskRun.id == task_id, TaskRun.task_type != "mock_delay"))).first()+ if row is None:+ raise LookupError("任务不存在")+ return (await _load_records(db, user, [row], owner_user_id))[0]diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex 3c2c369..d23d754 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -161,7 +161,48 @@ async def _await_kepu(task: TaskRun, aw: Awaitable[Any], **extra: Any) -> dict[sif task.cancel_requested:return {"cancelled": True, "project_id": task.project_id, **extra}raise- return {"ok": True, "project_id": task.project_id, **extra}+ result = {"ok": True, "project_id": task.project_id, **extra}+ result.update(await _kepu_output_snapshot(task, extra.get("phase")))+ return result+++async def _kepu_output_snapshot(task: TaskRun, phase: str | None) -> dict[str, Any]:+ """Freeze the completed generation's outputs before later edits replace them."""+ from sqlalchemy import select+ from app.database import AsyncSessionLocal+ from app.models import Project, Shot++ if task.task_type == "shot_regen_image" or phase == "assets":+ kind, field = "image", "image_url"+ elif task.task_type in {"shot_regen_audio", "project_regen_audio"} or phase == "audio":+ kind, field = "audio", "audio_url"+ elif task.task_type == "shot_regen_video" or phase == "videos":+ kind, field = "video", "video_url"+ elif task.task_type in {"project_compose_only", "project_pipeline"} and phase not in {"script", "storyboard"}:+ kind, field = "video", "final_video_url"+ else:+ kind, field = "text", None+ async with AsyncSessionLocal() as db:+ project = await db.get(Project, task.project_id)+ if project is None:+ return {"kind": kind, "urls": []}+ if field == "final_video_url":+ urls = [project.final_video_url] if project.final_video_url else []+ else:+ query = select(Shot).where(Shot.project_id == task.project_id).order_by(Shot.shot_no)+ if task.shot_id:+ query = query.where(Shot.id == task.shot_id)+ shots = list((await db.execute(query)).scalars().all())+ if field:+ urls = list(dict.fromkeys(getattr(shot, field) for shot in shots if getattr(shot, field)))+ else:+ return {"kind": "text", "text_content": "\n\n".join(+ shot.narration or shot.segment_script or "" for shot in shots+ )}+ result = {"kind": kind, "urls": urls}+ if project.cover_url:+ result["preview_url"] = project.cover_url+ return result# 执行科普分阶段流水线(严格按 payload.phase 预扣对应阶段)。@@ -312,6 +353,7 @@ TASK_HANDLERS: dict[tuple[str, str], TaskHandler] = {("drama", "voice_synthesis"): TaskHandler("drama", "voice_synthesis", _noop_ephemeral),("drama", "episode_compose"): TaskHandler("drama", "episode_compose", _noop_ephemeral),("kepu", "content_expand"): TaskHandler("kepu", "content_expand", _noop_ephemeral),+ ("kepu", "voice_preview"): TaskHandler("kepu", "voice_preview", _noop_ephemeral),("api", "v1_image"): TaskHandler("api", "v1_image", _noop_ephemeral),("api", "v1_video"): TaskHandler("api", "v1_video", _noop_ephemeral),("api", "v1_seedance"): TaskHandler("api", "v1_seedance", _noop_ephemeral),diff --git a/backend/app/services/tasks/inline.py b/backend/app/services/tasks/inline.pynew file mode 100644index 0000000..6a9c5b7--- /dev/null+++ b/backend/app/services/tasks/inline.py@@ -0,0 +1,60 @@+"""Renewable leases for accepted tasks owned by an HTTP coroutine."""+from __future__ import annotations++import asyncio+import logging+import uuid+from contextlib import asynccontextmanager+from datetime import UTC, datetime, timedelta++from sqlalchemy import update++from app.database import AsyncSessionLocal+from app.models_tasks import TaskRun++logger = logging.getLogger("app.tasks.inline")+INLINE_LEASE_PREFIX = "inline:"+INLINE_LEASE_SECONDS = 600+INLINE_HEARTBEAT_SECONDS = 10+++def start_inline_lease(task: TaskRun, now: datetime) -> None:+ """Persist with admission, before the first provider call can begin."""+ task.lease_token = INLINE_LEASE_PREFIX + uuid.uuid4().hex+ task.lease_until = now + timedelta(seconds=INLINE_LEASE_SECONDS)+ task.next_action_at = None+++@asynccontextmanager+async def hold_inline_lease(task: TaskRun):+ """A separate short transaction keeps long requests alive across workers."""+ owner = asyncio.current_task()+ heartbeat = asyncio.create_task(_renew_inline_lease(task.id, task.lease_token, owner))+ try:+ yield+ finally:+ heartbeat.cancel()+ await asyncio.gather(heartbeat, return_exceptions=True)+ task.lease_token = None+ task.lease_until = None+++async def _renew_inline_lease(task_id: int, token: str, owner: asyncio.Task) -> None:+ while True:+ await asyncio.sleep(INLINE_HEARTBEAT_SECONDS)+ try:+ async with AsyncSessionLocal() as db:+ result = await db.execute(update(TaskRun).where(+ TaskRun.id == task_id, TaskRun.lease_token == token,+ TaskRun.status == "running",+ ).values(lease_until=datetime.now(UTC) + timedelta(seconds=INLINE_LEASE_SECONDS)))+ await db.commit()+ if not result.rowcount:+ # Another worker already terminated the expired owner. Never+ # let its stale coroutine submit further work or settle twice.+ owner.cancel()+ return+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.exception("inline task heartbeat failed task_id=%s", task_id)diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.pyindex 2687a04..8a73d78 100644--- a/backend/app/services/tasks/scheduler.py+++ b/backend/app/services/tasks/scheduler.py@@ -403,8 +403,10 @@ async def _run_cancel_request(task_id: int) -> None:lease_until = getattr(task, "lease_until", None)if lease_until is not None and lease_until.tzinfo is None:lease_until = lease_until.replace(tzinfo=UTC)- if getattr(task, "execution_mode", "queued") == "direct" and lease_until and lease_until > datetime.now(UTC):- # 其他进程正在调用模型,由租约持有者取消并结算,不能先退冻结。+ if lease_until and lease_until > datetime.now(UTC):+ # Any live executor may still be writing media/usage in another+ # process. Its heartbeat observes cancel_requested and cancels+ # the owner coroutine; only that owner may settle until expiry.returnawait _mark_cancelled(db, task)except Exception: # noqa: BLE001@@ -537,6 +539,26 @@ async def recover_orphaned_tasks() -> int:for task in rows:if _job_alive(int(task.id)):continue+ from app.services.tasks.inline import INLINE_LEASE_PREFIX+ if str(task.lease_token or "").startswith(INLINE_LEASE_PREFIX):+ # HTTP inline executors have no replayable job. A restarted+ # process must not queue their noop handler or resubmit a POST.+ from app.services.billing.settlement import settle_task+ task.status = "cancelled" if task.cancel_requested else "failed"+ task.error_code = "inline_execution_interrupted"+ task.error_message = "生成请求执行中断,请重新发起"+ task.finished_at = now+ task.next_action_at = None+ task.lease_token = None+ task.lease_until = None+ await append_task_event(+ db, task.id, event_type=f"task.{task.status}", status=task.status,+ phase=task.current_step_key, message=task.error_message,+ )+ if task.billing_status in {"frozen", "reserved"}:+ await settle_task(db, task.id)+ changed += 1+ continuetask.status = "cancel_requested" if task.cancel_requested else "pending"task.next_action_at = nowtask.lease_token = Nonediff --git a/backend/tests/test_generation_history.py b/backend/tests/test_generation_history.pynew file mode 100644index 0000000..3d55a49--- /dev/null+++ b/backend/tests/test_generation_history.py@@ -0,0 +1,293 @@+"""Generation history merges durable tasks and legacy rows without mutating either."""++from datetime import UTC, datetime, timedelta+from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from app.database import Base, get_db+from app.deps import get_current_user+from app.models import Project, Shot, Template, ToolRun, User+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaProject+from app.models_tasks import TaskRun+from app.models_teams import Team, TeamMember+from app.services.tasks.generation_history import project_generation+++async def history():+ import app.main # noqa: F401+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")+ async with engine.begin() as connection:+ await connection.run_sync(Base.metadata.create_all)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ async with sessions() as db:+ users = [User(email=f"history-{index}@test.local", hashed_password="test") for index in range(3)]+ db.add_all(users)+ await db.flush()+ team = Team(name="History", owner_user_id=users[0].id)+ db.add(team)+ await db.flush()+ db.add_all([TeamMember(team_id=team.id, user_id=user.id, role="owner" if index == 0 else "member")+ for index, user in enumerate(users[:2])])+ await db.commit()+ yield sessions, users, team+ await engine.dispose()+++def task(user, task_type="asset_image", **values):+ return TaskRun(domain="drama", task_type=task_type, requested_by=user.id,+ queue_type="image", status="succeeded", payload={}, **values)+++async def client_for(sessions, user):+ from app.api.tasks import router+ app = FastAPI()+ app.include_router(router, prefix="/api")+ async def database():+ async with sessions() as db:+ yield db+ app.dependency_overrides[get_db] = database+ app.dependency_overrides[get_current_user] = lambda: user+ return httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test")+++async def test_history_merges_all_domains_and_legacy_without_duplicates(history):+ sessions, (user, other, _), team = history+ async with sessions() as db:+ rows = [task(user), task(user, "voice_synthesis"), task(user, "episode_script"),+ TaskRun(domain="api", task_type="v1_seedance", queue_type="video", requested_by=user.id,+ status="awaiting_poll", provider_task_id="provider-video", payload={}),+ task(other), task(user, team_id=team.id)]+ db.add_all(rows)+ await db.flush()+ db.add_all([ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="succeeded",+ task_id=f"task-{rows[0].id}", params={"platform_task_id": rows[0].id}, prompt="linked prompt"),+ ToolRun(user_id=user.id, tool_id="t2v", kind="video", status="failed", task_id="legacy-video"),+ ToolRun(user_id=other.id, tool_id="t2i", kind="image", status="succeeded")])+ await db.commit()+ async with await client_for(sessions, user) as client:+ response = await client.get("/api/tasks/generations?page_size=2")+ assert response.status_code == 200+ result = response.json()+ assert result["total"] == 5+ assert result["counts"] == {"all": 5, "processing": 1, "succeeded": 3, "failed": 1, "cancelled": 0}+ assert len(result["items"]) == 2+ all_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 len([row for row in all_rows if row["source"] == "tool"]) == 1+ filtered = (await client.get("/api/tasks/generations?kind=video&status=processing")).json()+ assert filtered["total"] == 1 and filtered["counts"]["all"] == 2+ assert filtered["items"][0]["status"] == "running"+ assert (await client.get("/api/tasks/generations?task_id=provider-video")).json()["total"] == 1+ assert (await client.get(f"/api/tasks/generations?task_id={rows[0].id}")).json()["total"] == 1+++async def test_pipeline_phase_kind_matches_sql_filter_and_projection(history):+ sessions, (user, _, _), _team = history+ expected = {"assets": "image", "audio": "audio", "storyboard": "text", "script": "text", "compose": "video"}+ async with sessions() as db:+ for phase in expected:+ db.add(TaskRun(domain="kepu", task_type="project_pipeline", queue_type="video", status="succeeded",+ requested_by=user.id, payload={"phase": phase}))+ await db.commit()+ 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 all(row["kind"] == kind and expected[row["params"]["phase"]] == kind for row in result["items"])+++async def test_provider_id_links_require_matching_tool_domain_and_media_kind(history):+ sessions, (user, _, _), _team = history+ async with sessions() as db:+ api = TaskRun(domain="api", task_type="v1_image", queue_type="image", requested_by=user.id,+ status="succeeded", provider_task_id="id-api", payload={})+ different_kind = TaskRun(domain="studio", task_type="tool_video", queue_type="video", requested_by=user.id,+ status="succeeded", provider_task_id="id-kind", payload={})+ matched = TaskRun(domain="studio", task_type="tool_image", queue_type="image", requested_by=user.id,+ status="succeeded", provider_task_id="id-match", payload={})+ db.add_all([api, different_kind, matched])+ db.add_all([ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="succeeded", task_id=provider_id,+ urls=[f"https://output.test/{provider_id}.png"])+ for provider_id in ("id-api", "id-kind", "id-match")])+ await db.commit()+ async with await client_for(sessions, user) as client:+ result = (await client.get("/api/tasks/generations")).json()+ assert result["total"] == 5+ tasks = {row["id"]: row for row in result["items"] if row["source"] == "task"}+ assert tasks[api.id]["urls"] == []+ assert tasks[different_kind.id]["urls"] == []+ assert tasks[matched.id]["urls"] == ["https://output.test/id-match.png"]+ assert tasks[api.id]["prompt"] == "API 图片生成"+++async def test_workspace_and_detail_are_isolated_and_money_is_private(history):+ sessions, (owner, member, stranger), team = history+ async with sessions() as db:+ personal = task(owner)+ shared = task(owner, team_id=team.id, billing_charged_fen=420, billing_status="settled")+ db.add_all([personal, shared])+ await db.commit()+ async with await client_for(sessions, member) as client:+ assert (await client.get("/api/tasks/generations")).json()["total"] == 0+ listing = (await client.get("/api/tasks/generations", headers={"X-Team-Id": str(team.id)})).json()+ assert listing["total"] == 1 and listing["items"][0]["billing_charged_fen"] is None+ assert (await client.get(f"/api/tasks/generations/{shared.id}")).status_code == 404+ detail = await client.get(f"/api/tasks/generations/{shared.id}", headers={"X-Team-Id": str(team.id)})+ assert detail.status_code == 200 and detail.json()["billing_charged_fen"] is None+ assert (await client.get(f"/api/tasks/generations/{personal.id}", headers={"X-Team-Id": str(team.id)})).status_code == 404+ assert (await client.get(f"/api/tasks/generations?team_id={team.id + 1}", headers={"X-Team-Id": str(team.id)})).status_code == 422+ async with await client_for(sessions, stranger) as client:+ assert (await client.get("/api/tasks/generations", headers={"X-Team-Id": str(team.id)})).status_code in {403, 404}+ async with await client_for(sessions, owner) as client:+ detail = await client.get(f"/api/tasks/generations/{shared.id}", headers={"X-Team-Id": str(team.id)})+ assert detail.json()["billing_charged_fen"] == 420+++async def test_history_filters_dates_preserves_rows_and_ignores_missing_links(history):+ sessions, (user, _, _), _team = history+ past = datetime.now(UTC) - timedelta(days=4)+ async with sessions() as db:+ row = task(user, created_at=past)+ db.add(row)+ db.add(ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="queued",+ params={"platform_task_id": 999999}, prompt="orphan"))+ await db.commit()+ async with await client_for(sessions, user) as client:+ result = await client.get("/api/tasks/generations", params={"created_from": (past + timedelta(days=1)).isoformat()})+ assert result.json()["total"] == 1+ assert result.json()["items"][0]["source"] == "tool"+ assert (await client.get("/api/tasks/generations?created_from=2026-10-02&created_to=2026-10-01")).status_code == 400+ async with sessions() as db:+ persisted = await db.get(TaskRun, row.id)+ assert persisted.status == "succeeded" and persisted.result_payload is None+++async def test_old_tasks_use_only_the_latest_owned_entity_output(history):+ sessions, (user, other, _), _team = history+ now = datetime.now(UTC)+ async with sessions() as db:+ project = DramaProject(user_id=user.id, title="Legacy project")+ other_project = DramaProject(user_id=other.id, title="Other project")+ db.add_all([project, other_project])+ await db.flush()+ asset = DramaAsset(project_id=project.id, asset_type="image", url="https://output.test/latest.png", updated_at=now)+ unrelated = DramaAsset(project_id=other_project.id, asset_type="image", url="https://private.test/other.png", updated_at=now)+ db.add_all([asset, unrelated])+ await db.flush()+ old = task(user, asset_id=asset.id, drama_project_id=project.id, finished_at=now)+ latest = task(user, asset_id=asset.id, drama_project_id=project.id, finished_at=now)+ mismatched = task(user, asset_id=unrelated.id, drama_project_id=project.id, finished_at=now)+ db.add_all([old, latest, mismatched])+ await db.commit()+ async with await client_for(sessions, user) as client:+ data = (await client.get("/api/tasks/generations")).json()["items"]+ by_id = {row["id"]: row for row in data}+ assert by_id[latest.id]["urls"] == ["https://output.test/latest.png"]+ assert by_id[old.id]["urls"] == []+ assert by_id[mismatched.id]["urls"] == []+++async def test_fragment_shot_and_project_artifacts_have_legacy_previews(history):+ sessions, (user, _, _), _team = history+ now = datetime.now(UTC)+ async with sessions() as db:+ drama = DramaProject(user_id=user.id, title="Legacy drama")+ template = Template(id="history", name="History", style_prefix="")+ db.add_all([drama, template])+ await db.flush()+ episode = DramaEpisode(project_id=drama.id, name="First episode")+ project = Project(user_id=user.id, template_id=template.id, title="Science", source_text="source",+ final_video_url="https://output.test/final.mp4", updated_at=now)+ db.add_all([episode, project])+ await db.flush()+ fragment = DramaEpisodeFragment(episode_id=episode.id, video="https://output.test/fragment.mp4", updated_at=now)+ shot = Shot(project_id=project.id, shot_no=1, audio_url="https://output.test/narration.wav")+ db.add_all([fragment, shot])+ await db.flush()+ fragment_task = task(user, "fragment_video", drama_project_id=drama.id,+ episode_id=episode.id, fragment_id=fragment.id, finished_at=now)+ audio_task = task(user, "shot_regen_audio", project_id=project.id, shot_id=shot.id, finished_at=now)+ final_task = task(user, "project_compose_only", project_id=project.id, finished_at=now)+ db.add_all([fragment_task, audio_task, final_task])+ await db.commit()+ async with await client_for(sessions, user) as client:+ records = (await client.get("/api/tasks/generations")).json()["items"]+ by_id = {row["id"]: row for row in records}+ assert by_id[fragment_task.id]["urls"] == ["https://output.test/fragment.mp4"]+ assert by_id[audio_task.id]["urls"] == ["https://output.test/narration.wav"]+ assert by_id[final_task.id]["urls"] == ["https://output.test/final.mp4"]+++def test_projection_accepts_only_outputs_and_safe_parameters():+ row = SimpleNamespace(id=14, task_type="asset_image", domain="drama", queue_type="image", status="succeeded",+ payload={"prompt": "a tree", "file_paths": ["C:/private.png"], "api_key": "secret", "ratio": "1:1",+ "reference_images": ["https://input.test/input.png"]},+ result_payload={"url": "https://output.test/generated.png", "input": {"url": "https://input.test/input.png"},+ "api_key": "secret", "preview_url": "file:///private.png"},+ steps=[], team_id=None, requested_by=1)+ output = project_generation(row, viewer_id=1)+ assert output.urls == ["https://output.test/generated.png"]+ assert output.params == {"prompt": "a tree", "ratio": "1:1"}+ assert output.preview_url == output.urls[0]+ assert "secret" not in output.model_dump_json() and "private.png" not in output.model_dump_json()+ row.result_payload = {"url": "C:/secret.png"}+ assert project_generation(row, viewer_id=1).urls == []+++def test_text_and_step_projections_exclude_upstream_traces():+ row = SimpleNamespace(id=1, task_type="episode_script", domain="drama", queue_type="text", status="succeeded",+ payload={}, result_payload={"text": "generated script", "token": "private", "provider_response": {"content": "secret"}},+ steps=[], team_id=None, requested_by=1)+ assert project_generation(row, viewer_id=1).text_content == "generated script"+ row.task_type = "v1_video"+ row.queue_type = "video"+ row.result_payload = {"ok": True}+ row.steps = [SimpleNamespace(output_payload={"video_url": "https://output.test/result.mp4", "api_key": "private"})]+ result = project_generation(row, viewer_id=1)+ assert result.urls == ["https://output.test/result.mp4"] and result.text_content == ""+++async def test_postgres_union_and_json_task_links(db_session):+ """Exercise PostgreSQL JSON text extraction, correlation and union pagination."""+ from app.services.tasks.generation_history import list_generations+ from tests.conftest import make_user+ user = await make_user(db_session)+ shared_team = Team(name="Postgres history", owner_user_id=user.id)+ db_session.add(shared_team)+ await db_session.flush()+ image = task(user, result_payload={"urls": ["https://output.test/image.png"]})+ audio = task(user, "voice_preview")+ shared = task(user, team_id=shared_team.id)+ waiting = TaskRun(domain="api", task_type="v1_seedance", requested_by=user.id,+ queue_type="video", status="cancel_requested", payload={})+ reviewing = TaskRun(domain="api", task_type="v1_video", requested_by=user.id,+ queue_type="video", status="awaiting_review", payload={})+ db_session.add_all([image, audio, shared, waiting, reviewing])+ await db_session.flush()+ db_session.add_all([+ ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="succeeded", params={"billing_task_id": image.id}),+ ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="succeeded", params={"platform_task_id": shared.id}),+ ToolRun(user_id=user.id, tool_id="t2i", kind="image", status="succeeded", params={"platform_task_id": "old-nonnumeric"}),+ ])+ await db_session.flush()+ result = await list_generations(db_session, user, page_size=2)+ assert result.total == 5 and result.counts["processing"] == 2 and len(result.items) == 2+ all_records = await list_generations(db_session, user, page_size=100)+ assert len([row for row in all_records.items if row.source == "tool"]) == 1+ assert (await list_generations(db_session, user, kind="audio")).items[0].platform_task_id == audio.id+ assert (await list_generations(db_session, user, status="processing")).total == 2diff --git a/backend/tests/test_generation_task_registration.py b/backend/tests/test_generation_task_registration.pynew file mode 100644index 0000000..7ca8df8--- /dev/null+++ b/backend/tests/test_generation_task_registration.py@@ -0,0 +1,227 @@+"""Accepted inline generations remain visible throughout their lifecycle."""+import asyncio+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from fastapi import HTTPException+from sqlalchemy import select++from app.models_tasks import TaskRun+from app.services.billing import ephemeral+++def inline_runtime(monkeypatch):+ task = TaskRun(id=42, status="pending", payload={})+ db = SimpleNamespace(flush=AsyncMock(), commit=AsyncMock(), refresh=AsyncMock())+ monkeypatch.setattr(ephemeral, "create_ephemeral_task_row", AsyncMock(return_value=task))+ monkeypatch.setattr(ephemeral, "freeze_for_task", AsyncMock())+ monkeypatch.setattr(ephemeral, "settle_task", AsyncMock())+ monkeypatch.setattr(ephemeral, "append_task_event", AsyncMock())+ return db, task++[email protected]("deferred", [False, True])+async def test_inline_generation_is_committed_before_external_io(monkeypatch, deferred):+ db, task = inline_runtime(monkeypatch)++ async def execute():+ db.commit.assert_awaited_once()+ assert task.status == "running"+ return {"task_id": "provider-42"} if deferred else "新的创作"++ run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ await run(db, SimpleNamespace(id=1), domain="api", task_type="v1_video", executor=execute, commit=False)+ assert db.commit.await_count == 1++[email protected]("deferred", [False, True])+async def test_inline_failure_remains_after_callers_rollback(monkeypatch, deferred):+ db, task = inline_runtime(monkeypatch)+ run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ with pytest.raises(RuntimeError, match="生成失败"):+ await run(db, SimpleNamespace(id=1), domain="api", task_type="v1_video",+ executor=AsyncMock(side_effect=RuntimeError("生成失败")), commit=False)+ assert task.status == "failed"+ assert task.finished_at is not None+ assert task.error_message == "生成失败"+ assert db.commit.await_count == 2+ ephemeral.create_ephemeral_task_row.assert_awaited_once()+ ephemeral.settle_task.assert_awaited_once()+++async def test_unbilled_generation_tracks_output_without_new_charges(monkeypatch):+ db, task = inline_runtime(monkeypatch)+ _, result = await ephemeral.run_billed_ephemeral(+ db, SimpleNamespace(id=1), domain="drama", task_type="voice_synthesis",+ executor=AsyncMock(return_value="/static/voice.mp3"), billable=False,+ result_payload_factory=lambda url: {"kind": "audio", "urls": [url]},+ )+ assert result == "/static/voice.mp3"+ assert task.status == "succeeded"+ assert task.result_payload == {"ok": True, "kind": "audio", "urls": [result]}+ ephemeral.freeze_for_task.assert_not_awaited()+ ephemeral.settle_task.assert_not_awaited()+ ephemeral.create_ephemeral_task_row.assert_awaited_once()+++async def test_inline_cancellation_is_persisted_and_unfreezes_once(monkeypatch):+ db, task = inline_runtime(monkeypatch)+ with pytest.raises(asyncio.CancelledError):+ await ephemeral.run_billed_ephemeral(+ db, SimpleNamespace(id=1), domain="drama", task_type="agent_chat",+ executor=AsyncMock(side_effect=asyncio.CancelledError()), commit=False,+ )+ assert task.status == "cancelled"+ assert task.finished_at is not None+ assert db.commit.await_count == 2+ ephemeral.settle_task.assert_awaited_once()+++async def test_generated_text_is_saved_in_task_result(monkeypatch):+ db, task = inline_runtime(monkeypatch)+ await ephemeral.run_billed_ephemeral(+ db, SimpleNamespace(id=1), domain="drama", task_type="agent_chat",+ executor=AsyncMock(return_value="新的创作"),+ )+ assert task.result_payload["kind"] == "text"+ assert task.result_payload["text_content"] == "新的创作"++[email protected]("fail", [False, True])+async def test_personal_voice_generation_has_one_durable_task_without_charging(db_session, monkeypatch, fail):+ from app.api.drama import generation+ from app.models_drama import DramaAsset, DramaProject+ from app.schemas_drama import DramaVoiceGenerateRequest+ from tests.conftest import make_user++ user = await make_user(db_session, balance_fen=0)+ user_id = user.id+ project = DramaProject(user_id=user.id)+ db_session.add(project)+ await db_session.flush()+ asset = DramaAsset(project_id=project.id, type="voice", asset_type="audio", params={})+ db_session.add(asset)+ await db_session.commit()+ monkeypatch.setattr(generation, "get_owned_drama_project", AsyncMock(return_value=project))++ async def synthesize(*_args, **_kwargs):+ tasks = list((await db_session.execute(select(TaskRun).where(TaskRun.requested_by == user.id))).scalars())+ assert len(tasks) == 1 and tasks[0].status == "running"+ if fail:+ raise RuntimeError("TTS unavailable")+ asset.url = "/static/generated-voice.mp3"+ await db_session.commit()+ await db_session.refresh(asset)+ return asset++ monkeypatch.setattr(generation, "generate_voice_asset_audio", synthesize)+ request = DramaVoiceGenerateRequest(project_id=project.id, asset_id=asset.id, voice_prompt="沉稳的声音")+ if fail:+ with pytest.raises(HTTPException, match="TTS unavailable"):+ await generation.generate_voice(request, db=db_session, user=user)+ else:+ await generation.generate_voice(request, db=db_session, user=user)+ # A request teardown rollback cannot remove the completed/failed task.+ await db_session.rollback()+ task = (await db_session.execute(select(TaskRun).where(TaskRun.requested_by == user_id))).scalar_one()+ assert task.status == ("failed" if fail else "succeeded")+ assert task.finished_at and task.started_at+ assert task.billing_status == "skipped"+ await db_session.refresh(user)+ assert user.balance_fen == 0 and user.frozen_fen == 0+ if not fail:+ assert task.result_payload["urls"] == ["/static/generated-voice.mp3"]++[email protected]("team_id", [None, 91])+async def test_episode_compose_registers_one_generation_and_keeps_billing_policy(monkeypatch, team_id):+ from app.api.drama import episodes+ from app.services.drama import episode_compose++ project = SimpleNamespace(id=3, team_id=team_id)+ episode = SimpleNamespace(id=7, project_id=3)+ monkeypatch.setattr(episodes, "get_owned_episode", AsyncMock(return_value=episode))+ monkeypatch.setattr(episodes, "get_owned_drama_project", AsyncMock(return_value=project))+ monkeypatch.setattr(episode_compose, "load_episode_for_compose", AsyncMock(return_value=episode))+ compose = AsyncMock(return_value="/static/composed.mp4")+ monkeypatch.setattr(episode_compose, "compose_episode_video", compose)++ async def register(*_args, **kwargs):+ assert kwargs["task_type"] == "episode_compose"+ assert kwargs["billable"] is (team_id is not None)+ result = await kwargs["executor"]()+ assert kwargs["result_payload_factory"](result) == {"kind": "video", "urls": [result]}+ return SimpleNamespace(id=1), result++ register_task = AsyncMock(side_effect=register)+ monkeypatch.setattr(episodes, "run_billed_ephemeral", register_task)+ result = await episodes.compose_episode(7, db=SimpleNamespace(), user=SimpleNamespace(id=1))+ assert result["video_url"] == "/static/composed.mp4"+ register_task.assert_awaited_once()+ compose.assert_awaited_once()+++async def test_voice_audition_registers_audio_task_without_charging(monkeypatch):+ from app.api import projects+ from app.schemas import VoicePreviewRequest++ preview = AsyncMock(return_value="/static/preview.mp3")+ monkeypatch.setattr(projects, "ensure_voice_preview", preview)++ async def register(*_args, **kwargs):+ assert kwargs["task_type"] == "voice_preview" and kwargs["billable"] is False+ result = await kwargs["executor"]()+ assert kwargs["result_payload_factory"](result) == {"kind": "audio", "urls": [result]}+ return SimpleNamespace(id=1), result++ registered = AsyncMock(side_effect=register)+ monkeypatch.setattr(projects, "run_billed_ephemeral", registered)+ result = await projects.preview_voice(VoicePreviewRequest(voice_id="narrator"), db=SimpleNamespace(), user=SimpleNamespace(id=1))+ assert result.url == "/static/preview.mp3"+ registered.assert_awaited_once()+ preview.assert_awaited_once()++[email protected]("task_type,phase,kind,url", [+ ("shot_regen_image", None, "image", "/static/output.png"),+ ("shot_regen_video", None, "video", "/static/output.mp4"),+ ("shot_regen_audio", None, "audio", "/static/output.mp3"),+ ("project_pipeline", "assets", "image", "/static/output.png"),+ ("project_compose_only", None, "video", "/static/final.mp4"),+])+async def test_kepu_output_snapshot_freezes_only_matching_media(db_session, monkeypatch, task_type, phase, kind, url):+ from app.models import Project, Shot, Template+ from app.services.tasks import handlers+ from tests.conftest import make_user++ user = await make_user(db_session)+ template = Template(id=f"output-{task_type}-{phase}", name="test", style_prefix="test")+ db_session.add(template)+ await db_session.flush()+ project = Project(user_id=user.id, template_id=template.id, source_text="input", final_video_url="/static/final.mp4")+ db_session.add(project)+ await db_session.flush()+ shot = Shot(project_id=project.id, shot_no=1, image_url="/static/output.png", video_url="/static/output.mp4", audio_url="/static/output.mp3")+ db_session.add(shot)+ await db_session.flush()++ @asynccontextmanager+ async def session_factory():+ yield db_session++ monkeypatch.setattr("app.database.AsyncSessionLocal", session_factory)+ result = await handlers._kepu_output_snapshot(TaskRun(task_type=task_type, project_id=project.id, shot_id=shot.id), phase)+ assert result == {"kind": kind, "urls": [url]}+ shot.image_url = "/static/replaced.png"+ assert result["urls"] == [url]diff --git a/backend/tests/test_inline_task_leases.py b/backend/tests/test_inline_task_leases.pynew file mode 100644index 0000000..79064eb--- /dev/null+++ b/backend/tests/test_inline_task_leases.py@@ -0,0 +1,163 @@+"""HTTP task leases survive a second scheduler without replaying generation."""+import asyncio+from datetime import UTC, datetime, timedelta++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++from app.config import get_settings+from app.database import Base+from app.models import UsageEvent, User, WalletLedger+from app.models_tasks import TaskEvent, TaskRun+from app.services.billing import ephemeral+from app.services.billing.settlement import freeze_for_task+from app.services.tasks import inline, scheduler+++async def inline_sessions(tmp_path, monkeypatch):+ """File SQLite has genuinely separate request, heartbeat and scheduler sessions."""+ import app.main # noqa: F401++ engine = create_async_engine("sqlite+aiosqlite:///" + (tmp_path / "inline.db").as_posix())+ async with engine.begin() as conn:+ await conn.run_sync(Base.metadata.create_all)+ sessions = async_sessionmaker(engine, expire_on_commit=False)+ monkeypatch.setattr(inline, "AsyncSessionLocal", sessions)+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", sessions)+ monkeypatch.setattr(scheduler, "_running_jobs", {})+ monkeypatch.setattr(scheduler, "_running_queues", {})+ monkeypatch.setattr(get_settings(), "billing_enabled", False)+ async with sessions() as db:+ user = User(email="[email protected]", hashed_password="test", balance_fen=10000)+ db.add(user)+ await db.commit()+ user_id = user.id+ yield sessions, user_id+ await engine.dispose()+++def aware(value):+ return value if value.tzinfo else value.replace(tzinfo=UTC)++[email protected]("deferred", [False, True])+async def test_slow_inline_generation_renews_remote_lease_and_is_never_requeued(inline_sessions, monkeypatch, deferred):+ sessions, user_id = inline_sessions+ monkeypatch.setattr(inline, "INLINE_LEASE_SECONDS", 0.15)+ monkeypatch.setattr(inline, "INLINE_HEARTBEAT_SECONDS", 0.02)+ started, finish = asyncio.Event(), asyncio.Event()+ calls = 0++ async def request():+ async with sessions() as db:+ user = await db.get(User, user_id)++ async def provider():+ nonlocal calls+ calls += 1+ started.set()+ await finish.wait()+ return "provider-result" if deferred else "完成的文案"++ run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ return await run(db, user, domain="drama", task_type="agent_chat", executor=provider)++ job = asyncio.create_task(request())+ try:+ await asyncio.wait_for(started.wait(), 3)+ async with sessions() as observer:+ task = (await observer.execute(select(TaskRun))).scalar_one()+ task_id, first_expiry = task.id, aware(task.lease_until)+ assert task.lease_token.startswith(inline.INLINE_LEASE_PREFIX)+ assert task.next_action_at is None and task.status == "running"+ # Initial admission is deliberately short; renewals use the production+ # window so SQLite/Windows scheduling jitter cannot expire the test owner.+ monkeypatch.setattr(inline, "INLINE_LEASE_SECONDS", 600)+ for _ in range(100):+ async with sessions() as observer:+ task = await observer.get(TaskRun, task_id)+ if aware(task.lease_until) > first_expiry + timedelta(seconds=1):+ break+ await asyncio.sleep(0.02)+ else:+ pytest.fail("independent inline heartbeat did not renew the lease")+ # The model outlives its original lease. Independent heartbeats keep it+ # valid; no scheduler-local HTTP job registration masks this regression.+ await asyncio.sleep(0.30)+ async with sessions() as observer:+ task = await observer.get(TaskRun, task_id)+ assert aware(task.lease_until) > first_expiry+ assert aware(task.lease_until) > datetime.now(UTC)+ task.updated_at = datetime.now(UTC) - timedelta(hours=1)+ await observer.commit()+ assert scheduler._running_jobs == {}+ assert await scheduler.recover_orphaned_tasks() == 0+ async with sessions() as observer:+ assert (await observer.get(TaskRun, task_id)).status == "running"+ finish.set()+ await asyncio.wait_for(job, 3)+ async with sessions() as observer:+ tasks = list((await observer.execute(select(TaskRun))).scalars())+ assert len(tasks) == 1 and calls == 1+ task = tasks[0]+ assert task.status == ("awaiting_poll" if deferred else "succeeded")+ assert task.lease_token is None and task.lease_until is None+ finally:+ finish.set()+ if not job.done():+ job.cancel()+ await asyncio.gather(job, return_exceptions=True)++[email protected]("cancel", [False, True])+async def test_failed_and_cancelled_inline_requests_release_leases(inline_sessions, cancel):+ sessions, user_id = inline_sessions++ async with sessions() as db:+ user = await db.get(User, user_id)++ async def provider():+ if cancel:+ raise asyncio.CancelledError()+ raise RuntimeError("provider unavailable")++ with pytest.raises(asyncio.CancelledError if cancel else RuntimeError):+ await ephemeral.run_billed_ephemeral(db, user, domain="drama", task_type="agent_chat", executor=provider)+ async with sessions() as observer:+ task = (await observer.execute(select(TaskRun))).scalar_one()+ assert task.status == ("cancelled" if cancel else "failed")+ assert task.lease_token is None and task.lease_until is None+ assert task.finished_at is not None+ assert await scheduler.recover_orphaned_tasks() == 0+++async def test_expired_inline_owner_fails_and_settles_once_without_replaying(inline_sessions, monkeypatch):+ sessions, user_id = inline_sessions+ monkeypatch.setattr(get_settings(), "billing_enabled", True)+ async with sessions() as db:+ task = TaskRun(requested_by=user_id, domain="drama", task_type="agent_chat", status="running", payload={})+ db.add(task)+ await db.flush()+ await freeze_for_task(db, task)+ assert task.billing_status == "frozen"+ db.add(UsageEvent(user_id=user_id, task_run_id=task.id, billing_key="llm_chat", charge_fen=25, settled=False))+ task.lease_token = inline.INLINE_LEASE_PREFIX + "stopped-process"+ task.lease_until = datetime.now(UTC) - timedelta(minutes=1)+ task.updated_at = datetime.now(UTC) - timedelta(hours=1)+ await db.commit()+ task_id = task.id+ assert await scheduler.recover_orphaned_tasks() == 1+ assert await scheduler.recover_orphaned_tasks() == 0+ async with sessions() as observer:+ task = await observer.get(TaskRun, task_id)+ user = await observer.get(User, user_id)+ assert task.status == "failed" and task.error_code == "inline_execution_interrupted"+ assert task.next_action_at is None and task.lease_token is None and task.lease_until is None+ assert task.billing_status == "settled" and task.billing_charged_fen == 25+ assert user.balance_fen == 9975 and user.frozen_fen == 0+ events = list((await observer.execute(select(TaskEvent.event_type).where(TaskEvent.task_id == task_id))).scalars())+ assert events.count("task.failed") == 1 and "task.recovered" not in events+ charges = list((await observer.execute(select(WalletLedger).where(WalletLedger.user_id == user_id, WalletLedger.kind == "settle"))).scalars())+ assert len(charges) == 1diff --git a/backend/tests/test_kepu_cancel_propagation.py b/backend/tests/test_kepu_cancel_propagation.pyindex 8cf8c8b..57413c8 100644--- a/backend/tests/test_kepu_cancel_propagation.py+++ b/backend/tests/test_kepu_cancel_propagation.py@@ -50,9 +50,11 @@ async def test_await_kepu_reraises_without_request() -> None:await _await_kepu(_fake_task(cancel_requested=False), _boom())-async def test_await_kepu_success_payload() -> None:+async def test_await_kepu_success_payload(monkeypatch) -> None:+ snapshot = AsyncMock(return_value={"kind": "image", "urls": ["/static/shot.png"]})+ monkeypatch.setattr("app.services.tasks.handlers._kepu_output_snapshot", snapshot)out = await _await_kepu(_fake_task(cancel_requested=False), _ok(), shot_id=3)- assert out == {"ok": True, "project_id": 7, "shot_id": 3}+ assert out == {"ok": True, "project_id": 7, "shot_id": 3, "kind": "image", "urls": ["/static/shot.png"]}def test_run_pipeline_reraises_after_cancel_side_effects() -> None:diff --git a/backend/tests/test_task_runtime_loading.py b/backend/tests/test_task_runtime_loading.pyindex 154ce29..a99b693 100644--- a/backend/tests/test_task_runtime_loading.py+++ b/backend/tests/test_task_runtime_loading.py@@ -7,6 +7,7 @@ from sqlalchemy import create_engine, inspectfrom sqlalchemy.orm import Sessionfrom app.models_tasks import TaskEvent, TaskRun, TaskStep, TaskTarget+import app.models_teams # noqa: F401 — resolve TaskRun.team_id before isolated table DDLfrom app.services.tasks.service import get_task_for_runtimediff --git a/backend/tests/test_team_voice_billing.py b/backend/tests/test_team_voice_billing.pyindex e0f2609..e11029f 100644--- a/backend/tests/test_team_voice_billing.py+++ b/backend/tests/test_team_voice_billing.py@@ -11,7 +11,7 @@ from app.api.drama import generation@pytest.mark.asyncio@pytest.mark.parametrize("team_id", [None, 91])-async def test_voice_endpoint_bills_only_team_inline_tasks(monkeypatch, team_id):+async def test_voice_endpoint_registers_all_tasks_and_bills_only_team(monkeypatch, team_id):project = DramaProject(id=17, user_id=2, team_id=team_id)asset = DramaAsset(id=8, project_id=17, type="voice", asset_type="audio", name="音色", url="/static/voice.mp3", params={})db = SimpleNamespace(get=AsyncMock(return_value=asset), commit=AsyncMock(), refresh=AsyncMock(), flush=AsyncMock(), rollback=AsyncMock())@@ -19,15 +19,18 @@ async def test_voice_endpoint_bills_only_team_inline_tasks(monkeypatch, team_id)synthesize = AsyncMock(return_value=asset)monkeypatch.setattr(generation, "generate_voice_asset_audio", synthesize)async def billed(_db, _user, **kwargs):- db.commit.assert_not_awaited()+ if team_id is not None:+ db.commit.assert_not_awaited()assert kwargs["task_type"] == "voice_synthesis"assert (kwargs["drama_project_id"], kwargs["asset_id"]) == (17, 8)+ assert kwargs["billable"] is (team_id is not None)+ assert kwargs["result_payload_factory"](asset) == {"kind": "audio", "urls": [asset.url], "asset_id": 8}return SimpleNamespace(id=5), await kwargs["executor"]()billing = AsyncMock(side_effect=billed)monkeypatch.setattr(generation, "run_billed_ephemeral", billing)result = await generation.generate_voice(DramaVoiceGenerateRequest(project_id=17, asset_id=8, voice_prompt="沉稳的声音"), db=db, user=User(id=2))assert result["asset"]["id"] == 8- assert billing.await_count == (0 if team_id is None else 1)+ billing.assert_awaited_once()synthesize.assert_awaited_once()diff --git a/backend/tests/test_upstream_observability.py b/backend/tests/test_upstream_observability.pyindex 376e1d8..0d2516e 100644--- a/backend/tests/test_upstream_observability.py+++ b/backend/tests/test_upstream_observability.py@@ -218,7 +218,7 @@ async def test_caller_session_logging_error_does_not_repeat_network_request(monk@pytest.mark.asyncio@pytest.mark.parametrize("deferred", [False, True])async def test_ephemeral_executor_installs_caller_event_session(monkeypatch, deferred):- """同步和异步轻量任务都在未提交事务内记录,不由日志增加提交或 flush。"""+ """同步和异步任务先登记受理;请求日志共用执行会话且不额外提交。"""from app.services.billing import ephemeraltask = TaskRun(id=42, status="pending", current_step_key="submit")@@ -242,7 +242,7 @@ async def test_ephemeral_executor_installs_caller_event_session(monkeypatch, defawait run(db, SimpleNamespace(id=9), domain="api", task_type="v1_video", executor=executor, commit=False)assert [event.event_type for event in events] == ["upstream.request.started", "upstream.request.accepted"]assert db.flush.await_count == 1 # 仅业务已有的 task.started flush。- db.commit.assert_not_awaited()+ db.commit.assert_awaited_once() # 接受任务在模型调用前持久化。assert upstream._event_session.get() is Nonediff --git a/docs/TASK_SCHEDULING.md b/docs/TASK_SCHEDULING.mdindex 595bcd2..2f50491 100644--- a/docs/TASK_SCHEDULING.md+++ b/docs/TASK_SCHEDULING.md@@ -17,7 +17,12 @@ TASK_QUEUE_VIDEO_CONCURRENCY=4## 生成与任务记录- `/tools/video`、`/tools/image`、`/tools/audio`:生成工作台;旧工具链接跳转到相应分类。-- `/tasks`:当前用户的独立生成记录,支持分类、状态、本地/上游任务 ID、日期筛选和下载。+- 主侧栏提供「视频」「图片」「我的任务」入口,桌面与移动菜单共用配置;视频、图片与 AI 短视频项目分别高亮。+- `/tasks`:「我的任务」统一展示工具工作台、漫剧、短视频、画布及开放 API 的生成任务,默认显示全部,支持视频、图片、音频、文字分类,以及状态、本地/上游任务 ID、日期筛选和下载。以上生成与任务页面需要登录,登录后返回原地址并保留查询参数。+- `GET /api/tasks/generations` 从 `TaskRun` 读取各入口任务,并合并没有关联统一任务的旧 `ToolRun`,关联记录只显示一次;服务端完成筛选、统计和分页,读取列表不会补写任务或调用上游。`GET /api/tasks/generations/{task_id}` 返回统一任务详情;旧工具记录仍使用工具详情接口。个人和团队空间分别授权,切换空间时取消旧请求并清空详情。+- 生成请求受理后先提交任务登记,再执行外部生成;个人配音、试听和分集合成也登记任务,保留各自原计费规则。完成、失败或取消均持久化状态,已保存的结果快照用于预览或下载,文字生成可查看及下载文本。+- HTTP 内联生成使用独立续租心跳保护长请求,调度器不会把仍在生成的任务误判为中断后重排队。进程中断且租约过期时,任务收敛为失败或取消并完成原有结算,不自动重发生成请求。+- 生成与任务页统一使用主站的白色、石墨灰和荧光绿配色,只保留主侧栏。「最近生成」和任务列表统一使用全局 `AssetDetailDialog`,复用媒体预览、放大、复制说明和下载,不再保留独立生成详情组件或样式。多结果可切换,进行中的详情独立刷新,任务离开当前筛选列表后仍能更新结果。- `POST /api/tools/run`:先创建 `ToolRun` 和同一条用于执行、计费的 `TaskRun`,事务提交后由调度器执行。响应中的 `task_id=task-<id>` 为本地查询标识,`platform_task_id` 为统一任务主键。- `TaskRun.provider_task_id` 为真实上游异步任务 ID;`provider_name`、`provider_status` 和任务事件记录上游状态。同步图片/音频接口可能没有上游异步任务 ID。- 视频提交后由服务端 poller 查询状态、保存结果和结算,浏览器只读取本地记录。旧视频记录仍兼容原 provider ID 查询,并由后台同步结果。diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 1f9d4a8..2ff5f81 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -10,6 +10,8 @@ import HomePage from './pages/HomePage'import MethodPage from './pages/MethodPage'import ToolsPage from './pages/ToolsPage'import ToolDetailPage from './pages/ToolDetailPage'+import GenerationPage from './pages/GenerationPage'+import GenerationTasksPage from './pages/GenerationTasksPage'import HelpPage from './pages/HelpPage'import { PrivacyPage, TermsPage } from './pages/LegalDocPage'import ContactPage from './pages/ContactPage'@@ -57,8 +59,11 @@ export default function App() {<Route path="/auth" element={<AuthPage />} /><Route path="/templates" element={<TemplatesPage />} /><Route path="/tools" element={<ToolsPage />} />+ <Route path="/tools/video" element={<RequireAuth><GenerationPage kind="video" /></RequireAuth>} />+ <Route path="/tools/image" element={<RequireAuth><GenerationPage kind="image" /></RequireAuth>} />+ <Route path="/tools/audio" element={<RequireAuth><GenerationPage kind="audio" /></RequireAuth>} /><Route path="/tools/:toolId" element={<ToolDetailPage />} />- <Route path="/tasks" element={<Navigate to="/settings?tab=tools" replace />} />+ <Route path="/tasks" element={<RequireAuth><GenerationTasksPage /></RequireAuth>} /><Route path="/assets" element={<AssetLibraryPage />} /><Route path="/help" element={<HelpPage />} /><Route path="/terms" element={<TermsPage />} />diff --git a/frontend/src/api/generationTasks.ts b/frontend/src/api/generationTasks.tsnew file mode 100644index 0000000..7a0f30b--- /dev/null+++ b/frontend/src/api/generationTasks.ts@@ -0,0 +1,20 @@+import { createJsonRequester } from './client'+import { apiErrorMessage } from './http'+import type { ToolRunFilters, ToolRunList, ToolRunRecord } from './tools'+import { generationDetailPath } 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}`)+}++export function getGenerationTaskDetail(record: Pick<ToolRunRecord, 'id' | 'source'>): Promise<ToolRunRecord> {+ return request(generationDetailPath(record))+}diff --git a/frontend/src/api/tools.ts b/frontend/src/api/tools.tsindex 41a0b17..71f50b5 100644--- a/frontend/src/api/tools.ts+++ b/frontend/src/api/tools.ts@@ -36,6 +36,12 @@ export type ToolTaskResult = {export type ToolRunRecord = {id: number+ source?: 'task' | 'tool'+ record_key?: string+ domain?: string | null+ task_type?: string | null+ text_content?: string | null+ billing_status?: string | nulltool_id: stringkind: stringstatus: string@@ -53,7 +59,7 @@ export type ToolRunRecord = {queue_type?: string | nullstarted_at?: string | nullfinished_at?: string | null- billing_charged_fen?: number+ billing_charged_fen?: number | null}export type ToolRunList = {diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsxindex 397c8bd..12f0df2 100644--- a/frontend/src/components/layout/SiteNav.tsx+++ b/frontend/src/components/layout/SiteNav.tsx@@ -2,7 +2,7 @@import { useEffect, useRef, useState } from 'react'import {ArrowUpRight, ChevronRight, CircleHelp, Clapperboard, CreditCard,- Images, LayoutDashboard, Menu, Plus, Settings2, UserRound, UsersRound,+ Image, Images, LayoutDashboard, ListTodo, Menu, Plus, Settings2, UserRound, UsersRound,Video, WandSparkles, Workflow, X,} from 'lucide-react'import { api } from '../../api'@@ -30,12 +30,16 @@ const NAV_ICONS = {drama: Clapperboard,canvas: Workflow,kepu: Video,+ video: Video,+ image: Image,tools: WandSparkles,+ tasks: ListTodo,assets: Images,team: UsersRound,pricing: CreditCard,}+/** 应用主侧栏及窄屏导航抽屉,共用路由与会话状态。 */export default function SiteNav({ active }: Props) {const nav = useNavigate()const location = useLocation()@@ -95,7 +99,8 @@ export default function SiteNav({ active }: Props) {if (!menuOpen) returnconst previousOverflow = document.body.style.overflowdocument.body.style.overflow = 'hidden'- closeButtonRef.current?.focus()+ // 等抽屉解除 visibility:hidden 后再移动焦点。+ const focusFrame = window.requestAnimationFrame(() => closeButtonRef.current?.focus())function keepFocusInside(event: KeyboardEvent) {// 独立弹窗接管自己的键盘事件;普通下拉仍归属当前抽屉。@@ -125,6 +130,7 @@ export default function SiteNav({ active }: Props) {document.addEventListener('keydown', keepFocusInside)return () => {+ window.cancelAnimationFrame(focusFrame)document.body.style.overflow = previousOverflowdocument.removeEventListener('keydown', keepFocusInside)menuButtonRef.current?.focus()@@ -167,7 +173,10 @@ export default function SiteNav({ active }: Props) {<button type="button" className="pf-mobile-create" aria-label={t('nav.startCreate')} onClick={goCreate}><Plus size={20} aria-hidden /></button></header>{menuOpen && <button type="button" className="pf-sidebar-backdrop" aria-label={t('nav.closeMenu')} tabIndex={-1} onClick={() => setMenuOpen(false)} />}- <aside ref={sidebarRef} id="pf-app-sidebar" className={`pf-app-sidebar${menuOpen ? ' is-open' : ''}`} role={menuOpen ? 'dialog' : undefined} aria-modal={menuOpen ? true : undefined} aria-label={t('nav.main')}>+ <aside ref={sidebarRef} id="pf-app-sidebar" className={`pf-app-sidebar${menuOpen ? ' is-open' : ''}`} role={menuOpen ? 'dialog' : undefined} aria-modal={menuOpen ? true : undefined} aria-label={t('nav.main')}+ onTransitionEnd={(event) => {+ if (menuOpen && event.target === event.currentTarget && event.propertyName === 'transform') closeButtonRef.current?.focus()+ }}><div className="pf-sidebar-top"><div className="pf-sidebar-brand"><BrandMark /><button ref={closeButtonRef} type="button" className="pf-sidebar-icon-button pf-sidebar-close" aria-label={t('nav.closeMenu')} onClick={() => setMenuOpen(false)}><X size={19} aria-hidden /></button></div><div className="pf-sidebar-workspace"><WorkspaceSwitcher /></div>diff --git a/frontend/src/components/layout/sidebar.css b/frontend/src/components/layout/sidebar.cssindex 2a54390..49ed2d9 100644--- a/frontend/src/components/layout/sidebar.css+++ b/frontend/src/components/layout/sidebar.css@@ -11,7 +11,6 @@.pf-shell--sidebar .pf-settings-side,.pf-shell--sidebar .pf-history-side { top: calc(var(--pf-content-top) + 24px); }.pf-shell--sidebar .pf-team-sidebar { top: calc(var(--pf-content-top) + 24px); }-.pf-shell--sidebar .gen-rail { top: calc(var(--pf-content-top) + 20px); }.pf-shell--sidebar .pf-create { min-height: calc(100dvh - var(--pf-content-top) - 5rem); }.pf-shell--sidebar .pf-editor,.pf-shell--sidebar .drama-workspace { min-height: calc(100dvh - var(--pf-content-top)); }@@ -47,7 +46,7 @@.pf-sidebar-navigation { flex: 1; min-height: 0; padding: 8px 14px 12px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: #e0e5dc transparent; }.pf-sidebar-group + .pf-sidebar-group { margin-top: 21px; }.pf-sidebar-group-label { display: block; padding: 9px 14px 10px; color: #90978f; font-size: 10px; font-weight: 550; letter-spacing: .1em; }-.pf-sidebar-link { position: relative; display: flex; align-items: center; gap: 12px; min-height: 44px; margin: 3px 0; padding: 11px 13px; border: 1px solid transparent; border-radius: 9px; color: #6e756e; font-size: 13px; transition: background .15s, color .15s, border-color .15s; }+.pf-sidebar-link { position: relative; display: flex; align-items: center; gap: 12px; min-height: 44px; margin: 3px 0; padding: 11px 13px; border: 1px solid transparent; border-radius: 9px; color: #6e756e; font-size: 14px; transition: background .15s, color .15s, border-color .15s; }.pf-sidebar-link > svg { flex: none; }.pf-sidebar-link > span { min-width: 0; }.pf-sidebar-link:hover { color: #20291a; background: #f5f7f1; }@@ -68,7 +67,7 @@.pf-sidebar-account > svg { color: #969e89; flex: none; }.pf-sidebar-account:hover, .pf-sidebar-account.is-active { border-color: #cfdcb8; background: #f5f9ed; }.pf-sidebar-account .pf-user-avatar { width: 31px; height: 31px; flex: none; }-.pf-sidebar-account > .pf-sidebar-account-guest { display: grid; place-items: center; width: 31px; height: 31px; flex: none; background: #edf1e5; border-radius: 50%; color: #7a8c61; }+.pf-sidebar-account > span.pf-sidebar-account-guest { display: grid; place-items: center; width: 31px; height: 31px; flex: 0 0 31px; background: #edf1e5; border-radius: 50%; color: #7a8c61; }.pf-sidebar-icon-button { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: #68735c; }.pf-sidebar-icon-button:hover { background: #eef2e6; }.pf-sidebar-close, .pf-app-mobile-header, .pf-sidebar-backdrop { display: none; }diff --git a/frontend/src/components/tools/GenerationLayout.tsx b/frontend/src/components/tools/GenerationLayout.tsxindex 7d96573..d19580f 100644--- a/frontend/src/components/tools/GenerationLayout.tsx+++ b/frontend/src/components/tools/GenerationLayout.tsx@@ -1,28 +1,13 @@import type { ReactNode } from 'react'-import { NavLink } from 'react-router-dom'-import { AudioLines, FolderOpen, Image, ListTodo, Video } from 'lucide-react'import AppShell from '../layout/AppShell'-import { useGenerationText } from '../../lib/generationMedia'+import { type MediaKind } from '../../lib/generationMedia'import '../../styles/generation.css'import '../../styles/generation-controls.css'-export default function GenerationLayout({ children, tasks = false }: { children: ReactNode; tasks?: boolean }) {- const text = useGenerationText()- const entries = [- { to: '/tools/video', label: text('视频', 'Video'), icon: Video },- { to: '/tools/image', label: text('图片', 'Image'), icon: Image },- { to: '/tools/audio', label: text('音频', 'Audio'), icon: AudioLines },- { to: '/tasks', label: text('任务', 'Tasks'), icon: ListTodo },- { to: '/assets', label: text('资产', 'Assets'), icon: FolderOpen },- ]- return <AppShell active={tasks ? 'tasks' : 'tools'} wide hideFooter>+/** 生成工作台与任务页共用布局,主侧栏按当前媒体类型高亮。 */+export default function GenerationLayout({ children, tasks = false, kind }: { children: ReactNode; tasks?: boolean; kind?: MediaKind }) {+ return <AppShell active={tasks ? 'tasks' : kind === 'video' || kind === 'image' ? kind : 'tools'} wide hideFooter><div className="gen-layout">- <nav className="gen-rail" aria-label={text('生成工作台', 'Generation studio')}>- <span className="gen-rail-mark" aria-hidden>✦</span>- {entries.map(({ to, label, icon: Icon }) => <NavLink key={to} to={to} className={({ isActive }) => isActive ? 'is-active' : ''}>- <Icon size={21} strokeWidth={1.8} /><span>{label}</span>- </NavLink>)}- </nav><div className="gen-main">{children}</div></div></AppShell>diff --git a/frontend/src/hooks/useToolRunDetail.ts b/frontend/src/hooks/useToolRunDetail.tsnew file mode 100644index 0000000..2313cb7--- /dev/null+++ b/frontend/src/hooks/useToolRunDetail.ts@@ -0,0 +1,56 @@+import { useEffect, useState } from 'react'+import type { ToolRunRecord } from '../api/tools'+import { getGenerationTaskDetail } from '../api/generationTasks'+import { toolRunDetailAsset } from '../lib/toolRunDetails'+import { useGenerationText } from '../lib/generationMedia'+import { subscribeWorkspace, workspaceScope } from '../features/teams/workspaceScope'++/** 管理选中生成记录及刷新;展示、复制和下载统一交给全局资产详情。 */+export function useToolRunDetail() {+ const text = useGenerationText()+ /* detail 选中任务的最新快照;error 更新错误;resultIndex 当前预览结果。 */+ const [detail, setDetail] = useState<ToolRunRecord | null>(null)+ const [error, setError] = useState('')+ const [resultIndex, selectResult] = useState(0)+ const recordId = detail?.id+ const recordSource = detail?.source || 'tool'++ useEffect(() => subscribeWorkspace(() => { setDetail(null); setError(''); selectResult(0) }), [])++ useEffect(() => {+ if (recordId === undefined) return+ // 先展示点击时的快照,异步结果只允许回填本次选中的任务。+ const selectedRecord = { id: recordId, source: recordSource }+ const epoch = workspaceScope.epoch+ let disposed = false+ let timer: ReturnType<typeof setTimeout>+ /** 任务移出筛选列表后继续更新详情,终态停止轮询。 */+ async function refresh() {+ try {+ const record = await getGenerationTaskDetail(selectedRecord)+ if (disposed || epoch !== workspaceScope.epoch) return+ setDetail(record)+ setError('')+ if (record.status === 'queued' || record.status === 'running') timer = setTimeout(refresh, 5000)+ } catch (cause) {+ if (disposed || epoch !== workspaceScope.epoch) return+ setError(cause instanceof Error ? cause.message : text('详情更新失败,正在重试', 'Could not update details. Retrying.'))+ timer = setTimeout(refresh, 10000)+ }+ }+ void refresh()+ return () => { disposed = true; clearTimeout(timer) }+ }, [recordId, recordSource, text])++ /** 每次打开都使用新快照并重置结果序号与上次错误。 */+ function openDetail(record: ToolRunRecord) {+ setDetail(record)+ selectResult(0)+ setError('')+ }++ /** 关闭后卸载全局弹窗,同时停止详情轮询。 */+ function closeDetail() { setDetail(null) }++ return { detail, asset: detail ? toolRunDetailAsset(detail, resultIndex) : null, error, resultIndex, selectResult, openDetail, closeDetail }+}diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.tsindex 67b514c..38df665 100644--- a/frontend/src/i18n/locales/en/shell.ts+++ b/frontend/src/i18n/locales/en/shell.ts@@ -55,6 +55,8 @@ export const enShell = {loginHint: 'Sign in to keep creating',skipContent: 'Skip to main content',kepu: 'AI Short Video',+ video: 'Video',+ image: 'Image',tools: 'Tools',tasks: 'My tasks',assets: 'Assets',diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.tsindex 73d8aa4..23b6714 100644--- a/frontend/src/i18n/locales/zh/shell.ts+++ b/frontend/src/i18n/locales/zh/shell.ts@@ -54,6 +54,8 @@ export const zhShell = {loginHint: '登录,继续你的创作',skipContent: '跳转到主要内容',kepu: 'AI短视频',+ video: '视频',+ image: '图片',tools: '小工具',tasks: '我的任务',assets: '资产',diff --git a/frontend/src/lib/generationTaskHistory.ts b/frontend/src/lib/generationTaskHistory.tsnew file mode 100644index 0000000..8333962--- /dev/null+++ b/frontend/src/lib/generationTaskHistory.ts@@ -0,0 +1,21 @@+import type { ToolRunRecord } from '../api/tools.ts'++/** TaskRun 与旧工具记录的数字 ID 独立,列表、下载和轮询必须带来源。 */+export function generationRecordKey(record: ToolRunRecord): string {+ return record.record_key || `${record.source || 'tool'}:${record.id}`+}++export function generationDetailPath(record: Pick<ToolRunRecord, 'id' | 'source'>): string {+ return record.source === 'task' ? `/api/tasks/generations/${record.id}` : `/api/tools/runs/${record.id}`+}++/** 完成时间不是结算凭据;费用被隐藏时不能将 null 当成零元。 */+export function generationBillingState(record: ToolRunRecord): 'hidden' | 'pending' | 'settled' | 'refunded' | 'free' | 'not_charged' {+ if (record.billing_charged_fen === null) return 'hidden'+ if (record.billing_status === 'refunded') return 'refunded'+ if (record.billing_status === 'settled') return 'settled'+ if (record.billing_status === 'skipped') return 'free'+ if (['reserved', 'frozen', 'pending'].includes(record.billing_status || '')) return 'pending'+ if ((record.billing_charged_fen || 0) > 0) return 'settled'+ return ['queued', 'running', 'pending'].includes(record.status) ? 'pending' : 'not_charged'+}diff --git a/frontend/src/lib/siteNavigation.ts b/frontend/src/lib/siteNavigation.tsindex a5b46c9..9cdbd08 100644--- a/frontend/src/lib/siteNavigation.ts+++ b/frontend/src/lib/siteNavigation.ts@@ -1,15 +1,20 @@-/** 主导航路由:自由画布与漫剧并列,旧短视频入口仍归属同一导航项。 */-export type NavActive = 'home' | 'canvas' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history' | 'team' | 'tasks' | 'help' | 'settings'+/** 主导航路由:创作产品、独立生成与资源协作共用同一份入口配置。 */+import { SHORT_VIDEO_LIST_PATH } from './shortVideoRoutes.ts'++export type NavActive = 'home' | 'canvas' | 'drama' | 'kepu' | 'video' | 'image' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history' | 'team' | 'tasks' | 'help' | 'settings'export const CREATION_NAV = [{ key: 'home', path: '/', label: 'nav.workbench' },{ key: 'drama', path: '/drama', label: 'nav.drama' },{ key: 'canvas', path: '/canvas', label: 'nav.canvas' },- { key: 'kepu', path: '/history', label: 'nav.kepu' },+ { key: 'kepu', path: SHORT_VIDEO_LIST_PATH, label: 'nav.kepu' },+ { key: 'video', path: '/tools/video', label: 'nav.video' },+ { key: 'image', path: '/tools/image', label: 'nav.image' },{ key: 'tools', path: '/tools', label: 'nav.tools' },] as constexport const RESOURCE_NAV = [+ { key: 'tasks', path: '/tasks', label: 'nav.tasks' },{ key: 'assets', path: '/assets', label: 'nav.assets' },{ key: 'team', path: '/teams', label: 'nav.team' },{ key: 'pricing', path: '/pricing', label: 'nav.pricing' },@@ -25,6 +30,8 @@ export function resolveNavActive(pathname: string, active?: NavActive): NavActivif (within('/drama/assets') || within('/assets')) return 'assets'if (within('/drama')) return 'drama'if (['/studio', '/templates', '/history'].some(within)) return 'kepu'+ if (within('/tools/video')) return 'video'+ if (within('/tools/image')) return 'image'if (within('/tools')) return 'tools'if (within('/tasks')) return 'tasks'if (within('/pricing')) return 'pricing'diff --git a/frontend/src/lib/toolRunDetails.ts b/frontend/src/lib/toolRunDetails.tsnew file mode 100644index 0000000..f3cac8e--- /dev/null+++ b/frontend/src/lib/toolRunDetails.ts@@ -0,0 +1,39 @@+import type { ToolRunRecord } from '../api/tools.ts'+import type { AssetDetailRecord } from './assetDetails.ts'++/** 将独立生成记录适配为全局资产详情,预览和下载始终使用所选正式结果。 */+export function toolRunDetailAsset(record: ToolRunRecord, resultIndex = 0): AssetDetailRecord {+ // 原始提示词与参数来自已提交的任务,不能使用当前生成表单覆盖。+ const params = record.params || {}+ const url = record.kind === 'text' ? null : record.urls[resultIndex] || record.urls[0] || null+ const duration = Number(String(params.duration || params.duration_sec || '').replace(/s$/i, ''))+ const labels: Record<string, string> = { video: '视频生成', image: '图片生成', audio: '音频生成', text: '文字生成' }+ const statuses: Record<string, string> = { queued: '任务正在排队,结果会自动更新。', running: '任务正在生成,结果会自动更新。', succeeded: '任务已完成,暂无可预览的媒体结果。', failed: '生成失败。', cancelled: '任务已取消。' }+ const textContent = record.text_content || record.error || statuses[record.status] || `任务状态:${record.status}`++ return {+ id: record.id,+ name: `${labels[record.kind] || '生成记录'} #${record.id}`,+ type: record.kind === 'text' || !url ? 'text' : record.kind,+ url,+ // 视频首帧只作已有视频的 poster;尚无成片时不能把图片作为视频下载或播放。+ cover: record.kind === 'image' ? url || record.preview_url+ : record.kind === 'video' && url && record.preview_url !== url ? record.preview_url : null,+ updated_at: record.finished_at || record.created_at,+ params: {+ ...((record.kind === 'text' || !url) ? { textContent } : {}),+ media_metadata: {+ source: 'generated',+ model_id: params.model_id || params.model,+ prompt: record.prompt,+ created_at: record.finished_at || record.created_at,+ parameters: {+ aspect_ratio: params.ratio || params.aspect_ratio,+ resolution: params.resolution,+ ...(record.kind === 'video' && Number.isFinite(duration) && duration > 0 ? { duration_sec: duration } : {}),+ ...(record.kind === 'audio' && params.voice ? { speaker: params.voice } : {}),+ },+ },+ },+ }+}diff --git a/frontend/src/pages/GenerationTasksPage.tsx b/frontend/src/pages/GenerationTasksPage.tsxindex d9a263b..32d4400 100644--- a/frontend/src/pages/GenerationTasksPage.tsx+++ b/frontend/src/pages/GenerationTasksPage.tsx@@ -1,24 +1,38 @@-import { useEffect, useState } from 'react'+import { useEffect, useState, useSyncExternalStore } from 'react'import { Link, Navigate, useSearchParams } from 'react-router-dom'-import { AlertCircle, ArrowUpRight, CheckCircle2, Clock3, Download, Eye, ListFilter, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react'-import { listToolRuns, resolveToolMediaUrl, type ToolRunRecord } from '../api/tools'+import { AlertCircle, ArrowUpRight, CheckCircle2, Clock3, Download, Eye, FileText, ListChecks, ListFilter, Loader2, Plus, RefreshCw, Search, X } from 'lucide-react'+import { resolveToolMediaUrl, type ToolRunRecord } from '../api/tools'+import { listGenerationTasks } from '../api/generationTasks'import GenerationLayout from '../components/tools/GenerationLayout'import GenerationDateRange from '../components/tools/GenerationDateRange'import GenerationSelect from '../components/tools/GenerationSelect'-import { mediaIcons, mediaKinds, type MediaKind, useGenerationText } from '../lib/generationMedia'-import Modal from '../components/ui/Modal'+import { AssetDetailDialog } from '../components/assets/AssetDetailDialog'+import { useToolRunDetail } from '../hooks/useToolRunDetail'+import { mediaIcons, useGenerationText } from '../lib/generationMedia'+import { generationBillingState, generationRecordKey } 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+export default function GenerationTasksPage() {if (!localStorage.getItem('token')) return <Navigate to="/auth?next=/tasks" replace />return <TaskHistory />}function TaskHistory() {+ const workspaceEpoch = useSyncExternalStore(subscribeWorkspace, workspaceSnapshot)+ return <TaskHistoryContent key={workspaceEpoch} />+}++function TaskHistoryContent() {const text = useGenerationText()const [params, setParams] = useSearchParams()- const kind = mediaKinds.includes(params.get('kind') as MediaKind) ? params.get('kind') as MediaKind : 'video'+ const kind = taskKinds.includes(params.get('kind') as TaskKind) ? params.get('kind') as TaskKind : 'all'const status = ['processing', 'succeeded', 'failed', 'cancelled'].includes(params.get('status') || '') ? params.get('status')! : ''const taskId = params.get('task_id') || ''const [query, setQuery] = useState(taskId)@@ -32,13 +46,22 @@ function TaskHistory() {const [loading, setLoading] = useState(true)const [error, setError] = useState('')const [revision, setRevision] = useState(0)- const [detail, setDetail] = useState<ToolRunRecord | null>(null)- const [downloading, setDownloading] = useState<number | null>(null)- const Icon = mediaIcons[kind]+ 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' ? '/tools' : kind === 'text' ? '/studio/new' : `/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'),+ }+ const billingLabels = {+ hidden: text('费用不可见', 'Cost hidden'), pending: text('待结算', 'Pending charge'), settled: text('已结算', 'Charged'),+ refunded: text('已退还', 'Refunded'), free: text('无需结算', 'No charge'), not_charged: text('未收费', 'Not charged'),+ }function filter(key: string, value: string) {const next = new URLSearchParams(params)if (value) next.set(key, value); else next.delete(key)@@ -52,7 +75,7 @@ function TaskHistory() {async function refresh() {if (from && to && from > to) { setError(text('开始日期不能晚于结束日期', 'Start date must precede end date')); setLoading(false); return }try {- const data = await listToolRuns(page, pageSize, { kind, status, task_id: taskId,+ const data = await listGenerationTasks(page, pageSize, { kind: kind === 'all' ? undefined : kind, status, task_id: taskId,created_from: from ? new Date(`${from}T00:00:00`).toISOString() : '',created_to: to ? new Date(`${to}T23:59:59.999`).toISOString() : '' })if (disposed) return@@ -68,9 +91,10 @@ function TaskHistory() {}, [kind, status, taskId, from, to, page, pageSize, revision, text])async function download(item: ToolRunRecord, url = item.urls[0]) {- setDownloading(item.id)+ setDownloading(generationRecordKey(item))try {- triggerBlobDownload(await fetchMediaBlob(resolveToolMediaUrl(url)), `printfilm_${item.kind}_${item.id}.${item.kind === 'video' ? 'mp4' : item.kind === 'audio' ? 'mp3' : 'png'}`)+ const blob = item.kind === 'text' ? new Blob([item.text_content || ''], { type: 'text/plain;charset=utf-8' }) : await fetchMediaBlob(resolveToolMediaUrl(url))+ triggerBlobDownload(blob, `printfilm_${item.kind}_${item.id}.${item.kind === 'video' ? 'mp4' : item.kind === 'audio' ? 'mp3' : item.kind === 'text' ? 'txt' : 'png'}`)} catch (err) { setError(err instanceof Error ? err.message : text('下载失败', 'Download failed')) }finally { setDownloading(null) }}@@ -94,20 +118,20 @@ function TaskHistory() {return <GenerationLayout tasks><header className="gen-tasks-heading"><div><div className="gen-section-eyebrow">{text('创作管理', 'CREATION LIBRARY')}</div><h1>{text('我的任务', 'My tasks')}<span className="gen-heading-dot" /></h1><p>{text('每一次灵感,都有迹可循。', 'Every idea, all in one place.')}</p></div>- <div className="gen-task-actions"><button className="gen-secondary" type="button" onClick={() => setRevision(value => value + 1)} disabled={loading}><RefreshCw size={16} className={loading ? 'gen-spin' : ''} />{text('刷新', 'Refresh')}</button><Link className="gen-primary" to={`/tools/${kind}`}><Plus size={18} />{text('去创作', 'Create something')}</Link></div>+ <div className="gen-task-actions"><button className="gen-secondary" type="button" onClick={() => setRevision(value => value + 1)} disabled={loading}><RefreshCw size={16} className={loading ? 'gen-spin' : ''} />{text('刷新', 'Refresh')}</button><Link className="gen-primary" to={createPath}><Plus size={18} />{text('去创作', 'Create something')}</Link></div></header><div className="gen-library"><div className="gen-task-tabs"><div role="tablist" aria-label={text('任务类型', 'Media type')}>- {mediaKinds.map((value, index) => {- const TabIcon = mediaIcons[value]+ {taskKinds.map((value, index) => {+ const TabIcon = taskIcons[value]return <button type="button" key={value} id={`gen-tab-${value}`} role="tab" tabIndex={value === kind ? 0 : -1}- aria-selected={value === kind} className={value === kind ? 'is-active' : ''} onClick={() => filter('kind', value)}+ aria-selected={value === kind} className={value === kind ? 'is-active' : ''} onClick={() => filter('kind', value === 'all' ? '' : value)}onKeyDown={event => {if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) returnevent.preventDefault()- const next = event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + (event.key === 'ArrowRight' ? 1 : 2)) % 3- filter('kind', mediaKinds[next]); document.getElementById(`gen-tab-${mediaKinds[next]}`)?.focus()- }}><TabIcon size={18} />{text(value === 'video' ? '视频任务' : value === 'image' ? '图片任务' : '音频任务', `${value[0].toUpperCase()}${value.slice(1)} tasks`)}</button>+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? taskKinds.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : taskKinds.length - 1)) % taskKinds.length+ filter('kind', taskKinds[next] === 'all' ? '' : taskKinds[next]); document.getElementById(`gen-tab-${taskKinds[next]}`)?.focus()+ }}><TabIcon size={18} />{kindLabels[value]}</button>})}</div><span className="gen-auto-sync"><i />{text('自动更新', 'Auto-updating')}</span></div><div className="gen-task-filters">@@ -127,32 +151,37 @@ function TaskHistory() {{error && <p className="gen-inline-error" role="alert">{error}</p>}<div className="gen-list-heading" aria-hidden><span><ListFilter size={14} />{text('生成内容', 'Creation')}</span><span>{text('任务状态', 'Status')}</span><span>{text('费用', 'Cost')}</span><span>{text('创建时间', 'Created')}</span><span>{text('操作', 'Actions')}</span></div><section className="gen-task-list" aria-label={text('生成任务记录', 'Generation history')} aria-busy={loading}>- {loading && !items.length ? <div className="gen-empty"><Loader2 className="gen-spin" size={28} />{text('加载任务中…', 'Loading tasks…')}</div> : !items.length ? <div className="gen-empty"><Icon size={36} /><strong>{text('暂无符合条件的任务', 'No matching tasks')}</strong><p>{text('调整筛选条件,或开始一次新的创作。', 'Adjust your filters or create something new.')}</p><Link to={`/tools/${kind}`}>{text('开始创作', 'Start creating')} →</Link></div> : items.map(item => {+ {loading && !items.length ? <div className="gen-empty"><Loader2 className="gen-spin" size={28} />{text('加载任务中…', 'Loading tasks…')}</div> : !items.length ? <div className="gen-empty"><Icon size={36} /><strong>{text('暂无符合条件的任务', 'No matching tasks')}</strong><p>{text('调整筛选条件,或开始一次新的创作。', 'Adjust your filters or create something new.')}</p><Link to={createPath}>{text('开始创作', 'Start creating')} →</Link></div> : items.map(item => {const RowStatusIcon = StatusIcon[item.status as keyof typeof StatusIcon] || Clock3- return <article className={`gen-task-row ${item.status === 'failed' ? 'has-error' : ''}`} key={item.id}>- <button className="gen-task-cover" type="button" onClick={() => setDetail(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 /> : <Icon size={28} />}+ const RowIcon = taskIcons[item.kind as TaskKind] || FileText+ const recordKey = generationRecordKey(item)+ const billingState = generationBillingState(item)+ 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={() => setDetail(item)} title={item.prompt}>{item.prompt || text('未命名创作', 'Untitled creation')}</button><div className="gen-task-metadata"><span className="gen-task-tag">{item.params?.ratio || (kind === 'audio' ? text('文字配音', 'Text to speech') : 'AI')}</span><span className="gen-task-number">#{item.platform_task_id || item.id}</span>{item.provider_task_id && <code title={item.provider_task_id}>{text('上游', 'Upstream')} {item.provider_task_id}</code>}</div>{item.error && <button type="button" className="gen-task-error" onClick={() => setDetail(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>{item.kind === 'video' ? 'MP4' : item.kind === 'audio' ? 'MP3' : text('图片', 'Image')}</small></div>- <div className="gen-task-cost"><strong>¥{((item.billing_charged_fen || 0) / 100).toFixed(2)}</strong><small>{item.finished_at ? text('已结算', 'Charged') : text('待结算', 'Pending charge')}</small></div>+ <div className="gen-task-description"><button type="button" className="gen-task-title" onClick={() => openDetail(item)} title={item.prompt}>{item.prompt || item.task_type || text('未命名创作', 'Untitled creation')}</button><div className="gen-task-metadata"><span className="gen-task-tag">{kindLabels[item.kind as TaskKind] || 'AI'}</span>{(item.params?.ratio || item.params?.aspect_ratio) && <span className="gen-task-tag">{item.params.ratio || item.params.aspect_ratio}</span>}<span className="gen-task-number">#{item.platform_task_id || item.id}</span>{item.provider_task_id && <code title={item.provider_task_id}>{text('上游', 'Upstream')} {item.provider_task_id}</code>}</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>- <div className="gen-row-actions">{item.status === 'succeeded' && item.urls[0] && <button type="button" className="gen-secondary" disabled={downloading === item.id} onClick={() => void download(item)}>{downloading === item.id ? <Loader2 size={15} className="gen-spin" /> : <Download size={15} />}{text('下载', 'Download')}</button>}<button type="button" className="gen-icon-button" onClick={() => setDetail(item)} aria-label={text('查看任务详情', 'Task details')}><Eye size={18} /></button></div>+ <div className="gen-row-actions">{item.status === 'succeeded' && (item.kind === 'text' ? item.text_content : item.urls[0]) && <button type="button" className="gen-secondary" disabled={downloading === recordKey} onClick={() => void download(item)}>{downloading === recordKey ? <Loader2 size={15} className="gen-spin" /> : <Download size={15} />}{text('下载', 'Download')}</button>}<button type="button" className="gen-icon-button" onClick={() => openDetail(item)} aria-label={text('查看任务详情', 'Task details')}><Eye size={18} /></button></div></article>})}</section><footer className="gen-task-pagination"><span>{text('共', 'Total')} <strong>{total}</strong> {text('条记录', 'creations')}<span className="gen-pagination-divider" />{text(`第 ${page} / ${pageCount} 页`, `Page ${page} of ${pageCount}`)}</span><div><Pagination page={page} pageCount={pageCount} onChange={setPage} showSummary={false} /><GenerationSelect compact label={text('每页条数', 'Items per page')} value={String(pageSize)} options={[8, 16, 24, 50].map(value => ({ value: String(value), label: text(`${value} 条 / 页`, `${value} / page`) }))} onChange={value => { setPageSize(Number(value)); setPage(1) }} /></div></footer></div>- <Modal open={Boolean(detail)} title={text('生成详情', 'Generation details')} onClose={() => setDetail(null)} className="gen-detail-modal">- {detail && <div className="gen-detail"><p className="gen-detail-prompt">{detail.prompt}</p><dl>- <div><dt>{text('任务 ID', 'Task ID')}</dt><dd>{detail.task_id || detail.id}</dd></div>- <div><dt>{text('调度队列', 'Queue')}</dt><dd>{{ text: text('文字', 'Text'), image: text('图片', 'Image'), video: text('视频', 'Video') }[detail.queue_type || ''] || '—'}</dd></div>- <div><dt>{text('上游任务 ID', 'Upstream task ID')}</dt><dd>{detail.provider_task_id || '—'}</dd></div>- <div><dt>{text('上游服务 / 状态', 'Provider / status')}</dt><dd>{detail.provider_name || '—'} / {detail.provider_status || '—'}</dd></div>- <div><dt>{text('耗时', 'Duration')}</dt><dd>{elapsed(detail)}</dd></div>- </dl>{detail.error && <p className="gen-inline-error">{detail.error}</p>}{detail.urls.map(url => <div key={url} className="gen-detail-media">{detail.kind === 'video' ? <video controls src={resolveToolMediaUrl(url)} /> : detail.kind === 'audio' ? <audio controls src={resolveToolMediaUrl(url)} /> : <img src={resolveToolMediaUrl(url)} alt={detail.prompt} />}<button type="button" className="gen-secondary" onClick={() => void download(detail, url)} disabled={downloading === detail.id}><Download size={16} />{text('下载结果', 'Download result')}</button></div>)}</div>}- </Modal>+ {detail && detailAsset && <AssetDetailDialog key={generationRecordKey(detail)} asset={detailAsset} onClose={closeDetail}+ notice={<section className="pf-asset-detail-prompt"><div className="pf-asset-detail-text">+ <p role="status">{labels[detail.status] || detail.status}{(detail.status === 'queued' || detail.status === 'running') && text(',结果会自动更新。', '. Results will update automatically.')}</p>+ {(detail.error || detailError) && <p role="alert">{detail.error || detailError}</p>}+ </div></section>}+ actions={detail.urls.length > 1 && <div className="pf-asset-detail-utilities" role="group" aria-label={text('生成结果', 'Generation results')}>+ {detail.urls.map((url, index) => <button type="button" key={url} className="pf-btn pf-btn-sm" aria-pressed={resultIndex === index} onClick={() => selectResult(index)}>{text(`结果 ${index + 1}`, `Result ${index + 1}`)}</button>)}+ </div>}>+ <section className="pf-asset-detail-history"><dl className="pf-asset-detail-meta"><dt>{text('任务 ID', 'Task ID')}</dt><dd>{detail.platform_task_id || detail.id}</dd>{detail.task_type && <><dt>{text('任务类型', 'Task type')}</dt><dd>{detail.task_type}</dd></>}</dl></section>+ </AssetDetailDialog>}</GenerationLayout>}diff --git a/frontend/src/styles/generation.css b/frontend/src/styles/generation.cssindex 81d0cd7..bfa0bb0 100644--- a/frontend/src/styles/generation.css+++ b/frontend/src/styles/generation.css@@ -1,171 +1,170 @@-.gen-layout { --gen-purple: #7450e4; --gen-line: #ece8f3; --gen-muted: #8c8399; display: grid; grid-template-columns: 76px minmax(0, 1fr); gap: 40px; min-height: calc(100vh - 150px); padding-top: 10px; color: #28253d; }-.gen-rail { position: sticky; top: 88px; display: flex; flex-direction: column; align-self: start; gap: 7px; padding: 13px 8px; background: #ffffffb8; border: 1px solid #fff; border-radius: 22px; box-shadow: 0 5px 24px #29223e04; }-.gen-rail-mark { color: var(--gen-purple); font-size: 33px; text-align: center; line-height: 1; padding: 8px 0 20px; }-.gen-rail a { display: flex; flex-direction: column; align-items: center; gap: 7px; padding: 15px 3px; color: #82758f; text-decoration: none; border-radius: 13px; font-size: 11px; font-weight: 500; transition: color .16s, background .16s; }-.gen-rail a:hover, .gen-rail a.is-active { background: #f0eaff; color: var(--gen-purple); }+.gen-layout, .gen-floating { --gen-accent: var(--pf-lime); --gen-accent-soft: var(--pf-lime-soft); --gen-accent-ink: #40571c; --gen-line: var(--pf-line); --gen-muted: var(--pf-muted); --gen-focus: #708e3b; }+.gen-layout { display: grid; grid-template-columns: minmax(0, 1fr); min-height: calc(100dvh - 120px); padding-top: 0; color: var(--pf-ink); }.gen-main { min-width: 0; padding: 12px 0 48px; }.gen-hero { position: relative; padding: 18px 0 36px; overflow: hidden; }-.gen-eyebrow { display: flex; align-items: center; gap: 10px; color: #6b41df; font-size: 18px; font-weight: 700; }+.gen-eyebrow { display: flex; align-items: center; gap: 10px; color: var(--pf-ink); font-size: 18px; font-weight: 700; }+.gen-eyebrow > svg { color: var(--gen-accent-ink); }.gen-hero h1 { font-size: clamp(32px, 3.1vw, 50px); font-weight: 800; letter-spacing: -1.5px; line-height: 1.3; margin: 24px 0 12px; position: relative; z-index: 1; }-.gen-hero h1 span { color: #7751ed; margin-left: 12px; }-.gen-hero p, .gen-tasks-heading p { color: #908b9e; margin: 10px 0 0; font-size: 14px; }-.gen-hero-art { position: absolute; right: 5%; top: 14px; color: #9d8bc2; transform: rotate(-9deg); opacity: .7; }-.gen-hero-art > svg { width: 130px; height: 130px; stroke-width: .75; filter: drop-shadow(8px 12px 0 #eee8fb); }-.gen-hero-art .gen-wave { position: absolute; right: -65px; top: 20px; width: 260px; color: #c8b7f9; transform: rotate(9deg); opacity: .5; }-.gen-composer { border: 1px solid #e6e1f1; border-radius: 20px; background: #fff; box-shadow: 0 6px 24px #40305006; overflow: hidden; transition: box-shadow .2s, border-color .2s; }-.gen-composer:focus-within { border-color: #baa5e6; box-shadow: 0 0 0 4px #7450e409, 0 8px 28px #40305008; }+.gen-hero h1 span { color: var(--gen-accent-ink); margin-left: 12px; }+.gen-hero p, .gen-tasks-heading p { color: var(--gen-muted); margin: 10px 0 0; font-size: 14px; }+.gen-hero-art { position: absolute; right: 5%; top: 14px; color: #8e9e75; transform: rotate(-9deg); opacity: .7; }+.gen-hero-art > svg { width: 130px; height: 130px; stroke-width: .75; filter: drop-shadow(8px 12px 0 var(--gen-accent-soft)); }+.gen-hero-art .gen-wave { position: absolute; right: -65px; top: 20px; width: 260px; color: #c9dba9; transform: rotate(9deg); opacity: .5; }+.gen-composer { border: 1px solid var(--gen-line); border-radius: 18px; background: var(--pf-card); box-shadow: 0 6px 24px #11131806; overflow: hidden; transition: box-shadow .2s, border-color .2s; }+.gen-composer:focus-within { border-color: #bdcc9e; box-shadow: 0 0 0 3px #cae88d33, 0 8px 28px #11131806; }.gen-input-area { display: flex; min-height: 255px; padding: 23px 24px 25px; gap: 24px; }.gen-prompt-wrap { position: relative; flex: 1; min-width: 0; }-.gen-prompt-wrap textarea { width: 100%; height: 100%; min-height: 210px; border: 0; outline: 0; border-radius: 8px; resize: vertical; color: #41354c; line-height: 1.95; padding: 8px 4px 35px; background: transparent; font: inherit; font-size: 15px; }-.gen-prompt-wrap textarea::placeholder { color: #b2acbf; }-.gen-counter { position: absolute; bottom: 2px; right: 2px; padding: 3px 8px; border-radius: 6px; background: #faf8fd; color: #a095a9; font-size: 11px; font-variant-numeric: tabular-nums; pointer-events: none; }+.gen-prompt-wrap textarea { width: 100%; height: 100%; min-height: 210px; border: 0; outline: 0; border-radius: 8px; resize: vertical; color: var(--pf-ink); line-height: 1.95; padding: 8px 4px 35px; background: transparent; font: inherit; font-size: 15px; }+.gen-prompt-wrap textarea::placeholder { color: #929b8a; }+.gen-counter { position: absolute; bottom: 2px; right: 2px; padding: 3px 8px; border-radius: 6px; background: var(--pf-bg); color: var(--gen-muted); font-size: 11px; font-variant-numeric: tabular-nums; pointer-events: none; }.gen-references { width: 220px; border-right: 1px solid var(--gen-line); padding-right: 22px; flex-shrink: 0; }-.gen-ref-count { display: flex; align-items: center; gap: 5px; color: #a39bac; font-size: 12px; margin-bottom: 12px; }+.gen-ref-count { display: flex; align-items: center; gap: 5px; color: var(--gen-muted); font-size: 12px; margin-bottom: 12px; }.gen-ref-grid { display: flex; flex-wrap: wrap; gap: 8px; }-.gen-upload { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 142px; width: 100%; color: #9c93ad; border: 1px dashed #e0d7ee; border-radius: 15px; background: #faf8ff; font-size: 13px; cursor: pointer; }-.gen-upload:hover { border-color: var(--gen-purple); color: var(--gen-purple); }+.gen-upload { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 142px; width: 100%; color: var(--gen-muted); border: 1px dashed var(--gen-line); border-radius: 15px; background: var(--pf-bg); font-size: 13px; cursor: pointer; }+.gen-upload:hover { border-color: #bdcc9e; background: #f5f9ed; color: var(--gen-accent-ink); }.gen-ref-item { position: relative; width: calc(50% - 4px); aspect-ratio: 1; }.gen-ref-item img, .gen-ref-item video { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; }-.gen-ref-item button { position: absolute; top: 3px; right: 3px; display: grid; place-items: center; border: 0; width: 20px; height: 20px; border-radius: 50%; background: #fff; cursor: pointer; }+.gen-ref-item button { position: absolute; top: 3px; right: 3px; display: grid; place-items: center; border: 0; width: 20px; height: 20px; border-radius: 50%; background: var(--pf-card); cursor: pointer; }.has-files .gen-upload { min-height: 70px; }-.gen-toolbar { border-top: 1px solid #f0edf6; background: #fcfbfe; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 17px 20px; }-.gen-control { display: inline-flex; align-items: center; gap: 10px; min-height: 52px; padding: 9px 12px; border: 1px solid #e6e0ed; border-radius: 11px; background: #fff; font-size: 13px; white-space: nowrap; }+.gen-toolbar { border-top: 1px solid var(--gen-line); background: var(--pf-bg); display: flex; align-items: center; gap: 10px; flex-wrap: wrap; padding: 17px 20px; }+.gen-control { display: inline-flex; align-items: center; gap: 10px; min-height: 52px; padding: 9px 12px; border: 1px solid var(--gen-line); border-radius: 11px; background: var(--pf-card); font-size: 13px; white-space: nowrap; }.gen-model { max-width: 235px; }.gen-model svg { flex-shrink: 0; }.gen-submit-group { display: flex; align-items: center; margin-left: auto; gap: 18px; }.gen-submit-group > span { font-size: 12px; color: var(--gen-muted); }+.gen-estimate { display: flex; flex-direction: column; align-items: flex-end; gap: 3px; max-width: 290px; color: var(--pf-muted); text-align: right; font-size: 12px; line-height: 1.6; }+.gen-estimate strong { color: var(--pf-ink); font-weight: 650; font-variant-numeric: tabular-nums; }+.gen-estimate small { font-size: 10px; }+.gen-estimate > button { padding: 0; border: 0; background: transparent; color: var(--gen-accent-ink); font-size: 11px; text-decoration: underline; }.gen-primary, .gen-secondary { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 42px; font: inherit; font-size: 13px; font-weight: 550; line-height: 1.4; border-radius: 11px; cursor: pointer; text-decoration: none; white-space: nowrap; transition: background .16s, box-shadow .16s, border-color .16s, transform .16s; }-.gen-primary { border: 1px solid var(--gen-purple); background: var(--gen-purple); color: #fff; padding: 10px 20px; box-shadow: 0 4px 9px #7450e426, inset 0 1px 0 #ffffff29; }-.gen-primary:hover { background: #6635df; color: #fff; }+.gen-primary { border: 1px solid #a8ec00; background: var(--gen-accent); color: #172300; padding: 10px 20px; box-shadow: 0 1px 2px #11131806; }+.gen-primary:hover { background: #aaf000; color: #172300; }.gen-primary:disabled { opacity: .4; cursor: not-allowed; box-shadow: none; }-.gen-secondary { border: 1px solid #e4ddec; background: #fff; color: #6d587f; padding: 10px 16px; box-shadow: 0 1px 2px #30264303; }-.gen-secondary:hover { background: #faf7ff; border-color: #c5acdb; color: var(--gen-purple); }+.gen-secondary { border: 1px solid var(--gen-line); background: var(--pf-card); color: var(--gen-muted); padding: 10px 16px; box-shadow: 0 1px 2px #11131803; }+.gen-secondary:hover { background: #f5f9ed; border-color: #bdcc9e; color: var(--gen-accent-ink); }.gen-secondary:disabled { opacity: .5; cursor: wait; }-.gen-icon-button { display: inline-grid; place-items: center; padding: 9px; border: 1px solid var(--gen-line); border-radius: 10px; color: #92859f; background: #fff; cursor: pointer; }+.gen-icon-button { display: inline-grid; place-items: center; padding: 9px; border: 1px solid var(--gen-line); border-radius: 10px; color: var(--gen-muted); background: var(--pf-card); cursor: pointer; }+.gen-icon-button:hover { background: #f5f9ed; color: var(--gen-accent-ink); border-color: #bdcc9e; }+.gen-icon-button:disabled { opacity: .5; cursor: wait; }.gen-notice { margin: 18px 0; color: #38846a; background: #f0faf5; border: 1px solid #dcf0e6; border-radius: 12px; padding: 12px 16px; font-size: 13px; display: flex; align-items: center; gap: 10px; }-.gen-notice a { margin-left: auto; display: inline-flex; align-items: center; gap: 5px; color: #6c42d0; }-.gen-recent { border: 1px solid var(--gen-line); border-radius: 20px; background: #fff; margin-top: 28px; overflow: hidden; }+.gen-notice a { margin-left: auto; display: inline-flex; align-items: center; gap: 5px; color: var(--gen-accent-ink); }+.gen-recent { border: 1px solid var(--gen-line); border-radius: 18px; background: var(--pf-card); margin-top: 28px; overflow: hidden; }.gen-recent > header { display: flex; justify-content: space-between; align-items: center; padding: 18px 24px; border-bottom: 1px solid var(--gen-line); }.gen-recent h2 { margin: 0; font-size: 16px; }-.gen-recent header a { display: flex; align-items: center; gap: 5px; color: var(--gen-purple); font-size: 13px; text-decoration: none; }-.gen-empty { min-height: 220px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 12px; padding: 35px 20px; color: #b4a6ca; }-.gen-empty strong { font-size: 15px; color: #8b7e9c; font-weight: 500; }-.gen-empty p { font-size: 13px; color: #ada4b6; margin: 0; }+.gen-recent header a { display: flex; align-items: center; gap: 5px; color: var(--gen-accent-ink); font-size: 13px; text-decoration: none; }+.gen-empty { min-height: 220px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 12px; padding: 35px 20px; color: #929b8a; }+.gen-empty strong { font-size: 15px; color: var(--gen-muted); font-weight: 500; }+.gen-empty p { font-size: 13px; color: #929b8a; margin: 0; }.gen-gallery { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; padding: 24px; }.gen-gallery-item { min-width: 0; }-.gen-gallery-preview { display: flex; align-items: center; justify-content: center; aspect-ratio: 16/10; position: relative; background: #f7f3fc; border-radius: 12px; color: #b6a3d3; overflow: hidden; }-.gen-gallery-preview img, .gen-gallery-preview video { width: 100%; height: 100%; object-fit: cover; }-.gen-result-status { position: absolute; bottom: 10px; right: 10px; border-radius: 6px; padding: 3px 8px; background: #fffE; color: #9c80d1; font-size: 11px; }+.gen-gallery-preview { display: flex; align-items: center; justify-content: center; width: 100%; padding: 0; border: 0; aspect-ratio: 16/10; position: relative; background: var(--pf-bg); border-radius: 12px; color: #929b8a; overflow: hidden; cursor: pointer; }+.gen-gallery-preview img, .gen-gallery-preview video { width: 100%; height: 100%; object-fit: cover; transition: transform .25s; }+.gen-gallery-preview:hover img, .gen-gallery-preview:hover video { transform: scale(1.035); }+.gen-result-status { position: absolute; bottom: 10px; right: 10px; border-radius: 6px; padding: 3px 8px; background: #fffE; color: var(--gen-muted); font-size: 11px; }.gen-result-status.is-succeeded { color: #22a17a; }.gen-result-status.is-failed { color: #d5676f; }.gen-gallery-caption { display: flex; align-items: center; justify-content: space-between; gap: 10px; }-.gen-gallery-caption p { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: #766b85; font-size: 12px; }+.gen-gallery-caption p, .gen-gallery-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--gen-muted); font-size: 12px; }+.gen-gallery-title { margin: 12px 0; padding: 0; border: 0; background: transparent; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }+.gen-gallery-title:hover { color: var(--gen-accent-ink); text-decoration: underline; }+.gen-gallery-caption .gen-icon-button { flex-shrink: 0; }.gen-gallery-item audio { width: 100%; height: 36px; margin-top: 8px; }/* Creation library and form hierarchy. */.gen-composer-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 19px 24px 0; }-.gen-composer-heading > span { display: flex; align-items: center; gap: 7px; color: #786386; font-size: 12px; font-weight: 600; }-.gen-composer-heading svg { color: #a183b9; }-.gen-composer-heading > small { color: #aa9bb6; font-size: 11px; }+.gen-composer-heading > span { display: flex; align-items: center; gap: 7px; color: var(--gen-muted); font-size: 12px; font-weight: 600; }+.gen-composer-heading svg { color: var(--gen-muted); }+.gen-composer-heading > small { color: var(--gen-muted); font-size: 11px; }.gen-prompt-wrap textarea:focus-visible { outline: none; }.gen-control small, .gen-control strong { display: block; }-.gen-control small { margin-bottom: 3px; color: #9a8aa6; font-size: 10px; line-height: 1.3; font-weight: 400; }-.gen-control strong { color: #55425f; font-size: 12px; font-weight: 550; line-height: 1.3; }+.gen-control small { margin-bottom: 3px; color: var(--gen-muted); font-size: 10px; line-height: 1.3; font-weight: 400; }+.gen-control strong { color: var(--pf-ink); font-size: 12px; font-weight: 550; line-height: 1.3; }.gen-model > span:last-child { min-width: 0; }.gen-model strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }-.gen-model-icon { display: grid; place-items: center; width: 32px; height: 32px; background: #f1ebfc; border-radius: 9px; color: #9568b9; flex-shrink: 0; }-.gen-output-count > svg { color: #a28ab4; }+.gen-model-icon { display: grid; place-items: center; width: 32px; height: 32px; background: var(--gen-accent-soft); border-radius: 9px; color: var(--gen-accent-ink); flex-shrink: 0; }+.gen-output-count > svg { color: var(--gen-muted); }.gen-submit-group .gen-primary { min-height: 48px; padding-inline: 25px; }-.gen-section-eyebrow { display: flex; align-items: center; gap: 9px; color: #9d87ac; font-size: 11px; font-weight: 600; letter-spacing: 1px; }+.gen-section-eyebrow { display: flex; align-items: center; gap: 9px; color: var(--gen-muted); font-size: 11px; font-weight: 600; letter-spacing: 1px; }.gen-tasks-heading { display: flex; justify-content: space-between; align-items: center; gap: 20px; margin: 5px 0 30px; }.gen-tasks-heading h1 { display: flex; align-items: center; gap: 10px; font-size: 34px; font-weight: 750; letter-spacing: -1px; line-height: 1.25; margin: 9px 0 0; }-.gen-heading-dot { width: 7px; height: 7px; margin-top: 15px; border-radius: 50%; background: #bba3e6; }+.gen-heading-dot { width: 7px; height: 7px; margin-top: 15px; border-radius: 50%; background: var(--gen-accent); }.gen-task-actions { display: flex; align-items: center; gap: 9px; }-.gen-library { border: 1px solid #e6dfed; border-radius: 18px; background: #fff; box-shadow: 0 5px 26px #30214206; overflow: hidden; }-.gen-task-tabs { display: flex; align-items: center; justify-content: space-between; padding: 18px 22px; border-bottom: 1px solid #f0eaf5; gap: 20px; }-.gen-task-tabs [role=tablist] { display: flex; gap: 7px; padding: 4px; border: 1px solid #eee7f5; border-radius: 12px; background: #f6f3fa; }-.gen-task-tabs [role=tab] { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 37px; padding: 8px 16px; border: 1px solid transparent; border-radius: 8px; color: #a18bad; background: transparent; font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; white-space: nowrap; transition: background .16s, color .16s, box-shadow .16s; }-.gen-task-tabs [role=tab]:hover { color: #87649d; }-.gen-task-tabs [role=tab].is-active { border-color: #e4d8ee; background: #fff; color: #8053a0; font-weight: 650; box-shadow: 0 2px 4px #5640630a; }-.gen-auto-sync { display: flex; align-items: center; gap: 6px; color: #a993b8; font-size: 10px; white-space: nowrap; }+.gen-library { border: 1px solid var(--gen-line); border-radius: 18px; background: var(--pf-card); box-shadow: 0 5px 26px #11131806; overflow: hidden; }+.gen-task-tabs { display: flex; align-items: center; justify-content: space-between; padding: 18px 22px; border-bottom: 1px solid var(--gen-line); gap: 20px; }+.gen-task-tabs [role=tablist] { display: flex; min-width: 0; overflow-x: auto; gap: 7px; padding: 4px; border: 1px solid var(--gen-line); border-radius: 12px; background: var(--pf-bg); }+.gen-task-tabs [role=tab] { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 37px; padding: 8px 16px; border: 1px solid transparent; border-radius: 8px; color: var(--gen-muted); background: transparent; font: inherit; font-size: 12px; font-weight: 500; cursor: pointer; white-space: nowrap; transition: background .16s, color .16s, box-shadow .16s; }+.gen-task-tabs [role=tab]:hover { color: var(--pf-ink); }+.gen-task-tabs [role=tab].is-active { border-color: #dce9c7; background: var(--gen-accent-soft); color: var(--gen-accent-ink); font-weight: 650; box-shadow: 0 2px 4px #11131806; }+.gen-auto-sync { display: flex; align-items: center; gap: 6px; color: var(--gen-muted); font-size: 10px; white-space: nowrap; }.gen-auto-sync > i { width: 5px; height: 5px; border-radius: 50%; background: #79ad98; box-shadow: 0 0 0 3px #edf6f2; }.gen-task-filters { display: flex; flex-direction: column; gap: 17px; padding: 20px 22px; }.gen-status-tabs { display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }-.gen-status-tabs button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; border: 1px solid transparent; border-radius: 8px; background: #fff; padding: 7px 11px; color: #9781a6; font: inherit; font-size: 12px; white-space: nowrap; cursor: pointer; transition: background .15s, border-color .15s; }-.gen-status-tabs button:hover { background: #faf6fe; }-.gen-status-tabs button.is-active { border-color: #dfcbee; background: #f4edfc; color: #9763b8; font-weight: 600; }-.gen-status-tabs span { min-width: 18px; padding: 1px 5px; border-radius: 5px; background: #f6f0fa; color: #ae91c2; text-align: center; font-size: 10px; font-weight: 500; font-variant-numeric: tabular-nums; }-.gen-status-tabs button.is-active > span { background: #e9dcf5; color: #9b6bb9; }+.gen-status-tabs button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; border: 1px solid transparent; border-radius: 8px; background: var(--pf-card); padding: 7px 11px; color: var(--gen-muted); font: inherit; font-size: 12px; white-space: nowrap; cursor: pointer; transition: background .15s, border-color .15s; }+.gen-status-tabs button:hover { background: var(--pf-bg); }+.gen-status-tabs button.is-active { border-color: #dce9c7; background: var(--gen-accent-soft); color: var(--gen-accent-ink); font-weight: 600; }+.gen-status-tabs span { min-width: 18px; padding: 1px 5px; border-radius: 5px; background: var(--pf-bg); color: #929b8a; text-align: center; font-size: 10px; font-weight: 500; font-variant-numeric: tabular-nums; }+.gen-status-tabs button.is-active > span { background: #dceeb8; color: var(--gen-accent-ink); }.gen-filter-inputs { display: flex; align-items: center; gap: 12px; }-.gen-search { display: flex; align-items: center; gap: 10px; width: min(100%, 330px); min-height: 42px; padding: 5px 6px 5px 12px; border: 1px solid #e4ddec; border-radius: 10px; background: #fff; color: #a58ab7; transition: box-shadow .16s, border-color .16s; }-.gen-search:focus-within { border-color: #b89ad5; box-shadow: 0 0 0 3px #b28ad915; }-.gen-search input { width: 100%; min-width: 0; padding: 5px 0; border: 0; outline: 0; background: transparent; font: inherit; font-size: 12px; color: #79538e; }+.gen-search { display: flex; align-items: center; gap: 10px; width: min(100%, 330px); min-height: 42px; padding: 5px 6px 5px 12px; border: 1px solid var(--gen-line); border-radius: 10px; background: var(--pf-card); color: var(--gen-muted); transition: box-shadow .16s, border-color .16s; }+.gen-search:focus-within { border-color: #bdcc9e; box-shadow: 0 0 0 3px #cae88d33; }+.gen-search input { width: 100%; min-width: 0; padding: 5px 0; border: 0; outline: 0; background: transparent; font: inherit; font-size: 12px; color: var(--pf-ink); }.gen-search input:focus-visible { outline: none; }-.gen-search input::placeholder { color: #b49fc1; }+.gen-search input::placeholder { color: #929b8a; }.gen-search > svg { flex-shrink: 0; }-.gen-search-submit, .gen-search-clear { display: inline-grid; place-items: center; flex-shrink: 0; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 7px; background: #f4ebfb; color: #b18acb; cursor: pointer; }-.gen-search-submit:hover { background: #eadcf6; color: #9866b9; }-.gen-search-clear { width: 20px; background: transparent; color: #b4a0c1; }-.gen-search-clear:hover { background: #f7f1fb; }-.gen-reset-filters { padding: 6px 0; border: 0; background: transparent; color: #a27fba; font-size: 11px; cursor: pointer; white-space: nowrap; }-.gen-reset-filters:hover { color: #87539f; text-decoration: underline; }-.gen-list-heading { display: grid; grid-template-columns: minmax(0, 1fr) 108px 82px 128px 112px; gap: 18px; align-items: center; padding: 12px 23px; border-block: 1px solid #f1e9f7; background: #fcfaff; color: #8b7b99; font-size: 11px; font-weight: 500; }+.gen-search-submit, .gen-search-clear { display: inline-grid; place-items: center; flex-shrink: 0; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 7px; background: var(--pf-bg); color: #929b8a; cursor: pointer; }+.gen-search-submit:hover { background: var(--gen-accent-soft); color: var(--gen-accent-ink); }+.gen-search-clear { width: 20px; background: transparent; color: #929b8a; }+.gen-search-clear:hover { background: var(--pf-bg); }+.gen-reset-filters { padding: 6px 0; border: 0; background: transparent; color: var(--gen-muted); font-size: 11px; cursor: pointer; white-space: nowrap; }+.gen-reset-filters:hover { color: var(--gen-accent-ink); text-decoration: underline; }+.gen-list-heading { display: grid; grid-template-columns: minmax(0, 1fr) 108px 82px 128px 112px; gap: 18px; align-items: center; padding: 12px 23px; border-block: 1px solid var(--gen-line); background: var(--pf-bg); color: var(--gen-muted); font-size: 11px; font-weight: 500; }.gen-list-heading > span:first-child { display: flex; align-items: center; gap: 7px; }.gen-list-heading > span:last-child { text-align: right; padding-right: 12px; }-.gen-task-list { background: #fff; }-.gen-task-row { display: grid; grid-template-columns: 108px minmax(0, 1fr) 108px 82px 128px 112px; align-items: center; padding: 21px 23px; gap: 18px; border-bottom: 1px solid #f2eaf7; transition: background .15s; }+.gen-task-list { background: var(--pf-card); }+.gen-task-row { display: grid; grid-template-columns: 108px minmax(0, 1fr) 108px 82px 128px 112px; align-items: center; padding: 21px 23px; gap: 18px; border-bottom: 1px solid var(--gen-line); transition: background .15s; }.gen-task-row:last-child { border-bottom: 0; }-.gen-task-row:hover { background: #fdfbff; }-.gen-task-cover { position: relative; width: 108px; height: 72px; display: grid; place-items: center; border: 1px solid #efe2f7; padding: 0; border-radius: 10px; overflow: hidden; background: #faf5ff; color: #c3a5d6; cursor: pointer; }+.gen-task-row:hover { background: var(--pf-bg); }+.gen-task-cover { position: relative; width: 108px; height: 72px; display: grid; place-items: center; border: 1px solid var(--gen-line); padding: 0; border-radius: 10px; overflow: hidden; background: var(--pf-bg); color: #929b8a; cursor: pointer; }.gen-task-cover img, .gen-task-cover video { width: 100%; height: 100%; object-fit: cover; transition: transform .25s; }.gen-task-cover:hover img, .gen-task-cover:hover video { transform: scale(1.06); }-.gen-cover-overlay { position: absolute; inset: 0; display: grid; place-items: center; color: #fff; background: #45245f55; opacity: 0; transition: opacity .2s; }-.gen-task-cover:hover .gen-cover-overlay { opacity: 1; }+.gen-cover-overlay { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; color: #fff; background: #11131866; font-size: 12px; opacity: 0; transition: opacity .2s; }+.gen-task-cover:hover .gen-cover-overlay, .gen-task-cover:focus-visible .gen-cover-overlay,+.gen-gallery-preview:hover .gen-cover-overlay, .gen-gallery-preview:focus-visible .gen-cover-overlay { opacity: 1; }.gen-task-description { min-width: 0; }-.gen-task-title { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; width: 100%; max-width: 100%; padding: 0; border: 0; overflow: hidden; text-align: left; background: transparent; color: #3f3549; font: inherit; font-size: 14px; line-height: 1.8; font-weight: 500; cursor: pointer; }-.gen-task-title:hover { color: #8856a6; }-.gen-task-metadata { display: flex; align-items: center; gap: 9px; margin-top: 9px; overflow: hidden; color: #97869f; font-size: 11px; white-space: nowrap; }-.gen-task-tag { flex-shrink: 0; padding: 2px 6px; border: 1px solid #eadcf3; border-radius: 5px; background: #f9f3fe; color: #aa83c2; font-size: 9px; line-height: 1.3; }-.gen-task-number { color: #a287b3; font-variant-numeric: tabular-nums; }-.gen-task-metadata code { overflow: hidden; text-overflow: ellipsis; color: #a092ac; font-size: 10px; }+.gen-task-title { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; width: 100%; max-width: 100%; padding: 0; border: 0; overflow: hidden; text-align: left; background: transparent; color: var(--pf-ink); font: inherit; font-size: 14px; line-height: 1.8; font-weight: 500; cursor: pointer; }+.gen-task-title:hover { color: var(--gen-accent-ink); }+.gen-task-metadata { display: flex; align-items: center; gap: 9px; margin-top: 9px; overflow: hidden; color: var(--gen-muted); font-size: 11px; white-space: nowrap; }+.gen-task-tag { flex-shrink: 0; padding: 2px 6px; border: 1px solid var(--gen-line); border-radius: 5px; background: var(--pf-bg); color: var(--gen-muted); font-size: 9px; line-height: 1.3; }+.gen-task-number { color: var(--gen-muted); font-variant-numeric: tabular-nums; }+.gen-task-metadata code { overflow: hidden; text-overflow: ellipsis; color: var(--gen-muted); font-size: 10px; }.gen-task-state, .gen-task-cost, .gen-task-time { display: flex; align-items: flex-start; flex-direction: column; gap: 8px; min-width: 0; font-size: 12px; }-.gen-task-row small { color: #a397ad; font-size: 11px; line-height: 1.4; }-.gen-state { display: inline-flex; align-items: center; justify-content: center; gap: 5px; padding: 5px 7px; border: 1px solid transparent; border-radius: 6px; background: #f6edfc; color: #946ab1; font-size: 11px; font-weight: 500; white-space: nowrap; }+.gen-task-row small { color: var(--gen-muted); font-size: 11px; line-height: 1.4; }+.gen-state { display: inline-flex; align-items: center; justify-content: center; gap: 5px; padding: 5px 7px; border: 1px solid transparent; border-radius: 6px; background: var(--pf-bg); color: var(--gen-muted); font-size: 11px; font-weight: 500; white-space: nowrap; }.gen-state.is-succeeded { color: #38846b; background: #f0f8f4; border-color: #e0efe7; }.gen-state.is-failed { color: #b96f84; background: #fff3f6; border-color: #f6e3e9; }-.gen-state.is-cancelled { color: #a08cad; background: #f7f3fa; }+.gen-state.is-cancelled { color: var(--gen-muted); background: var(--pf-bg); }.gen-task-state > small { padding-left: 4px; }-.gen-task-cost strong { color: #785a8b; font-size: 12px; font-weight: 550; font-variant-numeric: tabular-nums; }-.gen-task-time > span { color: #8c7a97; font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }+.gen-task-cost strong { color: var(--pf-ink); font-size: 12px; font-weight: 550; font-variant-numeric: tabular-nums; }+.gen-task-time > span { color: var(--gen-muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }.gen-task-error { display: flex; align-items: center; gap: 5px; max-width: 100%; margin-top: 7px; padding: 0; border: 0; background: transparent; color: #c48c9d; font-size: 10px; line-height: 1.5; text-align: left; cursor: pointer; }.gen-task-error > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.gen-task-error > svg { flex-shrink: 0; }.gen-task-error:hover { color: #b26a84; }.gen-row-actions { display: flex; justify-content: flex-end; align-items: center; gap: 7px; }-.gen-row-actions .gen-secondary { min-height: 33px; padding: 7px 10px; border-radius: 8px; font-size: 11px; color: #9271a3; border-color: #e8d8f2; }-.gen-row-actions .gen-icon-button { min-height: 33px; min-width: 33px; padding: 7px; color: #ac88c3; border-color: #eadcf4; border-radius: 8px; }-.gen-task-pagination { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px 23px; border-top: 1px solid #efe5f6; color: #a88ab9; font-size: 10px; }+.gen-row-actions .gen-secondary { min-height: 33px; padding: 7px 10px; border-radius: 8px; font-size: 11px; color: var(--gen-muted); border-color: var(--gen-line); }+.gen-row-actions .gen-icon-button { min-height: 33px; min-width: 33px; padding: 7px; color: var(--gen-muted); border-color: var(--gen-line); border-radius: 8px; }+.gen-task-pagination { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px 23px; border-top: 1px solid var(--gen-line); color: var(--gen-muted); font-size: 10px; }.gen-task-pagination > span { display: flex; align-items: center; flex-wrap: wrap; gap: 5px; }-.gen-task-pagination > span > strong { color: #976fae; font-weight: 600; }-.gen-pagination-divider { width: 1px; height: 10px; margin: 0 6px; background: #e5d5ee; }+.gen-task-pagination > span > strong { color: var(--pf-ink); font-weight: 600; }+.gen-pagination-divider { width: 1px; height: 10px; margin: 0 6px; background: var(--gen-line); }.gen-task-pagination > div { display: flex; align-items: center; gap: 12px; }.gen-task-pagination .pf-list-pagination { margin: 0; padding: 0; }-.gen-task-pagination .pf-page-btn { min-width: 30px; height: 30px; padding: 4px; border-radius: 7px; font-size: 10px; color: #a585ba; border-color: #e7d6f3; }-.gen-task-pagination .pf-page-btn.active { background: #f0e4fa; border-color: #d6b9e8; color: #a273c1; }+.gen-task-pagination .pf-page-btn { min-width: 30px; height: 30px; padding: 4px; border-radius: 7px; font-size: 10px; color: var(--gen-muted); border-color: var(--gen-line); }+.gen-task-pagination .pf-page-btn.active { background: var(--gen-accent-soft); border-color: #dce9c7; color: var(--gen-accent-ink); }.gen-inline-error { font-size: 13px; padding: 12px 16px; color: #be6279; background: #fff4f6; border-radius: 10px; overflow-wrap: anywhere; }.gen-task-list > nav { padding: 20px; }-.gen-detail { color: #55465f; }-.gen-detail-prompt { white-space: pre-wrap; max-height: 220px; overflow-y: auto; font-size: 14px; }-.gen-detail dl > div { display: flex; justify-content: space-between; gap: 15px; padding: 10px 0; border-bottom: 1px solid #eee8f5; font-size: 12px; }-.gen-detail dt { color: #a193ae; flex-shrink: 0; }-.gen-detail dd { margin: 0; word-break: break-all; text-align: right; }-.gen-detail-media { display: flex; flex-direction: column; gap: 12px; align-items: center; margin-top: 20px; }-.gen-detail-media img, .gen-detail-media video { width: 100%; max-height: 400px; object-fit: contain; border-radius: 10px; }-.gen-detail-media audio { width: 100%; }.gen-spin { animation: gen-spin 1s linear infinite; }@keyframes gen-spin { to { transform: rotate(360deg); } }-@media (min-width: 1600px) { .gen-layout { gap: 48px; } }@media (max-width: 1200px) {- .gen-layout { gap: 25px; grid-template-columns: 68px minmax(0, 1fr); }.gen-task-row { grid-template-columns: 96px minmax(0, 1fr) 100px 116px 104px; gap: 13px; padding-inline: 18px; }.gen-task-cover { width: 96px; height: 66px; }.gen-task-cost { display: none; }@@ -177,18 +176,12 @@}@media (max-width: 900px) {.gen-layout { display: block; }- .gen-rail { position: static; flex-direction: row; gap: 5px; padding: 6px; border-radius: 15px; margin-bottom: 20px; }- .gen-rail-mark { display: none; }- .gen-rail a { flex: 1; flex-direction: row; justify-content: center; gap: 7px; padding: 13px 5px; border-radius: 9px; }- .gen-rail a svg { width: 17px; height: 17px; }.gen-main { padding-top: 0; }.gen-tasks-heading { margin: 0 0 24px; }.gen-task-tabs, .gen-task-filters { padding-inline: 17px; }}@media (max-width: 650px) {.gen-layout { padding-top: 0; }- .gen-rail { gap: 2px; margin-bottom: 23px; }- .gen-rail a { flex-direction: column; gap: 5px; padding: 10px 2px; font-size: 10px; }.gen-tasks-heading { align-items: flex-start; gap: 10px; }.gen-tasks-heading h1 { font-size: 28px; }.gen-tasks-heading p { max-width: 165px; font-size: 11px; line-height: 1.7; }@@ -198,7 +191,7 @@.gen-library { border-radius: 15px; }.gen-task-tabs { padding: 14px; gap: 8px; }.gen-task-tabs [role=tablist] { width: 100%; gap: 2px; padding: 3px; border-radius: 10px; }- .gen-task-tabs [role=tab] { flex: 1; padding: 8px 7px; min-height: 35px; gap: 5px; font-size: 11px; }+ .gen-task-tabs [role=tab] { flex: 1 0 auto; padding: 8px 7px; min-height: 35px; gap: 5px; font-size: 11px; }.gen-task-tabs [role=tab] svg { width: 15px; }.gen-auto-sync { display: none; }.gen-task-filters { gap: 14px; padding: 15px 13px; }@@ -209,7 +202,7 @@.gen-search { width: 100%; min-height: 40px; }.gen-reset-filters { padding-inline: 4px; font-size: 10px; }.gen-list-heading { display: none; }- .gen-task-row { grid-template-columns: 72px minmax(0, 1fr) 34px; gap: 9px 12px; padding: 17px 14px; border-top: 1px solid #f0e5f7; border-bottom: 0; }+ .gen-task-row { grid-template-columns: 72px minmax(0, 1fr) 34px; gap: 9px 12px; padding: 17px 14px; border-top: 1px solid var(--gen-line); border-bottom: 0; }.gen-task-cover { grid-column: 1; grid-row: 1 / 3; width: 72px; height: 62px; }.gen-task-description { grid-column: 2 / 4; grid-row: 1; }.gen-task-title { font-size: 12px; -webkit-line-clamp: 2; }@@ -256,12 +249,14 @@.gen-control small { font-size: 9px; }.gen-control strong { font-size: 11px; }.gen-submit-group { width: 100%; margin: 5px 0 0; }+ .gen-submit-group:has(.gen-estimate) { flex-wrap: wrap; gap: 10px; }+ .gen-estimate { flex: 1 0 100%; max-width: none; align-items: flex-start; text-align: left; }.gen-submit-group > span { display: none; }.gen-submit-group .gen-primary { width: 100%; min-height: 42px; }.gen-notice { flex-wrap: wrap; font-size: 11px; padding: 11px; }.gen-gallery { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 15px; gap: 13px; }.gen-recent > header { padding: 16px; }.gen-recent h2 { font-size: 12px; }- .gen-gallery-caption p { font-size: 10px; }+ .gen-gallery-caption p, .gen-gallery-title { font-size: 10px; }}@media (prefers-reduced-motion: reduce) { .gen-layout *, .gen-floating { animation: none !important; transition: none !important; } }diff --git a/frontend/tests/generation-task-history.test.mjs b/frontend/tests/generation-task-history.test.mjsnew file mode 100644index 0000000..9342877--- /dev/null+++ b/frontend/tests/generation-task-history.test.mjs@@ -0,0 +1,56 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { generationRecordKey, generationDetailPath, generationBillingState } from '../src/lib/generationTaskHistory.ts'+import { toolRunDetailAsset } from '../src/lib/toolRunDetails.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('同数字 ID 的任务和旧工具记录使用独立标识及详情地址', () => {+ const task = { ...record, source: 'task' }+ assert.equal(generationRecordKey(task), 'task:42')+ assert.equal(generationRecordKey(record), 'tool:42')+ assert.equal(generationDetailPath(task), '/api/tasks/generations/42')+ assert.equal(generationDetailPath(record), '/api/tools/runs/42')+})++test('文字生成详情保留完整脚本,且不能把结果地址当图片预览', () => {+ const content = '镜头一\n完整生成脚本'.repeat(100)+ const asset = toolRunDetailAsset({ ...record, kind: 'text', text_content: content, urls: ['/static/result.txt'] })+ assert.equal(asset.type, 'text')+ assert.equal(asset.url, null)+ assert.equal(asset.params.textContent, content)+})++test('尚未产出媒体的任务详情显示可读状态或错误', () => {+ const queued = toolRunDetailAsset({ ...record, kind: 'video', status: 'queued', preview_url: '/static/frame.png' })+ assert.equal(queued.type, 'text')+ assert.equal(queued.url, null)+ assert.match(queued.params.textContent, /排队/)+ const failed = toolRunDetailAsset({ ...record, kind: 'audio', status: 'failed', error: '模型暂不可用' })+ assert.equal(failed.params.textContent, '模型暂不可用')+})++test('成功媒体仍按所选结果预览,视频首帧不能作为成片地址', () => {+ const asset = toolRunDetailAsset({ ...record, kind: 'video', urls: ['/static/a.mp4', '/static/b.mp4'], preview_url: '/static/frame.png' }, 1)+ assert.equal(asset.type, 'video')+ assert.equal(asset.url, '/static/b.mp4')+ assert.equal(asset.cover, '/static/frame.png')+})++test('结算状态不根据完成时间推断,隐藏费用不能显示成免费', () => {+ assert.equal(generationBillingState({ ...record, billing_status: 'pending', finished_at: record.created_at }), 'pending')+ assert.equal(generationBillingState({ ...record, billing_charged_fen: null }), 'hidden')+ assert.equal(generationBillingState({ ...record, status: 'failed', billing_charged_fen: 0 }), 'not_charged')+ assert.equal(generationBillingState({ ...record, billing_charged_fen: 500 }), 'settled')+})++test('统一任务列表和详情继承当前团队范围,切回个人时清除', () => {+ try {+ setWorkspaceTeam(12)+ assert.equal(new Headers(scopedRequestInit('/api/tasks/generations?page=1').headers).get('X-Team-Id'), '12')+ assert.equal(new Headers(scopedRequestInit(generationDetailPath({ ...record, source: 'task' })).headers).get('X-Team-Id'), '12')+ setWorkspaceTeam(null)+ assert.equal(new Headers(scopedRequestInit('/api/tasks/generations').headers).get('X-Team-Id'), null)+ } finally { setWorkspaceTeam(null) }+})