mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 智能助手支持软删会话并级联隐藏消息
This commit is contained in:
@@ -226,6 +226,7 @@ Agent 内部:`GET /api/internal/agent/llm-runtime?companyId=&providerId=&model
|
||||
| GET | `/sessions` | 当前用户会话列表(含 `llmProviderId` / `llmModel`) |
|
||||
| POST | `/sessions` | 新建会话(可带选型;缺省写公司默认) |
|
||||
| PATCH | `/sessions/{thread_id}` | 改标题;或同时改 `llmProviderId`+`llmModel` |
|
||||
| DELETE | `/sessions/{thread_id}` | 软删会话(`status=deleted`),级联软删该线程消息 |
|
||||
| GET | `/sessions/{thread_id}/messages` | 历史消息(分页/游标) |
|
||||
| POST | `/sessions/{thread_id}/chat` | **流式**发消息(SSE);按会话选型解析 runtime |
|
||||
| GET | `/memories` | 查看自己的记忆条目(可透明) |
|
||||
|
||||
@@ -50,7 +50,11 @@ async def session_service(
|
||||
llm_svc: LlmRuntimeService = Depends(llm_runtime_service),
|
||||
) -> SessionService:
|
||||
db = await get_db(settings)
|
||||
return SessionService(MongoSessionRepository(db), llm_runtime=llm_svc)
|
||||
return SessionService(
|
||||
MongoSessionRepository(db),
|
||||
llm_runtime=llm_svc,
|
||||
messages=MongoMessageRepository(db),
|
||||
)
|
||||
|
||||
|
||||
async def memory_service(settings: Settings = Depends(get_settings)) -> MemoryService:
|
||||
|
||||
@@ -120,3 +120,17 @@ async def archive_session(
|
||||
except LookupError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
return ok(_session_vo(s))
|
||||
|
||||
|
||||
@router.delete("/{thread_id}")
|
||||
async def delete_session(
|
||||
thread_id: str,
|
||||
actor: Actor = Depends(current_actor),
|
||||
svc: SessionService = Depends(session_service),
|
||||
):
|
||||
"""软删会话并级联软删消息;列表与聊天不再可见。"""
|
||||
try:
|
||||
s = await svc.delete(actor, thread_id)
|
||||
except LookupError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e)) from e
|
||||
return ok(_session_vo(s))
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import datetime
|
||||
|
||||
from application.llm_settings_service import LlmRuntimeService
|
||||
from domain.models import Actor, Session, SessionStatus
|
||||
from domain.ports import SessionRepository
|
||||
from domain.ports import MessageRepository, SessionRepository
|
||||
|
||||
|
||||
class SessionService:
|
||||
@@ -15,9 +15,11 @@ class SessionService:
|
||||
self,
|
||||
sessions: SessionRepository,
|
||||
llm_runtime: LlmRuntimeService | None = None,
|
||||
messages: MessageRepository | None = None,
|
||||
) -> None:
|
||||
self._sessions = sessions
|
||||
self._llm_runtime = llm_runtime
|
||||
self._messages = messages
|
||||
|
||||
async def create(
|
||||
self,
|
||||
@@ -118,3 +120,16 @@ class SessionService:
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.status = SessionStatus.ARCHIVED
|
||||
return await self._sessions.update(session)
|
||||
|
||||
async def delete(self, actor: Actor, thread_id: str) -> Session:
|
||||
"""软删会话,并级联软删该线程消息。"""
|
||||
session = await self.require_owned(actor, thread_id)
|
||||
session.status = SessionStatus.DELETED
|
||||
session.llm_response_chain = None
|
||||
session.summary = None
|
||||
saved = await self._sessions.update(session)
|
||||
if self._messages is not None:
|
||||
await self._messages.soft_delete_by_thread(
|
||||
actor.company_id, actor.user_id, thread_id
|
||||
)
|
||||
return saved
|
||||
|
||||
@@ -58,6 +58,13 @@ class MessageRepository(ABC):
|
||||
@abstractmethod
|
||||
async def next_seq(self, company_id: int, user_id: str, thread_id: str) -> int: ...
|
||||
|
||||
@abstractmethod
|
||||
async def soft_delete_by_thread(
|
||||
self, company_id: int, user_id: str, thread_id: str
|
||||
) -> int:
|
||||
"""软删某会话下全部消息,返回影响条数。"""
|
||||
...
|
||||
|
||||
|
||||
class MemoryRepository(ABC):
|
||||
@abstractmethod
|
||||
|
||||
@@ -222,7 +222,17 @@ class MongoMessageRepository(MessageRepository):
|
||||
) -> list[ChatMessage]:
|
||||
cursor = (
|
||||
self._col.find(
|
||||
{"company_id": company_id, "user_id": user_id, "thread_id": thread_id}
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"thread_id": thread_id,
|
||||
# 兼容旧文档无 status;软删后 status=deleted
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
}
|
||||
)
|
||||
.sort("seq", -1)
|
||||
.limit(limit)
|
||||
@@ -231,6 +241,24 @@ class MongoMessageRepository(MessageRepository):
|
||||
rows.reverse()
|
||||
return rows
|
||||
|
||||
async def soft_delete_by_thread(
|
||||
self, company_id: int, user_id: str, thread_id: str
|
||||
) -> int:
|
||||
result = await self._col.update_many(
|
||||
{
|
||||
"company_id": company_id,
|
||||
"user_id": user_id,
|
||||
"thread_id": thread_id,
|
||||
"$or": [
|
||||
{"status": {"$exists": False}},
|
||||
{"status": None},
|
||||
{"status": {"$ne": "deleted"}},
|
||||
],
|
||||
},
|
||||
{"$set": {"status": "deleted", "deleted_at": datetime.utcnow()}},
|
||||
)
|
||||
return int(result.modified_count or 0)
|
||||
|
||||
@staticmethod
|
||||
def _to_msg(doc: dict[str, Any]) -> ChatMessage:
|
||||
return ChatMessage(
|
||||
|
||||
@@ -112,6 +112,11 @@ export async function patchAgentSessionApi(
|
||||
);
|
||||
}
|
||||
|
||||
/** 软删会话(级联软删消息) */
|
||||
export async function deleteAgentSessionApi(threadId: string) {
|
||||
return requestClient.delete<AgentVO.Session>(`/agent/sessions/${threadId}`);
|
||||
}
|
||||
|
||||
export async function listAgentMessagesApi(threadId: string) {
|
||||
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||
`/agent/sessions/${threadId}/messages`,
|
||||
|
||||
@@ -4,6 +4,7 @@ export {
|
||||
createAgentSessionApi,
|
||||
deleteAgentLlmProviderApi,
|
||||
deleteAgentMemoryApi,
|
||||
deleteAgentSessionApi,
|
||||
getAgentLlmProviderApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentLlmProvidersApi,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { computed, h, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
|
||||
import { EllipsisText, Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
@@ -12,13 +12,26 @@ import {
|
||||
} from '@ant-design/icons-vue';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import { Empty, Popover, Select, Spin, Tooltip, message } from 'ant-design-vue';
|
||||
import type { MenuProps } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
Dropdown,
|
||||
Empty,
|
||||
Menu,
|
||||
Modal,
|
||||
Popover,
|
||||
Select,
|
||||
Spin,
|
||||
Tooltip,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
import { ChatItem, ChatLoading } from '@tdesign-vue-next/chat';
|
||||
import 'tdesign-vue-next/es/style/index.css';
|
||||
import '@tdesign-vue-next/chat/es/style/index.css';
|
||||
|
||||
import {
|
||||
createAgentSessionApi,
|
||||
deleteAgentSessionApi,
|
||||
listAgentEnabledLlmModelsApi,
|
||||
listAgentMessagesApi,
|
||||
listAgentSessionsApi,
|
||||
@@ -43,6 +56,8 @@ const PanelCloseIcon = createIconifyIcon('lucide:panel-left-close');
|
||||
const PanelOpenIcon = createIconifyIcon('lucide:panel-left');
|
||||
const NewChatIcon = createIconifyIcon('lucide:square-pen');
|
||||
const RecentChatIcon = createIconifyIcon('lucide:message-square');
|
||||
const MoreIcon = createIconifyIcon('lucide:ellipsis');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
|
||||
const SIDER_COLLAPSED_KEY = 'agent-chat-sider-collapsed';
|
||||
|
||||
@@ -334,6 +349,71 @@ function onSessionClick(threadId: string) {
|
||||
activeThreadId.value = threadId;
|
||||
}
|
||||
|
||||
const deletingThreadId = ref<string | null>(null);
|
||||
/** 打开中的会话操作菜单;用于悬停三点在菜单打开时保持可见 */
|
||||
const sessionMenuOpenThreadId = ref<string | null>(null);
|
||||
|
||||
const sessionMenuItems: MenuProps['items'] = [
|
||||
{
|
||||
key: 'delete',
|
||||
danger: true,
|
||||
label: '删除',
|
||||
icon: () => h(TrashIcon, { class: 'size-3.5' }),
|
||||
},
|
||||
];
|
||||
|
||||
function onSessionMenuOpenChange(threadId: string, open: boolean) {
|
||||
sessionMenuOpenThreadId.value = open ? threadId : null;
|
||||
}
|
||||
|
||||
function onSessionMenuClick(
|
||||
threadId: string,
|
||||
info: Parameters<NonNullable<MenuProps['onClick']>>[0],
|
||||
) {
|
||||
sessionMenuOpenThreadId.value = null;
|
||||
if (info.key === 'delete') {
|
||||
confirmDeleteSession(threadId);
|
||||
}
|
||||
}
|
||||
|
||||
/** 确认后软删会话;若删的是当前会话则回到新对话空态 */
|
||||
function confirmDeleteSession(threadId: string) {
|
||||
Modal.confirm({
|
||||
title: '删除会话',
|
||||
content: '删除后无法在列表中恢复,确定删除该会话?',
|
||||
okText: '删除',
|
||||
okType: 'danger',
|
||||
cancelText: '取消',
|
||||
async onOk() {
|
||||
await onDeleteSession(threadId);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function onDeleteSession(threadId: string) {
|
||||
if (sending.value) {
|
||||
message.warning('回复生成中,请稍候再删除');
|
||||
return Promise.reject(new Error('busy'));
|
||||
}
|
||||
if (deletingThreadId.value) {
|
||||
return Promise.reject(new Error('deleting'));
|
||||
}
|
||||
deletingThreadId.value = threadId;
|
||||
try {
|
||||
await deleteAgentSessionApi(threadId);
|
||||
sessions.value = sessions.value.filter((s) => s.threadId !== threadId);
|
||||
if (activeThreadId.value === threadId) {
|
||||
beginNewChat();
|
||||
}
|
||||
message.success('会话已删除');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除会话失败');
|
||||
return Promise.reject(e);
|
||||
} finally {
|
||||
deletingThreadId.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSessions() {
|
||||
loadingSessions.value = true;
|
||||
try {
|
||||
@@ -757,22 +837,57 @@ void loadEnabledModels().then(() => refreshSessions());
|
||||
>
|
||||
{{ group.label }}
|
||||
</div>
|
||||
<button
|
||||
<div
|
||||
v-for="s in group.items"
|
||||
:key="s.threadId"
|
||||
type="button"
|
||||
class="agent-session-item mb-0.5 w-full cursor-pointer rounded-lg px-3 py-2 text-left text-sm transition-colors"
|
||||
class="agent-session-item group mb-0.5 flex w-full cursor-pointer items-center gap-1 rounded-lg px-2 py-1.5 text-left text-sm transition-colors"
|
||||
:class="
|
||||
s.threadId === activeThreadId
|
||||
? 'agent-session-item--active'
|
||||
: ''
|
||||
"
|
||||
@click="onSessionClick(s.threadId)"
|
||||
>
|
||||
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||
{{ s.title || '新对话' }}
|
||||
</EllipsisText>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="min-w-0 flex-1 truncate px-1 py-0.5 text-left"
|
||||
@click="onSessionClick(s.threadId)"
|
||||
>
|
||||
<EllipsisText :tooltip-when-ellipsis="true" class="w-full">
|
||||
{{ s.title || '新对话' }}
|
||||
</EllipsisText>
|
||||
</button>
|
||||
<Dropdown
|
||||
:trigger="['click']"
|
||||
:open="sessionMenuOpenThreadId === s.threadId"
|
||||
@open-change="
|
||||
(open: boolean) =>
|
||||
onSessionMenuOpenChange(s.threadId, open)
|
||||
"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="text-muted-foreground hover:bg-accent hover:text-foreground flex size-7 shrink-0 items-center justify-center rounded-md opacity-0 transition-opacity group-hover:opacity-100"
|
||||
:class="
|
||||
sessionMenuOpenThreadId === s.threadId ||
|
||||
s.threadId === activeThreadId
|
||||
? 'opacity-100'
|
||||
: ''
|
||||
"
|
||||
aria-label="会话操作"
|
||||
@click.stop
|
||||
>
|
||||
<MoreIcon class="size-3.5" />
|
||||
</button>
|
||||
<template #overlay>
|
||||
<Menu
|
||||
:items="sessionMenuItems"
|
||||
@click="
|
||||
(info) => onSessionMenuClick(s.threadId, info)
|
||||
"
|
||||
/>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user