Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(chatwoot): send Chatwoot agent replies as quoted WhatsApp replies (#885)

felipemotter19d6c9959754
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index 2cb38024..1cbae0a1 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -614,6 +614,12 @@ 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.
+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.
+
+- A message mirrored from WhatsApp (`in_reply_to_external_id` is `WAID:<id>`) is quoted only when it is in the sending device's local message store and belongs to the same chat. An `@lid` chat matches its phone JID when the sending device knows the mapping.
+- An earlier agent message has no `source_id` in Chatwoot, so only its numeric `in_reply_to` arrives. It is resolved through the link GOWA stored when it delivered that message, in the same device, conversation, account, inbox and config; the link and the WhatsApp message it points to, in the sending device's local message store, must belong to the same chat too. A message sent with several attachments is quoted by its first file. The numeric id is not used when a `WAID:` reference is present.
+- A quote that cannot be resolved is not an error: the reply is sent without it, as before, and no failure note is added.
+
### Ignoring chats
`CHATWOOT_IGNORE_JIDS` lets you exclude chats from Chatwoot entirely, on top of the always-ignored system JIDs (`status@broadcast`, `[email protected]`). It accepts a comma-separated list of exact JIDs or the wildcards `@g.us` (all groups), `@s.whatsapp.net` (all DMs), or `@lid`:
@@ -653,6 +659,7 @@ Live WhatsApp messages that hit a transient Chatwoot failure (network error, HTT
| Audio | ✅ | Sent as voice note (PTT) |
| Video | ✅ | - |
| Files | ✅ | Any file type supported |
+| Quoted replies | ✅ | Quotes the original message when it can be resolved (see [Replies & reactions](#replies--reactions)) |
### Group Support
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index d28cc83d..0ec3ecb0 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -97,6 +97,19 @@ type ChatwootMessageLink struct {
ChatwootAccountID int `db:"chatwoot_account_id"`
}
+// ChatwootReplyLinkFilter scopes the lookup of the link behind a quoted
+// Chatwoot message. Every field must match; AllowLegacyAccountZero also lets
+// account 0 (legacy) rows match when ChatwootConfigID is 0.
+type ChatwootReplyLinkFilter struct {
+ DeviceID string
+ ChatwootMessageID int
+ ChatwootConversationID int
+ ChatwootAccountID int
+ ChatwootInboxID int
+ ChatwootConfigID int64
+ AllowLegacyAccountZero bool
+}
+
// ChatwootDeviceConfig is the per-device Chatwoot destination (URL + account +
// inbox + token). It enables routing each WhatsApp device to its own Chatwoot
// inbox. DeviceID is the user-facing device id; DeviceJID mirrors the WhatsApp
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index a32364d0..e54d2153 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -55,6 +55,9 @@ type IChatStorageRepository interface {
UpsertChatwootMessageLink(link *ChatwootMessageLink) error
GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*ChatwootMessageLink, error)
GetChatwootMessageLinkByChatwootID(deviceID string, chatwootMessageID int) (*ChatwootMessageLink, error)
+ // GetChatwootMessageLinkForReply returns the link of a quoted Chatwoot
+ // message within the filter's scope, or nil when there is none.
+ GetChatwootMessageLinkForReply(filter ChatwootReplyLinkFilter) (*ChatwootMessageLink, error)
// GetLatestChatwootMessageLinkByConversation resolves a conversation to its
// most recent link. Conversation ids are numbered per Chatwoot account, so the
// lookup is account-scoped. allowLegacyZero additionally matches rows whose
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 6bd16b6f..822afef2 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -1091,6 +1091,40 @@ func (r *SQLiteRepository) GetChatwootMessageLinkByChatwootID(deviceID string, c
return link, err
}
+// GetChatwootMessageLinkForReply applies the whole scope before LIMIT 1, so a
+// link from another config, account, inbox or conversation is never picked.
+// Several links (one per attachment) resolve to the first one delivered.
+func (r *SQLiteRepository) GetChatwootMessageLinkForReply(filter domainChatStorage.ChatwootReplyLinkFilter) (*domainChatStorage.ChatwootMessageLink, error) {
+ // Account 0 marks a legacy row: it never matches as an account id.
+ if filter.ChatwootAccountID <= 0 {
+ return nil, nil
+ }
+ legacyZero := 0
+ if filter.AllowLegacyAccountZero && filter.ChatwootConfigID == 0 {
+ legacyZero = 1
+ }
+ query := `
+ SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at, chatwoot_config_id, chatwoot_account_id
+ FROM chatwoot_message_links
+ WHERE device_id = ? AND chatwoot_message_id = ? AND chatwoot_conversation_id = ?
+ AND chatwoot_inbox_id = ? AND chatwoot_config_id = ?
+ AND (chatwoot_account_id = ? OR (? = 1 AND chatwoot_account_id = 0))
+ ORDER BY chatwoot_account_id = 0, created_at, wa_message_id
+ LIMIT 1
+ `
+
+ link, err := r.scanChatwootMessageLink(r.db.QueryRow(query,
+ filter.DeviceID, filter.ChatwootMessageID, filter.ChatwootConversationID,
+ filter.ChatwootInboxID, filter.ChatwootConfigID, filter.ChatwootAccountID, legacyZero))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return link, err
+}
+
// chatwootLinkLookupBeforeSelect runs inside the conversation-link transaction
// after the configuration count and before the final select. Production leaves
// it nil. Tests use it to insert another configuration on the same connection
diff --git a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go
index e7e8059d..27324ddb 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go
@@ -405,3 +405,131 @@ func TestSQLiteRepositoryChatwootForwardQueueLifecycle(t *testing.T) {
t.Fatalf("due after done len = %d, want 0", len(due))
}
}
+
+// replyLink is a link in the synthetic reply scope: Chatwoot message 41 of
+// conversation 7 (account 3, inbox 5, config 11), sent by device-a to peer-a.
+func replyLink(waMessageID string, createdAt time.Time) *domainChatStorage.ChatwootMessageLink {
+ return &domainChatStorage.ChatwootMessageLink{
+ DeviceID: "[email protected]", WhatsAppMessageID: waMessageID, WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 41, ChatwootConversationID: 7, ChatwootAccountID: 3, ChatwootInboxID: 5, ChatwootConfigID: 11,
+ Direction: "outgoing", CreatedAt: createdAt,
+ }
+}
+
+func replyLinkFilter() domainChatStorage.ChatwootReplyLinkFilter {
+ return domainChatStorage.ChatwootReplyLinkFilter{
+ DeviceID: "[email protected]", ChatwootMessageID: 41, ChatwootConversationID: 7,
+ ChatwootAccountID: 3, ChatwootInboxID: 5, ChatwootConfigID: 11,
+ }
+}
+
+// storeReplyLinks returns a fresh repository holding links.
+func storeReplyLinks(t *testing.T, links ...*domainChatStorage.ChatwootMessageLink) *SQLiteRepository {
+ t.Helper()
+ repo := newTestSQLiteRepository(t)
+ for _, link := range links {
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("upsert %s: %v", link.WhatsAppMessageID, err)
+ }
+ }
+ return repo
+}
+
+// findReplyLink returns the WhatsApp id of the link found for filter, or "".
+func findReplyLink(t *testing.T, repo *SQLiteRepository, filter domainChatStorage.ChatwootReplyLinkFilter) string {
+ t.Helper()
+ link, err := repo.GetChatwootMessageLinkForReply(filter)
+ if err != nil {
+ t.Fatalf("GetChatwootMessageLinkForReply: %v", err)
+ }
+ if link == nil {
+ return ""
+ }
+ return link.WhatsAppMessageID
+}
+
+// The scope is applied before LIMIT 1. A link that differs in one field is
+// older and sorts first, so it would be returned if that field were left out
+// of the query; on its own it is never returned.
+func TestSQLiteRepositoryReplyLinkLookupScopesBeforeLimit(t *testing.T) {
+ base := time.Date(2026, time.October, 1, 9, 0, 0, 0, time.UTC)
+ cases := map[string]func(*domainChatStorage.ChatwootMessageLink){
+ "device": func(l *domainChatStorage.ChatwootMessageLink) { l.DeviceID = "[email protected]" },
+ "message": func(l *domainChatStorage.ChatwootMessageLink) { l.ChatwootMessageID = 40 },
+ "conversation": func(l *domainChatStorage.ChatwootMessageLink) { l.ChatwootConversationID = 8 },
+ "account": func(l *domainChatStorage.ChatwootMessageLink) { l.ChatwootAccountID = 4 },
+ "inbox": func(l *domainChatStorage.ChatwootMessageLink) { l.ChatwootInboxID = 6 },
+ "config": func(l *domainChatStorage.ChatwootMessageLink) { l.ChatwootConfigID = 0 },
+ }
+ for field, differ := range cases {
+ t.Run(field, func(t *testing.T) {
+ other := replyLink("WA-A-OTHER", base)
+ differ(other)
+ repo := storeReplyLinks(t, other)
+ if got := findReplyLink(t, repo, replyLinkFilter()); got != "" {
+ t.Fatalf("only a link of another %s: got %q, want none", field, got)
+ }
+ if err := repo.UpsertChatwootMessageLink(replyLink("WA-B-MATCH", base.Add(time.Minute))); err != nil {
+ t.Fatalf("upsert WA-B-MATCH: %v", err)
+ }
+ if got := findReplyLink(t, repo, replyLinkFilter()); got != "WA-B-MATCH" {
+ t.Fatalf("next to a link of another %s: got %q, want WA-B-MATCH", field, got)
+ }
+ })
+ }
+}
+
+// Account 0 (legacy) rows match only when the caller allows them and the
+// config is 0. Config 0 is an equality, never a wildcard, and the exact
+// account comes before an older legacy row.
+func TestSQLiteRepositoryReplyLinkLookupLegacyAccountZero(t *testing.T) {
+ base := time.Date(2026, time.October, 1, 9, 0, 0, 0, time.UTC)
+ link := func(waMessageID string, accountID int, configID int64, minute int) *domainChatStorage.ChatwootMessageLink {
+ l := replyLink(waMessageID, base.Add(time.Duration(minute)*time.Minute))
+ l.ChatwootAccountID, l.ChatwootConfigID = accountID, configID
+ return l
+ }
+ filter := func(accountID int, configID int64, allowLegacy bool) domainChatStorage.ChatwootReplyLinkFilter {
+ f := replyLinkFilter()
+ f.ChatwootAccountID, f.ChatwootConfigID, f.AllowLegacyAccountZero = accountID, configID, allowLegacy
+ return f
+ }
+ cases := []struct {
+ name string
+ filter domainChatStorage.ChatwootReplyLinkFilter
+ links []*domainChatStorage.ChatwootMessageLink
+ want string
+ }{
+ {"legacy row allowed", filter(3, 0, true), []*domainChatStorage.ChatwootMessageLink{link("WA-LEGACY", 0, 0, 0)}, "WA-LEGACY"},
+ {"legacy row not allowed", filter(3, 0, false), []*domainChatStorage.ChatwootMessageLink{link("WA-LEGACY", 0, 0, 0)}, ""},
+ {"account 0 under a config", filter(3, 11, true), []*domainChatStorage.ChatwootMessageLink{link("WA-LEGACY", 0, 11, 0)}, ""},
+ {"legacy row of another account", filter(3, 0, true), []*domainChatStorage.ChatwootMessageLink{link("WA-OTHER", 4, 0, 0)}, ""},
+ {"config 0 is not a wildcard", filter(3, 0, true), []*domainChatStorage.ChatwootMessageLink{link("WA-CURRENT", 3, 11, 0)}, ""},
+ {"no account", filter(0, 0, false), []*domainChatStorage.ChatwootMessageLink{link("WA-LEGACY", 0, 0, 0)}, ""},
+ {"exact account before an older legacy row", filter(3, 0, true),
+ []*domainChatStorage.ChatwootMessageLink{link("WA-A-LEGACY", 0, 0, 0), link("WA-B-EXACT", 3, 0, 1)}, "WA-B-EXACT"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := findReplyLink(t, storeReplyLinks(t, tc.links...), tc.filter); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// A message sent with several attachments has one link per file; the lookup
+// returns the first one delivered, whatever the insertion order.
+func TestSQLiteRepositoryReplyLinkLookupPicksTheFirstFile(t *testing.T) {
+ base := time.Date(2026, time.October, 1, 9, 0, 0, 0, time.UTC)
+ first, second := replyLink("WA-Z-FIRST", base), replyLink("WA-A-SECOND", base.Add(time.Second))
+ if got := findReplyLink(t, storeReplyLinks(t, first, second), replyLinkFilter()); got != "WA-Z-FIRST" {
+ t.Fatalf("first stored first: got %q, want WA-Z-FIRST", got)
+ }
+ if got := findReplyLink(t, storeReplyLinks(t, second, first), replyLinkFilter()); got != "WA-Z-FIRST" {
+ t.Fatalf("first stored last: got %q, want WA-Z-FIRST", got)
+ }
+ if got := findReplyLink(t, storeReplyLinks(t, replyLink("WA-B", base), replyLink("WA-A", base)), replyLinkFilter()); got != "WA-A" {
+ t.Fatalf("same created_at: got %q, want the lowest WhatsApp id WA-A", got)
+ }
+}
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index c2d7c70f..aaaf396c 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -175,6 +175,13 @@ func (r *deviceChatStorage) GetChatwootMessageLinkByChatwootID(deviceID string,
return r.base.GetChatwootMessageLinkByChatwootID(targetDeviceID, chatwootMessageID)
}
+func (r *deviceChatStorage) GetChatwootMessageLinkForReply(filter domainChatStorage.ChatwootReplyLinkFilter) (*domainChatStorage.ChatwootMessageLink, error) {
+ if filter.DeviceID == "" {
+ filter.DeviceID = r.deviceID
+ }
+ return r.base.GetChatwootMessageLinkForReply(filter)
+}
+
func (r *deviceChatStorage) GetLatestChatwootMessageLinkByConversation(conversationID, accountID int, allowLegacyZero bool, configID int64) (*domainChatStorage.ChatwootMessageLink, error) {
return r.base.GetLatestChatwootMessageLinkByConversation(conversationID, accountID, allowLegacyZero, configID)
}
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper_test.go b/src/infrastructure/whatsapp/chatstorage_wrapper_test.go
new file mode 100644
index 00000000..5ee3c2af
--- /dev/null
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper_test.go
@@ -0,0 +1,49 @@
+package whatsapp
+
+import (
+ "errors"
+ "testing"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+// replyLinkSpy records the filters that reach the base repository.
+type replyLinkSpy struct {
+ domainChatStorage.IChatStorageRepository
+ filters []domainChatStorage.ChatwootReplyLinkFilter
+ link *domainChatStorage.ChatwootMessageLink
+ err error
+}
+
+func (s *replyLinkSpy) GetChatwootMessageLinkForReply(filter domainChatStorage.ChatwootReplyLinkFilter) (*domainChatStorage.ChatwootMessageLink, error) {
+ s.filters = append(s.filters, filter)
+ return s.link, s.err
+}
+
+// The wrapper fills an empty device with its own, keeps an explicit one,
+// passes the other fields unchanged and returns the base result as is.
+func TestDeviceChatStorageGetChatwootMessageLinkForReply(t *testing.T) {
+ filter := domainChatStorage.ChatwootReplyLinkFilter{
+ ChatwootMessageID: 41, ChatwootConversationID: 7, ChatwootAccountID: 3,
+ ChatwootInboxID: 5, ChatwootConfigID: 11, AllowLegacyAccountZero: true,
+ }
+ for _, tc := range []struct{ device, want string }{
+ } {
+ spy := &replyLinkSpy{link: &domainChatStorage.ChatwootMessageLink{WhatsAppMessageID: "WA-ORIG"}, err: errors.New("database is locked")}
+ in := filter
+ in.DeviceID = tc.device
+
+ link, err := newDeviceChatStorage("[email protected]", spy).GetChatwootMessageLinkForReply(in)
+
+ want := filter
+ want.DeviceID = tc.want
+ if len(spy.filters) != 1 || spy.filters[0] != want {
+ t.Fatalf("device %q: base filters = %+v, want [%+v]", tc.device, spy.filters, want)
+ }
+ if link != spy.link || !errors.Is(err, spy.err) {
+ t.Fatalf("device %q: got (%v, %v), want the base result", tc.device, link, err)
+ }
+ }
+}
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index 9c1781d4..5477f62b 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -606,6 +606,10 @@ func (h *ChatwootHandler) deliverChatwootReply(c fiber.Ctx, payload chatwoot.Web
// the same composed body.
outgoingText := composeOutgoingText(payload)
+ // The message the agent replied to, quoted by the text and by every
+ // attachment; nil sends them without a quote.
+ replyMessageID := h.chatwootReplyMessageID(ctx, payload, route, storageDeviceID, linkChatJID)
+
// Handle attachments if present
if len(payload.Attachments) > 0 {
sentAny := false
@@ -617,7 +621,7 @@ func (h *ChatwootHandler) deliverChatwootReply(c fiber.Ctx, payload chatwoot.Web
if i == 0 {
caption = outgoingText
}
- resp, err := h.handleAttachment(ctx, sendDestination, attachment, caption)
+ resp, err := h.handleAttachment(ctx, sendDestination, attachment, caption, replyMessageID)
if err != nil {
logrus.Errorf("Chatwoot Webhook: Failed to send attachment %d: %v", attachment.ID, err)
h.notifySendFailure(payload, route, fmt.Errorf("attachment %d failed: %w", attachment.ID, err))
@@ -636,7 +640,8 @@ func (h *ChatwootHandler) deliverChatwootReply(c fiber.Ctx, payload chatwoot.Web
// If content is present (and not just an attachment caption), send it as text
if outgoingText != "" {
req := domainSend.MessageRequest{
- Message: outgoingText,
+ Message: outgoingText,
+ ReplyMessageID: replyMessageID,
}
req.Phone = sendDestination
@@ -659,6 +664,79 @@ func (h *ChatwootHandler) deliverChatwootReply(c fiber.Ctx, payload chatwoot.Web
return c.SendStatus(fiber.StatusOK)
}
+// chatwootReplyMessageID returns the WhatsApp message that an agent reply
+// quotes, or nil to send the reply without a quote.
+func (h *ChatwootHandler) chatwootReplyMessageID(ctx context.Context, payload chatwoot.WebhookPayload, route chatwootWebhookRoute, deviceID, chatJID string) *string {
+ if h.ChatStorageRepo == nil {
+ return nil
+ }
+ // A message mirrored from WhatsApp carries its id as "WAID:<id>". Quote it
+ // only if it is stored for this device and belongs to the reply's chat.
+ if ref, _ := payload.ContentAttributes["in_reply_to_external_id"].(string); strings.HasPrefix(ref, "WAID:") {
+ waMessageID := strings.TrimPrefix(ref, "WAID:")
+ if !h.storedMessageInChat(ctx, deviceID, waMessageID, chatJID) {
+ return nil
+ }
+ return &waMessageID
+ }
+
+ // An earlier agent reply has no source_id, only its Chatwoot id. Find the
+ // link stored when it was delivered, in the scope storeChatwootOutboundLink
+ // writes. JSON numbers decode as float64; take exact positive integers only.
+ number, _ := payload.ContentAttributes["in_reply_to"].(float64)
+ quotedID := int(number)
+ if number < 1 || number >= 1<<53 || float64(quotedID) != number {
+ return nil
+ }
+ inboxID := route.InboxID
+ if inboxID == 0 {
+ inboxID = payload.Conversation.InboxID
+ }
+ link, err := h.ChatStorageRepo.GetChatwootMessageLinkForReply(domainChatStorage.ChatwootReplyLinkFilter{
+ DeviceID: deviceID,
+ ChatwootMessageID: quotedID,
+ ChatwootConversationID: payload.Conversation.ID,
+ ChatwootAccountID: route.AccountID,
+ ChatwootInboxID: inboxID,
+ ChatwootConfigID: route.ConfigID,
+ AllowLegacyAccountZero: h.legacyChatwootMode(),
+ })
+ if err != nil {
+ logrus.Warnf("Chatwoot Webhook: failed to look up quoted Chatwoot message %d: %v", quotedID, err)
+ return nil
+ }
+ // The link and the stored row the quote is built from must both be in the
+ // reply's chat: another chat may hold a row with the same WhatsApp id.
+ if link == nil || !chatwootSameChat(ctx, link.WhatsAppChatJID, chatJID) ||
+ !h.storedMessageInChat(ctx, deviceID, link.WhatsAppMessageID, chatJID) {
+ return nil
+ }
+ return &link.WhatsAppMessageID
+}
+
+// storedMessageInChat reports whether the row the send path quotes from
+// (GetMessageByIDAndDevice, which does not filter by chat) is in chatJID.
+func (h *ChatwootHandler) storedMessageInChat(ctx context.Context, deviceID, id, chatJID string) bool {
+ message, err := h.ChatStorageRepo.GetMessageByIDAndDevice(deviceID, id)
+ if err != nil {
+ logrus.Warnf("Chatwoot Webhook: failed to read quoted message %s: %v", id, err)
+ return false
+ }
+ return message != nil && chatwootSameChat(ctx, message.ChatJID, chatJID)
+}
+
+// chatwootSameChat reports whether two JIDs name the same chat. An @lid side
+// is mapped to its phone JID by the sending device, as the send path does.
+func chatwootSameChat(ctx context.Context, a, b string) bool {
+ jidA, errA := utils.ParseJID(a)
+ jidB, errB := utils.ParseJID(b)
+ if errA != nil || errB != nil {
+ return false
+ }
+ client := whatsapp.ClientFromContext(ctx)
+ return utils.ResolveLIDToPhone(ctx, jidA, client).ToNonAD() == utils.ResolveLIDToPhone(ctx, jidB, client).ToNonAD()
+}
+
func (h *ChatwootHandler) handleDeletedChatwootMessage(c fiber.Ctx, payload chatwoot.WebhookPayload, forced *chatwootWebhookRoute) error {
if !config.ChatwootMessageDelete {
return c.SendStatus(fiber.StatusOK)
@@ -843,15 +921,18 @@ func (h *ChatwootHandler) notifySendFailure(payload chatwoot.WebhookPayload, rou
}
}
-func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, att chatwoot.Attachment, caption string) (domainSend.GenericResponse, error) {
+// handleAttachment sends one Chatwoot attachment; replyMessageID (nil for none)
+// is quoted by every request, including the audio-to-file fallback.
+func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, att chatwoot.Attachment, caption string, replyMessageID *string) (domainSend.GenericResponse, error) {
// Chatwoot serves attachments from its own, possibly private, host.
ctx = utils.WithChatwootAttachmentFetch(ctx)
switch att.FileType {
case "image":
req := domainSend.ImageRequest{
- BaseRequest: domainSend.BaseRequest{Phone: phone},
- Caption: caption,
- ImageURL: &att.DataURL,
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ Caption: caption,
+ ImageURL: &att.DataURL,
+ ReplyMessageID: replyMessageID,
}
resp, err := h.SendUsecase.SendImage(ctx, req)
if err == nil {
@@ -861,9 +942,10 @@ func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, at
case "audio":
req := domainSend.AudioRequest{
- BaseRequest: domainSend.BaseRequest{Phone: phone},
- AudioURL: &att.DataURL,
- PTT: true, // Send as PTT (Voice Note) for better mobile experience
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ AudioURL: &att.DataURL,
+ PTT: true, // Send as PTT (Voice Note) for better mobile experience
+ ReplyMessageID: replyMessageID,
}
resp, err := h.SendUsecase.SendAudio(ctx, req)
if err == nil {
@@ -874,9 +956,10 @@ func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, at
logrus.Warnf("Chatwoot Webhook: Failed to send as audio (%v), retrying as file...", err)
// Fallback to sending as file
reqFile := domainSend.FileRequest{
- BaseRequest: domainSend.BaseRequest{Phone: phone},
- FileURL: &att.DataURL,
- Caption: caption,
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ FileURL: &att.DataURL,
+ Caption: caption,
+ ReplyMessageID: replyMessageID,
}
resp, err = h.SendUsecase.SendFile(ctx, reqFile)
if err == nil {
@@ -886,9 +969,10 @@ func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, at
case "video":
req := domainSend.VideoRequest{
- BaseRequest: domainSend.BaseRequest{Phone: phone},
- Caption: caption,
- VideoURL: &att.DataURL,
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ Caption: caption,
+ VideoURL: &att.DataURL,
+ ReplyMessageID: replyMessageID,
}
resp, err := h.SendUsecase.SendVideo(ctx, req)
if err == nil {
@@ -899,9 +983,10 @@ func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, at
default:
// Default to file for other types
req := domainSend.FileRequest{
- BaseRequest: domainSend.BaseRequest{Phone: phone},
- FileURL: &att.DataURL,
- Caption: caption,
+ BaseRequest: domainSend.BaseRequest{Phone: phone},
+ FileURL: &att.DataURL,
+ Caption: caption,
+ ReplyMessageID: replyMessageID,
}
resp, err := h.SendUsecase.SendFile(ctx, req)
if err == nil {
diff --git a/src/ui/rest/chatwoot_reply_test.go b/src/ui/rest/chatwoot_reply_test.go
new file mode 100644
index 00000000..34369a0c
--- /dev/null
+++ b/src/ui/rest/chatwoot_reply_test.go
@@ -0,0 +1,771 @@
+package rest
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "sync/atomic"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/gofiber/fiber/v3"
+ "go.mau.fi/whatsmeow"
+ "go.mau.fi/whatsmeow/store"
+ "go.mau.fi/whatsmeow/types"
+)
+
+// Synthetic fixtures: slot-a sends as device-a to peer-a, in Chatwoot
+// conversation 7 (account 3, inbox 5).
+const (
+ replyTestDevice = "[email protected]"
+ replyTestChat = "[email protected]"
+ replyTestLID = "peer-a@lid"
+ replyTestURL = "https://files.example.test/a.bin"
+)
+
+// replySend is one send made by the webhook handler; reply is "" when the
+// request carries no quote.
+type replySend struct {
+ method, phone, text, url, reply string
+ ptt bool
+ device *whatsapp.DeviceInstance
+}
+
+// replySendStub records the sends; fail maps a 1-based call number to its error.
+type replySendStub struct {
+ domainSend.ISendUsecase
+ calls []replySend
+ fail map[int]error
+}
+
+func (s *replySendStub) record(ctx context.Context, call replySend, reply *string) (domainSend.GenericResponse, error) {
+ if reply != nil {
+ call.reply = *reply
+ }
+ call.device, _ = whatsapp.DeviceFromContext(ctx)
+ s.calls = append(s.calls, call)
+ if err := s.fail[len(s.calls)]; err != nil {
+ return domainSend.GenericResponse{}, err
+ }
+ return domainSend.GenericResponse{MessageID: fmt.Sprintf("WA-SENT-%d", len(s.calls))}, nil
+}
+
+func (s *replySendStub) SendText(ctx context.Context, r domainSend.MessageRequest) (domainSend.GenericResponse, error) {
+ return s.record(ctx, replySend{method: "SendText", phone: r.Phone, text: r.Message}, r.ReplyMessageID)
+}
+
+func (s *replySendStub) SendImage(ctx context.Context, r domainSend.ImageRequest) (domainSend.GenericResponse, error) {
+ return s.record(ctx, replySend{method: "SendImage", phone: r.Phone, text: r.Caption, url: *r.ImageURL}, r.ReplyMessageID)
+}
+
+func (s *replySendStub) SendAudio(ctx context.Context, r domainSend.AudioRequest) (domainSend.GenericResponse, error) {
+ return s.record(ctx, replySend{method: "SendAudio", phone: r.Phone, url: *r.AudioURL, ptt: r.PTT}, r.ReplyMessageID)
+}
+
+func (s *replySendStub) SendVideo(ctx context.Context, r domainSend.VideoRequest) (domainSend.GenericResponse, error) {
+ return s.record(ctx, replySend{method: "SendVideo", phone: r.Phone, text: r.Caption, url: *r.VideoURL}, r.ReplyMessageID)
+}
+
+func (s *replySendStub) SendFile(ctx context.Context, r domainSend.FileRequest) (domainSend.GenericResponse, error) {
+ return s.record(ctx, replySend{method: "SendFile", phone: r.Phone, text: r.Caption, url: *r.FileURL}, r.ReplyMessageID)
+}
+
+// replyRepo adds the reads and writes of the reply path to the route stub.
+// A stored message is returned even with messageErr, so the handler must
+// check the error itself.
+type replyRepo struct {
+ chatwootRouteTestRepo
+ messages map[string]domainChatStorage.Message // by device + " " + id
+ messageErr error
+ reads []string
+ links []domainChatStorage.ChatwootMessageLink
+ writes int
+ writeErr error
+ lookups []domainChatStorage.ChatwootReplyLinkFilter
+ lookupErr error
+ counts int
+ configs []*domainChatStorage.ChatwootDeviceConfig
+}
+
+// CountChatwootDeviceConfigs counts the legacy-mode checks: routing makes two,
+// and a numeric quote one more.
+func (r *replyRepo) CountChatwootDeviceConfigs() (int, error) {
+ r.counts++
+ return r.chatwootRouteTestRepo.CountChatwootDeviceConfigs()
+}
+
+func (r *replyRepo) ListChatwootDeviceConfigs() ([]*domainChatStorage.ChatwootDeviceConfig, error) {
+ return r.configs, nil
+}
+
+func (r *replyRepo) GetChatwootDeviceConfigByIdentifier(identifier string) (*domainChatStorage.ChatwootDeviceConfig, error) {
+ for _, cfg := range r.configs {
+ if cfg.DeviceID == identifier || cfg.DeviceJID == identifier {
+ return cfg, nil
+ }
+ }
+ return nil, nil
+}
+
+func (r *replyRepo) GetMessageByIDAndDevice(deviceID, id string) (*domainChatStorage.Message, error) {
+ r.reads = append(r.reads, deviceID+" "+id)
+ if message, ok := r.messages[deviceID+" "+id]; ok {
+ return &message, r.messageErr
+ }
+ return nil, r.messageErr
+}
+
+// GetChatwootMessageLinkForReply records the filter and returns the first
+// stored link of that device and Chatwoot message; the scope is asserted on
+// the recorded filter. A found link is returned even with lookupErr.
+func (r *replyRepo) GetChatwootMessageLinkForReply(filter domainChatStorage.ChatwootReplyLinkFilter) (*domainChatStorage.ChatwootMessageLink, error) {
+ r.lookups = append(r.lookups, filter)
+ for _, link := range r.links {
+ if link.DeviceID == filter.DeviceID && link.ChatwootMessageID == filter.ChatwootMessageID {
+ return &link, r.lookupErr
+ }
+ }
+ return nil, r.lookupErr
+}
+
+func (r *replyRepo) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
+ r.writes++
+ if r.writeErr != nil {
+ return r.writeErr
+ }
+ r.links = append(r.links, *link)
+ return nil
+}
+
+// replyLIDs maps peer-a's LID to its phone JID while mapped is set.
+type replyLIDs struct {
+ store.LIDStore
+ mapped bool
+}
+
+func (s *replyLIDs) GetPNForLID(_ context.Context, lid types.JID) (types.JID, error) {
+ if s.mapped && lid.User == "peer-a" {
+ return types.NewJID("peer-a", types.DefaultUserServer), nil
+ }
+ return types.EmptyJID, nil
+}
+
+type replyEnv struct {
+ repo *replyRepo
+ sender *replySendStub
+ lids *replyLIDs
+ device *whatsapp.DeviceInstance
+ app *fiber.App
+ notes atomic.Int32
+}
+
+// newReplyEnv routes conversation 7 through its link to slot-a and peer-a, in
+// legacy mode, so failure notes go through the env Chatwoot client to a server
+// that counts them.
+func newReplyEnv(t *testing.T) *replyEnv {
+ t.Helper()
+ withChatwootWebhookSecret(t, "reply-test-secret")
+ chatwootReplays.reset()
+ t.Cleanup(chatwootReplays.reset)
+ env := &replyEnv{
+ repo: &replyRepo{chatwootRouteTestRepo: chatwootRouteTestRepo{link: &domainChatStorage.ChatwootMessageLink{
+ DeviceID: replyTestDevice, WhatsAppChatJID: replyTestChat,
+ ChatwootConversationID: 7, ChatwootAccountID: 3,
+ }}},
+ sender: &replySendStub{},
+ lids: &replyLIDs{},
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ env.notes.Add(1)
+ _, _ = w.Write([]byte(`{"id":1}`))
+ }))
+ t.Cleanup(server.Close)
+
+ prevURL, prevToken := config.ChatwootURL, config.ChatwootAPIToken
+ prevAccount, prevInbox := config.ChatwootAccountID, config.ChatwootInboxID
+ t.Cleanup(func() {
+ config.ChatwootURL, config.ChatwootAPIToken = prevURL, prevToken
+ config.ChatwootAccountID, config.ChatwootInboxID = prevAccount, prevInbox
+ })
+ config.ChatwootURL, config.ChatwootAPIToken = server.URL, "token"
+ config.ChatwootAccountID, config.ChatwootInboxID = 3, 5
+ chatwoot.InitClientRegistry(nil)
+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })
+
+ jid := types.NewJID("device-a", types.DefaultUserServer)
+ env.device = whatsapp.NewDeviceInstance("slot-a", &whatsmeow.Client{Store: &store.Device{ID: &jid, LIDs: env.lids}}, nil)
+ dm := whatsapp.NewDeviceManager(nil, nil, nil)
+ dm.AddDevice(env.device)
+
+ handler := &ChatwootHandler{SendUsecase: env.sender, DeviceManager: dm, ChatStorageRepo: env.repo}
+ env.app = fiber.New()
+ env.app.Post("/chatwoot/webhook", handler.HandleWebhook)
+ return env
+}
+
+func (e *replyEnv) store(deviceID, id, chatJID string) {
+ if e.repo.messages == nil {
+ e.repo.messages = map[string]domainChatStorage.Message{}
+ }
+ e.repo.messages[deviceID+" "+id] = domainChatStorage.Message{ID: id, ChatJID: chatJID, DeviceID: deviceID}
+}
+
+// seed stores the outbound link of an earlier agent message and, as the send
+// usecase does after delivering it, its WhatsApp message in the same chat.
+func (e *replyEnv) seed(chatwootMessageID int, waMessageID, chatJID string) {
+ e.repo.links = append(e.repo.links, domainChatStorage.ChatwootMessageLink{
+ DeviceID: replyTestDevice, WhatsAppMessageID: waMessageID, WhatsAppChatJID: chatJID, ChatwootMessageID: chatwootMessageID,
+ })
+ e.store(replyTestDevice, waMessageID, chatJID)
+}
+
+func (e *replyEnv) post(t *testing.T, body string) {
+ t.Helper()
+ timestamp := nowUnix(0)
+ status := postChatwootWebhook(t, e.app, webhookAuthRequest{
+ body: body,
+ headers: map[string]string{
+ "X-Chatwoot-Timestamp": timestamp,
+ "X-Chatwoot-Signature": chatwootSign("reply-test-secret", timestamp, body),
+ },
+ })
+ if status != fiber.StatusOK {
+ t.Fatalf("webhook status = %d, want 200", status)
+ }
+}
+
+// send is the expected record of a send from slot-a.
+func (e *replyEnv) send(method, phone, text, url, reply string) replySend {
+ return replySend{method: method, phone: phone, text: text, url: url, reply: reply, ptt: method == "SendAudio", device: e.device}
+}
+
+func (e *replyEnv) assertSends(t *testing.T, want ...replySend) {
+ t.Helper()
+ if !reflect.DeepEqual(e.sender.calls, want) {
+ t.Fatalf("sends = %+v, want %+v", e.sender.calls, want)
+ }
+}
+
+// replyBody is agent message 90 in conversation 7, as the JSON Chatwoot sends,
+// so numbers decode as float64 like in production. fields override the top
+// level.
+func replyBody(t *testing.T, attrs map[string]any, fields map[string]any) string {
+ t.Helper()
+ body := map[string]any{
+ "event": "message_created", "message_type": "outgoing", "id": 90, "content": "Olá",
+ "account": map[string]any{"id": 3},
+ "conversation": map[string]any{"id": 7, "inbox_id": 5},
+ "content_attributes": attrs,
+ }
+ for key, value := range fields {
+ body[key] = value
+ }
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatalf("marshal webhook: %v", err)
+ }
+ return string(raw)
+}
+
+// quoting is a reply to the mirrored WhatsApp message id; Chatwoot also sends
+// the quoted message's own numeric id, 41.
+func quoting(id string) map[string]any {
+ return map[string]any{"in_reply_to": 41, "in_reply_to_external_id": "WAID:" + id}
+}
+
+// quotingID is a reply to an earlier agent message, which has no source_id.
+func quotingID(id any) map[string]any {
+ return map[string]any{"in_reply_to": id, "in_reply_to_external_id": nil}
+}
+
+func attachments(fileTypes ...string) map[string]any {
+ list := make([]map[string]any, len(fileTypes))
+ for i, fileType := range fileTypes {
+ list[i] = map[string]any{"id": i + 1, "file_type": fileType, "data_url": replyTestURL}
+ }
+ return map[string]any{"attachments": list, "content": "Legenda"}
+}
+
+// chatwootSameChat compares full non-AD JIDs and maps an @lid side only
+// through the device in the context.
+func TestChatwootSameChat(t *testing.T) {
+ jid := types.NewJID("device-a", types.DefaultUserServer)
+ lids := &replyLIDs{}
+ ctx := whatsapp.ContextWithDevice(context.Background(),
+ whatsapp.NewDeviceInstance("slot-a", &whatsmeow.Client{Store: &store.Device{ID: &jid, LIDs: lids}}, nil))
+
+ cases := []struct {
+ name string
+ a, b string
+ mapped bool
+ want bool
+ }{
+ {"same phone JID", replyTestChat, replyTestChat, false, true},
+ {"device suffix ignored", "peer-a:[email protected]", replyTestChat, false, true},
+ {"other user", "[email protected]", replyTestChat, true, false},
+ {"same user on another server", "[email protected]", replyTestChat, true, false},
+ {"LID mapped to the phone JID", replyTestLID, replyTestChat, true, true},
+ {"phone JID mapped to the LID", replyTestChat, replyTestLID, true, true},
+ {"LID without a mapping", replyTestLID, replyTestChat, false, false},
+ {"same LID without a mapping", replyTestLID, replyTestLID, false, true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ lids.mapped = tc.mapped
+ if got := chatwootSameChat(ctx, tc.a, tc.b); got != tc.want {
+ t.Fatalf("chatwootSameChat(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
+ }
+ })
+ }
+}
+
+// A WAID reference is quoted only when that message is stored for the sending
+// device (read by its storage JID) in the reply's chat. Otherwise the reply
+// goes out unquoted, with no failure note.
+func TestChatwootReplyQuotesAStoredMessageOfTheSameChat(t *testing.T) {
+ cases := []struct {
+ name string
+ destination string
+ setup func(*replyEnv)
+ wantPhone string
+ wantReply string
+ }{
+ {"same chat", replyTestChat, func(e *replyEnv) { e.store(replyTestDevice, "WA-ORIG", replyTestChat) }, "peer-a", "WA-ORIG"},
+ {"group", "[email protected]", func(e *replyEnv) { e.store(replyTestDevice, "WA-ORIG", "[email protected]") }, "[email protected]", "WA-ORIG"},
+ {"stored under the LID the device maps", replyTestChat, func(e *replyEnv) {
+ e.lids.mapped = true
+ e.store(replyTestDevice, "WA-ORIG", replyTestLID)
+ }, "peer-a", "WA-ORIG"},
+ {"LID destination the device maps", replyTestLID, func(e *replyEnv) {
+ e.lids.mapped = true
+ e.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ }, replyTestLID, "WA-ORIG"},
+ {"stored under an unmapped LID", replyTestChat, func(e *replyEnv) { e.store(replyTestDevice, "WA-ORIG", replyTestLID) }, "peer-a", ""},
+ {"another chat", replyTestChat, func(e *replyEnv) { e.store(replyTestDevice, "WA-ORIG", "[email protected]") }, "peer-a", ""},
+ {"stored for another device", replyTestChat, func(e *replyEnv) { e.store("[email protected]", "WA-ORIG", replyTestChat) }, "peer-a", ""},
+ {"not stored", replyTestChat, func(*replyEnv) {}, "peer-a", ""},
+ {"read error", replyTestChat, func(e *replyEnv) {
+ e.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ e.repo.messageErr = errors.New("database is locked")
+ }, "peer-a", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.repo.link.WhatsAppChatJID = tc.destination
+ tc.setup(env)
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), nil))
+
+ env.assertSends(t, env.send("SendText", tc.wantPhone, "Olá", "", tc.wantReply))
+ if want := []string{replyTestDevice + " WA-ORIG"}; !reflect.DeepEqual(env.repo.reads, want) {
+ t.Fatalf("message reads = %q, want %q", env.repo.reads, want)
+ }
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+ })
+ }
+}
+
+// Without a usable WAID reference nothing is read and the reply goes out
+// unquoted, even though WA-ORIG is stored in the chat.
+func TestChatwootReplyWithoutAWAIDReference(t *testing.T) {
+ cases := map[string]map[string]any{
+ "no content_attributes": nil,
+ "null external id": {"in_reply_to": nil, "in_reply_to_external_id": nil},
+ "external id without the prefix": {"in_reply_to_external_id": "WA-ORIG"},
+ "lowercase prefix": {"in_reply_to_external_id": "waid:WA-ORIG"},
+ "external id is not a string": {"in_reply_to_external_id": 41},
+ }
+ for name, attrs := range cases {
+ t.Run(name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+
+ env.post(t, replyBody(t, attrs, nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", ""))
+ if len(env.repo.reads) != 0 {
+ t.Fatalf("message reads = %q, want none", env.repo.reads)
+ }
+ })
+ }
+}
+
+// Every attachment type reaches its send method with the quote, the
+// destination and the URL.
+func TestChatwootReplyQuotesEveryAttachmentType(t *testing.T) {
+ cases := []struct{ fileType, method, caption string }{
+ {"image", "SendImage", "Legenda"},
+ {"audio", "SendAudio", ""},
+ {"video", "SendVideo", "Legenda"},
+ {"file", "SendFile", "Legenda"},
+ {"location", "SendFile", "Legenda"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.fileType, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), attachments(tc.fileType)))
+
+ env.assertSends(t, env.send(tc.method, "peer-a", tc.caption, replyTestURL, "WA-ORIG"))
+ })
+ }
+}
+
+// Each file of a reply quotes the original; the caption stays on the first.
+func TestChatwootReplyQuotesEveryFile(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), attachments("image", "video", "file")))
+
+ env.assertSends(t,
+ env.send("SendImage", "peer-a", "Legenda", replyTestURL, "WA-ORIG"),
+ env.send("SendVideo", "peer-a", "", replyTestURL, "WA-ORIG"),
+ env.send("SendFile", "peer-a", "", replyTestURL, "WA-ORIG"),
+ )
+}
+
+// The audio-to-file fallback keeps the quote, the URL and the caption, and a
+// fallback that succeeds posts no failure note.
+func TestChatwootReplyAudioFallbackKeepsTheQuote(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ env.sender.fail = map[int]error{1: errors.New("unsupported audio")}
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), attachments("audio")))
+
+ env.assertSends(t,
+ env.send("SendAudio", "peer-a", "", replyTestURL, "WA-ORIG"),
+ env.send("SendFile", "peer-a", "Legenda", replyTestURL, "WA-ORIG"),
+ )
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+}
+
+// When the first file fails, the next one still quotes the original, nothing
+// is resent without the quote, and only the failed file gets a note.
+func TestChatwootReplyPartialAttachmentFailureKeepsTheQuote(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ env.sender.fail = map[int]error{1: errors.New("upload failed")}
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), attachments("image", "video")))
+
+ env.assertSends(t,
+ env.send("SendImage", "peer-a", "Legenda", replyTestURL, "WA-ORIG"),
+ env.send("SendVideo", "peer-a", "", replyTestURL, "WA-ORIG"),
+ )
+ if n := env.notes.Load(); n != 1 {
+ t.Fatalf("failure notes = %d, want 1", n)
+ }
+}
+
+// Private notes, incoming messages and echoes of mirrored messages stop
+// before the quote is resolved, so nothing is read or sent; the same reply
+// without a source_id is sent quoted.
+func TestChatwootReplyGuardsRunBeforeTheQuote(t *testing.T) {
+ refs := []struct {
+ name string
+ attrs map[string]any
+ quote string
+ }{
+ {"WAID", quoting("WA-ORIG"), "WA-ORIG"},
+ {"numeric only", quotingID(41), "WA-AGENT"},
+ }
+ cases := []struct {
+ name string
+ fields map[string]any
+ sent bool
+ }{
+ {"private note", map[string]any{"private": true}, false},
+ {"incoming message", map[string]any{"message_type": "incoming"}, false},
+ {"echo of a mirrored message", map[string]any{"source_id": "WAID:WA-ECHO"}, false},
+ {"agent reply without source_id", map[string]any{"source_id": ""}, true},
+ }
+ for _, ref := range refs {
+ for _, tc := range cases {
+ t.Run(ref.name+"/"+tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ env.seed(41, "WA-AGENT", replyTestChat)
+
+ env.post(t, replyBody(t, ref.attrs, tc.fields))
+
+ if tc.sent {
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", ref.quote))
+ return
+ }
+ env.assertSends(t)
+ if reads := len(env.repo.reads) + len(env.repo.lookups); reads != 0 {
+ t.Fatalf("quote reads = %d, want 0", reads)
+ }
+ })
+ }
+ }
+}
+
+// A link write that fails after a quoted send is not a delivery failure:
+// one send, no resend, no failure note.
+func TestChatwootReplyLinkWriteFailureDoesNotResend(t *testing.T) {
+ env := newReplyEnv(t)
+ env.store(replyTestDevice, "WA-ORIG", replyTestChat)
+ env.repo.writeErr = errors.New("disk full")
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", "WA-ORIG"))
+ if env.repo.writes != 1 {
+ t.Fatalf("link writes = %d, want 1", env.repo.writes)
+ }
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+}
+
+// A reply to an earlier agent message quotes the WhatsApp message stored by
+// that message's own delivery, looked up in exactly the scope its link was
+// written with, in each routing mode.
+func TestChatwootReplyQuotesAnEarlierAgentReply(t *testing.T) {
+ modes := []struct {
+ name string
+ configs int
+ configID int64
+ }{
+ {"per-device", 1, 11},
+ {"legacy", 0, 0},
+ }
+ for _, mode := range modes {
+ t.Run(mode.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.repo.count = mode.configs
+ env.repo.link.ChatwootConfigID = mode.configID
+ if mode.configID != 0 {
+ configs := &routeAuthRepo{configs: []*domainChatStorage.ChatwootDeviceConfig{{
+ ID: mode.configID, DeviceID: "slot-a", DeviceJID: replyTestDevice,
+ ChatwootURL: config.ChatwootURL, APIToken: "token", AccountID: 3, InboxID: 5, Enabled: true,
+ }}}
+ env.repo.configs = configs.configs
+ chatwoot.InitClientRegistry(configs)
+ }
+
+ env.post(t, replyBody(t, nil, map[string]any{"id": 50, "content": "Primeira"}))
+ env.store(replyTestDevice, "WA-SENT-1", replyTestChat) // stored by the send usecase
+ env.post(t, replyBody(t, quotingID(50), map[string]any{"id": 51, "content": "Segunda"}))
+
+ env.assertSends(t,
+ env.send("SendText", "peer-a", "Primeira", "", ""),
+ env.send("SendText", "peer-a", "Segunda", "", "WA-SENT-1"),
+ )
+ first := env.repo.links[0]
+ if first.DeviceID != replyTestDevice || first.WhatsAppMessageID != "WA-SENT-1" || first.ChatwootMessageID != 50 ||
+ first.ChatwootAccountID != 3 || first.ChatwootInboxID != 5 || first.ChatwootConfigID != mode.configID {
+ t.Fatalf("first link = %+v, want device-a, WA-SENT-1, message 50, account 3, inbox 5, config %d", first, mode.configID)
+ }
+ want := domainChatStorage.ChatwootReplyLinkFilter{
+ DeviceID: first.DeviceID, ChatwootMessageID: 50, ChatwootConversationID: first.ChatwootConversationID,
+ ChatwootAccountID: first.ChatwootAccountID, ChatwootInboxID: first.ChatwootInboxID,
+ ChatwootConfigID: first.ChatwootConfigID, AllowLegacyAccountZero: mode.configs == 0,
+ }
+ if !reflect.DeepEqual(env.repo.lookups, []domainChatStorage.ChatwootReplyLinkFilter{want}) {
+ t.Fatalf("lookups = %+v, want [%+v]", env.repo.lookups, want)
+ }
+ })
+ }
+}
+
+// The link must be in the reply's chat; an @lid chat counts only through the
+// sending device's mapping. Otherwise the reply goes out unquoted, with no
+// failure note. The stored message is in the reply's chat in every case.
+func TestChatwootReplyChecksTheChatOfTheLink(t *testing.T) {
+ cases := []struct {
+ name, chat string
+ mapped bool
+ want string
+ }{
+ {"same chat", replyTestChat, false, "WA-AGENT"},
+ {"another chat", "[email protected]", true, ""},
+ {"LID the device maps", replyTestLID, true, "WA-AGENT"},
+ {"unmapped LID", replyTestLID, false, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.lids.mapped = tc.mapped
+ env.seed(41, "WA-AGENT", tc.chat)
+ env.store(replyTestDevice, "WA-AGENT", replyTestChat)
+
+ env.post(t, replyBody(t, quotingID(41), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", tc.want))
+ if len(env.repo.lookups) != 1 {
+ t.Fatalf("lookups = %d, want 1", len(env.repo.lookups))
+ }
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+ })
+ }
+}
+
+// The quote is built from the message stored under the link's WhatsApp id,
+// read by id and device only, so that row must be in the reply's chat too: a
+// missing row, or one of another chat with the same id, sends no quote.
+func TestChatwootReplyChecksTheChatOfTheStoredMessage(t *testing.T) {
+ cases := []struct {
+ name, stored, want string // stored is the chat of WA-AGENT's row, "" when missing
+ }{
+ {"stored in the reply's chat", replyTestChat, "WA-AGENT"},
+ {"stored only in another chat", "[email protected]", ""},
+ {"not stored", "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.lids.mapped = true
+ env.seed(41, "WA-AGENT", replyTestChat)
+ delete(env.repo.messages, replyTestDevice+" WA-AGENT")
+ if tc.stored != "" {
+ env.store(replyTestDevice, "WA-AGENT", tc.stored)
+ }
+
+ env.post(t, replyBody(t, quotingID(41), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", tc.want))
+ if want := []string{replyTestDevice + " WA-AGENT"}; !reflect.DeepEqual(env.repo.reads, want) {
+ t.Fatalf("reads = %v, want %v", env.repo.reads, want)
+ }
+ if len(env.repo.lookups) != 1 {
+ t.Fatalf("lookups = %d, want 1", len(env.repo.lookups))
+ }
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+ })
+ }
+}
+
+// Without a link, or when the lookup fails, the reply goes out once,
+// unquoted, with no failure note.
+func TestChatwootReplyWithoutALinkIsSentUnquoted(t *testing.T) {
+ for name, lookupErr := range map[string]error{"no link": nil, "lookup error": errors.New("database is locked")} {
+ t.Run(name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ if lookupErr != nil {
+ env.seed(41, "WA-AGENT", replyTestChat)
+ env.repo.lookupErr = lookupErr
+ }
+
+ env.post(t, replyBody(t, quotingID(41), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", ""))
+ if len(env.repo.lookups) != 1 {
+ t.Fatalf("lookups = %d, want 1", len(env.repo.lookups))
+ }
+ if n := env.notes.Load(); n != 0 {
+ t.Fatalf("failure notes = %d, want 0", n)
+ }
+ })
+ }
+}
+
+// in_reply_to is used only as an exact positive integer; any other value is
+// sent unquoted, with no lookup and no extra legacy-mode check.
+func TestChatwootReplyIgnoresAnInvalidInReplyTo(t *testing.T) {
+ cases := []struct {
+ name string
+ value any
+ want string
+ lookups int
+ }{
+ {"integer", 41, "WA-AGENT", 1},
+ {"numeric string", "41", "", 0},
+ {"fraction", 41.5, "", 0},
+ {"zero", 0, "", 0},
+ {"negative", -41, "", 0},
+ {"beyond exact float64 integers", float64(1 << 53), "", 0},
+ {"boolean", true, "", 0},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.seed(41, "WA-AGENT", replyTestChat)
+
+ env.post(t, replyBody(t, quotingID(tc.value), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", tc.want))
+ if len(env.repo.lookups) != tc.lookups || env.repo.counts != 2+tc.lookups {
+ t.Fatalf("lookups = %+v, legacy-mode checks = %d; want %d and %d", env.repo.lookups, env.repo.counts, tc.lookups, 2+tc.lookups)
+ }
+ })
+ }
+}
+
+// A WAID reference wins over in_reply_to: accepted or refused, the link of
+// in_reply_to is never looked up and the legacy mode is not checked again.
+func TestChatwootReplyPrefersTheWAIDReference(t *testing.T) {
+ cases := []struct {
+ name, stored, want string // stored is the chat of WA-ORIG, "" when not stored
+ }{
+ {"WAID accepted", replyTestChat, "WA-ORIG"},
+ {"WAID of another chat", "[email protected]", ""},
+ {"WAID not stored", "", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ env := newReplyEnv(t)
+ env.seed(41, "WA-AGENT", replyTestChat)
+ if tc.stored != "" {
+ env.store(replyTestDevice, "WA-ORIG", tc.stored)
+ }
+
+ env.post(t, replyBody(t, quoting("WA-ORIG"), nil))
+
+ env.assertSends(t, env.send("SendText", "peer-a", "Olá", "", tc.want))
+ if len(env.repo.lookups) != 0 || env.repo.counts != 2 {
+ t.Fatalf("lookups = %+v, legacy-mode checks = %d; want none and 2 (routing)", env.repo.lookups, env.repo.counts)
+ }
+ })
+ }
+}
+
+// The quote of an earlier agent reply is resolved once and goes on every
+// file, including the audio-to-file fallback.
+func TestChatwootReplyQuotesAnEarlierAgentReplyOnEveryFile(t *testing.T) {
+ env := newReplyEnv(t)
+ env.seed(41, "WA-AGENT", replyTestChat)
+ env.sender.fail = map[int]error{2: errors.New("unsupported audio")}
+
+ env.post(t, replyBody(t, quotingID(41), attachments("image", "audio")))
+
+ env.assertSends(t,
+ env.send("SendImage", "peer-a", "Legenda", replyTestURL, "WA-AGENT"),
+ env.send("SendAudio", "peer-a", "", replyTestURL, "WA-AGENT"),
+ env.send("SendFile", "peer-a", "", replyTestURL, "WA-AGENT"),
+ )
+ if len(env.repo.lookups) != 1 {
+ t.Fatalf("lookups = %d, want 1", len(env.repo.lookups))
+ }
+}
+
+func TestChatwootReplyRejectsUnscopedLinkInPerDeviceMode(t *testing.T) {
+ env := newReplyEnv(t)
+ env.repo.count = 1
+ env.seed(50, "WA-AGENT", replyTestChat)
+ env.post(t, replyBody(t, quotingID(50), nil))
+ if len(env.sender.calls) != 0 || len(env.repo.lookups) != 0 {
+ t.Fatalf("unscoped link triggered sends=%+v lookups=%+v", env.sender.calls, env.repo.lookups)
+ }
+}