From 341b7e39909acd961a6412f273918c845e1392e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Sun, 20 Sep 2026 10:48:36 +0800 Subject: [PATCH] feat(dingtalk): deliver the finished answer as a single card DINGTALK_CARD_PARTIAL_UPDATES selects how much of an answer is written into the card while it is still being produced: partial (default, unset) - placeholder card plus throttled partial answer and progress frames, then the final update final - placeholder card, no partial frames at all; the finished answer lands in the single final update direct - no placeholder card; one card with the answer Both non-default modes drop the 500ms redraw pump for the turn, so the card only ever shows content that is actually final. handleNonStreaming and the two new modes share one delivery helper, and the markdown fallback keeps the existing behaviour when the card cannot be delivered. --- cmd/dobotai/card_stream.go | 24 +++ cmd/dobotai/card_stream_test.go | 31 +++ cmd/dobotai/main.go | 1 + .../channels/dingtalk/card_delivery_mode.go | 52 +++++ .../dingtalk/card_delivery_mode_test.go | 53 +++++ .../dingtalk/card_partial_updates_test.go | 186 ++++++++++++++++++ internal/channels/dingtalk/handler.go | 83 +++++++- 7 files changed, 422 insertions(+), 8 deletions(-) create mode 100644 cmd/dobotai/card_stream.go create mode 100644 cmd/dobotai/card_stream_test.go create mode 100644 internal/channels/dingtalk/card_delivery_mode.go create mode 100644 internal/channels/dingtalk/card_delivery_mode_test.go create mode 100644 internal/channels/dingtalk/card_partial_updates_test.go diff --git a/cmd/dobotai/card_stream.go b/cmd/dobotai/card_stream.go new file mode 100644 index 0000000..22c1b32 --- /dev/null +++ b/cmd/dobotai/card_stream.go @@ -0,0 +1,24 @@ +package main + +import ( + "log" + "os" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" +) + +// cardPartialUpdatesMode returns the configured card delivery mode for a +// finished answer (see dingtalk.CardPartialUpdatesMode): +// +// unset / on / partial → placeholder card + throttled partial frames (historical) +// off / final → placeholder card, and only the finished answer +// direct → no placeholder card; one card with the finished answer +// +// The default stays "partial" so an environment without the variable behaves +// exactly as before; DINGTALK_CARD_PARTIAL_UPDATES selects the other modes. The +// resolved mode is logged so the startup log always states what is running. +func cardPartialUpdatesMode() dingtalk.CardPartialUpdatesMode { + mode := dingtalk.ParseCardPartialUpdatesMode(os.Getenv("DINGTALK_CARD_PARTIAL_UPDATES")) + log.Printf("DingTalk card partial updates mode=%s", mode) + return mode +} diff --git a/cmd/dobotai/card_stream_test.go b/cmd/dobotai/card_stream_test.go new file mode 100644 index 0000000..562c0de --- /dev/null +++ b/cmd/dobotai/card_stream_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" +) + +func TestCardPartialUpdatesMode(t *testing.T) { + tests := []struct { + name string + raw string + want dingtalk.CardPartialUpdatesMode + }{ + {"unset keeps streaming", "", dingtalk.CardPartialUpdatesPartial}, + {"on keeps streaming", "on", dingtalk.CardPartialUpdatesPartial}, + {"partial keeps streaming", "PARTIAL", dingtalk.CardPartialUpdatesPartial}, + {"unknown keeps streaming", "hammer", dingtalk.CardPartialUpdatesPartial}, + {"final", " final ", dingtalk.CardPartialUpdatesFinal}, + {"off maps to final", "off", dingtalk.CardPartialUpdatesFinal}, + {"direct", "direct", dingtalk.CardPartialUpdatesDirect}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("DINGTALK_CARD_PARTIAL_UPDATES", tt.raw) + if got := cardPartialUpdatesMode(); got != tt.want { + t.Fatalf("cardPartialUpdatesMode(%q)=%q want %q", tt.raw, got, tt.want) + } + }) + } +} diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 8d24183..fc379f9 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -325,6 +325,7 @@ func main() { OutboundRewriteTimeout: outboundImages.rewriteTimeout, WideTableGrouping: cardWideTableGroupingMode(), + PartialUpdates: cardPartialUpdatesMode(), }, ) if err != nil { diff --git a/internal/channels/dingtalk/card_delivery_mode.go b/internal/channels/dingtalk/card_delivery_mode.go new file mode 100644 index 0000000..3c517c2 --- /dev/null +++ b/internal/channels/dingtalk/card_delivery_mode.go @@ -0,0 +1,52 @@ +package dingtalk + +import "strings" + +// CardPartialUpdatesMode selects how much of an answer is written into the card +// while the answer is still being produced. +// +// partial (default) → the card is created with the "processing" placeholder and +// partial answer/progress frames are pushed as they arrive, +// throttled by cardUpdateInterval (historical behaviour) +// final → same placeholder card, but no partial frame at all: the +// finished answer lands in the single final update +// direct → no placeholder card; one card is created carrying the +// finished answer +// +// "final" and "direct" remove the redraw loop (and with it the frozen card and +// the end-of-answer jump) at the cost of not showing interim progress. +type CardPartialUpdatesMode string + +const ( + CardPartialUpdatesPartial CardPartialUpdatesMode = "partial" + CardPartialUpdatesFinal CardPartialUpdatesMode = "final" + CardPartialUpdatesDirect CardPartialUpdatesMode = "direct" +) + +// ParseCardPartialUpdatesMode maps DINGTALK_CARD_PARTIAL_UPDATES onto a mode. +// Unset or unrecognised values keep the historical partial streaming so an +// environment without the variable renders exactly as before. +func ParseCardPartialUpdatesMode(raw string) CardPartialUpdatesMode { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "final", "off", "0", "false", "no", "answer", "answer_only": + return CardPartialUpdatesFinal + case "direct", "once", "single": + return CardPartialUpdatesDirect + default: + return CardPartialUpdatesPartial + } +} + +// streamsPartialFrames reports whether partial answer/progress frames may be +// pushed into the card. Only the explicit "final" and "direct" modes suppress +// them, so an unset or unknown mode keeps the historical streaming. +func (m CardPartialUpdatesMode) streamsPartialFrames() bool { + return m != CardPartialUpdatesFinal && m != CardPartialUpdatesDirect +} + +// placeholderCardRequested reports whether the card is created up front with the +// "processing" placeholder. Only "direct" waits for the finished answer before +// creating the card. +func (m CardPartialUpdatesMode) placeholderCardRequested() bool { + return m != CardPartialUpdatesDirect +} diff --git a/internal/channels/dingtalk/card_delivery_mode_test.go b/internal/channels/dingtalk/card_delivery_mode_test.go new file mode 100644 index 0000000..81add9a --- /dev/null +++ b/internal/channels/dingtalk/card_delivery_mode_test.go @@ -0,0 +1,53 @@ +package dingtalk + +import "testing" + +func TestParseCardPartialUpdatesMode(t *testing.T) { + tests := []struct { + raw string + want CardPartialUpdatesMode + }{ + {"", CardPartialUpdatesPartial}, + {"on", CardPartialUpdatesPartial}, + {"PARTIAL", CardPartialUpdatesPartial}, + {"sometimes", CardPartialUpdatesPartial}, + {"final", CardPartialUpdatesFinal}, + {" FINAL ", CardPartialUpdatesFinal}, + {"off", CardPartialUpdatesFinal}, + {"0", CardPartialUpdatesFinal}, + {"false", CardPartialUpdatesFinal}, + {"no", CardPartialUpdatesFinal}, + {"answer", CardPartialUpdatesFinal}, + {"answer_only", CardPartialUpdatesFinal}, + {"direct", CardPartialUpdatesDirect}, + {"Single", CardPartialUpdatesDirect}, + {"once", CardPartialUpdatesDirect}, + } + for _, tt := range tests { + if got := ParseCardPartialUpdatesMode(tt.raw); got != tt.want { + t.Fatalf("ParseCardPartialUpdatesMode(%q)=%q want %q", tt.raw, got, tt.want) + } + } +} + +func TestCardPartialUpdatesModeFramesAndPlaceholder(t *testing.T) { + tests := []struct { + mode CardPartialUpdatesMode + streamsPartials bool + placeholderIssued bool + }{ + {CardPartialUpdatesPartial, true, true}, + {CardPartialUpdatesFinal, false, true}, + {CardPartialUpdatesDirect, false, false}, + // An unset mode must keep the historical streaming behaviour. + {"", true, true}, + } + for _, tt := range tests { + if got := tt.mode.streamsPartialFrames(); got != tt.streamsPartials { + t.Fatalf("mode=%q streamsPartialFrames=%v want %v", tt.mode, got, tt.streamsPartials) + } + if got := tt.mode.placeholderCardRequested(); got != tt.placeholderIssued { + t.Fatalf("mode=%q placeholderCardRequested=%v want %v", tt.mode, got, tt.placeholderIssued) + } + } +} diff --git a/internal/channels/dingtalk/card_partial_updates_test.go b/internal/channels/dingtalk/card_partial_updates_test.go new file mode 100644 index 0000000..05027ba --- /dev/null +++ b/internal/channels/dingtalk/card_partial_updates_test.go @@ -0,0 +1,186 @@ +package dingtalk + +import ( + "context" + "errors" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/weknora" +) + +// pacedEventQA replays the answer events of a real turn and sleeps between them +// so the asynchronous 500ms frame pump gets a chance to fire. It is the +// sensitivity control for the frame assertions below: with mode "partial" the +// very same fixture must produce partial frames. +type pacedEventQA struct { + fakeStreamingQA + events []weknora.StreamEvent + hold time.Duration + eventsCalled bool +} + +func (f *pacedEventQA) AskEvents(_ context.Context, req core.QARequest, observer weknora.StreamObserver) (core.QAResult, error) { + f.eventsCalled = true + f.lastReq = req + for _, event := range f.events { + if observer != nil { + observer(event) + } + time.Sleep(f.hold) + } + return f.result, f.err +} + +func TestStreamingModesControlPartialCardFrames(t *testing.T) { + rawAnswer := "最终答案内容" + tests := []struct { + name string + mode CardPartialUpdatesMode + wantPartials bool + }{ + {"partial streams frames", CardPartialUpdatesPartial, true}, + {"final suppresses frames", CardPartialUpdatesFinal, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + card := &fakeStreamingCard{startID: "track-mode"} + qa := &pacedEventQA{ + fakeStreamingQA: fakeStreamingQA{result: core.QAResult{Answer: rawAnswer}}, + events: []weknora.StreamEvent{ + {ResponseType: "tool_call", ToolName: "knowledge_search"}, + {ResponseType: "references", ReferenceCount: 2}, + {ResponseType: "answer", FullAnswer: "最终"}, + {ResponseType: "answer", FullAnswer: rawAnswer, Done: true}, + }, + hold: 5 * time.Millisecond, + } + reply := &fakeReply{} + h, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, reply, HandlerOptions{CardSender: card, PartialUpdates: tt.mode}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + h.cardUpdateInterval = time.Millisecond + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatalf("Handle: %v", err) + } + + if !card.startCalled || card.startReq.Content != streamingPlaceholder { + t.Fatalf("placeholder card must be created: called=%v content=%q", card.startCalled, card.startReq.Content) + } + var partials, finals int + for _, update := range card.updates { + if update.isFinalize { + finals++ + continue + } + partials++ + } + if got := partials > 0; got != tt.wantPartials { + t.Fatalf("partial frames=%d want frames=%v updates=%+v", partials, tt.wantPartials, card.updates) + } + if finals != 1 { + t.Fatalf("final updates=%d want 1 updates=%+v", finals, card.updates) + } + last := card.updates[len(card.updates)-1] + if !last.isFinalize || last.isError || last.content != rawAnswer { + t.Fatalf("final update=%+v want the complete answer", last) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } + }) + } +} + +func TestDirectModeDeliversOneCardWithoutPlaceholder(t *testing.T) { + rawAnswer := "直接输出答案" + card := &fakeStreamingCard{finalID: "track-direct"} + qa := &fakeEventQA{ + fakeStreamingQA: fakeStreamingQA{result: core.QAResult{Answer: rawAnswer, TurnID: "turn-1", AnswerMessageID: "msg-1"}}, + events: []weknora.StreamEvent{ + {ResponseType: "tool_call", ToolName: "query_understand"}, + {ResponseType: "answer", FullAnswer: "直接"}, + {ResponseType: "answer", FullAnswer: rawAnswer, Done: true}, + }, + } + reply := &fakeReply{} + h, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, reply, HandlerOptions{CardSender: card, PartialUpdates: CardPartialUpdatesDirect}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + h.cardUpdateInterval = time.Millisecond + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatalf("Handle: %v", err) + } + + if card.startCalled { + t.Fatalf("no placeholder card may be created in direct mode: %q", card.startReq.Content) + } + if len(card.updates) != 0 { + t.Fatalf("no card update may be sent before the answer is complete: %+v", card.updates) + } + if !card.finalCalled || card.finalReq.Content != rawAnswer { + t.Fatalf("final card=%v content=%q want %q", card.finalCalled, card.finalReq.Content, rawAnswer) + } + if reply.called { + t.Fatal("SendMarkdown must not be called") + } + if len(qa.deliveries) == 0 || qa.deliveries[len(qa.deliveries)-1].DeliveryMethod != core.DeliveryMethodCard { + t.Fatalf("delivery audit=%+v", qa.deliveries) + } +} + +func TestDirectModeFallsBackToMarkdownWhenTheAnswerFails(t *testing.T) { + card := &fakeStreamingCard{finalID: "track-direct-error"} + qa := &fakeEventQA{fakeStreamingQA: fakeStreamingQA{err: errors.New("weknora down")}} + reply := &fakeReply{} + h, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, reply, HandlerOptions{CardSender: card, PartialUpdates: CardPartialUpdatesDirect}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatalf("Handle: %v", err) + } + if card.finalCalled || card.startCalled { + t.Fatal("a failed answer must not create a card") + } + if !reply.called || reply.lastText != qaErrorReply { + t.Fatalf("markdown fallback: called=%v text=%q", reply.called, reply.lastText) + } +} + +func TestDirectModeAppliesToTheStreamingAnswerPath(t *testing.T) { + rawAnswer := "流式接口直接输出" + card := &fakeStreamingCard{finalID: "track-direct-stream"} + qa := &fakeStreamingQA{chunks: []string{"流式", "接口直接输出"}, result: core.QAResult{Answer: rawAnswer}} + reply := &fakeReply{} + h, err := NewHandlerWithOptions( + TenantConfig{TenantKey: "tenant-a", Channel: "dingtalk"}, + qa, reply, HandlerOptions{CardSender: card, PartialUpdates: CardPartialUpdatesDirect}) + if err != nil { + t.Fatalf("NewHandlerWithOptions: %v", err) + } + if err := h.Handle(context.Background(), directTextCallback()); err != nil { + t.Fatalf("Handle: %v", err) + } + if !qa.streamCalled { + t.Fatal("the streaming asker must be used") + } + if qa.observerCaptured == nil { + t.Fatal("the streaming asker must still receive an observer") + } + if card.startCalled || len(card.updates) != 0 { + t.Fatalf("no placeholder/partial card may be created: start=%v updates=%+v", card.startCalled, card.updates) + } + if !card.finalCalled || card.finalReq.Content != rawAnswer { + t.Fatalf("final card=%v content=%q", card.finalCalled, card.finalReq.Content) + } +} diff --git a/internal/channels/dingtalk/handler.go b/internal/channels/dingtalk/handler.go index fdf257b..a2a0298 100644 --- a/internal/channels/dingtalk/handler.go +++ b/internal/channels/dingtalk/handler.go @@ -176,6 +176,10 @@ type HandlerOptions struct { // table on streaming frames so a forming table never freezes the card. // See tableGroupingForMode. WideTableGrouping string + // PartialUpdates selects whether the answer is streamed into the card. + // Empty (or an unknown value) keeps the historical partial streaming; see + // CardPartialUpdatesMode. + PartialUpdates CardPartialUpdatesMode } type Handler struct { @@ -206,6 +210,9 @@ type Handler struct { // groupAllTablesPartial groups every table on streaming frames (mode // "smooth"): the card keeps growing while a table is still forming. groupAllTablesPartial bool + // partialUpdates decides whether the answer is streamed into the card at + // all; see CardPartialUpdatesMode. + partialUpdates CardPartialUpdatesMode } // NewHandler accepts at most one image downloader. A nil/omitted downloader @@ -260,6 +267,7 @@ func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, o groupTablesPartial: groupPartial, groupTablesFinal: groupFinal, groupAllTablesPartial: groupAllPartial, + partialUpdates: opts.PartialUpdates, }, nil } @@ -470,22 +478,37 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req if result.Replayed && result.DeliveryStatus == core.DeliverySent { return nil } - content := h.rewriteOutboundContent(ctx, result.Answer) + return h.deliverAnswerCardDirect(ctx, webhookURL, req, result) +} + +// deliverAnswerCardDirect delivers a finished answer as a single card built from +// the final content (no partial frames), falling back to the markdown reply when +// the card cannot be delivered. The delivery gets a fresh deadline so a long +// answer whose QA context already expired still reaches the user. +func (h *Handler) deliverAnswerCardDirect(ctx context.Context, webhookURL string, req core.QARequest, result core.QAResult) error { + timeout := h.finalDeliveryTimeout + if timeout <= 0 { + timeout = defaultHTTPTimeout + } + deliverCtx, cancelDeliver := context.WithTimeout(context.WithoutCancel(ctx), timeout) + defer cancelDeliver() + + content := h.rewriteOutboundContent(deliverCtx, result.Answer) if h.card != nil { cardReq := CardRequest{ ConversationType: req.ConversationType, ExternalUserID: req.ExternalUserID, ExternalChatID: req.ExternalChatID, - Content: h.rewriteCardImages(ctx, content, true), + Content: h.rewriteCardImages(deliverCtx, content, true), } - if outTrackID, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil { + if outTrackID, cardErr := h.card.SendFinalCard(deliverCtx, cardReq); cardErr == nil { h.recordDelivery(ctx, result, core.DeliverySent, core.DeliveryMethodCard, outTrackID, "") return nil } log.Printf("DingTalk card delivery failed, falling back to markdown") } - if err := h.sendReply(ctx, webhookURL, content); err != nil { + if err := h.sendReply(deliverCtx, webhookURL, content); err != nil { h.recordDelivery(ctx, result, core.DeliveryFailed, "", "", core.DeliveryFailureChannelDelivery) return err } @@ -494,6 +517,20 @@ func (h *Handler) handleNonStreaming(ctx context.Context, webhookURL string, req } func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, streamingQA StreamingQAAsker) error { + if !h.partialUpdates.placeholderCardRequested() { + // Mode "direct": no placeholder card and no partial frames. The answer + // is asked for first and delivered as one finished card. + result, err := streamingQA.AskStream(ctx, req, func(string) {}) + if err != nil || strings.TrimSpace(result.Answer) == "" { + logQAFailure("stream_direct", errOrEmptyAnswer(err, result.Answer)) + return h.sendReply(ctx, webhookURL, qaErrorReply) + } + if result.Replayed && result.DeliveryStatus == core.DeliverySent { + return nil + } + return h.deliverAnswerCardDirect(ctx, webhookURL, req, result) + } + cardReq := CardRequest{ ConversationType: req.ConversationType, ExternalUserID: req.ExternalUserID, @@ -529,6 +566,11 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co var lastPartialContent string feed := reasoningmode.NewPartialFeed(req.ReasoningExecution) observer := func(fullContent string) { + if !h.partialUpdates.streamsPartialFrames() { + // Mode "final": the finished answer is the only card content, so the + // throttle and the frame itself are skipped. + return + } visible := feed.OnAnswer(fullContent) if strings.TrimSpace(visible) == "" { return @@ -561,6 +603,20 @@ func (h *Handler) handleStreaming(ctx context.Context, webhookURL string, req co } func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, req core.QARequest, streamingCard StreamingCardSender, eventQA EventQAAsker) error { + if !h.partialUpdates.placeholderCardRequested() { + // Mode "direct": no placeholder card and no partial frames. The answer + // is asked for first and delivered as one finished card. + result, err := eventQA.AskEvents(ctx, req, func(weknora.StreamEvent) {}) + if err != nil || strings.TrimSpace(result.Answer) == "" { + logQAFailure("event_direct", errOrEmptyAnswer(err, result.Answer)) + return h.sendReply(ctx, webhookURL, qaErrorReply) + } + if result.Replayed && result.DeliveryStatus == core.DeliverySent { + return nil + } + return h.deliverAnswerCardDirect(ctx, webhookURL, req, result) + } + cardReq := CardRequest{ ConversationType: req.ConversationType, ExternalUserID: req.ExternalUserID, @@ -587,11 +643,20 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r return nil } - pump := newCardUpdatePump(ctx, h.cardUpdateInterval, func(updateCtx context.Context, content string) error { - return streamingCard.UpdateCard(updateCtx, outTrackID, content, false, false) - }) + var pump *cardUpdatePump + if h.partialUpdates.streamsPartialFrames() { + pump = newCardUpdatePump(ctx, h.cardUpdateInterval, func(updateCtx context.Context, content string) error { + return streamingCard.UpdateCard(updateCtx, outTrackID, content, false, false) + }) + } feed := reasoningmode.NewPartialFeed(req.ReasoningExecution) result, err := eventQA.AskEvents(ctx, req, func(event weknora.StreamEvent) { + if pump == nil { + // Mode "final": the finished answer is the only card content, so the + // partial frames and the progress lines are dropped instead of being + // drawn on every model chunk. + return + } if event.ResponseType == "answer" { visible := feed.OnAnswer(event.FullAnswer) if strings.TrimSpace(visible) == "" { @@ -618,7 +683,9 @@ func (h *Handler) handleEventStreaming(ctx context.Context, webhookURL string, r }) // Stop and drain the asynchronous worker before the synchronous final update // so no stale progress/partial answer can overwrite the terminal card state. - pump.Stop() + if pump != nil { + pump.Stop() + } if err != nil || strings.TrimSpace(result.Answer) == "" { logQAFailure("event_streaming", errOrEmptyAnswer(err, result.Answer))