feat(agent): 添加智能体工作状态显示功能

实现智能体工作状态的实时显示,包括任务列表和文件管理功能
- 在 DeepAgent 中添加 todo 和 files 能力支持
- 新增 AgentPopover 组件展示工作状态
- 修改聊天界面添加状态显示按钮
- 更新服务端状态提取逻辑
- 更新文档和路线图
This commit is contained in:
Wenjie Zhang 2025-11-14 12:50:32 +08:00
parent 15acdaac73
commit 0d20cf66db
6 changed files with 628 additions and 14 deletions

View File

@ -6,7 +6,6 @@
### 看板
- 新建 DeepAgents 智能体(暂时没有场景)
- 统一图谱数据结构,优化可视化方式 [#298](https://github.com/xerrors/Yuxi-Know/issues/298) [#273](https://github.com/xerrors/Yuxi-Know/issues/273) <Badge type="info" text="0.4" />
- 集成智能体评估,首先使用命令行来实现,然后考虑放在 UI 里面展示
- 开发与生产环境隔离,构建生产镜像 <Badge type="info" text="0.4" />
@ -17,12 +16,14 @@
### Bugs
- 部分异常状态下,智能体的模型名称出现重叠[#279](https://github.com/xerrors/Yuxi-Know/issues/279)
- DeepSeek 官方接口适配会出现问题
- 当前版本如果调用结果为空的时候,工具调用状态会一直处于调用状态,尽管调用是成功的
### 新增
- 优化知识库详情页面,更加简洁清晰
- 新增对于上传文件的智能体中间件
- 增强文件下载功能
- 新增多模态模型支持(当前仅支持图片,详见文档)
- 新建 DeepAgents 智能体Demo
### 修复
- 修复重排序模型实际未生效的问题

View File

@ -102,7 +102,6 @@ async def set_default_agent(request_data: dict = Body(...), current_user=Depends
async def _get_langgraph_messages(agent_instance, config_dict):
"""获取LangGraph中的消息"""
graph = await agent_instance.get_graph()
state = await graph.aget_state(config_dict)
@ -113,6 +112,24 @@ async def _get_langgraph_messages(agent_instance, config_dict):
return state.values.get("messages", [])
def _extract_agent_state(values: dict) -> dict:
if not isinstance(values, dict):
return {}
def _norm_list(v):
if v is None:
return []
if isinstance(v, (list, tuple)):
return list(v)
return [v]
result = {}
result["todos"] = _norm_list(values.get("todos"))[:20]
result["files"] = _norm_list(values.get("files"))[:50]
return result
def _get_existing_message_ids(conv_mgr, thread_id):
"""获取已保存的消息ID集合"""
existing_messages = conv_mgr.get_messages_by_thread_id(thread_id)
@ -521,6 +538,7 @@ async def chat_agent(
try:
full_msg = None
langgraph_config = {"configurable": input_context}
async for msg, metadata in agent.stream_messages(messages, input_context=input_context):
if isinstance(msg, AIMessageChunk):
full_msg = msg if not full_msg else full_msg + msg
@ -534,7 +552,18 @@ async def chat_agent(
yield make_chunk(content=msg.content, msg=msg.model_dump(), metadata=metadata, status="loading")
else:
yield make_chunk(msg=msg.model_dump(), metadata=metadata, status="loading")
msg_dict = msg.model_dump()
yield make_chunk(msg=msg_dict, metadata=metadata, status="loading")
try:
if msg_dict.get("type") == "tool":
graph = await agent.get_graph()
state = await graph.aget_state(langgraph_config)
agent_state = _extract_agent_state(getattr(state, "values", {})) if state else {}
if agent_state:
yield make_chunk(status="agent_state", agent_state=agent_state, meta=meta)
except Exception:
pass
if (
conf.enable_content_guard
@ -548,13 +577,22 @@ async def chat_agent(
return
# After streaming finished, check for interrupts and save messages
langgraph_config = {"configurable": input_context}
# Check for human approval interrupts
async for chunk in check_and_handle_interrupts(agent, langgraph_config, make_chunk, meta, thread_id):
yield chunk
meta["time_cost"] = asyncio.get_event_loop().time() - start_time
try:
graph = await agent.get_graph()
state = await graph.aget_state(langgraph_config)
agent_state = _extract_agent_state(getattr(state, "values", {})) if state else {}
except Exception:
agent_state = {}
if agent_state:
yield make_chunk(status="agent_state", agent_state=agent_state, meta=meta)
yield make_chunk(status="finished", meta=meta)
# Save all messages from LangGraph state

View File

@ -179,6 +179,8 @@ class DeepAgent(BaseAgent):
context_schema = DeepContext
capabilities = [
"file_upload",
"todo",
"files",
]
def __init__(self, **kwargs):

View File

@ -43,6 +43,20 @@
</div>
</div>
<div class="header__right">
<!-- AgentState 显示按钮 - 只在智能体支持 todo files 能力时显示 -->
<AgentPopover
v-model:visible="agentStatePopoverVisible"
:agent-state="currentAgentState"
>
<div
class="agent-nav-btn agent-state-btn"
:class="{ 'has-content': hasAgentStateContent }"
:title="hasAgentStateContent ? '查看工作状态' : '暂无工作状态'"
>
<Activity class="nav-btn-icon" size="18"/>
<span v-if="hasAgentStateContent" class="text">{{ totalAgentStateItems }}</span>
</div>
</AgentPopover>
<!-- <div class="nav-btn" @click="shareChat" v-if="currentChatId && currentAgent">
<ShareAltOutlined style="font-size: 18px;"/>
</div> -->
@ -202,7 +216,8 @@
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
@ -217,7 +232,7 @@ import AgentMessageComponent from '@/components/AgentMessageComponent.vue'
import ImagePreviewComponent from '@/components/ImagePreviewComponent.vue'
import ChatSidebarComponent from '@/components/ChatSidebarComponent.vue'
import RefsComponent from '@/components/RefsComponent.vue'
import { PanelLeftOpen, MessageCirclePlus, LoaderCircle } from 'lucide-vue-next';
import { PanelLeftOpen, MessageCirclePlus, LoaderCircle, Activity } from 'lucide-vue-next';
import { handleChatError, handleValidationError } from '@/utils/errorHandler';
import { ScrollController } from '@/utils/scrollController';
import { AgentValidator } from '@/utils/agentValidator';
@ -228,6 +243,7 @@ import { MessageProcessor } from '@/utils/messageProcessor';
import { agentApi, threadApi } from '@/apis';
import HumanApprovalModal from '@/components/HumanApprovalModal.vue';
import { useApproval } from '@/composables/useApproval';
import AgentPopover from '@/components/AgentPopover.vue';
// ==================== PROPS & EMITS ====================
const props = defineProps({
@ -293,6 +309,9 @@ const attachmentState = reactive({
isUploading: false,
})
// AgentState Popover
const agentStatePopoverVisible = ref(false);
// ==================== COMPUTED PROPERTIES ====================
const currentAgentId = computed(() => {
if (props.singleMode) {
@ -333,6 +352,37 @@ const supportsFileUpload = computed(() => {
const capabilities = currentAgent.value.capabilities || [];
return capabilities.includes('file_upload');
});
const supportsTodo = computed(() => {
if (!currentAgent.value) return false;
const capabilities = currentAgent.value.capabilities || [];
return capabilities.includes('todo');
});
const supportsFiles = computed(() => {
if (!currentAgent.value) return false;
const capabilities = currentAgent.value.capabilities || [];
return capabilities.includes('files');
});
// AgentState
const currentAgentState = computed(() => {
return currentChatId.value ? getThreadState(currentChatId.value)?.agentState || null : null;
});
const hasAgentStateContent = computed(() => {
const agentState = currentAgentState.value;
if (!agentState) return false;
return (agentState.todos && agentState.todos.length > 0) ||
(agentState.files && Object.keys(agentState.files).length > 0);
});
const totalAgentStateItems = computed(() => {
const agentState = currentAgentState.value;
if (!agentState) return 0;
const todoCount = agentState.todos ? agentState.todos.length : 0;
const fileCount = agentState.files ? Object.keys(agentState.files).length : 0;
return todoCount + fileCount;
});
const currentThreadMessages = computed(() => threadMessages.value[currentChatId.value] || []);
@ -427,7 +477,7 @@ onMounted(() => {
onUnmounted(() => {
if (resizeObserver) resizeObserver.disconnect();
scrollController.cleanup();
// 线
// 线
resetOnGoingConv();
});
@ -439,7 +489,8 @@ const getThreadState = (threadId) => {
chatState.threadStates[threadId] = {
isStreaming: false,
streamAbortController: null,
onGoingConv: createOnGoingConvState()
onGoingConv: createOnGoingConvState(),
agentState: null // agentState
};
}
return chatState.threadStates[threadId];
@ -548,10 +599,27 @@ const _processStreamChunk = (chunk, threadId) => {
case 'human_approval_required':
// 使 composable
return processApprovalInStream(chunk, threadId, currentAgentId.value);
case 'agent_state':
if ((supportsTodo.value || supportsFiles.value) && chunk.agent_state) {
console.log('[AgentState]', {
threadId,
todos: chunk.agent_state?.todos || [],
files: chunk.agent_state?.files || []
});
threadState.agentState = chunk.agent_state;
}
return false;
case 'finished':
//
if (threadState) {
threadState.isStreaming = false;
if ((supportsTodo.value || supportsFiles.value) && threadState.agentState) {
console.log('[AgentState|Final]', {
threadId,
todos: threadState.agentState?.todos || [],
files: threadState.agentState?.files || []
});
}
}
//
fetchThreadMessages({ agentId: currentAgentId.value, threadId: threadId })
@ -1231,6 +1299,7 @@ const loadChatsList = async () => {
}
};
const initAll = async () => {
try {
if (!agentStore.isInitialized) {
@ -1244,7 +1313,7 @@ const initAll = async () => {
onMounted(async () => {
await initAll();
scrollController.enableAutoScroll();
});
});
watch(currentAgentId, async (newAgentId, oldAgentId) => {
if (newAgentId !== oldAgentId) {
@ -1769,6 +1838,16 @@ watch(conversations, () => {
}
}
/* AgentState 按钮有内容时的样式 */
.agent-nav-btn.agent-state-btn.has-content {
color: var(--main-600);
&:hover:not(.is-disabled) {
color: var(--main-700);
background-color: var(--main-40);
}
}
@keyframes spin {
from {
transform: rotate(0deg);

View File

@ -194,11 +194,6 @@ const validToolCalls = computed(() => {
});
const parsedData = computed(() => {
//
if (validToolCalls.value && validToolCalls.value.length > 0) {
console.log('Valid tool calls in message:', validToolCalls.value);
}
// Start with default values from the prop to avoid mutation.
let content = props.message.content.trim() || '';
let reasoning_content = props.message.additional_kwargs?.reasoning_content || '';

View File

@ -0,0 +1,499 @@
<template>
<a-popover
v-model:open="visible"
:title="null"
placement="bottomRight"
trigger="click"
:overlayStyle="{ width: '400px', zIndex: 1030 }"
>
<template #content>
<div class="popover-content">
<div class="tabs">
<button
class="tab"
:class="{ active: activeTab === 'todos' }"
@click="activeTab = 'todos'"
v-if="hasTodos"
>
任务 ({{ todoCount }})
</button>
<button
class="tab"
:class="{ active: activeTab === 'files' }"
@click="activeTab = 'files'"
v-if="hasFiles"
>
文件 ({{ fileCount }})
</button>
</div>
<div class="tab-content">
<!-- Todo Display -->
<div v-if="activeTab === 'todos'" class="todo-display">
<div v-if="!todos.length" class="empty">
暂无任务
</div>
<div v-else class="todo-list">
<div
v-for="(todo, index) in todos"
:key="index"
class="todo-item"
>
<span class="todo-status" :class="todo.status">
{{ todo.status === 'completed' ? '✓' : todo.status === 'in_progress' ? '⟳' : '○' }}
</span>
<span class="todo-text">{{ todo.content }}</span>
</div>
</div>
</div>
<!-- Files Display -->
<div v-if="activeTab === 'files'" class="files-display">
<div v-if="!fileCount" class="empty">
暂无文件
</div>
<div v-else class="file-list">
<div
v-for="(fileItem, index) in normalizedFiles"
:key="fileItem.path || index"
class="file-item"
@click="showFileContent(fileItem.path, fileItem)"
>
<div class="file-info">
<div class="file-name">{{ getFileName(fileItem) }}</div>
<div class="file-time" v-if="fileItem.modified_at">
{{ formatDate(fileItem.modified_at) }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<slot></slot>
</a-popover>
<!-- 文件内容 Modal -->
<a-modal
v-model:open="modalVisible"
:title="currentFilePath"
width="80%"
:footer="null"
@cancel="closeModal"
>
<div class="file-content">
<pre v-if="Array.isArray(currentFile?.content)">{{ formatContent(currentFile.content) }}</pre>
<div v-else-if="typeof currentFile?.content === 'string'">{{ currentFile.content }}</div>
<pre v-else>{{ JSON.stringify(currentFile, null, 2) }}</pre>
</div>
</a-modal>
</template>
<script setup>
import { computed, ref, watch } from 'vue';
const props = defineProps({
visible: {
type: Boolean,
default: false
},
agentState: {
type: Object,
default: () => ({})
}
});
const emit = defineEmits(['update:visible']);
const activeTab = ref('todos');
const modalVisible = ref(false);
const currentFile = ref(null);
const currentFilePath = ref('');
//
const visible = computed({
get: () => props.visible,
set: (value) => emit('update:visible', value)
});
const todos = computed(() => {
return props.agentState?.todos || [];
});
const files = computed(() => {
return props.agentState?.files || [];
});
const hasTodos = computed(() => {
return todos.value.length > 0;
});
const hasFiles = computed(() => {
return files.value.length > 0;
});
const todoCount = computed(() => {
return todos.value.length;
});
//
const normalizedFiles = computed(() => {
if (!Array.isArray(files.value)) return [];
const result = [];
files.value.forEach(item => {
if (typeof item === 'object' && item !== null) {
Object.entries(item).forEach(([filePath, fileData]) => {
result.push({
path: filePath,
...fileData
});
});
}
});
return result;
});
const fileCount = computed(() => {
return normalizedFiles.value.length;
});
// agentState
watch(() => props.agentState, (newState) => {
if (newState) {
if (hasFiles.value && !hasTodos.value) {
activeTab.value = 'files';
} else {
activeTab.value = 'todos';
}
}
}, { immediate: true });
//
const getFileName = (fileItem) => {
if (fileItem.path) {
return fileItem.path.split('/').pop() || fileItem.path;
}
return '未知文件';
};
const formatDate = (dateString) => {
if (!dateString) return '';
try {
const date = new Date(dateString);
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
} catch (error) {
return dateString;
}
};
const formatContent = (contentArray) => {
if (!Array.isArray(contentArray)) return String(contentArray);
return contentArray.join('\n');
};
const showFileContent = (filePath, fileData) => {
currentFilePath.value = filePath;
currentFile.value = fileData;
modalVisible.value = true;
};
const closeModal = () => {
modalVisible.value = false;
currentFile.value = null;
currentFilePath.value = '';
};
</script>
<style scoped lang="less">
.popover-content {
padding: 0;
background: var(--main-0);
border-radius: 6px;
overflow: hidden;
}
.tabs {
display: flex;
border-bottom: 1px solid var(--gray-200);
position: relative;
}
.tab {
padding: 10px 16px;
border: none;
background: none;
color: var(--gray-600);
cursor: pointer;
font-size: 13px;
font-weight: 500;
transition: all 0.15s ease;
position: relative;
border-radius: 6px 6px 0 0;
&:hover {
color: var(--main-700);
}
&.active {
color: var(--main-700);
&::after {
content: '';
position: absolute;
bottom: -1px;
left: 0;
right: 0;
height: 2px;
background: var(--main-500);
border-radius: 1px;
}
}
}
.tab-content {
max-height: 400px;
overflow-y: auto;
background: var(--main-0);
/* 自定义滚动条 */
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: var(--gray-50);
}
&::-webkit-scrollbar-thumb {
background: var(--gray-300);
border-radius: 3px;
&:hover {
background: var(--gray-400);
}
}
}
.todo-display,
.files-display {
padding: 16px 0;
}
.empty {
text-align: center;
color: var(--gray-500);
padding: 40px 0;
font-size: 14px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
&::before {
content: '📋';
font-size: 28px;
opacity: 0.6;
}
}
.todo-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.todo-item {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 12px;
background: var(--main-5);
border-radius: 6px;
border: 1px solid var(--gray-150);
transition: all 0.15s ease;
&:hover {
background: var(--main-10);
border-color: var(--gray-200);
}
}
.todo-status {
flex-shrink: 0;
width: 16px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 10px;
margin-top: 2px;
border-radius: 50%;
transition: all 0.15s ease;
&.completed {
background: var(--stats-success-bg);
color: var(--stats-success-color);
}
&.in_progress {
background: var(--stats-warning-bg);
color: var(--stats-warning-color);
}
&.pending {
background: var(--gray-100);
color: var(--gray-500);
}
}
.todo-text {
flex: 1;
font-size: 14px;
line-height: 1.5;
color: var(--gray-1000);
word-break: break-word;
.todo-item.completed & {
color: var(--gray-500);
text-decoration: line-through;
}
}
.file-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.file-item {
padding: 12px 14px;
background: var(--main-5);
border: 1px solid var(--gray-150);
border-radius: 6px;
cursor: pointer;
transition: all 0.15s ease;
position: relative;
&:hover {
background: var(--main-10);
border-color: var(--main-300);
}
}
.file-info {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
}
.file-name {
font-size: 14px;
color: var(--gray-1000);
font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-weight: 500;
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file-time {
font-size: 12px;
color: var(--gray-500);
font-weight: 400;
white-space: nowrap;
}
.file-content {
max-height: 60vh;
overflow-y: auto;
background: var(--main-5);
border-radius: 6px;
padding: 16px;
border: 1px solid var(--gray-200);
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: var(--gray-50);
border-radius: 4px;
}
&::-webkit-scrollbar-thumb {
background: var(--gray-300);
border-radius: 4px;
&:hover {
background: var(--gray-400);
}
}
pre {
font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
font-size: 13px;
line-height: 1.5;
margin: 0;
white-space: pre-wrap;
word-wrap: break-word;
color: var(--gray-1000);
background: transparent;
}
}
/* Modal 样式优化 - shadcn 风格 */
:deep(.ant-modal) {
z-index: 1050;
}
:deep(.ant-modal-content) {
border-radius: 8px;
overflow: hidden;
border: 1px solid var(--gray-200);
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}
:deep(.ant-modal-header) {
background: var(--main-5);
border-bottom: 1px solid var(--gray-200);
padding: 16px 20px;
}
:deep(.ant-modal-title) {
font-weight: 600;
color: var(--gray-1000);
font-family: 'JetBrains Mono', 'Fira Code', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}
:deep(.ant-modal-body) {
padding: 0;
}
:deep(.ant-modal-close) {
top: 12px;
right: 12px;
.ant-modal-close-x {
width: 28px;
height: 28px;
border-radius: 4px;
transition: all 0.15s ease;
color: var(--gray-500);
&:hover {
background: var(--gray-100);
color: var(--gray-700);
}
}
}
</style>