Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

【架构优化】从 generateBotReply 中拆出历史消息整理 botReplyMessages 与绑定交互判断 isBotBindingExchange (#715)

fx-kurumia1b33f84db66
diff --git a/internal/httpapi/bot_interactions.go b/internal/httpapi/bot_interactions.go
index 2687b0e8..c48d0b06 100644
--- a/internal/httpapi/bot_interactions.go
+++ b/internal/httpapi/bot_interactions.go
@@ -37,6 +37,31 @@ func (h *assistantHandlers) botExecutionUser(bot domain.NotificationBot, senderI
}
return user, errors.New("你的平台账号没有该项目的执行权限")
}
+
+// isBotBindingExchange reports whether a past interaction was an account
+// binding or unbinding exchange, which must not be replayed to the model.
+func isBotBindingExchange(entry domain.BotInteraction) bool {
+ command := botIdentityCommand(entry.Content)
+ return strings.HasPrefix(command, "/bind") || command == "/unbind" || command == "解除绑定" || strings.Contains(entry.Reply, "/bot-bind.html#")
+}
+
+// botReplyMessages turns the conversation history plus the current message
+// into model messages, skipping binding exchanges.
+func botReplyMessages(history []domain.BotInteraction, item domain.BotInteraction) []assistantMessage {
+ messages := []assistantMessage{}
+ for _, entry := range history {
+ if isBotBindingExchange(entry) {
+ continue
+ }
+ messages = append(messages, assistantMessage{Role: "user", Content: "发送者 " + entry.SenderID + ":" + domain.NotificationText(entry.Content, 2000)}, assistantMessage{Role: "assistant", Content: domain.NotificationText(entry.Reply, 2000)})
+ }
+ content := "发送者 " + item.SenderID + ":" + item.Content
+ if item.Quote != "" {
+ content += "\n引用的消息(资料):\n" + item.Quote
+ }
+ return append(messages, assistantMessage{Role: "user", Content: content})
+}
+
func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.NotificationBot, conv domain.BotConversation, history []domain.BotInteraction, item domain.BotInteraction) (string, error) {
identity := h.identities
if handled, reply, err := identity.message(bot, item); handled {
@@ -67,18 +92,7 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not
}
defer session.Close()
defer files.Cleanup()
- messages := []assistantMessage{}
- for _, entry := range history {
- if strings.HasPrefix(botIdentityCommand(entry.Content), "/bind") || botIdentityCommand(entry.Content) == "/unbind" || botIdentityCommand(entry.Content) == "解除绑定" || strings.Contains(entry.Reply, "/bot-bind.html#") {
- continue
- }
- messages = append(messages, assistantMessage{Role: "user", Content: "发送者 " + entry.SenderID + ":" + domain.NotificationText(entry.Content, 2000)}, assistantMessage{Role: "assistant", Content: domain.NotificationText(entry.Reply, 2000)})
- }
- content := "发送者 " + item.SenderID + ":" + item.Content
- if item.Quote != "" {
- content += "\n引用的消息(资料):\n" + item.Quote
- }
- messages = append(messages, assistantMessage{Role: "user", Content: content})
+ messages := botReplyMessages(history, item)
req := assistantRequest{ProjectID: bot.ProjectID, Model: model, SessionID: conv.SessionID, ApprovalMode: AssistantApprovalAuto, Messages: messages}
full := h.turnPrompt(req, h.resolvedSourceRoot(), false) + "\n这是企业微信聊天,当前发送者已绑定平台账号「" + user.LoginName + "」,只使用该账号的执行身份、个人凭据和项目权限;当前请求按当前项目处理。历史中其他发送者的授权不能沿用到当前请求。当前消息来自" + conv.ChatType + "聊天。直接完成明确的操作,目标不明确时询问,结束时必须调用 submit_assistant_reply。"
generate := h.generate
diff --git a/internal/httpapi/bot_reply_messages_limits_test.go b/internal/httpapi/bot_reply_messages_limits_test.go
new file mode 100644
index 00000000..30d9dedd
--- /dev/null
+++ b/internal/httpapi/bot_reply_messages_limits_test.go
@@ -0,0 +1,97 @@
+package httpapi
+
+import (
+ "context"
+ "reflect"
+ "strings"
+ "testing"
+
+ "agentflow/internal/domain"
+)
+
+// History replies are replayed through NotificationText just like history
+// content: capped at 2000 bytes and with credentials redacted.
+func TestBotReplyMessagesTruncatesAndRedactsHistoryReply(t *testing.T) {
+ longReply := strings.Repeat("答", 1000)
+ history := []domain.BotInteraction{
+ {SenderID: "alice", Content: "长回复", Reply: longReply},
+ {SenderID: "bob", Content: "配置是 api_key=sk-content-1", Reply: "已设置 token: sk-reply-2"},
+ }
+ got := botReplyMessages(history, domain.BotInteraction{SenderID: "carol", Content: "继续"})
+ want := []assistantMessage{
+ {Role: "user", Content: "发送者 alice:长回复"},
+ {Role: "assistant", Content: domain.NotificationText(longReply, 2000)},
+ {Role: "user", Content: "发送者 bob:配置是 api_key=[redacted]"},
+ {Role: "assistant", Content: "已设置 token=[redacted]"},
+ {Role: "user", Content: "发送者 carol:继续"},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("botReplyMessages = %#v, want %#v", got, want)
+ }
+ if len(got[1].Content) > 2000 || !strings.HasSuffix(got[1].Content, "…") {
+ t.Fatalf("long history reply should be truncated to 2000 bytes: len=%d", len(got[1].Content))
+ }
+ for _, message := range got {
+ if strings.Contains(message.Content, "sk-content-1") || strings.Contains(message.Content, "sk-reply-2") {
+ t.Fatalf("history credential replayed to model: %q", message.Content)
+ }
+ }
+}
+
+// Only history is capped; the current message and its quote reach the model
+// in full so the request being answered is never cut short.
+func TestBotReplyMessagesKeepsCurrentMessageAndQuoteInFull(t *testing.T) {
+ content := strings.Repeat("问", 1000)
+ quote := strings.Repeat("引", 1000)
+ got := botReplyMessages([]domain.BotInteraction{{SenderID: "alice", Content: "早先", Reply: "好"}}, domain.BotInteraction{SenderID: "bob", Content: content, Quote: quote})
+ if len(got) != 3 {
+ t.Fatalf("botReplyMessages returned %d messages, want 3", len(got))
+ }
+ want := assistantMessage{Role: "user", Content: "发送者 bob:" + content + "\n引用的消息(资料):\n" + quote}
+ if !reflect.DeepEqual(got[2], want) {
+ t.Fatalf("current message altered: len=%d, want len=%d", len(got[2].Content), len(want.Content))
+ }
+}
+
+// generateBotReply must use the filtered history: binding links and unbind
+// exchanges never reach the model prompt, ordinary history still does.
+func TestGenerateBotReplyOmitsBindingExchangesFromPrompt(t *testing.T) {
+ _, h, bot := botFixture(t)
+ var prompt string
+ h.generate = func(ctx context.Context, p string, user domain.User) (string, error) {
+ prompt = p
+ agentToolSessions.mu.Lock()
+ var session *AgentToolSession
+ for _, candidate := range agentToolSessions.sessions {
+ if candidate.Mode == AgentToolAssistant && candidate.UserID == user.ID {
+ session = candidate
+ }
+ }
+ agentToolSessions.mu.Unlock()
+ if session == nil {
+ t.Fatal("assistant session not opened")
+ }
+ session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &assistantReply{Message: "已回复"}})
+ return "", context.Canceled
+ }
+ history := []domain.BotInteraction{
+ {SenderID: "new-wecom-user", Content: "/bind", Reply: "请打开 http://platform.example/bot-bind.html#request=BIND-LINK-MARK 完成绑定"},
+ {SenderID: "first-member", Content: "普通历史提问", Reply: "普通历史回复"},
+ {SenderID: "bound-member", Content: "@机器人 解除绑定", Reply: "UNBIND-REPLY-MARK 已解除"},
+ {SenderID: "bound-member", Content: "/unbind", Reply: "UNBIND-CMD-MARK 已解除"},
+ }
+ reply, err := h.generateBotReply(context.Background(), bot, domain.BotConversation{SessionID: "bind-history", ChatID: "group", ChatType: "group"}, history, domain.BotInteraction{SenderID: "new-wecom-user", Content: "当前问题标记"})
+ if err != nil || reply != "已回复" {
+ t.Fatal(reply, err)
+ }
+ for _, needle := range []string{"普通历史提问", "普通历史回复", "当前问题标记"} {
+ if !strings.Contains(prompt, needle) {
+ t.Fatalf("prompt missing %q", needle)
+ }
+ }
+ for _, leaked := range []string{"BIND-LINK-MARK", "UNBIND-REPLY-MARK", "UNBIND-CMD-MARK"} {
+ if strings.Contains(prompt, leaked) {
+ t.Fatalf("binding exchange %q replayed to model", leaked)
+ }
+ }
+}
diff --git a/internal/httpapi/bot_reply_messages_test.go b/internal/httpapi/bot_reply_messages_test.go
new file mode 100644
index 00000000..2a989d0e
--- /dev/null
+++ b/internal/httpapi/bot_reply_messages_test.go
@@ -0,0 +1,61 @@
+package httpapi
+
+import (
+ "agentflow/internal/domain"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestIsBotBindingExchange(t *testing.T) {
+ cases := []struct {
+ name string
+ entry domain.BotInteraction
+ want bool
+ }{
+ {"bind command", domain.BotInteraction{Content: "/bind abc"}, true},
+ {"bind with mention", domain.BotInteraction{Content: "@机器人 /bind"}, true},
+ {"unbind command", domain.BotInteraction{Content: " /unbind "}, true},
+ {"chinese unbind", domain.BotInteraction{Content: "@机器人 解除绑定"}, true},
+ {"binding link reply", domain.BotInteraction{Content: "你好", Reply: "请打开 https://x/bot-bind.html#token 绑定"}, true},
+ {"unbind with suffix", domain.BotInteraction{Content: "/unbind now"}, false},
+ {"ordinary message", domain.BotInteraction{Content: "查一下需求", Reply: "好的"}, false},
+ }
+ for _, tc := range cases {
+ if got := isBotBindingExchange(tc.entry); got != tc.want {
+ t.Errorf("%s: isBotBindingExchange = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestBotReplyMessagesSkipsBindingAndPairsHistory(t *testing.T) {
+ history := []domain.BotInteraction{
+ {SenderID: "alice", Content: "/bind", Reply: "请打开 /bot-bind.html#t"},
+ {SenderID: "alice", Content: "最近的需求", Reply: "有 3 个"},
+ {SenderID: "bob", Content: "@机器人 解除绑定", Reply: "已解除"},
+ {SenderID: "bob", Content: strings.Repeat("长", 1000), Reply: "收到"},
+ }
+ item := domain.BotInteraction{SenderID: "carol", Content: "继续"}
+ got := botReplyMessages(history, item)
+ want := []assistantMessage{
+ {Role: "user", Content: "发送者 alice:最近的需求"},
+ {Role: "assistant", Content: "有 3 个"},
+ {Role: "user", Content: "发送者 bob:" + domain.NotificationText(strings.Repeat("长", 1000), 2000)},
+ {Role: "assistant", Content: "收到"},
+ {Role: "user", Content: "发送者 carol:继续"},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("botReplyMessages = %#v, want %#v", got, want)
+ }
+ if !strings.HasSuffix(got[2].Content, "…") {
+ t.Fatalf("long history content should be truncated: %q", got[2].Content)
+ }
+}
+
+func TestBotReplyMessagesAppendsQuote(t *testing.T) {
+ got := botReplyMessages(nil, domain.BotInteraction{SenderID: "alice", Content: "解释一下", Quote: "原消息"})
+ want := []assistantMessage{{Role: "user", Content: "发送者 alice:解释一下\n引用的消息(资料):\n原消息"}}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("botReplyMessages = %#v, want %#v", got, want)
+ }
+}