From 6f24743be29f3f23f661e494442d978f74c92ab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Thu, 13 Aug 2026 18:22:43 +0800 Subject: [PATCH] feat: verify and activate support group binding --- cmd/dobotai/main.go | 2 + cmd/dobotai/settings_binding_validator.go | 48 ++++++++++++++- .../settings_binding_validator_test.go | 60 +++++++++++++++++++ cmd/dobotai/settings_wiring.go | 3 +- cmd/dobotai/support_notifications.go | 2 +- cmd/dobotai/support_notifications_test.go | 8 ++- internal/channels/dingtalk/group_sender.go | 48 +++++++++++++++ .../channels/dingtalk/group_sender_test.go | 32 ++++++++++ internal/settings/controller.go | 13 +++- internal/settings/controller_test.go | 33 +++++++++- 10 files changed, 239 insertions(+), 10 deletions(-) create mode 100644 cmd/dobotai/settings_binding_validator_test.go diff --git a/cmd/dobotai/main.go b/cmd/dobotai/main.go index 6728d8f..4baf368 100644 --- a/cmd/dobotai/main.go +++ b/cmd/dobotai/main.go @@ -56,6 +56,8 @@ func main() { if err != nil { log.Fatal(err) } + settingsRuntime.bindings.restartDelay = 300 * time.Millisecond + settingsRuntime.bindings.restart = func() { restartRequested.Store(true); cancel() } address := strings.TrimSpace(os.Getenv("DOBOTAI_LISTEN_ADDR")) if address == "" { address = "127.0.0.1:8090" diff --git a/cmd/dobotai/settings_binding_validator.go b/cmd/dobotai/settings_binding_validator.go index eba4ad8..747ca72 100644 --- a/cmd/dobotai/settings_binding_validator.go +++ b/cmd/dobotai/settings_binding_validator.go @@ -3,7 +3,9 @@ package main import ( "context" "errors" + "time" + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/channels/dingtalk" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/store/postgres" @@ -11,8 +13,50 @@ import ( type validatedSettingsRepository struct { *postgres.SettingsRepository - clientID string - secret string + clientID string + secret string + testSupport func(context.Context, settings.ResourceBinding) error + saveBinding func(context.Context, settings.ResourceBinding) error + restart func() + restartDelay time.Duration +} + +func (r *validatedSettingsRepository) TestAndActivateSupportGroup(ctx context.Context, binding settings.ResourceBinding) error { + if r.testSupport != nil { + if err := r.testSupport(ctx, binding); err != nil { + return errors.New("support_group_test_failed") + } + } else { + sender, err := dingtalk.NewSupportGroupSender(r.clientID, r.secret, binding.ConversationID, nil) + if err != nil { + return errors.New("support_group_test_invalid_config") + } + if err = sender.SendTest(ctx); err != nil { + return errors.New("support_group_test_failed") + } + } + binding.ValidationCode = "support_test_ok" + binding.Activate = true + var err error + if r.saveBinding != nil { + err = r.saveBinding(ctx, binding) + } else if r.SettingsRepository != nil { + err = r.SettingsRepository.SaveBinding(ctx, binding) + } else { + err = errors.New("support_group_binding_repository_unavailable") + } + if err != nil { + return err + } + if r.restart != nil { + go func() { + if r.restartDelay > 0 { + time.Sleep(r.restartDelay) + } + r.restart() + }() + } + return nil } func (r *validatedSettingsRepository) SaveBinding(ctx context.Context, binding settings.ResourceBinding) error { diff --git a/cmd/dobotai/settings_binding_validator_test.go b/cmd/dobotai/settings_binding_validator_test.go new file mode 100644 index 0000000..0976f99 --- /dev/null +++ b/cmd/dobotai/settings_binding_validator_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "errors" + "testing" + "time" + + "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" +) + +func TestSupportGroupActivationRestartsOnlyAfterTestAndSaveSucceed(t *testing.T) { + for _, tc := range []struct { + name string + testErr error + saveErr error + wantSaved bool + wantRestart bool + }{ + {name: "test fails", testErr: errors.New("send failed")}, + {name: "save fails", saveErr: errors.New("save failed"), wantSaved: true}, + {name: "success", wantSaved: true, wantRestart: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var saved settings.ResourceBinding + restarted := make(chan struct{}, 1) + repo := &validatedSettingsRepository{ + testSupport: func(context.Context, settings.ResourceBinding) error { return tc.testErr }, + saveBinding: func(_ context.Context, binding settings.ResourceBinding) error { + saved = binding + return tc.saveErr + }, + restart: func() { restarted <- struct{}{} }, + restartDelay: 0, + } + err := repo.TestAndActivateSupportGroup(context.Background(), settings.ResourceBinding{ + Kind: "support_group", TenantKey: "tenant", ConversationID: "group", + }) + if (err != nil) != (tc.testErr != nil || tc.saveErr != nil) { + t.Fatalf("err=%v", err) + } + if got := saved.Kind != ""; got != tc.wantSaved { + t.Fatalf("saved=%v want=%v", got, tc.wantSaved) + } + if tc.wantSaved && (saved.ValidationCode != "support_test_ok" || !saved.Activate) { + t.Fatalf("binding=%+v", saved) + } + select { + case <-restarted: + if !tc.wantRestart { + t.Fatal("unexpected restart") + } + case <-time.After(50 * time.Millisecond): + if tc.wantRestart { + t.Fatal("restart not requested") + } + } + }) + } +} diff --git a/cmd/dobotai/settings_wiring.go b/cmd/dobotai/settings_wiring.go index 9c1d778..7f4da79 100644 --- a/cmd/dobotai/settings_wiring.go +++ b/cmd/dobotai/settings_wiring.go @@ -30,6 +30,7 @@ func (r *dingTalkSettingsRouter) Handle(ctx context.Context, m dingtalk.Settings type settingsRuntime struct { repository *postgres.SettingsRepository + bindings *validatedSettingsRepository controller *settings.Controller admin *adminweb.ControlService clientID string @@ -93,5 +94,5 @@ func buildSettingsRuntime(ctx context.Context, store *postgres.Store, tenantKey return nil, err } validatedRepo := &validatedSettingsRepository{SettingsRepository: repo, clientID: clientID, secret: secret} - return &settingsRuntime{repository: repo, controller: settings.NewController(validatedRepo), admin: control, clientID: clientID, secret: secret, secretRef: secretRef, secrets: secrets, verifier: verifier, pendingActivation: pendingActivation}, nil + return &settingsRuntime{repository: repo, bindings: validatedRepo, controller: settings.NewController(validatedRepo), admin: control, clientID: clientID, secret: secret, secretRef: secretRef, secrets: secrets, verifier: verifier, pendingActivation: pendingActivation}, nil } diff --git a/cmd/dobotai/support_notifications.go b/cmd/dobotai/support_notifications.go index be3a21b..f03d81b 100644 --- a/cmd/dobotai/support_notifications.go +++ b/cmd/dobotai/support_notifications.go @@ -25,7 +25,7 @@ func buildSupportDispatcher(repo coverage.NotificationRepository, clientID, clie return nil, errors.New("support notification repository is required") } if recordLinks == nil { - return nil, errors.New("support notification FAQ record links are required") + return nil, nil } sender, err := dingtalk.NewSupportGroupSender(clientID, clientSecret, openConversationID, nil, dingtalk.WithFAQRecordLinkBuilder(recordLinks)) diff --git a/cmd/dobotai/support_notifications_test.go b/cmd/dobotai/support_notifications_test.go index af4e81f..388c722 100644 --- a/cmd/dobotai/support_notifications_test.go +++ b/cmd/dobotai/support_notifications_test.go @@ -62,6 +62,13 @@ func TestBuildSupportDispatcherDisabledWithoutGroup(t *testing.T) { } } +func TestBuildSupportDispatcherBlocksWithoutFAQLinks(t *testing.T) { + dispatcher, err := buildSupportDispatcher(&supportNotificationRepoStub{}, "client", "secret", "group", nil) + if err != nil || dispatcher != nil { + t.Fatalf("dispatcher=%v err=%v, want blocked without process failure", dispatcher, err) + } +} + func TestBuildSupportDispatcherEnabledFailsClosed(t *testing.T) { repo := &supportNotificationRepoStub{} links := testFAQRecordLinks(t) @@ -74,7 +81,6 @@ func TestBuildSupportDispatcherEnabledFailsClosed(t *testing.T) { {name: "missing repo", clientID: "client", secret: "secret", gid: "group", links: links}, {name: "missing client", repo: repo, secret: "secret", gid: "group", links: links}, {name: "missing secret", repo: repo, clientID: "client", gid: "group", links: links}, - {name: "missing FAQ links", repo: repo, clientID: "client", secret: "secret", gid: "group"}, } { t.Run(tc.name, func(t *testing.T) { if _, err := buildSupportDispatcher(tc.repo, tc.clientID, tc.secret, tc.gid, tc.links); err == nil { diff --git a/internal/channels/dingtalk/group_sender.go b/internal/channels/dingtalk/group_sender.go index 70a5670..9a3b2ad 100644 --- a/internal/channels/dingtalk/group_sender.go +++ b/internal/channels/dingtalk/group_sender.go @@ -187,6 +187,54 @@ func (s *SupportGroupSender) Send(ctx context.Context, notif coverage.SupportNot return nil } +// SendTest sends a fixed, non-sensitive message used to verify that the +// configured robot can reach the candidate support group. It deliberately +// does not require an FAQ-table binding. +func (s *SupportGroupSender) SendTest(ctx context.Context) error { + msgParam, err := json.Marshal(map[string]string{ + "title": "DobotAI 技术支持群绑定测试", + "text": "DobotAI 技术支持群绑定测试成功。", + }) + if err != nil { + return errors.New("dingtalk group sender: encode test message failed") + } + body := map[string]any{ + "msgKey": "sampleMarkdown", + "msgParam": string(msgParam), + "openConversationId": s.openConversation, + "robotCode": s.clientID, + } + bodyJSON, err := json.Marshal(body) + if err != nil { + return errors.New("dingtalk group sender: encode test request failed") + } + if len(bodyJSON) > maxGroupPayloadBytes { + return fmt.Errorf("dingtalk group sender: payload exceeds %d bytes", maxGroupPayloadBytes) + } + token, err := s.accessToken(ctx) + if err != nil { + return err + } + respPayload, err := s.doJSON(ctx, http.MethodPost, s.groupURL, body, token) + if err != nil { + return err + } + var response struct { + ProcessQueryKey string `json:"processQueryKey"` + ErrCode int `json:"errcode"` + } + if json.Unmarshal(respPayload, &response) != nil { + return errors.New("dingtalk group sender: invalid API response") + } + if response.ErrCode != 0 { + return errors.New("dingtalk group sender: API returned business error") + } + if strings.TrimSpace(response.ProcessQueryKey) == "" { + return errors.New("dingtalk group sender: incomplete API response") + } + return nil +} + // renderMarkdown produces the compact customer-question context shown in the action card. func (s *SupportGroupSender) renderMarkdown(notif coverage.SupportNotification) (title, text string) { title = "知识库未覆盖提醒" diff --git a/internal/channels/dingtalk/group_sender_test.go b/internal/channels/dingtalk/group_sender_test.go index 2bf3562..5401e6b 100644 --- a/internal/channels/dingtalk/group_sender_test.go +++ b/internal/channels/dingtalk/group_sender_test.go @@ -539,6 +539,38 @@ func TestSupportGroupSenderNoPreviousQuestions(t *testing.T) { } } +func TestSupportGroupSenderSendTestDoesNotRequireFAQBinding(t *testing.T) { + gs := newGroupTestServer() + defer gs.Close() + + sender, err := newSupportGroupSenderForTest( + "appKey", "appSecret", "cid-abc", + gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send", + ) + if err != nil { + t.Fatal(err) + } + if err = sender.SendTest(context.Background()); err != nil { + t.Fatalf("SendTest: %v", err) + } + if gs.sendCalls != 1 { + t.Fatalf("sendCalls=%d want=1", gs.sendCalls) + } + if gs.lastSendBody["openConversationId"] != "cid-abc" || gs.lastSendBody["robotCode"] != "appKey" { + t.Fatalf("body=%v", gs.lastSendBody) + } + if gs.lastSendBody["msgKey"] != "sampleMarkdown" { + t.Fatalf("msgKey=%v want=sampleMarkdown", gs.lastSendBody["msgKey"]) + } + var params map[string]string + if err = json.Unmarshal([]byte(gs.lastSendBody["msgParam"].(string)), ¶ms); err != nil { + t.Fatal(err) + } + if params["title"] != "DobotAI 技术支持群绑定测试" || !strings.Contains(params["text"], "测试成功") { + t.Fatalf("params=%v", params) + } +} + func TestSupportGroupSenderRejectsMalformedOrIncompleteSuccessResponse(t *testing.T) { tests := []struct { name string diff --git a/internal/settings/controller.go b/internal/settings/controller.go index c8c0f03..c358ecd 100644 --- a/internal/settings/controller.go +++ b/internal/settings/controller.go @@ -29,6 +29,7 @@ type ControllerRepository interface { IsAdministrator(context.Context, string, string) (bool, error) SetPreference(context.Context, string, string, string, string) error SaveBinding(context.Context, ResourceBinding) error + TestAndActivateSupportGroup(context.Context, ResourceBinding) error DetectBootstrapCandidate(context.Context, BootstrapCandidate) error GetSettingSession(context.Context, string, string) (SettingSession, bool, error) SaveSettingSession(context.Context, SettingSession) error @@ -123,9 +124,17 @@ func (c *Controller) Handle(ctx context.Context, in SettingInput) (string, error if in.ConversationType != "group" || strings.TrimSpace(in.ConversationID) == "" { return "请在目标技术支持群中@机器人发送 /setting support。", nil } - err = c.repo.SaveBinding(ctx, ResourceBinding{Kind: "support_group", TenantKey: in.TenantKey, ConversationID: in.ConversationID, ConversationTitle: in.ConversationTitle, CreatedByStaffID: in.StaffID}) + binding := ResourceBinding{Kind: "support_group", TenantKey: in.TenantKey, ConversationID: in.ConversationID, ConversationTitle: in.ConversationTitle, CreatedByStaffID: in.StaffID} + if len(args) == 2 && strings.EqualFold(args[1], "test") { + err = c.repo.TestAndActivateSupportGroup(ctx, binding) + if err == nil { + return "✅ 测试成功,当前群已激活为技术支持群。", nil + } + break + } + err = c.repo.SaveBinding(ctx, binding) if err == nil { - return "✅ 当前群已保存为技术支持群(待后台验证)。", nil + return "✅ 当前群已保存为技术支持群(待验证)。确认发送测试消息后,请在本群@机器人发送 /setting support test。", nil } case "question", "faq": if len(args) != 2 { diff --git a/internal/settings/controller_test.go b/internal/settings/controller_test.go index 4231e0f..1d4eaa4 100644 --- a/internal/settings/controller_test.go +++ b/internal/settings/controller_test.go @@ -29,6 +29,12 @@ func (r *memoryRepo) SaveBinding(_ context.Context, b ResourceBinding) error { r.bindings[b.Kind] = b return nil } +func (r *memoryRepo) TestAndActivateSupportGroup(_ context.Context, b ResourceBinding) error { + b.Activate = true + b.ValidationCode = "support_test_ok" + r.bindings[b.Kind] = b + return nil +} func (r *memoryRepo) DetectBootstrapCandidate(_ context.Context, c BootstrapCandidate) error { r.candidate = c return nil @@ -72,12 +78,33 @@ func TestControllerBindsAdminSupportGroup(t *testing.T) { r := newMemoryRepo() r.admins["t/a"] = true c := NewController(r) - _, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) if err != nil { t.Fatal(err) } - if r.bindings["support_group"].ConversationID != "g" { - t.Fatalf("binding=%+v", r.bindings) + binding := r.bindings["support_group"] + if binding.ConversationID != "g" || binding.Activate { + t.Fatalf("binding=%+v", binding) + } + if !strings.Contains(out, "support test") { + t.Fatalf("reply=%q must explain explicit test command", out) + } +} + +func TestControllerExplicitlyTestsAndActivatesSupportGroup(t *testing.T) { + r := newMemoryRepo() + r.admins["t/a"] = true + c := NewController(r) + out, err := c.Handle(context.Background(), SettingInput{TenantKey: "t", StaffID: "a", Text: "/setting support test", ConversationType: "group", ConversationID: "g", ConversationTitle: "技术支持"}) + if err != nil { + t.Fatal(err) + } + binding := r.bindings["support_group"] + if binding.ConversationID != "g" || !binding.Activate { + t.Fatalf("binding=%+v", binding) + } + if !strings.Contains(out, "测试成功") || !strings.Contains(out, "已激活") { + t.Fatalf("reply=%q", out) } } func TestControllerHelpIsHandledLocally(t *testing.T) {