Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(message): accept an optional quotedMessageId on the send endpoints
Yudhi Armyndharisbb2598632838
diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex f94a1e0b3..e1b43d065 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -13,7 +13,7 @@ import {IsIn,} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';-import { MESSAGE_TEXT_MAX_LENGTH } from './send-message.dto';+import { MESSAGE_TEXT_MAX_LENGTH, QUOTED_MESSAGE_ID_DESCRIPTION, QUOTED_MESSAGE_ID_EXAMPLE } from './send-message.dto';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -55,6 +55,12 @@ export class SendLocationDto {@IsString()@MaxLength(LOCATION_TEXT_MAX_LENGTH)address?: string;++ @ApiPropertyOptional({ description: QUOTED_MESSAGE_ID_DESCRIPTION, example: QUOTED_MESSAGE_ID_EXAMPLE })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ quotedMessageId?: string;}export class SendContactDto {@@ -74,6 +80,12 @@ export class SendContactDto {@IsNotEmpty()@MaxLength(CONTACT_NUMBER_MAX_LENGTH)contactNumber!: string;++ @ApiPropertyOptional({ description: QUOTED_MESSAGE_ID_DESCRIPTION, example: QUOTED_MESSAGE_ID_EXAMPLE })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ quotedMessageId?: string;}export class SendPollDto {@@ -111,6 +123,12 @@ export class SendPollDto {@IsOptional()@IsBoolean()allowMultipleAnswers?: boolean;++ @ApiPropertyOptional({ description: QUOTED_MESSAGE_ID_DESCRIPTION, example: QUOTED_MESSAGE_ID_EXAMPLE })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ quotedMessageId?: string;}export class ReplyMessageDto {diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.tsindex f74e0a78b..2f4309ac8 100644--- a/src/modules/message/dto/send-message.dto.spec.ts+++ b/src/modules/message/dto/send-message.dto.spec.ts@@ -10,7 +10,11 @@ import {SEND_AUDIO_BODY_EXAMPLES,SEND_DOCUMENT_BODY_EXAMPLES,SEND_STICKER_BODY_EXAMPLES,+ SEND_LOCATION_BODY_EXAMPLES,+ SEND_CONTACT_BODY_EXAMPLES,+ SEND_POLL_BODY_EXAMPLES,} from './send-message.dto';+import { SendLocationDto, SendContactDto, SendPollDto } from './message-actions.dto';// Mirror the global ValidationPipe (main.ts): whitelist + forbidNonWhitelisted strip/reject unknown props.const validateDto = (cls: new () => object, obj: unknown) =>@@ -127,6 +131,39 @@ describe('media route body examples', () => {});});+// send-location, send-contact and send-poll were sampler-driven until quotedMessageId gave them an+// optional property whose sampled value the send path REFUSES (an unresolvable quote fails rather+// than delivering unquoted), which would have made every unedited Execute an error. Same trap as+// #1068, so the same contract: each example must validate, and must not carry a quotedMessageId.+describe('location / contact / poll body examples', () => {+ const suites: Array<[string, new () => object, Record<string, { value: unknown }>]> = [+ ['send-location', SendLocationDto, SEND_LOCATION_BODY_EXAMPLES],+ ['send-contact', SendContactDto, SEND_CONTACT_BODY_EXAMPLES],+ ['send-poll', SendPollDto, SEND_POLL_BODY_EXAMPLES],+ ];++ it.each(suites)('%s declares at least one example', (_route, _cls, examples) => {+ expect(Object.keys(examples).length).toBeGreaterThan(0);+ });++ it.each(suites)('%s examples all pass DTO validation', async (_route, cls, examples) => {+ for (const [name, example] of Object.entries(examples)) {+ const errors = await validateDto(cls, example.value);+ expect({ name, errors: errors.map(e => e.property) }).toEqual({ name, errors: [] });+ }+ });++ // The whole reason these examples exist: a pre-filled quoted id points at no real message.+ it.each(suites)('%s examples carry no quotedMessageId', (_route, _cls, examples) => {+ for (const [name, example] of Object.entries(examples)) {+ expect({ name, quoted: (example.value as { quotedMessageId?: string }).quotedMessageId }).toEqual({+ name,+ quoted: undefined,+ });+ }+ });+});+// Nothing checked the shape before, so a malformed entry reached WhatsApp Web's createWid and threw// from the minified bundle as `Error: t: t` — the caller got a 500 that named neither the field nor// the value (#1068). These cases are the contract: what an individual WID looks like, and what does not.diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex 6f1f77768..bf257b1d2 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -23,6 +23,18 @@ const MENTIONS_DESCRIPTION =// (src/core/agent-tools/tools/message.tools.ts) so MCP and REST enforce the same limit.export const MESSAGE_TEXT_MAX_LENGTH = 4096;+/**+ * Shared wording for the quoted-send field (issue #1271). One constant rather than five copies so+ * the two engine caveats — different id dialects, and Baileys' store requirement — cannot drift+ * apart between the endpoints that all accept the same field.+ */+export const QUOTED_MESSAGE_ID_DESCRIPTION =+ 'Quote an earlier message, turning this send into a reply. The id is engine-specific: ' ++ 'whatsapp-web.js matches the serialized message id, Baileys matches the raw message key id and ' ++ 'can only quote a message it has already stored. An id that cannot be resolved fails the send ' ++ 'rather than delivering it unquoted.';+export const QUOTED_MESSAGE_ID_EXAMPLE = '[email protected]_3EB0ABCD';+export class CustomLinkPreviewDto {@ApiProperty({description: 'The URL as it appears in the message text — WhatsApp anchors the preview to it.',@@ -105,6 +117,15 @@ export class SendTextMessageDto {@ValidateNested()@Type(() => CustomLinkPreviewDto)customLinkPreview?: CustomLinkPreviewDto;++ @ApiPropertyOptional({+ description: QUOTED_MESSAGE_ID_DESCRIPTION,+ example: QUOTED_MESSAGE_ID_EXAMPLE,+ })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ quotedMessageId?: string;}/**@@ -196,6 +217,15 @@ export class SendMediaMessageDto {@MaxLength(64, { each: true })@Validate(IsMentionWidConstraint, { each: true })mentions?: string[];++ @ApiPropertyOptional({+ description: QUOTED_MESSAGE_ID_DESCRIPTION,+ example: QUOTED_MESSAGE_ID_EXAMPLE,+ })+ @IsOptional()+ @IsString()+ @IsNotEmpty()+ quotedMessageId?: string;}/**@@ -229,6 +259,35 @@ export const SEND_DOCUMENT_BODY_EXAMPLES = mediaBodyExample('https://example.com});export const SEND_STICKER_BODY_EXAMPLES = mediaBodyExample('https://example.com/sticker.webp');+/**+ * Request-body examples for the location, contact and poll routes.+ *+ * These three had no `@ApiBody` and were left to the schema sampler, which was harmless while every+ * optional property was self-contained. `quotedMessageId` is not: the sampler emits EVERY property,+ * so a Try-it body would carry a made-up message id, and the send path refuses an id it cannot+ * resolve rather than delivering the message unquoted — turning every unedited Execute on these+ * three routes into an error. Same failure #1068 fixed for the text and media routes, arriving by a+ * different door, so the same remedy applies: pin an example that is submittable as-is.+ */+export const SEND_LOCATION_BODY_EXAMPLES = {+ minimal: {+ summary: 'Share a location',+ value: { chatId: '[email protected]', latitude: -6.2088, longitude: 106.8456, description: 'Jakarta' },+ },+};+export const SEND_CONTACT_BODY_EXAMPLES = {+ minimal: {+ summary: 'Share a contact card',+ value: { chatId: '[email protected]', contactName: 'Alice', contactNumber: '628999888777' },+ },+};+export const SEND_POLL_BODY_EXAMPLES = {+ minimal: {+ summary: 'Ask a single-choice poll',+ value: { chatId: '[email protected]', name: 'Where should we meet?', options: ['Park', 'Beach'] },+ },+};+export class SendAudioMessageDto extends SendMediaMessageDto {@ApiPropertyOptional({description:diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex c18f3a82c..cc49243dd 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -14,6 +14,9 @@ import {SEND_AUDIO_BODY_EXAMPLES,SEND_DOCUMENT_BODY_EXAMPLES,SEND_STICKER_BODY_EXAMPLES,+ SEND_LOCATION_BODY_EXAMPLES,+ SEND_CONTACT_BODY_EXAMPLES,+ SEND_POLL_BODY_EXAMPLES,} from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';import { SendBulkMessageDto, BulkMessageResponseDto } from './dto/bulk-message.dto';@@ -226,6 +229,7 @@ export class MessageController {@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a location message' })@ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SendLocationDto, examples: SEND_LOCATION_BODY_EXAMPLES })@ApiResponse({status: 201,description: 'Location sent',@@ -241,6 +245,7 @@ export class MessageController {@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a contact card message' })@ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SendContactDto, examples: SEND_CONTACT_BODY_EXAMPLES })@ApiResponse({status: 201,description: 'Contact sent',@@ -276,6 +281,7 @@ export class MessageController {@RequireRole(ApiKeyRole.OPERATOR)@ApiOperation({ summary: 'Send a native WhatsApp poll' })@ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiBody({ type: SendPollDto, examples: SEND_POLL_BODY_EXAMPLES })@ApiResponse({status: 201,description: 'Poll sent',diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 5400ca60e..e6fb81b2e 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1148,6 +1148,92 @@ describe('MessageService', () => {});});+ // ── quoted sends (issue #1271) ────────────────────────────────────++ describe('quotedMessageId on the send endpoints', () => {+ // One case per sender rather than the media funnel alone: location, contact and poll each build+ // their own engine payload, so a thread that covered only buildMediaInput would leave three+ // endpoints accepting the field and silently discarding it.+ it('sendImage forwards quotedMessageId in the media payload', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/a.png',+ quotedMessageId: 'wa-quoted-9',+ } as never);++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendLocation forwards quotedMessageId', async () => {+ await service.sendLocation('sess-1', {+ chatId: '[email protected]',+ latitude: 1,+ longitude: 2,+ quotedMessageId: 'wa-quoted-9',+ } as never);++ expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendContact forwards quotedMessageId', async () => {+ await service.sendContact('sess-1', {+ chatId: '[email protected]',+ contactName: 'Alice',+ contactNumber: '628999',+ quotedMessageId: 'wa-quoted-9',+ } as never);++ expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendPoll forwards quotedMessageId', async () => {+ await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Q',+ options: ['a', 'b'],+ quotedMessageId: 'wa-quoted-9',+ } as never);++ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendText forwards quotedMessageId through the options bag', async () => {+ await service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'hi',+ quotedMessageId: 'wa-quoted-9',+ } as never);++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'hi',+ undefined,+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ // Known-negative control: a plain text send must keep its narrow call shape. Without this an+ // implementation that always passed an options object would satisfy the assertion above while+ // rewriting every existing send.+ it('leaves an unquoted text send on its existing two-argument call shape', async () => {+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' } as never);++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');+ });+ });+// ── reply / forward ───────────────────────────────────────────────describe('reply', () => {diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 74d48216f..3f6f04cd7 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -118,6 +118,7 @@ export class MessageService {chatId: finalDto.chatId,body: finalDto.text,type: 'text',+ quotedMessageId: finalDto.quotedMessageId,});// Opt-in humanising "typing…" pause before the actual send (anti-automation signal).@@ -129,11 +130,12 @@ export class MessageService {// nor a preview choice keeps its two-argument shape, and one with mentions alone keeps its// three — trailing `undefined`s would be harmless to the engines but would rewrite the call// shape of every existing send for no behavioural gain.- const { linkPreview, customLinkPreview } = finalDto;- if (linkPreview !== undefined || customLinkPreview) {+ const { linkPreview, customLinkPreview, quotedMessageId } = finalDto;+ if (linkPreview !== undefined || customLinkPreview || quotedMessageId) {result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions, {...(linkPreview === undefined ? {} : { linkPreview }),...(customLinkPreview ? { customPreview: customLinkPreview } : {}),+ ...(quotedMessageId ? { quotedMessageId } : {}),});} else if (finalDto.mentions?.length) {result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions);@@ -261,6 +263,7 @@ export class MessageService {chatId: finalDto.chatId,body: finalDto.caption || '',type: 'image',+ quotedMessageId: finalDto.quotedMessageId,metadata: {media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},@@ -285,6 +288,7 @@ export class MessageService {chatId: finalDto.chatId,body: finalDto.caption || '',type: 'video',+ quotedMessageId: finalDto.quotedMessageId,metadata: {media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},@@ -321,6 +325,7 @@ export class MessageService {metadata: {media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: media.data },},+ quotedMessageId: finalDto.quotedMessageId,});let result: MessageResult;@@ -342,6 +347,7 @@ export class MessageService {chatId: finalDto.chatId,body: finalDto.caption || finalDto.filename || '',type: 'document',+ quotedMessageId: finalDto.quotedMessageId,metadata: {media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},@@ -445,7 +451,14 @@ export class MessageService {async sendLocation(sessionId: string,- dto: { chatId: string; latitude: number; longitude: number; description?: string; address?: string },+ dto: {+ chatId: string;+ latitude: number;+ longitude: number;+ description?: string;+ address?: string;+ quotedMessageId?: string;+ },): Promise<MessageResponseDto> {const finalDto = await this.applySendingGate(sessionId, 'location', dto);const engine = this.getEngine(sessionId);@@ -455,6 +468,7 @@ export class MessageService {chatId: finalDto.chatId,body: `📍 ${finalDto.description || 'Location'}`,type: 'location',+ quotedMessageId: finalDto.quotedMessageId,});let result: MessageResult;@@ -464,6 +478,7 @@ export class MessageService {longitude: finalDto.longitude,description: finalDto.description,address: finalDto.address,+ quotedMessageId: finalDto.quotedMessageId,});} catch (error) {return this.failSend(sessionId, 'location', message, finalDto, error);@@ -473,7 +488,7 @@ export class MessageService {async sendContact(sessionId: string,- dto: { chatId: string; contactName: string; contactNumber: string },+ dto: { chatId: string; contactName: string; contactNumber: string; quotedMessageId?: string },): Promise<MessageResponseDto> {const finalDto = await this.applySendingGate(sessionId, 'contact', dto);const engine = this.getEngine(sessionId);@@ -483,6 +498,7 @@ export class MessageService {chatId: finalDto.chatId,body: `📇 ${finalDto.contactName}`,type: 'contact',+ quotedMessageId: finalDto.quotedMessageId,});let result: MessageResult;@@ -490,6 +506,7 @@ export class MessageService {result = await engine.sendContactMessage(finalDto.chatId, {name: finalDto.contactName,number: finalDto.contactNumber,+ quotedMessageId: finalDto.quotedMessageId,});} catch (error) {return this.failSend(sessionId, 'contact', message, finalDto, error);@@ -499,7 +516,7 @@ export class MessageService {async sendPoll(sessionId: string,- dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean },+ dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean; quotedMessageId?: string },): Promise<MessageResponseDto> {const finalDto = await this.applySendingGate(sessionId, 'poll', dto);const engine = this.getEngine(sessionId);@@ -510,6 +527,7 @@ export class MessageService {chatId: finalDto.chatId,body: `📊 ${finalDto.name}`,type: 'poll',+ quotedMessageId: finalDto.quotedMessageId,});let result: MessageResult;@@ -518,6 +536,7 @@ export class MessageService {name: finalDto.name,options: finalDto.options,allowMultipleAnswers: finalDto.allowMultipleAnswers === true,+ quotedMessageId: finalDto.quotedMessageId,});} catch (error) {return this.failSend(sessionId, 'poll', message, finalDto, error);@@ -534,6 +553,7 @@ export class MessageService {const message = await this.saveOutgoingMessage(sessionId, {chatId: finalDto.chatId,type: 'sticker',+ quotedMessageId: finalDto.quotedMessageId,metadata: {media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },},@@ -643,6 +663,14 @@ export class MessageService {timestamp?: number;status?: MessageStatus;metadata?: Record<string, unknown>;+ /**+ * Quoted id for a send that is a reply. Folded into `metadata.quotedMessage` here rather than+ * by each sender so the nine send paths and `reply()` persist one shape — a row that quoted a+ * message but records nothing is simply wrong history, and the dashboard reads this key to+ * render the reply preview. The body is left empty: unlike `reply()`, the send paths do not+ * look the quoted message up, and '' is already reply()'s own value when that lookup fails.+ */+ quotedMessageId?: string;},): Promise<Message> {const session = await this.sessionService.findOne(sessionId);@@ -663,7 +691,9 @@ export class MessageService {direction: MessageDirection.OUTGOING,timestamp: data.timestamp,status: data.status ?? MessageStatus.PENDING,- metadata: data.metadata,+ metadata: data.quotedMessageId+ ? { ...data.metadata, quotedMessage: { id: data.quotedMessageId, body: '' } }+ : data.metadata,});const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {const waMessageId = message.waMessageId;@@ -1046,6 +1076,7 @@ export class MessageService {filename: dto.filename,caption: dto.caption,mentions: dto.mentions,+ quotedMessageId: dto.quotedMessageId,};}}