feat: Enhance event duration tracking and UI components in chat

- Added duration tracking for agent steps and tool calls, improving event data accuracy.
- Updated AgentStreamDisplay and ToolResultRenderer components to include fallback headers and improved output styling.
- Refactored duration handling in the agent engine and session management to ensure consistent duration reporting.
- Enhanced UI elements for better user experience, including scrollable output areas and improved tooltip visibility.
This commit is contained in:
wizardchen
2025-11-12 14:27:00 +08:00
parent 05154c8d75
commit 38beca1146
6 changed files with 219 additions and 81 deletions
@@ -1,5 +1,5 @@
<template>
<div class="agent-stream-display">
<div ref="rootElement" class="agent-stream-display">
<!-- Collapsed intermediate steps -->
<div v-if="shouldShowCollapsedSteps" class="intermediate-steps-collapsed">
@@ -131,7 +131,12 @@
<!-- Fallback to original output display -->
<div v-else-if="event.output" class="tool-output-wrapper">
<div class="detail-output">{{ event.output }}</div>
<div class="fallback-header">
<span class="fallback-label">原始输出</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ event.output }}</div>
</div>
</div>
<!-- Show Arguments only if no display_type and not for todo_write -->
@@ -179,7 +184,7 @@
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue';
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
@@ -188,6 +193,9 @@ import { getChunkByIdOnly } from '@/api/knowledge-base';
const router = useRouter();
// 根元素引用
const rootElement = ref<HTMLElement | null>(null);
// 浮层状态(Web/KB 共用)
const KB_SNIPPET_LIMIT = 600;
@@ -415,7 +423,6 @@ const intermediateStepsSummary = computed(() => {
const toolCalls: string[] = [];
let searchCount = 0;
let thinkingCount = 0;
let totalDuration = 0;
for (const event of stream) {
if (event.type === 'tool_call' && event.tool_name) {
@@ -433,22 +440,13 @@ const intermediateStepsSummary = computed(() => {
toolCalls.push(toolName);
}
}
// Accumulate duration for tool calls
if (event.duration) {
totalDuration += event.duration;
} else if (event.duration_ms) {
totalDuration += event.duration_ms;
}
} else if (event.type === 'thinking' && event.content) {
// Count if it's not the final thinking
if (finalContent.value.type !== 'thinking' || event.event_id !== finalContent.value.event_id) {
thinkingCount++;
// Accumulate duration for thinking events
if (event.duration_ms) {
totalDuration += event.duration_ms;
}
}
}
}
}
const parts: string[] = [];
@@ -471,17 +469,6 @@ const intermediateStepsSummary = computed(() => {
}
}
// Add duration info
if (totalDuration > 0) {
const durationStr = formatDuration(totalDuration);
// Extract numbers from duration string (e.g., "300ms" -> "300", "3s" -> "3", "2m 30s" -> "2" and "30")
// Process "ms" first to avoid matching "m" and "s" separately, then process "s" and "m"
const durationHtml = durationStr
.replace(/(\d+)(ms)/g, '<strong>$1</strong>$2')
.replace(/(\d+)([sm])(?!\w)/g, '<strong>$1</strong>$2');
parts.push(`耗时 ${durationHtml}`);
}
if (parts.length === 0) {
return `<strong>${intermediateStepsCount.value}</strong> 个中间步骤`;
}
@@ -868,22 +855,25 @@ const onRootKeydown = (e: KeyboardEvent) => {
};
onMounted(() => {
const root = document.querySelector('.agent-stream-display');
if (!root) return;
root.addEventListener('click', onRootClick, true);
const keydownListener: EventListener = (evt: Event) => onRootKeydown(evt as KeyboardEvent);
// Store on element for removal
(root as any).__citationKeydown__ = keydownListener;
root.addEventListener('keydown', keydownListener, true);
// 统一 hover 监听
root.addEventListener('mouseover', onHover, true);
root.addEventListener('mouseout', onHoverOut, true);
window.addEventListener('scroll', scheduleFloatClose, true);
window.addEventListener('resize', scheduleFloatClose, true);
// 使用 nextTick 确保 DOM 已渲染
nextTick(() => {
const root = rootElement.value;
if (!root) return;
root.addEventListener('click', onRootClick, true);
const keydownListener: EventListener = (evt: Event) => onRootKeydown(evt as KeyboardEvent);
// Store on element for removal
(root as any).__citationKeydown__ = keydownListener;
root.addEventListener('keydown', keydownListener, true);
// 统一 hover 监听
root.addEventListener('mouseover', onHover, true);
root.addEventListener('mouseout', onHoverOut, true);
window.addEventListener('scroll', scheduleFloatClose, true);
window.addEventListener('resize', scheduleFloatClose, true);
});
});
onBeforeUnmount(() => {
const root = document.querySelector('.agent-stream-display');
const root = rootElement.value;
if (!root) return;
root.removeEventListener('click', onRootClick, true);
root.removeEventListener('mouseover', onHover, true);
@@ -1865,16 +1855,67 @@ const formatJSON = (obj: any): string => {
}
.tool-output-wrapper {
.detail-output {
font-size: 13px;
color: #333;
background: #ffffff;
padding: 12px;
border-radius: 6px;
white-space: pre-wrap;
word-break: break-word;
margin: 12px 0;
padding: 0 10px;
.fallback-header {
display: flex;
align-items: center;
margin-bottom: 10px;
padding: 0 4px;
.fallback-label {
font-size: 12px;
color: #666;
font-weight: 500;
line-height: 1.5;
}
}
.detail-output-wrapper {
position: relative;
background: #fafafa;
border: 1px solid #e5e7eb;
line-height: 1.6;
border-radius: 6px;
overflow: hidden;
margin: 0;
padding: 0;
.detail-output {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'Courier New', monospace;
font-size: 12px;
color: #333;
padding: 16px;
margin: 0;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.6;
max-height: 400px;
overflow-y: auto;
overflow-x: auto;
background: #ffffff;
display: block;
// 滚动条样式
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: #f5f5f5;
border-radius: 4px;
}
&::-webkit-scrollbar-thumb {
background: #d1d5db;
border-radius: 4px;
&:hover {
background: #9ca3af;
}
}
}
}
}
@@ -2134,6 +2175,8 @@ const formatJSON = (obj: any): string => {
.tool-arguments-wrapper {
margin-top: 8px;
padding: 0 10px;
margin-bottom: 8px;
.arguments-header {
margin-bottom: 6px;
@@ -63,7 +63,12 @@
<!-- Fallback: Display raw output -->
<div v-else class="fallback-output">
<div class="detail-output">{{ output }}</div>
<div class="fallback-header">
<span class="fallback-label">原始输出</span>
</div>
<div class="detail-output-wrapper">
<div class="detail-output">{{ output }}</div>
</div>
</div>
</div>
</template>
@@ -116,15 +121,67 @@ const toolArguments = computed(() => props.arguments || {});
}
.fallback-output {
.detail-output {
font-size: 13px;
color: #333;
background: #f5f5f5;
padding: 8px;
border-radius: 4px;
white-space: pre-wrap;
word-break: break-word;
border: 1px solid #e7e7e7;
margin: 12px 0;
padding: 0;
.fallback-header {
display: flex;
align-items: center;
margin-bottom: 10px;
padding: 0 4px;
.fallback-label {
font-size: 12px;
color: #666;
font-weight: 500;
line-height: 1.5;
}
}
.detail-output-wrapper {
position: relative;
background: #fafafa;
border: 1px solid #e5e7eb;
border-radius: 6px;
overflow: hidden;
margin: 0;
padding: 0;
.detail-output {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'Courier New', monospace;
font-size: 12px;
color: #333;
padding: 16px;
margin: 0;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.6;
max-height: 400px;
overflow-y: auto;
overflow-x: auto;
background: #ffffff;
display: block;
// 滚动条样式
&::-webkit-scrollbar {
width: 8px;
height: 8px;
}
&::-webkit-scrollbar-track {
background: #f5f5f5;
border-radius: 4px;
}
&::-webkit-scrollbar-thumb {
background: #d1d5db;
border-radius: 4px;
&:hover {
background: #9ca3af;
}
}
}
}
}
</style>
+8 -1
View File
@@ -137,6 +137,8 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
content: step.thought,
done: true,
thinking: false,
// Extract duration from step if available
duration_ms: step.duration || undefined,
});
}
@@ -152,7 +154,9 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
success: toolCall.result?.success !== false,
output: toolCall.result?.output || '',
error: toolCall.result?.error || undefined,
// Use both duration and duration_ms for compatibility
duration: toolCall.duration,
duration_ms: toolCall.duration,
display_type: toolCall.result?.data?.display_type,
tool_data: toolCall.result?.data,
});
@@ -597,7 +601,10 @@ const handleAgentChunk = (data) => {
toolCallEvent.success = success;
toolCallEvent.output = success ? (data.data.output || data.content) : (data.data.error || data.content);
toolCallEvent.error = !success ? (data.data.error || data.content) : undefined;
toolCallEvent.duration = data.data.duration_ms;
// Set both duration and duration_ms for compatibility
const duration = data.data.duration_ms !== undefined ? data.data.duration_ms : data.data.duration;
toolCallEvent.duration = duration;
toolCallEvent.duration_ms = duration;
toolCallEvent.display_type = data.data.display_type;
toolCallEvent.tool_data = data.data;
+2 -13
View File
@@ -164,19 +164,6 @@ func (e *AgentEngine) executeLoop(
Timestamp: time.Now(),
}
// Emit step event
e.eventBus.Emit(ctx, event.Event{
ID: generateEventID("step"),
Type: event.EventAgentStep,
SessionID: sessionID,
Data: event.AgentStepData{
Iteration: state.CurrentRound,
Thought: response.Content,
ToolCalls: step.ToolCalls,
Duration: time.Since(roundStart).Milliseconds(),
},
})
// 2. Check finish reason - if stop and no tool calls, agent is done
if response.FinishReason == "stop" && len(response.ToolCalls) == 0 {
logger.Infof(ctx, "[Agent][Round-%d] Agent finished - no more tool calls needed", state.CurrentRound+1)
@@ -195,6 +182,7 @@ func (e *AgentEngine) executeLoop(
Done: true,
},
})
step.Duration = time.Since(roundStart).Milliseconds()
logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms", state.CurrentRound+1, time.Since(roundStart).Milliseconds())
break
}
@@ -345,6 +333,7 @@ func (e *AgentEngine) executeLoop(
}
}
step.Duration = time.Since(roundStart).Milliseconds()
state.RoundSteps = append(state.RoundSteps, step)
// 4. Observe: Add tool results to messages and write to context
messages = e.appendToolResults(ctx, messages, step)
+2 -2
View File
@@ -29,12 +29,12 @@ func NewMCPTool(service *types.MCPService, mcpTool *types.MCPTool, mcpManager *m
}
// Name returns the unique name for this tool
// Format: mcp_{service_name}_{tool_name}
// Format: mcp.{service_name}.{tool_name}
func (t *MCPTool) Name() string {
// Sanitize service name and tool name to create a valid identifier
serviceName := sanitizeName(t.service.Name)
toolName := sanitizeName(t.mcpTool.Name)
return fmt.Sprintf("mcp_%s_%s", serviceName, toolName)
return fmt.Sprintf("mcp.%s.%s", serviceName, toolName)
}
// Description returns the tool description
@@ -123,9 +123,15 @@ func (h *AgentStreamHandler) handleToolCall(ctx context.Context, evt event.Event
return nil
}
h.mu.Lock()
// Track start time for this tool call (use tool_call_id as key)
h.eventStartTimes[data.ToolCallID] = time.Now()
h.mu.Unlock()
metadata := map[string]interface{}{
"tool_name": data.ToolName,
"arguments": data.Arguments,
"tool_name": data.ToolName,
"arguments": data.Arguments,
"tool_call_id": data.ToolCallID,
}
// Append event to stream
@@ -150,6 +156,18 @@ func (h *AgentStreamHandler) handleToolResult(ctx context.Context, evt event.Eve
return nil
}
h.mu.Lock()
// Calculate duration from start time if available, otherwise use provided duration
var durationMs int64
if startTime, exists := h.eventStartTimes[data.ToolCallID]; exists {
durationMs = time.Since(startTime).Milliseconds()
delete(h.eventStartTimes, data.ToolCallID)
} else if data.Duration > 0 {
// Fallback to provided duration if start time not tracked
durationMs = data.Duration
}
h.mu.Unlock()
// Send SSE response (both success and failure)
responseType := types.ResponseTypeToolResult
content := data.Output
@@ -162,11 +180,12 @@ func (h *AgentStreamHandler) handleToolResult(ctx context.Context, evt event.Eve
// Build metadata including tool result data for rich frontend rendering
metadata := map[string]interface{}{
"tool_name": data.ToolName,
"success": data.Success,
"output": data.Output,
"error": data.Error,
"duration": data.Duration,
"tool_name": data.ToolName,
"success": data.Success,
"output": data.Output,
"error": data.Error,
"duration_ms": durationMs,
"tool_call_id": data.ToolCallID,
}
// Merge tool result data (contains display_type, formatted results, etc.)
@@ -264,8 +283,30 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
}
h.mu.Lock()
// Track start time on first chunk
if _, exists := h.eventStartTimes[evt.ID]; !exists {
h.eventStartTimes[evt.ID] = time.Now()
}
// Accumulate final answer locally for assistant message (database)
h.finalAnswer += data.Content
// Calculate duration if done
var metadata map[string]interface{}
if data.Done {
startTime := h.eventStartTimes[evt.ID]
duration := time.Since(startTime)
metadata = map[string]interface{}{
"event_id": evt.ID,
"duration_ms": duration.Milliseconds(),
"completed_at": time.Now().Unix(),
}
delete(h.eventStartTimes, evt.ID)
} else {
metadata = map[string]interface{}{
"event_id": evt.ID,
}
}
h.mu.Unlock()
// Append this chunk to stream (frontend will accumulate by event ID)
@@ -275,6 +316,7 @@ func (h *AgentStreamHandler) handleFinalAnswer(ctx context.Context, evt event.Ev
Content: data.Content, // Just this chunk
Done: data.Done,
Timestamp: time.Now(),
Data: metadata,
}); err != nil {
logger.GetLogger(h.ctx).Error("Append answer event to stream failed", "error", err)
}