diff --git a/docs/api/session.md b/docs/api/session.md index 11961136..3d116b9c 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -9,6 +9,7 @@ | GET | `/sessions` | 获取租户的会话列表 | | PUT | `/sessions/:id` | 更新会话 | | DELETE | `/sessions/:id` | 删除会话 | +| DELETE | `/sessions/batch` | 批量删除会话 | | POST | `/sessions/:session_id/generate_title` | 生成会话标题 | | POST | `/sessions/:session_id/stop` | 停止会话 | | GET | `/sessions/continue-stream/:session_id` | 继续未完成的会话 | @@ -315,6 +316,31 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/sessions/411d6b70 } ``` +## DELETE `/sessions/batch` - 批量删除会话 + +**请求**: + +```curl +curl --location --request DELETE 'http://localhost:8080/api/v1/sessions/batch' \ +--header 'X-API-Key: sk-vQHV2NZI_LK5W7wHQvH3yGYExX8YnhaHwZipUYbiZKCYJbBQ' \ +--header 'Content-Type: application/json' \ +--data '{ + "ids": [ + "411d6b70-9a85-4d03-bb74-aab0fd8bd12f", + "ceb9babb-1e30-41d7-817d-fd584954304b" + ] +}' +``` + +**响应**: + +```json +{ + "message": "Sessions deleted successfully", + "success": true +} +``` + ## POST `/sessions/:session_id/generate_title` - 生成会话标题 **请求**: diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index 5b3be855..b93c3921 100644 --- a/frontend/src/api/chat/index.ts +++ b/frontend/src/api/chat/index.ts @@ -44,6 +44,10 @@ export async function delSession(session_id: string) { return del(`/api/v1/sessions/${session_id}`); } +export async function batchDelSessions(ids: string[]) { + return del(`/api/v1/sessions/batch`, { ids }); +} + export async function getSession(session_id: string) { return get(`/api/v1/sessions/${session_id}`); } diff --git a/frontend/src/components/BatchManageDialog.vue b/frontend/src/components/BatchManageDialog.vue new file mode 100644 index 00000000..721ec28c --- /dev/null +++ b/frontend/src/components/BatchManageDialog.vue @@ -0,0 +1,390 @@ + + + + + + + + {{ t('batchManage.title') }} + + + + + + + + + + + + + + {{ item.title || t('menu.newSession') }} + {{ formatTime(item.updated_at || item.created_at) }} + + + + + + + + {{ t('menu.newSession') }} + + + + + + + + + + + + + + diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index ab664b0a..d703d0f6 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -34,7 +34,7 @@ {{ subitem.title }} @@ -54,6 +54,13 @@ + + + @@ -72,6 +79,7 @@ import { useUIStore } from '@/stores/ui'; import { MessagePlugin } from "tdesign-vue-next"; import UserMenu from '@/components/UserMenu.vue'; import TenantSelector from '@/components/TenantSelector.vue'; +import BatchManageDialog from '@/components/BatchManageDialog.vue'; import { useI18n } from 'vue-i18n'; const { t } = useI18n(); @@ -94,6 +102,21 @@ type MenuItem = { title: string; icon: string; path: string; childrenPath?: stri const { menuArr } = storeToRefs(usemenuStore); let activeSubmenu = ref(''); +// 批量管理状态 +const batchManageVisible = ref(false); + +// 所有会话列表(用于批量管理对话框) +const allSessions = computed(() => { + const chatMenu = (menuArr.value as unknown as MenuItem[]).find((item: MenuItem) => item.path === 'creatChat'); + if (!chatMenu || !chatMenu.children) return []; + return chatMenu.children.map((s: any) => ({ + id: s.id, + title: s.title, + created_at: s.created_at, + updated_at: s.updated_at, + })); +}); + // 是否可以访问所有租户 const canAccessAllTenants = computed(() => authStore.canAccessAllTenants); @@ -256,6 +279,8 @@ const mouseleaveBotDown = () => { const handleSessionMenuClick = (data: { value: string }, index: number, item: any) => { if (data?.value === 'delete') { delCard(index, item); + } else if (data?.value === 'batchManage') { + batchManageVisible.value = true; } }; @@ -288,6 +313,24 @@ const delCard = (index: number, item: any) => { } }) } + +const handleBatchDeleted = (ids: string[]) => { + const chatMenuItem = (menuArr.value as any[]).find((m: any) => m.path === 'creatChat'); + if (chatMenuItem && chatMenuItem.children) { + const children = chatMenuItem.children; + for (const id of ids) { + const idx = children.findIndex((s: any) => s.id === id); + if (idx !== -1) children.splice(idx, 1); + } + } + total.value = Math.max(0, total.value - ids.length); + // 如果当前会话被删除,跳转到创建页 + const currentChatId = route.params.chatid as string; + if (currentChatId && ids.includes(currentChatId)) { + router.push('/platform/creatChat'); + } +} + const debounce = (fn: (...args: any[]) => void, delay: number) => { let timer: ReturnType return (...args: any[]) => { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index e07d46f5..d03fa232 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -10,10 +10,22 @@ export default { logout: 'Logout', uploadKnowledge: 'Upload Knowledge', deleteRecord: 'Delete Record', + batchManage: 'Batch Manage', newSession: 'New Chat', confirmLogout: 'Are you sure you want to logout?', systemInfo: 'System Information' }, + batchManage: { + title: 'Manage Conversations', + selectAll: 'Select All', + cancel: 'Cancel', + delete: 'Delete Conversations', + deleteConfirmTitle: 'Delete Conversations', + deleteConfirmBody: 'Are you sure you want to delete the selected {count} conversation(s)? This action cannot be undone.', + deleteSuccess: 'Deleted successfully', + deleteFailed: 'Delete failed, please try again later', + noSelection: 'Please select at least one conversation', + }, listSpaceSidebar: { title: 'Filter', all: 'All', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 76363997..83841121 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -8,10 +8,22 @@ export default { logout: "로그아웃", uploadKnowledge: "지식 업로드", deleteRecord: "기록 삭제", + batchManage: "일괄 관리", newSession: "새 세션", confirmLogout: "정말 로그아웃 하시겠습니까?", systemInfo: "시스템 정보", }, + batchManage: { + title: "대화 관리", + selectAll: "전체 선택", + cancel: "취소", + delete: "대화 삭제", + deleteConfirmTitle: "대화 삭제", + deleteConfirmBody: "선택한 {count}개의 대화를 삭제하시겠습니까? 삭제 후 복구할 수 없습니다.", + deleteSuccess: "삭제 성공", + deleteFailed: "삭제 실패, 나중에 다시 시도해 주세요", + noSelection: "최소 하나의 대화를 선택해 주세요", + }, knowledgeBase: { title: "지식베이스", list: "지식베이스 목록", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index c7bcca38..979b4f6a 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -8,10 +8,22 @@ export default { logout: 'Выход', uploadKnowledge: 'Загрузить знания', deleteRecord: 'Удалить запись', + batchManage: 'Пакетное управление', newSession: 'Новый диалог', confirmLogout: 'Вы уверены, что хотите выйти?', systemInfo: 'Информация о системе' }, + batchManage: { + title: 'Управление диалогами', + selectAll: 'Выбрать все', + cancel: 'Отмена', + delete: 'Удалить диалоги', + deleteConfirmTitle: 'Удалить диалоги', + deleteConfirmBody: 'Вы уверены, что хотите удалить выбранные {count} диалог(ов)? Это действие необратимо.', + deleteSuccess: 'Успешно удалено', + deleteFailed: 'Ошибка удаления, попробуйте позже', + noSelection: 'Выберите хотя бы один диалог', + }, knowledgeBase: { title: 'База знаний', list: 'Список баз знаний', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 85072643..0e1735e3 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -10,10 +10,22 @@ export default { logout: "退出登录", uploadKnowledge: "上传知识", deleteRecord: "删除记录", + batchManage: "批量管理", newSession: "新会话", confirmLogout: "确定要退出登录吗?", systemInfo: "系统信息", }, + batchManage: { + title: "管理对话记录", + selectAll: "全选", + cancel: "取消", + delete: "删除对话", + deleteConfirmTitle: "删除对话", + deleteConfirmBody: "确定要删除选中的 {count} 条对话吗?删除后无法恢复。", + deleteSuccess: "删除成功", + deleteFailed: "删除失败,请稍后再试", + noSelection: "请至少选择一条对话", + }, listSpaceSidebar: { title: "筛选", all: "全部", diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go index 2219f1d3..666261b1 100644 --- a/internal/application/repository/session.go +++ b/internal/application/repository/session.go @@ -87,3 +87,11 @@ func (r *sessionRepository) Update(ctx context.Context, session *types.Session) func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, id string) error { return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}, "id = ?", id).Error } + +// BatchDelete deletes multiple sessions by IDs +func (r *sessionRepository) BatchDelete(ctx context.Context, tenantID uint64, ids []string) error { + if len(ids) == 0 { + return nil + } + return r.db.WithContext(ctx).Where("tenant_id = ? AND id IN ?", tenantID, ids).Delete(&types.Session{}).Error +} diff --git a/internal/application/service/session.go b/internal/application/service/session.go index dee8653a..30de72f5 100644 --- a/internal/application/service/session.go +++ b/internal/application/service/session.go @@ -225,6 +225,38 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error { return nil } +// BatchDeleteSessions deletes multiple sessions by IDs +func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string) error { + if len(ids) == 0 { + logger.Error(ctx, "Failed to batch delete sessions: IDs list is empty") + return errors.New("session ids are required") + } + + // Get tenant ID from context + tenantID := ctx.Value(types.TenantIDContextKey).(uint64) + + // Cleanup associated resources for each session + for _, id := range ids { + if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, id); err != nil { + logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", id, err) + } + if err := s.sessionStorage.Delete(ctx, id); err != nil { + logger.Warnf(ctx, "Failed to cleanup conversation context for session %s: %v", id, err) + } + } + + // Batch delete sessions from repository + if err := s.sessionRepo.BatchDelete(ctx, tenantID, ids); err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "session_ids": ids, + "tenant_id": tenantID, + }) + return err + } + + return nil +} + // GenerateTitle generates a title for the current conversation content // modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model) func (s *sessionService) GenerateTitle(ctx context.Context, diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 20e032f3..ef139c39 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -303,3 +303,56 @@ func (h *Handler) DeleteSession(c *gin.Context) { "message": "Session deleted successfully", }) } + +// batchDeleteRequest represents the request body for batch deleting sessions +type batchDeleteRequest struct { + IDs []string `json:"ids" binding:"required,min=1"` +} + +// BatchDeleteSessions godoc +// @Summary 批量删除会话 +// @Description 根据ID列表批量删除对话会话 +// @Tags 会话 +// @Accept json +// @Produce json +// @Param request body batchDeleteRequest true "批量删除请求" +// @Success 200 {object} map[string]interface{} "删除结果" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /sessions/batch [delete] +func (h *Handler) BatchDeleteSessions(c *gin.Context) { + ctx := c.Request.Context() + + var req batchDeleteRequest + if err := c.ShouldBindJSON(&req); err != nil { + logger.Errorf(ctx, "Invalid batch delete request: %v", err) + c.Error(errors.NewBadRequestError("invalid request: ids are required")) + return + } + + // Sanitize all IDs + sanitizedIDs := make([]string, 0, len(req.IDs)) + for _, id := range req.IDs { + sanitized := secutils.SanitizeForLog(id) + if sanitized != "" { + sanitizedIDs = append(sanitizedIDs, sanitized) + } + } + + if len(sanitizedIDs) == 0 { + c.Error(errors.NewBadRequestError("no valid session IDs provided")) + return + } + + if err := h.sessionService.BatchDeleteSessions(ctx, sanitizedIDs); err != nil { + logger.ErrorWithFields(ctx, err, nil) + c.Error(errors.NewInternalServerError(err.Error())) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": "Sessions deleted successfully", + }) +} diff --git a/internal/router/router.go b/internal/router/router.go index 8d533635..10315482 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -266,6 +266,7 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) { sessions := r.Group("/sessions") { sessions.POST("", handler.CreateSession) + sessions.DELETE("/batch", handler.BatchDeleteSessions) sessions.GET("/:id", handler.GetSession) sessions.GET("", handler.GetSessionsByTenant) sessions.PUT("/:id", handler.UpdateSession) diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.go index 30a7fbe8..264ee6809 100644 --- a/internal/types/interfaces/session.go +++ b/internal/types/interfaces/session.go @@ -21,6 +21,8 @@ type SessionService interface { UpdateSession(ctx context.Context, session *types.Session) error // DeleteSession deletes a session DeleteSession(ctx context.Context, id string) error + // BatchDeleteSessions deletes multiple sessions by IDs + BatchDeleteSessions(ctx context.Context, ids []string) error // GenerateTitle generates a title for the current conversation // modelID: optional model ID to use for title generation (if empty, uses first available KnowledgeQA model) GenerateTitle(ctx context.Context, session *types.Session, messages []types.Message, modelID string) (string, error) @@ -79,4 +81,6 @@ type SessionRepository interface { Update(ctx context.Context, session *types.Session) error // Delete deletes a session Delete(ctx context.Context, tenantID uint64, id string) error + // BatchDelete deletes multiple sessions by IDs + BatchDelete(ctx context.Context, tenantID uint64, ids []string) error }
{{ t('menu.newSession') }}