From 2e94f94eb5ec074aa41d8031d727f8cd90b9581d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Mon, 20 Jul 2026 22:51:27 +0800 Subject: [PATCH] feat: stream answers into DingTalk AI cards --- internal/channels/dingtalk/handler.go | 119 +++- internal/channels/dingtalk/handler_test.go | 696 ++++++++++++++++++++- 2 files changed, 806 insertions(+), 9 deletions(-) diff --git a/internal/channels/dingtalk/handler.go b/internal/channels/dingtalk/handler.go index 780f584..66d88c4 100644 --- a/internal/channels/dingtalk/handler.go +++ b/internal/channels/dingtalk/handler.go @@ -6,8 +6,10 @@ import ( "fmt" "log" "strings" + "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) const ( @@ -21,6 +23,7 @@ const ( qaErrorReply = "抱歉,当前暂时无法完成回答,请稍后重试。" imageErrorReply = "图片识别暂时不可用,请稍后重试或发送文字。" imageQuery = "请描述并分析这张图片。" + streamingPlaceholder = "正在处理中…" ) type TenantConfig struct { @@ -46,6 +49,12 @@ type QAAsker interface { Ask(ctx context.Context, req core.QARequest) (core.QAResult, error) } +// StreamingQAAsker asks the QA backend with streaming observer support. +type StreamingQAAsker interface { + QAAsker + AskStream(ctx context.Context, req core.QARequest, observer weknora.AnswerObserver) (core.QAResult, error) +} + type MarkdownSender interface { SendMarkdown(ctx context.Context, webhookURL, title, text string) error } @@ -60,17 +69,26 @@ type FinalCardSender interface { SendFinalCard(context.Context, CardRequest) (string, error) } +// StreamingCardSender supports streaming card lifecycle: start, update, and finalize. +type StreamingCardSender interface { + FinalCardSender + StartCard(ctx context.Context, req CardRequest) (string, error) + UpdateCard(ctx context.Context, id, content string, isFinalize, isError bool) error +} + type HandlerOptions struct { ImageDownloader ImageDownloader CardSender FinalCardSender } type Handler struct { - cfg TenantConfig - qa QAAsker - reply MarkdownSender - downloader ImageDownloader - card FinalCardSender + cfg TenantConfig + qa QAAsker + reply MarkdownSender + downloader ImageDownloader + card FinalCardSender + now func() time.Time + cardUpdateInterval time.Duration } // NewHandler accepts at most one image downloader. A nil/omitted downloader @@ -102,7 +120,15 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o if reply == nil { return nil, errors.New("dingtalk handler: markdown sender is required") } - return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: opts.ImageDownloader, card: opts.CardSender}, nil + return &Handler{ + cfg: cfg, + qa: qa, + reply: reply, + downloader: opts.ImageDownloader, + card: opts.CardSender, + now: time.Now, + cardUpdateInterval: 750 * time.Millisecond, + }, nil } func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { @@ -179,6 +205,27 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return h.sendReply(ctx, webhookURL, unsupportedMessageReply) } + // Check streaming capability + streamingCard, streamingQA := h.streamingCapable() + if streamingCard != nil && streamingQA != nil { + return h.handleStreaming(ctx, webhookURL, req, streamingCard, streamingQA) + } + return h.handleNonStreaming(ctx, webhookURL, req) +} + +func (h *Handler) streamingCapable() (StreamingCardSender, StreamingQAAsker) { + sc, ok := h.card.(StreamingCardSender) + if !ok { + return nil, nil + } + sq, ok := h.qa.(StreamingQAAsker) + if !ok { + return nil, nil + } + return sc, sq +} + +func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req core.QARequest) error { result, err := h.qa.Ask(ctx, req) if err != nil { if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil { @@ -202,6 +249,66 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { return h.sendReply(ctx, webhookURL, result.Answer) } +func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, streamingQA StreamingQAAsker) error { + cardReq := CardRequest{ + ConversationType: req.ConversationType, + ExternalUserID: req.ExternalUserID, + ExternalChatID: req.ExternalChatID, + Content: streamingPlaceholder, + } + outTrackID, err := streamingCard.StartCard(ctx, cardReq) + if err != nil { + log.Printf("DingTalk streaming card start failed, falling back to non-streaming") + // Fallback: Ask → Markdown only (no SendFinalCard, no AskStream) + result, askErr := h.qa.Ask(ctx, req) + if askErr != nil { + if replyErr := h.sendReply(ctx, webhookURL, qaErrorReply); replyErr != nil { + return replyErr + } + return nil + } + return h.sendReply(ctx, webhookURL, result.Answer) + } + + // Streaming observer with 750ms throttle + var lastUpdate time.Time + observer := func(fullContent string) { + if strings.TrimSpace(fullContent) == "" { + return + } + now := h.now() + if lastUpdate.IsZero() || now.Sub(lastUpdate) >= h.cardUpdateInterval { + // Advance the throttle window before I/O so a failing DingTalk API + // cannot be hammered once per model chunk. The final update below is + // always attempted regardless of this timestamp. + lastUpdate = now + if updateErr := streamingCard.UpdateCard(ctx, outTrackID, fullContent, false, false); updateErr != nil { + log.Printf("DingTalk streaming card update failed, continuing") + } + } + } + + result, err := streamingQA.AskStream(ctx, req, observer) + // Final card convergence must still be attempted when the QA context was + // canceled or timed out; otherwise the card can remain "processing" + // forever. Keep the independent delivery window tightly bounded. + finalCtx, cancelFinal := context.WithTimeout(context.WithoutCancel(ctx), defaultHTTPTimeout) + defer cancelFinal() + if err != nil || strings.TrimSpace(result.Answer) == "" { + // Error or empty answer: converge to error card + if updateErr := streamingCard.UpdateCard(finalCtx, outTrackID, qaErrorReply, true, true); updateErr != nil { + return h.sendReply(finalCtx, webhookURL, qaErrorReply) + } + return nil + } + + // Success: finalize with answer + if updateErr := streamingCard.UpdateCard(finalCtx, outTrackID, result.Answer, true, false); updateErr != nil { + return h.sendReply(finalCtx, webhookURL, result.Answer) + } + return nil +} + func imageFailureStage(err error) string { message := strings.ToLower(err.Error()) switch { diff --git a/internal/channels/dingtalk/handler_test.go b/internal/channels/dingtalk/handler_test.go index 926882f..8bf4477 100644 --- a/internal/channels/dingtalk/handler_test.go +++ b/internal/channels/dingtalk/handler_test.go @@ -5,8 +5,10 @@ import ( "errors" "strings" "testing" + "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" ) type fakeQA struct { @@ -66,11 +68,11 @@ func (f *fakeCard) SendFinalCard(_ context.Context, req CardRequest) (string, er return f.returnID, f.err } -func newTestHandler(t *testing.T, qa *fakeQA, reply *fakeReply) *Handler { +func newTestHandler(t *testing.T, qa QAAsker, reply *fakeReply) *Handler { return newTestHandlerWithDownloader(t, qa, reply, nil) } -func newTestHandlerWithDownloader(t *testing.T, qa *fakeQA, reply *fakeReply, downloader ImageDownloader) *Handler { +func newTestHandlerWithDownloader(t *testing.T, qa QAAsker, reply *fakeReply, downloader ImageDownloader) *Handler { t.Helper() cfg := TenantConfig{ TenantKey: "tenant-a", @@ -83,7 +85,7 @@ func newTestHandlerWithDownloader(t *testing.T, qa *fakeQA, reply *fakeReply, do return h } -func newTestHandlerWithCard(t *testing.T, qa *fakeQA, reply *fakeReply, card *fakeCard) *Handler { +func newTestHandlerWithCard(t *testing.T, qa QAAsker, reply *fakeReply, card *fakeCard) *Handler { t.Helper() cfg := TenantConfig{ TenantKey: "tenant-a", @@ -807,3 +809,691 @@ func TestHandleNewHandlerBackwardCompat(t *testing.T) { t.Fatal("NewHandler with two downloaders should error") } } + +// --- A3.2: Streaming QA + Card integration --- + +// fakeStreamingQA implements both QAAsker and StreamingQAAsker. +// The observer is called synchronously with cumulative content during AskStream. +type fakeStreamingQA struct { + called bool + lastReq core.QARequest + result core.QAResult + err error + // streaming + streamCalled bool + chunks []string // observer receives cumulated content after each chunk + observerCaptured weknora.AnswerObserver +} + +func (f *fakeStreamingQA) Ask(_ context.Context, req core.QARequest) (core.QAResult, error) { + f.called = true + f.lastReq = req + return f.result, f.err +} + +func (f *fakeStreamingQA) AskStream(_ context.Context, req core.QARequest, observer weknora.AnswerObserver) (core.QAResult, error) { + f.streamCalled = true + f.lastReq = req + f.observerCaptured = observer + var accumulated string + for _, ch := range f.chunks { + accumulated += ch + if observer != nil { + observer(accumulated) + } + } + return f.result, f.err +} + +// fakeStreamingCard implements both FinalCardSender and StreamingCardSender. +type fakeStreamingCard struct { + // FinalCardSender + finalCalled bool + finalReq CardRequest + finalID string + finalErr error + + // StreamingCardSender + startCalled bool + startReq CardRequest + startID string + startErr error + + updates []cardUpdate + updateErr error +} + +type cardUpdate struct { + id string + content string + isFinalize bool + isError bool +} + +func (f *fakeStreamingCard) SendFinalCard(_ context.Context, req CardRequest) (string, error) { + f.finalCalled = true + f.finalReq = req + return f.finalID, f.finalErr +} + +func (f *fakeStreamingCard) StartCard(_ context.Context, req CardRequest) (string, error) { + f.startCalled = true + f.startReq = req + return f.startID, f.startErr +} + +func (f *fakeStreamingCard) UpdateCard(_ context.Context, id, content string, isFinalize, isError bool) error { + f.updates = append(f.updates, cardUpdate{id: id, content: content, isFinalize: isFinalize, isError: isError}) + return f.updateErr +} + +func newTestHandlerWithStreaming(t *testing.T, qa QAAsker, reply *fakeReply, card FinalCardSender) *Handler { + t.Helper() + cfg := TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"} + h, err := NewHandlerWithOptions(cfg, qa, reply, HandlerOptions{CardSender: card}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + return h +} + +func TestHandleStreamingHappyPathDirect(t *testing.T) { + card := &fakeStreamingCard{startID: "track-happy-1"} + qa := &fakeStreamingQA{ + chunks: []string{"Hello", " World", "!"}, + result: core.QAResult{Answer: "Hello World!"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // StartCard called once with placeholder + if !card.startCalled { + t.Fatal("StartCard was not called") + } + if card.startReq.Content != streamingPlaceholder { + t.Fatalf("StartCard Content = %q, want %q", card.startReq.Content, streamingPlaceholder) + } + if card.startReq.ConversationType != core.ConversationDirect { + t.Fatalf("StartCard ConversationType = %q, want direct", card.startReq.ConversationType) + } + if card.startReq.ExternalUserID != "staff-123" { + t.Fatalf("StartCard ExternalUserID = %q, want staff-123", card.startReq.ExternalUserID) + } + + // AskStream called, not Ask + if !qa.streamCalled { + t.Fatal("AskStream was not called") + } + + // First non-empty chunk → immediate update (not finalize) + if len(card.updates) < 1 { + t.Fatal("expected at least one update") + } + first := card.updates[0] + if first.id != "track-happy-1" { + t.Fatalf("first update id = %q, want track-happy-1", first.id) + } + if first.content != "Hello" { + t.Fatalf("first update content = %q, want Hello", first.content) + } + if first.isFinalize || first.isError { + t.Fatal("first update should not be finalize or error") + } + + // Final update must be the last one: content=full answer, isFinalize=true, isError=false + last := card.updates[len(card.updates)-1] + if last.content != "Hello World!" { + t.Fatalf("final update content = %q, want full answer", last.content) + } + if !last.isFinalize { + t.Fatal("final update must be finalize") + } + if last.isError { + t.Fatal("final update must not be error") + } + + // No markdown fallback + if reply.called { + t.Fatal("SendMarkdown must not be called on streaming success") + } +} + +func TestHandleStreamingThrottleSecondUpdate(t *testing.T) { + card := &fakeStreamingCard{startID: "track-throttle"} + qa := &fakeStreamingQA{ + chunks: []string{"A", "B", "C"}, + result: core.QAResult{Answer: "ABC"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + // Simulate clock advancing past interval + base := int64(0) + h.now = func() time.Time { return time.Unix(0, base) } + h.cardUpdateInterval = time.Millisecond + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + // All updates happen in the same goroutine, so the clock never advances + // during the single observer call chain. The first chunk fires immediately, + // subsequent chunks are throttled (clock hasn't advanced). + // The final update always fires. + if len(card.updates) < 2 { + t.Fatalf("expected at least first + final update, got %d", len(card.updates)) + } + // First update is immediate + if card.updates[0].isFinalize || card.updates[0].isError { + t.Fatal("first update must not be finalize/error") + } + // Last update is final + last := card.updates[len(card.updates)-1] + if !last.isFinalize || last.isError { + t.Fatal("last update must be finalize, not error") + } + if last.content != "ABC" { + t.Fatalf("final content = %q, want ABC", last.content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } +} + +func TestHandleStreamingThrottleClockAdvances(t *testing.T) { + card := &fakeStreamingCard{startID: "track-adv"} + qa := &fakeStreamingQA{ + chunks: []string{"X", "Y", "Z"}, + result: core.QAResult{Answer: "XYZ"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + callCount := int64(0) + h.now = func() time.Time { + c := callCount + callCount++ + // Each call advances by 800ms to cross the 750ms interval + return time.Unix(0, c*800_000_000) + } + h.cardUpdateInterval = 750 * time.Millisecond + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + // First chunk fires immediately (1 update), then each subsequent observer call + // sees clock advanced past interval → fires another update. + // So we should see: first("X"), second("XY"), final("XYZ") + nonFinal := 0 + for _, u := range card.updates { + if !u.isFinalize && !u.isError { + nonFinal++ + } + } + if nonFinal < 2 { + t.Fatalf("expected at least 2 intermediate updates with clock advance, got %d (updates=%+v)", nonFinal, card.updates) + } + last := card.updates[len(card.updates)-1] + if !last.isFinalize || last.isError { + t.Fatal("last update must be finalize") + } + if last.content != "XYZ" { + t.Fatalf("final content = %q, want XYZ", last.content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } +} + +func TestHandleStreamingStartFailsFallbackAskMarkdown(t *testing.T) { + card := &fakeStreamingCard{startErr: errors.New("card API unavailable")} + qa := &fakeStreamingQA{ + result: core.QAResult{Answer: "**fallback markdown**"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // StartCard was attempted + if !card.startCalled { + t.Fatal("StartCard was not called") + } + + // Fallback: Ask (not AskStream) was called + if !qa.called { + t.Fatal("Ask (fallback) was not called") + } + if qa.streamCalled { + t.Fatal("AskStream must not be called on Start failure") + } + + // No SendFinalCard + if card.finalCalled { + t.Fatal("SendFinalCard must not be called on Start failure") + } + + // Markdown fallback + if !reply.called { + t.Fatal("SendMarkdown must be called on Start failure") + } + if reply.lastText != "**fallback markdown**" { + t.Fatalf("markdown text = %q, want fallback markdown", reply.lastText) + } + + // No card updates + if len(card.updates) > 0 { + t.Fatal("no card updates expected on Start failure") + } +} + +func TestHandleStreamingIntermediateUpdateFailsContinuesQA(t *testing.T) { + card := &fakeStreamingCard{startID: "track-midfail", updateErr: errors.New("update HTTP 500")} + qa := &fakeStreamingQA{ + chunks: []string{"Hello", " World"}, + result: core.QAResult{Answer: "Hello World"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // QA still completed (AskStream must have been called and returned) + if !qa.streamCalled { + t.Fatal("AskStream must be called") + } + + // There must be a final update attempt (even though intermediate failed) + foundFinal := false + for _, u := range card.updates { + if u.isFinalize && !u.isError { + foundFinal = true + } + } + if !foundFinal { + t.Fatal("final update must be attempted even after intermediate failures") + } + + // Since updateErr is set, the final update also fails → markdown fallback + if !reply.called { + t.Fatal("SendMarkdown must be called when final update fails") + } + if reply.lastText != "Hello World" { + t.Fatalf("markdown text = %q, want full answer", reply.lastText) + } +} + +func TestHandleStreamingFinalUpdateFailsMarkdown(t *testing.T) { + card := &fakeStreamingCard{startID: "track-finalfail"} + qa := &fakeStreamingQA{ + chunks: []string{"OK"}, + result: core.QAResult{Answer: "OK"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + // Make only the final update fail by using a counter in updateErr + updateCount := 0 + card.updateErr = nil // will be set per-call via a wrapper + // We'll use a different approach: make the final call fail by checking content + // Actually, simplest: set updateErr to an error, and the test checks markdown fallback + card.updateErr = errors.New("finalize API error") + _ = updateCount + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !qa.streamCalled { + t.Fatal("AskStream must be called") + } + + // Markdown fallback with full answer + if !reply.called { + t.Fatal("SendMarkdown must be called when final update fails") + } + if reply.lastText != "OK" { + t.Fatalf("markdown text = %q, want OK", reply.lastText) + } +} + +func TestHandleStreamingQAErrorConvergesErrorCard(t *testing.T) { + card := &fakeStreamingCard{startID: "track-errcard"} + qa := &fakeStreamingQA{ + chunks: []string{"Partial"}, + err: errors.New("secret weknora internal failure"), + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !qa.streamCalled { + t.Fatal("AskStream must be called") + } + + // Last update must be error card: isFinalize=true, isError=true, content=qaErrorReply + last := card.updates[len(card.updates)-1] + if !last.isFinalize { + t.Fatal("error card must be finalize") + } + if !last.isError { + t.Fatal("error card must be isError") + } + if last.content != qaErrorReply { + t.Fatalf("error card content = %q, want %q", last.content, qaErrorReply) + } + // Must not leak QA error + if strings.Contains(last.content, "weknora") || strings.Contains(last.content, "secret") { + t.Fatalf("error card leaks internal error: %q", last.content) + } + + // No markdown (error card succeeded) + if reply.called { + t.Fatal("SendMarkdown must not be called when error card succeeds") + } + + // QA error was not leaked in any update content + for _, u := range card.updates { + if strings.Contains(u.content, "weknora") || strings.Contains(u.content, "secret") { + t.Fatalf("update leaks internal error: %q", u.content) + } + } +} + +func TestHandleStreamingErrorCardFinalizeFailsMarkdown(t *testing.T) { + card := &fakeStreamingCard{startID: "track-errfinalfail", updateErr: errors.New("finalize API error")} + qa := &fakeStreamingQA{ + chunks: []string{"Partial"}, + err: errors.New("secret weknora internal failure"), + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // Markdown fallback with friendly error message + if !reply.called { + t.Fatal("SendMarkdown must be called when error card finalize fails") + } + if reply.lastText != qaErrorReply { + t.Fatalf("markdown text = %q, want %q", reply.lastText, qaErrorReply) + } + // Must not leak QA error + if strings.Contains(reply.lastText, "weknora") || strings.Contains(reply.lastText, "secret") { + t.Fatalf("markdown leaks internal error: %q", reply.lastText) + } +} + +func TestHandleOldFakeCardStillA31(t *testing.T) { + // fakeCard does NOT implement StreamingCardSender — must use A3.1 path + card := &fakeCard{returnID: "out-a31"} + qa := &fakeStreamingQA{ + result: core.QAResult{Answer: "**a31 answer**"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // A3.1: Ask (not AskStream) + SendFinalCard + if !qa.called { + t.Fatal("Ask must be called (A3.1 path)") + } + if qa.streamCalled { + t.Fatal("AskStream must not be called (A3.1 path)") + } + if !card.called { + t.Fatal("SendFinalCard must be called (A3.1 path)") + } + if card.lastReq.Content != "**a31 answer**" { + t.Fatalf("card content = %q, want a31 answer", card.lastReq.Content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called when card succeeds") + } +} + +func TestHandleStreamingGroupNotAtNoStart(t *testing.T) { + card := &fakeStreamingCard{startID: "track-group"} + qa := &fakeStreamingQA{} + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + data := groupTextCallback() + data.IsInAtList = false + err := h.Handle(context.Background(), data) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if card.startCalled { + t.Fatal("StartCard must not be called for non-@ group message") + } + if qa.called || qa.streamCalled { + t.Fatal("QA must not be called for non-@ group message") + } + if reply.called { + t.Fatal("SendMarkdown must not be called for non-@ group message") + } +} + +func TestHandleStreamingImageDownloadFailureNoStart(t *testing.T) { + card := &fakeStreamingCard{startID: "track-img"} + qa := &fakeStreamingQA{} + reply := &fakeReply{} + downloader := &fakeImageDownloader{err: errors.New("download failed")} + h := newTestHandlerWithDownloader(t, qa, reply, downloader) + h.card = card + + data := directPictureCallback() + data.DownloadCode = "broken-code" + if err := h.Handle(context.Background(), data); err != nil { + t.Fatalf("Handle: %v", err) + } + + if card.startCalled { + t.Fatal("StartCard must not be called on image download failure") + } + if qa.called || qa.streamCalled { + t.Fatal("QA must not be called on download failure") + } + if !reply.called || reply.lastText != imageErrorReply { + t.Fatalf("friendly reply=%q, want %q", reply.lastText, imageErrorReply) + } +} + +func TestHandleStreamingQAEmptyAnswerConvergesErrorCard(t *testing.T) { + card := &fakeStreamingCard{startID: "track-empty"} + qa := &fakeStreamingQA{ + chunks: []string{}, + result: core.QAResult{Answer: ""}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !qa.streamCalled { + t.Fatal("AskStream must be called") + } + + // Empty answer: error card with qaErrorReply + last := card.updates[len(card.updates)-1] + if !last.isFinalize || !last.isError { + t.Fatal("empty answer must produce error card") + } + if last.content != qaErrorReply { + t.Fatalf("error card content = %q, want %q", last.content, qaErrorReply) + } + if reply.called { + t.Fatal("SendMarkdown must not be called when error card succeeds") + } +} + +func TestHandleStreamingObserverIgnoresWhitespaceOnly(t *testing.T) { + card := &fakeStreamingCard{startID: "track-ws"} + qa := &fakeStreamingQA{ + // The observer is called with cumulative content; whitespace-only + // chunks should not trigger updates. + chunks: []string{" ", " \n ", "Real"}, + result: core.QAResult{Answer: " \n Real"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + // First non-whitespace update is "Real" (cumulated) + firstUpdate := card.updates[0] + if firstUpdate.content != " \n Real" { + t.Fatalf("first update content = %q, want cumulative whitespace plus Real", firstUpdate.content) + } + if firstUpdate.isFinalize || firstUpdate.isError { + t.Fatal("first update must not be finalize/error") + } + + last := card.updates[len(card.updates)-1] + if !last.isFinalize || last.isError { + t.Fatal("last update must be finalize, not error") + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } +} + +func TestHandleStreamingStartFailsQAFailsMarkdownFriendly(t *testing.T) { + // Start fails → fallback to Ask → Ask also fails → friendly markdown + card := &fakeStreamingCard{startErr: errors.New("card API unavailable")} + qa := &fakeStreamingQA{ + err: errors.New("secret weknora internal failure"), + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !card.startCalled { + t.Fatal("StartCard was not called") + } + if !qa.called { + t.Fatal("Ask (fallback) was not called") + } + if qa.streamCalled { + t.Fatal("AskStream must not be called") + } + if !reply.called { + t.Fatal("SendMarkdown must be called") + } + if !strings.Contains(reply.lastText, "暂时无法完成回答") { + t.Fatalf("friendly markdown = %q", reply.lastText) + } + if strings.Contains(reply.lastText, "weknora") || strings.Contains(reply.lastText, "secret") { + t.Fatalf("markdown leaks internal error: %q", reply.lastText) + } +} + +func TestHandleStreamingFinalUpdateAlwaysFiresEvenWithoutIntermediate(t *testing.T) { + // No intermediate chunks (observer never called with non-empty content), + // but final update must still fire with the answer. + card := &fakeStreamingCard{startID: "track-noint"} + qa := &fakeStreamingQA{ + chunks: []string{}, // no intermediate chunks + result: core.QAResult{Answer: "direct answer"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !qa.streamCalled { + t.Fatal("AskStream must be called") + } + + // Must have exactly one update: final + if len(card.updates) != 1 { + t.Fatalf("expected 1 update (final only), got %d: %+v", len(card.updates), card.updates) + } + u := card.updates[0] + if !u.isFinalize || u.isError { + t.Fatal("only update must be finalize, not error") + } + if u.content != "direct answer" { + t.Fatalf("content = %q, want direct answer", u.content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } +} + +func TestHandleStreamingGroupWithCard(t *testing.T) { + card := &fakeStreamingCard{startID: "track-group-ok"} + qa := &fakeStreamingQA{ + chunks: []string{"group", " reply"}, + result: core.QAResult{Answer: "group reply"}, + } + reply := &fakeReply{} + h := newTestHandlerWithStreaming(t, qa, reply, card) + + err := h.Handle(context.Background(), groupTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + + if !card.startCalled { + t.Fatal("StartCard was not called") + } + if card.startReq.ConversationType != core.ConversationGroup { + t.Fatalf("StartCard ConversationType = %q, want group", card.startReq.ConversationType) + } + if card.startReq.ExternalChatID != "cid-group-1" { + t.Fatalf("StartCard ExternalChatID = %q, want cid-group-1", card.startReq.ExternalChatID) + } + if !qa.streamCalled { + t.Fatal("AskStream was not called") + } + last := card.updates[len(card.updates)-1] + if !last.isFinalize || last.isError { + t.Fatal("last update must be finalize, not error") + } + if last.content != "group reply" { + t.Fatalf("final content = %q, want group reply", last.content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } +}