Skip to content

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

chore: 共享接线与配置同步——路由注册、计费基座、导航与 i18n

yica32af41eca2
diff --git a/.gitignore b/.gitignore
index 0032bb2..5473888 100644
--- a/.gitignore
+++ b/.gitignore
@@ -79,3 +79,4 @@ frontend/dist/
.claude/
.cursor/
.work/
+printfilm/
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
index 2bc773c..6580006 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -75,6 +75,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`
- **没有 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` 提权(只提升已注册用户,不造号,需重启)
### 媒体与 OSS
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
index 2659b25..e91504d 100644
--- a/admin/src/App.tsx
+++ b/admin/src/App.tsx
@@ -19,6 +19,8 @@ import { QueuesPage } from "@/pages/QueuesPage";
import { SettingsPage } from "@/pages/SettingsPage";
import { TemplatesPage } from "@/pages/TemplatesPage";
import { UsersPage } from "@/pages/UsersPage";
+import { TeamsPage } from "@/pages/TeamsPage";
+import { TeamDetailPage } from "@/pages/TeamDetailPage";
import { WorksPage } from "@/pages/WorksPage";
// Guard: require JWT + admin role
@@ -40,6 +42,8 @@ export default function App() {
<Route element={<AdminLayout />}>
<Route index element={<DashboardPage />} />
<Route path="users" element={<UsersPage />} />
+ <Route path="teams" element={<TeamsPage />} />
+ <Route path="teams/:teamId" element={<TeamDetailPage />} />
<Route path="orders" element={<OrdersPage />} />
<Route path="adjustments" element={<AdjustRecordsPage />} />
<Route path="finance" element={<FinanceListPage />} />
diff --git a/admin/src/api/types/finance.ts b/admin/src/api/types/finance.ts
index a275f0b..49e17dc 100644
--- a/admin/src/api/types/finance.ts
+++ b/admin/src/api/types/finance.ts
@@ -32,6 +32,8 @@ export type AdminLedger = {
};
export type AdminUsageEventBrief = {
+ cost_status?: 'verified' | 'pending' | 'estimated' | null;
+ billing_detail?: { mode: string; price_version: number; operation_id: string; model_id: string; resolution: string; duration?: number; unit_price_yuan: string; delivered: boolean; route: { channel_id: string; channel_name: string; upstream_model: string } } | null;
id: number;
billing_key: string;
capability?: string | null;
diff --git a/admin/src/components/layout/AdminLayout.tsx b/admin/src/components/layout/AdminLayout.tsx
index 8d53fbd..d59bcd9 100644
--- a/admin/src/components/layout/AdminLayout.tsx
+++ b/admin/src/components/layout/AdminLayout.tsx
@@ -90,6 +90,8 @@ const navGroups: NavGroup[] = [
{ to: "/users", label: "用户管理", icon: Users },
+ { to: "/teams", label: "团队管理", icon: Users, matchPrefix: true },
+
{ to: "/orders", label: "订单流水", icon: Receipt },
{ to: "/adjustments", label: "手动调账", icon: Scale },
@@ -154,6 +156,8 @@ const titles: Record<string, string> = {
"/users": "用户管理",
+ "/teams": "团队管理",
+
"/orders": "订单流水",
"/adjustments": "手动调账",
@@ -184,6 +188,8 @@ const titles: Record<string, string> = {
function resolveTitle(pathname: string): string {
+ if (pathname.startsWith("/teams/")) return "团队详情";
+
if (pathname.startsWith("/drama-projects/")) return "漫剧项目详情";
if (pathname.startsWith("/drama-assets/")) return "资产详情";
diff --git a/admin/src/components/settings/PaymentSettingsPanel.tsx b/admin/src/components/settings/PaymentSettingsPanel.tsx
index 541ad7b..0643ac0 100644
--- a/admin/src/components/settings/PaymentSettingsPanel.tsx
+++ b/admin/src/components/settings/PaymentSettingsPanel.tsx
@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { useAdminModelSettings } from "@/hooks/useAdminModelSettings";
import { api } from "@/api/client";
+import { MediaPriceSettings } from "./MediaPriceSettings";
// 易支付与 Token 计费配置
export function PaymentSettingsPanel() {
@@ -150,6 +151,7 @@ export function PaymentSettingsPanel() {
return (
<SettingsTabShell onSave={() => void handleSave()} saving={saving}>
+ <MediaPriceSettings />
<SettingsStatusBar
title="支付就绪状态"
items={[
@@ -236,7 +238,7 @@ export function PaymentSettingsPanel() {
<SettingsPanel
className="settings-panel--compact"
title="2. Token 计费"
- description="按 TokenFree 官方成本 1:1 扣费,不再加价"
+ description="图视频发布价格后按站内价格收费;上游费用单独记录为成本。LLM、TTS 沿用现有规则。"
>
<div className="settings-toggle-row">
<div>
diff --git a/admin/src/index.css b/admin/src/index.css
index 267abee..14aab6e 100644
--- a/admin/src/index.css
+++ b/admin/src/index.css
@@ -288,7 +288,9 @@
}
/* ---- Admin console shell ---- */
-.admin-app {
+/* 弹窗通过 Portal 挂载,需在自身继承同一套后台主题变量。 */
+.admin-app,
+.admin-modal {
--admin-bg: #e9eef5;
--admin-bg-subtle: #dfe6f0;
--admin-card: #ffffff;
@@ -312,6 +314,9 @@
--admin-sidebar-w: 232px;
--admin-radius: 12px;
--admin-shadow: 0 1px 3px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05);
+}
+
+.admin-app {
display: flex;
min-height: 100vh;
background:
diff --git a/backend/.env.example b/backend/.env.example
index 00f5884..ef64860 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -1,6 +1,12 @@
SECRET_KEY=dev-secret-change-me
# 本地联调若连接共享测试库,请设为 false,由测试服务器统一执行后台任务。
TASK_RUNTIME_ENABLED=true
+# 三个独立队列的全站并发上限;未配置时沿用 TASK_RUNTIME_MAX_CONCURRENCY(每队列默认 4)。
+TASK_QUEUE_TEXT_CONCURRENCY=4
+TASK_QUEUE_IMAGE_CONCURRENCY=4
+TASK_QUEUE_VIDEO_CONCURRENCY=4
+# 团队跨队列共用的生成槽位上限,同时受全站和个人上限限制。
+TASK_TEAM_MAX_CONCURRENCY=4
# DEBUG=true 时应用日志更详细;SQL_ECHO=true 才打印原始 SQL(默认关,避免刷屏)
# DEBUG=true
# SQL_ECHO=false
@@ -23,6 +29,9 @@ PUBLIC_BASE_URL=http://127.0.0.1:8000
ARK_MOCK=false
+# Local media simulation only. Text LLM requests remain real; no provider media calls.
+# Requests: .tmp/local-ai-requests.jsonl. Prepare fixtures with scripts/prepare_mock_media.py.
+LOCAL_MEDIA_MOCK=false
# 开源版统一走 TokenFree New API(https://www.tokenfree.com/v1)。
# 请在管理后台「系统设置 → 模型」填写 API Key,拉取并选择模型;此处仅作首次导入。
OPENAI_API_KEY=replace-me
diff --git a/backend/.env.test.example b/backend/.env.test.example
index 4faeeb1..9e1b38d 100644
--- a/backend/.env.test.example
+++ b/backend/.env.test.example
@@ -10,6 +10,7 @@ REDIS_URL=redis://127.0.0.1:16379/15
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173,http://localhost:5174,http://127.0.0.1:5174
PUBLIC_BASE_URL=http://127.0.0.1:8000
ARK_MOCK=true
+LOCAL_MEDIA_MOCK=false
ARK_API_KEY=
OPENAI_API_KEY=
OPENAI_BASE_URL=http://127.0.0.1:9/v1
diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py
index 1c2d78e..baabd9b 100644
--- a/backend/app/api/admin/__init__.py
+++ b/backend/app/api/admin/__init__.py
@@ -14,6 +14,7 @@ from app.api.admin import (
queues,
settings,
tasks,
+ teams,
templates,
usage,
users,
@@ -27,6 +28,7 @@ router.include_router(queues.router)
router.include_router(tasks.router)
router.include_router(settings.router)
router.include_router(users.router)
+router.include_router(teams.router)
router.include_router(orders.router)
router.include_router(ledger.router)
router.include_router(usage.router)
diff --git a/backend/app/api/admin/settings.py b/backend/app/api/admin/settings.py
index 7959a11..7c2737f 100644
--- a/backend/app/api/admin/settings.py
+++ b/backend/app/api/admin/settings.py
@@ -28,6 +28,43 @@ router = APIRouter()
logger = logging.getLogger(__name__)
+class MediaPricePublishBody(BaseModel):
+ prices: dict[str, dict[str, str]]
+ expected_version: int | None = Field(default=None, ge=1)
+
+
+class MediaPriceActivationBody(BaseModel):
+ enabled: bool
+ expected_version: int = Field(ge=1)
+
+
[email protected]("/settings/billing/media-prices/activation")
+async def activate_media_prices(body: MediaPriceActivationBody, _admin: User = Depends(get_current_admin), db: AsyncSession = Depends(get_db)):
+ from app.services.media_models.prices import set_pricing_enabled
+ await set_pricing_enabled(db, enabled=body.enabled, expected_version=body.expected_version)
+ await db.commit()
+ return {"enabled": body.enabled}
+
+
[email protected]("/settings/billing/media-prices")
+async def get_media_prices(_admin: User = Depends(get_current_admin), db: AsyncSession = Depends(get_db)):
+ from app.services.media_models import strategies
+ from app.services.media_models.prices import active_book, initial_draft
+ book = await active_book(db, include_disabled=True)
+ return {"active_version": book["version"] if book else None,
+ "enabled": book["enabled"] if book else False,
+ "prices": book["prices"] if book else initial_draft(),
+ "strategies": [{"id": strategy.model_id, **strategy.describe()} for strategy in strategies()]}
+
+
[email protected]("/settings/billing/media-prices")
+async def publish_media_prices(body: MediaPricePublishBody, admin: User = Depends(get_current_admin), db: AsyncSession = Depends(get_db)):
+ from app.services.media_models.prices import publish_book
+ result = await publish_book(db, prices=body.prices, expected_version=body.expected_version, user_id=admin.id)
+ await db.commit()
+ return result
+
+
class AdminUpstreamModelsRequest(BaseModel):
"""按渠道凭证拉取上游 /models 目录。"""
diff --git a/backend/app/api/admin/users.py b/backend/app/api/admin/users.py
index 8605c75..1340515 100644
--- a/backend/app/api/admin/users.py
+++ b/backend/app/api/admin/users.py
@@ -61,7 +61,7 @@ async def patch_user(
db: AsyncSession = Depends(get_db),
) -> AdminUserOut:
# Update plan / role; balance changes write WalletLedger
- user = await db.get(User, user_id)
+ user = (await db.execute(select(User).where(User.id == user_id).with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="用户不存在")
diff --git a/backend/app/api/billing.py b/backend/app/api/billing.py
index 0a291b9..e24467e 100644
--- a/backend/app/api/billing.py
+++ b/backend/app/api/billing.py
@@ -6,13 +6,14 @@ import logging
import time
import uuid
from datetime import datetime, timezone
+from decimal import Decimal, InvalidOperation
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import PlainTextResponse
-from pydantic import BaseModel
-from sqlalchemy import func, select
+from pydantic import BaseModel, Field
+from sqlalchemy import or_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import get_settings
@@ -32,6 +33,27 @@ router = APIRouter(prefix="/billing", tags=["billing"])
settings = get_settings()
+class MediaQuoteItem(BaseModel):
+ model_id: str = Field(min_length=1, max_length=128)
+ params: dict = Field(default_factory=dict)
+
+
+class MediaQuoteBody(BaseModel):
+ items: list[MediaQuoteItem] = Field(min_length=1, max_length=200)
+ price_version: int | None = Field(default=None, ge=1)
+
+
[email protected]("/media/quote")
+async def quote_media(body: MediaQuoteBody, _user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
+ from app.services.media_models.prices import active_book, quote_items
+ book = await active_book(db)
+ if not book:
+ raise HTTPException(409, detail="媒体固定价格尚未发布")
+ if body.price_version is not None and body.price_version != book["version"]:
+ raise HTTPException(409, detail="价格已更新,请刷新后重试")
+ return quote_items([item.model_dump() for item in body.items], book)
+
+
class CreateOrderBody(BaseModel):
sku_id: str
pay_type: Literal["alipay", "wxpay"]
@@ -64,12 +86,18 @@ async def billing_preflight(
domain: str = Query(..., min_length=1),
task_type: str = Query(..., min_length=1),
count: int = Query(1, ge=1, le=500),
+ team_id: int | None = Query(None, ge=1),
db: AsyncSession = Depends(get_db),
user: User = Depends(get_current_user),
) -> dict:
"""入队前余额预检:返回单项估算与批量总需求。"""
+ member = None
+ team = None
+ if team_id is not None:
+ from app.services.teams.access import get_team
+ team, member = await get_team(db, team_id, user.id)
if not billing_active(user):
- return {
+ result = {
"ok": True,
"billing_enabled": False,
"balance_fen": int(user.balance_fen or 0),
@@ -78,17 +106,24 @@ async def billing_preflight(
"requested_total_fen": 0,
"required_total_fen": 0,
}
+ if team_id is not None:
+ if team.owner_user_id == user.id:
+ result["balance_fen"] = int(user.balance_fen or 0)
+ else:
+ result.pop("balance_fen", None)
+ return result
probe = TaskRun(
domain=domain.strip(),
task_type=task_type.strip(),
requested_by=user.id,
+ team_id=team_id,
payload={},
)
try:
summary = await ensure_balance_for_task_batch(db, user, probe, count)
except ValueError as exc:
raise http_exception_for_value_error(exc) from exc
- return {
+ result = {
"ok": True,
"billing_enabled": True,
"balance_fen": summary["balance_fen"],
@@ -105,6 +140,10 @@ async def billing_preflight(
"domain": domain.strip(),
"task_type": task_type.strip(),
}
+ if team is not None and team.owner_user_id != user.id:
+ result.pop("balance_fen", None)
+ result.pop("balance_yuan", None)
+ return result
def _client_ip(request: Request) -> str:
@@ -195,7 +234,7 @@ async def usage_summary(
func.coalesce(func.sum(UsageEvent.cost_fen), 0),
func.count(UsageEvent.id),
).where(
- UsageEvent.user_id == user.id,
+ or_((UsageEvent.user_id == user.id) & UsageEvent.team_id.is_(None), UsageEvent.billing_payer_user_id == user.id),
UsageEvent.created_at >= month_start,
)
)
@@ -265,14 +304,14 @@ async def usage_events(
"""分页返回当前用户的按次扣费记录(新→旧)。"""
from app.models_drama import DramaProject
- count_stmt = select(func.count()).select_from(UsageEvent).where(UsageEvent.user_id == user.id)
+ count_stmt = select(func.count()).select_from(UsageEvent).where(or_((UsageEvent.user_id == user.id) & UsageEvent.team_id.is_(None), UsageEvent.billing_payer_user_id == user.id))
total = int((await db.execute(count_stmt)).scalar_one() or 0)
stmt = (
select(UsageEvent, Project.title, DramaProject.title)
.outerjoin(Project, UsageEvent.project_id == Project.id)
.outerjoin(DramaProject, UsageEvent.drama_project_id == DramaProject.id)
- .where(UsageEvent.user_id == user.id)
+ .where(or_((UsageEvent.user_id == user.id) & UsageEvent.team_id.is_(None), UsageEvent.billing_payer_user_id == user.id))
.order_by(UsageEvent.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
@@ -322,7 +361,7 @@ async def list_orders(
await billing.close_expired_pending_orders(db, user_id=user.id)
result = await db.execute(
select(Order)
- .where(Order.user_id == user.id)
+ .where(Order.user_id == user.id, Order.team_id.is_(None))
.order_by(Order.created_at.desc())
.limit(limit)
)
@@ -356,7 +395,7 @@ async def get_order(
await billing.close_expired_pending_orders(db, user_id=user.id, out_trade_no=out_trade_no)
result = await db.execute(select(Order).where(Order.out_trade_no == out_trade_no))
order = result.scalar_one_or_none()
- if not order or order.user_id != user.id:
+ if not order or order.user_id != user.id or order.team_id is not None:
raise HTTPException(status_code=404, detail="订单不存在")
return {
"out_trade_no": order.out_trade_no,
@@ -377,7 +416,7 @@ async def close_order(
"""用户主动取消支付时关闭待支付订单(过期订单由系统自动关闭)。"""
result = await db.execute(select(Order).where(Order.out_trade_no == out_trade_no))
order = result.scalar_one_or_none()
- if not order or order.user_id != user.id:
+ if not order or order.user_id != user.id or order.team_id is not None:
raise HTTPException(status_code=404, detail="订单不存在")
if order.status == "paid":
raise HTTPException(status_code=400, detail="已支付订单无法关闭")
@@ -420,7 +459,7 @@ async def epay_notify(request: Request, db: AsyncSession = Depends(get_db)) -> P
# 行锁串行化同一订单的并发回调:第二个回调在锁释放后读到 paid 即幂等返回,
# 避免重复入账(易支付会对同一笔支付重发多次 notify)。
result = await db.execute(
- select(Order).where(Order.out_trade_no == out_trade_no).with_for_update()
+ select(Order).where(Order.out_trade_no == out_trade_no).with_for_update().execution_options(populate_existing=True)
)
order = result.scalar_one_or_none()
if not order:
@@ -429,9 +468,12 @@ async def epay_notify(request: Request, db: AsyncSession = Depends(get_db)) -> P
# amount check
try:
- paid_fen = int(round(float(money) * 100))
- except ValueError:
- paid_fen = order.amount_fen
+ amount = Decimal(money)
+ if not amount.is_finite() or amount <= 0 or amount * 100 != (amount * 100).to_integral_value():
+ return PlainTextResponse("fail", status_code=400)
+ paid_fen = int(amount * 100)
+ except (InvalidOperation, ValueError):
+ return PlainTextResponse("fail", status_code=400)
if paid_fen != int(order.amount_fen):
logger.error(
"epay amount mismatch order=%s expect=%s got=%s",
@@ -451,13 +493,10 @@ async def epay_notify(request: Request, db: AsyncSession = Depends(get_db)) -> P
order.status = "paid"
order.trade_no = trade_no or None
order.paid_at = datetime.now(timezone.utc)
+ # 历史团队订单回款到原下单人的个人账户,转让不改变收款归属。
await billing.credit_topup(
- db,
- user,
- int(order.credit_fen),
- ref_type="order",
- ref_id=order.out_trade_no,
- note=f"epay:{order.pay_type}",
+ db, user, int(order.credit_fen), ref_type="order", ref_id=order.out_trade_no,
+ note=f"epay:{order.pay_type}" + (f" legacy_team:{order.team_id}" if order.team_id else ""),
)
await db.commit()
logger.info("epay paid order=%s user=%s credit=%s", out_trade_no, user.id, order.credit_fen)
diff --git a/backend/app/api/projects.py b/backend/app/api/projects.py
index 49a6a3b..c2cd9cb 100644
--- a/backend/app/api/projects.py
+++ b/backend/app/api/projects.py
@@ -82,11 +82,12 @@ async def get_voices() -> list[dict]:
@router.get("/media-models")
-async def get_media_models() -> dict:
+async def get_media_models(db: AsyncSession = Depends(get_db)) -> dict:
"""科普前台可选图/视频模型目录(TokenFree 已勾选模型)。"""
from app.services.media_catalog import catalog_payload
- return catalog_payload()
+ from app.services.media_models.catalog import priced_catalog
+ return await priced_catalog(db, catalog_payload())
@router.post("/voices/preview", response_model=VoicePreviewOut)
@@ -270,6 +271,8 @@ async def create_project(
extra_prompt=(body.extra_prompt or "").strip(),
image_model=(body.image_model or "").strip(),
video_model=(body.video_model or "").strip(),
+ image_resolution=body.image_resolution.strip().upper(),
+ video_resolution=body.video_resolution.strip().lower(),
ref_image_url=body.ref_image_url,
status=ProjectStatus.DRAFT,
)
@@ -428,7 +431,7 @@ async def update_project(
url = str(data["cover_url"]).strip()
if not (url.startswith("/static/") or url.startswith("http://") or url.startswith("https://")):
raise HTTPException(status_code=400, detail="无效封面地址")
- for key in ("style_prompt", "character_prompt", "extra_prompt", "image_model", "video_model"):
+ for key in ("style_prompt", "character_prompt", "extra_prompt", "image_model", "video_model", "image_resolution", "video_resolution"):
if key in data:
data[key] = str(data[key] or "").strip()
if "image_model" in data and data["image_model"]:
diff --git a/backend/app/api/v1/generation.py b/backend/app/api/v1/generation.py
index 50f14ed..8a391c6 100644
--- a/backend/app/api/v1/generation.py
+++ b/backend/app/api/v1/generation.py
@@ -24,7 +24,7 @@ from app.services.billing import (
settle_deferred_video_poll,
)
from app.services.drama.billing_util import record_seedream_image_usage
-from app.services.studio_tools import poll_video_task, ratio_to_size
+from app.services.studio_tools import poll_video_task
from app.services import storage
router = APIRouter(prefix="/v1", tags=["public-api"])
@@ -51,56 +51,57 @@ async def generate_image(
) -> V1GenerationOut:
"""文生图 / 图生图(Seedream)。"""
- async def _exec() -> str:
+ 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}。在保持主体可识别的前提下适度改变风格"
- size = ratio_to_size(body.ratio)
- try:
+ urls = []
+ for _ in range(body.count):
result = await ark.gen_image(
prompt,
body.negative,
refs,
project_id=0,
shot_no=user.id,
- size=size,
+ size=body.resolution,
+ model=body.model,
+ aspect_ratio=body.ratio,
)
- except Exception as exc: # noqa: BLE001
- raise HTTPException(status_code=502, detail=str(exc)[:400]) from exc
-
- await record_seedream_image_usage(
- db,
- user_id=user.id,
- model=get_settings().model_image,
- domain="api",
- image_result=result,
- extra_raw={"source": "api_v1_image"},
- )
- url = result.local_url or result.remote_url or ""
- if url:
+ url = result.local_url or result.remote_url or ""
+ if not url:
+ raise RuntimeError("生图结果为空")
url = storage.republish_url(url, sync=True) or url
- return 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, url = await run_billed_ephemeral(
+ task, urls = await run_billed_ephemeral(
db,
user,
domain="api",
task_type="v1_image",
executor=_exec,
- payload={"prompt_len": len(body.prompt or "")},
+ payload=body.model_dump(exclude_none=True),
commit=True,
)
except ValueError as exc:
- raise HTTPException(status_code=402, detail=str(exc)) from 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=[url] if url else [],
+ urls=urls,
task_id=str(task.id),
)
@@ -122,6 +123,8 @@ async def generate_video(
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
@@ -135,11 +138,12 @@ async def generate_video(
domain="api",
task_type="v1_video",
executor=_exec,
- payload={"duration": body.duration},
+ payload=body.model_dump(exclude_none=True),
commit=True,
)
except ValueError as exc:
- raise HTTPException(status_code=402, detail=str(exc)) from 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",
@@ -161,7 +165,7 @@ async def forward_seedance(
raise HTTPException(status_code=400, detail="content 不能为空")
settings = get_settings()
payload: dict = {
- "model": settings.model_video,
+ "model": body.model or settings.model_video,
"content": body.content,
"resolution": body.resolution,
"watermark": body.watermark,
@@ -189,11 +193,12 @@ async def forward_seedance(
domain="api",
task_type="v1_seedance",
executor=_exec,
- payload={"duration": body.duration},
+ payload={**body.model_dump(exclude_none=True), "prepared": {"seedance_body": payload}},
commit=True,
)
except ValueError as exc:
- raise HTTPException(status_code=402, detail=str(exc)) from 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=[])
@@ -218,7 +223,10 @@ async def get_task(
).scalar_one_or_none()
if owned is None:
raise HTTPException(status_code=404, detail="任务不存在")
- data = await poll_video_task(user, tid)
+ 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)
await settle_deferred_video_poll(
db,
user,
diff --git a/backend/app/config.py b/backend/app/config.py
index 1c75a32..c52b62d 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -72,12 +72,20 @@ class Settings(BaseSettings):
kepu_seedance_sfx_audio: bool = True
ark_mock: bool = False
+ # 本地媒体联调:文字仍请求真实 LLM,图片/视频/语音仅留痕并返回默认素材。
+ local_media_mock: bool = False
# 本地连接共享测试库时关闭,避免本机和服务器同时消费、恢复同一队列。
task_runtime_enabled: bool = True
- # 内置任务平台的进程内并发上限(全站 Worker 槽位)。
+ # 未单独配置队列时,每个队列使用的并发上限。
task_runtime_max_concurrency: int = 4
- # 单用户同时进行中的 Worker 槽位(不含 awaiting_poll 注册项)。
+ # 三个独立队列;None 沿用 task_runtime_max_concurrency 作为各队列容量。
+ task_queue_text_concurrency: int | None = None
+ task_queue_image_concurrency: int | None = None
+ task_queue_video_concurrency: int | None = None
+ # 单用户在每个队列的并发上限;视频包含等待上游完成的任务。
task_user_max_concurrency: int = 4
+ # 团队共用生成槽位,不取代单用户与全站上限。
+ task_team_max_concurrency: int = 4
# Selector 每轮并发非阻塞查询上游的上限(类似 NIO select 就绪 channel 批处理)。
task_poll_max_concurrency: int = 20
# 孤儿恢复:leased/running 超过该秒数无更新、且本进程无执行协程时重排队。
diff --git a/backend/app/database.py b/backend/app/database.py
index 6233047..abe41e4 100644
--- a/backend/app/database.py
+++ b/backend/app/database.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from collections.abc import AsyncGenerator
-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.config import get_settings
@@ -50,15 +50,18 @@ async def get_db() -> AsyncGenerator[AsyncSession, None]:
yield session
-async def init_db() -> None:
+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_drama # noqa: F401
from app import models_api # noqa: F401
from app import models_settings # noqa: F401
from app import models_tasks # noqa: F401
+ from app import models_teams, models_team_billing, models_team_locks # noqa: F401
- async with engine.begin() as conn:
+ target_engine = engine_override if engine_override is not None else engine
+ async with target_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
diff --git a/backend/app/main.py b/backend/app/main.py
index ef7d992..ee7d181 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -6,8 +6,10 @@ from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
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 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
from app.api.admin import router as admin_router
@@ -27,6 +29,29 @@ logger = logging.getLogger("app.http")
app = FastAPI(title=settings.app_name, version="0.2.0")
+
+async def media_price_context(request: Request, call_next):
+ from app.services.media_models.prices import expected_price_version
+ from fastapi.responses import JSONResponse
+ raw = request.headers.get("X-Media-Price-Version")
+ if raw is not None and (not raw.isdigit() or len(raw) > 18):
+ return JSONResponse(status_code=422, content={"detail": "无效的媒体价格版本"})
+ token = expected_price_version.set(int(raw) if raw is not None else None)
+ try:
+ return await call_next(request)
+ finally:
+ expected_price_version.reset(token)
+
+
+from app.services.media_models import MediaValidationError
+
+
[email protected]_handler(MediaValidationError)
+async def media_validation_error(_request, exc):
+ from fastapi.responses import JSONResponse
+ return JSONResponse(status_code=422, content={"detail": [{"loc": ["body", exc.field], "msg": str(exc), "type": "media_parameter"}]})
+
origins = [o.strip() for o in settings.cors_origins.split(",") if o.strip()]
# Allow LAN devices (phone/tablet) hitting Vite on private IPs
_LAN_ORIGIN_RE = (
@@ -92,6 +117,12 @@ 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")
+app.include_router(team_billing.router, prefix="/api")
+app.include_router(team_content.router, prefix="/api")
+app.include_router(team_content.personal_router, prefix="/api")
+app.include_router(team_edit_locks.router, prefix="/api")
app.include_router(admin_router, prefix="/api")
@@ -150,9 +181,15 @@ async def _pg_columns(conn, table: str) -> set[str]:
return {row[0] for row in result.fetchall()}
-async def _apply_schema_patches() -> None:
+async def _apply_schema_patches(engine_override: AsyncEngine | None = None) -> None:
"""Lightweight additive migrations(仅 PostgreSQL)。"""
- async with engine.begin() as conn:
+ target_engine = engine_override if engine_override is not None else engine
+ async with target_engine.begin() as conn:
+ from app.team_schema import apply_team_schema_patches
+
+ await apply_team_schema_patches(conn)
+ from app.media_schema import apply_media_schema_patches
+ await apply_media_schema_patches(conn)
scols = await _pg_columns(conn, "shots")
if "segment_script" not in scols:
await conn.execute(text("ALTER TABLE shots ADD COLUMN segment_script TEXT DEFAULT ''"))
@@ -220,6 +257,20 @@ async def _apply_schema_patches() -> None:
# Task platform additive columns
trcols = await _pg_columns(conn, "task_runs")
+ if "queue_type" not in trcols:
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN queue_type VARCHAR(16) NOT NULL DEFAULT 'text'"))
+ await conn.execute(text("""
+ UPDATE task_runs SET queue_type = CASE
+ WHEN task_type = 'project_pipeline' AND payload->>'phase' = 'assets' THEN 'image'
+ WHEN task_type = 'project_pipeline' AND payload->>'phase' IN ('videos', 'compose', 'produce') THEN 'video'
+ WHEN task_type LIKE '%video%' OR task_type IN ('v1_seedance', 'project_compose_only') THEN 'video'
+ WHEN task_type LIKE '%image%' THEN 'image'
+ ELSE 'text' END
+ """))
+ if "provider_name" not in trcols:
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN provider_name VARCHAR(64)"))
+ if "provider_status" not in trcols:
+ await conn.execute(text("ALTER TABLE task_runs ADD COLUMN provider_status VARCHAR(32)"))
if "dedupe_key" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN dedupe_key VARCHAR(128)"))
if "batch_key" not in trcols:
@@ -244,6 +295,7 @@ async def _apply_schema_patches() -> None:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_refunded_fen INTEGER DEFAULT 0"))
if "billing_status" not in trcols:
await conn.execute(text("ALTER TABLE task_runs ADD COLUMN billing_status VARCHAR(16) DEFAULT 'none'"))
+ await conn.execute(text("CREATE INDEX IF NOT EXISTS ix_task_runs_queue_due ON task_runs (queue_type, status, next_action_at, priority, id)"))
# Drop leftover worker-era columns that block the new task platform.
legacy_task_run_cols = (
diff --git a/backend/app/models.py b/backend/app/models.py
index ff071be..0f6dc11 100644
--- a/backend/app/models.py
+++ b/backend/app/models.py
@@ -129,6 +129,8 @@ class Project(Base):
# 科普图/视频模型;空则走后台 TokenFree 默认
image_model: Mapped[str] = mapped_column(String(64), default="")
video_model: Mapped[str] = mapped_column(String(64), default="")
+ image_resolution: Mapped[str] = mapped_column(String(16), default="")
+ video_resolution: Mapped[str] = mapped_column(String(16), default="")
ref_image_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(
@@ -210,6 +212,8 @@ class UsageEvent(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
+ billing_payer_user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True, index=True)
+ team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id"), nullable=True, index=True)
project_id: Mapped[int | None] = mapped_column(
ForeignKey("projects.id", ondelete="SET NULL"), nullable=True, index=True
)
@@ -230,6 +234,9 @@ class UsageEvent(Base):
estimated: Mapped[bool] = mapped_column(Boolean, default=False)
settled: Mapped[bool] = mapped_column(Boolean, default=False)
raw_usage_json: Mapped[str | None] = mapped_column(Text, nullable=True)
+ billing_detail: Mapped[dict | None] = mapped_column(JSON, nullable=True)
+ delivery_key: Mapped[str | None] = mapped_column(String(192), nullable=True, unique=True)
+ cost_status: Mapped[str | None] = mapped_column(String(16), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
@@ -268,6 +275,7 @@ class Order(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True)
out_trade_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True)
+ team_id: Mapped[int | None] = mapped_column(ForeignKey("teams.id"), nullable=True, index=True)
sku_id: Mapped[str] = mapped_column(String(64))
amount_fen: Mapped[int] = mapped_column(Integer)
credit_fen: Mapped[int] = mapped_column(Integer)
diff --git a/backend/app/models_settings.py b/backend/app/models_settings.py
index 0ad5524..d039e8e 100644
--- a/backend/app/models_settings.py
+++ b/backend/app/models_settings.py
@@ -22,6 +22,16 @@ class AppSettings(Base):
)
+class MediaPriceVersion(Base):
+ """Published price books are append-only; the active pointer lives in AppSettings."""
+
+ __tablename__ = "media_price_versions"
+ id: Mapped[int] = mapped_column(Integer, primary_key=True)
+ prices: Mapped[dict] = mapped_column(JSON, nullable=False)
+ created_by: Mapped[int] = mapped_column(Integer, nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+
+
class SystemModelChannelRow(Base):
"""Physical upstream provider channel."""
diff --git a/backend/app/schemas.py b/backend/app/schemas.py
index 7a06dee..d155c98 100644
--- a/backend/app/schemas.py
+++ b/backend/app/schemas.py
@@ -1,12 +1,21 @@
from datetime import datetime
-from typing import Any
+from typing import Annotated, Any
-from pydantic import BaseModel, EmailStr, Field, field_validator
+from pydantic import BaseModel, BeforeValidator, EmailStr, Field, field_validator
from app.schemas_common import PageMeta
from app.schemas_tasks import TaskRunBriefOut
+def _normalize_project_template_id(value: Any) -> Any:
+ """历史项目可能没有模板;响应沿用字符串契约,不改写数据库。"""
+ return "" if value is None else value
+
+
+# 仅用于项目响应,创建和更新请求仍使用各自的模板校验。
+ProjectTemplateIdOut = Annotated[str, BeforeValidator(_normalize_project_template_id)]
+
+
# ---- Auth ----
class RegisterRequest(BaseModel):
email: EmailStr
@@ -131,6 +140,8 @@ class ShotUpdate(BaseModel):
class ProjectCreate(BaseModel):
+ image_resolution: str = Field(default="", max_length=16)
+ video_resolution: str = Field(default="", max_length=16)
template_id: str
title: str = "未命名作品"
source_type: str = Field(default="theme", pattern="^(theme|script)$")
@@ -152,6 +163,8 @@ class ProjectCreate(BaseModel):
class ProjectUpdate(BaseModel):
+ 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)
source_type: str | None = Field(default=None, pattern="^(theme|script)$")
source_text: str | None = Field(default=None, min_length=2, max_length=20000)
@@ -176,8 +189,10 @@ class ProjectUpdate(BaseModel):
class ProjectOut(BaseModel):
+ image_resolution: str = ""
+ video_resolution: str = ""
id: int
- template_id: str
+ template_id: ProjectTemplateIdOut
title: str
source_type: str
source_text: str
@@ -210,7 +225,7 @@ class ProjectOut(BaseModel):
class ProjectListItem(BaseModel):
id: int
title: str
- template_id: str
+ template_id: ProjectTemplateIdOut
status: str
progress: int
cover_url: str | None
@@ -443,6 +458,8 @@ class AdminQueueSummaryOut(BaseModel):
name: str
label: str
pending: int
+ active: int = 0
+ max_concurrency: int = 0
sample: list[AdminQueueTaskOut]
@@ -544,7 +561,7 @@ class AdminProjectOut(BaseModel):
id: int
user_id: int
user_email: str | None = None
- template_id: str
+ template_id: ProjectTemplateIdOut
title: str
status: str
progress: int
diff --git a/backend/app/schemas_api.py b/backend/app/schemas_api.py
index 72017b9..5513da6 100644
--- a/backend/app/schemas_api.py
+++ b/backend/app/schemas_api.py
@@ -22,6 +22,11 @@ class ApiKeyCreatedOut(ApiKeyOut):
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")
@@ -29,17 +34,24 @@ class V1ImageGenerateRequest(BaseModel):
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=15)
+ 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
diff --git a/backend/app/schemas_routing.py b/backend/app/schemas_routing.py
index 31b5dab..87bd29a 100644
--- a/backend/app/schemas_routing.py
+++ b/backend/app/schemas_routing.py
@@ -29,6 +29,7 @@ class LogicalModel(BaseModel):
id: str
name: str = ""
capability: LogicalModelCapability
+ strategy_id: str | None = None
enabled: bool = True
bindings: list[LogicalModelBinding] = Field(default_factory=list)
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 431b7a9..f98cf90 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -58,6 +58,7 @@ from app.services.tokenfree_video import (
is_tokenfree_content_url,
normalize_video_task_status,
prepare_video_create_body,
+ post_video_create,
remap_video_path,
resolve_tokenfree_media_download_url,
tokenfree_video_content_url,
@@ -65,6 +66,10 @@ from app.services.tokenfree_video import (
uses_tokenfree_video,
)
from app.services import storage
+from app.services import local_media_mock
+from app.services.media_models.runtime import (
+ current_snapshot, current_operation, execution_params, operation_for, restore_route, stamp_usage,
+)
from app.services.drama.seedance_i2v_role import resolve_seedance_i2v_image_role
from app.services.ffmpeg_compose import is_near_silent_audio
from app.services.drama.llm import _extract_json
@@ -538,6 +543,8 @@ class ArkGateway:
@property
def mock(self) -> bool:
+ if getattr(self.settings, "local_media_mock", False):
+ return False # Media has its own branches; storyboard/expansion must use real LLM.
return self.settings.ark_mock or not self._ark_api_key()
def _headers(self) -> dict[str, str]:
@@ -556,8 +563,26 @@ class ArkGateway:
# 按逻辑路由解析 ARK 渠道凭证
def _resolve_ark_route(self, capability: str, model_id: str | None) -> ResolvedModelRoute | None:
+ operation = current_operation.get()
+ if current_snapshot.get():
+ if not operation or operation["capability"] != capability:
+ operation = operation_for(capability, model=model_id)
+ if operation:
+ return restore_route(operation["route"])
logical_id = resolve_logical_model_id(capability, model_id)
- return resolve_logical_model(capability, logical_id)
+ route = resolve_logical_model(capability, logical_id)
+ if route is None:
+ from app.services.model_settings import get_routing_snapshot
+ if get_routing_snapshot().channels:
+ raise RuntimeError(f"固定模型 {logical_id} 没有可用渠道,不会自动切换路由")
+ return route
+
+ def _poll_route(self) -> ResolvedModelRoute | None:
+ operation = operation_for("video") if current_snapshot.get() else None
+ if operation:
+ current_operation.set(operation)
+ return restore_route(operation["route"])
+ return None
def _route_headers(self, route: ResolvedModelRoute | None = None) -> dict[str, str]:
if route and route.api_key:
@@ -589,7 +614,10 @@ class ArkGateway:
"""TokenFree 上把 Seedance 方舟 body 包装成 POST /v1/videos 请求体。"""
base = (route.base_url if route and route.base_url else self.settings.ark_base_url) or ""
channel_id = (route.channel_id if route else "") or ""
- return prepare_video_create_body(body, base_url=base, channel_id=channel_id)
+ request = prepare_video_create_body(body, base_url=base, channel_id=channel_id)
+ if route is not None:
+ request["model"] = route.upstream_model
+ return request
def _finalize_video_result(self, result: TaskResult, task_id: str) -> TaskResult:
"""TokenFree 成功但无公网 URL 时,改用 GET /videos/{id}/content。"""
@@ -597,9 +625,15 @@ class ArkGateway:
if result.status == "succeeded" and not result.url and uses_tokenfree_video(
base_url=self.settings.ark_base_url
):
- result.url = tokenfree_video_content_url(self.settings.ark_base_url, task_id)
+ route = self._poll_route()
+ result.url = tokenfree_video_content_url(route.base_url if route else self.settings.ark_base_url, task_id)
return result
+ async def _request_media(self, client: Any, method: str, endpoint: str, **kwargs: Any) -> Any:
+ if getattr(self.settings, "local_media_mock", False):
+ return await local_media_mock.simulate_http_request(method, endpoint, **kwargs)
+ return await observed_request(client, method, endpoint, **kwargs)
+
async def download_result_media(self, url: str, dest: Path) -> None:
"""下载生成媒体;每次重试都重新解析 TokenFree 直链,避免沿用已断开的连接。"""
from app.services.storage import is_retryable_download_error
@@ -611,7 +645,8 @@ class ArkGateway:
timeout: float | httpx.Timeout = 300.0
download_url = source
if is_tokenfree_content_url(download_url) or is_tokenfree_image_url(download_url):
- api_key = self._ark_api_key()
+ route = self._poll_route() if is_tokenfree_content_url(download_url) else None
+ api_key = route.api_key if route else self._ark_api_key()
headers = {"Authorization": f"Bearer {api_key}"}
timeout = httpx.Timeout(connect=30.0, read=600.0, write=60.0, pool=30.0)
if is_tokenfree_content_url(download_url):
@@ -982,44 +1017,18 @@ class ArkGateway:
style_ref_urls: list[str] | None = None,
) -> ImageResult:
"""单次 Seedream 请求并落盘(文件名含 uuid,避免重生成覆盖)。"""
- route = self._resolve_ark_route("image", model)
- upstream_model = route.upstream_model if route else ((model or "").strip() or self.settings.model_image)
- from app.services.drama.seedream_options import (
- clamp_seedream_pixel_size,
- is_seedream_pro_model,
- )
-
- resolved_size = size or self.settings.ark_image_size
- if is_seedream_pro_model(upstream_model):
- # Pro:3K/4K 档位非法;超大 WxH 等比钳到 4624220
- tier = str(resolved_size or "").strip().upper()
- if tier in {"3K", "4K"}:
- resolved_size = "2K"
- else:
- resolved_size = clamp_seedream_pixel_size(str(resolved_size))
- from app.services.style_lock import split_seedream_subject_style_refs
-
- subject_refs, style_refs = split_seedream_subject_style_refs(ref_urls, style_ref_urls)
- # TokenFree 按逻辑路由解析出的上游模型原样发送,不硬改模型名
- chosen = (upstream_model or "").strip()
- if "gpt-image" in chosen.lower():
- from app.services.tokenfree_image import gpt_image_caps_at_2k
-
- # GPT Image 2 只吃 1K/2K;2.5 保留 4K。画幅靠 aspect_ratio 自然语言约束。
- raw_size = str(resolved_size or "").strip()
- upper = raw_size.upper()
- if gpt_image_caps_at_2k(chosen):
- if upper in {"3K", "4K"}:
- resolved_size = "2K"
- elif "x" in raw_size.lower() and str(aspect_ratio or "").strip():
- try:
- w_s, _, h_s = raw_size.lower().partition("x")
- area = int(w_s) * int(h_s)
- resolved_size = "2K" if area >= 1500 * 1500 else "1K"
- except ValueError:
- resolved_size = "2K"
- elif upper in {"3K", "4K"} or "x" in raw_size.lower():
- resolved_size = raw_size
+ strategy, normalized, pinned_route = execution_params("image", {
+ "prompt": full_prompt, "size": size or self.settings.ark_image_size,
+ "aspect_ratio": aspect_ratio or "auto", "ref_urls": ref_urls or [],
+ "style_ref_urls": style_ref_urls or [],
+ }, shot_no=shot_no, model=model)
+ route = pinned_route or self._resolve_ark_route("image", model)
+ upstream_model = route.upstream_model if route else strategy.model_id
+ request = strategy.build_provider_request(normalized, {"upstream_model": upstream_model})
+ resolved_size = request["size"]
+ subject_refs, style_refs = request["ref_urls"], request["style_ref_urls"]
+ chosen = upstream_model
+ aspect_ratio = normalized["aspect_ratio"]
from app.services.tokenfree_image import (
build_tokenfree_openai_image_body,
is_gpt_image_25,
@@ -1036,6 +1045,7 @@ class ArkGateway:
ref_urls=subject_refs,
style_ref_urls=style_refs,
)
+ body["resolution"] = normalized["resolution"]
else:
path = "/responses"
body = build_tokenfree_image_body(
@@ -1051,7 +1061,7 @@ class ArkGateway:
async with httpx.AsyncClient(timeout=_upstream_timeout(IMAGE_GEN_READ_SEC)) as client:
async def _post():
# 单次上游 POST,限流重试由外层包住
- return await observed_request(client, "POST",
+ return await self._request_media(client, "POST",
self._route_url(path, route),
headers=self._route_headers(route),
json=body,
@@ -1073,6 +1083,9 @@ class ArkGateway:
except httpx.TimeoutException as exc:
reraise_upstream_timeout(exc, kind="生图", read_sec=IMAGE_GEN_READ_SEC)
+ if getattr(self.settings, "local_media_mock", False):
+ return ImageResult(local_url=local_media_mock.media_url("default.jpg"), raw_usage={"simulated": True}, upstream_cost_fen=0)
+
raise_tokenfree_image_if_failed(data)
usage_parsed = parse_usage_dict(data)
@@ -1098,7 +1111,7 @@ class ArkGateway:
dest = dest_dir / name
dl_headers = None
if is_tokenfree_image_url(remote) or is_tokenfree_content_url(remote):
- dl_headers = {"Authorization": f"Bearer {self._ark_api_key()}"}
+ dl_headers = self._route_headers(route)
await storage.download_to(remote, dest, headers=dl_headers)
merged_usage = dict(raw_usage or {})
if resolved_size:
@@ -1109,7 +1122,7 @@ class ArkGateway:
total_tokens=int(usage_parsed.get("total_tokens") or 0),
prompt_tokens=int(usage_parsed.get("prompt_tokens") or 0),
completion_tokens=int(usage_parsed.get("completion_tokens") or 0),
- raw_usage=merged_usage or None,
+ raw_usage=stamp_usage(merged_usage, delivery=str(dest)),
upstream_cost_fen=upstream_cost_fen,
)
@@ -1277,11 +1290,22 @@ class ArkGateway:
character_consistency: bool = True,
resolution: str = "480p",
ratio: str | None = None,
- prompt_as_json: bool = True,
+ prompt_as_json: bool = False,
return_last_frame: bool = True,
generate_audio: bool = False,
extra_image_urls: list[str] | None = None,
+ model: str | None = None,
) -> str:
+ strategy, normalized, pinned_route = execution_params("video", {
+ "duration": duration, "resolution": resolution, "aspect_ratio": ratio or "9:16",
+ "generate_audio": generate_audio,
+ "reference_images": [image_url, *(extra_image_urls or [])],
+ }, model=model)
+ duration, resolution, ratio = normalized["duration"], normalized["resolution"], normalized["aspect_ratio"]
+ from app.services.media_models.runtime import existing_provider_task
+ existing = await existing_provider_task()
+ if existing:
+ return existing
if self.mock:
digest = hashlib.md5(f"{image_url}:{prompt}".encode()).hexdigest()[:10]
return f"mock-task-{digest}"
@@ -1292,7 +1316,15 @@ class ArkGateway:
safe_image_url = await ensure_seedance_compatible_image_url(image_url)
# Seedance needs a publicly reachable https image (data URI often rejected / odd errors)
image_ref = await self._resolve_image_ref(safe_image_url, prefer_https=True)
- # Prefer plain timed script for Seedance 2.5; JSON caption kept as fallback
+ route = pinned_route or self._resolve_ark_route("video", model or strategy.model_id)
+ from app.services.tokenfree_pricing import canonicalize_channel_model_id
+
+ video_model = canonicalize_channel_model_id(
+ route.upstream_model if route else self.settings.model_video
+ )
+ # Plain text is the default. Legacy JSON captions are opt-in for Seedance 2.0 only.
+ legacy_caption_model = "seedance" in video_model.lower() and bool(re.search(r"2[._-]0(?:[._-]|$)", video_model.lower()))
+ prompt_as_json = prompt_as_json and legacy_caption_model
plain = (prompt or "").strip() or "画面轻微动态,保持主体外形稳定"
text = plain if not prompt_as_json else self._seedance_prompt_text(prompt)
# If prompt looks like manju-style script, always send plain text
@@ -1310,8 +1342,8 @@ class ArkGateway:
try:
safe_extra = await ensure_seedance_compatible_image_url(text_url)
extra_refs.append(await self._resolve_image_ref(safe_extra, prefer_https=True))
- except Exception: # noqa: BLE001
- logger.warning("Seedance extra ref resolve failed url=%s", text_url[:120])
+ except Exception as exc:
+ raise ValueError("reference_images: 参考图无法处理,请修正后重新提交") from exc
if extra_refs:
# 多图只能走 reference_image,不能与 first_frame 混用
image_role = "reference_image"
@@ -1325,7 +1357,7 @@ class ArkGateway:
"role": image_role,
},
]
- for extra in extra_refs[:2]:
+ for extra in extra_refs:
content.append(
{
"type": "image_url",
@@ -1333,16 +1365,10 @@ class ArkGateway:
"role": "reference_image",
}
)
- route = self._resolve_ark_route("video", self.settings.model_video)
- from app.services.tokenfree_pricing import canonicalize_channel_model_id
-
- video_model = canonicalize_channel_model_id(
- route.upstream_model if route else self.settings.model_video
- )
body: dict[str, Any] = {
"model": video_model,
"content": content,
- "duration": self._seedance_duration(duration, model=video_model),
+ "duration": duration,
"resolution": resolution,
"watermark": False,
"generate_audio": bool(generate_audio),
@@ -1363,16 +1389,19 @@ class ArkGateway:
try:
async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_CREATE_READ_SEC)) as client:
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(body, route),
)
+ # 枚举兼容已在提交层尝试一次,不能继续走文案/画幅回退重复发送。
+ if resp.status_code == 400 and '"plugin_usage_invalid"' in resp.text:
+ raise RuntimeError(_format_seedance_create_error(resp.status_code, resp.text))
if resp.status_code >= 400 and prompt_as_json:
# Fallback: plain text prompt
body["content"][0]["text"] = plain
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(body, route),
)
@@ -1386,8 +1415,8 @@ class ArkGateway:
if cg_content is not None:
logger.warning("Seedance i2v text policy hit; retrying with CG style")
body = {**body, "content": cg_content}
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(body, route),
)
@@ -1404,8 +1433,8 @@ class ArkGateway:
and "ratio" in body
):
body.pop("ratio", None)
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(body, route),
)
@@ -1413,8 +1442,8 @@ class ArkGateway:
# 无目标画幅时的兼容回退;有竖屏目标时禁止 adaptive,避免再次出横屏
body["content"][1].pop("role", None)
body["ratio"] = "adaptive"
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(body, route),
)
@@ -1469,6 +1498,16 @@ class ArkGateway:
文案/策略拦截时追加 CG 厚涂提示词重试一次;参考图真人隐私拦截不重试。
"""
+ strategy, normalized, pinned_route = execution_params("video", {
+ **{key: body[key] for key in ("duration", "resolution", "generate_audio", "watermark", "return_last_frame", "content") if key in body},
+ "aspect_ratio": body.get("ratio") or "9:16",
+ }, model=str(body.get("model") or ""))
+ route = pinned_route or self._resolve_ark_route("video", str(body.get("model") or ""))
+ body = {**body, **strategy.build_provider_request(normalized, {"upstream_model": route.upstream_model if route else strategy.model_id})}
+ from app.services.media_models.runtime import existing_provider_task
+ existing = await existing_provider_task()
+ if existing:
+ return existing
if self.mock:
digest = hashlib.md5(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest()[
:10
@@ -1492,11 +1531,6 @@ class ArkGateway:
content_labels=content_labels,
project_id=project_id,
)
- payload["duration"] = self._seedance_duration(
- payload.get("duration", 8),
- model=str(payload.get("model") or ""),
- )
- route = self._resolve_ark_route("video", str(payload.get("model") or ""))
logger.info(
"Seedance multimodal create model=%s duration=%s items=%s",
@@ -1507,8 +1541,8 @@ class ArkGateway:
try:
async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_CREATE_READ_SEC)) as client:
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(payload, route),
)
@@ -1532,8 +1566,8 @@ class ArkGateway:
project_id,
)
payload = {**payload, "content": cg_content}
- resp = await observed_request(client, "POST",
- self._route_url("/contents/generations/tasks", route),
+ resp = await post_video_create(client, "POST",
+ self._route_url("/contents/generations/tasks", route), request_call=self._request_media,
headers=self._route_headers(route),
json=self._video_json(payload, route),
)
@@ -1564,114 +1598,31 @@ class ArkGateway:
content_labels: list[str] | None = None,
on_task_created: Any | None = None,
) -> tuple[str, str | None, TaskResult]:
- """创建 Seedance 多模态任务并等待完成;返回 (本地视频 URL, 可选本地尾帧 URL, 任务结果)。"""
- def _is_audio_download_error(err: Exception) -> bool:
- msg = str(err)
- return "audio_url" in msg and "resource download failed" in msg
-
- def _strip_reference_audio(src: dict[str, Any]) -> dict[str, Any] | None:
- content = src.get("content")
- if not isinstance(content, list):
- return None
- filtered: list[dict[str, Any]] = []
- removed = False
- for item in content:
- if not isinstance(item, dict):
- filtered.append(item)
- continue
- if item.get("type") == "audio_url" and item.get("role") == "reference_audio":
- removed = True
- continue
- if item.get("type") == "text":
- text = str(item.get("text") or "")
- cleaned_lines = [
- line
- for line in text.splitlines()
- if "参考音频" not in line
- and "角色音色" not in line
- and "旁白音色" not in line
- ]
- filtered.append({**item, "text": "\n".join(cleaned_lines).strip()})
- continue
- filtered.append(item)
- if not removed:
- return None
- return {**src, "content": filtered}
-
- last_err: Exception | None = None
- fallback_body = body
- audio_fallback_used = False
-
- def _audio_fallback(exc: Exception, *, accepted: bool) -> bool:
- """仅"参考音频下载失败"允许去掉参考音频重提一次;其他错误一律不重建任务。
-
- 上游接受任务后的重提会产生第二个计费任务,故必须严格白名单,
- 隐私拦截/失败/轮询超时等异常必须立即上抛,避免重复扣费。
- """
- nonlocal fallback_body, audio_fallback_used, last_err
- last_err = exc
- if audio_fallback_used or not _is_audio_download_error(exc):
- return False
- stripped = _strip_reference_audio(fallback_body)
- if not stripped:
- return False
- logger.warning(
- "Seedance reference_audio download failed (%s); retry once without audio refs project=%s shot=%s",
- "after accept" if accepted else "at submit",
- project_id,
- shot_no,
- )
- fallback_body = stripped
- audio_fallback_used = True
- return True
-
- for _attempt in range(max_attempts):
- # 提交阶段失败:除参考音频错误外立即上抛,绝不盲目重新建单
- try:
- task_id = await self.gen_video_seedance_body(
- fallback_body,
- project_id=project_id,
- content_labels=content_labels,
- )
- except Exception as exc: # noqa: BLE001
- if _audio_fallback(exc, accepted=False):
- continue
- raise
- if on_task_created is not None:
- try:
- await on_task_created(task_id)
- except Exception as exc: # noqa: BLE001
- from app.services.storage import RetryableMediaDownloadError
-
- raise RetryableMediaDownloadError(
- f"记录上游任务号失败: {exc}",
- provider_task_id=task_id,
- counts_attempt=False,
- ) from exc
- # 等待阶段失败:隐私/任务失败/超时等立即上抛;仅参考音频下载失败重提一次
+ """Submit once; retries only fetch/download the original provider task."""
+ task_id = await self.gen_video_seedance_body(body, project_id=project_id, content_labels=content_labels)
+ if on_task_created is not None:
try:
- return await self.wait_video_assets(
- task_id, project_id=project_id, shot_no=shot_no
- )
- except Exception as exc: # noqa: BLE001
- if _audio_fallback(exc, accepted=True):
- continue
- # 成片已在上游生成:只标记可重试下载,禁止外层再建一条视频任务
- from app.services.storage import (
- RetryableMediaDownloadError,
- is_retryable_download_error,
- )
-
- if isinstance(exc, RetryableMediaDownloadError):
- if not exc.provider_task_id:
- exc.provider_task_id = task_id
- raise
- if is_retryable_download_error(exc):
- raise RetryableMediaDownloadError(str(exc), provider_task_id=task_id) from exc
+ await on_task_created(task_id)
+ except Exception as exc:
+ from app.services.storage import RetryableMediaDownloadError
+ raise RetryableMediaDownloadError(
+ f"记录上游任务号失败: {exc}", provider_task_id=task_id, counts_attempt=False,
+ ) from exc
+ try:
+ return await self.wait_video_assets(task_id, project_id=project_id, shot_no=shot_no)
+ except Exception as exc:
+ from app.services.storage import RetryableMediaDownloadError, is_retryable_download_error
+ if isinstance(exc, RetryableMediaDownloadError):
+ if not exc.provider_task_id:
+ exc.provider_task_id = task_id
raise
- raise RuntimeError(str(last_err) if last_err else "Seedance multimodal failed")
+ if is_retryable_download_error(exc):
+ raise RetryableMediaDownloadError(str(exc), provider_task_id=task_id) from exc
+ raise
async def poll_task(self, task_id: str) -> TaskResult:
+ if getattr(self.settings, "local_media_mock", False) or task_id.startswith(local_media_mock.VIDEO_PREFIX):
+ return self._local_media_result(task_id)
if self.mock or task_id.startswith("mock-task-"):
return TaskResult(
status="succeeded",
@@ -1684,8 +1635,8 @@ class ArkGateway:
while time.monotonic() < deadline:
try:
resp = await observed_request(client, "GET",
- self._url(f"/contents/generations/tasks/{task_id}"),
- headers=self._headers(),
+ self._route_url(f"/contents/generations/tasks/{task_id}", self._poll_route()),
+ headers=self._route_headers(self._poll_route()),
)
except httpx.HTTPError as exc:
# 单次网络抖动:退避后继续轮询,由 deadline 收敛,不直接判失败
@@ -1733,6 +1684,8 @@ class ArkGateway:
async def fetch_task_once(self, task_id: str) -> TaskResult:
"""单次查询 Seedance 任务,不阻塞等待。"""
+ if getattr(self.settings, "local_media_mock", False) or task_id.startswith(local_media_mock.VIDEO_PREFIX):
+ return self._local_media_result(task_id)
if self.mock or task_id.startswith("mock-task-"):
return TaskResult(
status="succeeded",
@@ -1742,8 +1695,8 @@ class ArkGateway:
try:
async with httpx.AsyncClient(timeout=_upstream_timeout(VIDEO_FETCH_READ_SEC, connect=15.0)) as client:
resp = await observed_request(client, "GET",
- self._url(f"/contents/generations/tasks/{task_id}"),
- headers=self._headers(),
+ self._route_url(f"/contents/generations/tasks/{task_id}", self._poll_route()),
+ headers=self._route_headers(self._poll_route()),
)
except httpx.HTTPError as exc:
# 网络抖动对 poller 是下轮重试、对同步端点是继续转圈,均优于 500/误判失败
@@ -1760,6 +1713,11 @@ class ArkGateway:
return TaskResult(status="failed", error=resp.text[:500], provider_task_id=task_id)
return self._finalize_video_result(_build_task_result_from_payload(resp.json()), task_id)
+ def _local_media_result(self, task_id: str) -> TaskResult:
+ return TaskResult(status="succeeded", url=local_media_mock.media_url("default.mp4"),
+ last_frame_url=local_media_mock.media_url("default.jpg"),
+ provider_task_id=task_id, raw_usage={"simulated": True}, upstream_cost_fen=0)
+
async def save_video_assets_from_result(
self,
result: TaskResult,
@@ -1845,9 +1803,11 @@ class ArkGateway:
extra_image_urls: list[str] | None = None,
) -> tuple[str, TaskResult]:
"""Create i2v task and wait;开源版只走 TokenFree(不直连 Kie / 火山)。"""
+ if current_snapshot.get():
+ current_operation.set(operation_for("video", shot_no=shot_no, model=model))
last_err: Exception | None = None
+ use_json = False
for attempt in range(max_attempts):
- use_json = attempt != 1 # attempt0 json, attempt1 plain, attempt2 json again
try:
task_id = await self.gen_video_i2v(
image_url,
@@ -1859,35 +1819,16 @@ class ArkGateway:
prompt_as_json=use_json,
generate_audio=generate_audio,
extra_image_urls=extra_image_urls,
+ model=model,
)
return await self.wait_video(
task_id,
project_id=project_id,
shot_no=shot_no,
)
- except Exception as exc: # noqa: BLE001
- last_err = exc
- msg = str(exc)
- retryable = any(
- k in msg
- for k in (
- "summary_caption",
- "BodyFormat",
- "InvalidParameter",
- "poll timeout",
- )
- )
- logger.warning(
- "Seedance attempt %s/%s shot=%s failed: %s",
- attempt + 1,
- max_attempts,
- shot_no,
- msg[:300],
- )
- if not retryable or attempt >= max_attempts - 1:
- break
- await asyncio.sleep(1.5 * (attempt + 1))
- raise RuntimeError(str(last_err) if last_err else "video generation failed")
+ except Exception:
+ raise
+ raise RuntimeError("视频生成失败")
def _resolved_audio_model(self) -> str:
routed = (resolve_upstream_model("audio", None) or "").strip()
@@ -1905,7 +1846,7 @@ class ArkGateway:
"""TokenFree 上 Qwen-TTS 的 /audio/speech 未实现,改走 Omni/Gemini chat。"""
base = (self.settings.ark_base_url or "").rstrip("/")
key = (self.settings.ark_api_key or "").strip()
- if not base or not key:
+ if not base or (not key and not getattr(self.settings, "local_media_mock", False)):
return False
model_id = tokenfree_tts_chat_model(
resolve_tokenfree_tts_model((model or self._resolved_audio_model()).strip())
@@ -1914,7 +1855,7 @@ class ArkGateway:
if tokenfree_tts_uses_chat_audio(model_id):
return await self._tts_openai_chat_audio(text, voice, dest, model=model_id)
async with httpx.AsyncClient(timeout=120.0) as client:
- resp = await observed_request(client, "POST",
+ resp = await self._request_media(client, "POST",
f"{base}/audio/speech",
headers=self._headers(),
json={
@@ -1960,7 +1901,7 @@ class ArkGateway:
}
)
async with httpx.AsyncClient(timeout=120.0) as client:
- resp = await observed_request(client, "POST", f"{base}/chat/completions", headers=self._headers(), json=body)
+ resp = await self._request_media(client, "POST", f"{base}/chat/completions", headers=self._headers(), json=body)
if resp.status_code >= 400:
logger.warning(
"OpenAI chat-audio HTTP %s model=%s: %s",
@@ -1969,6 +1910,10 @@ class ArkGateway:
(resp.text or "")[:300],
)
return False
+ if getattr(self.settings, "local_media_mock", False):
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(resp.content)
+ return True
audio: bytes | None = extract_sse_audio_bytes(resp.text or "") if omni else None
if not audio:
try:
@@ -2032,6 +1977,8 @@ class ArkGateway:
try:
ok = await self._tts_openai_speech(clean, speaker, dest, model=model_id)
if ok:
+ if getattr(self.settings, "local_media_mock", False):
+ return local_media_mock.media_url("default.mp3")
url = await _accept_if_audible("tokenfree-speech")
if url:
logger.info(
@@ -2043,7 +1990,11 @@ class ArkGateway:
return url
except Exception as exc: # noqa: BLE001
logger.warning("tokenfree speech failed model=%s: %s", model_id, exc)
+ if getattr(self.settings, "local_media_mock", False):
+ raise RuntimeError("模拟语音请求组装失败,请检查模型配置和参数") from exc
+ if getattr(self.settings, "local_media_mock", False):
+ raise RuntimeError("模拟语音请求组装失败,未调用备用语音服务")
# edge-tts:按 speaker 映射不同 neural,上游都失败时仍能分出角色声线
try:
await self._tts_edge(clean, dest, voice_hint=speaker)
diff --git a/backend/app/services/billing/alerts.py b/backend/app/services/billing/alerts.py
index 1f64d9b..d45ac08 100644
--- a/backend/app/services/billing/alerts.py
+++ b/backend/app/services/billing/alerts.py
@@ -27,7 +27,7 @@ async def _user_total_charge_fen(db: AsyncSession, user_id: int) -> int:
row = (
await db.execute(
select(func.coalesce(func.sum(UsageEvent.charge_fen), 0)).where(
- UsageEvent.user_id == int(user_id),
+ func.coalesce(UsageEvent.billing_payer_user_id, UsageEvent.user_id) == int(user_id),
UsageEvent.settled.is_(True),
)
)
diff --git a/backend/app/services/billing/context.py b/backend/app/services/billing/context.py
index a125b94..f2fd484 100644
--- a/backend/app/services/billing/context.py
+++ b/backend/app/services/billing/context.py
@@ -7,20 +7,39 @@ from contextvars import ContextVar
from typing import AsyncIterator
_current_task_run_id: ContextVar[int | None] = ContextVar("billing_task_run_id", default=None)
+_current_team_id: ContextVar[int | None] = ContextVar("billing_team_id", default=None)
def get_current_task_run_id() -> int | None:
return _current_task_run_id.get()
+def get_current_team_id() -> int | None:
+ return _current_team_id.get()
+
+
+def set_current_team_id(team_id: int | None) -> None:
+ _current_team_id.set(team_id)
+
+
def set_current_task_run_id(task_run_id: int | None) -> None:
_current_task_run_id.set(task_run_id)
@asynccontextmanager
-async def billing_scope(task_run_id: int | None) -> AsyncIterator[None]:
+async def billing_scope(task_run_id: int | None, *, team_id: int | None = None, snapshot: dict | None = None) -> AsyncIterator[None]:
+ # Nested contexts for the same task retain its team unless explicitly supplied.
+ current_team = _current_team_id.get() if _current_task_run_id.get() == task_run_id else None
+ from app.services.media_models.runtime import current_snapshot, current_operation
+ inherited = current_snapshot.get() if _current_task_run_id.get() == task_run_id else None
+ media_token = current_snapshot.set(snapshot if snapshot is not None else inherited)
+ operation_token = current_operation.set(None)
token = _current_task_run_id.set(task_run_id)
+ team_token = _current_team_id.set(team_id if team_id is not None else current_team)
try:
yield
finally:
+ current_operation.reset(operation_token)
+ current_snapshot.reset(media_token)
+ _current_team_id.reset(team_token)
_current_task_run_id.reset(token)
diff --git a/backend/app/services/billing/display.py b/backend/app/services/billing/display.py
index d380dc0..729d264 100644
--- a/backend/app/services/billing/display.py
+++ b/backend/app/services/billing/display.py
@@ -13,6 +13,7 @@ from app.models import UsageEvent
from app.services.billing.pricing import parse_upstream_cost_fen
_BASIS_LABELS = {
+ "fixed_media": "站内固定价",
"estimate": "估算",
"upstream_usage": "实测(token)",
"upstream_cost": "实测(费用)",
@@ -50,7 +51,7 @@ def resolve_billing_basis(*, estimated: bool, raw_usage_json: str | None = None)
raw = None
if isinstance(raw, dict):
basis = str(raw.get("billing_basis") or "")
- if basis in {"official_rule", "newapi_log"}:
+ if basis in {"official_rule", "newapi_log", "fixed_media"}:
return basis
usage = raw.get("usage") if isinstance(raw, dict) and isinstance(raw.get("usage"), dict) else raw
if isinstance(usage, dict):
diff --git a/backend/app/services/billing/ephemeral.py b/backend/app/services/billing/ephemeral.py
index 5f593ad..6abf30f 100644
--- a/backend/app/services/billing/ephemeral.py
+++ b/backend/app/services/billing/ephemeral.py
@@ -17,6 +17,7 @@ from app.config import get_settings
from app.services.billing.context import billing_scope
from app.services.billing.settlement import freeze_for_task, settle_task
from app.services.tasks.handlers import get_task_handler
+from app.services.tasks.queues import task_queue
from app.services.tasks.service import append_task_event, build_task_event, build_task_step
from app.services.tasks.upstream import upstream_event_session
@@ -38,6 +39,14 @@ async def create_ephemeral_task_row(
episode_id: int | None = None,
) -> TaskRun:
"""创建并立即执行的轻量任务行(不经过调度器排队)。"""
+ payload = {key: value for key, value in (payload or {}).items() if not key.startswith("_team_")}
+ if drama_project_id is not None:
+ from app.services.tasks.team_scope import prepare_background_task
+ user = await prepare_background_task(db, int(drama_project_id), user)
+ from app.services.tasks.service import _validate_task_scope
+ from app.services.billing.settlement import ensure_balance_for_task
+ scope = TaskCreateRequest(domain=domain, task_type=task_type, 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)
+ await _validate_task_scope(db, user, scope)
handler = get_task_handler(domain, task_type)
planned = handler.plan_steps(TaskCreateRequest(domain=domain, task_type=task_type)) if handler else []
first = planned[0] if planned else None
@@ -45,6 +54,7 @@ async def create_ephemeral_task_row(
task = TaskRun(
domain=domain,
task_type=task_type,
+ queue_type=task_queue(task_type, payload),
status="pending",
priority=1,
requested_by=user.id,
@@ -55,14 +65,22 @@ async def create_ephemeral_task_row(
next_action_at=now,
payload=payload or {},
project_id=project_id,
- drama_project_id=drama_project_id,
+ drama_project_id=scope.drama_project_id,
shot_id=shot_id,
fragment_id=fragment_id,
asset_id=asset_id,
- episode_id=episode_id,
+ episode_id=scope.episode_id,
+ team_id=scope.team_id,
)
+ from app.services.media_models.planning import prepare_task_media
+ await prepare_task_media(db, task)
+ if task.team_id is not None:
+ task.billing_estimate_fen = await ensure_balance_for_task(db, user, task)
db.add(task)
await db.flush()
+ if task.team_id is not None:
+ from app.services.teams.edit_locks import claim_task_locks
+ await claim_task_locks(db, task, user.id)
if first:
db.add(build_task_step(task.id, first))
db.add(
@@ -137,14 +155,20 @@ async def run_billed_ephemeral(
)
await db.flush()
+ if task.team_id is not None or task.billing_snapshot is not None:
+ # Accepted team work is durable before network I/O; release the shared
+ # team/member/project/wallet admission locks even for commit=False callers.
+ await db.commit()
+
result: T
try:
- async with billing_scope(task.id), upstream_event_session(db):
+ async with billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot), upstream_event_session(db):
result = await executor()
task.status = "succeeded"
task.progress_percent = 100
task.finished_at = datetime.now(UTC)
- task.result_payload = {"ok": True} if result is None else {"ok": True, "result": str(type(result))}
+ task.result_payload = {**(task.result_payload or {}), "ok": True,
+ **({"result": str(type(result))} if result is not None else {})}
await append_task_event(
db,
task.id,
@@ -165,12 +189,12 @@ async def run_billed_ephemeral(
message=str(exc)[:200],
)
await settle_task(db, task.id)
- if commit:
+ if commit or task.team_id is not None:
await db.commit()
raise
await settle_task(db, task.id)
- if commit:
+ if commit or task.team_id is not None:
await db.commit()
await db.refresh(task)
return task, result
@@ -239,9 +263,12 @@ async def run_billed_ephemeral_deferred(
)
await db.flush()
+ if task.team_id is not None or task.billing_snapshot is not None:
+ await db.commit()
+
result: T
try:
- async with billing_scope(task.id), upstream_event_session(db):
+ async with 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:
@@ -272,11 +299,11 @@ async def run_billed_ephemeral_deferred(
message=str(exc)[:200],
)
await settle_task(db, task.id)
- if commit:
+ if commit or task.team_id is not None:
await db.commit()
raise
- if commit:
+ if commit or task.team_id is not None:
await db.commit()
await db.refresh(task)
return task, result
@@ -335,13 +362,13 @@ async def settle_deferred_video_poll(
now = datetime.now(UTC)
if terminal == "succeeded":
payload = task.payload if isinstance(task.payload, dict) else {}
- async with billing_scope(task.id):
+ async with billing_scope(task.id, team_id=task.team_id, snapshot=task.billing_snapshot):
from app.services.drama.billing_util import record_seedance_video_usage, seedance_billing_key
generate_audio = bool(payload.get("generate_audio", True))
key = billing_key or seedance_billing_key(generate_audio=generate_audio)
task_result = None
- if usage_tokens > 0:
+ if usage_tokens > 0 or (task.billing_snapshot or {}).get("mode") == "fixed_media":
from app.services.ark import TaskResult
task_result = TaskResult(
diff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.py
index c48e42b..d879837 100644
--- a/backend/app/services/billing/estimates.py
+++ b/backend/app/services/billing/estimates.py
@@ -37,11 +37,8 @@ __all__ = [
def _kepu_video_resolution(project: Project | None, settings: Settings) -> str:
"""科普成片清晰度:设置项;HD 且配置为 480p 时升到 720p(与 pipeline 一致)。"""
- raw = str(getattr(settings, "ark_video_resolution", "") or "480p")
- mode = str(getattr(project, "resolution_mode", "") or "")
- if mode == "hd" and raw.strip().lower() == "480p":
- return "720p"
- return raw
+ from app.services.seedance_resolutions import project_video_resolution
+ return project_video_resolution(project, settings)
def _drama_video_resolution(payload: dict) -> str:
@@ -180,9 +177,20 @@ def estimate_phase_fen(project: Project, phase: str, settings: Settings | None =
async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings | None = None) -> int:
"""按 domain + task_type 估算单任务预扣(分)。"""
s = settings or get_settings()
- await ensure_official_rates(s)
domain = (task.domain or "").strip()
task_type = (task.task_type or "").strip()
+ snapshot = task.billing_snapshot or {}
+ if snapshot.get("mode") == "fixed_media":
+ total = sum(item["total_fen"] for item in snapshot["items"])
+ if domain == "kepu" and task_type == "project_pipeline":
+ project = (await db.execute(select(Project).where(Project.id == task.project_id).options(selectinload(Project.shots)))).scalar_one_or_none()
+ if project and any(x["capability"] == "image" for x in snapshot["items"]) and not project_audio_ready(project):
+ _, tts = charge_fen_for_tokens(s.billing_est_tts_tokens * max(len(project.shots), 1), "tts", settings=s)
+ total += _buffered_fen(tts, s)
+ return total
+ if domain == "drama" and task_type == "episode_compose":
+ return 0
+ await ensure_official_rates(s)
payload = task.payload if isinstance(task.payload, dict) else {}
if domain == "kepu" and task_type == "project_pipeline":
@@ -281,6 +289,9 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
return _buffered_fen(c, s)
if domain in {"api", "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"}:
return _catalog_image_fen(s, payload=payload)
if task_type in {"v1_video", "v1_seedance", "tool_video"}:
@@ -291,6 +302,8 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
model=_payload_video_model(payload, s),
resolution=str(payload.get("resolution") or "").strip() or "480p",
)
+ if task_type == "tool_video" and payload.get("tool_id") == "t2v":
+ c += _catalog_image_fen(s, payload=payload)
return _buffered_fen(c, s)
c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
diff --git a/backend/app/services/billing/http.py b/backend/app/services/billing/http.py
index 431a19f..c7ace9b 100644
--- a/backend/app/services/billing/http.py
+++ b/backend/app/services/billing/http.py
@@ -8,5 +8,8 @@ from fastapi import HTTPException
def http_exception_for_value_error(exc: ValueError) -> HTTPException:
"""余额不足 → 402,其余 ValueError → 400。"""
detail = str(exc)
- status = 402 if detail.startswith("余额不足") else 400
+ from app.services.media_models import MediaValidationError
+ if isinstance(exc, MediaValidationError):
+ return HTTPException(status_code=422, detail=[{"loc": ["body", exc.field], "msg": detail, "type": "media_parameter"}])
+ status = 402 if detail.startswith(("余额不足", "团队余额不足")) else 400
return HTTPException(status_code=status, detail=detail)
diff --git a/backend/app/services/billing/newapi_bill.py b/backend/app/services/billing/newapi_bill.py
index ca43feb..25e8c1a 100644
--- a/backend/app/services/billing/newapi_bill.py
+++ b/backend/app/services/billing/newapi_bill.py
@@ -59,14 +59,16 @@ def apply_log_quota(event: UsageEvent, log: dict[str, Any]) -> bool:
if fen <= 0:
return False
event.cost_fen = fen
- event.charge_fen = fen
+ if not (getattr(event, "billing_detail", None) or {}).get("mode") == "fixed_media":
+ event.charge_fen = fen
+ event.cost_status = "verified"
event.estimated = False
raw = _load_raw(event)
usage = raw.get("usage") if isinstance(raw.get("usage"), dict) else {}
usage = dict(usage)
usage["quota"] = quota
raw["usage"] = usage
- raw["billing_basis"] = "newapi_log"
+ raw["billing_basis"] = "fixed_media" if (getattr(event, "billing_detail", None) or {}).get("mode") == "fixed_media" else "newapi_log"
if log.get("id") is not None:
raw["newapi_log_id"] = log.get("id")
event.raw_usage_json = json.dumps(raw, ensure_ascii=False)[:4000]
@@ -75,7 +77,7 @@ def apply_log_quota(event: UsageEvent, log: dict[str, Any]) -> bool:
async def apply_newapi_bills(events: list[UsageEvent]) -> int:
"""结算前按时间窗拉消费日志,能唯一对上的改成账单 quota。"""
- pending = [event for event in events if not _already_billed(event)]
+ pending = [event for event in events if not _already_billed(event) and not _load_raw(event).get("simulated")]
if not pending:
return 0
start, end = _window(pending)
diff --git a/backend/app/services/billing/settlement.py b/backend/app/services/billing/settlement.py
index 42476f8..70c495a 100644
--- a/backend/app/services/billing/settlement.py
+++ b/backend/app/services/billing/settlement.py
@@ -6,7 +6,7 @@ import logging
from datetime import UTC, datetime, timedelta
from typing import Any
-from sqlalchemy import select
+from sqlalchemy import and_, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import Settings, get_settings
@@ -92,8 +92,10 @@ async def pending_task_commitment_fen(
) -> int:
"""汇总用户进行中、尚未预扣冻结的任务估算占用(分)。"""
stmt = select(TaskRun).where(
- TaskRun.requested_by == int(user_id),
- TaskRun.billing_status == "none",
+ or_(
+ and_(TaskRun.requested_by == int(user_id), TaskRun.team_id.is_(None), TaskRun.billing_status == "none"),
+ and_(TaskRun.billing_payer_user_id == int(user_id), TaskRun.team_id.is_not(None), TaskRun.billing_status == "reserved"),
+ ),
TaskRun.status.in_(_PENDING_BILLING_TASK_STATUSES),
)
if exclude_task_id is not None:
@@ -110,6 +112,11 @@ async def pending_task_commitment_fen(
async def ensure_balance_for_task(db: AsyncSession, user: User, task: TaskRun) -> int:
"""入队前同步校验余额(含排队中未冻结估算),不足抛 ValueError;返回本任务估算分。"""
+ if task.team_id is not None:
+ from app.services.billing.team import check_team_budget
+ need = await estimate_task_fen(db, task) if billing_active(user) else 0
+ summary = await check_team_budget(db, task, need, reserve=True)
+ return summary["unit_estimate_fen"]
if not billing_active(user):
return 0
locked = await _lock_user(db, int(user.id))
@@ -139,6 +146,13 @@ async def ensure_balance_for_task_batch(
count: int,
) -> dict[str, int]:
"""批量入队前校验:pending + unit*count。不足抛 ValueError。"""
+ if task.id is None and task.billing_snapshot is None:
+ from app.services.media_models.planning import prepare_task_media
+ await prepare_task_media(db, task)
+ if task.team_id is not None:
+ from app.services.billing.team import check_team_budget
+ unit = await estimate_task_fen(db, task) if billing_active(user) else 0
+ return await check_team_budget(db, task, unit, count=count)
if not billing_active(user):
return {"unit_estimate_fen": 0, "required_total_fen": 0}
qty = max(1, int(count))
@@ -175,6 +189,9 @@ async def freeze_for_task(db: AsyncSession, task: TaskRun) -> int:
if locked_task is not task:
task.billing_status = locked_task.billing_status
task.billing_estimate_fen = locked_task.billing_estimate_fen
+ if task.team_id is not None:
+ from app.services.billing.team import freeze_team_task
+ return await freeze_team_task(db, task)
if task.billing_status == "frozen":
return int(task.billing_estimate_fen or 0)
@@ -216,6 +233,16 @@ async def settle_task(db: AsyncSession, task_id: int) -> dict[str, int]:
"refunded": int(task.billing_refunded_fen or 0),
}
+ from app.services.media_models.failure_costs import record_failed_costs
+ await record_failed_costs(db, task)
+ if task.team_id is not None:
+ from app.services.billing.team import settle_team_task
+ result = await settle_team_task(db, task)
+ if task.status in {"succeeded", "failed", "cancelled"}:
+ from app.services.teams.edit_locks import release_task_locks
+ await release_task_locks(db, int(task.id))
+ return result
+
# 钱包侧幂等:已有 unfreeze/settle 流水则只对齐状态,禁止二次退还
if task.billing_status == "frozen":
prior = (
@@ -393,7 +420,7 @@ async def reconcile_terminal_frozen_tasks(db: AsyncSession, *, limit: int = 100)
stmt = (
select(TaskRun)
.where(
- TaskRun.billing_status == "frozen",
+ TaskRun.billing_status.in_(("frozen", "reserved")),
TaskRun.status.in_(_RECONCILABLE_TERMINAL_STATUSES),
TaskRun.finished_at.is_not(None),
TaskRun.finished_at < cutoff,
@@ -437,6 +464,7 @@ async def close_expired_pending_orders(
*,
user_id: int | None = None,
out_trade_no: str | None = None,
+ team_id: int | None = None,
) -> int:
from datetime import datetime, timezone
@@ -444,8 +472,10 @@ async def close_expired_pending_orders(
now = datetime.now(timezone.utc)
stmt = select(Order).where(Order.status == "pending")
- if user_id is not None:
- stmt = stmt.where(Order.user_id == user_id)
+ if team_id is not None:
+ stmt = stmt.where(Order.team_id == team_id)
+ elif user_id is not None:
+ stmt = stmt.where(Order.user_id == user_id, Order.team_id.is_(None))
if out_trade_no is not None:
stmt = stmt.where(Order.out_trade_no == out_trade_no)
rows = (await db.execute(stmt)).scalars().all()
diff --git a/backend/app/services/billing/usage.py b/backend/app/services/billing/usage.py
index e53ee9a..12b314a 100644
--- a/backend/app/services/billing/usage.py
+++ b/backend/app/services/billing/usage.py
@@ -3,9 +3,11 @@
from __future__ import annotations
import json
+import hashlib
from datetime import UTC, datetime
from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
from app.config import get_settings
from app.models import UsageEvent
@@ -32,10 +34,22 @@ async def record_line(
domain: str | None = None,
) -> UsageEvent:
s = get_settings()
+ if getattr(s, "local_media_mock", False) and billing_key_to_capability(billing_key) in {"image", "video", "tts"}:
+ raw = {**(raw or {}), "simulated": True}
from app.services.tokenfree_pricing import ensure_official_rates
- await ensure_official_rates(s)
tid = task_run_id if task_run_id is not None else get_current_task_run_id()
+ team_id = None
+ task = None
+ if tid is not None:
+ from app.models_tasks import TaskRun
+ task = await db.get(TaskRun, int(tid))
+ if task is not None:
+ user_id = int(task.requested_by)
+ team_id = task.team_id
+ drama_project_id = task.drama_project_id or drama_project_id
+ if not task or (task.billing_snapshot or {}).get("mode") != "fixed_media" or billing_key_to_capability(billing_key) not in {"image", "video"}:
+ await ensure_official_rates(s)
total = int(tokens) or (int(prompt_tokens) + int(completion_tokens))
if total <= 0:
if billing_key == "llm_chat":
@@ -50,9 +64,64 @@ async def record_line(
elif billing_key.startswith("seedance"):
total = s.billing_est_seedance_tokens_per_sec * 5
estimated = True
- cost, charge, from_upstream = charge_fen_for_usage(
- total, billing_key, raw_usage=raw, settings=s, model=model
- )
+ detail = None
+ delivery_key = None
+ cost_status = None
+ snapshot = task.billing_snapshot if task is not None else None
+ if snapshot and snapshot.get("mode") == "fixed_media" and billing_key_to_capability(billing_key) in {"image", "video"}:
+ # Serialize delivery admission, including the uniqueness check and quantity cap.
+ # Lock fresh billing flags without expiring the executor's loaded step relationships.
+ flags = (await db.execute(select(type(task).billing_status, type(task).billing_enabled_snapshot)
+ .where(type(task).id == task.id).with_for_update())).one()
+ task.billing_status = flags.billing_status
+ task.billing_enabled_snapshot = flags.billing_enabled_snapshot
+ facts = dict(raw or {})
+ facts = {**(facts.get("usage") or {}), **facts}
+ capability = billing_key_to_capability(billing_key)
+ candidates = [x for x in snapshot["items"] if x["capability"] == capability]
+ operation = next((x for x in candidates if x["operation_id"] == facts.get("media_operation_id")), None)
+ if operation is None and shot_id:
+ operation = next((x for x in candidates if x.get("target_id") == shot_id), None)
+ if operation is None and len(candidates) == 1:
+ operation = candidates[0]
+ if operation is None:
+ raise ValueError("billing: 无法匹配已预留的生成操作")
+ delivery = facts.get("delivery_id")
+ identity = delivery or facts.get("attempt_id")
+ if identity:
+ digest = hashlib.sha256(str(identity).encode()).hexdigest()
+ delivery_key = f"{'media' if delivery else 'media-cost'}:{task.id}:{operation['operation_id']}:{digest}"
+ existing = (await db.execute(select(UsageEvent).where(UsageEvent.delivery_key == delivery_key))).scalar_one_or_none()
+ if existing:
+ return existing
+ if task.billing_status == "settled":
+ raise ValueError("billing: 已结算任务不能新增交付,请创建新的生成任务")
+ from app.services.billing.pricing import parse_upstream_cost_fen
+ parsed_cost = parse_upstream_cost_fen(raw, settings=s)
+ cost = parsed_cost or 0
+ cost_status = "verified" if parsed_cost is not None else "pending"
+ charge = operation["unit_charge_fen"] if delivery else 0
+ if task.billing_status == "skipped" or task.billing_enabled_snapshot is False:
+ charge = 0
+ if delivery:
+ delivered = list((await db.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id, UsageEvent.delivery_key.is_not(None)))).scalars())
+ count = sum(1 for event in delivered if (event.billing_detail or {}).get("operation_id") == operation["operation_id"] and (event.billing_detail or {}).get("delivered"))
+ if count >= operation["params"]["count"]:
+ raise ValueError("billing: 交付数量超过任务已预留数量")
+ model = operation["model_id"]
+ detail = {"mode": "fixed_media", "price_version": snapshot["price_version"],
+ "operation_id": operation["operation_id"], "model_id": model,
+ "resolution": operation["resolution"], "duration": operation.get("duration"),
+ "unit_price_yuan": operation["unit_price_yuan"], "delivered": bool(delivery),
+ "billing_enabled": task.billing_status != "skipped" and task.billing_enabled_snapshot is not False,
+ "route": operation["route"]}
+ raw = {**(raw or {}), "billing_basis": "fixed_media"}
+ from_upstream = parsed_cost is not None
+ estimated = False # Retail price is exact even when upstream cost is pending.
+ else:
+ cost, charge, from_upstream = charge_fen_for_usage(
+ total, billing_key, raw_usage=raw, settings=s, model=model
+ )
# 仅在确有上游 token / quota 时取消「估算」;官方表达式按秒估仍标估算
usage_parsed = raw.get("usage") if isinstance(raw, dict) and isinstance(raw.get("usage"), dict) else (
raw if isinstance(raw, dict) else {}
@@ -75,6 +144,8 @@ async def record_line(
# 显式写墙钟时间:长任务会话里 server_default=now() 会落成事务起点,用量明细按时间/日期筛会漏看
ev = UsageEvent(
user_id=user_id,
+ team_id=team_id,
+ billing_payer_user_id=task.billing_payer_user_id if task is not None else None,
project_id=project_id,
drama_project_id=drama_project_id,
task_run_id=tid,
@@ -88,7 +159,10 @@ async def record_line(
completion_tokens=int(completion_tokens),
total_tokens=total,
cost_fen=cost,
- charge_fen=charge,
+ cost_status=cost_status,
+ billing_detail=detail,
+ delivery_key=delivery_key,
+ charge_fen=0 if team_id is not None and task.billing_enabled_snapshot is False else charge,
estimated=estimated,
settled=False,
raw_usage_json=json.dumps(raw, ensure_ascii=False)[:4000] if raw else None,
diff --git a/backend/app/services/logical_model_router.py b/backend/app/services/logical_model_router.py
index 2338685..202fbe6 100644
--- a/backend/app/services/logical_model_router.py
+++ b/backend/app/services/logical_model_router.py
@@ -87,6 +87,9 @@ def resolve_logical_model_candidates(
return direct
# 默认/请求模型失效时,回落到同能力第一个可解析模型(DeepSeek / Kimi / 其它兼容均可)
+ if capability in {"image", "video"}:
+ # Media requests never switch model, including when the requested route is unavailable.
+ return []
for model in snapshot.logical_models:
if not model.enabled or model.capability != capability:
continue
diff --git a/backend/app/services/model_routing_config.py b/backend/app/services/model_routing_config.py
index d23ba84..b0698aa 100644
--- a/backend/app/services/model_routing_config.py
+++ b/backend/app/services/model_routing_config.py
@@ -185,6 +185,7 @@ def synchronize_logical_models_with_channels(
id=logical_id,
name=(existing.name if existing and existing.name else catalog_model["upstream_model"]),
capability=synced_cap,
+ strategy_id=existing.strategy_id if existing else None,
enabled=existing.enabled if existing else True,
bindings=bindings,
)
@@ -285,6 +286,15 @@ def model_routing_validation_errors(
errors.append(f"逻辑模型 {model.name or model.id} 至少需要一个渠道绑定")
binding_keys: set[str] = set()
for binding in model.bindings:
+ if model.capability in {"image", "video"}:
+ from app.services.media_models import get_strategy
+ try:
+ strategy = get_strategy(model.strategy_id or model.id)
+ if strategy.capability != model.capability or get_strategy(binding.upstream_model).model_id != strategy.model_id:
+ errors.append(f"逻辑模型 {model.id} 的渠道绑定必须匹配同款模型策略")
+ except ValueError:
+ if model.strategy_id:
+ errors.append(f"逻辑模型 {model.id} 的策略或上游模型未注册")
binding_key = f"{binding.channel_id}:{normalize_model_name(binding.upstream_model)}"
if binding.channel_id not in channel_ids:
errors.append(f"逻辑模型 {model.id} 引用了不存在的渠道 {binding.channel_id}")
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index a190995..3d96684 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -93,6 +93,7 @@ async def _record_seedream_usage(
image_result,
model: str,
shot_id: int | None = None,
+ delivered: bool = True,
) -> None:
try:
from app.services.drama.billing_util import record_seedream_image_usage
@@ -107,6 +108,7 @@ async def _record_seedream_usage(
model=model,
domain="kepu",
image_result=image_result,
+ delivered=delivered,
project_id=project_id,
shot_id=shot_id,
)
@@ -123,6 +125,7 @@ async def _record_seedance_usage(
task_result,
fallback_duration_sec: float,
shot_id: int | None = None,
+ delivered: bool = True,
) -> None:
try:
from app.services.drama.billing_util import record_seedance_video_usage
@@ -131,9 +134,8 @@ async def _record_seedance_usage(
project = await db.get(Project, project_id)
if not project:
return
- res = str(getattr(get_settings(), "ark_video_resolution", "") or "480p")
- if str(getattr(project, "resolution_mode", "") or "") == "hd" and res.strip().lower() == "480p":
- res = "720p"
+ from app.services.seedance_resolutions import project_video_resolution
+ res = project_video_resolution(project)
await record_seedance_video_usage(
db,
user_id=project.user_id,
@@ -141,6 +143,7 @@ async def _record_seedance_usage(
model=model,
domain="kepu",
task_result=task_result,
+ delivered=delivered,
fallback_duration_sec=fallback_duration_sec,
resolution=res,
provider_task_id=getattr(task_result, "provider_task_id", None),
@@ -431,6 +434,14 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:
)
return
+ if requested == "script":
+ # 文字任务直接执行时也不能因已有分镜而落入媒体生成分支。
+ await publish_progress(project_id, {
+ "event": "paused", "stage": "SCRIPT_READY", "percent": 15,
+ "message": "分镜脚本已就绪,请确认后继续生成素材",
+ })
+ return
+
logger.info(
"pipeline resume project=%s phase=%s skip_script=%s skip_assets=%s skip_videos=%s",
project_id,
@@ -820,6 +831,9 @@ def _effective_extra(project: Project) -> str:
def _image_size_for(project: Project) -> str | None:
+ explicit = str(getattr(project, "image_resolution", "") or "").strip().upper()
+ if explicit:
+ return explicit
ratio = _project_output_ratio(project)
return _IMAGE_SIZE_BY_RATIO.get(ratio)
@@ -970,6 +984,11 @@ async def _parallel_image_and_audio(project_id: int) -> None:
)
elif not shot.video_url:
shot.status = ShotStatus.IMAGE_READY
+ from app.services.media_models.runtime import current_snapshot
+ if (current_snapshot.get() or {}).get("mode") == "fixed_media":
+ from app.services.drama.billing_util import record_seedream_image_usage
+ await record_seedream_image_usage(db, user_id=project.user_id, model=image_model or get_settings().model_image,
+ domain="kepu", image_result=img, project_id=project_id, shot_id=shot.id)
await db.commit()
await bump_images()
@@ -999,14 +1018,11 @@ async def _parallel_image_and_audio(project_id: int) -> None:
model=image_model,
aspect_ratio=output_ratio or None,
)
- s = get_settings()
- await _record_seedream_usage(
- project_id,
- image_result=img,
- model=s.model_image,
- shot_id=meta["id"],
- )
await persist_image(meta, img)
+ from app.services.media_models.runtime import current_snapshot
+ if (current_snapshot.get() or {}).get("mode") != "fixed_media":
+ await _record_seedream_usage(project_id, image_result=img,
+ model=get_settings().model_image, shot_id=meta["id"])
return SimpleNamespace(image_ark_url=img.remote_url, image_url=img.local_url)
async def run_images() -> None:
@@ -1123,9 +1139,8 @@ async def _parallel_videos(project_id: int) -> None:
tpl.seedance_config.get("character_consistency", True)
)
motion = str(tpl.seedance_config.get("motion_bias", ""))
- resolution = cfg.ark_video_resolution
- if project.resolution_mode == "hd" and resolution == "480p":
- resolution = "720p"
+ from app.services.seedance_resolutions import project_video_resolution
+ resolution = project_video_resolution(project, cfg)
ratio = _project_output_ratio(project) or cfg.ark_video_ratio
shot_meta = [
{
@@ -1284,14 +1299,6 @@ async def _parallel_videos(project_id: int) -> None:
s = get_settings()
dur = max(float(dur), 2.0)
billing_key = "seedance2:video0" if generate_audio else "seedance2:video1"
- await _record_seedance_usage(
- project_id,
- billing_key=billing_key,
- model=s.model_video,
- task_result=task_result,
- fallback_duration_sec=dur,
- shot_id=meta["id"],
- )
async with _db_write_lock():
async with AsyncSessionLocal() as db:
shot = await db.get(Shot, meta["id"])
@@ -1300,7 +1307,24 @@ async def _parallel_videos(project_id: int) -> None:
shot.video_url = local_video
shot.last_frame_url = last
shot.status = ShotStatus.VIDEO_READY
+ from app.services.media_models.runtime import current_snapshot
+ if (current_snapshot.get() or {}).get("mode") == "fixed_media":
+ from app.services.drama.billing_util import record_seedance_video_usage
+ await record_seedance_video_usage(db, user_id=project.user_id, billing_key=billing_key,
+ model=video_model or get_settings().model_video, domain="kepu", task_result=task_result,
+ fallback_duration_sec=dur, resolution=resolution, provider_task_id=task_result.provider_task_id,
+ project_id=project_id, shot_id=shot.id)
await db.commit()
+ from app.services.media_models.runtime import current_snapshot
+ if (current_snapshot.get() or {}).get("mode") != "fixed_media":
+ await _record_seedance_usage(
+ project_id,
+ billing_key=billing_key,
+ model=s.model_video,
+ task_result=task_result,
+ fallback_duration_sec=dur,
+ shot_id=meta["id"],
+ )
done += 1
pct = 55 + int(30 * done / max(total, 1))
async with _db_write_lock():
@@ -1582,6 +1606,7 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
image_result=img,
model=s.model_image,
shot_id=shot_id,
+ delivered=not cancelled,
)
if cancelled:
raise PipelineCancelled(f"project {project_id} cancelled during regen image")
@@ -1611,9 +1636,8 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
consistency = template_consistency_mode(project.template) == "character" and bool(
project.template.seedance_config.get("character_consistency", True)
)
- resolution = cfg.ark_video_resolution
- if project.resolution_mode == "hd" and resolution == "480p":
- resolution = "720p"
+ from app.services.seedance_resolutions import project_video_resolution
+ resolution = project_video_resolution(project, cfg)
script = (getattr(shot, "segment_script", "") or shot.video_prompt or "").strip()
prompt = _kepu_video_prompt(
script,
@@ -1678,6 +1702,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
task_result=task_result,
fallback_duration_sec=max(float(dur), 2.0),
shot_id=shot_id,
+ delivered=not cancelled,
)
if cancelled:
raise PipelineCancelled(f"project {project_id} cancelled during regen video")
diff --git a/backend/app/services/tokenfree_pricing.py b/backend/app/services/tokenfree_pricing.py
index f3784b2..0e9c906 100644
--- a/backend/app/services/tokenfree_pricing.py
+++ b/backend/app/services/tokenfree_pricing.py
@@ -1005,6 +1005,8 @@ async def ensure_official_rates(settings: Settings | None = None) -> dict[str, O
Seedance 始终用 TF Ark 渠道导出的 billing_expr 覆盖,避免公开价目漂移。
"""
+ if getattr(settings or get_settings(), "local_media_mock", False):
+ return merge_seedance_tf_rates(cached_rates())
ttl = _FAIL_TTL_SEC if _cache_failed else _CACHE_TTL_SEC
if _cache is not None and _cache_at and (time.monotonic() - _cache_at) < ttl:
return merge_seedance_tf_rates(_cache)
diff --git a/backend/app/services/tokenfree_video.py b/backend/app/services/tokenfree_video.py
index 2f8bf1e..4132271 100644
--- a/backend/app/services/tokenfree_video.py
+++ b/backend/app/services/tokenfree_video.py
@@ -15,6 +15,33 @@ from typing import Any
from app.services.media_ref_limits import MAX_REFERENCE_IMAGES
+
+async def post_video_create(client: Any, method: str, url: str, *, request_call: Any = None, **kwargs: Any) -> Any:
+ """MiniMax 插件明确拒绝分辨率枚举时,仅转换大小写重试一次。"""
+ if request_call is None:
+ from app.services.tasks.upstream import observed_request
+
+ request_call = observed_request
+ response = await request_call(client, method, url, **kwargs)
+ body = kwargs.get("json")
+ if response.status_code != 400 or not isinstance(body, dict):
+ return response
+ if str(body.get("model") or "").lower() != "minimax-h3":
+ return response
+ try:
+ error = response.json()
+ except ValueError:
+ return response
+ if not isinstance(error, dict) or error.get("code") != "plugin_usage_invalid" or extract_video_task_id(error):
+ return response
+ metadata = body.get("metadata")
+ resolution = metadata.get("resolution") if isinstance(metadata, dict) else None
+ alternatives = {"480p": "480P", "768p": "768P", "480P": "480p", "768P": "768p"}
+ if resolution not in alternatives:
+ return response
+ retry_body = {**body, "metadata": {**metadata, "resolution": alternatives[resolution]}}
+ return await request_call(client, method, url, **{**kwargs, "json": retry_body})
+
# 方舟原生异步视频任务前缀
ARK_VIDEO_TASK_PREFIX = "/contents/generations/tasks"
# TokenFree OpenAI Videos 兼容前缀(相对 /v1)
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index d8c8ae3..b950e8e 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -22,6 +22,13 @@ from app.database import Base
from app.models import User
from app.models_tasks import TaskRun
+
[email protected](autouse=True)
+def isolate_direct_llm_launch(monkeypatch):
+ """普通测试不启动真实模型后台调用;执行生命周期用例显式替换此入口。"""
+ from unittest.mock import Mock
+ monkeypatch.setattr("app.services.tasks.direct.launch_direct_task", Mock())
+
_DB_NAME_RE = re.compile(r"^[A-Za-z0-9_]+$")
@@ -92,6 +99,9 @@ async def db_session(billing_enabled: None) -> AsyncIterator[AsyncSession]:
import app.models_drama # noqa: F401
import app.models_settings # noqa: F401
import app.models_tasks # noqa: F401
+ import app.models_teams # noqa: F401
+ import app.models_team_billing # noqa: F401
+ import app.models_team_locks # noqa: F401
url = (get_settings().database_url or "").strip()
if not url.startswith("postgresql"):
diff --git a/backend/tests/test_ark_poll_resilience.py b/backend/tests/test_ark_poll_resilience.py
index cf73185..ba14c78 100644
--- a/backend/tests/test_ark_poll_resilience.py
+++ b/backend/tests/test_ark_poll_resilience.py
@@ -223,44 +223,27 @@ async def test_seedance_submit_failure_does_not_recreate_task(seedance_client) -
seedance_client.wait_video_assets.assert_not_awaited()
-async def test_seedance_wait_audio_error_retries_once_without_audio(seedance_client) -> None:
- """等待阶段报参考音频下载失败:剥离 reference_audio 重提一次并成功。"""
- gen_mock = AsyncMock(side_effect=["t1", "t2"])
- seedance_client.gen_video_seedance_body = gen_mock
- seedance_client.wait_video_assets = AsyncMock(
- side_effect=[RuntimeError(_AUDIO_ERR), _OK_RESULT]
- )
- video_url, _last, result = await seedance_client.gen_and_wait_seedance_body(
- _audio_body(), project_id=1, shot_no=2
- )
- assert video_url == "/static/x.mp4"
- assert result.status == "succeeded"
- assert gen_mock.await_count == 2
- second_body = gen_mock.await_args_list[1].args[0]
- assert not any(
- item.get("type") == "audio_url" and item.get("role") == "reference_audio"
- for item in second_body["content"]
- if isinstance(item, dict)
- )
+async def test_seedance_wait_audio_error_preserves_original_task_and_references(seedance_client) -> None:
+ body = _audio_body()
+ seedance_client.gen_video_seedance_body = AsyncMock(return_value="t1")
+ seedance_client.wait_video_assets = AsyncMock(side_effect=RuntimeError(_AUDIO_ERR))
+ with pytest.raises(RuntimeError, match="resource download failed"):
+ await seedance_client.gen_and_wait_seedance_body(body, project_id=1, shot_no=2)
+ seedance_client.gen_video_seedance_body.assert_awaited_once_with(body, project_id=1, content_labels=None)
+ assert any(item.get("type") == "audio_url" for item in body["content"])
-async def test_seedance_submit_audio_error_retries_once(seedance_client) -> None:
- """提交阶段报参考音频下载失败:剥离后重提一次,随后等待成功。"""
- gen_mock = AsyncMock(side_effect=[RuntimeError(_AUDIO_ERR), "t2"])
- seedance_client.gen_video_seedance_body = gen_mock
- seedance_client.wait_video_assets = AsyncMock(return_value=_OK_RESULT)
- await seedance_client.gen_and_wait_seedance_body(_audio_body(), project_id=1, shot_no=2)
- assert gen_mock.await_count == 2
- seedance_client.wait_video_assets.assert_awaited_once()
+async def test_seedance_submit_audio_error_fails_without_resubmit(seedance_client) -> None:
+ seedance_client.gen_video_seedance_body = AsyncMock(side_effect=RuntimeError(_AUDIO_ERR))
+ seedance_client.wait_video_assets = AsyncMock()
+ with pytest.raises(RuntimeError, match="resource download failed"):
+ await seedance_client.gen_and_wait_seedance_body(_audio_body(), project_id=1, shot_no=2)
+ seedance_client.gen_video_seedance_body.assert_awaited_once()
+ seedance_client.wait_video_assets.assert_not_awaited()
-async def test_seedance_audio_fallback_used_no_third_submit(seedance_client) -> None:
- """剥离参考音频后仍然失败:最多两次建单,绝无第三次。"""
- gen_mock = AsyncMock(side_effect=[RuntimeError(_AUDIO_ERR), RuntimeError(_AUDIO_ERR)])
- seedance_client.gen_video_seedance_body = gen_mock
- seedance_client.wait_video_assets = AsyncMock(side_effect=RuntimeError(_AUDIO_ERR))
+async def test_attempt_count_cannot_enable_automatic_resubmission(seedance_client) -> None:
+ seedance_client.gen_video_seedance_body = AsyncMock(side_effect=RuntimeError(_AUDIO_ERR))
with pytest.raises(RuntimeError, match="resource download failed"):
- await seedance_client.gen_and_wait_seedance_body(
- _audio_body(), project_id=1, shot_no=2, max_attempts=2
- )
- assert gen_mock.await_count == 2
+ await seedance_client.gen_and_wait_seedance_body(_audio_body(), project_id=1, shot_no=2, max_attempts=3)
+ seedance_client.gen_video_seedance_body.assert_awaited_once()
diff --git a/backend/tests/test_kepu_project_listing.py b/backend/tests/test_kepu_project_listing.py
index 157d98d..8361332 100644
--- a/backend/tests/test_kepu_project_listing.py
+++ b/backend/tests/test_kepu_project_listing.py
@@ -70,3 +70,23 @@ async def test_empty_page_skips_task_and_publish_queries(monkeypatch):
assert page.stats.total == 0
batch.assert_not_awaited()
assert db.execute.await_count == 6
+
+
+async def test_listing_preserves_projects_without_a_template(monkeypatch):
+ """历史项目模板为空时仍返回完整列表,使用空字符串表示未选模板。"""
+ rows = [_project(12), _project(20)]
+ rows[0].template_id = None
+ monkeypatch.setattr(
+ kepu_projects, "list_active_tasks_for_projects",
+ AsyncMock(return_value={12: [], 20: []}),
+ )
+ db = SimpleNamespace(execute=AsyncMock(
+ side_effect=[_result(value) for value in [2, rows, [], 2, 0, 2, 0]],
+ ))
+
+ page = await kepu_projects.list_project_page(db, 7, page=1, page_size=8)
+
+ assert [item.id for item in page.items] == [12, 20]
+ assert [item.template_id for item in page.items] == ["", "test"]
+ assert rows[0].template_id is None
+ assert page.meta.total == page.stats.total == 2
diff --git a/backend/tests/test_project_template_schema.py b/backend/tests/test_project_template_schema.py
new file mode 100644
index 0000000..364e236
--- /dev/null
+++ b/backend/tests/test_project_template_schema.py
@@ -0,0 +1,35 @@
+"""历史空模板兼容响应序列化,同时保留新建项目的输入校验。"""
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+import pytest
+from pydantic import ValidationError
+
+from app.schemas import AdminProjectDetailOut, AdminProjectOut, ProjectCreate, ProjectListItem, ProjectOut
+
+
[email protected]("schema", [ProjectListItem, ProjectOut, AdminProjectOut, AdminProjectDetailOut])
[email protected]("template_id", [None, "test"])
+def test_project_responses_normalize_legacy_null_template(schema, template_id):
+ """列表、详情和管理端均兼容空模板,且不改写原始 ORM 属性。"""
+ project = SimpleNamespace(
+ id=1, user_id=7, title="历史项目", template_id=template_id,
+ source_type="theme", source_text="主题", status="DRAFT", progress=0,
+ error_msg=None, cover_url=None, final_video_url=None, ref_image_url=None,
+ resolution_mode="preview", pipeline_mode="full", output_ratio="", voice_id="",
+ created_at=datetime(2026, 10, 24, tzinfo=UTC),
+ updated_at=datetime(2026, 10, 24, tzinfo=UTC),
+ )
+
+ response = schema.model_validate(project)
+
+ assert response.model_dump(mode="json")["template_id"] == (template_id or "")
+ assert project.template_id == template_id
+
+
+def test_create_project_still_rejects_null_template():
+ """历史响应兼容不放宽新建项目的模板要求。"""
+ with pytest.raises(ValidationError) as exc:
+ ProjectCreate(template_id=None, title="新项目", source_text="主题")
+ assert any(error["loc"] == ("template_id",) for error in exc.value.errors())
diff --git a/deploy/README.md b/deploy/README.md
index 86e502d..cee7570 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -51,6 +51,23 @@ sudo apt-get install -y fonts-wqy-zenhei fonts-wqy-microhei fontconfig
缺字体时字幕会显示为「方框」(□),需装字体后**重新合成**该项目成片。
+## 升级前必须检查数据库结构
+
+2026-10-24 本地升级漏跑媒体计费迁移,分集列表因缺少 `task_runs.billing_snapshot` 返回 500。`DATABASE_BOOTSTRAP_ENABLED=false` 会跳过启动建表和补列;重启、未发布价格或健康检查成功都不能代替迁移。
+
+升级现有数据库时,先备份目标库,再用新版本代码及目标环境的数据库配置执行:
+
+```bash
+cd backend
+# 使用该环境的虚拟环境 Python;团队结构等其他迁移仍按对应发布说明执行。
+python scripts/prepare_media_schema.py
+python scripts/prepare_media_schema.py --check
+```
+
+两条命令都必须返回 0 才能重启 API 与任务执行节点。`--check` 在只读事务中校验媒体必需表、列和交付唯一索引,缺失时返回 1;发布脚本或 CI 必须传播该退出码并中止,不能忽略错误继续重启。迁移命令完成后也会校验结构,失败回滚。
+
+重启后除 `/api/health` 外,还须以有权限的登录用户读取目标环境现有项目的分集列表和任务列表,确认返回 200。价格发布另行操作;先完成结构迁移,不要求自动启用新价格。详见 [媒体迁移与故障记录](../docs/MEDIA_MODEL_STRATEGIES.md#发布与兼容)。
+
## 3. 启动 API 与任务平台
```bash
diff --git a/docs/BILLING.md b/docs/BILLING.md
index 1f79289..d8d214c 100644
--- a/docs/BILLING.md
+++ b/docs/BILLING.md
@@ -1,5 +1,9 @@
# PRINTFILM 计费说明
+> 图视频现支持模型策略与站内固定价格版本。后台发布价格后,新任务按成功交付图片张数、提交视频秒数结算;上游费用只更新成本,失败不自动切换路由。未发布价格及旧历史任务沿用下述原计费规则。部署、启停和接口详见 [模型策略与站内定价](MEDIA_MODEL_STRATEGIES.md)。
+
+团队模式使用独立钱包和按成员的上海自然月额度,任务受理时预留、执行时冻结、完成后按实结算。个人钱包不为团队垫付,充值订单与费用始终固定原团队归属。详见 [TEAM_MODE.md](./TEAM_MODE.md)。
+
## 原则
- 按上游 **真实 TokenFree 成本**(或无法拿到 usage 时的保守估价)计费。
@@ -221,3 +225,6 @@ EPAY_RETURN_URL=https://your-site.example.com/pricing?paid=1
5. Seedance 视频成功后 `usage_events.estimated=false` 且 `total_tokens` 与官方任务查询一致。
6. 配置 TokenFree API Key 后,管理端可刷新并查看近 30 日官方/本地成本对照。
7. 单次调用若带 New API `quota` / `quota_consumed`,按额度折人民币后按官方成本 1:1 扣费;管理端可查询 TokenFree 余额。
+
+
+团队模式现按所有者个人账户统一付款,同时限制团队总月额度与成员月额度;任务保存受理时付款人,转让不改变旧任务扣款对象。团队充值/独立调账入口已停用,历史账目兼容规则见 [TEAM_MODE.md](TEAM_MODE.md)。
diff --git a/docs/PLACEHOLDER_BACKLOG.md b/docs/PLACEHOLDER_BACKLOG.md
index 6b726f5..2f4ec34 100644
--- a/docs/PLACEHOLDER_BACKLOG.md
+++ b/docs/PLACEHOLDER_BACKLOG.md
@@ -10,7 +10,8 @@
| 区域 | 主要文件 |
|------|----------|
-| 顶栏 | `frontend/src/components/layout/SiteNav.tsx` |
+| 左侧主导航 / 窄屏抽屉 | `frontend/src/components/layout/SiteNav.tsx`、`AppShell.tsx` |
+| 漫剧 / 自由画布列表 | `frontend/src/pages/drama/DramaListPage.tsx`、`CanvasListPage.tsx` |
| 帮助抽屉 | `frontend/src/components/ui/HelpCenter.tsx`、`Modal.tsx`(`variant=drawer`) |
| 新建 | `frontend/src/pages/studio/CreateProjectPage.tsx` |
| 风格 | `frontend/src/pages/studio/StyleConfigPage.tsx` |
@@ -30,6 +31,8 @@
| G-02 | 帮助中心(侧边抽屉) | 已完成待部署 | P0 | 代码已改为右侧抽屉;需前端 build 上线 |
| G-03 | 通知中心 | 待开发 | P2 | 顶栏 disabled |
| G-04 | 用户资料下拉(设置/账单) | 待开发 | P2 | 当前头像点击为退出 |
+| G-05 | 顶部主菜单改为左侧分组导航 | 已完成待部署 | P0 | 创作组:工作台、漫剧、自由画布、AI 短视频、小工具;资源协作组:资产、团队、定价;帮助、GitHub、语言和账户放底部。窄屏使用导航抽屉,全屏分镜/画布编辑器保留独立布局 |
+| G-06 | 自由画布提升为一级入口 | 已完成待部署 | P0 | 新增 `/canvas` 独立画布列表;`/drama` 只展示剧本项目。共用现有 `workflow` 服务端筛选、项目管理与个人/团队权限;旧 API 不传 `workflow` 仍返回全部可访问项目,现有编辑地址兼容 |
---
@@ -124,7 +127,7 @@
| P-01 | 套餐 SKU 展示 | 已完成 | P1 | 定价页充值包 |
| P-02 | 支付与订单 | 已完成 | P1 | 易支付 alipay/wxpay,见 docs/BILLING.md |
| P-03 | 额度扣减与高清导出权限 | 部分完成 | P1 | token×1.5 预扣结算;hd 门禁可后续 |
-| P-04 | 团队空间 | 待开发 | P3 | |
+| P-04 | 团队空间 | 已接真实后端 | P3 | `/teams`:空间隔离、成员邀请、项目迁入、独立钱包/月额度、任务计费与编辑占用;见 `TEAM_MODE.md` |
---
@@ -150,6 +153,8 @@
| X-03 | 取消中途视频失败错误信息为空 | 待开发 | P1 | `RuntimeError('')` 日志难排查 |
| X-04 | 帮助中心 / 状态文案前端上线 | 已完成待部署 | P0 | `npm run build` + 静态发布 |
| X-05 | 视频阶段卡住时允许「仅补缺镜」 | 待开发 | P1 | 可走 `regen-video` + `compose`,避免整管线重入队 |
+| X-06 | 媒体计费重构上线前迁移与结构校验 | 已完成待部署 | P0 | 必须先备份、对目标库执行 `prepare_media_schema.py`,再以 `--check` 验证成功后重启 API/Worker;认证业务接口冒烟通过后开放流量,不能只检查 `/api/health`。见[发布与兼容](./MEDIA_MODEL_STRATEGIES.md#发布与兼容) |
+| X-07 | 分集编辑页移除右侧字幕板及 SRT 导出 | 已完成待部署 | P1 | 删除专用预览、导出逻辑及样式,保留顶部字幕生成模式设置。 |
---
@@ -196,3 +201,15 @@ PricingPage 整页定价方案
```
统计(约):**UI 占位入口 40+**;其中本迭代建议优先落地 **约 10~12 项**(Sprint A–C)。
+
+---
+
+## 14. 故障记录与上线约束
+
+### 2026-10-24:媒体计费数据库结构漏迁移
+
+本地 `GET /api/drama/episodes?project_id=422` 返回 500,报错 `UndefinedColumnError`。原因是 `DATABASE_BOOTSTRAP_ENABLED=false`,代码更新后未执行媒体计费增量迁移,`task_runs.billing_snapshot`、`media_provider_tasks` 等七列,以及媒体价格版本表和交付唯一索引未准备齐全。
+
+已在本地执行 `backend/scripts/prepare_media_schema.py`;修复后接口连续两次返回 200、读取 12 集,相关回归 16 条通过。项目 ID 422 仅为本次故障示例;后续上线须使用目标环境的可访问项目冒烟。本地修复不表示线上数据库已经完成迁移。
+
+上线顺序固定为:**备份 → 用目标库凭证执行迁移 → `--check` 成功 → 重启 API/Worker → 认证业务接口冒烟**。迁移或校验失败不得继续,`/api/health` 正常不能代替业务验证。价格发布独立于结构迁移,未启用新计费也必须补齐结构。命令、结构清单和发布记录要求见[媒体模型发布说明](./MEDIA_MODEL_STRATEGIES.md#发布与兼容)。
diff --git a/docs/PRINTFILM_UI_ROADMAP.md b/docs/PRINTFILM_UI_ROADMAP.md
index c041bf7..1b0271e 100644
--- a/docs/PRINTFILM_UI_ROADMAP.md
+++ b/docs/PRINTFILM_UI_ROADMAP.md
@@ -9,6 +9,8 @@
| 设计图 | 路由 | 页面组件 |
|--------|------|----------|
| 首页 | `/` | `frontend/src/pages/HomePage.tsx` |
+| 漫剧项目列表 | `/drama` | `frontend/src/pages/drama/DramaListPage.tsx`(`workflow=script`) |
+| 自由画布列表 | `/canvas` | `frontend/src/pages/drama/CanvasListPage.tsx`(复用列表,`workflow=canvas`) |
| 新建项目 | `/studio/new` | `frontend/src/pages/studio/CreateProjectPage.tsx` |
| 风格配置 | `/studio/:id/style` | `frontend/src/pages/studio/StyleConfigPage.tsx` |
| 分镜工作台 | `/studio/:id` | `frontend/src/pages/studio/StoryboardPage.tsx` |
@@ -21,9 +23,24 @@
共享壳层:`SiteNav` / `AppShell`(`frontend/src/components/layout/`),样式 token 见 `frontend/src/index.css` 与 `frontend/src/styles/printfilm.css`。
+## 2026-10-24 主导航与自由画布入口改版
+
+**状态:已完成待部署,尚未线上发布。** 顶部横向主菜单改为左侧分组导航,创作入口与资源协作入口分开展示;窄屏通过导航抽屉访问。全屏分镜与自由画布编辑器继续使用独立布局。
+
+| 位置 | 入口 |
+|---|---|
+| 创作 | 工作台 `/`、漫剧 `/drama`、自由画布 `/canvas`、AI 短视频 `/history`、小工具 `/tools` |
+| 资源协作 | 资产 `/assets`、团队 `/teams`、定价 `/pricing` |
+| 底部 | 帮助、GitHub、语言切换、账户 |
+
+自由画布提升为一级入口,不再依赖漫剧列表中的二级入口。`/canvas` 展示画布项目,`/drama` 只展示剧本项目;两者复用现有项目列表、创建与管理能力,分别向 `GET /api/drama/projects` 传入 `workflow=canvas`、`workflow=script`,由服务端筛选。旧调用不传 `workflow` 时继续返回全部可访问项目,个人与团队的空间隔离、权限和付款规则沿用现有实现,现有项目编辑地址不变。
+
+部署验收需覆盖两类列表分流、个人/团队空间切换、已有项目直达、桌面左栏及窄屏抽屉;全屏分镜/画布编辑器不应被全局侧栏挤占。对应清单为 [G-05 / G-06](./PLACEHOLDER_BACKLOG.md#2-全局--壳层)。
+
## 已实现(接线现有 API)
-- 登录 / 注册 / 顶栏用户态
+- 登录 / 注册 / 导航账户状态
+- 左侧分组主导航与窄屏抽屉,自由画布一级入口及剧本/画布列表分流(已完成待部署)
- 帮助中心(侧边抽屉 UI,需前端部署上线)
- 模板列表、分类筛选、从模板进入创作
- 创建项目(主题 / 完整文案)→ 风格配置 → `generate` 启动流水线
@@ -34,6 +51,7 @@
- 历史:列表、状态筛选、搜索、类型筛选、继续编辑、预览、删除、批量 zip、**服务端分页**;已发布按 Work 表区分
- 公开作品展示(首页)
- 全局 DialogHost(alert / confirm / prompt)
+- 团队空间:真实成员/邀请、项目与资产分页、个人项目迁入、独立钱包与月额度、编辑占用;见 [TEAM_MODE.md](./TEAM_MODE.md)
## 占位与待开发
@@ -41,10 +59,10 @@
| 优先级 | 方向 |
|--------|------|
-| P0 | 前端部署(帮助抽屉、续跑状态文案)、队列去重 / 项目互斥 |
+| P0 | 前端部署(左侧导航、自由画布一级入口、帮助抽屉、续跑状态文案)、队列去重 / 项目互斥 |
| P1 | 链接/文档导入、BGM+字幕、素材上传替换、加镜调序、导出/分享、定价额度 |
| P2 | 通知、社区、风格商店、平台分发、转场以外的编辑器增强 |
-| P3 | 福利、点赞播放量、转场、时间线精修、团队空间 |
+| P3 | 福利、点赞播放量、转场、时间线精修 |
## 建议迭代优先级(历史)
@@ -62,7 +80,8 @@
- 主色石灰绿:`#B6FF00`(`--pf-lime`)
- 背景:`#F7F8FA`(`--pf-bg`)
- 卡片白底、圆角约 14px、轻阴影
-- 顶栏居中导航 + 右侧「开始创作」
+- 左侧分组主导航:创作、资源协作;次要工具及账户放底部,窄屏使用抽屉
+- 全屏分镜与画布编辑器保留独立布局,不嵌入全局侧栏
- 帮助等次要面板:右侧抽屉(`Modal variant=drawer`),避免居中大弹层挡工作台
字体:Space Grotesk(品牌英文)+ Noto Sans SC(正文)。
diff --git a/frontend/README.md b/frontend/README.md
index 62a258d..5db9dd3 100644
--- a/frontend/README.md
+++ b/frontend/README.md
@@ -14,7 +14,22 @@ npm run lint
npm run build
```
-`npm test` 使用 Node 内建测试运行器及 TypeScript 类型擦除,无需额外测试框架。目前覆盖 API 地址解析、动态登录态、请求头覆盖、文件上传、下载及错误处理;不需要后端服务。
+`npm test` 使用 Node 内建测试运行器及 TypeScript 类型擦除,无需额外测试框架。覆盖 HTTP 传输、空间请求隔离、切换取消、占用冲突文案与并行分集任务状态。后端角色、邀请、钱包与租约校验由 PostgreSQL 集成测试覆盖;支付测试不会创建真实订单。
+
+## 团队模式
+
+- `/teams` 是真实团队目录,必须登录。团队创建、成员邀请、权限/额度、钱包明细、项目和共享资产都通过 `src/api/teams.ts` 访问服务端,并使用服务器分页与搜索。
+- `/teams/:id` 提供概览、项目、资产、成员、钱包和设置。团队项目进入既有 `/drama/projects/:id` 工作台;接口响应的 `team_id` 决定实际空间,不能通过切换菜单把个人内容变成团队内容。
+- `/teams/join?token=…` 与 `/team-invitations?token=…` 支持接受邀请;令牌通过 POST 正文验证,登录邮箱须匹配。接受成功后替换 URL 清除令牌。创建或重发后的加入链接仅保留在内存,不使用浏览器存储恢复邀请凭证。
+- 所有者管理全队财务、成员额度和所有权;管理员管理邀请与普通成员;成员和管理员只查看本人消费。服务端再次执行全部权限检查。
+- 个人和团队钱包独立,团队充值复用 `PaymentModal`,只有用户确认套餐与渠道才创建真实团队订单。页面不会模拟加款。
+- 个人项目可整体转入团队;确认前会明确说明不可转回。项目需没有在途任务或编辑占用。跨项目资产复制由后端校验来源/目标空间,不复制前端携带的任意参数。
+- `workspaceScope.ts` 只在内存保存当前请求空间,切换时取消旧请求;个人请求不携带团队 ID,团队创作带 `X-Team-Id`。现有项目的实际归属优先于导航选择。短视频、工具和任务中心进入个人空间。
+- `editLocks.ts`、`useTeamEditLock.ts` 与 `TeamEditingBoundary.tsx` 为团队写入附加 `X-Edit-Session`、`X-Edit-Token`、`X-Edit-Version`。页面占用每 30 秒续租,120 秒过期,离开时释放;冲突或失锁后进入只读;重新取得占用后先读取最新内容,旧草稿不会自动升级租约后提交。所有者/管理员可确认接管人工占用,系统任务不能强制接管。
+- 分集正文按集 PATCH,正文和该集分镜共用稳定集号占用;不同集的任务状态从 `script.params.episode_jobs` 独立读取。画布保存布局,资产写入走独立的资产接口和占用。
+- 团队页面及团队项目工作台隐藏个人生成队列和个人余额弹窗,避免把个人任务取消、充值入口混入团队空间。已有任务继续由服务端运行。
+
+不再加载示例团队、固定操作者或演示账单,也不将团队数据写入 `sessionStorage`。
## 目录职责
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 6034ac8..d2b5e10 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,4 +1,5 @@
-import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
+import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom'
+import { useLayoutEffect, useSyncExternalStore } from 'react'
import DialogHost from './components/ui/DialogHost'
import BillingAlertHost from './components/billing/BillingAlertHost'
import { DramaGenQueuePanel } from './components/drama/DramaGenQueuePanel'
@@ -21,18 +22,34 @@ import StyleConfigPage from './pages/studio/StyleConfigPage'
import StoryboardPage from './pages/studio/StoryboardPage'
import EditorPage from './pages/studio/EditorPage'
import DramaListPage from './pages/drama/DramaListPage'
+import CanvasListPage from './pages/drama/CanvasListPage'
import AssetLibraryPage from './pages/drama/AssetLibraryPage'
import ProjectWorkspacePage from './pages/drama/ProjectWorkspacePage'
import EpisodeEditPage from './pages/drama/EpisodeEditPage'
import EpisodesPage from './pages/drama/EpisodesPage'
import CanvasPage from './pages/drama/canvas/CanvasPage'
import EpisodeStoryboardPage from './pages/drama/episodeCanvas/EpisodeStoryboardPage'
+import TeamInvitationPage from './features/teams/TeamInvitationPage'
+import RequireAuth from './pages/drama/RequireAuth'
+import { setWorkspaceTeam, subscribeWorkspace, workspaceScope } from './features/teams/workspaceScope'
+import TeamPage from './features/teams/TeamPage'
+import { TeamPreviewProvider } from './features/teams/TeamPreviewContext'
import './styles/printfilm.css'
import './App.css'
+/** 生成队列支持个人和团队空间,余额引导仅在个人业务空间展示。 */
+function PersonalBusinessOverlays() {
+ const { pathname } = useLocation()
+ const teamId = useSyncExternalStore(subscribeWorkspace, () => workspaceScope.teamId)
+ useLayoutEffect(() => { if (!/^\/teams\/\d+/.test(pathname) && !/^\/drama\/projects\/\d+/.test(pathname)) setWorkspaceTeam(null) }, [pathname])
+ const personal = teamId === null && pathname !== '/teams' && !pathname.startsWith('/teams/') && pathname !== '/team-invitations'
+ return <><DramaGenQueuePanel />{personal && <BillingAlertHost />}</>
+}
+
+/** 用户端路由及全局交互宿主,团队界面使用真实认证服务。 */
export default function App() {
return (
- <BrowserRouter>
+ <TeamPreviewProvider><BrowserRouter>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/method" element={<MethodPage />} />
@@ -40,12 +57,17 @@ export default function App() {
<Route path="/templates" element={<TemplatesPage />} />
<Route path="/tools" element={<ToolsPage />} />
<Route path="/tools/:toolId" element={<ToolDetailPage />} />
+ <Route path="/tasks" element={<Navigate to="/settings?tab=tools" replace />} />
<Route path="/assets" element={<AssetLibraryPage />} />
<Route path="/help" element={<HelpPage />} />
<Route path="/terms" element={<TermsPage />} />
<Route path="/privacy" element={<PrivacyPage />} />
<Route path="/contact" element={<ContactPage />} />
<Route path="/settings" element={<SettingsPage />} />
+ <Route path="/teams" element={<RequireAuth><TeamPage /></RequireAuth>} />
+ <Route path="/teams/join" element={<TeamInvitationPage />} />
+ <Route path="/team-invitations" element={<TeamInvitationPage />} />
+ <Route path="/teams/:teamId" element={<RequireAuth><TeamPage /></RequireAuth>} />
<Route path="/pricing" element={<PricingPage />} />
<Route path="/history" element={<HistoryPage />} />
<Route path="/studio/new" element={<CreateProjectPage />} />
@@ -55,6 +77,7 @@ export default function App() {
<Route path="/studio" element={<StudioPage />} />
{/* Agent home (mirrors novel agent entry) */}
<Route path="/drama" element={<DramaListPage />} />
+ <Route path="/canvas" element={<CanvasListPage />} />
<Route path="/drama/dramas" element={<DramaListPage />} />
<Route path="/drama/assets" element={<AssetLibraryPage />} />
<Route path="/drama/projects/:projectId" element={<ProjectWorkspacePage />} />
@@ -68,9 +91,8 @@ export default function App() {
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
<WeChatGroupFab />
- <DramaGenQueuePanel />
- <BillingAlertHost />
+ <PersonalBusinessOverlays />
<DialogHost />
- </BrowserRouter>
+ </BrowserRouter></TeamPreviewProvider>
)
}
diff --git a/frontend/src/api.ts b/frontend/src/api.ts
index f5f5fbe..87ce1ee 100644
--- a/frontend/src/api.ts
+++ b/frontend/src/api.ts
@@ -1,3 +1,4 @@
+import { workspaceScope } from './features/teams/workspaceScope'
import { API_BASE, createJsonRequester, requestResponse, uploadFile } from './api/client'
import { apiErrorMessage } from './api/http'
@@ -65,6 +66,7 @@ export function defaultsFromTemplate(t: Template): {
}
export type Shot = {
+ video_skip_reason?: string | null
id: number
shot_no: number
duration: number
@@ -126,6 +128,8 @@ export type Project = {
extra_prompt?: string
image_model?: string
video_model?: string
+ image_resolution?: string
+ video_resolution?: string
ref_image_url: string | null
created_at: string
updated_at: string
@@ -154,6 +158,15 @@ export type MediaModelOption = {
description: string
provider: string
recommended?: boolean
+ strategy_id?: string
+ strategy_version?: number
+ billing_unit?: 'image' | 'second'
+ prices?: Record<string, string>
+ price_version?: number | null
+ available?: boolean
+ available_resolutions?: string[]
+ reference_limits?: { images: number; audios: number; videos: number }
+ defaults?: { resolution: string; aspect_ratio: string; duration?: number; count: number }
/** 该模型允许的清晰度 */
allowed_resolutions?: string[]
/** 该模型允许的画幅比例 */
@@ -169,6 +182,9 @@ export type MediaModelOption = {
}
export type MediaModelsCatalog = {
+ generation_defaults?: { image_resolution: string; video_resolution: string }
+ price_version?: number | null
+ billing_mode?: 'fixed_media' | 'legacy'
image_models: MediaModelOption[]
video_models: MediaModelOption[]
defaults: {
@@ -367,6 +383,8 @@ export const api = {
extra_prompt?: string
image_model?: string
video_model?: string
+ image_resolution?: string
+ video_resolution?: string
bgm_lock?: string
subtitle_preset?: string
cover_url?: string | null
@@ -587,6 +605,7 @@ export const api = {
task_type: params.task_type,
count: String(params.count ?? 1),
})
+ if (workspaceScope.teamId !== null && params.domain === 'drama') q.set('team_id', String(workspaceScope.teamId))
return request<BillingPreflight>(`/api/billing/preflight?${q.toString()}`)
},
eventsUrl(projectId: number) {
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index fd4358c..11c799f 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -1,6 +1,7 @@
import { throwApiError } from '../lib/apiError'
import { createHttpTransport, resolveApiBase } from './http'
import type { ApiErrorHandler } from './http'
+import { scopedRequestInit } from '../features/teams/workspaceScope'
/** 用户端统一 API 地址;空值为生产同源,未设置时使用开发端口 8000。 */
export const API_BASE = resolveApiBase(
@@ -16,17 +17,17 @@ const transport = createHttpTransport({
})
/** 共用鉴权与错误解析,返回原始响应以支持文件下载。 */
-export const requestResponse = transport.response
+export const requestResponse: typeof transport.response = (path, init, onError) => transport.response(path, scopedRequestInit(path, init), onError)
/** 为业务模块绑定固定错误策略,同时复用 JSON 请求实现。 */
export function createJsonRequester(onError?: ApiErrorHandler) {
// 对外保留泛型返回值,避免每个业务模块重复实现 fetch 包装器。
- return <T>(path: string, init?: RequestInit): Promise<T> => transport.json<T>(path, init, onError)
+ return <T>(path: string, init?: RequestInit): Promise<T> => transport.json<T>(path, scopedRequestInit(path, init), onError)
}
/** 统一单文件上传字段与 multipart 请求,业务模块只提供路径和错误策略。 */
export function uploadFile<T>(path: string, file: File, onError?: ApiErrorHandler): Promise<T> {
const body = new FormData()
body.append('file', file)
- return transport.json<T>(path, { method: 'POST', body }, onError)
+ return transport.json<T>(path, scopedRequestInit(path, { method: 'POST', body }), onError)
}
diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.ts
index e444148..f7c59bf 100644
--- a/frontend/src/api/http.ts
+++ b/frontend/src/api/http.ts
@@ -1,8 +1,15 @@
/** HTTP 基础能力:地址、登录态和响应解析;不依赖浏览器全局配置或业务模块。 */
+import { getMediaPriceVersion, setMediaPriceVersion } from '../lib/mediaPriceVersion.ts'
+
+/** 空间/路由切换的主动取消不属于业务失败,不能显示为红色报错。 */
+export function isRequestAborted(cause: unknown): boolean {
+ return cause !== null && typeof cause === 'object' && 'name' in cause && cause.name === 'AbortError'
+}
/** 将 FastAPI 的字符串或校验错误数组转换为可展示文案。 */
export function apiErrorMessage(detail: unknown, fallback: string): string {
if (typeof detail === 'string') return detail || fallback
+ if (detail && typeof detail === 'object' && 'message' in detail) return String(detail.message || fallback)
if (Array.isArray(detail)) {
const message = detail.map((item) => {
if (item && typeof item === 'object' && 'msg' in item) {
@@ -43,12 +50,24 @@ export function createHttpTransport(options: {
): Promise<Response> {
/* 每次请求重新读取 token,登录、登出后无需重建客户端。 */
const headers = new Headers()
+ const priceVersion = getMediaPriceVersion()
+ if (priceVersion !== null && init?.method && init.method.toUpperCase() !== 'GET') {
+ headers.set('X-Media-Price-Version', String(priceVersion))
+ }
const token = options.getToken()
if (token) headers.set('Authorization', `Bearer ${token}`)
if (!(init?.body instanceof FormData)) headers.set('Content-Type', 'application/json')
new Headers(init?.headers).forEach((value, key) => headers.set(key, value))
- const result = await fetch(`${options.baseUrl}${path}`, { ...init, headers })
+ let result: Response
+ try {
+ result = await fetch(`${options.baseUrl}${path}`, { ...init, headers })
+ } catch (cause) {
+ // 浏览器有时把中断显示为 TypeError/Failed to fetch;仍按原始取消原因处理。
+ if (init?.signal?.aborted) throw init.signal.reason || new DOMException('请求已取消', 'AbortError')
+ throw cause
+ }
if (!result.ok) {
+ if (result.status === 409 && typeof window !== 'undefined') window.dispatchEvent(new Event('media-prices-changed'))
const error = await result.json().catch(() => ({ detail: result.statusText }))
onError(result, error?.detail)
}
@@ -61,7 +80,9 @@ export function createHttpTransport(options: {
init?: RequestInit,
onError?: ApiErrorHandler,
): Promise<T> {
- return (await response(path, init, onError)).json() as Promise<T>
+ const data = await (await response(path, init, onError)).json()
+ if (path === '/api/media-models') setMediaPriceVersion(data.price_version ?? 0)
+ return data as T
}
return { response, json }
diff --git a/frontend/src/components/billing/BillingErrorNotice.tsx b/frontend/src/components/billing/BillingErrorNotice.tsx
index 975d9fc..4238371 100644
--- a/frontend/src/components/billing/BillingErrorNotice.tsx
+++ b/frontend/src/components/billing/BillingErrorNotice.tsx
@@ -1,6 +1,7 @@
import type { CSSProperties } from 'react'
import { Link } from 'react-router-dom'
import { isBillingError, PRICING_PATH } from '../../lib/billingError'
+import { workspaceScope } from '../../features/teams/workspaceScope'
type Props = {
message: string | null | undefined
@@ -33,8 +34,8 @@ export default function BillingErrorNotice({
return (
<Tag className={className} style={style} role={inline ? undefined : 'alert'}>
{text}{' '}
- <Link to={PRICING_PATH} className="pf-link pf-billing-topup-link">
- {linkText}
+ <Link to={workspaceScope.teamId === null ? PRICING_PATH : `/teams/${workspaceScope.teamId}?tab=billing`} className="pf-link pf-billing-topup-link">
+ {workspaceScope.teamId === null ? linkText : '查看团队用量 →'}
</Link>
</Tag>
)
diff --git a/frontend/src/components/billing/PaymentModal.tsx b/frontend/src/components/billing/PaymentModal.tsx
index 32efd8d..dabd24d 100644
--- a/frontend/src/components/billing/PaymentModal.tsx
+++ b/frontend/src/components/billing/PaymentModal.tsx
@@ -3,6 +3,7 @@ import QRCode from 'qrcode'
import Modal from '../ui/Modal'
import PaymentBrandIcon from './PaymentBrandIcon'
import { api } from '../../api'
+import { teamsApi } from '../../api/teams'
export type PayCheckout = {
out_trade_no: string
@@ -20,6 +21,7 @@ export type PayCheckout = {
}
type Props = {
+ teamId?: string
open: boolean
checkout: PayCheckout | null
onClose: () => void
@@ -39,7 +41,7 @@ function formatRemain(sec: number) {
}
/** 扫码支付弹窗:展示二维码或等待收银台回跳,并轮询订单状态 */
-export default function PaymentModal({ open, checkout, onClose, onPaid }: Props) {
+export default function PaymentModal({ open, checkout, onClose, onPaid, teamId }: Props) {
/*
* qrDataUrl 二维码 data URL
* remain 剩余秒数
@@ -63,7 +65,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
const tradeNo = checkout?.out_trade_no
if (tradeNo && status !== 'paid') {
try {
- await api.closeBillingOrder(tradeNo)
+ await (teamId ? teamsApi.closeOrder(teamId, tradeNo) : api.closeBillingOrder(tradeNo))
} catch {
/* 忽略关闭失败,仍允许退出弹窗 */
}
@@ -141,14 +143,14 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
setStatus('expired')
window.clearInterval(tick)
// 倒计时结束:后端自动关闭(拉取一次触发过期清理)
- void api.getBillingOrder(checkout.out_trade_no).catch(() => undefined)
+ void (teamId ? teamsApi.order(teamId, checkout.out_trade_no) : api.getBillingOrder(checkout.out_trade_no)).catch(() => undefined)
}
}, 250)
const poll = window.setInterval(async () => {
if (!checkout.out_trade_no) return
try {
- const order = await api.getBillingOrder(checkout.out_trade_no)
+ const order = await (teamId ? teamsApi.order(teamId, checkout.out_trade_no) : api.getBillingOrder(checkout.out_trade_no))
if (order.status === 'paid') {
setStatus('paid')
window.clearInterval(poll)
@@ -169,7 +171,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
window.clearInterval(tick)
window.clearInterval(poll)
}
- }, [open, checkout])
+ }, [open, checkout, teamId])
/** 主动查询订单到账状态,与后台轮询共用最新支付成功回调。 */
async function confirmPaid() {
@@ -177,7 +179,7 @@ export default function PaymentModal({ open, checkout, onClose, onPaid }: Props)
setChecking(true)
setError('')
try {
- const order = await api.getBillingOrder(checkout.out_trade_no)
+ const order = await (teamId ? teamsApi.order(teamId, checkout.out_trade_no) : api.getBillingOrder(checkout.out_trade_no))
if (order.status === 'paid') {
setStatus('paid')
onPaidRef.current()
diff --git a/frontend/src/components/layout/AppShell.tsx b/frontend/src/components/layout/AppShell.tsx
index 88a376f..cab0370 100644
--- a/frontend/src/components/layout/AppShell.tsx
+++ b/frontend/src/components/layout/AppShell.tsx
@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom'
import { useI18n } from '../../i18n'
import { GITHUB_REPO_URL } from '../../lib/siteLinks'
import SiteNav, { type NavActive } from './SiteNav'
+import './sidebar.css'
type Props = {
children: ReactNode
@@ -17,9 +18,10 @@ export default function AppShell({ children, active, wide, flush, hideFooter }:
const { t } = useI18n()
return (
- <div className="pf-shell">
+ <div className="pf-shell pf-shell--sidebar">
+ <a className="pf-skip-content" href="#pf-main-content">{t('nav.skipContent')}</a>
<SiteNav active={active} />
- <main className={['pf-shell-main', wide ? 'wide' : '', flush ? 'flush' : ''].filter(Boolean).join(' ')}>
+ <main id="pf-main-content" tabIndex={-1} className={['pf-shell-main', wide ? 'wide' : '', flush ? 'flush' : ''].filter(Boolean).join(' ')}>
{children}
</main>
{!hideFooter && !flush ? (
diff --git a/frontend/src/components/layout/SiteNav.tsx b/frontend/src/components/layout/SiteNav.tsx
index 52efdfa..397c8bd 100644
--- a/frontend/src/components/layout/SiteNav.tsx
+++ b/frontend/src/components/layout/SiteNav.tsx
@@ -1,77 +1,138 @@
-import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom'
-import { useEffect, useState } from 'react'
+import { Link, useLocation, useNavigate } from 'react-router-dom'
+import { useEffect, useRef, useState } from 'react'
+import {
+ ArrowUpRight, ChevronRight, CircleHelp, Clapperboard, CreditCard,
+ Images, LayoutDashboard, Menu, Plus, Settings2, UserRound, UsersRound,
+ Video, WandSparkles, Workflow, X,
+} from 'lucide-react'
import { api } from '../../api'
import type { User } from '../../api'
import UserAvatar from '../UserAvatar'
import BrandMark from '../BrandMark'
-import { IconGithub, IconHelp } from '../ui/Icons'
-import Button from '../ui/Button'
+import { IconGithub } from '../ui/Icons'
import CreateChoiceModal from '../ui/CreateChoiceModal'
import { USER_UPDATED_EVENT } from '../../lib/userEvents'
+import { loadSessionUser } from '../../lib/sessionUser'
import { GITHUB_REPO_URL } from '../../lib/siteLinks'
+import { CREATION_NAV, RESOURCE_NAV, resolveNavActive, type NavActive } from '../../lib/siteNavigation'
import { useI18n } from '../../i18n'
import LanguageSwitch from './LanguageSwitch'
+import WorkspaceSwitcher from '../../features/teams/WorkspaceSwitcher'
+import { useTeamPreview } from '../../features/teams/useTeamPreview'
-export type NavActive = 'home' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history'
+export type { NavActive } from '../../lib/siteNavigation'
-type Props = {
- active?: NavActive
-}
+type Props = { active?: NavActive }
+type NavItem = (typeof CREATION_NAV)[number] | (typeof RESOURCE_NAV)[number]
-// 将旧 active 别名归一到新 IA
-function normalizeActive(active: NavActive | undefined, pathname: string): NavActive | undefined {
- if (active === 'studio' || active === 'templates' || active === 'history') return 'kepu'
- if (active) return active
- if (pathname.startsWith('/drama/assets') || pathname.startsWith('/assets')) return 'assets'
- if (pathname.startsWith('/drama')) return 'drama'
- if (
- pathname.startsWith('/studio') ||
- pathname.startsWith('/templates') ||
- pathname.startsWith('/history')
- ) {
- return 'kepu'
- }
- if (pathname.startsWith('/tools')) return 'tools'
- if (pathname.startsWith('/pricing')) return 'pricing'
- if (pathname === '/') return 'home'
- return undefined
+const NAV_ICONS = {
+ home: LayoutDashboard,
+ drama: Clapperboard,
+ canvas: Workflow,
+ kepu: Video,
+ tools: WandSparkles,
+ assets: Images,
+ team: UsersRound,
+ pricing: CreditCard,
}
export default function SiteNav({ active }: Props) {
const nav = useNavigate()
const location = useLocation()
const { t } = useI18n()
- /*
- * user 当前用户
- * menuOpen 移动端抽屉
- * createOpen 开始创作选择弹层
- */
+ const { selectTeam } = useTeamPreview()
const [user, setUser] = useState<User | null>(null)
const [menuOpen, setMenuOpen] = useState(false)
const [createOpen, setCreateOpen] = useState(false)
-
- const current = normalizeActive(active, location.pathname)
-
- useEffect(() => {
- if (!localStorage.getItem('token')) return
- api.me().then(setUser).catch(() => localStorage.removeItem('token'))
- }, [])
+ const sidebarRef = useRef<HTMLElement>(null)
+ const menuButtonRef = useRef<HTMLButtonElement>(null)
+ const closeButtonRef = useRef<HTMLButtonElement>(null)
+ const current = resolveNavActive(location.pathname, active)
+ const currentItem = [...CREATION_NAV, ...RESOURCE_NAV].find((item) => item.key === current)
+ const currentLabel = currentItem ? t(currentItem.label) : current === 'settings' ? t('nav.profile') : current === 'help' ? t('nav.help') : t('nav.workbench')
useEffect(() => {
+ let active = true
+ let generation = 0
+ /** 只有当前请求的明确 401 可以清理会话,切空间导致的取消不会登出。 */
+ function refreshUser() {
+ const currentGeneration = ++generation
+ if (!localStorage.getItem('token')) { setUser(null); return }
+ void loadSessionUser({
+ loadUser: () => api.me(),
+ getToken: () => localStorage.getItem('token'),
+ isCurrent: () => active && currentGeneration === generation,
+ onUser: setUser,
+ onUnauthorized: () => {
+ localStorage.removeItem('token')
+ setUser(null)
+ window.dispatchEvent(new Event(USER_UPDATED_EVENT))
+ },
+ })
+ }
+ /** 用户事件先废弃旧请求,避免旧账号覆盖新登录或最新资料。 */
const onUserUpdated = (event: Event) => {
+ generation += 1
const detail = (event as CustomEvent<User>).detail
- if (detail) setUser(detail)
+ if (detail && localStorage.getItem('token')) setUser(detail)
+ else refreshUser()
}
window.addEventListener(USER_UPDATED_EVENT, onUserUpdated)
- return () => window.removeEventListener(USER_UPDATED_EVENT, onUserUpdated)
+ refreshUser()
+ return () => { active = false; generation += 1; window.removeEventListener(USER_UPDATED_EVENT, onUserUpdated) }
}, [])
+ useEffect(() => { setMenuOpen(false) }, [location.pathname, location.search])
+
useEffect(() => {
- setMenuOpen(false)
- }, [location.pathname])
+ const desktop = window.matchMedia('(min-width: 1001px)')
+ function closeOnDesktop() { if (desktop.matches) setMenuOpen(false) }
+ desktop.addEventListener('change', closeOnDesktop)
+ return () => desktop.removeEventListener('change', closeOnDesktop)
+ }, [])
+
+ useEffect(() => {
+ if (!menuOpen) return
+ const previousOverflow = document.body.style.overflow
+ document.body.style.overflow = 'hidden'
+ closeButtonRef.current?.focus()
+
+ function keepFocusInside(event: KeyboardEvent) {
+ // 独立弹窗接管自己的键盘事件;普通下拉仍归属当前抽屉。
+ const modal = document.querySelector<HTMLElement>('[role="dialog"][aria-modal="true"]:not(#pf-app-sidebar)')
+ if (modal && !sidebarRef.current?.contains(modal)) return
+ if (event.key === 'Escape') {
+ event.preventDefault()
+ setMenuOpen(false)
+ return
+ }
+ if (event.key !== 'Tab' || !sidebarRef.current) return
+ const focusable = Array.from(sidebarRef.current.querySelectorAll<HTMLElement>(
+ 'a[href], button:not(:disabled), summary, input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])',
+ )).filter((element) => element.getClientRects().length > 0 && !element.closest('[inert]'))
+ const first = focusable[0]
+ const last = focusable[focusable.length - 1]
+ if (!first || !last) { event.preventDefault(); return }
+ const focused = document.activeElement
+ if (!sidebarRef.current.contains(focused) || (event.shiftKey && focused === first)) {
+ event.preventDefault()
+ ;(event.shiftKey ? last : first).focus()
+ } else if (!event.shiftKey && focused === last) {
+ event.preventDefault()
+ first.focus()
+ }
+ }
+
+ document.addEventListener('keydown', keepFocusInside)
+ return () => {
+ document.body.style.overflow = previousOverflow
+ document.removeEventListener('keydown', keepFocusInside)
+ menuButtonRef.current?.focus()
+ }
+ }, [menuOpen])
- // 未登录去登录;已登录弹出漫剧/科普选择
function goCreate() {
+ setMenuOpen(false)
if (!user && !localStorage.getItem('token')) {
nav('/auth?next=/')
return
@@ -79,96 +140,56 @@ export default function SiteNav({ active }: Props) {
setCreateOpen(true)
}
- const isActive = (key: NavActive) => (current === key ? 'active' : undefined)
-
- const centerLinks = (
- <>
- <NavLink to="/" end className={() => isActive('home')}>
- {t('nav.workbench')}
- </NavLink>
- <NavLink to="/drama" className={() => isActive('drama')}>
- {t('nav.drama')}
- </NavLink>
- <NavLink to="/history" className={() => isActive('kepu')}>
- {t('nav.kepu')}
- </NavLink>
- <NavLink to="/tools" className={() => isActive('tools')}>
- {t('nav.tools')}
- </NavLink>
- <NavLink to="/assets" className={() => isActive('assets')}>
- {t('nav.assets')}
- </NavLink>
- <NavLink to="/pricing" className={() => isActive('pricing')}>
- {t('nav.pricing')}
- </NavLink>
- </>
- )
+ function renderLink(item: NavItem) {
+ const Icon = NAV_ICONS[item.key]
+ const selected = current === item.key
+ return <Link
+ key={item.key}
+ to={item.path}
+ className={`pf-sidebar-link${selected ? ' is-active' : ''}`}
+ aria-current={selected ? 'page' : undefined}
+ onClick={() => {
+ if (item.key !== 'team' && item.key !== 'home') selectTeam(null)
+ setMenuOpen(false)
+ }}
+ >
+ <Icon size={19} strokeWidth={1.8} aria-hidden />
+ <span>{t(item.label)}</span>
+ {selected && <ChevronRight size={15} className="pf-sidebar-link-arrow" aria-hidden />}
+ </Link>
+ }
- return (
- <header className="pf-nav">
- <div className="pf-nav-left">
- <BrandMark />
+ return <>
+ <header className="pf-app-mobile-header">
+ <button ref={menuButtonRef} type="button" className="pf-sidebar-icon-button" aria-label={t('nav.openMenu')} aria-controls="pf-app-sidebar" aria-expanded={menuOpen} onClick={() => setMenuOpen(true)}><Menu size={21} aria-hidden /></button>
+ <BrandMark />
+ <span className="pf-mobile-current">{currentLabel}</span>
+ <button type="button" className="pf-mobile-create" aria-label={t('nav.startCreate')} onClick={goCreate}><Plus size={20} aria-hidden /></button>
+ </header>
+ {menuOpen && <button type="button" className="pf-sidebar-backdrop" aria-label={t('nav.closeMenu')} tabIndex={-1} onClick={() => setMenuOpen(false)} />}
+ <aside ref={sidebarRef} id="pf-app-sidebar" className={`pf-app-sidebar${menuOpen ? ' is-open' : ''}`} role={menuOpen ? 'dialog' : undefined} aria-modal={menuOpen ? true : undefined} aria-label={t('nav.main')}>
+ <div className="pf-sidebar-top">
+ <div className="pf-sidebar-brand"><BrandMark /><button ref={closeButtonRef} type="button" className="pf-sidebar-icon-button pf-sidebar-close" aria-label={t('nav.closeMenu')} onClick={() => setMenuOpen(false)}><X size={19} aria-hidden /></button></div>
+ <div className="pf-sidebar-workspace"><WorkspaceSwitcher /></div>
+ <button type="button" className="pf-sidebar-create" onClick={goCreate}><Plus size={19} aria-hidden /><span>{t('nav.startCreate')}</span><ArrowUpRight size={17} aria-hidden /></button>
</div>
- <nav className="pf-nav-center" aria-label={t('nav.main')}>
- {centerLinks}
+ <nav className="pf-sidebar-navigation" aria-label={t('nav.main')}>
+ <div className="pf-sidebar-group"><span className="pf-sidebar-group-label">{t('nav.creation')}</span>{CREATION_NAV.map(renderLink)}</div>
+ <div className="pf-sidebar-group"><span className="pf-sidebar-group-label">{t('nav.resources')}</span>{RESOURCE_NAV.map(renderLink)}</div>
</nav>
- <div className="pf-nav-right">
- <LanguageSwitch />
- <a
- className="pf-nav-github"
- href={GITHUB_REPO_URL}
- target="_blank"
- rel="noopener noreferrer"
- title={t('nav.githubTitle')}
- aria-label={t('nav.githubTitle')}
- >
- <IconGithub size={18} />
- <span>{t('nav.github')}</span>
- </a>
- <button type="button" className="pf-nav-help-btn" title={t('nav.helpCenter')} onClick={() => nav('/help')}>
- <IconHelp size={18} className="pf-nav-help-icon" />
- <span>{t('nav.help')}</span>
- </button>
- {user ? (
- <button
- type="button"
- className="pf-avatar"
- title={`${user.nickname} · ${t('nav.profile')}`}
- onClick={() => nav('/settings')}
- >
- <UserAvatar user={user} size="sm" />
- </button>
- ) : (
- <Link to="/auth?next=/" className="pf-link pf-nav-login">
- {t('nav.login')}
- </Link>
- )}
- <Button variant="lime" size="sm" icon onClick={goCreate}>
- {t('nav.startCreate')}
- </Button>
- <button
- type="button"
- className="pf-nav-burger"
- aria-label={menuOpen ? t('nav.closeMenu') : t('nav.openMenu')}
- aria-expanded={menuOpen}
- onClick={() => setMenuOpen((v) => !v)}
- >
- <span />
- <span />
- <span />
- </button>
- </div>
- {menuOpen ? (
- <div className="pf-nav-drawer" role="dialog" aria-label={t('nav.mobileNav')}>
- <nav className="pf-nav-drawer-links">
- {centerLinks}
- <a href={GITHUB_REPO_URL} target="_blank" rel="noopener noreferrer">
- {t('nav.github')}
- </a>
- </nav>
+ <div className="pf-sidebar-bottom">
+ <div className="pf-sidebar-utilities">
+ <Link to="/help" className={current === 'help' ? 'is-active' : undefined} aria-current={current === 'help' ? 'page' : undefined} onClick={() => setMenuOpen(false)}><CircleHelp size={17} aria-hidden /><span>{t('nav.help')}</span></Link>
+ <a href={GITHUB_REPO_URL} target="_blank" rel="noopener noreferrer" title={t('nav.githubTitle')} onClick={() => setMenuOpen(false)}><IconGithub size={17} /><span>{t('nav.github')}</span></a>
</div>
- ) : null}
- <CreateChoiceModal open={createOpen} onClose={() => setCreateOpen(false)} />
- </header>
- )
+ <div className="pf-sidebar-language"><span>{t('nav.language')}</span><LanguageSwitch /></div>
+ <Link to={user ? '/settings' : '/auth?next=/'} className={`pf-sidebar-account${current === 'settings' ? ' is-active' : ''}`} aria-current={current === 'settings' ? 'page' : undefined} onClick={() => setMenuOpen(false)}>
+ {user ? <UserAvatar user={user} size="sm" /> : <span className="pf-sidebar-account-guest"><UserRound size={19} aria-hidden /></span>}
+ <span><strong>{user?.nickname || t('nav.login')}</strong><small>{user ? t('nav.profile') : t('nav.loginHint')}</small></span>
+ <Settings2 size={17} aria-hidden />
+ </Link>
+ </div>
+ </aside>
+ <CreateChoiceModal open={createOpen} onClose={() => setCreateOpen(false)} />
+ </>
}
diff --git a/frontend/src/components/layout/sidebar.css b/frontend/src/components/layout/sidebar.css
new file mode 100644
index 0000000..2a54390
--- /dev/null
+++ b/frontend/src/components/layout/sidebar.css
@@ -0,0 +1,124 @@
+/* 应用侧栏:纸白与石墨底色,荧光绿标记创作和当前位置。 */
+.pf-shell.pf-shell--sidebar {
+ --pf-sidebar-width: 236px;
+ --pf-content-top: 0px;
+ padding-inline-start: var(--pf-sidebar-width);
+}
+
+.pf-shell--sidebar .pf-shell-main:not(.flush) { padding: 34px clamp(24px, 3vw, 48px) 48px; }
+.pf-shell--sidebar .pf-shell-main { min-width: 0; }
+.pf-shell--sidebar .pf-shell-main:focus { outline: none; }
+.pf-shell--sidebar .pf-settings-side,
+.pf-shell--sidebar .pf-history-side { top: calc(var(--pf-content-top) + 24px); }
+.pf-shell--sidebar .pf-team-sidebar { top: calc(var(--pf-content-top) + 24px); }
+.pf-shell--sidebar .gen-rail { top: calc(var(--pf-content-top) + 20px); }
+.pf-shell--sidebar .pf-create { min-height: calc(100dvh - var(--pf-content-top) - 5rem); }
+.pf-shell--sidebar .pf-editor,
+.pf-shell--sidebar .drama-workspace { min-height: calc(100dvh - var(--pf-content-top)); }
+
+.pf-app-sidebar {
+ position: fixed;
+ inset: 0 auto 0 0;
+ z-index: 45;
+ display: flex;
+ flex-direction: column;
+ width: var(--pf-sidebar-width);
+ height: 100vh;
+ height: 100dvh;
+ background: #fff;
+ border-right: 1px solid #e6e8e9;
+ color: #18201b;
+}
+
+.pf-sidebar-top { flex: none; padding: 28px 18px 10px; }
+.pf-sidebar-brand { display: flex; align-items: center; justify-content: space-between; padding: 0 5px; margin-bottom: 27px; }
+.pf-sidebar-brand .brand-mark { gap: 10px; }
+.pf-sidebar-brand .brand-logo { width: 30px; height: 30px; }
+.pf-sidebar-brand .brand-word { font-size: 16px; letter-spacing: .065em; }
+.pf-sidebar-workspace { margin-bottom: 18px; }
+.pf-sidebar-workspace .pf-team-switcher { width: 100%; }
+.pf-sidebar-workspace .pf-team-switcher summary { padding: 10px; gap: 9px; background: #f7f8f5; border-color: #e9ece5; border-radius: 10px; font-size: 12px; color: #515c4c; }
+.pf-sidebar-workspace .pf-team-switcher-label { flex: 1; max-width: none; }
+.pf-sidebar-workspace .pf-team-switcher summary > svg:last-child { margin-left: auto; }
+.pf-sidebar-workspace .pf-team-switcher-menu { left: 0; width: 280px; max-width: calc(100vw - 48px); }
+.pf-sidebar-create { display: flex; align-items: center; gap: 10px; width: 100%; min-height: 43px; padding: 11px 14px; border: 1px solid #a8ec00; border-radius: 10px; background: var(--pf-lime); color: #172300; font-size: 13px; font-weight: 650; transition: background .15s, transform .15s; }
+.pf-sidebar-create > svg:last-child { margin-left: auto; }
+.pf-sidebar-create:hover { background: #aaf000; transform: translateY(-1px); }
+.pf-sidebar-navigation { flex: 1; min-height: 0; padding: 8px 14px 12px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: #e0e5dc transparent; }
+.pf-sidebar-group + .pf-sidebar-group { margin-top: 21px; }
+.pf-sidebar-group-label { display: block; padding: 9px 14px 10px; color: #90978f; font-size: 10px; font-weight: 550; letter-spacing: .1em; }
+.pf-sidebar-link { position: relative; display: flex; align-items: center; gap: 12px; min-height: 44px; margin: 3px 0; padding: 11px 13px; border: 1px solid transparent; border-radius: 9px; color: #6e756e; font-size: 13px; transition: background .15s, color .15s, border-color .15s; }
+.pf-sidebar-link > svg { flex: none; }
+.pf-sidebar-link > span { min-width: 0; }
+.pf-sidebar-link:hover { color: #20291a; background: #f5f7f1; }
+.pf-sidebar-link.is-active { color: #253319; font-weight: 650; background: #eef9dc; border-color: #e3f0d0; }
+.pf-sidebar-link.is-active > svg:first-child { color: #5c762e; }
+.pf-sidebar-link-arrow { margin-left: auto; color: #6f8d3d; }
+.pf-sidebar-bottom { flex: none; margin: 0 18px; padding: 11px 0 17px; border-top: 1px solid #edf0e8; }
+.pf-sidebar-utilities { display: grid; grid-template-columns: .9fr 1.1fr; gap: 5px; }
+.pf-sidebar-utilities > a { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 33px; border-radius: 7px; color: #858c80; font-size: 11px; }
+.pf-sidebar-utilities > a:hover, .pf-sidebar-utilities > a.is-active { background: #f4f7ed; color: #3f512b; }
+.pf-sidebar-language { display: flex; justify-content: space-between; align-items: center; padding: 13px 9px 14px; color: #999f94; font-size: 10px; }
+.pf-sidebar-language .pf-nav-lang { height: 24px; border-color: #e8ebe3; }
+.pf-sidebar-language .pf-nav-lang button { font-size: 10px; padding-inline: 8px; }
+.pf-sidebar-account { display: flex; align-items: center; gap: 10px; padding: 11px 9px; border: 1px solid #edf0e7; border-radius: 10px; background: #fafbf8; }
+.pf-sidebar-account > span:not(.pf-user-avatar) { display: grid; gap: 3px; flex: 1; min-width: 0; }
+.pf-sidebar-account strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; }
+.pf-sidebar-account small { color: #9bA18f; font-size: 10px; }
+.pf-sidebar-account > svg { color: #969e89; flex: none; }
+.pf-sidebar-account:hover, .pf-sidebar-account.is-active { border-color: #cfdcb8; background: #f5f9ed; }
+.pf-sidebar-account .pf-user-avatar { width: 31px; height: 31px; flex: none; }
+.pf-sidebar-account > .pf-sidebar-account-guest { display: grid; place-items: center; width: 31px; height: 31px; flex: none; background: #edf1e5; border-radius: 50%; color: #7a8c61; }
+.pf-sidebar-icon-button { display: inline-flex; align-items: center; justify-content: center; width: 34px; height: 34px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: #68735c; }
+.pf-sidebar-icon-button:hover { background: #eef2e6; }
+.pf-sidebar-close, .pf-app-mobile-header, .pf-sidebar-backdrop { display: none; }
+.pf-app-sidebar :focus-visible, .pf-app-mobile-header :focus-visible { outline: 2px solid #708e3b; outline-offset: 3px; }
+.pf-skip-content { position: fixed; top: -60px; left: calc(var(--pf-sidebar-width) + 20px); z-index: 100; padding: 10px 16px; border-radius: 8px; background: #18201b; color: #fff; }
+.pf-skip-content:focus { top: 12px; }
+.pf-project-list-intro { margin: 8px 0 0; font-size: 13px; color: #8b9288; line-height: 1.7; }
+.pf-dialog-root .pf-create-choice { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+.pf-dialog-root .pf-create-choice-card { min-width: 0; padding: 16px 13px; }
+.pf-dialog-root .pf-create-choice-card .pf-muted { font-size: 11px; line-height: 1.7; }
+
+@media (min-width: 1001px) and (max-width: 1350px) {
+ .pf-shell--sidebar .pf-create, .pf-shell--sidebar .pf-editor,
+ .pf-shell--sidebar .pf-history-layout { grid-template-columns: minmax(0, 1fr); }
+ .pf-shell--sidebar .pf-history-side { position: static; }
+ .pf-shell--sidebar .pf-team-layout { grid-template-columns: 170px minmax(0, 1fr); gap: 18px; }
+ .pf-shell--sidebar .pf-team-settings-grid { grid-template-columns: minmax(0, 1fr); }
+ .pf-shell--sidebar .pf-team-directory-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ .pf-shell--sidebar .pf-settings { grid-template-columns: 190px minmax(0, 1fr); gap: 24px; }
+}
+
+@media (max-width: 1000px) {
+ .pf-shell.pf-shell--sidebar { --pf-content-top: 60px; padding-inline-start: 0; }
+ .pf-app-mobile-header { position: sticky; top: 0; z-index: 40; display: flex; align-items: center; gap: 12px; height: 60px; flex: none; padding: 0 18px; background: #ffffffef; border-bottom: 1px solid #e5e9df; backdrop-filter: blur(12px); }
+ .pf-app-mobile-header .brand-mark { gap: 8px; }
+ .pf-app-mobile-header .brand-word { font-size: 13px; letter-spacing: .07em; }
+ .pf-app-mobile-header .brand-logo { width: 26px; height: 26px; }
+ .pf-mobile-current { margin-left: 4px; padding-left: 14px; border-left: 1px solid #e2e7d9; color: #939b87; font-size: 11px; }
+ .pf-mobile-create { display: grid; place-items: center; width: 32px; height: 32px; margin-left: auto; padding: 0; flex: none; background: var(--pf-lime); border: 0; border-radius: 9px; color: #26340f; }
+ .pf-app-sidebar { width: 260px; z-index: 90; visibility: hidden; transform: translateX(-100%); transition: transform .2s ease, visibility .2s; }
+ .pf-app-sidebar.is-open { visibility: visible; transform: translateX(0); box-shadow: 12px 0 60px #18201b20; }
+ .pf-sidebar-close { display: inline-flex; }
+ .pf-sidebar-top { padding-top: 21px; }
+ .pf-sidebar-brand { margin-bottom: 23px; }
+ .pf-sidebar-workspace .pf-team-switcher-menu { width: 224px; }
+ .pf-sidebar-backdrop { position: fixed; inset: 0; z-index: 85; display: block; width: 100%; height: 100%; border: 0; background: #15201045; backdrop-filter: blur(2px); }
+ .pf-shell--sidebar .pf-shell-main:not(.flush) { padding: 26px 22px 40px; }
+ .pf-shell--sidebar .pf-settings { grid-template-columns: minmax(0, 1fr); }
+ .pf-shell--sidebar .pf-settings-side { position: static; }
+ .pf-skip-content { left: 16px; }
+}
+
+@media (max-width: 560px) {
+ .pf-shell--sidebar .pf-shell-main:not(.flush) { padding: 23px 16px 36px; }
+ .pf-app-mobile-header { padding-inline: 12px; gap: 7px; }
+ .pf-mobile-current { max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10px; padding-left: 10px; }
+ .pf-dialog-root .pf-create-choice { grid-template-columns: minmax(0, 1fr); }
+ .pf-sidebar-workspace .pf-team-switcher-menu { left: 0; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .pf-app-sidebar, .pf-sidebar-create, .pf-sidebar-link { transition: none; }
+}
diff --git a/frontend/src/components/ui/CreateChoiceModal.tsx b/frontend/src/components/ui/CreateChoiceModal.tsx
index 60d8cff..e481020 100644
--- a/frontend/src/components/ui/CreateChoiceModal.tsx
+++ b/frontend/src/components/ui/CreateChoiceModal.tsx
@@ -1,5 +1,5 @@
import { Link, useNavigate } from 'react-router-dom'
-import { Clapperboard, Video } from 'lucide-react'
+import { Clapperboard, PanelsTopLeft, Video } from 'lucide-react'
import { useI18n } from '../../i18n'
import Modal from './Modal'
@@ -8,7 +8,7 @@ type Props = {
onClose: () => void
}
-/** 开始创作:在漫剧与科普之间选择入口 */
+/** 开始创作:选择漫剧、自由画布或短视频。 */
export default function CreateChoiceModal({ open, onClose }: Props) {
const nav = useNavigate()
const { t } = useI18n()
@@ -32,6 +32,11 @@ export default function CreateChoiceModal({ open, onClose }: Props) {
<strong>{t('create.drama')}</strong>
<span className="pf-muted">{t('create.dramaHint')}</span>
</button>
+ <button type="button" className="pf-create-choice-card" onClick={() => go('/canvas')}>
+ <span className="pf-ws-product-icon" aria-hidden><PanelsTopLeft size={24} strokeWidth={1.6} /></span>
+ <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')}>
<span className="pf-ws-product-icon" aria-hidden>
<Video size={24} strokeWidth={1.6} />
diff --git a/frontend/src/i18n/locales/en/pages.ts b/frontend/src/i18n/locales/en/pages.ts
index 223cbdc..549d28a 100644
--- a/frontend/src/i18n/locales/en/pages.ts
+++ b/frontend/src/i18n/locales/en/pages.ts
@@ -252,6 +252,11 @@ export const enPages = {
notLoggedIn: 'Not signed in',
},
items: {
+ audio: {
+ title: 'Audio generation', desc: 'Give your words a voice',
+ panelHint: 'Enter text and choose a voice.', cta: 'Generate speech',
+ fields: { prompt: { label: 'Text to read', placeholder: 'Enter the text you want to read…' } },
+ },
t2i: {
title: 'Text to image',
desc: 'Describe a scene and generate a still',
@@ -435,6 +440,9 @@ export const enPages = {
},
dramaList: {
title: 'My drama projects',
+ description: 'Manage your series from the first story idea to the storyboard.',
+ emptyTitle: 'No drama projects yet',
+ emptyDescription: 'Write a story idea to create your first drama.',
assets: 'Asset library',
canvas: 'Free canvas',
creating: 'Creating…',
@@ -464,6 +472,16 @@ export const enPages = {
deleteMany: 'Delete {count} selected projects, including episodes, scripts, and assets? This cannot be undone.',
deleteFailed: 'Delete failed',
},
+ canvasList: {
+ title: 'Free canvas',
+ description: 'Bring ideas, images, and videos together. Connect them your way.',
+ newCanvas: 'New canvas',
+ searchPlaceholder: 'Search canvases',
+ emptyFilter: 'Empty',
+ emptyTitle: 'Start with a blank canvas',
+ emptyDescription: 'Add references and connect images and videos at your own pace.',
+ usageTitle: 'Total canvas costs and generations',
+ },
legal: {
updatedAt: 'Updated {date}',
related: 'Related pages',
diff --git a/frontend/src/i18n/locales/en/shell.ts b/frontend/src/i18n/locales/en/shell.ts
index f0bc611..e1d389f 100644
--- a/frontend/src/i18n/locales/en/shell.ts
+++ b/frontend/src/i18n/locales/en/shell.ts
@@ -48,8 +48,15 @@ export const enShell = {
nav: {
workbench: 'Home',
drama: 'Drama',
+ canvas: 'Free canvas',
+ creation: 'CREATE',
+ resources: 'LIBRARY & TEAM',
+ team: 'Team spaces',
+ loginHint: 'Sign in to keep creating',
+ skipContent: 'Skip to main content',
kepu: 'AI Short Video',
tools: 'Tools',
+ tasks: 'My tasks',
assets: 'Assets',
pricing: 'Pricing',
help: 'Help',
@@ -119,6 +126,8 @@ export const enShell = {
hint: 'Pick a product and enter its workflow',
drama: 'AI Drama',
dramaHint: 'Script · episodes · film',
+ canvas: 'Free canvas',
+ canvasHint: 'Infinite canvas · images · video',
kepu: 'AI Short Video',
kepuHint: 'Storyboard pipeline',
toolsFootPrefix: 'Or browse standalone tools in the',
diff --git a/frontend/src/i18n/locales/zh/pages.ts b/frontend/src/i18n/locales/zh/pages.ts
index 4c76083..dc9165b 100644
--- a/frontend/src/i18n/locales/zh/pages.ts
+++ b/frontend/src/i18n/locales/zh/pages.ts
@@ -245,6 +245,11 @@ export const zhPages = {
notLoggedIn: '未登录',
},
items: {
+ audio: {
+ title: '音频生成', desc: '选择音色,让文字成为有温度的声音',
+ panelHint: '输入文字,选择音色,生成配音。', cta: '生成语音',
+ fields: { prompt: { label: '朗读文字', placeholder: '输入你想朗读的文字…' } },
+ },
t2i: {
title: '文生图',
desc: '用文字描述生成高质量画面',
@@ -428,6 +433,9 @@ export const zhPages = {
},
dramaList: {
title: '我的漫剧项目',
+ description: '从故事到分镜,管理你的系列漫剧创作。',
+ emptyTitle: '还没有漫剧项目',
+ emptyDescription: '写下故事创意,创建你的第一部漫剧。',
assets: '资产库',
canvas: '自由画布',
creating: '创建中…',
@@ -457,6 +465,16 @@ export const zhPages = {
deleteMany: '将删除已选择的 {count} 个项目,包含分集、剧本与资产等数据,删除后无法恢复。',
deleteFailed: '删除失败',
},
+ canvasList: {
+ title: '自由画布',
+ description: '把灵感、图片和视频放进同一张画布,自由连接与创作。',
+ newCanvas: '新建画布',
+ searchPlaceholder: '搜索画布名称',
+ emptyFilter: '空画布',
+ emptyTitle: '从一张空白画布开始',
+ emptyDescription: '放入参考素材,连接图片与视频,按自己的节奏展开创作。',
+ usageTitle: '此画布累计费用与生成次数',
+ },
legal: {
updatedAt: '更新日期:{date}',
related: '相关页面',
diff --git a/frontend/src/i18n/locales/zh/shell.ts b/frontend/src/i18n/locales/zh/shell.ts
index f0fe156..aa5e4e2 100644
--- a/frontend/src/i18n/locales/zh/shell.ts
+++ b/frontend/src/i18n/locales/zh/shell.ts
@@ -47,8 +47,15 @@ export const zhShell = {
nav: {
workbench: '工作台',
drama: '漫剧',
+ canvas: '自由画布',
+ creation: '创作',
+ resources: '资源与协作',
+ team: '团队空间',
+ loginHint: '登录,继续你的创作',
+ skipContent: '跳转到主要内容',
kepu: 'AI短视频',
- tools: '工具',
+ tools: '小工具',
+ tasks: '我的任务',
assets: '资产',
pricing: '定价',
help: '帮助',
@@ -118,6 +125,8 @@ export const zhShell = {
hint: '选择一个产品线,进入对应工作流',
drama: 'AI 漫剧',
dramaHint: '剧本 · 分集 · 成片',
+ canvas: '自由画布',
+ canvasHint: '无限画布 · 图像 · 视频',
kepu: 'AI短视频',
kepuHint: '分镜流水线出片',
toolsFootPrefix: '也可以先去',
diff --git a/frontend/src/lib/apiError.ts b/frontend/src/lib/apiError.ts
index 2c58778..f6e1884 100644
--- a/frontend/src/lib/apiError.ts
+++ b/frontend/src/lib/apiError.ts
@@ -1,9 +1,10 @@
import { notifyBillingErrorIfNeeded } from './billingError'
import { apiErrorMessage } from '../api/http'
+import { workspaceScope } from '../features/teams/workspaceScope'
/** 解析 FastAPI detail 并抛出;402 / 余额不足时弹出充值引导 */
export function throwApiError(status: number, detail: unknown, fallback = '请求失败'): never {
const finalMessage = apiErrorMessage(detail, fallback)
- notifyBillingErrorIfNeeded(status, finalMessage)
- throw new Error(finalMessage)
+ if (workspaceScope.teamId === null) notifyBillingErrorIfNeeded(status, finalMessage)
+ throw Object.assign(new Error(finalMessage), { status })
}
diff --git a/frontend/src/lib/billingError.ts b/frontend/src/lib/billingError.ts
index dff81a4..7ff3a2c 100644
--- a/frontend/src/lib/billingError.ts
+++ b/frontend/src/lib/billingError.ts
@@ -1,4 +1,5 @@
import { dialog } from './dialog'
+import { workspaceScope } from '../features/teams/workspaceScope'
export const PRICING_PATH = '/pricing'
@@ -10,7 +11,7 @@ export function isBillingError(message: string) {
/** 跳转定价页充值 */
export function goToTopup() {
if (typeof window !== 'undefined') {
- window.location.assign(PRICING_PATH)
+ window.location.assign(workspaceScope.teamId === null ? PRICING_PATH : `/teams/${workspaceScope.teamId}?tab=billing`)
}
}
@@ -24,6 +25,10 @@ export async function handleBillingError(
): Promise<boolean> {
const message = err instanceof Error ? err.message : String(err || '')
if (!isBillingError(message)) return false
+ if (workspaceScope.teamId !== null) {
+ await dialog.alert({ title: '团队消费受限', message: `${message}。请在团队钱包查看本人额度;团队余额与充值由所有者管理。`, confirmText: '知道了' })
+ return true
+ }
const go = await dialog.confirm({
title: '余额不足',
message: message || '当前余额不足以开始生成,请先充值。',
diff --git a/frontend/src/lib/sessionUser.ts b/frontend/src/lib/sessionUser.ts
new file mode 100644
index 0000000..7d87bc8
--- /dev/null
+++ b/frontend/src/lib/sessionUser.ts
@@ -0,0 +1,19 @@
+/** 用户资料请求失败只在当前凭证明确过期时结束会话,临时故障不影响登录。 */
+export async function loadSessionUser<T>(options: {
+ loadUser: () => Promise<T>
+ getToken: () => string | null
+ isCurrent: () => boolean
+ onUser: (user: T) => void
+ onUnauthorized: () => void
+}): Promise<void> {
+ const token = options.getToken()
+ if (!token) return
+ /** 账号事件、卸载和新登录都使旧响应失效。 */
+ const isCurrentSession = () => options.isCurrent() && token === options.getToken()
+ try {
+ const user = await options.loadUser()
+ if (isCurrentSession()) options.onUser(user)
+ } catch (cause) {
+ if (isCurrentSession() && cause !== null && typeof cause === 'object' && 'status' in cause && cause.status === 401) options.onUnauthorized()
+ }
+}
diff --git a/frontend/src/lib/siteNavigation.ts b/frontend/src/lib/siteNavigation.ts
new file mode 100644
index 0000000..a5b46c9
--- /dev/null
+++ b/frontend/src/lib/siteNavigation.ts
@@ -0,0 +1,35 @@
+/** 主导航路由:自由画布与漫剧并列,旧短视频入口仍归属同一导航项。 */
+export type NavActive = 'home' | 'canvas' | 'drama' | 'kepu' | 'tools' | 'assets' | 'pricing' | 'templates' | 'studio' | 'history' | 'team' | 'tasks' | 'help' | 'settings'
+
+export const CREATION_NAV = [
+ { key: 'home', path: '/', label: 'nav.workbench' },
+ { key: 'drama', path: '/drama', label: 'nav.drama' },
+ { key: 'canvas', path: '/canvas', label: 'nav.canvas' },
+ { key: 'kepu', path: '/history', label: 'nav.kepu' },
+ { key: 'tools', path: '/tools', label: 'nav.tools' },
+] as const
+
+export const RESOURCE_NAV = [
+ { key: 'assets', path: '/assets', label: 'nav.assets' },
+ { key: 'team', path: '/teams', label: 'nav.team' },
+ { key: 'pricing', path: '/pricing', label: 'nav.pricing' },
+] as const
+
+/** 路由段精确匹配,避免 /canvas-unknown 等非业务地址误高亮。 */
+export function resolveNavActive(pathname: string, active?: NavActive): NavActive | undefined {
+ if (active === 'studio' || active === 'templates' || active === 'history') return 'kepu'
+ if (active) return active
+ const within = (base: string) => pathname === base || pathname.startsWith(`${base}/`)
+ if (within('/canvas')) return 'canvas'
+ if (within('/teams') || within('/team-invitations')) return 'team'
+ if (within('/drama/assets') || within('/assets')) return 'assets'
+ if (within('/drama')) return 'drama'
+ if (['/studio', '/templates', '/history'].some(within)) return 'kepu'
+ if (within('/tools')) return 'tools'
+ if (within('/tasks')) return 'tasks'
+ if (within('/pricing')) return 'pricing'
+ if (within('/help')) return 'help'
+ if (within('/settings')) return 'settings'
+ if (pathname === '/') return 'home'
+ return undefined
+}
diff --git a/frontend/src/pages/AuthPage.tsx b/frontend/src/pages/AuthPage.tsx
index 95c2f2e..adb67d2 100644
--- a/frontend/src/pages/AuthPage.tsx
+++ b/frontend/src/pages/AuthPage.tsx
@@ -1,3 +1,4 @@
+import { USER_UPDATED_EVENT } from '../lib/userEvents'
import { useState } from 'react'
import type { FormEvent } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
@@ -136,6 +137,7 @@ export default function AuthPage() {
? await api.login(trimmedEmail, password)
: await api.register(trimmedEmail, password, nickname.trim())
localStorage.setItem('token', res.access_token)
+ window.dispatchEvent(new Event(USER_UPDATED_EVENT))
nav(nextPath)
} catch (err) {
setError(err instanceof Error ? err.message : t('common.fail'))
diff --git a/frontend/src/pages/SettingsPage.tsx b/frontend/src/pages/SettingsPage.tsx
index f85209c..8c2063a 100644
--- a/frontend/src/pages/SettingsPage.tsx
+++ b/frontend/src/pages/SettingsPage.tsx
@@ -14,6 +14,8 @@ import { dramaProjectEntryPath, formatDramaCardMeta } from '../lib/dramaWorkflow
import { STATUS_CN } from '../lib/status'
import SettingsToolRunsPanel from './SettingsToolRunsPanel'
import { formatDateTime, useI18n } from '../i18n'
+import TeamDirectory from '../features/teams/TeamDirectory'
+import { USER_UPDATED_EVENT } from '../lib/userEvents'
type SettingsTab =
| 'account'
@@ -46,7 +48,7 @@ const SIDE_ITEMS: { id: SettingsTab; soon?: boolean; group?: 'work' | 'account'
{ id: 'tools', group: 'work' },
{ id: 'assets', group: 'work' },
{ id: 'subscription', group: 'account' },
- { id: 'team', soon: true, group: 'account' },
+ { id: 'team', group: 'account' },
{ id: 'api', group: 'account' },
{ id: 'notify', soon: true, group: 'account' },
{ id: 'security', group: 'account' },
@@ -143,6 +145,7 @@ export default function SettingsPage() {
function logout() {
localStorage.removeItem('token')
+ window.dispatchEvent(new Event(USER_UPDATED_EVENT))
nav('/')
}
@@ -318,7 +321,9 @@ export default function SettingsPage() {
{tab === 'api' ? <ApiKeysPanel /> : null}
- {tab === 'team' || tab === 'notify' ? (
+ {tab === 'team' ? <TeamDirectory compact /> : null}
+
+ {tab === 'notify' ? (
<section className="pf-settings-card">
<h1>{t(`settings.tabs.${tab}`)}</h1>
<p className="pf-muted">{t('settings.soonModule')}</p>
diff --git a/frontend/src/pages/SettingsToolRunsPanel.tsx b/frontend/src/pages/SettingsToolRunsPanel.tsx
index 90d46f5..dfcfdbf 100644
--- a/frontend/src/pages/SettingsToolRunsPanel.tsx
+++ b/frontend/src/pages/SettingsToolRunsPanel.tsx
@@ -17,6 +17,7 @@ import { pageCountOf } from '../lib/pagination'
const PAGE_SIZE_DEFAULT = 8
const STATUS_CN: Record<string, string> = {
+ cancelled: '已取消',
queued: '生成中',
running: '生成中',
succeeded: '已完成',
@@ -172,7 +173,7 @@ export default function SettingsToolRunsPanel() {
<li key={item.id}>
<div className="pf-settings-list-row pf-settings-tool-row">
<button type="button" className="pf-settings-tool-main" onClick={() => void openDetail(item)}>
- {cover ? (
+ {cover && item.kind !== 'audio' ? (
video && !item.preview_url ? (
<video className="pf-settings-thumb" src={cover} muted />
) : (
@@ -263,7 +264,7 @@ export default function SettingsToolRunsPanel() {
<div className="pf-tool-run-detail">
<div className="pf-tool-run-media">
{detail.urls.length || detail.preview_url ? (
- isVideoRecord(detail) && (detail.urls[0] || '').match(/\.mp4/i) ? (
+ detail.kind === 'audio' ? <audio src={resolveToolMediaUrl(detail.urls[0])} controls /> : isVideoRecord(detail) && (detail.urls[0] || '').match(/\.mp4/i) ? (
<video src={resolveToolMediaUrl(detail.urls[0])} controls playsInline />
) : (
<img
diff --git a/frontend/tests/http.test.mjs b/frontend/tests/http.test.mjs
index 0e585cd..8b5cc18 100644
--- a/frontend/tests/http.test.mjs
+++ b/frontend/tests/http.test.mjs
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { apiErrorMessage, createHttpTransport, resolveApiBase } from '../src/api/http.ts'
+import { getMediaPriceVersion, setMediaPriceVersion } from '../src/lib/mediaPriceVersion.ts'
/** 创建带可观察 token 的客户端;错误策略不依赖浏览器弹窗。 */
function testTransport(getToken = () => 'first-token') {
@@ -101,3 +102,33 @@ test('网关返回非 JSON、null 或空 detail 时错误处理仍可运行', as
t.mock.restoreAll()
}
})
+test('目录中的价格版本随生成请求提交', async (t) => {
+ const originalVersion = getMediaPriceVersion()
+ t.after(() => setMediaPriceVersion(originalVersion))
+ const calls = []
+ t.mock.method(globalThis, 'fetch', async (url, init) => {
+ calls.push({ url, init })
+ return Response.json(url.endsWith('/api/media-models') ? { price_version: 7 } : { ok: true })
+ })
+ const transport = testTransport()
+ await transport.json('/api/media-models')
+ await transport.json('/api/generate', { method: 'POST', body: '{}' })
+ assert.equal(calls[1].init.headers.get('X-Media-Price-Version'), '7')
+})
+
+test('价格冲突通知目录刷新,但不自动重发生成请求', async (t) => {
+ const previous = globalThis.window
+ const window = new EventTarget()
+ globalThis.window = window
+ t.after(() => { if (previous === undefined) delete globalThis.window; else globalThis.window = previous })
+ let refreshes = 0
+ let requests = 0
+ window.addEventListener('media-prices-changed', () => { refreshes += 1 })
+ t.mock.method(globalThis, 'fetch', async () => {
+ requests += 1
+ return Response.json({ detail: '价格已更新' }, { status: 409 })
+ })
+ await assert.rejects(() => testTransport().json('/api/generate', { method: 'POST', body: '{}' }), /价格已更新/)
+ assert.equal(refreshes, 1)
+ assert.equal(requests, 1)
+})
diff --git a/frontend/tests/session-user.test.mjs b/frontend/tests/session-user.test.mjs
new file mode 100644
index 0000000..6a6de3e
--- /dev/null
+++ b/frontend/tests/session-user.test.mjs
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { loadSessionUser } from '../src/lib/sessionUser.ts'
+
+/** 记录会话和用户回写,模拟在请求期间切换账号或销毁导航栏。 */
+function sessionHarness(loadUser) {
+ let token = 'first-token'
+ let current = true
+ const users = []
+ let cleared = 0
+ return {
+ options: {
+ loadUser,
+ getToken: () => token,
+ isCurrent: () => current,
+ onUser: (user) => users.push(user),
+ onUnauthorized: () => { token = null; cleared += 1 },
+ },
+ replaceToken: (next) => { token = next },
+ invalidate: () => { current = false },
+ state: () => ({ token, users, cleared }),
+ }
+}
+
+/** 手动完成旧请求,覆盖请求返回前身份已变化的实际竞态。 */
+function deferred() {
+ let resolve
+ let reject
+ const promise = new Promise((resolvePromise, rejectPromise) => { resolve = resolvePromise; reject = rejectPromise })
+ return { promise, resolve, reject }
+}
+
+test('当前会话明确401才清除登录凭证', async () => {
+ const session = sessionHarness(async () => { throw Object.assign(new Error('凭证过期'), { status: 401 }) })
+ await loadSessionUser(session.options)
+ assert.deepEqual(session.state(), { token: null, users: [], cleared: 1 })
+})
+
+test('取消、网络故障、5xx和非401错误保留登录凭证', async () => {
+ const failures = [new DOMException('切换团队', 'AbortError'), new TypeError('Failed to fetch'), Object.assign(new Error('数据库超时'), { status: 503 }), Object.assign(new Error('Forbidden'), { status: 403 }), new Error('401 without HTTP status')]
+ for (const failure of failures) {
+ const session = sessionHarness(async () => { throw failure })
+ await loadSessionUser(session.options)
+ assert.deepEqual(session.state(), { token: 'first-token', users: [], cleared: 0 })
+ }
+})
+
+test('旧token迟到401不能清除新账号登录', async () => {
+ const response = deferred()
+ const session = sessionHarness(() => response.promise)
+ const pending = loadSessionUser(session.options)
+ session.replaceToken('second-token')
+ response.reject(Object.assign(new Error('旧凭证失效'), { status: 401 }))
+ await pending
+ assert.deepEqual(session.state(), { token: 'second-token', users: [], cleared: 0 })
+})
+
+test('旧token迟到成功不能覆盖新账号资料', async () => {
+ const response = deferred()
+ const session = sessionHarness(() => response.promise)
+ const pending = loadSessionUser(session.options)
+ session.replaceToken('second-token')
+ response.resolve({ id: 1, nickname: '旧账号' })
+ await pending
+ assert.deepEqual(session.state(), { token: 'second-token', users: [], cleared: 0 })
+})
+
+test('卸载或账号事件失效后的旧请求不再回写成功或401', async () => {
+ for (const unauthorized of [false, true]) {
+ const response = deferred()
+ const session = sessionHarness(() => response.promise)
+ const pending = loadSessionUser(session.options)
+ session.invalidate()
+ if (unauthorized) response.reject(Object.assign(new Error('凭证失效'), { status: 401 }))
+ else response.resolve({ id: 1 })
+ await pending
+ assert.deepEqual(session.state(), { token: 'first-token', users: [], cleared: 0 })
+ }
+})
+
+test('当前会话成功更新资料;未登录时不发资料请求', async () => {
+ let calls = 0
+ const user = { id: 1, nickname: '当前账号' }
+ const session = sessionHarness(async () => { calls += 1; return user })
+ await loadSessionUser(session.options)
+ assert.deepEqual(session.state(), { token: 'first-token', users: [user], cleared: 0 })
+ session.replaceToken(null)
+ await loadSessionUser(session.options)
+ assert.equal(calls, 1)
+})
diff --git a/frontend/tests/site-navigation.test.mjs b/frontend/tests/site-navigation.test.mjs
new file mode 100644
index 0000000..f749f01
--- /dev/null
+++ b/frontend/tests/site-navigation.test.mjs
@@ -0,0 +1,22 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { CREATION_NAV, RESOURCE_NAV, resolveNavActive } from '../src/lib/siteNavigation.ts'
+
+test('自由画布是独立主导航入口,所有入口路径唯一', () => {
+ const entries = [...CREATION_NAV, ...RESOURCE_NAV]
+ assert.equal(CREATION_NAV.find((item) => item.key === 'canvas')?.path, '/canvas')
+ assert.equal(new Set(entries.map((item) => item.path)).size, entries.length)
+ assert.equal(resolveNavActive('/canvas'), 'canvas')
+ assert.equal(resolveNavActive('/canvas-unknown'), undefined)
+})
+
+test('资产、团队和旧短视频地址高亮对应入口,不被漫剧前缀覆盖', () => {
+ for (const [path, expected] of [
+ ['/drama/assets', 'assets'], ['/drama/projects/422', 'drama'],
+ ['/teams/12', 'team'], ['/team-invitations', 'team'],
+ ['/studio/3/style', 'kepu'], ['/templates', 'kepu'], ['/history', 'kepu'],
+ ['/tools/t2i', 'tools'], ['/settings', 'settings'], ['/help', 'help'],
+ ]) assert.equal(resolveNavActive(path), expected)
+ assert.equal(resolveNavActive('/studio/3', 'studio'), 'kepu')
+ assert.equal(resolveNavActive('/drama', 'canvas'), 'canvas')
+})