feat: add clear session messages functionality
- Implemented a new API endpoint to clear all messages in a session, enhancing session management capabilities. - Updated the frontend to include a clear messages option in the session menu, allowing users to easily remove chat history. - Added localization support for the new feature in English, Korean, Russian, and Chinese, improving accessibility for a broader audience. - Enhanced the chat view to handle session message clearing events, ensuring a responsive user experience. These changes significantly improve the user experience by providing a straightforward method to manage session messages effectively.
This commit is contained in:
@@ -58,4 +58,8 @@ export async function getSession(session_id: string) {
|
|||||||
|
|
||||||
export async function stopSession(session_id: string, message_id: string) {
|
export async function stopSession(session_id: string, message_id: string) {
|
||||||
return post(`/api/v1/sessions/${session_id}/stop`, { message_id });
|
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`);
|
||||||
}
|
}
|
||||||
@@ -77,7 +77,7 @@
|
|||||||
{{ subitem.title }}
|
{{ subitem.title }}
|
||||||
</span>
|
</span>
|
||||||
<t-dropdown v-if="!batchMode"
|
<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)"
|
@click="handleSessionMenuClick($event, subitem.originalIndex, subitem)"
|
||||||
placement="bottom-right"
|
placement="bottom-right"
|
||||||
trigger="click">
|
trigger="click">
|
||||||
@@ -126,7 +126,7 @@
|
|||||||
import { storeToRefs } from 'pinia';
|
import { storeToRefs } from 'pinia';
|
||||||
import { onMounted, watch, computed, ref } from 'vue';
|
import { onMounted, watch, computed, ref } from 'vue';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
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 { getKnowledgeBaseById } from '@/api/knowledge-base';
|
||||||
import { logout as logoutApi } from '@/api/auth';
|
import { logout as logoutApi } from '@/api/auth';
|
||||||
import { useMenuStore } from '@/stores/menu';
|
import { useMenuStore } from '@/stores/menu';
|
||||||
@@ -423,11 +423,28 @@ const handleInlineBatchDelete = () => {
|
|||||||
const handleSessionMenuClick = (data: { value: string }, index: number, item: any) => {
|
const handleSessionMenuClick = (data: { value: string }, index: number, item: any) => {
|
||||||
if (data?.value === 'delete') {
|
if (data?.value === 'delete') {
|
||||||
delCard(index, item);
|
delCard(index, item);
|
||||||
|
} else if (data?.value === 'clearMessages') {
|
||||||
|
clearMessages(item);
|
||||||
} else if (data?.value === 'batchManage') {
|
} else if (data?.value === 'batchManage') {
|
||||||
enterBatchMode()
|
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) => {
|
const delCard = (index: number, item: any) => {
|
||||||
delSession(item.id).then((res: any) => {
|
delSession(item.id).then((res: any) => {
|
||||||
if (res && (res as any).success) {
|
if (res && (res as any).success) {
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ export default {
|
|||||||
logout: 'Logout',
|
logout: 'Logout',
|
||||||
uploadKnowledge: 'Upload Knowledge',
|
uploadKnowledge: 'Upload Knowledge',
|
||||||
deleteRecord: 'Delete Record',
|
deleteRecord: 'Delete Record',
|
||||||
|
clearMessages: 'Clear Messages',
|
||||||
|
clearMessagesSuccess: 'Messages cleared',
|
||||||
|
clearMessagesFailed: 'Failed to clear messages, please try again later',
|
||||||
batchManage: 'Batch Manage',
|
batchManage: 'Batch Manage',
|
||||||
newSession: 'New Chat',
|
newSession: 'New Chat',
|
||||||
confirmLogout: 'Are you sure you want to logout?',
|
confirmLogout: 'Are you sure you want to logout?',
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ export default {
|
|||||||
logout: "로그아웃",
|
logout: "로그아웃",
|
||||||
uploadKnowledge: "지식 업로드",
|
uploadKnowledge: "지식 업로드",
|
||||||
deleteRecord: "기록 삭제",
|
deleteRecord: "기록 삭제",
|
||||||
|
clearMessages: "메시지 지우기",
|
||||||
|
clearMessagesSuccess: "메시지가 지워졌습니다",
|
||||||
|
clearMessagesFailed: "메시지 지우기 실패, 나중에 다시 시도해 주세요",
|
||||||
batchManage: "일괄 관리",
|
batchManage: "일괄 관리",
|
||||||
newSession: "새 세션",
|
newSession: "새 세션",
|
||||||
confirmLogout: "정말 로그아웃 하시겠습니까?",
|
confirmLogout: "정말 로그아웃 하시겠습니까?",
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ export default {
|
|||||||
logout: 'Выход',
|
logout: 'Выход',
|
||||||
uploadKnowledge: 'Загрузить знания',
|
uploadKnowledge: 'Загрузить знания',
|
||||||
deleteRecord: 'Удалить запись',
|
deleteRecord: 'Удалить запись',
|
||||||
|
clearMessages: 'Очистить сообщения',
|
||||||
|
clearMessagesSuccess: 'Сообщения очищены',
|
||||||
|
clearMessagesFailed: 'Не удалось очистить сообщения, попробуйте позже',
|
||||||
batchManage: 'Пакетное управление',
|
batchManage: 'Пакетное управление',
|
||||||
newSession: 'Новый диалог',
|
newSession: 'Новый диалог',
|
||||||
confirmLogout: 'Вы уверены, что хотите выйти?',
|
confirmLogout: 'Вы уверены, что хотите выйти?',
|
||||||
|
|||||||
@@ -10,6 +10,9 @@ export default {
|
|||||||
logout: "退出登录",
|
logout: "退出登录",
|
||||||
uploadKnowledge: "上传知识",
|
uploadKnowledge: "上传知识",
|
||||||
deleteRecord: "删除记录",
|
deleteRecord: "删除记录",
|
||||||
|
clearMessages: "清空消息",
|
||||||
|
clearMessagesSuccess: "消息已清空",
|
||||||
|
clearMessagesFailed: "清空消息失败,请稍后再试",
|
||||||
batchManage: "批量管理",
|
batchManage: "批量管理",
|
||||||
newSession: "新会话",
|
newSession: "新会话",
|
||||||
confirmLogout: "确定要退出登录吗?",
|
confirmLogout: "确定要退出登录吗?",
|
||||||
|
|||||||
@@ -955,7 +955,15 @@ const updateAssistantSession = (payload) => {
|
|||||||
}
|
}
|
||||||
scrollToBottom();
|
scrollToBottom();
|
||||||
}
|
}
|
||||||
|
const handleSessionCleared = (e) => {
|
||||||
|
if (e.detail?.sessionId === session_id.value) {
|
||||||
|
messagesList.splice(0);
|
||||||
|
created_at.value = '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
|
window.addEventListener('session-messages-cleared', handleSessionCleared);
|
||||||
messagesList.splice(0);
|
messagesList.splice(0);
|
||||||
|
|
||||||
// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store
|
// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store
|
||||||
@@ -1001,6 +1009,9 @@ const clearData = () => {
|
|||||||
userquery.value = '';
|
userquery.value = '';
|
||||||
|
|
||||||
}
|
}
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener('session-messages-cleared', handleSessionCleared);
|
||||||
|
});
|
||||||
onBeforeRouteLeave((to, from, next) => {
|
onBeforeRouteLeave((to, from, next) => {
|
||||||
clearData()
|
clearData()
|
||||||
next()
|
next()
|
||||||
|
|||||||
@@ -245,6 +245,11 @@ func (r *messageRepository) UpdateMessageImages(ctx context.Context, sessionID,
|
|||||||
Update("images", images).Error
|
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 message
|
// UpdateMessageKnowledgeID updates the knowledge_id field for a message
|
||||||
func (r *messageRepository) UpdateMessageKnowledgeID(
|
func (r *messageRepository) UpdateMessageKnowledgeID(
|
||||||
ctx context.Context, messageID string, knowledgeID string,
|
ctx context.Context, messageID string, knowledgeID string,
|
||||||
|
|||||||
@@ -284,6 +284,29 @@ func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, me
|
|||||||
return nil
|
return 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)
|
// Chat History Knowledge Base — Configuration-driven (via Tenant.ChatHistoryConfig)
|
||||||
// ─────────────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -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 sessions
|
// batchDeleteRequest represents the request body for batch deleting sessions
|
||||||
type batchDeleteRequest struct {
|
type batchDeleteRequest struct {
|
||||||
IDs []string `json:"ids"`
|
IDs []string `json:"ids"`
|
||||||
|
|||||||
@@ -303,6 +303,7 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler) {
|
|||||||
sessions.GET("", handler.GetSessionsByTenant)
|
sessions.GET("", handler.GetSessionsByTenant)
|
||||||
sessions.PUT("/:id", handler.UpdateSession)
|
sessions.PUT("/:id", handler.UpdateSession)
|
||||||
sessions.DELETE("/:id", handler.DeleteSession)
|
sessions.DELETE("/:id", handler.DeleteSession)
|
||||||
|
sessions.DELETE("/:id/messages", handler.ClearSessionMessages)
|
||||||
sessions.POST("/:session_id/generate_title", handler.GenerateTitle)
|
sessions.POST("/:session_id/generate_title", handler.GenerateTitle)
|
||||||
sessions.POST("/:session_id/stop", handler.StopSession)
|
sessions.POST("/:session_id/stop", handler.StopSession)
|
||||||
// 继续接收活跃流
|
// 继续接收活跃流
|
||||||
|
|||||||
@@ -35,6 +35,9 @@ type MessageService interface {
|
|||||||
// DeleteMessage deletes a message
|
// DeleteMessage deletes a message
|
||||||
DeleteMessage(ctx context.Context, sessionID string, id string) error
|
DeleteMessage(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.
|
// 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.
|
// Uses the chat history knowledge base for vector search instead of in-memory computation.
|
||||||
SearchMessages(ctx context.Context, params *types.MessageSearchParams) (*types.MessageSearchResult, error)
|
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
|
UpdateMessageImages(ctx context.Context, sessionID, messageID string, images types.MessageImages) error
|
||||||
// DeleteMessage deletes a message
|
// DeleteMessage deletes a message
|
||||||
DeleteMessage(ctx context.Context, sessionID string, id string) error
|
DeleteMessage(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 user
|
// GetFirstMessageOfUser gets the first message of a user
|
||||||
GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error)
|
GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error)
|
||||||
// SearchMessagesByKeyword searches messages by keyword (ILIKE) across sessions for a tenant
|
// SearchMessagesByKeyword searches messages by keyword (ILIKE) across sessions for a tenant
|
||||||
|
|||||||
Reference in New Issue
Block a user