Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): keep formatting around a resolved mention

Yudhi Armyndharisaa11f913b89e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f7d0f1557..36b634f27 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The resolved name renders inside its own `<bdi>` element, outside Linkify's `ignoreTags`-respected walk, so a push name can never become a clickable link, however it's spelled. Thanks @TanmayChachra.
+
## [0.23.6] - 2026-09-23
### Added
@@ -37,7 +41,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
-- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The resolved name renders inside its own `<bdi>` element, outside Linkify's `ignoreTags`-respected walk, so a push name can never become a clickable link, however it's spelled. Thanks @TanmayChachra.
- The dashboard Chats page drops a staged reply when another chat or session is opened, so a text send there no longer fails with `404` and a media send no longer quotes the previous chat's message.
- whatsapp-web.js chat history resolves each message's sender through `getContact()`, as the live `message` handler already does, so a group participant outside the account's contacts gets a sender label in history too. Thanks @TanmayChachra.
- A WebSocket client that emits without an ack callback now receives command replies at all. The gateway answered by returning a frame, which Socket.IO delivers through the ack callback and nowhere else, so a client written to the documented `message` event saw no subscribe confirmation, no pong, and none of the refusals, including the session-scope denial. Replies now go out on `message` as well as through the ack.
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index aa28dcacb..b7da11600 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -509,6 +509,7 @@ test('resolveMentions needs a left boundary: start of text, whitespace, or openi
assert.equal(resolveMentions('(@12345678)', names), `(${wrap('@Ravi')})`);
assert.equal(resolveMentions('[@12345678]', names), `[${wrap('@Ravi')}]`);
assert.equal(resolveMentions('"@12345678"', names), `"${wrap('@Ravi')}"`);
+ assert.equal(resolveMentions('*@12345678*', names), `*${wrap('@Ravi')}*`);
});
test('resolveMentions does not fire inside an email address', () => {
@@ -560,3 +561,23 @@ test('a later usable name for the same participant is still picked up after a bl
]);
assert.equal(resolveMentions('@6281112345', names), wrap('@Ravi'));
});
+
+test('a participant who changed their push name mid-thread resolves to the newest one, not the oldest', () => {
+ const names = buildMentionNameMap([
+ msg({ author: '[email protected]', chatName: 'Ravi Kumar' }),
+ msg({ author: '[email protected]', chatName: 'RK Office' }),
+ msg({ author: '[email protected]', chatName: ' ' }),
+ ]);
+ assert.equal(resolveMentions('@6281112345', names), wrap('@RK'));
+});
+
+test('resolveMentions leaves a mention inside a ``` code block alone, so the block still renders as code', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
+ assert.equal(resolveMentions('```\n@12345678\n```', names), '```\n@12345678\n```');
+ assert.equal(resolveMentions('see `x` @12345678', names), `see \`x\` ${wrap('@Ravi')}`);
+});
+
+test('resolveMentions does not fire right after a closing backtick', () => {
+ const names = buildMentionNameMap([msg({ author: '[email protected]', chatName: 'Ravi' })]);
+ assert.equal(resolveMentions('`x`@12345678', names), '`x`@12345678');
+});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index b0d99a994..427c6a614 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -126,7 +126,8 @@ export function buildMentionNameMap(messages: Pick<ChatMessage, 'author' | 'chat
if (!m.author || !m.chatName) continue;
const local = m.author.split('@')[0].split(':')[0];
const name = blankMentionName(m.chatName) ? '' : m.chatName.trim();
- if (name && /^\d+$/.test(local) && !map.has(local)) map.set(local, name);
+ // Rows are ascending by time, so the last write is the participant's current push name.
+ if (name && /^\d+$/.test(local)) map.set(local, name);
}
return map;
}
@@ -139,6 +140,14 @@ function blankMentionName(name: string): boolean {
return name.replace(HANGUL_FILLER, '').trim() === '';
}
+// The left boundary is the start of the text, whitespace, opening punctuation, or a format opener
+// (`*_~`), so `*@digits*` resolves into a bold mention the way WhatsApp renders it.
+const MENTION_TOKEN = /(^|[\s([{"'*_~])@(\d{7,})/gu;
+
+// parseMessageBody peels code after this runs, so a mention inside a code span or block is left as
+// digits here: rewriting it would split the span and render its backticks literally.
+const CODE_SEGMENT = /(```[\s\S]*?```|`[^`]*`)/;
+
/**
* Replace "@<digits>" mention tokens with "@<FirstName>" wherever the digits match a known
* participant (see buildMentionNameMap). An unmatched token is left exactly as WhatsApp sent it —
@@ -160,10 +169,19 @@ function blankMentionName(name: string): boolean {
*/
export function resolveMentions(text: string, names: Map<string, string>): string {
if (names.size === 0 || !text.includes('@')) return text;
- return text.replace(/(^|[\s([{"'])@(\d{7,})/gu, (full: string, prefix: string, digits: string) => {
- const first = names.get(digits)?.split(' ')[0];
- return first ? `${prefix}${MENTION_OPEN}@${first}${MENTION_CLOSE}` : full;
- });
+ return text
+ .split(CODE_SEGMENT)
+ .map((part, i) =>
+ i % 2
+ ? part
+ : part.replace(MENTION_TOKEN, (full: string, prefix: string, digits: string) => {
+ // `^` only counts at the start of the whole text, not right after a closing backtick.
+ if (i > 0 && prefix === '') return full;
+ const first = names.get(digits)?.split(' ')[0];
+ return first ? `${prefix}${MENTION_OPEN}@${first}${MENTION_CLOSE}` : full;
+ }),
+ )
+ .join('');
}
// ChatMessageView extends ChatMessage with the view-only fields the chat page renders.
diff --git a/dashboard/src/utils/messageFormatter.test.ts b/dashboard/src/utils/messageFormatter.test.ts
index 72f142bb2..c444bc48c 100644
--- a/dashboard/src/utils/messageFormatter.test.ts
+++ b/dashboard/src/utils/messageFormatter.test.ts
@@ -128,3 +128,21 @@ test('two mentions in one message each become their own node', () => {
{ type: 'mention', value: '@Sam' },
]);
});
+
+test('a mention inside *bold* keeps the bold: the split happens at the text leaf, after format parsing', () => {
+ assert.deepEqual(parseMessageBody(`*Reminder ${wrap('@Ravi')} at 10*`), [
+ { type: 'bold', children: [text('Reminder '), { type: 'mention', value: '@Ravi' }, text(' at 10')] },
+ ]);
+});
+
+test('a format marker inside a mention name neither opens nor closes a span around it', () => {
+ assert.deepEqual(parseMessageBody(`*a ${wrap('@*x*')} b*`), [
+ { type: 'bold', children: [text('a '), { type: 'mention', value: '@*x*' }, text(' b')] },
+ ]);
+});
+
+test('a mention that fills a *bold* span on its own resolves and keeps the bold', () => {
+ assert.deepEqual(parseMessageBody(`*${wrap('@Ravi')}*`), [
+ { type: 'bold', children: [{ type: 'mention', value: '@Ravi' }] },
+ ]);
+});
diff --git a/dashboard/src/utils/messageFormatter.ts b/dashboard/src/utils/messageFormatter.ts
index 5d6c94b1c..fa2a68893 100644
--- a/dashboard/src/utils/messageFormatter.ts
+++ b/dashboard/src/utils/messageFormatter.ts
@@ -35,9 +35,6 @@ export const MENTION_CLOSE = '';
* Parse a WhatsApp-formatted text string into a list of MessageNode.
*
* Algorithm:
- * 0. Split off any resolveMentions-wrapped `MENTION_OPEN...MENTION_CLOSE` spans into `mention`
- * nodes first, so their content skips code/format parsing entirely — the substituted name is
- * opaque, not text a `*`/`` ` `` inside it should be able to reformat the surrounding message.
* 1. Extract code segments (triple-backtick blocks first, then single-backtick inline)
* by walking the string and emitting `codeblock` / `code` nodes for them; the
* remaining text segments are passed to the format parser.
@@ -47,36 +44,13 @@ export const MENTION_CLOSE = '';
* segments are emitted iteratively and nesting is depth-capped (MAX_FORMAT_DEPTH), so a
* pathological message can't exhaust the call stack; beyond the cap the rest stays literal.
* 3. Unbalanced or boundary-violating markers fall through as literal text.
+ * 4. Each text leaf is split on the `MENTION_OPEN...MENTION_CLOSE` spans resolveMentions wraps a
+ * resolved name in (see chatMessages.ts), emitting `mention` nodes. This runs at the leaf, after
+ * code and format parsing, so a mention inside *bold* keeps the bold; the format scanner steps
+ * over a span whole, so a `*` in a push name can neither open nor close a span.
*/
export function parseMessageBody(input: string): MessageNode[] {
if (input.length === 0) return [];
- if (!input.includes(MENTION_OPEN)) return parseMessageBodySegment(input);
-
- const nodes: MessageNode[] = [];
- let cursor = 0;
- while (cursor < input.length) {
- const openIdx = input.indexOf(MENTION_OPEN, cursor);
- if (openIdx === -1) {
- for (const n of parseMessageBodySegment(input.slice(cursor))) nodes.push(n);
- break;
- }
- const closeIdx = input.indexOf(MENTION_CLOSE, openIdx + 1);
- if (closeIdx === -1) {
- // Unterminated marker (should not happen from resolveMentions) — treat the rest as plain text.
- for (const n of parseMessageBodySegment(input.slice(cursor))) nodes.push(n);
- break;
- }
- if (openIdx > cursor) {
- for (const n of parseMessageBodySegment(input.slice(cursor, openIdx))) nodes.push(n);
- }
- nodes.push({ type: 'mention', value: input.slice(openIdx + 1, closeIdx) });
- cursor = closeIdx + 1;
- }
- return nodes;
-}
-
-function parseMessageBodySegment(input: string): MessageNode[] {
- if (input.length === 0) return [];
// Step 1: peel off code segments, emit nodes between them.
const nodes: MessageNode[] = [];
@@ -175,6 +149,31 @@ function findSingleBacktick(s: string, from: number): number {
*/
const MAX_FORMAT_DEPTH = 20;
+/**
+ * Emit a text leaf, splitting out the `MENTION_OPEN...MENTION_CLOSE` spans resolveMentions wraps a
+ * resolved name in as `mention` nodes. An unterminated marker stays literal text.
+ */
+function pushText(nodes: MessageNode[], value: string): MessageNode[] {
+ let cursor = 0;
+ while (cursor < value.length) {
+ const open = value.indexOf(MENTION_OPEN, cursor);
+ const close = open === -1 ? -1 : value.indexOf(MENTION_CLOSE, open + 1);
+ if (close === -1) {
+ nodes.push({ type: 'text', value: value.slice(cursor) });
+ break;
+ }
+ if (open > cursor) nodes.push({ type: 'text', value: value.slice(cursor, open) });
+ nodes.push({ type: 'mention', value: value.slice(open + 1, close) });
+ cursor = close + 1;
+ }
+ return nodes;
+}
+
+/** Index of the MENTION_CLOSE ending a span that opens at `i`, or -1 when no span opens there. */
+function mentionEnd(input: string, i: number): number {
+ return input[i] === MENTION_OPEN ? input.indexOf(MENTION_CLOSE, i + 1) : -1;
+}
+
/**
* Parse a text segment (no code in it) for *bold*, _italic_, ~strike~.
* Inner content is parsed again (depth-bounded) so *_a_* nests; sibling segments after a
@@ -182,17 +181,17 @@ const MAX_FORMAT_DEPTH = 20;
*/
function parseFormatting(input: string, depth = 0): MessageNode[] {
if (input.length === 0) return [];
- if (depth >= MAX_FORMAT_DEPTH) return [{ type: 'text', value: input }];
+ if (depth >= MAX_FORMAT_DEPTH) return pushText([], input);
const nodes: MessageNode[] = [];
let rest = input;
while (rest.length > 0) {
const split = splitFirstFormat(rest);
if (!split) {
- nodes.push({ type: 'text', value: rest });
+ pushText(nodes, rest);
break;
}
- if (split.before) nodes.push({ type: 'text', value: split.before });
+ if (split.before) pushText(nodes, split.before);
nodes.push({ type: split.fmt, children: parseFormatting(split.inner, depth + 1) });
rest = split.after;
}
@@ -210,6 +209,11 @@ function splitFirstFormat(
input: string,
): { before: string; fmt: 'bold' | 'italic' | 'strike'; inner: string; after: string } | null {
for (let i = 0; i < input.length; i++) {
+ const skip = mentionEnd(input, i);
+ if (skip !== -1) {
+ i = skip;
+ continue;
+ }
const ch = input[i];
const fmt = FORMATS[ch];
if (!fmt) continue;
@@ -224,6 +228,11 @@ function splitFirstFormat(
// Find the matching closing marker.
for (let j = i + 1; j < input.length; j++) {
+ const skipInner = mentionEnd(input, j);
+ if (skipInner !== -1) {
+ j = skipInner;
+ continue;
+ }
if (input[j] !== ch) continue;
// Char immediately before closer must NOT be whitespace.
const beforeCloser = input[j - 1];