Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(im/feishu): show progress card in full output mode (#2909)

Leonbcea5c1195ab
diff --git a/internal/im/adapter.go b/internal/im/adapter.go
index 6db12da68..fc84529ef 100644
--- a/internal/im/adapter.go
+++ b/internal/im/adapter.go
@@ -144,8 +144,9 @@ type Adapter interface {
}
// StreamSender is an optional interface that adapters can implement to support streaming replies.
-// When an adapter implements StreamSender, the IM service will push answer chunks in real-time
-// instead of waiting for the full answer.
+// In stream output mode the IM service pushes answer chunks in real time. In
+// full output mode it may use the same replaceable message only as a progress
+// placeholder, then replace it once with the completed answer.
type StreamSender interface {
// StartStream initializes a streaming reply session (e.g., creates a streaming card).
// Returns a platform-specific stream ID for subsequent chunk/end calls.
@@ -162,6 +163,14 @@ type StreamSender interface {
EndStream(ctx context.Context, incoming *IncomingMessage, streamID string) error
}
+// FullOutputProgressSender is an optional capability for adapters whose stream
+// starts with a visible placeholder that can safely be replaced once with the
+// completed answer. Full output never calls UpdateStreamContent.
+type FullOutputProgressSender interface {
+ StreamSender
+ SupportsFullOutputProgress() bool
+}
+
// FileDownloader is an optional interface that adapters can implement to support
// downloading file attachments from the IM platform. It allows file/image
// messages to be supplied to QA as attachments; when a knowledge_base_id is
diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.go
index 6b6d124cc..eb2d74703 100644
--- a/internal/im/feishu/adapter.go
+++ b/internal/im/feishu/adapter.go
@@ -36,8 +36,9 @@ import (
"github.com/gin-gonic/gin"
)
-// Compile-time check that Adapter implements im.StreamSender and im.FileDownloader.
+// Compile-time checks for the optional IM capabilities implemented by Adapter.
var _ im.StreamSender = (*Adapter)(nil)
+var _ im.FullOutputProgressSender = (*Adapter)(nil)
var _ im.FileDownloader = (*Adapter)(nil)
var httpClient = utils.NewSSRFSafeHTTPClient(utils.SSRFSafeHTTPClientConfig{
@@ -156,6 +157,12 @@ func (a *Adapter) Platform() im.Platform {
return a.region.Platform
}
+// SupportsFullOutputProgress reports that StartStream immediately sends a
+// visible, replaceable thinking card suitable for full-output mode.
+func (a *Adapter) SupportsFullOutputProgress() bool {
+ return true
+}
+
// VerifyCallback verifies the Feishu event callback by checking the verification token.
// If no verification token is configured (e.g., WebSocket mode), skip verification.
func (a *Adapter) VerifyCallback(c *gin.Context) error {
diff --git a/internal/im/full_output_test.go b/internal/im/full_output_test.go
new file mode 100644
index 000000000..526435aea
--- /dev/null
+++ b/internal/im/full_output_test.go
@@ -0,0 +1,381 @@
+package im
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/event"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+type fullOutputOrder struct {
+ mu sync.Mutex
+ steps []string
+}
+
+func (o *fullOutputOrder) add(step string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.steps = append(o.steps, step)
+}
+
+func (o *fullOutputOrder) snapshot() []string {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return append([]string(nil), o.steps...)
+}
+
+type fullOutputSessionService struct {
+ interfaces.SessionService
+ order *fullOutputOrder
+ answer string
+ hangUntilCancel bool
+ started chan struct{}
+}
+
+func (s *fullOutputSessionService) KnowledgeQA(ctx context.Context, req *types.QARequest, bus *event.EventBus) error {
+ s.order.add("qa")
+ if s.started != nil {
+ close(s.started)
+ }
+ if s.hangUntilCancel {
+ <-ctx.Done()
+ return ctx.Err()
+ }
+ return bus.Emit(ctx, event.Event{
+ ID: "answer-1",
+ Type: event.EventAgentFinalAnswer,
+ SessionID: req.Session.ID,
+ Data: event.AgentFinalAnswerData{
+ Content: s.answer,
+ Done: true,
+ },
+ })
+}
+
+type fullOutputMessageService struct {
+ interfaces.MessageService
+}
+
+func (s *fullOutputMessageService) CreateMessage(_ context.Context, msg *types.Message) (*types.Message, error) {
+ created := *msg
+ created.ID = created.Role + "-message"
+ return &created, nil
+}
+
+func (s *fullOutputMessageService) UpdateMessage(_ context.Context, _ *types.Message) error {
+ return nil
+}
+
+type fullOutputStreamManager struct {
+ interfaces.StreamManager
+}
+
+func (s *fullOutputStreamManager) AppendEvent(_ context.Context, _, _ string, _ interfaces.StreamEvent) error {
+ return nil
+}
+
+func (s *fullOutputStreamManager) GetEvents(
+ _ context.Context, _, _ string, from int,
+) ([]interfaces.StreamEvent, int, error) {
+ return nil, from, nil
+}
+
+type fullOutputAdapter struct {
+ Adapter
+ order *fullOutputOrder
+ finalContent string
+ updates int
+ plainReplies int
+ plainContent string
+ startErr error
+ finalizeErr error
+ sendErr error
+}
+
+func (a *fullOutputAdapter) SendReply(ctx context.Context, _ *IncomingMessage, reply *ReplyMessage) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if a.sendErr != nil {
+ a.order.add("plain-reply")
+ return a.sendErr
+ }
+ a.plainReplies++
+ if reply != nil {
+ a.plainContent = reply.Content
+ }
+ a.order.add("plain-reply")
+ return nil
+}
+
+func (a *fullOutputAdapter) StartStream(ctx context.Context, _ *IncomingMessage) (string, error) {
+ if err := ctx.Err(); err != nil {
+ return "", err
+ }
+ a.order.add("start")
+ if a.startErr != nil {
+ return "", a.startErr
+ }
+ return "full-output-stream", nil
+}
+
+func (a *fullOutputAdapter) SupportsFullOutputProgress() bool {
+ return true
+}
+
+func (a *fullOutputAdapter) UpdateStreamContent(ctx context.Context, _ *IncomingMessage, _ string, _ string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ a.updates++
+ a.order.add("update")
+ return nil
+}
+
+func (a *fullOutputAdapter) FinalizeStream(ctx context.Context, _ *IncomingMessage, _ string, content string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ a.finalContent = content
+ a.order.add("finalize")
+ return a.finalizeErr
+}
+
+func (a *fullOutputAdapter) EndStream(ctx context.Context, _ *IncomingMessage, _ string) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ a.order.add("end")
+ return nil
+}
+
+type fullOutputNoProgressAdapter struct {
+ *fullOutputAdapter
+}
+
+func (a *fullOutputNoProgressAdapter) SupportsFullOutputProgress() bool {
+ return false
+}
+
+func newFullOutputHarness(answer string) (*Service, *fullOutputAdapter, *fullOutputSessionService, *fullOutputOrder) {
+ order := &fullOutputOrder{}
+ adapter := &fullOutputAdapter{order: order}
+ sessionSvc := &fullOutputSessionService{order: order, answer: answer}
+ service := &Service{
+ sessionService: sessionSvc,
+ messageService: &fullOutputMessageService{},
+ streamManager: &fullOutputStreamManager{},
+ }
+ return service, adapter, sessionSvc, order
+}
+
+func TestHandleMessageFullOutputShowsPlaceholderWithoutIntermediateUpdates(t *testing.T) {
+ service, adapter, _, order := newFullOutputHarness("最终答案")
+ msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"}
+ session := &types.Session{ID: "session-1"}
+
+ err := service.handleMessageFullOutput(
+ context.Background(), msg, session, nil, nil, nil, nil, adapter, adapter, "user-key", nil,
+ )
+ if err != nil {
+ t.Fatalf("handleMessageFullOutput() error = %v", err)
+ }
+
+ wantOrder := []string{"start", "qa", "finalize", "end"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if adapter.updates != 0 {
+ t.Fatalf("full output sent %d intermediate updates, want 0", adapter.updates)
+ }
+ if adapter.finalContent != "最终答案" {
+ t.Fatalf("final content = %q, want %q", adapter.finalContent, "最终答案")
+ }
+ if adapter.plainReplies != 0 {
+ t.Fatalf("plain fallback replies = %d, want 0", adapter.plainReplies)
+ }
+}
+
+func TestHandleMessageFullOutputReplacesPlaceholderAfterCancel(t *testing.T) {
+ service, adapter, sessionSvc, order := newFullOutputHarness("")
+ sessionSvc.hangUntilCancel = true
+ sessionSvc.started = make(chan struct{})
+ msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"}
+ session := &types.Session{ID: "session-1"}
+
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() {
+ done <- service.handleMessageFullOutput(
+ ctx, msg, session, nil, nil, nil, nil, adapter, adapter, "user-key", nil,
+ )
+ }()
+
+ select {
+ case <-sessionSvc.started:
+ case <-time.After(2 * time.Second):
+ t.Fatal("QA did not start")
+ }
+ cancel()
+
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("handleMessageFullOutput() error = %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for full-output after cancel")
+ }
+
+ wantOrder := []string{"start", "qa", "finalize", "end"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if adapter.finalContent != imCancelledFallback {
+ t.Fatalf("final content = %q, want cancel fallback %q", adapter.finalContent, imCancelledFallback)
+ }
+ if adapter.plainReplies != 0 {
+ t.Fatalf("plain fallback replies = %d, want 0", adapter.plainReplies)
+ }
+}
+
+func TestHandleMessageFullOutputStartStreamErrorFallsBackToPlainReply(t *testing.T) {
+ service, adapter, _, order := newFullOutputHarness("最终答案")
+ adapter.startErr = errors.New("create card failed")
+ msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"}
+ session := &types.Session{ID: "session-1"}
+
+ err := service.handleMessageFullOutput(
+ context.Background(), msg, session, nil, nil, nil, nil, adapter, adapter, "user-key", nil,
+ )
+ if err != nil {
+ t.Fatalf("handleMessageFullOutput() error = %v", err)
+ }
+
+ wantOrder := []string{"start", "qa", "plain-reply"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if adapter.plainReplies != 1 {
+ t.Fatalf("plain fallback replies = %d, want 1", adapter.plainReplies)
+ }
+ if adapter.plainContent != "最终答案" {
+ t.Fatalf("plain reply = %q, want %q", adapter.plainContent, "最终答案")
+ }
+ if adapter.finalContent != "" {
+ t.Fatalf("FinalizeStream ran after StartStream failure, content=%q", adapter.finalContent)
+ }
+}
+
+func TestHandleMessageFullOutputFinalizeFailureSendsPlainReply(t *testing.T) {
+ service, adapter, _, order := newFullOutputHarness("最终答案")
+ adapter.finalizeErr = errors.New("card update failed")
+ msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"}
+ session := &types.Session{ID: "session-1"}
+
+ err := service.handleMessageFullOutput(
+ context.Background(), msg, session, nil, nil, nil, nil, adapter, adapter, "user-key", nil,
+ )
+ if err != nil {
+ t.Fatalf("successful plain fallback should not return error, got %v", err)
+ }
+
+ wantOrder := []string{"start", "qa", "finalize", "end", "plain-reply"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if adapter.plainReplies != 1 {
+ t.Fatalf("plain fallback replies = %d, want 1", adapter.plainReplies)
+ }
+ if adapter.plainContent != "最终答案" {
+ t.Fatalf("plain reply = %q, want %q", adapter.plainContent, "最终答案")
+ }
+}
+
+func TestHandleMessageFullOutputThinkOnlyReplacesWithNoAnswerFallback(t *testing.T) {
+ service, adapter, _, _ := newFullOutputHarness("<think>only reasoning</think>")
+ msg := &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"}
+ session := &types.Session{ID: "session-1"}
+
+ err := service.handleMessageFullOutput(
+ context.Background(), msg, session, nil, nil, nil, nil, adapter, adapter, "user-key", nil,
+ )
+ if err != nil {
+ t.Fatalf("handleMessageFullOutput() error = %v", err)
+ }
+ if adapter.finalContent != imNoAnswerFallback {
+ t.Fatalf("final content = %q, want %q", adapter.finalContent, imNoAnswerFallback)
+ }
+}
+
+func TestExecuteQARequestFullOutputDispatchesToProgressSender(t *testing.T) {
+ service, adapter, _, order := newFullOutputHarness("最终答案")
+ ctx, cancel := context.WithCancel(context.Background())
+ service.executeQARequest(&qaRequest{
+ ctx: ctx,
+ cancel: cancel,
+ msg: &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"},
+ session: &types.Session{ID: "session-1"},
+ adapter: adapter,
+ channel: &IMChannel{OutputMode: "full"},
+ userKey: "user-key",
+ })
+
+ wantOrder := []string{"start", "qa", "finalize", "end"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if adapter.plainReplies != 0 {
+ t.Fatalf("plain fallback replies = %d, want 0", adapter.plainReplies)
+ }
+}
+
+func TestExecuteQARequestFullOutputSkipsProgressWhenNotSupported(t *testing.T) {
+ service, inner, _, order := newFullOutputHarness("最终答案")
+ adapter := &fullOutputNoProgressAdapter{fullOutputAdapter: inner}
+ ctx, cancel := context.WithCancel(context.Background())
+ service.executeQARequest(&qaRequest{
+ ctx: ctx,
+ cancel: cancel,
+ msg: &IncomingMessage{Platform: PlatformFeishu, UserID: "user-1", Content: "问题"},
+ session: &types.Session{ID: "session-1"},
+ adapter: adapter,
+ channel: &IMChannel{OutputMode: "full"},
+ userKey: "user-key",
+ })
+
+ wantOrder := []string{"qa", "plain-reply"}
+ if got := order.snapshot(); !reflect.DeepEqual(got, wantOrder) {
+ t.Fatalf("lifecycle order = %v, want %v", got, wantOrder)
+ }
+ if inner.plainContent != "最终答案" {
+ t.Fatalf("plain reply = %q, want %q", inner.plainContent, "最终答案")
+ }
+}
+
+func TestFormatIMOutboundAnswerOrFallbackAfterCleanup(t *testing.T) {
+ got := formatIMOutboundAnswerOrFallback(
+ context.Background(), "<think>only reasoning</think>", nil, nil,
+ )
+ if got != imNoAnswerFallback {
+ t.Fatalf("think-only final content = %q, want fallback %q", got, imNoAnswerFallback)
+ }
+}
+
+func TestIMQAFailureReply(t *testing.T) {
+ if got := imQAFailureReply(context.Canceled); got != imCancelledFallback {
+ t.Fatalf("canceled = %q, want %q", got, imCancelledFallback)
+ }
+ if got := imQAFailureReply(context.DeadlineExceeded); got != imCancelledFallback {
+ t.Fatalf("deadline = %q, want %q", got, imCancelledFallback)
+ }
+ if got := imQAFailureReply(errors.New("boom")); got != imErrorFallback {
+ t.Fatalf("other error = %q, want %q", got, imErrorFallback)
+ }
+}
diff --git a/internal/im/service.go b/internal/im/service.go
index a96072004..b1733e14f 100644
--- a/internal/im/service.go
+++ b/internal/im/service.go
@@ -38,6 +38,10 @@ import (
)
const (
+ imNoAnswerFallback = "抱歉,我暂时无法回答这个问题。"
+ imErrorFallback = "抱歉,处理您的问题时出现了异常,请稍后再试。"
+ imCancelledFallback = "抱歉,回答已被取消。"
+
// dedupTTL is how long processed message IDs are retained.
dedupTTL = 5 * time.Minute
// dedupCleanupInterval is how often the dedup map is cleaned.
@@ -141,6 +145,42 @@ func formatIMOutboundAnswer(ctx context.Context, raw string, tenant *types.Tenan
return cleanIMContent(ctx, FormatIMDisplayContent(raw, StreamDisplayFinal), tenant, defaultFileSvc, storageResolvers...)
}
+// formatIMOutboundAnswerOrFallback guarantees that cleanup cannot turn a
+// non-empty model payload (for example, a think-only response) into an empty IM
+// message. Callers may pass imErrorFallback or imCancelledFallback as raw when
+// QA itself failed or was stopped.
+func formatIMOutboundAnswerOrFallback(
+ ctx context.Context,
+ raw string,
+ tenant *types.Tenant,
+ defaultFileSvc interfaces.FileService,
+ storageResolvers ...interfaces.StorageBackendResolver,
+) string {
+ content := formatIMOutboundAnswer(ctx, raw, tenant, defaultFileSvc, storageResolvers...)
+ if strings.TrimSpace(content) == "" {
+ return imNoAnswerFallback
+ }
+ return content
+}
+
+// imOutboundContext keeps values from ctx but drops cancellation. /stop cancels
+// the QA request; Feishu CardKit calls honor that deadline and would otherwise
+// leave the thinking placeholder on screen.
+func imOutboundContext(ctx context.Context) context.Context {
+ return context.WithoutCancel(ctx)
+}
+
+// imQAFailureReply maps a QA error onto the user-visible IM fallback text.
+func imQAFailureReply(err error) string {
+ if err == nil {
+ return imNoAnswerFallback
+ }
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return imCancelledFallback
+ }
+ return imErrorFallback
+}
+
// cleanIMContent applies all IM-specific content transformations:
// 1. Collapse <image> XML blocks back to plain markdown
// 2. Strip <kb/> and <web/> citation tags
@@ -1922,28 +1962,44 @@ func (s *Service) executeQARequest(req *qaRequest) {
// Determine output mode from channel config.
streamDisabled := req.channel.OutputMode == "full"
- // If the adapter supports streaming and output is not "full", use streaming.
- if !streamDisabled {
- if streamer, ok := req.adapter.(StreamSender); ok {
- if err := s.handleMessageStream(ctx, req.msg, req.session, req.agent, kbIDs, attachments, imageURLs, streamer, req.adapter, req.userKey, req.tenant); err != nil {
- logger.Errorf(ctx, "[IM] Stream QA failed: %v", err)
+ if streamDisabled {
+ if progressSender, ok := req.adapter.(FullOutputProgressSender); ok &&
+ progressSender.SupportsFullOutputProgress() {
+ // Full output still starts the platform stream so users immediately see
+ // its thinking placeholder. No intermediate reasoning/tool content is
+ // sent; the placeholder is replaced only after QA completes.
+ if err := s.handleMessageFullOutput(
+ ctx, req.msg, req.session, req.agent, kbIDs, attachments, imageURLs,
+ progressSender, req.adapter, req.userKey, req.tenant,
+ ); err != nil {
+ logger.Errorf(ctx, "[IM] Full-output QA failed: %v", err)
}
return
}
+ } else if streamer, ok := req.adapter.(StreamSender); ok {
+ // Stream mode sends intermediate reasoning and answer updates.
+ if err := s.handleMessageStream(
+ ctx, req.msg, req.session, req.agent, kbIDs, attachments, imageURLs,
+ streamer, req.adapter, req.userKey, req.tenant,
+ ); err != nil {
+ logger.Errorf(ctx, "[IM] Stream QA failed: %v", err)
+ }
+ return
}
// Non-streaming fallback: collect full answer then send.
answer, err := s.runQA(ctx, req.session, req.msg.Content, req.agent, kbIDs, attachments, imageURLs, req.userKey, req.msg.Quote)
if err != nil {
logger.Errorf(ctx, "[IM] QA failed: %v, sending fallback reply", err)
- answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
+ answer = imQAFailureReply(err)
}
+ outCtx := imOutboundContext(ctx)
reply := &ReplyMessage{
- Content: formatIMOutboundAnswer(ctx, answer, req.tenant, s.defaultFileSvc, s.storageResolver),
+ Content: formatIMOutboundAnswerOrFallback(outCtx, answer, req.tenant, s.defaultFileSvc, s.storageResolver),
IsFinal: true,
}
- if err := req.adapter.SendReply(ctx, req.msg, reply); err != nil {
+ if err := req.adapter.SendReply(outCtx, req.msg, reply); err != nil {
logger.Errorf(ctx, "[IM] Send reply failed: %v", err)
return
}
@@ -1952,6 +2008,73 @@ func (s *Service) executeQARequest(req *qaRequest) {
req.channelID, req.msg.Platform, req.msg.UserID, len(answer))
}
+// handleMessageFullOutput keeps the channel's full-output semantics while
+// providing immediate progress feedback on adapters that support replaceable
+// stream messages. StartStream creates the platform placeholder; no intermediate
+// updates are sent, and the final answer replaces it exactly once.
+func (s *Service) handleMessageFullOutput(
+ ctx context.Context,
+ msg *IncomingMessage,
+ session *types.Session,
+ customAgent *types.CustomAgent,
+ kbIDs []string,
+ attachments types.MessageAttachments,
+ imageURLs []string,
+ streamer FullOutputProgressSender,
+ adapter Adapter,
+ userKey string,
+ tenant *types.Tenant,
+) error {
+ streamID, err := streamer.StartStream(ctx, msg)
+ if err != nil {
+ logger.Warnf(ctx, "[IM] StartStream failed for full output, falling back to plain reply: %v", err)
+ return s.fallbackNonStream(
+ ctx, msg, session, customAgent, kbIDs, attachments, imageURLs, adapter, userKey, tenant,
+ )
+ }
+
+ answer, qaErr := s.runQA(
+ ctx, session, msg.Content, customAgent, kbIDs, attachments, imageURLs, userKey, msg.Quote,
+ )
+ if qaErr != nil {
+ logger.Errorf(ctx, "[IM] Full-output QA failed: %v, sending fallback reply", qaErr)
+ answer = imQAFailureReply(qaErr)
+ }
+
+ // QA (and /stop) may have cancelled ctx. Platform updates must still run so
+ // the thinking card is replaced instead of hanging forever.
+ outCtx := imOutboundContext(ctx)
+ finalContent := formatIMOutboundAnswerOrFallback(outCtx, answer, tenant, s.defaultFileSvc, s.storageResolver)
+
+ finalizeErr := streamer.FinalizeStream(outCtx, msg, streamID, finalContent)
+ if finalizeErr != nil {
+ logger.Warnf(ctx, "[IM] FinalizeStream failed for full output: %v", finalizeErr)
+ }
+ endErr := streamer.EndStream(outCtx, msg, streamID)
+ if endErr != nil {
+ logger.Warnf(ctx, "[IM] EndStream failed for full output: %v", endErr)
+ }
+
+ // If the placeholder could not be replaced, send a plain final reply so the
+ // user still receives the answer instead of being left on "thinking".
+ var fallbackErr error
+ if finalizeErr != nil {
+ fallbackErr = adapter.SendReply(outCtx, msg, &ReplyMessage{Content: finalContent, IsFinal: true})
+ if fallbackErr != nil {
+ logger.Errorf(ctx, "[IM] Plain reply fallback after full-output finalize failure failed: %v", fallbackErr)
+ }
+ }
+
+ if finalizeErr == nil || fallbackErr == nil {
+ logger.Infof(
+ ctx, "[IM] Full-output reply sent: platform=%s user=%s answer_len=%d",
+ msg.Platform, msg.UserID, len(answer),
+ )
+ return nil
+ }
+ return errors.Join(finalizeErr, endErr, fallbackErr)
+}
+
// handleCommand executes a slash-command and sends the result back to the user.
// It also handles side effects (ActionClear, ActionStop).
func (s *Service) handleCommand(
@@ -2737,9 +2860,9 @@ loop:
finalDisplay := cleanIMContent(ctx, FormatIMFinalFromParts(parts), tenant, s.defaultFileSvc, s.storageResolver)
if noVisibleContent || finalDisplay == "" {
- fallback := "抱歉,我暂时无法回答这个问题。"
+ fallback := imNoAnswerFallback
if finalErr != nil {
- fallback = "抱歉,处理您的问题时出现了异常,请稍后再试。"
+ fallback = imQAFailureReply(finalErr)
}
finalDisplay = fallback
if answer == "" {
@@ -2761,7 +2884,7 @@ loop:
}
if answer == "" {
- answer = "抱歉,我暂时无法回答这个问题。"
+ answer = imNoAnswerFallback
}
assistantMsg.Content = answer
@@ -2779,10 +2902,14 @@ func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, s
answer, err := s.runQA(ctx, session, msg.Content, customAgent, kbIDs, attachments, imageURLs, userKey, msg.Quote)
if err != nil {
logger.Errorf(ctx, "[IM] QA fallback failed: %v", err)
- answer = "抱歉,处理您的问题时出现了异常,请稍后再试。"
+ answer = imQAFailureReply(err)
}
- return adapter.SendReply(ctx, msg, &ReplyMessage{Content: formatIMOutboundAnswer(ctx, answer, tenant, s.defaultFileSvc, s.storageResolver), IsFinal: true})
+ outCtx := imOutboundContext(ctx)
+ return adapter.SendReply(outCtx, msg, &ReplyMessage{
+ Content: formatIMOutboundAnswerOrFallback(outCtx, answer, tenant, s.defaultFileSvc, s.storageResolver),
+ IsFinal: true,
+ })
}
// runQA executes the WeKnora QA pipeline and returns the full answer text.
@@ -2940,7 +3067,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
}
case <-ctx.Done():
// Mark assistant message as completed to avoid dangling incomplete records
- assistantMsg.Content = "抱歉,回答已被取消。"
+ assistantMsg.Content = imCancelledFallback
assistantMsg.IsCompleted = true
// Use a fresh context since the original is cancelled
if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil {
@@ -2959,7 +3086,7 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin
return "", qaError
}
if answer == "" {
- answer = "抱歉,我暂时无法回答这个问题。"
+ answer = imNoAnswerFallback
}
if notice := s.buildIMMCPAuthNotice(ctx, authServices); notice != "" {
answer = appendIMAuthNotice(answer, notice)