Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8382: fix(wecom): write the unreadable-message receipt in the sender's language (#9693)
Xichang(Seacen) Zhaoc066f7ea61ee
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 6e86b6990c..8b9bd7896d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1012,8 +1012,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Same store the Router claims on, so the receipt this// adapter sends before the Router sees the message cannot// also be answered there.- Dedup: wecom.NewDeduper(wecomStore),- Logger: slog.Default(),+ Dedup: wecom.NewDeduper(wecomStore),+ // The receipt for a message the bot cannot read is written+ // in the sender's profile language in a 1:1.+ Languages: queries,+ Logger: slog.Default(),})// Streaming replies: WeCom's smart-bot protocol has no// typing indicator, no reaction and no read receipt, so thediff --git a/server/cmd/server/wecom_replier_wiring_test.go b/server/cmd/server/wecom_replier_wiring_test.goindex 6a86b30520..5739c8d97f 100644--- a/server/cmd/server/wecom_replier_wiring_test.go+++ b/server/cmd/server/wecom_replier_wiring_test.go@@ -15,7 +15,8 @@ import ("github.com/multica-ai/multica/server/pkg/protocol")-// The replier's language lookup is an optional field, and a missing one has no+// A WeCom component's language lookup is an optional field — the replier's,+// and the read loop's for the receipt it sends itself — and a missing one has no// symptom of its own: nothing errors, nothing is empty, every notice simply// comes out in the deployment's language whatever the reader's profile says.// Every unit test in the wecom package sets it by hand, so the package stays@@ -23,14 +24,15 @@ import (// absent the first time.//// So this asserts it off the REAL boot path: NewRouter, the same call main()-// makes. What it reads is the warning NewOutboundReplier logs when the field is-// nil, which is also what an operator would have to notice today.+// makes. What it reads is the warning NewOutboundReplier and RegisterWecom each+// log when their field is nil, which is also what an operator would have to+// notice today.//// Two routers are built, one without the WeCom key and one with it, the same// way wecom_bubble_wiring_test.go does: chat:done has listeners outside WeCom// whenever another channel is configured, so only the difference between the// two says the WeCom block ran.-func TestWecomReplierGetsItsLanguageLookupOnTheRealBootPath(t *testing.T) {+func TestWecomGetsItsLanguageLookupsOnTheRealBootPath(t *testing.T) {key := make([]byte, secretbox.KeySize)if _, err := rand.Read(key); err != nil {t.Fatalf("generate a wecom secretbox key: %v", err)@@ -58,8 +60,8 @@ func TestWecomReplierGetsItsLanguageLookupOnTheRealBootPath(t *testing.T) {}if got := logged.String(); strings.Contains(got, "no language lookup wired") {- t.Errorf("the production replier was built without a language lookup, so every notice it sends "+- "uses the deployment language whatever the reader's profile says — which is the whole of "+- "what the copy pack is for. Set OutboundReplierConfig.Languages in router.go.\nlog:\n%s", got)+ t.Errorf("a WeCom component was built without a language lookup, so what it sends uses the "++ "deployment language whatever the reader's profile says — which is the whole of what the "++ "copy pack is for. The warning names the field to set in router.go.\nlog:\n%s", got)}}diff --git a/server/internal/integrations/wecom/language_lint_test.go b/server/internal/integrations/wecom/language_lint_test.goindex dda66d0d6c..f64f76c91f 100644--- a/server/internal/integrations/wecom/language_lint_test.go+++ b/server/internal/integrations/wecom/language_lint_test.go@@ -71,14 +71,13 @@ func TestOnlyStringsGoHoldsUserVisibleCopy(t *testing.T) {}var offenders []offence- // The two files below still hold their copy as literals. They are listed- // with an exact count rather than left out of the walk, so the lint still- // fails on a literal added anywhere else — including a new one in either of- // these two — and fails again if one of these loses a literal without this- // list being updated.+ // The files below still hold their copy as literals. They are listed with+ // an exact count rather than left out of the walk, so the lint still fails+ // on a literal added anywhere else — including a new one in a listed file —+ // and fails again if a listed file loses a literal without this list being+ // updated.pending := map[string]int{- "wecom_channel.go": 1,- "media_ingest.go": 2,+ "media_ingest.go": 2,}for _, name := range packageGoFiles(t, "strings.go") {diff --git a/server/internal/integrations/wecom/locale_wiring_test.go b/server/internal/integrations/wecom/locale_wiring_test.goindex a38411bad8..0b8fc05310 100644--- a/server/internal/integrations/wecom/locale_wiring_test.go+++ b/server/internal/integrations/wecom/locale_wiring_test.go@@ -13,6 +13,8 @@ package wecomimport ("context"+ "encoding/json"+ "log/slog""strings""testing"@@ -413,6 +415,94 @@ func TestTheBubbleClosesInTheAskersLanguage(t *testing.T) {// ---- surface 6: the read loop's own receipt ----+// TestUnreadableKindReceiptReadsTheSendersLanguage drives dispatchFrame with a+// message nothing here can read. The receipt is sent by the read loop before+// the Router or the Replier ever see the message, so it is a surface of its own+// and has to consult the pack itself.+//+// REVERSE VERIFICATION: put the zh-Hans literal back in dispatchFrame and the+// English case receives the Chinese line.+func TestUnreadableKindReceiptReadsTheSendersLanguage(t *testing.T) {+ t.Parallel()+ for _, tc := range localeCases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })+ c.installationID = mustTestUUID(t)+ c.languages = fakeLanguages{senderID: "USER_A", userID: localeTestUserID, language: tc.language}+ conn := &recordingConn{}+ if err := c.dispatchFrame(context.Background(), msgCallbackFrame(t, "location", ""),+ conn.autoAck(newWSSender(conn, nil)), slog.Default()); err != nil {+ t.Fatalf("dispatchFrame: %v", err)+ }+ if got, want := sentMarkdown(t, conn, 0), copyPacks[tc.locale].UnsupportedMsgType; got != want {+ t.Fatalf("receipt = %q, want the %s copy %q", got, tc.locale, want)+ }+ })+ }+}++// The factory is what router.go calls, and the unit tests above set the field by+// hand, so this is the one that fails if the copy from ChannelDeps into the+// channel stops happening.+//+// REVERSE VERIFICATION: drop languages: deps.Languages from newWecomFactory and+// this receives the Chinese line.+func TestTheFactoryCarriesTheLanguageLookupIntoTheReceipt(t *testing.T) {+ t.Parallel()+ factory := newWecomFactory(ChannelDeps{+ Credentials: fixedCredentials{},+ Languages: fakeLanguages{senderID: "USER_A", userID: localeTestUserID, language: "en"},+ })+ ch, err := factory(channel.Config{+ ID: mustTestUUID(t),+ Raw: []byte(`{"bot_id":"bot-1"}`),+ Handler: func(context.Context, channel.InboundMessage) error { return nil },+ })+ if err != nil {+ t.Fatalf("factory: %v", err)+ }+ wc, ok := ch.(*wecomChannel)+ if !ok {+ t.Fatalf("factory returned %T, want *wecomChannel", ch)+ }+ conn := &recordingConn{}+ if err := wc.dispatchFrame(context.Background(), msgCallbackFrame(t, "location", ""),+ conn.autoAck(newWSSender(conn, nil)), slog.Default()); err != nil {+ t.Fatalf("dispatchFrame: %v", err)+ }+ if got, want := sentMarkdown(t, conn, 0), copyPacks[LocaleEn].UnsupportedMsgType; got != want {+ t.Fatalf("receipt = %q, want the English %q: the factory dropped ChannelDeps.Languages", got, want)+ }+}++// In a room there is no one profile to read, so the receipt is the+// deployment's, whatever the sender's own profile says.+func TestUnreadableKindReceiptInARoomReadsTheDeployment(t *testing.T) {+ t.Parallel()+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })+ c.installationID = mustTestUUID(t)+ c.languages = fakeLanguages{senderID: "USER_A", userID: localeTestUserID, language: "en"}+ frame := msgCallbackFrame(t, "location", "")+ var mc aibotMsgCallback+ if err := json.Unmarshal(frame.Body, &mc); err != nil {+ t.Fatalf("decode: %v", err)+ }+ mc.ChatType = "group"+ body, err := json.Marshal(mc)+ if err != nil {+ t.Fatalf("encode: %v", err)+ }+ frame.Body = body+ conn := &recordingConn{}+ if err := c.dispatchFrame(context.Background(), frame, conn.autoAck(newWSSender(conn, nil)), slog.Default()); err != nil {+ t.Fatalf("dispatchFrame: %v", err)+ }+ if got, want := sentMarkdown(t, conn, 0), copyFor(deploymentLocale()).UnsupportedMsgType; got != want {+ t.Fatalf("room receipt = %q, want the deployment's %q", got, want)+ }+}+// ---- the deployment knob ----// restoreLocale points the deployment at l for the duration of one test anddiff --git a/server/internal/integrations/wecom/strings.go b/server/internal/integrations/wecom/strings.goindex c85f2f0854..9ef4cd3132 100644--- a/server/internal/integrations/wecom/strings.go+++ b/server/internal/integrations/wecom/strings.go@@ -219,6 +219,13 @@ type copyPack struct {MediaSendFailed stringMediaSendUnknown stringMediaLookupFailed string++ // UnsupportedMsgType answers a message kind the adapter cannot read at+ // all — sent from the read loop, which never reaches the Replier. It does+ // not name text, because photos, files, videos and 图文混排 route: a person+ // who has just watched the bot answer a screenshot and is then told it+ // only handles text reads that as the bot being broken.+ UnsupportedMsgType string}// label returns the display name for an inbox notification type.@@ -293,6 +300,7 @@ var copyPacks = map[Locale]copyPack{MediaSendFailed: "⚠️ 有文件没能发出来,我这边保留着,需要的话我再试一次。",MediaSendUnknown: "⚠️ 有文件我没收到企业微信的送达回执,可能已经发到了、也可能没有。我不会自动重发,免得发重了;你那边没看到的话说一声,我再发一次。",MediaLookupFailed: "⚠️ 我这边没查到这条回答带没带文件,所以要是有,这次没发出来。需要的话我再试一次。",+ UnsupportedMsgType: "抱歉,我暂时无法处理这类消息。",StreamCancelled: "⏹️ 这次处理已取消。",InboxDetailLink: "查看详情",@@ -335,6 +343,7 @@ var copyPacks = map[Locale]copyPack{MediaSendFailed: "⚠️ I couldn't send one of the files. It is still here — say the word and I'll try again.",MediaSendUnknown: "⚠️ WeCom never confirmed one of the files, so it may or may not have arrived. I won't resend it automatically in case that shows it twice — tell me if it isn't there and I'll send it again.",MediaLookupFailed: "⚠️ I couldn't check whether this answer had a file with it, so if it did, it didn't go out. Say the word and I'll try again.",+ UnsupportedMsgType: "Sorry, I can't read that kind of message.",StreamCancelled: "⏹️ That run was cancelled.",InboxDetailLink: "View details",diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.goindex 77e0cea729..0bc4df49ac 100644--- a/server/internal/integrations/wecom/wecom_channel.go+++ b/server/internal/integrations/wecom/wecom_channel.go@@ -61,14 +61,6 @@ const writeDeadline = 10 * time.Second// handshakeTimeout bounds the initial TCP + WS handshake dial.const handshakeTimeout = 15 * time.Second-// unsupportedMsgTypeReceipt is the one line sent back for a message this-// adapter cannot read at all. It used to say "我目前只能处理文字消息" — text-// only — which stopped being true the moment photos, files, videos and-// 图文混排 started routing: a person who has just watched the bot answer a-// screenshot, then gets told it only handles text, reads that as the bot-// being broken rather than as this one kind not being supported.-const unsupportedMsgTypeReceipt = "抱歉,我暂时无法处理这类消息。"-// wecomChannel is one installation's aibot smart-bot WebSocket connection.// The engine.Supervisor builds one per active installation via the// registered Factory and drives lease / reconnect lifecycle; Connect blocks@@ -101,6 +93,10 @@ type wecomChannel struct {// through mx(), which substitutes the no-op sink for a channel built// without one.metrics Metrics++ // languages resolves the chat a receipt goes back to into the language+ // it is written in. Nil puts every reader on the deployment default.+ languages languageLookup}var _ channel.Channel = (*wecomChannel)(nil)@@ -448,6 +444,15 @@ func (c *wecomChannel) subscribe(ctx context.Context, conn wsConn, sender *wsSen}}+// receiptCopy is the unsupported-kind receipt in the language of the chat it+// goes back to: the sender's profile language in a 1:1, the deployment's in a+// room, which has no shared profile (language.go). It costs a lookup, and only+// a message nothing here can read ever pays it.+func (c *wecomChannel) receiptCopy(ctx context.Context, msg channel.InboundMessage) string {+ return copyFor(localeFor(ctx, c.languages, c.installationID,+ aibotChatTypeFromChannel(msg.Source.ChatType), msg.Source.SenderID)).UnsupportedMsgType+}+// dispatchFrame routes one server frame. Only aibot_msg_callback ever// escalates back to the loop's caller (as a handler infra failure);// events are logged + acked and everything else is silently dropped.@@ -475,8 +480,7 @@ func (c *wecomChannel) dispatchFrame(ctx context.Context, env frameEnvelope, sen// one-line receipt and stop. Best-effort: a send failure degrades// to the prior silent drop.log.Debug("wecom: unsupported message kind, replying with a receipt", "msg_type", mc.MsgType, "msg_id", mc.MsgID)- c.sendUnsupportedReceipt(ctx, sender, mc.MsgID, msg.Source.ChatID,- aibotChatTypeFromChannel(msg.Source.ChatType), unsupportedMsgTypeReceipt, log)+ c.sendUnsupportedReceipt(ctx, sender, mc.MsgID, msg, log)return nil}if err := c.handler(ctx, msg); err != nil {@@ -617,6 +621,10 @@ type ChannelDeps struct {// turned off gets.Metrics Metrics+ // Languages resolves the chat a receipt goes back to into its copy+ // language (language.go). Nil puts every reader on the deployment default.+ Languages languageLookup+// Dialer overrides the default gorilla dialer. Tests point it at an// httptest server; production leaves this nil.Dialer Dialer@@ -652,12 +660,14 @@ type ChannelDeps struct {// the database unreachable the choice is a possible duplicate against a bot// that looks broken, and silence is the worse of the two. That is the same// stance the send itself takes.+//+// The copy is resolved only after the claim, so a redelivery stopped at the+// claim does not pay for the language lookup.func (c *wecomChannel) sendUnsupportedReceipt(ctx context.Context,sender *wsSender,- messageID, chatID string,- chatType int,- content string,+ messageID string,+ msg channel.InboundMessage,log *slog.Logger,) {var (@@ -681,7 +691,8 @@ func (c *wecomChannel) sendUnsupportedReceipt(}}- if err := sender.sendText(chatID, chatType, content); err != nil {+ chatType := aibotChatTypeFromChannel(msg.Source.ChatType)+ if err := sender.sendText(msg.Source.ChatID, chatType, c.receiptCopy(ctx, msg)); err != nil {log.Debug("wecom: unsupported-kind receipt send failed", "error", err, "msg_id", messageID)if claimed {// Nothing was delivered, so the claim must not stand: it would@@ -708,18 +719,22 @@ func (c *wecomChannel) sendUnsupportedReceipt(// adapter — no engine edit (same contract as lark.RegisterFeishu /// slack.RegisterSlack).func RegisterWecom(reg *channel.Registry, deps ChannelDeps) {+ logger := deps.Logger+ if logger == nil {+ logger = slog.Default()+ }if deps.Dedup == nil {// Not fatal — answering twice is what main does today — but it has no// other symptom: nothing errors, and the duplicate only shows up in// somebody's chat, one per redelivery, each spending a push from that// conversation's quota.- logger := deps.Logger- if logger == nil {- logger = slog.Default()- }logger.Warn("wecom: no deduper wired; a redelivered unreadable message will be answered again " +"on every delivery (set ChannelDeps.Dedup to NewDeduper(store))")}+ if deps.Languages == nil {+ logger.Warn("wecom: no language lookup wired; the receipt for a message the bot cannot read will use " ++ "the deployment language whatever the sender's profile says (set ChannelDeps.Languages)")+ }reg.Register(TypeWecom, newWecomFactory(deps))}@@ -749,6 +764,7 @@ func newWecomFactory(deps ChannelDeps) channel.Factory {return &wecomChannel{installationID: cfg.ID,dedup: deps.Dedup,+ languages: deps.Languages,botID: creds.BotID,secret: creds.Secret,botDisplayName: ic.BotDisplayName,