Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Align published prompt buttons with the click route and fix reply correctness.
Gabriel Moraes6a7436ecb89e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a116ca20c..7f26512ef 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,13 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added-- Baileys inbound button, template quick-reply, list-row and native-flow replies arrive as `type: "text"` with a structured `button { id, text? }` on `message.received` / chat history (whatsapp-web.js still has no interactive reply fields).-- Baileys inbound business prompts that offer buttons (or list rows) also carry `buttons: [{ id, text }, …]` on `message.received`, so choices like Sim/Não are no longer flattened away into `body` only.-- `POST /api/sessions/:sessionId/messages/click-button` sends a structured button/list reply against a stored WhatsApp Business prompt on Baileys (whatsapp-web.js returns `501`).-- The dashboard Chats thread renders inbound Baileys prompt `buttons` and taps them through `POST .../messages/click-button`; prompt choices are also kept in persisted message `metadata` so they survive reload.+- Baileys inbound button, template quick-reply, list-row and native-flow replies arrive as `type: "text"` with a structured `button { id, text? }` on `message.received` (whatsapp-web.js still has no interactive reply fields). The REST chat-history route is whatsapp-web.js only and does not carry these fields.+- Baileys inbound business prompts that offer clickable buttons (or list rows) also carry `buttons: [{ id, text }, …]` on `message.received` (URL/call CTAs are omitted — they cannot be clicked), so choices like Sim/Não are no longer flattened away into `body` only.+- `POST /api/sessions/:sessionId/messages/click-button` sends a structured button/list reply against a stored WhatsApp Business prompt on Baileys (whatsapp-web.js returns `501`). Classic `buttonsMessage` / `templateMessage` / `listMessage` prompts are supported; native-flow `interactiveMessage` replies are unverified.+- The dashboard Chats thread renders inbound Baileys prompt `buttons` and taps them through `POST .../messages/click-button`; prompt choices are also kept in persisted message `metadata` so they survive reload for rendering. Clicking still requires the prompt to be in the engine store — an evicted prompt 404s.### Changed+- Baileys `listMessage`, `buttonsResponseMessage`, `templateButtonReplyMessage` and `listResponseMessage` now classify as `type: "text"` (they previously fell through to `unknown`). Consumers filtering on `type` will see those shapes as text.- The PostgreSQL data connection is pinned to UTC: parameters bind as UTC, naive timestamps read back as UTC, every pooled connection sets its session `TimeZone`, and boot fails when the effective zone is not UTC year round.- Credentials on a `socks4://` session proxy are reported at session start as unauthenticatable: SOCKS4 sends the user name as the connect request's user id and drops the password.diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 801f8ae1e..079e99fe0 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -409,14 +409,14 @@ function ChatThread({{/* Inbound business prompt choices — tap calls POST .../messages/click-button. */}{!isMe && !isRevoked && !isMasked && (msg.metadata?.buttons?.length ?? 0) > 0 && (<div className="message-prompt-buttons" role="group" aria-label={t('chats.promptButtons')}>- {msg.metadata!.buttons!.map(btn => {+ {msg.metadata!.buttons!.map((btn, idx) => {const clickKey = msg.waMessageId || msg.id;const state = buttonClick[clickKey];const loading = state?.loadingId === btn.id;const disabled = Boolean(state?.loadingId || state?.done);return (<button- key={btn.id}+ key={`${idx}:${btn.id}`}type="button"className={`message-prompt-button${state?.selectedId === btn.id ? ' selected' : ''}${state?.done ? ' answered' : ''}`}disabled={disabled}diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 805d563f0..a55df29ed 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -28,6 +28,7 @@ import {patchMatchingMessage,byMessageId,getMediaSrc,+ liveMessageMetadata,type ChatMessageView,type MessageMedia,} from '../utils/chatMessages';@@ -373,12 +374,7 @@ export function Chats() {status: 'sent',timestamp: newMsg.timestamp,createdAt: new Date(newMsg.timestamp * 1000).toISOString(),- metadata: newMsg.metadata || {- media: newMsg.media,- quotedMessage: newMsg.quotedMessage,- call: newMsg.call,- buttons: newMsg.buttons,- },+ metadata: liveMessageMetadata(newMsg),kind: newMsg.kind,};diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 2a1b73e27..9fc444705 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -360,8 +360,6 @@ export interface EngineHistoryMessage {order?: { orderId: string; token?: string };/** Present on `product` messages only: the catalog product shared into the chat. */product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };- /** Business prompt choices (Baileys). Distinct from a button *reply* tap. */- buttons?: Array<{ id: string; text: string }>;}// Mirrors the backend engine Channel / ChannelMessage (GET /sessions/:id/channels[/:id/messages]).@@ -1084,10 +1082,7 @@ export const messageApi = {* Tap a choice on an inbound business button/list prompt (Baileys only).* `messageId` is the prompt's WhatsApp id; `buttonId` is `buttons[].id`.*/- clickButton: (- sessionId: string,- data: { chatId: string; messageId: string; buttonId: string; text?: string },- ) =>+ clickButton: (sessionId: string, data: { chatId: string; messageId: string; buttonId: string; text?: string }) =>request<MessageResponse>(`/sessions/${sessionId}/messages/click-button`, {method: 'POST',body: JSON.stringify(data),diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex 156067681..01cb0fbba 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -4,6 +4,7 @@ import {mapEngineHistoryMessage,mergeChatMessages,mergeReactionSnapshot,+ liveMessageMetadata,type EngineHistoryMessage,} from './chatMessages.ts';import type { ChatMessage } from '../services/api';@@ -72,13 +73,17 @@ test('mapEngineHistoryMessage: a text message gets no media metadata', () => {assert.equal(mapEngineHistoryMessage(hist({ type: 'text' })).metadata, undefined);});-test('mapEngineHistoryMessage: carries inbound prompt buttons into metadata', () => {+test('liveMessageMetadata: carries inbound prompt buttons from the live WS payload', () => {const buttons = [{ id: 'yes', text: 'Sim' },{ id: 'no', text: 'Não' },];- const m = mapEngineHistoryMessage(hist({ buttons }));- assert.deepEqual(m.metadata?.buttons, buttons);+ assert.deepEqual(liveMessageMetadata({ buttons }), { buttons });+});++test('liveMessageMetadata: prefers an existing metadata bag over top-level fields', () => {+ const metadata = { quotedMessage: { id: 'q', body: 'hi' } };+ assert.deepEqual(liveMessageMetadata({ buttons: [{ id: 'yes', text: 'Sim' }], metadata }), metadata);});test('mergeChatMessages: an engine-only message (no DB row) is included — the backfill case', () => {@@ -201,6 +206,14 @@ test('mergeOrAppend: an echo with undefined leaves keeps the existing quote/callassert.deepEqual(after[0].metadata, { quotedMessage: { id: 'q-1', body: 'quoted' } });});+test('mergeOrAppend: DB-persisted prompt buttons survive a button-less echo', () => {+ const buttons = [{ id: 'yes', text: 'Sim' }];+ const before = [msg({ id: 'm-1', metadata: { buttons } })];+ const echo = msg({ id: 'm-1', metadata: { media: undefined } });+ const after = mergeOrAppend(before, echo);+ assert.deepEqual(after[0].metadata?.buttons, buttons);+});+test('mergeOrAppend dedupes a live WS message against its DB copy (id != id but same waMessageId)', () => {// DB-persisted copy: id = UUID, waMessageId = WA serialized id.const dbCopy = msg({ id: 'uuid-1', waMessageId: '[email protected]_WA1', body: 'persisted' });diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex 022d6ef64..f7f8bf60c 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -34,7 +34,6 @@ export function mapEngineHistoryMessage(h: EngineHistoryMessage): ChatMessage {}if (h.quotedMessage) metadata.quotedMessage = h.quotedMessage;if (h.call) metadata.call = h.call;- if (h.buttons?.length) metadata.buttons = h.buttons;return Object.keys(metadata).length > 0 ? metadata : undefined;})(),};@@ -140,6 +139,27 @@ export interface ChatMessageView extends ChatMessage {};}+/**+ * Metadata for a live `message.received` / `message.sent` WS payload. Prompt `buttons` arrive+ * top-level on that event (the history route never populates them) and are folded here so the+ * thread renders from `metadata.buttons`, matching persisted DB rows.+ */+export function liveMessageMetadata(msg: {+ media?: MessageMedia;+ quotedMessage?: { id: string; body: string };+ call?: { video: boolean; missed: boolean };+ buttons?: Array<{ id: string; text: string }>;+ metadata?: ChatMessageView['metadata'];+}): ChatMessageView['metadata'] {+ if (msg.metadata) return msg.metadata;+ const metadata: NonNullable<ChatMessageView['metadata']> = {};+ if (msg.media) metadata.media = msg.media;+ if (msg.quotedMessage) metadata.quotedMessage = msg.quotedMessage;+ if (msg.call) metadata.call = msg.call;+ if (msg.buttons?.length) metadata.buttons = msg.buttons;+ return Object.keys(metadata).length > 0 ? metadata : undefined;+}+// Delivery ticks only ADVANCE, never regress. Live websocket events (incl. a replayed message.sent on// reconnect) and engine acks can arrive out of order, so a late/duplicate lower status must not visually// downgrade a row already shown as delivered/read. Mirrors the backend transition rules:diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 23f2bf829..5b5bce1be 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2042,12 +2042,12 @@ Tap a choice on a WhatsApp Business button / list prompt by sending the structur**Request body** — `ClickButtonDto`-| Field | Type | Required | Constraints | Description |-| -------- | ------ | -------- | ----------- | --------------------------------------------------------------------------- |-| chatId | string | Yes | non-empty | Chat that holds the prompt |-| messageId| string | Yes | non-empty | WhatsApp id of the inbound prompt (`buttons` on `message.received`) |-| buttonId | string | Yes | non-empty | Stable id of the choice (`buttons[].id`) |-| text | string | No | non-empty | Visible label; resolved from the stored prompt when omitted, else `buttonId` |+| Field | Type | Required | Constraints | Description |+| --------- | ------ | -------- | ------------------- | ---------------------------------------------------------------------------- |+| chatId | string | Yes | non-empty | Chat that holds the prompt |+| messageId | string | Yes | non-empty | WhatsApp id of the inbound prompt (`buttons` on `message.received`) |+| buttonId | string | Yes | non-empty | Stable id of the choice (`buttons[].id`) |+| text | string | No | non-empty, max 4096 | Visible label; resolved from the stored prompt when omitted, else `buttonId` |```json{ "chatId": "[email protected]", "messageId": "0587502EE4F5C80E5C", "buttonId": "yes", "text": "Sim" }@@ -2061,11 +2061,13 @@ Tap a choice on a WhatsApp Business button / list prompt by sending the structur> **Baileys only.** whatsapp-web.js has no interactive-reply send path and answers `501`.-> **Not a native UI tap.** The gateway relays a `buttonsResponseMessage` /-> `templateButtonReplyMessage` / `listResponseMessage` quoted to the stored prompt. WhatsApp may-> reject or treat it differently from a phone tap. The prompt must already be in the Baileys message-> store (received while the session was live). URL/call CTA buttons cannot be clicked this way —-> only quick-reply style choices and list rows.+> **Not a native UI tap.** Classic prompts go out through Baileys' `buttonReply` /+> `listReply` helpers quoted to the stored prompt. Native-flow `interactiveMessage` replies are+> unverified against a live business prompt and must not be treated as fully supported. WhatsApp may+> reject or treat any of these differently from a phone tap. The prompt must already be in the+> Baileys message store (received while the session was live); persisted `metadata.buttons` can still+> render after the store evicts the prompt, and a tap then 404s. URL/call CTA buttons cannot be+> clicked this way — only quick-reply style choices and list rows.**Errors:** `400` validation failure, session not active, the message is not a clickable prompt, or `buttonId` is not among its choices · `401` · `403` · `404` prompt not in the engine store / wrong chat · `501` whatsapp-web.js · `409` conflict or engine not ready (retryable) · `500` engine error@@ -6893,7 +6895,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| Event | When it fires | `data` payload sketch || ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one — **Baileys only**) |+| `message.received` | An inbound message arrives | The full message object: `id`, `from`, `to`, `body`, `type`, `timestamp` (epoch **seconds**), `isGroup`, `kind` (user-facing chat discriminator of `chatId` — `individual\|group\|channel\|status\|broadcast\|unknown`), `hasMedia`, `contact{…}` (plus optional `senderPhone` for `@lid` senders, `order{orderId,token?}` / `product{productId,…}` on `order` / `product` messages, `buttons:[{id,text}]` on a WhatsApp Business prompt that offers choices, and `button{id,text?}` when the sender tapped one — **Baileys only**) || `message.sent` | An outbound message is created/sent from this session | Same message object shape as `message.received` || `message.ack` | A delivery/read receipt updates an outbound message | `{ id, messageId, status, ack }` — `status` is the canonical state (`pending`/`sent`/`delivered`/`read`/`failed`); `ack` is the deprecated legacy integer derived from it || `message.failed` | A receipt resolves to `failed` (dispatched in addition to `message.ack`) | `{ id, messageId, status: "failed", ack: -1 }` |diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.mdindex 9c8f8e439..9500d3a05 100644--- a/docs/17-dashboard-design.md+++ b/docs/17-dashboard-design.md@@ -402,9 +402,9 @@ package to pull from.Chat-specific pieces live one level down in `components/chats/`: `MessageBody` (WhatsApp textformatting + link detection), `ChatThread` (bubble list, including inbound Baileys prompt buttonsthat call `POST /sessions/:id/messages/click-button`), and `MediaLightbox` (the media viewer, built-on `yet-another-react-lightbox`). Prompt choices arrive on live `message.received` / engine history-as top-level `buttons` and are also stored in message `metadata.buttons` so a reload can re-render-them.+on `yet-another-react-lightbox`). Prompt choices arrive on live `message.received` as top-level+`buttons` and are also stored in message `metadata.buttons` so a reload can re-render them.+Clicking still requires the prompt to be in the engine store; an evicted prompt 404s.The message thread is paged. `useChatMessages` is a `useInfiniteQuery` whose cursor is the numberof DB rows fetched so far, not the length of the rendered list — the thread also carries enginediff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 8b945e045..b2327dcf8 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -254,16 +254,16 @@ socket is caught by the transport instead. No REST route: the session watchdog p### 29.4.3 Message management-| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ | OpenWA REST |-| --------------------- | ------------------- | ---------------- | ------------ |-| `editMessage` | ✅ | ✅ | ✅ |-| `deleteMessage` | ✅ | ✅ | ✅ |-| `reactToMessage` | ✅ | ✅ | ✅ |-| `starMessage` | ✅ | ✅ | ✅ |-| `pinMessage` | ✅ | ✅ | ✅ |-| `unpinMessage` | ✅ | ✅ | ✅ |-| `getMessageReactions` | ❌ lib | ✅ | ⚠️ wwjs only |-| `votePoll` | ❌ lib | ✅ | ⚠️ wwjs only |+| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ | OpenWA REST |+| --------------------- | ------------------- | ---------------- | --------------- |+| `editMessage` | ✅ | ✅ | ✅ |+| `deleteMessage` | ✅ | ✅ | ✅ |+| `reactToMessage` | ✅ | ✅ | ✅ |+| `starMessage` | ✅ | ✅ | ✅ |+| `pinMessage` | ✅ | ✅ | ✅ |+| `unpinMessage` | ✅ | ✅ | ✅ |+| `getMessageReactions` | ❌ lib | ✅ | ⚠️ wwjs only |+| `votePoll` | ❌ lib | ✅ | ⚠️ wwjs only || `clickButton` | ✅ | ❌ lib | ⚠️ Baileys only |### 29.4.4 Chats@@ -876,12 +876,19 @@ adapter boundary — none silently stubs.| `sendProduct` | lib | No outbound product content type. || `sendCatalog` | lib | No `Client.sendCatalog` in `index.d.ts` (0 hits). || `setGroupEphemeral` | lib | No disappearing-timer setter (0 hits for `ephemeral` in `index.d.ts`); only the create-time `messageTimer` option (`Client.js:2328`). |-| `clickButton` | lib | No interactive button-reply send path; inbound buttons are not exposable as a clickable Client action. Baileys relays a response proto via `generateWAMessageFromContent` + `relayMessage`. |+| `clickButton` | lib | No interactive button-reply send path; inbound buttons are not exposable as a clickable Client action. Baileys uses `sendMessage({buttonReply})` / `sendMessage({listReply})` for classic prompts. Native-flow `interactiveMessage` replies are unverified. |## 29.7 Caveats on supported rows✅ means works end-to-end — but these rows carry behavioral differences worth knowing:+- **`clickButton` (Baileys) — native-flow is unverified.** Classic `buttonsMessage` /+ `templateMessage` / `listMessage` prompts go through Baileys' `buttonReply` / `listReply`+ helpers. A native-flow `interactiveMessage` prompt is answered with the same template+ `buttonReply` shape; Baileys also has `InteractiveResponseMessage.nativeFlowResponseMessage`,+ which this adapter does not construct. Until a live business native-flow prompt confirms+ what the server accepts, do not treat that arm as fully supported. URL/call CTAs are omitted+ from inbound `buttons[]` and cannot be clicked.- **`postTextStatus` / `postImageStatus` / `postVideoStatus` / `postVoiceStatus` (wwjs).**whatsapp-web.js has no status-recipient argument, so `StatusPostOptions.recipients` is **nothonored** — the post broadcasts to the account's status-privacy audience (a one-time warning isdiff --git a/openapi.json b/openapi.jsonindex 048a4d561..e196e62e4 100644--- a/openapi.json+++ b/openapi.json@@ -3016,6 +3016,61 @@]}},+ "/api/sessions/{sessionId}/messages/click-button": {+ "post": {+ "description": "Sends a structured button/list reply quoted to a previously received prompt. Not a native UI tap — WhatsApp may reject or treat it differently. Classic button/template/list prompts are supported; native-flow interactiveMessage replies are unverified. whatsapp-web.js returns 501. URL/call CTA buttons cannot be clicked this way. The prompt must still be in the engine store (a reloaded bubble can render choices from persisted metadata and then 404).",+ "operationId": "MessageController_clickButton",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ClickButtonDto"+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "Button reply sent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/MessageResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Session not active, prompt is not clickable, buttonId is not among its choices, or recipient unreachable"+ },+ "404": {+ "description": "No such message — the id is outside the engine's lookup window (roughly the last hundred messages of the chat, or absent from the Baileys store) or the message was revoked."+ },+ "409": {+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this. One window answers this while the session still reads `ready`: WhatsApp Web periodically reloads its own page and the engine re-injects into it — for those few seconds the answer is a `409` naming the reload; retry shortly."+ },+ "501": {+ "description": "The active engine cannot serve this operation. It is part of the engine contract, but the engine currently running has no implementation for it."+ }+ },+ "summary": "Click a button on a WhatsApp Business prompt (Baileys only)",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/forward": {"post": {"operationId": "MessageController_forward",@@ -11879,6 +11934,32 @@"text"]},+ "ClickButtonDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string"+ },+ "messageId": {+ "type": "string",+ "description": "WhatsApp id of the business prompt message that offered the buttons."+ },+ "buttonId": {+ "type": "string",+ "description": "Stable id of the choice to tap (inbound `buttons[].id`). URL/call CTA buttons cannot be clicked this way."+ },+ "text": {+ "type": "string",+ "description": "Visible label of the choice. When omitted, resolved from the stored prompt; falls back to buttonId.",+ "maxLength": 4096+ }+ },+ "required": [+ "chatId",+ "messageId",+ "buttonId"+ ]+ },"ForwardMessageDto": {"type": "object","properties": {diff --git a/sdk/go/chat_history_decode_test.go b/sdk/go/chat_history_decode_test.goindex 150fd4a63..2007abdc8 100644--- a/sdk/go/chat_history_decode_test.go+++ b/sdk/go/chat_history_decode_test.go@@ -39,22 +39,6 @@ func TestChatHistoryMessageDecodesEngineFields(t *testing.T) {}}-func TestChatHistoryMessageDecodesButtonReply(t *testing.T) {- raw := []byte(`{- "id":"[email protected]_BTN","from":"[email protected]","to":"[email protected]","chatId":"[email protected]",- "body":"Yes, notify me","type":"text","timestamp":1719312000,"fromMe":false,"isGroup":false,- "kind":"individual","button":{"id":"btn_yes","text":"Yes, notify me"}- }`)-- var m ChatHistoryMessage- if err := json.Unmarshal(raw, &m); err != nil {- t.Fatalf("unmarshal: %v", err)- }- if m.Button == nil || m.Button.ID != "btn_yes" || m.Button.Text != "Yes, notify me" {- t.Errorf("button = %+v, want {ID:btn_yes Text:Yes, notify me}", m.Button)- }-}-func TestChatHistoryMessageLeavesAbsentFieldsEmpty(t *testing.T) {raw := []byte(`{"id":"x","from":"a","to":"b","chatId":"c","body":"","type":"text","timestamp":1,"fromMe":false,"isGroup":false,"kind":"individual"}`)@@ -63,8 +47,8 @@ func TestChatHistoryMessageLeavesAbsentFieldsEmpty(t *testing.T) {if err := json.Unmarshal(raw, &m); err != nil {t.Fatalf("unmarshal: %v", err)}- if m.Call != nil || m.Contact != nil || m.Font != nil || m.Button != nil {- t.Errorf("absent optionals should stay nil: call=%v contact=%v font=%v button=%v", m.Call, m.Contact, m.Font, m.Button)+ if m.Call != nil || m.Contact != nil || m.Font != nil {+ t.Errorf("absent optionals should stay nil: call=%v contact=%v font=%v", m.Call, m.Contact, m.Font)}if m.EphemeralDuration != 0 || m.BackgroundColor != "" {t.Errorf("absent scalars should stay zero: ephemeral=%d bg=%q", m.EphemeralDuration, m.BackgroundColor)diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 886588281..cacb78a13 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -303,8 +303,6 @@ type ChatHistoryMessage struct {Location *MessageLocation `json:"location,omitempty"`Order *MessageOrder `json:"order,omitempty"`Product *MessageProduct `json:"product,omitempty"`- Button *MessageButton `json:"button,omitempty"`- Buttons []MessageButtonChoice `json:"buttons,omitempty"`}// MessageOrder is the order block on a live history message, present on order messages only: the@@ -323,14 +321,15 @@ type MessageProduct struct {BusinessOwnerJID string `json:"businessOwnerJid,omitempty"`}-// MessageButton is the button/list reply block when the sender tapped a WhatsApp Business control.-// Baileys only; ID is the stable handle, Text the visible label when WhatsApp still carries it.+// MessageButton is the button/list reply block on message.received when the sender tapped a+// WhatsApp Business control. Baileys only. Not populated on the REST chat-history route.type MessageButton struct {ID string `json:"id"`Text string `json:"text,omitempty"`}-// MessageButtonChoice is one choice on an inbound WhatsApp Business prompt (buttons or list rows).+// MessageButtonChoice is one clickable choice on an inbound WhatsApp Business prompt, carried on+// message.received. Baileys only. Not populated on the REST chat-history route.type MessageButtonChoice struct {ID string `json:"id"`Text string `json:"text"`diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.javaindex 7a9a6f063..9af781364 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatHistoryMessage.java@@ -36,9 +36,7 @@ public record ChatHistoryMessage(QuotedMessage quotedMessage,Location location,Order order,- Product product,- Button button,- List<ButtonChoice> buttons) {+ Product product) {/** Attached media; {@code data} is absent when the payload was omitted (too large). */public record Media(String mimetype, String filename, String data, Boolean omitted, Long sizeBytes) {}@@ -59,18 +57,6 @@ public record ChatHistoryMessage(/** Present on {@code product} messages only: the catalog product shared into the chat. */public record Product(String productId, String title, String description, String businessOwnerJid) {}- /**- * Present when the sender tapped a WhatsApp Business button, template quick-reply, list row, or- * native-flow control. Baileys only; {@code id} is the stable handle, {@code text} the visible- * label when WhatsApp still carries it.- */- public record Button(String id, String text) {}-- /**- * One choice on an inbound WhatsApp Business prompt (buttons or list rows). Baileys only.- */- public record ButtonChoice(String id, String text) {}-/*** Sender contact info. History carries {@code pushName} only; the richer fields arrive on* {@code message.received} when {@code WEBHOOK_CONTACT_DETAILS} is enabled.diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 5b8cf9587..d03bab9ac 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -609,16 +609,6 @@ export interface ChatHistoryMessage {order?: { orderId: string; token?: string };/** Present on `product` messages only: the catalog product shared into the chat. */product?: { productId: string; title?: string; description?: string; businessOwnerJid?: Jid };- /**- * Present when the sender tapped a WhatsApp Business button, template quick-reply, list row, or- * native-flow control. **Baileys only.**- */- button?: { id: string; text?: string };- /**- * Present on an inbound WhatsApp Business prompt that offers buttons (or list rows). Distinct from- * `button`, which is set only when someone taps a choice. **Baileys only.**- */- buttons?: Array<{ id: string; text: string }>;}/** Paginated payload returned by `GET /sessions/:id/messages`. */diff --git a/sdk/javascript/test/wire-contract.test-d.ts b/sdk/javascript/test/wire-contract.test-d.tsindex 1deb55133..9b9f070b8 100644--- a/sdk/javascript/test/wire-contract.test-d.ts+++ b/sdk/javascript/test/wire-contract.test-d.ts@@ -141,8 +141,6 @@ interface WireChatHistoryMessage {location?: { latitude: number; longitude: number; description?: string; address?: string; url?: string };order?: { orderId: string; token?: string };product?: { productId: string; title?: string; description?: string; businessOwnerJid?: string };- button?: { id: string; text?: string };- buttons?: Array<{ id: string; text: string }>;}/** `Catalog` — the control: this pair already agreed before #754 and must stay agreeing. */diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex f9a6e3e6b..f6bb9e5a7 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -560,15 +560,19 @@ class MessageProduct(TypedDict):class MessageButton(TypedDict):- """Button/list reply block on a live history message when the sender tapped a WhatsApp Business- control. Baileys only; ``id`` is the stable handle, ``text`` the visible label when present."""+ """Button/list reply block on ``message.received`` when the sender tapped a WhatsApp Business+ control. Baileys only; ``id`` is the stable handle, ``text`` the visible label when present.+ Not populated on the REST chat-history route.+ """id: strtext: NotRequired[str]class MessageButtonChoice(TypedDict):- """One choice on an inbound WhatsApp Business prompt (buttons or list rows). Baileys only."""+ """One clickable choice on an inbound WhatsApp Business prompt (buttons or list rows), carried+ on ``message.received``. Baileys only. Not populated on the REST chat-history route.+ """id: strtext: str@@ -624,8 +628,6 @@ ChatHistoryMessage = TypedDict("location": NotRequired[MessageLocation],"order": NotRequired[MessageOrder],"product": NotRequired[MessageProduct],- "button": NotRequired[MessageButton],- "buttons": NotRequired[list[MessageButtonChoice]],},)diff --git a/src/engine/adapters/baileys-click-button.spec.ts b/src/engine/adapters/baileys-click-button.spec.tsindex 99c4da2af..6fa3e57d3 100644--- a/src/engine/adapters/baileys-click-button.spec.ts+++ b/src/engine/adapters/baileys-click-button.spec.ts@@ -1,4 +1,4 @@-import type { WASocket } from '@whiskeysockets/baileys';+import type { WAMessage, WASocket } from '@whiskeysockets/baileys';import { BadRequestException } from '@nestjs/common';import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';import { MessageNotFoundError } from '../../common/errors/message-not-found.error';@@ -19,16 +19,54 @@ const PROMPT = {},};-function makeMessaging(stored: unknown = PROMPT) {- const relayMessage = jest.fn().mockResolvedValue(undefined);- const sock = { relayMessage, sendMessage: jest.fn() };- const getStoredMessage = jest.fn().mockResolvedValue(stored);- const putStoredMessage = jest.fn();- const generateWAMessageFromContent = jest.fn().mockReturnValue({- key: { id: 'CLICK-1', remoteJid: '[email protected]' },- message: { templateButtonReplyMessage: { selectedId: 'yes' } },+const LIST_PROMPT = {+ key: { id: 'PROMPT-LIST', remoteJid: '[email protected]', fromMe: false },+ message: {+ listMessage: {+ sections: [+ {+ rows: [+ { rowId: 'ship_express', title: 'Express' },+ { rowId: 'ship_std', title: 'Standard' },+ ],+ },+ ],+ },+ },+};++const TEMPLATE_PROMPT = {+ key: { id: 'PROMPT-TPL', remoteJid: '[email protected]', fromMe: false },+ message: {+ templateMessage: {+ hydratedTemplate: {+ hydratedButtons: [+ { index: 1, urlButton: { url: 'https://pay.example', displayText: 'Pay now' } },+ { index: 2, quickReplyButton: { id: 'yes', displayText: 'Sim' } },+ ],+ },+ },+ },+};++function contentTypeOf(message: unknown): string | undefined {+ const content = message as Record<string, unknown> | undefined;+ if (content?.buttonsMessage) return 'buttonsMessage';+ if (content?.templateMessage) return 'templateMessage';+ if (content?.listMessage) return 'listMessage';+ if (content?.interactiveMessage) return 'interactiveMessage';+ return undefined;+}++function makeMessaging(stored: unknown = PROMPT, opts: { ephemeralExpiration?: number } = {}) {+ const sendMessage = jest.fn().mockResolvedValue({+ key: { id: 'CLICK-1', remoteJid: '[email protected]', fromMe: true },messageTimestamp: 1700000000,});+ const sock = { sendMessage };+ const getStoredMessage = jest.fn().mockResolvedValue(stored);+ const putStoredMessage = jest.fn();+ const getEphemeralExpiration = jest.fn().mockReturnValue(opts.ephemeralExpiration);const host = {ensureReady: jest.fn(),sessionProxyUrl: () => undefined,@@ -37,14 +75,13 @@ function makeMessaging(stored: unknown = PROMPT) {toNeutralJid: (j: string) => j.replace('@c.us', '@s.whatsapp.net'),toEngineJid: (j: string) => j,normalizedSelfJid: () => '[email protected]',- getEphemeralExpiration: () => undefined,+ getEphemeralExpiration,toUnixSeconds: (ts: number | { toNumber(): number } | null | undefined) =>typeof ts === 'number' ? ts : ts && 'toNumber' in ts ? ts.toNumber() : 0,loadLib: () =>Promise.resolve({normalizeMessageContent: (c: unknown) => c,- getContentType: () => 'buttonsMessage',- generateWAMessageFromContent,+ getContentType: (c: unknown) => contentTypeOf(c),} as never),getStoredMessage,putStoredMessage,@@ -54,35 +91,61 @@ function makeMessaging(stored: unknown = PROMPT) {} as unknown as BaileysMessagingHost;return {messaging: new BaileysMessaging(host),- relayMessage,- generateWAMessageFromContent,+ sendMessage,getStoredMessage,putStoredMessage,+ getEphemeralExpiration,};}+const contentOf = (sendMessage: jest.Mock): Record<string, unknown> => {+ const [, content] = sendMessage.mock.calls[0] as [string, Record<string, unknown>];+ return content;+};++const optionsOf = (sendMessage: jest.Mock): Record<string, unknown> => {+ const [, , options] = sendMessage.mock.calls[0] as [string, unknown, Record<string, unknown>?];+ return options ?? {};+};+describe('BaileysMessaging.clickButton', () => {- it('relays a response proto quoted to the stored prompt', async () => {- const { messaging, relayMessage, generateWAMessageFromContent, putStoredMessage } = makeMessaging();+ it('sends a plain buttonReply quoted to the stored prompt', async () => {+ const { messaging, sendMessage, putStoredMessage } = makeMessaging();const result = await messaging.clickButton('[email protected]', 'PROMPT-1', 'yes', 'Sim');- expect(generateWAMessageFromContent).toHaveBeenCalledWith(- '[email protected]',- {- buttonsResponseMessage: {- selectedButtonId: 'yes',- selectedDisplayText: 'Sim',- type: 1,- },- },- expect.objectContaining({ quoted: PROMPT }),- );- expect(relayMessage).toHaveBeenCalledWith(- '[email protected]',- { templateButtonReplyMessage: { selectedId: 'yes' } },- { messageId: 'CLICK-1' },- );+ expect(contentOf(sendMessage)).toEqual({+ buttonReply: { displayText: 'Sim', id: 'yes', index: 0 },+ type: 'plain',+ });+ expect(optionsOf(sendMessage)).toEqual(expect.objectContaining({ quoted: PROMPT }));expect(putStoredMessage).toHaveBeenCalled();- expect(result).toEqual({ id: 'CLICK-1', timestamp: 1700000000 });+ expect(result).toEqual({ id: 'CLICK-1', timestamp: 1700000000, body: 'Sim' });+ });++ it('sends a listReply for a listMessage prompt', async () => {+ const { messaging, sendMessage } = makeMessaging(LIST_PROMPT);+ await messaging.clickButton('[email protected]', 'PROMPT-LIST', 'ship_std');+ expect(contentOf(sendMessage)).toEqual({+ listReply: {+ title: 'Standard',+ listType: 1,+ singleSelectReply: { selectedRowId: 'ship_std' },+ },+ });+ });++ it('sends a template buttonReply using the hydrated button index', async () => {+ const { messaging, sendMessage } = makeMessaging(TEMPLATE_PROMPT);+ await messaging.clickButton('[email protected]', 'PROMPT-TPL', 'yes');+ expect(contentOf(sendMessage)).toEqual({+ buttonReply: { displayText: 'Sim', id: 'yes', index: 2 },+ type: 'template',+ });+ });++ it('passes the chat disappearing-messages timer on the click send', async () => {+ const { messaging, sendMessage } = makeMessaging(PROMPT, { ephemeralExpiration: 604800 });+ await messaging.clickButton('[email protected]', 'PROMPT-1', 'yes', 'Sim');+ expect(optionsOf(sendMessage)).toEqual(expect.objectContaining({ quoted: PROMPT, ephemeralExpiration: 604800 }));});it('404s when the prompt is not in the store', async () => {@@ -92,6 +155,18 @@ describe('BaileysMessaging.clickButton', () => {);});+ it('404s when the prompt belongs to a different chat', async () => {+ const otherChat: WAMessage = {+ ...PROMPT,+ key: { ...PROMPT.key, remoteJid: '[email protected]' },+ };+ const { messaging, sendMessage } = makeMessaging(otherChat);+ await expect(messaging.clickButton('[email protected]', 'PROMPT-1', 'yes')).rejects.toBeInstanceOf(+ MessageNotFoundError,+ );+ expect(sendMessage).not.toHaveBeenCalled();+ });+it('400s when buttonId is not among the prompt choices', async () => {const { messaging } = makeMessaging();await expect(messaging.clickButton('[email protected]', 'PROMPT-1', 'maybe')).rejects.toBeInstanceOf(diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.tsindex 01b9b60ac..d181b3b62 100644--- a/src/engine/adapters/baileys-message-mapper.spec.ts+++ b/src/engine/adapters/baileys-message-mapper.spec.ts@@ -5,6 +5,9 @@ import {extractBaileysButtonReply,extractBaileysButtons,resolveBaileysButtonClick,+ toBaileysButtonClickContent,+ BUTTONS_MAX_ENTRIES,+ BUTTON_TEXT_MAX_LENGTH,extractBaileysCommerce,extractBaileysContext,isBaileysCatalogShare,@@ -564,7 +567,14 @@ describe('extractBaileysButtons (prompt choices Sim/Não / list rows)', () => {extractBaileysButtons({listMessage: {- sections: [{ rows: [{ rowId: 'ship_express', title: 'Express' }, { rowId: 'ship_std', title: 'Standard' }] }],+ sections: [+ {+ rows: [+ { rowId: 'ship_express', title: 'Express' },+ { rowId: 'ship_std', title: 'Standard' },+ ],+ },+ ],},},'listMessage',@@ -575,6 +585,54 @@ describe('extractBaileysButtons (prompt choices Sim/Não / list rows)', () => {]);});+ it('extracts templateMessage quick-replies and drops url/call CTAs', () => {+ expect(+ extractBaileysButtons(+ {+ templateMessage: {+ hydratedTemplate: {+ hydratedButtons: [+ { index: 1, urlButton: { url: 'https://pay.example', displayText: 'Pay now' } },+ { index: 2, quickReplyButton: { id: 'yes', displayText: 'Sim' } },+ { index: 3, callButton: { phoneNumber: '+15551212', displayText: 'Call us' } },+ ],+ },+ },+ },+ 'templateMessage',+ ),+ ).toEqual([{ id: 'yes', text: 'Sim' }]);+ });++ it('drops native-flow CTA names so published buttons agree with the click allowlist', () => {+ expect(+ extractBaileysButtons(+ {+ interactiveMessage: {+ nativeFlowMessage: {+ buttons: [+ { name: 'cta_url', buttonParamsJson: JSON.stringify({ id: 'docs', display_text: 'Docs' }) },+ { name: 'quick_reply', buttonParamsJson: JSON.stringify({ id: 'yes', display_text: 'Sim' }) },+ ],+ },+ },+ },+ 'interactiveMessage',+ ),+ ).toEqual([{ id: 'yes', text: 'Sim' }]);+ });++ it('caps the number of choices and the length of each label', () => {+ const rows = Array.from({ length: BUTTONS_MAX_ENTRIES + 5 }, (_, i) => ({+ rowId: `row_${i}`,+ title: 'x'.repeat(BUTTON_TEXT_MAX_LENGTH + 10),+ }));+ const buttons = extractBaileysButtons({ listMessage: { sections: [{ rows }] } }, 'listMessage');+ expect(buttons).toHaveLength(BUTTONS_MAX_ENTRIES);+ expect(buttons![0].text).toHaveLength(BUTTON_TEXT_MAX_LENGTH);+ expect(buttons![0].id).toBe('row_0');+ });+it('yields nothing for a non-prompt content type', () => {expect(extractBaileysButtons({}, 'conversation')).toBeUndefined();expect(extractBaileysButtons({ buttonsMessage: { buttons: [] } }, 'buttonsMessage')).toBeUndefined();@@ -582,7 +640,7 @@ describe('extractBaileysButtons (prompt choices Sim/Não / list rows)', () => {});describe('resolveBaileysButtonClick (API click against a stored prompt)', () => {- it('builds a buttonsResponseMessage for a classic buttonsMessage prompt', () => {+ it('builds a plain buttonReply for a classic buttonsMessage prompt', () => {const result = resolveBaileysButtonClick({buttonsMessage: {@@ -601,12 +659,9 @@ describe('resolveBaileysButtonClick (API click against a stored prompt)', () =>id: 'yes',text: 'Sim',index: 0,- message: {- buttonsResponseMessage: {- selectedButtonId: 'yes',- selectedDisplayText: 'Sim',- type: 1,- },+ content: {+ buttonReply: { displayText: 'Sim', id: 'yes', index: 0 },+ type: 'plain',},},});@@ -646,12 +701,9 @@ describe('resolveBaileysButtonClick (API click against a stored prompt)', () =>);expect(result.ok).toBe(true);if (result.ok) {- expect(result.payload.message).toEqual({- templateButtonReplyMessage: {- selectedId: 'yes',- selectedDisplayText: 'Sim',- selectedIndex: 0,- },+ expect(result.payload.content).toEqual({+ buttonReply: { displayText: 'Sim', id: 'yes', index: 1 },+ type: 'template',});}expect(@@ -673,6 +725,88 @@ describe('resolveBaileysButtonClick (API click against a stored prompt)', () =>),).toEqual({ ok: false, error: 'not_a_prompt' });});++ it('uses the hydrated template button index, not the filtered-list offset', () => {+ const result = resolveBaileysButtonClick(+ {+ templateMessage: {+ hydratedTemplate: {+ hydratedButtons: [+ { index: 1, urlButton: { url: 'https://pay.example', displayText: 'Pay now' } },+ { index: 2, quickReplyButton: { id: 'yes', displayText: 'Sim' } },+ ],+ },+ },+ },+ 'templateMessage',+ 'yes',+ );+ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.payload.index).toBe(2);+ expect(result.payload.content).toEqual({+ buttonReply: { displayText: 'Sim', id: 'yes', index: 2 },+ type: 'template',+ });+ }+ });++ it('builds a listReply for a listMessage prompt', () => {+ const result = resolveBaileysButtonClick(+ {+ listMessage: {+ sections: [+ {+ rows: [+ { rowId: 'ship_express', title: 'Express' },+ { rowId: 'ship_std', title: 'Standard' },+ ],+ },+ ],+ },+ },+ 'listMessage',+ 'ship_std',+ );+ expect(result).toEqual({+ ok: true,+ payload: {+ id: 'ship_std',+ text: 'Standard',+ index: 1,+ content: {+ listReply: {+ title: 'Standard',+ listType: 1,+ singleSelectReply: { selectedRowId: 'ship_std' },+ },+ },+ },+ });+ });++ it('disambiguates duplicate list row ids by the caller-supplied text', () => {+ const prompt = {+ listMessage: {+ sections: [{ rows: [{ rowId: 'same', title: 'Morning' }] }, { rows: [{ rowId: 'same', title: 'Evening' }] }],+ },+ };+ const evening = resolveBaileysButtonClick(prompt, 'listMessage', 'same', 'Evening');+ expect(evening.ok).toBe(true);+ if (evening.ok) {+ expect(evening.payload.text).toBe('Evening');+ expect(evening.payload.index).toBe(1);+ }+ });+});++describe('toBaileysButtonClickContent', () => {+ it('uses the plain buttonReply helper for buttonsMessage', () => {+ expect(toBaileysButtonClickContent('buttonsMessage', 'yes', 'Sim', 0)).toEqual({+ buttonReply: { displayText: 'Sim', id: 'yes', index: 0 },+ type: 'plain',+ });+ });});describe('extractBaileysCommerce (order / product ids)', () => {diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex 19c475d3c..8d521da76 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -322,6 +322,18 @@ export function extractBaileysButtonReply(return undefined;}+/**+ * One hydrated template button as WhatsApp sends it. `index` is the proto field+ * (`proto.IHydratedTemplateButton.index`); URL/call CTAs are parsed so they can be dropped, not+ * published as clickable ids.+ */+interface BaileysHydratedTemplateButton {+ index?: number | null;+ quickReplyButton?: { id?: string | null; displayText?: string | null } | null;+ urlButton?: { url?: string | null; displayText?: string | null } | null;+ callButton?: { phoneNumber?: string | null; displayText?: string | null } | null;+}+/*** The inbound message-content subset the prompt-buttons extractor reads. Declared structurally, as* {@link BaileysBodyContent} is.@@ -343,18 +355,10 @@ export interface BaileysButtonsPromptContent {} | null;templateMessage?: {hydratedTemplate?: {- hydratedButtons?: Array<{- quickReplyButton?: { id?: string | null; displayText?: string | null } | null;- urlButton?: { url?: string | null; displayText?: string | null } | null;- callButton?: { phoneNumber?: string | null; displayText?: string | null } | null;- } | null> | null;+ hydratedButtons?: Array<BaileysHydratedTemplateButton | null> | null;} | null;hydratedFourRowTemplate?: {- hydratedButtons?: Array<{- quickReplyButton?: { id?: string | null; displayText?: string | null } | null;- urlButton?: { url?: string | null; displayText?: string | null } | null;- callButton?: { phoneNumber?: string | null; displayText?: string | null } | null;- } | null> | null;+ hydratedButtons?: Array<BaileysHydratedTemplateButton | null> | null;} | null;} | null;listMessage?: {@@ -368,111 +372,68 @@ export interface BaileysButtonsPromptContent {}/**- * Extract the choices offered by an inbound business prompt (buttons / native-flow quick replies /- * template hydrated buttons / list rows). Returns `undefined` when the content is not a prompt- * shape or carries no usable choices. Pass the NORMALIZED content, as the adapter does.+ * WhatsApp's own ceilings are 3 reply buttons or 10 list rows. A slightly higher shared cap+ * covers every prompt arm (including native-flow) without letting a malformed `listMessage` with+ * thousands of rows reach persisted `metadata`, webhooks, WS clients, or `GET /messages`.*/-export function extractBaileysButtons(- content: BaileysButtonsPromptContent,- contentType: string | undefined,-): IncomingMessage['buttons'] {- if (contentType === 'buttonsMessage') {- return collectButtons(- (content.buttonsMessage?.buttons ?? []).map(button => {- const text = button?.buttonText?.displayText?.trim();- if (!text) return undefined;- const id = button?.buttonId?.trim() || text;- return { id, text };- }),- );- }-- if (contentType === 'interactiveMessage') {- return collectButtons(- (content.interactiveMessage?.nativeFlowMessage?.buttons ?? []).map(button => {- const parsed = parseNativeFlowButtonParams(button?.buttonParamsJson);- if (!parsed) return undefined;- const text = (parsed.text ?? parsed.id).trim();- if (!text) return undefined;- return { id: parsed.id.trim() || text, text };- }),- );- }+export const BUTTONS_MAX_ENTRIES = 20;+/** Length cap applied to both `id` and `text` so a single choice cannot bloat a row. */+export const BUTTON_TEXT_MAX_LENGTH = 256;- if (contentType === 'templateMessage') {- const hydrated =- content.templateMessage?.hydratedTemplate?.hydratedButtons ??- content.templateMessage?.hydratedFourRowTemplate?.hydratedButtons ??- [];- return collectButtons(- hydrated.map(entry => {- const quick = entry?.quickReplyButton;- if (quick?.displayText?.trim()) {- const text = quick.displayText.trim();- return { id: quick.id?.trim() || text, text };- }- const url = entry?.urlButton;- if (url?.displayText?.trim()) {- const text = url.displayText.trim();- return { id: url.url?.trim() || text, text };- }- const call = entry?.callButton;- if (call?.displayText?.trim()) {- const text = call.displayText.trim();- return { id: call.phoneNumber?.trim() || text, text };- }- return undefined;- }),- );- }+/** Native-flow button `name`s that can be answered with a structured reply. CTA names are dropped. */+const CLICKABLE_NATIVE_FLOW_NAMES = new Set(['quick_reply', 'button_click']);- if (contentType === 'listMessage') {- const rows = (content.listMessage?.sections ?? []).flatMap(section => section?.rows ?? []);- return collectButtons(- rows.map(row => {- const text = row?.title?.trim();- if (!text) return undefined;- return { id: row?.rowId?.trim() || text, text };- }),- );- }-- return undefined;+/**+ * One clickable choice, carrying the proto index a template reply must echo. Not published on+ * {@link IncomingMessage.buttons} — callers send `id` (and optional `text`) and the click path+ * looks the index up.+ */+export interface BaileysClickableChoice {+ id: string;+ text: string;+ /** `proto.IHydratedTemplateButton.index` when present; otherwise the choice's position. */+ index: number;}-function collectButtons(- entries: Array<{ id: string; text: string } | undefined>,+/**+ * Extract the choices offered by an inbound business prompt (buttons / native-flow quick replies /+ * template hydrated quick-replies / list rows). URL/call CTAs and other native-flow names are+ * omitted: they are not clickable, and publishing them in the same array `ClickButtonDto.buttonId`+ * points at would make every webhook consumer treat a URL as a button id. Returns `undefined` when+ * the content is not a prompt shape or carries no usable choices. Pass the NORMALIZED content, as+ * the adapter does.+ */+export function extractBaileysButtons(+ content: BaileysButtonsPromptContent,+ contentType: string | undefined,): IncomingMessage['buttons'] {- const buttons = entries.filter((entry): entry is { id: string; text: string } => entry != null);- return buttons.length > 0 ? buttons : undefined;+ const choices = extractBaileysClickableButtons(content, contentType);+ return choices?.map(({ id, text }) => ({ id, text }));}-const BUTTON_PROMPT_CONTENT_TYPES = new Set([- 'buttonsMessage',- 'templateMessage',- 'listMessage',- 'interactiveMessage',-]);+const BUTTON_PROMPT_CONTENT_TYPES = new Set(['buttonsMessage', 'templateMessage', 'listMessage', 'interactiveMessage']);export type BaileysButtonClickError = 'not_a_prompt' | 'unknown_button';/**- * The proto `IMessage` fragment a button-click send relays, plus the resolved visible label.+ * The Baileys `sendMessage` content a button-click send relays, plus the resolved visible label.* Declared structurally so it stays unit-testable without importing WAProto.*/export interface BaileysButtonClickPayload {id: string;text: string;- /** Index into template hydrated buttons when the prompt is a template; otherwise 0. */+ /** Index into template hydrated buttons when the prompt is a template; otherwise the choice's position. */index: number;- message: Record<string, unknown>;+ /** `AnyMessageContent` fragment: `{buttonReply,type}` or `{listReply}`. */+ content: Record<string, unknown>;}/*** Resolve a click against a stored business prompt: validate the content type and button id, fill- * in the display text when the caller omitted it, and build the response proto WhatsApp expects for- * that prompt shape. CTA url/call entries are not clickable — only quick-reply style choices and- * list rows.+ * in the display text when the caller omitted it, and build the `sendMessage` content WhatsApp+ * expects for that prompt shape. CTA url/call entries are not clickable — only quick-reply style+ * choices and list rows. When several choices share an id, a caller-supplied `text` disambiguates+ * (a list reusing `rowId` across sections).*/export function resolveBaileysButtonClick(content: BaileysButtonsPromptContent,@@ -490,42 +451,65 @@ export function resolveBaileysButtonClick(}const trimmedId = buttonId.trim();- const matchIndex = choices.findIndex(choice => choice.id === trimmedId);+ const trimmedText = text?.trim();+ // Prefer an (id, text) match so a list that reuses a rowId across sections answers with the+ // row whose title the caller sent, not the first duplicate. Fall back to the first id match+ // when text is omitted.+ let matchIndex = trimmedText+ ? choices.findIndex(choice => choice.id === trimmedId && choice.text === trimmedText)+ : -1;+ if (matchIndex < 0) {+ matchIndex = choices.findIndex(choice => choice.id === trimmedId);+ }if (matchIndex < 0) {return { ok: false, error: 'unknown_button' };}const match = choices[matchIndex];- const resolvedText = (text?.trim() || match.text || trimmedId).trim();+ const resolvedText = (trimmedText || match.text || trimmedId).trim();+ const selectedIndex = match.index;const payload: BaileysButtonClickPayload = {id: trimmedId,text: resolvedText,- index: matchIndex,- message: buildBaileysButtonClickMessage(contentType, trimmedId, resolvedText, matchIndex),+ index: selectedIndex,+ content: toBaileysButtonClickContent(contentType, trimmedId, resolvedText, selectedIndex),};return { ok: true, payload };}/**- * Choices that can be answered with a structured reply proto. URL/call CTAs are excluded — the- * WhatsApp client opens them locally and there is no reply shape to fake.+ * Choices that can be answered with a structured reply. URL/call CTAs and other native-flow names+ * are excluded — the WhatsApp client opens CTAs locally and there is no reply shape to fake.+ * {@link extractBaileysButtons} is a projection of this list, so the published `buttons[]` and the+ * click allowlist cannot disagree.*/export function extractBaileysClickableButtons(content: BaileysButtonsPromptContent,contentType: string | undefined,-): IncomingMessage['buttons'] {+): BaileysClickableChoice[] | undefined {+ if (contentType === 'buttonsMessage') {+ return collectChoices(+ (content.buttonsMessage?.buttons ?? []).map((button, position) => {+ const text = button?.buttonText?.displayText?.trim();+ if (!text) return undefined;+ const id = button?.buttonId?.trim() || text;+ return { id, text, index: position };+ }),+ );+ }+if (contentType === 'interactiveMessage') {- return collectButtons(- (content.interactiveMessage?.nativeFlowMessage?.buttons ?? []).map(button => {+ return collectChoices(+ (content.interactiveMessage?.nativeFlowMessage?.buttons ?? []).map((button, position) => {const name = button?.name ?? 'quick_reply';- if (name !== 'quick_reply' && name !== 'button_click') {+ if (!CLICKABLE_NATIVE_FLOW_NAMES.has(name)) {return undefined;}const parsed = parseNativeFlowButtonParams(button?.buttonParamsJson);if (!parsed) return undefined;const label = (parsed.text ?? parsed.id).trim();if (!label) return undefined;- return { id: parsed.id.trim() || label, text: label };+ return { id: parsed.id.trim() || label, text: label, index: position };}),);}@@ -535,20 +519,50 @@ export function extractBaileysClickableButtons(content.templateMessage?.hydratedTemplate?.hydratedButtons ??content.templateMessage?.hydratedFourRowTemplate?.hydratedButtons ??[];- return collectButtons(- hydrated.map(entry => {+ return collectChoices(+ hydrated.map((entry, position) => {const quick = entry?.quickReplyButton;if (!quick?.displayText?.trim()) return undefined;const label = quick.displayText.trim();- return { id: quick.id?.trim() || label, text: label };+ const protoIndex = typeof entry?.index === 'number' ? entry.index : position;+ return { id: quick.id?.trim() || label, text: label, index: protoIndex };}),);}- return extractBaileysButtons(content, contentType);+ if (contentType === 'listMessage') {+ const rows = (content.listMessage?.sections ?? []).flatMap(section => section?.rows ?? []);+ return collectChoices(+ rows.map((row, position) => {+ const text = row?.title?.trim();+ if (!text) return undefined;+ return { id: row?.rowId?.trim() || text, text, index: position };+ }),+ );+ }++ return undefined;}-function buildBaileysButtonClickMessage(+function collectChoices(entries: Array<BaileysClickableChoice | undefined>): BaileysClickableChoice[] | undefined {+ const choices: BaileysClickableChoice[] = [];+ for (const entry of entries) {+ if (!entry) continue;+ const id = entry.id.slice(0, BUTTON_TEXT_MAX_LENGTH);+ const text = entry.text.slice(0, BUTTON_TEXT_MAX_LENGTH);+ if (!id || !text) continue;+ choices.push({ id, text, index: entry.index });+ if (choices.length >= BUTTONS_MAX_ENTRIES) break;+ }+ return choices.length > 0 ? choices : undefined;+}++/**+ * Map a resolved click onto Baileys' `sendMessage` helpers (`buttonReply` / `listReply`). Native-flow+ * `interactiveMessage` has no helper; it uses the template `buttonReply` shape, which is unverified+ * against a live business native-flow prompt and must not be advertised as `interactiveResponseMessage`.+ */+export function toBaileysButtonClickContent(contentType: string,buttonId: string,text: string,@@ -557,15 +571,12 @@ function buildBaileysButtonClickMessage(switch (contentType) {case 'buttonsMessage':return {- buttonsResponseMessage: {- selectedButtonId: buttonId,- selectedDisplayText: text,- type: 1, // DISPLAY_TEXT / RESPONSE — wire enum member- },+ buttonReply: { displayText: text, id: buttonId, index },+ type: 'plain',};case 'listMessage':return {- listResponseMessage: {+ listReply: {title: text,listType: 1, // SINGLE_SELECTsingleSelectReply: { selectedRowId: buttonId },@@ -573,21 +584,17 @@ function buildBaileysButtonClickMessage(};case 'templateMessage':return {- templateButtonReplyMessage: {- selectedId: buttonId,- selectedDisplayText: text,- selectedIndex: index,- },+ buttonReply: { displayText: text, id: buttonId, index },+ type: 'template',};case 'interactiveMessage':default:- // Quick-reply taps commonly arrive as templateButtonReplyMessage on modern clients.+ // Unverified: Baileys has InteractiveResponseMessage.nativeFlowResponseMessage, but we have+ // not confirmed the server accepts it (or this template stand-in) when *sending* a reply to a+ // native-flow prompt. Keep the template helper so the send still inherits ephemeral/store/echo.return {- templateButtonReplyMessage: {- selectedId: buttonId,- selectedDisplayText: text,- selectedIndex: index,- },+ buttonReply: { displayText: text, id: buttonId, index },+ type: 'template',};}}@@ -625,7 +632,6 @@ function parseNativeFlowButtonParams(}}-function pickNonEmptyString(obj: Record<string, unknown>, keys: string[]): string | undefined {for (const key of keys) {const value = obj[key];diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 99f4b1ca3..b6e074d0b 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -477,8 +477,13 @@ export class BaileysMessaging {}/**- * Send a structured button/list reply against a stored business prompt. Relays the response proto- * (official Baileys has no buttonReply helper) quoted to the prompt message.+ * Send a structured button/list reply against a stored business prompt.+ *+ * Classic prompts (`buttonsMessage` / `templateMessage` / `listMessage`) go through Baileys'+ * `buttonReply` / `listReply` helpers via {@link sendContent}, so the send inherits+ * `withEphemeral`, the store put and the own-send echo. Native-flow `interactiveMessage` has no+ * helper; it uses the template `buttonReply` shape, which is unverified against a live business+ * native-flow prompt.*/async clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult> {this.host.ensureReady();@@ -500,40 +505,8 @@ export class BaileysMessaging {);}- const jid = await this.toDeliverableJid(chatId);- const generated = b.generateWAMessageFromContent(- jid,- // Structural builder — cast at the relay boundary onto Baileys' proto.IMessage.- resolved.payload.message as Parameters<typeof b.generateWAMessageFromContent>[1],- {- quoted,- // MessageGenerationOptionsFromContent requires userJid: string (not optional).- userJid: this.host.normalizedSelfJid() || jid,- },- );- if (!generated?.message || !generated.key?.id) {- throw new InternalServerErrorException('Failed to build button-click message');- }-- await this.sock().relayMessage(jid, generated.message, { messageId: generated.key.id });-- // Stamp fromMe so the store / own-send echo treat this like any other API send.- const sent: WAMessage = {- ...generated,- key: { ...generated.key, fromMe: true, remoteJid: jid },- messageTimestamp: generated.messageTimestamp ?? Math.floor(Date.now() / 1000),- };- void this.host.putStoredMessage(sent)?.catch(err =>- this.host.logger.warn('Failed to persist button-click message to store', {- error: err instanceof Error ? err.message : String(err),- }),- );- void this.emitOwnSendEcho(sent);-- return {- id: sent.key.id ?? '',- timestamp: this.host.toUnixSeconds(sent.messageTimestamp),- };+ const result = await this.sendContent(chatId, resolved.payload.content as AnyMessageContent, { quoted });+ return { ...result, body: resolved.payload.text };}async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex ac165ed25..c6edaba64 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -422,7 +422,7 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {wwjs: { status: 'not-available', rootCause: 'library-limitation' },baileys: { status: 'supported' },evidence:- 'wwjs has no interactive button-reply send path; baileys relays a buttonsResponseMessage / templateButtonReplyMessage / listResponseMessage / interactiveResponseMessage via generateWAMessageFromContent + relayMessage, quoting the stored prompt',+ 'wwjs has no interactive button-reply send path; baileys sendMessage({buttonReply,type}) / sendMessage({listReply}) for buttonsMessage, templateMessage and listMessage (Types/Message.d.ts ButtonReplyInfo / listReply; Utils/messages.js). Native-flow interactiveMessage has no helper and is unverified — the adapter sends a template buttonReply, not InteractiveResponseMessage, and must not be advertised as fully supported until a live business native-flow prompt confirms the server accepts it',},unpinMessage: {wwjs: { status: 'supported' },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex b757a0437..416d0da12 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -29,6 +29,12 @@ export enum EngineStatus {export interface MessageResult {id: string;timestamp: number;+ /**+ * Display text actually sent, when it differs from the caller's input. Button clicks resolve+ * the visible label from the stored prompt when the caller omitted `text`, so the persisted+ * row can store that label instead of the raw `buttonId`.+ */+ body?: string;}/**@@ -148,8 +154,11 @@ export interface IncomingMessage {};/*** Set on an inbound WhatsApp Business prompt that offers buttons (or list rows flattened as- * buttons): the choices shown to the recipient. Distinct from {@link IncomingMessage.button},- * which is set only when someone *taps* a choice. **Baileys only.**+ * buttons): the choices shown to the recipient. URL/call CTAs are omitted — they are not+ * clickable via {@link IWhatsAppEngine.clickButton} and must not masquerade as button ids.+ * Distinct from {@link IncomingMessage.button}, which is set only when someone *taps* a choice.+ * **Baileys only.** Capped (count and label length) so a malformed prompt cannot bloat+ * persisted rows / webhook payloads.*/buttons?: Array<{id: string;@@ -1051,9 +1060,10 @@ export interface MessageOperationsCapability {* label when known. **Baileys only** — whatsapp-web.js has no interactive-reply send path.** The prompt must already be in the engine message store (received while the session was live).- * This sends a structured response proto quoted to that message; it is not a native UI click and- * WhatsApp may reject or treat it differently from a phone tap. URL/call CTA buttons are not- * clickable this way — only quick-reply style choices and list rows.+ * Classic `buttonsMessage` / `templateMessage` / `listMessage` prompts go through Baileys'+ * `buttonReply` / `listReply` helpers. Native-flow `interactiveMessage` replies are unverified+ * against a live business prompt and must not be treated as fully supported. URL/call CTA+ * buttons are not clickable this way — only quick-reply style choices and list rows.*/clickButton(chatId: string, messageId: string, buttonId: string, text?: string): Promise<MessageResult>;diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex a0f9e69df..76bf993a2 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -307,12 +307,13 @@ export class ClickButtonDto {buttonId!: string;@ApiPropertyOptional({- description:- 'Visible label of the choice. When omitted, resolved from the stored prompt; falls back to buttonId.',+ description: 'Visible label of the choice. When omitted, resolved from the stored prompt; falls back to buttonId.',+ maxLength: MESSAGE_TEXT_MAX_LENGTH,})@IsOptional()@IsString()@IsNotEmpty()+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)text?: string;}diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 8ed6bbf7a..0c79fd9cd 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -35,6 +35,7 @@ function createMockEngine() {sendContactMessage: jest.fn().mockResolvedValue(mockEngineResult),sendPollMessage: jest.fn().mockResolvedValue(mockEngineResult),replyToMessage: jest.fn().mockResolvedValue(mockEngineResult),+ clickButton: jest.fn().mockResolvedValue({ ...mockEngineResult, body: 'Sim' }),forwardMessage: jest.fn().mockResolvedValue(mockEngineResult),sendChatState: jest.fn().mockResolvedValue(undefined),};@@ -1000,6 +1001,55 @@ describe('MessageSendService', () => {});});+ describe('clickButton', () => {+ it('calls the engine and persists the resolved label, not the raw buttonId', async () => {+ await service.clickButton('sess-1', {+ chatId: '[email protected]',+ messageId: 'PROMPT-1',+ buttonId: 'yes',+ });++ expect(mockEngine.clickButton).toHaveBeenCalledWith('[email protected]', 'PROMPT-1', 'yes', undefined);+ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({+ body: 'yes',+ type: 'text',+ status: MessageStatus.PENDING,+ metadata: expect.objectContaining({+ button: { id: 'yes', text: undefined },+ quotedMessage: { id: 'PROMPT-1', body: '' },+ }),+ }),+ );+ expect(repository.save).toHaveBeenLastCalledWith(+ expect.objectContaining({+ body: 'Sim',+ status: MessageStatus.SENT,+ metadata: expect.objectContaining({+ button: { id: 'yes', text: 'Sim' },+ }),+ }),+ );+ });++ it('routes an engine refusal through failSend so the pending row is marked failed', async () => {+ (mockEngine.clickButton as jest.Mock).mockRejectedValueOnce(+ new BadRequestException('message PROMPT-1 is not a WhatsApp Business button/list prompt that can be clicked'),+ );++ await expect(+ service.clickButton('sess-1', { chatId: '[email protected]', messageId: 'PROMPT-1', buttonId: 'yes' }),+ ).rejects.toBeInstanceOf(BadRequestException);++ expect(repository.save).toHaveBeenCalledWith(expect.objectContaining({ status: MessageStatus.FAILED }));+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ sessionId: 'sess-1', type: 'click-button' }),+ expect.anything(),+ );+ });+ });+describe('forward', () => {it('should call engine.forwardMessage with from/to chats', async () => {await service.forward('sess-1', {diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex c13e82004..9ba0f8b53 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -539,6 +539,15 @@ export class MessageSendService {} catch (error) {return this.failSend(sessionId, 'click-button', message, finalDto, error);}+ // The engine resolves the visible label from the stored prompt when the caller omitted `text`.+ // Persist that label (not the raw buttonId) so the row agrees with what went on the wire.+ if (result.body) {+ message.body = result.body;+ message.metadata = {+ ...(message.metadata ?? {}),+ button: { id: finalDto.buttonId, text: result.body },+ };+ }return this.persistSentState(message, result);}diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex 44b3336f3..144ddb011 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -366,8 +366,10 @@ export class MessageController {summary: 'Click a button on a WhatsApp Business prompt (Baileys only)',description:'Sends a structured button/list reply quoted to a previously received prompt. Not a native UI ' +- 'tap — WhatsApp may reject or treat it differently. whatsapp-web.js returns 501. URL/call CTA ' +- 'buttons cannot be clicked this way.',+ 'tap — WhatsApp may reject or treat it differently. Classic button/template/list prompts are ' ++ 'supported; native-flow interactiveMessage replies are unverified. whatsapp-web.js returns 501. ' ++ 'URL/call CTA buttons cannot be clicked this way. The prompt must still be in the engine store ' ++ '(a reloaded bubble can render choices from persisted metadata and then 404).',})@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({@@ -377,16 +379,13 @@ export class MessageController {})@ApiResponse({status: 400,- description: 'Session not active, prompt is not clickable, or buttonId is not among its choices',+ description:+ 'Session not active, prompt is not clickable, buttonId is not among its choices, or recipient unreachable',})@ApiResponse({ status: 404, description: MESSAGE_NOT_FOUND_404 })@ApiResponse({ status: 501, description: ENGINE_NOT_SUPPORTED_501 })@ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })- @ApiResponse({ status: 400, description: RECIPIENT_UNREACHABLE_400 })- async clickButton(- @Param('sessionId') sessionId: string,- @Body() dto: ClickButtonDto,- ): Promise<MessageResponseDto> {+ async clickButton(@Param('sessionId') sessionId: string, @Body() dto: ClickButtonDto): Promise<MessageResponseDto> {return this.messageService.clickButton(sessionId, dto);}