diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue
index 28f25f38..2d1e2c09 100644
--- a/frontend/src/components/IMChannelPanel.vue
+++ b/frontend/src/components/IMChannelPanel.vue
@@ -19,7 +19,7 @@
+
@@ -894,6 +894,19 @@ const finalContent = computed(() => {
return { type: 'answer' };
}
+ // Do NOT fall back to re-rendering the last thinking event when the
+ // intermediate-steps tree already shows it — that would duplicate the
+ // thinking card below the tree. The fallback is only meaningful for
+ // legacy conversations where the tree is absent. Also skip for
+ // user-stopped conversations which have no final answer to fall back to.
+ if (shouldShowCollapsedSteps.value) {
+ return null;
+ }
+ const wasStopped = stream.some((e: any) => e.type === 'stop');
+ if (wasStopped) {
+ return null;
+ }
+
// 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());
@@ -1071,6 +1084,14 @@ const displayEvents = computed(() => {
return answerEvents;
}
+ // If the intermediate-steps tree is active, all thinking/tool_call events
+ // are already rendered there. Showing anything else here would duplicate
+ // them. This covers both the user-stopped case and any completion path
+ // that didn't produce an answer event.
+ if (shouldShowCollapsedSteps.value) {
+ return [];
+ }
+
// Fallback: if no answer events, show last thinking (legacy compatibility)
const final = finalContent.value;
if (!final) {
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 69ed4826..b50b82c1 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -380,15 +380,14 @@ const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted
if (isFallback) answerEvent.is_fallback = true;
events.push(answerEvent);
} else if (isCompleted) {
- // 如果消息已完成但 content 为空(Agent 模式常见情况),添加一个空的 answer 事件标记完成
- // 这样可以确保 isConversationDone 返回 true,不显示 loading-indicator
- const answerEvent = {
- type: 'answer',
- content: '',
- done: true
- };
- if (isFallback) answerEvent.is_fallback = true;
- events.push(answerEvent);
+ // 消息已完成但 content 为空:说明是"停止时尚未产出最终答案"的场景。
+ // Push 一个 stop 事件,让 AgentStreamDisplay 的 isConversationDone 返回 true,
+ // 但不产生 answer 内容,也就不会渲染最终答案的 toolbar。与实时 stop 分支保持一致。
+ events.push({
+ type: 'stop',
+ timestamp: Date.now(),
+ reason: 'user_requested'
+ });
}
return events;
@@ -435,11 +434,9 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {
}
}
- // 只给非Agent模式的空内容已完成消息设置默认错误消息
- // Agent模式的消息内容在agent_steps中,content为空是正常的
- if (item.is_completed && !item.content && !item.isAgentMode) {
- item.content = t('chat.cannotAnswer');
- }
+ // 非 Agent 模式下若 content 为空(例如用户停止时尚未产出任何文字),
+ // 保持为空;botmsg.vue 会因 hasActualContent=false 不渲染内容区和 toolbar。
+ // 此前这里会兜底为 "chat.cannotAnswer",会让停止场景显示误导性文案并出现复制按钮。
messagesList.unshift(item);
if (isFirstEnter.value) {
scrollToBottom(true);
@@ -725,7 +722,25 @@ onChunk((data) => {
// 原有的知识库 QA 处理逻辑(非 Agent 模式)
// answer 内容中可能包含 ... 标签
-
+
+ // 非 Agent 模式下的 stop 事件:只更新状态,不把后端附带的 "Generation stopped by user"
+ // 文案拼进 content,保留用户点停止时已经流式输出的内容不变。
+ if (data.response_type === 'stop') {
+ console.log('[Stop Event] Non-agent generation stopped');
+ const stoppedMessage = messagesList.findLast((item) => {
+ if (item.request_id === data.id) return true;
+ return item.id === data.id;
+ });
+ if (stoppedMessage) {
+ stoppedMessage.is_completed = true;
+ }
+ loading.value = false;
+ isReplying.value = false;
+ fullContent.value = '';
+ currentAssistantMessageId.value = '';
+ return;
+ }
+
// 检查消息是否已经完成,如果已完成则忽略后续的完成事件(防止空内容覆盖)
const existingMessage = messagesList.findLast((item) => {
if (item.request_id === data.id) {
diff --git a/internal/agent/engine.go b/internal/agent/engine.go
index 671467c9..89a9118a 100644
--- a/internal/agent/engine.go
+++ b/internal/agent/engine.go
@@ -353,6 +353,24 @@ func (e *AgentEngine) executeLoop(
common.PipelineInfo(ctx, "Agent", "loop_start", map[string]interface{}{
"max_iterations": e.config.MaxIterations,
})
+
+ // Guarantee exactly-one EventAgentComplete emission on every exit path
+ // (normal finish, ctx cancel observed at the loop head, or iteration error
+ // bubbling up while ctx was cancelled). The emission triggers
+ // agent_stream_handler.handleComplete, which is where state.RoundSteps
+ // (thinking + tool_call history) gets written onto assistantMessage.AgentSteps
+ // so it can be persisted by the caller's defer. Use WithoutCancel so a
+ // cancelled ctx does not short-circuit the emit on the stop path.
+ completionEmitted := false
+ emitCompletion := func() {
+ if completionEmitted {
+ return
+ }
+ completionEmitted = true
+ e.emitCompletionEvent(context.WithoutCancel(ctx), state, sessionID, messageID, startTime)
+ }
+ defer emitCompletion()
+
emptyRetries := 0
consecutiveSameContent := 0
lastResponseContent := ""
@@ -393,14 +411,16 @@ loop:
}
}
- // If loop finished without final answer, generate one
- if !state.IsComplete {
+ // If loop finished without final answer, generate one — but skip this
+ // when the context was cancelled (user pressed stop). In that case the
+ // fallback LLM call would fail on the already-cancelled ctx and set
+ // state.FinalAnswer to the generic "Sorry, I was unable to generate a
+ // complete answer." message, which then leaks to the UI as the final
+ // answer for a conversation the user deliberately stopped.
+ if !state.IsComplete && ctx.Err() == nil {
e.handleMaxIterations(ctx, query, state, sessionID)
}
- // Emit completion event
- e.emitCompletionEvent(ctx, state, sessionID, messageID, startTime)
-
return state, nil
}
@@ -554,6 +574,25 @@ func (e *AgentEngine) runReActIteration(
Timestamp: time.Now(),
}
+ // If the request was cancelled while the LLM was streaming (e.g. the
+ // user pressed "stop"), the stream driver still returns a usable
+ // response (partial content / finish_reason="stop" / no tool calls).
+ // Do NOT let analyzeResponse treat that partial thinking text as the
+ // final answer — it would pollute Message.Content with mid-stream
+ // thinking and show up as a duplicate card next to the intermediate-
+ // steps tree. Preserve the partial thinking as an AgentStep and break
+ // out of the loop without marking state.IsComplete. executeLoop's
+ // deferred emitCompletionEvent will persist the step onto
+ // Message.AgentSteps so it still appears in the tree on refresh.
+ if ctx.Err() != nil {
+ logger.Warnf(ctx, "[Agent][Round-%d] Context cancelled during LLM call; preserving partial step",
+ round)
+ if step.Thought != "" || len(step.ToolCalls) > 0 {
+ state.RoundSteps = append(state.RoundSteps, step)
+ }
+ return iterOutcomeBreak, nil
+ }
+
// 2. Analyze: Check for stop conditions (natural stop or final_answer tool)
verdict := e.analyzeResponse(ctx, response, step, state.CurrentRound, sessionID, roundStart)
if verdict.isDone {
diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go
index fc68f574..5e5bb06c 100644
--- a/internal/handler/session/helpers.go
+++ b/internal/handler/session/helpers.go
@@ -213,9 +213,13 @@ func (h *Handler) setupStopEventHandler(
eventBus.On(event.EventStop, func(ctx context.Context, evt event.Event) error {
logger.Infof(ctx, "Received stop event, cancelling async operations for session: %s", sessionID)
cancel()
- assistantMessage.Content = "用户停止了本次对话"
- // Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent)
- updateCtx := context.WithValue(ctx, types.TenantIDContextKey, sessionTenantID)
+ // Preserve whatever has been streamed so far; do not overwrite Content.
+ // Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent).
+ // Use WithoutCancel so the GORM UPDATE survives the upcoming ctx.Done triggered by cancel()/client disconnect.
+ updateCtx := context.WithValue(
+ context.WithoutCancel(ctx),
+ types.TenantIDContextKey, sessionTenantID,
+ )
h.completeAssistantMessage(updateCtx, assistantMessage, "") // empty query: stopped conversations are not indexed
return nil
})
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index 76d8a67d..ea2de39d 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -615,7 +615,15 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
}
// Agent mode: complete the assistant message in defer (normal mode does it via event handler)
if mode == qaModeAgent {
- updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID)
+ // Use WithoutCancel so a user-triggered stop (which cancels
+ // asyncCtx) doesn't also cancel the GORM UPDATE that persists
+ // AgentSteps/Content. Without this, cancelled-ctx makes
+ // GORM skip the write and the agent's intermediate steps
+ // (thinking / tool_call history) are lost on page refresh.
+ updateCtx := context.WithValue(
+ context.WithoutCancel(streamCtx.asyncCtx),
+ types.TenantIDContextKey, reqCtx.session.TenantID,
+ )
h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query)
logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID)
}