Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(presence): restore own online preference after typing and sends
Gabriel Moraes2693492b68fe
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 1712ebe1c..adf21ff6c 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -193,6 +193,13 @@ export async function resolveMediaBuffer(}export class BaileysMessaging {+ /**+ * Last setOnlinePresence preference for this connection. Chat-scoped composing/recording+ * replaces the global available broadcast; after `paused` we re-assert this so a prior+ * `available: true` is not lost after typing or a simulated pre-send typing pause.+ */+ private desiredAvailable: boolean | undefined;+constructor(private readonly host: BaileysMessagingHost,private readonly queryBudgetMs: number = BAILEYS_QUERY_BUDGET_MS,@@ -305,6 +312,12 @@ export class BaileysMessaging {error: String(error),});}+ // composing/recording replace the global available broadcast; restore the caller's preference+ // once they clear the indicator. Do NOT restore after typing/recording themselves — that would+ // cancel the indicator the caller just asked for.+ if (state === 'paused') {+ await this.reannounceDesiredPresence();+ }}/**@@ -315,9 +328,26 @@ export class BaileysMessaging {*/async setOnlinePresence(available: boolean): Promise<void> {this.host.ensureReady();+ // Remember so chat-scoped composing/recording can be followed by a restore of this preference.+ this.desiredAvailable = available;await this.sock().sendPresenceUpdate(available ? 'available' : 'unavailable');}+ /**+ * Re-assert the last setOnlinePresence preference after a chat-scoped indicator. Best-effort:+ * a failure here must not surface on the typing endpoint.+ */+ private async reannounceDesiredPresence(): Promise<void> {+ if (this.desiredAvailable === undefined) return;+ try {+ await this.sock().sendPresenceUpdate(this.desiredAvailable ? 'available' : 'unavailable');+ } catch (error) {+ this.host.logger.warn('Could not reannounce own presence after chat state (best-effort)', {+ error: String(error),+ });+ }+ }+/*** Subscribe to a chat's presence. Unlike sendChatState this is NOT best-effort: the caller asked* for a subscription, and silently swallowing a failure would leave them waiting for updates thatdiff --git a/src/engine/adapters/own-presence.spec.ts b/src/engine/adapters/own-presence.spec.tsindex ffbf324f8..425f4c2e4 100644--- a/src/engine/adapters/own-presence.spec.ts+++ b/src/engine/adapters/own-presence.spec.ts@@ -49,6 +49,32 @@ describe('WwebjsChats.setOnlinePresence', () => {client.sendPresenceUnavailable.mockRejectedValue(new Error('page died'));await expect(chats.setOnlinePresence(false)).rejects.toThrow('page died');});++ it('reannounces a remembered available preference after paused', async () => {+ const clearState = jest.fn().mockResolvedValue(undefined);+ const client = {+ sendPresenceAvailable: jest.fn().mockResolvedValue(undefined),+ sendPresenceUnavailable: jest.fn().mockResolvedValue(undefined),+ getChatById: jest.fn().mockResolvedValue({ clearState }),+ };+ const messaging = {+ resolveSendId: jest.fn().mockResolvedValue('[email protected]'),+ } as unknown as WwebjsMessaging;+ const host = {+ ensureReady: jest.fn(),+ getClient: () => client as unknown as Client,+ logger,+ } as unknown as WwebjsEngineHost;+ const chats = new WwebjsChats(host, messaging);++ await chats.setOnlinePresence(true);+ client.sendPresenceAvailable.mockClear();++ await chats.sendChatState('[email protected]', 'paused');++ expect(clearState).toHaveBeenCalled();+ expect(client.sendPresenceAvailable).toHaveBeenCalledTimes(1);+ });});describe('BaileysMessaging.setOnlinePresence', () => {@@ -57,6 +83,8 @@ describe('BaileysMessaging.setOnlinePresence', () => {const host = {ensureReady: jest.fn(),getSocket: () => sock as unknown as WASocket,+ toEngineJid: (jid: string) => jid,+ recordLidMapping: jest.fn(),logger,} as unknown as BaileysMessagingHost;return { messaging: new BaileysMessaging(host), sock };@@ -79,4 +107,22 @@ describe('BaileysMessaging.setOnlinePresence', () => {sock.sendPresenceUpdate.mockRejectedValue(new Error('socket closed'));await expect(messaging.setOnlinePresence(true)).rejects.toThrow('socket closed');});++ it('reannounces a remembered available preference after paused', async () => {+ const { messaging, sock } = makeMessaging();+ await messaging.setOnlinePresence(true);+ sock.sendPresenceUpdate.mockClear();++ await messaging.sendChatState('[email protected]', 'paused');++ expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('paused', '[email protected]');+ expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('available');+ });++ it('does not reannounce after composing when no preference was set', async () => {+ const { messaging, sock } = makeMessaging();+ await messaging.sendChatState('[email protected]', 'typing');+ expect(sock.sendPresenceUpdate).toHaveBeenCalledTimes(1);+ expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('composing', '[email protected]');+ });});diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.tsindex ceadc4479..f89091a8c 100644--- a/src/engine/adapters/wwebjs-chats.ts+++ b/src/engine/adapters/wwebjs-chats.ts@@ -14,6 +14,12 @@ import { isProtocolTimeout } from './wwebjs-lifecycle';* the messaging delegate's send-id cache, exactly like a send.*/export class WwebjsChats {+ /**+ * Last setOnlinePresence preference for this connection. Typing/recording replace the global+ * available broadcast; after `paused` we re-assert this so a prior `available: true` survives.+ */+ private desiredAvailable: boolean | undefined;+constructor(private readonly host: WwebjsEngineHost,private readonly messaging: WwebjsMessaging,@@ -288,6 +294,7 @@ export class WwebjsChats {*/async setOnlinePresence(available: boolean): Promise<void> {this.host.ensureReady();+ this.desiredAvailable = available;if (available) {await this.client().sendPresenceAvailable();} else {@@ -320,5 +327,24 @@ export class WwebjsChats {error: String(error),});}+ // clearState ends the typing/recording indicator; put the remembered global preference back.+ if (state === 'paused') {+ await this.reannounceDesiredPresence();+ }+ }++ private async reannounceDesiredPresence(): Promise<void> {+ if (this.desiredAvailable === undefined) return;+ try {+ if (this.desiredAvailable) {+ await this.client().sendPresenceAvailable();+ } else {+ await this.client().sendPresenceUnavailable();+ }+ } catch (error) {+ this.host.logger.warn('Could not reannounce own presence after chat state (best-effort)', {+ error: String(error),+ });+ }}}diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex 9f132c439..45b8c6afa 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -76,6 +76,7 @@ describe('MessageSendService', () => {sessionService = {findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),+ reannounceOwnPresence: jest.fn().mockResolvedValue(undefined),};engines = new EngineRegistry();@@ -125,13 +126,17 @@ describe('MessageSendService', () => {await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'typing');+ expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'paused');expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');+ expect(sessionService.reannounceOwnPresence).toHaveBeenCalledWith('sess-1');});it('does not send typing presence when SIMULATE_TYPING=false', async () => {process.env.SIMULATE_TYPING = 'false';await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });expect(mockEngine.sendChatState).not.toHaveBeenCalled();+ // Preference is still reannounced after a successful send (covers media / typing-off paths).+ expect(sessionService.reannounceOwnPresence).toHaveBeenCalledWith('sess-1');});});diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 6afe93fe4..056066520 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -814,6 +814,10 @@ export class MessageSendService {});}}+ // Re-assert a prior PUT /presence preference after every successful send. Chat-scoped+ // indicators and some engine send paths replace the global available broadcast; without this,+ // `available: true` is lost after the first outbound message even when typing simulation is off.+ await this.sessionService.reannounceOwnPresence(message.sessionId);return { messageId: result.id, timestamp: result.timestamp };}@@ -831,6 +835,11 @@ export class MessageSendService {* `sendChatState`) and strictly best-effort — it never throws and never blocks the send if presence* fails or the engine has no presence concept. `SIMULATE_TYPING_MAX_MS` (default 5000) caps the pause.* Note: this covers single sends only; bulk sends use their own `delayBetweenMessages` throttle.+ *+ * Ends with `paused` so the typing indicator is cleared and the engine re-asserts any remembered+ * own-presence preference — otherwise composing replaces the global available broadcast and the+ * account looks offline after the first automated send. `persistSentState` also reannounces via+ * the session-level intent for sends that skip this pause.*/private async simulateTypingIfEnabled(engine: IWhatsAppEngine, chatId: string, text: string): Promise<void> {const { simulateTyping, simulateTypingMaxMs } = resolveFeatureFlags(this.configService);@@ -841,6 +850,7 @@ export class MessageSendService {const planned = Math.min(maxMs, 500 + text.length * 45);const jittered = Math.round(planned * (0.85 + Math.random() * 0.3)); // ±15% so it isn't metronomicawait new Promise(resolve => setTimeout(resolve, jittered));+ await engine.sendChatState(chatId, 'paused');} catch (error) {this.logger.warn(`simulateTyping skipped: ${error instanceof Error ? error.message : String(error)}`);}diff --git a/src/modules/session/presence-store.service.spec.ts b/src/modules/session/presence-store.service.spec.tsindex d7bc127f2..69c0d25ad 100644--- a/src/modules/session/presence-store.service.spec.ts+++ b/src/modules/session/presence-store.service.spec.ts@@ -133,7 +133,13 @@ describe('PresenceStore', () => {expect(store.get('s2', '[email protected]')).not.toBeNull();});- // After a clear the next report is news again — otherwise a restarted session would stay silent+ it('also drops the own-presence intent', () => {+ store.setOwnIntent('s1', true);+ store.clear('s1');+ expect(store.getOwnIntent('s1')).toBeUndefined();+ });++ // After a clear the next report is a change again — otherwise a restarted session would stay silent// until the contact happened to change state.it('makes the next report a change again', () => {store.record('s1', event());@@ -143,6 +149,23 @@ describe('PresenceStore', () => {});});+ describe('own presence intent', () => {+ it('remembers the last set preference', () => {+ expect(store.getOwnIntent('s1')).toBeUndefined();+ store.setOwnIntent('s1', true);+ expect(store.getOwnIntent('s1')).toBe(true);+ store.setOwnIntent('s1', false);+ expect(store.getOwnIntent('s1')).toBe(false);+ });++ it('keeps intents per session', () => {+ store.setOwnIntent('s1', true);+ store.setOwnIntent('s2', false);+ expect(store.getOwnIntent('s1')).toBe(true);+ expect(store.getOwnIntent('s2')).toBe(false);+ });+ });+// Presence is only reported for chats a caller explicitly subscribed, so the map is already// caller-bounded; the cap is there so a client that subscribes in a loop cannot grow it forever.it('evicts the least recently observed chat past the cap', () => {diff --git a/src/modules/session/presence-store.service.ts b/src/modules/session/presence-store.service.tsindex 4f9bd4e0f..b2724cc55 100644--- a/src/modules/session/presence-store.service.ts+++ b/src/modules/session/presence-store.service.ts@@ -29,6 +29,23 @@ const MAX_CHATS_PER_SESSION = 500;@Injectable()export class PresenceStore {private readonly bySession = new Map<string, Map<string, ChatPresence>>();+ /**+ * Last `PUT /presence` preference per session (`true` = stay online, `false` = stay offline).+ * Chat-scoped indicators (typing/recording) and some send paths replace the global available+ * broadcast; without remembering the caller's intent, that preference is lost after the first+ * message. Cleared with the rest of the session's presence on stop/replace.+ */+ private readonly ownIntent = new Map<string, boolean>();++ /** Remember the account's own global presence preference for this connection. */+ setOwnIntent(sessionId: string, available: boolean): void {+ this.ownIntent.set(sessionId, available);+ }++ /** The last setOwnIntent value, or undefined when the caller never set one. */+ getOwnIntent(sessionId: string): boolean | undefined {+ return this.ownIntent.get(sessionId);+ }/*** Record a report. Returns whether it CHANGED anything a consumer would care about — WhatsApp@@ -69,6 +86,7 @@ export class PresenceStore {/** Drop everything for a session — it stopped, was deleted, or its engine was replaced. */clear(sessionId: string): void {this.bySession.delete(sessionId);+ this.ownIntent.delete(sessionId);}}diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex cbc3f04b5..0835c91f8 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -603,7 +603,9 @@ export class SessionController {"offline suppresses the phone's own alerts — set `available: false` to hand them back.\n\n" +'The setting belongs to the connection: it does not survive a restart or reconnect and must ' +'be re-issued after `session.status` reports one (on Baileys the socket re-announces itself ' +- 'per its connect-time behaviour). Supported on both engines.',+ 'per its connect-time behaviour). While the connection is up, the preference is remembered and ' ++ 're-asserted after typing/recording indicators and outbound sends, so a prior `available: true` ' ++ 'is not lost when the account briefly shows as composing. Supported on both engines.',})@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({ status: 200, description: 'Presence published', type: SessionActionResponseDto })diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 5957311b3..f7f48d9f5 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -6751,6 +6751,34 @@ describe('SessionService', () => {expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'typing');});+ it('reannounces a remembered online preference after paused', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ await service.setOnlinePresence('sess-uuid-1', true);+ mockEngine.setOnlinePresence.mockClear();++ await service.sendChatState('sess-uuid-1', '[email protected]', 'paused');++ expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'paused');+ expect(mockEngine.setOnlinePresence).toHaveBeenCalledWith(true);+ });++ it('does not reannounce after typing when no preference was set', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ mockEngine.setOnlinePresence.mockClear();++ await service.sendChatState('sess-uuid-1', '[email protected]', 'typing');++ expect(mockEngine.setOnlinePresence).not.toHaveBeenCalled();+ });+it('should throw BadRequestException when session is not started', async () => {const session = createMockSession();(repository.findOne as jest.Mock).mockResolvedValue(session);@@ -6782,6 +6810,35 @@ describe('SessionService', () => {});});+ describe('reannounceOwnPresence', () => {+ it('re-publishes a remembered preference', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ await service.setOnlinePresence('sess-uuid-1', true);+ mockEngine.setOnlinePresence.mockClear();++ await service.reannounceOwnPresence('sess-uuid-1');++ expect(mockEngine.setOnlinePresence).toHaveBeenCalledWith(true);+ });++ it('is a no-op when the caller never set a preference', async () => {+ const session = createMockSession();+ (repository.findOne as jest.Mock).mockResolvedValue(session);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ await service.start('sess-uuid-1');+ mockEngine.setOnlinePresence.mockClear();++ await service.reannounceOwnPresence('sess-uuid-1');++ expect(mockEngine.setOnlinePresence).not.toHaveBeenCalled();+ });+ });+// ── onMessageRevoked (no localized string) ────────────────────────describe('onMessageRevoked callback', () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a0ac4d0cb..cce483490 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -771,14 +771,35 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat/*** Publish the account's own global presence (appear online/offline). Connection-scoped: the* setting resets on reconnect, so callers re-issue it after `session.status` reports one.+ * The preference is remembered for the life of the connection so chat-scoped indicators+ * (typing/recording) and outbound sends can re-assert it instead of leaving the account+ * looking offline after the first message.*/async setOnlinePresence(id: string, available: boolean): Promise<void> {await this.findOne(id);const engine = this.requireEngine(id);-+ this.presence.setOwnIntent(id, available);return engine.setOnlinePresence(available);}+ /**+ * Re-publish a prior setOnlinePresence preference. Best-effort no-op when the caller never set+ * one, the engine is gone, or the publish fails — presence must not break a surrounding send.+ */+ async reannounceOwnPresence(id: string): Promise<void> {+ const desired = this.presence.getOwnIntent(id);+ if (desired === undefined) return;+ const engine = this.engines.get(id);+ if (!engine) return;+ try {+ await engine.setOnlinePresence(desired);+ } catch (error) {+ this.logger.warn(`Could not reannounce own presence for session ${id} (best-effort)`, {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+/*** The last presence WhatsApp reported for a chat, or null when none has been — either because the* chat was never subscribed, or because nothing has changed since the subscription was made.@@ -864,6 +885,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst engine = this.requireEngine(id);await engine.sendChatState(chatId, state);+ // Typing/recording replace the global available broadcast; once the caller clears the+ // indicator, put the remembered own-presence preference back.+ if (state === 'paused') {+ await this.reannounceOwnPresence(id);+ }}/**