Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(presence): re-apply own presence once when the connection opens

Gabriel Moraes8b4ee033a251
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index eab0d88db..8acdabc43 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -888,9 +888,16 @@ from the phone while a linked device announces itself online, so a headless bot
offline suppresses the phone's own alerts — `available: false` hands them back. Supported on both
engines.
-The setting belongs to the connection: it does not survive a restart or reconnect and must be
-re-issued after `session.status` reports one. Not best-effort — a failure surfaces instead of
-leaving the account silently online.
+A successful call is remembered for the life of the running engine and re-applied once each time
+that connection opens, including a Baileys transient reconnect. Baileys broadcasts `available` on
+connect (`markOnlineOnConnect`), which would otherwise replace a previous `available: false`. The
+preference is dropped when the engine is replaced (stop, or a restart that builds a new engine) and
+must be re-issued after that. Typing, recording, and outbound sends do not change global presence.
+
+Not best-effort — a failure surfaces instead of leaving the account silently online. On Baileys a
+`409` is also returned when the account push name has not synced yet: `sendPresenceUpdate` returns
+without sending until `creds.me.name` is set, and the endpoint refuses that case instead of
+reporting success.
**Auth:** API key (OPERATOR) · **Scope:** session-scoped
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 6f3feddcd..03dbd5082 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -216,8 +216,10 @@ curl "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence/123456789
#### PUT /api/sessions/:sessionId/presence
-Set the account's OWN global presence — appear online or offline (OPERATOR, both engines). The
-setting does not survive a restart or reconnect; re-issue it after `session.status` reports one.
+Set the account's OWN global presence — appear online or offline (OPERATOR, both engines). A
+successful call is re-applied once each time that engine's connection opens, including a Baileys
+transient reconnect, and dropped when the engine is replaced. On Baileys a `409` means the push
+name has not synced yet and nothing was sent.
```bash
curl -X PUT "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/presence" \
diff --git a/openapi.json b/openapi.json
index 0dfd36c53..66331656b 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1218,7 +1218,7 @@
},
"/api/sessions/{sessionId}/presence": {
"put": {
- "description": "Publishes whether this account appears online. WhatsApp routes notifications away from the phone while a linked device announces itself online, so a headless bot that never goes offline suppresses the phone's own alerts — set `available: false` to hand them back.\n\nThe 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). 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.",
+ "description": "Publishes whether this account appears online. WhatsApp routes notifications away from the phone while a linked device announces itself online, so a headless bot that never goes offline suppresses the phone's own alerts — set `available: false` to hand them back.\n\nA successful call is remembered for the life of the running engine and re-applied once each time that connection opens, including a Baileys transient reconnect: the socket broadcasts `available` on connect (`markOnlineOnConnect`), which would otherwise wipe `available: false`. The preference is dropped when the engine is replaced (stop, or a restart that builds a new engine) and must be re-issued after that. Typing, recording, and outbound sends do not publish global presence.\n\nOn Baileys the call fails with 409 when the account push name has not synced yet — the library would otherwise accept the request and send nothing. Supported on both engines.",
"operationId": "SessionController_setOnlinePresence",
"parameters": [
{
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index adf21ff6c..515c85499 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -27,6 +27,7 @@ import { buildVCard } from './vcard';
import { resolveBaileysButtonClick, setBaileysText } from './baileys-message-mapper';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
import { BadRequestException, InternalServerErrorException } from '@nestjs/common';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import { MessageNotFoundError } from '../../common/errors/message-not-found.error';
import { type createLogger } from '../../common/services/logger.service';
@@ -193,13 +194,6 @@ 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,
@@ -312,40 +306,26 @@ 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();
- }
}
/**
* Publish the account's own GLOBAL presence — the no-jid form of sendPresenceUpdate, which
- * addresses the whole account rather than a chat. Not best-effort, unlike sendChatState: the
- * caller asked for a specific visibility, so a failure surfaces instead of leaving the account
- * silently online (#871). Resets on reconnect per the socket's markOnlineOnConnect option.
+ * addresses the whole account rather than a chat (`<presence>`, not a per-chat `<chatstate>`).
+ * Not best-effort, unlike sendChatState: the caller asked for a specific visibility, so a
+ * failure surfaces instead of leaving the account silently online (#871).
+ *
+ * Baileys resolves this call without sending anything when `creds.me.name` is unset (it logs
+ * "no name present, ignoring presence update request" and returns). `sock.user` is that cred.
+ * Refusing here keeps PUT /presence from reporting success for an update that never left.
*/
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),
- });
+ if (!this.sock().user?.name) {
+ throw new EngineNotReadyError(
+ 'The account push name is not available yet, so this presence update would be ignored. Retry once the session has synced its profile name.',
+ );
}
+ await this.sock().sendPresenceUpdate(available ? 'available' : 'unavailable');
}
/**
diff --git a/src/engine/adapters/own-presence.spec.ts b/src/engine/adapters/own-presence.spec.ts
index 425f4c2e4..a54c0f623 100644
--- a/src/engine/adapters/own-presence.spec.ts
+++ b/src/engine/adapters/own-presence.spec.ts
@@ -1,3 +1,4 @@
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { WwebjsChats } from './wwebjs-chats';
import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';
import { createLogger } from '../../common/services/logger.service';
@@ -11,7 +12,7 @@ import type { WASocket } from '@whiskeysockets/baileys';
* typing/recording indicator (sendChatState), this is NOT best-effort: the caller explicitly asked
* to appear offline — a bot that silently stays visible online causes exactly the missed-phone-
* notification problem the feature exists to solve (#871) — so a failure surfaces instead of being
- * swallowed. The setting belongs to the connection and resets on reconnect.
+ * swallowed. Chat state is a separate wire operation and does not republish this.
*/
const logger = createLogger('own-presence.spec');
@@ -50,7 +51,7 @@ describe('WwebjsChats.setOnlinePresence', () => {
await expect(chats.setOnlinePresence(false)).rejects.toThrow('page died');
});
- it('reannounces a remembered available preference after paused', async () => {
+ it('clears a chat indicator without publishing global presence', async () => {
const clearState = jest.fn().mockResolvedValue(undefined);
const client = {
sendPresenceAvailable: jest.fn().mockResolvedValue(undefined),
@@ -67,19 +68,23 @@ describe('WwebjsChats.setOnlinePresence', () => {
} 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);
+ expect(client.sendPresenceAvailable).not.toHaveBeenCalled();
});
});
describe('BaileysMessaging.setOnlinePresence', () => {
- function makeMessaging(): { messaging: BaileysMessaging; sock: { sendPresenceUpdate: jest.Mock } } {
- const sock = { sendPresenceUpdate: jest.fn().mockResolvedValue(undefined) };
+ function makeMessaging(name: string | null = 'Me'): {
+ messaging: BaileysMessaging;
+ sock: { sendPresenceUpdate: jest.Mock; user?: { name?: string } };
+ } {
+ const sock = {
+ sendPresenceUpdate: jest.fn().mockResolvedValue(undefined),
+ // null means creds.me itself is missing; '' is the empty name Baileys also ignores.
+ ...(name === null ? {} : { user: { name } }),
+ };
const host = {
ensureReady: jest.fn(),
getSocket: () => sock as unknown as WASocket,
@@ -108,18 +113,19 @@ describe('BaileysMessaging.setOnlinePresence', () => {
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');
+ it('refuses when the push name is not set — Baileys would resolve without sending', async () => {
+ const { messaging, sock } = makeMessaging(null);
+ await expect(messaging.setOnlinePresence(true)).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(sock.sendPresenceUpdate).not.toHaveBeenCalled();
+ });
- expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('paused', '[email protected]');
- expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('available');
+ it('refuses an empty push name the same way Baileys treats a missing one', async () => {
+ const { messaging, sock } = makeMessaging('');
+ await expect(messaging.setOnlinePresence(false)).rejects.toBeInstanceOf(EngineNotReadyError);
+ expect(sock.sendPresenceUpdate).not.toHaveBeenCalled();
});
- it('does not reannounce after composing when no preference was set', async () => {
+ it('sends composing as a per-chat update and nothing global', async () => {
const { messaging, sock } = makeMessaging();
await messaging.sendChatState('[email protected]', 'typing');
expect(sock.sendPresenceUpdate).toHaveBeenCalledTimes(1);
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index f89091a8c..ceadc4479 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -14,12 +14,6 @@ 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,
@@ -294,7 +288,6 @@ export class WwebjsChats {
*/
async setOnlinePresence(available: boolean): Promise<void> {
this.host.ensureReady();
- this.desiredAvailable = available;
if (available) {
await this.client().sendPresenceAvailable();
} else {
@@ -327,24 +320,5 @@ 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/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index 7f58ba22b..1873dffa0 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -392,7 +392,7 @@ export const CURATED_CAPABILITY_EXCEPTIONS: Record<string, MethodCapability> = {
wwjs: { status: 'supported' },
baileys: { status: 'supported' },
evidence:
- "wwjs Client.sendPresenceAvailable()/sendPresenceUnavailable() (index.d.ts:230/233); baileys sendPresenceUpdate('available'|'unavailable') with no jid — the global whole-account form (Socket/chats.d.ts:38). Connection-scoped on both: resets on reconnect (Baileys re-announces per markOnlineOnConnect)",
+ "wwjs Client.sendPresenceAvailable()/sendPresenceUnavailable() (index.d.ts:230/233); baileys sendPresenceUpdate('available'|'unavailable') with no jid — the global <presence> form, distinct from per-chat <chatstate> (Socket/chats.js). Baileys returns without sending when creds.me.name is unset; the adapter surfaces that as EngineNotReadyError. A successful call is remembered on the engine and re-applied once on each connection open, because markOnlineOnConnect re-broadcasts available",
},
setProfileName: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 798dea23c..883dd9214 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1492,9 +1492,16 @@ export interface PresenceCapability {
* A linked device that announces itself online routes notifications away from the phone, so a
* headless bot that never goes offline suppresses the phone's own alerts — which is why this is
* NOT best-effort, unlike sendChatState: the caller asked for a specific visibility, and a
- * swallowed failure would leave the account silently online. The setting belongs to the
- * connection and resets on reconnect (Baileys re-announces per its `markOnlineOnConnect`
- * socket option), so callers re-issue it after a reconnect.
+ * swallowed failure would leave the account silently online. Chat-state updates are a separate
+ * wire operation (`<chatstate>` / `sendStateTyping`) and do not publish this.
+ *
+ * The call itself is one-shot. The gateway remembers a successful one for the life of the running
+ * engine and re-applies it once each time that connection opens: Baileys broadcasts `available`
+ * on connect (`markOnlineOnConnect`), which would otherwise wipe `available: false` on a
+ * transient reconnect. Replacing the engine drops the preference.
+ *
+ * On Baileys this throws when the account push name is not set yet. `sendPresenceUpdate`
+ * resolves without sending in that case (`no name present, ignoring presence update request`).
*/
setOnlinePresence(available: boolean): Promise<void>;
diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.ts
index 45b8c6afa..2c29d448f 100644
--- a/src/modules/message/message-send.service.spec.ts
+++ b/src/modules/message/message-send.service.spec.ts
@@ -76,7 +76,6 @@ describe('MessageSendService', () => {
sessionService = {
findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),
- reannounceOwnPresence: jest.fn().mockResolvedValue(undefined),
};
engines = new EngineRegistry();
@@ -125,18 +124,15 @@ describe('MessageSendService', () => {
await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });
+ expect(mockEngine.sendChatState).toHaveBeenCalledTimes(1);
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.ts
index 056066520..6afe93fe4 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -814,10 +814,6 @@ 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 };
}
@@ -835,11 +831,6 @@ 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);
@@ -850,7 +841,6 @@ 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 metronomic
await 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.ts b/src/modules/session/presence-store.service.ts
index b2724cc55..d6c4dbdcd 100644
--- a/src/modules/session/presence-store.service.ts
+++ b/src/modules/session/presence-store.service.ts
@@ -30,10 +30,11 @@ const MAX_CHATS_PER_SESSION = 500;
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.
+ * Last successful `PUT /presence` preference per session (`true` = stay online, `false` = stay
+ * offline). Re-applied once each time that engine's connection opens — Baileys broadcasts
+ * `available` on connect, which would otherwise wipe it. Cleared with the rest of the session's
+ * presence when the engine is replaced or the session is deleted. Not written when the publish
+ * itself failed.
*/
private readonly ownIntent = new Map<string, boolean>();
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index e7feafd5a..961894696 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -850,6 +850,13 @@ export class SessionEngineLifecycle {
}),
);
+ // Re-apply a prior PUT /presence once per open. Baileys' markOnlineOnConnect has already
+ // broadcast `available` during this handshake; without this, an `available: false` the caller
+ // published would not survive a transient reconnect inside the same engine. A replaced engine
+ // cleared the preference in initializeEngine, so this is a no-op there. Not awaited — on
+ // whatsapp-web.js the call is a page evaluate, and READY must not wait on it.
+ this.reapplyOwnPresence(id);
+
// Best-effort snapshot of the account's own contacts' currently-active statuses. Live status
// posts arrive through onMessage below; this just backfills what was already up before we
// connected. Not awaited — onReady must not block on it.
@@ -863,6 +870,25 @@ export class SessionEngineLifecycle {
}
}
+ /**
+ * Re-publish the last successful PUT /presence for this engine. No-op when the caller never set
+ * one, or the engine is already gone. A failure is logged and swallowed: presence must not turn
+ * a successful connect into an error, and the stored preference stays for the next open.
+ */
+ private reapplyOwnPresence(id: string): void {
+ const desired = this.presence.getOwnIntent(id);
+ if (desired === undefined) return;
+ const engine = this.engines.get(id);
+ if (!engine) return;
+ void engine.setOnlinePresence(desired).catch(error => {
+ this.logger.warn(`Could not re-apply own presence for session ${id} (best-effort)`, {
+ sessionId: id,
+ error: error instanceof Error ? error.message : String(error),
+ action: 'own_presence_reapply_failed',
+ });
+ });
+ }
+
/**
* Announce that a restriction has ended. Shared by the two paths that can end one — the engine
* reporting it lifted, and a session reaching READY despite a connection-level block — so the two
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 0835c91f8..d79d2b272 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -601,11 +601,14 @@ export class SessionController {
'Publishes whether this account appears online. WhatsApp routes notifications away from the ' +
'phone while a linked device announces itself online, so a headless bot that never goes ' +
"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). 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.',
+ 'A successful call is remembered for the life of the running engine and re-applied once each ' +
+ 'time that connection opens, including a Baileys transient reconnect: the socket broadcasts ' +
+ '`available` on connect (`markOnlineOnConnect`), which would otherwise wipe `available: false`. ' +
+ 'The preference is dropped when the engine is replaced (stop, or a restart that builds a new ' +
+ 'engine) and must be re-issued after that. Typing, recording, and outbound sends do not ' +
+ 'publish global presence.\n\n' +
+ 'On Baileys the call fails with 409 when the account push name has not synced yet — the ' +
+ 'library would otherwise accept the request and send nothing. 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.ts
index f7f48d9f5..f3db4877d 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -5661,6 +5661,28 @@ describe('SessionService', () => {
expect(auth[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', phone: '628123', pushName: 'Alice' });
});
+ it('re-applies a successful own-presence preference once when the connection opens', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ await service.setOnlinePresence('sess-uuid-1', false);
+ mockEngine.setOnlinePresence.mockClear();
+
+ callbacks.onReady!('628123', 'Alice');
+ await flush();
+
+ expect(mockEngine.setOnlinePresence).toHaveBeenCalledTimes(1);
+ expect(mockEngine.setOnlinePresence).toHaveBeenCalledWith(false);
+ });
+
+ it('does not publish own presence on ready when the caller never set one', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ mockEngine.setOnlinePresence.mockClear();
+
+ callbacks.onReady!('628123', 'Alice');
+ await flush();
+
+ expect(mockEngine.setOnlinePresence).not.toHaveBeenCalled();
+ });
+
it('does not fetch status history on ready by default', async () => {
const callbacks = await startAndCaptureCallbacks();
@@ -6751,7 +6773,7 @@ describe('SessionService', () => {
expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'typing');
});
- it('reannounces a remembered online preference after paused', async () => {
+ it('does not publish global presence when a chat indicator is cleared', async () => {
const session = createMockSession();
(repository.findOne as jest.Mock).mockResolvedValue(session);
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
@@ -6763,19 +6785,6 @@ describe('SessionService', () => {
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();
});
@@ -6808,32 +6817,21 @@ describe('SessionService', () => {
await expect(service.setOnlinePresence('sess-uuid-1', true)).rejects.toThrow(BadRequestException);
});
- });
- describe('reannounceOwnPresence', () => {
- it('re-publishes a remembered preference', async () => {
+ it('does not remember a preference the engine refused to publish', 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();
+ mockEngine.setOnlinePresence.mockRejectedValueOnce(new Error('no name'));
- await service.reannounceOwnPresence('sess-uuid-1');
+ await expect(service.setOnlinePresence('sess-uuid-1', true)).rejects.toThrow('no name');
- 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');
+ const callbacks = (mockEngine.initialize.mock.calls as [EngineEventCallbacks][])[0][0];
+ callbacks.onReady!('628123', 'Alice');
+ await new Promise(resolve => setImmediate(resolve));
expect(mockEngine.setOnlinePresence).not.toHaveBeenCalled();
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index cce483490..0bc192c12 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -769,35 +769,16 @@ 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.
+ * Publish the account's own global presence (appear online/offline). A successful call is
+ * remembered for the life of this engine and re-applied once each time the connection opens.
+ * The intent is stored only after the publish succeeds, so a refusal (Baileys has no push name
+ * yet) does not get replayed as if the caller had been told it applied.
*/
async setOnlinePresence(id: string, available: boolean): Promise<void> {
await this.findOne(id);
const engine = this.requireEngine(id);
+ await engine.setOnlinePresence(available);
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),
- });
- }
}
/**
@@ -884,12 +865,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.findOne(id); // Verify session exists
const 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);
- }
+ return engine.sendChatState(chatId, state);
}
/**