From c4a942a1ac927d57e756f93f34fe0b351b6ebde2 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 21:28:21 +0800 Subject: [PATCH] feat: deliver final answers as DingTalk AI cards --- .env.example | 5 + cmd/dobotai/main.go | 12 +- internal/channels/dingtalk/handler.go | 48 ++++- internal/channels/dingtalk/handler_test.go | 204 +++++++++++++++++++++ 4 files changed, 259 insertions(+), 10 deletions(-) diff --git a/.env.example b/.env.example index 522c8a3..974a3ec 100644 --- a/.env.example +++ b/.env.example @@ -15,5 +15,10 @@ DINGTALK_CLIENT_SECRET= # Tenant key this DingTalk ingress serves (matches tenant_key used by QA). DOBOTAI_TENANT_KEY= +# Optional DingTalk AI card template ID. Leave empty to use markdown-only replies. +# When set, a successful QA answer will be delivered as an AI card; markdown +# is only sent as a fallback when card delivery fails. Never commit real values. +DINGTALK_CARD_TEMPLATE_ID= + # Independent DobotAI PostgreSQL; never point this at WeKnora's database DATABASE_URL=postgres://dobotai:replace-me@127.0.0.1:5432/dobotai?sslmode=disable diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 3b3a84d..a5f40dc 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -72,11 +72,19 @@ func main() { if err != nil { log.Fatal(err) } - handler, err := dingtalk.NewHandler( + var cardSender dingtalk.FinalCardSender + if cardTemplateID := strings.TrimSpace(os.Getenv("DINGTALK_CARD_TEMPLATE_ID")); cardTemplateID != "" { + cs, err := dingtalk.NewCardSender(dingCfg.ClientID, dingCfg.ClientSecret, cardTemplateID, nil) + if err != nil { + log.Fatalf("DingTalk card sender init failed: %v", err) + } + cardSender = cs + } + handler, err := dingtalk.NewHandlerWithOptions( dingtalk.TenantConfig{TenantKey: dingCfg.TenantKey, Channel: "dingtalk"}, qaService, sender, - downloader, + dingtalk.HandlerOptions{ImageDownloader: downloader, CardSender: cardSender}, ) if err != nil { log.Fatal(err) diff --git a/internal/channels/dingtalk/handler.go b/internal/channels/dingtalk/handler.go index d895dfb..780f584 100644 --- a/internal/channels/dingtalk/handler.go +++ b/internal/channels/dingtalk/handler.go @@ -54,16 +54,42 @@ type ImageDownloader interface { Download(ctx context.Context, downloadCode string) (core.ImageInput, error) } +// FinalCardSender sends an AI card as the final reply. Implementations must +// not log err, outTrackID, or content at any level. +type FinalCardSender interface { + SendFinalCard(context.Context, CardRequest) (string, error) +} + +type HandlerOptions struct { + ImageDownloader ImageDownloader + CardSender FinalCardSender +} + type Handler struct { cfg TenantConfig qa QAAsker reply MarkdownSender downloader ImageDownloader + card FinalCardSender } // NewHandler accepts at most one image downloader. A nil/omitted downloader // keeps text ingress available while picture messages fail closed. func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender, downloaders ...ImageDownloader) (*Handler, error) { + var downloader ImageDownloader + if len(downloaders) > 1 { + return nil, errors.New("dingtalk handler: at most one image downloader is allowed") + } + if len(downloaders) == 1 { + downloader = downloaders[0] + } + return NewHandlerWithOptions(cfg, qa, reply, HandlerOptions{ImageDownloader: downloader}) +} + +// NewHandlerWithOptions creates a Handler with an optional image downloader +// and optional card sender. Passing nil for either option is equivalent to +// omitting the feature. +func NewHandlerWithOptions(cfg TenantConfig, qa QAAsker, reply MarkdownSender, opts HandlerOptions) (*Handler, error) { if strings.TrimSpace(cfg.TenantKey) == "" { return nil, errors.New("dingtalk handler: tenant key is required") } @@ -76,14 +102,7 @@ func NewHandler(cfg TenantConfig, qa QAAsker, reply MarkdownSender, downloaders if reply == nil { return nil, errors.New("dingtalk handler: markdown sender is required") } - if len(downloaders) > 1 { - return nil, errors.New("dingtalk handler: at most one image downloader is allowed") - } - var downloader ImageDownloader - if len(downloaders) == 1 { - downloader = downloaders[0] - } - return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: downloader}, nil + return &Handler{cfg: cfg, qa: qa, reply: reply, downloader: opts.ImageDownloader, card: opts.CardSender}, nil } func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { @@ -167,6 +186,19 @@ func (h *Handler) Handle(ctx context.Context, cb BotCallback) error { } return nil } + + if h.card != nil { + cardReq := CardRequest{ + ConversationType: req.ConversationType, + ExternalUserID: req.ExternalUserID, + ExternalChatID: req.ExternalChatID, + Content: result.Answer, + } + if _, cardErr := h.card.SendFinalCard(ctx, cardReq); cardErr == nil { + return nil + } + log.Printf("DingTalk card delivery failed, falling back to markdown") + } return h.sendReply(ctx, webhookURL, result.Answer) } diff --git a/internal/channels/dingtalk/handler_test.go b/internal/channels/dingtalk/handler_test.go index 85d795d..926882f 100644 --- a/internal/channels/dingtalk/handler_test.go +++ b/internal/channels/dingtalk/handler_test.go @@ -51,6 +51,21 @@ func (f *fakeImageDownloader) Download(_ context.Context, code string) (core.Ima return f.image, f.err } +// fakeCard implements FinalCardSender for tests. It must not log err, outTrackID, +// or content. All fields are test-observable and never leak sensitive values. +type fakeCard struct { + called bool + lastReq CardRequest + returnID string + err error +} + +func (f *fakeCard) SendFinalCard(_ context.Context, req CardRequest) (string, error) { + f.called = true + f.lastReq = req + return f.returnID, f.err +} + func newTestHandler(t *testing.T, qa *fakeQA, reply *fakeReply) *Handler { return newTestHandlerWithDownloader(t, qa, reply, nil) } @@ -68,6 +83,19 @@ func newTestHandlerWithDownloader(t *testing.T, qa *fakeQA, reply *fakeReply, do return h } +func newTestHandlerWithCard(t *testing.T, qa *fakeQA, reply *fakeReply, card *fakeCard) *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 directTextCallback() BotCallback { return BotCallback{ ConversationType: "1", @@ -603,3 +631,179 @@ func TestHandleReplySendFailureReturnsError(t *testing.T) { t.Fatal("expected error when reply send fails") } } + +// --- A3.1: AI card priority / markdown fallback --- + +func TestHandleCardSuccessDirectFieldsCorrectNoMarkdown(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "**card answer**"}} + reply := &fakeReply{} + card := &fakeCard{returnID: "out-track-123"} + h := newTestHandlerWithCard(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + if !card.called { + t.Fatal("card.SendFinalCard was not called") + } + if card.lastReq.ConversationType != core.ConversationDirect { + t.Fatalf("card ConversationType = %q, want direct", card.lastReq.ConversationType) + } + if card.lastReq.ExternalUserID != "staff-123" { + t.Fatalf("card ExternalUserID = %q, want staff-123", card.lastReq.ExternalUserID) + } + if card.lastReq.Content != "**card answer**" { + t.Fatalf("card Content = %q, want answer", card.lastReq.Content) + } + if reply.called { + t.Fatal("SendMarkdown must not be called when card succeeds") + } +} + +func TestHandleCardSuccessGroupChatIDCorrect(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "group card answer"}} + reply := &fakeReply{} + card := &fakeCard{returnID: "out-track-group"} + h := newTestHandlerWithCard(t, qa, reply, card) + + err := h.Handle(context.Background(), groupTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + if !card.called { + t.Fatal("card.SendFinalCard was not called") + } + if card.lastReq.ConversationType != core.ConversationGroup { + t.Fatalf("card ConversationType = %q, want group", card.lastReq.ConversationType) + } + if card.lastReq.ExternalChatID != "cid-group-1" { + t.Fatalf("card ExternalChatID = %q, want cid-group-1", card.lastReq.ExternalChatID) + } + if reply.called { + t.Fatal("SendMarkdown must not be called when card succeeds") + } +} + +func TestHandleCardFailureFallsBackToMarkdown(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "**fallback answer**"}} + reply := &fakeReply{} + card := &fakeCard{err: errors.New("card API 500")} + h := newTestHandlerWithCard(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + if !card.called { + t.Fatal("card.SendFinalCard was not called") + } + if !reply.called { + t.Fatal("SendMarkdown must be called when card fails (fallback)") + } + if reply.lastText != "**fallback answer**" { + t.Fatalf("fallback reply text = %q, want answer", reply.lastText) + } +} + +func TestHandleQAFailureNoCardAndFriendlyMarkdown(t *testing.T) { + qa := &fakeQA{err: errors.New("internal weknora error")} + reply := &fakeReply{} + card := &fakeCard{} + h := newTestHandlerWithCard(t, qa, reply, card) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + if card.called { + t.Fatal("card.SendFinalCard must not be called on QA failure") + } + if !reply.called { + t.Fatal("SendMarkdown must be called on QA failure") + } + if !strings.Contains(reply.lastText, "暂时无法完成回答") { + t.Fatalf("friendly reply text = %q", reply.lastText) + } + if strings.Contains(reply.lastText, "weknora") { + t.Fatalf("reply text leaks internal error: %q", reply.lastText) + } +} + +func TestHandleNilCardNormalTextRegression(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "**plain markdown**"}} + reply := &fakeReply{} + // Use NewHandler (no card) — must behave exactly as before + h := newTestHandler(t, qa, reply) + + err := h.Handle(context.Background(), directTextCallback()) + if err != nil { + t.Fatalf("Handle: %v", err) + } + if !reply.called { + t.Fatal("SendMarkdown must be called when no card sender") + } + if reply.lastText != "**plain markdown**" { + t.Fatalf("reply text = %q, want answer", reply.lastText) + } +} + +func TestHandleImageDownloadFailureNoCard(t *testing.T) { + qa := &fakeQA{} + reply := &fakeReply{} + card := &fakeCard{} + downloader := &fakeImageDownloader{err: errors.New("download failed")} + h := newTestHandlerWithDownloader(t, qa, reply, downloader) + // Inject card via options — test that download failure short-circuits before card + 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.called { + t.Fatal("card.SendFinalCard must not be called on image download failure") + } + if qa.called { + 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 TestHandleNewHandlerBackwardCompat(t *testing.T) { + qa := &fakeQA{result: core.QAResult{Answer: "ok"}} + reply := &fakeReply{} + + // one downloader + h, err := NewHandler(TenantConfig{TenantKey: "t", Channel: "c"}, qa, reply, &fakeImageDownloader{}) + if err != nil { + t.Fatalf("NewHandler with one downloader: %v", err) + } + if h.downloader == nil { + t.Fatal("downloader should be set") + } + if h.card != nil { + t.Fatal("card should be nil when using NewHandler") + } + + // zero downloader + h2, err := NewHandler(TenantConfig{TenantKey: "t", Channel: "c"}, qa, reply) + if err != nil { + t.Fatalf("NewHandler with zero downloader: %v", err) + } + if h2.downloader != nil { + t.Fatal("downloader should be nil when not provided") + } + if h2.card != nil { + t.Fatal("card should be nil when using NewHandler") + } + + // two downloaders — must error + _, err = NewHandler(TenantConfig{TenantKey: "t", Channel: "c"}, qa, reply, &fakeImageDownloader{}, &fakeImageDownloader{}) + if err == nil { + t.Fatal("NewHandler with two downloaders should error") + } +}