Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): resolve LID-addressing residuals — reply/forward, presence, mapping, dashboard (#583) (#584)

Yudhi Armyndharisc9b7451b7406
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 147fdbf62..7c4e48f9a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **Replying to and forwarding to a LID-migrated contact no longer fail with HTTP 500 on the whatsapp-web.js engine.** These paths sent to the phone id (`@c.us`) like the original send bug (#573), so a contact WhatsApp had migrated to `@lid` rejected them with `No LID for user`. They now resolve the recipient the same way as a normal send (including the self-heal retry), and a forward reads back its delivered id from the resolved chat so delivery status still reconciles. (#583)
+- **The typing/presence endpoint no longer returns HTTP 500 on the Baileys engine when a presence update fails.** Presence is best-effort; a failure (e.g. `No LID for user` for a migrated contact) is now caught and logged at `WARN` and the request succeeds, matching the whatsapp-web.js engine. This also covers the presence agent tool. (#583)
+- **Chat history for a LID-migrated contact is no longer split across two entries on the whatsapp-web.js engine.** The engine now records the `phone ↔ lid` mapping it learns (when resolving a send, and when resolving an inbound `@lid` sender's number), so the messages API bridges a contact's `@c.us` and `@lid` rows into one conversation — previously only the Baileys engine populated this mapping. (#583)
+- **The dashboard chat list no longer refetches on every message sent to a LID-migrated contact.** The outgoing echo can arrive addressed as `@lid` while the open chat is `@c.us`; the sent message is already shown via the send response, so the sidebar no longer triggers a full reload for an outgoing echo with no matching chat. (#583)
+
## [0.7.20] - 2026-07-02
### Fixed
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 158807d56..bc356369f 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -241,7 +241,15 @@ export function Chats() {
setChats(prevChats => {
const chatIndex = prevChats.findIndex(c => c.id === newMsg.chatId);
if (chatIndex === -1) {
- void loadChats(selectedSessionId);
+ // A message for a chat not in the sidebar. Suppress the refetch ONLY for an outgoing echo
+ // addressed as `@lid`: a LID-migrated contact echoes back `@lid` while the user sent to
+ // `@c.us`, and the sent bubble is already reconciled in the active chat, so refetching on
+ // every such send just churns the chat list (#583 R2). Incoming messages and ordinary
+ // outgoing sends to a genuinely new chat still refetch so the sidebar stays complete.
+ const isMigratedEcho = newMsg.fromMe && (newMsg.chatId?.endsWith('@lid') ?? false);
+ if (!isMigratedEcho) {
+ void loadChats(selectedSessionId);
+ }
return prevChats;
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index f277e4593..7399295e0 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -611,6 +611,12 @@ describe('BaileysAdapter messaging', () => {
expect(fakeSock.sendPresenceUpdate).toHaveBeenCalledWith('composing', '[email protected]');
});
+ it('sendChatState swallows a presence failure (best-effort, mirrors wwjs) (#583 R4)', async () => {
+ const adapter = await readyAdapter();
+ fakeSock.sendPresenceUpdate.mockRejectedValueOnce(new Error('No LID for user'));
+ await expect(adapter.sendChatState('[email protected]', 'typing')).resolves.toBeUndefined();
+ });
+
it('messaging methods throw EngineNotReadyError before the connection is open', async () => {
const adapter = newAdapter();
await adapter.initialize({});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index a7ac775f0..e8d30fe57 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -506,7 +506,14 @@ export class BaileysAdapter implements IWhatsAppEngine {
async sendChatState(chatId: string, state: ChatState): Promise<void> {
this.ensureReady();
const presence = state === 'typing' ? 'composing' : state === 'recording' ? 'recording' : 'paused';
- await this.sock!.sendPresenceUpdate(presence, chatId);
+ try {
+ await this.sock!.sendPresenceUpdate(presence, chatId);
+ } catch (error) {
+ // Presence is best-effort — a failure here must never surface as a 500 on the direct typing
+ // endpoint or MCP tool (mirrors the whatsapp-web.js adapter; #583 R4). A migrated contact can
+ // yield `No LID for user` on the presence path even when the actual send succeeds.
+ this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, String(error));
+ }
}
async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 4d05a367e..a263ed53b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1391,6 +1391,78 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lid
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(getNumberId).toHaveBeenCalledTimes(1);
});
+
+ it('reply routes its send leg to the resolved @lid (#583 R1)', 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: '159442138038327@lid' });
+ await ready({ getChatById, getNumberId }).replyToMessage('[email protected]', 'Q1', 'hi');
+ expect(reply).toHaveBeenCalledWith('hi', '159442138038327@lid');
+ });
+
+ it('reply is unchanged for a non-migrated contact (#583 R1)', 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');
+ 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 };
+ const srcChat = { fetchMessages: jest.fn().mockResolvedValue([srcMsg]) };
+ const destChat = { fetchMessages: jest.fn().mockResolvedValue([{ id: { _serialized: 'OUT1' }, timestamp: 123 }]) };
+ const getChatById = jest.fn().mockResolvedValueOnce(srcChat).mockResolvedValueOnce(destChat);
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });
+ const res = await ready({ getChatById, getNumberId }).forwardMessage('[email protected]', '[email protected]', 'M1');
+ expect(forward).toHaveBeenCalledWith('159442138038327@lid');
+ expect(getChatById).toHaveBeenNthCalledWith(2, '159442138038327@lid');
+ expect(res.id).toBe('OUT1');
+ });
+});
+
+describe('LID mapping persistence to LidMappingStore (#583 R3)', () => {
+ const readyWithStore = (client: unknown, lidMappingStore: unknown): WhatsAppWebJsAdapter => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: 's1',
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ lidMappingStore: lidMappingStore as never,
+ });
+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;
+ (adapter as unknown as { client: unknown }).client = client;
+ return adapter;
+ };
+ const sentMessage = { id: { _serialized: 'OUT1' }, timestamp: 1700000001 };
+ const makeStore = (remember: jest.Mock) => ({ remember, getCached: () => undefined, lidsForPhone: () => [] });
+
+ it('persists phone->lid (bare digits) when a contact resolves to an @lid', async () => {
+ const remember = jest.fn().mockResolvedValue(undefined);
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ await readyWithStore({ getNumberId, sendMessage }, makeStore(remember)).sendTextMessage('[email protected]', 'hi');
+ expect(remember).toHaveBeenCalledWith('159442138038327', '529934031058', 's1');
+ });
+
+ it('does not persist a confirmed non-migrated (@c.us) resolution', async () => {
+ const remember = jest.fn().mockResolvedValue(undefined);
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '[email protected]' });
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ await readyWithStore({ getNumberId, sendMessage }, makeStore(remember)).sendTextMessage('[email protected]', 'hi');
+ expect(remember).not.toHaveBeenCalled();
+ });
+
+ it('a rejecting remember never fails the send (fire-and-forget)', async () => {
+ const remember = jest.fn().mockRejectedValue(new Error('db down'));
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '159442138038327@lid' });
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ await expect(
+ readyWithStore({ getNumberId, sendMessage }, makeStore(remember)).sendTextMessage('[email protected]', 'hi'),
+ ).resolves.toBeDefined();
+ });
});
describe('extractWwebjsCall (call_log → { video, missed }, salvaged from #494)', () => {
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8033cb3a1..f8e4775f2 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -34,7 +34,8 @@ import {
ReactionEvent,
} from '../interfaces/whatsapp-engine.interface';
import { resolveWebVersionPin } from '../wa-web-version';
-import { isChannelJid } from '../identity/wa-id';
+import { isChannelJid, userPart } from '../identity/wa-id';
+import { LidMappingStore } from '../identity/lid-mapping-store.service';
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
import { createLogger } from '../../common/services/logger.service';
import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
@@ -139,6 +140,9 @@ export interface WhatsAppWebJsConfig {
url: string;
type: 'http' | 'https' | 'socks4' | 'socks5';
};
+ // Shared lid<->phone table. Threaded in so the wwjs engine can persist the `phone -> lid` pairs it
+ // learns while resolving sends, letting the message read-path bridge `@c.us`/`@lid` rows (#583 R3).
+ lidMappingStore?: LidMappingStore;
}
const READY_RECONCILE_INTERVAL_MS = 2000;
@@ -844,6 +848,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
const wid = await this.getNumberId(chatId);
if (wid) {
this.resolvedSendIds.set(chatId, wid);
+ if (wid.endsWith('@lid')) {
+ // Persist the learned phone -> lid so the message read-path (resolveJidCandidates) can
+ // bridge this contact's `@c.us` and `@lid` rows on a pure whatsapp-web.js deployment
+ // (#583 R3). Fire-and-forget: resolution (and the send) must never block/fail on the write.
+ void this.config.lidMappingStore
+ ?.remember(userPart(wid), userPart(chatId), this.config.sessionId)
+ ?.catch(() => {});
+ }
return wid;
}
return chatId;
@@ -1099,7 +1111,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
throw new MessageNotFoundError(quotedMsgId);
}
- const msg = await quotedMsg.reply(text);
+ // 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));
return {
id: msg.id._serialized,
timestamp: msg.timestamp,
@@ -1116,7 +1131,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
throw new MessageNotFoundError(messageId);
}
- await msgToForward.forward(toChatId);
+ // The forward's send leg fails with `No LID for user` for a LID-migrated destination, so resolve
+ // it (and self-heal a stale mapping) via sendResolved. Capture the id actually sent to so the
+ // id-recovery below reads back from the SAME (resolved) chat, not the raw @c.us (#583 R1).
+ let resolvedTo = toChatId;
+ await this.sendResolved(toChatId, to => {
+ resolvedTo = to;
+ return msgToForward.forward(to);
+ });
// whatsapp-web.js's forward() returns void, so BEST-EFFORT recover the REAL id of the sent copy by
// reading it back from the destination chat (the most recent outgoing message). The delivery-ack
@@ -1127,7 +1149,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// which could cross-drive another row's delivery status. Concurrent forwards to the same chat may
// mis-identify the copy — acceptable for delivery-status accuracy.
try {
- const destChat = await this.client!.getChatById(toChatId);
+ const destChat = await this.client!.getChatById(resolvedTo);
const sentByMe = (await destChat?.fetchMessages({ limit: 5, fromMe: true })) ?? [];
let sent: (typeof sentByMe)[number] | undefined;
for (const m of sentByMe) {
@@ -1263,6 +1285,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Reactions (Phase 3)
async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {
this.ensureReady();
+ // NOTE: do NOT resolve chatId to @lid here — whatsapp-web.js reacts using the found message's own
+ // id, not this chatId, so LID-resolving the lookup gives no send benefit and would miss a message
+ // stored under the pre-migration @c.us chat (#583 R1 review).
const chat = await this.client!.getChatById(chatId);
const messages = await chat.fetchMessages({ limit: 100 });
const message = messages.find(m => m.id._serialized === messageId);
@@ -1511,6 +1536,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// Delete Message
async deleteMessage(chatId: string, messageId: string, forEveryone: boolean = true): Promise<void> {
this.ensureReady();
+ // NOTE: do NOT resolve chatId to @lid here — delete operates on the found message's own key, not
+ // this chatId, so LID-resolving the lookup gives no benefit and would miss a message stored under
+ // the pre-migration @c.us chat (#583 R1 review).
const chat = await this.client!.getChatById(chatId);
const messages = await chat.fetchMessages({ limit: 100 });
const message = messages.find(m => m.id._serialized === messageId || m.id.id === messageId);
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 6d37b2cce..12b9ded91 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -52,7 +52,7 @@ export class EngineFactory implements OnModuleInit {
provides: ['whatsapp-engine'],
};
- const wwjsPlugin = new WhatsAppWebJsPlugin(engineConfig);
+ const wwjsPlugin = new WhatsAppWebJsPlugin(engineConfig, this.lidMappingStore);
this.pluginLoader.registerBuiltInPlugin(wwjsManifest, wwjsPlugin, engineConfig);
// Register Baileys as a second built-in engine plugin. Same opaque engine blob; the plugin
@@ -147,6 +147,7 @@ export class EngineFactory implements OnModuleInit {
type: options.proxyType ?? 'http',
}
: undefined,
+ lidMappingStore: this.lidMappingStore,
});
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index ac13bffdc..2e1243976 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -8,6 +8,7 @@ import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageStatus } from '../message/entities/message.entity';
import { MessageBatch } from '../message/entities/message-batch.entity';
import { EngineFactory } from '../../engine/engine.factory';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
@@ -42,6 +43,7 @@ describe('SessionService', () => {
let webhookService: jest.Mocked<Partial<WebhookService>>;
let hookManager: jest.Mocked<Partial<HookManager>>;
let configService: jest.Mocked<Partial<ConfigService>>;
+ let lidMappingStore: jest.Mocked<Partial<LidMappingStoreService>>;
let mockEngine: Record<string, jest.Mock>;
beforeEach(async () => {
@@ -117,6 +119,12 @@ describe('SessionService', () => {
get: jest.fn().mockImplementation(<T>(_key: string, def?: T): T => def as T),
};
+ lidMappingStore = {
+ remember: jest.fn().mockResolvedValue(undefined),
+ getCached: jest.fn().mockReturnValue(undefined),
+ lidsForPhone: jest.fn().mockReturnValue([]),
+ };
+
const module: TestingModule = await Test.createTestingModule({
providers: [
SessionService,
@@ -137,6 +145,7 @@ describe('SessionService', () => {
{ provide: WebhookService, useValue: webhookService },
{ provide: HookManager, useValue: hookManager },
{ provide: ConfigService, useValue: configService },
+ { provide: LidMappingStoreService, useValue: lidMappingStore },
],
}).compile();
@@ -1292,6 +1301,9 @@ describe('SessionService', () => {
expect(received).toHaveLength(1);
expect((received[0][2] as IncomingMessage).senderPhone).toBe('628111222333');
expect(mockEngine.resolveContactPhone).toHaveBeenCalledWith('111@lid');
+ // #583 R3 Phase 2: the resolved inbound @lid -> phone is persisted so the read-path can bridge
+ // this contact's @lid and @c.us rows even if the operator never sent to them.
+ expect(lidMappingStore.remember).toHaveBeenCalledWith('111', '628111222333', expect.any(String));
} finally {
delete process.env.RESOLVE_LID_TO_PHONE;
}
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 000de75e0..cfbe569ca 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -17,6 +17,8 @@ import { Message, MessageDirection, MessageStatus } from '../message/entities/me
import { MessageBatch } from '../message/entities/message-batch.entity';
import { CreateSessionDto } from './dto';
import { EngineFactory } from '../../engine/engine.factory';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { userPart } from '../../engine/identity/wa-id';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import {
@@ -144,6 +146,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly hookManager: HookManager,
@Optional()
private readonly configService?: ConfigService,
+ // Shared lid<->phone table (global). Used to persist an inbound @lid sender's resolved phone so
+ // an inbound-only migrated contact's `@lid` and `@c.us` rows bridge in the read-path (#583 R3 Ph2).
+ @Optional()
+ private readonly lidMappingStore?: LidMappingStoreService,
) {}
/**
@@ -1266,6 +1272,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
this.lidPhoneCache.set(key, phone);
+ // Persist a real @lid -> phone resolution so the read-path can bridge this contact's `@lid` and
+ // `@c.us` rows even when the operator never sent to them (#583 R3 Phase 2). Reuses the resolution
+ // above — no extra network call — and is fire-and-forget so dispatch never blocks/fails on it.
+ if (phone) {
+ void this.lidMappingStore?.remember(userPart(contactId), phone, sessionId)?.catch(() => {});
+ }
return phone;
}
diff --git a/src/plugins/engines/whatsapp-web-js/index.ts b/src/plugins/engines/whatsapp-web-js/index.ts
index d8c6d76a6..9bc375fee 100644
--- a/src/plugins/engines/whatsapp-web-js/index.ts
+++ b/src/plugins/engines/whatsapp-web-js/index.ts
@@ -6,6 +6,7 @@
import { PluginContext, PluginType, IEnginePlugin } from '../../../core/plugins';
import { IWhatsAppEngine } from '../../../engine/interfaces/whatsapp-engine.interface';
import { WhatsAppWebJsAdapter } from '../../../engine/adapters/whatsapp-web-js.adapter';
+import { LidMappingStore } from '../../../engine/identity/lid-mapping-store.service';
export class WhatsAppWebJsPlugin implements IEnginePlugin {
type = PluginType.ENGINE as const;
@@ -14,7 +15,12 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {
// The engine config blob is also supplied at construction so createEngine has operator
// config even if enablePlugin fails before onLoad runs (which would leave this.context unset).
// The healthy path still prefers context.config (it carries any persisted-override merge).
- constructor(private readonly registeredConfig?: Record<string, unknown>) {}
+ constructor(
+ private readonly registeredConfig?: Record<string, unknown>,
+ // Shared lid<->phone table, threaded to the adapter so it can persist learned phone->lid pairs
+ // (mirrors how BaileysPlugin receives it; #583 R3).
+ private readonly lidMappingStore?: LidMappingStore,
+ ) {}
onLoad(context: PluginContext): Promise<void> {
this.context = context;
@@ -64,6 +70,7 @@ export class WhatsAppWebJsPlugin implements IEnginePlugin {
type: proxyType ?? 'http',
}
: undefined,
+ lidMappingStore: this.lidMappingStore,
});
}