fix(chat): persist failed quick-answer turns so errors survive refresh (#4306)
* fix(chat): persist failed quick-answer turns so errors survive refresh A KnowledgeQA (fast-answer/RAG) turn that failed left the assistant row empty and incomplete forever. The pipeline error was already surfaced live as an SSE error event (bubble text + toast), but nothing ever completed the turn: no content was saved, is_completed stayed false, and the SSE stream never published its completion event, so a refresh rendered a blank bubble and the connection polled until the client hung up (issue #4145). Register an EventError handler for the quick-answer mode that completes the turn through the same path as a streamed answer: - persist the error text on the assistant message (appending to a partial answer instead of replacing it), falling back to a fixed explanation when the error carries no message - mark the row completed, release the turn lease and publish the SSE completion so the stream closes cleanly - skip chat-history indexing, follow-up suggestions and memory writes for the failed turn by completing with an empty query A late error after a fallback already completed the turn is ignored via the shared completion guard. * test: wrap over-length fixture error string to satisfy lllmain
parent
6dd0a6a3d6
commit
12e3e49d80
|
|
@ -1412,6 +1412,12 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle
|
|||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
// A failed pipeline never streams EventAgentFinalAnswer with Done=true,
|
||||
// so the turn would otherwise end with an empty, incomplete assistant
|
||||
// row: the live UI shows the error event, but a refresh renders a blank
|
||||
// bubble and the SSE stream never closes (issue #4145).
|
||||
h.registerQuickAnswerFailureHandler(streamCtx, &completionHandled, reqCtx.session.TenantID)
|
||||
}
|
||||
|
||||
// Execute QA asynchronously
|
||||
|
|
@ -2023,6 +2029,46 @@ func (h *Handler) completeQuickAnswerTurn(
|
|||
}
|
||||
}
|
||||
|
||||
// quickAnswerFailureContent is persisted when a pipeline error carries no
|
||||
// message, so the failed turn does not save an empty answer.
|
||||
const quickAnswerFailureContent = "Failed to generate the answer"
|
||||
|
||||
// registerQuickAnswerFailureHandler completes and persists the assistant
|
||||
// message when the quick-answer pipeline reports EventError. The empty query
|
||||
// keeps the failed turn out of the chat-history index, follow-up suggestions
|
||||
// and memory writes — only the visible error text belongs in history.
|
||||
func (h *Handler) registerQuickAnswerFailureHandler(
|
||||
streamCtx *sseStreamContext, completionHandled *bool, sessionTenantID uint64,
|
||||
) {
|
||||
streamCtx.eventBus.On(event.EventError, func(ctx context.Context, evt event.Event) error {
|
||||
data, ok := evt.Data.(event.ErrorData)
|
||||
if !ok || *completionHandled {
|
||||
return nil
|
||||
}
|
||||
*completionHandled = true
|
||||
|
||||
errorContent := strings.TrimSpace(data.Error)
|
||||
if errorContent == "" {
|
||||
errorContent = quickAnswerFailureContent
|
||||
}
|
||||
msg := streamCtx.assistantMessage
|
||||
// Keep any partial answer the stream produced before failing and
|
||||
// append the error, so a reload shows both instead of losing the text.
|
||||
if remaining := strings.TrimSpace(msg.Content); remaining != "" {
|
||||
msg.Content += "\n\n" + errorContent
|
||||
} else {
|
||||
msg.Content = errorContent
|
||||
}
|
||||
|
||||
updateCtx := context.WithValue(
|
||||
context.WithoutCancel(ctx),
|
||||
types.TenantIDContextKey, sessionTenantID,
|
||||
)
|
||||
h.completeQuickAnswerTurn(updateCtx, streamCtx, "", "")
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// sessionTenantInfoContext makes the tenant info match the session owner (the
|
||||
// context's tenant here). The chat history KB is read from the tenant info,
|
||||
// and a shared agent's run carries the agent workspace's: the receiver's
|
||||
|
|
|
|||
|
|
@ -0,0 +1,118 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newQuickAnswerFailureHarness(
|
||||
t *testing.T, msg *types.Message,
|
||||
) (*sseStreamContext, *imageCompletionMessages, *imageCompletionStream, *bool) {
|
||||
t.Helper()
|
||||
messages := &imageCompletionMessages{}
|
||||
stream := &imageCompletionStream{}
|
||||
h := &Handler{messageService: messages, streamManager: stream}
|
||||
bus := event.NewEventBus()
|
||||
ctx := types.WithExecutionTenant(context.Background(), 1)
|
||||
streamHandler := h.setupStreamHandler(ctx, msg.SessionID, msg.ID, "req", 1, time.Now(), msg, bus)
|
||||
released := false
|
||||
streamCtx := &sseStreamContext{
|
||||
eventBus: bus,
|
||||
streamHandler: streamHandler,
|
||||
assistantMessage: msg,
|
||||
releaseTurn: func() { released = true },
|
||||
}
|
||||
h.registerQuickAnswerFailureHandler(streamCtx, new(bool), 1)
|
||||
return streamCtx, messages, stream, &released
|
||||
}
|
||||
|
||||
const testStreamError = `create chat completion: Post "https://model.example:9999/v1/chat/completions": EOF`
|
||||
|
||||
// A failed quick-answer turn must persist the error text, complete the
|
||||
// assistant row, release the turn lease and close the SSE stream with a
|
||||
// completion event. Without this the row stayed empty and incomplete: the
|
||||
// live UI showed the error, but a refresh rendered a blank bubble (issue
|
||||
// #4145).
|
||||
func TestQuickAnswerFailurePersistsErrorAndCompletesTurn(t *testing.T) {
|
||||
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
|
||||
streamCtx, messages, stream, released := newQuickAnswerFailureHarness(t, msg)
|
||||
|
||||
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
|
||||
Type: event.EventError,
|
||||
Data: event.ErrorData{
|
||||
Error: testStreamError,
|
||||
Stage: "chat_completion_stream",
|
||||
SessionID: "s",
|
||||
},
|
||||
}))
|
||||
|
||||
require.NotNil(t, messages.saved)
|
||||
require.Equal(t, testStreamError, messages.saved.Content)
|
||||
require.True(t, messages.saved.IsCompleted)
|
||||
require.Equal(t, uint64(1), messages.tenant)
|
||||
require.True(t, *released)
|
||||
last := stream.events[len(stream.events)-1]
|
||||
require.Equal(t, types.ResponseTypeComplete, last.Type)
|
||||
}
|
||||
|
||||
// A stream that produced partial text before failing keeps it; the error is
|
||||
// appended instead of replacing the answer.
|
||||
func TestQuickAnswerFailureAppendsErrorToPartialAnswer(t *testing.T) {
|
||||
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant", Content: "partial answer"}
|
||||
streamCtx, messages, _, released := newQuickAnswerFailureHarness(t, msg)
|
||||
|
||||
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
|
||||
Type: event.EventError,
|
||||
Data: event.ErrorData{Error: "stream ended early", Stage: "chat_completion_stream"},
|
||||
}))
|
||||
|
||||
require.NotNil(t, messages.saved)
|
||||
require.Equal(t, "partial answer\n\nstream ended early", messages.saved.Content)
|
||||
require.True(t, messages.saved.IsCompleted)
|
||||
require.True(t, *released)
|
||||
}
|
||||
|
||||
// After the turn already completed (e.g. a fallback answer), a late error
|
||||
// event must not re-complete or overwrite the saved answer.
|
||||
func TestQuickAnswerFailureAfterCompletionIsIgnored(t *testing.T) {
|
||||
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
|
||||
messages := &imageCompletionMessages{}
|
||||
stream := &imageCompletionStream{}
|
||||
h := &Handler{messageService: messages, streamManager: stream}
|
||||
bus := event.NewEventBus()
|
||||
ctx := types.WithExecutionTenant(context.Background(), 1)
|
||||
h.setupStreamHandler(ctx, "s", "m", "req", 1, time.Now(), msg, bus)
|
||||
streamCtx := &sseStreamContext{eventBus: bus, assistantMessage: msg}
|
||||
|
||||
handled := true
|
||||
h.registerQuickAnswerFailureHandler(streamCtx, &handled, 1)
|
||||
|
||||
require.NoError(t, bus.Emit(ctx, event.Event{
|
||||
Type: event.EventError,
|
||||
Data: event.ErrorData{Error: "late failure", Stage: "chat_completion_stream"},
|
||||
}))
|
||||
require.Nil(t, messages.saved)
|
||||
require.Equal(t, "", msg.Content)
|
||||
}
|
||||
|
||||
// An error event carrying no message still completes the turn, with a
|
||||
// non-empty explanation instead of a blank answer.
|
||||
func TestQuickAnswerFailureWithEmptyErrorUsesFallbackText(t *testing.T) {
|
||||
msg := &types.Message{ID: "m", SessionID: "s", Role: "assistant"}
|
||||
streamCtx, messages, _, released := newQuickAnswerFailureHarness(t, msg)
|
||||
|
||||
require.NoError(t, streamCtx.eventBus.Emit(context.Background(), event.Event{
|
||||
Type: event.EventError,
|
||||
Data: event.ErrorData{Stage: "knowledge_qa_execution"},
|
||||
}))
|
||||
|
||||
require.NotNil(t, messages.saved)
|
||||
require.Equal(t, quickAnswerFailureContent, messages.saved.Content)
|
||||
require.True(t, messages.saved.IsCompleted)
|
||||
require.True(t, *released)
|
||||
}
|
||||
Loading…
Reference in New Issue