Commit 234e7cdb by imwangxiaozhou

feat(异步任务管理): 新增批量取消和取消全部任务功能,同步更新调用记录状态

- 新增CancelResult类型定义用于返回取消操作的统计结果
- 后端新增批量取消、取消全部异步任务接口,优化单个取消逻辑,同步更新关联调用记录状态为cancelled,内部分批处理避免阻塞
- 前端新增对应服务方法和store封装,在监控页面添加批量选择、批量取消和取消全部功能,新增已取消状态展示
- 更新所有相关设计文档、数据库注释和API定义,新增cancelled任务状态枚举
1 parent 2ea6b1c1
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import logging import logging
from typing import Optional from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db from app.core.database import get_db
...@@ -12,12 +13,31 @@ logger = logging.getLogger(__name__) ...@@ -12,12 +13,31 @@ logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/async-tasks", tags=["异步任务"]) router = APIRouter(prefix="/api/v1/async-tasks", tags=["异步任务"])
class BatchCancelRequest(BaseModel):
task_ids: list[str] = Field(..., description="待取消的任务 ID 数组")
@router.post("", status_code=201) @router.post("", status_code=201)
async def create_task(data: AsyncTaskCreate, db: AsyncSession = Depends(get_db)): async def create_task(data: AsyncTaskCreate, db: AsyncSession = Depends(get_db)):
"""创建异步任务记录""" """创建异步任务记录"""
return await async_task_service.create_task(db, data) return await async_task_service.create_task(db, data)
@router.post("/batch-cancel")
async def batch_cancel_tasks(data: BatchCancelRequest, db: AsyncSession = Depends(get_db)):
"""批量取消多个异步任务,同步更新关联调用记录。内部分批处理(每批 100 条)。"""
if not data.task_ids:
raise HTTPException(status_code=400, detail="task_ids 不能为空")
return await async_task_service.batch_cancel_tasks(db, data.task_ids)
@router.post("/cancel-all")
async def cancel_all_tasks(db: AsyncSession = Depends(get_db)):
"""取消全部 pending/processing 状态的异步任务,同步更新关联调用记录。内部分批处理。"""
result = await async_task_service.cancel_all_tasks(db)
return result
@router.put("/{task_id}") @router.put("/{task_id}")
async def update_task( async def update_task(
task_id: str, data: AsyncTaskUpdate, db: AsyncSession = Depends(get_db) task_id: str, data: AsyncTaskUpdate, db: AsyncSession = Depends(get_db)
...@@ -42,7 +62,7 @@ async def get_task(task_id: str, db: AsyncSession = Depends(get_db)): ...@@ -42,7 +62,7 @@ async def get_task(task_id: str, db: AsyncSession = Depends(get_db)):
async def list_tasks( async def list_tasks(
page: int = Query(1, ge=1, description="页码"), page: int = Query(1, ge=1, description="页码"),
page_size: int = Query(20, ge=1, le=100, description="每页条数"), page_size: int = Query(20, ge=1, le=100, description="每页条数"),
status: Optional[str] = Query(None, description="按状态筛选:pending/processing/success/failed"), status: Optional[str] = Query(None, description="按状态筛选:pending/processing/success/failed/cancelled"),
task_id: Optional[str] = Query(None, description="按 celery_task_id 模糊搜索"), task_id: Optional[str] = Query(None, description="按 celery_task_id 模糊搜索"),
db: AsyncSession = Depends(get_db), db: AsyncSession = Depends(get_db),
): ):
...@@ -54,7 +74,7 @@ async def list_tasks( ...@@ -54,7 +74,7 @@ async def list_tasks(
@router.post("/{task_id}/cancel") @router.post("/{task_id}/cancel")
async def cancel_task(task_id: str, db: AsyncSession = Depends(get_db)): async def cancel_task(task_id: str, db: AsyncSession = Depends(get_db)):
"""取消异步任务""" """取消单个异步任务,同步更新关联调用记录状态为 cancelled"""
try: try:
result = await async_task_service.cancel_task(db, task_id) result = await async_task_service.cancel_task(db, task_id)
if not result: if not result:
......
...@@ -71,7 +71,7 @@ class CallRecord(Base): ...@@ -71,7 +71,7 @@ class CallRecord(Base):
) )
status: Mapped[str] = mapped_column( status: Mapped[str] = mapped_column(
VARCHAR(20), nullable=False, default="pending", VARCHAR(20), nullable=False, default="pending",
comment="状态:pending/success/failed" comment="状态:pending/success/failed/cancelled"
) )
error_message: Mapped[str | None] = mapped_column( error_message: Mapped[str | None] = mapped_column(
TEXT, nullable=True, TEXT, nullable=True,
......
...@@ -7,6 +7,7 @@ from sqlalchemy import select, func, and_, or_ ...@@ -7,6 +7,7 @@ from sqlalchemy import select, func, and_, or_
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from app.models.async_task import AsyncTask from app.models.async_task import AsyncTask
from app.models.call_record import CallRecord
from app.schemas.async_task import AsyncTaskCreate, AsyncTaskUpdate from app.schemas.async_task import AsyncTaskCreate, AsyncTaskUpdate
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -125,7 +126,7 @@ async def list_tasks( ...@@ -125,7 +126,7 @@ async def list_tasks(
async def cancel_task(db: AsyncSession, task_id: str) -> Optional[dict]: async def cancel_task(db: AsyncSession, task_id: str) -> Optional[dict]:
"""取消异步任务""" """取消异步任务,同步更新关联调用记录状态为 cancelled"""
result = await db.execute( result = await db.execute(
select(AsyncTask).where(AsyncTask.id == task_id) select(AsyncTask).where(AsyncTask.id == task_id)
) )
...@@ -133,13 +134,90 @@ async def cancel_task(db: AsyncSession, task_id: str) -> Optional[dict]: ...@@ -133,13 +134,90 @@ async def cancel_task(db: AsyncSession, task_id: str) -> Optional[dict]:
if not task: if not task:
return None return None
# 只有 processing 状态的任务可以取消 # 只有 pending/processing 状态的任务可以取消
if task.status not in ("pending", "processing"): if task.status not in ("pending", "processing"):
raise ValueError(f"任务状态不允许取消: {task.status}") raise ValueError(f"任务状态不允许取消: {task.status}")
task.status = "cancelled" task.status = "cancelled"
task.completed_at = datetime.now() task.completed_at = datetime.now()
# 同步更新关联调用记录状态
call_result = await db.execute(
select(CallRecord).where(CallRecord.id == task.call_record_id)
)
call_record = call_result.scalar_one_or_none()
if call_record and call_record.status == "pending":
call_record.status = "cancelled"
await db.flush() await db.flush()
await db.refresh(task) await db.refresh(task)
logger.info(f"异步任务已取消: id={task_id}") logger.info(f"异步任务已取消: id={task_id}, 关联调用记录已同步为 cancelled")
return _to_task_dict(task) return _to_task_dict(task)
async def batch_cancel_tasks(db: AsyncSession, task_ids: list[str]) -> dict:
"""批量取消异步任务,每批 100 条处理"""
total = len(task_ids)
success_count = 0
failed_ids = []
BATCH_SIZE = 100
for i in range(0, total, BATCH_SIZE):
batch = task_ids[i : i + BATCH_SIZE]
for tid in batch:
try:
result = await cancel_task(db, tid)
if result is None:
failed_ids.append(tid)
else:
success_count += 1
except ValueError:
failed_ids.append(tid)
logger.info(f"批量取消完成: total={total}, success={success_count}, failed={len(failed_ids)}")
return {
"total": total,
"success_count": success_count,
"failed_count": len(failed_ids),
"failed_ids": failed_ids,
}
async def cancel_all_tasks(db: AsyncSession) -> dict:
"""取消全部 pending/processing 状态的异步任务,分批处理"""
total_cancelled = 0
batch_count = 0
BATCH_SIZE = 100
while True:
result = await db.execute(
select(AsyncTask)
.where(AsyncTask.status.in_(["pending", "processing"]))
.limit(BATCH_SIZE)
)
tasks = result.scalars().all()
if not tasks:
break
for task in tasks:
task.status = "cancelled"
task.completed_at = datetime.now()
total_cancelled += 1
# 同步更新关联调用记录
call_result = await db.execute(
select(CallRecord).where(CallRecord.id == task.call_record_id)
)
call_record = call_result.scalar_one_or_none()
if call_record and call_record.status == "pending":
call_record.status = "cancelled"
batch_count += 1
logger.info(f"取消全部 - 第 {batch_count} 批完成, 本批取消 {len(tasks)} 个任务")
await db.flush()
logger.info(f"取消全部完成: total={total_cancelled}, batch_count={batch_count}")
return {
"total": total_cancelled,
"batch_count": batch_count,
}
...@@ -14,6 +14,7 @@ const CALL_STATUS_MAP: Record<string, { label: string; color: string; icon: Reac ...@@ -14,6 +14,7 @@ const CALL_STATUS_MAP: Record<string, { label: string; color: string; icon: Reac
pending: { label: '待调度', color: 'default', icon: <ClockCircleOutlined /> }, pending: { label: '待调度', color: 'default', icon: <ClockCircleOutlined /> },
success: { label: '成功', color: 'success', icon: <CheckCircleOutlined /> }, success: { label: '成功', color: 'success', icon: <CheckCircleOutlined /> },
failed: { label: '失败', color: 'error', icon: <CloseCircleOutlined /> }, failed: { label: '失败', color: 'error', icon: <CloseCircleOutlined /> },
cancelled: { label: '已取消', color: 'warning', icon: <MinusCircleOutlined /> },
}; };
const TASK_STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = { const TASK_STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
...@@ -213,7 +214,7 @@ const taskColumns = [ ...@@ -213,7 +214,7 @@ const taskColumns = [
function handleCancel(record: AsyncTask) { function handleCancel(record: AsyncTask) {
Modal.confirm({ Modal.confirm({
title: '取消任务', title: '取消任务',
content: `确定要取消任务「${record.celery_task_id}」吗?`, content: `确定要取消任务「${record.celery_task_id || record.id.slice(0, 8)}」吗?`,
okText: '取消任务', okText: '取消任务',
okType: 'danger', okType: 'danger',
cancelText: '返回', cancelText: '返回',
...@@ -228,6 +229,47 @@ function handleCancel(record: AsyncTask) { ...@@ -228,6 +229,47 @@ function handleCancel(record: AsyncTask) {
}); });
} }
function handleBatchCancel(taskIds: string[], setTaskIds: (ids: string[]) => void) {
if (taskIds.length === 0) {
message.warning('请先选择要取消的任务');
return;
}
Modal.confirm({
title: '批量取消任务',
content: `确定要取消选中的 ${taskIds.length} 个任务吗?`,
okText: '批量取消',
okType: 'danger',
cancelText: '返回',
onOk: async () => {
try {
const result = await useAsyncTaskStore.getState().batchCancelTasks(taskIds);
message.success(`批量取消完成:成功 ${result.success_count} 个${result.failed_count ? `,失败 ${result.failed_count} 个` : ''}`);
setTaskIds([]);
} catch {
message.error('批量取消失败');
}
},
});
}
function handleCancelAll() {
Modal.confirm({
title: '取消全部任务',
content: '确定要取消所有等待中和处理中的任务吗?此操作不可撤销。',
okText: '取消全部',
okType: 'danger',
cancelText: '返回',
onOk: async () => {
try {
const result = await useAsyncTaskStore.getState().cancelAllTasks();
message.success(`已取消全部 ${result.total} 个任务${result.batch_count ? `(分 ${result.batch_count} 批处理)` : ''}`);
} catch {
message.error('取消全部失败');
}
},
});
}
export default function CallMonitor() { export default function CallMonitor() {
const { records, total: crTotal, page: crPage, pageSize: crPageSize, loading: crLoading, fetchRecords } = useCallRecordStore(); const { records, total: crTotal, page: crPage, pageSize: crPageSize, loading: crLoading, fetchRecords } = useCallRecordStore();
const { tasks, total: atTotal, page: atPage, pageSize: atPageSize, loading: atLoading, fetchTasks } = useAsyncTaskStore(); const { tasks, total: atTotal, page: atPage, pageSize: atPageSize, loading: atLoading, fetchTasks } = useAsyncTaskStore();
...@@ -235,6 +277,7 @@ export default function CallMonitor() { ...@@ -235,6 +277,7 @@ export default function CallMonitor() {
const [detailOpen, setDetailOpen] = useState(false); const [detailOpen, setDetailOpen] = useState(false);
const [detailCallId, setDetailCallId] = useState<string | null>(null); const [detailCallId, setDetailCallId] = useState<string | null>(null);
const [taskSearchId, setTaskSearchId] = useState(''); const [taskSearchId, setTaskSearchId] = useState('');
const [selectedTaskIds, setSelectedTaskIds] = useState<string[]>([]);
const handleRowClick = (record: CallRecord) => { const handleRowClick = (record: CallRecord) => {
setDetailCallId(record.id); setDetailCallId(record.id);
...@@ -328,7 +371,7 @@ export default function CallMonitor() { ...@@ -328,7 +371,7 @@ export default function CallMonitor() {
), ),
children: ( children: (
<div> <div>
<div className="task-search-bar"> <div className="task-search-bar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0' }}>
<Input.Search <Input.Search
placeholder="搜索任务 ID..." placeholder="搜索任务 ID..."
allowClear allowClear
...@@ -338,6 +381,27 @@ export default function CallMonitor() { ...@@ -338,6 +381,27 @@ export default function CallMonitor() {
style={{ width: 320 }} style={{ width: 320 }}
enterButton enterButton
/> />
<div style={{ flex: 1 }} />
{selectedTaskIds.length > 0 && (
<span style={{ fontSize: 13, color: 'var(--color-text-secondary)' }}>
已选 {selectedTaskIds.length} 项
</span>
)}
<Button
icon={<StopOutlined />}
danger
disabled={selectedTaskIds.length === 0}
onClick={() => handleBatchCancel(selectedTaskIds, setSelectedTaskIds)}
>
批量取消
</Button>
<Button
icon={<MinusCircleOutlined />}
danger
onClick={handleCancelAll}
>
取消全部
</Button>
</div> </div>
<Table <Table
dataSource={tasks} dataSource={tasks}
...@@ -346,6 +410,13 @@ export default function CallMonitor() { ...@@ -346,6 +410,13 @@ export default function CallMonitor() {
loading={atLoading} loading={atLoading}
className="page-table" className="page-table"
style={{ borderTop: '1px solid var(--color-border-light)' }} style={{ borderTop: '1px solid var(--color-border-light)' }}
rowSelection={{
selectedRowKeys: selectedTaskIds,
onChange: (keys) => setSelectedTaskIds(keys as string[]),
getCheckboxProps: (record: AsyncTask) => ({
disabled: record.status !== 'pending' && record.status !== 'processing',
}),
}}
onRow={(record: AsyncTask) => ({ onRow={(record: AsyncTask) => ({
onClick: () => handleTaskRowClick(record), onClick: () => handleTaskRowClick(record),
style: { cursor: record.call_record_id ? 'pointer' : 'default' }, style: { cursor: record.call_record_id ? 'pointer' : 'default' },
...@@ -358,7 +429,10 @@ export default function CallMonitor() { ...@@ -358,7 +429,10 @@ export default function CallMonitor() {
showQuickJumper: true, showQuickJumper: true,
pageSizeOptions: ['10', '20', '50'], pageSizeOptions: ['10', '20', '50'],
showTotal: (t) => `共 ${t} 条`, showTotal: (t) => `共 ${t} 条`,
onChange: (p, ps) => fetchTasks({ page: p, page_size: ps, task_id: taskSearchId || undefined }), onChange: (p, ps) => {
setSelectedTaskIds([]);
fetchTasks({ page: p, page_size: ps, task_id: taskSearchId || undefined });
},
}} }}
/> />
</div> </div>
......
import api from './api'; import api from './api';
import type { AsyncTask, PaginatedResponse } from '../types'; import type { AsyncTask, PaginatedResponse, CancelResult } from '../types';
export const asyncTaskService = { export const asyncTaskService = {
list: (params?: { list: (params?: {
...@@ -12,4 +12,10 @@ export const asyncTaskService = { ...@@ -12,4 +12,10 @@ export const asyncTaskService = {
getById: (id: string) => api.get<AsyncTask>(`/v1/async-tasks/${id}`).then((r) => r.data), getById: (id: string) => api.get<AsyncTask>(`/v1/async-tasks/${id}`).then((r) => r.data),
cancel: (id: string) => api.post<AsyncTask>(`/v1/async-tasks/${id}/cancel`).then((r) => r.data), cancel: (id: string) => api.post<AsyncTask>(`/v1/async-tasks/${id}/cancel`).then((r) => r.data),
batchCancel: (taskIds: string[]) =>
api.post<CancelResult>('/v1/async-tasks/batch-cancel', { task_ids: taskIds }).then((r) => r.data),
cancelAll: () =>
api.post<CancelResult>('/v1/async-tasks/cancel-all').then((r) => r.data),
}; };
import { create } from 'zustand'; import { create } from 'zustand';
import type { AsyncTask, PaginatedResponse } from '../types'; import type { AsyncTask, PaginatedResponse, CancelResult } from '../types';
import { asyncTaskService } from '../services/asyncTaskService'; import { asyncTaskService } from '../services/asyncTaskService';
interface AsyncTaskState { interface AsyncTaskState {
...@@ -17,6 +17,8 @@ interface AsyncTaskState { ...@@ -17,6 +17,8 @@ interface AsyncTaskState {
task_id?: string; task_id?: string;
}) => Promise<void>; }) => Promise<void>;
cancelTask: (id: string) => Promise<void>; cancelTask: (id: string) => Promise<void>;
batchCancelTasks: (taskIds: string[]) => Promise<CancelResult>;
cancelAllTasks: () => Promise<CancelResult>;
} }
export const useAsyncTaskStore = create<AsyncTaskState>((set, get) => ({ export const useAsyncTaskStore = create<AsyncTaskState>((set, get) => ({
...@@ -52,4 +54,16 @@ export const useAsyncTaskStore = create<AsyncTaskState>((set, get) => ({ ...@@ -52,4 +54,16 @@ export const useAsyncTaskStore = create<AsyncTaskState>((set, get) => ({
await asyncTaskService.cancel(id); await asyncTaskService.cancel(id);
await get().fetchTasks(); await get().fetchTasks();
}, },
batchCancelTasks: async (taskIds) => {
const result = await asyncTaskService.batchCancel(taskIds);
await get().fetchTasks();
return result;
},
cancelAllTasks: async () => {
const result = await asyncTaskService.cancelAll();
await get().fetchTasks();
return result;
},
})); }));
...@@ -242,3 +242,12 @@ export interface AsyncTask { ...@@ -242,3 +242,12 @@ export interface AsyncTask {
created_at: string; created_at: string;
updated_at: string; updated_at: string;
} }
/** 取消操作结果 */
export interface CancelResult {
total: number;
success_count?: number;
failed_count?: number;
failed_ids?: string[];
batch_count?: number;
}
...@@ -27,7 +27,9 @@ ...@@ -27,7 +27,9 @@
{"type": "update_task", "desc": "更新任务状态和结果(Celery Worker 回调写入)", "endpoint": "PUT /api/v1/async-tasks/:task_id"}, {"type": "update_task", "desc": "更新任务状态和结果(Celery Worker 回调写入)", "endpoint": "PUT /api/v1/async-tasks/:task_id"},
{"type": "detail_task", "desc": "查询异步任务的状态、进度和执行结果", "endpoint": "GET /api/v1/async-tasks/:task_id"}, {"type": "detail_task", "desc": "查询异步任务的状态、进度和执行结果", "endpoint": "GET /api/v1/async-tasks/:task_id"},
{"type": "list_task", "desc": "按状态/时间范围分页查询异步任务列表", "endpoint": "GET /api/v1/async-tasks"}, {"type": "list_task", "desc": "按状态/时间范围分页查询异步任务列表", "endpoint": "GET /api/v1/async-tasks"},
{"type": "cancel_task", "desc": "取消正在执行的异步任务", "endpoint": "POST /api/v1/async-tasks/:task_id/cancel"} {"type": "cancel_task", "desc": "取消正在执行的异步任务,同时将关联调用记录标记为 cancelled", "endpoint": "POST /api/v1/async-tasks/:task_id/cancel"},
{"type": "cancel_batch", "desc": "批量取消多个异步任务,同时将关联调用记录标记为 cancelled。分批处理以支持取消任意数量任务", "endpoint": "POST /api/v1/async-tasks/batch-cancel"},
{"type": "cancel_all", "desc": "取消当前所有 pending/processing 状态的异步任务,同时将关联调用记录标记为 cancelled。分批处理以支持取消全部任务", "endpoint": "POST /api/v1/async-tasks/cancel-all"}
], ],
"changelogs": [ "changelogs": [
{ {
...@@ -61,6 +63,14 @@ ...@@ -61,6 +63,14 @@
"title": "调用详情展示实际敏感词替换结果", "title": "调用详情展示实际敏感词替换结果",
"desc": "call_records 表新增 sensitive_replacements JSON 字段。后端替换敏感词时将详情保存到 call_records。前端展示原始词→替换词对照表。", "desc": "call_records 表新增 sensitive_replacements JSON 字段。后端替换敏感词时将详情保存到 call_records。前端展示原始词→替换词对照表。",
"done": true "done": true
},
{
"date": "2026-06-25",
"id": "CHG-026",
"type": "modify",
"title": "新增批量取消和取消全部任务功能,取消时同步更新调用记录状态",
"desc": "1. 新增 POST /api/v1/async-tasks/batch-cancel 批量取消接口(按 ID 列表取消)\n2. 新增 POST /api/v1/async-tasks/cancel-all 取消全部接口(取消所有 pending/processing 任务,分批处理无限制)\n3. 取消任务时同步将关联 call_record 状态设为 cancelled\n4. async_tasks 和 call_records 两表状态枚举均新增 cancelled 值",
"done": true
} }
] ]
} }
...@@ -89,7 +89,7 @@ ...@@ -89,7 +89,7 @@
"任务" "任务"
], ],
"status": "done", "status": "done",
"note": "记录每次模型调用的完整信息和关联的异步任务状态。包含两块业务:<br><br>1. <b>调用记录</b>:请求/响应 JSON、Token 消耗(prompt/completion/total)、耗时、状态(success/failed)、错误信息、关联账号名称等。MD5 去重防止重复提交。列表展示关联账号名称。<br>2. <b>异步任务记录</b>:Celery 异步任务的 task_id、关联调用 ID、状态(pending/processing/success/failed)、提交/完成时间、结果和错误信息。支持按 task_id 模糊搜索。<br><br>复用自 Java 项目的 LlmCallDetailsMapper + LlmCallLlmJobsMapper + LlmCallProgressDetailsMapper 三表合一设计。新平台使用 Celery 原生任务状态管理,替代 Java 项目的 Elastic-Job 定时轮询模式。<br><br><b>CHG-019</b>:调用详情展示组装过程信息。GET /api/v1/calls/:id 增强返回 provider_name 和 template_info(标题/编码/类型/System Prompt/User Prompt/版本)。前端详情弹窗分步骤展示:模板信息 → 最终请求体 → 调用结果。数据库新增 template_id 字段。<br><br><b>CHG-020</b>:异步任务列表展示 celery_task_id 列,新增按 task_id 搜索功能。GET /api/v1/async-tasks 新增 task_id 查询参数在后端模糊匹配。<br><br><b>CHG-022</b>:sensitive_replacements 字段记录敏感词替换详情,前端组装过程展示原始词→替换词对照表。", "note": "记录每次模型调用的完整信息和关联的异步任务状态。包含两块业务:<br><br>1. <b>调用记录</b>:请求/响应 JSON、Token 消耗(prompt/completion/total)、耗时、状态(success/failed/cancelled)、错误信息、关联账号名称等。MD5 去重防止重复提交。列表展示关联账号名称。<br>2. <b>异步任务记录</b>:Celery 异步任务的 task_id、关联调用 ID、状态(pending/processing/success/failed/cancelled)、提交/完成时间、结果和错误信息。支持按 task_id 模糊搜索、单个取消/批量取消/取消全部。取消时同步更新关联调用记录状态。<br><br>复用自 Java 项目的 LlmCallDetailsMapper + LlmCallLlmJobsMapper + LlmCallProgressDetailsMapper 三表合一设计。新平台使用 Celery 原生任务状态管理,替代 Java 项目的 Elastic-Job 定时轮询模式。<br><br><b>CHG-019</b>:调用详情展示组装过程信息。GET /api/v1/calls/:id 增强返回 provider_name 和 template_info(标题/编码/类型/System Prompt/User Prompt/版本)。前端详情弹窗分步骤展示:模板信息 → 最终请求体 → 调用结果。数据库新增 template_id 字段。<br><br><b>CHG-020</b>:异步任务列表展示 celery_task_id 列,新增按 task_id 搜索功能。GET /api/v1/async-tasks 新增 task_id 查询参数在后端模糊匹配。<br><br><b>CHG-022</b>:sensitive_replacements 字段记录敏感词替换详情,前端组装过程展示原始词→替换词对照表。<br><br><b>CHG-026</b>:新增批量取消和取消全部功能,取消时同步更新关联调用记录状态为 cancelled。【已实现】",
"fileKey": "call-and-task-records" "fileKey": "call-and-task-records"
}, },
{ {
......
...@@ -424,7 +424,7 @@ ...@@ -424,7 +424,7 @@
"title": "取消正在执行的异步任务", "title": "取消正在执行的异步任务",
"required": true, "required": true,
"precondition": "存在处理中的异步任务", "precondition": "存在处理中的异步任务",
"expect": "任务状态更新为 cancelled", "expect": "任务状态更新为 cancelled,关联调用记录状态同步更新为 cancelled",
"tab": "admin", "tab": "admin",
"steps": [ "steps": [
{ {
...@@ -448,11 +448,15 @@ ...@@ -448,11 +448,15 @@
}, },
{ {
"tag": "validate", "tag": "validate",
"text": "验证请求参数" "text": "验证任务存在且状态为 pending/processing"
}, },
{ {
"tag": "write", "tag": "write",
"text": "向数据库表插入新记录" "text": "更新 async_tasks 表:status=cancelled"
},
{
"tag": "write",
"text": "更新关联 call_records 表:status=cancelled"
}, },
{ {
"tag": "return", "tag": "return",
...@@ -460,8 +464,121 @@ ...@@ -460,8 +464,121 @@
} }
], ],
"expected": [ "expected": [
"任务状态更新为 cancelled" "任务状态更新为 cancelled",
"关联调用记录状态更新为 cancelled"
],
"changelog": {"id": "CHG-026", "date": "2026-06-25", "reason": "取消任务时同步更新调用记录状态为 cancelled"}
}
] ]
},
{
"title": "批量取消异步任务",
"required": true,
"precondition": "存在多个处理中的异步任务",
"expect": "选中任务的状态更新为 cancelled,关联调用记录状态同步更新为 cancelled",
"tab": "admin",
"steps": [
{
"op": "OP-F-04.10.1",
"status": "done",
"tab": "admin",
"nav": [
"管理后台",
"模型调用与任务记录",
"batch_cancel"
],
"actions": [
"登录管理后台",
"进入「模型调用与任务记录」模块",
"选择多个异步任务",
"点击「批量取消」按钮",
"在确认弹框中点击「确认取消」"
],
"backend": [
{
"tag": "receive",
"text": "接收 POST /api/v1/async-tasks/batch-cancel 请求"
},
{
"tag": "validate",
"text": "验证 task_ids 数组非空,每项为有效 UUID"
},
{
"tag": "write",
"text": "分批查询 async_tasks 表:WHERE id IN (:ids) AND status IN (pending,processing),每批 100 条"
},
{
"tag": "write",
"text": "逐批更新 async_tasks:status=cancelled"
},
{
"tag": "write",
"text": "逐批更新关联 call_records:status=cancelled"
},
{
"tag": "return",
"text": "返回取消结果统计(total/成功/失败数)"
}
],
"expected": [
"页面提示「批量取消成功,共取消 N 个任务」",
"被取消的任务状态显示为 cancelled",
"关联的调用记录状态同步为 cancelled"
],
"changelog": {"id": "CHG-026", "date": "2026-06-25", "reason": "新增批量取消异步任务功能"}
}
]
},
{
"title": "取消全部异步任务",
"required": true,
"precondition": "存在 pending/processing 状态的异步任务",
"expect": "所有 pending/processing 任务状态更新为 cancelled,关联调用记录同步更新",
"tab": "admin",
"steps": [
{
"op": "OP-F-04.11.1",
"status": "notimpl",
"tab": "admin",
"nav": [
"管理后台",
"模型调用与任务记录",
"cancel_all"
],
"actions": [
"登录管理后台",
"进入「模型调用与任务记录」模块",
"点击「取消全部」按钮",
"在确认弹框中点击「确认取消全部」"
],
"backend": [
{
"tag": "receive",
"text": "接收 POST /api/v1/async-tasks/cancel-all 请求"
},
{
"tag": "write",
"text": "分批查询 async_tasks 表:WHERE status IN (pending,processing),每批 100 条,循环取消直至全部处理完毕"
},
{
"tag": "write",
"text": "逐批更新 async_tasks:status=cancelled"
},
{
"tag": "write",
"text": "逐批更新关联 call_records:status=cancelled"
},
{
"tag": "return",
"text": "返回取消结果统计(total/成功/失败数)"
}
],
"expected": [
"页面提示「取消全部成功,共取消 N 个任务」",
"所有 pending/processing 任务状态显示为 cancelled",
"关联的调用记录状态同步为 cancelled"
],
"changelog": {"id": "CHG-026", "date": "2026-06-25", "reason": "新增取消全部异步任务功能"}
} }
] ]
} }
...@@ -491,6 +608,7 @@ ...@@ -491,6 +608,7 @@
"desc": "OP-F-04.3.1 → notimpl。增强 GET /api/v1/calls/:id 返回 provider_name 和 template_info。前端详情弹窗新增「组装过程」视图展示模板-变量-请求-响应的完整流程。", "desc": "OP-F-04.3.1 → notimpl。增强 GET /api/v1/calls/:id 返回 provider_name 和 template_info。前端详情弹窗新增「组装过程」视图展示模板-变量-请求-响应的完整流程。",
"done": true "done": true
}, },
{"date": "2026-06-17", "id": "CHG-020", "type": "modify", "title": "异步任务列表新增 task_id 搜索功能", "desc": "OP-F-04.7.1 → notimpl。GET /api/v1/async-tasks 新增 task_id 查询参数。前端异步任务 Tab 新增搜索输入框,可按 celery_task_id 模糊搜索。", "done": true} {"date": "2026-06-17", "id": "CHG-020", "type": "modify", "title": "异步任务列表新增 task_id 搜索功能", "desc": "OP-F-04.7.1 → notimpl。GET /api/v1/async-tasks 新增 task_id 查询参数。前端异步任务 Tab 新增搜索输入框,可按 celery_task_id 模糊搜索。", "done": true},
{"date": "2026-06-25", "id": "CHG-026", "type": "modify", "title": "新增批量取消和取消全部任务功能,取消时同步更新调用记录状态", "desc": "OP-F-04.9.1 → notimpl。新增 OP-F-04.10.1(批量取消)、OP-F-04.11.1(取消全部)。取消时同步更新关联 call_records 状态为 cancelled。", "done": true}
] ]
} }
\ No newline at end of file \ No newline at end of file
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"field_count": 10, "field_count": 10,
"index_count": 3, "index_count": 3,
"related_modules": "关联 F-04", "related_modules": "关联 F-04",
"field_rows": "<tr class=\"row-pk\">\n <td class=\"field-name\">id</td>\n <td><span class=\"field-type type-uuid\">UUID</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span></td>\n <td>主键</td>\n</tr>\n<tr>\n <td class=\"field-name\">call_record_id</td>\n <td><span class=\"field-type type-uuid\">UUID</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span></td>\n <td>关联调用记录 ID(外键 → ai_llmbase_call_records.id)</td>\n</tr>\n<tr>\n <td class=\"field-name\">celery_task_id</td>\n <td><span class=\"field-type type-varchar\">VARCHAR(255)</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-unique\">UNIQUE</span></td>\n <td>Celery 任务 ID</td>\n</tr>\n<tr>\n <td class=\"field-name\">status</td>\n <td><span class=\"field-type type-varchar\">VARCHAR(20)</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT 'pending'</span></td>\n <td>状态:pending/processing/success/failed</td>\n</tr>\n<tr>\n <td class=\"field-name\">progress</td>\n <td><span class=\"field-type type-int\">INTEGER</span></td>\n <td><span class=\"constraint-tag c-default\">DEFAULT 0</span></td>\n <td>进度百分比 0-100</td>\n</tr>\n<tr>\n <td class=\"field-name\">result</td>\n <td><span class=\"field-type type-json\">JSONB</span></td>\n <td></td>\n <td>任务结果 JSON</td>\n</tr>\n<tr>\n <td class=\"field-name\">error_message</td>\n <td><span class=\"field-type type-text\">TEXT</span></td>\n <td></td>\n <td>错误信息</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">submitted_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT NOW()</span></td>\n <td>提交时间</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">completed_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td></td>\n <td>完成时间</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">created_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT NOW()</span></td>\n <td>创建时间</td>\n</tr>\n", "field_rows": "<tr class=\"row-pk\">\n <td class=\"field-name\">id</td>\n <td><span class=\"field-type type-uuid\">UUID</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span></td>\n <td>主键</td>\n</tr>\n<tr>\n <td class=\"field-name\">call_record_id</td>\n <td><span class=\"field-type type-uuid\">UUID</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span></td>\n <td>关联调用记录 ID(外键 → ai_llmbase_call_records.id)</td>\n</tr>\n<tr>\n <td class=\"field-name\">celery_task_id</td>\n <td><span class=\"field-type type-varchar\">VARCHAR(255)</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-unique\">UNIQUE</span></td>\n <td>Celery 任务 ID</td>\n</tr>\n<tr>\n <td class=\"field-name\">status</td>\n <td><span class=\"field-type type-varchar\">VARCHAR(20)</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT 'pending'</span></td>\n <td>状态:pending/processing/success/failed/cancelled</td>\n</tr>\n<tr>\n <td class=\"field-name\">progress</td>\n <td><span class=\"field-type type-int\">INTEGER</span></td>\n <td><span class=\"constraint-tag c-default\">DEFAULT 0</span></td>\n <td>进度百分比 0-100</td>\n</tr>\n<tr>\n <td class=\"field-name\">result</td>\n <td><span class=\"field-type type-json\">JSONB</span></td>\n <td></td>\n <td>任务结果 JSON</td>\n</tr>\n<tr>\n <td class=\"field-name\">error_message</td>\n <td><span class=\"field-type type-text\">TEXT</span></td>\n <td></td>\n <td>错误信息</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">submitted_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT NOW()</span></td>\n <td>提交时间</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">completed_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td></td>\n <td>完成时间</td>\n</tr>\n<tr class=\"row-ts\">\n <td class=\"field-name\">created_at</td>\n <td><span class=\"field-type type-ts\">TIMESTAMP</span></td>\n <td><span class=\"constraint-tag c-notnull\">NOT NULL</span><span class=\"constraint-tag c-default\">DEFAULT NOW()</span></td>\n <td>创建时间</td>\n</tr>\n",
"index_rows": "<tr>\n <td>idx_at_call_record_id</td>\n <td>call_record_id</td>\n <td>INDEX</td>\n <td>调用记录 ID 索引</td>\n</tr>\n<tr>\n <td>idx_at_celery_task_id</td>\n <td>celery_task_id</td>\n <td>UNIQUE</td>\n <td>Celery 任务 ID 唯一索引</td>\n</tr>\n<tr>\n <td>idx_at_status</td>\n <td>status</td>\n <td>INDEX</td>\n <td>状态索引</td>\n</tr>\n", "index_rows": "<tr>\n <td>idx_at_call_record_id</td>\n <td>call_record_id</td>\n <td>INDEX</td>\n <td>调用记录 ID 索引</td>\n</tr>\n<tr>\n <td>idx_at_celery_task_id</td>\n <td>celery_task_id</td>\n <td>UNIQUE</td>\n <td>Celery 任务 ID 唯一索引</td>\n</tr>\n<tr>\n <td>idx_at_status</td>\n <td>status</td>\n <td>INDEX</td>\n <td>状态索引</td>\n</tr>\n",
"relation_svg": "", "relation_svg": "",
"relation_rows": "<tr>\n <td>ai_llmbase_call_records</td>\n <td>call_record_id</td>\n <td><span class=\"relation-tag rel-1n\">N:1</span></td>\n</tr>\n" "relation_rows": "<tr>\n <td>ai_llmbase_call_records</td>\n <td>call_record_id</td>\n <td><span class=\"relation-tag rel-1n\">N:1</span></td>\n</tr>\n"
......
...@@ -189,7 +189,7 @@ ...@@ -189,7 +189,7 @@
"method": "POST", "method": "POST",
"path": "/api/v1/async-tasks/:task_id/cancel", "path": "/api/v1/async-tasks/:task_id/cancel",
"name": "取消异步任务", "name": "取消异步任务",
"description": "取消正在执行的异步任务", "description": "取消正在执行的异步任务,同步更新关联调用记录状态为 cancelled",
"params": [ "params": [
{"name": "task_id", "in": "path", "type": "string", "required": true, "desc": "任务 ID"} {"name": "task_id", "in": "path", "type": "string", "required": true, "desc": "任务 ID"}
], ],
...@@ -200,10 +200,50 @@ ...@@ -200,10 +200,50 @@
], ],
"backend": [ "backend": [
{"tag": "receive", "text": "接收 POST /api/v1/async-tasks/:task_id/cancel 请求"}, {"tag": "receive", "text": "接收 POST /api/v1/async-tasks/:task_id/cancel 请求"},
{"tag": "validate", "text": "验证请求参数"}, {"tag": "validate", "text": "验证任务存在且状态为 pending/processing"},
{"tag": "write", "text": "向数据库表插入新记录"}, {"tag": "write", "text": "更新 async_tasks 表 status=cancelled"},
{"tag": "write", "text": "更新关联 call_records 表 status=cancelled"},
{"tag": "return", "text": "返回操作结果"} {"tag": "return", "text": "返回操作结果"}
] ]
},
{
"method": "POST",
"path": "/api/v1/async-tasks/batch-cancel",
"name": "批量取消异步任务",
"description": "批量取消多个异步任务,同步更新关联调用记录。支持任意数量任务,内部分批处理(每批 100 条)。",
"params": [
{"name": "task_ids", "in": "body", "type": "array", "required": true, "desc": "待取消的任务 ID 数组"}
],
"responses": [
{"code": 200, "desc": "批量取消成功", "schema": "{total: integer, success_count: integer, failed_count: integer, failed_ids: string[]}"},
{"code": 400, "desc": "参数错误", "schema": ""}
],
"backend": [
{"tag": "receive", "text": "接收 POST /api/v1/async-tasks/batch-cancel 请求"},
{"tag": "validate", "text": "验证 task_ids 数组非空,每项为有效 UUID"},
{"tag": "write", "text": "分批查询 async_tasks 表 WHERE id IN (:ids) AND status IN (pending,processing),每批 100 条"},
{"tag": "write", "text": "逐批更新 async_tasks:status=cancelled"},
{"tag": "write", "text": "逐批更新关联 call_records:status=cancelled"},
{"tag": "return", "text": "返回取消结果统计(total/success_count/failed_count/failed_ids)"}
]
},
{
"method": "POST",
"path": "/api/v1/async-tasks/cancel-all",
"name": "取消全部异步任务",
"description": "取消当前所有 pending/processing 状态的异步任务,同步更新关联调用记录。内部分批处理(每批 100 条),循环直至全部处理完毕。",
"params": [],
"responses": [
{"code": 200, "desc": "取消成功", "schema": "{total: integer, batch_count: integer}"},
{"code": 400, "desc": "无待取消任务", "schema": ""}
],
"backend": [
{"tag": "receive", "text": "接收 POST /api/v1/async-tasks/cancel-all 请求"},
{"tag": "query", "text": "分批查询 async_tasks:WHERE status IN (pending,processing),每批 100 条"},
{"tag": "write", "text": "逐批更新 async_tasks:status=cancelled"},
{"tag": "write", "text": "逐批更新关联 call_records:status=cancelled"},
{"tag": "return", "text": "返回取消结果统计(total/batch_count)"}
]
} }
], ],
"changelogs": [ "changelogs": [
...@@ -216,6 +256,7 @@ ...@@ -216,6 +256,7 @@
"done": true "done": true
}, },
{"date": "2026-06-17", "id": "CHG-019", "type": "modify", "title": "调用详情展示组装过程信息", "desc": "GET /api/v1/calls/:id 增强返回 provider_name 和 template_info(title/code/template_type/system_prompt/user_prompt/version)。POST /api/v1/calls 增加可选 template_id 参数。前端详情弹窗新增「组装过程」Tab 展示模板-变量-请求-响应的完整流程。", "done": true}, {"date": "2026-06-17", "id": "CHG-019", "type": "modify", "title": "调用详情展示组装过程信息", "desc": "GET /api/v1/calls/:id 增强返回 provider_name 和 template_info(title/code/template_type/system_prompt/user_prompt/version)。POST /api/v1/calls 增加可选 template_id 参数。前端详情弹窗新增「组装过程」Tab 展示模板-变量-请求-响应的完整流程。", "done": true},
{"date": "2026-06-17", "id": "CHG-020", "type": "modify", "title": "异步任务列表新增 task_id 搜索功能", "desc": "GET /api/v1/async-tasks 新增 task_id 查询参数,后端按 celery_task_id 模糊匹配。", "done": true} {"date": "2026-06-17", "id": "CHG-020", "type": "modify", "title": "异步任务列表新增 task_id 搜索功能", "desc": "GET /api/v1/async-tasks 新增 task_id 查询参数,后端按 celery_task_id 模糊匹配。", "done": true},
{"date": "2026-06-25", "id": "CHG-026", "type": "modify", "title": "新增批量取消和取消全部任务功能,取消时同步更新调用记录状态", "desc": "1. PUT /api/v1/async-tasks/:task_id/cancel 增强:取消时同步更新关联 call_records 状态为 cancelled\n2. 新增 POST /api/v1/async-tasks/batch-cancel 批量取消接口\n3. 新增 POST /api/v1/async-tasks/cancel-all 取消全部接口", "done": true}
] ]
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!