Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat: implement final_answer tool and enhance agent duration tracking
wizardchena4b255a456c7
diff --git "a/.codebuddy/rules/\345\233\275\351\231\205\345\214\226\350\257\255\350\250\200\346\224\257\346\214\201.mdc" "b/.codebuddy/rules/\345\233\275\351\231\205\345\214\226\350\257\255\350\250\200\346\224\257\346\214\201.mdc"new file mode 100644index 000000000..5db199f39--- /dev/null+++ "b/.codebuddy/rules/\345\233\275\351\231\205\345\214\226\350\257\255\350\250\200\346\224\257\346\214\201.mdc"@@ -0,0 +1,9 @@+---+description:+alwaysApply: true+enabled: true+updatedAt: 2026-03-06T08:11:34.113Z+provider:+---++i18n国际化文件修改的时候同时修改i18n/locals下面的所有语言文件\ No newline at end of filediff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex cecd9cbcc..13d2cfea0 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -266,6 +266,8 @@ export default {webSearchFound: 'Found <strong>{count}</strong> web search result(s)',argumentsLabel: 'Arguments',toolFallback: 'Tool',+ stepsCompleted: 'Completed <strong>{steps}</strong> step(s)',+ stepsCompletedWithDuration: 'Completed <strong>{steps}</strong> step(s) in <strong>{duration}</strong>',title: 'Agents',subtitle: 'Configure and manage your agents to customize conversation behavior and capabilities',createAgent: 'Create Agent',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 81bbe05ad..44f7c36f7 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -917,6 +917,8 @@ export default {webSearchFound: "<strong>{count}</strong>개의 웹 검색 결과 발견",argumentsLabel: "파라미터",toolFallback: "도구",+ stepsCompleted: "<strong>{steps}</strong>개 단계 완료",+ stepsCompletedWithDuration: "<strong>{steps}</strong>개 단계 완료, 소요 시간 <strong>{duration}</strong>",title: "에이전트",subtitle: "에이전트 구성 및 관리, 대화 동작 및 기능 맞춤화",createAgent: "에이전트 만들기",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 2c5895673..b7d8b53d3 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -256,6 +256,8 @@ export default {webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',argumentsLabel: 'Параметры',toolFallback: 'Инструмент',+ stepsCompleted: 'Выполнено <strong>{steps}</strong> шаг(ов)',+ stepsCompletedWithDuration: 'Выполнено <strong>{steps}</strong> шаг(ов) за <strong>{duration}</strong>',editor: {skillsConfig: 'Skills',skillsConfigDesc: 'Настройка предустановленных Skills для агента, предоставляющих специализированные знания и рабочие процессы',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex b0bc35df5..6146acc3f 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -910,6 +910,8 @@ export default {webSearchFound: "找到 <strong>{count}</strong> 个网络搜索结果",argumentsLabel: "参数",toolFallback: "工具",+ stepsCompleted: "已完成 <strong>{steps}</strong> 个步骤",+ stepsCompletedWithDuration: "已完成 <strong>{steps}</strong> 个步骤,耗时 <strong>{duration}</strong>",title: "智能体",subtitle: "配置和管理您的智能体,自定义对话行为和能力",createAgent: "创建智能体",diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex 72d6a039f..13fbd2d67 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -1,23 +1,158 @@<template><div ref="rootElement" class="agent-stream-display">- <!-- Collapsed intermediate steps -->- <div v-if="shouldShowCollapsedSteps" class="intermediate-steps-collapsed">- <div class="intermediate-steps-header" @click="toggleIntermediateSteps">- <div class="intermediate-steps-title">+ <!-- Collapsed intermediate steps (tree root) -->+ <div v-if="shouldShowCollapsedSteps" class="tree-container">+ <div class="tree-root" @click="toggleIntermediateSteps">+ <div class="tree-root-title"><img :src="agentIcon" alt="" /><span v-html="intermediateStepsSummaryHtml"></span></div>- <div class="intermediate-steps-show-icon">+ <div class="tree-root-toggle"><t-icon :name="showIntermediateSteps ? 'chevron-up' : 'chevron-down'" /></div></div>+ <!-- Tree children (intermediate steps) -->+ <div v-if="showIntermediateSteps" class="tree-children">+ <template v-for="(event, index) in intermediateEvents" :key="getEventKey(event, index)">+ <div v-if="event && event.type" class="tree-child" :class="{ 'tree-child-last': index === intermediateEvents.length - 1 }">+ <div class="tree-branch"></div>+ <div class="tree-child-content">+ <!-- Plan Task Change Event -->+ <div v-if="event.type === 'plan_task_change'" class="plan-task-change-event">+ <div class="plan-task-change-card">+ <div class="plan-task-change-content">+ <strong>{{ $t('agent.taskLabel') }}</strong> {{ event.task }}+ </div>+ </div>+ </div>++ <!-- Thinking Event (streaming / merged) -->+ <div v-if="event.type === 'thinking'" class="tool-event">+ <div class="action-card" :class="{ 'action-pending': isThinkingActive(event.event_id) }">+ <div class="action-header" @click="toggleEvent(event.event_id)">+ <div class="action-title">+ <img class="action-title-icon" :src="thinkingIcon" alt="" />+ <span class="action-name">深度思考</span>+ <span v-if="getThinkingSummary(event) && !isEventExpanded(event.event_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>+ </div>+ <div v-if="event.content" class="action-show-icon">+ <t-icon :name="isEventExpanded(event.event_id) ? 'chevron-up' : 'chevron-down'" />+ </div>+ </div>+ <div v-if="event.content && isEventExpanded(event.event_id)" class="action-details">+ <div class="thinking-detail-content markdown-content">+ <div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>+ </div>+ </div>+ </div>+ </div>++ <!-- Thinking Tool Call -->+ <div v-else-if="event.type === 'tool_call' && event.tool_name === 'thinking'" class="tool-event">+ <div class="action-card" :class="{ 'action-pending': event.pending || isThinkingActive(event.tool_call_id) }">+ <div class="action-header" @click="toggleEvent(event.tool_call_id)">+ <div class="action-title">+ <img class="action-title-icon" :src="thinkingIcon" alt="" />+ <span class="action-name">深度思考</span>+ <span v-if="event.tool_data?.thought_number" class="action-badge">{{ event.tool_data.thought_number }}/{{ event.tool_data.total_thoughts }}</span>+ <span v-if="getThinkingSummary(event) && !isEventExpanded(event.tool_call_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>+ </div>+ <div v-if="event.tool_data?.thought" class="action-show-icon">+ <t-icon :name="isEventExpanded(event.tool_call_id) ? 'chevron-up' : 'chevron-down'" />+ </div>+ </div>+ <div v-if="event.tool_data?.thought && isEventExpanded(event.tool_call_id)" class="action-details">+ <div class="thinking-detail-content markdown-content">+ <div v-for="(token, idx) in getTokens(event.tool_data.thought)" :key="idx" v-html="getTokenHTML(token)"></div>+ </div>+ </div>+ </div>+ </div>++ <!-- Tool Call Event (non-thinking) -->+ <div v-else-if="event.type === 'tool_call'" class="tool-event">+ <div+ class="action-card"+ :class="{+ 'action-pending': event.pending,+ 'action-error': event.success === false+ }"+ >+ <div class="action-header" @click="handleActionHeaderClick(event)" :class="{ 'no-results': !hasResults(event) }">+ <div class="action-title">+ <img v-if="event.tool_name && !isBookIcon(event.tool_name)" class="action-title-icon" :src="getToolIcon(event.tool_name)" alt="" />+ <t-icon v-if="event.tool_name && isBookIcon(event.tool_name)" class="action-title-icon" name="book" />+ <t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="t('agent.updatePlan')" placement="top">+ <span class="action-name">{{ $t('agent.updatePlan') }}</span>+ </t-tooltip>+ <t-tooltip v-else :content="getToolTitle(event)" placement="top">+ <span class="action-name">{{ getToolTitle(event) }}</span>+ </t-tooltip>+ </div>+ <div v-if="!event.pending && hasResults(event)" class="action-show-icon">+ <t-icon :name="isEventExpanded(event.tool_call_id) ? 'chevron-up' : 'chevron-down'" />+ </div>+ </div>++ <div v-if="!event.pending && event.tool_name === 'todo_write' && event.tool_data?.steps" class="plan-status-summary-fixed">+ <div class="plan-status-text">+ <template v-for="(part, partIndex) in getPlanStatusItems(event)" :key="partIndex">+ <t-icon :name="part.icon" :class="['status-icon', part.class]" />+ <span>{{ part.label }} {{ part.count }}</span>+ <span v-if="partIndex < getPlanStatusItems(event).length - 1" class="separator">·</span>+ </template>+ </div>+ </div>++ <div v-if="!event.pending && (event.tool_name === 'search_knowledge' || event.tool_name === 'knowledge_search') && event.tool_data" class="search-results-summary-fixed">+ <div class="results-summary-text" v-html="getSearchResultsSummary(event)"></div>+ </div>++ <div v-if="!event.pending && event.tool_name === 'web_search' && event.tool_data" class="search-results-summary-fixed">+ <div class="results-summary-text" v-html="t('agent.webSearchFound', { count: getResultsCount(event.tool_data) })"></div>+ </div>++ <div v-if="!event.pending && event.tool_name === 'grep_chunks' && event.tool_data" class="search-results-summary-fixed grep-summary">+ <div class="results-summary-text" v-html="getGrepResultsSummary(event.tool_data)"></div>+ </div>++ <div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasResults(event)" class="action-details">+ <div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">+ <ToolResultRenderer+ :display-type="event.display_type"+ :tool-data="event.tool_data"+ :output="event.output"+ :arguments="event.arguments"+ />+ </div>+ <div v-else-if="event.output" class="tool-output-wrapper">+ <div class="fallback-header">+ <span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>+ </div>+ <div class="detail-output-wrapper">+ <div class="detail-output">{{ event.output }}</div>+ </div>+ </div>+ <div v-if="event.arguments && event.tool_name !== 'todo_write' && !event.display_type" class="tool-arguments-wrapper">+ <div class="arguments-header">+ <span class="arguments-label">{{ $t('agent.argumentsLabel') }}</span>+ </div>+ <pre class="detail-code">{{ formatJSON(event.arguments) }}</pre>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </template>+ </div></div>-- <!-- Event Stream -->++ <!-- Event Stream (non-tree mode: before answer starts, or answer events) --><template v-for="(event, index) in displayEvents" :key="getEventKey(event, index)">- <div v-if="event && event.type" class="event-item" :data-event-index="index" :class="{ 'event-last': index === displayEvents.length - 1, 'no-timeline': !shouldShowTimeline }">-+ <div v-if="event && event.type" class="event-item" :class="{ 'event-answer': event.type === 'answer' }">+<!-- Plan Task Change Event --><div v-if="event.type === 'plan_task_change'" class="plan-task-change-event"><div class="plan-task-change-card">@@ -26,35 +161,57 @@</div></div></div>-- <!-- Thinking Event -->- <div v-if="event.type === 'thinking'" class="thinking-event">- <div- class="thinking-phase"- :class="{- 'thinking-active': event.thinking,- 'thinking-last': isLastThinking(event.event_id)- }"- >- <div v-if="event.content" class="thinking-content markdown-content">- <div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>++ <!-- Thinking Event (streaming / merged) -->+ <div v-if="event.type === 'thinking'" class="tool-event">+ <div class="action-card" :class="{ 'action-pending': isThinkingActive(event.event_id) }">+ <div class="action-header" @click="toggleEvent(event.event_id)">+ <div class="action-title">+ <img class="action-title-icon" :src="thinkingIcon" alt="" />+ <span class="action-name">深度思考</span>+ <span v-if="getThinkingSummary(event) && !isEventExpanded(event.event_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>+ </div>+ <div v-if="event.content" class="action-show-icon">+ <t-icon :name="isEventExpanded(event.event_id) ? 'chevron-up' : 'chevron-down'" />+ </div>+ </div>+ <div v-if="event.content && isEventExpanded(event.event_id)" class="action-details">+ <div class="thinking-detail-content markdown-content">+ <div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>+ </div></div></div></div>-++ <!-- Thinking Tool Call -->+ <div v-else-if="event.type === 'tool_call' && event.tool_name === 'thinking'" class="tool-event">+ <div class="action-card" :class="{ 'action-pending': event.pending || isThinkingActive(event.tool_call_id) }">+ <div class="action-header" @click="toggleEvent(event.tool_call_id)">+ <div class="action-title">+ <img class="action-title-icon" :src="thinkingIcon" alt="" />+ <span class="action-name">深度思考</span>+ <span v-if="event.tool_data?.thought_number" class="action-badge">{{ event.tool_data.thought_number }}/{{ event.tool_data.total_thoughts }}</span>+ <span v-if="getThinkingSummary(event) && !isEventExpanded(event.tool_call_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>+ </div>+ <div v-if="event.tool_data?.thought" class="action-show-icon">+ <t-icon :name="isEventExpanded(event.tool_call_id) ? 'chevron-up' : 'chevron-down'" />+ </div>+ </div>+ <div v-if="event.tool_data?.thought && isEventExpanded(event.tool_call_id)" class="action-details">+ <div class="thinking-detail-content markdown-content">+ <div v-for="(token, idx) in getTokens(event.tool_data.thought)" :key="idx" v-html="getTokenHTML(token)"></div>+ </div>+ </div>+ </div>+ </div>+<!-- Answer Event --><div v-else-if="event.type === 'answer' && (event.done || (event.content && event.content.trim()))" class="answer-event"><divv-if="event.content && event.content.trim()"- class="answer-content-wrapper"- :class="{- 'answer-active': !event.done,- 'answer-done': event.done- }"+ class="answer-content markdown-content">- <div class="answer-content markdown-content">- <div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div>- </div>+ <div v-for="(token, idx) in getTokens(event.content)" :key="idx" v-html="getTokenHTML(token)"></div></div><div v-if="event.done" class="answer-toolbar"><t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)" :title="$t('agent.copy')">@@ -63,7 +220,6 @@<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)" :title="$t('agent.addToKnowledgeBase')"><t-icon name="add" /></t-button>- <!-- Fallback 提示图标 --><t-tooltip v-if="event.is_fallback" :content="$t('chat.fallbackHint')" placement="top"><t-button size="small" variant="outline" shape="round" class="fallback-icon-btn"><t-icon name="info-circle" />@@ -71,27 +227,25 @@</t-tooltip></div></div>-- <!-- Tool Call Event -->++ <!-- Tool Call Event (non-thinking) --><div v-else-if="event.type === 'tool_call'" class="tool-event">- <div- class="action-card"- :class="{+ <div+ class="action-card"+ :class="{'action-pending': event.pending,- 'action-error': event.success === false+ 'action-error': event.success === false}"><div class="action-header" @click="handleActionHeaderClick(event)" :class="{ 'no-results': !hasResults(event) }"><div class="action-title"><img v-if="event.tool_name && !isBookIcon(event.tool_name)" class="action-title-icon" :src="getToolIcon(event.tool_name)" alt="" /><t-icon v-if="event.tool_name && isBookIcon(event.tool_name)" class="action-title-icon" name="book" />- <!-- Custom header for todo_write tool --><t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="t('agent.updatePlan')" placement="top"><span class="action-name">{{ $t('agent.updatePlan') }}</span></t-tooltip>- <!-- Use tool summary as title if available, otherwise use description --><t-tooltip v-else :content="getToolTitle(event)" placement="top"><span class="action-name">{{ getToolTitle(event) }}</span></t-tooltip>@@ -100,8 +254,7 @@<t-icon :name="isEventExpanded(event.tool_call_id) ? 'chevron-up' : 'chevron-down'" /></div></div>-- <!-- Plan Status Summary (Fixed, always visible, outside action-details) -->+<div v-if="!event.pending && event.tool_name === 'todo_write' && event.tool_data?.steps" class="plan-status-summary-fixed"><div class="plan-status-text"><template v-for="(part, partIndex) in getPlanStatusItems(event)" :key="partIndex">@@ -111,45 +264,29 @@</template></div></div>-- <!-- Search Results Summary (Fixed, always visible, outside action-details) -->+<div v-if="!event.pending && (event.tool_name === 'search_knowledge' || event.tool_name === 'knowledge_search') && event.tool_data" class="search-results-summary-fixed"><div class="results-summary-text" v-html="getSearchResultsSummary(event)"></div></div>-- <!-- Web Search Results Summary (Fixed, always visible, outside action-details) -->+<div v-if="!event.pending && event.tool_name === 'web_search' && event.tool_data" class="search-results-summary-fixed"><div class="results-summary-text" v-html="t('agent.webSearchFound', { count: getResultsCount(event.tool_data) })"></div></div>-- <!-- Grep Results Summary (Fixed, always visible, outside action-details) -->+<div v-if="!event.pending && event.tool_name === 'grep_chunks' && event.tool_data" class="search-results-summary-fixed grep-summary"><div class="results-summary-text" v-html="getGrepResultsSummary(event.tool_data)"></div></div>-+<div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasResults(event)" class="action-details">- <!-- Thinking tool: only render markdown thought content -->- <template v-if="event.tool_name === 'thinking' && event.tool_data?.thought">- <div class="thinking-thought-content">- <div class="thinking-thought-markdown markdown-content">- <div v-for="(token, idx) in getTokens(event.tool_data.thought)" :key="idx" v-html="getTokenHTML(token)"></div>- </div>- </div>- </template>-- <!-- For other tools: show ToolResultRenderer or output -->- <template v-else>- <!-- Use ToolResultRenderer if display_type is available --><div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">- <ToolResultRenderer+ <ToolResultRenderer:display-type="event.display_type":tool-data="event.tool_data":output="event.output":arguments="event.arguments"/></div>-- <!-- Fallback to original output display -->+<div v-else-if="event.output" class="tool-output-wrapper"><div class="fallback-header"><span class="fallback-label">{{ $t('chat.rawOutputLabel') }}</span>@@ -158,23 +295,21 @@<div class="detail-output">{{ event.output }}</div></div></div>-- <!-- Show Arguments only if no display_type and not for todo_write -->+<div v-if="event.arguments && event.tool_name !== 'todo_write' && !event.display_type" class="tool-arguments-wrapper"><div class="arguments-header"><span class="arguments-label">{{ $t('agent.argumentsLabel') }}</span></div><pre class="detail-code">{{ formatJSON(event.arguments) }}</pre></div>- </template></div></div></div></div></template>-+<!-- Loading Indicator -->- <div v-if="!isConversationDone && eventStream.length > 0" class="loading-indicator" :class="{ 'no-timeline': !shouldShowTimeline }">+ <div v-if="!isConversationDone && eventStream.length > 0" class="loading-indicator"><!-- 方案1: 三个跳动的圆点 --><!-- <div class="loading-dots"><span></span>@@ -417,71 +552,99 @@ marked.use({// Event streamconst eventStream = computed(() => props.session?.agentEventStream || []);-// Check if should show timeline (only show when there are tool calls or thinking events)-const shouldShowTimeline = computed(() => {- // Only show timeline in agent mode and when there are intermediate steps- if (props.session?.isAgentMode !== true) {- return false;- }-- const stream = eventStream.value;- if (!stream || stream.length === 0) {- return false;- }-- // Check if there are any tool calls or thinking events (not just simple answer)- const hasToolCalls = stream.some((e: any) => e.type === 'tool_call');- const hasThinking = stream.some((e: any) => e.type === 'thinking');-- // Only show timeline if there are tool calls or thinking events- return hasToolCalls || hasThinking;-});--// Expanded events tracking (for tool calls)-// Initialize with thinking tools expanded by default+// Expanded events tracking (for tool calls and thinking events)const expandedEvents = ref<Set<string>>(new Set());-// Watch event stream to auto-expand thinking tools+// Track IDs of thinking events that are currently "active" (latest, not yet followed by non-thinking)+const activeThinkingIds = ref<Set<string>>(new Set());+// Reactive version number to force template re-evaluation when activeThinkingIds changes+const activeThinkingVersion = ref(0);++const isThinkingActive = (eventId: string): boolean => {+ // Reference version to create reactive dependency+ void activeThinkingVersion.value;+ return activeThinkingIds.value.has(eventId);+};++// Watch event stream to auto-expand thinking events and auto-collapse when non-thinking followswatch(eventStream, (stream) => {if (!stream || !Array.isArray(stream)) return;- stream.forEach((event: any) => {- if (event?.type === 'tool_call' && event?.tool_name === 'thinking' && event?.tool_call_id) {- expandedEvents.value.add(event.tool_call_id);+ // Scan stream to find thinking events to expand and collapse+ const newActiveIds = new Set<string>();++ // Walk backwards to find the trailing thinking block+ let inTrailingThinking = true;+ for (let i = stream.length - 1; i >= 0; i--) {+ const event = stream[i];+ if (!event) continue;++ const isThinking = event.type === 'thinking' ||+ (event.type === 'tool_call' && event.tool_name === 'thinking');+ const id = event.type === 'thinking' ? event.event_id : event.tool_call_id;++ if (inTrailingThinking && isThinking && id) {+ newActiveIds.add(id);+ // Auto-expand if not yet known+ expandedEvents.value.add(id);+ } else if (!isThinking) {+ inTrailingThinking = false;}- });+ }++ // Collapse thinking events that were active before but are no longer trailing+ for (const oldId of activeThinkingIds.value) {+ if (!newActiveIds.has(oldId)) {+ expandedEvents.value.delete(oldId);+ }+ }++ activeThinkingIds.value = newActiveIds;+ activeThinkingVersion.value++;nextTick(async () => {await hydrateProtectedFileImages(rootElement.value);- // 只在会话完成后渲染 Mermaid 图表if (props.session?.is_completed) {renderMermaidDiagrams();}+ // Auto-scroll thinking detail content to bottom during streaming+ if (newActiveIds.size > 0 && rootElement.value) {+ const els = rootElement.value.querySelectorAll('.thinking-detail-content');+ els.forEach((el: Element) => {+ const htmlEl = el as HTMLElement;+ if (htmlEl.scrollHeight > htmlEl.clientHeight) {+ htmlEl.scrollTop = htmlEl.scrollHeight;+ }+ });+ }});}, { immediate: true, deep: true });// State for intermediate steps collapseconst showIntermediateSteps = ref(false);-// Find the last thinking event in the current message's event stream-// Only the last thinking should have the green border-left-const lastThinkingEventId = computed(() => {- const stream = eventStream.value;- if (!stream || stream.length === 0) return null;-- // Find all thinking events- const thinkingEvents = stream.filter((e: any) => e.type === 'thinking');- if (thinkingEvents.length === 0) return null;-- // Return the event_id of the last thinking event- const lastThinking = thinkingEvents[thinkingEvents.length - 1];- return lastThinking.event_id;-});+// Track whether answer has started streaming (for early collapse)+const hasAnswerStarted = ref(false);+const agentDurationMs = ref<number>(0);+watch(eventStream, (stream) => {+ if (!stream || !Array.isArray(stream)) return;++ // Check for agent_complete event with authoritative duration from backend+ if (agentDurationMs.value === 0) {+ const completeEvent = stream.find((e: any) => e.type === 'agent_complete' && e.total_duration_ms);+ if (completeEvent) {+ agentDurationMs.value = completeEvent.total_duration_ms;+ }+ }++ if (hasAnswerStarted.value) return;++ const hasAnswer = stream.some((e: any) => e.type === 'answer' && e.content);+ if (hasAnswer) {+ hasAnswerStarted.value = true;+ }+}, { deep: true, immediate: true });-// Check if a thinking event is the last one (should have green border)-const isLastThinking = (eventId: string): boolean => {- return eventId === lastThinkingEventId.value;-};// Check if conversation is done (based on answer event with done=true or stop event)const isConversationDone = computed(() => {@@ -511,147 +674,57 @@ const isConversationDone = computed(() => {const finalContent = computed(() => {const stream = eventStream.value;if (!stream || stream.length === 0) {- console.log('[Collapse] finalContent: no stream');return null;}-+if (!isConversationDone.value) {- console.log('[Collapse] finalContent: not done yet');return null;}-- // Check if there's an answer event++ // Check if there's an answer event with content (normal path via final_answer tool)const answerEvents = stream.filter((e: any) => e.type === 'answer');- const doneAnswer = answerEvents.find((e: any) => e.done === true);const hasAnswerContent = answerEvents.some((e: any) => e.content && e.content.trim());-- console.log('[Collapse] Answer events:', answerEvents.length, 'Done answer:', !!doneAnswer, 'Has content:', hasAnswerContent);-- // Priority: answer with content > last thinking (if answer is empty)+if (hasAnswerContent) {- // Answer has content, it's the final content- console.log('[Collapse] finalContent: showing answer with content');return { type: 'answer' };- } else if (doneAnswer) {- // Answer is done but empty, find last thinking with content to show as final content- // (answer toolbar will still be shown via displayEvents logic)- const thinkingEvents = stream.filter((e: any) => e.type === 'thinking' && e.content && e.content.trim());- console.log('[Collapse] Thinking events with content:', thinkingEvents.length);-- if (thinkingEvents.length > 0) {- const lastThinking = thinkingEvents[thinkingEvents.length - 1];- console.log('[Collapse] finalContent: showing last thinking (answer empty, toolbar will show)', lastThinking.event_id);- return { type: 'thinking', event_id: lastThinking.event_id, showAnswerToolbar: true };- } else {- // No thinking content, show empty answer- console.log('[Collapse] finalContent: showing empty answer');- return { type: 'answer' };- }- } else {- // Answer is empty, find last thinking with content- const thinkingEvents = stream.filter((e: any) => e.type === 'thinking' && e.content && e.content.trim());- console.log('[Collapse] Thinking events with content:', thinkingEvents.length);-- if (thinkingEvents.length > 0) {- const lastThinking = thinkingEvents[thinkingEvents.length - 1];- console.log('[Collapse] finalContent: showing last thinking', lastThinking.event_id);- return { type: 'thinking', event_id: lastThinking.event_id };- }}-- console.log('[Collapse] finalContent: no final content found');++ // Fallback: if no answer content (legacy path or LLM didn't call final_answer),+ // use last thinking as final content+ const thinkingEvents = stream.filter((e: any) => e.type === 'thinking' && e.content && e.content.trim());+ if (thinkingEvents.length > 0) {+ const lastThinking = thinkingEvents[thinkingEvents.length - 1];+ const doneAnswer = answerEvents.find((e: any) => e.done === true);+ return {+ type: 'thinking',+ event_id: lastThinking.event_id,+ showAnswerToolbar: !!doneAnswer+ };+ }+return null;});-// Count intermediate steps (tools + thinking that will be collapsed)+// Count intermediate steps (after merging consecutive thinking events, matching what user sees in tree)const intermediateStepsCount = computed(() => {- if (!finalContent.value) {- console.log('[Collapse] intermediateStepsCount: no final content');- return 0;- }-- const stream = eventStream.value;- let count = 0;-- for (const event of stream) {- if (event.type === 'tool_call') {- count++;- } 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) {- count++;- }- }- }-- console.log('[Collapse] intermediateStepsCount:', count);- return count;+ if (!hasAnswerStarted.value && !isConversationDone.value) return 0;+ // Count only thinking and tool_call events (exclude plan_task_change, etc.)+ return intermediateEvents.value.filter((e: any) => e.type === 'thinking' || e.type === 'tool_call').length;});-// Get intermediate steps summary with special infoconst intermediateStepsSummary = computed(() => {- if (!finalContent.value || !eventStream.value) {+ if (!eventStream.value) {return '';}-- const stream = eventStream.value;- const toolCalls: string[] = [];- let searchCount = 0;- let thinkingCount = 0;-- for (const event of stream) {- if (event.type === 'tool_call' && event.tool_name) {- const toolName = event.tool_name;- if (toolName === 'search_knowledge' || toolName === 'knowledge_search') {- searchCount++;- } else if (toolName === 'thinking') {- // Count if it's not the final thinking- if (finalContent.value.type !== 'thinking' || event.event_id !== finalContent.value.event_id) {- thinkingCount++;- }- } else if (toolName !== 'todo_write') {- // Only add unique tool names- if (!toolCalls.includes(toolName)) {- toolCalls.push(toolName);- }- }-- } 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++;- }- }- }-- const parts: string[] = [];- if (searchCount > 0) {- parts.push(t('agentStream.summary.searchKb', { count: searchCount }));- }- if (thinkingCount > 0) {- parts.push(t('agentStream.summary.thinking', { count: thinkingCount }));- }- if (toolCalls.length > 0) {- const toolNames = toolCalls.map(name => getLocalizedToolName(name));- if (toolNames.length === 1) {- parts.push(t('agentStream.summary.callTool', { name: toolNames[0] }));- } else {- parts.push(t('agentStream.summary.callTools', { names: toolNames.join(t('agentStream.summary.separator')) }));- }- }- if (parts.length === 0) {- return t('agentStream.summary.intermediateSteps', { count: intermediateStepsCount.value });- }+ const steps = intermediateStepsCount.value;+ const elapsed = agentDurationMs.value;- if (parts.length === 1) {- return parts[0];- } else if (parts.length === 2) {- return `${parts[0]}${t('agentStream.summary.comma')}${parts[1]}`;- } else {- const last = parts.pop();- return `${parts.join(t('agentStream.summary.separator'))}${t('agentStream.summary.comma')}${last}`;+ if (elapsed > 0) {+ return t('agent.stepsCompletedWithDuration', { steps, duration: formatDuration(elapsed) });}++ return t('agent.stepsCompleted', { steps });});// HTML version of intermediate steps summary with colored numbers@@ -659,40 +732,55 @@ const intermediateStepsSummaryHtml = computed(() => {return intermediateStepsSummary.value;});-// Should show the collapsed steps indicator+// Should show the collapsed steps indicator (tree root)+// Triggers when answer starts streaming (early collapse) or when conversation is doneconst shouldShowCollapsedSteps = computed(() => {- const result = isConversationDone.value && intermediateStepsCount.value > 0;- console.log('[Collapse] shouldShowCollapsedSteps:', result, 'done:', isConversationDone.value, 'count:', intermediateStepsCount.value);- return result;+ const hasSteps = intermediateStepsCount.value > 0;+ return hasSteps && (hasAnswerStarted.value || isConversationDone.value);});-// Events to display (based on collapse state)-const displayEvents = computed(() => {- const stream = eventStream.value;- if (!stream || !Array.isArray(stream)) {- console.log('[Collapse] displayEvents: no stream or not array');- return [];+// Check if event is a "deep thinking" type (either streaming thinking or thinking tool call)+const isThinkingLikeEvent = (event: any): boolean => {+ if (event.type === 'thinking') return true;+ if (event.type === 'tool_call' && event.tool_name === 'thinking') return true;+ return false;+};++// Extract thinking content from an event+const getThinkingContent = (event: any): string => {+ if (event.type === 'thinking') return event.content || '';+ if (event.type === 'tool_call' && event.tool_name === 'thinking') {+ return event.tool_data?.thought || event.output || '';}-- // Filter out invalid events+ return '';+};++// Get a short summary snippet from thinking content for display in the header+const getThinkingSummary = (event: any): string => {+ const content = getThinkingContent(event);+ if (!content) return '';+ // Strip markdown formatting and take first meaningful line+ const cleaned = content+ .replace(/^#+\s+/gm, '') // remove heading markers+ .replace(/\*\*/g, '') // remove bold+ .replace(/\*/g, '') // remove italic+ .replace(/`/g, '') // remove code ticks+ .replace(/\n+/g, ' ') // collapse newlines+ .trim();+ if (cleaned.length <= 50) return cleaned;+ return cleaned.slice(0, 50) + '...';+};++// Helper: build the full result list with plan_task_change injections and thinking merging+const buildFullEventList = (stream: any[]) => {const validStream = stream.filter((e: any) => e && typeof e === 'object' && e.type);-- console.log('[Collapse] displayEvents: total stream length:', validStream.length);-- // Track task changes for todo_write events- // This works for both real-time streaming and historical messageslet lastTask: string | null = null;const result: any[] = [];-+for (let i = 0; i < validStream.length; i++) {const event = validStream[i];-- // Check if this is a todo_write event with task changeif (event.type === 'tool_call' && event.tool_name === 'todo_write' && event.tool_data?.task) {const currentTask = event.tool_data.task;-- // If task changed (or is first task), insert a task change event before the todo_write event- // For historical messages, we need to show the first task as wellif (lastTask === null || currentTask !== lastTask) {result.push({type: 'plan_task_change',@@ -701,56 +789,83 @@ const displayEvents = computed(() => {timestamp: event.timestamp || Date.now()});}-lastTask = currentTask;}-++ // Merge consecutive thinking-like events+ if (isThinkingLikeEvent(event) && result.length > 0) {+ const prev = result[result.length - 1];+ if (isThinkingLikeEvent(prev)) {+ // Merge into previous: combine content+ const prevContent = prev._mergedContent || getThinkingContent(prev);+ const curContent = getThinkingContent(event);+ const merged = [prevContent, curContent].filter(Boolean).join('\n\n');+ // Replace previous with a merged thinking event+ result[result.length - 1] = {+ type: 'thinking',+ event_id: prev.event_id,+ content: merged,+ thinking: prev.thinking || event.thinking,+ timestamp: prev.timestamp,+ _mergedContent: merged, // track for further merges+ };+ continue;+ }+ }+result.push(event);}-- // If not done, show everything (with task change events)- if (!isConversationDone.value) {- console.log('[Collapse] displayEvents: not done, showing all', result.length);- return result;+ return result;+};++// Intermediate events (tree children: everything except answer)+const intermediateEvents = computed(() => {+ const stream = eventStream.value;+ if (!stream || !Array.isArray(stream)) return [];+ const result = buildFullEventList(stream);+ return result.filter((e: any) => e.type !== 'answer' && e.type !== 'agent_complete');+});++// Events to display (non-tree: before answer starts show all, after answer starts show only answer)+const displayEvents = computed(() => {+ const stream = eventStream.value;+ if (!stream || !Array.isArray(stream)) {+ return [];}-- // If done but user wants to see intermediate steps, show all- if (showIntermediateSteps.value) {- console.log('[Collapse] displayEvents: user expanded, showing all', result.length);++ const result = buildFullEventList(stream);++ // If answer hasn't started and not done, show everything (no tree yet)+ if (!hasAnswerStarted.value && !isConversationDone.value) {return result;}-- // Otherwise, show only final content++ // When tree is active (shouldShowCollapsedSteps), displayEvents only shows answer events+ // The intermediate steps are rendered inside the tree-children via intermediateEvents++ // When answer has started (streaming or done), show only answer events here+ const answerEvents = result.filter((e: any) => e.type === 'answer');+ if (answerEvents.length > 0) {+ return answerEvents;+ }++ // Fallback: if no answer events, show last thinking (legacy compatibility)const final = finalContent.value;if (!final) {- console.log('[Collapse] displayEvents: no final content, showing all', result.length);return result;}-- if (final.type === 'answer') {- // Filter to show only answer events- const filtered = result.filter((e: any) => e.type === 'answer');- console.log('[Collapse] displayEvents: showing answer only', filtered.length);- return filtered;- } else if (final.type === 'thinking') {- // Show the last thinking as final content- const thinkingFiltered = result.filter((e: any) =>++ if (final.type === 'thinking') {+ const thinkingFiltered = result.filter((e: any) =>e.type === 'thinking' && e.event_id === final.event_id);-- // If answer is done but empty, also include answer event for toolbarif (final.showAnswerToolbar) {- const answerEvents = result.filter((e: any) => e.type === 'answer' && e.done === true);- const combined = [...thinkingFiltered, ...answerEvents];- console.log('[Collapse] displayEvents: showing last thinking + answer toolbar', combined.length);- return combined;+ const answerDoneEvents = result.filter((e: any) => e.type === 'answer' && e.done === true);+ return [...thinkingFiltered, ...answerDoneEvents];}-- console.log('[Collapse] displayEvents: showing last thinking only', thinkingFiltered.length);return thinkingFiltered;}-- console.log('[Collapse] displayEvents: fallback, showing all', result.length);+return result;});@@ -764,6 +879,11 @@ const getEventKey = (event: any, index: number): string => {const toggleIntermediateSteps = () => {showIntermediateSteps.value = !showIntermediateSteps.value;+ nextTick(async () => {+ if (rootElement.value) {+ await hydrateProtectedFileImages(rootElement.value);+ }+ });};const toggleEvent = (eventId: string) => {@@ -1001,15 +1121,17 @@ const onRootClick = (e: Event) => {const target = e.target as HTMLElement;if (!target) return;- // Handle image clicks -> open preview+ // Handle image clicks -> open preview (only for images inside markdown/answer content, not icons)if (target.tagName === 'IMG') {const imgEl = target as HTMLImageElement;- const src = imgEl.getAttribute('src');- if (src) {- e.preventDefault();- e.stopPropagation();- openImagePreview(src);- return;+ if (imgEl.closest('.markdown-content') || imgEl.closest('.answer-content')) {+ const src = imgEl.getAttribute('src');+ if (src) {+ e.preventDefault();+ e.stopPropagation();+ openImagePreview(src);+ return;+ }}}@@ -1706,323 +1828,130 @@ const handleAddToKnowledge = (answerEvent: any) => {position: relative;}-// 时间轴连线容器+// Event items (flat, no timeline).event-item {position: relative;- padding-left: 32px;margin-bottom: 12px;-- // 时间轴垂直线++ &.event-answer {+ // answer 事件无特殊左侧装饰+ }+}++// ============ Tree View ============+.tree-container {+ margin-bottom: 16px;+ position: relative;+}++.tree-root {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 5px 12px;+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ border-radius: 6px;+ background: linear-gradient(135deg, rgba(7, 192, 95, 0.06) 0%, rgba(7, 192, 95, 0.02) 50%, transparent 100%);+ border: 1px solid rgba(7, 192, 95, 0.12);+ backdrop-filter: blur(8px);+ color: var(--td-text-color-primary);+ transition: all 0.25s ease;++ &:hover {+ background: linear-gradient(135deg, rgba(7, 192, 95, 0.10) 0%, rgba(7, 192, 95, 0.04) 50%, transparent 100%);+ border-color: rgba(7, 192, 95, 0.22);+ box-shadow: 0 2px 8px rgba(7, 192, 95, 0.08);+ }+}++.tree-root-title {+ display: flex;+ align-items: center;++ img {+ width: 14px;+ height: 14px;+ margin-right: 7px;+ }++ span {+ white-space: nowrap;+ font-size: 13px;++ :deep(strong) {+ color: var(--td-brand-color);+ font-weight: 600;+ }+ }+}++.tree-root-toggle {+ font-size: 13px;+ padding: 0 2px 1px 2px;+ color: var(--td-brand-color);+}++.tree-children {+ position: relative;+ padding-left: 12px; // indent for branch lines+ margin-top: 6px; // gap from root+}++.tree-child {+ position: relative;+ padding-left: 20px; // space for the horizontal branch+ padding-bottom: 0;+ margin-bottom: 6px; // gap between children++ // vertical trunk line (continues for non-last children)&::before {content: '';position: absolute;- left: 10px;+ left: 0;top: 0;- bottom: -12px;- width: 1.5px;- background: linear-gradient(- to bottom,- rgba(7, 192, 95, 0.1) 0%,- rgba(7, 192, 95, 0.15) 50%,- rgba(7, 192, 95, 0.1) 100%- );- z-index: 0;- }-- // 第一个事件的连线从节点开始- &:first-child::before {- top: 14px;- }-- // 最后一个事件不显示底部连线- &.event-last::before {- bottom: auto;- height: 22px;+ bottom: 0;+ width: 0;+ border-left: 1px dashed var(--td-component-stroke);}-- // 时间轴节点(圆点)- &::after {- content: '';++ // horizontal branch connector+ .tree-branch {position: absolute;- left: 6.25px; // 线条中心 10.75px - 圆点半径 4.5px = 6.25px (box-sizing: border-box)- top: 14px;- width: 9px;- height: 9px;- border-radius: 50%;- background: var(--td-bg-color-container);- border: 2px solid rgba(7, 192, 95, 0.3);- z-index: 1;- transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);- box-shadow: var(--td-shadow-1);- box-sizing: border-box; // 确保 border 包含在尺寸内+ left: 0;+ top: 15px; // align with the middle of the child card header+ width: 16px;+ height: 0;+ border-top: 1px dashed var(--td-component-stroke);}- // 不同事件类型的节点颜色- &:has(.thinking-event)::after {- border-color: rgba(156, 163, 175, 0.4);- background: var(--td-bg-color-secondarycontainer);- box-shadow: var(--td-shadow-1);- }-- &:has(.answer-event)::after {- border-color: var(--td-brand-color);- background: var(--td-brand-color);- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.12), 0 2px 4px rgba(7, 192, 95, 0.2);- transform: scale(1.1);- }-- &:has(.tool-event)::after {- border-color: var(--td-brand-color);- background: var(--td-bg-color-container);- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.15);- }-- &:has(.tool-event .action-pending)::after {- border-color: var(--td-brand-color);- background: rgba(7, 192, 95, 0.15);- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);- animation: pulseNode 2s ease-in-out infinite;- }-- &:has(.tool-event .action-error)::after {- border-color: var(--td-error-color);- background: var(--td-error-color);- box-shadow: 0 0 0 2px rgba(227, 77, 89, 0.15), 0 2px 4px rgba(227, 77, 89, 0.2);- }-- &:has(.plan-task-change-event)::after {- border-color: var(--td-brand-color);- background: var(--td-brand-color);- transform: rotate(45deg) scale(0.9);- border-radius: 2px;- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.2);- }-- // 普通模式下隐藏时间轴(放在最后以确保优先级)- &.no-timeline {- padding-left: 0 !important;-- &::before,- &::after {- display: none !important;- content: none !important;- visibility: hidden !important;- opacity: 0 !important;- width: 0 !important;- height: 0 !important;- }-- // 确保所有事件类型的时间轴都被隐藏(使用更强的选择器)- &.event-last::before,- &.event-last::after,- &:first-child::before,- &:first-child::after,- &:has(.thinking-event)::before,- &:has(.thinking-event)::after,- &:has(.answer-event)::before,- &:has(.answer-event)::after,- &:has(.tool-event)::before,- &:has(.tool-event)::after,- &:has(.plan-task-change-event)::before,- &:has(.plan-task-change-event)::after {- display: none !important;- content: none !important;- visibility: hidden !important;- opacity: 0 !important;- width: 0 !important;- height: 0 !important;- }+ // last child: vertical line only goes to the branch, then stops+ &.tree-child-last {+ margin-bottom: 0;++ &::before {+ bottom: auto;+ height: 16px; // stops at the branch level+ }}}-.intermediate-steps-collapsed {- display: flex;- flex-direction: column;- font-size: 13px;- width: 100%;- border-radius: 6px;- background-color: var(--td-bg-color-container);- border: 1px solid var(--td-component-stroke);- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.06);- overflow: hidden;- box-sizing: border-box;- transition: all 0.2s ease;- margin-bottom: 16px;- position: relative;-- .intermediate-steps-header {- display: flex;- justify-content: space-between;- align-items: center;- padding: 8px 12px;- color: var(--td-text-color-primary);- font-weight: 500;- cursor: pointer;- background: linear-gradient(to right, rgba(7, 192, 95, 0.03), transparent);-- &:hover {- background: linear-gradient(to right, rgba(7, 192, 95, 0.05), rgba(7, 192, 95, 0.01));- }- }-- .intermediate-steps-title {- display: flex;- align-items: center;-- img {- width: 14px;- height: 14px;- margin-right: 7px;- }-- span {- white-space: nowrap;- font-size: 13px;-- :deep(strong) {- color: var(--td-brand-color);- font-weight: 600;- }- }- }-- .intermediate-steps-show-icon {- font-size: 13px;- padding: 0 2px 1px 2px;- color: var(--td-brand-color);- }+.tree-child-content {+ // child content area}-// Thinking Event-.thinking-event {- animation: fadeInUp 0.25s ease-out;- min-height: 20px;-- .thinking-phase {- background: var(--td-bg-color-container);- border-radius: 6px;- padding: 8px 12px;- border: 1px solid var(--td-component-stroke);- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);- transition: all 0.2s ease;-- &.thinking-last {- border-color: var(--td-brand-color);- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.06);-- // 最后一个 Thinking 作为最终答案时,字体应该更大- .thinking-content {- font-size: 14px;- }- }-- &.thinking-active {- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.06);- }- }-- .thinking-content {- font-size: 13px;- color: var(--td-text-color-primary);- line-height: 1.6;-- &.markdown-content {- :deep(p) {- margin: 0 0;- line-height: 1.6;- }-- :deep(code) {- background: var(--td-bg-color-secondarycontainer);- padding: 2px 5px;- border-radius: 3px;- font-family: 'Monaco', 'Menlo', 'Courier New', monospace;- font-size: 11px;- }-- :deep(pre) {- background: var(--td-bg-color-secondarycontainer);- padding: 10px;- border-radius: 4px;- overflow-x: auto;- margin: 6px 0;-- code {- background: none;- padding: 0;- }- }-- :deep(ul), :deep(ol) {- margin: 6px 0;- padding-left: 20px;- }-- :deep(li) {- margin: 3px 0;- }-- :deep(blockquote) {- border-left: 2px solid var(--td-brand-color);- padding-left: 10px;- margin: 6px 0;- color: var(--td-text-color-secondary);- }-- :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {- margin: 10px 0 6px 0;- font-weight: 600;- color: var(--td-text-color-primary);- }-- :deep(a) {- color: var(--td-brand-color);- text-decoration: none;-- &:hover {- text-decoration: underline;- }- }-- :deep(table) {- border-collapse: collapse;- margin: 6px 0;- font-size: 11px;-- th, td {- border: 1px solid var(--td-component-stroke);- padding: 5px 8px;- }-- th {- background: var(--td-bg-color-secondarycontainer);- font-weight: 600;- }- }-- :deep(img) {- max-width: 80%;- max-height: 300px;- width: auto;- height: auto;- min-height: 100px; /* 防止流式输出时图片高度塌陷导致抖动 */- border-radius: 8px;- display: block;- margin: 8px 0;- border: 0.5px solid var(--td-component-stroke);- object-fit: contain;- cursor: pointer;- transition: transform 0.2s ease;- background-color: var(--td-bg-color-secondarycontainer); /* 加载时的占位背景色 */-- &:hover {- }- }- }- }+// Thinking detail content (inside action-details)+.thinking-detail-content {+ padding: 2px 12px;+ font-size: 13px;+ color: var(--td-text-color-primary);+ line-height: 1.6;+ max-height: 200px;+ overflow-y: auto;}-// Answer Event - 类似 thinking 但有独特样式+// Answer Event - 无边框,直接显示内容.answer-event {animation: fadeInUp 0.25s ease-out;min-height: 20px;@@ -2037,25 +1966,8 @@ const handleAddToKnowledge = (answerEvent: any) => {}}- .answer-content-wrapper {- background: var(--td-bg-color-container);- border-radius: 6px;- padding: 8px 12px;- border: 1px solid var(--td-brand-color);- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.06);- transition: all 0.2s ease;-- &.answer-active {- background: linear-gradient(to right, rgba(7, 192, 95, 0.02), var(--td-bg-color-container));- }-- &.answer-done {- border-color: var(--td-brand-color);- }- }-.answer-content {- font-size: 13px;+ font-size: 15px;color: var(--td-text-color-primary);line-height: 1.6;@@ -2159,7 +2071,6 @@ const handleAddToKnowledge = (answerEvent: any) => {background-color: var(--td-bg-color-secondarycontainer); /* 加载时的占位背景色 */&:hover {- transform: scale(1.02);}}@@ -2191,12 +2102,12 @@ const handleAddToKnowledge = (answerEvent: any) => {.action-card {background: var(--td-bg-color-container);- border-radius: 6px;+ border-radius: 5px;border: 1px solid var(--td-component-stroke);overflow: hidden;position: relative;transition: all 0.2s ease;- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);> * {position: relative;@@ -2284,7 +2195,7 @@ const handleAddToKnowledge = (answerEvent: any) => {display: flex;justify-content: space-between;align-items: center;- padding: 8px 12px;+ padding: 5px 10px;color: var(--td-text-color-primary);font-weight: 500;cursor: pointer;@@ -2294,10 +2205,10 @@ const handleAddToKnowledge = (answerEvent: any) => {&:hover {background-color: rgba(7, 192, 95, 0.03);}-+&.no-results {cursor: default;-+&:hover {background-color: transparent;}@@ -2333,7 +2244,30 @@ const handleAddToKnowledge = (answerEvent: any) => {.action-name {white-space: nowrap;- font-size: 13px;+ font-size: 12px;+ }++ .action-badge {+ display: inline-flex;+ align-items: center;+ padding: 0 6px;+ height: 18px;+ border-radius: 9px;+ background: rgba(7, 192, 95, 0.10);+ color: var(--td-brand-color);+ font-size: 11px;+ font-weight: 500;+ white-space: nowrap;+ flex-shrink: 0;+ }++ .action-summary {+ color: var(--td-text-color-placeholder);+ font-size: 12px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ flex-shrink: 1;}}@@ -2371,21 +2305,6 @@ const handleAddToKnowledge = (answerEvent: any) => {}}-@keyframes pulseNode {- 0%, 100% {- border-color: var(--td-brand-color);- background: rgba(7, 192, 95, 0.15);- box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);- transform: scale(1);- }- 50% {- border-color: var(--td-brand-color);- background: rgba(7, 192, 95, 0.25);- box-shadow: 0 0 0 3px rgba(7, 192, 95, 0.15);- transform: scale(1.05);- }-}-// Loading 动画关键帧@keyframes dotBounce {0%, 80%, 100% {@@ -2484,9 +2403,9 @@ const handleAddToKnowledge = (answerEvent: any) => {}.action-show-icon {- font-size: 13px;- padding: 0 2px 1px 2px;- color: var(--td-brand-color);+ font-size: 12px;+ padding: 0 2px;+ color: var(--td-text-color-placeholder);}.action-details {@@ -2503,7 +2422,7 @@ const handleAddToKnowledge = (answerEvent: any) => {.search-results-summary-fixed {padding: 6px 10px;- background: var(--td-bg-color-secondarycontainer);+ background: var(--td-bg-color-container);border-top: 1px solid var(--td-component-stroke);.results-summary-text {@@ -2521,7 +2440,7 @@ const handleAddToKnowledge = (answerEvent: any) => {.plan-status-summary-fixed {padding: 6px 10px;- background: var(--td-bg-color-secondarycontainer);+ background: var(--td-bg-color-container);border-top: 1px solid var(--td-component-stroke);.plan-status-text {@@ -2658,107 +2577,6 @@ const handleAddToKnowledge = (answerEvent: any) => {}}-.thinking-thought-content {- padding: 6px 10px;-- .thinking-thought-markdown {- font-size: 13px;- color: var(--td-text-color-primary);- line-height: 1.6;-- :deep(p) {- margin: 5px 0;- line-height: 1.6;- font-size: 13px;- color: var(--td-text-color-primary);-- &:first-child {- margin-top: 0;- }-- &:last-child {- margin-bottom: 0;- }- }-- :deep(code) {- background: var(--td-bg-color-secondarycontainer);- padding: 2px 5px;- border-radius: 3px;- font-family: 'Monaco', 'Menlo', 'Courier New', monospace;- font-size: 11px;- color: var(--td-text-color-primary);- }-- :deep(pre) {- background: var(--td-bg-color-secondarycontainer);- padding: 8px;- border-radius: 4px;- overflow-x: auto;- margin: 5px 0;-- code {- background: none;- padding: 0;- }- }-- :deep(ul), :deep(ol) {- margin: 6px 0;- padding-left: 24px;- }-- :deep(li) {- margin: 2px 0;- line-height: 1.6;- }-- :deep(blockquote) {- border-left: 3px solid var(--td-brand-color);- margin: 6px 0;- color: var(--td-text-color-secondary);- background: rgba(7, 192, 95, 0.05);- padding: 6px 12px;- border-radius: 4px;- }-- :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {- margin: 8px 0 4px 0;- font-weight: 600;- color: var(--td-text-color-primary);-- &:first-child {- margin-top: 0;- }- }-- :deep(a) {- color: var(--td-brand-color);- text-decoration: none;-- &:hover {- text-decoration: underline;- }- }-- :deep(table) {- border-collapse: collapse;- margin: 6px 0;- font-size: 12px;-- th, td {- border: 1px solid var(--td-component-stroke);- padding: 6px 10px;- }-- th {- background: var(--td-bg-color-secondarycontainer);- font-weight: 600;- }- }- }-}-/* Global citation styles fallback to ensure rendering in any container */:deep(.citation) {display: inline-flex;@@ -2951,14 +2769,10 @@ const handleAddToKnowledge = (answerEvent: any) => {align-items: center;padding: 12px 0;margin-top: 0;- padding-left: 28px;+ padding-left: 0;position: relative;animation: fadeInUp 0.3s ease-out;- &.no-timeline {- padding-left: 0;- }-// 方案1: 三个跳动的圆点.loading-dots {display: flex;@@ -3065,7 +2879,7 @@ const handleAddToKnowledge = (answerEvent: any) => {<style lang="less">// Dark mode: invert agent icon (uses currentColor which doesn't work in <img>)-html[theme-mode="dark"] .intermediate-steps-title img {+html[theme-mode="dark"] .tree-root-title img {filter: invert(1);opacity: 0.55;}diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex 497959826..c77621cff 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -156,12 +156,15 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {// Reconstruct agentEventStream from agent_steps stored in database// This allows the frontend to restore the exact conversation state including all agent reasoning steps-const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted = false, isFallback = false) => {+const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted = false, isFallback = false, agentDurationMs = 0) => {const events = [];// Process agent steps if they existif (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) {agentSteps.forEach((step) => {+ // Compute step timestamp (milliseconds) from step.timestamp if available+ const stepTimestamp = step.timestamp ? new Date(step.timestamp).getTime() : 0;+// Add thinking event if thought content existsif (step.thought && step.thought.trim()) {events.push({@@ -170,14 +173,16 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompletedcontent: step.thought,done: true,thinking: false,+ timestamp: stepTimestamp || undefined,// Extract duration from step if availableduration_ms: step.duration || undefined,});}-- // Add tool call and result events++ // Add tool call and result events (skip final_answer as its content is in the answer event)if (step.tool_calls && Array.isArray(step.tool_calls)) {step.tool_calls.forEach((toolCall) => {+ if (toolCall.name === 'final_answer') return; // Skip - shown as answer eventevents.push({type: 'tool_call',tool_call_id: toolCall.id,@@ -187,6 +192,7 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompletedsuccess: toolCall.result?.success !== false,output: toolCall.result?.output || '',error: toolCall.result?.error || undefined,+ timestamp: stepTimestamp || undefined,// Use both duration and duration_ms for compatibilityduration: toolCall.duration,duration_ms: toolCall.duration,@@ -198,6 +204,14 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted});}+ // Add agent_complete event with duration info (before answer event)+ if (agentDurationMs > 0) {+ events.push({+ type: 'agent_complete',+ total_duration_ms: agentDurationMs,+ });+ }+// 总是添加 answer 事件如果有内容(无论是否有 agent_steps)// 这样可以确保最终答案始终被渲染if (messageContent && messageContent.trim()) {@@ -236,7 +250,7 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) {console.log('[Message Load] Reconstructing agent steps for message:', item.id, 'steps:', item.agent_steps.length);item.isAgentMode = true;- item.agentEventStream = reconstructEventStreamFromSteps(item.agent_steps, item.content, item.is_completed, item.is_fallback);+ item.agentEventStream = reconstructEventStreamFromSteps(item.agent_steps, item.content, item.is_completed, item.is_fallback, item.agent_duration_ms || 0);// 隐藏最终答案内容,因为它已经包含在 agentEventStream 的 answer 事件中item.hideContent = true;console.log('[Message Load] Reconstructed', item.agentEventStream.length, 'events from agent steps');@@ -652,6 +666,10 @@ const handleAgentChunk = (data) => {break;case 'tool_call':+ // Skip final_answer tool call from event stream - its content appears as answer events+ if (data.data && data.data.tool_name === 'final_answer') {+ break;+ }// Store or update pending tool call to pair with result laterif (data.data && (data.data.tool_name || data.data.tool_call_id)) {const incomingToolName = data.data.tool_name;@@ -851,7 +869,14 @@ const handleAgentChunk = (data) => {console.log('[Agent] Complete event received');loading.value = false;isReplying.value = false;- // 不清空 message.content,保持已有内容+ // 将 total_duration_ms 存入事件流供 AgentStreamDisplay 使用+ if (data.data?.total_duration_ms && message.agentEventStream) {+ message.agentEventStream.push({+ type: 'agent_complete',+ total_duration_ms: data.data.total_duration_ms,+ total_steps: data.data.total_steps,+ });+ }break;case 'stop':diff --git a/internal/agent/engine.go b/internal/agent/engine.goindex f376a4b2d..86965e125 100644--- a/internal/agent/engine.go+++ b/internal/agent/engine.go@@ -8,7 +8,7 @@ import ("time""github.com/Tencent/WeKnora/internal/agent/skills"- "github.com/Tencent/WeKnora/internal/agent/tools"+ agenttools "github.com/Tencent/WeKnora/internal/agent/tools""github.com/Tencent/WeKnora/internal/common""github.com/Tencent/WeKnora/internal/event""github.com/Tencent/WeKnora/internal/logger"@@ -26,7 +26,7 @@ func generateEventID(suffix string) string {// AgentEngine is the core engine for running ReAct agentstype AgentEngine struct {config *types.AgentConfig- toolRegistry *tools.ToolRegistry+ toolRegistry *agenttools.ToolRegistrychatModel chat.ChateventBus *event.EventBusknowledgeBasesInfo []*KnowledgeBaseInfo // Detailed knowledge base information for prompt@@ -50,7 +50,7 @@ func listToolNames(ts []chat.Tool) []string {func NewAgentEngine(config *types.AgentConfig,chatModel chat.Chat,- toolRegistry *tools.ToolRegistry,+ toolRegistry *agenttools.ToolRegistry,eventBus *event.EventBus,knowledgeBasesInfo []*KnowledgeBaseInfo,selectedDocs []*SelectedDocumentInfo,@@ -78,7 +78,7 @@ func NewAgentEngine(func NewAgentEngineWithSkills(config *types.AgentConfig,chatModel chat.Chat,- toolRegistry *tools.ToolRegistry,+ toolRegistry *agenttools.ToolRegistry,eventBus *event.EventBus,knowledgeBasesInfo []*KnowledgeBaseInfo,selectedDocs []*SelectedDocumentInfo,@@ -237,7 +237,27 @@ func (e *AgentEngine) executeLoop(})// 1. Think: Call LLM with function calling and stream thinking through EventBus- logger.Infof(ctx, "[Agent][Round-%d] Calling LLM with %d tools available...", state.CurrentRound+1, len(tools))+ logger.Infof(ctx, "[Agent][Round-%d] Calling LLM with %d messages, %d tools", state.CurrentRound+1, len(messages), len(tools))+ for i, msg := range messages {+ contentPreview := msg.Content+ if len(contentPreview) > 200 {+ contentPreview = contentPreview[:200] + "..."+ }+ if msg.Role == "tool" {+ logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=tool, name=%s, tool_call_id=%s, content_len=%d",+ state.CurrentRound+1, i, msg.Name, msg.ToolCallID, len(msg.Content))+ } else if len(msg.ToolCalls) > 0 {+ tcNames := make([]string, len(msg.ToolCalls))+ for j, tc := range msg.ToolCalls {+ tcNames[j] = tc.Function.Name+ }+ logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=%s, content_len=%d, tool_calls=%v",+ state.CurrentRound+1, i, msg.Role, len(msg.Content), tcNames)+ } else {+ logger.Infof(ctx, "[Agent][Round-%d] messages[%d]: role=%s, content_len=%d, content=%s",+ state.CurrentRound+1, i, msg.Role, len(msg.Content), contentPreview)+ }+ }common.PipelineInfo(ctx, "Agent", "think_start", map[string]interface{}{"iteration": state.CurrentRound,"round": state.CurrentRound + 1,@@ -260,17 +280,15 @@ func (e *AgentEngine) executeLoop("content_len": len(response.Content),})- // Debug: log finish reason and tool call count from LLM- logger.Infof(ctx, "[Agent][Round-%d] LLM response received: finish_reason=%s, tool_calls=%d, content_length=%d",- state.CurrentRound+1, response.FinishReason, len(response.ToolCalls), len(response.Content))- logger.Debugf(- ctx,- "[Agent] LLM response finish=%s, toolCalls=%d",- response.FinishReason,- len(response.ToolCalls),- )+ // Log LLM response summary+ logger.Infof(ctx, "[Agent][Round-%d] LLM response: finish_reason=%s, content_len=%d, tool_calls=%d",+ state.CurrentRound+1, response.FinishReason, len(response.Content), len(response.ToolCalls))if response.Content != "" {- logger.Debugf(ctx, "[Agent][Round-%d] LLM thought content:\n%s", state.CurrentRound+1, response.Content)+ logger.Infof(ctx, "[Agent][Round-%d] LLM content:\n%s", state.CurrentRound+1, response.Content)+ }+ for i, tc := range response.ToolCalls {+ logger.Infof(ctx, "[Agent][Round-%d] tool_call[%d]: %s(%s)",+ state.CurrentRound+1, i, tc.Function.Name, tc.Function.Arguments)}// Create agent step@@ -313,7 +331,53 @@ func (e *AgentEngine) executeLoop(break}- // 3. Act: Execute tool calls if any+ // 3. Check for final_answer tool call - if present, agent is done+ hasFinalAnswer := false+ if len(response.ToolCalls) > 0 {+ for _, tc := range response.ToolCalls {+ if tc.Function.Name == agenttools.ToolFinalAnswer {+ var faArgs struct {+ Answer string `json:"answer"`+ }+ if err := json.Unmarshal([]byte(tc.Function.Arguments), &faArgs); err != nil {+ logger.Warnf(ctx, "[Agent][Round-%d] Failed to parse final_answer args: %v", state.CurrentRound+1, err)+ } else {+ logger.Infof(ctx, "[Agent][Round-%d] final_answer tool called, answer length: %d",+ state.CurrentRound+1, len(faArgs.Answer))+ state.FinalAnswer = faArgs.Answer+ state.IsComplete = true+ hasFinalAnswer = true++ // Emit answer done marker (content was already streamed via processToolCallsDelta)+ e.eventBus.Emit(ctx, event.Event{+ ID: generateEventID("answer-done"),+ Type: event.EventAgentFinalAnswer,+ SessionID: sessionID,+ Data: event.AgentFinalAnswerData{+ Content: "",+ Done: true,+ },+ })++ common.PipelineInfo(ctx, "Agent", "final_answer_tool", map[string]interface{}{+ "iteration": state.CurrentRound,+ "round": state.CurrentRound + 1,+ "answer_len": len(faArgs.Answer),+ })+ }+ break+ }+ }+ }++ if hasFinalAnswer {+ state.RoundSteps = append(state.RoundSteps, step)+ logger.Infof(ctx, "[Agent][Round-%d] Duration: %dms (final_answer tool)",+ state.CurrentRound+1, time.Since(roundStart).Milliseconds())+ break+ }++ // 4. Act: Execute tool calls if anyif len(response.ToolCalls) > 0 {logger.Infof(ctx,@@ -664,7 +728,12 @@ func (e *AgentEngine) streamLLMToEventBus(chunkCount++if chunk.Content != "" {- fullContent += chunk.Content+ // Only accumulate LLM's own text output, not content extracted from tool arguments+ // (e.g. final_answer's answer or thinking tool's thought are streamed separately)+ isExtracted := chunk.Data != nil && chunk.Data["source"] != nil+ if !isExtracted {+ fullContent += chunk.Content+ }}// Collect tool calls if present@@ -754,9 +823,12 @@ func (e *AgentEngine) streamThinkingToEventBus(logger.Debug(context.Background(), "[Agent] streamLLM opts tool_choice=auto temperature=", e.config.Temperature)pendingToolCalls := make(map[string]bool)+ thinkingToolIDs := make(map[string]string) // tool_call_id -> event ID for thinking tool streams// Generate a single ID for this entire thinking streamthinkingID := generateEventID("thinking")+ // Generate a single ID for final_answer streaming (if applicable)+ answerID := generateEventID("answer")logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] ThinkingID: %s", iteration+1, thinkingID)fullContent, toolCalls, err := e.streamLLMToEventBus(@@ -783,6 +855,45 @@ func (e *AgentEngine) streamThinkingToEventBus(}}+ // Handle final_answer tool's streaming answer content+ if chunk.ResponseType == types.ResponseTypeAnswer {+ if source, _ := chunk.Data["source"].(string); source == "final_answer_tool" {+ e.eventBus.Emit(ctx, event.Event{+ ID: answerID,+ Type: event.EventAgentFinalAnswer,+ SessionID: sessionID,+ Data: event.AgentFinalAnswerData{+ Content: chunk.Content,+ Done: false,+ },+ })+ return+ }+ }++ // Handle thinking tool's streaming thought content+ if chunk.ResponseType == types.ResponseTypeThinking && chunk.Data != nil {+ if source, _ := chunk.Data["source"].(string); source == "thinking_tool" {+ toolCallID, _ := chunk.Data["tool_call_id"].(string)+ eventID, exists := thinkingToolIDs[toolCallID]+ if !exists {+ eventID = generateEventID("thinking-tool")+ thinkingToolIDs[toolCallID] = eventID+ }+ e.eventBus.Emit(ctx, event.Event{+ ID: eventID,+ Type: event.EventAgentThought,+ SessionID: sessionID,+ Data: event.AgentThoughtData{+ Content: chunk.Content,+ Iteration: iteration,+ Done: false,+ },+ })+ return+ }+ }+if chunk.Content != "" {// logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] Emitting thought chunk: %d chars",// iteration+1, len(chunk.Content))diff --git a/internal/agent/prompts.go b/internal/agent/prompts.goindex 8ba76fb11..b57c28337 100644--- a/internal/agent/prompts.go+++ b/internal/agent/prompts.go@@ -403,12 +403,13 @@ To help users solve problems by planning, thinking, and using available tools (l1. **Analyze:** Understand the user's request.2. **Plan:** If the task is complex, use todo_write to create a plan.3. **Execute:** Use available tools to gather information or perform actions.-4. **Synthesize:** Provide a comprehensive answer.+4. **Synthesize:** Call the final_answer tool with your comprehensive answer. You MUST always end by calling final_answer.### Tool Guidelines* **web_search / web_fetch:** Use these if enabled to find information from the internet.* **todo_write:** Use for managing multi-step tasks.* **thinking:** Use to plan and reflect.+* **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it.### System StatusCurrent Time: {{current_time}}@@ -460,7 +461,7 @@ If in **Path B**, execute tasks in todo_write sequentially. For **EACH** task:Only when ALL todo_write tasks are "completed":* Synthesize findings from the full text of all retrieved chunks.* Check for consistency.-* Generate the final response.+* Call the **final_answer** tool with your complete, well-formatted response. You MUST always end by calling final_answer.### Core Retrieval Strategy (Strict Sequence)For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:@@ -478,6 +479,7 @@ For every retrieval attempt (Phase 1 or Phase 3), follow this exact chain:* **web_search / web_fetch:** Use these ONLY when Web Search is Enabled and KB retrieval is insufficient.* **todo_write:** Your "Manager". Tracks multi-step research.* **think:** Your "Conscience". Use to plan and reflect the content returned by list_knowledge_chunks.+* **final_answer:** MANDATORY as your final action. Always submit your complete answer through this tool. NEVER end your turn without calling it.### Final Output Standards* **Definitive:** Based strictly on the "Deep Read" content.diff --git a/internal/agent/tools/definitions.go b/internal/agent/tools/definitions.goindex 80cad752c..2acc180c0 100644--- a/internal/agent/tools/definitions.go+++ b/internal/agent/tools/definitions.go@@ -18,6 +18,7 @@ const (ToolDataSchema = "data_schema"ToolWebSearch = "web_search"ToolWebFetch = "web_fetch"+ ToolFinalAnswer = "final_answer"// Skills-related tools (only available when skills are enabled)ToolExecuteSkillScript = "execute_skill_script"ToolReadSkill = "read_skill"@@ -46,6 +47,7 @@ func AvailableToolDefinitions() []AvailableTool {{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息"},{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},+ {Name: ToolFinalAnswer, Label: "提交最终回答", Description: "提交最终回答给用户"},}}@@ -62,5 +64,6 @@ func DefaultAllowedTools() []string {ToolDatabaseQuery,ToolDataAnalysis,ToolDataSchema,+ ToolFinalAnswer,}}diff --git a/internal/agent/tools/final_answer.go b/internal/agent/tools/final_answer.gonew file mode 100644index 000000000..1d83e01aa--- /dev/null+++ b/internal/agent/tools/final_answer.go@@ -0,0 +1,87 @@+package tools++import (+ "context"+ "encoding/json"+ "fmt"++ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+)++var finalAnswerTool = BaseTool{+ name: ToolFinalAnswer,+ description: `Submit your final answer to the user's question.++## When to Use This Tool++You MUST call this tool as your LAST action when you are ready to deliver your final response to the user.+After gathering all necessary information through other tools (search, retrieval, analysis, etc.),+synthesize your findings and submit the complete answer through this tool.++## Important Rules++1. NEVER end your turn without calling this tool+2. The answer parameter must contain your complete, well-formatted response+3. Include all citations, structure, and formatting in the answer+4. This should always be the last tool you call++## Parameters++- **answer**: Your complete final answer in Markdown format, including all citations and formatting`,+ schema: json.RawMessage(`{+ "type": "object",+ "properties": {+ "answer": {+ "type": "string",+ "description": "Your complete final answer in Markdown format. Include all citations, structure, images, and formatting."+ }+ },+ "required": ["answer"]+}`),+}++// FinalAnswerInput defines the input parameters for the final answer tool+type FinalAnswerInput struct {+ Answer string `json:"answer"`+}++// FinalAnswerTool submits the agent's final answer to the user+type FinalAnswerTool struct {+ BaseTool+}++// NewFinalAnswerTool creates a new final answer tool instance+func NewFinalAnswerTool() *FinalAnswerTool {+ return &FinalAnswerTool{+ BaseTool: finalAnswerTool,+ }+}++// Execute executes the final answer tool+func (t *FinalAnswerTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {+ logger.Infof(ctx, "[Tool][FinalAnswer] Execute started")++ var input FinalAnswerInput+ if err := json.Unmarshal(args, &input); err != nil {+ logger.Errorf(ctx, "[Tool][FinalAnswer] Failed to parse args: %v", err)+ return &types.ToolResult{+ Success: false,+ Error: fmt.Sprintf("Failed to parse args: %v", err),+ }, err+ }++ if input.Answer == "" {+ return &types.ToolResult{+ Success: false,+ Error: "answer must be a non-empty string",+ }, fmt.Errorf("answer must be a non-empty string")+ }++ logger.Infof(ctx, "[Tool][FinalAnswer] Answer length: %d characters", len(input.Answer))++ return &types.ToolResult{+ Success: true,+ Output: input.Answer,+ }, nil+}diff --git a/internal/agent/tools/sequentialthinking.go b/internal/agent/tools/sequentialthinking.goindex e2008a8e7..be4c7289f 100644--- a/internal/agent/tools/sequentialthinking.go+++ b/internal/agent/tools/sequentialthinking.go@@ -37,7 +37,7 @@ Each thought can build on, question, or revise previous insights as understandin- Generates a solution hypothesis- Verifies the hypothesis based on the Chain of Thought steps- Repeats the process until satisfied-- Provides a correct answer+- When thinking is complete, you can call the final_answer tool to deliver your answer if all your thinking is complete. NEVER include the final answer directly in a thought.## Parameters Explained@@ -78,8 +78,8 @@ Each thought can build on, question, or revise previous insights as understandin7. Generate a solution hypothesis when appropriate8. Verify the hypothesis based on the Chain of Thought steps9. Repeat the process until satisfied with the solution-10. Provide a single, ideally correct answer as the final output-11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`,+10. Only set next_thought_needed to false when truly done and a satisfactory answer is reached+11. NEVER include the final answer in the thought content. When thinking is complete, you can call the final_answer tool to deliver the final answer to the user`,schema: json.RawMessage(`{"type": "object","properties": {diff --git a/internal/application/service/agent_service.go b/internal/application/service/agent_service.goindex f7f50c288..da3f7a6ba 100644--- a/internal/application/service/agent_service.go+++ b/internal/application/service/agent_service.go@@ -347,8 +347,9 @@ func (s *agentService) registerTools(allowedTools = append(allowedTools, tools.ToolWebSearch)allowedTools = append(allowedTools, tools.ToolWebFetch)}- logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)+ logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)+ allowedTools = append(allowedTools, tools.ToolFinalAnswer)// Register each allowed toolfor _, toolName := range allowedTools {var toolToRegister types.Tool@@ -402,6 +403,9 @@ func (s *agentService) registerTools(toolToRegister = tools.NewDataSchemaTool(s.knowledgeService, s.chunkService.GetRepository())logger.Infof(ctx, "Registered data_schema tool")+ case tools.ToolFinalAnswer:+ toolToRegister = tools.NewFinalAnswerTool()+ logger.Infof(ctx, "Registered final_answer tool")default:logger.Warnf(ctx, "Unknown tool: %s", toolName)}diff --git a/internal/handler/session/agent_stream_handler.go b/internal/handler/session/agent_stream_handler.goindex 399ca4abd..db1a3e557 100644--- a/internal/handler/session/agent_stream_handler.go+++ b/internal/handler/session/agent_stream_handler.go@@ -422,6 +422,7 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Eventif data.MessageID == h.assistantMessageID {// h.assistantMessage.Content = data.FinalAnswerh.assistantMessage.IsCompleted = true+ h.assistantMessage.AgentDurationMs = data.TotalDurationMs// Update knowledge references if providedif len(data.KnowledgeRefs) > 0 {@@ -434,6 +435,8 @@ func (h *AgentStreamHandler) handleComplete(ctx context.Context, evt event.Eventh.assistantMessage.KnowledgeReferences = knowledgeRefs}+ h.assistantMessage.Content += data.FinalAnswer+// Update agent steps if providedif data.AgentSteps != nil {if steps, ok := data.AgentSteps.([]types.AgentStep); ok {diff --git a/internal/models/chat/json_field_extractor.go b/internal/models/chat/json_field_extractor.gonew file mode 100644index 000000000..f0bfa4ebb--- /dev/null+++ b/internal/models/chat/json_field_extractor.go@@ -0,0 +1,224 @@+package chat++import (+ "strings"+ "unicode/utf8"+)++// jsonFieldExtractor extracts a specific string field value from streaming JSON fragments.+// It processes incremental JSON argument chunks from LLM tool calls.+//+// Example: for fieldName="answer", expected JSON format: {"answer":"...content..."}+// The extractor uses a simple state machine to skip the JSON prefix and extract the string value.+type jsonFieldExtractor struct {+ fieldName string // the JSON field name to extract (e.g. "answer", "thought")+ buffer string // accumulated full arguments string+ valueStart int // byte offset where the field value starts (-1 if not found yet)+ lastEmit int // byte offset of the last emitted position within the value+ done bool // whether we've seen the closing quote+}++// newJSONFieldExtractor creates a new extractor instance for the given field name+func newJSONFieldExtractor(fieldName string) *jsonFieldExtractor {+ return &jsonFieldExtractor{+ fieldName: fieldName,+ valueStart: -1,+ lastEmit: 0,+ }+}++// Feed processes a new argument delta and returns any new content to emit.+// Returns empty string if no new content is available yet.+func (e *jsonFieldExtractor) Feed(argsDelta string) string {+ if e.done {+ return ""+ }++ e.buffer += argsDelta++ // If we haven't found the value start yet, try to find it+ if e.valueStart < 0 {+ idx := findFieldValueStart(e.buffer, e.fieldName)+ if idx < 0 {+ return "" // Haven't seen the value start yet+ }+ e.valueStart = idx+ e.lastEmit = 0+ }++ // Extract new content from the value portion+ valueContent := e.buffer[e.valueStart:]++ // Find how far we can safely emit (stop before potential incomplete escape at the end)+ safeEnd, finished := findSafeEnd(valueContent, e.lastEmit)++ if safeEnd <= e.lastEmit {+ if finished {+ e.done = true+ }+ return ""+ }++ // Extract the new chunk and unescape JSON string escapes+ rawChunk := valueContent[e.lastEmit:safeEnd]+ unescaped := unescapeJSONString(rawChunk)++ e.lastEmit = safeEnd+ if finished {+ e.done = true+ }++ return unescaped+}++// IsDone returns whether the extractor has finished (closing quote found)+func (e *jsonFieldExtractor) IsDone() bool {+ return e.done+}++// findFieldValueStart finds the byte offset where the field's string value content begins+// (after the opening quote of the value). Returns -1 if not found.+func findFieldValueStart(buf string, fieldName string) int {+ // Look for "fieldName" key followed by colon and opening quote+ key := `"` + fieldName + `"`+ idx := strings.Index(buf, key)+ if idx < 0 {+ return -1+ }++ // Skip past the key+ pos := idx + len(key)++ // Skip whitespace and colon+ for pos < len(buf) {+ ch := buf[pos]+ if ch == ':' {+ pos+++ continue+ }+ if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {+ pos+++ continue+ }+ if ch == '"' {+ // Found the opening quote of the value+ return pos + 1+ }+ // Unexpected character+ return -1+ }++ return -1 // Haven't seen the opening quote yet+}++// findSafeEnd finds the safe end position for emission within the value content.+// It scans from lastEmit forward, handling escape sequences.+// Returns (safeEnd, finished) where finished=true if the closing quote was found.+func findSafeEnd(value string, from int) (int, bool) {+ i := from+ for i < len(value) {+ ch := value[i]+ if ch == '\\' {+ // Escape sequence - need at least 2 bytes+ if i+1 >= len(value) {+ // Incomplete escape at end, stop before it+ return i, false+ }+ nextCh := value[i+1]+ if nextCh == 'u' {+ // Unicode escape \uXXXX - need 6 bytes total+ if i+5 >= len(value) {+ return i, false+ }+ i += 6+ } else {+ // Simple escape: \", \\, \n, \t, \r, \/, \b, \f+ i += 2+ }+ } else if ch == '"' {+ // Closing quote of the JSON string value+ return i, true+ } else {+ // Regular character - handle multi-byte UTF-8+ _, size := utf8.DecodeRuneInString(value[i:])+ if size == 0 {+ size = 1+ }+ i += size+ }+ }+ return i, false+}++// unescapeJSONString converts JSON string escape sequences to their actual characters+func unescapeJSONString(s string) string {+ if !strings.ContainsRune(s, '\\') {+ return s+ }++ var b strings.Builder+ b.Grow(len(s))++ i := 0+ for i < len(s) {+ if s[i] == '\\' && i+1 < len(s) {+ switch s[i+1] {+ case '"':+ b.WriteByte('"')+ i += 2+ case '\\':+ b.WriteByte('\\')+ i += 2+ case '/':+ b.WriteByte('/')+ i += 2+ case 'n':+ b.WriteByte('\n')+ i += 2+ case 'r':+ b.WriteByte('\r')+ i += 2+ case 't':+ b.WriteByte('\t')+ i += 2+ case 'b':+ b.WriteByte('\b')+ i += 2+ case 'f':+ b.WriteByte('\f')+ i += 2+ case 'u':+ // Unicode escape \uXXXX+ if i+5 < len(s) {+ // Parse hex digits+ hexStr := s[i+2 : i+6]+ var codepoint int+ for _, h := range hexStr {+ codepoint <<= 4+ switch {+ case h >= '0' && h <= '9':+ codepoint += int(h - '0')+ case h >= 'a' && h <= 'f':+ codepoint += int(h-'a') + 10+ case h >= 'A' && h <= 'F':+ codepoint += int(h-'A') + 10+ }+ }+ b.WriteRune(rune(codepoint))+ i += 6+ } else {+ b.WriteByte(s[i])+ i+++ }+ default:+ b.WriteByte(s[i])+ i+++ }+ } else {+ b.WriteByte(s[i])+ i+++ }+ }++ return b.String()+}diff --git a/internal/models/chat/json_field_extractor_test.go b/internal/models/chat/json_field_extractor_test.gonew file mode 100644index 000000000..2b84df7ae--- /dev/null+++ b/internal/models/chat/json_field_extractor_test.go@@ -0,0 +1,165 @@+package chat++import (+ "testing"+)++func TestJSONFieldExtractor_Basic(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ // Simulate streaming JSON: {"answer":"Hello world"}+ got := ""+ got += e.Feed(`{"answer":"`)+ got += e.Feed(`Hello`)+ got += e.Feed(` world`)+ got += e.Feed(`"}`)++ if got != "Hello world" {+ t.Errorf("expected 'Hello world', got %q", got)+ }+ if !e.IsDone() {+ t.Error("expected extractor to be done")+ }+}++func TestJSONFieldExtractor_WithEscapes(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ // Simulate: {"answer":"line1\nline2 and \"quoted\""}+ got := ""+ got += e.Feed(`{"answer":"line1\nline2`)+ got += e.Feed(` and \"quoted`)+ got += e.Feed(`\""}`)++ expected := "line1\nline2 and \"quoted\""+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+}++func TestJSONFieldExtractor_OneChunk(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ got := e.Feed(`{"answer":"complete answer here"}`)++ if got != "complete answer here" {+ t.Errorf("expected 'complete answer here', got %q", got)+ }+ if !e.IsDone() {+ t.Error("expected extractor to be done")+ }+}++func TestJSONFieldExtractor_SmallChunks(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ // Very small chunks+ got := ""+ chunks := []string{`{`, `"`, `a`, `n`, `s`, `w`, `e`, `r`, `"`, `:`, `"`, `H`, `i`, `"`, `}`}+ for _, c := range chunks {+ got += e.Feed(c)+ }++ if got != "Hi" {+ t.Errorf("expected 'Hi', got %q", got)+ }+}++func TestJSONFieldExtractor_Markdown(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ got := ""+ got += e.Feed(`{"answer":"# Title\n\n`)+ got += e.Feed(`This is **bold** and `)+ got += e.Feed(`*italic* text.\n\n`)+ got += e.Feed(`- item 1\n- item 2`)+ got += e.Feed(`"}`)++ expected := "# Title\n\nThis is **bold** and *italic* text.\n\n- item 1\n- item 2"+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+}++func TestJSONFieldExtractor_UnicodeEscape(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ got := ""+ got += e.Feed(`{"answer":"Hello \u4e16\u754c`)+ got += e.Feed(`"}`)++ expected := "Hello 世界"+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+}++func TestJSONFieldExtractor_IncompleteEscapeAtBoundary(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ // Escape sequence split across chunks+ got := ""+ got += e.Feed(`{"answer":"before\`)+ got += e.Feed(`nafter"}`)++ expected := "before\nafter"+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+}++func TestJSONFieldExtractor_WhitespaceInJSON(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ // Whitespace around colon+ got := e.Feed(`{ "answer" : "content here" }`)++ if got != "content here" {+ t.Errorf("expected 'content here', got %q", got)+ }+}++func TestJSONFieldExtractor_EmptyAnswer(t *testing.T) {+ e := newJSONFieldExtractor("answer")++ got := e.Feed(`{"answer":""}`)++ if got != "" {+ t.Errorf("expected empty string, got %q", got)+ }+ if !e.IsDone() {+ t.Error("expected extractor to be done")+ }+}++// Test extracting "thought" field (for thinking tool)+func TestJSONFieldExtractor_ThoughtField(t *testing.T) {+ e := newJSONFieldExtractor("thought")++ got := ""+ got += e.Feed(`{"thought":"Let me analyze`)+ got += e.Feed(` the problem step by step`)+ got += e.Feed(`","next_thought_needed":true,"thought_number":1,"total_thoughts":3}`)++ expected := "Let me analyze the problem step by step"+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+ if !e.IsDone() {+ t.Error("expected extractor to be done")+ }+}++func TestJSONFieldExtractor_ThoughtFieldWithEscapes(t *testing.T) {+ e := newJSONFieldExtractor("thought")++ got := ""+ got += e.Feed(`{"thought":"Step 1:\n- Analyze the query\n- `)+ got += e.Feed(`Search for \"relevant\" info`)+ got += e.Feed(`","thought_number":1}`)++ expected := "Step 1:\n- Analyze the query\n- Search for \"relevant\" info"+ if got != expected {+ t.Errorf("expected %q, got %q", expected, got)+ }+}diff --git a/internal/models/chat/ollama.go b/internal/models/chat/ollama.goindex 17abde0d6..a7dbf1d7f 100644--- a/internal/models/chat/ollama.go+++ b/internal/models/chat/ollama.go@@ -197,6 +197,35 @@ func (c *OllamaChat) ChatStream(ToolCalls: c.toolCallTo(resp.Message.ToolCalls),Done: false,}++ // Extract and stream content from special tools (complete, not incremental)+ for _, tc := range resp.Message.ToolCalls {+ switch tc.Function.Name {+ case "final_answer":+ if answer, ok := tc.Function.Arguments["answer"].(string); ok && answer != "" {+ streamChan <- types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer,+ Content: answer,+ Done: false,+ Data: map[string]interface{}{+ "source": "final_answer_tool",+ },+ }+ }+ case "thinking":+ if thought, ok := tc.Function.Arguments["thought"].(string); ok && thought != "" {+ streamChan <- types.StreamResponse{+ ResponseType: types.ResponseTypeThinking,+ Content: thought,+ Done: false,+ Data: map[string]interface{}{+ "source": "thinking_tool",+ "tool_call_id": tooli2s(tc.Function.Index),+ },+ }+ }+ }+ }}if resp.Done {diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.goindex 1beb1a959..1900fd050 100644--- a/internal/models/chat/remote_api.go+++ b/internal/models/chat/remote_api.go@@ -334,7 +334,7 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, customReq anyreturn nil, fmt.Errorf("marshal request: %w", err)}- logger.Infof(ctx, "[LLM Stream] model=%s, raw HTTP request:\n%s", c.modelName, string(jsonData))+ logger.Infof(ctx, "[LLM Stream] model=%s", c.modelName)endpoint := c.baseURL + "/chat/completions"httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewBuffer(jsonData))@@ -456,6 +456,7 @@ type streamState struct {lastFunctionName map[int]stringnameNotified map[int]boolhasThinking bool+ fieldExtractors map[int]*jsonFieldExtractor // per tool-call-index extractors for streaming field extraction}func newStreamState() *streamState {@@ -464,6 +465,7 @@ func newStreamState() *streamState {lastFunctionName: make(map[int]string),nameNotified: make(map[int]bool),hasThinking: false,+ fieldExtractors: make(map[int]*jsonFieldExtractor),}}@@ -587,6 +589,47 @@ func (c *RemoteAPIChat) processToolCallsDelta(toolCalls []openai.ToolCall, state}state.lastFunctionName[toolCallIndex] = currName++ // Stream final_answer tool arguments as answer-type chunks+ if toolCallEntry.Function.Name == "final_answer" && argsUpdated {+ extractor, exists := state.fieldExtractors[toolCallIndex]+ if !exists {+ extractor = newJSONFieldExtractor("answer")+ state.fieldExtractors[toolCallIndex] = extractor+ }+ answerChunk := extractor.Feed(tc.Function.Arguments)+ if answerChunk != "" {+ streamChan <- types.StreamResponse{+ ResponseType: types.ResponseTypeAnswer,+ Content: answerChunk,+ Done: false,+ Data: map[string]interface{}{+ "source": "final_answer_tool",+ },+ }+ }+ }++ // Stream thinking tool's thought field as thinking-type chunks+ if toolCallEntry.Function.Name == "thinking" && argsUpdated {+ extractor, exists := state.fieldExtractors[toolCallIndex]+ if !exists {+ extractor = newJSONFieldExtractor("thought")+ state.fieldExtractors[toolCallIndex] = extractor+ }+ thoughtChunk := extractor.Feed(tc.Function.Arguments)+ if thoughtChunk != "" {+ streamChan <- types.StreamResponse{+ ResponseType: types.ResponseTypeThinking,+ Content: thoughtChunk,+ Done: false,+ Data: map[string]interface{}{+ "source": "thinking_tool",+ "tool_call_id": toolCallEntry.ID,+ },+ }+ }+ }}}diff --git a/internal/types/message.go b/internal/types/message.goindex c664afd9e..1db2e4b2b 100644--- a/internal/types/message.go+++ b/internal/types/message.go@@ -80,6 +80,8 @@ type Message struct {IsCompleted bool `json:"is_completed"`// Whether this response is a fallback (no knowledge base match found)IsFallback bool `json:"is_fallback,omitempty"`+ // Agent total execution duration in milliseconds (from query start to answer start)+ AgentDurationMs int64 `json:"agent_duration_ms,omitempty" gorm:"column:agent_duration_ms;default:0"`// Message creation timestampCreatedAt time.Time `json:"created_at"`// Last update timestampdiff --git a/migrations/versioned/000017_add_agent_duration_ms.down.sql b/migrations/versioned/000017_add_agent_duration_ms.down.sqlnew file mode 100644index 000000000..ea747ad81--- /dev/null+++ b/migrations/versioned/000017_add_agent_duration_ms.down.sql@@ -0,0 +1,2 @@+-- Remove agent_duration_ms column from messages table+ALTER TABLE messages DROP COLUMN IF EXISTS agent_duration_ms;diff --git a/migrations/versioned/000017_add_agent_duration_ms.up.sql b/migrations/versioned/000017_add_agent_duration_ms.up.sqlnew file mode 100644index 000000000..47478289c--- /dev/null+++ b/migrations/versioned/000017_add_agent_duration_ms.up.sql@@ -0,0 +1,3 @@+-- Add agent_duration_ms column to messages table+-- Stores the total agent execution duration in milliseconds (from query start to answer start)+ALTER TABLE messages ADD COLUMN IF NOT EXISTS agent_duration_ms BIGINT DEFAULT 0;