Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(message): widen mentions to every text-carrying route
Yudhi Armyndharis1437fa969fd9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 745f403be..a4c2532be 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Changed+- `mentions` reaches every route whose engine can carry it: `reply`, `edit`, `send-template` and each `send-bulk` item, alongside the send routes that already had it. `send-template` also gained `linkPreview`. On `edit` the tags are re-applied rather than preserved, because an edit replaces the message content. Thanks @Magnarks for the report.- `POST /sessions/{sessionId}/chats/unread` publishes its own `MarkChatUnreadDto` rather than sharing `MarkChatReadDto`. The body is unchanged (`chatId` alone), but a generated client sees the schema under a new name.- ⚠️ **Breaking (Go, Java and typed Python callers).** `markRead` and `subscribePresence` each take their own request type rather than the shared `MarkChatRequest`, which now serves `markUnread` alone. Swap the type at both call sites; the wire body is unchanged and the JavaScript and PHP clients are unaffected. `SubscribePresenceDto` had no contract-gate coverage while one type stood for two routes.diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2a0dada86..ef593682c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -163,7 +163,7 @@ There is a **single shared media byte cap**, not a per-type table. A base64 (or### Mentions-`send-text` and the media send routes accept an optional `mentions` array of WIDs (`<phone>@c.us`) to tag participants — most useful in groups. Two things are required for WhatsApp to render a tag and notify the participant:+`send-text`, the media send routes, `send-template`, `send-bulk` (per item), `reply` and `edit` all accept an optional `mentions` array of WIDs (`<phone>@c.us`) to tag participants — most useful in groups. On `edit` the tags are re-applied rather than preserved: an edit replaces the message content, so a rewritten body that still reads `@62811` loses the tag unless the list is sent again. Two things are required for WhatsApp to render a tag and notify the participant:1. The `mentions` array lists the WID(s), e.g. `["[email protected]"]`.2. The `text`/`caption` contains the matching `@<number>` token, e.g. `Hello @62811`.@@ -1571,8 +1571,8 @@ rejected with `400` rather than guessing which half was meant.Nine `send-*` routes accept an optional `quotedMessageId`: `send-text` above, and `send-image`,`send-video`, `send-audio`, `send-document`, `send-sticker`, `send-location`, `send-contact` and`send-poll` below. Supplying it turns that send into a reply, so a reply can carry media, a location,-a contact card or a poll — not only text. `POST .../messages/reply` is unchanged and remains the text-shorthand.+a contact card or a poll — not only text. `POST .../messages/reply` remains the text shorthand, and+like the send routes it accepts `mentions`.`send-template`, `send-bulk` and `send-product` do NOT accept the field, and reject itas an unknown property.@@ -1626,6 +1626,8 @@ Render a stored text template (header/body/footer joined by blank lines, `{{vars| templateId | string | Conditional | non-empty; required when `templateName` is absent | Stored template id || templateName | string | Conditional | non-empty; required when `templateId` is absent | Stored template name || vars | Record\<string,string\> | No | object | Substituted into `{{placeholder}}` tokens; defaults to `{}` |+| mentions | string[] | No | array of WIDs | WIDs to @mention in the rendered body |+| linkPreview | boolean | No | — | Same engine split as `send-text`; see **Link previews** |```json{@@ -1919,11 +1921,12 @@ Reply to a message, quoting a prior message.**Request body** — `ReplyMessageDto`-| Field | Type | Required | Constraints | Description |-| --------------- | ------ | -------- | ----------- | --------------------------------------- |-| chatId | string | Yes | non-empty | Target chat |-| quotedMessageId | string | Yes | non-empty | WhatsApp id of the message being quoted |-| text | string | Yes | non-empty | Reply text |+| Field | Type | Required | Constraints | Description |+| --------------- | -------- | -------- | ------------- | ---------------------------------------- |+| chatId | string | Yes | non-empty | Target chat |+| quotedMessageId | string | Yes | non-empty | WhatsApp id of the message being quoted |+| text | string | Yes | non-empty | Reply text |+| mentions | string[] | No | array of WIDs | WIDs to @mention. See **Mentions** above |```json{ "chatId": "[email protected]", "quotedMessageId": "[email protected]_3EB0ABCD", "text": "Replying to you" }@@ -2055,11 +2058,12 @@ Edit the text of a message sent by this account; also updates the stored record'**Request body** — `EditMessageDto`-| Field | Type | Required | Constraints | Description |-| --------- | ------ | -------- | ----------------------- | ------------------------------------------------- |-| chatId | string | Yes | non-empty | Chat containing the message |-| messageId | string | Yes | non-empty | Message to edit (the send response's `messageId`) |-| body | string | Yes | non-empty, ≤ 4096 chars | New text content |+| Field | Type | Required | Constraints | Description |+| --------- | -------- | -------- | ----------------------- | ------------------------------------------------- |+| chatId | string | Yes | non-empty | Chat containing the message |+| messageId | string | Yes | non-empty | Message to edit (the send response's `messageId`) |+| body | string | Yes | non-empty, ≤ 4096 chars | New text content |+| mentions | string[] | No | array of WIDs | Re-applies participant tags to the new body |```json{ "chatId": "[email protected]", "messageId": "[email protected]_3EB0ABCD", "body": "Corrected text" }@@ -2095,7 +2099,7 @@ Send messages to multiple recipients as an async batch — returns immediately a| messages | BulkMessageItemDto[] | Yes | array, max 100, nested-validated | The batch items (see below); duplicate `chatId`s are collapsed before processing — first occurrence wins, order preserved || options | BulkMessageOptionsDto | No | nested-validated | Pacing/error options (see below) |-Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename? }`, `caption?: string`.+Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename? }`, `caption?: string`, `mentions?: string[]` (per item; a batch fans out to many chats, and a WID is only taggable in a chat the participant is in).`BulkMessageOptionsDto`: `{ delayBetweenMessages?: number (1000–60000, default 3000), randomizeDelay?: boolean (default true), stopOnError?: boolean (default false) }`.diff --git a/openapi.json b/openapi.jsonindex ba8ff23e8..b09a35952 100644--- a/openapi.json+++ b/openapi.json@@ -11363,6 +11363,21 @@"customer": "Alice","orderId": "1234"}+ },+ "mentions": {+ "description": "WIDs to @mention (e.g. [\"[email protected]\"]). The text/caption must also contain the @<number> token.",+ "example": [+ ],+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "linkPreview": {+ "type": "boolean",+ "description": "Controls the URL preview on the rendered body, with the same engine split as send-text: whatsapp-web.js builds one by default and `false` suppresses it, while on Baileys previews are opt-in and only `true` attaches one.",+ "example": false}},"required": [@@ -11593,6 +11608,16 @@"text": {"type": "string","maxLength": 4096+ },+ "mentions": {+ "description": "WIDs to @mention (e.g. [\"[email protected]\"]). The text/caption must also contain the @<number> token.",+ "example": [+ ],+ "type": "array",+ "items": {+ "type": "string"+ }}},"required": [@@ -12130,6 +12155,16 @@"type": "string","description": "New text body for the message","maxLength": 4096+ },+ "mentions": {+ "description": "WIDs to @mention (e.g. [\"[email protected]\"]). The text/caption must also contain the @<number> token.",+ "example": [+ ],+ "type": "array",+ "items": {+ "type": "string"+ }}},"required": [@@ -12207,6 +12242,16 @@"type": "string","description": "Caption for media messages","maxLength": 1024+ },+ "mentions": {+ "description": "WIDs to @mention (e.g. [\"[email protected]\"]). The text/caption must also contain the @<number> token.",+ "example": [+ ],+ "type": "array",+ "items": {+ "type": "string"+ }}}},diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 47a38d551..012a1aa35 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -99,6 +99,11 @@ type SendTemplateRequest struct {TemplateID string `json:"templateId,omitempty"`TemplateName string `json:"templateName,omitempty"`Vars map[string]string `json:"vars,omitempty"`+ // Mentions lists WIDs to @mention in the rendered body, which must carry the @<number> token.+ Mentions []string `json:"mentions,omitempty"`+ // LinkPreview controls the URL preview on the rendered body, with the same engine split as+ // SendTextRequest. A pointer so an explicit false is distinguishable from "not set".+ LinkPreview *bool `json:"linkPreview,omitempty"`}// SendPollRequest sends a native WhatsApp poll. Options holds the choices to@@ -121,6 +126,8 @@ type ReplyMessageRequest struct {ChatID string `json:"chatId"`QuotedMessageID string `json:"quotedMessageId"`Text string `json:"text"`+ // Mentions lists WIDs to @mention. The text must also contain the @<number> token.+ Mentions []string `json:"mentions,omitempty"`}// ForwardMessageRequest forwards a message between chats.@@ -151,6 +158,9 @@ type EditMessageRequest struct {ChatID string `json:"chatId"`MessageID string `json:"messageId"`Body string `json:"body"`+ // Mentions re-applies participant tags: an edit REPLACES the body rather than amending it, so+ // tags the original carried are lost unless resent.+ Mentions []string `json:"mentions,omitempty"`}// ListMessagesQuery filters GET /sessions/:id/messages.@@ -340,6 +350,9 @@ type BulkMessageContent struct {Audio *BulkMediaContent `json:"audio,omitempty"`Document *BulkMediaContent `json:"document,omitempty"`Caption string `json:"caption,omitempty"`+ // Mentions is per item: a batch fans out to many chats, and a WID is only taggable in a chat+ // the participant is in.+ Mentions []string `json:"mentions,omitempty"`}// BulkMessageItem is one message in a bulk send. Type is one of: text, image,diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.javaindex 80855ba3f..b2cb1b8cd 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/BulkMessageContent.java@@ -1,5 +1,7 @@package com.rmyndharis.openwa.model;+import java.util.List;+/** Content payload for one bulk-send item. Populate the field matching the item's {@link BulkMessageType}. */public record BulkMessageContent(String text,@@ -7,7 +9,14 @@ public record BulkMessageContent(BulkMediaRequest video,BulkMediaRequest audio,BulkMediaRequest document,- String caption) {+ String caption,+ List<String> mentions) {+ /** Back-compatible constructor without mentions. */+ public BulkMessageContent(+ String text, BulkMediaRequest image, BulkMediaRequest video, BulkMediaRequest audio,+ BulkMediaRequest document, String caption) {+ this(text, image, video, audio, document, caption, null);+ }public static Builder builder() {return new Builder();@@ -20,6 +29,7 @@ public record BulkMessageContent(private BulkMediaRequest audio;private BulkMediaRequest document;private String caption;+ private List<String> mentions;public Builder text(String v) {this.text = v;@@ -51,8 +61,14 @@ public record BulkMessageContent(return this;}+ /** Per item: a batch fans out to many chats, and a WID is only taggable in a chat it is in. */+ public Builder mentions(List<String> v) {+ this.mentions = v;+ return this;+ }+public BulkMessageContent build() {- return new BulkMessageContent(text, image, video, audio, document, caption);+ return new BulkMessageContent(text, image, video, audio, document, caption, mentions);}}}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.javaindex ecbb72324..e3033c96f 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/EditMessageRequest.java@@ -1,7 +1,14 @@package com.rmyndharis.openwa.model;+import java.util.List;+/** Request body for editing the text of a message sent by this account. */-public record EditMessageRequest(String chatId, String messageId, String body) {+public record EditMessageRequest(String chatId, String messageId, String body, List<String> mentions) {+ /** Back-compatible constructor without mentions. */+ public EditMessageRequest(String chatId, String messageId, String body) {+ this(chatId, messageId, body, null);+ }+public static Builder builder() {return new Builder();}@@ -10,6 +17,7 @@ public record EditMessageRequest(String chatId, String messageId, String body) {private String chatId;private String messageId;private String body;+ private List<String> mentions;public Builder chatId(String v) {this.chatId = v;@@ -27,8 +35,14 @@ public record EditMessageRequest(String chatId, String messageId, String body) {return this;}+ /** An edit REPLACES the body, so tags are re-applied rather than preserved. */+ public Builder mentions(List<String> v) {+ this.mentions = v;+ return this;+ }+public EditMessageRequest build() {- return new EditMessageRequest(chatId, messageId, body);+ return new EditMessageRequest(chatId, messageId, body, mentions);}}}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ReplyMessageRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ReplyMessageRequest.javaindex d8ab534ac..f0c298668 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ReplyMessageRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ReplyMessageRequest.java@@ -1,7 +1,14 @@package com.rmyndharis.openwa.model;+import java.util.List;+/** Request body for replying to a specific message. */-public record ReplyMessageRequest(String chatId, String quotedMessageId, String text) {+public record ReplyMessageRequest(String chatId, String quotedMessageId, String text, List<String> mentions) {+ /** Back-compatible constructor without mentions. */+ public ReplyMessageRequest(String chatId, String quotedMessageId, String text) {+ this(chatId, quotedMessageId, text, null);+ }+public static Builder builder() {return new Builder();}@@ -10,6 +17,7 @@ public record ReplyMessageRequest(String chatId, String quotedMessageId, Stringprivate String chatId;private String quotedMessageId;private String text;+ private List<String> mentions;public Builder chatId(String v) {this.chatId = v;@@ -26,8 +34,14 @@ public record ReplyMessageRequest(String chatId, String quotedMessageId, Stringreturn this;}+ /** WIDs to @mention; the text must also contain the matching @<number> token. */+ public Builder mentions(List<String> v) {+ this.mentions = v;+ return this;+ }+public ReplyMessageRequest build() {- return new ReplyMessageRequest(chatId, quotedMessageId, text);+ return new ReplyMessageRequest(chatId, quotedMessageId, text, mentions);}}}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTemplateRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTemplateRequest.javaindex c6e19fcb4..0f6781e89 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTemplateRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendTemplateRequest.java@@ -1,9 +1,17 @@package com.rmyndharis.openwa.model;+import java.util.List;import java.util.Map;/** Request body for rendering and sending a stored message template. */-public record SendTemplateRequest(String chatId, String templateId, String templateName, Map<String, String> vars) {+public record SendTemplateRequest(+ String chatId, String templateId, String templateName, Map<String, String> vars, List<String> mentions,+ Boolean linkPreview) {+ /** Back-compatible constructor without the send-text passthrough options. */+ public SendTemplateRequest(String chatId, String templateId, String templateName, Map<String, String> vars) {+ this(chatId, templateId, templateName, vars, null, null);+ }+public static Builder builder() {return new Builder();}@@ -13,6 +21,8 @@ public record SendTemplateRequest(String chatId, String templateId, String templprivate String templateId;private String templateName;private Map<String, String> vars;+ private List<String> mentions;+ private Boolean linkPreview;public Builder chatId(String v) {this.chatId = v;@@ -37,8 +47,20 @@ public record SendTemplateRequest(String chatId, String templateId, String templreturn this;}+ /** WIDs to @mention in the rendered body, which must carry the matching @<number> token. */+ public Builder mentions(List<String> v) {+ this.mentions = v;+ return this;+ }++ /** Controls the URL preview on the rendered body, with the same engine split as send-text. */+ public Builder linkPreview(Boolean v) {+ this.linkPreview = v;+ return this;+ }+public SendTemplateRequest build() {- return new SendTemplateRequest(chatId, templateId, templateName, vars);+ return new SendTemplateRequest(chatId, templateId, templateName, vars, mentions, linkPreview);}}}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 2a845881e..68c66c182 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -314,6 +314,8 @@ export interface ReplyMessageRequest {chatId: Jid;quotedMessageId: string;text: string;+ /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */+ mentions?: string[];}export interface ForwardMessageRequest {@@ -414,6 +416,8 @@ export interface EditMessageRequest {messageId: string;/** New text body; max 4096 chars (same cap as a send). Own messages only — 404 if not found. */body: string;+ /** WIDs to @mention. An edit REPLACES the body, so tags are re-applied rather than preserved. */+ mentions?: string[];}export interface SendTemplateRequest {@@ -424,6 +428,10 @@ export interface SendTemplateRequest {templateName?: string;/** Template variables (server DTO field is `vars`). */vars?: Record<string, string>;+ /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */+ mentions?: string[];+ /** Controls the URL preview on the rendered body, with the same engine split as `send-text`. */+ linkPreview?: boolean;}export interface SendPollRequest {@@ -600,6 +608,8 @@ export interface BulkMessageContent {audio?: BulkMediaRequest;document?: BulkMediaRequest;caption?: string;+ /** WIDs to @mention (e.g. `["[email protected]"]`). The text/caption must also contain the `@<number>` token. */+ mentions?: string[];}export interface BulkMessageItem {diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex 0ac6401f9..b120b3f11 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -379,6 +379,8 @@ class ReplyMessageRequest(TypedDict):chatId: JidquotedMessageId: strtext: str+ # WIDs to @mention; the text must also contain the matching @<number> token.+ mentions: NotRequired[list[str]]class ForwardMessageRequest(TypedDict):@@ -405,6 +407,8 @@ class EditMessageRequest(TypedDict):messageId: str# Same 4096-char cap as SendTextRequest.text — an edit cannot exceed what a send allows.body: str+ # An edit REPLACES the body, so tags are re-applied rather than preserved.+ mentions: NotRequired[list[str]]class SendTemplateRequest(TypedDict):@@ -414,6 +418,9 @@ class SendTemplateRequest(TypedDict):templateId: NotRequired[str]templateName: NotRequired[str]vars: NotRequired[dict[str, str]]+ # The rendered body is dispatched like a send-text, so it carries the same two optionals.+ mentions: NotRequired[list[str]]+ linkPreview: NotRequired[bool]class SendPollRequest(TypedDict):@@ -583,6 +590,8 @@ class BulkMessageContent(TypedDict, total=False):audio: BulkMediaRequestdocument: BulkMediaRequestcaption: str+ # Per item: a batch fans out to many chats, and a WID is only taggable in a chat it is in.+ mentions: list[str]class BulkMessageItem(TypedDict):diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex e5b32a15c..f94f84b9b 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -428,7 +428,7 @@ export class BaileysMessaging {);}- async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {+ async replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {this.host.ensureReady();const quoted = await this.requireStored(quotedMsgId);// The one requireStored path that had no chat check. whatsapp-web.js resolves the quote by@@ -438,7 +438,7 @@ export class BaileysMessaging {// NOT applied to quoteOption: cross-chat quoting on the send-* routes is deliberate and// published in docs/06.this.assertStoredInChat(quoted, chatId, quotedMsgId);- return this.sendContent(chatId, { text }, { quoted });+ return this.sendContent(chatId, { text, ...this.withMentions(mentions) }, { quoted });}async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {@@ -484,7 +484,7 @@ export class BaileysMessaging {);}- async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {this.host.ensureReady();const target = await this.requireStored(messageId);// Only the account's own messages are editable: WhatsApp refuses the edit of an inbound message@@ -502,10 +502,14 @@ export class BaileysMessaging {const jid = await this.toDeliverableJid(chatId);// Same guard as sendContent: an edit carries text, so without it the library would fetch// every URL in the new body through its own vulnerable generator.+ // Tags are applied to the inner message's contextInfo BEFORE the library wraps it in the+ // protocolMessage edit envelope, so an edit can re-tag participants. An edit REPLACES the+ // content, so omitting mentions drops whatever tags the original carried.+ const editContent = { text: body, ...this.withMentions(mentions), edit: target.key };const sent = await this.sock().sendMessage(jid,- this.previewSafe({ text: body, edit: target.key }),- this.previewSafeOptions({ text: body, edit: target.key }),+ this.previewSafe(editContent),+ this.previewSafeOptions(editContent),);return { id: sent?.key?.id ?? messageId, timestamp: this.host.toUnixSeconds(sent?.messageTimestamp) };}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 5e790a664..1583f601b 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -2595,6 +2595,30 @@ describe('BaileysAdapter store-backed ops', () => {);});+ it('replyToMessage tags the participants it was given, de-normalized to the engine dialect', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.replyToMessage('[email protected]', 'TARGET', 'hi @62811', ['[email protected]']);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ { text: 'hi @62811', mentions: ['[email protected]'], linkPreview: null },+ expect.objectContaining({ quoted: stored }),+ );+ });++ it('replyToMessage sends no mentions key for an empty list, keeping an untagged reply byte-identical', async () => {+ // Control for the case above: an empty array must not add the key, or every untagged reply would+ // start carrying an empty contextInfo tag list.+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.replyToMessage('[email protected]', 'TARGET', 'my reply', []);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ { text: 'my reply', linkPreview: null },+ expect.objectContaining({ quoted: stored }),+ );+ });+// The one requireStored path that had no chat check, while whatsapp-web.js resolves the quote by// fetching from the named chat and 404s when the id is not in it.it('replyToMessage throws MessageNotFoundError when the quoted key belongs to another chat', async () => {@@ -2759,6 +2783,25 @@ describe('BaileysAdapter store-backed ops', () => {expect(fakeSock.sendMessage).not.toHaveBeenCalled();});+ it('editMessage re-applies participant tags to the new body', async () => {+ // An edit REPLACES the content, so a body that still reads "@62811" needs the tag list resent or+ // the rewritten message loses the tag the original had.+ fakeStore.getMessage.mockResolvedValue(ownStored);+ fakeSock.sendMessage.mockResolvedValue({ key: { ...ownStored.key }, messageTimestamp: 1700000010 });+ const adapter = await ready();+ await adapter.editMessage('[email protected]', 'TARGET', 'edited @62811', ['[email protected]']);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ {+ text: 'edited @62811',+ mentions: ['[email protected]'],+ edit: ownStored.key,+ linkPreview: null,+ },+ expect.objectContaining({ getUrlInfo: expect.any(Function) as unknown }) as unknown,+ );+ });+it('editMessage edits via the stored key and returns the (unchanged) message id', async () => {fakeStore.getMessage.mockResolvedValue(ownStored);fakeSock.sendMessage.mockResolvedValue({ key: { ...ownStored.key }, messageTimestamp: 1700000010 });diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex f577fde50..a86d1238e 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -317,8 +317,8 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.messaging.sendPollMessage(chatId, poll);}- async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {- return this.messaging.replyToMessage(chatId, quotedMsgId, text);+ async replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {+ return this.messaging.replyToMessage(chatId, quotedMsgId, text, mentions);}async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {@@ -345,8 +345,8 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.messaging.unpinMessage(chatId, messageId);}- async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {- return this.messaging.editMessage(chatId, messageId, body);+ async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {+ return this.messaging.editMessage(chatId, messageId, body, mentions);}// ----- Groups -----diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 1a02084f2..537beb2bd 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -4249,6 +4249,21 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lidexpect(reply).toHaveBeenCalledWith('hi', '[email protected]');});+ it('reply passes the tag list through as send options, and omits the options bag without one', async () => {+ const reply = jest.fn().mockResolvedValue(sentMessage);+ const quoted = { id: { _serialized: 'Q1' }, reply };+ const getChatById = jest.fn().mockResolvedValue({ fetchMessages: jest.fn().mockResolvedValue([quoted]) });+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '[email protected]' });++ await ready({ getChatById, getNumberId }).replyToMessage('[email protected]', 'Q1', 'hi @62811', ['[email protected]']);+ expect(reply).toHaveBeenCalledWith('hi @62811', '[email protected]', { mentions: ['[email protected]'] });++ // Control: an empty list must not start passing an options bag to every untagged reply.+ reply.mockClear();+ await ready({ getChatById, getNumberId }).replyToMessage('[email protected]', 'Q1', 'hi', []);+ expect(reply).toHaveBeenCalledWith('hi', '[email protected]');+ });+it('forward routes to the resolved @lid and recovers the id from that chat (#583 R1)', async () => {const forward = jest.fn().mockResolvedValue(undefined);const srcMsg = { id: { _serialized: 'M1' }, forward };@@ -4282,6 +4297,19 @@ describe('editMessage', () => {expect(res).toEqual({ id: 'M1', timestamp: 1700000002 });});+ it('edit re-applies participant tags, and sends no options bag when none were asked for', async () => {+ const edit = jest.fn().mockResolvedValue({ id: { _serialized: 'M1' }, timestamp: 1700000002 });+ const adapter = ready(chatWith([{ id: { _serialized: 'M1', id: 'RAW1' }, edit }]));++ await adapter.editMessage('[email protected]', 'M1', 'new @62811', ['[email protected]']);+ expect(edit).toHaveBeenCalledWith('new @62811', { mentions: ['[email protected]'] });++ // Control: without tags the library call keeps its single-argument shape.+ edit.mockClear();+ await adapter.editMessage('[email protected]', 'M1', 'new body', []);+ expect(edit).toHaveBeenCalledWith('new body');+ });+it('also matches the bare id.id fallback (like deleteMessage)', async () => {const edit = jest.fn().mockResolvedValue({ id: { _serialized: '[email protected]_RAW1' }, timestamp: 1700000002 });const adapter = ready(chatWith([{ id: { _serialized: '[email protected]_RAW1', id: 'RAW1' }, edit }]));diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex d6fa18e09..5e2255ab6 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -591,8 +591,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.messaging.sendPollMessage(chatId, poll);}- replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {- return this.messaging.replyToMessage(chatId, quotedMsgId, text);+ replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {+ return this.messaging.replyToMessage(chatId, quotedMsgId, text, mentions);}forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {@@ -722,8 +722,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}// Edit Message- editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {- return this.messaging.editMessage(chatId, messageId, body);+ editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {+ return this.messaging.editMessage(chatId, messageId, body, mentions);}// Get Profile Picturediff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 5023c3806..da0ffdf2a 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -521,7 +521,7 @@ export class WwebjsMessaging {return toMessageResult(msg);}- async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {+ async replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult> {this.host.ensureReady();try {// Find the message to quote@@ -536,7 +536,13 @@ export class WwebjsMessaging {// Reply's send leg hits the same `No LID for user` path as a normal send for a migrated contact,// so route it through sendResolved (resolve @c.us->@lid, cache, self-heal). reply(content, chatId)// accepts an explicit target (#583 R1).- const msg = await this.sendResolved(chatId, to => quotedMsg.reply(text, to));+ // reply(content, chatId, options) takes the same options bag as sendMessage, so a quoted send+ // tags participants exactly as a plain one does. The options argument is omitted entirely when+ // no tags were asked for, keeping an ordinary reply's call shape untouched (same rule as the+ // send path).+ const msg = await this.sendResolved(chatId, to =>+ mentions?.length ? quotedMsg.reply(text, to, { mentions }) : quotedMsg.reply(text, to),+ );return toMessageResult(msg);} catch (error) {this.host.reportIfPageTransportError(error, 'replyToMessage');@@ -750,7 +756,7 @@ export class WwebjsMessaging {this.host.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);}- async editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult> {+ async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {this.host.ensureReady();// Same lookup window as react/delete: fetchMessages sees only the 100 most recent messages.// NOTE: do NOT resolve chatId to @lid here — edit operates on the found message's own key, not@@ -767,7 +773,9 @@ export class WwebjsMessaging {if (!message) {throw new MessageNotFoundError(messageId, chatId);}- const edited = await message.edit(body);+ // An edit REPLACES the content, so tags are re-applied rather than preserved: omitting mentions+ // drops whatever the original carried. Options omitted entirely when none were asked for.+ const edited = mentions?.length ? await message.edit(body, { mentions }) : await message.edit(body);if (!edited) {// wwebjs RESOLVES null (instead of throwing) when the page-side edit is refused — only the// account's own text messages are editable; surface the refusal, not a phantom success.diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 7a2557159..e2b1d19fa 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -909,7 +909,11 @@ export interface MessagingCapability {sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult>;- replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult>;+ /**+ * Reply to a message, quoting it. `mentions` tags participants exactly as on the send routes: the+ * text must also carry the matching `@<number>` token for WhatsApp to render the tag.+ */+ replyToMessage(chatId: string, quotedMsgId: string, text: string, mentions?: string[]): Promise<MessageResult>;forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult>;}@@ -930,8 +934,11 @@ export interface MessageOperationsCapability {/*** Edit the body of a text message. Only the account's OWN messages can be edited; engines reject* non-text or foreign messages at their own layer — the engine's error is surfaced as-is.+ *+ * `mentions` re-applies participant tags to the new body. An edit REPLACES the message content, so+ * omitting it drops whatever tags the original carried rather than preserving them.*/- editMessage(chatId: string, messageId: string, body: string): Promise<MessageResult>;+ editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult>;/*** Star (bookmark) a message, or remove its star. Starring is a private, account-local marker —diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex fa0dc0d4c..f4205a3bd 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -267,7 +267,11 @@ describe('BulkMessageService.processBatch', () => {}) as unknown as MessageBatch;beforeEach(async () => {- engine = { sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 111 }) };+ engine = {+ sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 111 }),+ sendImageMessage: jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 111 }),+ sendAudioMessage: jest.fn().mockResolvedValue({ id: 'wa1', timestamp: 111 }),+ };engines = new EngineRegistry();engines.set('s1', engine as unknown as IWhatsAppEngine);messageService = { saveOutgoingMessage: jest.fn().mockResolvedValue(undefined) };@@ -772,6 +776,76 @@ describe('BulkMessageService.processBatch', () => {expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Sam');});+ it('tags participants per item, on the text body and on a media caption alike', async () => {+ // Each item names its own list: a batch fans out to many chats, and a WID is only taggable in a+ // chat the participant is actually in.+ const batch = makeBatch(1);+ batch.messages[0].content = { text: 'Hi @62811', mentions: ['[email protected]'] };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi @62811', ['[email protected]']);++ const media = makeBatch(1);+ media.messages[0].type = 'image';+ media.messages[0].content = {+ image: { base64: 'AAAA', mimetype: 'image/jpeg' },+ caption: 'look @62811',+ mentions: ['[email protected]'],+ };+ repo.findOne.mockResolvedValue(media);++ await runProcessBatch();++ expect(engine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ caption: 'look @62811', mentions: ['[email protected]'] }),+ );+ });++ it('substitutes variables inside mentions, so a campaign can tag a different participant per item', async () => {+ // applyVariables walks the whole content tree, so a placeholder in a WID is rendered like one in+ // the body. That is load-bearing for a personalised batch, and nothing else pins it: a future+ // rewrite of applyVariables that rebuilt the object field by field would drop mentions silently.+ const batch = makeBatch(1);+ batch.messages[0].content = { text: 'Hi @{{num}}', mentions: ['{{num}}@c.us'] };+ batch.messages[0].variables = { num: '62811' };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi @62811', ['[email protected]']);+ });++ it('tags an audio item too, which has no caption to anchor a visible @token', async () => {+ // Audio carries no caption, but a mention still tags through contextInfo, which is why the+ // single-send audio route accepts the field. Skipping it here would accept the list and deliver+ // an untagged voice note, turning a clear 400 into a silent no-op for one bulk type only.+ const batch = makeBatch(1);+ batch.messages[0].type = 'audio';+ batch.messages[0].content = { audio: { base64: 'AAAA', mimetype: 'audio/mpeg' }, mentions: ['[email protected]'] };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendAudioMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mentions: ['[email protected]'] }),+ );+ });++ it('leaves an untagged batch item on its two-argument send', async () => {+ // Control: without a list the call shape every existing batch makes is untouched.+ const batch = makeBatch(1);+ batch.messages[0].content = { text: 'Hi there', mentions: [] };+ repo.findOne.mockResolvedValue(batch);++ await runProcessBatch();++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi there');+ });+it('fails an item whose rendered variables grow its base64 media past the cap (no send, explicit failure)', async () => {process.env.MEDIA_DOWNLOAD_MAX_BYTES = '16';try {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 92aa6621e..faef5df15 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -40,6 +40,7 @@ import { resolveNonNegativeIntEnv } from '../../config/configuration';interface BulkMessageContent {text?: string;caption?: string;+ mentions?: string[];image?: { url?: string; base64?: string; mimetype?: string; filename?: string };video?: { url?: string; base64?: string; mimetype?: string; filename?: string };audio?: { url?: string; base64?: string; mimetype?: string; filename?: string; ptt?: boolean };@@ -767,24 +768,33 @@ export class BulkMessageService implements OnApplicationBootstrap {): Promise<MessageResult> {switch (type) {case 'text':- return engine.sendTextMessage(chatId, content.text || '');+ return content.mentions?.length+ ? engine.sendTextMessage(chatId, content.text || '', content.mentions)+ : engine.sendTextMessage(chatId, content.text || '');case 'image':return engine.sendImageMessage(chatId, {mimetype: content.image?.mimetype || 'image/jpeg',data: stripBase64DataUri(content.image?.base64) || content.image?.url || '',caption: content.caption,+ mentions: content.mentions,});case 'video':return engine.sendVideoMessage(chatId, {mimetype: content.video?.mimetype || 'video/mp4',data: stripBase64DataUri(content.video?.base64) || content.video?.url || '',caption: content.caption,+ mentions: content.mentions,});case 'audio':+ // Forwarded even though audio carries no caption: a mention tags the recipient through+ // contextInfo without visible @text, which is why the single-send audio route accepts it too+ // (see sendAudioMessage in baileys-messaging.ts). Dropping it here would accept the field and+ // then deliver an untagged voice note with nothing to say so.return engine.sendAudioMessage(chatId, {mimetype: content.audio?.mimetype || (content.audio?.ptt ? 'audio/ogg; codecs=opus' : 'audio/mpeg'),data: stripBase64DataUri(content.audio?.base64) || content.audio?.url || '',ptt: content.audio?.ptt,+ mentions: content.mentions,});case 'document':return engine.sendDocumentMessage(chatId, {@@ -792,6 +802,7 @@ export class BulkMessageService implements OnApplicationBootstrap {data: stripBase64DataUri(content.document?.base64) || content.document?.url || '',filename: content.document?.filename,caption: content.caption,+ mentions: content.mentions,});default:return Promise.reject(new Error(`Unsupported message type: ${type}`));diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.tsindex c07194fa8..bf34d26c7 100644--- a/src/modules/message/dto/bulk-message.dto.ts+++ b/src/modules/message/dto/bulk-message.dto.ts@@ -14,7 +14,15 @@ import {ArrayMaxSize,} from 'class-validator';import { Type } from 'class-transformer';+import { Validate } from 'class-validator';import { ToStrictBoolean } from '../../../common/utils/strict-boolean';+import {+ MENTIONS_DESCRIPTION,+ MENTIONS_MAX,+ MENTION_WID_MAX_LENGTH,+ MESSAGE_TEXT_MAX_LENGTH,+} from './send-message.dto';+import { IsMentionWidConstraint } from './is-mention-wid.validator';import { BatchMessageStatus, BatchStatus } from '../entities/message-batch.entity';class BulkMediaDto {@@ -46,10 +54,10 @@ class BulkMediaDto {}class BulkMessageContentDto {- @ApiPropertyOptional({ description: 'Text content for text messages', maxLength: 4096 })+ @ApiPropertyOptional({ description: 'Text content for text messages', maxLength: MESSAGE_TEXT_MAX_LENGTH })@IsOptional()@IsString()- @MaxLength(4096)+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)text?: string;// Typed nested DTOs (not bare object literals) so the global ValidationPipe's whitelist /@@ -84,6 +92,18 @@ class BulkMessageContentDto {@IsString()@MaxLength(1024)caption?: string;++ // Applies to the text body and to a media caption alike, matching the single-send routes. Every+ // item in a batch names its own list: a batch fans out to many chats, and a WID is only taggable+ // in a chat the participant is in.+ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @ArrayMaxSize(MENTIONS_MAX)+ @IsString({ each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })+ @Validate(IsMentionWidConstraint, { each: true })+ mentions?: string[];}class BulkMessageItemDto {diff --git a/src/modules/message/dto/message-actions.dto.spec.ts b/src/modules/message/dto/message-actions.dto.spec.tsindex 670d52522..a1816c1e0 100644--- a/src/modules/message/dto/message-actions.dto.spec.ts+++ b/src/modules/message/dto/message-actions.dto.spec.ts@@ -1,3 +1,4 @@+import { ValidationPipe } from '@nestjs/common';import { plainToInstance } from 'class-transformer';import { validate, ValidationError } from 'class-validator';import {@@ -7,7 +8,9 @@ import {DeleteMessageDto,ForwardMessageDto,EditMessageDto,+ ReplyMessageDto,} from './message-actions.dto';+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';/*** Regression locks: these endpoints previously took inline @Body literals (no@@ -141,3 +144,47 @@ describe('message action DTOs', () => {expect(errs.some(e => e.property === 'messageId')).toBe(true);});});++/**+ * These run through the REAL production pipe rather than bare `validate()`, because the defect they+ * lock is a whitelist rejection: `forbidNonWhitelisted` answers 400 "property X should not exist"+ * for anything the DTO does not declare, and a plain validate() call cannot see that at all.+ */+describe('mentions on the quoted-send and edit routes (whitelist behaviour)', () => {+ const pipe = new ValidationPipe(GLOBAL_VALIDATION_OPTIONS);+ const through = (metatype: unknown, value: object): Promise<unknown> =>+ pipe.transform(value, { type: 'body', metatype: metatype as never });++ const REPLY = { chatId: '[email protected]', quotedMessageId: 'Q1', text: 'hi @62811' };+ const EDIT = { chatId: '[email protected]', messageId: 'M1', body: 'hi @62811' };++ it('ReplyMessageDto accepts a mentions array', async () => {+ await expect(through(ReplyMessageDto, { ...REPLY, mentions: ['[email protected]'] })).resolves.toMatchObject({+ mentions: ['[email protected]'],+ });+ });++ it('EditMessageDto accepts a mentions array', async () => {+ await expect(through(EditMessageDto, { ...EDIT, mentions: ['[email protected]'] })).resolves.toMatchObject({+ mentions: ['[email protected]'],+ });+ });++ // Control for both cases above. Without it, a pipe whose whitelist had been switched off entirely+ // would satisfy them just as well, and the assertions would prove nothing about the new field.+ it('still refuses a property no DTO declares', async () => {+ await expect(through(ReplyMessageDto, { ...REPLY, notAField: 1 })).rejects.toMatchObject({+ response: { message: ['property notAField should not exist'] },+ });+ await expect(through(EditMessageDto, { ...EDIT, notAField: 1 })).rejects.toMatchObject({+ response: { message: ['property notAField should not exist'] },+ });+ });++ it('rejects a mentions entry that is not an individual WID', async () => {+ // A group id is not a participant, and the shared constraint refuses it on every route that+ // takes the field.+ await expect(through(ReplyMessageDto, { ...REPLY, mentions: ['[email protected]'] })).rejects.toBeDefined();+ await expect(through(EditMessageDto, { ...EDIT, mentions: ['not-a-wid'] })).rejects.toBeDefined();+ });+});diff --git a/src/modules/message/dto/message-actions.dto.ts b/src/modules/message/dto/message-actions.dto.tsindex e1b43d065..e02a487a2 100644--- a/src/modules/message/dto/message-actions.dto.ts+++ b/src/modules/message/dto/message-actions.dto.ts@@ -11,9 +11,18 @@ import {ArrayMaxSize,MaxLength,IsIn,+ Validate,} from 'class-validator';import { ToStrictBoolean, ToStrictNumber } from '../../../common/utils/strict-boolean';-import { MESSAGE_TEXT_MAX_LENGTH, QUOTED_MESSAGE_ID_DESCRIPTION, QUOTED_MESSAGE_ID_EXAMPLE } from './send-message.dto';+import {+ MENTIONS_DESCRIPTION,+ MENTIONS_MAX,+ MENTION_WID_MAX_LENGTH,+ MESSAGE_TEXT_MAX_LENGTH,+ QUOTED_MESSAGE_ID_DESCRIPTION,+ QUOTED_MESSAGE_ID_EXAMPLE,+} from './send-message.dto';+import { IsMentionWidConstraint } from './is-mention-wid.validator';/*** Validated DTOs for the message action endpoints. These replaced inline@@ -148,6 +157,15 @@ export class ReplyMessageDto {@IsNotEmpty()@MaxLength(MESSAGE_TEXT_MAX_LENGTH)text!: string;++ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @ArrayMaxSize(MENTIONS_MAX)+ @IsString({ each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })+ @Validate(IsMentionWidConstraint, { each: true })+ mentions?: string[];}export class ForwardMessageDto {@@ -311,10 +329,22 @@ export class EditMessageDto {@IsNotEmpty()messageId!: string;- // Same body cap as SendTextMessageDto.text — an edit cannot exceed what a send allows.- @ApiProperty({ description: 'New text body for the message', maxLength: 4096 })+ // Same body cap as SendTextMessageDto.text — an edit cannot exceed what a send allows. Bound to the+ // shared constant rather than restated, so the two cannot drift apart.+ @ApiProperty({ description: 'New text body for the message', maxLength: MESSAGE_TEXT_MAX_LENGTH })@IsString()@IsNotEmpty()- @MaxLength(4096)+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)body!: string;++ // An edit REPLACES the message content, so tags are re-applied rather than preserved: omitting+ // this drops whatever the original body carried.+ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @ArrayMaxSize(MENTIONS_MAX)+ @IsString({ each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })+ @Validate(IsMentionWidConstraint, { each: true })+ mentions?: string[];}diff --git a/src/modules/message/dto/send-message.dto.ts b/src/modules/message/dto/send-message.dto.tsindex bf257b1d2..4b90cd43c 100644--- a/src/modules/message/dto/send-message.dto.ts+++ b/src/modules/message/dto/send-message.dto.ts@@ -16,9 +16,18 @@ import { Type } from 'class-transformer';import { IsMentionWidConstraint } from './is-mention-wid.validator';import { ToStrictBoolean } from '../../../common/utils/strict-boolean';-const MENTIONS_DESCRIPTION =+export const MENTIONS_DESCRIPTION ='WIDs to @mention (e.g. ["[email protected]"]). The text/caption must also contain the @<number> token.';+/**+ * Caps for a `mentions` array, exported because the field now appears on every REST route whose+ * engine can carry it: send, reply, edit, template and bulk. Inline literals repeated per site is+ * how the two numbers would drift apart between endpoints that share one documented contract. The+ * agent-tool schemas do NOT declare mentions on any tool yet, so nothing there reads these.+ */+export const MENTIONS_MAX = 1024;+export const MENTION_WID_MAX_LENGTH = 64;+// Single source of truth for the text-body cap, shared with the agent-tool input schemas// (src/core/agent-tools/tools/message.tools.ts) so MCP and REST enforce the same limit.export const MESSAGE_TEXT_MAX_LENGTH = 4096;@@ -84,9 +93,9 @@ export class SendTextMessageDto {@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })@IsOptional()@IsArray()- @ArrayMaxSize(1024)+ @ArrayMaxSize(MENTIONS_MAX)@IsString({ each: true })- @MaxLength(64, { each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })@Validate(IsMentionWidConstraint, { each: true })mentions?: string[];@@ -212,9 +221,9 @@ export class SendMediaMessageDto {@ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })@IsOptional()@IsArray()- @ArrayMaxSize(1024)+ @ArrayMaxSize(MENTIONS_MAX)@IsString({ each: true })- @MaxLength(64, { each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })@Validate(IsMentionWidConstraint, { each: true })mentions?: string[];diff --git a/src/modules/message/dto/send-template.dto.ts b/src/modules/message/dto/send-template.dto.tsindex 1a6b0ebb3..bfb955c46 100644--- a/src/modules/message/dto/send-template.dto.ts+++ b/src/modules/message/dto/send-template.dto.ts@@ -1,5 +1,19 @@import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';-import { IsString, IsNotEmpty, IsOptional, IsObject, ValidateIf } from 'class-validator';+import {+ IsString,+ IsNotEmpty,+ IsOptional,+ IsObject,+ ValidateIf,+ IsArray,+ ArrayMaxSize,+ MaxLength,+ IsBoolean,+ Validate,+} from 'class-validator';+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';+import { MENTIONS_DESCRIPTION, MENTIONS_MAX, MENTION_WID_MAX_LENGTH } from './send-message.dto';+import { IsMentionWidConstraint } from './is-mention-wid.validator';export class SendTemplateMessageDto {@ApiProperty({@@ -37,4 +51,29 @@ export class SendTemplateMessageDto {@IsOptional()@IsObject()vars?: Record<string, string>;++ // The rendered body is dispatched through the same path as send-text, so it carries the same two+ // optionals. `quotedMessageId` is deliberately NOT among them: docs/06 publishes this route as one+ // that rejects it.+ @ApiPropertyOptional({ description: MENTIONS_DESCRIPTION, example: ['[email protected]'], type: [String] })+ @IsOptional()+ @IsArray()+ @ArrayMaxSize(MENTIONS_MAX)+ @IsString({ each: true })+ @MaxLength(MENTION_WID_MAX_LENGTH, { each: true })+ @Validate(IsMentionWidConstraint, { each: true })+ mentions?: string[];++ @ApiPropertyOptional({+ description:+ 'Controls the URL preview on the rendered body, with the same engine split as send-text: ' ++ 'whatsapp-web.js builds one by default and `false` suppresses it, while on Baileys previews ' ++ 'are opt-in and only `true` attaches one.',+ example: false,+ })+ // Same guard as send-text: implicit conversion would turn the string "false" into true.+ @ToStrictBoolean()+ @IsOptional()+ @IsBoolean()+ linkPreview?: boolean;}diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex debd70294..436465781 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -426,6 +426,33 @@ describe('MessageSendService', () => {expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Alice {{unknown}}');});+ it('carries mentions and linkPreview from the template body through to the send', async () => {+ // The rendered body is dispatched through sendText, so the two optionals it already honours+ // reach the engine unchanged rather than being dropped at the template DTO.+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi @62811' }));++ await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ mentions: ['[email protected]'],+ linkPreview: false,+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi @62811', ['[email protected]'], {+ linkPreview: false,+ });+ });++ it('leaves a plain template send on its two-argument call shape', async () => {+ // Control for the case above: without either optional the call must not gain arguments, or+ // every existing template send changes shape.+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi there' }));++ await service.sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1' });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi there');+ });+it('should propagate NotFoundException when the template cannot be resolved', async () => {(templateService.resolve as jest.Mock).mockRejectedValue(new NotFoundException('Template not found'));@@ -925,6 +952,53 @@ describe('MessageSendService', () => {expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'This is a reply');});++ it('forwards the tag list to the engine, and keeps the untagged call three-argument', async () => {+ await service.reply('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'wa-quoted-1',+ text: 'hi @62811',+ mentions: ['[email protected]'],+ });++ expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'hi @62811', ['[email protected]']);++ // Control: an empty list is not a tag request, so the call shape every existing reply makes is+ // left untouched rather than gaining a trailing argument.+ mockEngine.replyToMessage.mockClear();+ await service.reply('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'wa-quoted-1',+ text: 'plain',+ mentions: [],+ });+ expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'plain');+ });++ it('honours a plugin that rewrites the tag list, not the list the caller sent', async () => {+ // message:sending is a moderation chokepoint. Reading the caller's own dto here instead of the+ // gated result would send the unredacted tags while the hook reported success.+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: {+ input: {+ chatId: '[email protected]',+ quotedMessageId: 'wa-quoted-1',+ text: 'hi @62811',+ mentions: ['[email protected]'],+ },+ },+ });++ await service.reply('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'wa-quoted-1',+ text: 'hi @62811 @62999',+ mentions: ['[email protected]', '[email protected]'],+ });++ expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'hi @62811', ['[email protected]']);+ });});describe('forward', () => {diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex c3e58d6a7..2afadef19 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -238,7 +238,12 @@ export class MessageSendService {);}- return this.sendText(sessionId, { chatId: dto.chatId, text });+ return this.sendText(sessionId, {+ chatId: dto.chatId,+ text,+ mentions: dto.mentions,+ linkPreview: dto.linkPreview,+ });}async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {@@ -471,7 +476,7 @@ export class MessageSendService {async reply(sessionId: string,- dto: { chatId: string; quotedMessageId: string; text: string },+ dto: { chatId: string; quotedMessageId: string; text: string; mentions?: string[] },): Promise<MessageResponseDto> {const finalDto = await this.applySendingGate(sessionId, 'reply', dto);const engine = this.getEngine(sessionId);@@ -499,7 +504,11 @@ export class MessageSendService {let result: MessageResult;try {- result = await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text);+ // Widened only as far as the caller asked, exactly like the send path: a reply with no tags+ // keeps its three-argument shape.+ result = finalDto.mentions?.length+ ? await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text, finalDto.mentions)+ : await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text);} catch (error) {return this.failSend(sessionId, 'reply', message, finalDto, error);}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex dbc84c141..ba1a6a01b 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -621,6 +621,25 @@ describe('MessageService', () => {expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'redacted');expect(messageProjector.recordOutboundMessageEdit).toHaveBeenCalledWith('sess-1', 'wa-msg-1', 'redacted');});++ it('honours a plugin that rewrites the tag list, not the list the caller sent', async () => {+ // message:sending is a moderation chokepoint, so a handler that drops a WID from the list must+ // win. Reading the caller's own dto here instead of the gated one would send the unredacted+ // tags while the hook reported success, and no other assertion in this file would notice.+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { input: { chatId: '[email protected]', messageId: 'wa-msg-1', body: 'hi @62811', mentions: ['[email protected]'] } },+ });++ await service.editMessage('sess-1', {+ chatId: '[email protected]',+ messageId: 'wa-msg-1',+ body: 'hi @62811 @62999',+ mentions: ['[email protected]', '[email protected]'],+ });++ expect(mockEngine.editMessage).toHaveBeenCalledWith('[email protected]', 'wa-msg-1', 'hi @62811', ['[email protected]']);+ });});// ── pin / unpin ───────────────────────────────────────────────────diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 248668b01..718b5b59b 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -480,14 +480,16 @@ export class MessageService {async editMessage(sessionId: string,- dto: { chatId: string; messageId: string; body: string },+ dto: { chatId: string; messageId: string; body: string; mentions?: string[] },): Promise<MessageResponseDto> {const engine = this.getEngine(sessionId);// An edit replaces the text the recipient sees, so it is content leaving the account and goes// through the same moderation chokepoint as every other sender. A plugin can rewrite `body`// here exactly as it can for a first send.const finalDto = await this.applySendingGate(sessionId, 'edit', dto);- const result = await engine.editMessage(finalDto.chatId, finalDto.messageId, finalDto.body);+ const result = finalDto.mentions?.length+ ? await engine.editMessage(finalDto.chatId, finalDto.messageId, finalDto.body, finalDto.mentions)+ : await engine.editMessage(finalDto.chatId, finalDto.messageId, finalDto.body);// Best-effort: reflect the new body in the stored copy (mirrors deleteMessage's revoked flag),// serialized with the inbound edit/reaction writers through the session's per-message mutation