refactor(agent): remove final_answer tool references and update related logic
- Eliminated all instances of the final_answer tool from the agent's configuration and logic, transitioning to a model where the agent concludes responses with plain text instead. - Updated event handling and response analysis to reflect this change, ensuring that the agent's output is now directly delivered as text without relying on a dedicated final answer tool. - Adjusted localization strings across multiple languages to remove references to final_answer, enhancing clarity and consistency in user-facing messages. - Improved the overall structure of the agent's response handling to streamline the process and reduce potential confusion regarding tool usage. refactor(agent): streamline answer handling and preamble logic - Updated the agent's response handling to treat any text streamed before a tool call as a preamble, ensuring it is not included in the final answer. - Removed the superseded marker logic from the event emission process, simplifying the flow of answer content and enhancing clarity in the UI. - Adjusted the event handling to ensure that preamble segments are correctly retracted and relocated into the steps tree, improving the overall user experience. - Enhanced the agent's internal logic to better manage answer segments and their states during streaming, leading to a more coherent response structure.
This commit is contained in:
@@ -762,6 +762,10 @@ export default {
|
||||
toolFallback: 'Tool',
|
||||
stepsCompleted: 'Completed <strong>{steps}</strong> step(s)',
|
||||
stepsCompletedWithDuration: 'Completed <strong>{steps}</strong> step(s) in <strong>{duration}</strong>',
|
||||
reasoningRounds: '<strong>{rounds}</strong> reasoning round(s)',
|
||||
toolCalls: '<strong>{tools}</strong> tool call(s)',
|
||||
durationSuffix: '<strong>{duration}</strong>',
|
||||
stepSummarySeparator: ' · ',
|
||||
title: 'Agents',
|
||||
subtitle: 'Configure and manage your agents to customize conversation behavior and capabilities',
|
||||
createAgent: 'Create Agent',
|
||||
@@ -4525,7 +4529,6 @@ export default {
|
||||
thinking: 'Thinking',
|
||||
imageAnalysis: 'Image Analysis',
|
||||
queryKnowledgeGraph: 'Knowledge Graph Query',
|
||||
finalAnswer: 'Generate Answer',
|
||||
readSkill: 'Read Skill',
|
||||
executeSkillScript: 'Execute Skill Script',
|
||||
dataAnalysis: 'Data Analysis',
|
||||
@@ -4708,7 +4711,6 @@ export default {
|
||||
// Runtime system-injected tools (preview only)
|
||||
webSearch: 'Web Search',
|
||||
webFetch: 'Web Fetch',
|
||||
finalAnswer: 'Submit Final Answer',
|
||||
// Groups
|
||||
groupBase: 'Basic',
|
||||
groupRag: 'Knowledge Retrieval (RAG)',
|
||||
|
||||
@@ -1725,6 +1725,10 @@ export default {
|
||||
toolFallback: "도구",
|
||||
stepsCompleted: "<strong>{steps}</strong>개 단계 완료",
|
||||
stepsCompletedWithDuration: "<strong>{steps}</strong>개 단계 완료, 소요 시간 <strong>{duration}</strong>",
|
||||
reasoningRounds: "사고 <strong>{rounds}</strong>회",
|
||||
toolCalls: "도구 <strong>{tools}</strong>회 호출",
|
||||
durationSuffix: "소요 시간 <strong>{duration}</strong>",
|
||||
stepSummarySeparator: " · ",
|
||||
title: "에이전트",
|
||||
subtitle: "에이전트 구성 및 관리, 대화 동작 및 기능 맞춤화",
|
||||
createAgent: "에이전트 만들기",
|
||||
@@ -4580,7 +4584,6 @@ export default {
|
||||
thinking: '사고',
|
||||
imageAnalysis: '이미지 내용 분석',
|
||||
queryKnowledgeGraph: '지식 그래프 조회',
|
||||
finalAnswer: '답변 생성',
|
||||
readSkill: '스킬 읽기',
|
||||
executeSkillScript: '스킬 스크립트 실행',
|
||||
dataAnalysis: '데이터 분석',
|
||||
@@ -4817,7 +4820,6 @@ export default {
|
||||
// 런타임 주입 (미리보기용)
|
||||
webSearch: '웹 검색',
|
||||
webFetch: '웹 페이지 가져오기',
|
||||
finalAnswer: '최종 답변 제출',
|
||||
// 그룹
|
||||
groupBase: '기본',
|
||||
groupRag: '지식베이스 검색 (RAG)',
|
||||
|
||||
@@ -682,6 +682,10 @@ export default {
|
||||
toolFallback: 'Инструмент',
|
||||
stepsCompleted: 'Выполнено <strong>{steps}</strong> шаг(ов)',
|
||||
stepsCompletedWithDuration: 'Выполнено <strong>{steps}</strong> шаг(ов) за <strong>{duration}</strong>',
|
||||
reasoningRounds: '<strong>{rounds}</strong> раунд(ов) рассуждений',
|
||||
toolCalls: '<strong>{tools}</strong> вызов(ов) инструментов',
|
||||
durationSuffix: '<strong>{duration}</strong>',
|
||||
stepSummarySeparator: ' · ',
|
||||
editor: {
|
||||
skillsConfig: 'Skills',
|
||||
skillsConfigDesc: 'Настройка предустановленных Skills для агента, предоставляющих специализированные знания и рабочие процессы',
|
||||
@@ -4080,7 +4084,6 @@ export default {
|
||||
thinking: 'Размышление',
|
||||
imageAnalysis: 'Анализ изображения',
|
||||
queryKnowledgeGraph: 'Запрос графа знаний',
|
||||
finalAnswer: 'Генерация ответа',
|
||||
readSkill: 'Чтение навыка',
|
||||
executeSkillScript: 'Выполнение скрипта навыка',
|
||||
dataAnalysis: 'Анализ данных',
|
||||
@@ -4263,7 +4266,6 @@ export default {
|
||||
// Служебные (только предпросмотр)
|
||||
webSearch: 'Поиск в сети',
|
||||
webFetch: 'Загрузка веб-страницы',
|
||||
finalAnswer: 'Отправить окончательный ответ',
|
||||
// Группы
|
||||
groupBase: 'Базовые',
|
||||
groupRag: 'Поиск в базе знаний (RAG)',
|
||||
|
||||
@@ -1726,6 +1726,10 @@ export default {
|
||||
toolFallback: "工具",
|
||||
stepsCompleted: "已完成 <strong>{steps}</strong> 个步骤",
|
||||
stepsCompletedWithDuration: "已完成 <strong>{steps}</strong> 个步骤,耗时 <strong>{duration}</strong>",
|
||||
reasoningRounds: "思考 <strong>{rounds}</strong> 轮",
|
||||
toolCalls: "调用 <strong>{tools}</strong> 次工具",
|
||||
durationSuffix: "耗时 <strong>{duration}</strong>",
|
||||
stepSummarySeparator: " · ",
|
||||
title: "智能体",
|
||||
subtitle: "配置和管理您的智能体,自定义对话行为和能力",
|
||||
createAgent: "创建智能体",
|
||||
@@ -4519,7 +4523,6 @@ export default {
|
||||
thinking: "思考",
|
||||
imageAnalysis: "查看图片内容",
|
||||
queryKnowledgeGraph: "知识图谱查询",
|
||||
finalAnswer: "生成回答",
|
||||
readSkill: "读取技能",
|
||||
executeSkillScript: "执行技能脚本",
|
||||
dataAnalysis: "数据分析",
|
||||
@@ -4756,7 +4759,6 @@ export default {
|
||||
// 运行时系统注入(只读,用于预览)
|
||||
webSearch: "网络搜索",
|
||||
webFetch: "网页抓取",
|
||||
finalAnswer: "提交最终回答",
|
||||
// 分组
|
||||
groupBase: "基础",
|
||||
groupRag: "知识库检索(RAG)",
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
//
|
||||
// Helpers for normalising LLM-emitted final answers before rendering.
|
||||
//
|
||||
// Background: not every model reliably calls our `final_answer` tool. Many
|
||||
// models — especially smaller ones or those SFT'd on different conventions —
|
||||
// instead embed the answer inside <answer>…</answer>, <final_answer>…</final_answer>,
|
||||
// or prefix it with "Final Answer:" / "最终答案:". When the agent loop accepts
|
||||
// such a natural-stop response as the final answer, those wrappers leak into
|
||||
// the rendered output. This module provides a single helper to strip them
|
||||
// before the markdown renderer sees the text.
|
||||
// Background: the agent ends a turn by writing its answer as plain assistant
|
||||
// text. Many models — especially smaller ones or those SFT'd on different
|
||||
// conventions — wrap that answer inside <answer>…</answer>,
|
||||
// <final_answer>…</final_answer>, or prefix it with "Final Answer:" /
|
||||
// "最终答案:". When the agent loop accepts such a natural-stop response as the
|
||||
// final answer, those wrappers leak into the rendered output. This module
|
||||
// provides a single helper to strip them before the markdown renderer sees
|
||||
// the text.
|
||||
//
|
||||
// The function is intentionally conservative: it only strips a wrapper when
|
||||
// it covers the *entire* trimmed content. We don't want to corrupt user-
|
||||
@@ -25,8 +26,8 @@ const ANSWER_PREFIX_RE =
|
||||
/^\s*(?:final\s*answer|最终答案|答案|答)\s*[::]\s*/i;
|
||||
|
||||
/**
|
||||
* Remove common "final answer" wrappers that some models emit instead of
|
||||
* calling the structured `final_answer` tool. Returns the original string
|
||||
* Remove common "final answer" wrappers that some models wrap their
|
||||
* plain-text answer in. Returns the original string
|
||||
* (trimmed only when stripping happens) when no wrapper is detected.
|
||||
*
|
||||
* Recognised wrappers (must cover the entire trimmed content):
|
||||
|
||||
@@ -44,7 +44,6 @@ export const TOOL_CAPABILITY_REQUIREMENTS: Record<string, ToolRequirement> = {
|
||||
// ---- base / reasoning (no KB dependency) ----
|
||||
thinking: {},
|
||||
todo_write: {},
|
||||
final_answer: {},
|
||||
|
||||
// ---- RAG / chunk retrieval (need at least one chunk-indexed KB) ----
|
||||
// We use vector|keyword as the canonical "has RAG chunks" signal. FAQ KBs
|
||||
|
||||
@@ -1655,8 +1655,7 @@ const groupedAvailableTools = computed(() => {
|
||||
// 规则:基于 allowed_tools 过滤
|
||||
// 1) 勾选但缺失对应能力(无 KB / 无 Wiki 能力 KB)的工具会被灰显/隐藏
|
||||
// 2) 无论是否勾选,web_search / web_fetch 随 web_search_enabled 出现
|
||||
// 3) final_answer 始终存在
|
||||
// 4) 当 kb_selection_mode === 'none' 时,RAG/Wiki 工具都视为不可用
|
||||
// 3) 当 kb_selection_mode === 'none' 时,RAG/Wiki 工具都视为不可用
|
||||
const effectiveTools = computed(() => {
|
||||
const chosen = new Set(formData.value.config.allowed_tools || []);
|
||||
const items: Array<{ value: string; label: string; reason?: string; active: boolean }> = [];
|
||||
@@ -1673,7 +1672,6 @@ const effectiveTools = computed(() => {
|
||||
items.push({ value: 'web_search', label: t('agentEditor.tools.webSearch'), active: true });
|
||||
items.push({ value: 'web_fetch', label: t('agentEditor.tools.webFetch'), active: true });
|
||||
}
|
||||
items.push({ value: 'final_answer', label: t('agentEditor.tools.finalAnswer'), active: true });
|
||||
return items;
|
||||
});
|
||||
|
||||
|
||||
@@ -27,14 +27,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Thinking Event (streaming / merged) -->
|
||||
<!-- Thinking Event (streaming / merged). When a round's retracted
|
||||
preamble was folded in, it becomes the card title and the
|
||||
reasoning is the expandable body. -->
|
||||
<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 v-if="isEventExpanded(event.event_id)" class="action-name">{{ $t('agent.think') }}</span>
|
||||
<span v-if="getThinkingSummary(event) && !isEventExpanded(event.event_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>
|
||||
<span v-if="event.title" class="action-name action-preamble-title">{{ event.title }}</span>
|
||||
<span v-else-if="isEventExpanded(event.event_id)" class="action-name">{{ $t('agent.think') }}</span>
|
||||
<span v-else-if="getThinkingSummary(event)" 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'" />
|
||||
@@ -161,7 +164,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Event Stream (non-tree mode: before answer starts, or answer events) -->
|
||||
<div ref="streamingStepsContainer" class="streaming-steps-container" :class="{ 'streaming-steps-constrained': !hasAnswerStarted && !isConversationDone }">
|
||||
<div ref="streamingStepsContainer" class="streaming-steps-container" :class="{ 'streaming-steps-constrained': !answerEverStarted && !isConversationDone }">
|
||||
<template v-for="(event, index) in displayEvents" :key="getEventKey(event, index)">
|
||||
<div v-if="event && event.type" class="event-item" :class="{ 'event-answer': event.type === 'answer' }">
|
||||
|
||||
@@ -174,14 +177,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Thinking Event (streaming / merged) -->
|
||||
<!-- Thinking Event (streaming / merged). A folded preamble (retracted
|
||||
from the answer area) is shown as the card title; the reasoning is
|
||||
the expandable body. -->
|
||||
<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">{{ $t('agent.think') }}</span>
|
||||
<span v-if="getThinkingSummary(event) && !isEventExpanded(event.event_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>
|
||||
<span v-if="event.title" class="action-name action-preamble-title">{{ event.title }}</span>
|
||||
<span v-else class="action-name">{{ $t('agent.think') }}</span>
|
||||
<span v-if="!event.title && 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'" />
|
||||
@@ -339,7 +345,7 @@
|
||||
<ChatRequestInfoButton :session="session" :session-id="sessionId" />
|
||||
</div>
|
||||
<!-- Loading Indicator (inside container so it scrolls into view) -->
|
||||
<div v-if="!isConversationDone && eventStream.length > 0" class="loading-indicator">
|
||||
<div v-if="showAgentActivityIndicator" class="loading-indicator">
|
||||
<div class="loading-typing">
|
||||
<span></span>
|
||||
<span></span>
|
||||
@@ -505,7 +511,6 @@ const TOOL_NAME_KEYS: Record<string, string> = {
|
||||
thinking: 'agentStream.tools.thinking',
|
||||
image_analysis: 'agentStream.tools.imageAnalysis',
|
||||
query_knowledge_graph: 'agentStream.tools.queryKnowledgeGraph',
|
||||
final_answer: 'agentStream.tools.finalAnswer',
|
||||
read_skill: 'agentStream.tools.readSkill',
|
||||
execute_skill_script: 'agentStream.tools.executeSkillScript',
|
||||
data_analysis: 'agentStream.tools.dataAnalysis',
|
||||
@@ -870,8 +875,10 @@ watch(eventStream, (stream) => {
|
||||
}
|
||||
});
|
||||
}
|
||||
// Auto-scroll streaming steps container to bottom during streaming
|
||||
if (!hasAnswerStarted.value && streamingStepsContainer.value) {
|
||||
// Auto-scroll the steps container to the bottom while it is still height-
|
||||
// capped (steps-only phase). Once answer text appears the cap is released
|
||||
// and the container grows with the page, so internal scrolling is moot.
|
||||
if (!answerEverStarted.value && streamingStepsContainer.value) {
|
||||
const el = streamingStepsContainer.value;
|
||||
if (el.scrollHeight > el.clientHeight) {
|
||||
el.scrollTop = el.scrollHeight;
|
||||
@@ -883,8 +890,30 @@ watch(eventStream, (stream) => {
|
||||
// State for intermediate steps collapse
|
||||
const showIntermediateSteps = ref(false);
|
||||
|
||||
// Track whether answer has started streaming (for early collapse)
|
||||
const hasAnswerStarted = ref(false);
|
||||
// Track whether a non-superseded answer is streaming. Plain content streams
|
||||
// optimistically as an `answer` event (rendered answer-style in the answer
|
||||
// area). If the round turns out to be a tool round, that event is marked
|
||||
// `superseded` and retracted into the steps — so a superseded segment must NOT
|
||||
// count as "answer started", otherwise the answer-only view would stick after
|
||||
// the preamble was retracted.
|
||||
const hasAnswerStarted = computed(() => {
|
||||
const stream = eventStream.value;
|
||||
if (!stream || !Array.isArray(stream)) return false;
|
||||
return stream.some((e: any) => e.type === 'answer' && !e.superseded && e.content && e.content.trim());
|
||||
});
|
||||
|
||||
// Whether ANY answer text has ever appeared this turn — including a preamble
|
||||
// that was later superseded (its content stays in the stream). Used to release
|
||||
// the live container's height cap. Unlike hasAnswerStarted this is monotonic:
|
||||
// it does not flip back when a preamble is retracted, so the container does not
|
||||
// shrink back to the capped height (which would look like a jump). Once the
|
||||
// model starts producing answer-style text, give it full height to breathe.
|
||||
const answerEverStarted = computed(() => {
|
||||
const stream = eventStream.value;
|
||||
if (!stream || !Array.isArray(stream)) return false;
|
||||
return stream.some((e: any) => e.type === 'answer' && e.content && e.content.trim());
|
||||
});
|
||||
|
||||
const agentDurationMs = ref<number>(0);
|
||||
watch(eventStream, (stream) => {
|
||||
if (!stream || !Array.isArray(stream)) return;
|
||||
@@ -896,13 +925,6 @@ watch(eventStream, (stream) => {
|
||||
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 });
|
||||
|
||||
|
||||
@@ -927,15 +949,21 @@ const isConversationDone = computed(() => {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for answer event with done=true
|
||||
const answerEvents = stream.filter((e: any) => e.type === 'answer');
|
||||
// Check for answer event with done=true. Exclude superseded preambles: a
|
||||
// retracted tool-round preamble is also closed with done=true, but the agent
|
||||
// keeps running, so it must not mark the whole conversation as finished.
|
||||
const answerEvents = stream.filter((e: any) => e.type === 'answer' && !e.superseded);
|
||||
const doneAnswer = answerEvents.find((e: any) => e.done === true);
|
||||
|
||||
console.log('[Collapse] Answer events:', answerEvents.length, 'Done answer:', !!doneAnswer);
|
||||
|
||||
|
||||
return !!doneAnswer;
|
||||
});
|
||||
|
||||
// Typing indicator while the agent turn is still streaming (not done).
|
||||
const showAgentActivityIndicator = computed(() => {
|
||||
if (isConversationDone.value) return false;
|
||||
return (eventStream.value?.length ?? 0) > 0;
|
||||
});
|
||||
|
||||
// Whether a completed answer with content is rendered (its toolbar hosts the
|
||||
// request-info button inline, so the standalone toolbar should not duplicate it)
|
||||
const hasDoneAnswerContent = computed(() => {
|
||||
@@ -957,8 +985,10 @@ const finalContent = computed(() => {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if there's an answer event with content (normal path via final_answer tool)
|
||||
const answerEvents = stream.filter((e: any) => e.type === 'answer');
|
||||
// Check if there's a (non-superseded) answer event with content. Superseded
|
||||
// preambles carry content too, but they were retracted into the steps and are
|
||||
// not the final answer, so they must not count here.
|
||||
const answerEvents = stream.filter((e: any) => e.type === 'answer' && !e.superseded);
|
||||
const hasAnswerContent = answerEvents.some((e: any) => e.content && e.content.trim());
|
||||
|
||||
if (hasAnswerContent) {
|
||||
@@ -978,7 +1008,7 @@ const finalContent = computed(() => {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fallback: if no answer content (legacy path or LLM didn't call final_answer),
|
||||
// Fallback: if no answer content (e.g. the model ended with only reasoning),
|
||||
// use last thinking as final content
|
||||
const thinkingEvents = stream.filter((e: any) => e.type === 'thinking' && e.content && e.content.trim());
|
||||
if (thinkingEvents.length > 0) {
|
||||
@@ -998,7 +1028,23 @@ const finalContent = computed(() => {
|
||||
const intermediateStepsCount = computed(() => {
|
||||
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;
|
||||
return intermediateEvents.value.filter(
|
||||
(e: any) => e.type === 'thinking' || e.type === 'tool_call'
|
||||
).length;
|
||||
});
|
||||
|
||||
// Number of reasoning rounds (thinking cards) and tool invocations. We report
|
||||
// these separately instead of summing them into one opaque "step" count, which
|
||||
// over-counts what the user perceives as agent loops (a single loop emits one
|
||||
// thinking card plus its tool calls).
|
||||
const reasoningRoundsCount = computed(() => {
|
||||
if (!hasAnswerStarted.value && !isConversationDone.value) return 0;
|
||||
return intermediateEvents.value.filter((e: any) => e.type === 'thinking').length;
|
||||
});
|
||||
|
||||
const toolCallsCount = computed(() => {
|
||||
if (!hasAnswerStarted.value && !isConversationDone.value) return 0;
|
||||
return intermediateEvents.value.filter((e: any) => e.type === 'tool_call').length;
|
||||
});
|
||||
|
||||
const intermediateStepsSummary = computed(() => {
|
||||
@@ -1006,14 +1052,28 @@ const intermediateStepsSummary = computed(() => {
|
||||
return '';
|
||||
}
|
||||
|
||||
const steps = intermediateStepsCount.value;
|
||||
const rounds = reasoningRoundsCount.value;
|
||||
const tools = toolCallsCount.value;
|
||||
const elapsed = agentDurationMs.value;
|
||||
|
||||
if (elapsed > 0) {
|
||||
return t('agent.stepsCompletedWithDuration', { steps, duration: formatDuration(elapsed) });
|
||||
const parts: string[] = [];
|
||||
if (rounds > 0) {
|
||||
parts.push(t('agent.reasoningRounds', { rounds }));
|
||||
}
|
||||
if (tools > 0) {
|
||||
parts.push(t('agent.toolCalls', { tools }));
|
||||
}
|
||||
// Fallback to a generic step count if neither bucket has anything (shouldn't
|
||||
// normally happen once the tree is shown).
|
||||
if (parts.length === 0) {
|
||||
parts.push(t('agent.stepsCompleted', { steps: intermediateStepsCount.value }));
|
||||
}
|
||||
|
||||
return t('agent.stepsCompleted', { steps });
|
||||
if (elapsed > 0) {
|
||||
parts.push(t('agent.durationSuffix', { duration: formatDuration(elapsed) }));
|
||||
}
|
||||
|
||||
return parts.join(t('agent.stepSummarySeparator'));
|
||||
});
|
||||
|
||||
// HTML version of intermediate steps summary with colored numbers
|
||||
@@ -1021,11 +1081,15 @@ const intermediateStepsSummaryHtml = computed(() => {
|
||||
return intermediateStepsSummary.value;
|
||||
});
|
||||
|
||||
// Should show the collapsed steps indicator (tree root)
|
||||
// Triggers when answer starts streaming (early collapse) or when conversation is done
|
||||
// Should show the collapsed steps indicator (tree root). Collapse ONLY once the
|
||||
// conversation is done. Collapsing mid-stream (when answer content appears)
|
||||
// would thrash: a tool round's optimistic preamble streams as answer content,
|
||||
// briefly looking like the final answer, then gets retracted (superseded) —
|
||||
// which would collapse then re-expand the tree. Deferring collapse to the end
|
||||
// keeps the steps stable while the agent runs and the preamble retracts.
|
||||
const shouldShowCollapsedSteps = computed(() => {
|
||||
const hasSteps = intermediateStepsCount.value > 0;
|
||||
return hasSteps && (hasAnswerStarted.value || isConversationDone.value);
|
||||
return hasSteps && isConversationDone.value;
|
||||
});
|
||||
|
||||
// Check if event is a "deep thinking" type (either streaming thinking or thinking tool call)
|
||||
@@ -1122,15 +1186,46 @@ const buildFullEventList = (stream: any[]) => {
|
||||
result.push(event);
|
||||
}
|
||||
|
||||
// Drop thinking events whose content is whitespace-only. Some models emit
|
||||
// "\n\n" before a tool call (see e.g. qwen3 emitting blank lines between
|
||||
// [assistant] and tool_calls), which the backend faithfully forwards as
|
||||
// thought_chunk events. Without this filter the tree shows an empty
|
||||
// "思考" card with no text — confusing to the user.
|
||||
return result.filter((e: any) => {
|
||||
// Relocate each retracted (superseded) answer — a tool round's optimistic
|
||||
// preamble that was pulled out of the answer area — into that round's
|
||||
// thinking card as its TITLE, with the reasoning as the body (one card per
|
||||
// round). A lone preamble (model has no separate reasoning channel) becomes a
|
||||
// title-only thinking card. Non-superseded answers stay as `answer` and are
|
||||
// rendered in the answer area, never here.
|
||||
const folded: any[] = [];
|
||||
for (const e of result) {
|
||||
if (e.type === 'answer' && e.superseded) {
|
||||
const preambleText = typeof e.content === 'string' ? e.content : '';
|
||||
const prev = folded[folded.length - 1];
|
||||
if (prev && prev.type === 'thinking' && !prev.title) {
|
||||
folded[folded.length - 1] = { ...prev, title: preambleText };
|
||||
continue;
|
||||
}
|
||||
// No reasoning channel: title-only thinking card (same chrome as merged
|
||||
// rounds). Rounds with reasoning_content merge preamble into prev.title.
|
||||
folded.push({
|
||||
type: 'thinking',
|
||||
event_id: e.event_id,
|
||||
title: preambleText,
|
||||
content: '',
|
||||
thinking: false,
|
||||
timestamp: e.timestamp,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
folded.push(e);
|
||||
}
|
||||
|
||||
// Drop thinking cards that are entirely empty (no title and no body). Some
|
||||
// models emit "\n\n" before a tool call (e.g. qwen3 blank lines between
|
||||
// [assistant] and tool_calls), which would otherwise show an empty "思考"
|
||||
// card. Keep cards that carry a title (a relocated preamble) even with no
|
||||
// reasoning body.
|
||||
return folded.filter((e: any) => {
|
||||
if (e.type !== 'thinking') return true;
|
||||
const content = typeof e.content === 'string' ? e.content : '';
|
||||
return content.trim().length > 0;
|
||||
const title = typeof e.title === 'string' ? e.title : '';
|
||||
return content.trim().length > 0 || title.trim().length > 0;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1154,7 +1249,7 @@ const hiddenThinkingEventIds = computed<Set<string>>(() => {
|
||||
const final = finalContent.value;
|
||||
if (final && final.type === 'thinking') {
|
||||
const hasRealAnswer = stream.some(
|
||||
(e: any) => e.type === 'answer' && e.content && e.content.trim()
|
||||
(e: any) => e.type === 'answer' && !e.superseded && e.content && e.content.trim()
|
||||
);
|
||||
if (!hasRealAnswer && final.event_id) {
|
||||
hidden.add(final.event_id);
|
||||
@@ -1163,17 +1258,26 @@ const hiddenThinkingEventIds = computed<Set<string>>(() => {
|
||||
|
||||
// Case 2: natural-stop duplicates — answer events carry the same content
|
||||
// already streamed as thinking chunks. Compare merged thinking events
|
||||
// against the concatenated answer content and hide on match.
|
||||
// against the concatenated answer content and hide on match. Superseded
|
||||
// preambles are excluded: they are the retracted tool-round narration, not
|
||||
// the final answer, and are intentionally shown in the steps as titles.
|
||||
const answerContent = stream
|
||||
.filter((e: any) => e.type === 'answer' && e.content)
|
||||
.filter((e: any) => e.type === 'answer' && !e.superseded && e.content)
|
||||
.map((e: any) => e.content)
|
||||
.join('');
|
||||
if (answerContent.trim()) {
|
||||
const merged = buildFullEventList(stream);
|
||||
for (const e of merged) {
|
||||
if (e.type !== 'thinking' || !e.event_id || !e.content) continue;
|
||||
if (e.type !== 'thinking' || !e.event_id) continue;
|
||||
if (hidden.has(e.event_id)) continue;
|
||||
if (thinkingEqualsAnswer(e.content, answerContent)) {
|
||||
// Hide a step card that duplicates the final answer. Match the body, or a
|
||||
// title-only card (a relocated preamble) whose title equals the answer —
|
||||
// but keep cards that still carry a distinct reasoning body so the
|
||||
// reasoning stays visible.
|
||||
const bodyMatches = e.content && thinkingEqualsAnswer(e.content, answerContent);
|
||||
const titleOnlyMatches = e.title && !(e.content && e.content.trim()) &&
|
||||
thinkingEqualsAnswer(e.title, answerContent);
|
||||
if (bodyMatches || titleOnlyMatches) {
|
||||
hidden.add(e.event_id);
|
||||
}
|
||||
}
|
||||
@@ -1204,15 +1308,17 @@ const displayEvents = computed(() => {
|
||||
|
||||
const result = buildFullEventList(stream);
|
||||
|
||||
// If answer hasn't started and not done, show everything (no tree yet)
|
||||
if (!hasAnswerStarted.value && !isConversationDone.value) {
|
||||
// While the conversation is still running, show EVERYTHING inline (steps plus
|
||||
// the optimistically-streamed answer). We must never hide the steps the
|
||||
// moment answer content appears: a tool round's preamble streams as answer
|
||||
// content and briefly looks like the final answer, but it may still be
|
||||
// retracted (superseded). Hiding the steps then would make them vanish and
|
||||
// reappear. The tree collapse happens only once, at the end.
|
||||
if (!isConversationDone.value) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 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
|
||||
// Done: the steps live in the collapsed tree; show only the answer here.
|
||||
const answerEvents = result.filter((e: any) => e.type === 'answer');
|
||||
if (answerEvents.length > 0) {
|
||||
return answerEvents;
|
||||
@@ -1234,7 +1340,7 @@ const displayEvents = computed(() => {
|
||||
|
||||
if (final.type === 'thinking') {
|
||||
// The agent loop ended via natural-stop (the model wrote its answer as
|
||||
// free text instead of calling final_answer). Synthesize a virtual
|
||||
// free text). Synthesize a virtual
|
||||
// `answer` event from the trailing thinking content so it renders with
|
||||
// the answer card UI (expanded markdown + copy/add toolbar) rather than
|
||||
// the collapsed "思考" card. The original thinking event is still in
|
||||
@@ -1902,9 +2008,8 @@ const renderMarkdownContent = (content: any): string => {
|
||||
};
|
||||
|
||||
// Renders an answer event's content. Strips final-answer wrappers
|
||||
// (e.g. <answer>…</answer>, "Final Answer:") that some models emit instead
|
||||
// of calling the structured final_answer tool, then delegates to the
|
||||
// standard markdown renderer.
|
||||
// (e.g. <answer>…</answer>, "Final Answer:") that some models wrap their
|
||||
// plain-text answer in, then delegates to the standard markdown renderer.
|
||||
const renderAnswerContent = (content: any): string => {
|
||||
const contentStr = typeof content === 'string' ? content : String(content || '');
|
||||
return renderMarkdownContent(unwrapFinalAnswerWrappers(contentStr));
|
||||
@@ -2861,6 +2966,17 @@ const handleAddToKnowledge = (answerEvent: any) => {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
// Retracted preamble used as the card title: allow it to wrap to its full
|
||||
// text (it carries meaning) and use primary text color, while the reasoning
|
||||
// body stays in the collapsible details.
|
||||
.action-preamble-title {
|
||||
white-space: normal;
|
||||
word-break: break-word;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
color: var(--td-text-color-primary);
|
||||
}
|
||||
|
||||
.action-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
<div v-if="session.role == 'user'">
|
||||
<usermsg :content="session.content" :mentioned_items="session.mentioned_items" :images="session.images" :attachments="session.attachments" :embeddedMode="embeddedMode"></usermsg>
|
||||
</div>
|
||||
<div v-if="session.role == 'assistant'">
|
||||
<div v-if="session.role == 'assistant' && shouldRenderAssistantMessage(session)">
|
||||
<botmsg :content="session.content" :session="session" :session-id="session_id"
|
||||
:user-query="getUserQuery(index)" @scroll-bottom="scrollToBottom"
|
||||
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"></botmsg>
|
||||
@@ -131,6 +131,33 @@ const props = defineProps({
|
||||
|
||||
const usemenuStore = useMenuStore();
|
||||
const useSettingsStoreInstance = useSettingsStore();
|
||||
|
||||
// Whether the active chat session is using the Agent pipeline (not quick-answer).
|
||||
const isAgentStreamSession = () => {
|
||||
if (props.embeddedMode) {
|
||||
return !!(props.agentId && props.agentId !== 'builtin-quick-answer');
|
||||
}
|
||||
return useSettingsStoreInstance.isAgentEnabled;
|
||||
};
|
||||
|
||||
const ensureAgentMessageShell = (message, requestId) => {
|
||||
message.isAgentMode = true;
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
if (!message._eventMap) message._eventMap = new Map();
|
||||
if (!message._pendingToolCalls) message._pendingToolCalls = new Map();
|
||||
if (requestId) {
|
||||
if (!message.id) message.id = requestId;
|
||||
if (!message.request_id) message.request_id = requestId;
|
||||
}
|
||||
};
|
||||
|
||||
// Agent 占位消息在 agent_query 时仅有空 eventStream。若立刻渲染 botmsg,会把列表
|
||||
// 底部的全局 Loading 顶下去造成跳动;等有首个事件再渲染,Loading 位置保持稳定。
|
||||
const shouldRenderAssistantMessage = (session) => {
|
||||
if (!session?.isAgentMode) return true;
|
||||
const stream = session.agentEventStream;
|
||||
return Array.isArray(stream) && stream.length > 0;
|
||||
};
|
||||
const uiStore = useUIStore();
|
||||
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
|
||||
const { t } = useI18n();
|
||||
@@ -416,6 +443,21 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
|
||||
})
|
||||
}
|
||||
|
||||
// Recompose the visible answer from the agent event stream: concatenate every
|
||||
// non-superseded `answer` event, in arrival order. Superseded events are
|
||||
// per-round preambles that were retracted from the answer area (and relocated
|
||||
// into the steps tree), so they must not leak into message.content.
|
||||
const recomposeAgentAnswer = (message) => {
|
||||
if (!message.agentEventStream) return '';
|
||||
let out = '';
|
||||
for (const e of message.agentEventStream) {
|
||||
if (e.type === 'answer' && !e.superseded && e.content) {
|
||||
out += e.content;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
// 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, agentDurationMs = 0) => {
|
||||
@@ -427,34 +469,51 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
|
||||
// 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 exists.
|
||||
// For tool-calling rounds, providers like MiMo / DeepSeek thinking-mode
|
||||
// emit reasoning into the OpenAI-protocol `reasoning_content` field
|
||||
// rather than visible `content`, so step.thought is often empty even
|
||||
// though the model did reason. Fall back to step.reasoning_content so
|
||||
// the historical step card mirrors what the user saw live.
|
||||
const thoughtText = (step.thought && step.thought.trim())
|
||||
? step.thought
|
||||
: (step.reasoning_content && step.reasoning_content.trim())
|
||||
? step.reasoning_content
|
||||
: '';
|
||||
if (thoughtText) {
|
||||
const hasToolCalls = step.tool_calls && Array.isArray(step.tool_calls) && step.tool_calls.length > 0;
|
||||
|
||||
// Mirror what the user saw live, as two channels of one round (same
|
||||
// order as live: reasoning streams before the plain-content preamble):
|
||||
// - `reasoning_content` (e.g. DeepSeek / MiMo thinking-mode) → the
|
||||
// thinking card body.
|
||||
// - plain `content` narration (`step.thought`) → only a preamble when
|
||||
// this round went on to call tools. We replay it as a *superseded*
|
||||
// answer event, exactly like the live supersede signal, so
|
||||
// buildFullEventList relocates it into this round's thinking card
|
||||
// (as its title) instead of the answer area. For a terminal round
|
||||
// (no tool calls) `step.thought` is the final answer itself and
|
||||
// already lives in messageContent, so we never duplicate it here.
|
||||
const reasoningText = step.reasoning_content && step.reasoning_content.trim()
|
||||
? step.reasoning_content
|
||||
: '';
|
||||
if (reasoningText) {
|
||||
events.push({
|
||||
type: 'thinking',
|
||||
event_id: `step-${step.iteration}-thought`,
|
||||
content: thoughtText,
|
||||
content: reasoningText,
|
||||
done: true,
|
||||
thinking: false,
|
||||
timestamp: stepTimestamp || undefined,
|
||||
// Extract duration from step if available
|
||||
duration_ms: step.duration || undefined,
|
||||
});
|
||||
}
|
||||
const preambleText = step.thought && step.thought.trim() ? step.thought : '';
|
||||
if (preambleText && hasToolCalls) {
|
||||
events.push({
|
||||
type: 'answer',
|
||||
event_id: `step-${step.iteration}-preamble`,
|
||||
content: preambleText,
|
||||
done: true,
|
||||
superseded: true,
|
||||
timestamp: stepTimestamp || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
// Add tool call and result events (skip final_answer as its content is in the answer event)
|
||||
// Add tool call and result events. Legacy histories may still contain a
|
||||
// final_answer tool call (the tool has since been removed); skip it since
|
||||
// its content is replayed as 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 event
|
||||
if (toolCall.name === 'final_answer') return; // legacy data — shown as answer event
|
||||
events.push({
|
||||
type: 'tool_call',
|
||||
tool_call_id: toolCall.id,
|
||||
@@ -788,14 +847,32 @@ onChunk((data) => {
|
||||
});
|
||||
|
||||
// 检查是否是继续流式传输(消息已存在)
|
||||
const existingMessage = findLastMessage((item) => item.id === data.id || item.request_id === data.id);
|
||||
let existingMessage = findLastMessage((item) => item.id === data.id || item.request_id === data.id);
|
||||
if (!existingMessage) {
|
||||
// 新消息,设置 loading 状态
|
||||
loading.value = true;
|
||||
console.log('[Agent Query] New message, setting loading=true');
|
||||
// 预建 Agent 占位消息,确保紧随其后的 answer 分片走 handleAgentChunk
|
||||
// 写入 agentEventStream,而不是非 Agent 路径的 message.content。
|
||||
existingMessage = {
|
||||
id: data.id,
|
||||
request_id: data.id,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
isAgentMode: true,
|
||||
is_completed: false,
|
||||
agentEventStream: [],
|
||||
_eventMap: new Map(),
|
||||
_pendingToolCalls: new Map(),
|
||||
knowledge_references: [],
|
||||
};
|
||||
messagesList.push(existingMessage);
|
||||
attachStreamDebugToMessage(existingMessage);
|
||||
// 保持全局 Loading,直到首个 thinking/answer/tool 到达(handleAgentChunk
|
||||
// 会关闭)。若此处过早 loading=false,eventStream 仍为空时 Agent 内也无
|
||||
// 指示器,会出现「闪一下消失 → 空白 → 再出答案/再 Loading」。
|
||||
scrollToBottom(true);
|
||||
console.log('[Agent Query] Created agent placeholder message');
|
||||
} else {
|
||||
// 继续流式传输(刷新页面场景),不设置 loading,因为消息已经在列表中
|
||||
console.log('[Agent Query] Continuing stream for existing message, keeping current loading state');
|
||||
ensureAgentMessageShell(existingMessage, data.id);
|
||||
console.log('[Agent Query] Continuing stream for existing message');
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -827,9 +904,26 @@ onChunk((data) => {
|
||||
// 检查当前消息是否已经是 Agent 模式
|
||||
const lastMessage = messagesList[messagesList.length - 1];
|
||||
const isCurrentlyAgentMode = lastMessage?.isAgentMode === true;
|
||||
const targetsActiveAgentRequest =
|
||||
isAgentStreamSession() &&
|
||||
!!data.id &&
|
||||
(data.id === currentAssistantMessageId.value ||
|
||||
lastMessage?.request_id === data.id ||
|
||||
lastMessage?.id === data.id);
|
||||
// Agent 开场白会先以 answer 分片流出;若此时尚未打上 isAgentMode,
|
||||
// 会误走非 Agent 路径写入 message.content,tool_call 后才切到 Agent,
|
||||
// AgentStreamDisplay 读不到 agentEventStream 中的开场白。
|
||||
const isAgentAnswerChunk =
|
||||
data.response_type === 'answer' && (isAgentStreamSession() || targetsActiveAgentRequest);
|
||||
const isAgentCompleteChunk =
|
||||
data.response_type === 'complete' && (isAgentStreamSession() || targetsActiveAgentRequest);
|
||||
|
||||
// 如果是 Agent 专有的响应类型,或者当前消息已经是 Agent 模式,则走 Agent 处理
|
||||
const shouldHandleAsAgent = isAgentOnlyResponse || isCurrentlyAgentMode;
|
||||
const shouldHandleAsAgent =
|
||||
isAgentOnlyResponse ||
|
||||
isCurrentlyAgentMode ||
|
||||
isAgentAnswerChunk ||
|
||||
isAgentCompleteChunk;
|
||||
|
||||
// 处理 references 事件 - 在两种模式下都需要处理,但不改变模式
|
||||
if (data.response_type === 'references') {
|
||||
@@ -1056,7 +1150,7 @@ const handleAgentChunk = (data) => {
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
case 'tool_approval_required': {
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
const d = data.data || {};
|
||||
@@ -1090,10 +1184,30 @@ const handleAgentChunk = (data) => {
|
||||
break;
|
||||
}
|
||||
case 'tool_call':
|
||||
// Skip final_answer tool call from event stream - its content appears as answer events
|
||||
// Legacy guard: the final_answer tool has been removed, but old
|
||||
// streamed/replayed data may still carry it — its content appears
|
||||
// as answer events, so skip the tool-call rendering.
|
||||
if (data.data && data.data.tool_name === 'final_answer') {
|
||||
break;
|
||||
}
|
||||
// 任何在本工具调用之前流入答案区的纯文本都是这一轮的开场白,而非最终
|
||||
// 答案(Agent 只会以"纯文本、无工具调用"自然结束)。因此一旦出现工具
|
||||
// 调用,就把先前的答案片段从答案区回撤、交给步骤树重新定位,等效于旧的
|
||||
// 后端 superseded 标记,并用剩余片段重组 message.content。
|
||||
if (message.agentEventStream) {
|
||||
let retracted = false;
|
||||
for (const ev of message.agentEventStream) {
|
||||
if (ev.type === 'answer' && !ev.superseded && ev.content && ev.content.trim()) {
|
||||
ev.superseded = true;
|
||||
ev.done = true;
|
||||
retracted = true;
|
||||
}
|
||||
}
|
||||
if (retracted) {
|
||||
message.content = recomposeAgentAnswer(message);
|
||||
fullContent.value = message.content;
|
||||
}
|
||||
}
|
||||
// Store or update pending tool call to pair with result later
|
||||
if (data.data && (data.data.tool_name || data.data.tool_call_id)) {
|
||||
const incomingToolName = data.data.tool_name;
|
||||
@@ -1225,42 +1339,36 @@ const handleAgentChunk = (data) => {
|
||||
}
|
||||
break;
|
||||
|
||||
case 'answer':
|
||||
// 最终答案
|
||||
case 'answer': {
|
||||
// 最终答案(乐观流式)。普通 content 先按答案样式流入答案区;若这一轮
|
||||
// 其实调用了工具(是开场白),后续的 tool_call 事件会把该片段从答案区
|
||||
// 回撤、交给步骤树重新定位(见 'tool_call' 分支),并用剩余未被回撤的
|
||||
// 片段重组 message.content。每轮答案各自一个事件(按 event_id 区分),
|
||||
// 这样开场白不会和最终答案合并。
|
||||
message.thinking = false;
|
||||
|
||||
console.log('[Answer Event] Received:', {
|
||||
has_content: !!data.content,
|
||||
content_length: data.content?.length || 0,
|
||||
done: data.done,
|
||||
current_message_content_length: message.content?.length || 0
|
||||
});
|
||||
|
||||
const eventId = data.data?.event_id;
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
if (!message._eventMap) message._eventMap = new Map();
|
||||
|
||||
let answerEvent = eventId
|
||||
? message._eventMap.get(eventId)
|
||||
: message.agentEventStream.find((e) => e.type === 'answer' && !e.event_id);
|
||||
if (!answerEvent) {
|
||||
answerEvent = { type: 'answer', event_id: eventId, content: '', done: false };
|
||||
message.agentEventStream.push(answerEvent);
|
||||
if (eventId) message._eventMap.set(eventId, answerEvent);
|
||||
}
|
||||
|
||||
// 若 answer 分片曾误走非 Agent 路径,首次进入 Agent 处理时迁入事件流
|
||||
if (!answerEvent.content && message.content && message.content.trim()) {
|
||||
answerEvent.content = message.content;
|
||||
}
|
||||
|
||||
// 只有当有实际内容时才追加,避免空内容覆盖
|
||||
if (data.content) {
|
||||
message.content = (message.content || '') + data.content;
|
||||
fullContent.value += data.content;
|
||||
console.log('[Answer] Content appended, new length:', message.content.length);
|
||||
}
|
||||
|
||||
// Add or update answer event in agentEventStream
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
|
||||
let answerEvent = message.agentEventStream.find((e) => e.type === 'answer');
|
||||
if (!answerEvent) {
|
||||
answerEvent = {
|
||||
type: 'answer',
|
||||
content: '',
|
||||
done: false
|
||||
};
|
||||
message.agentEventStream.push(answerEvent);
|
||||
console.log('[Answer] Created new answer event in stream');
|
||||
}
|
||||
|
||||
// 只有当有实际内容时才更新 answerEvent.content
|
||||
if (data.content) {
|
||||
answerEvent.content = message.content;
|
||||
console.log('[Answer] answerEvent.content updated, length:', answerEvent.content.length);
|
||||
answerEvent.content += data.content;
|
||||
message.content = recomposeAgentAnswer(message);
|
||||
fullContent.value = message.content;
|
||||
}
|
||||
|
||||
// 检查是否为 fallback 回答
|
||||
@@ -1268,27 +1376,22 @@ const handleAgentChunk = (data) => {
|
||||
answerEvent.is_fallback = true;
|
||||
message.is_fallback = true;
|
||||
}
|
||||
|
||||
|
||||
// 只在第一次收到 done:true 时标记完成,忽略后续重复的完成事件
|
||||
if (data.done && !answerEvent.done) {
|
||||
answerEvent.done = true;
|
||||
console.log('[Agent] Answer done, content length:', message.content?.length || 0, 'answerEvent.content length:', answerEvent.content?.length || 0);
|
||||
attachStreamDebugToMessage(message);
|
||||
pendingStreamDebug.value = null;
|
||||
|
||||
|
||||
// 完成 - 关闭所有状态
|
||||
loading.value = false;
|
||||
isReplying.value = false;
|
||||
fullContent.value = '';
|
||||
// 清空当前 assistant message ID
|
||||
currentAssistantMessageId.value = '';
|
||||
|
||||
// 标题生成已改为异步事件推送,不再需要在这里手动调用
|
||||
// 如果标题还未生成,前端会通过 SSE 事件接收
|
||||
} else if (data.done && answerEvent.done) {
|
||||
console.log('[Answer] Ignoring duplicate done event, current content preserved:', answerEvent.content?.length || 0);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'complete':
|
||||
// 整个流式响应完成事件 - 确保状态正确关闭
|
||||
|
||||
@@ -1684,3 +1684,4 @@ onMounted(loadAll)
|
||||
color: #CE1126;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user