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:
@@ -1,5 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="agent-stream-display">
|
<div ref="rootElement" class="agent-stream-display">
|
||||||
|
|
||||||
<!-- Collapsed intermediate steps -->
|
<!-- Collapsed intermediate steps -->
|
||||||
<div v-if="shouldShowCollapsedSteps" class="intermediate-steps-collapsed">
|
<div v-if="shouldShowCollapsedSteps" class="intermediate-steps-collapsed">
|
||||||
@@ -131,7 +131,12 @@
|
|||||||
|
|
||||||
<!-- Fallback to original output display -->
|
<!-- Fallback to original output display -->
|
||||||
<div v-else-if="event.output" class="tool-output-wrapper">
|
<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>
|
</div>
|
||||||
|
|
||||||
<!-- Show Arguments only if no display_type and not for todo_write -->
|
<!-- Show Arguments only if no display_type and not for todo_write -->
|
||||||
@@ -179,7 +184,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<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 { useRouter } from 'vue-router';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import DOMPurify from 'dompurify';
|
import DOMPurify from 'dompurify';
|
||||||
@@ -188,6 +193,9 @@ import { getChunkByIdOnly } from '@/api/knowledge-base';
|
|||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
// 根元素引用
|
||||||
|
const rootElement = ref<HTMLElement | null>(null);
|
||||||
|
|
||||||
// 浮层状态(Web/KB 共用)
|
// 浮层状态(Web/KB 共用)
|
||||||
const KB_SNIPPET_LIMIT = 600;
|
const KB_SNIPPET_LIMIT = 600;
|
||||||
|
|
||||||
@@ -415,7 +423,6 @@ const intermediateStepsSummary = computed(() => {
|
|||||||
const toolCalls: string[] = [];
|
const toolCalls: string[] = [];
|
||||||
let searchCount = 0;
|
let searchCount = 0;
|
||||||
let thinkingCount = 0;
|
let thinkingCount = 0;
|
||||||
let totalDuration = 0;
|
|
||||||
|
|
||||||
for (const event of stream) {
|
for (const event of stream) {
|
||||||
if (event.type === 'tool_call' && event.tool_name) {
|
if (event.type === 'tool_call' && event.tool_name) {
|
||||||
@@ -433,22 +440,13 @@ const intermediateStepsSummary = computed(() => {
|
|||||||
toolCalls.push(toolName);
|
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) {
|
} else if (event.type === 'thinking' && event.content) {
|
||||||
// Count if it's not the final thinking
|
// Count if it's not the final thinking
|
||||||
if (finalContent.value.type !== 'thinking' || event.event_id !== finalContent.value.event_id) {
|
if (finalContent.value.type !== 'thinking' || event.event_id !== finalContent.value.event_id) {
|
||||||
thinkingCount++;
|
thinkingCount++;
|
||||||
// Accumulate duration for thinking events
|
|
||||||
if (event.duration_ms) {
|
|
||||||
totalDuration += event.duration_ms;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const parts: string[] = [];
|
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) {
|
if (parts.length === 0) {
|
||||||
return `<strong>${intermediateStepsCount.value}</strong> 个中间步骤`;
|
return `<strong>${intermediateStepsCount.value}</strong> 个中间步骤`;
|
||||||
}
|
}
|
||||||
@@ -868,22 +855,25 @@ const onRootKeydown = (e: KeyboardEvent) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
const root = document.querySelector('.agent-stream-display');
|
// 使用 nextTick 确保 DOM 已渲染
|
||||||
if (!root) return;
|
nextTick(() => {
|
||||||
root.addEventListener('click', onRootClick, true);
|
const root = rootElement.value;
|
||||||
const keydownListener: EventListener = (evt: Event) => onRootKeydown(evt as KeyboardEvent);
|
if (!root) return;
|
||||||
// Store on element for removal
|
root.addEventListener('click', onRootClick, true);
|
||||||
(root as any).__citationKeydown__ = keydownListener;
|
const keydownListener: EventListener = (evt: Event) => onRootKeydown(evt as KeyboardEvent);
|
||||||
root.addEventListener('keydown', keydownListener, true);
|
// Store on element for removal
|
||||||
// 统一 hover 监听
|
(root as any).__citationKeydown__ = keydownListener;
|
||||||
root.addEventListener('mouseover', onHover, true);
|
root.addEventListener('keydown', keydownListener, true);
|
||||||
root.addEventListener('mouseout', onHoverOut, true);
|
// 统一 hover 监听
|
||||||
window.addEventListener('scroll', scheduleFloatClose, true);
|
root.addEventListener('mouseover', onHover, true);
|
||||||
window.addEventListener('resize', scheduleFloatClose, true);
|
root.addEventListener('mouseout', onHoverOut, true);
|
||||||
|
window.addEventListener('scroll', scheduleFloatClose, true);
|
||||||
|
window.addEventListener('resize', scheduleFloatClose, true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
const root = document.querySelector('.agent-stream-display');
|
const root = rootElement.value;
|
||||||
if (!root) return;
|
if (!root) return;
|
||||||
root.removeEventListener('click', onRootClick, true);
|
root.removeEventListener('click', onRootClick, true);
|
||||||
root.removeEventListener('mouseover', onHover, true);
|
root.removeEventListener('mouseover', onHover, true);
|
||||||
@@ -1865,16 +1855,67 @@ const formatJSON = (obj: any): string => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.tool-output-wrapper {
|
.tool-output-wrapper {
|
||||||
.detail-output {
|
margin: 12px 0;
|
||||||
font-size: 13px;
|
padding: 0 10px;
|
||||||
color: #333;
|
|
||||||
background: #ffffff;
|
.fallback-header {
|
||||||
padding: 12px;
|
display: flex;
|
||||||
border-radius: 6px;
|
align-items: center;
|
||||||
white-space: pre-wrap;
|
margin-bottom: 10px;
|
||||||
word-break: break-word;
|
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: 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 {
|
.tool-arguments-wrapper {
|
||||||
margin-top: 8px;
|
margin-top: 8px;
|
||||||
|
padding: 0 10px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
|
||||||
.arguments-header {
|
.arguments-header {
|
||||||
margin-bottom: 6px;
|
margin-bottom: 6px;
|
||||||
|
|||||||
@@ -63,7 +63,12 @@
|
|||||||
|
|
||||||
<!-- Fallback: Display raw output -->
|
<!-- Fallback: Display raw output -->
|
||||||
<div v-else class="fallback-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>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -116,15 +121,67 @@ const toolArguments = computed(() => props.arguments || {});
|
|||||||
}
|
}
|
||||||
|
|
||||||
.fallback-output {
|
.fallback-output {
|
||||||
.detail-output {
|
margin: 12px 0;
|
||||||
font-size: 13px;
|
padding: 0;
|
||||||
color: #333;
|
|
||||||
background: #f5f5f5;
|
.fallback-header {
|
||||||
padding: 8px;
|
display: flex;
|
||||||
border-radius: 4px;
|
align-items: center;
|
||||||
white-space: pre-wrap;
|
margin-bottom: 10px;
|
||||||
word-break: break-word;
|
padding: 0 4px;
|
||||||
border: 1px solid #e7e7e7;
|
|
||||||
|
.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>
|
</style>
|
||||||
|
|||||||
@@ -137,6 +137,8 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
|
|||||||
content: step.thought,
|
content: step.thought,
|
||||||
done: true,
|
done: true,
|
||||||
thinking: false,
|
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,
|
success: toolCall.result?.success !== false,
|
||||||
output: toolCall.result?.output || '',
|
output: toolCall.result?.output || '',
|
||||||
error: toolCall.result?.error || undefined,
|
error: toolCall.result?.error || undefined,
|
||||||
|
// Use both duration and duration_ms for compatibility
|
||||||
duration: toolCall.duration,
|
duration: toolCall.duration,
|
||||||
|
duration_ms: toolCall.duration,
|
||||||
display_type: toolCall.result?.data?.display_type,
|
display_type: toolCall.result?.data?.display_type,
|
||||||
tool_data: toolCall.result?.data,
|
tool_data: toolCall.result?.data,
|
||||||
});
|
});
|
||||||
@@ -597,7 +601,10 @@ const handleAgentChunk = (data) => {
|
|||||||
toolCallEvent.success = success;
|
toolCallEvent.success = success;
|
||||||
toolCallEvent.output = success ? (data.data.output || data.content) : (data.data.error || data.content);
|
toolCallEvent.output = success ? (data.data.output || data.content) : (data.data.error || data.content);
|
||||||
toolCallEvent.error = !success ? (data.data.error || data.content) : undefined;
|
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.display_type = data.data.display_type;
|
||||||
toolCallEvent.tool_data = data.data;
|
toolCallEvent.tool_data = data.data;
|
||||||
|
|
||||||
|
|||||||
@@ -164,19 +164,6 @@ func (e *AgentEngine) executeLoop(
|
|||||||
Timestamp: time.Now(),
|
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
|
// 2. Check finish reason - if stop and no tool calls, agent is done
|
||||||
if response.FinishReason == "stop" && len(response.ToolCalls) == 0 {
|
if response.FinishReason == "stop" && len(response.ToolCalls) == 0 {
|
||||||
logger.Infof(ctx, "[Agent][Round-%d] Agent finished - no more tool calls needed", state.CurrentRound+1)
|
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,
|
Done: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
step.Duration = time.Since(roundStart).Milliseconds()
|
||||||
logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms", state.CurrentRound+1, time.Since(roundStart).Milliseconds())
|
logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms", state.CurrentRound+1, time.Since(roundStart).Milliseconds())
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -345,6 +333,7 @@ func (e *AgentEngine) executeLoop(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
step.Duration = time.Since(roundStart).Milliseconds()
|
||||||
state.RoundSteps = append(state.RoundSteps, step)
|
state.RoundSteps = append(state.RoundSteps, step)
|
||||||
// 4. Observe: Add tool results to messages and write to context
|
// 4. Observe: Add tool results to messages and write to context
|
||||||
messages = e.appendToolResults(ctx, messages, step)
|
messages = e.appendToolResults(ctx, messages, step)
|
||||||
|
|||||||
@@ -29,12 +29,12 @@ func NewMCPTool(service *types.MCPService, mcpTool *types.MCPTool, mcpManager *m
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the unique name for this tool
|
// 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 {
|
func (t *MCPTool) Name() string {
|
||||||
// Sanitize service name and tool name to create a valid identifier
|
// Sanitize service name and tool name to create a valid identifier
|
||||||
serviceName := sanitizeName(t.service.Name)
|
serviceName := sanitizeName(t.service.Name)
|
||||||
toolName := sanitizeName(t.mcpTool.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
|
// Description returns the tool description
|
||||||
|
|||||||
@@ -123,9 +123,15 @@ func (h *AgentStreamHandler) handleToolCall(ctx context.Context, evt event.Event
|
|||||||
return nil
|
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{}{
|
metadata := map[string]interface{}{
|
||||||
"tool_name": data.ToolName,
|
"tool_name": data.ToolName,
|
||||||
"arguments": data.Arguments,
|
"arguments": data.Arguments,
|
||||||
|
"tool_call_id": data.ToolCallID,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append event to stream
|
// Append event to stream
|
||||||
@@ -150,6 +156,18 @@ func (h *AgentStreamHandler) handleToolResult(ctx context.Context, evt event.Eve
|
|||||||
return nil
|
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)
|
// Send SSE response (both success and failure)
|
||||||
responseType := types.ResponseTypeToolResult
|
responseType := types.ResponseTypeToolResult
|
||||||
content := data.Output
|
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
|
// Build metadata including tool result data for rich frontend rendering
|
||||||
metadata := map[string]interface{}{
|
metadata := map[string]interface{}{
|
||||||
"tool_name": data.ToolName,
|
"tool_name": data.ToolName,
|
||||||
"success": data.Success,
|
"success": data.Success,
|
||||||
"output": data.Output,
|
"output": data.Output,
|
||||||
"error": data.Error,
|
"error": data.Error,
|
||||||
"duration": data.Duration,
|
"duration_ms": durationMs,
|
||||||
|
"tool_call_id": data.ToolCallID,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Merge tool result data (contains display_type, formatted results, etc.)
|
// 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()
|
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)
|
// Accumulate final answer locally for assistant message (database)
|
||||||
h.finalAnswer += data.Content
|
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()
|
h.mu.Unlock()
|
||||||
|
|
||||||
// Append this chunk to stream (frontend will accumulate by event ID)
|
// 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
|
Content: data.Content, // Just this chunk
|
||||||
Done: data.Done,
|
Done: data.Done,
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
|
Data: metadata,
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
logger.GetLogger(h.ctx).Error("Append answer event to stream failed", "error", err)
|
logger.GetLogger(h.ctx).Error("Append answer event to stream failed", "error", err)
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user