Skip to content

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

fix(tasks): 按实际提交快照展示生成参数

yi326c0c833843
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index a0e9313..d5d2aff 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -188,11 +188,12 @@ def write_fragment_video_output_meta(
video_path: Path | str | None = None,
) -> None:
from app.services import storage as storage_svc
- from app.services.ffmpeg_compose import probe_video_dimensions
+ from app.services.ffmpeg_compose import probe_duration, probe_video_dimensions
params = dict(fragment.params or {}) if isinstance(fragment.params, dict) else {}
width = 0
height = 0
+ duration = None
path = video_path if isinstance(video_path, Path) else None
if path is None and isinstance(video_path, str) and video_path.strip():
path = storage_svc.local_path_from_url(video_path.strip())
@@ -204,6 +205,7 @@ def write_fragment_video_output_meta(
dims = probe_video_dimensions(path)
if dims:
width, height = dims
+ duration = probe_duration(path)
ratio_label = (
infer_aspect_ratio_from_pixels(width, height)
if width > 0 and height > 0
@@ -211,15 +213,25 @@ def write_fragment_video_output_meta(
)
params["aspect_ratio"] = ratio_label
params["resolution"] = resolution
+ params.pop("video_width", None)
+ params.pop("video_height", None)
if width > 0 and height > 0:
params["video_width"] = width
params["video_height"] = height
+ params.pop("video_duration_sec", None)
+ if duration is not None and duration > 0:
+ params["video_duration_sec"] = duration
gen = dict(params.get("generation") or {}) if isinstance(params.get("generation"), dict) else {}
gen["aspect_ratio"] = ratio_label
gen["resolution"] = resolution
+ gen.pop("video_width", None)
+ gen.pop("video_height", None)
if width > 0 and height > 0:
gen["video_width"] = width
gen["video_height"] = height
+ gen.pop("video_duration_sec", None)
+ if duration is not None and duration > 0:
+ gen["video_duration_sec"] = duration
params["generation"] = gen
fragment.params = params
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 18490cb..9828697 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -1187,6 +1187,7 @@ async def run_episode_fragment_plan_job(
# 任务平台(NIO):Worker 短生命周期 — prepare → submit → 注册 awaiting_poll,由 Selector 轮询。
async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
+ from app.services.tasks.generation_metadata import prepared_generation_params
from app.services.tasks.service import append_task_event, get_task_for_runtime, set_task_step_state
payload = task.payload if isinstance(task.payload, dict) else {}
@@ -1287,6 +1288,7 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
next_payload["generation_attempts"] = attempts
next_payload["attempt_limit"] = max_attempts
next_payload["prepared"] = serialize_fragment_video_prepared(prepared)
+ next_payload["generation_params"] = prepared_generation_params(next_payload["prepared"])
task_row.status = "pending"
task_row.progress_percent = 25
task_row.current_step_status = "prepared"
@@ -1330,6 +1332,8 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
frag.params = params
task_row.progress_percent = max(int(task_row.progress_percent or 0), 30)
task_row.current_step_status = "submitting"
+ generation_params = prepared_generation_params(serialize_fragment_video_prepared(prepared))
+ task_row.payload = {**payload, "generation_params": generation_params}
await db.commit()
provider_task_id = await submit_prepared_fragment_video(prepared, project_id=project.id)
@@ -1355,6 +1359,7 @@ async def submit_fragment_video_task(task: TaskRun) -> dict[str, Any]:
task_row.lease_until = None
next_payload = dict(payload)
next_payload.pop("prepared", None)
+ next_payload["generation_params"] = generation_params
next_payload["nio_phase"] = "poll"
next_payload["generation_attempts"] = attempts
next_payload["attempt_limit"] = max_attempts
@@ -1454,6 +1459,16 @@ async def _recover_complete_fragment_video(
"ok": True, "fragment_id": int(fragment_id), "kind": "video",
"urls": [fragment.video] if fragment and fragment.video else [],
}
+ if fragment:
+ # Freeze metadata with this output; later fragment edits cannot rewrite task history.
+ params = fragment.params if isinstance(fragment.params, dict) else {}
+ generation = params.get("generation") if isinstance(params.get("generation"), dict) else {}
+ if generation.get("video") == fragment.video:
+ result_payload["media_info"] = {
+ field: generation[key] for field, key in (
+ ("duration_sec", "video_duration_sec"), ("width", "video_width"), ("height", "video_height"))
+ if isinstance(generation.get(key), (int, float)) and generation[key] > 0
+ }
if recovered:
result_payload["recovered"] = True
await _complete_task(db, locked, result_payload)
diff --git a/backend/app/services/tasks/generation_history.py b/backend/app/services/tasks/generation_history.py
index c20dc77..40eed30 100644
--- a/backend/app/services/tasks/generation_history.py
+++ b/backend/app/services/tasks/generation_history.py
@@ -17,33 +17,22 @@ 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.models_tasks import TaskEvent, TaskRun
from app.schemas_generation_history import GenerationListOut, GenerationRecordOut
+from app.services.tasks.generation_metadata import (
+ merge_generation_params, planned_generation_params, prepared_generation_params,
+ public_generation_params, request_matches_generation, submitted_generation_params,
+)
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": "合成短视频", "tool_image": "生成图片", "tool_video": "生成视频", "tool_audio": "生成音频",
-}
-_PIPELINE_LABELS = {"script": "生成短视频剧本", "storyboard": "规划短视频分镜", "assets": "生成分镜图片",
- "videos": "生成分镜视频", "audio": "生成短视频配音", "compose": "合成短视频", "produce": "生成短视频"}
def _public_status(status: str) -> str:
@@ -114,8 +103,7 @@ def _safe_url(value) -> str | 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}
+ return public_generation_params(data)
def _result_urls(result, kind: str) -> list[str]:
@@ -150,7 +138,8 @@ def _text_output(result) -> str:
def project_generation(task, *, viewer_id: int, owner_user_id: int | None = None,
- linked_tool: ToolRun | None = None, fallback: dict | None = None) -> GenerationRecordOut:
+ linked_tool: ToolRun | None = None, fallback: dict | None = None,
+ submitted_params: 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 {}
@@ -166,14 +155,22 @@ def project_generation(task, *, viewer_id: int, owner_user_id: int | None = None
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)}
+ payload = task.payload if isinstance(task.payload, dict) else {}
+ params = merge_generation_params(
+ linked_tool.params if linked_tool is not None else {}, payload,
+ planned_generation_params(task, kind), prepared_generation_params(payload.get("prepared")),
+ payload.get("generation_params"), submitted_params,
+ )
+ media = result.get("media_info")
+ if isinstance(media, dict):
+ for field, key in (("duration_sec", "media_duration_sec"), ("width", "media_width"), ("height", "media_height")):
+ value = media.get(field)
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and 0 < value < 1_000_000:
+ params[key] = value
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(
@@ -307,6 +304,43 @@ async def _legacy_entity_outputs(db, tasks) -> dict[int, dict]:
return outputs
+async def _submitted_parameters(db, tasks) -> dict[int, dict]:
+ """Recover only accepted matching requests, never current editable project/fragment fields."""
+ candidates = {task.id: task for task in tasks
+ if _generation_kind(task) in {"image", "video"} and task.task_type != "project_pipeline"}
+ if not candidates:
+ return {}
+ payload = TaskEvent.payload
+ rows = (await db.execute(select(
+ TaskEvent.task_id, payload["provider_task_id"].as_string(),
+ payload["is_video_submit"].as_boolean(), payload["endpoint"].as_string(),
+ payload["request"]["body"], TaskEvent.event_type, payload["provider"].as_string(),
+ payload["simulated"].as_boolean(), payload["operation"].as_string(),
+ payload["request_stage"].as_string(), payload["request_id"].as_string(),
+ ).where(TaskEvent.task_id.in_(candidates), TaskEvent.event_type.in_(
+ ("upstream.request.accepted", "upstream.request.simulated")),
+ payload["method"].as_string() == "POST").order_by(TaskEvent.id.desc()))).all()
+ recovered = {}
+ for task_id, provider_id, is_video, endpoint, body, event_type, provider, simulated, operation, stage, request_id in rows:
+ if task_id in recovered:
+ continue
+ task = candidates[task_id]
+ kind = _generation_kind(task)
+ if event_type == "upstream.request.simulated":
+ if (provider != "local-mock" or simulated is not True or stage != "http_ready"
+ or operation != f"{kind}.generate"):
+ continue
+ if kind == "video":
+ provider_id = f"local-media-{request_id}" if request_id else None
+ is_video = True
+ if not request_matches_generation(_generation_kind(task), endpoint, is_video_submit=is_video):
+ continue
+ if _generation_kind(task) == "video" and task.provider_task_id and provider_id != task.provider_task_id:
+ continue
+ recovered[task_id] = submitted_generation_params(body)
+ return recovered
+
+
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"]
@@ -319,8 +353,10 @@ async def _load_records(db, user, references, owner_user_id):
for task_id, tool in linked:
linked_by_task.setdefault(task_id, tool)
fallback = await _legacy_entity_outputs(db, tasks)
+ submitted = await _submitted_parameters(db, tasks)
records = {f"task:{task.id}": project_generation(task, viewer_id=user.id, owner_user_id=owner_user_id,
- linked_tool=linked_by_task.get(task.id), fallback=fallback.get(task.id)) for task in tasks}
+ linked_tool=linked_by_task.get(task.id), fallback=fallback.get(task.id),
+ submitted_params=submitted.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]
diff --git a/backend/app/services/tasks/generation_metadata.py b/backend/app/services/tasks/generation_metadata.py
new file mode 100644
index 0000000..5ff9410
--- /dev/null
+++ b/backend/app/services/tasks/generation_metadata.py
@@ -0,0 +1,94 @@
+"""Credential-free generation parameters captured from immutable task evidence."""
+
+from __future__ import annotations
+
+import math
+from urllib.parse import urlsplit
+
+PUBLIC_PARAMETERS = frozenset({
+ "prompt", "negative", "negative_prompt", "model_id", "model", "ratio", "aspect_ratio", "resolution",
+ "duration", "duration_sec", "seconds", "voice", "voice_id", "phase", "video_mode", "mode", "strength",
+ "motion", "pack", "image_style_id", "episode_number", "generate_audio", "seed", "size", "count", "n",
+ "watermark", "camera_fixed", "speaker",
+})
+
+
+def public_generation_params(data) -> dict:
+ """Copy bounded public primitives, then normalize provider aliases without exposing references."""
+ params = {key: value for key, value in (data.items() if isinstance(data, dict) else [])
+ if key in PUBLIC_PARAMETERS and isinstance(value, (str, int, float, bool))
+ and len(str(value)) <= 7000 and (not isinstance(value, float) or math.isfinite(value))}
+ for canonical, aliases in (("model_id", ("model_id", "model")),
+ ("aspect_ratio", ("aspect_ratio", "ratio")),
+ ("duration", ("duration", "duration_sec", "seconds")),
+ ("count", ("count", "n")),
+ ("negative", ("negative", "negative_prompt"))):
+ value = next((params[key] for key in aliases if params.get(key) not in (None, "")), None)
+ if value is not None:
+ params[canonical] = value
+ return params
+
+
+def submitted_generation_params(body) -> dict:
+ """Project actual OpenAI/Seedance request bodies, including text-only content slots."""
+ metadata = body.get("metadata") if isinstance(body, dict) else None
+ dimensions = {key: metadata[key] for key in (
+ "duration", "resolution", "ratio", "aspect_ratio", "generate_audio", "seed", "watermark", "return_last_frame",
+ "camera_fixed", "speaker",
+ ) if isinstance(metadata, dict) and key in metadata}
+ params = merge_generation_params(dimensions, body)
+ if isinstance(body, dict) and not params.get("prompt") and isinstance(body.get("content"), list):
+ text = "\n\n".join(item["text"] for item in body["content"]
+ if isinstance(item, dict) and item.get("type") == "text"
+ and isinstance(item.get("text"), str))
+ if text:
+ params["prompt"] = text[:7000]
+ if isinstance(body, dict) and not params.get("prompt") and isinstance(body.get("input"), str):
+ params["prompt"] = body["input"][:7000]
+ return params
+
+
+def merge_generation_params(*sources) -> dict:
+ """Merge oldest to newest evidence while keeping public aliases consistent."""
+ params = {}
+ for source in sources:
+ params.update(public_generation_params(source))
+ for canonical, aliases in (("model_id", ("model",)), ("aspect_ratio", ("ratio",)),
+ ("duration", ("duration_sec", "seconds")), ("count", ("n",))):
+ if canonical in params:
+ for alias in aliases:
+ if alias in params:
+ params[alias] = params[canonical]
+ return params
+
+
+def prepared_generation_params(prepared) -> dict:
+ """Retain final preparation parameters after the private request context is discarded."""
+ if not isinstance(prepared, dict):
+ return {}
+ return merge_generation_params(prepared, submitted_generation_params(prepared.get("seedance_body")))
+
+
+def planned_generation_params(task, kind: str) -> dict:
+ """Use only a single matching operation; composite tasks have no one global parameter set."""
+ snapshot = getattr(task, "billing_snapshot", None)
+ items = snapshot.get("items", []) if isinstance(snapshot, dict) else []
+ operations = [item for item in (items if isinstance(items, list) else [])
+ if isinstance(item, dict) and item.get("capability") == kind]
+ if len(operations) != 1:
+ return {}
+ operation = operations[0]
+ return merge_generation_params(operation.get("params"), {"model_id": operation.get("model_id")})
+
+
+def request_matches_generation(kind: str, endpoint, *, is_video_submit=False) -> bool:
+ """Ignore helper images and text calls when recovering a media task's submitted parameters."""
+ if kind == "video":
+ return bool(is_video_submit)
+ if kind != "image" or not isinstance(endpoint, str):
+ return False
+ try:
+ path = urlsplit(endpoint).path.rstrip("/")
+ except ValueError:
+ return False
+ return path.endswith(("/images/generations", "/images/edits", "/responses"))
diff --git a/backend/tests/test_generation_history.py b/backend/tests/test_generation_history.py
index 9df4b75..1642883 100644
--- a/backend/tests/test_generation_history.py
+++ b/backend/tests/test_generation_history.py
@@ -12,7 +12,7 @@ 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_tasks import TaskEvent, TaskRun
from app.models_teams import Team, TeamMember
from app.services.tasks.generation_history import project_generation
@@ -127,7 +127,7 @@ async def test_provider_id_links_require_matching_tool_domain_and_media_kind(his
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"] == "生成任务"
+ assert tasks[api.id]["prompt"] == ""
@pytest.mark.asyncio
@@ -241,7 +241,7 @@ def test_projection_accepts_only_outputs_and_safe_parameters():
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.params == {"prompt": "a tree", "ratio": "1:1", "aspect_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"}
@@ -261,6 +261,117 @@ def test_text_and_step_projections_exclude_upstream_traces():
assert result.urls == ["https://output.test/result.mp4"] and result.text_content == ""
+async def test_history_restores_actual_submission_without_other_attempts_or_helper_images(history):
+ """Current accepted video parameters override requested/planned data, without leaking traces."""
+ sessions, (user, _, _), _team = history
+ async with sessions() as db:
+ row = TaskRun(domain="drama", task_type="fragment_video", queue_type="video", status="succeeded",
+ requested_by=user.id, provider_task_id="final-video",
+ payload={"model_id": "requested", "duration_sec": 12, "ratio": "9:16"},
+ billing_snapshot={"items": [{"capability": "video", "model_id": "planned",
+ "params": {"duration": 10, "aspect_ratio": "9:16"}}]},
+ result_payload={"urls": ["https://output.test/video.mp4"],
+ "media_info": {"duration_sec": 8.04, "width": 854, "height": 480}})
+ db.add(row)
+ await db.flush()
+ actual = {"model": "MiniMax-H3", "seconds": "6", "ratio": "16:9", "resolution": "480p",
+ "generate_audio": False, "content": [{"type": "text", "text": "Final submitted scene"},
+ {"type": "image_url", "image_url": {"url": "https://private.test/reference.png"}}], "api_key": "private"}
+ for event_type, provider_id, is_video, body in (
+ ("upstream.request.accepted", "final-video", True, actual),
+ ("upstream.request.accepted", None, False, {"model": "helper-image", "prompt": "Helper still"}),
+ ("upstream.request.failed", "final-video", True, {"model": "failed", "prompt": "Failed retry"}),
+ ("upstream.request.accepted", "other-video", True, {"model": "other", "prompt": "Other attempt"}),
+ ):
+ db.add(TaskEvent(task_id=row.id, event_type=event_type, payload={
+ "method": "POST", "endpoint": "https://gateway.test/v1/videos" if is_video else "https://gateway.test/v1/images/generations",
+ "is_video_submit": is_video, "provider_task_id": provider_id,
+ "request": {"body": body, "headers": {"Authorization": "private-header"}},
+ }))
+ await db.commit()
+ async with await client_for(sessions, user) as client:
+ response = await client.get(f"/api/tasks/generations/{row.id}")
+ assert response.status_code == 200
+ record = response.json()
+ assert record["prompt"] == "Final submitted scene"
+ assert record["params"]["model_id"] == "MiniMax-H3"
+ assert record["params"]["duration"] == record["params"]["duration_sec"] == "6"
+ assert record["params"]["ratio"] == record["params"]["aspect_ratio"] == "16:9"
+ assert record["params"]["generate_audio"] is False
+ assert record["params"]["media_duration_sec"] == 8.04
+ assert record["params"]["media_width"] == 854 and record["params"]["media_height"] == 480
+ assert "private" not in response.text and "Helper still" not in response.text
+ async with sessions() as db:
+ persisted = await db.get(TaskRun, row.id)
+ assert persisted.payload == {"model_id": "requested", "duration_sec": 12, "ratio": "9:16"}
+
+
+def test_history_uses_prepared_snapshot_and_leaves_unknown_prompt_empty():
+ """Helper operations cannot supply video parameters; missing historical prompts stay unknown."""
+ row = SimpleNamespace(id=1, task_type="fragment_video", domain="drama", queue_type="video", status="running",
+ payload={"generation_params": {"prompt": "Frozen scene", "model_id": "actual", "duration": 6}},
+ billing_snapshot={"items": [{"capability": "video", "model_id": "planned", "params": {"duration": 8}},
+ {"capability": "image", "model_id": "helper", "params": {"prompt": "Helper"}}]},
+ result_payload={}, steps=[], team_id=None, requested_by=1)
+ output = project_generation(row, viewer_id=1)
+ assert output.prompt == "Frozen scene" and output.params["model_id"] == "actual"
+ assert output.params["duration"] == 6
+ row.payload = {}
+ assert project_generation(row, viewer_id=1).prompt == ""
+
+
+async def test_history_restores_matching_local_simulated_http_parameters(history):
+ """本地模拟同样保留最终参数,但必须匹配实际产出 request_id,不串入后续请求。"""
+ sessions, (user, _, _), _team = history
+ async with sessions() as db:
+ row = TaskRun(domain="drama", task_type="fragment_video", queue_type="video", status="succeeded",
+ requested_by=user.id, provider_task_id="local-media-matching", payload={})
+ db.add(row)
+ await db.flush()
+ for request_id, overrides in (("matching", {}), ("later", {}), ("matching", {"provider": "untrusted"}),
+ ("matching", {"request_stage": "business_input"})):
+ db.add(TaskEvent(task_id=row.id, event_type="upstream.request.simulated", payload={
+ "method": "POST", "endpoint": "https://gateway.test/v1/videos", "provider": "local-mock",
+ "simulated": True, "operation": "video.generate", "request_stage": "http_ready",
+ "request_id": request_id,
+ "request": {"body": {"model": "MiniMax-H3", "prompt": f"Prompt {request_id}", "seconds": "12",
+ "metadata": {"ratio": "9:16", "resolution": "480p", "generate_audio": True,
+ "duration": 12, "api_key": "private", "prompt": "Nested unrelated prompt"}}},
+ **overrides,
+ }))
+ await db.commit()
+ async with await client_for(sessions, user) as client:
+ response = await client.get(f"/api/tasks/generations/{row.id}")
+ assert response.status_code == 200
+ record = response.json()
+ assert record["prompt"] == "Prompt matching"
+ assert record["params"]["duration"] == "12" and record["params"]["resolution"] == "480p"
+ assert record["params"]["aspect_ratio"] == "9:16" and record["params"]["generate_audio"] is True
+ assert "Nested unrelated" not in response.text and "private" not in response.text
+
+
+async def test_image_history_restores_the_final_responses_input(history):
+ """TokenFree /responses 生图实际文案在 input,画幅等计费规格来自本次固定快照。"""
+ sessions, (user, _, _), _team = history
+ async with sessions() as db:
+ row = task(user, billing_snapshot={"items": [{"capability": "image", "model_id": "gpt-image-2",
+ "params": {"aspect_ratio": "3:4", "resolution": "2K"}}]})
+ db.add(row)
+ await db.flush()
+ db.add(TaskEvent(task_id=row.id, event_type="upstream.request.accepted", payload={
+ "method": "POST", "endpoint": "https://gateway.test/v1/responses",
+ "request": {"body": {"model": "gpt-image-2", "input": "Character sheet. Final canvas must be 3:4."}},
+ }))
+ await db.commit()
+ async with await client_for(sessions, user) as client:
+ record = (await client.get(f"/api/tasks/generations/{row.id}")).json()
+ assert record["prompt"] == "Character sheet. Final canvas must be 3:4."
+ assert record["params"]["model_id"] == "gpt-image-2" and record["params"]["aspect_ratio"] == "3:4"
+
+
@pytest.mark.asyncio
async def test_postgres_union_and_json_task_links(db_session):
"""Exercise PostgreSQL JSON text extraction, correlation and union pagination."""
diff --git a/backend/tests/test_generation_parameter_snapshot.py b/backend/tests/test_generation_parameter_snapshot.py
new file mode 100644
index 0000000..64ff844
--- /dev/null
+++ b/backend/tests/test_generation_parameter_snapshot.py
@@ -0,0 +1,112 @@
+"""分镜参数与成片元数据快照:离线执行,不发生成请求。"""
+
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+from app.models import User
+from app.models_drama import DramaEpisode, DramaEpisodeFragment
+from app.models_tasks import TaskRun
+from app.services.drama.generation import FragmentVideoPrepared, write_fragment_video_output_meta
+from app.services.tasks.generation_metadata import merge_generation_params, submitted_generation_params
+
+
+def test_public_submission_parameters_preserve_false_zero_and_image_count_alias():
+ """已知公开开关、音色及图片张数留痕,不能因 false/0 被当成缺失而丢掉。"""
+ submitted = submitted_generation_params({
+ "model": "image-model", "n": 0, "seed": 0, "speaker": "voice-a",
+ "metadata": {"watermark": False, "camera_fixed": False, "generate_audio": False, "api_key": "private"},
+ })
+ params = merge_generation_params({"count": 3, "watermark": True, "camera_fixed": True}, submitted)
+ assert params["count"] == params["n"] == 0 and params["seed"] == 0
+ assert params["watermark"] is False and params["camera_fixed"] is False
+ assert params["generate_audio"] is False and params["speaker"] == "voice-a"
+ assert "private" not in str(params)
+
+
+async def test_fragment_submission_keeps_parameters_after_discarding_prepared_context(monkeypatch):
+ """NIO prepare→submit 丢弃私有素材上下文后,真实提示词和规格仍持久化。"""
+ from app.services.drama import jobs
+ from app.services.tasks import service
+
+ task = TaskRun(id=5, requested_by=1, fragment_id=9, episode_id=3, payload={}, steps=[], progress_percent=0)
+ project = SimpleNamespace(id=2)
+ episode = SimpleNamespace(id=3, project=project)
+ fragment = SimpleNamespace(id=9, episode_id=3, params={})
+
+ async def get_entity(model, _id, **_kwargs):
+ """只提供执行器所需的已授权目标,不访问数据库。"""
+ return {DramaEpisode: episode, DramaEpisodeFragment: fragment, User: SimpleNamespace(id=1)}[model]
+
+ db = SimpleNamespace(get=get_entity, commit=AsyncMock())
+
+ @asynccontextmanager
+ async def session():
+ """借用同一假的任务事务观察两次短生命周期执行。"""
+ yield db
+
+ prepared = FragmentVideoPrepared(
+ submit_mode="seedance_body", prompt="Base draft", duration=8, ratio="9:16", resolution="720p",
+ model_id="planned", seedance_body={"model": "actual-model", "duration": 6, "ratio": "16:9",
+ "resolution": "480p", "generate_audio": False,
+ "content": [{"type": "text", "text": "Final generated prompt"},
+ {"type": "image_url", "image_url": {"url": "https://private.test/reference.png"}}]},
+ )
+ monkeypatch.setattr(jobs, "AsyncSessionLocal", session)
+ monkeypatch.setattr(jobs, "_is_episode_video_cancelled", lambda _: False)
+ monkeypatch.setattr(jobs, "prepare_fragment_video_for_submit", AsyncMock(return_value=prepared))
+ monkeypatch.setattr(jobs, "submit_prepared_fragment_video", AsyncMock(return_value="provider-5"))
+ monkeypatch.setattr(service, "get_task_for_runtime", AsyncMock(return_value=task))
+ monkeypatch.setattr(service, "append_task_event", AsyncMock())
+
+ assert (await jobs.submit_fragment_video_task(task))["nio_phase"] == "submit"
+ assert task.payload["generation_params"]["prompt"] == "Final generated prompt"
+ assert (await jobs.submit_fragment_video_task(task))["provider_task_id"] == "provider-5"
+ assert "prepared" not in task.payload
+ snapshot = task.payload["generation_params"]
+ assert snapshot["model_id"] == "actual-model" and snapshot["duration"] == 6
+ assert snapshot["aspect_ratio"] == "16:9" and snapshot["generate_audio"] is False
+ assert "private.test" not in str(snapshot)
+
+
+def test_output_metadata_probes_media_duration_and_clears_previous_measurements(tmp_path, monkeypatch):
+ """成片时长来自 ffprobe;探测失败不沿用前一次视频的时长和像素。"""
+ video = tmp_path / "output.mp4"
+ video.write_bytes(b"mocked-video")
+ fragment = SimpleNamespace(params={"generation": {"status": "running"}})
+ monkeypatch.setattr("app.services.ffmpeg_compose.probe_video_dimensions", lambda _: (854, 480))
+ monkeypatch.setattr("app.services.ffmpeg_compose.probe_duration", lambda _: 8.04)
+ write_fragment_video_output_meta(fragment, aspect_ratio="9:16", resolution="480p", video_path=video)
+ assert fragment.params["video_duration_sec"] == 8.04
+ assert fragment.params["generation"]["video_width"] == 854
+
+ monkeypatch.setattr("app.services.ffmpeg_compose.probe_video_dimensions", lambda _: None)
+ monkeypatch.setattr("app.services.ffmpeg_compose.probe_duration", lambda _: None)
+ write_fragment_video_output_meta(fragment, aspect_ratio="9:16", resolution="720p", video_path=video)
+ assert "video_duration_sec" not in fragment.params
+ assert "video_width" not in fragment.params["generation"]
+
+
+async def test_task_completion_freezes_metadata_for_the_matching_output(monkeypatch):
+ """完成时复制本次视频的实测信息,历史详情不再依赖可变分镜。"""
+ from app.services.billing import settlement
+ from app.services.drama import jobs
+ from app.services.tasks import executor, service
+
+ task = TaskRun(id=42, status="awaiting_poll", payload={}, steps=[])
+ fragment = SimpleNamespace(video="https://output.test/current.mp4", params={"generation": {
+ "video": "https://output.test/current.mp4", "video_duration_sec": 8.04, "video_width": 854, "video_height": 480}})
+ db = SimpleNamespace(get=AsyncMock(return_value=fragment), refresh=AsyncMock())
+ complete = AsyncMock()
+ monkeypatch.setattr(settlement, "_lock_task", AsyncMock(return_value=task))
+ monkeypatch.setattr(executor, "_complete_task", complete)
+ monkeypatch.setattr(service, "activate_next_sequential_task", AsyncMock())
+ assert await jobs._recover_complete_fragment_video(db, 42, fragment_id=9, batch_key=None, batch_index=0)
+ result = complete.await_args.args[2]
+ assert result["media_info"] == {"duration_sec": 8.04, "width": 854, "height": 480}
+ fragment.params["generation"]["video_duration_sec"] = 20
+ assert result["media_info"]["duration_sec"] == 8.04
+
+ fragment.params["generation"]["video"] = "https://output.test/previous.mp4"
+ await jobs._recover_complete_fragment_video(db, 42, fragment_id=9, batch_key=None, batch_index=0)
+ assert "media_info" not in complete.await_args.args[2]
diff --git a/frontend/src/api/tools.ts b/frontend/src/api/tools.ts
index e7b3b8c..968879b 100644
--- a/frontend/src/api/tools.ts
+++ b/frontend/src/api/tools.ts
@@ -50,7 +50,7 @@ export type ToolRunRecord = {
preview_url?: string | null
urls: string[]
task_id?: string | null
- params?: Record<string, string> | null
+ params?: Record<string, unknown> | null
error?: string | null
created_at: string
platform_task_id?: number | null
diff --git a/frontend/src/components/assets/AssetDetailDialog.tsx b/frontend/src/components/assets/AssetDetailDialog.tsx
index 8ec1d91..cec2064 100644
--- a/frontend/src/components/assets/AssetDetailDialog.tsx
+++ b/frontend/src/components/assets/AssetDetailDialog.tsx
@@ -3,7 +3,8 @@ import { useEffect, useState, type ReactNode } from 'react'
import Modal from '../ui/Modal'
import { Copy, Download, Maximize2, Minimize2, X } from 'lucide-react'
import { resolveDramaMediaUrl } from '../../api/drama'
-import { assetDetailInfo, type AssetDetailRecord } from '../../lib/assetDetails'
+import { assetDetailInfo, formatMediaDuration, type AssetDetailRecord } from '../../lib/assetDetails'
+import { formatDateTime } from '../../i18n'
import { canvasMediaFilename, downloadCanvasMedia, downloadCanvasText, isPlayableVideoUrl } from '../../lib/canvasNodeMedia'
import { AssetVisual } from './AssetLibrary'
import './asset-detail.css'
@@ -36,6 +37,7 @@ export function AssetDetailDialog({ asset, open = true, onClose, actions, childr
const [feedback, setFeedback] = useState('')
const [downloading, setDownloading] = useState(false)
const [dimensions, setDimensions] = useState('')
+ const [mediaDuration, setMediaDuration] = useState('')
const info = assetDetailInfo(asset)
const title = asset.name || info.filename || '资产详情'
const url = resolveDramaMediaUrl(asset.url || asset.cover)
@@ -46,7 +48,7 @@ export function AssetDetailDialog({ asset, open = true, onClose, actions, childr
const labels: Record<string, string> = { character: '角色', scene: '场景', prop: '道具', voice: '音色', image: '图片', video: '视频', audio: '音频', text: '文本' }
useEffect(() => {
- if (open) { setZoomed(false); setFeedback(''); setDimensions('') }
+ if (open) { setZoomed(false); setFeedback(''); setDimensions(''); setMediaDuration('') }
}, [open, asset.id, asset.url])
/** 复制完整提示词,折叠展示不会截断复制内容。 */
@@ -71,8 +73,8 @@ export function AssetDetailDialog({ asset, open = true, onClose, actions, childr
return <Modal open={open} onClose={onClose} size="xl" className="pf-asset-detail-shell">
<div className={`pf-asset-detail-dialog${zoomed ? ' is-zoomed' : ''}`}>
<section className={`pf-asset-detail-media is-${kind}`} aria-label="媒体预览">
- {kind === 'video' && url ? <video key={url} src={url} poster={resolveDramaMediaUrl(asset.cover)} controls playsInline preload="metadata" onLoadedMetadata={(event) => { const media = event.currentTarget; setDimensions(`${media.videoWidth} × ${media.videoHeight}`) }} />
- : kind === 'audio' ? <div className="pf-asset-detail-audio"><AssetVisual asset={asset} />{url && <audio key={url} src={url} controls preload="metadata" />}</div>
+ {kind === 'video' && url ? <video key={url} src={url} poster={resolveDramaMediaUrl(asset.cover)} controls playsInline preload="metadata" onLoadedMetadata={(event) => { const media = event.currentTarget; setDimensions(media.videoWidth > 0 && media.videoHeight > 0 ? `${media.videoWidth} × ${media.videoHeight}` : ''); setMediaDuration(formatMediaDuration(media.duration)) }} />
+ : kind === 'audio' ? <div className="pf-asset-detail-audio"><AssetVisual asset={asset} />{url && <audio key={url} src={url} controls preload="metadata" onLoadedMetadata={(event) => setMediaDuration(formatMediaDuration(event.currentTarget.duration))} />}</div>
: kind === 'text' ? <pre>{text || '暂无文本'}</pre>
: url ? <img key={url} src={url} alt={title} onLoad={(event) => { const media = event.currentTarget; setDimensions(`${media.naturalWidth} × ${media.naturalHeight}`) }} />
: <AssetVisual asset={asset} />}
@@ -92,8 +94,9 @@ export function AssetDetailDialog({ asset, open = true, onClose, actions, childr
<dt>来源</dt><dd>{info.source}</dd>
{info.source !== '上传' && <><dt>模型</dt><dd title={info.model}>{info.model || '未记录'}</dd></>}
{dimensions && <><dt>媒体尺寸</dt><dd>{dimensions}</dd></>}
+ {(mediaDuration || info.mediaDuration) && <><dt>{kind === 'audio' ? '音频时长' : '成片时长'}</dt><dd>{mediaDuration || info.mediaDuration}</dd></>}
{info.fileSize !== null && <><dt>文件大小</dt><dd>{info.fileSize >= 1048576 ? `${(info.fileSize / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(info.fileSize / 1024))} KB`}</dd></>}
- {info.createdAt && <><dt>记录时间</dt><dd title={info.createdAt}>{info.createdAt.replace('T', ' ').slice(0, 16)}</dd></>}
+ {info.createdAt && <><dt>记录时间</dt><dd title={info.createdAt}>{formatDateTime(info.createdAt)}</dd></>}
{asset.project_id && <><dt>来源项目</dt><dd>#{asset.project_id}</dd></>}
{info.parameters.map((item) => <div className="pf-asset-detail-meta-row" key={item.key}><dt>{item.label}</dt><dd title={item.value}>{item.value}</dd></div>)}
</dl>
diff --git a/frontend/src/lib/assetDetails.ts b/frontend/src/lib/assetDetails.ts
index c9f3ed9..02be739 100644
--- a/frontend/src/lib/assetDetails.ts
+++ b/frontend/src/lib/assetDetails.ts
@@ -1,3 +1,5 @@
+import { getImageStyleLabel } from './dramaImageStyles.ts'
+
/** 统一资产详情数据:成功媒体快照优先,上传素材不混入旧生成参数。 */
export type AssetDetailRecord = {
id?: number
@@ -22,6 +24,12 @@ function display(value: unknown): string {
return typeof value === 'string' || typeof value === 'number' ? String(value) : ''
}
+/** 成片时长最多保留两位小数,未知或无效值不伪造为零。 */
+export function formatMediaDuration(value: unknown): string {
+ const duration = typeof value === 'number' ? value : Number.NaN
+ return Number.isFinite(duration) && duration > 0 ? `${Number(duration.toFixed(2))} 秒` : ''
+}
+
/** 从当前媒体读取生成参数;新快照存在时绝不回退到旧模型。 */
export function assetDetailInfo(asset: AssetDetailRecord) {
const params = object(asset.params)
@@ -34,16 +42,26 @@ export function assetDetailInfo(asset: AssetDetailRecord) {
const source = uploaded ? '上传' : (hasSnapshot ? snapshot.source === 'generated' : Boolean(model)) ? 'AI 生成' : '未记录'
const prompt = display(hasSnapshot ? snapshot.prompt : params.visualPrompt || params.visualImage || params.voicePrompt || params.prompt || params.description)
const labels: Record<string, string> = {
- aspect_ratio: '比例', resolution: '分辨率', size: '尺寸', duration_sec: '时长', duration: '时长',
+ aspect_ratio: snapshot.parameter_source === 'request' ? '设定画幅' : '比例',
+ resolution: snapshot.parameter_source === 'request' ? '设定分辨率' : '分辨率',
+ size: snapshot.parameter_source === 'request' ? '设定尺寸' : '尺寸', duration_sec: '时长', duration: '时长',
+ requested_duration_sec: '设定时长', video_mode: '生成方式', count: '生成数量', negative: '负向提示词',
+ strength: '参考强度', motion: '运动幅度',
image_style_id: '画面风格', generate_audio: '生成声音', watermark: '水印', camera_fixed: '固定镜头',
seed: '随机种子', speaker: '音色', sample_text: '试听文本', sampleText: '试听文本',
}
const parameters = uploaded ? [] : Object.entries(labels).flatMap(([key, label]) => {
- const value = display(options[key])
- return value ? [{ key, label, value: key.startsWith('duration') ? `${value} 秒` : value }] : []
+ const modes: Record<string, string> = { text_to_video: '文生视频', first_last_frame: '首尾帧', omni_reference: '全能参考' }
+ const raw = options[key]
+ const value = key === 'video_mode' ? modes[display(raw)] || ''
+ : key === 'image_style_id' ? getImageStyleLabel(display(raw)) || display(raw)
+ : ['generate_audio', 'watermark', 'camera_fixed'].includes(key) && typeof raw === 'string' && /^(true|false)$/i.test(raw) ? display(raw.toLowerCase() === 'true')
+ : display(raw)
+ const duration = key.includes('duration') && (typeof raw === 'number' || typeof raw === 'string') ? formatMediaDuration(Number(String(raw).replace(/\s*s$/i, ''))) : ''
+ return value ? [{ key, label, value: key.includes('duration') ? duration : value }].filter((item) => item.value) : []
})
return {
- source, model, prompt, parameters,
+ source, model, prompt, parameters, mediaDuration: formatMediaDuration(options.media_duration_sec),
filename: display(snapshot.filename), fileSize: typeof snapshot.file_size === 'number' ? snapshot.file_size : null,
createdAt: display(snapshot.created_at || gen.finished_at || asset.updated_at),
}
diff --git a/frontend/src/lib/toolRunDetails.ts b/frontend/src/lib/toolRunDetails.ts
index f3cac8e..f149614 100644
--- a/frontend/src/lib/toolRunDetails.ts
+++ b/frontend/src/lib/toolRunDetails.ts
@@ -1,19 +1,31 @@
import type { ToolRunRecord } from '../api/tools.ts'
import type { AssetDetailRecord } from './assetDetails.ts'
+/** 只接收参数标量,忽略请求引用、对象和内部追踪信息。 */
+function scalar(value: unknown): string | number | boolean | undefined {
+ return typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value)) ? value : undefined
+}
+
+/** 时长允许旧记录的“8s”,但不得把空值或布尔值变成秒数。 */
+function seconds(value: unknown): number | undefined {
+ if (typeof value !== 'string' && typeof value !== 'number') return undefined
+ const parsed = Number(String(value).replace(/\s*s$/i, ''))
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined
+}
+
/** 将独立生成记录适配为全局资产详情,预览和下载始终使用所选正式结果。 */
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 duration = seconds(params.duration_sec ?? params.duration)
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}`,
+ name: labels[record.kind] || '生成记录',
type: record.kind === 'text' || !url ? 'text' : record.kind,
url,
// 视频首帧只作已有视频的 poster;尚无成片时不能把图片作为视频下载或播放。
@@ -24,15 +36,21 @@ export function toolRunDetailAsset(record: ToolRunRecord, resultIndex = 0): Asse
...((record.kind === 'text' || !url) ? { textContent } : {}),
media_metadata: {
source: 'generated',
- model_id: params.model_id || params.model,
+ model_id: scalar(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 } : {}),
- },
+ parameter_source: 'request',
+ parameters: Object.fromEntries(Object.entries({
+ aspect_ratio: scalar(params.aspect_ratio ?? params.ratio),
+ resolution: scalar(params.resolution), size: scalar(params.size),
+ ...(record.kind === 'video' && duration !== undefined ? { requested_duration_sec: duration } : {}),
+ media_duration_sec: seconds(params.media_duration_sec),
+ video_mode: scalar(params.video_mode), image_style_id: scalar(params.image_style_id),
+ generate_audio: scalar(params.generate_audio), watermark: scalar(params.watermark),
+ camera_fixed: scalar(params.camera_fixed), seed: scalar(params.seed), count: scalar(params.count),
+ negative: scalar(params.negative), strength: scalar(params.strength), motion: scalar(params.motion),
+ ...(record.kind === 'audio' ? { speaker: scalar(params.speaker ?? params.voice ?? params.voice_id) } : {}),
+ }).filter(([, value]) => value !== undefined && value !== '')),
},
},
}
diff --git a/frontend/src/pages/GenerationPage.tsx b/frontend/src/pages/GenerationPage.tsx
index a7bc36a..12d0d86 100644
--- a/frontend/src/pages/GenerationPage.tsx
+++ b/frontend/src/pages/GenerationPage.tsx
@@ -292,7 +292,6 @@ function GenerationWorkspace({ kind }: { kind: MediaKind }) {
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.task_id || detail.id}</dd></dl></section>
</AssetDetailDialog>}
</GenerationLayout>
}
diff --git a/frontend/src/pages/GenerationTasksPage.tsx b/frontend/src/pages/GenerationTasksPage.tsx
index 32d4400..49af6eb 100644
--- a/frontend/src/pages/GenerationTasksPage.tsx
+++ b/frontend/src/pages/GenerationTasksPage.tsx
@@ -49,7 +49,7 @@ function TaskHistoryContent() {
const { detail, asset: detailAsset, error: detailError, resultIndex, selectResult, openDetail, closeDetail } = useToolRunDetail()
const [downloading, setDownloading] = useState<string | null>(null)
const Icon = taskIcons[kind]
- const createPath = kind === 'all' ? '/tools' : kind === 'text' ? '/studio/new' : `/tools/${kind}`
+ const createPath = kind === 'all' ? '/' : 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'),
@@ -156,13 +156,14 @@ function TaskHistoryContent() {
const RowIcon = taskIcons[item.kind as TaskKind] || FileText
const recordKey = generationRecordKey(item)
const billingState = generationBillingState(item)
+ const ratio = typeof (item.params?.aspect_ratio ?? item.params?.ratio) === 'string' ? String(item.params?.aspect_ratio ?? item.params?.ratio) : ''
const formatLabel = item.kind === 'video' ? 'MP4' : item.kind === 'audio' ? 'MP3' : item.kind === 'text' ? text('文字', 'Text') : text('图片', 'Image')
return <article className={`gen-task-row ${item.status === 'failed' ? 'has-error' : ''}`} key={recordKey}>
<button className="gen-task-cover" type="button" onClick={() => openDetail(item)} aria-label={text('查看生成结果', 'View result')}>
{item.kind === 'image' && (item.preview_url || item.urls[0]) ? <img src={resolveToolMediaUrl(item.preview_url || item.urls[0])} alt="" /> : item.kind === 'video' && item.preview_url ? <img src={resolveToolMediaUrl(item.preview_url)} alt="" /> : item.kind === 'video' && item.urls[0] ? <video src={resolveToolMediaUrl(item.urls[0])} preload="metadata" muted /> : <RowIcon size={28} />}
<span className="gen-cover-overlay"><Eye size={18} /></span>
</button>
- <div className="gen-task-description"><button type="button" className="gen-task-title" onClick={() => openDetail(item)} title={item.prompt}>{item.prompt || 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-description"><button type="button" className="gen-task-title" onClick={() => openDetail(item)} title={item.prompt}>{item.prompt || text('生成任务', 'Generation task')}</button><div className="gen-task-metadata"><span className="gen-task-tag">{kindLabels[item.kind as TaskKind] || 'AI'}</span>{ratio && <span className="gen-task-tag">{ratio}</span>}</div>{item.error && <button type="button" className="gen-task-error" onClick={() => openDetail(item)} title={item.error}><AlertCircle size={12} /><span>{errorSummary(item.error)}</span><ArrowUpRight size={12} /></button>}</div>
<div className="gen-task-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>
@@ -181,7 +182,6 @@ function TaskHistoryContent() {
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/tests/asset-details.test.mjs b/frontend/tests/asset-details.test.mjs
index ceebf2e..0714710 100644
--- a/frontend/tests/asset-details.test.mjs
+++ b/frontend/tests/asset-details.test.mjs
@@ -1,6 +1,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
-import { assetDetailInfo } from '../src/lib/assetDetails.ts'
+import { assetDetailInfo, formatMediaDuration } from '../src/lib/assetDetails.ts'
test('上传媒体显示上传,隐藏残留的旧模型与生成参数', () => {
const value = assetDetailInfo({ type: 'character', params: { model_id: 'old', generation: { source: 'upload', resolution: '4K' } } })
@@ -21,3 +21,11 @@ test('未记录的来源和模型不伪造生成信息', () => {
assert.equal(value.source, '未记录')
assert.equal(value.model, '')
})
+
+test('媒体时长只接受正的有限实测值,旧时长字符串不重复拼单位', () => {
+ assert.equal(formatMediaDuration(8), '8 秒')
+ assert.equal(formatMediaDuration(8.125), '8.13 秒')
+ for (const value of [0, -1, Infinity, NaN, '8', true, null]) assert.equal(formatMediaDuration(value), '')
+ const info = assetDetailInfo({ type: 'video', params: { media_metadata: { source: 'generated', parameters: { duration_sec: '8s', generate_audio: 'false', seed: 0 } } } })
+ assert.deepEqual(info.parameters.map((item) => item.value), ['8 秒', '否', '0'])
+})
diff --git a/frontend/tests/generation-task-history.test.mjs b/frontend/tests/generation-task-history.test.mjs
index 9342877..cd62927 100644
--- a/frontend/tests/generation-task-history.test.mjs
+++ b/frontend/tests/generation-task-history.test.mjs
@@ -2,6 +2,7 @@ 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 { assetDetailInfo } from '../src/lib/assetDetails.ts'
import { scopedRequestInit, setWorkspaceTeam } from '../src/features/teams/workspaceScope.ts'
const record = { id: 42, tool_id: 'image', kind: 'image', status: 'succeeded', prompt: 'A portrait', urls: [], created_at: '2026-10-26T10:00:00Z' }
@@ -38,6 +39,41 @@ test('成功媒体仍按所选结果预览,视频首帧不能作为成片地
assert.equal(asset.cover, '/static/frame.png')
})
+test('详情不把内部任务编号写入标题,未记录提示词保持为空', () => {
+ const asset = toolRunDetailAsset({ ...record, kind: 'video', prompt: '', task_type: 'fragment_video', provider_task_id: 'private-provider-id' })
+ assert.equal(asset.name, '视频生成')
+ assert.equal(asset.params.media_metadata.prompt, '')
+ assert.doesNotMatch(JSON.stringify(asset.params), /fragment_video|private-provider-id/)
+})
+
+test('提交参数保留数值和布尔值,请求时长与成片时长分开', () => {
+ const asset = toolRunDetailAsset({ ...record, kind: 'video', urls: ['/static/movie.mp4'], params: {
+ model_id: 'actual-model', model: 'old-model', ratio: '1:1', aspect_ratio: '9:16', resolution: '480p',
+ duration: '12s', media_duration_sec: 8, video_mode: 'first_last_frame', seed: 0,
+ generate_audio: false, watermark: false, count: 1, references: [{ secret: 'not-for-display' }],
+ } })
+ const info = assetDetailInfo(asset)
+ assert.equal(info.model, 'actual-model')
+ assert.equal(info.mediaDuration, '8 秒')
+ const values = Object.fromEntries(info.parameters.map((item) => [item.label, item.value]))
+ assert.equal(values['设定时长'], '12 秒')
+ assert.equal(values['设定画幅'], '9:16')
+ assert.equal(values['设定分辨率'], '480p')
+ assert.equal(values['生成方式'], '首尾帧')
+ assert.equal(values['生成声音'], '否')
+ assert.equal(values['水印'], '否')
+ assert.equal(values['随机种子'], '0')
+ assert.equal(values['生成数量'], '1')
+ assert.doesNotMatch(JSON.stringify(asset.params), /references|not-for-display/)
+})
+
+test('未记录的媒体时长不能用任务执行耗时推算', () => {
+ const asset = toolRunDetailAsset({ ...record, kind: 'video', started_at: '2026-10-26T10:00:00Z', finished_at: '2026-10-26T10:00:12Z', params: {} })
+ const info = assetDetailInfo(asset)
+ assert.equal(info.mediaDuration, '')
+ assert.equal(info.parameters.some((item) => item.label.includes('时长')), false)
+})
+
test('结算状态不根据完成时间推断,隐藏费用不能显示成免费', () => {
assert.equal(generationBillingState({ ...record, billing_status: 'pending', finished_at: record.created_at }), 'pending')
assert.equal(generationBillingState({ ...record, billing_charged_fen: null }), 'hidden')