Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: add deleteAllSessions functionality and update batch delete logic
wizardchen284d6c623e5b
diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.tsindex b93c39218..634958d78 100644--- a/frontend/src/api/chat/index.ts+++ b/frontend/src/api/chat/index.ts@@ -48,6 +48,10 @@ export async function batchDelSessions(ids: string[]) {return del(`/api/v1/sessions/batch`, { ids });}+export async function deleteAllSessions() {+ return del(`/api/v1/sessions/batch`, { delete_all: true });+}+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.vuedeleted file mode 100644index a6f61154b..000000000--- a/frontend/src/components/BatchManageDialog.vue+++ /dev/null@@ -1,424 +0,0 @@-<template>- <Teleport to="body">- <Transition name="modal">- <div v-if="visible" class="batch-overlay" @click.self="handleClose">- <div class="batch-modal">- <!-- 顶部标题栏 -->- <div class="batch-header">- <h2 class="batch-title">{{ t('batchManage.title') }}</h2>- <button class="close-btn" @click="handleClose">- <svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">- <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>- </svg>- </button>- </div>-- <!-- 会话列表 -->- <div class="batch-body">- <div v-if="loading" class="empty-state">- <t-loading />- </div>- <div class="session-list" v-else-if="sessions.length > 0">- <div- class="session-item"- v-for="item in sessions"- :key="item.id"- >- <t-checkbox- :checked="selectedIds.includes(item.id)"- @change="toggleSelect(item.id)"- />- <div class="session-info" @click="toggleSelect(item.id)">- <div class="session-title">{{ item.title || t('menu.newSession') }}</div>- <div class="session-time">{{ formatTime(item.updated_at || item.created_at) }}</div>- </div>- <button class="delete-single-btn" @click="handleDeleteSingle(item)">- <t-icon name="delete" />- </button>- </div>- </div>- <div v-else class="empty-state">- <p>{{ t('menu.newSession') }}</p>- </div>- </div>-- <!-- 底部操作栏 -->- <div class="batch-footer">- <div class="footer-left">- <t-checkbox- :checked="isAllSelected"- :indeterminate="isIndeterminate"- @change="toggleSelectAll"- >- {{ t('batchManage.selectAll') }}- </t-checkbox>- </div>- <div class="footer-right">- <t-button theme="default" variant="outline" @click="handleClose">- {{ t('batchManage.cancel') }}- </t-button>- <t-button- theme="danger"- :disabled="selectedIds.length === 0"- :loading="deleting"- @click="handleBatchDelete"- >- {{ t('batchManage.delete') }}- </t-button>- </div>- </div>- </div>- </div>- </Transition>- </Teleport>-</template>--<script setup lang="ts">-import { ref, computed, watch } from 'vue'-import { useI18n } from 'vue-i18n'-import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'-import { batchDelSessions, delSession, getSessionsList } from '@/api/chat/index'--const { t } = useI18n()--const props = defineProps<{- visible: boolean-}>()--const emit = defineEmits<{- (e: 'update:visible', val: boolean): void- (e: 'deleted', ids: string[]): void-}>()--const selectedIds = ref<string[]>([])-const deleting = ref(false)-const loading = ref(false)-const sessions = ref<Array<{ id: string; title: string; created_at?: string; updated_at?: string }>>([])--const isAllSelected = computed(() =>- sessions.value.length > 0 && selectedIds.value.length === sessions.value.length-)-const isIndeterminate = computed(() =>- selectedIds.value.length > 0 && selectedIds.value.length < sessions.value.length-)--// 打开弹窗时拉取全量会话列表-const fetchAllSessions = async () => {- loading.value = true- try {- const allItems: any[] = []- let page = 1- const pageSize = 100- let hasMore = true- while (hasMore) {- const res: any = await getSessionsList(page, pageSize)- const items = res?.data?.items || res?.data || []- allItems.push(...items)- const total = res?.data?.total ?? items.length- hasMore = allItems.length < total- page++- }- sessions.value = allItems.map((s: any) => ({- id: s.id,- title: s.title,- created_at: s.created_at,- updated_at: s.updated_at,- }))- } catch {- sessions.value = []- MessagePlugin.error(t('batchManage.loadFailed') || 'Failed to load sessions')- }- loading.value = false-}--watch(() => props.visible, (val) => {- if (val) {- selectedIds.value = []- fetchAllSessions()- }-})--const toggleSelect = (id: string) => {- const idx = selectedIds.value.indexOf(id)- if (idx > -1) {- selectedIds.value.splice(idx, 1)- } else {- selectedIds.value.push(id)- }-}--const toggleSelectAll = (checked: boolean) => {- selectedIds.value = checked ? sessions.value.map(s => s.id) : []-}--const formatTime = (dateStr?: string) => {- if (!dateStr) return ''- const d = new Date(dateStr)- const pad = (n: number) => String(n).padStart(2, '0')- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`-}--const handleDeleteSingle = (item: { id: string; title: string }) => {- const confirmDialog = DialogPlugin.confirm({- header: t('batchManage.deleteConfirmTitle'),- body: t('batchManage.deleteConfirmBody', { count: 1 }),- confirmBtn: { content: t('common.delete'), theme: 'danger' },- cancelBtn: t('common.cancel'),- theme: 'warning',- onConfirm: async () => {- try {- const res: any = await delSession(item.id)- if (res && res.success === true) {- sessions.value = sessions.value.filter(s => s.id !== item.id)- selectedIds.value = selectedIds.value.filter(id => id !== item.id)- emit('deleted', [item.id])- MessagePlugin.success(t('batchManage.deleteSuccess'))- } else {- MessagePlugin.error(t('batchManage.deleteFailed'))- }- } catch {- MessagePlugin.error(t('batchManage.deleteFailed'))- }- confirmDialog.destroy()- },- })-}--const handleBatchDelete = () => {- if (selectedIds.value.length === 0) {- MessagePlugin.warning(t('batchManage.noSelection'))- return- }- const confirmDialog = DialogPlugin.confirm({- header: t('batchManage.deleteConfirmTitle'),- body: t('batchManage.deleteConfirmBody', { count: selectedIds.value.length }),- confirmBtn: { content: t('common.delete'), theme: 'danger' },- cancelBtn: t('common.cancel'),- theme: 'warning',- onConfirm: async () => {- deleting.value = true- try {- const ids = [...selectedIds.value]- const res: any = await batchDelSessions(ids)- if (res && res.success === true) {- sessions.value = sessions.value.filter(s => !ids.includes(s.id))- emit('deleted', ids)- selectedIds.value = []- MessagePlugin.success(t('batchManage.deleteSuccess'))- } else {- MessagePlugin.error(t('batchManage.deleteFailed'))- }- } catch {- MessagePlugin.error(t('batchManage.deleteFailed'))- }- deleting.value = false- confirmDialog.destroy()- },- })-}--const handleClose = () => {- emit('update:visible', false)-}-</script>--<style lang="less" scoped>-/* 遮罩层 - 与 Settings.vue 保持一致 */-.batch-overlay {- position: fixed;- inset: 0;- z-index: 1100;- background: rgba(0, 0, 0, 0.5);- display: flex;- align-items: center;- justify-content: center;- padding: 20px;- backdrop-filter: blur(4px);-}--/* 弹窗容器 */-.batch-modal {- position: relative;- width: 100%;- max-width: 600px;- max-height: 70vh;- background: #ffffff;- border-radius: 12px;- box-shadow: 0 6px 28px rgba(15, 23, 42, 0.08);- display: flex;- flex-direction: column;- overflow: hidden;-}--/* 顶部标题栏 */-.batch-header {- display: flex;- align-items: center;- justify-content: space-between;- padding: 20px 24px 16px;- border-bottom: 1px solid #e5e7eb;- flex-shrink: 0;-}--.batch-title {- font-size: 18px;- font-weight: 600;- color: #333333;- margin: 0;-}--.close-btn {- width: 32px;- height: 32px;- border: none;- background: transparent;- color: #666666;- cursor: pointer;- border-radius: 6px;- display: flex;- align-items: center;- justify-content: center;- transition: all 0.2s ease;-- &:hover {- background: #f5f5f5;- color: #333333;- }-}--/* 会话列表区域 */-.batch-body {- flex: 1;- overflow-y: auto;- min-height: 0;-}--/* 滚动条样式 - 与 Settings 一致 */-.batch-body::-webkit-scrollbar {- width: 6px;-}-.batch-body::-webkit-scrollbar-track {- background: #ffffff;-}-.batch-body::-webkit-scrollbar-thumb {- background: #d0d0d0;- border-radius: 3px;-}-.batch-body::-webkit-scrollbar-thumb:hover {- background: #b0b0b0;-}--.session-list {- padding: 4px 0;-}--.session-item {- display: flex;- align-items: center;- padding: 14px 24px;- border-bottom: 1px solid #f0f0f0;- gap: 14px;- transition: background 0.2s ease;-- &:last-child {- border-bottom: none;- }-- &:hover {- background: #f8f9fa;-- .delete-single-btn {- opacity: 1;- }- }-}--.session-info {- flex: 1;- min-width: 0;- cursor: pointer;-}--.session-title {- font-size: 14px;- font-weight: 400;- color: #333333;- overflow: hidden;- white-space: nowrap;- text-overflow: ellipsis;- line-height: 22px;-}--.session-time {- font-size: 12px;- color: #999999;- margin-top: 4px;- line-height: 18px;-}--.delete-single-btn {- opacity: 0;- transition: all 0.2s ease;- width: 32px;- height: 32px;- border: none;- background: transparent;- color: #999999;- cursor: pointer;- border-radius: 6px;- display: flex;- align-items: center;- justify-content: center;- flex-shrink: 0;-- &:hover {- color: #e34d59;- background: rgba(227, 77, 89, 0.06);- }-}--.empty-state {- padding: 48px 24px;- text-align: center;- color: #999999;- font-size: 14px;-}--/* 底部操作栏 */-.batch-footer {- display: flex;- align-items: center;- justify-content: space-between;- padding: 16px 24px;- border-top: 1px solid #e5e7eb;- flex-shrink: 0;- background: #ffffff;-}--.footer-right {- display: flex;- gap: 8px;-}--/* 弹窗动画 */-.modal-enter-active,-.modal-leave-active {- transition: opacity 0.2s ease;-}--.modal-enter-active .batch-modal,-.modal-leave-active .batch-modal {- transition: transform 0.2s ease, opacity 0.2s ease;-}--.modal-enter-from,-.modal-leave-to {- opacity: 0;-}--.modal-enter-from .batch-modal,-.modal-leave-to .batch-modal {- transform: scale(0.95);- opacity: 0;-}-</style>diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vueindex fedf5d9f9..996a45333 100644--- a/frontend/src/components/menu.vue+++ b/frontend/src/components/menu.vue@@ -71,7 +71,7 @@:loading="batchDeleting"@click="handleInlineBatchDelete">- {{ t('batchManage.delete') }}{{ batchSelectedIds.length > 0 ? `(${batchSelectedIds.length})` : '' }}+ {{ t('batchManage.delete') }}{{ batchSelectedIds.length > 0 ? `(${batchDisplayCount})` : '' }}</t-button></div></div>@@ -83,12 +83,6 @@<UserMenu /></div>- <!-- 批量管理对话框 -->- <BatchManageDialog- v-model:visible="batchManageVisible"- @deleted="handleBatchDeleted"- />-</div></template>@@ -96,7 +90,7 @@import { storeToRefs } from 'pinia';import { onMounted, watch, computed, ref } from 'vue';import { useRoute, useRouter } from 'vue-router';-import { getSessionsList, delSession, batchDelSessions } from "@/api/chat/index";+import { getSessionsList, delSession, batchDelSessions, deleteAllSessions } from "@/api/chat/index";import { getKnowledgeBaseById } from '@/api/knowledge-base';import { logout as logoutApi } from '@/api/auth';import { useMenuStore } from '@/stores/menu';@@ -133,6 +127,24 @@ const batchMode = ref(false)const batchSelectedIds = ref<string[]>([])const batchDeleting = ref(false)+const allSessionIds = computed(() => {+ const chatMenu = (menuArr.value as unknown as MenuItem[]).find((item: MenuItem) => item.path === 'creatChat');+ if (!chatMenu?.children) return [];+ return (chatMenu.children as any[]).map((s: any) => s.id);+})++const isAllBatchSelected = computed(() =>+ allSessionIds.value.length > 0 && batchSelectedIds.value.length === allSessionIds.value.length+)++const isBatchIndeterminate = computed(() =>+ batchSelectedIds.value.length > 0 && batchSelectedIds.value.length < allSessionIds.value.length+)++const batchDisplayCount = computed(() =>+ isAllBatchSelected.value ? total.value : batchSelectedIds.value.length+)+// 是否可以访问所有租户const canAccessAllTenants = computed(() => authStore.canAccessAllTenants);@@ -319,35 +331,47 @@ const toggleBatchSelectAll = (checked: boolean) => {const handleInlineBatchDelete = () => {if (batchSelectedIds.value.length === 0) return+ const isDeleteAll = isAllBatchSelected.value+ const displayCount = batchDisplayCount.valueconst confirmDialog = DialogPlugin.confirm({header: t('batchManage.deleteConfirmTitle'),- body: t('batchManage.deleteConfirmBody', { count: batchSelectedIds.value.length }),+ body: isDeleteAll+ ? t('batchManage.deleteAllConfirmBody') || t('batchManage.deleteConfirmBody', { count: displayCount })+ : t('batchManage.deleteConfirmBody', { count: displayCount }),confirmBtn: { content: t('batchManage.delete'), theme: 'danger' as const },cancelBtn: t('batchManage.cancel'),theme: 'warning',onConfirm: async () => {batchDeleting.value = truetry {- const ids = [...batchSelectedIds.value]- const res: any = await batchDelSessions(ids)+ let res: any+ if (isDeleteAll) {+ res = await deleteAllSessions()+ } else {+ res = await batchDelSessions([...batchSelectedIds.value])+ }if (res && res.success === true) {const chatMenuItem = (menuArr.value as any[]).find((m: any) => m.path === 'creatChat');- if (chatMenuItem && chatMenuItem.children) {- for (const id of ids) {- const idx = chatMenuItem.children.findIndex((s: any) => s.id === id);- if (idx !== -1) chatMenuItem.children.splice(idx, 1);+ if (isDeleteAll) {+ if (chatMenuItem) chatMenuItem.children = [];+ total.value = 0;+ } else {+ const ids = [...batchSelectedIds.value]+ if (chatMenuItem && chatMenuItem.children) {+ for (const id of ids) {+ const idx = chatMenuItem.children.findIndex((s: any) => s.id === id);+ if (idx !== -1) chatMenuItem.children.splice(idx, 1);+ }}+ total.value = Math.max(0, total.value - ids.length);}- total.value = Math.max(0, total.value - ids.length);const currentChatId = route.params.chatid as string;- if (currentChatId && ids.includes(currentChatId)) {+ if (currentChatId && (isDeleteAll || batchSelectedIds.value.includes(currentChatId))) {router.push('/platform/creatChat');}batchSelectedIds.value = []MessagePlugin.success(t('batchManage.deleteSuccess'))- if (!chatMenuItem?.children?.length) {- exitBatchMode()- }+ exitBatchMode()} else {MessagePlugin.error(t('batchManage.deleteFailed'))}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex ea59fa726..296c1f0ae 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -23,6 +23,7 @@ export default {delete: 'Delete Conversations',deleteConfirmTitle: 'Delete Conversations',deleteConfirmBody: 'Are you sure you want to delete the selected {count} conversation(s)? This action cannot be undone.',+ deleteAllConfirmBody: 'Are you sure you want to delete all conversations? This action cannot be undone.',deleteSuccess: 'Deleted successfully',deleteFailed: 'Delete failed, please try again later',noSelection: 'Please select at least one conversation',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 913070a7a..9825e8c56 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -23,6 +23,7 @@ export default {delete: "대화 삭제",deleteConfirmTitle: "대화 삭제",deleteConfirmBody: "선택한 {count}개의 대화를 삭제하시겠습니까? 삭제 후 복구할 수 없습니다.",+ deleteAllConfirmBody: "모든 대화를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.",deleteSuccess: "삭제 성공",deleteFailed: "삭제 실패, 나중에 다시 시도해 주세요",noSelection: "최소 하나의 대화를 선택해 주세요",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 5f370a995..bb10d6638 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -21,6 +21,7 @@ export default {delete: 'Удалить диалоги',deleteConfirmTitle: 'Удалить диалоги',deleteConfirmBody: 'Вы уверены, что хотите удалить выбранные {count} диалог(ов)? Это действие необратимо.',+ deleteAllConfirmBody: 'Вы уверены, что хотите удалить все диалоги? Это действие необратимо.',deleteSuccess: 'Успешно удалено',deleteFailed: 'Ошибка удаления, попробуйте позже',noSelection: 'Выберите хотя бы один диалог',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex e2533d091..806f9adf1 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -23,6 +23,7 @@ export default {delete: "删除对话",deleteConfirmTitle: "删除对话",deleteConfirmBody: "确定要删除选中的 {count} 条对话吗?删除后无法恢复。",+ deleteAllConfirmBody: "确定要删除所有对话吗?此操作无法恢复。",deleteSuccess: "删除成功",deleteFailed: "删除失败,请稍后再试",noSelection: "请至少选择一条对话",diff --git a/internal/application/repository/session.go b/internal/application/repository/session.goindex 666261b14..9187fce3a 100644--- a/internal/application/repository/session.go+++ b/internal/application/repository/session.go@@ -95,3 +95,8 @@ func (r *sessionRepository) BatchDelete(ctx context.Context, tenantID uint64, id}return r.db.WithContext(ctx).Where("tenant_id = ? AND id IN ?", tenantID, ids).Delete(&types.Session{}).Error}++// DeleteAllByTenantID deletes all sessions for a tenant+func (r *sessionRepository) DeleteAllByTenantID(ctx context.Context, tenantID uint64) error {+ return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}).Error+}diff --git a/internal/application/service/session.go b/internal/application/service/session.goindex 8a09f0f60..527ae5a6f 100644--- a/internal/application/service/session.go+++ b/internal/application/service/session.go@@ -260,6 +260,36 @@ func (s *sessionService) BatchDeleteSessions(ctx context.Context, ids []string)return nil}+// DeleteAllSessions deletes all sessions for the current tenant+func (s *sessionService) DeleteAllSessions(ctx context.Context) error {+ tenantID := types.MustTenantIDFromContext(ctx)+ logger.Infof(ctx, "Deleting all sessions for tenant %d", tenantID)++ sessions, err := s.sessionRepo.GetByTenantID(ctx, tenantID)+ if err != nil {+ logger.Warnf(ctx, "Failed to list sessions for cleanup: %v", err)+ } else {+ for _, session := range sessions {+ if err := s.webSearchStateRepo.DeleteWebSearchTempKBState(ctx, session.ID); err != nil {+ logger.Warnf(ctx, "Failed to cleanup temporary KB for session %s: %v", session.ID, err)+ }+ if err := s.sessionStorage.Delete(ctx, session.ID); err != nil {+ logger.Warnf(ctx, "Failed to cleanup conversation context for session %s: %v", session.ID, err)+ }+ }+ }++ if err := s.sessionRepo.DeleteAllByTenantID(ctx, tenantID); err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{+ "tenant_id": tenantID,+ })+ return err+ }++ logger.Infof(ctx, "All sessions deleted for tenant %d", tenantID)+ 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.goindex ef139c392..d05d73a59 100644--- a/internal/handler/session/handler.go+++ b/internal/handler/session/handler.go@@ -306,12 +306,13 @@ func (h *Handler) DeleteSession(c *gin.Context) {// batchDeleteRequest represents the request body for batch deleting sessionstype batchDeleteRequest struct {- IDs []string `json:"ids" binding:"required,min=1"`+ IDs []string `json:"ids"`+ DeleteAll bool `json:"delete_all"`}// BatchDeleteSessions godoc// @Summary 批量删除会话-// @Description 根据ID列表批量删除对话会话+// @Description 根据ID列表批量删除对话会话,或设置 delete_all=true 删除当前租户的所有会话// @Tags 会话// @Accept json// @Produce json@@ -327,7 +328,25 @@ func (h *Handler) BatchDeleteSessions(c *gin.Context) {var req batchDeleteRequestif err := c.ShouldBindJSON(&req); err != nil {logger.Errorf(ctx, "Invalid batch delete request: %v", err)- c.Error(errors.NewBadRequestError("invalid request: ids are required"))+ c.Error(errors.NewBadRequestError("invalid request"))+ return+ }++ if req.DeleteAll {+ if err := h.sessionService.DeleteAllSessions(ctx); err != nil {+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(errors.NewInternalServerError(err.Error()))+ return+ }+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "message": "All sessions deleted successfully",+ })+ return+ }++ if len(req.IDs) == 0 {+ c.Error(errors.NewBadRequestError("ids are required when delete_all is false"))return}diff --git a/internal/types/interfaces/session.go b/internal/types/interfaces/session.goindex 1a4b9b229..9b2d53f95 100644--- a/internal/types/interfaces/session.go+++ b/internal/types/interfaces/session.go@@ -23,6 +23,8 @@ type SessionService interface {DeleteSession(ctx context.Context, id string) error// BatchDeleteSessions deletes multiple sessions by IDsBatchDeleteSessions(ctx context.Context, ids []string) error+ // DeleteAllSessions deletes all sessions for the current tenant+ DeleteAllSessions(ctx context.Context) 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)@@ -84,4 +86,6 @@ type SessionRepository interface {Delete(ctx context.Context, tenantID uint64, id string) error// BatchDelete deletes multiple sessions by IDsBatchDelete(ctx context.Context, tenantID uint64, ids []string) error+ // DeleteAllByTenantID deletes all sessions for a tenant+ DeleteAllByTenantID(ctx context.Context, tenantID uint64) error}