Compare commits

...

2 Commits

Author SHA1 Message Date
xiaoxia 00045131f6 feat(points): P2 step 1 - POINTS_ENABLED safety gate (default false) (#1936)
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Waiting to run
CI/CD Pipeline / Check if frontend-only change (push) Waiting to run
CI/CD Pipeline / Validate - Style (push) Blocked by required conditions
CI/CD Pipeline / Validate - Security (push) Blocked by required conditions
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Blocked by required conditions
CI/CD Pipeline / Unit Tests (push) Blocked by required conditions
CI/CD Pipeline / Integration Tests (push) Blocked by required conditions
CI/CD Pipeline / Frontend Lint (push) Blocked by required conditions
CI/CD Pipeline / Frontend Unit Tests (push) Blocked by required conditions
CI/CD Pipeline / PR Build API Image (push) Blocked by required conditions
CI/CD Pipeline / PR Build Web Image (push) Blocked by required conditions
CI/CD Pipeline / PR Build Worker Image (push) Blocked by required conditions
CI/CD Pipeline / Check push changed paths (push) Waiting to run
CI/CD Pipeline / Build Staging API Image (push) Blocked by required conditions
CI/CD Pipeline / Build Staging Web Image (push) Blocked by required conditions
CI/CD Pipeline / Build Staging Worker Image (push) Blocked by required conditions
CI/CD Pipeline / Retag skipped Staging API Image (push) Blocked by required conditions
CI/CD Pipeline / Retag skipped Staging Web Image (push) Blocked by required conditions
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Blocked by required conditions
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Blocked by required conditions
CI/CD Pipeline / Staging E2E Tests (push) Blocked by required conditions
CI/CD Pipeline / Staging API Integration Tests (push) Blocked by required conditions
CI/CD Pipeline / Build Production API Image (push) Blocked by required conditions
CI/CD Pipeline / Build Production Web Image (push) Blocked by required conditions
CI/CD Pipeline / Build Production Worker Image (push) Blocked by required conditions
CI/CD Pipeline / Deploy Production (push) Blocked by required conditions
CI/CD Pipeline / Production Browser E2E (push) Blocked by required conditions
CI/CD Pipeline / ACR Image Cleanup (push) Blocked by required conditions
CI/CD Pipeline / Canary Release to Production (push) Blocked by required conditions
CI/CD Pipeline / CI Gate (push) Blocked by required conditions
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com>
Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
2026-09-16 00:26:27 +08:00
xiaoxia ab90a5ec9f fix: #1800 批量生成进度卡片布局 + #1893 文案库 AI 入口 UX 细节 (#1937)
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (push) Successful in 11s
CI/CD Pipeline / Check push changed paths (push) Successful in 11s
CI/CD Pipeline / PR Build API Image (push) Has been skipped
CI/CD Pipeline / PR Build Web Image (push) Has been skipped
CI/CD Pipeline / PR Build Worker Image (push) Has been skipped
CI/CD Pipeline / Frontend Lint (push) Has been skipped
CI/CD Pipeline / Integration Tests (push) Successful in 4m12s
CI/CD Pipeline / Validate - Style (push) Successful in 5m8s
CI/CD Pipeline / Validate - Python (mypy + alembic) (push) Successful in 5m2s
CI/CD Pipeline / Frontend Unit Tests (push) Failing after 3m46s
CI/CD Pipeline / Build Staging API Image (push) Successful in 34s
CI/CD Pipeline / Build Staging Worker Image (push) Successful in 29s
CI/CD Pipeline / Build Staging Web Image (push) Successful in 2m3s
CI/CD Pipeline / Unit Tests (push) Successful in 11m1s
CI/CD Pipeline / Validate - Security (push) Successful in 13m26s
CI/CD Pipeline / Retag skipped Staging API Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (push) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (push) Has been skipped
CI/CD Pipeline / Build Production API Image (push) Has been skipped
CI/CD Pipeline / Build Production Web Image (push) Has been skipped
CI/CD Pipeline / Build Production Worker Image (push) Has been skipped
CI/CD Pipeline / CI Gate (push) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Has been cancelled
CI/CD Pipeline / Staging E2E Tests (push) Has been cancelled
CI/CD Pipeline / Staging API Integration Tests (push) Has been cancelled
CI/CD Pipeline / Deploy Production (push) Has been cancelled
CI/CD Pipeline / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / ACR Image Cleanup (push) Has been cancelled
CI/CD Pipeline / Canary Release to Production (push) Has been cancelled
fix: #1800 批量生成进度卡片布局 + #1893 文案库 AI 入口 UX 细节

- #1800: 卡片标题加 ellipsis 防溢出,grid 列宽 minmax(320px,1fr) max380px,card-head flex 布局
- #1893: AI 生成标题/改写按钮 disabled 时用 Tooltip 包裹 span,改写弹窗 loading 时禁关禁点
2026-09-15 23:31:26 +08:00
8 changed files with 272 additions and 87 deletions
+7
View File
@@ -196,3 +196,10 @@ DOUBAO_MODEL=doubao-seed-1-6-250615
DOUBAO_BASE_URL=https://ark.cn-beijing.volces.com/api/v3
DOUBAO_TIMEOUT=30
DOUBAO_MAX_RETRIES=2
# ==================== 积分/会员系统 (#1895) ====================
# 积分扣点总开关:默认 false(对现有用户零影响)。
# P2 阶段各业务路由逐个接入 @points_gate 时,用
# `if settings.points_enabled: ...`
# 包裹扣点逻辑;所有路由接入完成并验证通过后再在 staging/prod 打开。
POINTS_ENABLED=false
@@ -1,8 +1,14 @@
/**
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677
* 第5步「确认生成」— 批量渲染进度网格(Issue #1677 / #1800 布局修复
*
* N 个正式生成任务各自独立卡片:进度条 / 成功成片播放 / 失败原因 + 单独重试。
* 数据来自 useGenerateVideo 的 batchTasksuseGenerationPolling 实时回传)。
*
* #1800 修复点:
* - 不再用 inline style 硬编码 grid 列宽 / 卡片 maxWidth,改由 CSS 统一控制
* (便于响应式 + 避免 inline 覆盖类规则)。
* - 标题图标 + 文本拆分为独立 span,文本 span 加 flex:1/min-width:0/ellipsis
* 防止长标题在窄列里溢出导致与相邻卡片进度条视觉重叠。
*/
import React from "react"
import { LoadingOutlined, CheckCircleFilled, CloseCircleOutlined } from "@ant-design/icons"
@@ -34,36 +40,34 @@ const BatchGenerationGrid: React.FC<BatchGenerationGridProps> = ({
{tasks.filter((t) => t.status === "completed").length} / {tasks.length}
</span>
</div>
<div
className="xx-batch-gen-grid"
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fill, minmax(280px, 320px))",
justifyContent: "center",
justifyItems: "center",
gap: 14,
width: "100%",
}}
>
{/* #1800: grid 列宽 / gap / justify 全部交由 .xx-batch-gen-grid CSS 控制 */}
<div className="xx-batch-gen-grid">
{sorted.map((task) => {
const title = titles[task.variantIndex] || `视频 ${task.variantIndex + 1}`
const video = (task.videos?.[0] || null) as GeneratedVideo | null
return (
<div
key={task.taskId}
className={`xx-batch-gen-card status-${task.status}`}
style={{ maxWidth: 320 }}
>
<div key={task.taskId} className={`xx-batch-gen-card status-${task.status}`}>
<div className="xx-batch-gen-card-head">
<span className="xx-batch-gen-card-title" title={title}>
{task.status === "completed" ? (
<CheckCircleFilled style={{ color: "#52c41a", marginRight: 6 }} />
<CheckCircleFilled
className="xx-batch-gen-card-icon"
style={{ color: "#52c41a" }}
/>
) : task.status === "failed" ? (
<CloseCircleOutlined style={{ color: "#ef4444", marginRight: 6 }} />
<CloseCircleOutlined
className="xx-batch-gen-card-icon"
style={{ color: "#ef4444" }}
/>
) : (
<LoadingOutlined style={{ color: "#1677ff", marginRight: 6 }} />
<LoadingOutlined
className="xx-batch-gen-card-icon"
style={{ color: "#1677ff" }}
/>
)}
{task.variantIndex + 1}{title}
<span className="xx-batch-gen-card-title-text">
{task.variantIndex + 1}{title}
</span>
</span>
</div>
+29 -6
View File
@@ -3376,14 +3376,18 @@
}
/* ============================================================
第5步确认生成:批量渲染进度网格(Issue #1677
第5步确认生成:批量渲染进度网格(Issue #1677 / #1800 布局修复
- 列宽从 minmax(160,180) 放宽到 minmax(300,360),避免进度条/标题挤压
- 卡片 width:100% 撑满列宽,避免 inline maxWidth 硬编码
- 标题图标/文本拆分 flex 布局,文本 ellipsis 长标题不溢出
============================================================ */
.xx-batch-gen-grid {
justify-items: center;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(160px, 180px));
grid-template-columns: repeat(auto-fill, minmax(300px, 360px));
justify-content: center;
justify-items: stretch;
gap: 14px;
width: 100%;
}
.xx-batch-gen-card {
@@ -3394,7 +3398,9 @@
display: flex;
flex-direction: column;
gap: 10px;
width: 100%;
min-width: 0;
box-sizing: border-box;
}
.xx-batch-gen-card.status-completed {
@@ -3410,14 +3416,30 @@
.xx-batch-gen-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
min-width: 0;
}
.xx-batch-gen-card-title {
display: flex;
align-items: center;
gap: 6px;
font-size: 14px;
font-weight: 600;
color: var(--text-primary, #1a1a1a);
flex: 1;
min-width: 0;
overflow: hidden;
}
.xx-batch-gen-card-icon {
flex-shrink: 0;
font-size: 14px;
}
.xx-batch-gen-card-title-text {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -3427,6 +3449,7 @@
display: flex;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.xx-batch-gen-card-pct {
@@ -3455,10 +3478,10 @@
word-break: break-word;
}
/* ── 响应式:窄屏批量网格回退单列.xx-canvas-grid 的窄屏限宽见网格定义处 #1741) ── */
/* ── 响应式:窄屏批量网格回退单列 ── */
@media (max-width: 960px) {
.xx-batch-gen-grid {
justify-items: center;
grid-template-columns: minmax(0, 320px);
grid-template-columns: minmax(0, 360px);
}
}
+46 -21
View File
@@ -31,6 +31,7 @@ import {
Space,
Spin,
Tag,
Tooltip,
Typography,
message,
} from "antd"
@@ -604,18 +605,25 @@ const ScriptLibrary: React.FC = () => {
label={
<span>
<Button
type="link"
size="small"
icon={<BulbOutlined />}
loading={titleGenLoading}
disabled={contentEmpty}
onClick={handleGenerateTitles}
{/* #1893 UX: disabled 时原生 title 在 antd Button 上不触发,
用 Tooltip + span 包裹保证提示可见 */}
<Tooltip
title={contentEmpty ? "请先填写文案内容" : "基于正文 AI 生成 3 个候选标题"}
style={{ padding: "0 4px", marginLeft: 4, height: 22 }}
>
AI
</Button>
<span style={{ display: "inline-flex", marginLeft: 4 }}>
<Button
type="link"
size="small"
icon={<BulbOutlined />}
loading={titleGenLoading}
disabled={contentEmpty}
onClick={handleGenerateTitles}
style={{ padding: "0 4px", height: 22 }}
>
AI
</Button>
</span>
</Tooltip>
</span>
}
rules={[{ required: true, message: "请填写文案名称" }, { max: 200 }]}
@@ -662,16 +670,29 @@ const ScriptLibrary: React.FC = () => {
options={REWRITE_STYLE_OPTIONS}
style={{ width: 110 }}
size="small"
disabled={rewriteLoading}
/>
<Button
size="small"
icon={<RobotOutlined />}
loading={rewriteLoading}
onClick={() => setRewriteModalOpen(true)}
>
AI
</Button>
{rewriteResult && (
{/* #1893 UX: content 为空时禁用改写按钮并给提示,避免用户点了才弹 warning */}
<Tooltip title={contentEmpty ? "请先填写文案正文再改写" : ""}>
<span style={{ display: "inline-flex" }}>
<Button
size="small"
icon={<RobotOutlined />}
loading={rewriteLoading}
disabled={contentEmpty}
onClick={() => {
// 每次打开重置上一次结果,避免误看旧对比
if (!rewriteLoading) {
setRewriteResult(null)
setRewriteModalOpen(true)
}
}}
>
AI
</Button>
</span>
</Tooltip>
{rewriteResult && !contentEmpty && (
<Button size="small" type="link" onClick={() => setRewriteModalOpen(true)}>
</Button>
@@ -782,7 +803,9 @@ const ScriptLibrary: React.FC = () => {
<Modal
title={`✨ AI 改写(${rewriteStyle}风格)`}
open={rewriteModalOpen}
onCancel={() => setRewriteModalOpen(false)}
onCancel={() => !rewriteLoading && setRewriteModalOpen(false)}
maskClosable={!rewriteLoading}
closable={!rewriteLoading}
footer={
rewriteResult ? (
<Space>
@@ -792,7 +815,9 @@ const ScriptLibrary: React.FC = () => {
</Button>
</Space>
) : (
<Button onClick={() => setRewriteModalOpen(false)}></Button>
<Button disabled={rewriteLoading} onClick={() => setRewriteModalOpen(false)}>
</Button>
)
}
width={640}
+5
View File
@@ -74,6 +74,11 @@ class SharedSettings(BaseSettings):
mediakit_base_url: str = "https://mediakit.cn-beijing.volces.com/api/v1"
mediakit_timeout: int = 60
# ── 积分/会员系统 (#1895) ────────────────────────────────────────────
# 总开关:默认 false(对所有用户零影响),P2 路由逐个接入时用
# `if settings.points_enabled:` 包裹,防止未完善的扣点逻辑影响现有用户。
points_enabled: bool = False
@property
def effective_database_url(self) -> str:
"""返回实际使用的数据库 URL。
+97 -39
View File
@@ -9,6 +9,7 @@ import asyncio
import functools
import inspect
import logging
import types
from collections.abc import Callable
from typing import Any
@@ -17,6 +18,77 @@ from fastapi import HTTPException
logger = logging.getLogger(__name__)
def _points_gate_enabled() -> bool:
"""读取配置开关:总开关关闭时装饰器完全放行(零开销/零副作用)。
放在模块顶层便于测试时 monkeypatch。
"""
try:
from app.config import settings as _settings
return bool(_settings.points_enabled)
except Exception: # pragma: no cover
return False
def _make_wrapper(
func: Callable,
is_async: bool,
scene_key: str,
per_unit,
unit_field,
quantity_field,
) -> Callable:
"""在被装饰函数所在模块的 globals 下创建 wrapper。
关键点:Python 闭包默认在「定义闭包的模块」globals 下查找自由变量。若直接
在 points_gate 模块内定义 wrapperwrapper.__globals__ 将指向本模块,导致
FastAPI/Pydantic 在解析函数类型注解(ForwardRef)时找不到路由模块中
导入的 Pydantic Model,出现 PydanticUndefinedAnnotation。
这里通过 types.FunctionType 把 wrapper 的 code 绑定到「被装饰函数所在模块
的 globals(补充装饰器内部符号)」,使 wrapper 的 ForwardRef 解析行为
与原路由函数一致。
"""
if is_async:
async def wrapper(*args: Any, **kwargs: Any) -> Any:
if not _points_gate_enabled():
return await func(*args, **kwargs)
return await _execute_with_gate(
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=True
)
else:
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not _points_gate_enabled():
return func(*args, **_filter_kwargs(func, kwargs))
return _execute_with_gate(
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=False
)
# 把闭包所需的内部符号注入到被装饰模块的 globals,避免闭包找不到名字
merged_globals: dict = dict(func.__globals__)
for _k, _v in (
("_points_gate_enabled", _points_gate_enabled),
("_execute_with_gate", _execute_with_gate),
("_run_async", _run_async),
("_filter_kwargs", _filter_kwargs),
):
merged_globals.setdefault(_k, _v)
new_wrapper = types.FunctionType(
wrapper.__code__,
merged_globals,
wrapper.__name__,
wrapper.__defaults__,
wrapper.__closure__,
)
new_wrapper = functools.wraps(func)(new_wrapper)
return new_wrapper
def points_gate(
scene_key: str,
per_unit: int | None = None,
@@ -25,42 +97,30 @@ def points_gate(
) -> Callable:
"""AI 功能入口积分扣费装饰器。
Args:
scene_key: 消耗场景标识(对应 points_rules.POINTS_SCENES 的 key
per_unit: 固定消耗积分(直接指定,不走规则计算)
unit_field: 从 request body 取时长字段名(按时长计费场景)
quantity_field: 从 request body 取数量字段名(按次计费场景)
使用示例::
@router.post("/ai/voice")
@points_gate("ai_voice", unit_field="duration_minutes")
async def create_ai_voice(body: VoiceRequest, current_user=Depends(get_current_user), db=Depends(get_db_session)):
...
当 POINTS_ENABLED=false(默认)时,装饰器完全透传原函数,零副作用。
开启后才会执行扣费逻辑:业务异常自动退费,积分不足返回 402。
"""
def decorator(func: Callable) -> Callable:
is_async = asyncio.iscoroutinefunction(func)
@functools.wraps(func)
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
return await _execute_with_gate(
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=True
)
@functools.wraps(func)
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
return _execute_with_gate(
func, args, kwargs, scene_key, per_unit, unit_field, quantity_field, is_async=False
)
if is_async:
return async_wrapper
return sync_wrapper
return _make_wrapper(func, is_async, scene_key, per_unit, unit_field, quantity_field)
return decorator
def _filter_kwargs(func: Callable, kwargs: dict) -> dict:
"""过滤掉目标函数签名不接受的 kwargs(避免 TypeError)。"""
try:
sig = inspect.signature(func)
params = sig.parameters
has_var_keyword = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values())
if has_var_keyword:
return kwargs
return {k: v for k, v in kwargs.items() if k in params}
except (ValueError, TypeError):
return kwargs
def _extract_kwargs(func: Callable, args: tuple, kwargs: dict) -> dict:
"""将位置参数映射到函数签名中的参数名,便于统一按 kwargs 提取。"""
sig = inspect.signature(func)
@@ -83,10 +143,9 @@ def _execute_with_gate(
"""积分扣费核心逻辑。"""
merged = _extract_kwargs(func, args, kwargs)
# 提取 current_user
current_user = merged.get("current_user")
# 提取 current_user(兼容 authenticated_user 命名)
current_user = merged.get("current_user") or merged.get("authenticated_user")
if current_user is None:
# 尝试从位置参数中找
for arg in args:
if hasattr(arg, "user"):
current_user = arg
@@ -114,8 +173,8 @@ def _execute_with_gate(
kwargs["_points_deducted"] = 0
kwargs["_is_free_quota"] = True
if is_async:
return _run_async(func, args, kwargs)
return func(*args, **kwargs)
return _run_async(func, args, _filter_kwargs(func, kwargs))
return func(*args, **_filter_kwargs(func, kwargs))
# ── 计算积分消耗 ──
if per_unit is not None:
@@ -139,12 +198,11 @@ def _execute_with_gate(
member_type=member_type,
)
# 零消耗场景(如免费的声音克隆训练)直接放行
if total_points == 0:
kwargs["_points_deducted"] = 0
if is_async:
return _run_async(func, args, kwargs)
return func(*args, **kwargs)
return _run_async(func, args, _filter_kwargs(func, kwargs))
return func(*args, **_filter_kwargs(func, kwargs))
# ── 扣减积分 ──
from packages.domain.points_service import PointsService
@@ -170,8 +228,8 @@ def _execute_with_gate(
# ── 执行业务函数,失败则退还积分 ──
try:
if is_async:
return _run_async(func, args, kwargs)
return func(*args, **kwargs)
return _run_async(func, args, _filter_kwargs(func, kwargs))
return func(*args, **_filter_kwargs(func, kwargs))
except Exception:
svc.refund_points(user.id, total_points, scene_key, db, ref_id=str(job_id))
raise
@@ -179,4 +237,4 @@ def _execute_with_gate(
def _run_async(func: Callable, args: tuple, kwargs: dict):
"""在 async wrapper 中 await 原始 async 函数。"""
return func(*args, **kwargs)
return func(*args, **_filter_kwargs(func, kwargs))
+55
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from packages.config.base import (
@@ -176,3 +178,56 @@ class TestSettingsSingleton:
shared = get_shared_settings()
api = get_cached_settings(APISettings)
assert shared is not api
class TestPointsEnabledSwitch:
"""#1895 P2: POINTS_ENABLED 配置开关(默认 false 保护现有用户)。"""
def test_default_points_enabled_is_false(self):
from packages.config.base import SharedSettings
s = SharedSettings()
assert s.points_enabled is False
def test_points_enabled_can_be_set_true(self, monkeypatch):
from packages.config import base as base_mod
monkeypatch.setenv("POINTS_ENABLED", "true")
base_mod.reload_settings_cache()
try:
s = base_mod.SharedSettings()
assert s.points_enabled is True
finally:
monkeypatch.delenv("POINTS_ENABLED", raising=False)
base_mod.reload_settings_cache()
def test_points_gate_disabled_passthrough(self, monkeypatch):
"""开关关闭时,@points_gate 装饰器完全透传原函数。"""
import packages.middleware.points_gate as pg_mod
from packages.middleware.points_gate import points_gate
monkeypatch.setattr(pg_mod, "_points_gate_enabled", lambda: False)
@points_gate("ai_rewrite")
def my_func(current_user=None, db=None):
return "bypass"
# 不传 current_user/db 也不报错(证明扣点逻辑被跳过)
assert my_func() == "bypass"
def test_points_gate_enabled_blocks_without_user(self, monkeypatch):
"""开关开启时,没有 current_user 会抛 401。"""
from fastapi import HTTPException
import packages.middleware.points_gate as pg_mod
from packages.middleware.points_gate import points_gate
monkeypatch.setattr(pg_mod, "_points_gate_enabled", lambda: True)
@points_gate("ai_rewrite")
def my_func(current_user=None, db=None):
return "ok"
with pytest.raises(HTTPException) as exc:
my_func(db=MagicMock())
assert exc.value.status_code == 401
+8
View File
@@ -8,9 +8,17 @@ from unittest.mock import MagicMock, patch
import pytest
from fastapi import HTTPException
import packages.middleware.points_gate as _pg_module
from packages.middleware.points_gate import _execute_with_gate, _extract_kwargs, points_gate
@pytest.fixture(autouse=True)
def _enable_points_gate(monkeypatch):
"""测试用:强制开启 points_gate,绕过 POINTS_ENABLED 默认关闭。"""
monkeypatch.setattr(_pg_module, "_points_gate_enabled", lambda: True)
yield
def _make_user(user_id="user-1", is_member=False, member_type=None):
user = MagicMock()
user.id = user_id