Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(wecom): answer an unreadable message once per message, not once per delivery (#8836)

Xichang(Seacen) Zhao7551ff1ddccd
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 4b51872561..00ca29e45d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -994,7 +994,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
Credentials: credsResolver,
Senders: wecomSenders,
Metrics: wecomMetricsOrNil(opts.WecomMetrics),
- Logger: slog.Default(),
+ // 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(),
})
// Streaming replies: WeCom's smart-bot protocol has no
// typing indicator, no reaction and no read receipt, so the
diff --git a/server/cmd/server/wecom_dedup_wiring_test.go b/server/cmd/server/wecom_dedup_wiring_test.go
new file mode 100644
index 0000000000..692a1ebd7f
--- /dev/null
+++ b/server/cmd/server/wecom_dedup_wiring_test.go
@@ -0,0 +1,59 @@
+package main
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/base64"
+ "log/slog"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// The deduper is an optional field on ChannelDeps, and a missing one has no
+// symptom of its own: nothing errors, and the duplicate only shows up in
+// somebody's chat — one per redelivery, each spending a push from that
+// conversation's quota. Every unit test in the wecom package assigns the field
+// itself, so the package stays green with the production wiring absent.
+//
+// So this asserts it off the REAL boot path: NewRouter, the same call main()
+// makes. What it reads is the warning RegisterWecom logs when the field is nil,
+// which is also the only thing an operator would have to notice.
+func TestWecomChannelGetsItsDeduperOnTheRealBootPath(t *testing.T) {
+ key := make([]byte, secretbox.KeySize)
+ if _, err := rand.Read(key); err != nil {
+ t.Fatalf("generate a wecom secretbox key: %v", err)
+ }
+
+ // Anti-vacuity as a difference rather than a count: chat:done has listeners
+ // that have nothing to do with WeCom, so a non-zero count proves nothing.
+ withoutWecom := events.New()
+ NewRouter(nil, realtime.NewHub(), withoutWecom, analytics.NoopClient{}, nil)
+
+ var logged bytes.Buffer
+ restore := slog.Default()
+ slog.SetDefault(slog.New(slog.NewTextHandler(&logged, &slog.HandlerOptions{Level: slog.LevelDebug})))
+ t.Cleanup(func() { slog.SetDefault(restore) })
+
+ t.Setenv("MULTICA_WECOM_SECRET_KEY", base64.StdEncoding.EncodeToString(key))
+ withWecom := events.New()
+ NewRouter(nil, realtime.NewHub(), withWecom, analytics.NoopClient{}, nil)
+
+ if got, base := withWecom.SubscriberCount(protocol.EventChatDone),
+ withoutWecom.SubscriberCount(protocol.EventChatDone); got <= base {
+ t.Fatalf("the WeCom boot block did not run: chat:done listeners %d with the key set vs %d without, "+
+ "so RegisterWecom was never reached and the check below proves nothing. "+
+ "Re-point this guard at wherever WeCom is wired now", got, base)
+ }
+
+ if got := logged.String(); strings.Contains(got, "no deduper wired") {
+ t.Errorf("the production channel was registered without a deduper, so a redelivered unreadable "+
+ "message is answered again on every delivery — which is the whole of what this fixes. "+
+ "Set ChannelDeps.Dedup in router.go.\nlog:\n%s", got)
+ }
+}
diff --git a/server/internal/integrations/wecom/receipt_dedup_test.go b/server/internal/integrations/wecom/receipt_dedup_test.go
new file mode 100644
index 0000000000..2b1f6781cc
--- /dev/null
+++ b/server/internal/integrations/wecom/receipt_dedup_test.go
@@ -0,0 +1,258 @@
+package wecom
+
+// receipt_dedup_test.go — the unsupported-kind receipt is answered once per
+// message, not once per delivery.
+//
+// WeCom redelivers a callback it did not get an ack for. The receipt for a
+// message the adapter cannot read is sent from dispatchFrame, which returns
+// before c.handler, so the Router's own Claim never runs for that message and
+// nothing downstream deduplicates it. Unclaimed, a redelivered photo puts a
+// second "sorry, I can't read that" in the chat — and each copy spends one of
+// the conversation's active pushes.
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "sync"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// fakeDeduper implements the same two-phase contract as the real deduper
+// (wecom_resolvers.go) against a map: Claim mints a token and refuses a second
+// claim on a live or processed key, Mark seals it, Release frees it again.
+type fakeDeduper struct {
+ mu sync.Mutex
+ // state maps message id -> claimed (false) / processed (true).
+ state map[string]bool
+ // claimErr, when set, makes Claim fail the way an unreachable database
+ // would — neither a duplicate nor a token.
+ claimErr error
+
+ claims, marks, releases int
+}
+
+func newFakeDeduper() *fakeDeduper { return &fakeDeduper{state: map[string]bool{}} }
+
+func (f *fakeDeduper) Claim(_ context.Context, _ pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.claims++
+ if f.claimErr != nil {
+ return pgtype.UUID{}, f.claimErr
+ }
+ if _, held := f.state[messageID]; held {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ f.state[messageID] = false
+ return pgtype.UUID{Bytes: [16]byte{1}, Valid: true}, nil
+}
+
+func (f *fakeDeduper) Mark(_ context.Context, _ pgtype.UUID, messageID string, _ pgtype.UUID) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.marks++
+ f.state[messageID] = true
+ return nil
+}
+
+func (f *fakeDeduper) Release(_ context.Context, _ pgtype.UUID, messageID string, _ pgtype.UUID) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.releases++
+ delete(f.state, messageID)
+ return nil
+}
+
+func (f *fakeDeduper) counts() (claims, marks, releases int) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.claims, f.marks, f.releases
+}
+
+// sendFrames counts the outbound message sends on the double, ignoring
+// anything else the connection carries.
+func sendFrames(t *testing.T, conn *recordingConn) int {
+ t.Helper()
+ conn.mu.Lock()
+ defer conn.mu.Unlock()
+ n := 0
+ for _, f := range conn.frames {
+ if f.Cmd == cmdSendMsg {
+ n++
+ }
+ }
+ return n
+}
+
+// dedupChannel assigns c.dedup straight onto the struct, which skips both
+// newWecomFactory and router.go. That is fine for driving the state machine
+// below, but it is why this file cannot tell whether production wires the thing
+// at all — TestRegisterWecomCarriesTheDeduperIntoTheChannel goes through the
+// factory, and cmd/server has the one that reads the real boot path.
+func dedupChannel(t *testing.T, d engine.Deduper) *wecomChannel {
+ t.Helper()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
+ c.installationID = mustTestUUID(t)
+ c.dedup = d
+ return c
+}
+
+// The factory is what router.go actually calls, and it is where a ChannelDeps
+// field goes missing without anything failing. Driving it here means the copy
+// from deps into the channel cannot silently stop happening.
+func TestRegisterWecomCarriesTheDeduperIntoTheChannel(t *testing.T) {
+ t.Parallel()
+ dedup := newFakeDeduper()
+ factory := newWecomFactory(ChannelDeps{Credentials: fixedCredentials{}, Dedup: dedup})
+
+ 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)
+ }
+ if wc.dedup == nil {
+ t.Fatal("the factory dropped ChannelDeps.Dedup, so every channel it builds answers a " +
+ "redelivered unreadable message again on each delivery")
+ }
+}
+
+// The user sends one location card. WeCom delivers the callback twice.
+func TestUnsupportedReceipt_ARedeliveryDoesNotRepeatTheReceipt(t *testing.T) {
+ t.Parallel()
+ dedup := newFakeDeduper()
+ c := dedupChannel(t, dedup)
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ // Same frame, same msg_id: one message, delivered twice.
+ for i := 0; i < 2; i++ {
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "location", ""), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame delivery %d: %v", i+1, err)
+ }
+ }
+
+ if n := sendFrames(t, conn); n != 1 {
+ t.Errorf("the user was told %d times that the message could not be read, want once — WeCom "+
+ "redelivers a callback, and each repeat also spends one of the conversation's pushes", n)
+ }
+ if _, marks, releases := dedup.counts(); marks != 1 || releases != 0 {
+ t.Errorf("marks=%d releases=%d, want the delivered receipt marked processed and nothing released",
+ marks, releases)
+ }
+}
+
+// The send fails. The claim must not survive it: the redelivery is the only
+// remaining chance this message is ever answered.
+func TestUnsupportedReceipt_AFailedSendReleasesTheClaim(t *testing.T) {
+ t.Parallel()
+ dedup := newFakeDeduper()
+ c := dedupChannel(t, dedup)
+ conn := &recordingConn{refuseCode: 40001, refuseMsg: "refused"}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "location", ""), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if _, _, releases := dedup.counts(); releases != 1 {
+ t.Fatalf("releases=%d after a refused send, want 1 — a claim held over a receipt that never "+
+ "arrived turns one failed send into permanent silence", releases)
+ }
+
+ // The server stops refusing and WeCom redelivers.
+ conn.mu.Lock()
+ conn.refuseCode, conn.refuseMsg = 0, ""
+ conn.mu.Unlock()
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "location", ""), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame on the redelivery: %v", err)
+ }
+ if n := sendFrames(t, conn); n != 2 {
+ t.Errorf("send frames = %d, want 2 (the refused one and the redelivery that succeeded) — the "+
+ "user must still get an answer after a transient failure", n)
+ }
+ if _, marks, _ := dedup.counts(); marks != 1 {
+ t.Errorf("marks=%d, want the successful redelivery marked exactly once", marks)
+ }
+}
+
+// The dedup itself fails — the database is unreachable. Silence reads as a
+// broken bot, so the receipt still goes out: the user's worst case stays the
+// behaviour they had before the claim existed.
+func TestUnsupportedReceipt_AnUnreachableDedupStillAnswers(t *testing.T) {
+ t.Parallel()
+ dedup := newFakeDeduper()
+ dedup.claimErr = errors.New("connection refused")
+ c := dedupChannel(t, dedup)
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "location", ""), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if n := sendFrames(t, conn); n != 1 {
+ t.Errorf("send frames = %d, want 1 — a dedup that cannot answer must not silence the receipt, "+
+ "or an unreachable database makes the bot look broken to every user who sends a photo", n)
+ }
+ if _, marks, releases := dedup.counts(); marks != 0 || releases != 0 {
+ t.Errorf("marks=%d releases=%d, want neither on a claim that was never granted", marks, releases)
+ }
+}
+
+// A message the adapter CAN read is the Router's to claim. The adapter must
+// not claim it here, or the Router's own Claim sees a duplicate and the
+// message is dropped without ever reaching the agent.
+func TestUnsupportedReceipt_AReadableMessageIsNotClaimedByTheAdapter(t *testing.T) {
+ t.Parallel()
+ dedup := newFakeDeduper()
+ handled := false
+ c := dedupChannel(t, dedup)
+ c.handler = func(context.Context, channel.InboundMessage) error { handled = true; return nil }
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "text", "hello"), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if !handled {
+ t.Fatal("a text message did not reach the handler")
+ }
+ if claims, _, _ := dedup.counts(); claims != 0 {
+ t.Errorf("the adapter claimed %d readable message(s); the Router claims those, and a double "+
+ "claim makes it see a duplicate and drop the message before the agent ever sees it", claims)
+ }
+}
+
+// Without a dedup wired the receipt still goes out — the behaviour every
+// caller that does not pass ChannelDeps.Dedup keeps.
+func TestUnsupportedReceipt_NoDedupWiredStillAnswersOnce(t *testing.T) {
+ t.Parallel()
+ c := testChannel(func(context.Context, channel.InboundMessage) error { return nil })
+ c.installationID = mustTestUUID(t)
+ conn := &recordingConn{}
+ sender := conn.autoAck(newWSSender(conn, nil))
+
+ if err := c.dispatchFrame(context.Background(),
+ msgCallbackFrame(t, "location", ""), sender, slog.Default()); err != nil {
+ t.Fatalf("dispatchFrame: %v", err)
+ }
+ if n := sendFrames(t, conn); n != 1 {
+ t.Errorf("send frames = %d, want 1 with no dedup configured", n)
+ }
+}
diff --git a/server/internal/integrations/wecom/wecom_channel.go b/server/internal/integrations/wecom/wecom_channel.go
index 6c18b5decb..77e0cea729 100644
--- a/server/internal/integrations/wecom/wecom_channel.go
+++ b/server/internal/integrations/wecom/wecom_channel.go
@@ -29,6 +29,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"github.com/multica-ai/multica/server/internal/util"
)
@@ -73,6 +74,13 @@ const unsupportedMsgTypeReceipt = "抱歉,我暂时无法处理这类消息。
// registered Factory and drives lease / reconnect lifecycle; Connect blocks
// on the receive loop until ctx is cancelled or the link drops.
type wecomChannel struct {
+ // dedup claims the inbound message id for the one reply this adapter sends
+ // before the Router sees the message: the unsupported-kind receipt. It goes
+ // out from dispatchFrame, ahead of c.handler, so the Router's own Claim
+ // never runs for it and nothing else can dedupe it. Nil leaves it
+ // unclaimed, which is main's behaviour.
+ dedup engine.Deduper
+
installationID pgtype.UUID
botID string
secret string
@@ -467,9 +475,8 @@ 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)
- if err := sender.sendText(msg.Source.ChatID, aibotChatTypeFromChannel(msg.Source.ChatType), unsupportedMsgTypeReceipt); err != nil {
- log.Debug("wecom: unsupported-kind receipt send failed", "error", err, "msg_id", mc.MsgID)
- }
+ c.sendUnsupportedReceipt(ctx, sender, mc.MsgID, msg.Source.ChatID,
+ aibotChatTypeFromChannel(msg.Source.ChatType), unsupportedMsgTypeReceipt, log)
return nil
}
if err := c.handler(ctx, msg); err != nil {
@@ -589,6 +596,13 @@ var ErrSendNotSupported = errors.New("wecom: Channel.Send is not supported; outb
// channel.Config.Handler; the CredentialsResolver decrypts the stored
// secret.
type ChannelDeps struct {
+ // Dedup claims the unsupported-kind receipt so a redelivered callback does
+ // not answer twice. Build it with NewDeduper(store) — the same store the
+ // Router's own claim uses, so a message answered here can never also be
+ // answered there. Nil keeps main's behaviour: every redelivery repeats the
+ // receipt, and RegisterWecom says so at WARN.
+ Dedup engine.Deduper
+
Credentials CredentialsResolver
Logger *slog.Logger
@@ -611,12 +625,101 @@ type ChannelDeps struct {
WSURL string
}
+// sendUnsupportedReceipt answers a message kind the adapter cannot read, once
+// per message rather than once per delivery.
+//
+// WeCom redelivers a callback it did not get an ack for, and the receipt is
+// sent from dispatchFrame — before c.handler, so the Router's own Claim
+// (router.go) never runs for this message and nothing downstream deduplicates
+// it. Unclaimed, every redelivery of one unreadable photo puts another "sorry,
+// I can only read text" in the chat, and each copy spends one of the
+// conversation's active pushes.
+//
+// The claim is the same two-phase token the Router uses, on the same table and
+// the same (installation, message) key, so a message answered here can never
+// also be answered there.
+//
+// Three outcomes, and the failure directions are chosen so the user's worst
+// case is the behaviour they already had:
+//
+// - already claimed → the receipt is on their screen; say nothing.
+// - sent → Mark it processed, and later redeliveries stop at the claim.
+// - send failed → Release, so the NEXT redelivery may try again. Holding the
+// claim would turn one failed send into permanent silence for a message
+// the user is waiting on an answer for.
+//
+// A dedup that errors (or is not wired) falls through and sends anyway: with
+// 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.
+func (c *wecomChannel) sendUnsupportedReceipt(
+ ctx context.Context,
+ sender *wsSender,
+ messageID, chatID string,
+ chatType int,
+ content string,
+ log *slog.Logger,
+) {
+ var (
+ token pgtype.UUID
+ claimed bool
+ )
+ if c.dedup != nil && messageID != "" {
+ tok, err := c.dedup.Claim(ctx, c.installationID, messageID)
+ switch {
+ case errors.Is(err, engine.ErrDuplicate):
+ // A redelivery of a message already answered. The receipt the
+ // user is meant to read is the one they already have.
+ log.Debug("wecom: unsupported-kind receipt already sent for this message, not repeating",
+ "msg_id", messageID)
+ return
+ case err != nil:
+ log.Warn("wecom: cannot claim the unsupported-kind receipt, sending it unclaimed",
+ "error", err, "msg_id", messageID)
+ default:
+ token, claimed = tok, true
+ }
+ }
+
+ if err := sender.sendText(chatID, chatType, content); 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
+ // suppress the redelivery that is this message's only remaining
+ // chance of being answered at all.
+ if rerr := c.dedup.Release(ctx, c.installationID, messageID, token); rerr != nil {
+ log.Warn("wecom: cannot release the unsupported-kind receipt claim; a redelivery will "+
+ "now be silently dropped", "error", rerr, "msg_id", messageID)
+ }
+ }
+ return
+ }
+ if claimed {
+ if err := c.dedup.Mark(ctx, c.installationID, messageID, token); err != nil {
+ log.Warn("wecom: cannot mark the unsupported-kind receipt processed; a redelivery may repeat it",
+ "error", err, "msg_id", messageID)
+ }
+ }
+}
+
// RegisterWecom registers the per-installation wecom smart-bot Factory so
// the engine.Supervisor builds + supervises one wecomChannel per active
// installation. "Adding wecom smart-bot inbound" is this call plus the
// adapter — no engine edit (same contract as lark.RegisterFeishu /
// slack.RegisterSlack).
func RegisterWecom(reg *channel.Registry, deps ChannelDeps) {
+ 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))")
+ }
reg.Register(TypeWecom, newWecomFactory(deps))
}
@@ -645,6 +748,7 @@ func newWecomFactory(deps ChannelDeps) channel.Factory {
}
return &wecomChannel{
installationID: cfg.ID,
+ dedup: deps.Dedup,
botID: creds.BotID,
secret: creds.Secret,
botDisplayName: ic.BotDisplayName,
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index e543b51f56..5ed40707be 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -60,7 +60,7 @@ func NewResolverSet(
set := engine.ResolverSet{
Installation: &installationResolver{store: store},
Identity: &identityResolver{store: store},
- Dedup: &deduper{store: store},
+ Dedup: NewDeduper(store),
Session: &sessionBinder{session: session},
Audit: &auditor{store: store},
OriginType: originWecomChat,
@@ -188,6 +188,11 @@ func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.Resolv
// ---- dedup ----
+// NewDeduper builds the claim store the Router and the adapter share. Both must
+// go through it: they claim the same (installation, message) key on the same
+// table, which is what keeps one message from being answered in both places.
+func NewDeduper(store *Store) engine.Deduper { return &deduper{store: store} }
+
// deduper is the wecom Deduper. It uses the shared channel_inbound_message_dedup
// sqlc queries — the same table Feishu / Slack use — so the two-phase
// idempotency invariant is enforced uniformly across channels.