GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat(chatwoot): thread WhatsApp replies and reactions onto agent messages (#950)
andersonrfsilvaf0e07573abf7
diff --git a/docs/chatwoot.md b/docs/chatwoot.mdindex 7e80d6d5..c0888452 100644--- a/docs/chatwoot.md+++ b/docs/chatwoot.md@@ -614,6 +614,9 @@ With `CHATWOOT_MESSAGE_READ=true`, WhatsApp read receipts update Chatwoot `last_Inbound replies and reactions are threaded onto the message they reference (again via the `WAID:` source-id), so a reply or 👍 lands attached to the right message in the Chatwoot conversation.+- A message sent by an agent from Chatwoot has no `WAID:` source-id. When GOWA stored a link for it (written when the agent reply was delivered), a WhatsApp reply or reaction to it also sets Chatwoot's native `in_reply_to`. Only links written for the current Chatwoot destination (same config, or for the legacy env client the same account) and for the conversation the new message lands in are used; with `CHATWOOT_REOPEN_CONVERSATION=false` a returning contact can get a new conversation, and Chatwoot does not accept a reference across conversations.+- When no link can be used, a reply also starts with the quoted text as a one-line `> excerpt` (80 characters at most), so the context is visible even if Chatwoot cannot attach the reply.+Mirrored reaction notes use the reaction event's own `WAID:<id>` as their source ID. This prevents outgoing reaction echoes from being sent back to WhatsApp when Chatwoot's webhook arrives before the sent-message cache is updated.Agent replies are quoted the other way: when an agent uses **Reply** in Chatwoot, the WhatsApp message quotes the original. The text and every attachment carry the quote, including the audio-to-file fallback; the caption stays on the first attachment only.diff --git a/src/infrastructure/whatsapp/chatwoot_forward_test.go b/src/infrastructure/whatsapp/chatwoot_forward_test.goindex 6ba7cb85..5bbeaded 100644--- a/src/infrastructure/whatsapp/chatwoot_forward_test.go+++ b/src/infrastructure/whatsapp/chatwoot_forward_test.go@@ -6,9 +6,11 @@ import ("errors""net/http""net/http/httptest"+ "strings""testing""github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot")@@ -452,6 +454,136 @@ func TestBuildReactionChatwootContent(t *testing.T) {}}+type replyAttrsTestRepo struct {+ domainChatStorage.IChatStorageRepository+ links map[string]*domainChatStorage.ChatwootMessageLink+}++func (r *replyAttrsTestRepo) GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*domainChatStorage.ChatwootMessageLink, error) {+ return r.links[deviceID+"|"+waMessageID], nil+}++func TestResolveChatwootReplyTarget(t *testing.T) {+ repo := &replyAttrsTestRepo{+ links: map[string]*domainChatStorage.ChatwootMessageLink{+ "device-1|wamid-linked": {ChatwootMessageID: 77, ChatwootConversationID: 10},+ "device-1|wamid-zero-link": {ChatwootMessageID: 0},+ "device-1|wamid-other-config": {ChatwootMessageID: 78, ChatwootConfigID: 9},+ "device-1|wamid-other-account": {ChatwootMessageID: 79, ChatwootAccountID: 2},+ "device-1|wamid-current-config": {ChatwootMessageID: 80, ChatwootConfigID: 5},+ },+ }+ legacy := &chatwoot.Client{AccountID: 1}++ usable := []struct {+ id string+ configID int64+ wantID int+ }{+ {"wamid-linked", 0, 77},+ {"wamid-current-config", 5, 80},+ }+ for _, tc := range usable {+ target := resolveChatwootReplyTarget(legacy, tc.configID, "device-1", repo, tc.id, "")+ if target.link == nil || target.link.ChatwootMessageID != tc.wantID {+ t.Fatalf("%s: expected link %d, got %+v", tc.id, tc.wantID, target.link)+ }+ }++ // No link, a zero id, a link written for another Chatwoot destination+ // (its message id belongs to that server/account), no repository or no+ // device: nothing to thread natively.+ unusable := []struct {+ name string+ repo domainChatStorage.IChatStorageRepository+ device string+ id string+ configID int64+ }{+ {"unknown", repo, "device-1", "wamid-unknown", 0},+ {"zero chatwoot id", repo, "device-1", "wamid-zero-link", 0},+ {"per-device client, other config", repo, "device-1", "wamid-other-config", 5},+ {"legacy client, other account", repo, "device-1", "wamid-other-account", 0},+ {"legacy client, per-device link", repo, "device-1", "wamid-current-config", 0},+ {"nil repo", nil, "device-1", "wamid-linked", 0},+ {"empty device", repo, "", "wamid-linked", 0},+ }+ for _, tc := range unusable {+ target := resolveChatwootReplyTarget(legacy, tc.configID, tc.device, tc.repo, tc.id, "Hello\nthere")+ if target.link != nil {+ t.Fatalf("%s: expected no link, got %+v", tc.name, target.link)+ }+ if target.excerpt != "> Hello there" {+ t.Fatalf("%s: excerpt = %q", tc.name, target.excerpt)+ }+ }++ if target := resolveChatwootReplyTarget(legacy, 0, "device-1", repo, "wamid-linked", " "); target.excerpt != "" {+ t.Fatalf("blank quoted body must not produce an excerpt, got %q", target.excerpt)+ }+}++func TestChatwootReplyTargetApply(t *testing.T) {+ link := &domainChatStorage.ChatwootMessageLink{ChatwootMessageID: 77, ChatwootConversationID: 10}+ newOpts := func() chatwoot.MessageOptions {+ return chatwoot.MessageOptions{ContentAttributes: map[string]any{"in_reply_to_external_id": "WAID:x"}}+ }++ tests := []struct {+ name string+ target *chatwootReplyTarget+ conversationID int+ content string+ wantContent string+ wantInReplyTo any // nil: must not be set+ }{+ {"link in this conversation", &chatwootReplyTarget{link: link, excerpt: "> hi"}, 10, "ok", "ok", 77},+ // A returning contact can get a new conversation+ // (CHATWOOT_REOPEN_CONVERSATION=false); Chatwoot rejects in_reply_to+ // across conversations, so fall back to the excerpt.+ {"link in another conversation", &chatwootReplyTarget{link: link, excerpt: "> hi"}, 11, "ok", "> hi\n\nok", nil},+ {"reaction link in another conversation", &chatwootReplyTarget{link: link}, 11, "Alice reacted 👍", "Alice reacted 👍", nil},+ {"no link, excerpt only", &chatwootReplyTarget{excerpt: "> hi"}, 10, "ok", "> hi\n\nok", nil},+ {"no link, empty content", &chatwootReplyTarget{excerpt: "> hi"}, 10, "", "> hi", nil},+ {"nil target", nil, 10, "ok", "ok", nil},+ }+ for _, tt := range tests {+ opts := newOpts()+ got := tt.target.apply(tt.conversationID, tt.content, &opts)+ if got != tt.wantContent {+ t.Fatalf("%s: content = %q, want %q", tt.name, got, tt.wantContent)+ }+ inReplyTo, set := opts.ContentAttributes["in_reply_to"]+ if tt.wantInReplyTo == nil && set {+ t.Fatalf("%s: in_reply_to must not be set, got %v", tt.name, inReplyTo)+ }+ if tt.wantInReplyTo != nil && inReplyTo != tt.wantInReplyTo {+ t.Fatalf("%s: in_reply_to = %v, want %v", tt.name, inReplyTo, tt.wantInReplyTo)+ }+ }+}++func TestOneLineExcerpt(t *testing.T) {+ tests := []struct {+ name string+ in string+ max int+ want string+ }{+ {name: "collapses newlines and spaces", in: " olá,\n como vai? ", max: 80, want: "olá, como vai?"},+ {name: "truncates with ellipsis", in: strings.Repeat("b", 90), max: 80, want: strings.Repeat("b", 80) + "…"},+ {name: "short string unchanged", in: "oi", max: 80, want: "oi"},+ {name: "empty string", in: "", max: 80, want: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := oneLineExcerpt(tt.in, tt.max); got != tt.want {+ t.Fatalf("oneLineExcerpt(%q) = %q, want %q", tt.in, got, tt.want)+ }+ })+ }+}+func TestSyncPayloadToChatwoot_ReactionEchoStampsSourceID(t *testing.T) {var capturedBody map[string]anyserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.goindex 39340a89..bc0733e1 100644--- a/src/infrastructure/whatsapp/webhook_forward.go+++ b/src/infrastructure/whatsapp/webhook_forward.go@@ -835,6 +835,75 @@ func buildReactionChatwootContent(data map[string]any, fromName string) string {return fmt.Sprintf("%s reacted %s", actor, reaction)}+const quotedExcerptMaxRunes = 80++// oneLineExcerpt collapses whitespace/newlines into single spaces and truncates+// to maxRunes (appending an ellipsis), so quoted excerpts stay on one line.+func oneLineExcerpt(s string, maxRunes int) string {+ s = strings.Join(strings.Fields(s), " ")+ if runes := []rune(s); len(runes) > maxRunes {+ s = string(runes[:maxRunes]) + "…"+ }+ return s+}++// chatwootReplyTarget threads a WhatsApp reply or reaction onto the message it+// references. in_reply_to_external_id (WAID:<id>) is always set and resolves+// only for messages that carry that source_id, i.e. messages mirrored from+// WhatsApp. Agent replies sent from Chatwoot have none, so the stored link is+// kept to set the native in_reply_to once the target conversation is known+// (see apply).+type chatwootReplyTarget struct {+ link *domainChatStorage.ChatwootMessageLink // nil when no usable link+ excerpt string // "> ..." quote; empty for reactions+}++// resolveChatwootReplyTarget looks up the link for repliedToID. A link is used+// only when it was written for the current Chatwoot destination+// (chatwootLinkMatchesClient): Chatwoot message ids repeat across servers and+// accounts. quotedBody, when set, becomes the inline excerpt shown if the link+// cannot be used.+func resolveChatwootReplyTarget(cw *chatwoot.Client, configID int64, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, repliedToID, quotedBody string) *chatwootReplyTarget {+ target := &chatwootReplyTarget{}+ if strings.TrimSpace(quotedBody) != "" {+ target.excerpt = "> " + oneLineExcerpt(quotedBody, quotedExcerptMaxRunes)+ }+ if linkRepo == nil || deviceID == "" {+ return target+ }+ link, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, repliedToID)+ if err != nil {+ logrus.Warnf("Chatwoot: Failed to resolve quoted message link for %s: %v", repliedToID, err)+ return target+ }+ if link != nil && link.ChatwootMessageID != 0 && chatwootLinkMatchesClient(link, cw, configID) {+ target.link = link+ }+ return target+}++// apply sets the native in_reply_to when the linked message is in+// conversationID: Chatwoot rejects a reference to another conversation, which+// happens when a returning contact gets a new conversation+// (CHATWOOT_REOPEN_CONVERSATION=false). Otherwise the excerpt, if any, is+// prepended to content. opts.ContentAttributes must already be set.+func (r *chatwootReplyTarget) apply(conversationID int, content string, opts *chatwoot.MessageOptions) string {+ if r == nil {+ return content+ }+ if r.link != nil && r.link.ChatwootConversationID == conversationID {+ opts.ContentAttributes["in_reply_to"] = r.link.ChatwootMessageID+ return content+ }+ if r.excerpt == "" {+ return content+ }+ if content == "" {+ return r.excerpt+ }+ return r.excerpt + "\n\n" + content+}+func chatwootMessageTypeFromPayload(data map[string]any) string {if isFromMe, ok := data["is_from_me"].(bool); ok && isFromMe {return "outgoing"@@ -968,7 +1037,7 @@ func structuredContactsArraySummary(contacts []webhookContactPayload) string {}// syncMessageToChatwoot creates or finds contact/conversation and sends the message.-func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, content string, attachments []string, opts chatwoot.MessageOptions) (*chatwootSyncResult, error) {+func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, content string, attachments []string, opts chatwoot.MessageOptions, reply *chatwootReplyTarget) (*chatwootSyncResult, error) {// Lock per-identifier mutex to prevent duplicate contact/conversation creationmu := getContactMutex(info.Identifier)mu.Lock()@@ -986,6 +1055,7 @@ func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, contereturn nil, fmt.Errorf("failed to find/create conversation for contact %d: %w", contact.ID, err)}logrus.Infof("Chatwoot: Conversation ID: %d", conversation.ID)+ content = reply.apply(conversation.ID, content, &opts)logrus.Infof("Chatwoot: Creating message (Length: %d, Attachments: %d)", len(content), len(attachments))messageType := "incoming"@@ -1659,6 +1729,7 @@ func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventNamcontent stringattachments []stringmsgOpts chatwoot.MessageOptions+ reply *chatwootReplyTarget // resolved against the conversation in syncMessageToChatwoot)switch eventName {case "message.reaction":@@ -1668,6 +1739,7 @@ func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventNam}if rid, _ := data["reacted_message_id"].(string); rid != "" {msgOpts.ContentAttributes = map[string]any{"in_reply_to_external_id": "WAID:" + rid}+ reply = resolveChatwootReplyTarget(cw, resolved.ConfigID, deviceID, linkRepo, rid, "")}case "message.edited", "message.revoked", "message.deleted":var threadID string@@ -1686,6 +1758,8 @@ func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventNam}if rid, _ := data["replied_to_id"].(string); rid != "" {msgOpts.ContentAttributes = map[string]any{"in_reply_to_external_id": "WAID:" + rid}+ quoted, _ := data["quoted_body"].(string)+ reply = resolveChatwootReplyTarget(cw, resolved.ConfigID, deviceID, linkRepo, rid, quoted)}}info.IsFromMe = chatwootMessageTypeFromPayload(data) == "outgoing"@@ -1705,7 +1779,7 @@ func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventNam}}- result, err := syncMessageToChatwoot(cw, info, content, attachments, msgOpts)+ result, err := syncMessageToChatwoot(cw, info, content, attachments, msgOpts, reply)if err != nil {return err}