Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
add support buttons chat
Gabriel Moraes2b8806a77b63
diff --git a/dashboard/src/components/chats/ChatThread.tsx b/dashboard/src/components/chats/ChatThread.tsxindex 77ad5ef44..801f8ae1e 100644--- a/dashboard/src/components/chats/ChatThread.tsx+++ b/dashboard/src/components/chats/ChatThread.tsx@@ -35,6 +35,8 @@ interface ChatThreadProps {onReply: (message: ChatMessageView) => void;onReact: (message: ChatMessageView, emoji: string) => void;onDelete: (message: ChatMessageView) => void;+ /** Tap a choice on an inbound business button/list prompt (Baileys click-button). */+ onClickButton: (message: ChatMessageView, button: { id: string; text: string }) => Promise<void>;}// The messages area of the active chat room: the bubble list (media, quotes, reactions, hover@@ -57,6 +59,7 @@ function ChatThread({onReply,onReact,onDelete,+ onClickButton,}: ChatThreadProps) {const { t } = useTranslation();@@ -70,6 +73,12 @@ function ChatThread({// overwrite the first, after which whichever settled first cleared the other's state — re-enabling// a button whose fetch was still open, and landing a failure marker on the wrong bubble.const [mediaFetch, setMediaFetch] = useState<Record<string, 'loading' | 'failed'>>({});+ // In-flight / completed taps on inbound prompt buttons. Keyed by waMessageId so a second click+ // on another choice of the same prompt is blocked while one request is open, and after success+ // the whole row stays disabled (WhatsApp treats a prompt as single-choice once answered).+ const [buttonClick, setButtonClick] = useState<+ Record<string, { loadingId?: string; done?: boolean; selectedId?: string }>+ >({});const downloadMedia = useCallback(async (message: ChatMessageView) => {const messageId = message.waMessageId;@@ -101,6 +110,34 @@ function ChatThread({[sessionId, activeChat.id],);+ const handleClickButton = useCallback(+ async (message: ChatMessageView, button: { id: string; text: string }) => {+ const key = message.waMessageId || message.id;+ if (!key) return;+ let blocked = false;+ setButtonClick(prev => {+ if (prev[key]?.loadingId || prev[key]?.done) {+ blocked = true;+ return prev;+ }+ return { ...prev, [key]: { loadingId: button.id } };+ });+ if (blocked) return;+ try {+ await onClickButton(message, button);+ setButtonClick(prev => ({ ...prev, [key]: { done: true, selectedId: button.id } }));+ } catch {+ // Parent already toasts; clear the in-flight state so the user can retry.+ setButtonClick(prev => {+ const next = { ...prev };+ delete next[key];+ return next;+ });+ }+ },+ [onClickButton],+ );+// Scroll-to-bottom button visibility. The main scroll-position memory is owned by// useChatScrollPosition, which doesn't expose its pin state (intentionally — that would re-render// the whole room on every scroll). This small listener tracks only the boolean "user is far from@@ -139,6 +176,7 @@ function ChatThread({// useChatScrollPosition and our listener will resync on its first scroll tick.useEffect(() => {setShowJumpToBottom(false);+ setButtonClick({});}, [activeChat?.id]);// Helper formats@@ -368,6 +406,29 @@ function ChatThread({msg.type !== 'call' && <MessageBody text={msg.body} className="message-text" />)}+ {/* 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 => {+ 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}+ type="button"+ className={`message-prompt-button${state?.selectedId === btn.id ? ' selected' : ''}${state?.done ? ' answered' : ''}`}+ disabled={disabled}+ onClick={() => void handleClickButton(msg, btn)}+ >+ {loading ? <Loader2 size={14} className="animate-spin" /> : btn.text}+ </button>+ );+ })}+ </div>+ )}+<div className="message-meta"><span className="message-time">{formattedTime}</span>{/* delivered and read render the SAME glyph and differ only in colour, whichdiff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 7b7e55bbc..0a3f2d1e7 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -113,6 +113,7 @@"groupSubtitle": "Group","privateContactSubtitle": "Private contact","deleteConfirm": "Delete this message for everyone?",+ "promptButtons": "Message choices","messageDeleted": "🚫 This message was deleted","messageMasked": "🔒 Masked by WhatsApp for linked devices — check your primary phone","kind": {@@ -162,6 +163,7 @@"send": "Failed to send message","react": "Failed to react to message","delete": "Failed to delete message",+ "clickButton": "Failed to click button","fileTooLarge": "File is too large (max 18 MB)"},"loadMessagesError": "Couldn't load messages. Check the server logs.",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 4c670f5f0..a436c1c66 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -113,6 +113,7 @@"groupSubtitle": "Grupo","privateContactSubtitle": "Contato privado","deleteConfirm": "Excluir esta mensagem para todos?",+ "promptButtons": "Opções da mensagem","messageDeleted": "🚫 Esta mensagem foi excluída","messageMasked": "🔒 Ocultada pelo WhatsApp em dispositivos vinculados — verifique no seu telefone principal","kind": {@@ -162,6 +163,7 @@"send": "Erro ao enviar a mensagem","react": "Erro ao reagir à mensagem","delete": "Erro ao excluir a mensagem",+ "clickButton": "Erro ao clicar no botão","fileTooLarge": "O arquivo é muito grande (máx. 18 MB)"},"loadMessagesError": "Não foi possível carregar as mensagens. Verifique os registros do servidor.",diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.cssindex 04c818319..e2299e7da 100644--- a/dashboard/src/pages/Chats.css+++ b/dashboard/src/pages/Chats.css@@ -1230,6 +1230,79 @@max-width: 250px;}+/* Inbound business prompt buttons (Baileys click-button) */+.chats-page .message-prompt-buttons {+ display: flex;+ flex-direction: column;+ gap: 0.375rem;+ margin-top: 0.5rem;+ width: 100%;+}++.chats-page .message-prompt-button {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.375rem;+ width: 100%;+ padding: 0.5rem 0.75rem;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--bg-white);+ color: var(--primary);+ font-size: 0.875rem;+ font-weight: 500;+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease, opacity 0.15s ease;+}++.chats-page .message-prompt-button:hover:not(:disabled) {+ background: rgba(0, 0, 0, 0.04);+ border-color: var(--primary);+}++.chats-page .message-prompt-button:disabled {+ cursor: default;+ opacity: 0.55;+}++.chats-page .message-prompt-button.selected {+ opacity: 1;+ border-color: var(--primary);+ background: rgba(0, 128, 105, 0.08);+ font-weight: 600;+}++.chats-page .message-prompt-button.answered:not(.selected) {+ opacity: 0.4;+}++[data-theme='dark'] .chats-page .message-prompt-button {+ background: rgba(255, 255, 255, 0.06);+}++[data-theme='dark'] .chats-page .message-prompt-button:hover:not(:disabled) {+ background: rgba(255, 255, 255, 0.1);+}++[data-theme='dark'] .chats-page .message-prompt-button.selected {+ background: rgba(0, 168, 132, 0.18);+}++@media (prefers-color-scheme: dark) {+ :root:not([data-theme='light']) .chats-page .message-prompt-button {+ background: rgba(255, 255, 255, 0.06);+ }++ :root:not([data-theme='light']) .chats-page .message-prompt-button:hover:not(:disabled) {+ background: rgba(255, 255, 255, 0.1);+ }++ :root:not([data-theme='light']) .chats-page .message-prompt-button.selected {+ background: rgba(0, 168, 132, 0.18);+ }+}+/* Replying Preview Banner above Input Footer */.chats-page .replying-preview-banner {background: var(--bg-white);diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsxindex 1b7951fa7..805d563f0 100644--- a/dashboard/src/pages/Chats.tsx+++ b/dashboard/src/pages/Chats.tsx@@ -78,6 +78,8 @@ interface IncomingWsMessage {// The backend emits `call` as a top-level field on the live `message.received` event (it's only// folded into `metadata` on the persisted/history path), so declare it here to carry it through.call?: { video: boolean; missed: boolean };+ /** Business prompt choices (Baileys); top-level on the live event, folded into metadata for the UI. */+ buttons?: Array<{ id: string; text: string }>;metadata?: ChatMessageView['metadata'];kind?: ChatKind;/** Group poster: `from` is the group JID, so `contact`/`author` identify who actually sent it. */@@ -375,6 +377,7 @@ export function Chats() {media: newMsg.media,quotedMessage: newMsg.quotedMessage,call: newMsg.call,+ buttons: newMsg.buttons,},kind: newMsg.kind,};@@ -648,6 +651,22 @@ export function Chats() {}};+ const handleClickButton = async (msg: ChatMessageView, button: { id: string; text: string }) => {+ if (!selectedSessionId || !activeChat) return;+ const msgId = msg.waMessageId || msg.id;+ try {+ await messageApi.clickButton(selectedSessionId, {+ chatId: activeChat.id,+ messageId: msgId,+ buttonId: button.id,+ text: button.text,+ });+ } catch (err) {+ showErrorToast(t('chats.errors.clickButton'), err instanceof Error ? err.message : undefined);+ throw err;+ }+ };+// Side effects when the active chat changes: mark-as-read on the gateway + clear sidebar unread badge.// The message-history fetch is driven by useChatMessages; scroll restoration is driven by// useChatScrollPosition (both keyed off activeChat?.id). Deliberately keying off `activeChat?.id`@@ -938,6 +957,7 @@ export function Chats() {onReply={setReplyingTo}onReact={handleReactMessage}onDelete={handleDeleteMessage}+ onClickButton={handleClickButton}/>{/* Composer: attachment preview, emoji panel, reply banner, input bar —diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 2ca63f5e9..2a1b73e27 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -295,6 +295,8 @@ export interface ChatMessage {quotedMessage?: { id: string; body: string };reactions?: Record<string, string>;call?: { video: boolean; missed: boolean };+ /** Business prompt choices (Baileys). Present on inbound prompts that offer buttons. */+ buttons?: Array<{ id: string; text: string }>;};}@@ -358,6 +360,8 @@ 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]).@@ -1076,6 +1080,18 @@ export const messageApi = {method: 'POST',body: JSON.stringify(data),}),+ /**+ * 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 },+ ) =>+ request<MessageResponse>(`/sessions/${sessionId}/messages/click-button`, {+ method: 'POST',+ body: JSON.stringify(data),+ }),react: (sessionId: string, data: { chatId: string; messageId: string; emoji: string }) =>request<void>(`/sessions/${sessionId}/messages/react`, {method: 'POST',diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.tsindex e04985b62..156067681 100644--- a/dashboard/src/utils/chatMessages.test.ts+++ b/dashboard/src/utils/chatMessages.test.ts@@ -72,6 +72,15 @@ 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', () => {+ const buttons = [+ { id: 'yes', text: 'Sim' },+ { id: 'no', text: 'Não' },+ ];+ const m = mapEngineHistoryMessage(hist({ buttons }));+ assert.deepEqual(m.metadata?.buttons, buttons);+});+test('mergeChatMessages: an engine-only message (no DB row) is included — the backfill case', () => {const merged = mergeChatMessages([], [mapEngineHistoryMessage(hist())]);assert.equal(merged.length, 1);diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.tsindex aa727607a..022d6ef64 100644--- a/dashboard/src/utils/chatMessages.ts+++ b/dashboard/src/utils/chatMessages.ts@@ -25,11 +25,18 @@ export function mapEngineHistoryMessage(h: EngineHistoryMessage): ChatMessage {status: 'read',timestamp: h.timestamp,createdAt: new Date((h.timestamp ?? 0) * 1000).toISOString(),- metadata: h.media- ? { media: h.media }- : HISTORY_MEDIA_TYPES.has(h.type)- ? { media: { mimetype: '', omitted: true } }- : undefined,+ metadata: (() => {+ const metadata: ChatMessageView['metadata'] = {};+ if (h.media) {+ metadata.media = h.media;+ } else if (HISTORY_MEDIA_TYPES.has(h.type)) {+ metadata.media = { mimetype: '', omitted: true };+ }+ 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;+ })(),};}@@ -129,6 +136,7 @@ export interface ChatMessageView extends ChatMessage {quotedMessage?: { id: string; body: string };reactions?: Record<string, string>;call?: { video: boolean; missed: boolean };+ buttons?: Array<{ id: string; text: string }>;};}@@ -197,6 +205,8 @@ function mergeMessageMetadata(if (reactions) merged.reactions = reactions;const call = incoming.call ?? existing.call;if (call) merged.call = call;+ const buttons = incoming.buttons ?? existing.buttons;+ if (buttons?.length) merged.buttons = buttons;return Object.keys(merged).length > 0 ? merged : undefined;}diff --git a/src/modules/session/message-row.mapper.spec.ts b/src/modules/session/message-row.mapper.spec.tsindex 3293b613b..661e6ad8e 100644--- a/src/modules/session/message-row.mapper.spec.ts+++ b/src/modules/session/message-row.mapper.spec.ts@@ -26,6 +26,19 @@ describe('buildMessageMetadata', () => {expect(buildMessageMetadata(msg({ call }))).toEqual({ call });});+ it('stores prompt buttons', () => {+ const buttons = [+ { id: 'yes', text: 'Sim' },+ { id: 'no', text: 'Não' },+ ];++ expect(buildMessageMetadata(msg({ buttons }))).toEqual({ buttons });+ });++ it('ignores an empty buttons array', () => {+ expect(buildMessageMetadata(msg({ buttons: [] }))).toBeUndefined();+ });+it('stores every present field together', () => {const built = buildMessageMetadata(msg({@@ -33,10 +46,11 @@ describe('buildMessageMetadata', () => {media: { mimetype: 'image/png' },quotedMessage: { id: 'q' },call: { video: false, missed: false },+ buttons: [{ id: 'ok', text: 'OK' }],} as Partial<IncomingMessage>),);- expect(Object.keys(built!).sort()).toEqual(['call', 'media', 'quotedMessage']);+ expect(Object.keys(built!).sort()).toEqual(['buttons', 'call', 'media', 'quotedMessage']);});describe('omitted-media synthesis', () => {diff --git a/src/modules/session/message-row.mapper.ts b/src/modules/session/message-row.mapper.tsindex 11d2d5892..52a456b68 100644--- a/src/modules/session/message-row.mapper.ts+++ b/src/modules/session/message-row.mapper.ts@@ -29,7 +29,7 @@ export const OMITTED_MEDIA = { mimetype: '', omitted: true } as const;* and an empty object would be noise).*/export function buildMessageMetadata(- message: Pick<IncomingMessage, 'media' | 'quotedMessage' | 'call' | 'type'>,+ message: Pick<IncomingMessage, 'media' | 'quotedMessage' | 'call' | 'buttons' | 'type'>,synthesizeOmittedMedia = false,): Record<string, unknown> | undefined {const metadata: Record<string, unknown> = {};@@ -44,6 +44,10 @@ export function buildMessageMetadata(if (message.call) {metadata.call = message.call;}+ // Business prompt choices (Baileys). Kept so the dashboard can re-render clickable buttons after reload.+ if (message.buttons?.length) {+ metadata.buttons = message.buttons;+ }return Object.keys(metadata).length > 0 ? metadata : undefined;}