From 780f2beb5af306fce79b0a7ab0b396a4c8aa28b1 Mon Sep 17 00:00:00 2001 From: vicfei Date: Tue, 8 Sep 2026 13:15:08 +0800 Subject: [PATCH] fix(agent): stop emitting terminal answer events for retryable empty stops MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit analyzeResponse emitted EventAgentFinalAnswer with Done=true before returning emptyContent=true to the retry loop, so every empty natural stop produced a premature terminal answer event while the agent was still running. Consumers that finalize on Done=true (e.g. the IM channel, which closes its answer-done channel and then only waits a bounded time for EventAgentComplete) can lock in a fallback and cancel the still-running agent when the nudged retry is slower than that window (#2906). An empty natural stop now emits nothing — the verdict alone tells the caller the round is retryable. When retries are exhausted, the loop emits the selected fallback as the turn's sole terminal answer, so a turn always ends with exactly one terminal answer event. Regression tests cover all three shapes: the empty verdict emits no answer events; empty-then-answer ends with exactly one terminal event carrying the real answer; all-empty runs end with exactly one terminal event carrying the fallback (each red on the pre-fix code). --- internal/agent/engine.go | 27 +++++- internal/agent/observe.go | 17 +++- internal/agent/terminal_event_test.go | 126 ++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 3 deletions(-) create mode 100644 internal/agent/terminal_event_test.go diff --git a/internal/agent/engine.go b/internal/agent/engine.go index 857ba90b..879cfee4 100644 --- a/internal/agent/engine.go +++ b/internal/agent/engine.go @@ -789,10 +789,33 @@ func (e *AgentEngine) runReActIteration( }) return iterOutcomeContinue, nil } - // Retries exhausted — use fallback message rather than empty answer + // Retries exhausted — use fallback message rather than empty answer. + // analyzeResponse emitted nothing for the empty rounds (they were + // retryable), so the fallback must be emitted here as the turn's + // sole terminal answer event (#2906). logger.Warnf(ctx, "[Agent][Round-%d] Empty content after %d retries - using fallback", round, maxEmptyResponseRetries) - state.FinalAnswer = "I'm sorry, I was unable to generate a response. Please try again." + fallback := "I'm sorry, I was unable to generate a response. Please try again." + answerID := generateEventID("answer") + _ = e.eventBus.Emit(ctx, event.Event{ + ID: answerID, + Type: event.EventAgentFinalAnswer, + SessionID: sessionID, + Data: event.AgentFinalAnswerData{ + Content: fallback, + Done: false, + }, + }) + _ = e.eventBus.Emit(ctx, event.Event{ + ID: answerID, + Type: event.EventAgentFinalAnswer, + SessionID: sessionID, + Data: event.AgentFinalAnswerData{ + Content: "", + Done: true, + }, + }) + state.FinalAnswer = fallback state.IsComplete = true state.RoundSteps = append(state.RoundSteps, verdict.step) e.closeAnswerStream(ctx, sessionID, verdict.answerID) diff --git a/internal/agent/observe.go b/internal/agent/observe.go index e65fa26e..6316887f 100644 --- a/internal/agent/observe.go +++ b/internal/agent/observe.go @@ -421,6 +421,21 @@ func (e *AgentEngine) analyzeResponse( "answer_len": len(response.Content), }) + // An empty natural stop is retryable (the caller nudges the model and + // runs another round), so it must not emit any terminal answer event + // yet: downstream consumers treat a Done=true EventAgentFinalAnswer as + // "the answer is finished" and would finalize (or cancel) while the + // retry is still running (#2906). When retries are exhausted the + // caller emits the fallback as the sole terminal answer. + if response.Content == "" { + return responseVerdict{ + isDone: true, + finalAnswer: "", + emptyContent: true, + step: step, + } + } + // Emit the final answer. The answer text reaches the UI by one of two // paths: // (a) Already streamed live during the think phase — the common case @@ -456,7 +471,7 @@ func (e *AgentEngine) analyzeResponse( return responseVerdict{ isDone: true, finalAnswer: response.Content, - emptyContent: response.Content == "", + emptyContent: false, step: step, answerID: answerID, } diff --git a/internal/agent/terminal_event_test.go b/internal/agent/terminal_event_test.go new file mode 100644 index 00000000..32f8d5d2 --- /dev/null +++ b/internal/agent/terminal_event_test.go @@ -0,0 +1,126 @@ +package agent + +import ( + "context" + "strings" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// terminalAnswerRecorder captures every EventAgentFinalAnswer so tests can +// assert how many terminal (Done=true) markers a turn emitted and which +// answer text they closed. +type terminalAnswerRecorder struct { + mu sync.Mutex + contents []string // Done=false payloads in emission order + done int // Done=true terminal markers +} + +func (r *terminalAnswerRecorder) attach(bus *event.EventBus) { + bus.On(event.EventAgentFinalAnswer, func(_ context.Context, evt event.Event) error { + data, ok := evt.Data.(event.AgentFinalAnswerData) + if !ok { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + if data.Done { + r.done++ + } else if data.Content != "" { + r.contents = append(r.contents, data.Content) + } + return nil + }) +} + +func (r *terminalAnswerRecorder) snapshot() (int, string) { + r.mu.Lock() + defer r.mu.Unlock() + return r.done, strings.Join(r.contents, "") +} + +// TestAnalyzeResponse_EmptyNaturalStop_EmitsNoTerminalAnswer pins the #2906 +// fix at the verdict layer: an empty natural stop is retryable, so it must +// not emit any EventAgentFinalAnswer — downstream consumers treat Done=true +// as "answer finished" and would terminate while the retry is still running. +func TestAnalyzeResponse_EmptyNaturalStop_EmitsNoTerminalAnswer(t *testing.T) { + engine := newTestEngine(t, &mockChat{}) + recorder := &terminalAnswerRecorder{} + recorder.attach(engine.eventBus) + + verdict := engine.analyzeResponse( + context.Background(), + &types.ChatResponse{FinishReason: "stop", Content: ""}, + types.AgentStep{}, 0, "sess-1", time.Now(), + ) + + done, content := recorder.snapshot() + assert.True(t, verdict.isDone, "an empty natural stop still ends the round") + assert.True(t, verdict.emptyContent, "the caller must see emptyContent to trigger the retry") + assert.Empty(t, verdict.finalAnswer) + assert.Equal(t, 0, done, "a retryable empty stop must not emit a terminal answer event") + assert.Empty(t, content, "a retryable empty stop must not emit answer content either") +} + +// TestExecuteLoop_EmptyThenAnswer_EmitsSingleTerminalAnswer is the +// deterministic reproduction from #2906: the first LLM response is an empty +// natural stop, the retry produces the real answer. The turn must end with +// exactly one terminal answer event carrying the real answer — not one +// premature empty marker plus a second one after the retry. +func TestExecuteLoop_EmptyThenAnswer_EmitsSingleTerminalAnswer(t *testing.T) { + mock := &mockChat{ + responses: []mockResponse{ + {chunks: []types.StreamResponse{{Done: true}}}, + {chunks: []types.StreamResponse{{Content: "Here is my complete answer", Done: true}}}, + }, + } + engine := newTestEngine(t, mock) + recorder := &terminalAnswerRecorder{} + recorder.attach(engine.eventBus) + + state := &types.AgentState{} + _, err := engine.executeLoop(context.Background(), state, "test query", emptyMessages(), emptyTools(), "sess-1", "msg-1") + + require.NoError(t, err) + assert.True(t, state.IsComplete) + assert.Equal(t, "Here is my complete answer", state.FinalAnswer) + + done, content := recorder.snapshot() + assert.Equal(t, 1, done, "the whole turn must emit exactly one terminal answer event") + assert.Contains(t, content, "Here is my complete answer") + assert.NotContains(t, content, "unable to generate", "the retry succeeded, no fallback should surface") +} + +// TestExecuteLoop_AllEmptyResponses_FallbackIsSoleTerminalAnswer covers the +// exhausted-retry path: analyzeResponse stays silent for every empty round, +// so the fallback the loop selects must be emitted as the turn's sole +// terminal answer. +func TestExecuteLoop_AllEmptyResponses_FallbackIsSoleTerminalAnswer(t *testing.T) { + // 1 initial attempt + maxEmptyResponseRetries nudges. + responses := make([]mockResponse, 0, 1+maxEmptyResponseRetries) + for i := 0; i < 1+maxEmptyResponseRetries; i++ { + responses = append(responses, mockResponse{chunks: []types.StreamResponse{{Done: true}}}) + } + mock := &mockChat{responses: responses} + + engine := newTestEngine(t, mock) + recorder := &terminalAnswerRecorder{} + recorder.attach(engine.eventBus) + + state := &types.AgentState{} + _, err := engine.executeLoop(context.Background(), state, "test query", emptyMessages(), emptyTools(), "sess-1", "msg-1") + + require.NoError(t, err) + assert.True(t, state.IsComplete) + assert.NotEmpty(t, state.FinalAnswer) + + done, content := recorder.snapshot() + assert.Equal(t, 1, done, "retries exhausted must still emit exactly one terminal answer event") + assert.Contains(t, content, "unable to generate a response", "the terminal answer must be the fallback text") +}