Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): harden LID send resolution (cache + self-heal) and quiet typing log (#580, #582) (#581)

Yudhi Armyndharis58c15b0b4d18
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05e666f84..e077b547a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **Sends to a LID-migrated contact no longer intermittently fail with HTTP 500 on the whatsapp-web.js engine.** The v0.7.19 fix resolves such a contact's phone id to its `@lid` before sending, but that resolution is a WhatsApp Web round-trip that occasionally throws an internal error — in which case the send fell back to the phone id and hit `No LID for user` again, so the message tester (and the API) still returned a 500 now and then. The engine now caches each contact's confirmed resolution for the session (both a migrated `@lid` and a confirmed non-migrated `@c.us`), so a later flaky resolution reuses the known-good id and ordinary contacts are not re-probed on every send. If a send still fails with `No LID for user` — e.g. a contact that migrates mid-session — the engine drops the stale mapping, re-resolves once, and retries. (#580) Thanks @lexcorp.
+- **The typing indicator no longer logs a misleading `ERROR` when sending to a LID-migrated contact.** The best-effort "typing…" presence step is already caught and never affects the send, but a failed attempt (`No LID for user`) was logged at `ERROR`, which read as a fault even though nothing broke. It now logs at `WARN` and the typing target is resolved the same way as the send. (#582) Thanks @lexcorp.
+
## [0.7.19] - 2026-07-02
### Added
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index a8a23c633..4d05a367e 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1314,6 +1314,83 @@ describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lid
expect(getChatById).toHaveBeenCalledWith('159442138038327@lid');
expect(sendStateTyping).toHaveBeenCalled();
});
+
+ it('caches a resolved @lid so a later getNumberId failure still sends to the @lid, not @c.us (#580)', async () => {
+ // getNumberId is flaky: it resolves the first time, then throws `t: t` (a WhatsApp Web internal
+ // error). Without a cache the second send falls back to @c.us and 500s with `No LID for user`.
+ const getNumberId = jest
+ .fn()
+ .mockResolvedValueOnce({ _serialized: '159442138038327@lid' })
+ .mockRejectedValueOnce(new Error('t: t'));
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ const adapter = ready({ getNumberId, sendMessage });
+ await adapter.sendTextMessage('[email protected]', 'first');
+ await adapter.sendTextMessage('[email protected]', 'second');
+ // Second send reused the cached lid instead of re-querying the flaky resolver.
+ expect(getNumberId).toHaveBeenCalledTimes(1);
+ expect(sendMessage).toHaveBeenNthCalledWith(1, '159442138038327@lid', 'first');
+ expect(sendMessage).toHaveBeenNthCalledWith(2, '159442138038327@lid', 'second');
+ });
+
+ it('does not cache a non-resolution (getNumberId null) — keeps retrying for that contact', async () => {
+ const getNumberId = jest.fn().mockResolvedValue(null);
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ const adapter = ready({ getNumberId, sendMessage });
+ await adapter.sendTextMessage('[email protected]', 'a');
+ await adapter.sendTextMessage('[email protected]', 'b');
+ expect(getNumberId).toHaveBeenCalledTimes(2);
+ expect(sendMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'a');
+ expect(sendMessage).toHaveBeenNthCalledWith(2, '[email protected]', 'b');
+ });
+
+ it('caches a confirmed non-migrated @c.us so repeat sends do not re-probe getNumberId (#580 perf)', async () => {
+ // getNumberId confirms the contact is not migrated (echoes the @c.us). That is a stable fact,
+ // so it must be cached — otherwise every ordinary send re-runs the rate-limited existence probe.
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '[email protected]' });
+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);
+ const adapter = ready({ getNumberId, sendMessage });
+ await adapter.sendTextMessage('[email protected]', 'a');
+ await adapter.sendTextMessage('[email protected]', 'b');
+ expect(getNumberId).toHaveBeenCalledTimes(1);
+ expect(sendMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'a');
+ expect(sendMessage).toHaveBeenNthCalledWith(2, '[email protected]', 'b');
+ });
+
+ it('re-resolves and retries once when a send fails with "No LID for user" (contact migrated mid-session)', async () => {
+ // First resolution said non-migrated (@c.us) and was cached; the contact then migrated, so the
+ // send fails with `No LID for user`. The adapter evicts, re-resolves to the new @lid, and retries.
+ const getNumberId = jest
+ .fn()
+ .mockResolvedValueOnce({ _serialized: '[email protected]' })
+ .mockResolvedValueOnce({ _serialized: '999@lid' });
+ const sendMessage = jest
+ .fn()
+ .mockRejectedValueOnce(new Error('No LID for user'))
+ .mockResolvedValueOnce(sentMessage);
+ const adapter = ready({ getNumberId, sendMessage });
+ const res = await adapter.sendTextMessage('[email protected]', 'x');
+ expect(sendMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'x');
+ expect(sendMessage).toHaveBeenNthCalledWith(2, '999@lid', 'x');
+ expect(getNumberId).toHaveBeenCalledTimes(2);
+ expect(res.id).toBe('OUT1');
+ });
+
+ it('does not retry when re-resolution yields the same id (no pointless second send)', async () => {
+ const getNumberId = jest.fn().mockResolvedValue(null); // unresolvable → fallback stays @c.us
+ const sendMessage = jest.fn().mockRejectedValue(new Error('No LID for user'));
+ const adapter = ready({ getNumberId, sendMessage });
+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toThrow('No LID for user');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry on a non-LID send error', async () => {
+ const getNumberId = jest.fn().mockResolvedValue({ _serialized: '999@lid' });
+ const sendMessage = jest.fn().mockRejectedValue(new Error('rate limited'));
+ const adapter = ready({ getNumberId, sendMessage });
+ await expect(adapter.sendTextMessage('[email protected]', 'x')).rejects.toThrow('rate limited');
+ expect(sendMessage).toHaveBeenCalledTimes(1);
+ expect(getNumberId).toHaveBeenCalledTimes(1);
+ });
});
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 12a8b22de..8033cb3a1 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -186,6 +186,15 @@ export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): string
return candidate._serialized ?? null;
}
+/**
+ * True when a send error is whatsapp-web.js's "recipient needs a LID we don't have" failure, raised
+ * when sending to a `@c.us` for a contact WhatsApp has migrated to `@lid`.
+ * ponytail: matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.
+ */
+export function isNoLidForUserError(err: unknown): boolean {
+ return err instanceof Error && err.message.includes('No LID for user');
+}
+
export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngine {
private client: Client | null = null;
private status: EngineStatus = EngineStatus.DISCONNECTED;
@@ -803,32 +812,76 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.pushName;
}
+ // Cache of resolved individual recipients: `<phone>@c.us` -> the id `sendMessage` accepts (a
+ // `<lid>@lid` for a migrated contact, or the confirmed `@c.us` for a non-migrated one). `getNumberId`
+ // is a rate-limited WhatsApp Web existence probe that also throws intermittently, so caching every
+ // confirmed resolution keeps ordinary sends from re-probing on each message (#580). A `@lid` is
+ // stable; a stale entry (a contact that migrates mid-session) self-heals via the retry in
+ // `sendResolved`.
+ // ponytail: unbounded Map, bounded in practice by distinct recipients per session; add an LRU only
+ // if a session ever addresses a truly unbounded set of fresh numbers.
+ private readonly resolvedSendIds = new Map<string, string>();
+
/**
- * Resolve an individual (`@c.us`) recipient to its LID (`@lid`) when WhatsApp has migrated that
- * contact to privacy-id addressing. On a migrated chat whatsapp-web.js throws `No LID for user`
- * for the phone WID, but the id `getNumberId` returns (which may be a `@lid`) is accepted (#573).
- * Groups/channels and already-`@lid` targets are returned unchanged, and any resolution failure
- * falls back to the original id so a send is never blocked on it.
+ * Resolve an individual (`@c.us`) recipient to the id whatsapp-web.js will accept. WhatsApp has
+ * migrated some contacts to privacy-id addressing, for which `sendMessage` throws `No LID for user`
+ * on the phone WID but accepts the `@lid` that `getNumberId` returns (#573). Any server-confirmed
+ * resolution (a distinct `@lid` OR a confirmed non-migrated `@c.us`) is cached, since it is stable
+ * and re-probing costs a rate-limited round-trip (#580); a `null`/thrown lookup is NOT cached so an
+ * unregistered or transiently-flaky contact keeps being retried. Groups/channels and already-`@lid`
+ * targets are returned unchanged, and any resolution failure falls back to the original id so a send
+ * is never blocked on it.
*/
private async resolveSendId(chatId: string): Promise<string> {
if (!chatId.endsWith('@c.us')) {
return chatId;
}
+ const cached = this.resolvedSendIds.get(chatId);
+ if (cached) {
+ return cached;
+ }
try {
- return (await this.getNumberId(chatId)) ?? chatId;
+ const wid = await this.getNumberId(chatId);
+ if (wid) {
+ this.resolvedSendIds.set(chatId, wid);
+ return wid;
+ }
+ return chatId;
} catch {
return chatId;
}
}
+ /**
+ * Resolve `chatId` and run `send` against the resolved id. If the send fails with `No LID for user`
+ * — the signature of a contact whose cached/resolved id is stale (typically a `@c.us` for a contact
+ * that has since migrated to `@lid`) — drop the mapping, re-resolve once, and retry only if the
+ * fresh id differs, so a genuinely unreachable recipient surfaces its error instead of looping.
+ */
+ private async sendResolved<T>(chatId: string, send: (to: string) => Promise<T>): Promise<T> {
+ const to = await this.resolveSendId(chatId);
+ try {
+ return await send(to);
+ } catch (err) {
+ if (!chatId.endsWith('@c.us') || !isNoLidForUserError(err)) {
+ throw err;
+ }
+ this.resolvedSendIds.delete(chatId);
+ const fresh = await this.resolveSendId(chatId);
+ if (fresh === to) {
+ throw err;
+ }
+ return send(fresh);
+ }
+ }
+
async sendTextMessage(chatId: string, text: string, mentions?: string[]): Promise<MessageResult> {
this.ensureReady();
- const to = await this.resolveSendId(chatId);
// wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization
// is needed. Omit the options object entirely when none are given to keep today's send behavior.
- const msg = mentions?.length
- ? await this.client!.sendMessage(to, text, { mentions })
- : await this.client!.sendMessage(to, text);
+ const msg = await this.sendResolved(chatId, to =>
+ mentions?.length ? this.client!.sendMessage(to, text, { mentions }) : this.client!.sendMessage(to, text),
+ );
return {
id: msg.id._serialized,
timestamp: msg.timestamp,
@@ -857,7 +910,6 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
extraOptions?: { sendAudioAsVoice?: boolean },
): Promise<MessageResult> {
this.ensureReady();
- const to = await this.resolveSendId(chatId);
let messageMedia: MessageMedia;
@@ -874,12 +926,15 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
messageMedia = new MessageMedia(media.mimetype, media.data.toString('base64'), media.filename);
}
- const msg = await this.client!.sendMessage(to, messageMedia, {
- caption: media.caption,
- ...(media.mentions?.length ? { mentions: media.mentions } : {}),
- // sendAudioAsVoice only for audio; {...undefined} contributes no keys.
- ...extraOptions,
- });
+ // Build the media once (a remote URL is fetched here); sendResolved may retry the send itself.
+ const msg = await this.sendResolved(chatId, to =>
+ this.client!.sendMessage(to, messageMedia, {
+ caption: media.caption,
+ ...(media.mentions?.length ? { mentions: media.mentions } : {}),
+ // sendAudioAsVoice only for audio; {...undefined} contributes no keys.
+ ...extraOptions,
+ }),
+ );
return {
id: msg.id._serialized,
@@ -984,8 +1039,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
name: location.description || '',
address: location.address || '',
});
- const to = await this.resolveSendId(chatId);
- const msg = await this.client!.sendMessage(to, loc);
+ const msg = await this.sendResolved(chatId, to => this.client!.sendMessage(to, loc));
return {
id: msg.id._serialized,
timestamp: msg.timestamp,
@@ -998,10 +1052,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
// can't inject extra vCard fields — the previous inline build interpolated raw values.
const vcard = buildVCard(contact);
- const to = await this.resolveSendId(chatId);
- const msg = await this.client!.sendMessage(to, vcard, {
- parseVCards: true,
- });
+ const msg = await this.sendResolved(chatId, to =>
+ this.client!.sendMessage(to, vcard, {
+ parseVCards: true,
+ }),
+ );
return {
id: msg.id._serialized,
timestamp: msg.timestamp,
@@ -1022,10 +1077,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
messageMedia = new MessageMedia(media.mimetype, media.data.toString('base64'), media.filename);
}
- const to = await this.resolveSendId(chatId);
- const msg = await this.client!.sendMessage(to, messageMedia, {
- sendMediaAsSticker: true,
- });
+ const msg = await this.sendResolved(chatId, to =>
+ this.client!.sendMessage(to, messageMedia, {
+ sendMediaAsSticker: true,
+ }),
+ );
return {
id: msg.id._serialized,
timestamp: msg.timestamp,
@@ -1691,8 +1747,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
await chat.clearState();
}
} catch (error) {
- // Presence is best-effort — a failure here must never break the surrounding send.
- this.logger.error(`Error setting chat state '${state}' for ${chatId}`, String(error));
+ // Presence is best-effort and already swallowed here — it never breaks the surrounding send —
+ // so log at WARN, not ERROR: a migrated contact routinely yields `No LID for user` on the
+ // presence path and an ERROR line reads as a fault when nothing actually failed (#582).
+ this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, String(error));
}
}