PRINTFILM: AI short-video marketing and AI short-drama creation platform
refactor(api): 移除开放生成接口和 API Key 功能
yi9444f6e81706
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6580006..7fbb4fe 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -8,7 +8,7 @@ PRINTFILM(仓库目录 `ai_movie`):模板驱动的 AI 短视频(科普 k- **科普短视频**:主题/口播 → 模板拆镜 → 分镜图 →(可选)视频 → 旁白 → FFmpeg 合成;状态机 `SCRIPTING → IMAGING → VIDEOING/AUDIOING → COMPOSING → DONE`- **漫剧 drama**:项目 → 剧本摘要/分集 → 资产库(角色/场景/道具/音色)→ 分集分镜 → React Flow 画布-- 另有工具中心(t2i/i2p/t2v 等)、开放 API(`/api/v1`)、管理后台、可选钱包计费(易支付)+- 另有工具中心(t2i/i2p/t2v 等)、管理后台、可选钱包计费(易支付)三条独立进程 + 两个容器中间件:FastAPI(:8000)、用户端 Vite(:5173)、管理端 Vite(:5174)、Postgres(:15432)、Redis(:16379)。技术栈:Python 3.12 / FastAPI / SQLAlchemy(asyncpg) / React 19 / TS / Vite 8。需要本机安装 FFmpeg。@@ -50,7 +50,7 @@ pytest tests/test_x.py::test_name # 单测- `poller.py`:NIO 式 Selector,集中非阻塞轮询所有 `awaiting_poll` 的上游任务(信号量 `TASK_POLL_MAX_CONCURRENCY`),完成后触发计费结算- `runtime.py` + watchdog:心跳过期自动软重启调度/轮询循环-`TaskRun` 状态与 steps/events/targets 见 `models_tasks.py`;**新任务类型必须在 `tasks/handlers.py` 的 `HANDLERS` 注册表登记 `(domain, task_type)`**(kepu/drama/api/studio/tools 五个 domain)。部分类型注册为 `_noop_ephemeral`——这些在创建请求内联执行,TaskRun 仅用于计费/留痕。管理端任务中心 `/queues` 直接读这些表。+`TaskRun` 状态与 steps/events/targets 见 `models_tasks.py`;**新任务类型必须在 `tasks/handlers.py` 的 `HANDLERS` 注册表登记 `(domain, task_type)`**(kepu/drama/studio/tools 四个 domain)。部分类型注册为 `_noop_ephemeral`——这些在创建请求内联执行,TaskRun 仅用于计费/留痕。管理端任务中心 `/queues` 直接读这些表。### 科普流水线与分阶段计费共用同一就绪判定@@ -73,7 +73,7 @@ pytest tests/test_x.py::test_name # 单测### 数据层与"迁移"方式- 异步引擎 asyncpg(`AsyncSessionLocal`,业务全异步);同步引擎 psycopg2 仅少量场景-- ORM 按域拆文件:`models.py`(users/projects/shots/templates/计费/订单/tool_runs 等)、`models_drama.py`、`models_tasks.py`、`models_api.py`(API Key)、`models_agent.py`(导演 Skill)、`models_settings.py`+- ORM 按域拆文件:`models.py`(users/projects/shots/templates/计费/订单/tool_runs 等)、`models_drama.py`、`models_tasks.py`、`models_agent.py`(导演 Skill)、`models_settings.py`- **没有 Alemantic 类迁移工具**:启动时 `init_db()` 做 `create_all`,新增列必须手写进 `main.py` 的 `_apply_schema_patches()`(只允许 additive 的 PG DDL;conftest 里的测试 schema 也要同步)。线上建议 uvicorn 单 worker 以规避建表竞态- **发布前先迁移并检查**:2026-10-24 因 `DATABASE_BOOTSTRAP_ENABLED=false` 且漏跑媒体迁移,分集查询缺少 `task_runs.billing_snapshot` 返回 500。后续发布必须先备份目标库,运行 `backend/scripts/prepare_media_schema.py`,再加 `--check` 只读验证;任一步非零就停止发布,成功后才重启 API/任务执行节点,并用已登录业务接口冒烟。未发布新价格也必须迁移,`/api/health` 成功不能代替结构或业务检查。详见 `docs/MEDIA_MODEL_STRATEGIES.md` 与本机 `docs/DEPLOY.md`。- 启动还会执行:模板 seed(只插缺失,不覆盖后台改动)、内置 Skill seed、`ADMIN_BOOTSTRAP_EMAILS` 提权(只提升已注册用户,不造号,需重启)diff --git a/README.md b/README.mdindex e0e951f..bbd1f70 100644--- a/README.md+++ b/README.md@@ -59,9 +59,9 @@不走完整流水线的单点能力:文生图、图生图、图生产品、文生视频、视频生视频、电商拼图。-### 4. 管理后台与开放 API+### 4. 管理后台-用户、订单、模板、任务中心、模型路由。开放接口 `/api/v1` 生图 / 生视频(Bearer 或 `X-Api-Key`)。+用户、订单、模板、任务中心和模型路由。## 工作流程diff --git a/README_EN.md b/README_EN.mdindex c75d293..17a72ea 100644--- a/README_EN.md+++ b/README_EN.md@@ -59,9 +59,9 @@ Manage short videos as project cards at `/history`, then start a new project atOne-shot capabilities without the full pipeline: text-to-image, image-to-image, image-to-product, text-to-video, video-to-video, e-commerce collage.-### 4. Admin console and open API+### 4. Admin console-Users, orders, templates, task center, model routing. Open API `/api/v1` for image / video generation (Bearer or `X-Api-Key`).+Users, orders, templates, task center, and model routing.## Workflowdiff --git a/admin/src/lib/statusLabels.ts b/admin/src/lib/statusLabels.tsindex 0338e97..d62d635 100644--- a/admin/src/lib/statusLabels.ts+++ b/admin/src/lib/statusLabels.ts@@ -72,7 +72,6 @@ export const TASK_DOMAIN_LABELS: Record<string, string> = {kepu: "AI短视频",tools: "工具",studio: "工作室",- api: "开放 API",};/** Task type → Chinese(轻量同步 + 平台任务) */@@ -95,9 +94,6 @@ export const TASK_TYPE_LABELS: Record<string, string> = {shot_regen_audio: "单镜配音",project_regen_audio: "全片配音",project_compose_only: "仅合成",- v1_image: "API 生图",- v1_video: "API 生视频",- v1_seedance: "API Seedance",tool_image: "工具生图",tool_video: "工具生视频",};diff --git a/admin/src/pages/OrdersPage.tsx b/admin/src/pages/OrdersPage.tsxindex faeaef0..6449e7c 100644--- a/admin/src/pages/OrdersPage.tsx+++ b/admin/src/pages/OrdersPage.tsx@@ -325,7 +325,6 @@ export function OrdersPage() {<option value="kepu">科普</option><option value="drama">漫剧</option><option value="studio">工作室</option>- <option value="api">开放 API</option></Select><Inputplaceholder="billing_key"diff --git a/admin/src/pages/dashboard/DashboardFilters.tsx b/admin/src/pages/dashboard/DashboardFilters.tsxindex 017736a..7ef93fa 100644--- a/admin/src/pages/dashboard/DashboardFilters.tsx+++ b/admin/src/pages/dashboard/DashboardFilters.tsx@@ -3,7 +3,7 @@ import { AdminFilterBar } from "@/components/admin/AdminFilterBar";/** 仪表盘筛选维度 */export type DashboardDays = "1" | "7" | "14" | "30";-export type DashboardDomain = "all" | "drama" | "kepu" | "api" | "tools" | "studio";+export type DashboardDomain = "all" | "drama" | "kepu" | "tools" | "studio";export type DashboardCapability = "all" | "llm" | "image" | "video" | "tts";export type DashboardMetric = "charge" | "calls";@@ -46,7 +46,6 @@ const DOMAIN_OPTIONS = [{ value: "all", label: "全部领域" },{ value: "drama", label: "漫剧" },{ value: "kepu", label: "AI短视频" },- { value: "api", label: "开放 API" },{ value: "tools", label: "工具" },{ value: "studio", label: "工作室" },];diff --git a/admin/src/pages/dashboard/dashboardInsightMaps.tsx b/admin/src/pages/dashboard/dashboardInsightMaps.tsxindex 2f6e3cd..7f6af53 100644--- a/admin/src/pages/dashboard/dashboardInsightMaps.tsx+++ b/admin/src/pages/dashboard/dashboardInsightMaps.tsx@@ -6,7 +6,6 @@ import {Mic,Palette,Video,- Webhook,Wrench,type LucideIcon,} from "lucide-react";@@ -26,7 +25,6 @@ const CAPABILITY_META: Record<string, { label: string; icon: LucideIcon; tone: Dconst DOMAIN_META: Record<string, { label: string; icon: LucideIcon; tone: DashboardInsightTone }> = {drama: { label: "漫剧", icon: Film, tone: "teal" },kepu: { label: "AI短视频", icon: Clapperboard, tone: "blue" },- api: { label: "开放 API", icon: Webhook, tone: "purple" },tools: { label: "工具", icon: Wrench, tone: "sand" },studio: { label: "工作室", icon: Palette, tone: "mint" },unknown: { label: "其他", icon: Wrench, tone: "slate" },diff --git a/backend/app/api/api_keys.py b/backend/app/api/api_keys.pydeleted file mode 100644index db9579f..0000000--- a/backend/app/api/api_keys.py+++ /dev/null@@ -1,45 +0,0 @@-from fastapi import APIRouter, Depends, HTTPException-from sqlalchemy.ext.asyncio import AsyncSession--from app.database import get_db-from app.deps import get_current_user-from app.models import User-from app.schemas_api import ApiKeyCreateRequest, ApiKeyCreatedOut, ApiKeyOut-from app.services import api_keys--router = APIRouter(prefix="/user/api-keys", tags=["api-keys"])--[email protected]("", response_model=list[ApiKeyOut])-async def list_keys(- db: AsyncSession = Depends(get_db),- user: User = Depends(get_current_user),-) -> list[ApiKeyOut]:- rows = await api_keys.list_api_keys(db, user.id)- return [ApiKeyOut.model_validate(row) for row in rows]--[email protected]("", response_model=ApiKeyCreatedOut)-async def create_key(- body: ApiKeyCreateRequest,- db: AsyncSession = Depends(get_db),- user: User = Depends(get_current_user),-) -> ApiKeyCreatedOut:- row, raw = await api_keys.create_api_key(db, user, body.name)- await db.commit()- await db.refresh(row)- out = ApiKeyOut.model_validate(row)- return ApiKeyCreatedOut(**out.model_dump(), secret=raw)--[email protected]("/{key_id}")-async def revoke_key(- key_id: int,- db: AsyncSession = Depends(get_db),- user: User = Depends(get_current_user),-) -> dict:- ok = await api_keys.revoke_api_key(db, user.id, key_id)- if not ok:- raise HTTPException(status_code=404, detail="Key 不存在或已撤销")- await db.commit()- return {"ok": True}diff --git a/backend/app/api/v1/__init__.py b/backend/app/api/v1/__init__.pydeleted file mode 100644index cde5af6..0000000--- a/backend/app/api/v1/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-from fastapi import APIRouter--from app.api.v1 import generation--router = APIRouter()-router.include_router(generation.router)diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.pydeleted file mode 100644index 32448db..0000000--- a/backend/app/api/v1/generation.py+++ /dev/null@@ -1,248 +0,0 @@-"""对外 REST API:生图 / 生视频 / Seedance 转发。"""--from __future__ import annotations--from fastapi import APIRouter, Depends, Header, HTTPException-from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession--from app.config import get_settings-from app.database import get_db-from app.deps import get_api_user-from app.models import User-from app.models_tasks import TaskRun-from app.schemas_api import (- V1GenerationOut,- V1ImageGenerateRequest,- V1SeedanceTaskRequest,- V1VideoGenerateRequest,-)-from app.services.ark import get_ark-from app.services.billing import (- run_billed_ephemeral,- run_billed_ephemeral_deferred,- settle_deferred_video_poll,-)-from app.services.drama.billing_util import record_seedream_image_usage-from app.services.studio_tools import poll_video_task-from app.services import storage--router = APIRouter(prefix="/v1", tags=["public-api"])---async def _resolve_api_user(- db: AsyncSession = Depends(get_db),- authorization: str | None = Header(default=None),- x_api_key: str | None = Header(default=None, alias="X-Api-Key"),-) -> User:- from fastapi.security import HTTPAuthorizationCredentials-- creds = None- if authorization and authorization.lower().startswith("bearer "):- creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=authorization[7:].strip())- return await get_api_user(creds=creds, db=db, x_api_key=x_api_key)--[email protected]("/images/generations", response_model=V1GenerationOut)-async def generate_image(- body: V1ImageGenerateRequest,- db: AsyncSession = Depends(get_db),- user: User = Depends(_resolve_api_user),-) -> V1GenerationOut:- """文生图 / 图生图(Seedream)。"""-- async def _exec() -> list[str]:- ark = get_ark()- refs: list[str] | None = None- prompt = body.prompt.strip()- if body.image_url:- refs = [body.image_url.strip()]- prompt = f"{prompt}。在保持主体可识别的前提下适度改变风格"- urls = []- for _ in range(body.count):- result = await ark.gen_image(- prompt,- body.negative,- refs,- project_id=0,- shot_no=user.id,- size=body.resolution,- model=body.model,- aspect_ratio=body.ratio,- )- url = result.local_url or result.remote_url or ""- if not url:- raise RuntimeError("生图结果为空")- url = storage.republish_url(url, sync=True) or url- urls.append(url)- from app.services.billing.context import get_current_task_run_id- task_row = await db.get(TaskRun, get_current_task_run_id())- task_row.result_payload = {"kind": "image", "urls": list(urls)}- await record_seedream_image_usage(- db, user_id=user.id, model=body.model or get_settings().model_image,- domain="api", image_result=result, extra_raw={"source": "api_v1_image"},- )- return urls-- try:- task, urls = await run_billed_ephemeral(- db,- user,- domain="api",- task_type="v1_image",- executor=_exec,- payload=body.model_dump(exclude_none=True),- commit=True,- )- except ValueError as exc:- from app.services.billing.http import http_exception_for_value_error- raise http_exception_for_value_error(exc) from exc-- return V1GenerationOut(- status="succeeded",- kind="image",- urls=urls,- task_id=str(task.id),- )--[email protected]("/videos/generations", response_model=V1GenerationOut)-async def generate_video(- body: V1VideoGenerateRequest,- db: AsyncSession = Depends(get_db),- user: User = Depends(_resolve_api_user),-) -> V1GenerationOut:- """首帧图 + 文案 → Seedance 图生视频,返回 task_id。"""-- async def _exec() -> str:- ark = get_ark()- try:- upstream_id = await ark.gen_video_i2v(- body.image_url.strip(),- body.prompt.strip(),- body.duration,- resolution=body.resolution,- generate_audio=body.generate_audio,- model=body.model,- ratio=body.ratio,- )- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc-- return upstream_id-- try:- task, upstream_id = await run_billed_ephemeral_deferred(- db,- user,- domain="api",- task_type="v1_video",- executor=_exec,- payload=body.model_dump(exclude_none=True),- commit=True,- )- except ValueError as exc:- from app.services.billing.http import http_exception_for_value_error- raise http_exception_for_value_error(exc) from exc-- return V1GenerationOut(- status="queued",- kind="video",- task_id=upstream_id,- preview_url=body.image_url,- urls=[],- )--[email protected]("/seedance/tasks", response_model=V1GenerationOut)-async def forward_seedance(- body: V1SeedanceTaskRequest,- db: AsyncSession = Depends(get_db),- user: User = Depends(_resolve_api_user),-) -> V1GenerationOut:- """转发 Seedance 多模态 body 到 TokenFree。"""- if not body.content:- raise HTTPException(status_code=400, detail="content 不能为空")- settings = get_settings()- payload: dict = {- "model": body.model or settings.model_video,- "content": body.content,- "resolution": body.resolution,- "watermark": body.watermark,- "generate_audio": body.generate_audio,- "return_last_frame": body.return_last_frame,- }- if body.duration is not None:- payload["duration"] = body.duration- if body.ratio:- payload["ratio"] = body.ratio-- async def _exec() -> str:- ark = get_ark()- try:- upstream_id = await ark.gen_video_seedance_body(payload, project_id=0)- except Exception as exc: # noqa: BLE001- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc-- return upstream_id-- try:- task, upstream_id = await run_billed_ephemeral_deferred(- db,- user,- domain="api",- task_type="v1_seedance",- executor=_exec,- payload={**body.model_dump(exclude_none=True), "prepared": {"seedance_body": payload}},- commit=True,- )- except ValueError as exc:- from app.services.billing.http import http_exception_for_value_error- raise http_exception_for_value_error(exc) from exc-- return V1GenerationOut(status="queued", kind="video", task_id=upstream_id, urls=[])--[email protected]("/tasks/{task_id}", response_model=V1GenerationOut)-async def get_task(- task_id: str,- db: AsyncSession = Depends(get_db),- user: User = Depends(_resolve_api_user),-) -> V1GenerationOut:- """查询 Seedance 视频任务状态(仅可查询本人提交的任务)。"""- if not task_id.strip():- raise HTTPException(status_code=400, detail="缺少 task_id")- tid = task_id.strip()- # 归属校验:上游 task_id 本身是可传递的凭据,不校验会拖走他人视频- owned = (- await db.execute(- select(TaskRun.id)- .where(TaskRun.requested_by == user.id, TaskRun.provider_task_id == tid)- .limit(1)- )- ).scalar_one_or_none()- if owned is None:- raise HTTPException(status_code=404, detail="任务不存在")- from app.services.billing.context import billing_scope- owned_task = await db.get(TaskRun, owned)- async with billing_scope(owned, snapshot=owned_task.billing_snapshot):- data = await poll_video_task(user, tid)- owned_task.result_payload = {"kind": "video", **data}- await settle_deferred_video_poll(- db,- user,- provider_task_id=tid,- poll_status=str(data.get("status") or ""),- error=str(data.get("error") or "") or None,- usage_tokens=int((data.get("usage") or {}).get("total_tokens") or 0),- completion_tokens=int((data.get("usage") or {}).get("completion_tokens") or 0),- raw_usage=data.get("raw_usage") if isinstance(data.get("raw_usage"), dict) else None,- )- await db.commit()- return V1GenerationOut(- status=str(data.get("status") or "running"),- kind="video",- urls=list(data.get("urls") or []),- task_id=task_id.strip(),- error=data.get("error"),- )diff --git a/backend/app/database.py b/backend/app/database.pyindex 3833c51..637bc95 100644--- a/backend/app/database.py+++ b/backend/app/database.py@@ -56,7 +56,6 @@ async def init_db(engine_override: AsyncEngine | None = None) -> None:from app import models_agent # noqa: F401from app import models_creation # noqa: F401from app import models_drama # noqa: F401- from app import models_api # noqa: F401from app import models_settings # noqa: F401from app import models_tasks # noqa: F401from app import models_teams, models_team_billing, models_team_locks # noqa: F401diff --git a/backend/app/deps.py b/backend/app/deps.pyindex def64f9..238b7be 100644--- a/backend/app/deps.py+++ b/backend/app/deps.py@@ -1,19 +1,16 @@-from fastapi import Depends, HTTPException, Header, status+from fastapi import Depends, HTTPException, statusfrom fastapi.security import HTTPAuthorizationCredentials, HTTPBearerfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.database import get_dbfrom app.models import User-from app.services.api_keys import API_KEY_PREFIX, user_from_api_keyfrom app.services.auth import decode_token, get_user_by_idsecurity = HTTPBearer(auto_error=False)async def _user_from_bearer(db: AsyncSession, token: str) -> User | None:- """Bearer 令牌换用户:pf_ 前缀走 API Key,否则按 JWT 解析。"""- if token.startswith(API_KEY_PREFIX):- return await user_from_api_key(db, token)+ """站内 Bearer 登录令牌仅接受有效 JWT。"""sub = decode_token(token)if not sub:return None@@ -36,23 +33,6 @@ async def get_current_user(return user-async def get_api_user(- creds: HTTPAuthorizationCredentials | None = Depends(security),- db: AsyncSession = Depends(get_db),- x_api_key: str | None = Header(default=None, alias="X-Api-Key"),-) -> User:- """对外 API:支持 JWT 或 pf_live_ API Key(Bearer / X-Api-Key)。"""- token = (x_api_key or "").strip()- if not token and creds:- token = creds.credentials- if not token:- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="缺少 API Key")- user = await _user_from_bearer(db, token)- if not user:- raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="API Key 无效或已撤销")- return user--async def get_current_admin(user: User = Depends(get_current_user)) -> User:# Require role=admin for /api/admin routesif (user.role or "user") != "admin":diff --git a/backend/app/main.py b/backend/app/main.pyindex 68aed8f..653929c 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -10,8 +10,6 @@ from sqlalchemy.ext.asyncio import AsyncEnginefrom app.api import auth, billing, creation, projects, tasks, templates, toolsfrom 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_routerfrom app.api.admin import router as admin_routerfrom app.api.drama import router as drama_routerfrom app.config import get_settings@@ -115,8 +113,6 @@ 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")-app.include_router(user_api_keys.router, prefix="/api")-app.include_router(v1_router, prefix="/api")app.include_router(drama_router, prefix="/api")app.include_router(teams.router, prefix="/api")app.include_router(teams.invitation_router, prefix="/api")diff --git a/backend/app/models_api.py b/backend/app/models_api.pydeleted file mode 100644index 0c99edd..0000000--- a/backend/app/models_api.py+++ /dev/null@@ -1,21 +0,0 @@-"""对外 API Key 模型。"""--from datetime import datetime--from sqlalchemy import DateTime, ForeignKey, Integer, String, func-from sqlalchemy.orm import Mapped, mapped_column--from app.database import Base---class UserApiKey(Base):- __tablename__ = "user_api_keys"-- id: Mapped[int] = mapped_column(Integer, primary_key=True)- user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)- name: Mapped[str] = mapped_column(String(64), default="默认 Key")- key_prefix: Mapped[str] = mapped_column(String(24), index=True)- key_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)- created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())- last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)- revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)diff --git a/backend/app/schemas_api.py b/backend/app/schemas_api.pydeleted file mode 100644index 5513da6..0000000--- a/backend/app/schemas_api.py+++ /dev/null@@ -1,69 +0,0 @@-from datetime import datetime--from pydantic import BaseModel, Field---class ApiKeyCreateRequest(BaseModel):- name: str = Field(default="默认 Key", max_length=64)---class ApiKeyOut(BaseModel):- id: int- name: str- key_prefix: str- created_at: datetime | None = None- last_used_at: datetime | None = None-- model_config = {"from_attributes": True}---class ApiKeyCreatedOut(ApiKeyOut):- secret: str---class V1ImageGenerateRequest(BaseModel):- model_config = {"extra": "forbid"}- model: str | None = Field(default=None, max_length=128)- resolution: str = "2K"- count: int = Field(default=1, ge=1, le=100)- price_version: int | None = Field(default=None, ge=1)- prompt: str = Field(min_length=1, max_length=4000)- negative: str = Field(default="", max_length=2000)- ratio: str = Field(default="1:1", description="1:1 | 16:9 | 9:16")- image_url: str | None = Field(default=None, description="参考图 URL,传入则为图生图")---class V1VideoGenerateRequest(BaseModel):- model_config = {"extra": "forbid"}- model: str | None = Field(default=None, max_length=128)- ratio: str = "9:16"- price_version: int | None = Field(default=None, ge=1)- prompt: str = Field(min_length=1, max_length=8000)- image_url: str = Field(min_length=8, description="首帧图公网 URL")- duration: int = Field(default=5, ge=4, le=30)- resolution: str = Field(default="480p")- generate_audio: bool = False---class V1SeedanceTaskRequest(BaseModel):- """接近火山 Seedance 的任务体,服务端补全 model 并转发。"""- model_config = {"extra": "forbid"}-- content: list[dict]- model: str | None = Field(default=None, max_length=128)- price_version: int | None = Field(default=None, ge=1)- duration: int | None = Field(default=None, ge=4, le=30)- resolution: str = Field(default="480p")- ratio: str | None = None- generate_audio: bool = False- return_last_frame: bool = True- watermark: bool = False---class V1GenerationOut(BaseModel):- status: str- kind: str- urls: list[str] = Field(default_factory=list)- task_id: str | None = None- preview_url: str | None = None- error: str | None = Nonediff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.pyindex ff31739..365352a 100644--- a/backend/app/schemas_tasks.py+++ b/backend/app/schemas_tasks.py@@ -22,7 +22,7 @@ class TaskTargetBind(BaseModel):class TaskCreateRequest(BaseModel):"""Create a platform task run."""- domain: str = Field(default="drama", description="drama | kepu | tools | api | studio")+ domain: str = Field(default="drama", description="drama | kepu | tools | studio")task_type: str = Field(min_length=1, max_length=64)priority: int = Field(default=100, ge=0, le=1000)client_request_id: str | None = Field(default=None, max_length=128)diff --git a/backend/app/services/api_keys.py b/backend/app/services/api_keys.pydeleted file mode 100644index e182761..0000000--- a/backend/app/services/api_keys.py+++ /dev/null@@ -1,76 +0,0 @@-"""用户 API Key 创建、校验与撤销。"""--from __future__ import annotations--import hashlib-import secrets-from datetime import datetime, timezone--from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession--from app.models import User-from app.models_api import UserApiKey--API_KEY_PREFIX = "pf_live_"---def _hash_key(raw: str) -> str:- return hashlib.sha256(raw.encode("utf-8")).hexdigest()---def generate_api_key() -> tuple[str, str, str]:- """返回 (完整 key, 展示前缀, hash)。"""- secret = secrets.token_urlsafe(24).replace("-", "").replace("_", "")[:32]- raw = f"{API_KEY_PREFIX}{secret}"- prefix = raw[:16]- return raw, prefix, _hash_key(raw)---async def create_api_key(db: AsyncSession, user: User, name: str) -> tuple[UserApiKey, str]:- raw, prefix, key_hash = generate_api_key()- row = UserApiKey(- user_id=user.id,- name=(name or "默认 Key").strip()[:64] or "默认 Key",- key_prefix=prefix,- key_hash=key_hash,- )- db.add(row)- await db.flush()- return row, raw---async def list_api_keys(db: AsyncSession, user_id: int) -> list[UserApiKey]:- result = await db.execute(- select(UserApiKey)- .where(UserApiKey.user_id == user_id, UserApiKey.revoked_at.is_(None))- .order_by(UserApiKey.id.desc())- )- return list(result.scalars().all())---async def revoke_api_key(db: AsyncSession, user_id: int, key_id: int) -> bool:- row = await db.get(UserApiKey, key_id)- if not row or row.user_id != user_id or row.revoked_at is not None:- return False- row.revoked_at = datetime.now(timezone.utc)- await db.flush()- return True---async def user_from_api_key(db: AsyncSession, raw_key: str) -> User | None:- if not raw_key.startswith(API_KEY_PREFIX):- return None- key_hash = _hash_key(raw_key.strip())- result = await db.execute(- select(UserApiKey, User)- .join(User, User.id == UserApiKey.user_id)- .where(UserApiKey.key_hash == key_hash, UserApiKey.revoked_at.is_(None))- )- row = result.first()- if not row:- return None- api_key, user = row- api_key.last_used_at = datetime.now(timezone.utc)- await db.flush()- return userdiff --git a/backend/app/services/billing/__init__.py b/backend/app/services/billing/__init__.pyindex 41c035c..41f5018 100644--- a/backend/app/services/billing/__init__.py+++ b/backend/app/services/billing/__init__.py@@ -6,7 +6,6 @@ from app.services.billing.context import billing_scope, get_current_task_run_id,from app.services.billing.ephemeral import (create_ephemeral_task_row,run_billed_ephemeral,- run_billed_ephemeral_deferred,settle_deferred_video_poll,)from app.services.billing.estimates import estimate_phase_fen, estimate_task_fen@@ -62,7 +61,6 @@ __all__ = ["record_llm_chat_line","record_usage","run_billed_ephemeral",- "run_billed_ephemeral_deferred","settle_deferred_video_poll","set_current_task_run_id","settle_task",diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.pyindex afdfcbe..88dc693 100644--- a/backend/app/services/billing/ephemeral.py+++ b/backend/app/services/billing/ephemeral.py@@ -121,7 +121,7 @@ async def run_billed_ephemeral() -> tuple[TaskRun, T]:"""创建轻量 TaskRun → 预扣 → 在 billing_scope 内执行 → 结算。- 用于聊天、开放 API、工作室工具等同步调用。+ 用于聊天、配音与工作室工具等同步调用。"""task = await create_ephemeral_task_row(db,@@ -243,117 +243,6 @@ async def _cancel_inline_task(db: AsyncSession, task: TaskRun, *, billable: boolawait db.commit()-def _extract_provider_task_id(result: Any) -> str:- """从 executor 返回值解析上游 task_id。"""- if isinstance(result, dict):- raw = result.get("task_id") or result.get("provider_task_id") or ""- return str(raw).strip()- return str(result).strip()---async def run_billed_ephemeral_deferred(- db: AsyncSession,- user: User,- *,- domain: str,- task_type: str,- executor: Callable[[], Awaitable[T]],- payload: dict | None = None,- project_id: int | None = None,- drama_project_id: int | None = None,- shot_id: int | None = None,- fragment_id: int | None = None,- asset_id: int | None = None,- episode_id: int | None = None,- commit: bool = True,-) -> tuple[TaskRun, T]:- """- 轻量 TaskRun:预扣 → 提交上游异步任务 → 保持 awaiting_poll,轮询终态后再结算。- 用于开放 API / 工作室生视频,避免提交成功即扣费。- """- task = await create_ephemeral_task_row(- db,- user,- domain=domain,- task_type=task_type,- payload=payload,- project_id=project_id,- drama_project_id=drama_project_id,- shot_id=shot_id,- fragment_id=fragment_id,- asset_id=asset_id,- episode_id=episode_id,- )- try:- await freeze_for_task(db, task)- except ValueError:- task.status = "failed"- task.error_code = "insufficient_balance"- task.error_message = "余额不足"- task.billing_status = "none"- await db.flush()- raise-- now = datetime.now(UTC)- task.status = "running"- task.started_at = now- start_inline_lease(task, now)- await append_task_event(- db,- task.id,- event_type="task.started",- status=task.status,- message="轻量视频任务开始",- )- await db.flush()-- await db.commit()-- result: T- try:- async with hold_inline_lease(task), billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):- result = await executor()- provider_id = _extract_provider_task_id(result)- if not provider_id:- raise RuntimeError("上游未返回 task_id")- task.status = "awaiting_poll"- task.provider_task_id = provider_id- task.progress_percent = 30- task.next_action_at = now- task.result_payload = {"awaiting_poll": True, "provider_task_id": provider_id}- await append_task_event(- db,- task.id,- event_type="task.submitted",- status=task.status,- message="已提交上游,等待轮询",- payload={"provider_task_id": provider_id},- )- except asyncio.CancelledError:- await _cancel_inline_task(db, task)- raise- except Exception as exc:- task.status = "failed"- task.error_code = "ephemeral_failed"- task.error_message = str(exc)[:500]- task.finished_at = datetime.now(UTC)- await append_task_event(- db,- task.id,- event_type="task.failed",- status=task.status,- message=str(exc)[:200],- )- await settle_task(db, task.id)- await db.commit()- raise-- if commit or task.team_id is not None:- await db.commit()- await db.refresh(task)- return task, result--async def settle_deferred_video_poll(db: AsyncSession,user: User,@@ -436,7 +325,7 @@ async def settle_deferred_video_poll(user_id=user.id,billing_key=key,model=billing_model,- domain=task.domain or "api",+ domain=task.domain or "studio",task_result=task_result,fallback_duration_sec=payload.get("duration"),resolution=str(payload.get("resolution") or ""),diff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.pyindex 0bd6c47..974b19c 100644--- a/backend/app/services/billing/estimates.py+++ b/backend/app/services/billing/estimates.py@@ -288,13 +288,13 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settingsc = charge_fen_official_llm(s.billing_est_llm_tokens, s)return _buffered_fen(c, s)- if domain in {"api", "studio"}:+ if domain == "studio":if task_type == "tool_audio":_, c = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)return _buffered_fen(c, s)- if task_type in {"v1_image", "tool_image"}:+ if task_type == "tool_image":return _catalog_image_fen(s, payload=payload)- if task_type in {"v1_video", "v1_seedance", "tool_video"}:+ if task_type == "tool_video":dur = float(payload.get("duration") or 5)c = charge_fen_official_video(max(dur, 2.0),diff --git a/backend/app/services/media_models/planning.py b/backend/app/services/media_models/planning.pyindex e6ad346..48335f3 100644--- a/backend/app/services/media_models/planning.py+++ b/backend/app/services/media_models/planning.py@@ -93,7 +93,7 @@ async def plan_items(db, task) -> list[dict]:"aspect_ratio": _project_output_ratio(project) or "9:16"},model=project.video_model or settings.model_video, target=shot.id, shot_no=shot.shot_no)return items- if kind in {"asset_image", "v1_image", "tool_image"}:+ if kind in {"asset_image", "tool_image"}:model = p.get("model_id") or p.get("model") or generation.get("model")params = {"aspect_ratio": p.get("aspect_ratio") or p.get("ratio") or generation.get("aspect_ratio") or "1:1","resolution": p.get("resolution") or p.get("size") or generation.get("resolution") or "2K",@@ -112,7 +112,7 @@ async def plan_items(db, task) -> list[dict]:if kind == "asset_image" and not p.get("aspect_ratio"):params["aspect_ratio"] = "3:4" if p.get("kind", "character") == "character" else "16:9"add("image", params, model=model, target=task.asset_id or task.shot_id)- if kind in {"asset_video", "fragment_video", "v1_video", "v1_seedance", "tool_video"}:+ if kind in {"asset_video", "fragment_video", "tool_video"}:body = dict(mapping(prepared.get("seedance_body"), "prepared.seedance_body"))if kind == "asset_video":# Canvas workers load linked assets themselves; client-prepared content cannot hide them.@@ -166,8 +166,8 @@ async def plan_items(db, task) -> list[dict]:content_images = isinstance(content, list) and any(isinstance(item, dict) and item.get("type") == "image_url" for item in content)if helper_needed and not content_images and not any(references.get(key) for key in ("image_url", "first_frame", "reference_images")):references["image_url"] = "pending://generated-first-frame"- add("video", {"duration": duration if duration is not None else (5 if task.domain in {"studio", "api"} else 8),- "resolution": resolution or ("480p" if task.domain in {"studio", "api"} else "720p"),+ add("video", {"duration": duration if duration is not None else (5 if task.domain == "studio" else 8),+ "resolution": resolution or ("480p" if task.domain == "studio" else "720p"),"aspect_ratio": ratio or "9:16",**({"generate_audio": p["generate_audio"]} if "generate_audio" in p else {}),**references},diff --git a/backend/app/services/tasks/generation_history.py b/backend/app/services/tasks/generation_history.pyindex bbbc785..c20dc77 100644--- a/backend/app/services/tasks/generation_history.py+++ b/backend/app/services/tasks/generation_history.py@@ -40,8 +40,7 @@ _TASK_LABELS = {"content_expand": "扩写创作内容", "creation_turn": "创作对话", "voice_preview": "配音试听","shot_regen_image": "重新生成分镜图片", "shot_regen_video": "重新生成分镜视频","shot_regen_audio": "重新生成分镜配音", "project_regen_audio": "重新生成全片配音",- "project_compose_only": "合成短视频", "v1_image": "API 图片生成", "v1_video": "API 视频生成",- "v1_seedance": "API 视频生成", "tool_image": "生成图片", "tool_video": "生成视频", "tool_audio": "生成音频",+ "project_compose_only": "合成短视频", "tool_image": "生成图片", "tool_video": "生成视频", "tool_audio": "生成音频",}_PIPELINE_LABELS = {"script": "生成短视频剧本", "storyboard": "规划短视频分镜", "assets": "生成分镜图片","videos": "生成分镜视频", "audio": "生成短视频配音", "compose": "合成短视频", "produce": "生成短视频"}@@ -61,7 +60,7 @@ def _kind_expression():(and_(TaskRun.task_type == "project_pipeline", phase == "assets"), "image"),(and_(TaskRun.task_type == "project_pipeline", phase == "audio"), "audio"),(and_(TaskRun.task_type == "project_pipeline", phase.in_(("script", "text", "plan", "storyboard"))), "text"),- (TaskRun.task_type.in_(("project_pipeline", "episode_compose", "project_compose_only", "v1_seedance")), "video"),+ (TaskRun.task_type.in_(("project_pipeline", "episode_compose", "project_compose_only")), "video"),(TaskRun.task_type.contains("video"), "video"),(TaskRun.task_type.contains("image"), "image"),(TaskRun.queue_type.in_(("image", "video")), TaskRun.queue_type),@@ -82,7 +81,7 @@ def _generation_kind(task) -> str:if phase == "audio":return "audio"return "text" if phase in {"script", "text", "plan", "storyboard"} else "video"- if name in {"episode_compose", "project_compose_only", "v1_seedance"} or "video" in name:+ if name in {"episode_compose", "project_compose_only"} or "video" in name:return "video"if "image" in name:return "image"diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex d23d754..87db59b 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -354,9 +354,6 @@ TASK_HANDLERS: dict[tuple[str, str], TaskHandler] = {("drama", "episode_compose"): TaskHandler("drama", "episode_compose", _noop_ephemeral),("kepu", "content_expand"): TaskHandler("kepu", "content_expand", _noop_ephemeral),("kepu", "voice_preview"): TaskHandler("kepu", "voice_preview", _noop_ephemeral),- ("api", "v1_image"): TaskHandler("api", "v1_image", _noop_ephemeral),- ("api", "v1_video"): TaskHandler("api", "v1_video", _noop_ephemeral),- ("api", "v1_seedance"): TaskHandler("api", "v1_seedance", _noop_ephemeral),("studio", "tool_image"): TaskHandler("studio", "tool_image", _run_studio_generation),("studio", "tool_video"): TaskHandler("studio", "tool_video", _run_studio_generation),("studio", "tool_audio"): TaskHandler("studio", "tool_audio", _run_studio_generation),diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.pyindex 3613d59..b8d9454 100644--- a/backend/app/services/tasks/poller.py+++ b/backend/app/services/tasks/poller.py@@ -128,7 +128,7 @@ async def _select_and_poll_due() -> None:now = datetime.now(UTC)batch_limit = max(1, int(get_settings().task_poll_max_concurrency or 20))async with AsyncSessionLocal() as db:- # 仅 drama fragment_video 走 drama 收尾轮询;api/studio 的轻量 deferred+ # 仅 drama fragment_video 走 drama 收尾轮询;独立轻量 deferred# 视频由 _poll_ephemeral_deferred_tasks 处理,误送 drama poller 会被立即判失败。stmt = (select(TaskRun.id)@@ -215,7 +215,7 @@ async def _poll_one_task(task_id: int) -> None:await db.commit()-# 后台轮询 api/studio 轻量视频任务:主动查上游终态,超时则失败并解冻。+# 后台轮询独立轻量视频任务(含历史在途任务):主动查上游终态,超时则失败并解冻。async def _poll_ephemeral_deferred_tasks() -> None:now = datetime.now(UTC)timeout_sec = float(get_settings().ark_video_poll_timeout or 900.0)@@ -227,7 +227,8 @@ async def _poll_ephemeral_deferred_tasks() -> None:select(TaskRun).where(TaskRun.status == "awaiting_poll",- TaskRun.domain.in_(["api", "studio"]),+ TaskRun.domain.not_in(["drama", "kepu"]),+ TaskRun.provider_task_id.is_not(None),TaskRun.billing_status == "frozen",or_(TaskRun.domain != "studio", TaskRun.task_type != "tool_video",TaskRun.payload["run_id"].as_integer().is_(None)),@@ -249,7 +250,7 @@ async def _poll_ephemeral_deferred_tasks() -> None:logger.exception("ephemeral deferred poll failed task_id=%s", task_id)-# 轮询单条 api/studio 轻量 deferred 视频任务:超时判失败、运行中写回退避、终态结算。+# 轮询单条独立轻量视频任务(含历史在途任务):超时判失败、运行中写回退避、终态结算。async def _poll_one_ephemeral_task(task_id: int, *, now, timeout_sec: float) -> None:from app.models import Userfrom app.services.billing.ephemeral import settle_deferred_video_polldiff --git a/backend/app/services/tasks/queues.py b/backend/app/services/tasks/queues.pyindex 2fd37af..fc6b181 100644--- a/backend/app/services/tasks/queues.py+++ b/backend/app/services/tasks/queues.py@@ -14,7 +14,7 @@ def task_queue(task_type: str, payload: dict | None = None) -> QueueType:return "image"if phase in {"videos", "compose", "produce"}:return "video"- if task_type in {"v1_seedance", "project_compose_only"} or "video" in task_type:+ if task_type == "project_compose_only" or "video" in task_type:return "video"if "image" in task_type:return "image"diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex b950e8e..146663c 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -95,7 +95,6 @@ async def db_session(billing_enabled: None) -> AsyncIterator[AsyncSession]:# 注册全部 ORM 表import app.models # noqa: F401import app.models_agent # noqa: F401- import app.models_api # noqa: F401import app.models_drama # noqa: F401import app.models_settings # noqa: F401import app.models_tasks # noqa: F401@@ -160,8 +159,8 @@ async def make_task(db: AsyncSession,user: User,*,- domain: str = "api",- task_type: str = "v1_image",+ domain: str = "studio",+ task_type: str = "tool_image",status: str = "pending",billing_status: str = "none",provider_task_id: str | None = None,diff --git a/backend/tests/test_billing_alerts.py b/backend/tests/test_billing_alerts.pyindex bd9e092..b9edd64 100644--- a/backend/tests/test_billing_alerts.py+++ b/backend/tests/test_billing_alerts.py@@ -26,7 +26,7 @@ async def _add_settled_usage() -> UsageEvent:ev = UsageEvent(user_id=user_id,- domain="api",+ domain="studio",capability="llm",billing_key="llm_chat",model="test",diff --git a/backend/tests/test_billing_integration.py b/backend/tests/test_billing_integration.pyindex ed14496..b9ac668 100644--- a/backend/tests/test_billing_integration.py+++ b/backend/tests/test_billing_integration.py@@ -72,7 +72,7 @@ async def test_freeze_settle_refunds_unused_estimate(db_session: AsyncSession) -async def test_ensure_balance_rejects_insufficient_funds(db_session: AsyncSession) -> None:"""入队前余额预检应抛 ValueError。"""user = await make_user(db_session, balance_fen=0)- task = await make_task(db_session, user, domain="api", task_type="v1_image")+ task = await make_task(db_session, user, domain="studio", task_type="tool_image")await db_session.commit()with pytest.raises(ValueError, match="余额不足"):@@ -89,7 +89,7 @@ async def test_create_task_rejects_insufficient_balance(db_session: AsyncSessionawait create_task(db_session,user,- TaskCreateRequest(domain="api", task_type="v1_image"),+ TaskCreateRequest(domain="studio", task_type="tool_image"),commit=False,)@@ -129,18 +129,18 @@ async def test_ensure_balance_counts_pending_unfrozen_tasks(db_session: AsyncSesasync def test_create_task_stores_billing_estimate_at_enqueue(db_session: AsyncSession) -> None:"""create_task 入队时应写入 billing_estimate_fen,供后续累计校验。"""user = await make_user(db_session, balance_fen=100_000)- task = await make_task(db_session, user, domain="api", task_type="v1_image")+ task = await make_task(db_session, user, domain="studio", task_type="tool_image")await db_session.commit()from app.services.billing.estimates import estimate_task_fen- probe = TaskRun(domain="api", task_type="v1_image", requested_by=user.id, payload={})+ probe = TaskRun(domain="studio", task_type="tool_image", requested_by=user.id, payload={})expected = await estimate_task_fen(db_session, probe)created = await create_task(db_session,user,- TaskCreateRequest(domain="api", task_type="v1_image"),+ TaskCreateRequest(domain="studio", task_type="tool_image"),commit=True,)assert int(created.billing_estimate_fen or 0) == expected@@ -215,8 +215,8 @@ async def test_settle_deferred_video_poll_idempotent_on_success(db_session: Asyntask = await make_task(db_session,user,- domain="api",- task_type="v1_video",+ domain="studio",+ task_type="tool_video",status="awaiting_poll",billing_status="none",provider_task_id="upstream-ok-1",@@ -273,8 +273,8 @@ async def test_settle_deferred_video_poll_failed_refunds_freeze(db_session: Asyntask = await make_task(db_session,user,- domain="api",- task_type="v1_video",+ domain="studio",+ task_type="tool_video",status="awaiting_poll",billing_status="none",provider_task_id="upstream-task-1",diff --git a/backend/tests/test_generation_history.py b/backend/tests/test_generation_history.pyindex 3d55a49..9df4b75 100644--- a/backend/tests/test_generation_history.py+++ b/backend/tests/test_generation_history.py@@ -127,7 +127,7 @@ async def test_provider_id_links_require_matching_tool_domain_and_media_kind(hisassert tasks[api.id]["urls"] == []assert tasks[different_kind.id]["urls"] == []assert tasks[matched.id]["urls"] == ["https://output.test/id-match.png"]- assert tasks[api.id]["prompt"] == "API 图片生成"+ assert tasks[api.id]["prompt"] == "生成任务"@pytest.mark.asynciodiff --git a/backend/tests/test_generation_task_registration.py b/backend/tests/test_generation_task_registration.pyindex 7ca8df8..0792755 100644--- a/backend/tests/test_generation_task_registration.py+++ b/backend/tests/test_generation_task_registration.py@@ -23,27 +23,25 @@ def inline_runtime(monkeypatch):@pytest.mark.asyncio[email protected]("deferred", [False, True])-async def test_inline_generation_is_committed_before_external_io(monkeypatch, deferred):+async def test_inline_generation_is_committed_before_external_io(monkeypatch):db, task = inline_runtime(monkeypatch)async def execute():db.commit.assert_awaited_once()assert task.status == "running"- return {"task_id": "provider-42"} if deferred else "新的创作"+ return "新的创作"- run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral- await run(db, SimpleNamespace(id=1), domain="api", task_type="v1_video", executor=execute, commit=False)+ run = ephemeral.run_billed_ephemeral+ await run(db, SimpleNamespace(id=1), domain="studio", task_type="tool_video", executor=execute, commit=False)assert db.commit.await_count == 1@pytest.mark.asyncio[email protected]("deferred", [False, True])-async def test_inline_failure_remains_after_callers_rollback(monkeypatch, deferred):+async def test_inline_failure_remains_after_callers_rollback(monkeypatch):db, task = inline_runtime(monkeypatch)- run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ run = ephemeral.run_billed_ephemeralwith pytest.raises(RuntimeError, match="生成失败"):- await run(db, SimpleNamespace(id=1), domain="api", task_type="v1_video",+ await run(db, SimpleNamespace(id=1), domain="studio", task_type="tool_video",executor=AsyncMock(side_effect=RuntimeError("生成失败")), commit=False)assert task.status == "failed"assert task.finished_at is not Nonediff --git a/backend/tests/test_inline_task_leases.py b/backend/tests/test_inline_task_leases.pyindex 79064eb..f5fae00 100644--- a/backend/tests/test_inline_task_leases.py+++ b/backend/tests/test_inline_task_leases.py@@ -42,8 +42,7 @@ def aware(value):return value if value.tzinfo else value.replace(tzinfo=UTC)[email protected]("deferred", [False, True])-async def test_slow_inline_generation_renews_remote_lease_and_is_never_requeued(inline_sessions, monkeypatch, deferred):+async def test_slow_inline_generation_renews_remote_lease_and_is_never_requeued(inline_sessions, monkeypatch):sessions, user_id = inline_sessionsmonkeypatch.setattr(inline, "INLINE_LEASE_SECONDS", 0.15)monkeypatch.setattr(inline, "INLINE_HEARTBEAT_SECONDS", 0.02)@@ -59,9 +58,9 @@ async def test_slow_inline_generation_renews_remote_lease_and_is_never_requeued(calls += 1started.set()await finish.wait()- return "provider-result" if deferred else "完成的文案"+ return "完成的文案"- run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral+ run = ephemeral.run_billed_ephemeralreturn await run(db, user, domain="drama", task_type="agent_chat", executor=provider)job = asyncio.create_task(request())@@ -102,7 +101,7 @@ async def test_slow_inline_generation_renews_remote_lease_and_is_never_requeued(tasks = list((await observer.execute(select(TaskRun))).scalars())assert len(tasks) == 1 and calls == 1task = tasks[0]- assert task.status == ("awaiting_poll" if deferred else "succeeded")+ assert task.status == "succeeded"assert task.lease_token is None and task.lease_until is Nonefinally:finish.set()diff --git a/backend/tests/test_media_fixed_billing.py b/backend/tests/test_media_fixed_billing.pyindex 6deba7d..ae3a9ae 100644--- a/backend/tests/test_media_fixed_billing.py+++ b/backend/tests/test_media_fixed_billing.py@@ -41,7 +41,7 @@ async def test_partial_delivery_uses_snapshot_and_upstream_cannot_replace_retaildb = db_sessionuser = await make_user(db)await publish_book(db, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)- task = TaskRun(domain="api", task_type="v1_image", requested_by=user.id,+ task = TaskRun(domain="studio", task_type="tool_image", requested_by=user.id,payload={"model": "seedream-5.0-pro", "resolution": "2K"}, status="running")await prepare_task_media(db, task)db.add(task)@@ -70,7 +70,7 @@ async def test_failed_without_delivery_refunds_all(db_session):db = db_sessionuser = await make_user(db)await publish_book(db, prices={"seedance-2.5": {"720p": "0.5000"}}, expected_version=None, user_id=user.id)- task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id,+ task = TaskRun(domain="studio", task_type="tool_video", requested_by=user.id,payload={"model": "seedance-2.5", "resolution": "720p", "duration": 5}, status="running")await prepare_task_media(db, task)db.add(task)@@ -132,7 +132,7 @@ async def test_fixed_price_disabled_billing_never_charges_wallet(db_session, monfrom app.config import get_settingsuser = await make_user(db_session)await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)- task = TaskRun(domain="api", task_type="v1_image", requested_by=user.id, payload={"model": "seedream-5.0-pro"}, status="running")+ task = TaskRun(domain="studio", task_type="tool_image", requested_by=user.id, payload={"model": "seedream-5.0-pro"}, status="running")await prepare_task_media(db_session, task)db_session.add(task)await db_session.flush()diff --git a/backend/tests/test_media_fixed_routes.py b/backend/tests/test_media_fixed_routes.pyindex 8641b09..c56f13b 100644--- a/backend/tests/test_media_fixed_routes.py+++ b/backend/tests/test_media_fixed_routes.py@@ -79,7 +79,7 @@ async def test_recovery_reuses_accepted_provider_id_without_submit(gateway, db_sark, alpha = gatewayuser = await make_user(db_session)op = operation()- task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id,+ task = TaskRun(domain="studio", task_type="tool_video", requested_by=user.id,billing_snapshot={"items": [op]}, media_provider_tasks={op["operation_id"]: "accepted-id"})db_session.add(task)await db_session.flush()diff --git a/backend/tests/test_media_pricing_api.py b/backend/tests/test_media_pricing_api.pyindex 1f6ae3f..7e667b1 100644--- a/backend/tests/test_media_pricing_api.py+++ b/backend/tests/test_media_pricing_api.py@@ -1,6 +1,3 @@-from unittest.mock import AsyncMock-from types import SimpleNamespace-import httpximport pytestfrom sqlalchemy import func, select@@ -8,9 +5,8 @@ from sqlalchemy import func, selectfrom app.database import get_dbfrom app.deps import get_current_admin, get_current_userfrom app.main import app-from app.models import UsageEvent+from app.models import UsageEvent, Userfrom app.models_tasks import TaskRun-from app.services.ark import ImageResultfrom app.services.media_models.prices import active_book, publish_bookfrom conftest import make_user@@ -18,13 +14,16 @@ from conftest import make_user@pytest.fixtureasync def client(db_session):user = await make_user(db_session)+ user_id = user.id+ await db_session.commit()async def database():yield db_session+ async def current_user():+ return await db_session.get(User, user_id, populate_existing=True)saved = dict(app.dependency_overrides)- from app.api.v1.generation import _resolve_api_user- app.dependency_overrides.update({get_db: database, get_current_user: lambda: user,- get_current_admin: lambda: user, _resolve_api_user: lambda: user})- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app, raise_app_exceptions=False), base_url="http://test") as http:+ app.dependency_overrides.update({get_db: database, get_current_user: current_user,+ get_current_admin: current_user})+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as http:yield http, userapp.dependency_overrides.clear()app.dependency_overrides.update(saved)@@ -53,30 +52,38 @@ async def test_admin_publish_catalog_and_quote_have_same_price(client, db_sessio@pytest.mark.asyncio-async def test_stale_catalog_and_unpriced_resolution_never_create_task(client, db_session, monkeypatch):+async def test_stale_catalog_and_unpriced_resolution_never_create_task(client, db_session):http, user = clientbook = await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.10"}}, expected_version=None, user_id=user.id)- provider = AsyncMock()- monkeypatch.setattr("app.api.v1.generation.get_ark", lambda: SimpleNamespace(gen_image=provider))+ await db_session.commit()before = await db_session.scalar(select(func.count(TaskRun.id)))- response = await http.post("/api/v1/images/generations", headers={"X-Media-Price-Version": str(book["version"] + 1)}, json={"prompt": "test", "model": "seedream-5.0-pro"})+ response = await http.post("/api/tools/run", headers={"X-Media-Price-Version": str(book["version"] + 1)}, data={+ "tool_id": "t2i", "prompt": "test", "model_id": "seedream-5.0-pro"})assert response.status_code == 409, response.text- response = await http.post("/api/v1/images/generations", json={"prompt": "test", "model": "seedream-5.0-pro", "resolution": "1K"})+ response = await http.post("/api/tools/run", data={"tool_id": "t2i",+ "prompt": "test", "model_id": "seedream-5.0-pro", "resolution": "1K"})assert response.status_code == 422, response.textassert await db_session.scalar(select(func.count(TaskRun.id))) == before- provider.assert_not_awaited()@pytest.mark.asyncio-async def test_api_partial_delivery_is_persisted_and_charged_once(client, db_session, monkeypatch):- http, user = client+async def test_partial_inline_delivery_is_persisted_and_charged_once(client, db_session):+ from app.services.billing.ephemeral import run_billed_ephemeral+ from app.services.billing.context import get_current_task_run_id+ from app.services.billing.usage import record_line++ _, user = clientawait publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)- provider = AsyncMock(side_effect=[ImageResult(local_url="/static/one.png"),- ImageResult(local_url="/static/two.png"), RuntimeError("provider unavailable")])- monkeypatch.setattr("app.api.v1.generation.get_ark", lambda: SimpleNamespace(gen_image=provider))- monkeypatch.setattr("app.services.storage.republish_url", lambda url, **kwargs: url)- response = await http.post("/api/v1/images/generations", json={"prompt": "test", "model": "seedream-5.0-pro", "count": 3})- assert response.status_code >= 400+ async def deliver():+ task = await db_session.get(TaskRun, get_current_task_run_id())+ task.result_payload = {"kind": "image", "urls": ["/static/one.png", "/static/two.png"]}+ for index in range(2):+ await record_line(db_session, user_id=user.id, billing_key="seedream", model="seedream-5.0-pro",+ domain="studio", raw={"delivery_id": f"stored-image-{index}"})+ raise RuntimeError("provider unavailable")+ with pytest.raises(RuntimeError, match="provider unavailable"):+ await run_billed_ephemeral(db_session, user, domain="studio", task_type="tool_image", executor=deliver,+ payload={"model": "seedream-5.0-pro", "count": 3}, commit=True)task = (await db_session.execute(select(TaskRun).where(TaskRun.requested_by == user.id))).scalar_one()assert task.status == "failed"assert task.billing_estimate_fen == 39@@ -91,13 +98,15 @@ async def test_disable_only_affects_new_tasks_and_rejects_stale_fixed_price(cliehttp, user = clientbook = await publish_book(db_session, prices={"seedance-2.5": {"720p": "0.50"}}, expected_version=None, user_id=user.id)from app.services.media_models.planning import prepare_task_media- task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id, payload={"model": "seedance-2.5", "resolution": "720p", "duration": 5})+ task = TaskRun(domain="studio", task_type="tool_video", requested_by=user.id, payload={"model": "seedance-2.5", "resolution": "720p", "duration": 5})await prepare_task_media(db_session, task)response = await http.patch("/api/admin/settings/billing/media-prices/activation", json={"enabled": False, "expected_version": book["version"]})assert response.status_code == 200assert await active_book(db_session) is Noneassert task.billing_snapshot["mode"] == "fixed_media"- response = await http.post("/api/v1/videos/generations", headers={"X-Media-Price-Version": str(book["version"])}, json={"prompt": "test", "image_url": "https://test/a.jpg", "model": "seedance-2.5"})+ response = await http.post("/api/tools/run", headers={"X-Media-Price-Version": str(book["version"])}, data={+ "tool_id": "t2v", "prompt": "test", "model_id": "seedance-2.5", "duration": "5",+ "resolution": "720p", "video_mode": "text_to_video"})assert response.status_code == 409, response.textdiff --git a/backend/tests/test_media_reference_limits.py b/backend/tests/test_media_reference_limits.pyindex b55a809..16448ff 100644--- a/backend/tests/test_media_reference_limits.py+++ b/backend/tests/test_media_reference_limits.py@@ -103,21 +103,21 @@ async def test_reference_video_url_is_resolved_before_provider_request(monkeypat@pytest.mark.asyncio@pytest.mark.parametrize("task_type,payload", [- ("v1_image", {"model": "seedream-5.0-pro", "reference_images": ["a", "b"]}),- ("v1_video", {"model": "seedance-2.5", "reference_audios": ["a", "b"]}),- ("v1_seedance", {"model": "seedance-2.5", "prepared": {"seedance_body": {+ ("tool_image", {"model": "seedream-5.0-pro", "reference_images": ["a", "b"]}),+ ("tool_video", {"model": "seedance-2.5", "reference_audios": ["a", "b"]}),+ ("tool_video", {"model": "seedance-2.5", "prepared": {"seedance_body": {"content": [{"type": "video_url", "video_url": {"url": "a"}}] * 2}}}),])async def test_direct_task_requests_are_rejected_during_planning(configured, task_type, payload):with pytest.raises(MediaValidationError):- await plan_items(None, TaskRun(domain="api", task_type=task_type, payload=payload))+ await plan_items(None, TaskRun(domain="studio", task_type=task_type, payload=payload))@pytest.mark.asyncioasync def test_zero_image_limit_blocks_single_image_api_request(configured):configured.media_reference_limits["seedream-5.0-pro"]["images"] = 0with pytest.raises(MediaValidationError, match="不支持参考图片"):- await plan_items(None, TaskRun(domain="api", task_type="v1_image",+ await plan_items(None, TaskRun(domain="studio", task_type="tool_image",payload={"model": "seedream-5.0-pro", "image_url": "https://example.com/a.png"}))@@ -180,7 +180,7 @@ async def test_rejected_task_does_not_insert_or_check_balance(configured, monkeybalance = AsyncMock()monkeypatch.setattr("app.services.billing.settlement.ensure_balance_for_task", balance)db = SimpleNamespace(add=Mock(), flush=AsyncMock())- body = TaskCreateRequest(domain="api", task_type="v1_image",+ body = TaskCreateRequest(domain="studio", task_type="tool_image",payload={"model": "seedream-5.0-pro", "reference_images": ["a", "b"]})with pytest.raises(MediaValidationError):await service.create_task(db, User(id=1), body)@@ -192,7 +192,7 @@ async def test_rejected_task_does_not_insert_or_check_balance(configured, monkey@pytest.mark.asyncioasync def test_rejected_media_does_not_read_price_book(configured):db = SimpleNamespace(execute=AsyncMock())- task = TaskRun(domain="api", task_type="v1_video", payload={"model": "seedance-2.5", "reference_videos": ["a", "b"]})+ task = TaskRun(domain="studio", task_type="tool_video", payload={"model": "seedance-2.5", "reference_videos": ["a", "b"]})with pytest.raises(MediaValidationError):await prepare_task_media(db, task)db.execute.assert_not_awaited()diff --git a/backend/tests/test_public_api_removed.py b/backend/tests/test_public_api_removed.pynew file mode 100644index 0000000..f37d670--- /dev/null+++ b/backend/tests/test_public_api_removed.py@@ -0,0 +1,67 @@+"""Removed external generation routes and keys must never grant application access."""+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest+from fastapi import HTTPException+from fastapi.security import HTTPAuthorizationCredentials++from app.deps import _user_from_bearer, get_current_user+from app.main import app+from app.schemas_tasks import TaskCreateRequest+from app.services.tasks.handlers import get_task_handler+from app.services.tasks.service import create_task++[email protected]("method,path", [+ ("GET", "/api/user/api-keys"), ("POST", "/api/user/api-keys"),+ ("DELETE", "/api/user/api-keys/1"), ("POST", "/api/v1/images/generations"),+ ("POST", "/api/v1/videos/generations"), ("POST", "/api/v1/seedance/tasks"),+ ("GET", "/api/v1/tasks/retired-task"),+])+async def test_removed_routes_are_not_reachable(method, path):+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ response = await client.request(method, path)+ assert response.status_code == 404+ assert not any(route.startswith(("/api/v1/", "/api/user/api-keys")) for route in app.openapi()["paths"])+++async def test_retired_key_is_not_accepted_as_application_bearer():+ db = SimpleNamespace(execute=AsyncMock())+ creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials="pf_live_retired_test_key")+ assert await _user_from_bearer(db, creds.credentials) is None+ with pytest.raises(HTTPException) as error:+ await get_current_user(creds=creds, db=db)+ assert error.value.status_code == 401+ db.execute.assert_not_awaited()+++async def test_valid_login_jwt_still_resolves_application_user(monkeypatch):+ user = SimpleNamespace(id=31)+ lookup = AsyncMock(return_value=user)+ monkeypatch.setattr("app.deps.decode_token", lambda token: "31")+ monkeypatch.setattr("app.deps.get_user_by_id", lookup)+ assert await _user_from_bearer(None, "login-jwt") is user+ lookup.assert_awaited_once_with(None, 31)+++async def test_key_header_cannot_authenticate_an_application_route():+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:+ response = await client.get("/api/tasks/generations", headers={"X-Api-Key": "pf_live_retired_test_key"})+ assert response.status_code == 401++[email protected]("kind", ["v1_image", "v1_video", "v1_seedance"])+async def test_generic_task_admission_cannot_recreate_removed_generations(kind):+ assert get_task_handler("api", kind) is None+ db = SimpleNamespace(add=AsyncMock(), flush=AsyncMock())+ with pytest.raises(ValueError, match="尚未接入"):+ await create_task(db, SimpleNamespace(id=1), TaskCreateRequest(domain="api", task_type=kind))+ db.add.assert_not_called()+ db.flush.assert_not_awaited()diff --git a/backend/tests/test_record_seedream_image_usage.py b/backend/tests/test_record_seedream_image_usage.pyindex ca35b32..4ec4885 100644--- a/backend/tests/test_record_seedream_image_usage.py+++ b/backend/tests/test_record_seedream_image_usage.py@@ -23,7 +23,7 @@ async def test_record_seedream_with_upstream_tokens(db_session: AsyncSession) ->db_session,user_id=user.id,model="seedream-test",- domain="api",+ domain="studio",image_result=image,)await db_session.commit()diff --git a/backend/tests/test_security_hardening.py b/backend/tests/test_security_hardening.pyindex a6ee55a..05ec801 100644--- a/backend/tests/test_security_hardening.py+++ b/backend/tests/test_security_hardening.py@@ -14,12 +14,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.api import billing as billing_apifrom app.api import tools as tools_api-from app.api.v1 import generation as v1_generationfrom app.deps import _user_from_bearerfrom app.models import Order, User, WalletLedgerfrom app.services import epay-from tests.conftest import make_task, make_user+from tests.conftest import make_userclass _FakeNotifyRequest:@@ -105,48 +104,6 @@ def test_epay_verify_constant_time_signature() -> None:assert "compare_digest" in inspect.getsource(epay.verify)-async def test_v1_get_task_rejects_other_user(db_session: AsyncSession) -> None:- """B 用户不得凭上游 task_id 查询 A 用户的视频任务(IDOR)。"""- user_a = await make_user(db_session)- user_b = await make_user(db_session)- await make_task(- db_session,- user_a,- domain="api",- task_type="v1_seedance",- status="awaiting_poll",- billing_status="frozen",- provider_task_id="prov-idor-1",- )-- poll = AsyncMock(return_value={"status": "running"})- with patch.object(v1_generation, "poll_video_task", poll):- with pytest.raises(HTTPException) as exc:- await v1_generation.get_task("prov-idor-1", db=db_session, user=user_b)- assert exc.value.status_code == 404- poll.assert_not_called()---async def test_v1_get_task_allows_owner(db_session: AsyncSession) -> None:- """归属人查询自己的任务正常透传上游状态。"""- user = await make_user(db_session)- await make_task(- db_session,- user,- domain="api",- task_type="v1_seedance",- status="awaiting_poll",- billing_status="frozen",- provider_task_id="prov-owner-1",- )-- poll = AsyncMock(return_value={"status": "running"})- with patch.object(v1_generation, "poll_video_task", poll):- out = await v1_generation.get_task("prov-owner-1", db=db_session, user=user)- assert out.status == "running"- poll.assert_awaited_once()--async def test_tools_get_task_404_without_local_row(db_session: AsyncSession) -> None:"""/api/tools/tasks 本地无归属记录时不得代理查询上游。"""user = await make_user(db_session)diff --git a/backend/tests/test_studio_generation.py b/backend/tests/test_studio_generation.pyindex 14ee8e4..fa00350 100644--- a/backend/tests/test_studio_generation.py+++ b/backend/tests/test_studio_generation.py@@ -50,7 +50,7 @@ async def studio(monkeypatch):@pytest.mark.parametrize("kind,payload,queue", [("script_summary", {}, "text"), ("voice_synthesis", {}, "text"), ("tool_audio", {}, "text"),("asset_image", {}, "image"), ("tool_image", {}, "image"), ("shot_regen_image", {}, "image"),- ("fragment_video", {}, "video"), ("asset_video", {}, "video"), ("v1_seedance", {}, "video"),+ ("fragment_video", {}, "video"), ("asset_video", {}, "video"),("project_pipeline", {"phase": "script"}, "text"), ("project_pipeline", {"phase": "assets"}, "image"),("project_pipeline", {"phase": "videos"}, "video"),])diff --git a/backend/tests/test_task_executor_freeze_steps.py b/backend/tests/test_task_executor_freeze_steps.pyindex 55db764..623214c 100644--- a/backend/tests/test_task_executor_freeze_steps.py+++ b/backend/tests/test_task_executor_freeze_steps.py@@ -30,7 +30,7 @@ def test_execute_task_run_source_reads_steps_before_freeze() -> None:async def test_freeze_expires_preloaded_steps_relationship(db_session: AsyncSession) -> None:"""根因:_lock_task(populate_existing) 会使已 selectinload 的 steps 失效。"""user = await make_user(db_session, balance_fen=50_000)- task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ task = await make_task(db_session, user, domain="studio", task_type="tool_image", status="leased")db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))await db_session.commit()@@ -47,7 +47,7 @@ async def test_freeze_expires_preloaded_steps_relationship(db_session: AsyncSessasync def test_held_step_survives_freeze_populate_existing(db_session: AsyncSession) -> None:"""修复路径:先持有 step 再 freeze,仍可写步骤状态(不必再碰 task.steps)。"""user = await make_user(db_session, balance_fen=50_000)- task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ task = await make_task(db_session, user, domain="studio", task_type="tool_image", status="leased")db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))await db_session.commit()@@ -80,8 +80,8 @@ async def test_execute_task_run_survives_freeze_populate_existing(task = await make_task(db_session,user,- domain="api",- task_type="v1_image",+ domain="studio",+ task_type="tool_image",status="leased",)db_session.add(@@ -99,7 +99,12 @@ async def test_execute_task_run_survives_freeze_populate_existing(async def same_session():yield db_session- with patch("app.services.tasks.executor.AsyncSessionLocal", same_session):+ from app.services.tasks.handlers import TaskHandler+ fake = TaskHandler("studio", "tool_image", AsyncMock(return_value={"ok": True}))+ with (+ patch("app.services.tasks.executor.AsyncSessionLocal", same_session),+ patch("app.services.tasks.executor.get_task_handler", return_value=fake),+ ):await execute_task_run(task_id)db_session.expire_all()@@ -120,8 +125,8 @@ async def test_execute_task_run_marks_failed_when_handler_returns_ok_false(task = await make_task(db_session,user,- domain="api",- task_type="v1_image",+ domain="studio",+ task_type="tool_image",status="leased",)db_session.add(@@ -142,7 +147,7 @@ async def test_execute_task_run_marks_failed_when_handler_returns_ok_false(async def same_session():yield db_session- fake = TaskHandler("api", "v1_image", _failing_executor)+ fake = TaskHandler("studio", "tool_image", _failing_executor)with (patch("app.services.tasks.executor.AsyncSessionLocal", same_session),patch("app.services.tasks.executor.get_task_handler", return_value=fake),@@ -162,7 +167,7 @@ async def _lease_task_with_step(db_session: AsyncSession):from contextlib import asynccontextmanager as _acmuser = await make_user(db_session, balance_fen=50_000)- task = await make_task(db_session, user, domain="api", task_type="v1_image", status="leased")+ task = await make_task(db_session, user, domain="studio", task_type="tool_image", status="leased")db_session.add(TaskStep(task_id=task.id, step_key="main", step_type="run", status="pending"))await db_session.commit()diff --git a/backend/tests/test_task_poller_dispatch.py b/backend/tests/test_task_poller_dispatch.pyindex 3030f74..445fb8f 100644--- a/backend/tests/test_task_poller_dispatch.py+++ b/backend/tests/test_task_poller_dispatch.py@@ -24,7 +24,7 @@ async def _same_session(db: AsyncSession):async def test_selector_only_dispatches_fragment_video_to_drama_poller(db_session: AsyncSession,) -> None:- """api/studio deferred 视频任务必须只走 ephemeral 轮询,不能被 drama poller 判失败。"""+ """studio deferred 视频任务必须只走 ephemeral 轮询,不能被 drama poller 判失败。"""user = await make_user(db_session)now = datetime.now(UTC)# 漫剧分镜视频:唯一允许进入 drama poller 的任务@@ -36,19 +36,19 @@ async def test_selector_only_dispatches_fragment_video_to_drama_poller(status="awaiting_poll",provider_task_id="prov-drama-1",)- # 开放 API / 工具的 deferred 视频:旧实现下会被误送 drama poller 并立即判失败- api_task = await make_task(+ # 工作室工具的 deferred 视频:旧实现下会被误送 drama poller 并立即判失败+ studio_task = await make_task(db_session,user,- domain="api",- task_type="v1_seedance",+ domain="studio",+ task_type="tool_video",status="awaiting_poll",- provider_task_id="prov-api-1",+ provider_task_id="prov-studio-1",)drama_task.next_action_at = now - timedelta(seconds=1)- api_task.next_action_at = now - timedelta(seconds=1)+ studio_task.next_action_at = now - timedelta(seconds=1)await db_session.commit()- api_task_id = int(api_task.id)+ studio_task_id = int(studio_task.id)drama_poll = AsyncMock()with (@@ -59,7 +59,7 @@ async def test_selector_only_dispatches_fragment_video_to_drama_poller(called_ids = {call.args[0] for call in drama_poll.await_args_list}assert called_ids == {int(drama_task.id)}- assert api_task_id not in called_ids+ assert studio_task_id not in called_ids@pytest.mark.asyncio@@ -102,8 +102,8 @@ async def test_ephemeral_poller_respects_next_action_at_gate(due_task = await make_task(db_session,user,- domain="api",- task_type="v1_video",+ domain="studio",+ task_type="tool_video",status="awaiting_poll",provider_task_id="prov-due",)diff --git a/backend/tests/test_upstream_observability.py b/backend/tests/test_upstream_observability.pyindex 0d2516e..c299742 100644--- a/backend/tests/test_upstream_observability.py+++ b/backend/tests/test_upstream_observability.py@@ -216,8 +216,7 @@ async def test_caller_session_logging_error_does_not_repeat_network_request(monk@pytest.mark.asyncio[email protected]("deferred", [False, True])-async def test_ephemeral_executor_installs_caller_event_session(monkeypatch, deferred):+async def test_ephemeral_executor_installs_caller_event_session(monkeypatch):"""同步和异步任务先登记受理;请求日志共用执行会话且不额外提交。"""from app.services.billing import ephemeral@@ -238,8 +237,8 @@ async def test_ephemeral_executor_installs_caller_event_session(monkeypatch, defawait upstream.observed_request(client, "POST", "https://gateway.test/v1/videos", json={"model": "MiniMax-H3"})return {"task_id": "inline-provider"}- run = ephemeral.run_billed_ephemeral_deferred if deferred else ephemeral.run_billed_ephemeral- await run(db, SimpleNamespace(id=9), domain="api", task_type="v1_video", executor=executor, commit=False)+ run = ephemeral.run_billed_ephemeral+ await run(db, SimpleNamespace(id=9), domain="studio", task_type="tool_video", executor=executor, commit=False)assert [event.event_type for event in events] == ["upstream.request.started", "upstream.request.accepted"]assert db.flush.await_count == 1 # 仅业务已有的 task.started flush。db.commit.assert_awaited_once() # 接受任务在模型调用前持久化。diff --git a/docs/BILLING.md b/docs/BILLING.mdindex 658168d..5f8f108 100644--- a/docs/BILLING.md+++ b/docs/BILLING.md@@ -145,7 +145,6 @@ sequenceDiagram| 科普选题扩写 | `run_billed_ephemeral(domain=kepu, content_expand)` || 漫剧资产 seed(轻量同步) | `run_billed_ephemeral(domain=drama, seed_assets)` || 工作室工具 | `run_billed_ephemeral(domain=studio, tool_image/tool_video)` |-| 开放 API | `run_billed_ephemeral(domain=api, v1_image/v1_video/v1_seedance)` |### LLM 操作全清单(`billing_key=llm_chat`)@@ -221,7 +220,7 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=11. 科普:确认分镜只冻出图+配音;继续生成视频另冻视频段;合成走 compose。各阶段任务结束按实际用量结算。2. 漫剧分镜视频/资产生成:有 `task_run_id` 的用量行,任务结束扣费。-3. 漫剧聊天 / 选题扩写 / Skill 优化 / 音色描述 / 开放 API / 工作室工具:响应含 `task_id`(轻量 TaskRun),余额变化正确。+3. 漫剧聊天 / 选题扩写 / Skill 优化 / 音色描述 / 工作室工具:响应含 `task_id`(轻量 TaskRun),余额变化正确。4. 管理端可按 `task_run_id` 或 `billing_key=llm_chat` 查到每条 LLM/图/视频/TTS 费用。5. Seedance 视频成功后 `usage_events.estimated=false` 且 `total_tokens` 与官方任务查询一致。6. 财务列表支持按时间范围汇总本地扣费与用量,仪表盘和订单用量不显示上游成本、利润或官方对照。diff --git a/docs/MEDIA_MODEL_STRATEGIES.md b/docs/MEDIA_MODEL_STRATEGIES.mdindex 72c9ee3..920d5dc 100644--- a/docs/MEDIA_MODEL_STRATEGIES.md+++ b/docs/MEDIA_MODEL_STRATEGIES.md@@ -57,6 +57,6 @@| `POST /api/admin/settings/billing/media-prices` | `{prices: {model_id: {resolution: "元单价"}}, expected_version}`,发布不可变新版本 || `PATCH /api/admin/settings/billing/media-prices/activation` | `{enabled, expected_version}`,切换新任务计费模式 |-前端生成请求携带 `X-Media-Price-Version`(旧模式目录为 0)。价格或模式发生变化返回 409,在建任务、冻结资金、提交上游之前结束。刷新目录后由用户重新提交,不自动重发生成请求。开放 API 也可在请求体提供 `price_version`。+前端生成请求携带 `X-Media-Price-Version`(旧模式目录为 0)。价格或模式发生变化返回 409,在建任务、冻结资金、提交上游之前结束。刷新目录后由用户重新提交,不自动重发生成请求。-图片开放 API 支持 `model`、`resolution`、`count`;视频支持 `model`、`resolution`、`duration` 和画幅。缺省值兼容原请求形式,但模型不支持的组合会返回字段错误,不自动降档。+站内图片生成按模型、分辨率和数量报价;视频按模型、分辨率和提交时长报价。模型不支持的组合返回字段错误,不自动降档。diff --git a/docs/PLACEHOLDER_BACKLOG.md b/docs/PLACEHOLDER_BACKLOG.mdindex c4db790..e33dae4 100644--- a/docs/PLACEHOLDER_BACKLOG.md+++ b/docs/PLACEHOLDER_BACKLOG.md@@ -37,6 +37,7 @@| G-07 | 个人漫剧 / 自由画布 / 团队统一项目卡片 | 已完成待部署 | P1 | 共用 `ProjectCard` / `ProjectGrid`:封面叠字、状态胶囊、简介与真实费用信息;仅有真实分集数据时显示进度。菜单、复选框与打开操作独立,保留团队删除权限和历史账单 || G-08 | 统一新建入口、弹窗与项目输入样式 | 已完成待部署 | P1 | 取消网格内大尺寸新增占位卡,新建按钮置于项目标题右侧;共用 `ProjectCreateDialog`,区分漫剧和画布字段;计划集数严格校验 1–120 整数,支持字段错误聚焦、提交防重和失败保留输入 || G-09 | 资产库增加图片 / 视频 / 音频及无项目素材 | 已完成待部署 | P1 | 删除顶部三个快捷跳转;新增只读 `/api/drama/library-assets` 聚合项目资产和独立工具正式输出,支持未关联项目筛选、来源独立 key、搜索分页、预览下载与个人/团队隔离。媒体分类可覆盖角色等业务分类;科普镜头/成片及未建资产的分镜视频尚未纳入 |+| G-10 | 移除开放 API 功能与专用代码 | 已完成待部署 | P1 | 删除用户密钥面板、客户端、鉴权、ORM、`/api/user/api-keys` 与 `/api/v1` 路由、任务注册及专用计费提交逻辑。保留历史记录和通用在途结算;部署后旧路由须 404、旧密钥须 401。需重启全部后端实例,不能只更新前端 |---diff --git a/docs/PRINTFILM_UI_ROADMAP.md b/docs/PRINTFILM_UI_ROADMAP.mdindex b633eda..16f6952 100644--- a/docs/PRINTFILM_UI_ROADMAP.md+++ b/docs/PRINTFILM_UI_ROADMAP.md@@ -67,6 +67,16 @@2026-10-26 本地验收:运行中的后端已加载新路由,未登录请求返回 401;使用已授权诊断项目的所属账号进行只读查询,全部资产、图片、视频、音频、未关联项目、单项目、项目名搜索及第二页均返回 200。检查分类匹配、跨页 key 不重复、无项目记录不产生项目链接、非法类型返回 422。前端 73 项及后端相关 19 项回归通过。此记录仅表示本地验收通过,线上发布仍需完成部署后的同类检查。+## 2026-10-26 移除开放 API++删除设置页 API Key 分区、密钥管理客户端及样式,旧 `?tab=api` 回落到账号信息。后端删除用户密钥路由、密钥服务、ORM/请求模型及 `/api/v1` 生图、生视频、Seedance 提交和查询路由;站内鉴权只接受登录 JWT,旧密钥及 `X-Api-Key` 不再提供站内访问能力。任务注册、报价/估价分支、管理端领域筛选和对外调用说明同步清理。++历史账单、用量与任务记录不删除、不重算;已取得上游任务 ID 的历史任务仍通过共用轮询与结算代码收尾,避免冻结资金悬挂。历史队列字段回填保留必要的数据兼容。旧 `user_api_keys` 表不再注册或访问,本次不执行删表;上游模型渠道密钥与站内生成继续使用。++发布需更新前端、管理端并重启后端全部实例,确认旧密钥管理和生成地址返回 404、旧密钥访问站内接口返回 401、登录 JWT 正常,再验证工具生成、计费和历史记录。只刷新前端不能停用仍在运行的旧后端。++本次源码验收:前端 79 项、后端相关 211 项测试通过,前端与管理端构建及静态检查通过(保留已有告警)。本地旧后端未开启热重载,自动审批拦截了进程重启,运行服务尚需重启验证;旧地址返回 401 仅表示未登录,不能作为路由删除成功的证据,重启后必须检查为 404。+## 已实现(接线现有 API)- 登录 / 注册 / 导航账户状态diff --git a/docs/TASK_SCHEDULING.md b/docs/TASK_SCHEDULING.mdindex 7a01af0..334ac6f 100644--- a/docs/TASK_SCHEDULING.md+++ b/docs/TASK_SCHEDULING.md@@ -12,13 +12,13 @@ TASK_QUEUE_VIDEO_CONCURRENCY=4未配置时,各队列沿用 `TASK_RUNTIME_MAX_CONCURRENCY`,默认每队列 4,总容量 12。单用户限制按队列计算,团队限制仍跨队列共用。视频等待上游的 `awaiting_poll` 任务占视频队列容量,但不占本地执行协程。-调度器使用 PostgreSQL 每队列事务级 advisory lock、任务行锁与状态条件更新领取任务。持有执行任务的进程每 10 秒续租;其他进程只恢复已经过期的租约。取消使用独立槽位。仍以内联方式响应的聊天及开放 API 请求保留原请求行为,并记录所属队列。+调度器使用 PostgreSQL 每队列事务级 advisory lock、任务行锁与状态条件更新领取任务。持有执行任务的进程每 10 秒续租;其他进程只恢复已经过期的租约。取消使用独立槽位。仍以内联方式响应的聊天请求保留原请求行为,并记录所属队列。## 生成与任务记录- 主侧栏提供「视频」「图片」「我的任务」入口,桌面与移动菜单共用配置;视频、图片与 AI 短视频项目分别高亮。- `/tools/video`、`/tools/image`、`/tools/audio`:复用已有接口的独立生成工作台;原 `/tools/t2i`、`/tools/t2v` 等工具地址保留原工具表单。-- `/tasks`:「我的任务」统一展示工具工作台、漫剧、短视频、画布及开放 API 的生成任务,默认显示全部,支持视频、图片、音频、文字分类,以及状态、本地/上游任务 ID、日期筛选和下载。以上生成与任务页面需要登录,登录后返回原地址并保留查询参数。+- `/tasks`:「我的任务」统一展示工具工作台、漫剧、短视频及画布的生成任务,默认显示全部,支持视频、图片、音频、文字分类,以及状态、本地/上游任务 ID、日期筛选和下载。以上生成与任务页面需要登录,登录后返回原地址并保留查询参数。- `GET /api/tasks/generations` 从 `TaskRun` 读取各入口任务,并合并没有关联统一任务的旧 `ToolRun`,关联记录只显示一次;服务端完成筛选、统计和分页,读取列表不会补写任务或调用上游。`GET /api/tasks/generations/{task_id}` 返回统一任务详情;旧工具记录仍使用工具详情接口。个人和团队空间分别授权,切换空间时取消旧请求并清空详情。- 生成请求受理后先提交任务登记,再执行外部生成;个人配音、试听和分集合成也登记任务,保留各自原计费规则。完成、失败或取消均持久化状态,已保存的结果快照用于预览或下载,文字生成可查看及下载文本。- HTTP 内联生成使用独立续租心跳保护长请求,调度器不会把仍在生成的任务误判为中断后重排队。进程中断且租约过期时,任务收敛为失败或取消并完成原有结算,不自动重发生成请求。diff --git a/frontend/src/api/apiKeys.ts b/frontend/src/api/apiKeys.tsdeleted file mode 100644index f815e53..0000000--- a/frontend/src/api/apiKeys.ts+++ /dev/null@@ -1,41 +0,0 @@-/** API Key 管理客户端(/api/user/api-keys) */--import { API_BASE, createJsonRequester } from './client'-import { apiErrorMessage } from './http'--/** API Key 错误仅交由当前页面展示,不触发计费弹窗。 */-const request = createJsonRequester((response, detail) => {- throw new Error(apiErrorMessage(detail, response.statusText) || '请求失败')-})--export type ApiKeyItem = {- id: number- name: string- key_prefix: string- created_at: string | null- last_used_at: string | null-}--export type ApiKeyCreated = ApiKeyItem & {- secret: string-}--/** 返回开放 API 调用示例使用的服务根地址。 */-export function getPublicApiBase() {- return API_BASE-}--export const apiKeysApi = {- list() {- return request<ApiKeyItem[]>('/api/user/api-keys')- },- create(name: string) {- return request<ApiKeyCreated>('/api/user/api-keys', {- method: 'POST',- body: JSON.stringify({ name }),- })- },- revoke(id: number) {- return request<{ ok: boolean }>(`/api/user/api-keys/${id}`, { method: 'DELETE' })- },-}diff --git a/frontend/src/i18n/locales/en/pages.ts b/frontend/src/i18n/locales/en/pages.tsindex a33a60a..9f9f5a0 100644--- a/frontend/src/i18n/locales/en/pages.ts+++ b/frontend/src/i18n/locales/en/pages.ts@@ -137,7 +137,7 @@ export const enPages = {},{q: 'What’s in Account?',- a: 'Profile, drama projects, AI Short Video history, tool runs, asset library entry, and plan & balance. Team, API, and notifications are still in progress.',+ a: 'Profile, drama projects, AI Short Video history, tool runs, asset library entry, and plan & balance. Team workspace and account security are available; notification preferences are still in progress.',},{q: 'How do top-ups and charges work?',@@ -196,7 +196,7 @@ export const enPages = {},{title: 'Enterprise / wire transfer',- desc: 'For bulk credits, API partnerships, or invoices, email your company name and request.',+ desc: 'For bulk credits, business partnerships, or invoices, email your company name and request.',href: 'mailto:[email protected]?subject=PRINTFILM%20Enterprise',actionLabel: 'Email partnerships',},diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.tsindex 38df665..68b4b5c 100644--- a/frontend/src/i18n/locales/en/shell.ts+++ b/frontend/src/i18n/locales/en/shell.ts@@ -148,7 +148,6 @@ export const enShell = {assets: 'Assets',subscription: 'Plan & balance',team: 'Team',- api: 'API',notify: 'Notifications',security: 'Security',},diff --git a/frontend/src/i18n/locales/zh/pages.ts b/frontend/src/i18n/locales/zh/pages.tsindex 8729b05..79f1db7 100644--- a/frontend/src/i18n/locales/zh/pages.ts+++ b/frontend/src/i18n/locales/zh/pages.ts@@ -137,7 +137,7 @@ export const zhPages = {},{q: '个人中心有哪些内容?',- a: '包含账号信息、漫剧项目、AI短视频历史、工具创作记录、资产管理入口,以及订阅与余额。团队、API、通知偏好等能力仍在建设中。',+ a: '包含账号信息、漫剧项目、AI短视频历史、工具创作记录、资产管理入口,以及订阅与余额。可进入团队空间并管理账号安全,通知偏好仍在建设中。',},{q: '如何充值?余额怎么扣?',@@ -196,7 +196,7 @@ export const zhPages = {},{title: '企业合作 / 对公转账',- desc: '企业批量充值、API 合作或发票需求,请邮件说明公司名称与需求,我们会安排对接。',+ desc: '企业批量充值、商务合作或发票需求,请邮件说明公司名称与需求,我们会安排对接。',href: 'mailto:[email protected]?subject=PRINTFILM%20Enterprise',actionLabel: '发送合作邮件',},diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.tsindex 23b6714..bc3e372 100644--- a/frontend/src/i18n/locales/zh/shell.ts+++ b/frontend/src/i18n/locales/zh/shell.ts@@ -147,7 +147,6 @@ export const zhShell = {assets: '资产管理',subscription: '订阅与余额',team: '团队管理',- api: 'API',notify: '通知偏好',security: '安全',},diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsxindex c8b3697..9c782be 100644--- a/frontend/src/pages/SettingsPage.tsx+++ b/frontend/src/pages/SettingsPage.tsx@@ -6,7 +6,6 @@ import { api, type User, type Wallet } from '../api'import { dramaApi, type DramaProjectListItem } from '../api/drama'import MonthlyUsageCard from '../components/billing/MonthlyUsageCard'import UsageChargeRecords from '../components/billing/UsageChargeRecords'-import ApiKeysPanel from './settings/ApiKeysPanel'import AccountProfileCard from './settings/AccountProfileCard'import ChangePasswordCard from './settings/ChangePasswordCard'import ComingSoon from '../components/ui/ComingSoon'@@ -25,7 +24,6 @@ type SettingsTab =| 'assets'| 'subscription'| 'team'- | 'api'| 'notify'| 'security'@@ -49,7 +47,6 @@ const SIDE_ITEMS: { id: SettingsTab; soon?: boolean; group?: 'work' | 'account'{ id: 'assets', group: 'work' },{ id: 'subscription', group: 'account' },{ id: 'team', group: 'account' },- { id: 'api', group: 'account' },{ id: 'notify', soon: true, group: 'account' },{ id: 'security', group: 'account' },]@@ -319,8 +316,6 @@ export default function SettingsPage() {{tab === 'security' ? <ChangePasswordCard email={user?.email || ''} /> : null}- {tab === 'api' ? <ApiKeysPanel /> : null}-{tab === 'team' ? <TeamDirectory compact /> : null}{tab === 'notify' ? (diff --git a/frontend/src/pages/settings/ApiKeysPanel.tsx b/frontend/src/pages/settings/ApiKeysPanel.tsxdeleted file mode 100644index eeba25e..0000000--- a/frontend/src/pages/settings/ApiKeysPanel.tsx+++ /dev/null@@ -1,195 +0,0 @@-import { useEffect, useState } from 'react'-import { apiKeysApi, getPublicApiBase, type ApiKeyItem } from '../../api/apiKeys'-import { dialog } from '../../lib/dialog'--/** 格式化时间 */-function formatWhen(iso?: string | null) {- if (!iso) return '—'- const d = new Date(iso)- if (Number.isNaN(d.getTime())) return '—'- return d.toLocaleString('zh-CN', {- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit',- })-}--/** 设置页 API:Key 管理与调用文档 */-export default function ApiKeysPanel() {- /*- * keys Key 列表- * name 新建名称- * busy 提交中- * error 错误- * createdSecret 刚创建的一次性 secret- */- const [keys, setKeys] = useState<ApiKeyItem[]>([])- const [name, setName] = useState('')- const [busy, setBusy] = useState(false)- const [error, setError] = useState('')- const [createdSecret, setCreatedSecret] = useState('')-- const base = getPublicApiBase()-- async function reload() {- setError('')- try {- setKeys(await apiKeysApi.list())- } catch (e) {- setError(e instanceof Error ? e.message : '加载失败')- }- }-- useEffect(() => {- void reload()- }, [])-- async function handleCreate() {- if (busy) return- setBusy(true)- setError('')- setCreatedSecret('')- try {- const row = await apiKeysApi.create(name.trim() || '默认 Key')- setCreatedSecret(row.secret)- setName('')- await reload()- } catch (e) {- setError(e instanceof Error ? e.message : '创建失败')- } finally {- setBusy(false)- }- }-- async function handleRevoke(item: ApiKeyItem) {- const ok = await dialog.confirm({- title: '撤销 API Key',- message: `确定撤销「${item.name}」(${item.key_prefix}…)?撤销后无法恢复。`,- confirmText: '撤销',- })- if (!ok) return- setBusy(true)- setError('')- try {- await apiKeysApi.revoke(item.id)- await reload()- } catch (e) {- setError(e instanceof Error ? e.message : '撤销失败')- } finally {- setBusy(false)- }- }-- async function copyText(text: string) {- try {- await navigator.clipboard.writeText(text)- } catch {- /* ignore */- }- }-- return (- <section className="pf-settings-card">- <h1>API</h1>- <p className="pf-muted">使用 API Key 调用生图、生视频与 Seedance 转发,按量从余额扣费</p>-- <div className="pf-api-create">- <input- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="Key 名称,如「生产环境」"- maxLength={64}- />- <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" disabled={busy} onClick={() => void handleCreate()}>- {busy ? '处理中…' : '创建 Key'}- </button>- </div>-- {createdSecret ? (- <div className="pf-api-secret">- <p>- <strong>请立即复制保存,关闭后无法再次查看:</strong>- </p>- <code>{createdSecret}</code>- <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" onClick={() => void copyText(createdSecret)}>- 复制 Key- </button>- </div>- ) : null}-- {error ? <p className="pf-error">{error}</p> : null}-- {keys.length > 0 ? (- <ul className="pf-settings-list pf-api-key-list">- {keys.map((item) => (- <li key={item.id}>- <div className="pf-settings-list-row">- <span className="pf-settings-list-main">- <strong>{item.name}</strong>- <em className="pf-muted">- {item.key_prefix}… · 创建于 {formatWhen(item.created_at)}- {item.last_used_at ? ` · 最近使用 ${formatWhen(item.last_used_at)}` : ''}- </em>- </span>- <button- type="button"- className="pf-btn pf-btn-ghost pf-btn-sm"- disabled={busy}- onClick={() => void handleRevoke(item)}- >- 撤销- </button>- </div>- </li>- ))}- </ul>- ) : (- <div className="pf-settings-empty">- <p>还没有 API Key</p>- </div>- )}-- <div className="pf-api-docs">- <h3>调用说明</h3>- <p className="pf-muted">鉴权:Header 任选其一</p>- <pre>{`Authorization: Bearer pf_live_...\nX-Api-Key: pf_live_...`}</pre>-- <p className="pf-muted">生图(Seedream)</p>- <pre>{`POST ${base}/api/v1/images/generations-Content-Type: application/json--{- "prompt": "赛博朋克城市夜景",- "ratio": "16:9",- "image_url": null-}`}</pre>-- <p className="pf-muted">生视频(Seedance 首帧图生视频)</p>- <pre>{`POST ${base}/api/v1/videos/generations--{- "prompt": "镜头缓慢推进,霓虹闪烁",- "image_url": "https://.../first_frame.jpg",- "duration": 5,- "resolution": "480p"-}`}</pre>-- <p className="pf-muted">Seedance 转发(多模态 body)</p>- <pre>{`POST ${base}/api/v1/seedance/tasks--{- "content": [- { "type": "text", "text": "描述..." },- { "type": "image_url", "image_url": { "url": "https://..." }, "role": "first_frame" }- ],- "duration": 5,- "resolution": "480p"-}`}</pre>-- <p className="pf-muted">查询视频任务</p>- <pre>{`GET ${base}/api/v1/tasks/{task_id}`}</pre>- </div>- </section>- )-}diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.cssindex 64ef57f..c9d2de4 100644--- a/frontend/src/styles/printfilm.css+++ b/frontend/src/styles/printfilm.css@@ -5044,65 +5044,6 @@ button.pf-shot-editable:disabled {color: #b45309;}-.pf-api-create {- display: flex;- gap: 0.6rem;- margin: 1rem 0;- flex-wrap: wrap;-}--.pf-api-create input {- flex: 1;- min-width: 180px;- border: 1px solid var(--pf-line);- border-radius: 10px;- padding: 0.55rem 0.75rem;- font: inherit;-}--.pf-api-secret {- margin: 0.75rem 0 1rem;- padding: 0.85rem 1rem;- border-radius: 12px;- border: 1px solid #fde68a;- background: #fffbeb;-}--.pf-api-secret code {- display: block;- margin: 0.5rem 0;- word-break: break-all;- font-size: 0.82rem;-}--.pf-api-key-list {- margin-top: 0.75rem;-}--.pf-api-docs {- margin-top: 1.5rem;- padding-top: 1.25rem;- border-top: 1px solid var(--pf-line);-}--.pf-api-docs h3 {- margin: 0 0 0.75rem;- font-size: 1rem;-}--.pf-api-docs pre {- margin: 0.35rem 0 1rem;- padding: 0.75rem 0.85rem;- border-radius: 10px;- background: #0f172a;- color: #e2e8f0;- font-size: 0.75rem;- line-height: 1.45;- overflow-x: auto;- white-space: pre-wrap;- word-break: break-all;-}-.pf-usage-card-head {margin-bottom: 0.85rem;}