diff --git a/internal/application/service/agent_history.go b/internal/application/service/agent_history.go index c9c2c686..a471f0a0 100644 --- a/internal/application/service/agent_history.go +++ b/internal/application/service/agent_history.go @@ -194,11 +194,14 @@ func buildAssistantHistoryMessages(m *types.Message) []chat.Message { const legacyFinalAnswerToolName = "final_answer" // filterNonTerminalToolCalls drops legacy final_answer entries from historical -// tool calls (see legacyFinalAnswerToolName). New turns never produce them. +// tool calls (see legacyFinalAnswerToolName), plus the pipeline stages a +// fast-answer turn records for its own timeline (see +// types.PipelineToolCallIDPrefix): the model never issued those, so replaying +// them would attribute calls to it that it cannot answer for. func filterNonTerminalToolCalls(calls []types.ToolCall) []types.ToolCall { out := make([]types.ToolCall, 0, len(calls)) for _, tc := range calls { - if tc.Name == legacyFinalAnswerToolName { + if tc.Name == legacyFinalAnswerToolName || types.IsPipelineToolCallID(tc.ID) { continue } out = append(out, tc) diff --git a/internal/application/service/agent_history_test.go b/internal/application/service/agent_history_test.go index 69bcad3a..1f83d7fd 100644 --- a/internal/application/service/agent_history_test.go +++ b/internal/application/service/agent_history_test.go @@ -182,6 +182,37 @@ func TestBuildAssistantHistoryMessages_ToolCallsExpandIntoOpenAIShape(t *testing assert.Empty(t, got[2].ToolCalls) } +// A fast-answer turn persists its retrieval stages so the UI can redraw the +// timeline after a reload. Those calls came from the pipeline, not the model, so +// replaying them would hand the model tool calls it never made — and, in a +// KnowledgeQA turn, tools it was never offered. +func TestBuildAssistantHistoryMessages_SkipsPipelineTimelineToolCalls(t *testing.T) { + msg := &types.Message{ + Role: "assistant", + Content: "你好!很高兴见到你。", + AgentSteps: types.AgentSteps{ + { + Iteration: 0, + ToolCalls: []types.ToolCall{ + { + ID: types.PipelineToolCallIDPrefix + "abc", + Name: agenttools.ToolKnowledgeSearch, + Args: map[string]interface{}{"query": "你好"}, + Result: &types.ToolResult{Success: true, Output: "未检索到相关内容"}, + }, + }, + }, + }, + } + got := buildAssistantHistoryMessages(msg) + if !assert.Len(t, got, 1) { + return + } + assert.Equal(t, "assistant", got[0].Role) + assert.Equal(t, "你好!很高兴见到你。", got[0].Content) + assert.Empty(t, got[0].ToolCalls) +} + // TestBuildAssistantHistoryMessages_ToolFailureSurfacesAsError ensures a // historical failed tool call is replayed as an "Error: …" tool message so the // model can see (and avoid retrying) the same failure path. diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index afe5e0e9..ac26bc98 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -943,6 +943,11 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle if mode == qaModeNormal { var completionHandled bool + // Persist the pipeline's retrieval/attachment stages so a reloaded + // conversation redraws the timeline it showed while streaming, including + // turns that searched and cited nothing. + registerQuickAnswerTimelineRecorder(streamCtx.eventBus, streamCtx.assistantMessage) + // Persist reasoning_content into agent_steps so historical reload can // reconstruct the thinking card (same shape as Agent-mode steps). // Accumulate on assistantMessage directly so user-initiated stop also @@ -1409,14 +1414,7 @@ func appendQuickAnswerReasoning(msg *types.Message, content string) { if content == "" { return } - if len(msg.AgentSteps) == 0 { - msg.AgentSteps = types.AgentSteps{{ - Iteration: 0, - Timestamp: time.Now(), - ToolCalls: make([]types.ToolCall, 0), - }} - } - msg.AgentSteps[0].ReasoningContent += content + ensureQuickAnswerStep(msg).ReasoningContent += content } // completeAssistantMessage marks an assistant message as complete, updates it, diff --git a/internal/handler/session/quick_answer_timeline.go b/internal/handler/session/quick_answer_timeline.go new file mode 100644 index 00000000..1c6f1508 --- /dev/null +++ b/internal/handler/session/quick_answer_timeline.go @@ -0,0 +1,130 @@ +package session + +import ( + "context" + "sync" + "time" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/types" +) + +// quickAnswerTimelineTools are the stages a fast-answer turn draws on its +// timeline. A turn that retrieved nothing still reports the search it ran, so +// the set is what decides whether the step survives a reload — not whether it +// produced citations. Keep in sync with RAG_TIMELINE_TOOL_NAMES on the frontend. +var quickAnswerTimelineTools = map[string]struct{}{ + "query_understand": {}, + "knowledge_search": {}, + "attachment_parsing": {}, + "image_analysis": {}, +} + +// quickAnswerTimelineRecorder persists the fast-answer pipeline's timeline into +// the assistant message's AgentSteps. +// +// Reconstructing the timeline from knowledge_references only works for turns +// that cited something: a turn that searched and found nothing, or that only +// parsed an attachment, came back from history with no steps at all and lost +// the timeline it had while streaming. +type quickAnswerTimelineRecorder struct { + mu sync.Mutex + msg *types.Message + pending map[string]map[string]any + startedAt map[string]time.Time +} + +// registerQuickAnswerTimelineRecorder subscribes to the pipeline's tool events +// for the lifetime of one fast-answer turn. Agent mode is excluded on purpose: +// its own steps are written by the agent stream handler, which overwrites +// AgentSteps wholesale. +func registerQuickAnswerTimelineRecorder(bus *event.EventBus, msg *types.Message) { + if bus == nil || msg == nil { + return + } + rec := &quickAnswerTimelineRecorder{ + msg: msg, + pending: make(map[string]map[string]any), + startedAt: make(map[string]time.Time), + } + bus.On(event.EventAgentToolCall, rec.onToolCall) + bus.On(event.EventAgentToolResult, rec.onToolResult) +} + +func (r *quickAnswerTimelineRecorder) onToolCall(_ context.Context, evt event.Event) error { + data, ok := evt.Data.(event.AgentToolCallData) + if !ok || !isQuickAnswerTimelineTool(data.ToolName) || data.ToolCallID == "" { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + r.pending[data.ToolCallID] = data.Arguments + r.startedAt[data.ToolCallID] = time.Now() + return nil +} + +// onToolResult is where the step is persisted. Waiting for the result keeps a +// half-finished stage out of history: a stage still running when the turn is +// stopped would come back from a reload looking like it had completed. +func (r *quickAnswerTimelineRecorder) onToolResult(_ context.Context, evt event.Event) error { + data, ok := evt.Data.(event.AgentToolResultData) + if !ok || !isQuickAnswerTimelineTool(data.ToolName) || data.ToolCallID == "" { + return nil + } + + r.mu.Lock() + defer r.mu.Unlock() + + args := r.pending[data.ToolCallID] + delete(r.pending, data.ToolCallID) + started, hasStart := r.startedAt[data.ToolCallID] + delete(r.startedAt, data.ToolCallID) + + duration := data.Duration + if duration == 0 && hasStart { + duration = time.Since(started).Milliseconds() + } + + appendQuickAnswerToolCall(r.msg, types.ToolCall{ + ID: types.PipelineToolCallIDPrefix + data.ToolCallID, + Name: data.ToolName, + Args: args, + Result: &types.ToolResult{ + Success: data.Success, + Output: data.Output, + Error: data.Error, + Data: data.Data, + }, + Duration: duration, + }) + return nil +} + +func isQuickAnswerTimelineTool(name string) bool { + _, ok := quickAnswerTimelineTools[name] + return ok +} + +// ensureQuickAnswerStep returns the single step a fast-answer turn records +// into. There is no ReAct loop here, so everything belongs to iteration 0. +func ensureQuickAnswerStep(msg *types.Message) *types.AgentStep { + if len(msg.AgentSteps) == 0 { + msg.AgentSteps = types.AgentSteps{{ + Iteration: 0, + Timestamp: time.Now(), + ToolCalls: make([]types.ToolCall, 0), + }} + } + return &msg.AgentSteps[0] +} + +func appendQuickAnswerToolCall(msg *types.Message, call types.ToolCall) { + step := ensureQuickAnswerStep(msg) + for i := range step.ToolCalls { + if step.ToolCalls[i].ID == call.ID { + step.ToolCalls[i] = call + return + } + } + step.ToolCalls = append(step.ToolCalls, call) +} diff --git a/internal/handler/session/quick_answer_timeline_test.go b/internal/handler/session/quick_answer_timeline_test.go new file mode 100644 index 00000000..433893db --- /dev/null +++ b/internal/handler/session/quick_answer_timeline_test.go @@ -0,0 +1,111 @@ +package session + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func emitTimelineStage( + t *testing.T, + bus *event.EventBus, + toolCallID, toolName string, + args map[string]any, + result event.AgentToolResultData, +) { + t.Helper() + require.NoError(t, bus.Emit(context.Background(), event.Event{ + Type: event.EventAgentToolCall, + Data: event.AgentToolCallData{ToolCallID: toolCallID, ToolName: toolName, Arguments: args}, + })) + result.ToolCallID = toolCallID + result.ToolName = toolName + require.NoError(t, bus.Emit(context.Background(), event.Event{ + Type: event.EventAgentToolResult, + Data: result, + })) +} + +// A turn that searched and cited nothing is exactly the case history replay +// could not reconstruct from knowledge_references, so it must be persisted. +func TestQuickAnswerTimelineRecorderPersistsSearchWithoutResults(t *testing.T) { + bus := event.NewEventBus() + msg := &types.Message{} + registerQuickAnswerTimelineRecorder(bus, msg) + + emitTimelineStage(t, bus, "call-1", "knowledge_search", + map[string]any{"query": "你好", "search_source": "knowledge"}, + event.AgentToolResultData{ + Output: "未检索到相关内容", + Success: true, + Duration: 12, + Data: map[string]interface{}{"count": 0, "doc_count": 0, "web_count": 0}, + }) + + require.Len(t, msg.AgentSteps, 1) + require.Len(t, msg.AgentSteps[0].ToolCalls, 1) + call := msg.AgentSteps[0].ToolCalls[0] + assert.Equal(t, "knowledge_search", call.Name) + assert.Equal(t, types.PipelineToolCallIDPrefix+"call-1", call.ID) + assert.Equal(t, "你好", call.Args["query"]) + require.NotNil(t, call.Result) + assert.True(t, call.Result.Success) + assert.Equal(t, "未检索到相关内容", call.Result.Output) + assert.Equal(t, 0, call.Result.Data["count"]) + assert.Equal(t, int64(12), call.Duration) +} + +func TestQuickAnswerTimelineRecorderKeepsStageOrderAndIgnoresOtherTools(t *testing.T) { + bus := event.NewEventBus() + msg := &types.Message{} + registerQuickAnswerTimelineRecorder(bus, msg) + + emitTimelineStage(t, bus, "call-1", "query_understand", nil, + event.AgentToolResultData{Output: "已完成问题理解", Success: true}) + emitTimelineStage(t, bus, "call-2", "web_search", nil, + event.AgentToolResultData{Output: "ignored", Success: true}) + emitTimelineStage(t, bus, "call-3", "knowledge_search", nil, + event.AgentToolResultData{Output: "检索到 3 条相关内容", Success: true}) + + require.Len(t, msg.AgentSteps, 1) + names := make([]string, 0, len(msg.AgentSteps[0].ToolCalls)) + for _, call := range msg.AgentSteps[0].ToolCalls { + names = append(names, call.Name) + } + assert.Equal(t, []string{"query_understand", "knowledge_search"}, names) +} + +// A stage that never reported a result belongs to an interrupted turn. Keeping +// it out of history is what stops a reload from showing it as completed. +func TestQuickAnswerTimelineRecorderSkipsStagesWithoutResult(t *testing.T) { + bus := event.NewEventBus() + msg := &types.Message{} + registerQuickAnswerTimelineRecorder(bus, msg) + + require.NoError(t, bus.Emit(context.Background(), event.Event{ + Type: event.EventAgentToolCall, + Data: event.AgentToolCallData{ToolCallID: "call-1", ToolName: "knowledge_search"}, + })) + + assert.Empty(t, msg.AgentSteps) +} + +// Reasoning and timeline stages share one step, so neither may clobber the other. +func TestQuickAnswerReasoningAndTimelineShareOneStep(t *testing.T) { + bus := event.NewEventBus() + msg := &types.Message{} + registerQuickAnswerTimelineRecorder(bus, msg) + + appendQuickAnswerReasoning(msg, "思考中") + emitTimelineStage(t, bus, "call-1", "knowledge_search", nil, + event.AgentToolResultData{Output: "未检索到相关内容", Success: true}) + appendQuickAnswerReasoning(msg, "继续") + + require.Len(t, msg.AgentSteps, 1) + assert.Equal(t, "思考中继续", msg.AgentSteps[0].ReasoningContent) + require.Len(t, msg.AgentSteps[0].ToolCalls, 1) +} diff --git a/internal/types/agent.go b/internal/types/agent.go index 57bfabaa..8591b0b3 100644 --- a/internal/types/agent.go +++ b/internal/types/agent.go @@ -4,6 +4,7 @@ import ( "context" "database/sql/driver" "encoding/json" + "strings" "time" ) @@ -206,6 +207,20 @@ type ToolCall struct { ProviderMetadata ToolCallMetadata `json:"provider_metadata,omitempty"` // Provider-specific tool-call state for replay } +// PipelineToolCallIDPrefix marks a persisted tool call the model never made. +// The fast-answer (KnowledgeQA) pipeline records its retrieval stages as tool +// calls so a reloaded conversation can redraw the same timeline it showed while +// streaming. History replay must skip them: asking the model to account for +// calls it never issued, against tools it may not even have, breaks the +// request protocol. +const PipelineToolCallIDPrefix = "ragpipe-" + +// IsPipelineToolCallID reports whether a tool call was synthesized by the +// fast-answer pipeline rather than requested by the model. +func IsPipelineToolCallID(id string) bool { + return strings.HasPrefix(id, PipelineToolCallIDPrefix) +} + // AgentStep represents one iteration of the ReAct loop type AgentStep struct { Iteration int `json:"iteration"` // Iteration number (0-indexed)