Skip to content

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

feat(creation): 支持短视频分步创作、恢复和旧会话编辑

yi29df46f38ae4
diff --git a/README.md b/README.md
index 6ca59cf..e0e951f 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
> **把故事做成能播的片子** — AI 漫剧与 AI 短视频,从文案到成片。
-模板驱动的创作平台:主题 / 剧本 → 分镜 → 生图 → 生视频 → 成片。口播由 Seedance 出片时生成,无需单独配音。
+分步短视频创作:创作设置 → 文案与分镜 → 画面与配音 → 成片预览。默认 3D 动画画风、9:16 竖屏、约 60 秒,各阶段检查与编辑后再继续制作。
**源码**:[github.com/yi1108/printfilm](https://github.com/yi1108/printfilm) · **版本** 0.2.0
@@ -46,12 +46,14 @@
### 2. AI 短视频
-选模板后沿分镜流水线出片,适合获客与科普。
+在 `/history` 通过项目卡片管理短视频,点击新建进入 `/studio/new`。
-- 20+ 内置风格模板
-- `full`(图 + 视频 + 合成)或 `image_text`(静图,更快更省)
-- 单镜重绘、重生视频;任务离开页面也会继续跑
-- 成片由 FFmpeg 合成
+- 精选四款非真人风格:3D 动画、二维动漫、绘本插画、国风水墨
+- 输入想法生成文案,或粘贴已有文案;文案可编辑并保存草稿
+- 确认文案后生成分镜卡片,逐镜编辑旁白与画面,再生成图片和外部 TTS 配音
+- 图片和配音准备好后手动合成;FFmpeg 添加图片运镜和字幕,支持预览、下载
+- 制作中可停止,失败时继续补齐缺失素材;离开页面后可回到项目恢复进度
+- 旧对话项目在任务停止并结算后移交分步编辑,各历史版本保留原素材
### 3. 工具中心
@@ -64,14 +66,23 @@
## 工作流程
```
-输入主题或剧本
- → 分镜
- → 生图
- → 生视频(Seedance 自带口播)
- → FFmpeg 合成成片
+选择画风、输入想法或已有文案
+ → 编辑与保存文案 → 确认后生成分镜
+ → 检查分镜卡片 → 生成图片与外部 TTS 配音
+ → 检查画面、试听配音 → 合成运镜、字幕与旁白
+ → 预览与下载成片
```
-每个阶段都可以回头重做单镜;进度在历史页查看。
+每个阶段完成后停下来等待检查,下一步由用户明确启动。项目列表、分镜和素材均采用卡片展示。漫剧和工具中心沿用原有流程。
+
+更新版本时需创建 `creation_sessions`、`creation_messages`、`creation_runs`,并添加项目会话和目标时长字段。默认启动会自动处理;已有数据库设置 `DATABASE_BOOTSTRAP_ENABLED=false` 时,先在 `backend` 目录执行以下专用增量迁移,再重启后端以加载新接口。该命令只创建上述三张表、两个项目字段及索引,不执行种子数据,也不修改其他业务结构或已有数据;可重复运行。
+
+```bash
+python scripts/prepare_creation_schema.py
+python scripts/prepare_creation_schema.py --check
+```
+
+Windows 可将 `python` 替换为 `.venv\Scripts\python.exe`;使用 `backend/.env` 的现有数据库配置。`--check` 只读检查,结构缺失时返回非零退出码。
## 技术特点
diff --git a/README_EN.md b/README_EN.md
index 355aad9..c75d293 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -7,7 +7,7 @@
> **Turn stories into videos you can ship** — AI short drama and AI short video, from script to final cut.
-A template-driven creation platform: topic / script → storyboard → image gen → video gen → final compose. Voice-over is generated with Seedance at render time — no separate TTS step.
+Step-by-step short-video creation: settings → copy and storyboard → images and narration → final preview. Defaults: 3D animation, 9:16 portrait and approximately 60 seconds. Review and edit each stage before continuing.
**Source:** [github.com/yi1108/printfilm](https://github.com/yi1108/printfilm) · **Version** 0.2.0
@@ -46,12 +46,14 @@ From a one-liner to episode-ready video, with reusable characters and scenes.
### 2. AI short video
-Pick a template and run the storyboard pipeline — good for marketing and explainers.
+Manage short videos as project cards at `/history`, then start a new project at `/studio/new`.
-- 20+ built-in style templates
-- `full` (image + video + compose) or `image_text` (stills — faster and cheaper)
-- Per-shot redraw / regenerate video; jobs keep running after you leave the page
-- Final cut composed with FFmpeg
+- Four curated styles: 3D animation, 2D anime, picture-book illustration, and ink painting
+- Generate copy from an idea or paste an existing script; edit and save it as a draft
+- Confirm the copy to generate editable storyboard cards, then generate images and external TTS narration
+- Review images and audition narration before composing camera motion, captions and audio; preview and download the result
+- Stop production or resume missing media after a failure; saved projects and tasks recover after leaving the page
+- Existing conversations transfer to the step editor after their producers stop and settle; historical versions retain their media
### 3. Tools hub
@@ -64,14 +66,23 @@ Users, orders, templates, task center, model routing. Open API `/api/v1` for ima
## Workflow
```
-Enter a topic or script
- → Storyboard
- → Image generation
- → Video generation (Seedance includes voice-over)
- → FFmpeg final compose
+Choose a style and enter an idea or existing copy
+ → Edit and save copy → Confirm to generate storyboard cards
+ → Review storyboard → Generate images and external TTS
+ → Review images and audition narration → Compose motion and captions
+ → Preview and download the final video
```
-You can redo any single shot at each stage; progress shows on the history page.
+Each stage pauses for review until the user starts the next one. Projects, storyboards and media use cards. Drama and standalone tools retain their existing workflows.
+
+Upgrades require `creation_sessions`, `creation_messages`, `creation_runs`, and the project conversation/duration fields. Startup handles this by default. For an existing database with `DATABASE_BOOTSTRAP_ENABLED=false`, run the scoped, repeatable migration below from `backend`, then restart the backend to load the new routes. It creates only those three tables, two project fields and indexes; it does not seed data, change other business structures or rewrite existing rows.
+
+```bash
+python scripts/prepare_creation_schema.py
+python scripts/prepare_creation_schema.py --check
+```
+
+On Windows, use `.venv\Scripts\python.exe` in place of `python`. The command uses the existing database configuration in `backend/.env`. `--check` is read-only and exits nonzero if required structures are missing.
## Technical highlights
diff --git a/backend/app/api/creation.py b/backend/app/api/creation.py
new file mode 100644
index 0000000..4246b57
--- /dev/null
+++ b/backend/app/api/creation.py
@@ -0,0 +1,87 @@
+"""Owner-scoped, resumable conversational short-video creation."""
+from __future__ import annotations
+
+import asyncio
+
+from fastapi import APIRouter, Depends, Query, Request
+from sqlalchemy.ext.asyncio import AsyncSession
+from sse_starlette.sse import EventSourceResponse
+
+from app.database import AsyncSessionLocal, get_db
+from app.deps import get_current_user
+from app.models import User
+from app.schemas import ProjectOut
+from app.schemas_creation import CreationMessageCreate, CreationSessionCreate, CreationSessionListOut, CreationSessionOut
+from app.services import creation
+from app.services.billing.http import http_exception_for_value_error
+
+router = APIRouter(prefix="/creation-sessions", tags=["creation"])
+
+
[email protected]("", response_model=CreationSessionOut)
+async def create(body: CreationSessionCreate, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ try:
+ return await creation.create_session(db, user, body)
+ except ValueError as exc:
+ await db.rollback()
+ raise http_exception_for_value_error(exc) from exc
+
+
[email protected]("", response_model=CreationSessionListOut)
+async def list_recent(limit: int = Query(5, ge=1, le=20), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ return await creation.list_sessions(db, user.id, limit)
+
+
[email protected]("/{session_id}", response_model=CreationSessionOut)
+async def get(session_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ return await creation.session_snapshot(db, session_id, user.id)
+
+
[email protected]("/{session_id}/messages", response_model=CreationSessionOut)
+async def message(session_id: int, body: CreationMessageCreate, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ try:
+ return await creation.add_message(db, user, session_id, body)
+ except ValueError as exc:
+ await db.rollback()
+ raise http_exception_for_value_error(exc) from exc
+
+
[email protected]("/{session_id}/cancel", response_model=CreationSessionOut)
+async def cancel(session_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ return await creation.cancel_session(db, user, session_id)
+
+
[email protected]("/{session_id}/retry", response_model=CreationSessionOut)
+async def retry(session_id: int, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ try:
+ return await creation.retry_session(db, user, session_id)
+ except ValueError as exc:
+ await db.rollback()
+ raise http_exception_for_value_error(exc) from exc
+
+
[email protected]("/{session_id}/open-editor", response_model=ProjectOut)
+async def open_editor(session_id: int, project_id: int | None = Query(None, ge=1),
+ db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ return await creation.open_editor(db, user, session_id, project_id=project_id)
+
+
[email protected]("/{session_id}/events")
+async def events(session_id: int, request: Request, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)):
+ user_id = int(user.id)
+ initial = await creation.session_snapshot(db, session_id, user_id)
+ await db.rollback() # Do not retain a request transaction for an SSE connection.
+
+ async def stream():
+ previous = initial.model_dump_json()
+ yield {"event": "session", "data": previous}
+ while not await request.is_disconnected():
+ await asyncio.sleep(1.5)
+ async with AsyncSessionLocal() as current_db:
+ snapshot = await creation.session_snapshot(current_db, session_id, user_id)
+ serialized = snapshot.model_dump_json()
+ if serialized != previous:
+ previous = serialized
+ yield {"event": "session", "data": serialized}
+
+ return EventSourceResponse(stream(), ping=15)
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index c2cd9cb..2012c68 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -185,8 +185,15 @@ _PROJECT_WIDE_TASK_TYPES = {
}
+def _ensure_wizard_project(project: Project) -> None:
+ """Conversation projects are exclusively coordinated by their session."""
+ if getattr(project, "creation_session_id", None):
+ raise HTTPException(status_code=409, detail="请在创作对话中修改、停止或重试该短片")
+
+
def _ensure_side_task_allowed(project: Project) -> None:
"""整片任务未终态前拒绝侧任务;单镜重绘可并行,不因残留 IMAGING 卡住。"""
+ _ensure_wizard_project(project)
for task in getattr(project, "active_tasks", []) or []:
if str(getattr(task, "status", "") or "") not in ACTIVE_TASK_STATUSES:
continue
@@ -196,6 +203,7 @@ def _ensure_side_task_allowed(project: Project) -> None:
# COMPOSING 且无进行中任务时视为拼接已失败卡住,允许重新发起
async def _ensure_compose_allowed(db: AsyncSession, user: User, project: Project) -> None:
+ _ensure_wizard_project(project)
active = await list_active_tasks_for_owner(db, user.id, project_id=project.id)
if active:
raise HTTPException(status_code=409, detail="生成进行中,请稍后")
@@ -251,7 +259,10 @@ async def create_project(
user: User = Depends(get_current_user),
) -> Project:
from app.models import Template
+ from app.services.creation_templates import CREATION_TEMPLATE_IDS
+ if body.template_id not in CREATION_TEMPLATE_IDS:
+ raise HTTPException(status_code=400, detail="请选择可用的动画模板")
tpl = await db.get(Template, body.template_id)
if not tpl or not tpl.is_active:
raise HTTPException(status_code=400, detail="无效模板")
@@ -261,6 +272,7 @@ async def create_project(
title=body.title,
source_type=body.source_type,
source_text=body.source_text,
+ target_duration_sec=body.target_duration_sec,
resolution_mode=body.resolution_mode,
pipeline_mode=body.pipeline_mode,
output_ratio=(body.output_ratio or "").strip(),
@@ -403,6 +415,7 @@ async def update_project(
user: User = Depends(get_current_user),
) -> Project:
project = await _get_owned_project(db, project_id, user)
+ _ensure_wizard_project(project)
if project.status in {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
@@ -519,6 +532,7 @@ async def generate_project(
- restart=true: wipe shots/media and regenerate storyboard from scratch.
"""
project = await _get_owned_project(db, project_id, user)
+ _ensure_wizard_project(project)
if project.status in {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
@@ -587,6 +601,7 @@ async def cancel_project(
user: User = Depends(get_current_user),
) -> Project:
project = await _get_owned_project(db, project_id, user)
+ _ensure_wizard_project(project)
running = {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
@@ -797,6 +812,7 @@ async def update_shot(
from app.services.pipeline import clamp_shot_duration
project = await _get_owned_project(db, project_id, user)
+ _ensure_wizard_project(project)
shot = next((s for s in project.shots if s.id == shot_id), None)
if not shot:
raise HTTPException(status_code=404, detail="分镜不存在")
@@ -956,6 +972,7 @@ async def regen_all_audio(
) -> Project:
"""Re-TTS all shots with current voice_id, then recompose final video."""
project = await _get_owned_project(db, project_id, user)
+ _ensure_wizard_project(project)
if project.status in {
ProjectStatus.SCRIPTING,
ProjectStatus.IMAGING,
diff --git a/backend/app/api/templates.py b/backend/app/api/templates.py
index 05749aa..4676536 100644
--- a/backend/app/api/templates.py
+++ b/backend/app/api/templates.py
@@ -5,21 +5,27 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models import Template
from app.schemas import TemplateDetailOut
+from app.services.creation_templates import CREATION_TEMPLATE_IDS, normalize_creation_template
router = APIRouter(prefix="/templates", tags=["templates"])
@router.get("", response_model=list[TemplateDetailOut])
-async def list_templates(db: AsyncSession = Depends(get_db)) -> list[Template]:
+async def list_templates(db: AsyncSession = Depends(get_db)) -> list[dict]:
result = await db.execute(
- select(Template).where(Template.is_active.is_(True)).order_by(Template.sort_order)
+ select(Template).where(Template.is_active.is_(True), Template.id.in_(CREATION_TEMPLATE_IDS))
)
- return list(result.scalars().all())
+ by_id = {template.id: template for template in result.scalars().all()}
+ return [
+ normalize_creation_template(by_id[template_id])
+ for template_id in CREATION_TEMPLATE_IDS
+ if template_id in by_id
+ ]
@router.get("/{template_id}", response_model=TemplateDetailOut)
-async def get_template(template_id: str, db: AsyncSession = Depends(get_db)) -> Template:
+async def get_template(template_id: str, db: AsyncSession = Depends(get_db)) -> dict:
tpl = await db.get(Template, template_id)
if not tpl or not tpl.is_active:
raise HTTPException(status_code=404, detail="模板不存在")
- return tpl
+ return normalize_creation_template(tpl)
diff --git a/backend/app/creation_schema.py b/backend/app/creation_schema.py
new file mode 100644
index 0000000..75ddd81
--- /dev/null
+++ b/backend/app/creation_schema.py
@@ -0,0 +1,82 @@
+"""Scoped additive migration for conversational short-video creation."""
+from __future__ import annotations
+
+from sqlalchemy import inspect, text
+from sqlalchemy.ext.asyncio import AsyncConnection
+
+
+PROJECT_COLUMNS = {
+ "creation_session_id": "INTEGER",
+ "target_duration_sec": "INTEGER DEFAULT 60",
+}
+PROJECT_INDEX = "ix_projects_creation_session_id"
+
+
+class CreationSchemaNotReady(RuntimeError):
+ """Only schema identifiers are exposed; never connection or business data."""
+
+ def __init__(self, missing: list[str]):
+ self.missing = missing
+ super().__init__("创作会话结构未就绪:" + "、".join(missing))
+
+
+def _creation_tables():
+ # Register FK targets, but never create or alter these prerequisite tables.
+ from app import models, models_tasks # noqa: F401
+ from app.models_creation import CreationMessage, CreationRun, CreationSession
+
+ return (CreationSession.__table__, CreationMessage.__table__, CreationRun.__table__)
+
+
+async def apply_creation_schema_patches(conn: AsyncConnection) -> None:
+ """Create only creation tables and the two project columns; preserve all rows."""
+ if conn.dialect.name == "postgresql":
+ # Serialize concurrent invocations before inspecting/creating structures.
+ await conn.execute(text("SELECT pg_advisory_xact_lock(82632024, 10424)"))
+
+ present = await conn.run_sync(lambda sync: set(inspect(sync).get_table_names()))
+ prerequisites = {"users", "templates", "projects", "task_runs"}
+ if missing := sorted(prerequisites - present):
+ raise CreationSchemaNotReady(missing)
+
+ columns = await conn.run_sync(
+ lambda sync: {column["name"] for column in inspect(sync).get_columns("projects")}
+ )
+ for name, definition in PROJECT_COLUMNS.items():
+ if name not in columns:
+ # Identifiers/types are exclusively from the static whitelist above.
+ await conn.execute(text(f"ALTER TABLE projects ADD COLUMN {name} {definition}"))
+ await conn.execute(text(
+ f"CREATE INDEX IF NOT EXISTS {PROJECT_INDEX} ON projects (creation_session_id)"
+ ))
+
+ for table in _creation_tables():
+ await conn.run_sync(lambda sync, table=table: table.create(sync, checkfirst=True))
+
+
+async def assert_creation_schema_ready(conn: AsyncConnection) -> None:
+ """Read-only verification of every column required by the creation models."""
+ expected = {"projects": set(PROJECT_COLUMNS)}
+ for table in _creation_tables():
+ expected[table.name] = set(table.columns.keys())
+
+ def inspect_missing(sync):
+ inspector = inspect(sync)
+ tables = set(inspector.get_table_names())
+ missing = []
+ for table, columns in expected.items():
+ if table not in tables:
+ missing.append(table)
+ continue
+ present = {column["name"] for column in inspector.get_columns(table)}
+ missing.extend(f"{table}.{column}" for column in sorted(columns - present))
+ if "projects" in tables:
+ indexes = inspector.get_indexes("projects")
+ if not any(index["name"] == PROJECT_INDEX and index["column_names"] == ["creation_session_id"]
+ for index in indexes):
+ missing.append(f"projects.{PROJECT_INDEX}")
+ return missing
+
+ missing = await conn.run_sync(inspect_missing)
+ if missing:
+ raise CreationSchemaNotReady(missing)
diff --git a/backend/app/database.py b/backend/app/database.py
index abe41e4..3833c51 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -54,6 +54,7 @@ async def init_db(engine_override: AsyncEngine | None = None) -> None:
"""注册全部模型建表;独立迁移可显式提供引擎而不改变应用连接池。"""
from app import models # noqa: F401
from app import models_agent # noqa: F401
+ from app import models_creation # noqa: F401
from app import models_drama # noqa: F401
from app import models_api # noqa: F401
from app import models_settings # noqa: F401
diff --git a/backend/app/main.py b/backend/app/main.py
index ee7d181..68aed8f 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -8,7 +8,7 @@ from fastapi.staticfiles import StaticFiles
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncEngine
-from app.api import auth, billing, projects, tasks, templates, tools
+from app.api import auth, billing, creation, projects, tasks, templates, tools
from app.api import teams, team_billing, team_content, team_edit_locks
from app.api import api_keys as user_api_keys
from app.api.v1 import router as v1_router
@@ -111,6 +111,7 @@ app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
app.include_router(auth.router, prefix="/api")
app.include_router(templates.router, prefix="/api")
app.include_router(projects.router, prefix="/api")
+app.include_router(creation.router, prefix="/api")
app.include_router(tasks.router, prefix="/api")
app.include_router(billing.router, prefix="/api")
app.include_router(tools.router, prefix="/api")
@@ -201,6 +202,11 @@ async def _apply_schema_patches(engine_override: AsyncEngine | None = None) -> N
pcols = await _pg_columns(conn, "projects")
if "pipeline_mode" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN pipeline_mode VARCHAR(32) DEFAULT 'full'"))
+ if "creation_session_id" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN creation_session_id INTEGER"))
+ if "target_duration_sec" not in pcols:
+ await conn.execute(text("ALTER TABLE projects ADD COLUMN target_duration_sec INTEGER DEFAULT 60"))
+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_projects_creation_session_id ON projects (creation_session_id)"))
if "output_ratio" not in pcols:
await conn.execute(text("ALTER TABLE projects ADD COLUMN output_ratio VARCHAR(16) DEFAULT ''"))
if "voice_id" not in pcols:
diff --git a/backend/app/models.py b/backend/app/models.py
index 855fb28..73b825f 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -112,6 +112,9 @@ class Project(Base):
# full = 图→视频→配音→合成;image_text = 静图+叠字+配音+Ken Burns(跳过 AI 视频)
# 由用户选择,不由模板锁定
pipeline_mode: Mapped[str] = mapped_column(String(32), default="full")
+ # Agent 会话归属和目标时长;历史向导项目保持空会话标识。
+ creation_session_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
+ target_duration_sec: Mapped[int] = mapped_column(Integer, default=60)
# 输出画幅,如 16:9 / 9:16;空则回退模板 default_ratio
output_ratio: Mapped[str] = mapped_column(String(16), default="")
# 配音预设 id;空则用模板默认
diff --git a/backend/app/models_creation.py b/backend/app/models_creation.py
new file mode 100644
index 0000000..f0fffdc
--- /dev/null
+++ b/backend/app/models_creation.py
@@ -0,0 +1,64 @@
+"""Durable conversations and independent production versions for short videos."""
+from __future__ import annotations
+
+from datetime import datetime
+
+from sqlalchemy import JSON, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint, func
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.database import Base
+
+
+class CreationSession(Base):
+ __tablename__ = "creation_sessions"
+ __table_args__ = (UniqueConstraint("user_id", "client_request_id", name="uq_creation_session_request"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
+ client_request_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
+ title: Mapped[str] = mapped_column(String(200), default="新的创作")
+ template_id: Mapped[str] = mapped_column(ForeignKey("templates.id"), default="anim_3d")
+ status: Mapped[str] = mapped_column(String(32), default="drafting", index=True)
+ brief: Mapped[dict] = mapped_column(JSON, default=dict)
+ # Logical pointers avoid circular foreign keys during bootstrap/deletion.
+ latest_message_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ active_turn_task_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ active_run_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
+
+
+class CreationMessage(Base):
+ __tablename__ = "creation_messages"
+ __table_args__ = (
+ UniqueConstraint("session_id", "client_message_id", name="uq_creation_client_message"),
+ UniqueConstraint("reply_to_message_id", name="uq_creation_reply"),
+ )
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ session_id: Mapped[int] = mapped_column(ForeignKey("creation_sessions.id", ondelete="CASCADE"), index=True)
+ role: Mapped[str] = mapped_column(String(16))
+ content: Mapped[str] = mapped_column(Text)
+ client_message_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
+ reply_to_message_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ task_id: Mapped[int | None] = mapped_column(ForeignKey("task_runs.id", ondelete="SET NULL"), nullable=True)
+ response_payload: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+
+class CreationRun(Base):
+ __tablename__ = "creation_runs"
+ __table_args__ = (UniqueConstraint("session_id", "version", name="uq_creation_run_version"),)
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ session_id: Mapped[int] = mapped_column(ForeignKey("creation_sessions.id", ondelete="CASCADE"), index=True)
+ source_message_id: Mapped[int] = mapped_column(ForeignKey("creation_messages.id"))
+ version: Mapped[int] = mapped_column(Integer)
+ status: Mapped[str] = mapped_column(String(32), default="generating", index=True)
+ phase: Mapped[str] = mapped_column(String(32), default="planning")
+ copy_text: Mapped[str] = mapped_column(Text)
+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
+ project_id: Mapped[int | None] = mapped_column(ForeignKey("projects.id", ondelete="SET NULL"), nullable=True, unique=True)
+ current_task_id: Mapped[int | None] = mapped_column(ForeignKey("task_runs.id", ondelete="SET NULL"), nullable=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index aa4aeee..72454eb 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -140,6 +140,7 @@ class ShotUpdate(BaseModel):
class ProjectCreate(BaseModel):
+ target_duration_sec: int = Field(default=60, ge=15, le=180)
image_resolution: str = Field(default="", max_length=16)
video_resolution: str = Field(default="", max_length=16)
template_id: str
@@ -163,6 +164,7 @@ class ProjectCreate(BaseModel):
class ProjectUpdate(BaseModel):
+ target_duration_sec: int | None = Field(default=None, ge=15, le=180)
image_resolution: str | None = Field(default=None, max_length=16)
video_resolution: str | None = Field(default=None, max_length=16)
title: str | None = Field(default=None, max_length=200)
@@ -189,6 +191,8 @@ class ProjectUpdate(BaseModel):
class ProjectOut(BaseModel):
+ creation_session_id: int | None = None
+ target_duration_sec: int = 60
image_resolution: str = ""
video_resolution: str = ""
id: int
@@ -223,6 +227,7 @@ class ProjectOut(BaseModel):
class ProjectListItem(BaseModel):
+ creation_session_id: int | None = None
id: int
title: str
template_id: ProjectTemplateIdOut
diff --git a/backend/app/schemas_creation.py b/backend/app/schemas_creation.py
new file mode 100644
index 0000000..419eb13
--- /dev/null
+++ b/backend/app/schemas_creation.py
@@ -0,0 +1,87 @@
+"""Public conversation snapshots; media remains represented by ProjectOut."""
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Literal
+
+from pydantic import BaseModel, Field, field_validator
+
+from app.schemas import ProjectOut
+
+
+class CreationSessionCreate(BaseModel):
+ template_id: str | None = None
+ message: str | None = Field(default=None, max_length=12000)
+ client_message_id: str | None = Field(default=None, min_length=1, max_length=128)
+
+
+class CreationMessageCreate(BaseModel):
+ content: str = Field(min_length=1, max_length=12000)
+ client_message_id: str = Field(min_length=1, max_length=128)
+ template_id: str | None = None
+
+ @field_validator("content", "client_message_id")
+ @classmethod
+ def nonblank(cls, value: str) -> str:
+ value = value.strip()
+ if not value:
+ raise ValueError("请输入内容")
+ return value
+
+
+class CreationMessageOut(BaseModel):
+ id: int
+ role: str
+ content: str
+ created_at: datetime
+ model_config = {"from_attributes": True}
+
+
+class CreationRunOut(BaseModel):
+ id: int
+ version: int
+ status: str
+ phase: str
+ copy_text: str
+ error_message: str | None
+ project_id: int | None
+ project: ProjectOut | None = None
+ model_config = {"from_attributes": True}
+
+
+class CreationSessionOut(BaseModel):
+ id: int
+ title: str
+ status: str
+ template_id: str
+ brief: dict = Field(default_factory=dict)
+ messages: list[CreationMessageOut] = Field(default_factory=list)
+ runs: list[CreationRunOut] = Field(default_factory=list)
+ active_run_id: int | None = None
+
+
+class CreationSessionListItem(BaseModel):
+ id: int
+ title: str
+ status: str
+ template_id: str
+ updated_at: datetime
+ model_config = {"from_attributes": True}
+
+
+class CreationSessionListOut(BaseModel):
+ items: list[CreationSessionListItem]
+
+
+class CreationDecision(BaseModel):
+ action: Literal["ask", "produce"]
+ reply: str = Field(default="", max_length=4000)
+ title: str = Field(default="", max_length=200)
+ template_id: str | None = None
+ copy_text: str = Field(default="", max_length=12000)
+ brief: dict = Field(default_factory=dict)
+
+ @field_validator("copy_text")
+ @classmethod
+ def strip_copy(cls, value: str) -> str:
+ return value.strip()
diff --git a/backend/app/services/creation.py b/backend/app/services/creation.py
new file mode 100644
index 0000000..4bf2eaa
--- /dev/null
+++ b/backend/app/services/creation.py
@@ -0,0 +1,634 @@
+"""Conversation planning and durable, billed production-stage orchestration.
+
+Every user turn and media stage is a TaskRun. Database row locks serialize
+advancement, and the scheduler reconciles committed state after restarts.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import re
+from datetime import UTC, datetime
+from uuid import uuid4
+
+from fastapi import HTTPException
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.orm import selectinload
+
+from app.config import get_settings
+from app.database import AsyncSessionLocal
+from app.models import Project, ProjectStatus, Template, User
+from app.models_creation import CreationMessage, CreationRun, CreationSession
+from app.models_tasks import TaskRun
+from app.schemas import ProjectOut
+from app.schemas_creation import (
+ CreationDecision, CreationMessageCreate, CreationMessageOut,
+ CreationRunOut, CreationSessionCreate, CreationSessionListItem, CreationSessionListOut, CreationSessionOut,
+)
+from app.schemas_tasks import TaskCreateRequest, TaskTargetBind
+from app.services.creation_templates import CREATION_TEMPLATE_IDS, DEFAULT_CREATION_TEMPLATE_ID
+from app.services.tasks.service import ACTIVE_TASK_STATUSES, TERMINAL_TASK_STATUSES, append_task_event, create_task
+from app.services.voices import list_voices
+
+logger = logging.getLogger(__name__)
+_reconcile_cursor = 0
+
+
+async def _session(db: AsyncSession, session_id: int, user_id: int, *, lock: bool = False) -> CreationSession:
+ stmt = select(CreationSession).where(CreationSession.id == session_id, CreationSession.user_id == user_id)
+ if lock:
+ stmt = stmt.with_for_update().execution_options(populate_existing=True)
+ row = (await db.execute(stmt)).scalar_one_or_none()
+ if row is None:
+ raise HTTPException(status_code=404, detail="创作会话不存在")
+ return row
+
+
+async def _template(db: AsyncSession, template_id: str | None) -> str:
+ tid = template_id or DEFAULT_CREATION_TEMPLATE_ID
+ if tid not in CREATION_TEMPLATE_IDS:
+ raise HTTPException(status_code=400, detail="请选择可用的动画模板")
+ tpl = await db.get(Template, tid)
+ if tpl is None or not tpl.is_active:
+ raise HTTPException(status_code=400, detail="模板暂不可用")
+ return tid
+
+
+async def session_snapshot(db: AsyncSession, session_id: int, user_id: int) -> CreationSessionOut:
+ session = await _session(db, session_id, user_id)
+ messages = list((await db.execute(select(CreationMessage).where(
+ CreationMessage.session_id == session.id,
+ ).order_by(CreationMessage.id))).scalars())
+ runs = list((await db.execute(select(CreationRun).where(
+ CreationRun.session_id == session.id,
+ ).order_by(CreationRun.version))).scalars())
+ project_ids = [run.project_id for run in runs if run.project_id is not None]
+ projects = {}
+ if project_ids:
+ rows = (await db.execute(select(Project).where(
+ Project.id.in_(project_ids), Project.user_id == user_id,
+ ).options(selectinload(Project.shots)).execution_options(populate_existing=True))).scalars()
+ for project in rows:
+ projects[project.id] = ProjectOut.model_validate(project)
+ return CreationSessionOut(
+ id=session.id, title=session.title, status=session.status, template_id=session.template_id,
+ brief=session.brief or {}, active_run_id=session.active_run_id,
+ messages=[CreationMessageOut.model_validate(message) for message in messages],
+ runs=[CreationRunOut.model_validate(run).model_copy(update={"project": projects.get(run.project_id)}) for run in runs],
+ )
+
+
+async def list_sessions(db: AsyncSession, user_id: int, limit: int = 5) -> CreationSessionListOut:
+ rows = (await db.execute(select(CreationSession).where(CreationSession.user_id == user_id)
+ .order_by(CreationSession.updated_at.desc(), CreationSession.id.desc()).limit(limit))).scalars()
+ return CreationSessionListOut(items=[CreationSessionListItem.model_validate(row) for row in rows])
+
+
+async def create_session(db: AsyncSession, user: User, body: CreationSessionCreate) -> CreationSessionOut:
+ # The owner row also serializes duplicate first-message requests before a session exists.
+ await db.execute(select(User.id).where(User.id == user.id).with_for_update())
+ if body.client_message_id:
+ existing = (await db.execute(select(CreationSession).where(
+ CreationSession.user_id == user.id, CreationSession.client_request_id == body.client_message_id,
+ ))).scalar_one_or_none()
+ if existing is not None:
+ if body.message and body.message.strip():
+ first = (await db.execute(select(CreationMessage).where(
+ CreationMessage.session_id == existing.id,
+ CreationMessage.client_message_id == body.client_message_id,
+ ))).scalar_one_or_none()
+ if first is not None and first.content != body.message.strip():
+ raise HTTPException(status_code=409, detail="消息编号已使用,请重新发送")
+ return await session_snapshot(db, existing.id, user.id)
+ session = CreationSession(
+ user_id=user.id, client_request_id=body.client_message_id,
+ template_id=await _template(db, body.template_id), brief=_brief({}),
+ )
+ db.add(session)
+ await db.flush()
+ if body.message and body.message.strip():
+ await _submit_message(db, user, session, CreationMessageCreate(
+ content=body.message, client_message_id=body.client_message_id or uuid4().hex,
+ template_id=body.template_id,
+ ))
+ else:
+ db.add(CreationMessage(session_id=session.id, role="assistant", content="想做什么视频?告诉我主题、受众或故事,我会帮你完成文案并制作成片。"))
+ await db.commit()
+ await reconcile_creation_sessions(db, session_id=session.id)
+ return await session_snapshot(db, session.id, user.id)
+
+
+async def add_message(db: AsyncSession, user: User, session_id: int, body: CreationMessageCreate) -> CreationSessionOut:
+ session = await _session(db, session_id, user.id, lock=True)
+ _ensure_conversation_writable(session)
+ duplicate = (await db.execute(select(CreationMessage).where(
+ CreationMessage.session_id == session.id, CreationMessage.client_message_id == body.client_message_id,
+ ))).scalar_one_or_none()
+ if duplicate is not None:
+ if duplicate.content != body.content:
+ raise HTTPException(status_code=409, detail="消息编号已使用,请重新发送")
+ return await session_snapshot(db, session.id, user.id)
+ await _submit_message(db, user, session, body)
+ await db.commit()
+ await reconcile_creation_sessions(db, session_id=session.id)
+ return await session_snapshot(db, session.id, user.id)
+
+
+def _session_task_filter(session_id: int):
+ return TaskRun.payload["creation_session_id"].as_integer() == session_id
+
+
+async def _cancel_session_tasks(db: AsyncSession, session: CreationSession) -> None:
+ tasks = list((await db.execute(select(TaskRun).where(
+ TaskRun.requested_by == session.user_id, _session_task_filter(session.id),
+ TaskRun.status.in_(ACTIVE_TASK_STATUSES),
+ ).with_for_update())).scalars())
+ for task in tasks:
+ if task.cancel_requested:
+ continue
+ task.cancel_requested = True
+ task.status = "cancel_requested"
+ task.next_action_at = datetime.now(UTC)
+ await append_task_event(db, task.id, event_type="task.cancel_requested", status=task.status, message="创作会话取消或已有新需求")
+ if session.active_run_id:
+ run = await db.get(CreationRun, session.active_run_id)
+ if run and run.status == "generating":
+ run.status = "cancelled"
+ if run.project_id:
+ project = await db.get(Project, run.project_id)
+ if project and project.status != ProjectStatus.DONE:
+ project.status = ProjectStatus.CANCELLED
+ project.error_msg = "创作已取消"
+
+
+async def _new_turn_task(db: AsyncSession, user: User, session: CreationSession, message: CreationMessage,
+ *, requested_template_id: str | None = None) -> TaskRun:
+ if requested_template_id is None and message.task_id:
+ previous_task = await db.get(TaskRun, message.task_id)
+ requested_template_id = (previous_task.payload or {}).get("requested_template_id") if previous_task else None
+ task = await create_task(db, user, TaskCreateRequest(
+ domain="kepu", task_type="creation_turn", defer_activation=True,
+ client_request_id=f"creation:{session.id}:message:{message.id}",
+ payload={"creation_session_id": session.id, "message_id": message.id,
+ "requested_template_id": requested_template_id},
+ ), commit=False)
+ message.task_id = task.id
+ session.active_turn_task_id = task.id
+ return task
+
+
+async def _submit_message(db: AsyncSession, user: User, session: CreationSession, body: CreationMessageCreate) -> None:
+ if body.template_id:
+ session.template_id = await _template(db, body.template_id)
+ await _cancel_session_tasks(db, session)
+ message = CreationMessage(session_id=session.id, role="user", content=body.content,
+ client_message_id=body.client_message_id)
+ db.add(message)
+ await db.flush()
+ session.latest_message_id = message.id
+ session.status = "thinking"
+ if session.title == "新的创作":
+ session.title = body.content[:40]
+ await _new_turn_task(db, user, session, message, requested_template_id=body.template_id)
+
+
+async def cancel_session(db: AsyncSession, user: User, session_id: int) -> CreationSessionOut:
+ session = await _session(db, session_id, user.id, lock=True)
+ _ensure_conversation_writable(session)
+ if session.status != "cancelled":
+ await _cancel_session_tasks(db, session)
+ session.status = "cancelled"
+ db.add(CreationMessage(session_id=session.id, role="system", content="已停止本次创作。已有素材已保存,可重试或继续提出新需求。"))
+ await db.commit()
+ return await session_snapshot(db, session.id, user.id)
+
+
+async def retry_session(db: AsyncSession, user: User, session_id: int) -> CreationSessionOut:
+ session = await _session(db, session_id, user.id, lock=True)
+ _ensure_conversation_writable(session)
+ if session.status not in {"failed", "cancelled"}:
+ # Idempotent retry clicks cannot enqueue another stage.
+ return await session_snapshot(db, session.id, user.id)
+ run = await db.get(CreationRun, session.active_run_id) if session.active_run_id else None
+ if run and run.source_message_id == session.latest_message_id and run.project_id:
+ run.status = "generating"
+ run.error_message = None
+ run.current_task_id = None
+ project = await db.get(Project, run.project_id)
+ if project is None:
+ raise HTTPException(status_code=409, detail="制作项目已删除,请发送新的需求")
+ project.error_msg = None
+ session.status = "generating"
+ else:
+ message = await db.get(CreationMessage, session.latest_message_id) if session.latest_message_id else None
+ if message is None:
+ session.status = "drafting"
+ elif message.response_payload and message.response_payload.get("action") == "ask":
+ # A cancelled clarification already has a durable answer; restore it
+ # without paying for the same question or leaving a completed turn pending.
+ session.status = "drafting"
+ else:
+ await _new_turn_task(db, user, session, message)
+ session.status = "thinking"
+ await db.commit()
+ await reconcile_creation_sessions(db, session_id=session.id)
+ return await session_snapshot(db, session.id, user.id)
+
+
+def _ensure_conversation_writable(session: CreationSession) -> None:
+ if session.status in {"editor_pending", "editor"}:
+ raise HTTPException(status_code=409, detail="该作品已转入分步创作,请在作品编辑页继续")
+
+
+async def open_editor(db: AsyncSession, user: User, session_id: int, *, project_id: int | None = None) -> ProjectOut:
+ """Transfer a conversation to the wizard only after all producers settle.
+
+ The session lock serializes this handoff with planning and reconciliation.
+ Persisting editor_pending before returning 409 prevents restart/callbacks or
+ an old conversation tab from enqueuing another producer during the wait.
+ """
+ session = await _session(db, session_id, user.id, lock=True)
+ editor_project_id = (session.brief or {}).get("editor_project_id")
+ project = None
+ if project_id is not None:
+ # Validate the selected version before cancelling anything. Owner scope
+ # alone is insufficient: the project must belong to this conversation.
+ project = (await db.execute(select(Project).join(CreationRun, CreationRun.project_id == Project.id).where(
+ CreationRun.session_id == session.id, Project.user_id == user.id, Project.id == project_id,
+ ).options(selectinload(Project.shots)).with_for_update(of=Project))).scalar_one_or_none()
+ if project is None:
+ raise HTTPException(status_code=404, detail="该创作版本不存在")
+ elif session.status == "editor" and editor_project_id:
+ project = (await db.execute(select(Project).where(
+ Project.id == editor_project_id, Project.user_id == user.id,
+ ).options(selectinload(Project.shots)))).scalar_one_or_none()
+ if project is None:
+ raise HTTPException(status_code=404, detail="已转入编辑的项目不存在")
+ if session.status == "editor" and project is not None and project.creation_session_id is None:
+ # Already transferred: a wizard task may now be writing this project.
+ # Opening another old link must not reset its status or cancellation.
+ return ProjectOut.model_validate(project)
+
+ task_stmt = select(TaskRun).where(
+ TaskRun.requested_by == user.id, _session_task_filter(session.id),
+ )
+ if session.status != "editor":
+ await _cancel_session_tasks(db, session)
+ session.status = "editor_pending"
+ elif project is not None:
+ # Other versions have already stopped; inspect only this version's old
+ # producers and never cancel new ordinary editor tasks.
+ task_stmt = task_stmt.where(TaskRun.project_id == project.id)
+ tasks = list((await db.execute(task_stmt.with_for_update().execution_options(populate_existing=True))).scalars())
+ if any(task.status not in TERMINAL_TASK_STATUSES or not _settled(task) for task in tasks):
+ await db.commit()
+ raise HTTPException(status_code=409, detail="正在停止旧创作任务并结算,请稍后重试进入编辑",
+ headers={"Retry-After": "2"})
+
+ # Prefer the newest surviving version; completed frames/audio stay attached
+ # to their original project and old completed versions remain accessible.
+ if project is None:
+ project = (await db.execute(select(Project).join(CreationRun, CreationRun.project_id == Project.id).where(
+ CreationRun.session_id == session.id, Project.user_id == user.id,
+ ).order_by(CreationRun.version.desc()).limit(1).options(selectinload(Project.shots))
+ .with_for_update(of=Project))).scalar_one_or_none()
+ if project is None:
+ message = (await db.execute(select(CreationMessage).where(
+ CreationMessage.session_id == session.id, CreationMessage.role == "user",
+ ).order_by(CreationMessage.id.desc()).limit(1))).scalar_one_or_none()
+ payload = (message.response_payload or {}) if message else {}
+ copy_text = str(payload.get("copy_text") or "").strip()
+ source_text = copy_text or (message.content.strip() if message else "")
+ if len(source_text) < 2:
+ await db.rollback()
+ raise HTTPException(status_code=400, detail="会话中还没有创作内容,请从新建短片开始")
+ brief = _brief(session.brief or {})
+ project = Project(
+ user_id=user.id, template_id=await _template(db, session.template_id), title=session.title,
+ source_type="script" if copy_text else "theme", source_text=source_text, pipeline_mode="image_text",
+ resolution_mode="hd", output_ratio=brief["output_ratio"], voice_id=brief["voice_id"],
+ target_duration_sec=brief["target_duration_sec"], status=ProjectStatus.DRAFT,
+ )
+ db.add(project)
+ await db.flush()
+ else:
+ if project.status != ProjectStatus.DONE or not project.final_video_url:
+ from app.services.kepu_stages import resolve_kepu_billing_phase
+ phase = resolve_kepu_billing_phase(project)
+ project.status = {"script": ProjectStatus.DRAFT, "assets": ProjectStatus.SCRIPT_READY,
+ "videos": ProjectStatus.IMAGE_READY, "compose": ProjectStatus.IMAGE_READY}[phase]
+ project.error_msg = None
+ project.creation_session_id = None
+ from app.services import pipeline
+ pipeline.clear_pipeline_cancellation(project.id)
+ session.status = "editor"
+ session.brief = {**(session.brief or {}), "editor_project_id": editor_project_id or project.id}
+ await db.commit()
+ project = (await db.execute(select(Project).where(Project.id == project.id)
+ .options(selectinload(Project.shots)))).scalar_one()
+ return ProjectOut.model_validate(project)
+
+
+def _brief(raw: dict) -> dict:
+ try:
+ duration = int(raw.get("target_duration_sec", 60))
+ except (TypeError, ValueError):
+ duration = 60
+ ratio = str(raw.get("output_ratio") or "9:16")
+ voice = str(raw.get("voice_id") or "")
+ valid_voices = {preset["id"] for preset in list_voices()}
+ return {
+ "target_duration_sec": max(15, min(duration, 180)),
+ "output_ratio": ratio if ratio in {"9:16", "16:9", "1:1"} else "9:16",
+ "voice_id": voice if voice in valid_voices else "",
+ **{key: str(raw.get(key) or "")[:400] for key in ("topic", "audience", "tone")},
+ }
+
+
+_PLANNER_SYSTEM = """你是动画短视频创作 Agent。根据完整对话理解用户需求,产出可直接朗读的中文文案。
+只输出 JSON:action 为 ask 或 produce,reply 为给用户的简短说明,title 为作品标题,copy_text 为最终旁白文案,
+template_id 为动画模板ID,brief 为 {topic,audience,tone,target_duration_sec,output_ratio,voice_id}。
+用户主题不明确、连要讲什么都不知道时,action=ask,一次只问一个关键问题。只要主题/故事明确,
+即自动补全合理的受众、语气和结构,action=produce,不问是否开始、不要求确认文案/分镜/素材。
+默认普通话、约60秒、9:16,按每秒约4个汉字控制文案。用户给出时长时遵循15~180秒。
+用户修改先前作品时必须结合历史文案重新产出完整文案。风格只允许3D动画、二维动漫、绘本、水墨,禁止真人写实。
+template_id 只能取 available_templates 中的ID;用户提到国风/水墨、二维动漫、绘本、3D时正确切换。
+voice_id 只能取 available_voices 中的ID,未指定时沿用 brief.voice_id 或空字符串;用户换男声/女声或指定音色时选择对应预设。
+不编造商店地址、功效、价格等事实,未提供的具体信息不要虚构;无需这些信息也能成片时采用通用表达。
+produce 时 copy_text 仅包含旁白正文(不得放运镜提示、markdown或分镜编号),至少20字。
+ask 时 copy_text 为空。不要宣称已经生成了图片或视频,媒体会在文案产出后由系统自动制作。"""
+
+
+def _requested_preferences(text: str) -> tuple[dict, str | None]:
+ """Honor explicit controls even when a text model omits them in its JSON."""
+ brief: dict = {}
+ seconds = re.search(r"(\d{1,3})\s*(?:秒|seconds?\b)", text, re.I)
+ minutes = re.search(r"(\d(?:\.\d)?)\s*分钟", text)
+ if seconds:
+ brief["target_duration_sec"] = int(seconds.group(1))
+ elif minutes:
+ brief["target_duration_sec"] = round(float(minutes.group(1)) * 60)
+ else:
+ for phrase, duration in (("半分钟", 30), ("一分钟", 60), ("一分半", 90), ("两分钟", 120), ("二分钟", 120), ("三分钟", 180)):
+ if phrase in text:
+ brief["target_duration_sec"] = duration
+ break
+ if "横屏" in text or "16:9" in text:
+ brief["output_ratio"] = "16:9"
+ elif "竖屏" in text or "9:16" in text:
+ brief["output_ratio"] = "9:16"
+ voices = list_voices()
+ genders = list(re.finditer(r"(?:不要|不用)?[男女]声", text))
+ if genders:
+ mention = genders[-1].group()
+ male = "男声" in mention
+ if mention.startswith(("不要", "不用")):
+ male = not male
+ brief["voice_id"] = next(preset["id"] for preset in voices if preset["gender"] == ("male" if male else "female"))
+ for preset in voices:
+ if preset["label"].split(" · ")[0] in text:
+ brief["voice_id"] = preset["id"]
+ styles = [(match.start(), tid) for pattern, tid in (
+ (r"3d|三维", "anim_3d"), (r"二维|日漫|动漫", "soft_anime"),
+ (r"绘本|插画", "kids_flat"), (r"国风|水墨|古风", "ink_guofeng"),
+ ) for match in re.finditer(pattern, text, re.I)]
+ return brief, max(styles)[1] if styles else None
+
+
+def _mock_decision(history: list[dict], brief: dict) -> CreationDecision:
+ latest = next((item["content"] for item in reversed(history) if item["role"] == "user"), "")
+ if (len(latest.strip()) < 5 and not brief.get("topic")) or latest.strip() in {"做个视频", "帮我做视频", "我想做一个视频", "帮我做一个视频"}:
+ return CreationDecision(action="ask", reply="你想讲哪个主题或故事?例如:给小学生讲为什么天空是蓝色的。", brief=brief)
+ revision = brief.get("topic") and any(word in latest for word in ("改成", "改为", "换成", "换男声", "换女声", "调整", "保持"))
+ topic = (brief["topic"] if revision else latest.strip())[:60]
+ preferences, template = _requested_preferences(latest)
+ merged_brief = _brief({**brief, **preferences, "topic": topic})
+ copy_text = (
+ f"{topic}。一个小小的问题,也能打开认识世界的新视角。"
+ "先从身边最熟悉的场景开始,留意那些平时没有注意到的细节。"
+ "把复杂的过程拆成简单的几步,再通过一个直观的例子理解它。"
+ "当你知道其中的联系,就会发现,好奇心正是探索的第一步。"
+ "下次遇到同样的情景,不妨换一个角度观察,把你的发现分享给身边的人。"
+ "观察并不需要复杂的工具,从一个提问开始,就能找到新的线索。"
+ "试着把看到的现象记录下来,将前后的变化放在一起比较。"
+ "遇到暂时不理解的地方,可以重新看看每个步骤,也可以和朋友一起讨论。"
+ "每一次认真观察,都让我们离答案更近一点。现在,就带着这个问题,开始你自己的探索吧。"
+ )
+ target_chars = merged_brief["target_duration_sec"] * 4
+ while len(copy_text) < target_chars:
+ copy_text += "把新的发现与原来的想法比较,寻找它们之间的联系,再用自己的话讲给朋友听。"
+ if len(copy_text) > target_chars + 35:
+ end = copy_text.rfind("。", 20, target_chars + 15)
+ copy_text = copy_text[:end + 1] if end > 20 else copy_text[:target_chars] + "。"
+ return CreationDecision(action="produce", title=topic[:40], template_id=template,
+ reply="文案已经整理好,我会继续生成分镜、画面和配音,为你制作成片。",
+ copy_text=copy_text, brief=merged_brief)
+
+
+async def execute_creation_turn(task: TaskRun) -> dict:
+ payload = task.payload or {}
+ session_id, message_id = int(payload["creation_session_id"]), int(payload["message_id"])
+ async with AsyncSessionLocal() as db:
+ session = await _session(db, session_id, task.requested_by)
+ message = await db.get(CreationMessage, message_id)
+ if message is None or session.latest_message_id != message_id or session.status in {"cancelled", "editor_pending", "editor"}:
+ return {"cancelled": True}
+ if message.response_payload is not None:
+ return {"ok": True, "restored": True}
+ rows = list((await db.execute(select(CreationMessage).where(
+ CreationMessage.session_id == session_id, CreationMessage.id <= message_id,
+ ).order_by(CreationMessage.id.desc()).limit(40))).scalars())
+ recent = []
+ remaining = 30000
+ for row in rows:
+ if remaining <= 0:
+ break
+ content = row.content[:min(12000, remaining)]
+ recent.append({"role": row.role, "content": content})
+ remaining -= len(content)
+ history = list(reversed(recent))
+ context = {
+ "history": history, "brief": session.brief or {}, "template_id": session.template_id,
+ "available_templates": {"anim_3d": "3D动画", "soft_anime": "二维动漫", "kids_flat": "绘本插画", "ink_guofeng": "国风水墨"},
+ "available_voices": [{key: preset[key] for key in ("id", "label", "gender")} for preset in list_voices()],
+ }
+ if get_settings().ark_mock:
+ decision = _mock_decision(history, context["brief"])
+ else:
+ from app.services.drama.llm import drama_chat_json
+ decision = CreationDecision.model_validate(await drama_chat_json(
+ _PLANNER_SYSTEM, json.dumps(context, ensure_ascii=False), temperature=0.6, max_tokens=5000,
+ ))
+ if decision.action == "produce" and len(decision.copy_text) < 20:
+ raise ValueError("文案生成不完整,请重试")
+ if decision.action == "ask" and not decision.reply.strip():
+ raise ValueError("创作助手未返回有效问题,请重试")
+ async with AsyncSessionLocal() as db:
+ session = await _session(db, session_id, task.requested_by, lock=True)
+ message = await db.get(CreationMessage, message_id)
+ if message.response_payload is not None:
+ return {"ok": True, "restored": True}
+ if not get_settings().ark_mock:
+ from app.services.billing import record_line
+ await record_line(db, user_id=task.requested_by, billing_key="llm_chat", model=get_settings().model_llm,
+ estimated=True, task_run_id=task.id, domain="kepu")
+ live_task = await db.get(TaskRun, task.id)
+ if session.latest_message_id != message_id or session.status in {"cancelled", "editor_pending", "editor"} or live_task.cancel_requested:
+ await db.commit()
+ return {"cancelled": True}
+ preferences, requested_style = _requested_preferences(message.content)
+ brief = _brief({**(session.brief or {}), **decision.brief, **preferences})
+ template_id = payload.get("requested_template_id") or requested_style or decision.template_id or session.template_id
+ session.template_id = await _template(db, template_id)
+ session.brief = brief
+ message.response_payload = decision.model_dump()
+ reply = decision.reply.strip()
+ if decision.action == "ask":
+ session.status = "drafting"
+ else:
+ session.title = decision.title.strip() or session.title
+ project = Project(
+ user_id=session.user_id, template_id=session.template_id, title=session.title,
+ source_type="script", source_text=decision.copy_text, pipeline_mode="image_text",
+ output_ratio=brief["output_ratio"], resolution_mode="hd", status=ProjectStatus.DRAFT,
+ creation_session_id=session.id, target_duration_sec=brief["target_duration_sec"],
+ voice_id=brief["voice_id"],
+ extra_prompt=f"动画短片,禁止真人摄影。目标时长约{brief['target_duration_sec']}秒。",
+ )
+ db.add(project)
+ await db.flush()
+ version = int((await db.scalar(select(func.max(CreationRun.version)).where(CreationRun.session_id == session.id))) or 0) + 1
+ run = CreationRun(session_id=session.id, source_message_id=message.id, version=version,
+ copy_text=decision.copy_text, project_id=project.id, current_task_id=task.id)
+ db.add(run)
+ await db.flush()
+ session.active_run_id = run.id
+ session.status = "generating"
+ reply = (reply or "文案已准备好,正在为你制作视频。") + "\n\n" + decision.copy_text
+ db.add(CreationMessage(session_id=session.id, role="assistant", content=reply,
+ reply_to_message_id=message.id))
+ await db.commit()
+ return {"ok": True, "action": decision.action, "creation_session_id": session_id,
+ "kind": "text", "text_content": reply}
+
+
+def _settled(task: TaskRun) -> bool:
+ return task.billing_status not in {"frozen", "reserved"}
+
+
+def _fail_session(db: AsyncSession, session: CreationSession, run: CreationRun | None, message: str) -> None:
+ if session.status != "failed":
+ db.add(CreationMessage(session_id=session.id, role="system", content=f"制作暂时停下了:{message}。已有素材已保留,重试会继续完成。"))
+ session.status = "failed"
+ if run:
+ run.status = "failed"
+ run.error_message = message[:2000]
+
+
+async def _advance_session(db: AsyncSession, session: CreationSession) -> bool:
+ if session.status not in {"thinking", "generating"}:
+ return False
+ tasks = list((await db.execute(select(TaskRun).where(
+ TaskRun.requested_by == session.user_id, _session_task_filter(session.id),
+ ))).scalars())
+ by_id = {task.id: task for task in tasks}
+ if session.status == "thinking":
+ turn = by_id.get(session.active_turn_task_id)
+ if turn is None:
+ _fail_session(db, session, None, "未找到创作任务")
+ return True
+ if turn.status in {"failed", "cancelled"}:
+ _fail_session(db, session, None, turn.error_message or "创作任务已停止")
+ return True
+ # New requirements wait until every previous producer has stopped writing.
+ blockers = [task for task in tasks if task.id != turn.id and (
+ task.status not in TERMINAL_TASK_STATUSES or not _settled(task)
+ )]
+ if turn.status == "pending" and turn.next_action_at is None and not blockers:
+ turn.next_action_at = datetime.now(UTC)
+ return True
+ return False
+ run = await db.get(CreationRun, session.active_run_id) if session.active_run_id else None
+ if run is None or run.status != "generating":
+ return False
+ task = by_id.get(run.current_task_id)
+ if task:
+ if task.status not in TERMINAL_TASK_STATUSES or not _settled(task):
+ return False
+ if task.status != "succeeded":
+ _fail_session(db, session, run, task.error_message or "生成任务已停止")
+ return True
+ elif any(task.status not in TERMINAL_TASK_STATUSES or not _settled(task) for task in tasks):
+ return False
+ project = (await db.execute(select(Project).where(Project.id == run.project_id).options(
+ selectinload(Project.shots), selectinload(Project.template),
+ ).execution_options(populate_existing=True))).scalar_one_or_none()
+ if project is None:
+ _fail_session(db, session, run, "制作项目已删除")
+ return True
+ if project.status == ProjectStatus.DONE and project.final_video_url:
+ run.phase, run.status = "done", "completed"
+ session.status = "completed"
+ db.add(CreationMessage(session_id=session.id, role="assistant", content="视频制作完成,可以直接播放或下载。还想调整内容的话,继续告诉我。"))
+ return True
+ from app.services.kepu_stages import resolve_kepu_billing_phase
+ phase = resolve_kepu_billing_phase(project)
+ if phase == "videos":
+ _fail_session(db, session, run, "当前制作模式不正确")
+ return True
+ user = await db.get(User, session.user_id)
+ # Explicit retry reaches here only after old producers have become terminal.
+ # Restore the stage status now, before the newly queued handler reads it.
+ from app.services import pipeline
+ pipeline.clear_pipeline_cancellation(project.id)
+ try:
+ async with db.begin_nested():
+ next_task = await create_task(db, user, TaskCreateRequest(
+ domain="kepu", task_type="project_compose_only" if phase == "compose" else "project_pipeline",
+ project_id=project.id,
+ payload={"project_id": project.id, "phase": phase, "pipeline_mode": "image_text",
+ "creation_session_id": session.id, "creation_run_id": run.id},
+ dedupe_key=f"creation:{session.id}:run:{run.id}:{phase}",
+ targets=[TaskTargetBind(target_type="project", target_id=project.id)],
+ ), commit=False)
+ except (ValueError, HTTPException) as exc:
+ _fail_session(db, session, run, str(exc.detail if isinstance(exc, HTTPException) else exc))
+ return True
+ run.phase, run.current_task_id = phase, next_task.id
+ project.status = {"script": ProjectStatus.SCRIPTING, "assets": ProjectStatus.IMAGING, "compose": ProjectStatus.COMPOSING}[phase]
+ project.error_msg = None
+ return True
+
+
+async def reconcile_creation_sessions(db: AsyncSession, *, session_id: int | None = None, limit: int = 32) -> int:
+ global _reconcile_cursor
+ stmt = select(CreationSession).where(CreationSession.status.in_(("thinking", "generating")))
+ if session_id is not None:
+ stmt = stmt.where(CreationSession.id == session_id)
+ scan = stmt if session_id is not None else stmt.where(CreationSession.id > _reconcile_cursor)
+ rows = list((await db.execute(scan.order_by(CreationSession.id).limit(limit).with_for_update(skip_locked=True)
+ .execution_options(populate_existing=True))).scalars())
+ if session_id is None and not rows and _reconcile_cursor:
+ _reconcile_cursor = 0
+ rows = list((await db.execute(stmt.order_by(CreationSession.id).limit(limit).with_for_update(skip_locked=True)
+ .execution_options(populate_existing=True))).scalars())
+ if session_id is None and rows:
+ _reconcile_cursor = rows[-1].id
+ changed = 0
+ for session in rows:
+ changed += int(await _advance_session(db, session))
+ await db.commit()
+ return changed
+
+
+async def reconcile_after_task(task: TaskRun) -> None:
+ session_id = (task.payload or {}).get("creation_session_id")
+ if not session_id:
+ return
+ try:
+ async with AsyncSessionLocal() as db:
+ await reconcile_creation_sessions(db, session_id=int(session_id))
+ except Exception:
+ # The periodic reconciler is the durable fallback if this notification is lost.
+ logger.exception("creation completion reconcile failed session=%s", session_id)
diff --git a/backend/app/services/creation_templates.py b/backend/app/services/creation_templates.py
new file mode 100644
index 0000000..4567a2f
--- /dev/null
+++ b/backend/app/services/creation_templates.py
@@ -0,0 +1,36 @@
+"""Public short-video styles without changing stored legacy templates."""
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from app.schemas import TemplateDetailOut
+
+if TYPE_CHECKING:
+ from app.models import Template
+
+
+CREATION_TEMPLATE_IDS = ("anim_3d", "soft_anime", "kids_flat", "ink_guofeng")
+DEFAULT_CREATION_TEMPLATE_ID = CREATION_TEMPLATE_IDS[0]
+
+_PUBLIC_PRESENTATION = {
+ "anim_3d": ("3D 动画", "圆润的三维角色与柔和光影,适合知识讲解和故事短片。", ["3D", "动画"]),
+ "soft_anime": ("二维动漫", "干净线稿与柔和赛璐璐色彩,适合青春故事和情感表达。", ["二维", "动漫"]),
+ "kids_flat": ("绘本插画", "柔和粉彩与亲切的插画角色,适合儿童科普和温暖故事。", ["绘本", "插画"]),
+ "ink_guofeng": ("国风水墨", "水墨留白与写意笔触,适合历史文化和诗意故事。", ["国风", "水墨"]),
+}
+
+
+def normalize_creation_template(template: Template) -> dict:
+ """Return public defaults; do not mutate ORM rows used by old projects."""
+ data = TemplateDetailOut.model_validate(template).model_dump()
+ presentation = _PUBLIC_PRESENTATION.get(template.id)
+ if presentation:
+ name, description, category = presentation
+ data.update(
+ name=name,
+ description=description,
+ category=list(category),
+ default_ratio="9:16",
+ sort_order=CREATION_TEMPLATE_IDS.index(template.id),
+ )
+ return data
diff --git a/backend/app/services/kepu_projects.py b/backend/app/services/kepu_projects.py
index 7d77140..332b0e8 100644
--- a/backend/app/services/kepu_projects.py
+++ b/backend/app/services/kepu_projects.py
@@ -80,6 +80,7 @@ def _scope_filters(user_id: int, mode: str, keyword: str) -> list:
def _list_item(project: Project, *, published: bool) -> ProjectListItem:
status, progress, error_msg = project_runtime_view(project)
return ProjectListItem(
+ creation_session_id=getattr(project, "creation_session_id", None),
id=project.id,
title=project.title,
template_id=project.template_id,
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index a3f6ffd..b42a9ad 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -721,6 +721,11 @@ async def _script_stage(project_id: int) -> None:
style = _effective_style(project)
extra = _effective_extra(project)
+ if image_text:
+ target = int(getattr(project, "target_duration_sec", 60) or 60)
+ extra = f"{extra}\n成片目标约 {target} 秒。每镜一个清晰画面,按旁白节奏分配镜头。".strip()
+ if project.source_type == "script":
+ extra += "严格保留用户已生成文案的全部旁白,只拆分镜头,不增加或删改旁白。"
char_hint = _effective_character_prompt(project)
consist = template_consistency_mode(tpl)
plans_result = await ark.chat_storyboard(
@@ -1453,6 +1458,18 @@ async def _compose_stage(project_id: int) -> None:
if not full_audio.exists():
full_audio = None
+ if mode == "image_text":
+ if not media or any(item.image_path is None for item in media):
+ raise RuntimeError("分镜图片尚未齐备,请重试素材生成")
+ if full_audio is not None:
+ if not _continuous_audio_ok(project_id):
+ raise RuntimeError("整片配音不可用,请重新生成配音")
+ elif any(
+ item.audio_path is None or is_near_silent_audio(item.audio_path)
+ for item in media
+ ):
+ raise RuntimeError("配音尚未齐备,请重新生成配音")
+
sub_cfg = _merge_subtitle_preset(
(project.template.subtitle_config if project.template else None) or {},
getattr(project, "subtitle_preset", "") or "",
diff --git a/backend/app/services/tasks/executor.py b/backend/app/services/tasks/executor.py
index a6f4929..4b99b3b 100644
--- a/backend/app/services/tasks/executor.py
+++ b/backend/app/services/tasks/executor.py
@@ -164,6 +164,8 @@ async def _complete_task(db, task, result: dict) -> None:
except Exception: # noqa: BLE001
logger.exception("settle_task failed task_id=%s", task.id)
await db.commit()
+ from app.services.creation import reconcile_after_task
+ await reconcile_after_task(task)
# 预扣阶段(handler 尚未执行)失败收敛:此时 _lock_task(populate_existing) 已卸掉
diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.py
index 5b94673..3c2c369 100644
--- a/backend/app/services/tasks/handlers.py
+++ b/backend/app/services/tasks/handlers.py
@@ -285,6 +285,11 @@ async def _run_studio_generation(task: TaskRun) -> dict[str, Any] | None:
return await execute_generation(task)
+async def _run_creation_turn(task: TaskRun) -> dict[str, Any] | None:
+ from app.services.creation import execute_creation_turn
+ return await execute_creation_turn(task)
+
+
# 确保关键主键字段存在。
def _require_int(value: int | None, field_name: str) -> int:
if isinstance(value, int) and value > 0:
@@ -293,6 +298,7 @@ def _require_int(value: int | None, field_name: str) -> int:
TASK_HANDLERS: dict[tuple[str, str], TaskHandler] = {
+ ("kepu", "creation_turn"): TaskHandler("kepu", "creation_turn", _run_creation_turn),
("drama", "script_summary"): TaskHandler("drama", "script_summary", _run_drama_script_summary),
("drama", "episode_script"): TaskHandler("drama", "episode_script", _run_drama_episode_script),
("drama", "fragment_plan"): TaskHandler("drama", "fragment_plan", _run_drama_fragment_plan),
diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.py
index 83be8b9..2687a04 100644
--- a/backend/app/services/tasks/scheduler.py
+++ b/backend/app/services/tasks/scheduler.py
@@ -225,6 +225,13 @@ async def _tick() -> None:
if job.done():
_cancel_jobs.pop(task_id, None)
await _claim_cancel_requests()
+ # Conversations advance from persisted, settled stage results, including after restarts.
+ try:
+ from app.services.creation import reconcile_creation_sessions
+ async with AsyncSessionLocal() as db:
+ await reconcile_creation_sessions(db)
+ except Exception:
+ logger.exception("creation workflow reconciliation failed")
await _claim_direct_llm_tasks(now)
# Each lane owns its capacity; a blocked image/video lane never blocks text.
diff --git a/backend/scripts/prepare_creation_schema.py b/backend/scripts/prepare_creation_schema.py
new file mode 100644
index 0000000..3992d87
--- /dev/null
+++ b/backend/scripts/prepare_creation_schema.py
@@ -0,0 +1,59 @@
+"""Explicit, scoped creation-schema upgrade when database bootstrap is disabled."""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import os
+from pathlib import Path
+import sys
+
+
+async def prepare(*, check_only: bool = False) -> None:
+ """Use one transaction; a failed migration or validation rolls back the DDL."""
+ from sqlalchemy import text
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ from app.config import get_settings
+ from app.creation_schema import apply_creation_schema_patches, assert_creation_schema_ready
+
+ engine = create_async_engine(get_settings().database_url, connect_args={"server_settings": {
+ "application_name": "printfilm-creation-schema",
+ "jit": "off",
+ "statement_timeout": "45000",
+ "idle_in_transaction_session_timeout": "45000",
+ "lock_timeout": "10000",
+ }})
+ try:
+ async with engine.begin() as conn:
+ if check_only:
+ await conn.execute(text("SET TRANSACTION READ ONLY"))
+ else:
+ await apply_creation_schema_patches(conn)
+ await assert_creation_schema_ready(conn)
+ finally:
+ await engine.dispose()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="创作会话增量迁移(不执行种子数据或其他业务迁移)")
+ parser.add_argument("--check", action="store_true", help="只读校验结构;缺失时返回 1")
+ args = parser.parse_args(argv)
+ backend = Path(__file__).resolve().parents[1]
+ os.chdir(backend)
+ sys.path.insert(0, str(backend))
+ from app.creation_schema import CreationSchemaNotReady
+
+ try:
+ asyncio.run(prepare(check_only=args.check))
+ except CreationSchemaNotReady as error:
+ print(str(error), file=sys.stderr)
+ return 1
+ except Exception as error:
+ print(f"创作会话结构准备失败({type(error).__name__}),请检查数据库连接后重试。", file=sys.stderr)
+ return 1
+ print("创作会话结构检查通过。" if args.check else "创作会话结构已就绪,请重启后端以加载新接口。")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/tests/test_creation_cancel_lease.py b/backend/tests/test_creation_cancel_lease.py
new file mode 100644
index 0000000..bf21746
--- /dev/null
+++ b/backend/tests/test_creation_cancel_lease.py
@@ -0,0 +1,31 @@
+"""Cross-process cancellation cannot settle while a media writer owns its lease."""
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.services.tasks import scheduler
+
+
[email protected]("execution_mode", ["direct", "queued"])
+async def test_cross_process_cancel_waits_for_any_live_executor_lease(monkeypatch, execution_mode):
+ task = SimpleNamespace(
+ status="cancel_requested", payload={}, execution_mode=execution_mode,
+ lease_until=datetime.now(UTC) + timedelta(minutes=5),
+ )
+
+ @asynccontextmanager
+ async def session():
+ yield SimpleNamespace(commit=AsyncMock())
+
+ settle = AsyncMock()
+ monkeypatch.setattr(scheduler, "AsyncSessionLocal", session)
+ monkeypatch.setattr(scheduler, "get_task_for_runtime", AsyncMock(return_value=task))
+ monkeypatch.setattr(scheduler, "_mark_cancelled", settle)
+ await scheduler._run_cancel_request(12345)
+ settle.assert_not_awaited()
+ task.lease_until = datetime.now(UTC) - timedelta(seconds=1)
+ await scheduler._run_cancel_request(12345)
+ settle.assert_awaited_once()
diff --git a/backend/tests/test_creation_legacy_gate.py b/backend/tests/test_creation_legacy_gate.py
new file mode 100644
index 0000000..b00bb7c
--- /dev/null
+++ b/backend/tests/test_creation_legacy_gate.py
@@ -0,0 +1,38 @@
+"""Legacy endpoints cannot create an uncoordinated second producer."""
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+
+from app.api import projects
+from app.schemas import ProjectUpdate, ShotUpdate
+
+
[email protected]("endpoint,kwargs", [
+ (projects.generate_project, {}),
+ (projects.cancel_project, {}),
+ (projects.compose_only, {}),
+ (projects.regen_all_audio, {}),
+ (projects.regen_image, {"shot_id": 1}),
+ (projects.regen_video, {"shot_id": 1}),
+ (projects.regen_audio, {"shot_id": 1}),
+ (projects.update_project, {"body": ProjectUpdate(title="绕过会话")}),
+ (projects.update_shot, {"shot_id": 1, "body": ShotUpdate(narration="绕过会话")}),
+])
+async def test_agent_project_rejects_legacy_mutation(monkeypatch, endpoint, kwargs):
+ project = SimpleNamespace(id=1, creation_session_id=91, status="SCRIPT_READY", active_tasks=[])
+ monkeypatch.setattr(projects, "_get_owned_project", AsyncMock(return_value=project))
+ db = SimpleNamespace(commit=AsyncMock(), execute=AsyncMock())
+ with pytest.raises(HTTPException) as error:
+ await endpoint(project_id=1, db=db, user=SimpleNamespace(id=1), **kwargs)
+ assert error.value.status_code == 409
+ assert "对话" in error.value.detail
+ db.commit.assert_not_awaited()
+ db.execute.assert_not_awaited()
+
+
+def test_legacy_project_remains_editable():
+ projects._ensure_wizard_project(SimpleNamespace(creation_session_id=None))
+ projects._ensure_side_task_allowed(SimpleNamespace(active_tasks=[]))
diff --git a/backend/tests/test_creation_media_e2e.py b/backend/tests/test_creation_media_e2e.py
new file mode 100644
index 0000000..2e4e737
--- /dev/null
+++ b/backend/tests/test_creation_media_e2e.py
@@ -0,0 +1,213 @@
+"""Real media acceptance for the conversation's automatically scheduled stages.
+
+All provider calls are local substitutes. The shared DB fixture uses a separate
+test database and rollback; generated files live only inside pytest's tmp_path.
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import shutil
+import subprocess
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from sqlalchemy import select
+
+from app.config import get_settings
+from app.models import ProjectStatus, Template
+from app.models_creation import CreationRun, CreationSession
+from app.models_tasks import TaskRun
+from app.schemas_creation import CreationDecision, CreationSessionCreate
+from app.services import creation, ffmpeg_compose, pipeline, storage
+from app.services.ark import ShotPlan, StoryboardResult
+from app.services.tasks import executor
+from app.services.templates_seed import TEMPLATES
+from tests.conftest import make_user
+
+
+def _media_command(command: list[str]) -> subprocess.CompletedProcess:
+ result = subprocess.run(command, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60)
+ assert result.returncode == 0, result.stderr[-3000:]
+ return result
+
+
+async def test_conversation_delivers_real_vertical_mp4_with_voice_motion_and_captions(
+ db_session, monkeypatch, tmp_path,
+):
+ ffmpeg = shutil.which(get_settings().ffmpeg_path) or shutil.which("ffmpeg")
+ ffprobe = shutil.which(get_settings().ffprobe_path) or shutil.which("ffprobe")
+ if not ffmpeg or not ffprobe:
+ pytest.skip("real FFmpeg acceptance requires ffmpeg and ffprobe")
+ if not ffmpeg_compose._find_cjk_font():
+ pytest.skip("real Chinese-caption acceptance requires a CJK font")
+
+ db = db_session
+ settings = get_settings()
+ monkeypatch.setattr(settings, "ark_mock", True)
+ monkeypatch.setattr(settings, "billing_enabled", False)
+ monkeypatch.setattr(settings, "ffmpeg_path", ffmpeg)
+ monkeypatch.setattr(settings, "ffprobe_path", ffprobe)
+ monkeypatch.setattr(storage, "STATIC_ROOT", tmp_path / "static")
+ monkeypatch.setattr(storage, "GENERATED_ROOT", tmp_path / "static" / "generated")
+ monkeypatch.setattr("app.services.oss.oss_enabled", lambda: False)
+ # No model, storage, music, or other HTTP service is permitted in this test.
+ network = AsyncMock(side_effect=AssertionError("media acceptance must stay offline"))
+ monkeypatch.setattr(httpx.AsyncClient, "send", network)
+ monkeypatch.setattr(pipeline, "resolve_bgm_path", lambda _mood: None)
+ monkeypatch.setattr(pipeline, "_record_usage_est", AsyncMock())
+ monkeypatch.setattr(pipeline, "_record_seedream_usage", AsyncMock())
+
+ @asynccontextmanager
+ async def local_session():
+ yield db
+
+ for module in (creation, pipeline, executor):
+ monkeypatch.setattr(module, "AsyncSessionLocal", local_session)
+
+ template = await db.get(Template, "anim_3d")
+ if template is None:
+ template = Template(**next(item for item in TEMPLATES if item["id"] == "anim_3d"))
+ db.add(template)
+ await db.flush()
+ user = await make_user(db)
+
+ narration = ["阳光遇到空气会向四周散射。", "蓝光散射得更多,让天空呈现蓝色。"]
+ copy_text = "".join(narration)
+ monkeypatch.setattr(creation, "_mock_decision", lambda _history, _brief: CreationDecision(
+ action="produce", title="为什么天空是蓝色的", copy_text=copy_text,
+ reply="文案已经整理好,继续制作。", brief={"target_duration_sec": 60, "output_ratio": "9:16"},
+ ))
+ images_ready = asyncio.Event()
+ progress_events = []
+
+ async def progress(_project_id, payload):
+ progress_events.append(payload)
+ if payload.get("message", "").startswith("出图 2/2"):
+ images_ready.set()
+
+ monkeypatch.setattr(pipeline, "publish_progress", progress)
+ # A single transaction/session is deliberately reused by the fixture. These
+ # cancellation reads are covered separately; avoid concurrent use of its
+ # connection by the image/audio branches of this successful-path test.
+ monkeypatch.setattr(pipeline, "_ensure_not_cancelled", AsyncMock())
+
+ async def storyboard(**kwargs):
+ assert kwargs["source_type"] == "script"
+ assert kwargs["source_text"] == copy_text
+ assert kwargs["pipeline_mode"] == "image_text"
+ assert kwargs["output_ratio"] == "9:16"
+ assert "3D" in kwargs["style_prefix"] or "三维" in kwargs["style_prefix"]
+ return StoryboardResult(shots=[
+ ShotPlan(shot=index, duration=4, text=text, img_prompt="3D 动画小角色观察天空",
+ video_prompt="缓慢推近", camera="push-in", bgm="",
+ overlay_title="蓝色天空", overlay_subtitle="观察阳光")
+ for index, text in enumerate(narration, 1)
+ ], character_bible="圆润的三维卡通角色")
+
+ image_calls = []
+
+ async def image(prompt, _negative, _refs, **kwargs):
+ assert kwargs["aspect_ratio"] == "9:16"
+ assert "三维" in prompt or "3D" in prompt
+ image_calls.append(kwargs["shot_no"])
+ path = storage.project_dir(kwargs["project_id"]) / f"mock_{kwargs['shot_no']}.png"
+ _media_command([
+ ffmpeg, "-y", "-f", "lavfi", "-i", "testsrc2=size=256x256:rate=1",
+ "-frames:v", "1", str(path),
+ ])
+ url = storage.publish_local(path)
+ return SimpleNamespace(local_url=url, remote_url=url)
+
+ audio_calls = []
+
+ async def tts(text, voice, **kwargs):
+ assert text == copy_text
+ assert voice
+ audio_calls.append(text)
+ # Let image writes finish before this branch writes through the single
+ # transaction-bound fixture session; actual FFmpeg remains unchanged.
+ await asyncio.wait_for(images_ready.wait(), timeout=10)
+ path = storage.project_dir(kwargs["project_id"]) / "mock_tts.mp3"
+ _media_command([
+ ffmpeg, "-y", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=24000:duration=3",
+ "-c:a", "libmp3lame", "-q:a", "3", str(path),
+ ])
+ return storage.publish_local(path)
+
+ video_model = AsyncMock(side_effect=AssertionError("image_text must not call a video model"))
+ gateway = SimpleNamespace(
+ chat_storyboard=storyboard, gen_image=image, tts=tts, gen_video_i2v=video_model,
+ _sanitize_seedream_prompt=lambda value: value,
+ )
+ monkeypatch.setattr(pipeline, "get_ark", lambda: gateway)
+ ffmpeg_commands = []
+ original_run = ffmpeg_compose._run
+
+ def traced_ffmpeg(command):
+ ffmpeg_commands.append(command.copy())
+ original_run(command)
+
+ monkeypatch.setattr(ffmpeg_compose, "_run", traced_ffmpeg)
+
+ initial = await creation.create_session(db, user, CreationSessionCreate(
+ message="给小学生讲讲为什么天空是蓝色的", client_message_id="real-media-acceptance",
+ ))
+ session = await db.get(CreationSession, initial.id)
+ executed_stages = []
+ for _ in range(4):
+ run = await db.get(CreationRun, session.active_run_id) if session.active_run_id else None
+ task = await db.get(TaskRun, run.current_task_id if run else session.active_turn_task_id)
+ # Direct text stages are marked running when committed; conftest stops
+ # their background launch so this loop can execute every stage itself.
+ assert task.status in {"pending", "running"}, (task.status, task.error_message)
+ executed_stages.append(task.payload.get("phase", task.task_type))
+ await executor.execute_task_run(task.id)
+ await db.refresh(task)
+ assert task.status == "succeeded", task.error_message
+ # Completion callbacks, rather than a UI next-step action, create the
+ # next task. The shorter TTS above retimes the two planned 4 s shots.
+ await db.refresh(session)
+
+ snapshot = await creation.session_snapshot(db, session.id, user.id)
+ assert executed_stages == ["creation_turn", "script", "assets", "compose"]
+ assert snapshot.status == "completed"
+ assert len(snapshot.runs) == 1
+ project = snapshot.runs[0].project
+ assert project is not None
+ assert project.status == ProjectStatus.DONE and project.progress == 100
+ assert project.pipeline_mode == "image_text" and project.template_id == "anim_3d"
+ assert project.creation_session_id == session.id
+ assert image_calls == [1, 2] and audio_calls == [copy_text]
+ assert len(project.shots) == 2
+ assert all(shot.image_url and shot.audio_url and not shot.video_url for shot in project.shots)
+ assert sum("视频制作完成" in message.content for message in snapshot.messages) == 1
+ tasks = list((await db.execute(select(TaskRun).where(creation._session_task_filter(session.id)))).scalars())
+ assert len(tasks) == 4 and all(task.status == "succeeded" for task in tasks)
+
+ final = storage.local_path_from_url(project.final_video_url)
+ assert final and final.is_file() and final.stat().st_size > 2000
+ probe = json.loads(_media_command([
+ ffprobe, "-v", "error", "-show_streams", "-show_format", "-of", "json", str(final),
+ ]).stdout)
+ video_stream = next(stream for stream in probe["streams"] if stream["codec_type"] == "video")
+ audio_stream = next(stream for stream in probe["streams"] if stream["codec_type"] == "audio")
+ assert video_stream["width"] * 16 == video_stream["height"] * 9
+ assert video_stream["codec_name"] == "h264" and audio_stream["codec_name"] == "aac"
+ assert abs(float(video_stream["duration"]) - float(audio_stream["duration"])) < 0.15
+ assert 2.9 <= float(probe["format"]["duration"]) <= 3.3
+ narration_path = storage.local_path_from_url(project.shots[0].audio_url)
+ assert abs(sum(shot.duration for shot in project.shots) - ffmpeg_compose.probe_duration(narration_path)) < 0.02
+ assert not ffmpeg_compose.is_near_silent_audio(final)
+ visual_filters = [command[command.index("-vf") + 1] for command in ffmpeg_commands if "-vf" in command]
+ assert sum("zoompan=" in value for value in visual_filters) == 2
+ assert all("drawtext=" in value and "enable='between" in value for value in visual_filters if "zoompan=" in value)
+ assert any("蓝色天空" in value for value in visual_filters)
+ assert any("阳光" in value for value in visual_filters)
+ assert any(event.get("event") == "done" for event in progress_events)
+ video_model.assert_not_awaited()
+ network.assert_not_awaited()
diff --git a/backend/tests/test_creation_open_editor.py b/backend/tests/test_creation_open_editor.py
new file mode 100644
index 0000000..9dbcd76
--- /dev/null
+++ b/backend/tests/test_creation_open_editor.py
@@ -0,0 +1,261 @@
+"""A conversation can become an ordinary wizard project without racing writers."""
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+from pydantic import ValidationError
+from sqlalchemy import func, select
+
+from app.api.projects import create_project, update_project
+from app.models import Project, ProjectStatus, Shot
+from app.models_creation import CreationMessage, CreationRun, CreationSession
+from app.models_tasks import TaskRun
+from app.schemas import ProjectCreate, ProjectUpdate
+from app.schemas_creation import CreationMessageCreate, CreationSessionCreate
+from app.services import creation, pipeline
+from app.services.ark import StoryboardResult
+from tests.conftest import make_task, make_user
+from tests.test_creation_workflow import context, produce, start, succeed # noqa: F401
+
+
+async def test_handoff_waits_for_terminal_and_settled_writer_then_keeps_materials(context):
+ db, user = context
+ session, run, task = await produce(context)
+ project = await db.get(Project, run.project_id)
+ shot = Shot(project_id=project.id, shot_no=1, narration="已有旁白", img_prompt="天空", image_url="/kept.png")
+ db.add(shot)
+ task.status = "running"
+ await db.commit()
+ task_count = await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id)))
+
+ with pytest.raises(HTTPException) as waiting:
+ await creation.open_editor(db, user, session.id)
+ assert waiting.value.status_code == 409
+ assert waiting.value.headers["Retry-After"] == "2"
+ assert task.cancel_requested and session.status == "editor_pending"
+ assert project.creation_session_id == session.id
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == task_count
+
+ task.status, task.billing_status = "cancelled", "frozen"
+ await db.commit()
+ with pytest.raises(HTTPException) as settling:
+ await creation.open_editor(db, user, session.id)
+ assert settling.value.status_code == 409
+ task.billing_status = "settled"
+ await db.commit()
+ handed = await creation.open_editor(db, user, session.id)
+ assert handed.id == project.id and handed.creation_session_id is None
+ assert handed.status == ProjectStatus.SCRIPT_READY
+ assert handed.shots[0].image_url == "/kept.png"
+ assert session.status == "editor"
+
+ # Opening the legacy URL twice must not cancel a subsequent wizard task.
+ project.status = ProjectStatus.IMAGING
+ project.error_msg = "new wizard progress"
+ await db.commit()
+ repeated = await creation.open_editor(db, user, session.id)
+ assert repeated.id == handed.id and repeated.status == ProjectStatus.IMAGING
+ assert repeated.error_msg == "new wizard progress"
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == task_count
+
+
+async def test_empty_or_foreign_session_cannot_create_editor_project(context):
+ db, user = context
+ snapshot = await creation.create_session(db, user, CreationSessionCreate())
+ stranger = await make_user(db)
+ with pytest.raises(HTTPException) as forbidden:
+ await creation.open_editor(db, stranger, snapshot.id)
+ assert forbidden.value.status_code == 404
+ with pytest.raises(HTTPException) as empty:
+ await creation.open_editor(db, user, snapshot.id)
+ assert empty.value.status_code == 400
+
+
+async def test_draft_handoff_reuses_one_project_and_prevents_late_turn_or_retry(context):
+ db, user = context
+ session, turn = await start(context)
+ with pytest.raises(HTTPException):
+ await creation.open_editor(db, user, session.id)
+ # The queued planner may still get a late executor callback after cancellation.
+ assert (await creation.execute_creation_turn(turn))["cancelled"]
+ turn.status, turn.billing_status = "cancelled", "settled"
+ await db.commit()
+ project = await creation.open_editor(db, user, session.id)
+ again = await creation.open_editor(db, user, session.id)
+ assert again.id == project.id
+ assert project.status == ProjectStatus.DRAFT and project.source_type == "theme"
+ assert project.source_text == "给小学生讲为什么天空是蓝色的"
+ assert project.pipeline_mode == "image_text" and project.output_ratio == "9:16"
+ assert await db.scalar(select(func.count(Project.id)).where(Project.user_id == user.id)) == 1
+ for operation in (
+ creation.retry_session(db, user, session.id),
+ creation.cancel_session(db, user, session.id),
+ creation.add_message(db, user, session.id, CreationMessageCreate(content="修改内容", client_message_id="old-tab")),
+ ):
+ with pytest.raises(HTTPException) as rejected:
+ await operation
+ assert rejected.value.status_code == 409
+ assert session.status == "editor"
+
+
+async def test_completed_video_and_copy_are_preserved(context):
+ db, user = context
+ session, run, task = await produce(context)
+ await succeed(db, task)
+ project = await db.get(Project, run.project_id)
+ project.status, project.final_video_url = ProjectStatus.DONE, "/finished.mp4"
+ session.status, run.status = "completed", "completed"
+ await db.commit()
+ result = await creation.open_editor(db, user, session.id)
+ assert result.final_video_url == "/finished.mp4" and result.status == ProjectStatus.DONE
+ assert result.source_text == run.copy_text
+
+
+async def test_selecting_old_version_keeps_other_wizard_versions_independent(context):
+ db, user = context
+ session, first_run, task = await produce(context)
+ await succeed(db, task)
+ old_project_id = first_run.project_id
+ await creation.add_message(db, user, session.id, CreationMessageCreate(content="再做一个温暖的版本", client_message_id="version-two"))
+ turn = await db.get(TaskRun, session.active_turn_task_id)
+ await creation.execute_creation_turn(turn)
+ await succeed(db, turn)
+ latest_run = await db.get(CreationRun, session.active_run_id)
+ assert latest_run.project_id != old_project_id
+
+ old_version = await creation.open_editor(db, user, session.id, project_id=old_project_id)
+ assert old_version.id == old_project_id and old_version.creation_session_id is None
+ old_project = await db.get(Project, old_project_id)
+ old_project.status = ProjectStatus.IMAGING
+ wizard_task = await make_task(db, user, domain="kepu", task_type="project_pipeline", status="running")
+ wizard_task.project_id = old_project_id
+ unsettled = await make_task(db, user, domain="kepu", task_type="project_pipeline", status="succeeded", billing_status="frozen")
+ unsettled.project_id = latest_run.project_id
+ unsettled.payload = {"creation_session_id": session.id}
+ await db.commit()
+ with pytest.raises(HTTPException) as waiting:
+ await creation.open_editor(db, user, session.id, project_id=latest_run.project_id)
+ assert waiting.value.status_code == 409 and session.status == "editor"
+ assert not wizard_task.cancel_requested
+ unsettled.billing_status = "settled"
+ await db.commit()
+ latest_version = await creation.open_editor(db, user, session.id, project_id=latest_run.project_id)
+ assert latest_version.id == latest_run.project_id and latest_version.creation_session_id is None
+ assert old_project.status == ProjectStatus.IMAGING and not wizard_task.cancel_requested
+ assert (await creation.open_editor(db, user, session.id)).id == old_project_id
+ assert (await creation.open_editor(db, user, session.id, project_id=latest_run.project_id)).id == latest_version.id
+
+
+async def test_selected_version_must_belong_to_owner_and_session_before_cancellation(context):
+ db, user = context
+ session, _run, task = await produce(context)
+ other = await creation.create_session(db, user, CreationSessionCreate(message="另一段独立故事", client_message_id="other-session"))
+ other_session = await db.get(CreationSession, other.id)
+ other_turn = await db.get(TaskRun, other_session.active_turn_task_id)
+ await creation.execute_creation_turn(other_turn)
+ other_run = await db.get(CreationRun, other_session.active_run_id)
+ stranger = await make_user(db)
+ foreign_project = Project(user_id=stranger.id, template_id="anim_3d", source_text="他人作品", status=ProjectStatus.DRAFT)
+ db.add(foreign_project)
+ await db.commit()
+ for invalid_id in (other_run.project_id, foreign_project.id, 100000000):
+ with pytest.raises(HTTPException) as rejected:
+ await creation.open_editor(db, user, session.id, project_id=invalid_id)
+ assert rejected.value.status_code == 404
+ assert not task.cancel_requested and session.status == "generating"
+
+
+async def test_saved_copy_without_project_becomes_editable_script(context):
+ db, user = context
+ session, turn = await start(context)
+ message = await db.get(CreationMessage, session.latest_message_id)
+ message.response_payload = {"action": "produce", "copy_text": "这是已经生成并保存的完整文案。"}
+ await succeed(db, turn)
+ result = await creation.open_editor(db, user, session.id)
+ assert result.source_type == "script" and result.source_text == message.response_payload["copy_text"]
+
+
+async def test_inflight_planner_cannot_publish_a_run_after_handoff_request(context, monkeypatch):
+ from app.config import get_settings
+ db, user = context
+ session, turn = await start(context)
+ monkeypatch.setattr(get_settings(), "ark_mock", False)
+
+ async def response_after_handoff(*_args, **_kwargs):
+ with pytest.raises(HTTPException) as waiting:
+ await creation.open_editor(db, user, session.id)
+ assert waiting.value.status_code == 409
+ return {"action": "produce", "title": "迟到的结果", "copy_text": "这是已停止的旧模型请求返回的文案,不应创建新的自动制作版本。"}
+
+ monkeypatch.setattr("app.services.drama.llm.drama_chat_json", response_after_handoff)
+ assert (await creation.execute_creation_turn(turn))["cancelled"]
+ assert session.status == "editor_pending"
+ assert await db.scalar(select(func.count(CreationRun.id)).where(CreationRun.session_id == session.id)) == 0
+ await succeed(db, turn)
+ project = await creation.open_editor(db, user, session.id)
+ assert project.source_type == "theme" and "迟到" not in project.source_text
+
+
+async def test_open_editor_http_contract(context):
+ import httpx
+ from app.database import get_db
+ from app.deps import get_current_user
+ from app.main import app
+ db, user = context
+ session, turn = await start(context)
+
+ async def database():
+ yield db
+
+ app.dependency_overrides[get_db] = database
+ app.dependency_overrides[get_current_user] = lambda: user
+ try:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test.local") as client:
+ url = f"/api/creation-sessions/{session.id}/open-editor"
+ assert (await client.post(url + "?project_id=-1")).status_code == 422
+ assert (await client.post(url + "?project_id=100000000")).status_code == 404
+ assert not turn.cancel_requested
+ response = await client.post(url)
+ assert response.status_code == 409 and response.headers["Retry-After"] == "2"
+ turn.status, turn.billing_status = "cancelled", "settled"
+ await db.commit()
+ response = await client.post(url)
+ assert response.status_code == 200
+ assert response.json()["creation_session_id"] is None
+ assert response.json()["status"] == "DRAFT"
+ finally:
+ app.dependency_overrides.pop(get_db, None)
+ app.dependency_overrides.pop(get_current_user, None)
+
+
+async def test_wizard_duration_persists_and_reaches_storyboard_prompt(context, monkeypatch):
+ db, user = context
+ project = await create_project(ProjectCreate(template_id="anim_3d", source_type="script", source_text="完整旁白文案。",
+ pipeline_mode="image_text", target_duration_sec=90), db, user)
+ assert project.target_duration_sec == 90 and project.creation_session_id is None
+ updated = await update_project(project.id, ProjectUpdate(target_duration_sec=30), db, user)
+ assert updated.target_duration_sec == 30
+
+ @asynccontextmanager
+ async def local_session():
+ yield db
+
+ planner = AsyncMock(return_value=StoryboardResult(shots=[], character_bible="无人物"))
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", local_session)
+ monkeypatch.setattr(pipeline, "get_ark", lambda: SimpleNamespace(chat_storyboard=planner))
+ monkeypatch.setattr(pipeline, "publish_progress", AsyncMock())
+ monkeypatch.setattr(pipeline, "_record_usage_est", AsyncMock())
+ await pipeline._script_stage(project.id)
+ extra = planner.await_args.kwargs["extra_requirements"]
+ assert "30 秒" in extra and "不增加或删改旁白" in extra
+
+
[email protected]("duration", [14, 181])
+def test_invalid_target_duration_rejected(duration):
+ with pytest.raises(ValidationError):
+ ProjectCreate(template_id="anim_3d", source_text="测试主题", target_duration_sec=duration)
+ with pytest.raises(ValidationError):
+ ProjectUpdate(target_duration_sec=duration)
diff --git a/backend/tests/test_creation_pipeline_recovery.py b/backend/tests/test_creation_pipeline_recovery.py
new file mode 100644
index 0000000..3f962fc
--- /dev/null
+++ b/backend/tests/test_creation_pipeline_recovery.py
@@ -0,0 +1,106 @@
+"""Automatic creation must distinguish shutdown from user cancellation."""
+from __future__ import annotations
+
+import asyncio
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.models import ProjectStatus
+from app.services import pipeline
+
+
+def _session_factory(project):
+ db = SimpleNamespace(get=AsyncMock(return_value=project), commit=AsyncMock())
+
+ @asynccontextmanager
+ async def factory():
+ yield db
+
+ return db, factory
+
+
+async def test_shutdown_preserves_project_and_resume_can_complete(monkeypatch):
+ project = SimpleNamespace(status=ProjectStatus.IMAGING, progress=35, error_msg=None)
+ db, factory = _session_factory(project)
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", factory)
+ monkeypatch.setattr(pipeline, "_ensure_not_cancelled", AsyncMock())
+ monkeypatch.setattr(pipeline, "_resume_plan", AsyncMock(side_effect=asyncio.CancelledError()))
+ events = AsyncMock()
+ monkeypatch.setattr(pipeline, "publish_progress", events)
+
+ with pytest.raises(asyncio.CancelledError):
+ await pipeline.run_pipeline(98761, phase="assets")
+
+ assert project.status == ProjectStatus.IMAGING
+ assert project.error_msg is None
+ db.commit.assert_not_awaited()
+ events.assert_not_awaited()
+
+ monkeypatch.setattr(pipeline, "_resume_plan", AsyncMock(return_value=(True, True, True, True)))
+ compose = AsyncMock()
+ monkeypatch.setattr(pipeline, "_compose_stage", compose)
+ monkeypatch.setattr(pipeline, "_final_url", AsyncMock(return_value="/final.mp4"))
+ await pipeline.run_pipeline(98761, phase=None)
+ compose.assert_awaited_once_with(98761)
+ assert project.status == ProjectStatus.DONE
+
+
+async def test_explicit_cancel_remains_cancelled_and_propagates(monkeypatch):
+ project = SimpleNamespace(status=ProjectStatus.IMAGING, error_msg=None)
+ _, factory = _session_factory(project)
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", factory)
+ monkeypatch.setattr(pipeline, "_ensure_not_cancelled", AsyncMock(side_effect=pipeline.PipelineCancelled("cancel")))
+ monkeypatch.setattr(pipeline, "publish_progress", AsyncMock())
+
+ with pytest.raises(pipeline.PipelineCancelled):
+ await pipeline.run_pipeline(98762)
+
+ assert project.status == ProjectStatus.CANCELLED
+ assert project.error_msg == "用户取消"
+
+
+async def test_failure_after_cancel_does_not_report_success(monkeypatch):
+ project = SimpleNamespace(status=ProjectStatus.IMAGING, error_msg=None)
+ _, factory = _session_factory(project)
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", factory)
+ monkeypatch.setattr(pipeline, "_ensure_not_cancelled", AsyncMock(side_effect=RuntimeError("provider interrupted")))
+ monkeypatch.setattr(pipeline, "publish_progress", AsyncMock())
+ pipeline._cancelled.add(98763)
+ with pytest.raises(pipeline.PipelineCancelled):
+ await pipeline.run_pipeline(98763)
+ assert project.status == ProjectStatus.CANCELLED
+ assert 98763 not in pipeline._cancelled
+
+
[email protected]("has_image", [False, True])
+async def test_image_text_refuses_missing_image_or_audio(monkeypatch, tmp_path, has_image):
+ image = tmp_path / "shot.png"
+ image.write_bytes(b"image")
+ shot = SimpleNamespace(
+ shot_no=1, duration=3.0, narration="测试旁白", video_url=None,
+ audio_url=None, image_url="/image.png" if has_image else None,
+ )
+ project = SimpleNamespace(shots=[shot], output_ratio="9:16", template=None, pipeline_mode="image_text")
+ db = SimpleNamespace(execute=AsyncMock(return_value=SimpleNamespace(scalar_one=lambda: project)))
+
+ @asynccontextmanager
+ async def factory():
+ yield db
+
+ monkeypatch.setattr(pipeline, "AsyncSessionLocal", factory)
+ monkeypatch.setattr(pipeline, "_set_status", AsyncMock())
+ monkeypatch.setattr(pipeline.storage, "project_dir", lambda _id: tmp_path)
+ monkeypatch.setattr(pipeline.storage, "local_path_from_url", lambda url: image if url else None)
+ compose = AsyncMock()
+ monkeypatch.setattr(pipeline, "_run_ffmpeg_compose_with_retry", compose)
+
+ with pytest.raises(RuntimeError, match="配音" if has_image else "图片"):
+ await pipeline._compose_stage(98764)
+ compose.assert_not_awaited()
diff --git a/backend/tests/test_creation_schema.py b/backend/tests/test_creation_schema.py
new file mode 100644
index 0000000..3cac1e7
--- /dev/null
+++ b/backend/tests/test_creation_schema.py
@@ -0,0 +1,92 @@
+"""Exercise scoped migration DDL against an isolated in-memory database."""
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+from sqlalchemy import inspect, text
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app import config, creation_schema
+from scripts import prepare_creation_schema as cli
+
+
[email protected]("has_duration", [False, True])
+async def test_additive_upgrade_is_repeatable_and_preserves_legacy_data(has_duration):
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ try:
+ async with engine.begin() as conn:
+ await conn.execute(text("PRAGMA foreign_keys=ON"))
+ for table in ("users", "task_runs"):
+ await conn.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY)"))
+ await conn.execute(text("CREATE TABLE templates (id VARCHAR(64) PRIMARY KEY)"))
+ duration = ", target_duration_sec INTEGER DEFAULT 60" if has_duration else ""
+ await conn.execute(text(f"CREATE TABLE projects (id INTEGER PRIMARY KEY, title TEXT{duration})"))
+ await conn.execute(text("CREATE TABLE unrelated_records (id INTEGER PRIMARY KEY, payload TEXT)"))
+ await conn.execute(text("INSERT INTO unrelated_records VALUES (1, 'keep')"))
+ await conn.execute(text("INSERT INTO projects (id, title) VALUES (1, 'legacy')"))
+ if has_duration:
+ await conn.execute(text("UPDATE projects SET target_duration_sec = 77"))
+
+ with pytest.raises(creation_schema.CreationSchemaNotReady):
+ await creation_schema.assert_creation_schema_ready(conn)
+ before = set(await conn.run_sync(lambda sync: inspect(sync).get_table_names()))
+ for _ in range(2):
+ await creation_schema.apply_creation_schema_patches(conn)
+ await creation_schema.assert_creation_schema_ready(conn)
+
+ after = set(await conn.run_sync(lambda sync: inspect(sync).get_table_names()))
+ assert after - before == {"creation_sessions", "creation_messages", "creation_runs"}
+ row = (await conn.execute(text("SELECT title, creation_session_id, target_duration_sec FROM projects"))).one()
+ assert tuple(row) == ("legacy", None, 77 if has_duration else 60)
+ assert await conn.scalar(text("SELECT payload FROM unrelated_records")) == "keep"
+ assert await conn.scalar(text("SELECT COUNT(*) FROM creation_sessions")) == 0
+ finally:
+ await engine.dispose()
+
+
+async def test_missing_prerequisites_fail_before_altering_schema():
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
+ try:
+ async with engine.begin() as conn:
+ with pytest.raises(creation_schema.CreationSchemaNotReady) as failure:
+ await creation_schema.apply_creation_schema_patches(conn)
+ assert failure.value.missing == ["projects", "task_runs", "templates", "users"]
+ assert await conn.run_sync(lambda sync: inspect(sync).get_table_names()) == []
+ finally:
+ await engine.dispose()
+
+
[email protected]("check_only", [False, True])
+async def test_cli_check_is_read_only_and_uses_dedicated_transaction(monkeypatch, check_only):
+ from sqlalchemy.ext import asyncio as sqlalchemy_asyncio
+
+ conn = SimpleNamespace(execute=AsyncMock())
+
+ @asynccontextmanager
+ async def begin():
+ yield conn
+
+ engine = SimpleNamespace(begin=begin, dispose=AsyncMock())
+ monkeypatch.setattr(config, "get_settings", lambda: SimpleNamespace(database_url="postgresql+asyncpg://test.invalid/test"))
+ create = Mock(return_value=engine)
+ monkeypatch.setattr(sqlalchemy_asyncio, "create_async_engine", create)
+ patches, verify = AsyncMock(), AsyncMock()
+ monkeypatch.setattr(creation_schema, "apply_creation_schema_patches", patches)
+ monkeypatch.setattr(creation_schema, "assert_creation_schema_ready", verify)
+ await cli.prepare(check_only=check_only)
+ assert patches.await_count == int(not check_only)
+ verify.assert_awaited_once_with(conn)
+ if check_only:
+ assert str(conn.execute.await_args.args[0]) == "SET TRANSACTION READ ONLY"
+ assert create.call_args.kwargs["connect_args"]["server_settings"]["lock_timeout"] == "10000"
+ engine.dispose.assert_awaited_once()
+
+
+def test_cli_errors_do_not_expose_connection_credentials(monkeypatch, capsys):
+ monkeypatch.setattr(cli, "prepare", AsyncMock(side_effect=RuntimeError("postgresql://[email protected]/db")))
+ assert cli.main(["--check"]) == 1
+ assert "secret" not in capsys.readouterr().err
diff --git a/backend/tests/test_creation_templates.py b/backend/tests/test_creation_templates.py
new file mode 100644
index 0000000..0edcd8d
--- /dev/null
+++ b/backend/tests/test_creation_templates.py
@@ -0,0 +1,69 @@
+"""Curated public styles keep legacy template storage and lookups intact."""
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+from fastapi import HTTPException
+
+from app.api.templates import get_template, list_templates
+from app.services.creation_templates import (
+ CREATION_TEMPLATE_IDS,
+ DEFAULT_CREATION_TEMPLATE_ID,
+ normalize_creation_template,
+)
+from app.services.templates_seed import TEMPLATES
+
+
+def template_for(template_id: str) -> SimpleNamespace:
+ return SimpleNamespace(**next(item for item in TEMPLATES if item["id"] == template_id))
+
+
+def test_public_styles_have_default_vertical_ratio_without_mutating_legacy_rows():
+ expected_names = ("3D 动画", "二维动漫", "绘本插画", "国风水墨")
+ assert DEFAULT_CREATION_TEMPLATE_ID == "anim_3d"
+ for index, (template_id, name) in enumerate(zip(CREATION_TEMPLATE_IDS, expected_names)):
+ template = template_for(template_id)
+ previous = vars(template).copy()
+ data = normalize_creation_template(template)
+ assert data["name"] == name
+ assert data["default_ratio"] == "9:16"
+ assert data["sort_order"] == index
+ assert data["preview_cover"] == template.preview_cover
+ assert data["style_prefix"] == template.style_prefix
+ assert vars(template) == previous
+
+
+async def test_public_list_is_curated_and_ordered_independently_of_database_sort():
+ rows = [template_for(template_id) for template_id in reversed(CREATION_TEMPLATE_IDS)]
+ rows.append(template_for("huoke_douyin_hook"))
+ result = Mock()
+ result.scalars.return_value.all.return_value = rows
+ db = SimpleNamespace(execute=AsyncMock(return_value=result))
+
+ data = await list_templates(db)
+
+ assert tuple(item["id"] for item in data) == CREATION_TEMPLATE_IDS
+ query = db.execute.call_args.args[0]
+ assert set(query.compile().params["id_1"]) == set(CREATION_TEMPLATE_IDS)
+ assert "is_active IS true" in str(query)
+
+
+async def test_legacy_template_details_remain_available():
+ legacy = template_for("huoke_douyin_hook")
+ db = SimpleNamespace(get=AsyncMock(return_value=legacy))
+ data = await get_template(legacy.id, db)
+ assert data["id"] == legacy.id
+ assert data["name"] == legacy.name
+ assert data["seedream_config"] == legacy.seedream_config
+
+
+async def test_inactive_template_is_not_exposed_by_detail_endpoint():
+ template = template_for("anim_3d")
+ template.is_active = False
+ db = SimpleNamespace(get=AsyncMock(return_value=template))
+ with pytest.raises(HTTPException) as exc:
+ await get_template(template.id, db)
+ assert exc.value.status_code == 404
diff --git a/backend/tests/test_creation_workflow.py b/backend/tests/test_creation_workflow.py
new file mode 100644
index 0000000..587f075
--- /dev/null
+++ b/backend/tests/test_creation_workflow.py
@@ -0,0 +1,393 @@
+"""Durable conversation revisions, billing boundaries and automatic media stages."""
+from __future__ import annotations
+
+from contextlib import asynccontextmanager
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy import func, select
+
+from app.config import get_settings
+from app.models import Project, ProjectStatus, Shot, Template, UsageEvent
+from app.models_creation import CreationMessage, CreationRun, CreationSession
+from app.models_tasks import TaskRun
+from app.schemas_creation import CreationMessageCreate, CreationSessionCreate
+from app.services import creation
+from app.services.creation_templates import CREATION_TEMPLATE_IDS
+from app.services.templates_seed import TEMPLATES
+from tests.conftest import make_user
+
+
+async def context(db_session, monkeypatch):
+ db = db_session
+ monkeypatch.setattr(get_settings(), "ark_mock", True)
+ for data in TEMPLATES:
+ if data["id"] in CREATION_TEMPLATE_IDS and await db.get(Template, data["id"]) is None:
+ db.add(Template(**data))
+ await db.flush()
+
+ @asynccontextmanager
+ async def local_session():
+ yield db
+
+ monkeypatch.setattr(creation, "AsyncSessionLocal", local_session)
+ monkeypatch.setattr("app.services.kepu_stages.project_audio_ready", lambda p: bool(p.shots) and all(s.audio_url for s in p.shots))
+ user = await make_user(db)
+ return db, user
+
+
+async def start(context, *, message="给小学生讲为什么天空是蓝色的"):
+ db, user = context
+ snapshot = await creation.create_session(db, user, CreationSessionCreate(
+ message=message, client_message_id="initial",
+ ))
+ session = await db.get(CreationSession, snapshot.id)
+ task = await db.get(TaskRun, session.active_turn_task_id)
+ return session, task
+
+
+async def succeed(db, task, *, settled=True):
+ task.status = "succeeded"
+ task.billing_status = "settled" if settled else "frozen"
+ await db.commit()
+
+
+async def produce(context):
+ db, _user = context
+ session, turn = await start(context)
+ await creation.execute_creation_turn(turn)
+ await succeed(db, turn)
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ run = await db.get(CreationRun, session.active_run_id)
+ return session, run, await db.get(TaskRun, run.current_task_id)
+
+
+async def test_first_message_and_duplicate_submission_are_idempotent(context):
+ db, user = context
+ session, task = await start(context)
+ assert task.task_type == "creation_turn"
+ assert task.status == "pending" and task.next_action_at is not None
+ same = await creation.create_session(db, user, CreationSessionCreate(
+ message="给小学生讲为什么天空是蓝色的", client_message_id="initial",
+ ))
+ assert same.id == session.id
+ await creation.add_message(db, user, session.id, CreationMessageCreate(
+ content="给小学生讲为什么天空是蓝色的", client_message_id="initial",
+ ))
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == 1
+ assert await db.scalar(select(func.count(CreationMessage.id)).where(CreationMessage.session_id == session.id)) == 1
+ with pytest.raises(HTTPException) as conflict:
+ await creation.add_message(db, user, session.id, CreationMessageCreate(content="换一个完全不同的主题", client_message_id="initial"))
+ assert conflict.value.status_code == 409
+
+
+async def test_asks_one_question_then_uses_conversation_history(context, monkeypatch):
+ db, user = context
+ session, turn = await start(context, message="帮我做一个视频")
+ await creation.execute_creation_turn(turn)
+ await succeed(db, turn)
+ snapshot = await creation.session_snapshot(db, session.id, user.id)
+ assert snapshot.status == "drafting"
+ assert not snapshot.runs
+ assert "主题" in snapshot.messages[-1].content
+ await creation.add_message(db, user, session.id, CreationMessageCreate(content="为什么天空是蓝色的", client_message_id="topic"))
+ message_task = await db.get(TaskRun, session.active_turn_task_id)
+ seen = []
+
+ async def planner(_system, user_context, **_kwargs):
+ import json
+ seen.extend(json.loads(user_context)["history"])
+ return {"action": "produce", "title": "蓝色天空", "copy_text": "太阳光包含不同颜色,进入大气后,较短波长的蓝光更容易向各个方向散射。", "brief": {}}
+
+ monkeypatch.setattr(get_settings(), "ark_mock", False)
+ monkeypatch.setattr("app.services.drama.llm.drama_chat_json", planner)
+ await creation.execute_creation_turn(message_task)
+ assert [item["role"] for item in seen] == ["user", "assistant", "user"]
+ assert seen[0]["content"] == "帮我做一个视频"
+
+
+async def test_auto_production_advances_only_after_settlement_and_once(context):
+ db, user = context
+ session, turn = await start(context)
+ await creation.execute_creation_turn(turn)
+ run = await db.get(CreationRun, session.active_run_id)
+ project = await db.get(Project, run.project_id)
+ assert project.pipeline_mode == "image_text" and project.source_type == "script"
+ assert project.output_ratio == "9:16"
+ assert project.target_duration_sec == 60
+ assert project.creation_session_id == session.id
+ await succeed(db, turn, settled=False)
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert run.phase == "planning"
+ turn.billing_status = "settled"
+ await db.commit()
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ script_task_id = run.current_task_id
+ assert run.phase == "script"
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert run.current_task_id == script_task_id
+ shot = Shot(project_id=project.id, shot_no=1, narration=run.copy_text, img_prompt="3D小角色望着天空")
+ db.add(shot)
+ project.status = ProjectStatus.SCRIPT_READY
+ await succeed(db, await db.get(TaskRun, script_task_id))
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert run.phase == "assets"
+ assets_task = await db.get(TaskRun, run.current_task_id)
+ assert assets_task.payload["phase"] == "assets"
+ shot.image_url, shot.audio_url = "/static/test/image.png", "/static/test/audio.mp3"
+ await succeed(db, assets_task)
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert run.phase == "compose"
+ compose_task = await db.get(TaskRun, run.current_task_id)
+ assert compose_task.task_type == "project_compose_only"
+ project.status, project.final_video_url = ProjectStatus.DONE, "/static/test/final.mp4"
+ await succeed(db, compose_task)
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ snapshot = await creation.session_snapshot(db, session.id, user.id)
+ assert snapshot.status == "completed"
+ assert snapshot.runs[0].phase == "done"
+ assert snapshot.runs[0].project.final_video_url.endswith("final.mp4")
+ assert len(snapshot.runs[0].project.shots) == 1
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == 4
+ assert sum("视频制作完成" in m.content for m in snapshot.messages) == 1
+
+
+async def test_new_requirement_waits_for_old_writer_then_creates_independent_version(context):
+ db, user = context
+ session, old_run, old_task = await produce(context)
+ old_project_id, old_copy = old_run.project_id, old_run.copy_text
+ old_task.status = "running"
+ await db.commit()
+ await creation.add_message(db, user, session.id, CreationMessageCreate(content="改成温暖的睡前故事语气", client_message_id="revision"))
+ new_turn = await db.get(TaskRun, session.active_turn_task_id)
+ assert old_run.status == "cancelled" and old_task.cancel_requested
+ assert new_turn.next_action_at is None
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert new_turn.next_action_at is None
+ old_task.status, old_task.billing_status = "cancelled", "settled"
+ await db.commit()
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert new_turn.next_action_at is not None
+ await creation.execute_creation_turn(new_turn)
+ new_run = await db.get(CreationRun, session.active_run_id)
+ assert new_run.version == 2 and new_run.project_id != old_project_id
+ assert old_run.copy_text == old_copy
+
+
+async def test_cancel_does_not_resume_without_explicit_retry_and_retry_keeps_materials(context):
+ db, user = context
+ session, run, task = await produce(context)
+ project_id = run.project_id
+ shot = Shot(project_id=project_id, shot_no=1, narration="保留已经完成的旁白", img_prompt="3D天空", image_url="/static/kept.png")
+ db.add(shot)
+ await db.commit()
+ await creation.cancel_session(db, user, session.id)
+ task.status, task.billing_status = "cancelled", "settled"
+ await db.commit()
+ before = await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id)))
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == before
+ await creation.retry_session(db, user, session.id)
+ retried = await db.get(CreationRun, session.active_run_id)
+ assert retried.id == run.id and retried.project_id == project_id
+ assert retried.phase == "assets"
+ assert (await db.get(Shot, shot.id)).image_url == "/static/kept.png"
+ first_retry_task = run.current_task_id
+ await creation.retry_session(db, user, session.id)
+ assert run.current_task_id == first_retry_task
+
+
+async def test_failed_stage_retries_same_version_and_preserves_error(context):
+ db, user = context
+ session, run, task = await produce(context)
+ task.status, task.billing_status, task.error_message = "failed", "settled", "余额不足"
+ await db.commit()
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ snapshot = await creation.session_snapshot(db, session.id, user.id)
+ assert snapshot.status == "failed" and snapshot.runs[0].error_message == "余额不足"
+ await creation.retry_session(db, user, session.id)
+ assert run.version == 1 and run.current_task_id != task.id
+
+
+async def test_persisted_turn_result_is_reused_without_duplicate_llm_or_usage(context, monkeypatch):
+ db, user = context
+ session, task = await start(context)
+ monkeypatch.setattr(get_settings(), "ark_mock", False)
+ planner = AsyncMock(return_value={
+ "action": "produce", "title": "蓝色天空", "copy_text": "太阳光进入大气后,蓝光向不同方向散射。抬头望向天空,我们就能看到这些散射的蓝色光。", "brief": {},
+ })
+ monkeypatch.setattr("app.services.drama.llm.drama_chat_json", planner)
+ await creation.execute_creation_turn(task)
+ restored = await creation.execute_creation_turn(task)
+ assert restored["restored"]
+ assert planner.await_count == 1
+ assert await db.scalar(select(func.count(UsageEvent.id)).where(UsageEvent.task_run_id == task.id)) == 1
+ assert await db.scalar(select(func.count(CreationRun.id)).where(CreationRun.session_id == session.id)) == 1
+
+
+async def test_owner_isolation_and_rejects_photoreal_templates(context):
+ db, user = context
+ session, _task = await start(context)
+ stranger = await make_user(db)
+ for action in (
+ lambda: creation.session_snapshot(db, session.id, stranger.id),
+ lambda: creation.cancel_session(db, stranger, session.id),
+ lambda: creation.retry_session(db, stranger, session.id),
+ lambda: creation.add_message(db, stranger, session.id, CreationMessageCreate(content="新的主题", client_message_id="foreign")),
+ ):
+ with pytest.raises(HTTPException) as denied:
+ await action()
+ assert denied.value.status_code == 404
+ with pytest.raises(HTTPException) as invalid:
+ await creation.create_session(db, user, CreationSessionCreate(template_id="live_person"))
+ assert invalid.value.status_code == 400
+
+
+async def test_natural_language_voice_style_duration_and_explicit_chip_precedence(context):
+ db, user = context
+ session, turn = await start(context, message="给孩子讲月亮的故事,换成国风水墨,用男声,90秒横屏")
+ await creation.execute_creation_turn(turn)
+ run = await db.get(CreationRun, session.active_run_id)
+ project = await db.get(Project, run.project_id)
+ assert project.template_id == session.template_id == "ink_guofeng"
+ assert "male" in project.voice_id and "female" not in project.voice_id
+ assert project.target_duration_sec == 90 and project.output_ratio == "16:9"
+ await succeed(db, turn)
+ await creation.add_message(db, user, session.id, CreationMessageCreate(
+ content="改为国风,换女声,半分钟", client_message_id="chip-overrides-text", template_id="kids_flat",
+ ))
+ turn2 = await db.get(TaskRun, session.active_turn_task_id)
+ await creation.execute_creation_turn(turn2)
+ revised = await db.get(CreationRun, session.active_run_id)
+ revised_project = await db.get(Project, revised.project_id)
+ assert revised_project.template_id == "kids_flat"
+ assert "female" in revised_project.voice_id
+ assert revised_project.target_duration_sec == 30
+ assert revised_project.title == project.title
+ assert creation._brief({"voice_id": "unconfigured-secret-voice"})["voice_id"] == ""
+
+
+async def test_recent_sessions_include_drafts_and_snapshot_is_read_only(context):
+ db, user = context
+ session, _turn = await start(context)
+ draft = await creation.create_session(db, user, CreationSessionCreate())
+ stranger = await make_user(db)
+ await db.commit()
+ own = await creation.list_sessions(db, user.id, 5)
+ assert {item.id for item in own.items} == {session.id, draft.id}
+ assert (await creation.list_sessions(db, stranger.id)).items == []
+ dirty_before = set(db.dirty)
+ await creation.session_snapshot(db, session.id, user.id)
+ assert set(db.dirty) == dirty_before
+
+
+async def test_reconcile_cursor_does_not_starve_later_pending_conversations(context, monkeypatch):
+ db, user = context
+ monkeypatch.setattr(creation, "_reconcile_cursor", 0)
+ sessions = []
+ for index in range(5):
+ row = CreationSession(user_id=user.id, template_id="anim_3d", status="thinking")
+ db.add(row)
+ await db.flush()
+ message = CreationMessage(session_id=row.id, role="user", content=f"第{index}个天空故事")
+ db.add(message)
+ await db.flush()
+ task = await creation._new_turn_task(db, user, row, message)
+ row.latest_message_id = message.id
+ if index < 4:
+ task.status = "running"
+ sessions.append((row, task))
+ await db.commit()
+ # Older long-running turns fill both first pages; the fifth still activates.
+ for _ in range(3):
+ await creation.reconcile_creation_sessions(db, limit=2)
+ assert sessions[-1][1].next_action_at is not None
+
+
+async def test_retry_waits_for_cancellation_owner_before_resetting_project(context):
+ from app.services import pipeline
+ db, user = context
+ session, run, task = await produce(context)
+ task.status = "running"
+ task.lease_until = datetime.now(UTC) + timedelta(minutes=10)
+ await db.commit()
+ await creation.cancel_session(db, user, session.id)
+ project = await db.get(Project, run.project_id)
+ pipeline.cancel_pipeline(project.id)
+ await creation.retry_session(db, user, session.id)
+ assert project.status == ProjectStatus.CANCELLED
+ assert run.current_task_id is None
+ task.status, task.billing_status = "cancelled", "settled"
+ await db.commit()
+ await creation.reconcile_creation_sessions(db, session_id=session.id)
+ assert project.status == ProjectStatus.SCRIPTING
+ assert not pipeline.is_cancelled(project.id)
+ assert run.current_task_id is not None
+
+
+async def test_sse_uses_captured_owner_id_after_rollback(context, monkeypatch):
+ from app.api import creation as api
+ db, user = context
+ session, _turn = await start(context)
+ session_id, user_id = session.id, user.id
+ monkeypatch.setattr(api, "AsyncSessionLocal", creation.AsyncSessionLocal)
+ monkeypatch.setattr(api.asyncio, "sleep", AsyncMock())
+ request = SimpleNamespace(is_disconnected=AsyncMock(side_effect=[False, True]))
+ snapshot_mock = AsyncMock(wraps=creation.session_snapshot)
+ monkeypatch.setattr(creation, "session_snapshot", snapshot_mock)
+ response = await api.events(session_id, request, db, user)
+ first = await anext(response.body_iterator)
+ assert first["event"] == "session"
+ with pytest.raises(StopAsyncIteration):
+ await anext(response.body_iterator)
+ assert snapshot_mock.await_args_list[-1].args[-1] == user_id
+
+
+async def test_cancelled_clarification_retry_restores_question_without_another_charge(context):
+ db, user = context
+ session, task = await start(context, message="帮我做一个视频")
+ await creation.execute_creation_turn(task)
+ await succeed(db, task)
+ await creation.cancel_session(db, user, session.id)
+ await creation.retry_session(db, user, session.id)
+ assert session.status == "drafting"
+ assert await db.scalar(select(func.count(TaskRun.id)).where(creation._session_task_filter(session.id))) == 1
+
+
+async def test_http_contract_and_owner_isolation(context):
+ import httpx
+ from app.database import get_db
+ from app.deps import get_current_user
+ from app.main import app
+ db, user = context
+
+ async def database():
+ yield db
+
+ app.dependency_overrides[get_db] = database
+ app.dependency_overrides[get_current_user] = lambda: user
+ try:
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test.local") as client:
+ created = await client.post("/api/creation-sessions", json={"message": "给孩子讲天空为什么是蓝色的", "client_message_id": "http-initial"})
+ assert created.status_code == 200
+ session_id = created.json()["id"]
+ assert created.json()["status"] == "thinking"
+ assert created.json()["brief"]["target_duration_sec"] == 60
+ recent = await client.get("/api/creation-sessions?limit=5")
+ assert recent.status_code == 200 and recent.json()["items"][0]["id"] == session_id
+ detail = await client.get(f"/api/creation-sessions/{session_id}")
+ assert detail.status_code == 200 and len(detail.json()["messages"]) == 1
+ invalid = await client.post(f"/api/creation-sessions/{session_id}/messages", json={"content": " ", "client_message_id": "blank"})
+ assert invalid.status_code == 422
+ app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(id=user.id + 1000000)
+ assert (await client.get(f"/api/creation-sessions/{session_id}")).status_code == 404
+ assert (await client.post(f"/api/creation-sessions/{session_id}/cancel")).status_code == 404
+ assert (await client.get(f"/api/creation-sessions/{session_id}/events")).status_code == 404
+ finally:
+ app.dependency_overrides.pop(get_db, None)
+ app.dependency_overrides.pop(get_current_user, None)
diff --git a/backend/tests/test_kepu_project_listing.py b/backend/tests/test_kepu_project_listing.py
index 8361332..7642a0e 100644
--- a/backend/tests/test_kepu_project_listing.py
+++ b/backend/tests/test_kepu_project_listing.py
@@ -27,6 +27,7 @@ def _project(project_id):
async def test_listing_batches_tasks_and_projects_runtime_once(monkeypatch):
"""列表一次获取整页任务,运行态与已发布标记保持原响应语义。"""
rows = [_project(12), _project(20)]
+ rows[0].creation_session_id = 91
task = SimpleNamespace(
id=99, domain="kepu", task_type="project_pipeline", status="running",
progress_percent=60, error_message=None, payload={"phase": "videos"},
@@ -45,6 +46,7 @@ async def test_listing_batches_tasks_and_projects_runtime_once(monkeypatch):
assert page.stats.model_dump() == {"total": 10, "generating": 2, "done": 5, "published": 1}
assert (page.items[0].status, page.items[0].progress, page.items[0].error_msg) == (ProjectStatus.VIDEOING, 60, None)
assert [item.published for item in page.items] == [False, True]
+ assert [item.creation_session_id for item in page.items] == [91, None]
assert page.items[1].error_msg == "旧错误"
compiled = [call.args[0].compile(dialect=postgresql.dialect()) for call in db.execute.await_args_list]
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index d2b5e10..1f9d4a8 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -18,6 +18,7 @@ import PricingPage from './pages/PricingPage'
import StudioPage from './pages/StudioPage'
import TemplatesPage from './pages/TemplatesPage'
import CreateProjectPage from './pages/studio/CreateProjectPage'
+import CreationSessionEditorBridge from './pages/studio/CreationSessionEditorBridge'
import StyleConfigPage from './pages/studio/StyleConfigPage'
import StoryboardPage from './pages/studio/StoryboardPage'
import EditorPage from './pages/studio/EditorPage'
@@ -71,6 +72,7 @@ export default function App() {
<Route path="/pricing" element={<PricingPage />} />
<Route path="/history" element={<HistoryPage />} />
<Route path="/studio/new" element={<CreateProjectPage />} />
+ <Route path="/studio/sessions/:sessionId" element={<CreationSessionEditorBridge />} />
<Route path="/studio/:id/style" element={<StyleConfigPage />} />
<Route path="/studio/:id/editor" element={<EditorPage />} />
<Route path="/studio/:id" element={<StoryboardPage />} />
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index 470f86d..36328f8 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -1,6 +1,7 @@
import { workspaceScope } from './features/teams/workspaceScope'
import { API_BASE, createJsonRequester, requestResponse, uploadFile } from './api/client'
import { apiErrorMessage } from './api/http'
+import { curatedCreationTemplates } from './lib/creationTemplates'
/** 科普、账号和计费 API 共用 JSON 传输层。 */
const request = createJsonRequester()
@@ -107,6 +108,8 @@ export function resolveVoiceId(raw: string, voices: VoicePreset[]): string {
export type Project = {
id: number
+ target_duration_sec?: number
+ creation_session_id?: number | null
template_id: string
title: string
source_type: string
@@ -349,13 +352,17 @@ export const api = {
})
},
templates() {
- return request<Template[]>('/api/templates')
+ return request<Template[]>('/api/templates').then(curatedCreationTemplates)
+ },
+ getTemplate(id: string) {
+ return request<Template>(`/api/templates/${encodeURIComponent(id)}`)
},
createProject(body: {
template_id: string
title: string
source_type: 'theme' | 'script'
source_text: string
+ target_duration_sec?: number
resolution_mode?: 'preview' | 'hd'
pipeline_mode?: PipelineMode
output_ratio?: string
@@ -372,6 +379,7 @@ export const api = {
title?: string
source_type?: 'theme' | 'script'
source_text?: string
+ target_duration_sec?: number
template_id?: string
pipeline_mode?: PipelineMode
output_ratio?: string
diff --git a/frontend/src/api/creation.ts b/frontend/src/api/creation.ts
new file mode 100644
index 0000000..414119c
--- /dev/null
+++ b/frontend/src/api/creation.ts
@@ -0,0 +1,105 @@
+import type { Project } from '../api'
+import { createJsonRequester } from './client'
+import { throwApiError } from '../lib/apiError'
+import { creationApiErrorDetail } from '../lib/creationApiError'
+
+const request = createJsonRequester((response, detail) =>
+ throwApiError(response.status, creationApiErrorDetail(response.status, detail), response.statusText),
+)
+
+export type CreationMessage = {
+ id: number | string
+ role: string
+ content: string
+ created_at?: string
+}
+
+export type CreationRun = {
+ id: number | string
+ version: number
+ status: string
+ phase: string
+ copy_text?: string | null
+ error_message?: string | null
+ project_id?: number | null
+ project?: Project | null
+}
+
+export type CreationSession = {
+ id: number | string
+ title: string
+ status: string
+ template_id: string
+ messages: CreationMessage[]
+ runs: CreationRun[]
+ active_run_id?: number | string | null
+ brief?: Record<string, unknown> | null
+}
+
+export type CreationSessionSummary = Pick<
+ CreationSession,
+ 'id' | 'title' | 'status' | 'template_id'
+> & {
+ updated_at?: string
+}
+
+type MessageInput = {
+ content: string
+ client_message_id: string
+ template_id?: string
+}
+const path = (id: number | string) =>
+ `/api/creation-sessions/${encodeURIComponent(id)}`
+
+export const creationApi = {
+ openEditor(id: number | string, signal?: AbortSignal, projectId?: number) {
+ const query = projectId ? `?project_id=${projectId}` : ''
+ return request<Project>(`${path(id)}/open-editor${query}`, { method: 'POST', signal })
+ },
+ async list(limit = 5, signal?: AbortSignal) {
+ const value = await request<
+ CreationSessionSummary[] | { items: CreationSessionSummary[] }
+ >(`/api/creation-sessions?limit=${limit}`, { signal })
+ return Array.isArray(value)
+ ? value
+ : Array.isArray(value.items)
+ ? value.items
+ : []
+ },
+ create(
+ body: {
+ template_id?: string
+ message?: string
+ client_message_id?: string
+ },
+ signal?: AbortSignal,
+ ) {
+ return request<CreationSession>('/api/creation-sessions', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ signal,
+ })
+ },
+ get(id: number | string, signal?: AbortSignal) {
+ return request<CreationSession>(path(id), { signal })
+ },
+ send(id: number | string, body: MessageInput, signal?: AbortSignal) {
+ return request<CreationSession>(`${path(id)}/messages`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ signal,
+ })
+ },
+ cancel(id: number | string, signal?: AbortSignal) {
+ return request<CreationSession>(`${path(id)}/cancel`, {
+ method: 'POST',
+ signal,
+ })
+ },
+ retry(id: number | string, signal?: AbortSignal) {
+ return request<CreationSession>(`${path(id)}/retry`, {
+ method: 'POST',
+ signal,
+ })
+ },
+}
diff --git a/frontend/src/components/ui/CreateChoiceModal.tsx b/frontend/src/components/ui/CreateChoiceModal.tsx
index e481020..020f6ee 100644
--- a/frontend/src/components/ui/CreateChoiceModal.tsx
+++ b/frontend/src/components/ui/CreateChoiceModal.tsx
@@ -1,6 +1,7 @@
import { Link, useNavigate } from 'react-router-dom'
import { Clapperboard, PanelsTopLeft, Video } from 'lucide-react'
import { useI18n } from '../../i18n'
+import { SHORT_VIDEO_CREATE_PATH } from '../../lib/shortVideoRoutes'
import Modal from './Modal'
type Props = {
@@ -37,7 +38,7 @@ export default function CreateChoiceModal({ open, onClose }: Props) {
<strong>{t('create.canvas')}</strong>
<span className="pf-muted">{t('create.canvasHint')}</span>
</button>
- <button type="button" className="pf-create-choice-card" onClick={() => go('/studio/new')}>
+ <button type="button" className="pf-create-choice-card" onClick={() => go(SHORT_VIDEO_CREATE_PATH)}>
<span className="pf-ws-product-icon" aria-hidden>
<Video size={24} strokeWidth={1.6} />
</span>
diff --git a/frontend/src/hooks/useCreationSession.ts b/frontend/src/hooks/useCreationSession.ts
new file mode 100644
index 0000000..e49465a
--- /dev/null
+++ b/frontend/src/hooks/useCreationSession.ts
@@ -0,0 +1,156 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { creationApi, type CreationSession } from '../api/creation'
+import { isRequestAborted } from '../api/http'
+import { isCreationBusy } from '../lib/creationSession'
+
+/** 服务端持续制作;轮询只恢复界面,退出页面会取消请求但不会停止任务。 */
+export function useCreationSession(
+ sessionId: string | undefined,
+ onUnauthorized: () => void,
+) {
+ const [session, setSession] = useState<CreationSession | null>(null)
+ const [loading, setLoading] = useState(Boolean(sessionId))
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [connectionError, setConnectionError] = useState(false)
+ const current = useRef<CreationSession | null>(null)
+ const route = useRef(sessionId)
+ const revision = useRef(0)
+ const mutation = useRef<AbortController | null>(null)
+ const unauthorized = useRef(onUnauthorized)
+ unauthorized.current = onUnauthorized
+ route.current = sessionId
+
+ const accept = useCallback((value: CreationSession) => {
+ current.current = value
+ setSession(value)
+ }, [])
+
+ const report = useCallback((cause: unknown) => {
+ if (isRequestAborted(cause)) return
+ if (
+ cause &&
+ typeof cause === 'object' &&
+ 'status' in cause &&
+ cause.status === 401
+ ) {
+ unauthorized.current()
+ return
+ }
+ setError(
+ cause instanceof Error ? cause.message : '暂时无法连接,请稍后重试',
+ )
+ }, [])
+
+ useEffect(() => {
+ let disposed = false
+ let retrying = true
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let controller: AbortController | null = null
+ mutation.current?.abort()
+ mutation.current = null
+ revision.current += 1
+ setBusy(false)
+ const matching = current.current && String(current.current.id) === sessionId
+ if (!matching) {
+ current.current = null
+ setSession(null)
+ }
+ setError('')
+ setConnectionError(false)
+ setLoading(Boolean(sessionId && !matching))
+ if (!sessionId) return
+
+ async function refresh(initial = false) {
+ if (disposed) return
+ if (!initial && (!isCreationBusy(current.current) || mutation.current)) {
+ timer = setTimeout(() => {
+ void refresh()
+ }, 2000)
+ return
+ }
+ controller = new AbortController()
+ const requestRevision = revision.current
+ try {
+ const value = await creationApi.get(sessionId!, controller.signal)
+ if (!disposed && requestRevision === revision.current) {
+ accept(value)
+ setConnectionError(false)
+ setError('')
+ }
+ } catch (cause) {
+ if (disposed || isRequestAborted(cause)) return
+ const status =
+ cause && typeof cause === 'object' && 'status' in cause
+ ? Number(cause.status)
+ : 0
+ if ([401, 403, 404].includes(status)) retrying = false
+ if (status === 401) unauthorized.current()
+ else if (!current.current) report(cause)
+ else setConnectionError(true)
+ } finally {
+ if (!disposed) {
+ setLoading(false)
+ if (retrying)
+ timer = setTimeout(() => {
+ void refresh(!current.current)
+ }, 2000)
+ }
+ }
+ }
+ void refresh(true)
+ return () => {
+ disposed = true
+ controller?.abort()
+ if (timer) clearTimeout(timer)
+ }
+ }, [sessionId, accept, report])
+
+ useEffect(
+ () => () => {
+ mutation.current?.abort()
+ },
+ [],
+ )
+
+ const perform = useCallback(
+ async (operation: (signal: AbortSignal) => Promise<CreationSession>) => {
+ if (mutation.current) return null
+ const controller = new AbortController()
+ const startedAt = route.current
+ mutation.current = controller
+ revision.current += 1
+ setBusy(true)
+ setError('')
+ try {
+ const value = await operation(controller.signal)
+ if (controller.signal.aborted || startedAt !== route.current)
+ return null
+ accept(value)
+ setConnectionError(false)
+ return value
+ } catch (cause) {
+ if (!controller.signal.aborted && startedAt === route.current)
+ report(cause)
+ return null
+ } finally {
+ if (mutation.current === controller) {
+ mutation.current = null
+ if (!controller.signal.aborted) setBusy(false)
+ }
+ }
+ },
+ [accept, report],
+ )
+
+ return {
+ session,
+ loading,
+ busy,
+ error,
+ connectionError,
+ perform,
+ report,
+ clearError: () => setError(''),
+ }
+}
diff --git a/frontend/src/i18n/locales/en/pages.ts b/frontend/src/i18n/locales/en/pages.ts
index 549d28a..a33a60a 100644
--- a/frontend/src/i18n/locales/en/pages.ts
+++ b/frontend/src/i18n/locales/en/pages.ts
@@ -4,7 +4,7 @@ export const enPages = {
home: {
headlineBefore: 'Turn stories into',
headlineEm: 'films you can play',
- lede: 'AI drama from script to episodic film. AI short video from offer to storyboard to film. One studio, two ways to ship.',
+ lede: 'AI drama from script to episodic film. For short videos, start with an idea, refine the copy and storyboard, create images and narration, then compose your film.',
startCreate: 'Start creating',
browseTools: 'Browse tools',
githubCta: 'Open source · View on GitHub',
@@ -13,11 +13,14 @@ export const enPages = {
dramaFor: 'For short-drama makers',
dramaDesc: 'Generate a script from one line, lock characters and scenes, then board each episode.',
kepuTitle: 'AI Short Video',
- kepuTag: 'Lead-gen shorts',
- kepuFor: 'For brands that need leads',
- kepuDesc: 'Turn an offer into short videos you can post, then batch them through the storyboard pipeline.',
+ kepuTag: 'Step-by-step creation',
+ kepuFor: 'Start with one idea',
+ kepuDesc: 'Describe your idea, review the copy and storyboard, create images and narration, then preview and download. Each stage is ready to review and refine.',
+ templatesTitle: 'Four curated short-video styles',
+ templatesHint: '3D animation by default, with 2D anime, storybook illustration, and Chinese ink painting.',
+ templatesLoadFailed: 'Styles could not load. Try again later or start creating directly.',
howKicker: 'How it works',
- howTitle: 'Three steps to a film',
+ howTitle: 'A clear path from idea to film',
capsKicker: 'Capabilities',
capsTitle: 'What the studio actually does',
toolsKicker: 'Tools',
@@ -32,17 +35,18 @@ export const enPages = {
footBrand: 'AI drama and AI short video studio',
footNav: 'Footer',
dramaSteps: ['AI script', 'Cast & scenes', 'Episode boards', 'Export'],
- kepuSteps: ['Pick a style', 'Write boards', 'Voice & compose', 'Batch output'],
+ kepuSteps: ['Share an idea', 'Copy & storyboard', 'Images & voice', 'Compose your film'],
pipeline: [
{ step: '01', title: 'Write the idea', desc: 'A one-line story, a knowledge point, or a full script — any of these can start a project.' },
- { step: '02', title: 'Build assets', desc: 'Characters, scenes, props, and voices stay consistent across later shots.' },
- { step: '03', title: 'Board and ship', desc: 'Split episodes, cite assets, generate stills and video, then export a playable film.' },
+ { step: '02', title: 'Copy and storyboard', desc: 'Generate the copy and storyboard, then review the content, image descriptions, and narration before production.' },
+ { step: '03', title: 'Images and narration', desc: 'Generate images for each shot and model-based voice-over. Adjust or retry individual assets as needed.' },
+ { step: '04', title: 'Compose and download', desc: 'Combine image movement, narration, and subtitles into a film to preview and download.' },
],
capabilities: [
- { title: '19 film looks', desc: 'From mythic epics to urban realism and neon cyberpunk — one style carries the whole piece.' },
+ { title: 'Four short-video styles', desc: 'Choose 3D animation, 2D anime, storybook illustration, or Chinese ink painting for a consistent film.' },
{ title: 'Reusable assets', desc: 'Generate a character once, reuse it across the series instead of redrawing every shot.' },
{ title: 'Editable boards', desc: '@-mention assets, set duration and camera moves, and see the shot before you generate.' },
- { title: 'Two output paths', desc: 'Drama for episodic stories, AI short video for the storyboard pipeline — one account and one wallet.' },
+ { title: 'Create in stages, pick up anytime', desc: 'Manage projects as cards and resume saved work from copy and storyboards through assets and the finished film.' },
],
audiences: [
{ title: 'Short-drama creators', desc: 'Break a story into shootable episodes. Assets first, film second.' },
@@ -401,6 +405,10 @@ export const enPages = {
history: {
title: 'AI Short Video',
lead: 'Manage AI short video projects — keep editing or download the film.',
+ projectsHeading: 'My short videos',
+ workflowHint: 'Idea → Copy & storyboard → Images & voice → Compose',
+ selectProject: 'Select {title} for download',
+ progress: 'Production progress',
newKepu: 'New short',
goDrama: 'Go to Drama',
statTotal: 'Projects',
diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.ts
index e1d389f..67b514c 100644
--- a/frontend/src/i18n/locales/en/shell.ts
+++ b/frontend/src/i18n/locales/en/shell.ts
@@ -129,7 +129,7 @@ export const enShell = {
canvas: 'Free canvas',
canvasHint: 'Infinite canvas · images · video',
kepu: 'AI Short Video',
- kepuHint: 'Storyboard pipeline',
+ kepuHint: 'Idea · Copy & storyboard · Images & voice · Compose',
toolsFootPrefix: 'Or browse standalone tools in the',
toolsFootLink: 'tool hub',
toolsFootSuffix: '',
diff --git a/frontend/src/i18n/locales/zh/pages.ts b/frontend/src/i18n/locales/zh/pages.ts
index dc9165b..8729b05 100644
--- a/frontend/src/i18n/locales/zh/pages.ts
+++ b/frontend/src/i18n/locales/zh/pages.ts
@@ -4,7 +4,7 @@ export const zhPages = {
home: {
headlineBefore: '把故事做成',
headlineEm: '能播的片子',
- lede: 'AI 漫剧从剧本到分集成片,AI短视频从卖点到分镜成片。一套工作台,两种出片方式。',
+ lede: 'AI 漫剧从剧本到分集成片。AI短视频从想法开始,分步完善文案、分镜、画面与配音,再合成短片。',
startCreate: '开始创作',
browseTools: '浏览工具',
githubCta: '开源仓库 · 在 GitHub 查看',
@@ -13,11 +13,14 @@ export const zhPages = {
dramaFor: '给短剧创作者',
dramaDesc: '从一句话生成剧本,沉淀角色与场景,再按集分镜成片。',
kepuTitle: 'AI短视频',
- kepuTag: '获客短视频',
- kepuFor: '给要获客的品牌',
- kepuDesc: '把卖点做成可投放的短视频,选定风格后沿分镜流水线批量出片。',
+ kepuTag: '分步创作',
+ kepuFor: '从一个想法开始',
+ kepuDesc: '输入想法,生成并修改文案分镜,制作画面和配音,最后预览、下载成片。每一步都能查看和调整。',
+ templatesTitle: '四种精选短视频画风',
+ templatesHint: '默认 3D 动画,也可选择二维动漫、绘本插画或国风水墨。',
+ templatesLoadFailed: '暂时无法加载画风,请稍后重试,或直接开始创作。',
howKicker: 'How it works',
- howTitle: '三步出片',
+ howTitle: '从想法到成片,每一步都清楚',
capsKicker: 'Capabilities',
capsTitle: '工作台里真正能用的',
toolsKicker: 'Tools',
@@ -32,17 +35,18 @@ export const zhPages = {
footBrand: 'AI 漫剧与 AI短视频创作平台',
footNav: '页脚导航',
dramaSteps: ['AI 生剧本', '角色与场景', '分集分镜', '成片导出'],
- kepuSteps: ['选画面风格', '写分镜旁白', '配音与成片', '批量出片'],
+ kepuSteps: ['输入想法', '文案与分镜', '画面与配音', '合成成片'],
pipeline: [
{ step: '01', title: '写下创意', desc: '一句话故事、知识点或完整剧本,都能作为起点。' },
- { step: '02', title: '生成资产', desc: '角色、场景、道具与音色入库,后续镜头保持同一套面孔。' },
- { step: '03', title: '分镜成片', desc: '按集拆镜、引用资产、生成画面与视频,导出可播成片。' },
+ { step: '02', title: '文案与分镜', desc: '生成文案与分镜脚本,检查内容、画面描述和旁白,再进入素材制作。' },
+ { step: '03', title: '画面与配音', desc: '按分镜生成图片,使用配音模型制作旁白;需要时可单独调整和重试。' },
+ { step: '04', title: '合成与下载', desc: '将画面运镜、旁白和字幕合成短片,预览完成后下载。' },
],
capabilities: [
- { title: '19 种成片风格', desc: '从神话史诗到都市写实、赛博霓虹,选定后贯穿整部作品。' },
+ { title: '四种短视频画风', desc: '3D 动画、二维动漫、绘本插画与国风水墨,选定后贯穿整部短片。' },
{ title: '资产可复用', desc: '角色、场景、道具、音色一次生成,全剧引用,避免每镜重画。' },
{ title: '分镜可编辑', desc: '脚本里 @ 引用资产、插入时长与运镜,生成前就能看清这一镜。' },
- { title: '两条出片路径', desc: '漫剧走分集叙事,AI短视频走分镜流水线,同一套账号与积分。' },
+ { title: '分步制作,随时接续', desc: '项目以卡片集中展示,从文案、分镜到素材与成片,保存进度后继续创作。' },
],
audiences: [
{ title: '短剧创作者', desc: '把故事拆成可拍的分集,先出资产再成片。' },
@@ -394,6 +398,10 @@ export const zhPages = {
history: {
title: 'AI短视频',
lead: '管理你的 AI短视频项目,继续编辑或下载成片。',
+ projectsHeading: '我的短视频',
+ workflowHint: '输入想法 → 文案分镜 → 画面配音 → 合成成片',
+ selectProject: '选择下载 {title}',
+ progress: '制作进度',
newKepu: '新建短视频',
goDrama: '去漫剧',
statTotal: '总作品数',
diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.ts
index aa5e4e2..73d8aa4 100644
--- a/frontend/src/i18n/locales/zh/shell.ts
+++ b/frontend/src/i18n/locales/zh/shell.ts
@@ -128,7 +128,7 @@ export const zhShell = {
canvas: '自由画布',
canvasHint: '无限画布 · 图像 · 视频',
kepu: 'AI短视频',
- kepuHint: '分镜流水线出片',
+ kepuHint: '输入想法 · 文案分镜 · 画面配音 · 合成成片',
toolsFootPrefix: '也可以先去',
toolsFootLink: '工具中心',
toolsFootSuffix: '浏览独立能力',
diff --git a/frontend/src/lib/creationApiError.ts b/frontend/src/lib/creationApiError.ts
new file mode 100644
index 0000000..ba16ffc
--- /dev/null
+++ b/frontend/src/lib/creationApiError.ts
@@ -0,0 +1,9 @@
+/** 框架的通用 404 表示接口未加载;业务 404 则保留会话不存在等真实原因。 */
+export function creationApiErrorDetail(status: number, detail: unknown): unknown {
+ if (status !== 404) return detail
+ if (typeof detail === 'string' && detail.trim().toLowerCase() === 'not found')
+ return '创作服务接口尚未加载,请重启后端服务后重试。'
+ if (detail === '创作会话不存在')
+ return '创作会话不存在或已被删除,请返回我的短片或新建对话。'
+ return detail
+}
diff --git a/frontend/src/lib/creationSession.ts b/frontend/src/lib/creationSession.ts
new file mode 100644
index 0000000..e670cbb
--- /dev/null
+++ b/frontend/src/lib/creationSession.ts
@@ -0,0 +1,146 @@
+import type { CreationRun, CreationSession } from '../api/creation.ts'
+
+export const CREATION_PHASES = [
+ {
+ key: 'planning',
+ label: '创作文案',
+ description: '正在把你的想法写成适合讲述的文案',
+ },
+ {
+ key: 'script',
+ label: '编排脚本',
+ description: '正在安排镜头、旁白和画面节奏',
+ },
+ {
+ key: 'assets',
+ label: '绘制与配音',
+ description: '正在绘制动画画面,并生成旁白配音',
+ },
+ {
+ key: 'compose',
+ label: '合成短片',
+ description: '正在加入运镜、字幕和配音,合成最终视频',
+ },
+] as const
+
+const BUSY_SESSION = new Set([
+ 'thinking',
+ 'generating',
+ 'planning',
+ 'producing',
+])
+const BUSY_RUN = new Set([
+ 'pending',
+ 'queued',
+ 'running',
+ 'thinking',
+ 'generating',
+ 'planning',
+ 'producing',
+])
+
+export function activeCreationRun(
+ session: Pick<CreationSession, 'active_run_id' | 'runs'> | null,
+): CreationRun | undefined {
+ if (!session) return undefined
+ return (
+ session.runs.find(
+ (run) => String(run.id) === String(session.active_run_id),
+ ) || [...session.runs].sort((a, b) => b.version - a.version)[0]
+ )
+}
+
+export function isCreationBusy(
+ session: Pick<CreationSession, 'status' | 'runs' | 'active_run_id'> | null,
+): boolean {
+ if (!session) return false
+ if (
+ [
+ 'completed',
+ 'done',
+ 'failed',
+ 'cancelled',
+ 'drafting',
+ 'collecting',
+ ].includes(session.status)
+ )
+ return false
+ return (
+ BUSY_SESSION.has(session.status) ||
+ BUSY_RUN.has(activeCreationRun(session)?.status || '')
+ )
+}
+
+export function creationPhaseIndex(phase: string): number {
+ if (phase === 'done') return CREATION_PHASES.length
+ if (phase === 'copy') return 0
+ return Math.max(
+ 0,
+ CREATION_PHASES.findIndex((item) => item.key === phase),
+ )
+}
+
+export function creationStatusLabel(status: string): string {
+ return (
+ (
+ {
+ drafting: '构思中',
+ collecting: '构思中',
+ thinking: '正在思考',
+ planning: '正在思考',
+ generating: '制作中',
+ producing: '制作中',
+ completed: '已完成',
+ done: '已完成',
+ failed: '需要重试',
+ cancelled: '已停止',
+ } as Record<string, string>
+ )[status] || '创作中'
+ )
+}
+
+/** 同一条消息失败后重发时保留此 ID,由服务端避免重复创建与计费。 */
+export function creationMessageId(): string {
+ return (
+ globalThis.crypto?.randomUUID?.() ||
+ `msg-${Date.now()}-${Math.random().toString(36).slice(2, 12)}`
+ )
+}
+
+export type CreationSubmission = {
+ content: string
+ templateId?: string
+ sessionId?: string
+ id: string
+}
+
+/** 默认3D交给后端;只有明确选择的风格覆盖自然语言决策。 */
+export function buildCreationSubmission(options: {
+ content: string
+ selectedTemplateId: string
+ sessionId?: string
+ explicitTemplateId?: string
+ previous?: CreationSubmission | null
+}): CreationSubmission | null {
+ const content = options.content.trim()
+ if (!content) return null
+ const templateId =
+ options.explicitTemplateId ??
+ (options.sessionId || options.selectedTemplateId === 'anim_3d'
+ ? undefined
+ : options.selectedTemplateId)
+ const previous = options.previous
+ if (
+ previous &&
+ previous.content === content &&
+ previous.templateId === templateId &&
+ previous.sessionId === options.sessionId
+ )
+ return previous
+ return {
+ content,
+ templateId,
+ sessionId: options.sessionId,
+ id: creationMessageId(),
+ }
+}
diff --git a/frontend/src/lib/creationTemplates.ts b/frontend/src/lib/creationTemplates.ts
new file mode 100644
index 0000000..376e8ef
--- /dev/null
+++ b/frontend/src/lib/creationTemplates.ts
@@ -0,0 +1,56 @@
+import type { Template } from '../api'
+
+/** 新建短片的公开精选名单;历史项目仍通过 getTemplate(id) 读取原模板。 */
+export const CREATION_TEMPLATE_IDS = [
+ 'anim_3d',
+ 'soft_anime',
+ 'kids_flat',
+ 'ink_guofeng',
+] as const
+
+export const DEFAULT_CREATION_TEMPLATE_ID = CREATION_TEMPLATE_IDS[0]
+
+const PRESENTATION = {
+ anim_3d: {
+ name: '3D 动画',
+ description: '圆润的三维角色与柔和光影,适合知识讲解和故事短片。',
+ category: ['3D', '动画'],
+ },
+ soft_anime: {
+ name: '二维动漫',
+ description: '干净线稿与柔和赛璐璐色彩,适合青春故事和情感表达。',
+ category: ['二维', '动漫'],
+ },
+ kids_flat: {
+ name: '绘本插画',
+ description: '柔和粉彩与亲切的插画角色,适合儿童科普和温暖故事。',
+ category: ['绘本', '插画'],
+ },
+ ink_guofeng: {
+ name: '国风水墨',
+ description: '水墨留白与写意笔触,适合历史文化和诗意故事。',
+ category: ['国风', '水墨'],
+ },
+}
+
+export function creationTemplateId(id?: string | null): string {
+ return CREATION_TEMPLATE_IDS.find((candidate) => candidate === id)
+ ?? DEFAULT_CREATION_TEMPLATE_ID
+}
+
+/** 兼容尚未更新的服务端列表,同时保留真实素材与模型配置,不伪造可用模板。 */
+export function curatedCreationTemplates(templates: Template[]): Template[] {
+ const byId = new Map(templates.map((template) => [template.id, template]))
+ return CREATION_TEMPLATE_IDS.flatMap((id, sort_order) => {
+ const template = byId.get(id)
+ if (!template) return []
+ const presentation = PRESENTATION[id]
+ return [{
+ ...template,
+ ...presentation,
+ category: [...presentation.category],
+ default_ratio: '9:16',
+ sort_order,
+ }]
+ })
+}
diff --git a/frontend/src/lib/imageTextStoryboard.ts b/frontend/src/lib/imageTextStoryboard.ts
new file mode 100644
index 0000000..bd872e3
--- /dev/null
+++ b/frontend/src/lib/imageTextStoryboard.ts
@@ -0,0 +1,39 @@
+/** Four manual checkpoints for the image + narration short-video workflow. */
+export const IMAGE_TEXT_STEPS = [
+ { key: 'topic', label: '创作设置' },
+ { key: 'confirm', label: '文案与分镜' },
+ { key: 'assets', label: '画面与配音' },
+ { key: 'compose', label: '成片预览' },
+]
+
+type ImageTextProject = {
+ status: string
+ progress?: number
+ final_video_url?: string | null
+ shots?: Array<{ image_url?: string | null; audio_url?: string | null }>
+}
+
+export function imageTextAssetReadiness(project: ImageTextProject) {
+ const shots = project.shots || []
+ const images = shots.filter((shot) => Boolean(shot.image_url)).length
+ const audio = shots.filter((shot) => Boolean(shot.audio_url)).length
+ return { total: shots.length, images, audio, ready: shots.length > 0 && images === shots.length && audio === shots.length }
+}
+
+/** Finishing assets stays on step three until the user starts composition. */
+export function imageTextBoardStep(project: ImageTextProject): 1 | 2 | 3 {
+ if (project.final_video_url || ['COMPOSING', 'AUDITING', 'DONE'].includes(project.status)) return 3
+ const assets = imageTextAssetReadiness(project)
+ if (
+ assets.images > 0 || assets.audio > 0 ||
+ ['IMAGING', 'AUDIOING', 'IMAGE_READY', 'AUDIO_READY', 'PARALLEL_ASSETS', 'VIDEO_READY'].includes(project.status) ||
+ (assets.total > 0 && (project.progress || 0) >= 18)
+ ) return 2
+ return 1
+}
+
+export function imageTextNextAction(project: ImageTextProject): 'script' | 'assets' | 'compose' | 'preview' {
+ if (project.final_video_url) return 'preview'
+ if (!project.shots?.length) return 'script'
+ return imageTextAssetReadiness(project).ready ? 'compose' : 'assets'
+}
diff --git a/frontend/src/lib/shortVideoRoutes.ts b/frontend/src/lib/shortVideoRoutes.ts
new file mode 100644
index 0000000..aa27c7a
--- /dev/null
+++ b/frontend/src/lib/shortVideoRoutes.ts
@@ -0,0 +1,30 @@
+export const SHORT_VIDEO_LIST_PATH = '/history'
+export const SHORT_VIDEO_CREATE_PATH = '/studio/new'
+
+/** 旧书签进入卡片列表;带创作参数的链接仍直接打开对应工作区。 */
+export function legacyStudioEntryPath(params: { project?: string | null; template?: string | null; mode?: string | null }): string {
+ if (params.project && /^[1-9]\d*$/.test(params.project)) return `/studio/${params.project}`
+ if (!params.template && !params.mode) return SHORT_VIDEO_LIST_PATH
+ const query = new URLSearchParams()
+ if (params.template) query.set('template', params.template)
+ if (params.mode) query.set('mode', params.mode)
+ return `${SHORT_VIDEO_CREATE_PATH}?${query.toString()}`
+}
+
+export function shortVideoCreatePath(templateId?: string): string {
+ return templateId
+ ? `${SHORT_VIDEO_CREATE_PATH}?template=${encodeURIComponent(templateId)}`
+ : SHORT_VIDEO_CREATE_PATH
+}
+
+/** Existing creation sessions use their recovery route; regular projects open the step editor. */
+export function shortVideoProjectPath(project: {
+ id: number
+ status: string
+ creation_session_id?: number | null
+ pipeline_mode?: string | null
+}): string {
+ if (project.creation_session_id) return `/studio/sessions/${project.creation_session_id}?project=${project.id}`
+ if (project.status === 'DRAFT' && project.pipeline_mode === 'image_text') return `/studio/new?project=${project.id}`
+ return project.status === 'DRAFT' ? `/studio/${project.id}/style` : `/studio/${project.id}`
+}
diff --git a/frontend/src/lib/status.ts b/frontend/src/lib/status.ts
index 346b36c..3abc816 100644
--- a/frontend/src/lib/status.ts
+++ b/frontend/src/lib/status.ts
@@ -1,5 +1,6 @@
import { getActiveLocale } from '../i18n/detect'
import { messages } from '../i18n/messages'
+import { IMAGE_TEXT_STEPS, imageTextBoardStep } from './imageTextStoryboard'
export const RUNNING = new Set([
'SCRIPTING',
@@ -223,7 +224,7 @@ export const BOARD_STEPS = KEPU_STEPS
/** 静图成片跳过「镜头视频」步 */
export function kepuSteps(pipelineMode?: string | null) {
if (pipelineMode === 'image_text') {
- return KEPU_STEPS.filter((s) => s.key !== 'videos')
+ return IMAGE_TEXT_STEPS
}
return KEPU_STEPS
}
@@ -263,6 +264,10 @@ export function kepuStepIndex(
shots?: Array<{ image_url?: string | null; audio_url?: string | null; video_url?: string | null }>
} | null,
): number {
+ if (project?.pipeline_mode === 'image_text') {
+ if (page === 'create' || page === 'style') return 0
+ return imageTextBoardStep(project)
+ }
const steps = kepuSteps(project?.pipeline_mode)
const idx = (key: string) => {
const n = steps.findIndex((s) => s.key === key)
@@ -293,6 +298,13 @@ export function kepuPhaseHint(project: {
pipeline_mode?: string | null
shots?: Array<{ image_url?: string | null; audio_url?: string | null; video_url?: string | null }>
}): string {
+ if (project.pipeline_mode === 'image_text') {
+ if (isRunning(effectiveStatus(project))) return '当前步骤正在制作,完成后可查看结果并继续下一步。'
+ const phase = kepuBillingPhase(project)
+ if (phase === 'script') return '保存文案后生成分镜,确认每张卡片里的旁白和画面。'
+ if (phase === 'assets') return '确认分镜后生成图片与配音;已完成的素材会继续保留。'
+ return '图片与配音已齐,可以试听后合成带运镜和字幕的成片。'
+ }
if (isRunning(effectiveStatus(project))) {
return '生成进行中,可在右侧查看各阶段进度。'
}
diff --git a/frontend/src/pages/HistoryPage.tsx b/frontend/src/pages/HistoryPage.tsx
index 68f780d..0481b7e 100644
--- a/frontend/src/pages/HistoryPage.tsx
+++ b/frontend/src/pages/HistoryPage.tsx
@@ -6,17 +6,14 @@ import BillingErrorNotice from '../components/billing/BillingErrorNotice'
import AppShell from '../components/layout/AppShell'
import PillTabs from '../components/ui/PillTabs'
import Pagination from '../components/ui/Pagination'
-import StatCard from '../components/ui/StatCard'
+import { ProjectCard, ProjectGrid } from '../components/projects/ProjectCard'
import {
IconClapper,
- IconClock,
IconDownload,
IconEdit,
IconEye,
IconPlus,
- IconRefresh,
IconSearch,
- IconSend,
IconTrash,
} from '../components/ui/Icons'
import { dialog } from '../lib/dialog'
@@ -25,9 +22,12 @@ import {
triggerBlobDownload,
zipVideosClient,
} from '../lib/clientDownload'
-import { hasActiveTasks, isRunning, STATUS_CN, statusTone } from '../lib/status'
+import { hasActiveTasks, isRunning, STATUS_CN } from '../lib/status'
import { pageCountOf } from '../lib/pagination'
+import { SHORT_VIDEO_CREATE_PATH, shortVideoProjectPath } from '../lib/shortVideoRoutes'
import { formatDateTime, useI18n } from '../i18n'
+import './drama/project-list.css'
+import './shortVideoList.css'
type HistoryItem = Omit<Project, 'shots'> & {
published?: boolean
@@ -40,7 +40,8 @@ type HistoryItem = Omit<Project, 'shots'> & {
type HistoryTab = 'all' | 'draft' | 'running' | 'done' | 'published'
-const PAGE_SIZE_DEFAULT = 8
+const PAGE_SIZE_DEFAULT = 9
+const PAGE_SIZE_OPTIONS = [6, 9, 18] as const
const TAB_STATUS: Record<HistoryTab, 'all' | 'draft' | 'running' | 'done' | 'published'> = {
all: 'all',
@@ -56,15 +57,6 @@ function canDownload(p: HistoryItem) {
return p.status === 'DONE' && Boolean(p.final_video_url)
}
-function statusBadgeClass(status: string) {
- const tone = statusTone(status)
- if (tone === 'ok') return 'ok'
- if (tone === 'run') return 'run'
- if (tone === 'bad') return 'bad'
- if (status === 'DRAFT') return 'draft'
- return ''
-}
-
export default function HistoryPage() {
const nav = useNavigate()
const { t, m, locale } = useI18n()
@@ -155,7 +147,7 @@ export default function HistoryPage() {
const map: Record<string, string> = {}
for (const t of list) map[t.id] = t.name
setTemplates(map)
- })
+ }).catch(() => undefined)
}, [nav])
useEffect(() => {
@@ -278,58 +270,35 @@ export default function HistoryPage() {
}
function continueEdit(p: HistoryItem) {
- if (p.status === 'DRAFT') nav(`/studio/${p.id}/style`)
- else nav(`/studio/${p.id}`)
+ nav(shortVideoProjectPath(p))
}
return (
- <AppShell active="kepu" wide>
- <div className="pf-history-head">
- <div>
- <h1>{t('history.title')}</h1>
- <p>{t('history.lead')}</p>
- </div>
- <div className="pf-history-head-actions">
- <button type="button" className="pf-btn pf-btn-lime pf-btn-icon" onClick={() => nav('/studio/new')}>
- <IconPlus size={16} />
- {t('history.newKepu')}
- </button>
- <Link to="/drama" className="pf-btn pf-btn-ghost pf-btn-sm">
- {t('history.goDrama')}
+ <AppShell active="kepu">
+ <div className="pf-project-list-page pf-short-video-list-page">
+ <header className="pf-project-page-header">
+ <div>
+ <span className="pf-project-page-eyebrow">SHORT VIDEO STUDIO</span>
+ <h1>{t('history.title')}</h1>
+ <p>{t('history.lead')}</p>
+ </div>
+ <Link to="/templates" className="pf-btn pf-btn-ghost pf-btn-sm">
+ <IconClapper size={17} />{t('home.templatesTitle')}
</Link>
- </div>
- </div>
+ </header>
- <div className="pf-stats">
- <StatCard
- label={t('history.statTotal')}
- value={stats.total}
- trend="—"
- icon={<IconClapper size={18} />}
- />
- <StatCard
- label={t('history.statRunning')}
- value={stats.generating}
- trend={stats.generating ? t('history.runningNow') : t('history.noTask')}
- icon={<IconRefresh size={18} />}
- />
- <StatCard
- label={t('history.statDone')}
- value={stats.done}
- trend="—"
- icon={<IconSend size={18} />}
- />
- <StatCard
- label={t('history.statPublished')}
- value={stats.published}
- trend="—"
- icon={<IconClock size={18} />}
- />
- </div>
+ <section className="pf-project-list-panel" aria-label={t('history.projectsHeading')}>
+ <div className="pf-project-list-heading">
+ <div>
+ <h2>{t('history.projectsHeading')}{!loading && <span>{stats.total}</span>}</h2>
+ <p>{t('history.workflowHint')}</p>
+ </div>
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-icon" onClick={() => nav(SHORT_VIDEO_CREATE_PATH)}>
+ <IconPlus size={18} />{t('history.newKepu')}
+ </button>
+ </div>
- <div className="pf-history-layout">
- <section className="pf-history-main">
- <div className="pf-history-filters">
+ <div className="pf-project-list-toolbar">
<PillTabs
items={HISTORY_TABS.map((id) => m.history.tabs[id])}
value={m.history.tabs[tab]}
@@ -338,161 +307,73 @@ export default function HistoryPage() {
if (next) setTab(next)
}}
ariaLabel={t('history.statusAria')}
+ lime
/>
- <div className="pf-history-filter-right">
- <select
- className="pf-type-select"
- value={typeMode}
- aria-label={t('history.typeAria')}
- onChange={(e) => setTypeMode(e.target.value as '' | 'full' | 'image_text')}
- >
+ <div className="pf-short-video-filters">
+ <select className="pf-type-select" value={typeMode} aria-label={t('history.typeAria')} onChange={(e) => setTypeMode(e.target.value as '' | 'full' | 'image_text')}>
<option value="">{t('history.typeAll')}</option>
<option value="full">{t('history.typeFull')}</option>
<option value="image_text">{t('history.typeImageText')}</option>
</select>
- <label className="pf-search-field">
- <IconSearch size={15} />
- <input
- value={q}
- onChange={(e) => setQ(e.target.value)}
- placeholder={t('history.searchPlaceholder')}
- />
+ <label className="pf-project-list-search">
+ <IconSearch size={17} />
+ <input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t('history.searchPlaceholder')} aria-label={t('history.searchPlaceholder')} />
</label>
</div>
</div>
- <div className="pf-history-batch">
- <button
- type="button"
- className="pf-btn-text"
- disabled={!selectedDownloadable.length || packing}
- onClick={packSelected}
- >
+ {selectedDownloadable.length > 0 ? <div className="pf-short-video-batch">
+ <button type="button" className="pf-btn-text" disabled={packing} onClick={packSelected}>
<IconDownload size={15} />
- {packing
- ? t('history.packing', { progress: packProgress })
- : t('history.packDownload', { count: selectedDownloadable.length })}
+ {packing ? t('history.packing', { progress: packProgress }) : t('history.packDownload', { count: selectedDownloadable.length })}
</button>
- </div>
+ <button type="button" className="pf-btn-text" disabled={packing} onClick={() => setSelected(new Set())}>{t('common.cancel')}</button>
+ </div> : null}
{error ? <BillingErrorNotice message={error} /> : null}
- {loading ? <p className="pf-muted">{t('common.loading')}</p> : null}
- {!loading && total === 0 ? (
- <div className="pf-history-empty">{t('history.empty')}</div>
- ) : null}
-
- <div className="pf-project-list">
- {pageItems.map((p) => {
- const badge = statusBadgeClass(p.status)
- const ratio =
- p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')
- const tplName = templates[p.template_id] || p.template_id
- return (
- <article key={p.id} className="pf-project-card">
- <label className="pf-project-check">
- <input
- type="checkbox"
- checked={selected.has(p.id)}
- disabled={!canDownload(p)}
- onChange={() => toggle(p.id)}
- />
- </label>
- <button
- type="button"
- className="pf-project-thumb"
- onClick={() => continueEdit(p)}
- >
- {p.cover_url ? (
- <img src={api.assetUrl(p.cover_url, p.updated_at)} alt="" />
- ) : (
- <div className="ph">{t('history.noCover')}</div>
- )}
- {isRunning(p.status) ? (
- <span className="pf-thumb-progress">{p.progress}%</span>
- ) : null}
- </button>
- <div className="pf-project-info">
- <h3>
- {p.title}
- {p.published ? <span className="pf-badge ok" style={{ marginLeft: 8 }}>{t('history.published')}</span> : null}
- </h3>
- <div className="pf-project-meta">
- <span className={`pf-badge ${badge}`}>
- {STATUS_CN[p.status] || p.status}
- </span>
- <span className="pf-muted">
- {t('history.templateMeta', {
- name: tplName,
- when: formatDateTime(p.updated_at || p.created_at, locale),
- })}
- </span>
- </div>
- {isRunning(p.status) ? (
- <div className="pf-inline-meter">
- <i style={{ width: `${Math.min(100, p.progress)}%` }} />
- </div>
- ) : null}
- {p.error_msg ? <p className="pf-error pf-project-err">{p.error_msg}</p> : null}
- </div>
- <div className="pf-project-ratio">{ratio}</div>
- <div className="pf-project-actions">
- <button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}>
- <IconEdit size={14} />
- {t('history.continueEdit')}
- </button>
- <button
- type="button"
- className="pf-btn-text"
- disabled={!p.final_video_url}
- onClick={() =>
- p.final_video_url &&
- setPreview({
- url: api.assetUrl(p.final_video_url, p.updated_at),
- title: p.title,
- projectId: p.id,
- })
- }
- >
- <IconEye size={14} />
- {t('common.preview')}
- </button>
- <button
- type="button"
- className="pf-btn-text"
- disabled={!canDownload(p) || busyId === p.id || packing}
- onClick={() => downloadOne(p)}
- >
- <IconDownload size={14} />
- {busyId === p.id ? t('common.downloading') : t('common.download')}
- </button>
- <button
- type="button"
- className="pf-icon-btn danger"
- disabled={busyId === p.id}
- title={t('common.delete')}
- onClick={() => remove(p.id)}
- >
- <IconTrash size={16} />
- </button>
- </div>
- </article>
- )
- })}
- </div>
-
+ {loading ? (
+ <div aria-busy="true" aria-label={t('common.loading')}><ProjectGrid>{Array.from({ length: 6 }, (_, i) => <div key={i} className="pf-project-list-skeleton" aria-hidden />)}</ProjectGrid></div>
+ ) : total === 0 ? (
+ <div className="pf-empty-state">
+ <div className="pf-empty-illust" aria-hidden><IconClapper size={42} /></div>
+ <p className="pf-muted">{t('history.empty')}</p>
+ <button type="button" className="pf-btn pf-btn-lime" onClick={() => nav(SHORT_VIDEO_CREATE_PATH)}><IconPlus size={17} />{t('history.newKepu')}</button>
+ </div>
+ ) : (
+ <ProjectGrid>
+ {pageItems.map((p) => {
+ const running = isRunning(p.status) || hasActiveTasks(p)
+ const ratio = p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9')
+ const tplName = templates[p.template_id] || p.template_id
+ return <ProjectCard
+ key={p.id}
+ kind="short-video"
+ title={p.title}
+ coverUrl={p.cover_url ? api.assetUrl(p.cover_url, p.updated_at) : undefined}
+ category={`${tplName} · ${ratio}`}
+ status={{ label: STATUS_CN[p.status] || p.status, tone: p.status === 'DONE' ? 'completed' : running ? 'producing' : p.status === 'DRAFT' ? 'draft' : 'neutral' }}
+ description={p.source_text || t('history.workflowHint')}
+ progress={running ? { label: t('history.progress'), value: Math.max(0, Math.min(100, p.progress)), total: 100 } : undefined}
+ meta={p.error_msg ? <span className="pf-error" role="status">{p.error_msg}</span> : undefined}
+ footer={<>
+ <span>{p.published ? t('history.published') : (p.pipeline_mode === 'image_text' ? t('history.typeImageText') : t('history.typeFull'))}</span>
+ <time dateTime={p.updated_at || p.created_at}>{formatDateTime(p.updated_at || p.created_at, locale)}</time>
+ </>}
+ selection={canDownload(p) ? { checked: selected.has(p.id), visible: selected.size > 0, onChange: () => toggle(p.id), label: t('history.selectProject', { title: p.title }) } : undefined}
+ onOpen={() => continueEdit(p)}
+ openLabel={`${t('history.continueEdit')} ${p.title}`}
+ menu={<button type="button" className="pf-icon-btn danger" disabled={busyId === p.id} title={t('common.delete')} aria-label={`${t('common.delete')} ${p.title}`} onClick={() => remove(p.id)}><IconTrash size={16} /></button>}
+ actions={<>
+ <button type="button" className="pf-btn-text" onClick={() => continueEdit(p)}><IconEdit size={14} />{t('history.continueEdit')}</button>
+ <button type="button" className="pf-btn-text" disabled={!p.final_video_url} onClick={() => p.final_video_url && setPreview({ url: api.assetUrl(p.final_video_url, p.updated_at), title: p.title, projectId: p.id })}><IconEye size={14} />{t('common.preview')}</button>
+ <button type="button" className="pf-btn-text" disabled={!canDownload(p) || busyId === p.id || packing} onClick={() => downloadOne(p)}><IconDownload size={14} />{busyId === p.id ? t('common.downloading') : t('common.download')}</button>
+ </>}
+ />
+ })}
+ </ProjectGrid>
+ )}
{total > 0 ? (
- <Pagination
- page={page}
- pageCount={pageCount}
- total={total}
- pageSize={pageSize}
- onPageSizeChange={(size) => {
- setPageSize(size)
- setPage(1)
- }}
- onChange={setPage}
- ariaLabel={t('history.pagination')}
- />
+ <Pagination page={page} pageCount={pageCount} total={total} pageSize={pageSize} pageSizeOptions={PAGE_SIZE_OPTIONS} onPageSizeChange={(size) => { setPageSize(size); setPage(1) }} onChange={setPage} ariaLabel={t('history.pagination')} />
) : null}
</section>
</div>
diff --git a/frontend/src/pages/HomePage.tsx b/frontend/src/pages/HomePage.tsx
index 4cf0e9c..9f93a64 100644
--- a/frontend/src/pages/HomePage.tsx
+++ b/frontend/src/pages/HomePage.tsx
@@ -1,5 +1,5 @@
/** PRINTFILM 官网首页:产品主张、漫剧/科普入口、成片流程与工具 */
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { ArrowRight } from 'lucide-react'
import AppShell from '../components/layout/AppShell'
@@ -11,16 +11,30 @@ import { useI18n } from '../i18n'
import { getDramaImageStylePreviewUrl } from '../lib/dramaImageStylePreviews'
import { GITHUB_REPO_URL } from '../lib/siteLinks'
import { PRODUCT_ICONS, localizeToolDefs } from '../lib/toolsCatalog'
+import { api, type Template } from '../api'
+import { SHORT_VIDEO_LIST_PATH, shortVideoCreatePath } from '../lib/shortVideoRoutes'
export default function HomePage() {
const nav = useNavigate()
const { t, m } = useI18n()
const loggedIn = Boolean(localStorage.getItem('token'))
const [createOpen, setCreateOpen] = useState(false)
+ const [templates, setTemplates] = useState<Template[]>([])
+ const [templatesError, setTemplatesError] = useState(false)
const DramaIcon = PRODUCT_ICONS.drama
const KepuIcon = PRODUCT_ICONS.kepu
const tools = localizeToolDefs(m)
+ useEffect(() => {
+ let active = true
+ api.templates().then((items) => {
+ if (active) setTemplates(items)
+ }).catch(() => {
+ if (active) setTemplatesError(true)
+ })
+ return () => { active = false }
+ }, [])
+
// 未登录去登录;已登录弹出产品选择
function goCreate() {
if (!loggedIn) {
@@ -73,7 +87,7 @@ export default function HomePage() {
<figcaption>{t('home.dramaTitle')}</figcaption>
</figure>
<figure className="pf-land-frame is-kepu">
- <img src={getDramaImageStylePreviewUrl('neon-cyberpunk-film')} alt="" />
+ <img src={api.assetUrl(templates[0]?.preview_cover || '/static/templates/covers/anim_3d.png')} alt="" />
<figcaption>{t('home.kepuTitle')}</figcaption>
</figure>
</div>
@@ -98,7 +112,7 @@ export default function HomePage() {
<ArrowRight size={16} strokeWidth={2} />
</span>
</button>
- <button type="button" className="pf-land-product is-kepu" onClick={() => goAuthOr('/studio/new')}>
+ <button type="button" className="pf-land-product is-kepu" onClick={() => goAuthOr(SHORT_VIDEO_LIST_PATH)}>
<span className="pf-land-product-icon" aria-hidden>
<KepuIcon size={26} strokeWidth={1.6} />
</span>
@@ -121,6 +135,31 @@ export default function HomePage() {
</button>
</section>
+ <section className="pf-land-caps" aria-labelledby="pf-land-templates-title">
+ <header className="pf-land-section-head">
+ <p className="pf-land-kicker">Styles</p>
+ <h2 id="pf-land-templates-title">{t('home.templatesTitle')}</h2>
+ <p className="pf-muted">{t('home.templatesHint')}</p>
+ </header>
+ <div className="pf-template-grid">
+ {templates.map((template) => (
+ <button
+ key={template.id}
+ type="button"
+ className="pf-template-card"
+ onClick={() => goAuthOr(shortVideoCreatePath(template.id))}
+ >
+ <img src={api.assetUrl(template.preview_cover)} alt="" loading="lazy" />
+ <div className="body">
+ <h3>{template.name}</h3>
+ <p>{template.description}</p>
+ </div>
+ </button>
+ ))}
+ </div>
+ {templatesError ? <p className="pf-muted">{t('home.templatesLoadFailed')}</p> : null}
+ </section>
+
<section className="pf-land-pipeline" aria-labelledby="pf-land-pipeline-title">
<header className="pf-land-section-head">
<p className="pf-land-kicker">{t('home.howKicker')}</p>
@@ -221,7 +260,7 @@ export default function HomePage() {
</div>
<nav className="pf-land-foot-nav" aria-label={t('home.footNav')}>
<Link to="/drama">{t('nav.drama')}</Link>
- <Link to="/history">{t('nav.kepu')}</Link>
+ <Link to={SHORT_VIDEO_LIST_PATH}>{t('nav.kepu')}</Link>
<Link to="/method">{t('home.methodLink')}</Link>
<Link to="/tools">{t('nav.tools')}</Link>
<Link to="/pricing">{t('nav.pricing')}</Link>
diff --git a/frontend/src/pages/StudioPage.tsx b/frontend/src/pages/StudioPage.tsx
index 6399a3d..691eed2 100644
--- a/frontend/src/pages/StudioPage.tsx
+++ b/frontend/src/pages/StudioPage.tsx
@@ -1,19 +1,8 @@
import { Navigate, useSearchParams } from 'react-router-dom'
+import { legacyStudioEntryPath } from '../lib/shortVideoRoutes'
-/** Legacy `/studio` entry — redirect to multi-step routes. */
+/** 旧短视频首页也进入项目卡片列表,明确的新建/项目链接保留。 */
export default function StudioPage() {
const [params] = useSearchParams()
- const project = params.get('project')
- const template = params.get('template')
- const mode = params.get('mode')
-
- if (project) {
- return <Navigate to={`/studio/${project}`} replace />
- }
-
- const q = new URLSearchParams()
- if (template) q.set('template', template)
- if (mode) q.set('mode', mode)
- const qs = q.toString()
- return <Navigate to={qs ? `/studio/new?${qs}` : '/studio/new'} replace />
+ return <Navigate to={legacyStudioEntryPath({ project: params.get('project'), template: params.get('template'), mode: params.get('mode') })} replace />
}
diff --git a/frontend/src/pages/TemplatesPage.tsx b/frontend/src/pages/TemplatesPage.tsx
index 239b105..6be81e8 100644
--- a/frontend/src/pages/TemplatesPage.tsx
+++ b/frontend/src/pages/TemplatesPage.tsx
@@ -4,14 +4,12 @@ import { api } from '../api'
import type { Template } from '../api'
import BillingErrorNotice from '../components/billing/BillingErrorNotice'
import AppShell from '../components/layout/AppShell'
-import PillTabs from '../components/ui/PillTabs'
-import { CATEGORY_ORDER, HOME_CATEGORY_LABELS } from '../lib/categories'
+import { shortVideoCreatePath } from '../lib/shortVideoRoutes'
export default function TemplatesPage() {
const nav = useNavigate()
const [templates, setTemplates] = useState<Template[]>([])
const [error, setError] = useState('')
- const [category, setCategory] = useState('全部')
const [q, setQ] = useState('')
useEffect(() => {
@@ -21,26 +19,8 @@ export default function TemplatesPage() {
.catch((e) => setError(String(e.message || e)))
}, [])
- const categoryKeys = useMemo(() => {
- const found = new Set<string>()
- for (const t of templates) {
- for (const c of t.category || []) {
- if (CATEGORY_ORDER.includes(c)) found.add(c)
- }
- }
- return ['全部', ...CATEGORY_ORDER.filter((c) => found.has(c))]
- }, [templates])
-
- const categoryLabels = categoryKeys.map((k) => HOME_CATEGORY_LABELS[k] || k)
- const labelToKey = useMemo(() => {
- const m = new Map<string, string>()
- for (const k of categoryKeys) m.set(HOME_CATEGORY_LABELS[k] || k, k)
- return m
- }, [categoryKeys])
-
const filtered = useMemo(() => {
let list = templates
- if (category !== '全部') list = list.filter((t) => (t.category || []).includes(category))
if (q.trim()) {
const s = q.trim().toLowerCase()
list = list.filter(
@@ -48,14 +28,11 @@ export default function TemplatesPage() {
)
}
return list
- }, [templates, category, q])
+ }, [templates, q])
function openTemplate(t: Template) {
- if (!localStorage.getItem('token')) {
- nav('/auth')
- return
- }
- nav(`/studio/new?template=${t.id}`)
+ const path = shortVideoCreatePath(t.id)
+ nav(localStorage.getItem('token') ? path : `/auth?next=${encodeURIComponent(path)}`)
}
return (
@@ -63,7 +40,7 @@ export default function TemplatesPage() {
<div className="pf-section-head">
<div>
<h2>模板库</h2>
- <p>为科普与知识短片挑选画面语言</p>
+ <p>四种精选动画与插画风格,从想法、文案分镜到画面配音,分步完成短片。默认使用 3D 动画。</p>
</div>
</div>
<div className="pf-search" style={{ maxWidth: 420, marginBottom: '1rem' }}>
@@ -73,12 +50,6 @@ export default function TemplatesPage() {
placeholder="搜索模板名称或描述"
/>
</div>
- <PillTabs
- items={categoryLabels}
- value={HOME_CATEGORY_LABELS[category] || category}
- onChange={(label) => setCategory(labelToKey.get(label) || '全部')}
- ariaLabel="模板分类"
- />
{error ? <BillingErrorNotice message={error} /> : null}
<div className="pf-template-grid" style={{ marginTop: '1rem' }}>
{filtered.map((t) => (
diff --git a/frontend/src/pages/shortVideoList.css b/frontend/src/pages/shortVideoList.css
new file mode 100644
index 0000000..ac72229
--- /dev/null
+++ b/frontend/src/pages/shortVideoList.css
@@ -0,0 +1,16 @@
+.pf-short-video-list-page { margin-inline: auto; }
+.pf-short-video-list-page .pf-pill-tabs { flex-wrap: wrap; gap: 7px; }
+.pf-short-video-filters { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
+.pf-short-video-filters .pf-type-select { min-height: 43px; border-radius: 10px; }
+.pf-short-video-filters .pf-project-list-search { width: 240px; }
+.pf-short-video-batch { display: flex; justify-content: space-between; gap: 16px; margin: -6px 0 20px; padding: 12px 16px; border: 1px solid #dce8bf; border-radius: 10px; background: #f5f9ed; }
+.pf-shared-project-card--short-video .pf-shared-project-cover { background: radial-gradient(ellipse at 85% 0%, #e2d8ac 0%, transparent 60%), linear-gradient(145deg, #788257, #35412b); }
+.pf-shared-project-card--short-video .pf-shared-project-actions { justify-content: space-between; flex-wrap: wrap; gap: 9px; padding: 0 8px 3px; }
+.pf-shared-project-card--short-video .pf-shared-project-actions .pf-btn-text { min-height: 30px; font-size: 12px; }
+.pf-shared-project-card--short-video .pf-shared-project-menu .pf-icon-btn { width: 30px; height: 30px; border: 1px solid #ffffff66; border-radius: 8px; background: #fffffff0; color: #7a786e; }
+.pf-shared-project-card--short-video .pf-shared-project-menu .pf-icon-btn:hover { background: #fff4f0; color: #a74f3e; }
+.pf-shared-project-card--short-video .pf-shared-project-meta .pf-error { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
+@media (max-width: 760px) {
+ .pf-short-video-filters { width: 100%; }
+ .pf-short-video-filters .pf-project-list-search { flex: 1; width: auto; min-width: 150px; }
+}
diff --git a/frontend/src/pages/studio/CreateProjectPage.tsx b/frontend/src/pages/studio/CreateProjectPage.tsx
index dbee8b4..4125695 100644
--- a/frontend/src/pages/studio/CreateProjectPage.tsx
+++ b/frontend/src/pages/studio/CreateProjectPage.tsx
@@ -1,516 +1,248 @@
-import { useEffect, useMemo, useState } from 'react'
-import { useNavigate, useSearchParams } from 'react-router-dom'
-import { api, defaultsFromTemplate } from '../../api'
-import type { Template } from '../../api'
-import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
+import { useEffect, useRef, useState, type FormEvent } from 'react'
+import { Link, useNavigate, useSearchParams } from 'react-router-dom'
+import { ArrowLeft, ArrowRight, Check, Clapperboard, Clock3, LoaderCircle, Save, Sparkles } from 'lucide-react'
+import { api, type Project, type Template, type VoicePreset } from '../../api'
import AppShell from '../../components/layout/AppShell'
+import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
+import Button from '../../components/ui/Button'
import Stepper from '../../components/ui/Stepper'
-import PillTabs from '../../components/ui/PillTabs'
-import { IconChevronLeft, IconRefresh, IconSparkles } from '../../components/ui/Icons'
-import { CATEGORY_ORDER } from '../../lib/categories'
-import { kepuStepIndex, kepuSteps } from '../../lib/status'
-
-type Inspiration = {
- title: string
- theme: string
- script: string
-}
-
-const INSPIRATION_POOL: Inspiration[] = [
- {
- title: '到店打卡怎么拍',
- theme: '把一家本地店的卖点做成抖音获客口播:前3秒钩子、场景、1-2个体验、到店号召。只写已知事实。',
- script:
- '路过这条街十次,这次才走进去。\n\n' +
- '店面不大,招牌清楚,位置就在地铁口附近。\n\n' +
- '我点了他们家主打那一项,口感按我自己的感受来:味道正、上桌快。\n\n' +
- '想试的话,按店里现有套餐自己看,别听绝对化承诺。',
- },
- {
- title: '闺蜜安利一篇笔记',
- theme: '小红书获客安利:钩子标题、第一印象、分点真实体验、推荐给谁。卖点只作客观陈述。',
- script:
- '本来只是路过,结果在店里坐了很久。\n\n' +
- '第一印象是光线干净、座位不挤。\n\n' +
- '我点了招牌,份量如实说;环境安静,适合聊天。\n\n' +
- '更适合想慢慢坐的人;赶时间的可以先看套餐再决定。',
- },
- {
- title: '口碑拆解给决策',
- theme: '点评式获客讲解:总体评价、环境服务、推荐项带理由、性价比、适合谁。没写的价格不要猜。',
- script:
- '总体感受:干净、流程清楚,适合第一次来的人。\n\n' +
- '环境通透,服务员会主动说明怎么选。\n\n' +
- '推荐他们家主打项目,理由是我当场体验过、步骤好懂。\n\n' +
- '人均以店内公示为准。带朋友来比一个人更合适。',
- },
- {
- title: '熟人圈轻推荐',
- theme: '朋友圈获客短片:一句真实感受、一个具体细节、一句轻推荐。克制,不像广告。',
- script:
- '今天路过顺路坐了一会儿,比想象中安静。\n\n' +
- '窗边那张桌子有自然光,适合歇脚。\n\n' +
- '你们要是附近,可以自己去看看。',
- },
- {
- title: '黑洞是如何形成的',
- theme: '黑洞是如何形成的?用通俗方式讲清恒星坍缩、事件视界与时空弯曲,面向中学生。',
- script:
- '夜空里最神秘的天体之一,就是黑洞。\n\n' +
- '当一颗足够大的恒星燃料烧尽,核心会在引力下剧烈坍缩,密度高到连光都逃不出去,事件视界就此诞生。\n\n' +
- '它不是宇宙吸尘器,而是时空被严重弯曲的区域。靠近它,时间流逝也会变得奇怪。\n\n' +
- '记住:质量够大、坍缩够猛,黑洞就会出现。下一次看科普新闻,你就能分清传说与科学。',
- },
- {
- title: '为什么天空是蓝色的',
- theme: '为什么天空是蓝色的?用瑞利散射解释阳光、空气分子与傍晚火烧云,适合科普入门。',
- script:
- '抬头一看,白天的天空常常是蓝的,这是巧合吗?\n\n' +
- '阳光看起来发白,其实包含多种颜色。空气分子对蓝光散射更强,蓝光更容易被「弹」向四面八方,于是我们眼里的天空偏蓝。\n\n' +
- '早晚太阳更低,光穿过更厚大气,蓝光散得更干净,剩下的红橙光就染红了天边。\n\n' +
- '所以天空的颜色,是光与空气的一场合作。',
- },
- {
- title: 'AI 如何改变生活',
- theme: 'AI 如何改变生活:从推荐、语音助手到医疗影像,讲清便利与需要警惕的偏见。',
- script:
- '打开手机,推荐视频、导航路线、语音助手——人工智能已经悄悄进了日常。\n\n' +
- '它擅长从海量数据里找规律:帮医生看影像线索,帮工厂预判故障,也帮你把搜索变成对话。\n\n' +
- '但 AI 不是魔法。数据有偏见,模型会犯错,隐私也需要边界。真正有用的,是把 AI 当工具,而不是当权威。\n\n' +
- '理解它能做什么、不能做什么,你才能用得更聪明。',
- },
- {
- title: '火星上的一天',
- theme: '火星上的一天长什么样?对比地球日长、气温、沙尘与人类基地想象,做成场景化科普。',
- script:
- '想象你在火星醒来:太阳更远更小,天空偏奶油色,一天大约 24 小时 39 分钟。\n\n' +
- '白天可能「温暖」到零下,夜晚更冷。薄薄的二氧化碳大气留不住热量,沙尘暴偶尔遮天。\n\n' +
- '科学家仍在规划基地:要防辐射、造氧气、种食物。火星不是第二地球,却是最近的外太空课堂。\n\n' +
- '了解火星的一天,就是在预习人类下一次远行。',
- },
- {
- title: '梦的力量',
- theme: '梦的力量:睡眠周期、快速眼动与记忆整理,用故事讲清做梦如何帮助大脑「复盘」。',
- script:
- '你睡着以后,大脑并没有下班。\n\n' +
- '进入快速眼动睡眠时,大脑像在回放白天的片段,拼接成奇幻的梦。科学家认为,这有助于整理记忆、调节情绪。\n\n' +
- '睡不够,注意力和创造力都会打折;规律睡眠,则像给大脑做夜间维护。\n\n' +
- '下次做怪梦,别只觉得荒唐——那可能是大脑在加班学习。',
- },
- {
- title: '一只流浪猫的春天',
- theme: '一只流浪猫的春天:用拟人旁白讲城市生态、投喂边界与人宠共处,温暖向科普叙事。',
- script:
- '春天来了,巷口的橘猫开始换毛,也开始寻找更安全的角落。\n\n' +
- '城市里的流浪动物,靠的是残存野性与人类不经意的善意。科学投喂、绝育与尊重距离,比冲动更重要。\n\n' +
- '它们不是风景,也不是麻烦,而是城市生态的一部分。\n\n' +
- '这个春天,愿每一只猫,都能遇见更稳妥的明天。',
- },
- {
- title: '光合作用的秘密',
- theme: '光合作用的秘密:叶子如何把阳光变成糖,讲清叶绿体、能量转化与地球氧气来源。',
- script:
- '绿叶不只是装饰,它们是地球上最安静的化工厂。\n\n' +
- '叶绿体抓住阳光,把水和二氧化碳做成糖,并释放氧气。没有这个过程,绝大多数食物链都会断裂。\n\n' +
- '你呼吸的氧气、餐桌上的米饭和蔬菜,都间接来自这场光的魔法。\n\n' +
- '看懂光合作用,就看懂了生命运转的底层账本。',
- },
- {
- title: '地震来了怎么办',
- theme: '地震来了怎么办:用场景教学讲清震前准备、避险姿势与谣言辨别,实用安全科普。',
- script:
- '地面突然晃起来,第一反应往往是慌。\n\n' +
- '正确做法是就近伏地、掩护、抓稳,远离窗户与高架物;不要一窝蜂挤电梯。提前准备应急包,比临时抱佛脚更管用。\n\n' +
- '震后还要警惕余震和谣言。权威信息、互助秩序,才是真正的安全感。\n\n' +
- '懂一点地震知识,关键时刻就能多一分从容。',
- },
- {
- title: '咖啡因如何提神',
- theme: '咖啡因如何提神:腺苷受体、耐受与睡眠代价,帮上班族科学喝咖啡。',
- script:
- '困的时候来杯咖啡,真的是「叫醒大脑」吗?\n\n' +
- '咖啡因会抢占腺苷的位置,让你暂时感觉不困。但它不能替代睡眠,下午喝太多,夜里更容易翻来覆去。\n\n' +
- '逐渐耐受后,同样一杯效果会变弱。更聪明的用法是:需要专注时再用,并给睡眠留窗口。\n\n' +
- '提神可以靠咖啡,恢复还是得靠睡。',
- },
- {
- title: '塑料去哪了',
- theme: '塑料去哪了:微塑料、海洋环流与可替代材料,做成环保主题科普短片。',
- script:
- '扔掉的塑料袋,真的消失了吗?\n\n' +
- '多数只是被撕成更小的碎片。微塑料进入河流与海洋,再进入食物链,最终可能回到我们的餐桌。\n\n' +
- '减少一次性塑料、做好分类、推动更好的材料,比事后清理便宜得多。\n\n' +
- '问「塑料去哪了」,其实是在问:我们愿为未来留什么。',
- },
- {
- title: '疫苗为什么有效',
- theme: '疫苗为什么有效:用「预演」比喻讲清抗原、抗体与群体免疫,澄清常见误解。',
- script:
- '疫苗不是药,更像给免疫系统发的预告片。\n\n' +
- '它让身体提前认识病原体的关键特征,真正遇到时能更快调动抗体。这不是改写基因,而是训练记忆。\n\n' +
- '足够多人获得保护,传播链会被削弱,这就是群体免疫的意义。\n\n' +
- '科学接种,是把自己和身边人一起放进更安全的网络。',
- },
- {
- title: '潮汐的涨落',
- theme: '潮汐为何涨落:月球引力、离心效应与大潮小潮,海边场景化讲解。',
- script:
- '海边的人最懂:水位会按时涨、按时退。\n\n' +
- '主要推手是月球的引力,太阳也来凑热闹。地球、月球、太阳排成一线时,潮差更大,就是大潮。\n\n' +
- '潮汐还影响航行、发电甚至生物节律。抬头看月亮,脚下的海也在回应。\n\n' +
- '涨落之间,是天地引力的可见痕迹。',
- },
-]
+import { creationTemplateId } from '../../lib/creationTemplates'
+import { IMAGE_TEXT_STEPS } from '../../lib/imageTextStoryboard'
+import { isRunning } from '../../lib/status'
+import { dialog } from '../../lib/dialog'
+import './shortVideoCreate.css'
-const PAGE_SIZE = 6
-
-function isDefaultTitle(value: string) {
- const t = value.trim()
- return !t || t === '未命名作品'
-}
-
-function deriveTitle(text: string) {
- const line = text
- .trim()
- .split(/\n/)[0]
- .replace(/["""'']/g, '')
- .replace(/[。!?!?::].*$/, '')
- .trim()
- if (!line) return '未命名作品'
- return line.slice(0, 18)
-}
+const EXAMPLES = ['给小学生讲讲为什么天空是蓝色的', '一只胆小的小猫在雨天遇见新朋友', '用轻松的方式介绍二十四节气里的霜降']
export default function CreateProjectPage() {
const nav = useNavigate()
const [params] = useSearchParams()
+ const editId = Number(params.get('project')) || null
+ const requestedTemplate = creationTemplateId(params.get('template'))
const [templates, setTemplates] = useState<Template[]>([])
- const [templateId, setTemplateId] = useState(params.get('template') || '')
- const [category, setCategory] = useState('全部')
- const [q, setQ] = useState('')
- const [inputTab, setInputTab] = useState('一句话主题')
- const [sourceText, setSourceText] = useState(INSPIRATION_POOL[0].theme)
- const [title, setTitle] = useState(INSPIRATION_POOL[0].title)
- const [titleTouched, setTitleTouched] = useState(false)
- const [inspPage, setInspPage] = useState(0)
- const [busy, setBusy] = useState(false)
- const [aiBusy, setAiBusy] = useState(false)
+ const [voices, setVoices] = useState<VoicePreset[]>([])
+ const [project, setProject] = useState<Project | null>(null)
+ const [templateId, setTemplateId] = useState(requestedTemplate)
+ const [ratio, setRatio] = useState('9:16')
+ const [duration, setDuration] = useState(60)
+ const [voice, setVoice] = useState('')
+ const [mode, setMode] = useState<'idea' | 'copy'>('idea')
+ const [idea, setIdea] = useState('')
+ const [copy, setCopy] = useState('')
+ const [title, setTitle] = useState('')
+ const [step, setStep] = useState(0)
+ const [loading, setLoading] = useState(Boolean(editId))
+ const [busy, setBusy] = useState('')
const [error, setError] = useState('')
+ const [voiceError, setVoiceError] = useState(false)
+ const working = useRef(false)
+ const savedProject = useRef<Project | null>(null)
+ const mounted = useRef(true)
useEffect(() => {
+ mounted.current = true
+ return () => { mounted.current = false }
+ }, [])
+ useEffect(() => {
+ let disposed = false
if (!localStorage.getItem('token')) {
- nav('/auth')
+ nav(`/auth?next=${encodeURIComponent('/studio/new' + (editId ? `?project=${editId}` : ''))}`, { replace: true })
return
}
- api.me().catch(() => nav('/auth'))
- api.templates().then((list) => {
- setTemplates(list)
- const fromUrl = params.get('template') || ''
- setTemplateId((prev) => prev || fromUrl || list[0]?.id || '')
- })
- }, [nav, params])
-
- const categories = useMemo(() => {
- const found = new Set<string>()
- for (const t of templates) {
- for (const c of t.category || []) {
- if (CATEGORY_ORDER.includes(c)) found.add(c)
- }
+ api.templates().then(rows => { if (!disposed) setTemplates(rows) }).catch(cause => { if (!disposed) setError(cause.message || '模板加载失败') })
+ api.voices().then(rows => { if (!disposed) setVoices(rows) }).catch(() => { if (!disposed) setVoiceError(true) })
+ return () => { disposed = true }
+ }, [nav, editId])
+ useEffect(() => {
+ let disposed = false
+ if (!editId) {
+ savedProject.current = null
+ setProject(null)
+ setLoading(false)
+ setTemplateId(requestedTemplate)
+ setRatio('9:16')
+ setDuration(60)
+ setVoice('')
+ setMode('idea')
+ setIdea('')
+ setCopy('')
+ setTitle('')
+ setStep(0)
+ return
}
- return ['全部', '热门推荐', ...CATEGORY_ORDER.filter((c) => found.has(c))]
- }, [templates])
-
- const filtered = useMemo(() => {
- let list = templates
- if (category === '热门推荐') list = [...templates].sort((a, b) => a.sort_order - b.sort_order).slice(0, 8)
- else if (category !== '全部') list = list.filter((t) => (t.category || []).includes(category))
- if (q.trim()) {
- const s = q.trim().toLowerCase()
- list = list.filter((t) => t.name.toLowerCase().includes(s))
+ // 新建后更新 URL 时,保留当前输入与文案。
+ if (savedProject.current?.id === editId) return
+ setLoading(true)
+ api.getProject(editId).then(value => {
+ if (disposed) return
+ if (value.creation_session_id) {
+ nav(`/studio/sessions/${value.creation_session_id}?project=${value.id}`, { replace: true })
+ return
+ }
+ savedProject.current = value
+ setProject(value)
+ setTemplateId(creationTemplateId(value.template_id))
+ setRatio(value.output_ratio || '9:16')
+ setDuration(value.target_duration_sec || 60)
+ setVoice(value.voice_id || '')
+ setTitle(value.title)
+ setIdea(value.source_text)
+ if (value.source_type === 'script') {
+ setCopy(value.source_text)
+ setMode('copy')
+ setStep(1)
+ } else setStep(0)
+ }).catch(cause => { if (!disposed) setError(cause.message || '项目加载失败') })
+ .finally(() => { if (!disposed) setLoading(false) })
+ return () => { disposed = true }
+ }, [editId, requestedTemplate, nav])
+
+ const selectedTemplate = templates.find(item => item.id === templateId)
+ const running = Boolean(project && (isRunning(project.status) || project.active_tasks?.some(task => ['pending', 'leased', 'running', 'awaiting_poll', 'awaiting_review', 'cancel_requested'].includes(task.status))))
+ const disabled = Boolean(busy || loading || running)
+ function payload(text: string, name: string) {
+ return {
+ template_id: templateId, title: name.trim().slice(0, 200) || text.trim().slice(0, 30),
+ source_type: 'script' as const, source_text: text.trim(),
+ pipeline_mode: 'image_text' as const, resolution_mode: 'hd' as const,
+ output_ratio: ratio, target_duration_sec: duration, voice_id: voice,
}
- return list
- }, [templates, category, q])
-
- const selected = templates.find((t) => t.id === templateId)
- const sourceType = inputTab === '粘贴完整文案' ? 'script' : 'theme'
- const inspTotal = Math.ceil(INSPIRATION_POOL.length / PAGE_SIZE)
- const inspirations = INSPIRATION_POOL.slice(inspPage * PAGE_SIZE, inspPage * PAGE_SIZE + PAGE_SIZE)
-
- // 把灵感示例填进主题/文案,并同步短标题
- function applyInspiration(item: Inspiration) {
- if (sourceType === 'script') {
- setInputTab('粘贴完整文案')
- setSourceText(item.script.slice(0, 8000))
- } else {
- setInputTab('一句话主题')
- setSourceText(item.theme.slice(0, 100))
+ }
+ const draftFields = payload(copy, title)
+ const draftChanged = Boolean(project && (
+ project.title !== draftFields.title || project.source_text !== draftFields.source_text ||
+ project.template_id !== templateId || project.output_ratio !== ratio ||
+ (project.target_duration_sec || 60) !== duration || (project.voice_id || '') !== voice
+ ))
+ const canSaveDraft = !project?.shots.length && !project?.final_video_url
+ async function createDraft(text: string, name: string) {
+ if (savedProject.current) return savedProject.current
+ const value = await api.createProject(payload(text, name))
+ savedProject.current = value
+ if (mounted.current) {
+ setProject(value)
+ nav(`/studio/new?project=${value.id}`, { replace: true })
}
- setTitle(item.title.slice(0, 24))
- setTitleTouched(false)
- setError('')
+ return value
}
-
- function shuffleInspirations() {
- setInspPage((p) => (p + 1) % inspTotal)
+ async function saveDraft(text: string, name: string) {
+ const old = savedProject.current
+ if (!old) return createDraft(text, name)
+ // Existing generated assets are changed only after the explicit restart confirmation.
+ if (old.shots.length || old.final_video_url) return old
+ const value = await api.updateProject(old.id, payload(text, name))
+ savedProject.current = value
+ if (mounted.current) setProject(value)
+ return value
}
-
- async function aiExpand() {
- const seed = sourceText.trim() || title.trim() || '人工智能如何改变生活'
- setAiBusy(true)
+ async function saveCopyDraft() {
+ if (!copy.trim() || disabled || working.current || !selectedTemplate || !canSaveDraft) return
+ working.current = true
+ setBusy('正在保存草稿…')
setError('')
try {
- const mode = sourceType === 'script' ? 'script' : 'theme'
- const result = await api.expandContent(seed, mode)
- setSourceText(result.content.slice(0, mode === 'theme' ? 100 : 8000))
- if (!titleTouched || isDefaultTitle(title)) {
- setTitle(result.title.slice(0, 24))
- }
- } catch (err) {
- setError(err instanceof Error ? err.message : 'AI 生成失败')
+ await saveDraft(copy, title)
+ } catch (cause) {
+ if (mounted.current) setError(cause instanceof Error ? cause.message : '草稿保存失败,请重试')
} finally {
- setAiBusy(false)
+ working.current = false
+ if (mounted.current) setBusy('')
}
}
-
- async function next() {
- if (!templateId || !sourceText.trim()) {
- setError('请选择模板并填写主题内容')
- return
- }
- setBusy(true)
+ async function prepareCopy(event: FormEvent) {
+ event.preventDefault()
+ if (!idea.trim() || disabled || working.current || !selectedTemplate) return
+ working.current = true
setError('')
+ setBusy(mode === 'idea' ? '正在生成文案…' : '正在保存文案…')
+ try {
+ const result = mode === 'copy'
+ ? { title: title || idea.trim().slice(0, 30), content: idea.trim() }
+ : await api.expandContent(`${idea.trim()}\n\n创作要求:约 ${duration} 秒,${selectedTemplate.name} 风格,普通话旁白。请写可直接配音的完整文案,保持内容与时长匹配。`, 'script')
+ if (!mounted.current) return
+ setCopy(result.content)
+ setTitle(result.title)
+ setStep(1)
+ await saveDraft(result.content, result.title)
+ } catch (cause) {
+ if (mounted.current) setError(cause instanceof Error ? cause.message : '文案生成失败,请重试')
+ } finally {
+ working.current = false
+ if (mounted.current) setBusy('')
+ }
+ }
+ async function generateStoryboard() {
+ if (!copy.trim() || disabled || working.current || !selectedTemplate) return
+ working.current = true
try {
- const tpl = templates.find((t) => t.id === templateId)
- const d = tpl ? defaultsFromTemplate(tpl) : undefined
- const modeParam = params.get('mode')
- const pipeline_mode: 'full' | 'image_text' =
- modeParam === 'image_text' || modeParam === 'full' ? modeParam : 'full'
- const finalTitle =
- title.trim() || deriveTitle(sourceText) || sourceText.trim().slice(0, 24) || '未命名作品'
- const project = await api.createProject({
- template_id: templateId,
- title: finalTitle,
- source_type: sourceType,
- source_text: sourceText.trim(),
- resolution_mode: 'preview',
- pipeline_mode,
- output_ratio: d?.output_ratio || '16:9',
- voice_id: d?.voice_id,
- })
- nav(`/studio/${project.id}/style`)
- } catch (err) {
- setError(err instanceof Error ? err.message : '创建失败')
+ const old = savedProject.current
+ if (old?.shots.length) {
+ const confirmed = await dialog.confirm({ title: '重新生成分镜', message: '新的文案与设置将重新生成分镜,并替换本项目已有的图片、配音和成片。', confirmText: '重新生成', tone: 'danger' })
+ if (!confirmed || !mounted.current) return
+ }
+ setBusy('正在保存并生成分镜…')
+ setError('')
+ let value = await createDraft(copy, title)
+ value = await api.updateProject(value.id, payload(copy, title))
+ savedProject.current = value
+ setProject(value)
+ await api.generate(value.id, { restart: Boolean(value.shots.length) })
+ if (mounted.current) nav(`/studio/${value.id}`)
+ } catch (cause) {
+ if (mounted.current) setError(cause instanceof Error ? cause.message : '分镜生成失败,请重试')
} finally {
- setBusy(false)
+ working.current = false
+ if (mounted.current) setBusy('')
}
}
- return (
- <AppShell active="studio" wide>
- <header className="pf-page-head">
- <div className="pf-page-head-row">
- <div>
- <button type="button" className="pf-back" onClick={() => nav('/')}>
- <IconChevronLeft size={18} />
- 新建项目 / 开始创作
- </button>
- <h1 className="pf-page-title">创建项目</h1>
- </div>
- <Stepper steps={kepuSteps()} current={kepuStepIndex('create')} doneThrough={-1} />
- </div>
+ return <AppShell active="studio">
+ <div className="sv-create-page">
+ <header className="sv-create-header">
+ <div><Link className="sv-back" to="/history"><ArrowLeft size={16} /> 我的短片</Link><h1>{editId ? '编辑短片' : '创建短片'}</h1><p>从一个想法开始,每一步都可以查看和调整。</p></div>
+ <Stepper steps={IMAGE_TEXT_STEPS} current={step} />
</header>
-
- <div className="pf-create">
- <aside className="pf-create-col">
- <h3>选择模板</h3>
- <div className="pf-search">
- <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="搜索模板…" />
- </div>
- <PillTabs items={categories.slice(0, 6)} value={category} onChange={setCategory} ariaLabel="模板分类" />
- <div className="pf-tpl-list" style={{ marginTop: '0.75rem' }}>
- {filtered.map((t) => (
- <button
- key={t.id}
- type="button"
- className={templateId === t.id ? 'pf-tpl-mini selected' : 'pf-tpl-mini'}
- onClick={() => setTemplateId(t.id)}
- >
- <img src={api.assetUrl(t.preview_cover)} alt="" />
- <div>
- <strong>{t.name}</strong>
- <span>
- {t.default_ratio} · {(t.category || [])[0] || '通用'}
- </span>
+ {error && <BillingErrorNotice message={error} />}
+ {loading ? <div className="sv-loading"><LoaderCircle className="sv-spin" size={20} /> 正在加载项目…</div> : <>
+ {running && <div className="sv-running-note">项目正在制作中,请在工作台查看进度或停止任务。<Link to={`/studio/${project!.id}`}>查看工作台 <ArrowRight size={15} /></Link></div>}
+ <div className="sv-create-grid">
+ <main>
+ {step === 0 ? <form onSubmit={prepareCopy}>
+ <section className="sv-panel">
+ <div className="sv-section-heading"><span>01</span><div><h2>选择画面风格</h2><p>四种动画与插画风格,整个短片保持统一。</p></div></div>
+ <div className="sv-style-grid" role="group" aria-label="画面风格">
+ {templates.map(item => <button key={item.id} type="button" className={`sv-style-card${item.id === templateId ? ' is-selected' : ''}`} disabled={disabled} aria-pressed={item.id === templateId} onClick={() => setTemplateId(item.id)}>
+ <img src={api.assetUrl(item.preview_cover)} alt="" /><div><strong>{item.name}</strong><p>{item.description}</p></div>
+ {item.id === templateId && <span className="sv-style-check"><Check size={14} /></span>}
+ </button>)}
</div>
- </button>
- ))}
- </div>
- </aside>
-
- <section className="pf-create-col">
- <h3>输入内容</h3>
- <div className="pf-input-tabs">
- {['一句话主题', '粘贴完整文案'].map((tab) => (
- <button
- key={tab}
- type="button"
- className={['pf-pill', inputTab === tab ? 'lime active' : ''].join(' ')}
- onClick={() => setInputTab(tab)}
- >
- {tab}
- </button>
- ))}
- </div>
-
- <label className="pf-field">
- <span className="pf-field-label">项目名称</span>
- <input
- className="pf-field-input"
- value={title}
- onChange={(e) => {
- setTitle(e.target.value)
- setTitleTouched(true)
- }}
- onBlur={() => {
- if (isDefaultTitle(title) && sourceText.trim()) {
- setTitle(deriveTitle(sourceText))
- setTitleTouched(false)
- }
- }}
- placeholder="将根据内容自动填充"
- />
- </label>
-
- <div className="pf-textarea-wrap">
- <div className="pf-textarea-toolbar">
- <button
- type="button"
- className="pf-btn pf-btn-ai pf-btn-sm pf-btn-icon"
- disabled={aiBusy || busy}
- onClick={aiExpand}
- >
- <IconSparkles size={14} />
- {aiBusy ? '生成中…' : sourceType === 'script' ? 'AI 扩写文案' : 'AI 生成主题'}
- </button>
- <span className="pf-muted" style={{ fontSize: '0.75rem' }}>
- {sourceType === 'script' ? '可从一句话扩成完整口播' : '补全受众与知识点'}
- </span>
- </div>
- <textarea
- value={sourceText}
- onChange={(e) => {
- const next = e.target.value.slice(0, sourceType === 'theme' ? 100 : 8000)
- setSourceText(next)
- if (!titleTouched || isDefaultTitle(title)) {
- setTitle(deriveTitle(next))
- }
- }}
- placeholder={
- sourceType === 'theme'
- ? '例如:黑洞是如何形成的?用通俗方式讲清引力与时空'
- : '粘贴或 AI 生成完整口播文案…'
- }
- />
- {sourceType === 'theme' ? (
- <span className="pf-char-count">{sourceText.length}/100</span>
- ) : (
- <span className="pf-char-count">{sourceText.length} 字</span>
- )}
- </div>
-
- <div className="pf-inspire">
- <div className="pf-inspire-head">
- <strong>灵感示例</strong>
- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm pf-btn-icon" onClick={shuffleInspirations}>
- <IconRefresh size={14} />
- 换一批
- </button>
- </div>
- <div className="pf-chips">
- {inspirations.map((item) => (
- <button
- key={item.title}
- type="button"
- className="pf-chip"
- title={sourceType === 'script' ? item.script.slice(0, 80) : item.theme}
- onClick={() => applyInspiration(item)}
- >
- {item.title}
- </button>
- ))}
- </div>
- <p className="pf-muted" style={{ fontSize: '0.78rem', margin: '0.55rem 0 0' }}>
- 点击示例会填充完整{sourceType === 'script' ? '文案' : '主题'}并自动写入项目名称
- </p>
- </div>
-
- <div className="pf-hint" style={{ marginTop: '1rem' }}>
- 主题越具体,AI 越容易生成准确的科普分镜与旁白。可写清受众与核心知识点。
- </div>
- {error ? <BillingErrorNotice message={error} /> : null}
- </section>
-
- <aside className="pf-create-col">
- <h3>创作摘要</h3>
- {selected ? (
- <div style={{ marginBottom: '0.85rem' }}>
- <img
- src={api.assetUrl(selected.preview_cover)}
- alt=""
- style={{ width: '100%', borderRadius: 12, aspectRatio: '16/9', objectFit: 'cover' }}
- />
- <strong style={{ display: 'block', marginTop: '0.5rem' }}>{selected.name}</strong>
- <p className="pf-muted" style={{ margin: '0.25rem 0 0', fontSize: '0.85rem' }}>
- {selected.description}
- </p>
- </div>
- ) : (
- <p className="pf-muted">请选择模板</p>
- )}
- <div className="pf-summary-row">
- <span>作品名称</span>
- <span>{title.trim() || '未命名作品'}</span>
- </div>
- <div className="pf-summary-row">
- <span>输出模式</span>
- <span>{selected?.default_ratio === '9:16' ? '视频 · 9:16' : '视频 · 16:9'}</span>
- </div>
- <div className="pf-summary-row">
- <span>预估时长</span>
- <span>~1–3 分钟</span>
- </div>
- <div className="pf-summary-row">
- <span>语言</span>
- <span>中文(普通话)</span>
- </div>
- <div className="pf-summary-row">
- <span>输入方式</span>
- <span>{inputTab}</span>
- </div>
- <button
- type="button"
- className="pf-btn pf-btn-lime pf-btn-block pf-btn-lg pf-btn-icon"
- style={{ marginTop: '1.25rem' }}
- disabled={busy || aiBusy || !templateId || !sourceText.trim()}
- onClick={next}
- >
- {busy ? '创建中…' : '下一步:风格配置'}
- {!busy ? <span aria-hidden>→</span> : null}
- </button>
- <button
- type="button"
- className="pf-btn pf-btn-ghost pf-btn-block pf-btn-sm pf-btn-icon"
- style={{ marginTop: '0.55rem' }}
- disabled={aiBusy || busy}
- onClick={aiExpand}
- >
- <IconSparkles size={14} />
- {aiBusy ? 'AI 生成中…' : '不够完整?让 AI 帮你写'}
- </button>
- <p className="pf-muted" style={{ fontSize: '0.78rem', marginTop: '0.5rem' }}>
- 画风已随模板带上。下一步确认配音与成片方式。
- </p>
- </aside>
- </div>
- </AppShell>
- )
+ </section>
+ <section className="sv-panel">
+ <div className="sv-section-heading"><span>02</span><div><h2>写下你想表达的内容</h2><p>描述主题、受众和重点,或直接粘贴已有文案。</p></div></div>
+ <div className="sv-input-tabs"><button type="button" className={mode === 'idea' ? 'is-active' : ''} onClick={() => setMode('idea')} disabled={disabled}>输入想法</button><button type="button" className={mode === 'copy' ? 'is-active' : ''} onClick={() => setMode('copy')} disabled={disabled}>已有文案</button></div>
+ <label className="sv-field"><span>{mode === 'idea' ? '短片想法' : '完整文案'}</span><textarea aria-label={mode === 'idea' ? '短片想法' : '完整文案'} value={idea} onChange={event => setIdea(event.target.value)} rows={6} maxLength={20000} disabled={disabled} placeholder={mode === 'idea' ? '例如:用 3D 动画给小学生解释天空为什么是蓝色,语言轻松,约 60 秒。' : '粘贴可以直接配音的文案,下一步可以继续编辑。'} required /></label>
+ {mode === 'idea' && <div className="sv-examples">{EXAMPLES.map(example => <button type="button" key={example} onClick={() => setIdea(example)} disabled={disabled}>{example}</button>)}</div>}
+ <div className="sv-actions"><span>文案生成后可修改,再继续生成分镜。</span><div className="sv-action-buttons">{copy.trim() && <Button variant="outline" disabled={disabled} onClick={() => setStep(1)}>编辑已有文案</Button>}<Button type="submit" variant="lime" disabled={disabled || !idea.trim() || !selectedTemplate}>{busy ? <LoaderCircle size={16} className="sv-spin" /> : <Sparkles size={16} />}{busy || (mode === 'idea' ? '生成文案' : '下一步:检查文案')}<ArrowRight size={16} /></Button></div></div>
+ </section>
+ </form> : <section className="sv-panel">
+ <div className="sv-section-heading"><span>02</span><div><h2>检查文案,再生成分镜</h2><p>这份文案将作为旁白。确认内容后,再拆分画面与镜头。</p></div></div>
+ <label className="sv-field"><span>短片名称</span><input value={title} onChange={event => setTitle(event.target.value)} maxLength={200} disabled={disabled} /></label>
+ <label className="sv-field"><span>配音文案 <small>{copy.length} 字</small></span><textarea aria-label="配音文案" value={copy} onChange={event => setCopy(event.target.value)} rows={13} maxLength={20000} disabled={disabled} /></label>
+ <div className="sv-actions"><Button variant="outline" disabled={disabled} onClick={() => setStep(0)}><ArrowLeft size={15} /> 返回调整</Button><div className="sv-action-buttons">{canSaveDraft && <Button variant="outline" disabled={disabled || !copy.trim() || !selectedTemplate || Boolean(project && !draftChanged)} onClick={() => { void saveCopyDraft() }}><Save size={15} />保存草稿</Button>}<Button variant="lime" disabled={disabled || !copy.trim() || !selectedTemplate} onClick={() => { void generateStoryboard() }}>{busy ? <LoaderCircle size={16} className="sv-spin" /> : <Clapperboard size={16} />}{busy || '生成分镜脚本'}<ArrowRight size={16} /></Button></div></div>
+ {project && <p className="sv-saved-note">{draftChanged ? canSaveDraft ? '有未保存的修改,可先保存草稿,或生成分镜时一并保存。' : '修改将在重新生成分镜时保存。' : canSaveDraft ? '草稿已保存。' : '已载入项目文案。'}<Link to={`/studio/${project.id}`}>打开项目工作台</Link></p>}
+ </section>}
+ </main>
+ <aside className="sv-panel sv-settings">
+ <h2>短片设置</h2><p>先用默认设置,也可以按需要调整。</p>
+ <label className="sv-field"><span>画面比例</span><select value={ratio} onChange={event => setRatio(event.target.value)} disabled={disabled}><option value="9:16">9:16 竖屏</option><option value="16:9">16:9 横屏</option><option value="1:1">1:1 方形</option></select></label>
+ <label className="sv-field"><span>目标时长</span><select value={duration} onChange={event => setDuration(Number(event.target.value))} disabled={disabled}>{[...new Set([30, 60, 90, 120, 180, duration])].sort((a, b) => a - b).map(value => <option key={value} value={value}>约 {value} 秒</option>)}</select></label>
+ <label className="sv-field"><span>旁白音色</span><select value={voice} onChange={event => setVoice(event.target.value)} disabled={disabled}><option value="">默认普通话音色</option>{voice && !voices.some(item => (item.speaker || item.id) === voice) && <option value={voice}>项目原有音色</option>}{voices.map(item => <option key={item.id} value={item.speaker || item.id}>{item.label}</option>)}</select></label>
+ {voiceError && <p className="sv-saved-note">音色列表暂未加载,仍可使用默认配音。</p>}
+ <div className="sv-setting-summary"><Clapperboard size={17} /><div><strong>{selectedTemplate?.name || '3D 动画'}</strong><span>图片运镜 · 普通话旁白 · 中文字幕</span></div></div>
+ <div className="sv-workflow-hint"><Clock3 size={17} /><p>检查分镜后生成图片和配音,素材准备好后再合成视频。</p></div>
+ </aside>
+ </div>
+ </>}
+ </div>
+ </AppShell>
}
diff --git a/frontend/src/pages/studio/CreationSessionEditorBridge.tsx b/frontend/src/pages/studio/CreationSessionEditorBridge.tsx
new file mode 100644
index 0000000..4f9e4c2
--- /dev/null
+++ b/frontend/src/pages/studio/CreationSessionEditorBridge.tsx
@@ -0,0 +1,58 @@
+import { useEffect, useState } from 'react'
+import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
+import { ArrowLeft, LoaderCircle, RefreshCw } from 'lucide-react'
+import { creationApi } from '../../api/creation'
+import { isRequestAborted } from '../../api/http'
+import AppShell from '../../components/layout/AppShell'
+import Button from '../../components/ui/Button'
+import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
+import './shortVideoCreate.css'
+
+/** 旧会话先等待生产者退出,再安全移交普通分步工作台。 */
+export default function CreationSessionEditorBridge() {
+ const { sessionId } = useParams()
+ const [params] = useSearchParams()
+ const projectId = Number(params.get('project')) || undefined
+ const returnPath = `/studio/sessions/${sessionId}${projectId ? `?project=${projectId}` : ''}`
+ const nav = useNavigate()
+ const [error, setError] = useState('')
+ const [attempt, setAttempt] = useState(0)
+ const [waiting, setWaiting] = useState(false)
+ useEffect(() => {
+ if (!sessionId) return
+ if (!localStorage.getItem('token')) {
+ nav(`/auth?next=${encodeURIComponent(returnPath)}`, { replace: true })
+ return
+ }
+ let disposed = false
+ const controller = new AbortController()
+ let timer: ReturnType<typeof setTimeout> | undefined
+ setError('')
+ async function transfer() {
+ try {
+ const project = await creationApi.openEditor(sessionId!, controller.signal, projectId)
+ if (disposed) return
+ nav(project.shots.length || project.final_video_url ? `/studio/${project.id}` : `/studio/new?project=${project.id}`, { replace: true })
+ } catch (cause) {
+ if (disposed || isRequestAborted(cause)) return
+ const status = cause && typeof cause === 'object' && 'status' in cause ? Number(cause.status) : 0
+ if (status === 409 && cause instanceof Error && cause.message.includes('正在停止旧创作任务')) {
+ setWaiting(true)
+ timer = setTimeout(() => { void transfer() }, 2000)
+ } else if (status === 401) {
+ nav(`/auth?next=${encodeURIComponent(returnPath)}`, { replace: true })
+ } else setError(cause instanceof Error ? cause.message : '暂时无法打开项目,请重试')
+ }
+ }
+ void transfer()
+ return () => { disposed = true; controller.abort(); if (timer) clearTimeout(timer) }
+ }, [sessionId, projectId, returnPath, nav, attempt])
+ return <AppShell active="studio"><div className="sv-create-page">
+ <Link to="/history" className="sv-back"><ArrowLeft size={16} /> 我的短片</Link>
+ <section className="sv-panel" style={{ marginTop: 24 }}>
+ <h2>打开分步工作台</h2>
+ <p>{waiting ? '正在停止旧制作任务,已有文案与素材会保留。任务退出后自动进入编辑。' : '正在整理项目文案与素材,准备继续编辑。'}</p>
+ {error ? <><BillingErrorNotice message={error} /><Button variant="lime" onClick={() => setAttempt(value => value + 1)}><RefreshCw size={16} /> 重试</Button></> : <div className="sv-loading"><LoaderCircle size={20} className="sv-spin" /> {waiting ? '等待原任务退出…' : '正在打开…'}</div>}
+ </section>
+ </div></AppShell>
+}
diff --git a/frontend/src/pages/studio/EditorPage.tsx b/frontend/src/pages/studio/EditorPage.tsx
index c340007..923a051 100644
--- a/frontend/src/pages/studio/EditorPage.tsx
+++ b/frontend/src/pages/studio/EditorPage.tsx
@@ -34,6 +34,10 @@ export default function EditorPage() {
api
.getProject(projectId)
.then((p) => {
+ if (p.creation_session_id) {
+ nav(`/studio/sessions/${p.creation_session_id}?project=${p.id}`, { replace: true })
+ return
+ }
setProject(p)
const first = p.shots[0]
if (first) {
diff --git a/frontend/src/pages/studio/ImageTextStoryboard.tsx b/frontend/src/pages/studio/ImageTextStoryboard.tsx
new file mode 100644
index 0000000..d0f7dad
--- /dev/null
+++ b/frontend/src/pages/studio/ImageTextStoryboard.tsx
@@ -0,0 +1,138 @@
+import { useState } from 'react'
+import { ArrowLeft, ArrowRight, Check, Clapperboard, Download, Pause, Pencil, RefreshCw, Volume2 } from 'lucide-react'
+import { api, type Project, type Shot, type Template } from '../../api'
+import { ProjectCard, ProjectGrid } from '../../components/projects/ProjectCard'
+import { IMAGE_TEXT_STEPS, imageTextAssetReadiness, imageTextBoardStep, imageTextNextAction } from '../../lib/imageTextStoryboard'
+import { formatMmSs, isProjectWideBusy, isShotGenerating, statusLabel } from '../../lib/status'
+import { shotDisplayDurationSec } from '../../lib/segmentDuration'
+import { scenePromptForDisplay } from '../../promptDisplay'
+import './imageTextStoryboard.css'
+
+type Props = {
+ project: Project
+ template: Template | null
+ busy: boolean
+ running: boolean
+ busyShotIds: Set<number>
+ onBack: () => void
+ onSettings: () => void
+ onGenerate: () => void
+ onCompose: () => void
+ onCancel: () => void
+ onRestart: () => void
+ onExport: () => void
+ onDownload: () => void
+ onEditor: () => void
+ onEditShot: (shot: Shot, focus?: string) => void
+ onPreviewShot: (shot: Shot) => void
+ onRegenImage: (shot: Shot) => void
+ onRegenAudio: (shot: Shot) => void
+}
+
+export default function ImageTextStoryboard({ project, template, busy, running, busyShotIds, onBack, onSettings, onGenerate, onCompose, onCancel, onRestart, onExport, onDownload, onEditor, onEditShot, onPreviewShot, onRegenImage, onRegenAudio }: Props) {
+ const stage = imageTextBoardStep(project)
+ // Remember a previous view only while the production stage is unchanged.
+ const [view, setView] = useState<{ stage: number; step: number } | null>(null)
+ const step = view?.stage === stage ? view.step : stage
+ const readiness = imageTextAssetReadiness(project)
+ const nextAction = imageTextNextAction(project)
+ const shots = [...project.shots].sort((a, b) => a.shot_no - b.shot_no)
+ const duration = shots.reduce((sum, shot) => sum + shotDisplayDurationSec(shot), 0)
+ const targetDuration = project.target_duration_sec || 60
+ const audioShot = shots.find((shot) => shot.audio_url)
+ const cancelling = Boolean(project.active_tasks?.some((task) => task.cancel_requested))
+ const failed = ['FAILED', 'CANCELLED', 'REJECTED'].includes(project.status)
+ const locked = busy || running
+ const actionLabel = nextAction === 'script' ? '生成分镜脚本' : nextAction === 'assets'
+ ? readiness.images || readiness.audio ? '继续生成缺失素材' : '确认分镜,生成画面与配音'
+ : nextAction === 'compose' ? '下一步:合成成片' : '查看成片'
+ function next() {
+ if (nextAction === 'preview') setView({ stage, step: 3 })
+ else if (nextAction === 'compose') onCompose()
+ else onGenerate()
+ }
+
+ return (
+ <div className="pf-image-storyboard">
+ <header className="pf-is-header">
+ <div>
+ <button type="button" className="pf-back" onClick={onBack}><ArrowLeft size={16} />我的短片</button>
+ <h1>{project.title}</h1>
+ <p>{template?.name || '动画短片'}<span>·</span>{project.output_ratio || '9:16'}<span>·</span>目标约 {targetDuration} 秒{shots.length ? <><span>·</span>{shots.length} 个镜头 · {formatMmSs(duration)}</> : null}</p>
+ </div>
+ <div className="pf-is-header-actions">
+ <button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={locked} onClick={onSettings}><Pencil size={14} />修改创作设置</button>
+ <button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={!shots.length || locked} onClick={onEditor}>打开编辑器</button>
+ </div>
+ </header>
+
+ <nav className="pf-is-steps" aria-label="短片创作步骤">
+ {IMAGE_TEXT_STEPS.map((item, index) => (
+ <button key={item.key} type="button" className={`${step === index ? 'is-current' : ''} ${index < stage ? 'is-complete' : ''}`}
+ aria-current={step === index ? 'step' : undefined}
+ disabled={index > stage || (index === 0 && locked)}
+ onClick={() => index === 0 ? onSettings() : setView({ stage, step: index })}>
+ <span>{index < stage ? <Check size={16} /> : index + 1}</span><strong>{item.label}</strong>
+ </button>
+ ))}
+ </nav>
+
+ {running ? (
+ <section className="pf-is-progress" aria-live="polite">
+ <div><strong>{cancelling ? '正在停止,请稍候…' : statusLabel(project)}</strong><p>进度会自动保存,可以离开页面,稍后从「我的短片」继续。</p></div>
+ <div className="pf-is-progress-track"><span style={{ width: `${Math.max(2, Math.min(100, project.progress))}%` }} /></div>
+ <span>{project.progress}%</span>
+ <button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={busy || cancelling} onClick={onCancel}><Pause size={14} />停止</button>
+ </section>
+ ) : failed ? <p className="pf-is-resume-note">{project.status === 'CANCELLED' ? '制作已停止。' : '本阶段未完成。'}已完成的素材已保存,可以从当前步骤继续。</p> : null}
+
+ {step === 1 ? (
+ <section className="pf-is-section">
+ <div className="pf-is-section-head"><div><span className="pf-is-eyebrow">STEP 02</span><h2>确认文案与分镜</h2><p>逐张查看镜头,调整旁白和画面,满意后再生成素材。</p></div><button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={!shots.length} onClick={onExport}><Download size={14} />导出脚本</button></div>
+ <details className="pf-is-copy" open={!shots.length}><summary>完整文案 <span>{project.source_text.length} 字</span></summary><p>{project.source_text}</p></details>
+ {shots.length ? <ProjectGrid className="pf-is-script-grid">
+ {shots.map((shot) => {
+ const shotBusy = locked || busyShotIds.has(shot.id) || isShotGenerating(project, shot.id)
+ return <article key={shot.id} className="pf-is-script-card">
+ <header><span>镜头 {String(shot.shot_no).padStart(2, '0')}</span><span>{formatMmSs(shotDisplayDurationSec(shot))}</span></header>
+ <h3>{shot.overlay_title || `场景 ${shot.shot_no}`}</h3>
+ <div className="pf-is-script-field"><label>旁白</label><p>{shot.narration || '暂无旁白,点击编辑补充'}</p></div>
+ <div className="pf-is-script-field"><label>画面</label><p>{scenePromptForDisplay(shot.img_prompt) || '暂无画面描述'}</p></div>
+ <footer><button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={shotBusy} onClick={() => onEditShot(shot, 'narration')}><Pencil size={13} />编辑旁白</button><button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={shotBusy} onClick={() => onEditShot(shot)}>编辑分镜</button></footer>
+ </article>
+ })}
+ </ProjectGrid> : <div className="pf-is-empty"><Clapperboard size={38} /><h3>{running ? '正在把文案拆成分镜' : '文案已就绪'}</h3><p>{running ? '生成后,每个镜头会显示为一张可编辑卡片。' : '点击下方按钮生成分镜脚本。'}</p></div>}
+ </section>
+ ) : step === 2 ? (
+ <section className="pf-is-section">
+ <div className="pf-is-section-head"><div><span className="pf-is-eyebrow">STEP 03</span><h2>检查画面与配音</h2><p>画面 {readiness.images}/{readiness.total} · 配音 {readiness.audio === readiness.total && readiness.total ? '已完成' : '待完成'}。画面齐备、试听满意后,即可合成。</p></div></div>
+ <div className="pf-is-audio"><div><Volume2 size={22} /><div><strong>整片旁白</strong><p>成片按真实配音时长安排画面,自动添加字幕。</p></div></div>{audioShot?.audio_url ? <audio aria-label="试听整片旁白" controls preload="metadata" src={api.assetUrl(audioShot.audio_url, project.updated_at)} /> : <span className="pf-muted">{running ? '配音生成中…' : '等待生成配音'}</span>}<button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={locked || !shots.length} onClick={() => onRegenAudio(shots[0])}><RefreshCw size={13} />重新配音</button></div>
+ <ProjectGrid>
+ {shots.map((shot) => {
+ const generating = busyShotIds.has(shot.id) || isShotGenerating(project, shot.id)
+ const shotBusy = busy || isProjectWideBusy(project) || generating
+ const imageReady = Boolean(shot.image_url)
+ return <ProjectCard key={shot.id} className="pf-is-media-card" kind="drama" title={shot.overlay_title || `场景 ${shot.shot_no}`} category={`镜头 ${String(shot.shot_no).padStart(2, '0')} · ${formatMmSs(shotDisplayDurationSec(shot))}`}
+ coverUrl={shot.image_url ? api.assetUrl(shot.image_url, shot.version) : undefined}
+ status={{ label: generating ? '生成中' : imageReady ? '画面已就绪' : shot.status === 'FAILED' ? '生成失败' : '待生成', tone: generating ? 'producing' : imageReady ? 'completed' : 'draft' }}
+ description={shot.narration} meta={<span>{shot.audio_url ? '✓ 配音已就绪' : '○ 等待配音'}</span>}
+ onOpen={() => onPreviewShot(shot)} openLabel={`预览镜头 ${shot.shot_no}`}
+ actions={<><button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={shotBusy} onClick={() => onEditShot(shot)}>编辑</button><button type="button" className="pf-btn pf-btn-outline pf-btn-sm" disabled={shotBusy} onClick={() => onRegenImage(shot)}><RefreshCw size={12} />{imageReady ? '重绘画面' : '生成画面'}</button></>} />
+ })}
+ </ProjectGrid>
+ </section>
+ ) : (
+ <section className="pf-is-section">
+ <div className="pf-is-section-head"><div><span className="pf-is-eyebrow">STEP 04</span><h2>{project.final_video_url ? '你的短片已完成' : '合成短片'}</h2><p>图片运镜、旁白和字幕,合为一部完整短片。</p></div></div>
+ {project.final_video_url ? <div className="pf-is-final"><div className="pf-is-final-player"><video controls preload="metadata" src={api.assetUrl(project.final_video_url, project.updated_at)} poster={project.cover_url ? api.assetUrl(project.cover_url) : undefined} /></div><div><span className="pf-is-complete"><Check size={15} />制作完成</span><h3>{project.title}</h3><p>{project.output_ratio || '9:16'} · MP4 · 配音与字幕</p><button type="button" className="pf-btn pf-btn-lime" disabled={busy} onClick={onDownload}><Download size={16} />{busy ? '处理中…' : '下载成片'}</button><button type="button" className="pf-btn pf-btn-outline" disabled={locked} onClick={() => setView({ stage, step: 2 })}>返回修改素材</button><button type="button" className="pf-btn pf-btn-ghost" disabled={locked || !readiness.ready} onClick={onCompose}>用当前素材重新合成</button></div></div>
+ : <div className="pf-is-empty"><Clapperboard size={42} /><h3>{running ? '正在合成成片' : '准备合成'}</h3><p>{running ? '正在安排图片运镜、同步配音和字幕。完成后可直接预览和下载。' : '确认画面与配音后,开始合成最终视频。'}</p></div>}
+ </section>
+ )}
+
+ <footer className="pf-is-next">
+ <div><strong>{running ? cancelling ? '正在停止制作' : '当前步骤制作中' : nextAction === 'preview' ? '成片已保存' : actionLabel}</strong><p>{running ? '完成后会停在当前阶段,等待你检查。' : nextAction === 'assets' && (readiness.images || readiness.audio) ? '沿用已成功的素材,补齐后继续。' : nextAction === 'compose' ? '图片和配音已齐,下一步添加运镜与字幕。' : '每一步都可以查看和调整结果。'}</p></div>
+ <div className="pf-is-next-buttons">{step > 1 ? <button type="button" className="pf-btn pf-btn-outline" onClick={() => setView({ stage, step: step - 1 })}><ArrowLeft size={14} />上一步</button> : <button type="button" className="pf-btn pf-btn-ghost" disabled={locked} onClick={onRestart}><RefreshCw size={14} />重新生成分镜</button>}{nextAction === 'preview' && step === 3 ? null : <button type="button" className="pf-btn pf-btn-lime" disabled={locked} onClick={step === 1 && stage > 1 ? () => setView({ stage, step: 2 }) : next}>{running ? '制作中…' : step === 1 && stage > 1 ? '下一步:画面与配音' : actionLabel}<ArrowRight size={16} /></button>}</div>
+ </footer>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/studio/StoryboardPage.tsx b/frontend/src/pages/studio/StoryboardPage.tsx
index eca8210..6781b45 100644
--- a/frontend/src/pages/studio/StoryboardPage.tsx
+++ b/frontend/src/pages/studio/StoryboardPage.tsx
@@ -4,6 +4,7 @@ import { api, defaultsFromTemplate } from '../../api'
import type { Project, Shot, Template } from '../../api'
import AppShell from '../../components/layout/AppShell'
import Stepper from '../../components/ui/Stepper'
+import ImageTextStoryboard from './ImageTextStoryboard'
import {
IconChevronLeft,
IconDownload,
@@ -17,6 +18,7 @@ import {
} from '../../components/ui/Icons'
import { scenePromptForDisplay } from '../../promptDisplay'
import { dialog } from '../../lib/dialog'
+import { downloadSingleVideo } from '../../lib/clientDownload'
import { handleBillingError } from '../../lib/billingError'
import BillingErrorNotice from '../../components/billing/BillingErrorNotice'
import {
@@ -104,10 +106,10 @@ function shotCaption(shot: Shot) {
}
function hasActiveUnifiedTasks(project: Project | null): boolean {
- const activeStatuses = ['pending', 'leased', 'running', 'awaiting_poll', 'awaiting_review']
+ const activeStatuses = ['pending', 'leased', 'running', 'awaiting_poll', 'awaiting_review', 'cancel_requested']
return Boolean(
project?.active_tasks?.some(
- (task) => !task.cancel_requested && activeStatuses.includes(task.status),
+ (task) => activeStatuses.includes(task.status),
),
)
}
@@ -161,9 +163,14 @@ export default function StoryboardPage() {
api
.getProject(projectId)
.then((p) => {
+ if (p.creation_session_id) {
+ nav(`/studio/sessions/${p.creation_session_id}?project=${p.id}`, { replace: true })
+ return
+ }
setProject(p)
- return api.templates().then((list) => {
- setTemplate(list.find((t) => t.id === p.template_id) || null)
+ return api.templates().then(async (list) => {
+ const selected = list.find((t) => t.id === p.template_id)
+ setTemplate(selected || (p.template_id ? await api.getTemplate(p.template_id) : null))
})
})
.catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
@@ -379,10 +386,38 @@ export default function StoryboardPage() {
async function composeOnly() {
if (!project) return
setBusy(true)
+ setError('')
try {
setProject(await api.compose(project.id))
} catch (err) {
setError(err instanceof Error ? err.message : '合成失败')
+ await handleBillingError(err, nav)
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function cancelGeneration() {
+ if (!project) return
+ setBusy(true)
+ setError('')
+ try {
+ setProject(await api.cancelProject(project.id))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '停止失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function downloadFinal() {
+ if (!project?.final_video_url) return
+ setBusy(true)
+ setError('')
+ try {
+ await downloadSingleVideo({ url: api.assetUrl(project.final_video_url, project.updated_at), title: project.title, projectId: project.id })
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '下载失败')
} finally {
setBusy(false)
}
@@ -681,6 +716,32 @@ export default function StoryboardPage() {
return (
<AppShell active="studio" wide>
+ {!isFullPipeline ? <>
+ {error ? <BillingErrorNotice message={error} /> : null}
+ {project.error_msg ? <p className="pf-error">{project.error_msg}</p> : null}
+ <ImageTextStoryboard
+ key={project.id}
+ project={project}
+ template={template}
+ busy={busy}
+ running={running}
+ busyShotIds={busyShotIds}
+ onBack={() => nav('/history')}
+ onSettings={() => nav(`/studio/new?project=${project.id}`)}
+ onGenerate={() => void continueGenerate()}
+ onCompose={() => void composeOnly()}
+ onCancel={() => void cancelGeneration()}
+ onRestart={() => void restartGenerate()}
+ onExport={() => downloadStoryboardCsv(project)}
+ onDownload={() => void downloadFinal()}
+ onEditor={() => nav(`/studio/${project.id}/editor`)}
+ onEditShot={openShotEdit}
+ onPreviewShot={(shot) => setPreview({ kind: 'shot', shotNo: shot.shot_no, imageUrl: shot.image_url, videoUrl: shot.video_url, audioUrl: shot.audio_url, caption: shotCaption(shot) })}
+ onRegenImage={(shot) => void regenImage(shot)}
+ onRegenAudio={(shot) => void regenAudio(shot)}
+ />
+ <ProjectMediaCostSummary project={project} />
+ </> : <>
<header className="pf-page-head">
<div className="pf-page-head-row">
<div>
@@ -1271,6 +1332,8 @@ title="用当前镜头重新拼接"
</aside>
</div>
+ </>}
+
{batchOpen && project ? (
<div className="modal-backdrop" onClick={() => !busy && setBatchOpen(false)}>
<div className="modal" onClick={(e) => e.stopPropagation()}>
@@ -1378,7 +1441,7 @@ title="用当前镜头重新拼接"
? `编辑镜头 ${editing.shot_no} · 旁白与标题`
: editMode === 'segment'
? `编辑镜头 ${editing.shot_no} · 逐段分镜`
- : `编辑镜头 ${editing.shot_no} · 全部提示词`}
+ : `编辑镜头 ${editing.shot_no} · ${isFullPipeline ? '全部提示词' : '画面与旁白'}`}
</h3>
<div className="pf-prompt-modal-scroll">
{editMode === 'narration' || editMode === 'full' ? (
@@ -1401,7 +1464,7 @@ title="用当前镜头重新拼接"
onChange={(e) => setEditing({ ...editing, overlay_subtitle: e.target.value })}
/>
<span className="pf-muted pf-prompt-hint">
- 图文成片叠字;AI 视频成片不烧这行,只作分镜说明
+ {isFullPipeline ? '作为分镜说明使用' : '可选,会和标题一起显示在成片中'}
</span>
</label>
<label>
@@ -1420,7 +1483,7 @@ title="用当前镜头重新拼接"
) : null}
{editMode === 'full' ? (
<label>
- 画面提示词(首帧)
+ {isFullPipeline ? '画面提示词(首帧)' : '画面描述'}
<textarea
autoFocus={editFocus === 'img_prompt'}
value={editing.img_prompt}
@@ -1428,11 +1491,11 @@ title="用当前镜头重新拼接"
rows={3}
/>
<span className="pf-muted pf-prompt-hint">
- 会同步到脚本首段画面,出图与视频都用这一段
+ {isFullPipeline ? '会同步到脚本首段画面,出图与视频都用这一段' : '描述角色、场景和动作;修改后可重新生成这一张图片'}
</span>
</label>
) : null}
- {editMode === 'segment' || editMode === 'full' ? (
+ {isFullPipeline && (editMode === 'segment' || editMode === 'full') ? (
<>
<label>
逐段分镜脚本(画面节奏与 @duration)
@@ -1492,7 +1555,7 @@ title="用当前镜头重新拼接"
) : null}
</div>
<div className="pf-prompt-modal-foot">
- {editMode !== 'segment' ? (
+ {isFullPipeline && editMode !== 'segment' ? (
<button
type="button"
className="pf-btn pf-btn-ghost pf-btn-sm"
@@ -1504,7 +1567,7 @@ title="用当前镜头重新拼接"
逐段分镜…
</button>
) : null}
- {editMode !== 'narration' ? (
+ {isFullPipeline && editMode !== 'narration' ? (
<button
type="button"
className="pf-btn pf-btn-ghost pf-btn-sm"
@@ -1516,7 +1579,7 @@ title="用当前镜头重新拼接"
旁白与标题…
</button>
) : null}
- {editMode !== 'full' ? (
+ {isFullPipeline && editMode !== 'full' ? (
<button
type="button"
className="pf-btn pf-btn-ghost pf-btn-sm"
diff --git a/frontend/src/pages/studio/StyleConfigPage.tsx b/frontend/src/pages/studio/StyleConfigPage.tsx
index f9deea4..34f2b11 100644
--- a/frontend/src/pages/studio/StyleConfigPage.tsx
+++ b/frontend/src/pages/studio/StyleConfigPage.tsx
@@ -80,17 +80,25 @@ export default function StyleConfigPage() {
if (!projectId) {
nav('/studio/new')
}
- api.templates().then(setTemplates)
api.voices().then(setVoices)
- api
- .getProject(projectId)
- .then((p) => {
+ Promise.all([api.templates(), api.getProject(projectId)])
+ .then(async ([list, p]) => {
+ if (p.pipeline_mode === 'image_text') {
+ nav(`/studio/new?project=${p.id}`, { replace: true })
+ return
+ }
+ // 下架的风格不再展示给新用户,历史项目仍可加载其原模板。
+ if (p.template_id && !list.some((item) => item.id === p.template_id)) {
+ const legacy = await api.getTemplate(p.template_id)
+ list = [...list, legacy]
+ }
+ setTemplates(list)
setProject(p)
setStylePrompt(p.style_prompt || '')
setExtraPrompt(p.extra_prompt || '')
setVoiceId(p.voice_id || '')
setPipelineMode(p.pipeline_mode || 'full')
- setRatio(p.output_ratio || (p.pipeline_mode === 'image_text' ? '9:16' : '16:9'))
+ setRatio(p.output_ratio || '16:9')
if (p.image_model) setImageModel(p.image_model)
if (p.video_model) setVideoModel(p.video_model)
if (p.image_resolution) setImageResolution(p.image_resolution)
diff --git a/frontend/src/pages/studio/creationAgent.css b/frontend/src/pages/studio/creationAgent.css
new file mode 100644
index 0000000..54bfc14
--- /dev/null
+++ b/frontend/src/pages/studio/creationAgent.css
@@ -0,0 +1,1191 @@
+.creation-workspace {
+ --creation-lime: #b7f500;
+ --creation-ink: #18231c;
+ --creation-muted: #7b827d;
+ max-width: 1000px;
+ margin: 0 auto;
+ color: var(--creation-ink);
+ padding: 0 28px 60px;
+ min-height: calc(100dvh - 40px);
+}
+.creation-topbar {
+ display: flex;
+ align-items: center;
+ gap: 24px;
+ min-height: 62px;
+ border-bottom: 1px solid #e5e9e3;
+ margin-bottom: 18px;
+ font-size: 12px;
+}
+.creation-back,
+.creation-new {
+ display: inline-flex;
+ align-items: center;
+ gap: 7px;
+ text-decoration: none;
+ color: #606c61 !important;
+ white-space: nowrap;
+}
+.creation-back:hover,
+.creation-new:hover {
+ color: var(--creation-ink) !important;
+}
+.creation-new {
+ margin-left: auto;
+ background: #fff;
+ border: 1px solid #dfe5db;
+ padding: 8px 12px;
+ border-radius: 9px;
+}
+.creation-topbar-label {
+ color: #969b96;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.creation-topbar-label span {
+ padding: 0 9px;
+ color: #c4c9bf;
+}
+.creation-welcome {
+ text-align: center;
+ padding: 49px 0 26px;
+}
+.creation-welcome-mark {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ width: 54px;
+ height: 54px;
+ background: var(--creation-lime);
+ border-radius: 18px 18px 18px 5px;
+ box-shadow: 4px 4px 0 #e5edcf;
+ margin-bottom: 23px;
+ transform: rotate(-5deg);
+}
+.creation-welcome-mark svg {
+ transform: rotate(5deg);
+}
+.creation-eyebrow {
+ font-family: Consolas, 'SFMono-Regular', monospace;
+ font-size: 9px;
+ font-weight: 500;
+ letter-spacing: 0.15em;
+ color: #859177;
+ line-height: 1.5;
+}
+.creation-welcome > .creation-eyebrow {
+ font-size: 9px;
+ margin: 0 0 15px;
+ color: #818a78;
+}
+.creation-welcome h1 {
+ font-family:
+ 'Noto Serif SC', 'Source Han Serif SC', 'Songti SC', SimSun, serif !important;
+ font-size: clamp(32px, 4.2vw, 49px);
+ font-weight: 650;
+ letter-spacing: -0.04em;
+ line-height: 1.33;
+ margin: 0 0 20px;
+}
+.creation-welcome h1 span {
+ position: relative;
+ isolation: isolate;
+}
+.creation-welcome h1 span:after {
+ content: '';
+ position: absolute;
+ z-index: -1;
+ bottom: 2px;
+ height: 12px;
+ background: #daf99b;
+ left: 4px;
+ right: -5px;
+ transform: rotate(-1.5deg);
+}
+.creation-welcome-description {
+ font-size: 14px;
+ line-height: 1.9;
+ color: #7b857b;
+ margin: 0 0 18px;
+}
+.creation-mobile-break {
+ display: none;
+}
+.creation-defaults {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 13px;
+ color: #8c9489;
+ font-size: 10px;
+}
+.creation-defaults span {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+}
+.creation-defaults i {
+ width: 3px;
+ height: 3px;
+ background: #c4ccb9;
+ border-radius: 100%;
+}
+.creation-composer-dock {
+ max-width: 796px;
+ margin: 0 auto;
+ z-index: 5;
+}
+.creation-composer {
+ border: 1px solid #dfe5d6;
+ border-radius: 19px;
+ background: #fff;
+ box-shadow:
+ 0 7px 35px #22351106,
+ 0 0 0 5px #edf1e754;
+ overflow: hidden;
+ transition:
+ border-color 0.2s,
+ box-shadow 0.2s;
+}
+.creation-composer:focus-within {
+ border-color: #a9c378;
+ box-shadow:
+ 0 7px 35px #22351106,
+ 0 0 0 4px #dafa9321;
+}
+.creation-style-row {
+ display: flex;
+ align-items: center;
+ gap: 13px;
+ padding: 16px 19px 10px;
+}
+.creation-style-label {
+ font-size: 10px;
+ color: #9a9f94;
+ white-space: nowrap;
+}
+.creation-style-chips {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+}
+.creation-style-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ line-height: 1;
+ padding: 7px 9px;
+ border: 1px solid #edf0e9;
+ background: #fff;
+ color: #7c8674;
+ border-radius: 7px;
+ cursor: pointer;
+ transition:
+ background 0.2s,
+ border-color 0.2s;
+}
+.creation-style-chip > span {
+ font-family: Consolas, monospace;
+ font-size: 9px;
+ font-weight: 700;
+ color: #98a18f;
+}
+.creation-style-chip:hover {
+ background: #f6f9f0;
+}
+.creation-style-chip.is-selected {
+ background: #f1f8df;
+ border-color: #d9e7b4;
+ color: #405825;
+}
+.creation-style-chip.is-selected > span {
+ color: #7c9a42;
+}
+.creation-style-chip:disabled {
+ cursor: wait;
+ opacity: 0.6;
+}
+.creation-composer textarea {
+ display: block;
+ width: 100%;
+ resize: none;
+ border: 0 !important;
+ outline: 0 !important;
+ box-shadow: none !important;
+ background: none !important;
+ padding: 12px 21px 7px !important;
+ min-height: 76px;
+ max-height: 180px;
+ border-radius: 0;
+ font: inherit;
+ font-size: 14px !important;
+ line-height: 1.8;
+ color: #263526;
+}
+.creation-composer textarea::placeholder {
+ color: #b0b6aa;
+}
+.creation-composer textarea:disabled {
+ opacity: 0.65;
+}
+.creation-composer-footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 10px 13px 13px 21px;
+}
+.creation-composer-footer > span {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 10px;
+ line-height: 1.6;
+ color: #9da58f;
+}
+.creation-send {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ background: var(--creation-lime);
+ border: 0;
+ border-radius: 11px;
+ padding: 10px 15px;
+ font-size: 12px;
+ font-weight: 650;
+ color: #253b00;
+ white-space: nowrap;
+ cursor: pointer;
+ transition:
+ background 0.2s,
+ transform 0.2s;
+}
+.creation-send:hover:not(:disabled) {
+ background: #c5ff25;
+ transform: translateY(-1px);
+}
+.creation-send:disabled {
+ background: #edf1e5;
+ color: #b0b9a4;
+ cursor: default;
+}
+.creation-composer-hint {
+ text-align: center;
+ font-size: 9px;
+ color: #afb5a7;
+ margin: 13px 0 0;
+ letter-spacing: 0.01em;
+}
+.creation-composer-hint span {
+ padding: 0 7px;
+}
+.creation-workspace button:focus-visible,
+.creation-workspace a:focus-visible,
+.creation-artifact summary:focus-visible {
+ outline: 2px solid #8cae42;
+ outline-offset: 3px;
+}
+.creation-ideas {
+ max-width: 796px;
+ margin: 34px auto 0;
+}
+.creation-recent {
+ max-width: 796px;
+ margin: 30px auto 0;
+}
+.creation-recent-heading {
+ display: flex;
+ align-items: center;
+ gap: 11px;
+ padding-bottom: 11px;
+ border-bottom: 1px solid #e2e7d9;
+}
+.creation-recent-heading h2 {
+ margin: 0;
+ color: #7c8a6d;
+ font-size: 11px;
+ font-weight: 550;
+}
+.creation-recent-heading > span {
+ color: #b0b7a6;
+ font-size: 9px;
+}
+.creation-recent-list {
+ display: flex;
+ flex-direction: column;
+}
+.creation-recent-list a {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 14px 4px;
+ border-bottom: 1px solid #e9ede3;
+ color: #8d9c7b;
+ text-decoration: none;
+}
+.creation-recent-list a > span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: #7c8b6c;
+ font-size: 12px;
+}
+.creation-recent-list a > small {
+ margin-left: auto;
+ white-space: nowrap;
+ color: #a5b197;
+ font-size: 9px;
+}
+.creation-recent-list a > svg {
+ flex-shrink: 0;
+}
+.creation-recent-list a > svg:last-child {
+ transform: rotate(45deg);
+ color: #b2bda4;
+}
+.creation-recent-list a:hover {
+ background: #f0f5e7;
+ border-radius: 7px;
+}
+.creation-recent-error {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 13px 0;
+ color: #a5ad9a;
+ font-size: 10px;
+}
+.creation-recent-error button {
+ display: inline-flex;
+ gap: 5px;
+ align-items: center;
+ border: 0;
+ background: transparent;
+ color: #8d9f72;
+ font-size: 10px;
+ cursor: pointer;
+}
+.creation-ideas-heading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ font-size: 10px;
+ color: #9aab86;
+ margin-bottom: 14px;
+}
+.creation-idea-list {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 10px;
+}
+.creation-idea-list button {
+ position: relative;
+ text-align: left;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 8px;
+ padding: 17px 15px 19px;
+ border: 1px solid #e3e8dc;
+ border-radius: 12px;
+ background: #ffffff80;
+ cursor: pointer;
+ transition:
+ background 0.2s,
+ border-color 0.2s,
+ transform 0.2s;
+}
+.creation-idea-list button:hover {
+ background: #fff;
+ border-color: #bfce9b;
+ transform: translateY(-2px);
+}
+.creation-idea-index {
+ font-family: Consolas, monospace;
+ color: #adb79d;
+ font-size: 9px;
+}
+.creation-idea-list strong {
+ font-size: 12px;
+ font-weight: 550;
+ color: #5d6b52;
+}
+.creation-idea-list button > span:last-of-type {
+ font-size: 10px;
+ line-height: 1.8;
+ color: #a0a893;
+ max-width: 94%;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.creation-idea-list button > svg {
+ position: absolute;
+ right: 13px;
+ top: 16px;
+ color: #a4b091;
+ transform: rotate(45deg);
+}
+.has-conversation .creation-composer-dock {
+ position: sticky;
+ bottom: 0;
+ padding: 15px 0 18px;
+ background: linear-gradient(0deg, #f6f8f3 0%, #f6f8f3f5 90%, #f6f8f300 100%);
+}
+.has-conversation {
+ padding-bottom: 0;
+}
+.creation-thread {
+ max-width: 796px;
+ margin: 32px auto 20px;
+}
+.creation-thread-intro {
+ display: flex;
+ align-items: center;
+ gap: 11px;
+ padding: 0 0 28px;
+ border-bottom: 1px dashed #e0e5d7;
+ margin-bottom: 24px;
+}
+.creation-agent-avatar {
+ width: 36px;
+ height: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 12px 12px 12px 4px;
+ background: #e9f2d4;
+ color: #6d8738;
+ flex-shrink: 0;
+}
+.creation-thread-intro > div {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+}
+.creation-thread-intro strong {
+ font-size: 12px;
+ font-weight: 600;
+}
+.creation-thread-intro > div > span {
+ font-size: 10px;
+ color: #9da58f;
+}
+.creation-session-badge {
+ margin-left: auto;
+ background: #edf1e5;
+ border: 1px solid #e5eadd;
+ padding: 6px 9px;
+ border-radius: 20px;
+ color: #879275;
+ font-size: 10px;
+ white-space: nowrap;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+.creation-session-badge.is-running {
+ background: #f0f7dc;
+ color: #6b8c30;
+}
+.creation-live-dot {
+ width: 5px;
+ height: 5px;
+ background: #89ae42;
+ display: inline-block;
+ border-radius: 50%;
+ flex-shrink: 0;
+ box-shadow: 0 0 0 3px #94b34a12;
+}
+.creation-messages {
+ display: flex;
+ flex-direction: column;
+ gap: 22px;
+}
+.creation-system-message {
+ display: flex;
+ align-items: flex-start;
+ gap: 7px;
+ padding: 10px 4px;
+ font-size: 10px;
+ line-height: 1.9;
+ color: #9aa58b;
+}
+.creation-system-message > svg {
+ flex-shrink: 0;
+ margin-top: 3px;
+}
+.creation-message {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 7px;
+ max-width: 89%;
+}
+.creation-message-label {
+ font-size: 9px;
+ color: #a1aa95;
+ padding: 0 4px;
+}
+.creation-message-content {
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ font-size: 13px;
+ line-height: 1.9;
+ padding: 15px 18px;
+ background: #fff;
+ border: 1px solid #e7ebe0;
+ border-radius: 4px 15px 15px 15px;
+ color: #526046;
+}
+.creation-message.is-user {
+ align-self: flex-end;
+ align-items: flex-end;
+}
+.creation-message.is-user .creation-message-content {
+ background: #eaf1db;
+ border-color: #e2ebcf;
+ border-radius: 15px 4px 15px 15px;
+ color: #485e2e;
+}
+.creation-message.is-pending {
+ opacity: 0.6;
+}
+.creation-thinking {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 15px 3px;
+}
+.creation-thinking > span {
+ height: 4px;
+ width: 4px;
+ border-radius: 50%;
+ background: #a0b17e;
+ animation: creation-pulse 1.4s ease-in-out infinite;
+}
+.creation-thinking > span:nth-child(2) {
+ animation-delay: 0.15s;
+}
+.creation-thinking > span:nth-child(3) {
+ animation-delay: 0.3s;
+}
+.creation-thinking p {
+ margin: 0 0 0 6px;
+ color: #9ca88c;
+ font-size: 11px;
+}
+.creation-runs {
+ display: flex;
+ flex-direction: column;
+ gap: 18px;
+ margin-top: 24px;
+}
+.creation-session-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 15px 0;
+ color: #9ca88c;
+ font-size: 11px;
+}
+.creation-run {
+ border: 1px solid #dfe6d3;
+ background: #fff;
+ border-radius: 16px;
+ overflow: hidden;
+ box-shadow: 0 4px 20px #203b0a03;
+}
+.creation-run-heading {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 21px 22px 18px;
+}
+.creation-run-symbol {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 38px;
+ height: 38px;
+ flex-shrink: 0;
+ border-radius: 12px;
+ color: #7b963f;
+ background: #f2f7e5;
+}
+.creation-run-title {
+ flex: 1;
+ min-width: 0;
+}
+.creation-run-title h2 {
+ font-size: 13px;
+ font-weight: 550;
+ line-height: 1.7;
+ margin: 3px 0 0;
+ color: #4b603b;
+}
+.creation-run-title .creation-eyebrow {
+ font-size: 8px;
+}
+.creation-quiet-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ color: #8c967f;
+ background: transparent;
+ border: 1px solid #e7ebdf;
+ border-radius: 7px;
+ font-size: 10px;
+ white-space: nowrap;
+ padding: 6px 8px;
+ cursor: pointer;
+}
+.creation-quiet-button:hover {
+ border-color: #c5d0b1;
+ color: #5b713e;
+}
+.creation-quiet-button:disabled {
+ opacity: 0.5;
+ cursor: wait;
+}
+.creation-run-progress {
+ height: 3px;
+ background: #f0f3ea;
+ margin: 0 22px;
+ border-radius: 5px;
+ overflow: hidden;
+}
+.creation-run-progress i {
+ display: block;
+ height: 100%;
+ background: #b0d54f;
+ transition: width 0.8s ease;
+}
+.creation-run-phases {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ padding: 15px 22px 18px;
+ margin: 0;
+ list-style: none;
+ gap: 7px;
+}
+.creation-run-phases li {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ color: #b5bdab;
+ font-size: 9px;
+ white-space: nowrap;
+}
+.creation-run-phases li.is-active {
+ color: #6b8b33;
+}
+.creation-run-phases li.is-done {
+ color: #91a76c;
+}
+.creation-run-note {
+ font-size: 11px;
+ color: #a0aa92;
+ line-height: 1.8;
+ margin: 0;
+ padding: 0 22px 18px;
+}
+.creation-run-error {
+ font-size: 11px;
+ line-height: 1.9;
+ padding: 12px 15px;
+ background: #fff7f3;
+ border-radius: 8px;
+ color: #b17c65;
+ margin: 0 20px 16px;
+ overflow-wrap: anywhere;
+}
+.creation-artifact {
+ border-top: 1px solid #eff1eb;
+}
+.creation-artifact summary {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 13px 22px;
+ cursor: pointer;
+ list-style: none;
+ font-size: 11px;
+ color: #859277;
+ user-select: none;
+}
+.creation-artifact summary::-webkit-details-marker {
+ display: none;
+}
+.creation-artifact summary > svg:first-child {
+ color: #a9b09f;
+}
+.creation-artifact summary > svg:last-child {
+ color: #b1baa4;
+ transition: transform 0.2s;
+}
+.creation-artifact[open] summary > svg:last-child {
+ transform: rotate(180deg);
+}
+.creation-artifact-meta {
+ margin-left: auto;
+ font-size: 9px;
+ color: #afb6a6;
+}
+.creation-copy {
+ font-size: 12px;
+ line-height: 2.1;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ padding: 0 24px 21px;
+ color: #77856a;
+}
+.creation-script-list {
+ list-style: none;
+ padding: 0 22px 18px;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 15px;
+}
+.creation-script-list li {
+ display: flex;
+ gap: 12px;
+}
+.creation-script-list li > span {
+ font-size: 10px;
+ font-family: Consolas, monospace;
+ color: #b2bca0;
+ line-height: 2;
+}
+.creation-script-list li > div {
+ min-width: 0;
+}
+.creation-script-list p {
+ font-size: 11px;
+ color: #738561;
+ line-height: 1.9;
+ margin: 0;
+}
+.creation-script-list small {
+ display: block;
+ font-size: 10px;
+ color: #abb39f;
+ line-height: 1.9;
+ margin-top: 4px;
+ overflow-wrap: anywhere;
+}
+.creation-picture-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 9px;
+ padding: 0 22px 18px;
+}
+.creation-picture-grid figure {
+ margin: 0;
+}
+.creation-picture-grid img {
+ display: block;
+ aspect-ratio: 9/12;
+ width: 100%;
+ object-fit: cover;
+ border-radius: 8px;
+ background: #f0f3e9;
+}
+.creation-picture-grid figcaption {
+ font-family: Consolas, monospace;
+ font-size: 8px;
+ color: #a4af94;
+ margin-top: 6px;
+}
+.creation-final {
+ border-top: 1px solid #edf1e6;
+}
+.creation-video-frame {
+ display: flex;
+ justify-content: center;
+ background: #20281f;
+ padding: 16px;
+ min-height: 220px;
+}
+.creation-video-frame video {
+ display: block;
+ max-height: 470px;
+ max-width: 100%;
+ min-height: 200px;
+ border-radius: 8px;
+ background: #151b12;
+}
+.creation-final-description {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 21px 22px;
+}
+.creation-final-description h3 {
+ margin: 6px 0;
+ font-size: 14px;
+ font-weight: 600;
+ color: #496030;
+}
+.creation-final-description p {
+ font-size: 10px;
+ color: #a6b195;
+ margin: 0;
+}
+.creation-download-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 10px 14px;
+ white-space: nowrap;
+ font-size: 11px;
+ font-weight: 600;
+ border-radius: 9px;
+ border: 0;
+ color: #344e10;
+ background: var(--creation-lime);
+ cursor: pointer;
+}
+.creation-download-button:hover {
+ background: #c5ff25;
+}
+.creation-download-button:disabled {
+ opacity: 0.6;
+ cursor: wait;
+}
+.creation-result-hint {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ margin: 0;
+ padding: 0 22px 20px;
+ color: #a1ad92;
+ font-size: 10px;
+}
+.creation-run.is-completed .creation-run-symbol {
+ background: #e8f4c8;
+ color: #7c9e39;
+}
+.creation-run.is-failed .creation-run-symbol {
+ background: #fcf0e7;
+ color: #bc9171;
+}
+.creation-run.is-failed .creation-run-title h2 {
+ color: #9f8168;
+}
+.creation-error {
+ margin-bottom: 12px;
+ font-size: 12px;
+}
+.creation-connection {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 7px;
+ font-size: 10px;
+ color: #a49d77;
+ margin: 0 0 12px;
+}
+.creation-loading {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ color: #9baa83;
+ padding: 140px 0;
+ font-size: 13px;
+}
+.creation-sr-only {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0, 0, 0, 0);
+ white-space: nowrap;
+ border: 0;
+}
+.creation-spin {
+ animation: creation-spin 1.2s linear infinite;
+}
+@keyframes creation-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@keyframes creation-pulse {
+ 0%,
+ 70%,
+ 100% {
+ opacity: 0.35;
+ transform: translateY(0);
+ }
+ 35% {
+ opacity: 1;
+ transform: translateY(-3px);
+ }
+}
+@media (min-width: 900px) {
+ .creation-welcome {
+ animation: creation-enter 0.55s ease both;
+ }
+ .creation-workspace:not(.has-conversation) .creation-composer-dock {
+ animation: creation-enter 0.55s 0.08s ease both;
+ }
+ .creation-ideas {
+ animation: creation-enter 0.55s 0.16s ease both;
+ }
+ @keyframes creation-enter {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ }
+}
+@media (max-width: 760px) {
+ .creation-workspace {
+ padding: 0 6px 35px;
+ }
+ .creation-topbar {
+ gap: 12px;
+ min-height: 53px;
+ }
+ .creation-topbar-label {
+ font-size: 10px;
+ }
+ .creation-topbar-label span {
+ padding: 0 5px;
+ }
+ .creation-back,
+ .creation-new {
+ font-size: 10px;
+ }
+ .creation-new {
+ padding: 7px 9px;
+ }
+ .creation-welcome {
+ padding: 34px 0 24px;
+ }
+ .creation-welcome h1 {
+ font-size: 36px;
+ }
+ .creation-welcome-description {
+ font-size: 12px;
+ }
+ .creation-defaults {
+ font-size: 9px;
+ gap: 9px;
+ }
+ .creation-style-row {
+ align-items: flex-start;
+ gap: 9px;
+ padding: 14px 14px 8px;
+ }
+ .creation-style-label {
+ padding-top: 8px;
+ font-size: 9px;
+ }
+ .creation-style-chips {
+ gap: 5px;
+ }
+ .creation-style-chip {
+ font-size: 10px;
+ padding: 7px;
+ }
+ .creation-composer textarea {
+ padding: 12px 15px 8px !important;
+ font-size: 13px !important;
+ }
+ .creation-composer-footer {
+ padding: 9px 11px 12px 15px;
+ }
+ .creation-composer-footer > span {
+ font-size: 9px;
+ max-width: 65%;
+ }
+ .creation-send {
+ font-size: 11px;
+ padding: 9px 11px;
+ }
+ .creation-ideas {
+ margin-top: 25px;
+ }
+ .creation-idea-list {
+ gap: 7px;
+ }
+ .creation-idea-list button {
+ padding: 12px 11px 14px;
+ }
+ .creation-idea-list strong {
+ font-size: 10px;
+ }
+ .creation-idea-list button > span:last-of-type {
+ font-size: 9px;
+ max-width: 100%;
+ }
+ .creation-composer-hint {
+ font-size: 8px;
+ }
+ .creation-thread {
+ margin-top: 23px;
+ }
+ .creation-run-heading {
+ padding: 17px 15px 15px;
+ gap: 9px;
+ }
+ .creation-run-title h2 {
+ font-size: 12px;
+ }
+ .creation-run-symbol {
+ width: 31px;
+ height: 31px;
+ }
+ .creation-run-progress {
+ margin: 0 15px;
+ }
+ .creation-run-phases {
+ padding: 13px 15px 16px;
+ }
+ .creation-run-phases li {
+ font-size: 8px;
+ gap: 4px;
+ }
+ .creation-artifact summary {
+ padding: 12px 15px;
+ }
+ .creation-final-description {
+ padding: 17px 15px;
+ }
+ .creation-final-description h3 {
+ font-size: 12px;
+ }
+ .creation-result-hint {
+ padding: 0 15px 17px;
+ font-size: 9px;
+ }
+ .creation-picture-grid {
+ padding: 0 15px 16px;
+ gap: 7px;
+ }
+ .creation-copy {
+ padding: 0 16px 18px;
+ }
+ .creation-message-content {
+ font-size: 12px;
+ padding: 12px 14px;
+ }
+ .has-conversation {
+ padding-bottom: 0;
+ }
+ .has-conversation .creation-composer-dock {
+ padding-bottom: 12px;
+ }
+ .creation-final-description .creation-eyebrow {
+ font-size: 8px;
+ }
+}
+@media (max-width: 450px) {
+ .creation-topbar-label {
+ max-width: 40%;
+ }
+ .creation-welcome h1 {
+ font-size: 32px;
+ }
+ .creation-mobile-break {
+ display: block;
+ }
+ .creation-welcome-description {
+ font-size: 11px;
+ }
+ .creation-style-label {
+ display: none;
+ }
+ .creation-style-row {
+ padding-bottom: 7px;
+ }
+ .creation-idea-list {
+ grid-template-columns: 1fr;
+ }
+ .creation-idea-list button {
+ display: grid;
+ grid-template-columns: 22px 1fr;
+ gap: 5px 8px;
+ padding: 11px 14px;
+ }
+ .creation-idea-index {
+ grid-row: 1/3;
+ padding-top: 2px;
+ }
+ .creation-idea-list button > span:last-of-type {
+ -webkit-line-clamp: 1;
+ max-width: 95%;
+ }
+ .creation-idea-list button > svg {
+ top: 14px;
+ right: 13px;
+ }
+ .creation-session-badge {
+ font-size: 9px;
+ padding: 5px 7px;
+ }
+ .creation-thread-intro > div > span {
+ font-size: 9px;
+ }
+ .creation-thread-intro strong {
+ font-size: 11px;
+ }
+ .creation-run-phases li {
+ gap: 3px;
+ }
+ .creation-run-phases {
+ gap: 3px;
+ }
+ .creation-run-phases li svg {
+ width: 10px;
+ }
+ .creation-quiet-button {
+ font-size: 9px;
+ padding: 6px;
+ }
+ .creation-run-title h2 {
+ font-size: 11px;
+ }
+ .creation-picture-grid {
+ grid-template-columns: repeat(3, 1fr);
+ }
+ .creation-download-button {
+ font-size: 10px;
+ padding: 9px 10px;
+ }
+ .creation-composer-hint {
+ font-size: 7px;
+ }
+ .creation-message {
+ max-width: 94%;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .creation-workspace * {
+ animation: none !important;
+ scroll-behavior: auto !important;
+ transition: none !important;
+ }
+}
diff --git a/frontend/src/pages/studio/imageTextStoryboard.css b/frontend/src/pages/studio/imageTextStoryboard.css
new file mode 100644
index 0000000..2b48d00
--- /dev/null
+++ b/frontend/src/pages/studio/imageTextStoryboard.css
@@ -0,0 +1,69 @@
+.pf-image-storyboard { max-width: 1440px; margin: 0 auto; color: #283022; }
+.pf-is-header { display: flex; justify-content: space-between; align-items: center; gap: 24px; margin-bottom: 28px; }
+.pf-is-header h1 { margin: 16px 0 10px; font-size: clamp(26px, 2.5vw, 34px); letter-spacing: -.035em; line-height: 1.3; overflow-wrap: anywhere; }
+.pf-is-header p { margin: 0; color: #87917e; font-size: 13px; }
+.pf-is-header p > span { margin: 0 10px; }
+.pf-is-header-actions, .pf-is-next-buttons { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
+.pf-image-storyboard .pf-btn { display: inline-flex; align-items: center; justify-content: center; gap: 7px; border-radius: 10px; }
+.pf-is-steps { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); margin-bottom: 26px; border: 1px solid #e3e7dc; border-radius: 14px; padding: 6px; background: #fff; gap: 6px; }
+.pf-is-steps button { display: flex; align-items: center; justify-content: center; gap: 10px; padding: 17px 10px; border: 0; border-radius: 10px; color: #98a08f; background: transparent; font: inherit; cursor: pointer; }
+.pf-is-steps button > span { width: 27px; height: 27px; display: grid; place-items: center; border-radius: 8px; background: #f0f2ed; font-size: 12px; }
+.pf-is-steps button > strong { font-size: 13px; font-weight: 600; }
+.pf-is-steps .is-complete { color: #647b43; }
+.pf-is-steps .is-current { background: #edf5da; color: #41572a; }
+.pf-is-steps .is-current > span { background: #bddf7b; }
+.pf-is-steps button:disabled { cursor: default; }
+.pf-is-steps button:focus-visible { outline: 2px solid #91b73b; outline-offset: 1px; }
+.pf-is-progress { display: flex; align-items: center; gap: 18px; padding: 18px 22px; border: 1px solid #dce8c6; border-radius: 12px; background: #f4f8ec; margin: 0 0 24px; font-size: 12px; }
+.pf-is-progress > div:first-child { flex: 1; }
+.pf-is-progress strong { font-size: 14px; }
+.pf-is-progress p { margin: 6px 0 0; color: #839174; line-height: 1.7; }
+.pf-is-progress-track { width: 180px; height: 5px; border-radius: 5px; background: #e1e8d5; overflow: hidden; }
+.pf-is-progress-track > span { height: 100%; display: block; background: #a2c866; transition: width .3s; }
+.pf-is-resume-note { padding: 15px 20px; background: #fcf7e9; border-radius: 10px; color: #8c7742; font-size: 13px; }
+.pf-is-section { border: 1px solid #e3e7dd; border-radius: 18px; background: #fff; padding: 28px; }
+.pf-is-section-head { display: flex; justify-content: space-between; align-items: center; gap: 18px; margin-bottom: 25px; }
+.pf-is-eyebrow { color: #8d9c7c; font-size: 10px; letter-spacing: .13em; font-weight: 600; }
+.pf-is-section-head h2 { font-size: 21px; margin: 9px 0; letter-spacing: -.02em; }
+.pf-is-section-head p { color: #8a9580; font-size: 12px; margin: 0; line-height: 1.8; }
+.pf-is-copy { border: 1px solid #e7ebdf; border-radius: 11px; background: #fafbf8; padding: 16px 18px; margin-bottom: 24px; }
+.pf-is-copy summary { font-size: 13px; font-weight: 550; cursor: pointer; }
+.pf-is-copy summary > span { color: #9aa38f; font-weight: 400; margin-left: 8px; font-size: 11px; }
+.pf-is-copy p { white-space: pre-wrap; overflow-wrap: anywhere; color: #67735c; font-size: 13px; line-height: 1.95; margin: 16px 0 0; }
+.pf-is-script-card { min-width: 0; display: flex; flex-direction: column; padding: 22px; border: 1px solid #e2e6dc; border-radius: 16px; background: #fff; }
+.pf-is-script-card header { display: flex; justify-content: space-between; color: #8a987a; font-size: 11px; }
+.pf-is-script-card h3 { margin: 18px 0 21px; font-size: 18px; line-height: 1.5; }
+.pf-is-script-field { margin-bottom: 18px; }
+.pf-is-script-field > label { color: #94a087; font-size: 10px; letter-spacing: .09em; }
+.pf-is-script-field > p { font-size: 13px; line-height: 1.85; margin: 7px 0 0; color: #5d6b51; white-space: pre-wrap; overflow-wrap: anywhere; max-height: 200px; overflow-y: auto; }
+.pf-is-script-card footer { display: flex; justify-content: space-between; gap: 6px; flex-wrap: wrap; margin-top: auto; padding-top: 17px; border-top: 1px solid #edf0e7; }
+.pf-is-audio { display: flex; gap: 18px; align-items: center; flex-wrap: wrap; padding: 18px 20px; border: 1px solid #e5e9de; border-radius: 12px; background: #fafbf7; margin-bottom: 24px; }
+.pf-is-audio > div { display: flex; align-items: center; gap: 12px; flex: 1; color: #758365; min-width: 220px; }
+.pf-is-audio strong { font-size: 13px; color: #3e4e30; }
+.pf-is-audio p { margin: 5px 0 0; font-size: 11px; line-height: 1.8; color: #919d84; }
+.pf-is-audio audio { width: 280px; max-width: 100%; height: 36px; }
+.pf-is-media-card .pf-shared-project-actions { margin: 0; padding: 0 18px 17px; justify-content: space-between; }
+.pf-is-media-card .pf-shared-project-actions .pf-btn { color: #697d52; }
+.pf-is-empty { min-height: 310px; padding: 40px 20px; display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; color: #8d9d7a; }
+.pf-is-empty h3 { color: #58684a; margin: 22px 0 8px; font-size: 17px; }
+.pf-is-empty p { margin: 0; font-size: 13px; line-height: 1.8; max-width: 30em; }
+.pf-is-final { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 46px; align-items: center; padding: 16px 20px 24px; }
+.pf-is-final-player { background: #162018; border-radius: 16px; overflow: hidden; text-align: center; }
+.pf-is-final-player video { width: 100%; max-height: 580px; display: block; }
+.pf-is-final h3 { font-size: 26px; line-height: 1.5; margin: 23px 0 12px; overflow-wrap: anywhere; }
+.pf-is-final p { margin: 0 0 28px; font-size: 13px; color: #8b987f; }
+.pf-is-final > div:last-child { display: flex; align-items: flex-start; flex-direction: column; gap: 12px; }
+.pf-is-complete { display: inline-flex; align-items: center; gap: 7px; padding: 7px 10px; border-radius: 7px; background: #edf5e3; color: #668747; font-size: 12px; }
+.pf-is-next { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 18px; border: 1px solid #e3e7dd; border-radius: 14px; background: #fff; margin-top: 22px; padding: 20px 24px; }
+.pf-is-next strong { font-size: 14px; }
+.pf-is-next p { margin: 7px 0 0; font-size: 12px; color: #8b977e; line-height: 1.7; }
+@media (max-width: 1000px) { .pf-is-header { align-items: flex-start; } .pf-is-header-actions { justify-content: flex-end; } .pf-is-final { gap: 24px; padding: 0; } .pf-is-progress-track { width: 100px; } }
+@media (max-width: 700px) {
+ .pf-is-header { flex-wrap: wrap; gap: 18px; } .pf-is-header h1 { font-size: 25px; } .pf-is-header-actions { justify-content: flex-start; }
+ .pf-is-steps { gap: 2px; padding: 4px; } .pf-is-steps button { flex-direction: column; gap: 7px; padding: 13px 3px; } .pf-is-steps button > strong { font-size: 11px; }
+ .pf-is-section { padding: 18px; } .pf-is-section-head { gap: 12px; align-items: flex-start; } .pf-is-section-head h2 { font-size: 19px; } .pf-is-section-head .pf-btn { padding: 7px 9px; font-size: 11px; white-space: nowrap; }
+ .pf-is-progress { flex-wrap: wrap; padding: 15px; gap: 10px; } .pf-is-progress > div:first-child { flex-basis: 100%; } .pf-is-progress-track { flex: 1; }
+ .pf-is-audio { padding: 16px; } .pf-is-audio audio { width: 100%; } .pf-is-final { grid-template-columns: minmax(0, 1fr); } .pf-is-final-player video { max-height: 450px; }
+ .pf-is-next { padding: 18px; } .pf-is-next-buttons { width: 100%; } .pf-is-next-buttons .pf-btn-lime { flex: 1; } .pf-is-script-card { padding: 18px; }
+}
+@media (prefers-reduced-motion: reduce) { .pf-is-progress-track > span { transition: none; } }
diff --git a/frontend/src/pages/studio/shortVideoCreate.css b/frontend/src/pages/studio/shortVideoCreate.css
new file mode 100644
index 0000000..90bc4a8
--- /dev/null
+++ b/frontend/src/pages/studio/shortVideoCreate.css
@@ -0,0 +1,52 @@
+.sv-create-page { max-width: 1440px; margin: 0 auto; padding-bottom: 48px; color: #202c23; }
+.sv-create-header { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin-bottom: 28px; }
+.sv-back { display: inline-flex; align-items: center; gap: 8px; color: #647369; font-size: 13px; text-decoration: none; }
+.sv-create-header h1 { font-size: 28px; margin: 12px 0 6px; letter-spacing: -.5px; }
+.sv-create-header p, .sv-section-heading p, .sv-settings > p { color: #7a867c; font-size: 13px; margin: 0; line-height: 1.6; }
+.sv-create-grid { display: grid; grid-template-columns: minmax(0, 1fr) 290px; gap: 22px; align-items: start; }
+.sv-create-grid main { min-width: 0; }
+.sv-panel { border: 1px solid #e3e8df; border-radius: 18px; background: white; padding: 26px; margin-bottom: 20px; }
+.sv-panel h2 { font-size: 17px; margin: 0 0 7px; }
+.sv-section-heading { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 22px; }
+.sv-section-heading > span { display: grid; place-items: center; height: 30px; width: 30px; border-radius: 9px; background: #f0f7e3; color: #607e22; font-size: 12px; font-weight: 700; flex-shrink: 0; }
+.sv-style-grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
+.sv-style-card { position: relative; border: 1px solid #e4e8e1; border-radius: 13px; background: #fff; padding: 0; overflow: hidden; text-align: left; cursor: pointer; min-width: 0; color: inherit; }
+.sv-style-card:hover { border-color: #a3c85b; }
+.sv-style-card.is-selected { border-color: #93bf36; box-shadow: 0 0 0 2px #c9ed844a; background: #f8fcee; }
+.sv-style-card img { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; display: block; }
+.sv-style-card > div { padding: 11px; }
+.sv-style-card strong { display: block; font-size: 13px; }
+.sv-style-card p { font-size: 11px; color: #839078; line-height: 1.6; margin: 6px 0 0; }
+.sv-style-check { position: absolute; right: 8px; top: 8px; width: 23px; height: 23px; border-radius: 50%; background: #c5fa68; display: grid; place-items: center; }
+.sv-input-tabs { display: inline-flex; padding: 4px; border-radius: 10px; background: #f3f5ef; margin-bottom: 18px; gap: 3px; }
+.sv-input-tabs button { background: transparent; color: #78816d; border: 0; border-radius: 7px; padding: 8px 15px; cursor: pointer; }
+.sv-input-tabs button.is-active { background: white; color: #293321; box-shadow: 0 1px 4px #2f3f1420; font-weight: 600; }
+.sv-field { display: flex; flex-direction: column; gap: 9px; margin: 0 0 20px; font-size: 13px; font-weight: 500; }
+.sv-field > span { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
+.sv-field small { color: #9aa18e; font-weight: 400; }
+.sv-field textarea, .sv-field input, .sv-field select { width: 100%; border: 1px solid #dfe5d9; border-radius: 10px; background: #fbfcf9; padding: 12px 14px; font: inherit; font-weight: 400; color: #293328; line-height: 1.8; box-sizing: border-box; }
+.sv-field textarea { resize: vertical; min-height: 150px; }
+.sv-field textarea:focus, .sv-field input:focus, .sv-field select:focus { outline: 2px solid #bae56b80; outline-offset: 1px; border-color: #a6c95e; }
+.sv-field textarea::placeholder { color: #a1a99a; }
+.sv-examples { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 24px; }
+.sv-examples button { border: 1px solid #e4e8dc; background: white; border-radius: 20px; padding: 6px 10px; font-size: 11px; color: #7e8874; cursor: pointer; }
+.sv-actions { display: flex; align-items: center; justify-content: space-between; gap: 16px; border-top: 1px solid #f0f2eb; padding-top: 20px; }
+.sv-action-buttons { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
+.sv-actions > span, .sv-saved-note { font-size: 12px; color: #929c87; line-height: 1.6; }
+.sv-settings { position: sticky; top: 20px; padding: 24px; }
+.sv-settings > p { margin-bottom: 24px; }
+.sv-setting-summary, .sv-workflow-hint { border-top: 1px solid #eaf0e0; padding-top: 20px; display: flex; gap: 10px; color: #697956; margin-top: 24px; }
+.sv-setting-summary strong, .sv-setting-summary span { display: block; }
+.sv-setting-summary strong { font-size: 13px; }
+.sv-setting-summary span { font-size: 11px; margin-top: 7px; line-height: 1.6; color: #98a08d; }
+.sv-workflow-hint { background: #f7faef; border: 0; padding: 13px; border-radius: 10px; }
+.sv-workflow-hint svg { flex-shrink: 0; margin-top: 2px; }
+.sv-workflow-hint p { margin: 0; font-size: 12px; line-height: 1.8; }
+.sv-running-note { background: #f6faec; border: 1px solid #deebc4; padding: 16px; border-radius: 12px; margin-bottom: 20px; font-size: 13px; }
+.sv-running-note a { display: inline-flex; align-items: center; gap: 4px; margin-left: 12px; }
+.sv-loading { display: flex; align-items: center; justify-content: center; gap: 12px; padding: 80px 20px; color: #8d987e; }
+.sv-spin { animation: sv-rotate 1s linear infinite; }
+@keyframes sv-rotate { to { transform: rotate(360deg); } }
+@media (max-width: 1150px) { .sv-create-header { align-items: flex-start; flex-direction: column; } .sv-create-grid { grid-template-columns: minmax(0, 1fr) 250px; } .sv-style-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+@media (max-width: 800px) { .sv-create-grid { grid-template-columns: minmax(0, 1fr); } .sv-settings { position: static; } .sv-panel { padding: 20px; } .sv-create-header .pf-stepper { flex-wrap: wrap; row-gap: 12px; } .sv-create-header .pf-step { font-size: 11px; gap: 5px; } .sv-create-header .pf-step-line { width: 12px; margin: 0 5px; } .sv-create-header .pf-step-dot { width: 23px; height: 23px; } .sv-actions { flex-wrap: wrap; } .sv-actions > span { width: 100%; } }
+@media (prefers-reduced-motion: reduce) { .sv-spin { animation: none; } }
diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.css
index 1c75ece..64ef57f 100644
--- a/frontend/src/styles/printfilm.css
+++ b/frontend/src/styles/printfilm.css
@@ -672,7 +672,7 @@
.pf-land-pipeline-list {
display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
+ grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 0.85rem;
margin: 0;
padding: 0;
diff --git a/frontend/tests/creation-catalog.test.mjs b/frontend/tests/creation-catalog.test.mjs
new file mode 100644
index 0000000..4936af6
--- /dev/null
+++ b/frontend/tests/creation-catalog.test.mjs
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ CREATION_TEMPLATE_IDS,
+ creationTemplateId,
+ curatedCreationTemplates,
+} from '../src/lib/creationTemplates.ts'
+import { creationApiErrorDetail } from '../src/lib/creationApiError.ts'
+
+test('旧服务端返回全部模板时,新创作只展示固定顺序的四个非真人模板', () => {
+ const legacy = [
+ { id: 'real_person', name: '真人街访', preview_cover: '/real.png' },
+ { id: 'kids_flat', name: '儿童绘本扁平', default_ratio: '16:9' },
+ { id: 'ink_guofeng', name: '水墨国风' },
+ { id: 'soft_anime', name: '柔光动漫' },
+ { id: 'anim_3d', name: '旧动画名称', preview_cover: '/3d.png', seedream_config: { strength: 0.8 } },
+ { id: 'photorealistic', name: '写实摄影' },
+ { id: 'anim_3d', name: '旧动画名称', preview_cover: '/3d.png', seedream_config: { strength: 0.8 } },
+ ]
+ const before = structuredClone(legacy)
+ const curated = curatedCreationTemplates(legacy)
+ assert.deepEqual(curated.map((item) => item.id), CREATION_TEMPLATE_IDS)
+ assert.deepEqual(curated.map((item) => item.name), ['3D 动画', '二维动漫', '绘本插画', '国风水墨'])
+ assert.ok(curated.every((item) => item.default_ratio === '9:16'))
+ assert.equal(curated[0].preview_cover, '/3d.png')
+ assert.deepEqual(curated[0].seedream_config, { strength: 0.8 })
+ assert.deepEqual(legacy, before)
+})
+
+test('精选模板未返回时不伪造可用素材,旧画风链接回到默认3D', () => {
+ assert.deepEqual(curatedCreationTemplates([]), [])
+ assert.deepEqual(curatedCreationTemplates([{ id: 'real_person' }]), [])
+ assert.deepEqual(curatedCreationTemplates([{ id: 'ink_guofeng' }]).map((item) => item.id), ['ink_guofeng'])
+ assert.equal(creationTemplateId('real_person'), 'anim_3d')
+ assert.equal(creationTemplateId(null), 'anim_3d')
+ assert.equal(creationTemplateId('ink_guofeng'), 'ink_guofeng')
+})
+
+test('接口404与会话404分别说明原因,余额不足和其他业务错误保留原详情', () => {
+ const endpointError = creationApiErrorDetail(404, 'Not Found')
+ const sessionError = creationApiErrorDetail(404, '创作会话不存在')
+ assert.match(endpointError, /接口尚未加载/)
+ assert.match(sessionError, /创作会话不存在/)
+ assert.doesNotMatch(sessionError, /重启/)
+ const billing = { code: 'insufficient_balance', message: '余额不足' }
+ assert.equal(creationApiErrorDetail(402, billing), billing)
+ assert.equal(creationApiErrorDetail(404, '关联项目不存在'), '关联项目不存在')
+ assert.equal(creationApiErrorDetail(503, '服务暂不可用'), '服务暂不可用')
+})
diff --git a/frontend/tests/creation-session.test.mjs b/frontend/tests/creation-session.test.mjs
new file mode 100644
index 0000000..3d9fa6c
--- /dev/null
+++ b/frontend/tests/creation-session.test.mjs
@@ -0,0 +1,139 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ activeCreationRun,
+ buildCreationSubmission,
+ creationMessageId,
+ creationPhaseIndex,
+ creationStatusLabel,
+ isCreationBusy,
+} from '../src/lib/creationSession.ts'
+
+test('会话优先展示服务端指定版本,没有 active_run_id 时恢复最新版', () => {
+ const runs = [
+ { id: 1, version: 1, status: 'completed', phase: 'done' },
+ { id: 2, version: 2, status: 'running', phase: 'assets' },
+ ]
+ assert.equal(activeCreationRun({ runs, active_run_id: '1' }).id, 1)
+ assert.equal(activeCreationRun({ runs }).id, 2)
+ assert.equal(activeCreationRun(null), undefined)
+})
+
+test('终态不会被旧版本运行状态阻塞,新任务或未知状态用当前版本恢复', () => {
+ const runs = [{ id: 1, version: 1, status: 'running', phase: 'script' }]
+ for (const status of ['completed', 'failed', 'cancelled', 'drafting'])
+ assert.equal(isCreationBusy({ status, runs }), false)
+ for (const status of ['thinking', 'generating'])
+ assert.equal(isCreationBusy({ status, runs: [] }), true)
+ assert.equal(isCreationBusy({ status: 'recovering', runs }), true)
+ assert.equal(isCreationBusy(null), false)
+})
+
+test('阶段映射与旧 copy 命名兼容,未知阶段安全落到文案', () => {
+ assert.equal(creationPhaseIndex('copy'), 0)
+ assert.equal(creationPhaseIndex('script'), 1)
+ assert.equal(creationPhaseIndex('assets'), 2)
+ assert.equal(creationPhaseIndex('compose'), 3)
+ assert.equal(creationPhaseIndex('done'), 4)
+ assert.equal(creationPhaseIndex('new-phase'), 0)
+ assert.equal(creationStatusLabel('completed'), '已完成')
+ assert.equal(creationStatusLabel('new-status'), '创作中')
+})
+
+test('每条新消息的幂等键均唯一', () => {
+ const ids = Array.from({ length: 50 }, () => creationMessageId())
+ assert.equal(new Set(ids).size, ids.length)
+ assert.ok(ids.every((id) => typeof id === 'string' && id.length > 10))
+})
+
+test('初次默认不强制3D,首句国风与后续自然语言画风均可由后端决策', () => {
+ const first = buildCreationSubmission({
+ content: ' 用国风水墨做节气视频 ',
+ selectedTemplateId: 'anim_3d',
+ })
+ assert.equal(first.content, '用国风水墨做节气视频')
+ assert.equal(first.templateId, undefined)
+ assert.equal(JSON.stringify(first).includes('templateId'), false)
+ const defaultStyle = buildCreationSubmission({
+ content: '做一条月亮科普',
+ selectedTemplateId: 'anim_3d',
+ })
+ assert.equal(defaultStyle.templateId, undefined)
+ const followup = buildCreationSubmission({
+ content: '改成国风水墨',
+ sessionId: '12',
+ selectedTemplateId: 'anim_3d',
+ })
+ assert.equal(followup.templateId, undefined)
+ assert.equal(JSON.stringify(followup).includes('templateId'), false)
+ const explicit = buildCreationSubmission({
+ content: '旁白再活泼一点',
+ sessionId: '12',
+ selectedTemplateId: 'ink_guofeng',
+ explicitTemplateId: 'ink_guofeng',
+ })
+ assert.equal(explicit.templateId, 'ink_guofeng')
+ assert.equal(
+ buildCreationSubmission({ content: ' \n ', selectedTemplateId: 'anim_3d' }),
+ null,
+ )
+})
+
+test('非默认预选和明确选择3D仍作为用户风格选择提交', () => {
+ const preselected = buildCreationSubmission({
+ content: '做一条月亮科普',
+ selectedTemplateId: 'ink_guofeng',
+ })
+ assert.equal(preselected.templateId, 'ink_guofeng')
+ const explicitDefault = buildCreationSubmission({
+ content: '用国风水墨做节气视频',
+ selectedTemplateId: 'anim_3d',
+ explicitTemplateId: 'anim_3d',
+ })
+ assert.equal(explicitDefault.templateId, 'anim_3d')
+ const explicitFollowup = buildCreationSubmission({
+ content: '换个画风',
+ sessionId: '12',
+ selectedTemplateId: 'anim_3d',
+ explicitTemplateId: 'anim_3d',
+ })
+ assert.equal(explicitFollowup.templateId, 'anim_3d')
+})
+
+test('失败重发保留幂等键,编辑需求、显式风格或会话后创建新消息', () => {
+ const options = {
+ content: '让故事更温暖',
+ sessionId: '4',
+ selectedTemplateId: 'anim_3d',
+ }
+ const previous = buildCreationSubmission(options)
+ assert.equal(
+ buildCreationSubmission({ ...options, previous }).id,
+ previous.id,
+ )
+ assert.equal(
+ buildCreationSubmission({
+ ...options,
+ selectedTemplateId: 'soft_anime',
+ previous,
+ }).id,
+ previous.id,
+ )
+ assert.notEqual(
+ buildCreationSubmission({ ...options, content: '让故事更有趣', previous })
+ .id,
+ previous.id,
+ )
+ assert.notEqual(
+ buildCreationSubmission({
+ ...options,
+ explicitTemplateId: 'soft_anime',
+ previous,
+ }).id,
+ previous.id,
+ )
+ assert.notEqual(
+ buildCreationSubmission({ ...options, sessionId: '5', previous }).id,
+ previous.id,
+ )
+})
diff --git a/frontend/tests/image-text-storyboard.test.mjs b/frontend/tests/image-text-storyboard.test.mjs
new file mode 100644
index 0000000..8341fc1
--- /dev/null
+++ b/frontend/tests/image-text-storyboard.test.mjs
@@ -0,0 +1,43 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { IMAGE_TEXT_STEPS, imageTextAssetReadiness, imageTextBoardStep, imageTextNextAction } from '../src/lib/imageTextStoryboard.ts'
+
+const shot = (image_url = null, audio_url = null) => ({ image_url, audio_url })
+
+test('image-text creation has four manual checkpoints without a video generation stage', () => {
+ assert.deepEqual(IMAGE_TEXT_STEPS.map(({ label }) => label), ['创作设置', '文案与分镜', '画面与配音', '成片预览'])
+})
+
+test('generated script waits for confirmation before beginning assets', () => {
+ const project = { status: 'SCRIPT_READY', progress: 15, shots: [shot(), shot()] }
+ assert.equal(imageTextBoardStep(project), 1)
+ assert.equal(imageTextNextAction(project), 'assets')
+ assert.equal(imageTextBoardStep({ ...project, status: 'IMAGING', progress: 18 }), 2)
+})
+
+test('complete images alone cannot enable composition without voiceover', () => {
+ const project = { status: 'FAILED', progress: 40, shots: [shot('/1.png', '/voice.mp3'), shot('/2.png')] }
+ assert.deepEqual(imageTextAssetReadiness(project), { total: 2, images: 2, audio: 1, ready: false })
+ assert.equal(imageTextNextAction(project), 'assets')
+ assert.equal(imageTextBoardStep(project), 2)
+})
+
+test('completed assets remain available for review until the user starts composition', () => {
+ const project = { status: 'IMAGE_READY', shots: [shot('/1.png', '/voice.mp3')] }
+ assert.equal(imageTextBoardStep(project), 2)
+ assert.equal(imageTextNextAction(project), 'compose')
+ assert.equal(imageTextBoardStep({ ...project, status: 'COMPOSING' }), 3)
+})
+
+test('cancellation or failures resume the available step and preserve successful assets', () => {
+ assert.equal(imageTextNextAction({ status: 'FAILED', shots: [] }), 'script')
+ assert.equal(imageTextBoardStep({ status: 'CANCELLED', progress: 18, shots: [shot()] }), 2)
+ assert.equal(imageTextNextAction({ status: 'CANCELLED', shots: [shot('/1.png', '/voice.mp3')] }), 'compose')
+ assert.equal(imageTextAssetReadiness({ status: 'DRAFT' }).ready, false)
+})
+
+test('finished films open preview and remain accessible while reviewing earlier stages', () => {
+ const project = { status: 'DONE', shots: [shot('/1.png', '/voice.mp3')], final_video_url: '/movie.mp4' }
+ assert.equal(imageTextBoardStep(project), 3)
+ assert.equal(imageTextNextAction(project), 'preview')
+})
diff --git a/frontend/tests/short-video-routes.test.mjs b/frontend/tests/short-video-routes.test.mjs
new file mode 100644
index 0000000..d33eb6f
--- /dev/null
+++ b/frontend/tests/short-video-routes.test.mjs
@@ -0,0 +1,50 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ SHORT_VIDEO_CREATE_PATH,
+ SHORT_VIDEO_LIST_PATH,
+ shortVideoCreatePath,
+ shortVideoProjectPath,
+ legacyStudioEntryPath,
+} from '../src/lib/shortVideoRoutes.ts'
+import { CREATION_NAV, resolveNavActive } from '../src/lib/siteNavigation.ts'
+
+test('short-video navigation opens project cards while templates start the step workflow', () => {
+ assert.equal(SHORT_VIDEO_CREATE_PATH, '/studio/new')
+ assert.equal(SHORT_VIDEO_LIST_PATH, '/history')
+ assert.equal(CREATION_NAV.find(({ key }) => key === 'kepu').path, SHORT_VIDEO_LIST_PATH)
+ assert.equal(shortVideoCreatePath(), SHORT_VIDEO_CREATE_PATH)
+ assert.equal(shortVideoCreatePath('anim_3d'), '/studio/new?template=anim_3d')
+ assert.equal(shortVideoCreatePath('style & colour'), '/studio/new?template=style%20%26%20colour')
+ assert.equal(resolveNavActive(SHORT_VIDEO_CREATE_PATH), 'kepu')
+})
+
+test('existing session projects keep their recovery route in every production state', () => {
+ for (const status of ['DRAFT', 'SCRIPTING', 'GENERATING', 'COMPOSING', 'DONE', 'FAILED']) {
+ assert.equal(
+ shortVideoProjectPath({ id: 40, status, creation_session_id: 12 }),
+ '/studio/sessions/12?project=40',
+ )
+ }
+ assert.equal(resolveNavActive('/studio/sessions/12'), 'kepu')
+})
+
+test('legacy projects retain draft and asset editor entry points', () => {
+ assert.equal(shortVideoProjectPath({ id: 40, status: 'DRAFT' }), '/studio/40/style')
+ assert.equal(shortVideoProjectPath({ id: 41, status: 'DRAFT', pipeline_mode: 'image_text' }), '/studio/new?project=41')
+ assert.equal(shortVideoProjectPath({ id: 40, status: 'DONE', creation_session_id: null }), '/studio/40')
+ assert.equal(resolveNavActive('/history'), 'kepu')
+})
+
+test('historical conversation versions retain their own project while opening the step editor', () => {
+ assert.equal(shortVideoProjectPath({ id: 41, status: 'DONE', creation_session_id: 12 }), '/studio/sessions/12?project=41')
+ assert.equal(shortVideoProjectPath({ id: 42, status: 'DONE', creation_session_id: 12 }), '/studio/sessions/12?project=42')
+})
+
+test('old studio bookmarks open cards while explicit creation links retain their parameters', () => {
+ assert.equal(legacyStudioEntryPath({}), '/history')
+ assert.equal(legacyStudioEntryPath({ project: '40' }), '/studio/40')
+ assert.equal(legacyStudioEntryPath({ project: 'not-a-project' }), '/history')
+ assert.equal(legacyStudioEntryPath({ template: 'ink_guofeng' }), '/studio/new?template=ink_guofeng')
+ assert.equal(legacyStudioEntryPath({ mode: 'image_text' }), '/studio/new?mode=image_text')
+})