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 clear session messages functionality
wizardchende0e93d9bbd4
diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.tsindex 634958d78..8b59875d4 100644--- a/frontend/src/api/chat/index.ts+++ b/frontend/src/api/chat/index.ts@@ -58,4 +58,8 @@ export async function getSession(session_id: string) {export async function stopSession(session_id: string, message_id: string) {return post(`/api/v1/sessions/${session_id}/stop`, { message_id });+}++export async function clearSessionMessages(session_id: string) {+ return del(`/api/v1/sessions/${session_id}/messages`);}\ No newline at end of filediff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vueindex 957edc39a..a4063f0b6 100644--- a/frontend/src/components/menu.vue+++ b/frontend/src/components/menu.vue@@ -77,7 +77,7 @@{{ subitem.title }}</span><t-dropdown v-if="!batchMode"- :options="[{ content: t('upload.deleteRecord'), value: 'delete' }, { content: t('menu.batchManage'), value: 'batchManage' }]"+ :options="[{ content: t('menu.clearMessages'), value: 'clearMessages' }, { content: t('upload.deleteRecord'), value: 'delete' }, { content: t('menu.batchManage'), value: 'batchManage' }]"@click="handleSessionMenuClick($event, subitem.originalIndex, subitem)"placement="bottom-right"trigger="click">@@ -126,7 +126,7 @@import { storeToRefs } from 'pinia';import { onMounted, watch, computed, ref } from 'vue';import { useRoute, useRouter } from 'vue-router';-import { getSessionsList, delSession, batchDelSessions, deleteAllSessions } from "@/api/chat/index";+import { getSessionsList, delSession, batchDelSessions, deleteAllSessions, clearSessionMessages } from "@/api/chat/index";import { getKnowledgeBaseById } from '@/api/knowledge-base';import { logout as logoutApi } from '@/api/auth';import { useMenuStore } from '@/stores/menu';@@ -423,11 +423,28 @@ const handleInlineBatchDelete = () => {const handleSessionMenuClick = (data: { value: string }, index: number, item: any) => {if (data?.value === 'delete') {delCard(index, item);+ } else if (data?.value === 'clearMessages') {+ clearMessages(item);} else if (data?.value === 'batchManage') {enterBatchMode()}};+const clearMessages = (item: any) => {+ clearSessionMessages(item.id).then((res: any) => {+ if (res && res.success) {+ MessagePlugin.success(t('menu.clearMessagesSuccess'));+ if (item.id === route.params.chatid) {+ window.dispatchEvent(new CustomEvent('session-messages-cleared', { detail: { sessionId: item.id } }));+ }+ } else {+ MessagePlugin.error(t('menu.clearMessagesFailed'));+ }+ }).catch(() => {+ MessagePlugin.error(t('menu.clearMessagesFailed'));+ });+};+const delCard = (index: number, item: any) => {delSession(item.id).then((res: any) => {if (res && (res as any).success) {diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 89bdf6318..e103fb951 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -10,6 +10,9 @@ export default {logout: 'Logout',uploadKnowledge: 'Upload Knowledge',deleteRecord: 'Delete Record',+ clearMessages: 'Clear Messages',+ clearMessagesSuccess: 'Messages cleared',+ clearMessagesFailed: 'Failed to clear messages, please try again later',batchManage: 'Batch Manage',newSession: 'New Chat',confirmLogout: 'Are you sure you want to logout?',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 966c22fd1..63580e0da 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -10,6 +10,9 @@ export default {logout: "로그아웃",uploadKnowledge: "지식 업로드",deleteRecord: "기록 삭제",+ clearMessages: "메시지 지우기",+ clearMessagesSuccess: "메시지가 지워졌습니다",+ clearMessagesFailed: "메시지 지우기 실패, 나중에 다시 시도해 주세요",batchManage: "일괄 관리",newSession: "새 세션",confirmLogout: "정말 로그아웃 하시겠습니까?",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 82138efb3..54797ee01 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -8,6 +8,9 @@ export default {logout: 'Выход',uploadKnowledge: 'Загрузить знания',deleteRecord: 'Удалить запись',+ clearMessages: 'Очистить сообщения',+ clearMessagesSuccess: 'Сообщения очищены',+ clearMessagesFailed: 'Не удалось очистить сообщения, попробуйте позже',batchManage: 'Пакетное управление',newSession: 'Новый диалог',confirmLogout: 'Вы уверены, что хотите выйти?',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 048c7a53e..8b3e7477e 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -10,6 +10,9 @@ export default {logout: "退出登录",uploadKnowledge: "上传知识",deleteRecord: "删除记录",+ clearMessages: "清空消息",+ clearMessagesSuccess: "消息已清空",+ clearMessagesFailed: "清空消息失败,请稍后再试",batchManage: "批量管理",newSession: "新会话",confirmLogout: "确定要退出登录吗?",diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex 492d7900c..3d30eba63 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -955,7 +955,15 @@ const updateAssistantSession = (payload) => {}scrollToBottom();}+const handleSessionCleared = (e) => {+ if (e.detail?.sessionId === session_id.value) {+ messagesList.splice(0);+ created_at.value = '';+ }+};+onMounted(async () => {+ window.addEventListener('session-messages-cleared', handleSessionCleared);messagesList.splice(0);// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store@@ -1001,6 +1009,9 @@ const clearData = () => {userquery.value = '';}+onUnmounted(() => {+ window.removeEventListener('session-messages-cleared', handleSessionCleared);+});onBeforeRouteLeave((to, from, next) => {clearData()next()diff --git a/internal/application/repository/message.go b/internal/application/repository/message.goindex 011d1ca81..c5d7f4ce5 100644--- a/internal/application/repository/message.go+++ b/internal/application/repository/message.go@@ -245,6 +245,11 @@ func (r *messageRepository) UpdateMessageImages(ctx context.Context, sessionID,Update("images", images).Error}+// DeleteMessagesBySessionID deletes all messages belonging to a session (soft delete)+func (r *messageRepository) DeleteMessagesBySessionID(ctx context.Context, sessionID string) error {+ return r.db.WithContext(ctx).Where("session_id = ?", sessionID).Delete(&types.Message{}).Error+}+// UpdateMessageKnowledgeID updates the knowledge_id field for a messagefunc (r *messageRepository) UpdateMessageKnowledgeID(ctx context.Context, messageID string, knowledgeID string,diff --git a/internal/application/service/message.go b/internal/application/service/message.goindex 5199a9f74..baac08927 100644--- a/internal/application/service/message.go+++ b/internal/application/service/message.go@@ -284,6 +284,29 @@ func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, mereturn nil}+// ClearSessionMessages deletes all messages in a session, along with their chat history KB entries.+func (s *messageService) ClearSessionMessages(ctx context.Context, sessionID string) error {+ logger.Infof(ctx, "Start clearing all messages for session: %s", sessionID)++ tenantID := types.MustTenantIDFromContext(ctx)+ if _, err := s.sessionRepo.Get(ctx, tenantID, sessionID); err != nil {+ logger.Errorf(ctx, "Failed to get session: %v", err)+ return err+ }++ // Async cleanup: delete associated Knowledge entries from the chat history KB+ bgCtx := context.WithoutCancel(ctx)+ go s.DeleteSessionKnowledge(bgCtx, sessionID)++ if err := s.messageRepo.DeleteMessagesBySessionID(ctx, sessionID); err != nil {+ logger.Errorf(ctx, "Failed to delete messages for session %s: %v", sessionID, err)+ return err+ }++ logger.Infof(ctx, "All messages cleared for session: %s", sessionID)+ return nil+}+// ─────────────────────────────────────────────────────────────────────────────// Chat History Knowledge Base — Configuration-driven (via Tenant.ChatHistoryConfig)// ─────────────────────────────────────────────────────────────────────────────diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.goindex 02dbee6ea..c7453e084 100644--- a/internal/handler/session/handler.go+++ b/internal/handler/session/handler.go@@ -318,6 +318,48 @@ func (h *Handler) DeleteSession(c *gin.Context) {})}+// ClearSessionMessages godoc+// @Summary 清空会话消息+// @Description 删除会话中的所有消息,同时清除 LLM 上下文和聊天历史知识库条目。会话本身保留。+// @Tags 会话+// @Accept json+// @Produce json+// @Param id path string true "会话ID"+// @Success 200 {object} map[string]interface{} "清空成功"+// @Failure 400 {object} errors.AppError "请求参数错误"+// @Failure 404 {object} errors.AppError "会话不存在"+// @Security Bearer+// @Security ApiKeyAuth+// @Router /sessions/{id}/messages [delete]+func (h *Handler) ClearSessionMessages(c *gin.Context) {+ ctx := c.Request.Context()++ id := secutils.SanitizeForLog(c.Param("id"))+ if id == "" {+ logger.Error(ctx, "Session ID is empty")+ c.Error(errors.NewBadRequestError(errors.ErrInvalidSessionID.Error()))+ return+ }++ logger.Infof(ctx, "Clearing all messages for session: %s", id)++ if err := h.messageService.ClearSessionMessages(ctx, id); err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": id})+ c.Error(errors.NewInternalServerError(err.Error()))+ return+ }++ if err := h.sessionService.ClearContext(ctx, id); err != nil {+ logger.Warnf(ctx, "Failed to clear LLM context for session %s: %v", id, err)+ }++ logger.Infof(ctx, "Session messages cleared successfully, ID: %s", id)+ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "message": "Session messages cleared successfully",+ })+}+// batchDeleteRequest represents the request body for batch deleting sessionstype batchDeleteRequest struct {IDs []string `json:"ids"`diff --git a/internal/router/router.go b/internal/router/router.goindex 77ef3f11b..bb5027b22 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -307,6 +307,7 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) {sessions.GET("", handler.GetSessionsByTenant)sessions.PUT("/:id", handler.UpdateSession)sessions.DELETE("/:id", handler.DeleteSession)+ sessions.DELETE("/:id/messages", handler.ClearSessionMessages)sessions.POST("/:session_id/generate_title", handler.GenerateTitle)sessions.POST("/:session_id/stop", handler.StopSession)// 继续接收活跃流diff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.goindex 1be5777b1..673c268b1 100644--- a/internal/types/interfaces/message.go+++ b/internal/types/interfaces/message.go@@ -35,6 +35,9 @@ type MessageService interface {// DeleteMessage deletes a messageDeleteMessage(ctx context.Context, sessionID string, id string) error+ // ClearSessionMessages deletes all messages in a session, along with their chat history KB entries+ ClearSessionMessages(ctx context.Context, sessionID string) error+// SearchMessages searches messages by keyword and/or vector similarity across all sessions of the current tenant.// Uses the chat history knowledge base for vector search instead of in-memory computation.SearchMessages(ctx context.Context, params *types.MessageSearchParams) (*types.MessageSearchResult, error)@@ -73,6 +76,8 @@ type MessageRepository interface {UpdateMessageImages(ctx context.Context, sessionID, messageID string, images types.MessageImages) error// DeleteMessage deletes a messageDeleteMessage(ctx context.Context, sessionID string, id string) error+ // DeleteMessagesBySessionID deletes all messages belonging to a session+ DeleteMessagesBySessionID(ctx context.Context, sessionID string) error// GetFirstMessageOfUser gets the first message of a userGetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error)// SearchMessagesByKeyword searches messages by keyword (ILIKE) across sessions for a tenant