Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(presence): set the account's own global presence (appear online/offline)

Yudhi Armyndharis016b67cabf27
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b629aad69..f47ff9eb5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Group membership requests: list, approve, reject, and a `group.join_request` event** — the join-approval queue wwebjs/Baileys both expose is now surfaced: `GET/POST .../groups/:groupId/membership-requests[/approve|/reject]` on both engines, plus a webhook/socket event when someone asks to join an administered group. Refs #1164 (discussion).
+- **Own global presence: `PUT /sessions/:id/presence`** — appear online or offline on both engines; an always-online headless bot suppresses the phone's own notifications, and `available: false` hands them back. Connection-scoped (re-issue after a reconnect). Refs #871.
+
- **The media download route now serves media sent by the account** — `GET /messages/:chatId/:messageId/media` falls back to the inline copy stored on the message row when no archived file exists, which covers outbound messages (never archived) and inbound messages whose archived file retention has purged.
### Changed
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d7cf62e6c..43cfd7e74 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -729,6 +729,37 @@ restart would be worse than answering nothing.
**Errors:** `401` · `403` · `404` session not found
+#### PUT /api/sessions/:id/presence
+
+Set the account's OWN global presence: appear online or offline. 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 — `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.
+
+**Auth:** API key (OPERATOR) · **Scope:** session-scoped
+
+**Request body** — `SetOwnPresenceDto`
+
+| Field | Type | Required | Description |
+| --------- | ------- | -------- | ------------------------------------------------ |
+| available | boolean | Yes | `true` = appear online, `false` = appear offline |
+
+```json
+{ "available": false }
+```
+
+**Response** `200`
+
+```json
+{ "success": true }
+```
+
+**Errors:** `400` session not started / validation · `401` · `403` key lacks OPERATOR role · `404` session not found · `409` engine not ready
+
#### POST /api/sessions/:id/chats/read
Mark a chat as read/seen.
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 9633452b0..d4cfe1e1e 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -22,7 +22,7 @@ The `rootCause`/`evidence` fields are hand-curated from source traces of the ins
## Unwired-capability inventory
-21 of the 103 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.
+21 of the 104 interface methods are `not-available` on at least one adapter (22 not-available adapter-cells total). Grouped by cluster below. Each entry shows: status today → rootCause → evidence → wiring note.
### Channels / Newsletter
@@ -174,8 +174,8 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **103** interface methods, **206** adapter-cells (103 × 2 engines).
-- **184** supported cells; **22** not-available cells across **21** methods.
+- **104** interface methods, **208** adapter-cells (104 × 2 engines).
+- **186** supported cells; **22** not-available cells across **21** methods.
- Of the 22 not-available cells: **2 adapter-gaps** (fixable) + **20 library-limitations** + **0 uncertain**.
- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
diff --git a/openapi.json b/openapi.json
index 1b38c90b3..46d0ec9c9 100644
--- a/openapi.json
+++ b/openapi.json
@@ -1032,6 +1032,51 @@
]
}
},
+ "/api/sessions/{id}/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). Supported on both engines.",
+ "operationId": "SessionController_setOnlinePresence",
+ "parameters": [
+ {
+ "name": "id",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SetOwnPresenceDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Presence published"
+ },
+ "400": {
+ "description": "Session not started, or validation failed"
+ },
+ "404": {
+ "description": "Session not found"
+ },
+ "409": {
+ "description": "The session is not connected — an engine exists for it but is not `ready`: disconnected, reconnecting, or still initializing, so the request never reached WhatsApp. Wait for `ready` and retry. A session that was never started answers `400` instead, and the session lifecycle routes answer `409` for a conflicting state rather than this."
+ }
+ },
+ "summary": "Set the account's own global presence (appear online or offline)",
+ "tags": [
+ "sessions"
+ ]
+ }
+ },
"/api/sessions/{id}/presence/{chatId}": {
"get": {
"description": "Serves the most recent report received since the chat was subscribed. Returns `null` when nothing has been reported — either the chat was never subscribed, or nothing has changed since. That is a normal state, not a missing resource, so it is `200` with a null body rather than a `404`.\n\nHeld in memory and never persisted: presence is short-lived, and answering \"typing\" from before a restart would be worse than answering nothing.",
@@ -9612,6 +9657,19 @@
"chatId"
]
},
+ "SetOwnPresenceDto": {
+ "type": "object",
+ "properties": {
+ "available": {
+ "type": "boolean",
+ "description": "true = appear online; false = appear offline (hands notifications back to the phone — an always-online linked device suppresses the phone's own alerts)",
+ "example": false
+ }
+ },
+ "required": [
+ "available"
+ ]
+ },
"ParticipantPresenceDto": {
"type": "object",
"properties": {
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index 6d3072397..40a8f63f2 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -186,6 +186,17 @@ export class BaileysMessaging {
}
}
+ /**
+ * 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.
+ */
+ async setOnlinePresence(available: boolean): Promise<void> {
+ this.host.ensureReady();
+ await this.sock().sendPresenceUpdate(available ? 'available' : 'unavailable');
+ }
+
/**
* 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 that
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index dc072c427..ce873555a 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -311,6 +311,10 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.messaging.sendChatState(chatId, state);
}
+ async setOnlinePresence(available: boolean): Promise<void> {
+ return this.messaging.setOnlinePresence(available);
+ }
+
async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {
return this.messaging.sendImageMessage(chatId, media);
}
diff --git a/src/engine/adapters/own-presence.spec.ts b/src/engine/adapters/own-presence.spec.ts
new file mode 100644
index 000000000..ffbf324f8
--- /dev/null
+++ b/src/engine/adapters/own-presence.spec.ts
@@ -0,0 +1,82 @@
+import { WwebjsChats } from './wwebjs-chats';
+import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+import { type WwebjsMessaging } from './wwebjs-messaging';
+import type { Client } from 'whatsapp-web.js';
+import type { WASocket } from '@whiskeysockets/baileys';
+
+/**
+ * Own GLOBAL presence (appear online/offline) across both engines. Unlike the per-chat
+ * 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.
+ */
+
+const logger = createLogger('own-presence.spec');
+
+describe('WwebjsChats.setOnlinePresence', () => {
+ function makeChats(): { chats: WwebjsChats; client: { [k: string]: jest.Mock } } {
+ const client = {
+ sendPresenceAvailable: jest.fn().mockResolvedValue(undefined),
+ sendPresenceUnavailable: jest.fn().mockResolvedValue(undefined),
+ };
+ const host = {
+ ensureReady: jest.fn(),
+ getClient: () => client as unknown as Client,
+ logger,
+ } as unknown as WwebjsEngineHost;
+ return { chats: new WwebjsChats(host, {} as unknown as WwebjsMessaging), client };
+ }
+
+ it('true publishes available', async () => {
+ const { chats, client } = makeChats();
+ await chats.setOnlinePresence(true);
+ expect(client.sendPresenceAvailable).toHaveBeenCalledTimes(1);
+ expect(client.sendPresenceUnavailable).not.toHaveBeenCalled();
+ });
+
+ it('false publishes unavailable', async () => {
+ const { chats, client } = makeChats();
+ await chats.setOnlinePresence(false);
+ expect(client.sendPresenceUnavailable).toHaveBeenCalledTimes(1);
+ expect(client.sendPresenceAvailable).not.toHaveBeenCalled();
+ });
+
+ it('propagates a failure — the caller asked for this state, so a swallow would lie', async () => {
+ const { chats, client } = makeChats();
+ client.sendPresenceUnavailable.mockRejectedValue(new Error('page died'));
+ await expect(chats.setOnlinePresence(false)).rejects.toThrow('page died');
+ });
+});
+
+describe('BaileysMessaging.setOnlinePresence', () => {
+ function makeMessaging(): { messaging: BaileysMessaging; sock: { sendPresenceUpdate: jest.Mock } } {
+ const sock = { sendPresenceUpdate: jest.fn().mockResolvedValue(undefined) };
+ const host = {
+ ensureReady: jest.fn(),
+ getSocket: () => sock as unknown as WASocket,
+ logger,
+ } as unknown as BaileysMessagingHost;
+ return { messaging: new BaileysMessaging(host), sock };
+ }
+
+ it('true publishes a GLOBAL available update (no chat jid)', async () => {
+ const { messaging, sock } = makeMessaging();
+ await messaging.setOnlinePresence(true);
+ expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('available');
+ });
+
+ it('false publishes a GLOBAL unavailable update', async () => {
+ const { messaging, sock } = makeMessaging();
+ await messaging.setOnlinePresence(false);
+ expect(sock.sendPresenceUpdate).toHaveBeenCalledWith('unavailable');
+ });
+
+ it('propagates a failure rather than swallowing it', async () => {
+ const { messaging, sock } = makeMessaging();
+ sock.sendPresenceUpdate.mockRejectedValue(new Error('socket closed'));
+ await expect(messaging.setOnlinePresence(true)).rejects.toThrow('socket closed');
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 8a677b357..63c7af69a 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1849,6 +1849,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.chats.sendChatState(chatId, state);
}
+ setOnlinePresence(available: boolean): Promise<void> {
+ return this.chats.setOnlinePresence(available);
+ }
+
private ensureReady(): void {
if (this.status !== EngineStatus.READY || !this.client) {
// Typed so the global filter returns 409 Conflict ("session not connected")
diff --git a/src/engine/adapters/wwebjs-chats.ts b/src/engine/adapters/wwebjs-chats.ts
index 031aa2a08..85caba066 100644
--- a/src/engine/adapters/wwebjs-chats.ts
+++ b/src/engine/adapters/wwebjs-chats.ts
@@ -141,6 +141,21 @@ export class WwebjsChats {
}
}
+ /**
+ * Publish the account's own GLOBAL presence. Not best-effort, unlike sendChatState: the caller
+ * asked for a specific visibility, and swallowing a failure would leave the account silently
+ * online after the API reported otherwise (#871 — an always-online bot suppresses the phone's
+ * own notifications).
+ */
+ async setOnlinePresence(available: boolean): Promise<void> {
+ this.host.ensureReady();
+ if (available) {
+ await this.client().sendPresenceAvailable();
+ } else {
+ await this.client().sendPresenceUnavailable();
+ }
+ }
+
async sendChatState(chatId: string, state: ChatState): Promise<void> {
this.host.ensureReady();
if (isChannelJid(chatId)) {
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index dc2c2d7c7..fdd3347ef 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -353,6 +353,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
evidence:
'wwjs GroupChat.setSubject(newSubject) → boolean (index.d.ts:1982; false → adapter throws EngineRefusedError); baileys groupUpdateSubject(jid, subject) (Socket/groups.d.ts:20)',
},
+ setOnlinePresence: {
+ 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)",
+ },
setProfileName: {
wwjs: { status: 'supported' },
baileys: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 9acc56aa5..1233a651b 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -1086,6 +1086,16 @@ export interface IWhatsAppEngine {
* Engine-agnostic and best-effort: engines without a presence concept should no-op.
*/
sendChatState(chatId: string, state: ChatState): Promise<void>;
+ /**
+ * Publish the ACCOUNT's own global presence: `true` = appear online, `false` = appear offline.
+ * 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.
+ */
+ setOnlinePresence(available: boolean): Promise<void>;
/**
* Ask WhatsApp to start reporting a chat's presence, delivered through `onPresenceUpdate`.
*
diff --git a/src/modules/session/dto/presence.dto.ts b/src/modules/session/dto/presence.dto.ts
index 087cc9057..300cbfd13 100644
--- a/src/modules/session/dto/presence.dto.ts
+++ b/src/modules/session/dto/presence.dto.ts
@@ -1,5 +1,17 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
-import { IsNotEmpty, IsString, Matches } from 'class-validator';
+import { IsBoolean, IsNotEmpty, IsString, Matches } from 'class-validator';
+import { ToStrictBoolean } from '../../../common/utils/strict-boolean';
+
+export class SetOwnPresenceDto {
+ @ApiProperty({
+ description:
+ "true = appear online; false = appear offline (hands notifications back to the phone — an always-online linked device suppresses the phone's own alerts)",
+ example: false,
+ })
+ @ToStrictBoolean()
+ @IsBoolean()
+ available!: boolean;
+}
export class SubscribePresenceDto {
@ApiProperty({
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 4fc8193d5..21da5af8a 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -3,6 +3,7 @@ import {
Get,
Post,
Patch,
+ Put,
Delete,
Param,
Query,
@@ -21,6 +22,7 @@ import {
QRCodeResponseDto,
MarkChatReadDto,
SubscribePresenceDto,
+ SetOwnPresenceDto,
ChatPresenceResponseDto,
ArchiveChatDto,
DeleteChatDto,
@@ -469,6 +471,31 @@ export class SessionController {
return { success: true };
}
+ @Put(':id/presence')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({
+ summary: "Set the account's own global presence (appear online or offline)",
+ 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\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.',
+ })
+ @ApiParam({ name: 'id', description: 'Session ID' })
+ @ApiResponse({ status: 200, description: 'Presence published' })
+ @ApiResponse({ status: 400, description: 'Session not started, or validation failed' })
+ @ApiResponse({ status: 404, description: 'Session not found' })
+ @ApiResponse({ status: 409, description: ENGINE_NOT_READY_409 })
+ async setOnlinePresence(
+ @Param('id', ParseUUIDPipe) id: string,
+ @Body() dto: SetOwnPresenceDto,
+ ): Promise<{ success: boolean }> {
+ await this.sessionService.setOnlinePresence(id, dto.available);
+ return { success: true };
+ }
+
@Get(':id/presence/:chatId')
@RequireRole(ApiKeyRole.VIEWER)
@ApiOperation({
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 43d800269..14a3cfc62 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -151,6 +151,7 @@ describe('SessionService', () => {
markUnread: jest.fn().mockResolvedValue(true),
deleteChat: jest.fn().mockResolvedValue(true),
sendChatState: jest.fn().mockResolvedValue(undefined),
+ setOnlinePresence: jest.fn().mockResolvedValue(undefined),
resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),
rejectCall: jest.fn().mockResolvedValue(undefined),
getContactStatuses: jest.fn().mockResolvedValue([]),
@@ -5096,6 +5097,29 @@ describe('SessionService', () => {
});
});
+ // ── setOnlinePresence (own global presence) ───────────────────────
+
+ describe('setOnlinePresence', () => {
+ it('delegates the availability flag to the engine', 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', false);
+
+ expect(mockEngine.setOnlinePresence).toHaveBeenCalledWith(false);
+ });
+
+ it('throws BadRequestException when the session is not started', async () => {
+ const session = createMockSession();
+ (repository.findOne as jest.Mock).mockResolvedValue(session);
+
+ await expect(service.setOnlinePresence('sess-uuid-1', true)).rejects.toThrow(BadRequestException);
+ });
+ });
+
// ── onMessageRevoked (no localized string) ────────────────────────
describe('onMessageRevoked callback', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 8174ca7e3..afe4b0e00 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -517,6 +517,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return engine.subscribeToPresence(chatId);
}
+ /**
+ * 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.
+ */
+ async setOnlinePresence(id: string, available: boolean): Promise<void> {
+ await this.findOne(id);
+ const engine = this.engines.get(id);
+
+ if (!engine) {
+ throw new BadRequestException('Session is not started');
+ }
+
+ return engine.setOnlinePresence(available);
+ }
+
/**
* 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.