Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sessions): observe chat presence — who is online and who is typing
Yudhi Armyndharisc616bf2a6b5a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b38eafc6c..b4b65bb5d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Presence: see who is online or typing.** `POST /api/sessions/:id/presence/subscribe` starts+ WhatsApp reporting a chat's presence; `GET /api/sessions/:id/presence/:chatId` serves the latest+ report; changes arrive as the new `presence.update` webhook **and** socket event. Exposed in all+ five SDKs and as two MCP tools.++ Baileys only. whatsapp-web.js exposes `sendPresenceAvailable`/`sendPresenceUnavailable`, which+ publish the account's *own* presence, and emits no presence event at all — so it answers `501`+ rather than pretending. That refusal is declared inline on the adapter so the engine parity gate+ can actually verify it, unlike the delegated refusals it cannot see.++ Two properties are documented rather than papered over. The subscription belongs to the+ **connection**: it does not survive a restart or an automatic reconnect and must be re-issued,+ because silently replaying subscriptions would report presence the account never asked for. And+ presence is **push-only** — it cannot be queried from either library — which is why `GET` serves a+ remembered report and answers `null`, not `404`, when nothing has been reported yet.++ Only genuine state *changes* are dispatched. WhatsApp repeats itself freely, and one watched chat+ with an active typist would otherwise bury every other event a consumer subscribes to; `lastSeen`+ and the group online count drifting on their own do not count as changes. The last report is held+ in memory and cleared when the session restarts, since presence from before a restart is worse than+ no answer at all.+- **Group participant adds are paced too.** `POST .../groups/:groupId/participants` and`POST .../groups` reached WhatsApp with no gate of any kind — no moderation hook, no pacing, nopersisted record — while being the most ban-associated action the product performs: they put thediff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex 17b6dd598..a94c5af72 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -103,6 +103,7 @@ const availableEventNames = ['session.disconnected','session.reconnect_loop','session.restriction',+ 'presence.update','group.join','group.leave','group.update',diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex b6163b912..6f913edd4 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -57,6 +57,24 @@ export interface Session {restriction?: AccountRestriction | null;}+/** One participant's presence within a chat. */+export interface ParticipantPresence {+ id: string;+ /** `composing`/`recording` mean actively typing or recording; `paused` means they stopped. */+ state: 'available' | 'unavailable' | 'composing' | 'recording' | 'paused';+ /** Unix SECONDS. Absent whenever the contact's privacy settings hide last-seen. */+ lastSeen?: number;+}++/** The last presence reported for a chat since it was subscribed. */+export interface ChatPresence {+ chatId: string;+ participants: ParticipantPresence[];+ groupOnlineCount?: number;+ /** When the gateway received the report — NOT a WhatsApp timestamp. */+ observedAt: string;+}+/*** A restriction WhatsApp has in force on a session's account.*diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 4e3e7542d..970286cb9 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -396,6 +396,7 @@ CREATE TABLE webhooks ("session.disconnected","session.reconnect_loop","session.restriction",+ "presence.update","group.join","group.leave","group.update",diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 065c0d2cb..fdca85212 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -659,6 +659,77 @@ Request an 8-char pairing code to link via phone number (alternative to QR).**Errors:** `400` validation, or session not started, or already authenticated · `401` · `403` · `404` not found+#### POST /api/sessions/:id/presence/subscribe++Ask WhatsApp to start reporting who is online or typing in a chat.++**Auth:** API key (OPERATOR) · **Scope:** session-scoped · **Engines:** Baileys only++There is no synchronous answer: presence cannot be *fetched* from either engine, only received.+Updates arrive as the `presence.update` webhook and socket event; the latest is readable at+`GET /api/sessions/:id/presence/:chatId`.++Two properties to design around:++- **The subscription belongs to the connection.** It does not survive a restart or an automatic+ reconnect, and must be re-issued. The gateway does not silently replay subscriptions, because a+ replay would report a presence the account never actually asked for.+- **Subscribe per chat, not to everything.** WhatsApp emits an update on every transition — each time+ someone starts and stops typing — so a broad subscription is a firehose. Only genuine state+ *changes* are dispatched onward, which bounds the event volume but not the socket traffic.++**Path parameters**++| Name | Type | Description |+| --- | --- | --- |+| `id` | string | Session UUID |++**Request body** — `SubscribePresenceDto`++| Field | Type | Required | Constraints | Description |+| --- | --- | --- | --- | --- |+| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) |++**Response** `200`++```json+{ "success": true }+```++**Errors:** `400` validation, or session not started · `401` · `403` · `404` session not found · `501` the active engine cannot observe presence (whatsapp-web.js exposes only `sendPresenceAvailable`/`sendPresenceUnavailable`, which publish the account's *own* presence, and emits no presence event)++#### GET /api/sessions/:id/presence/:chatId++The last presence reported for a chat.++**Auth:** API key (VIEWER) · **Scope:** session-scoped++**Response** `200`++```json+{+ "chatId": "[email protected]",+ "participants": [{ "id": "[email protected]", "state": "composing", "lastSeen": 1786000000 }],+ "observedAt": "2026-08-03T12:00:00.000Z"+}+```++`state` is one of `available` / `unavailable` / `composing` / `recording` / `paused` — the middle two+mean actively typing or recording *in this chat*, `paused` means they stopped without sending.+`lastSeen` is epoch **seconds** and is absent whenever the contact's privacy settings hide last-seen,+which is the default for most accounts and is not an error. `groupOnlineCount` appears for groups+when WhatsApp reports it. A 1:1 chat still returns a `participants` array, holding the one contact.++`observedAt` is when **this gateway** received the report, not a WhatsApp timestamp. Presence is+short-lived, so an old `observedAt` means the state is stale rather than steady.++The body is `null` when nothing has been reported — the chat was never subscribed, or nothing has+changed since. That is a normal state rather than a missing resource, so it is `200` with a null+body, not a `404`. Presence is held in memory and never persisted: answering "typing" from before a+restart would be worse than answering nothing.++**Errors:** `401` · `403` · `404` session not found+#### POST /api/sessions/:id/chats/readMark a chat as read/seen.@@ -3556,7 +3627,7 @@ Webhooks are configured per session and managed under `/api/sessions/:sessionId/Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.-The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by the engines.+The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `presence.update`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by the engines.#### GET /api/sessions/:sessionId/webhooks@@ -5501,6 +5572,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` || `session.disconnected` | The session disconnects on the engine or WhatsApp side (drop, conflict, or a phone-initiated unlink). Not fired for API-initiated stop/logout/delete — those are acknowledged by the API response and the `session.status` transition | `{ sessionId, reason }` || `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |+| `presence.update` | A subscribed chat's presence changed — someone came online, started typing, or stopped. Only actual CHANGES are dispatched: WhatsApp repeats itself freely, and every repeat would otherwise be a delivery | `{ sessionId, chatId, participants: [{ id, state, lastSeen? }], groupOnlineCount? }` — `state` is `available`/`unavailable`/`composing`/`recording`/`paused`; `lastSeen` is epoch **seconds** and absent when the contact hides it. Requires `POST .../presence/subscribe` first, and Baileys — whatsapp-web.js cannot observe presence || `session.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values || `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` || `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }` — `actorId` is the admin/inviter when known |diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 3bf1f464e..7f0261e80 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1101,6 +1101,7 @@ available_events:- session.disconnected # Session disconnected- session.reconnect_loop # Every 5th consecutive reconnect attempt (payload: sessionId, attempts, nextDelayMs)- session.restriction # WhatsApp restricted the account, or lifted it (payload: sessionId, active, kind, code, expiresAt)+ - presence.update # A subscribed chat's presence changed (payload: sessionId, chatId, participants, groupOnlineCount)# Groups- group.join # Participant(s) added/joineddiff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.mdindex f5958a258..f06c67e13 100644--- a/docs/22-n8n-integration.md+++ b/docs/22-n8n-integration.md@@ -89,6 +89,7 @@ Start workflows when WhatsApp events occur.| `session.disconnected` | Session lost connection | Alert monitoring || `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting || `session.restriction` | WhatsApp restricted the account, or lifted it | Pausing outreach while an account is limited |+| `presence.update` | A watched chat's online/typing state changed | Live agent hand-off, presence-aware routing || `group.join` | Participant(s) joined a group | Welcome messages || `group.leave` | Participant(s) left a group | Churn tracking || `group.update` | Group subject/description/settings changed | Group administration |diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex e7b75732f..69b262045 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -154,8 +154,9 @@ These are honestly out of reach of a clean adapter wiring because the installed- `sendCatalog` — no catalog-share message type in `AnyMessageContent` (only single `{product}`).- `votePoll` — no vote-SEND helper at all; the library only decrypts INCOMING votes (`decryptPollVote`). Sending one means hand-building a `proto.Message.PollUpdateMessage` with HMAC-SHA256 vote encryption keyed by the poll creation's `messageSecret`. Supported on whatsapp-web.js.-**wwjs (6 cells):**+**wwjs (7 cells):**+- `subscribeToPresence` — no way to observe another party's presence. `WAWebPresenceChatAction` offers only `sendPresenceAvailable` / `sendPresenceUnavailable` (`index.d.ts:230,233`), which publish the ACCOUNT's own presence, and the library emits no presence event at all. Baileys: `presenceSubscribe` + the `presence.update` event. Reaching it would mean injecting page-level subscriptions against undocumented WA Web modules.- `getCatalog` / `getProducts` / `getProduct` — no catalog API at all (`index.d.ts` 0 hits; `Product` is inbound-only).- `sendProduct` — no outbound product content type.- `sendCatalog` — no outbound catalog content type.@@ -169,14 +170,19 @@ These are hand-maintained and had drifted from the source before this pass; theyfrom `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way whenadding a method, instead of incrementing the previous figure.-- **91** interface methods, **182** adapter-cells (91 × 2 engines).-- **164** supported cells; **18** not-available cells across **17** methods.-- Of the 18 not-available cells: **2 adapter-gaps** (fixable) + **16 library-limitations** + **0 uncertain**.+- **92** interface methods, **184** adapter-cells (92 × 2 engines).+- **165** supported cells; **19** not-available cells across **18** methods.+- Of the 19 not-available cells: **2 adapter-gaps** (fixable) + **17 library-limitations** + **0 uncertain**.- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.Note that the drift gate does **not** verify that for whatsapp-web.js. `engine-parity.spec.ts`detects a throw with `Class.prototype.method.toString()`, and the wwjs adapter's methods are thinforwarders whose throws live in delegate modules (`wwebjs-catalog.ts` and friends), so the scansees no throwing method on that adapter at all — its `supported ⇒ does not throw` invariant is- vacuously true. Baileys is unaffected: its unavailable methods call `this.unsupported(...)` inline- on the adapter. Until that is addressed, the wwjs column is guarded by review, not by the gate.+ vacuously true for those. Baileys is unaffected: its unavailable methods call `this.unsupported(...)`+ inline on the adapter. Until the delegated ones are addressed, most of the wwjs column is guarded by+ review rather than by the gate.++ New wwjs `not-available` methods should therefore throw **inline on the adapter class**, the way+ `subscribeToPresence` does, so the scan can see them — a delegate keeps the code tidy at the cost of+ the only automated check this column has.diff --git a/openapi.json b/openapi.jsonindex d00068631..2327233c4 100644--- a/openapi.json+++ b/openapi.json@@ -868,6 +868,96 @@]}},+ "/api/sessions/{id}/presence/subscribe": {+ "post": {+ "description": "Asks WhatsApp to start reporting who is online or typing in this chat. Updates arrive as the `presence.update` webhook and socket event — there is no synchronous answer, because presence cannot be queried from either engine, only received.\n\nThe subscription belongs to the connection: it does **not** survive a restart or an automatic reconnect, and must be re-issued. Subscribe per chat rather than to everything — WhatsApp emits an update on every transition, so a broad subscription is a firehose.\n\nwhatsapp-web.js cannot do this at all (it exposes no presence subscribe and emits no presence event) and answers `501`.",+ "operationId": "SessionController_subscribeToPresence",+ "parameters": [+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SubscribePresenceDto"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Subscribed; updates now arrive as presence.update events"+ },+ "400": {+ "description": "Session not started"+ },+ "404": {+ "description": "Session not found"+ },+ "501": {+ "description": "The active engine cannot observe presence (whatsapp-web.js)"+ }+ },+ "summary": "Subscribe to a chat's presence",+ "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.",+ "operationId": "SessionController_getPresence",+ "parameters": [+ {+ "name": "id",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "chatId",+ "required": true,+ "in": "path",+ "description": "Chat ID as subscribed",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Last reported presence, or null",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChatPresenceResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "Session not found"+ }+ },+ "summary": "Read a chat's last reported presence",+ "tags": [+ "sessions"+ ]+ }+ },"/api/sessions/{id}/chats/unread": {"post": {"operationId": "SessionController_markChatUnread",@@ -7003,6 +7093,81 @@"chatId"]},+ "SubscribePresenceDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string",+ "description": "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",+ "example": "[email protected]"+ }+ },+ "required": [+ "chatId"+ ]+ },+ "ParticipantPresenceDto": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": "Participant id. In a 1:1 chat this is the chat itself.",+ "example": "[email protected]"+ },+ "state": {+ "type": "string",+ "enum": [+ "available",+ "unavailable",+ "composing",+ "recording",+ "paused"+ ],+ "description": "`composing` and `recording` mean actively typing or recording in this chat; `paused` means they stopped without sending. `available`/`unavailable` describe reachability.",+ "example": "composing"+ },+ "lastSeen": {+ "type": "number",+ "description": "Unix SECONDS the contact was last seen. Absent whenever the contact's privacy settings hide last-seen — the common case, and not an error.",+ "example": 1786000000+ }+ },+ "required": [+ "id",+ "state"+ ]+ },+ "ChatPresenceResponseDto": {+ "type": "object",+ "properties": {+ "chatId": {+ "type": "string",+ "example": "[email protected]"+ },+ "participants": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ParticipantPresenceDto"+ }+ },+ "groupOnlineCount": {+ "type": "number",+ "description": "Online member count, groups only.",+ "example": 3+ },+ "observedAt": {+ "type": "string",+ "format": "date-time",+ "description": "When this gateway received the report — NOT a WhatsApp timestamp. Presence is short-lived, so an old `observedAt` means the state is stale rather than steady.",+ "example": "2026-08-03T12:00:00Z"+ }+ },+ "required": [+ "chatId",+ "participants",+ "observedAt"+ ]+ },"ArchiveChatDto": {"type": "object","properties": {@@ -7091,6 +7256,7 @@"session.disconnected","session.reconnect_loop","session.restriction",+ "presence.update","group.join","group.leave","group.update",@@ -7238,6 +7404,7 @@"session.disconnected","session.reconnect_loop","session.restriction",+ "presence.update","group.join","group.leave","group.update",diff --git a/sdk/go/chats.go b/sdk/go/chats.goindex dbaec170b..15681fd7f 100644--- a/sdk/go/chats.go+++ b/sdk/go/chats.go@@ -17,6 +17,29 @@ func (s *ChatsService) List(ctx context.Context, sessionID string, query *ListChreturn out, err}+// SubscribePresence asks WhatsApp to start reporting a chat's presence; updates then arrive as+// presence.update webhook/socket events. Presence cannot be fetched from either engine, only+// received.+//+// The subscription belongs to the connection and does NOT survive a restart or an automatic+// reconnect, so re-issue it when the session comes back. Subscribe per chat: WhatsApp emits an+// update on every transition, so a broad subscription is a firehose. whatsapp-web.js answers 501.+func (s *ChatsService) SubscribePresence(ctx context.Context, sessionID string, body MarkChatRequest) (*SuccessResult, error) {+ var out SuccessResult+ err := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/presence/subscribe", nil, body, &out)+ return &out, err+}++// GetPresence returns the last presence reported for a chat, or nil when none has been — the chat+// was never subscribed, or nothing has changed since. Held in memory, so a restart clears it.+func (s *ChatsService) GetPresence(ctx context.Context, sessionID, chatID string) (*ChatPresence, error) {+ var out *ChatPresence+ err := s.client.do(+ ctx, "GET", "/api/sessions/"+pathEscape(sessionID)+"/presence/"+pathEscape(chatID), nil, nil, &out,+ )+ return out, err+}+// MarkRead marks a chat as read.func (s *ChatsService) MarkRead(ctx context.Context, sessionID string, body MarkChatRequest) (*SuccessResult, error) {return s.post(ctx, sessionID, "/read", body)diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 6af0a5f8c..1e82efaeb 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -990,6 +990,7 @@ func TestWebhookEventWireValues(t *testing.T) {EventSessionDisconnected: "session.disconnected",EventSessionReconnectLoop: "session.reconnect_loop",EventSessionRestriction: "session.restriction",+ EventPresenceUpdate: "presence.update",EventGroupJoin: "group.join",EventGroupLeave: "group.leave",EventGroupUpdate: "group.update",diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.goindex f801efada..23e57ef1d 100644--- a/sdk/go/routing_test.go+++ b/sdk/go/routing_test.go@@ -90,6 +90,8 @@ func TestRouting(t *testing.T) {{"Chats.List", func(c *Client) { c.Chats.List(ctx, "s1", nil) }, "GET", "/api/sessions/s1/chats"},{"Chats.MarkRead", func(c *Client) { c.Chats.MarkRead(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/read"},+ {"Chats.SubscribePresence", func(c *Client) { c.Chats.SubscribePresence(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/presence/subscribe"},+ {"Chats.GetPresence", func(c *Client) { c.Chats.GetPresence(ctx, "s1", "[email protected]") }, "GET", "/api/sessions/s1/presence/[email protected]"},{"Chats.MarkUnread", func(c *Client) { c.Chats.MarkUnread(ctx, "s1", MarkChatRequest{}) }, "POST", "/api/sessions/s1/chats/unread"},{"Chats.ClearMessages", func(c *Client) { c.Chats.ClearMessages(ctx, "s1", "c1") }, "DELETE", "/api/sessions/s1/chats/c1/messages"},{"Chats.Archive", func(c *Client) { c.Chats.Archive(ctx, "s1", ArchiveChatRequest{}) }, "POST", "/api/sessions/s1/chats/archive"},diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goindex bf8de07bc..5c8a75550 100644--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -15,6 +15,27 @@ func (q *ListSessionsQuery) values() url.Values {return v}+// ParticipantPresence is one participant's presence within a chat.+type ParticipantPresence struct {+ ID string `json:"id"`+ // State is one of: available, unavailable, composing, recording, paused. "composing" and+ // "recording" mean actively typing or recording; "paused" means they stopped.+ State string `json:"state"`+ // LastSeen is Unix SECONDS. Nil whenever the contact's privacy settings hide last-seen — the+ // common case, not an error.+ LastSeen *int64 `json:"lastSeen,omitempty"`+}++// ChatPresence is the last presence reported for a chat since it was subscribed.+type ChatPresence struct {+ ChatID string `json:"chatId"`+ Participants []ParticipantPresence `json:"participants"`+ // GroupOnlineCount is the online member count, groups only.+ GroupOnlineCount *int `json:"groupOnlineCount,omitempty"`+ // ObservedAt is when the gateway received the report — NOT a WhatsApp timestamp.+ ObservedAt string `json:"observedAt"`+}+// AccountRestriction is a restriction WhatsApp has in force on a session's account.//// "reachout_timelock" leaves the session connected and existing chats working -- only starting newdiff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.goindex 7b7eda96b..e8c670e10 100644--- a/sdk/go/types_webhook.go+++ b/sdk/go/types_webhook.go@@ -22,6 +22,7 @@ const (EventSessionDisconnected WebhookEvent = "session.disconnected"EventSessionReconnectLoop WebhookEvent = "session.reconnect_loop"EventSessionRestriction WebhookEvent = "session.restriction"+ EventPresenceUpdate WebhookEvent = "presence.update"EventGroupJoin WebhookEvent = "group.join"EventGroupLeave WebhookEvent = "group.leave"EventGroupUpdate WebhookEvent = "group.update"diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatPresence.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatPresence.javanew file mode 100644index 000000000..d4a0ccd0c--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ChatPresence.java@@ -0,0 +1,12 @@+package com.rmyndharis.openwa.model;++import java.util.List;++/**+ * The last presence reported for a chat since it was subscribed.+ *+ * @param groupOnlineCount online member count, groups only+ * @param observedAt when the gateway received the report — NOT a WhatsApp timestamp+ */+public record ChatPresence(+ String chatId, List<ParticipantPresence> participants, Integer groupOnlineCount, String observedAt) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.javanew file mode 100644index 000000000..7ebee6a98--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ParticipantPresence.java@@ -0,0 +1,12 @@+package com.rmyndharis.openwa.model;++/**+ * One participant's presence within a chat.+ *+ * @param id participant id; in a 1:1 chat this is the chat itself+ * @param state one of {@code available}, {@code unavailable}, {@code composing}, {@code recording},+ * {@code paused} — the middle two mean actively typing or recording, {@code paused} means they stopped+ * @param lastSeen Unix SECONDS; {@code null} whenever the contact's privacy settings hide last-seen,+ * which is the common case and not an error+ */+public record ParticipantPresence(String id, String state, Long lastSeen) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.javaindex d9a876122..ef3024cfd 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java@@ -34,6 +34,8 @@ public enum WebhookEvent {SESSION_RECONNECT_LOOP,@SerializedName("session.restriction")SESSION_RESTRICTION,+ @SerializedName("presence.update")+ PRESENCE_UPDATE,@SerializedName("group.join")GROUP_JOIN,@SerializedName("group.leave")diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.javaindex df435f8a9..285ba75ad 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java@@ -5,6 +5,7 @@ import static com.rmyndharis.openwa.http.Http.encodeSegment;import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.model.ArchiveChatRequest;+import com.rmyndharis.openwa.model.ChatPresence;import com.rmyndharis.openwa.model.ChatSummary;import com.rmyndharis.openwa.model.DeleteChatRequest;import com.rmyndharis.openwa.model.ListChatsQuery;@@ -38,6 +39,36 @@ public final class ChatsResource {HttpMethod.GET, "/api/sessions/" + encodeSegment(sessionId) + "/chats", query, null, ChatSummary.class);}+ /**+ * Subscribe to a chat's presence; updates then arrive as {@code presence.update} events. Presence+ * cannot be fetched from either engine, only received.+ *+ * <p>The subscription belongs to the connection and does NOT survive a restart or an automatic+ * reconnect, so re-issue it when the session comes back. Subscribe per chat: WhatsApp emits an+ * update on every transition. whatsapp-web.js answers {@code 501}.+ */+ public SuccessResult subscribePresence(String sessionId, MarkChatRequest body) {+ return client.request(+ HttpMethod.POST,+ "/api/sessions/" + encodeSegment(sessionId) + "/presence/subscribe",+ null,+ body,+ SuccessResult.class);+ }++ /**+ * The last presence reported for a chat, or {@code null} when none has been — the chat was never+ * subscribed, or nothing has changed since. Held in memory, so a restart clears it.+ */+ public ChatPresence getPresence(String sessionId, String chatId) {+ return client.request(+ HttpMethod.GET,+ "/api/sessions/" + encodeSegment(sessionId) + "/presence/" + encodeSegment(chatId),+ null,+ null,+ ChatPresence.class);+ }+/** Mark a chat as read/seen. */public SuccessResult markRead(String sessionId, MarkChatRequest body) {return client.request(diff --git a/sdk/javascript/src/resources/chats.ts b/sdk/javascript/src/resources/chats.tsindex fbd49f0a3..256e49ccd 100644--- a/sdk/javascript/src/resources/chats.ts+++ b/sdk/javascript/src/resources/chats.ts@@ -15,6 +15,7 @@ import type {ChatSummary,DeleteChatRequest,MarkChatRequest,+ ChatPresence,SendChatStateRequest,SuccessResult,} from '../types.js';@@ -36,6 +37,33 @@ export class ChatsResource {});}+ /**+ * Subscribe to a chat's presence. Updates then arrive as `presence.update` webhook/socket events —+ * presence cannot be fetched from either engine, only received.+ *+ * The subscription belongs to the connection and does NOT survive a restart or an automatic+ * reconnect, so re-issue it when the session comes back. Subscribe per chat: WhatsApp emits an+ * update on every transition, so a broad subscription is a firehose. whatsapp-web.js answers 501.+ */+ subscribePresence(sessionId: string, body: MarkChatRequest): Promise<SuccessResult> {+ return this.client.request<SuccessResult>({+ method: 'POST',+ path: `/api/sessions/${encodeSegment(sessionId)}/presence/subscribe`,+ body,+ });+ }++ /**+ * The last presence reported for a chat, or `null` when none has been — the chat was never+ * subscribed, or nothing has changed since. Held in memory, so a restart clears it.+ */+ getPresence(sessionId: string, chatId: string): Promise<ChatPresence | null> {+ return this.client.request<ChatPresence | null>({+ method: 'GET',+ path: `/api/sessions/${encodeSegment(sessionId)}/presence/${encodeSegment(chatId)}`,+ });+ }+/** Mark a chat as read/seen. */markRead(sessionId: string, body: MarkChatRequest): Promise<SuccessResult> {return this.client.request<SuccessResult>({diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 68491a4f4..52d801e75 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -80,6 +80,25 @@ export interface AccountRestriction {expiresAt?: string | null;}+/** One participant's presence within a chat. */+export interface ParticipantPresence {+ id: string;+ /** `composing`/`recording` mean actively typing or recording; `paused` means they stopped. */+ state: 'available' | 'unavailable' | 'composing' | 'recording' | 'paused';+ /** Unix SECONDS. Absent whenever the contact's privacy settings hide last-seen — the common case. */+ lastSeen?: number;+}++/** The last presence reported for a chat since it was subscribed. */+export interface ChatPresence {+ chatId: string;+ participants: ParticipantPresence[];+ /** Online member count, groups only. */+ groupOnlineCount?: number;+ /** When the gateway received the report — NOT a WhatsApp timestamp. */+ observedAt: string;+}+export interface CreateSessionRequest {/** Alphanumeric + hyphens, 3–50 chars. */name: string;@@ -604,6 +623,7 @@ export type WebhookEvent =| 'session.disconnected'| 'session.reconnect_loop'| 'session.restriction'+ | 'presence.update'| 'group.join'| 'group.leave'| 'group.update'diff --git a/sdk/php/src/Resources/ChatsResource.php b/sdk/php/src/Resources/ChatsResource.phpindex cc6250716..08d70c48c 100644--- a/sdk/php/src/Resources/ChatsResource.php+++ b/sdk/php/src/Resources/ChatsResource.php@@ -30,6 +30,31 @@ class ChatsResourcereturn $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/chats", $query) ?? [];}+ /**+ * Subscribe to a chat's presence; updates then arrive as `presence.update` events. Presence+ * cannot be fetched from either engine, only received. The subscription belongs to the+ * connection and does NOT survive a restart or an automatic reconnect, so re-issue it when the+ * session comes back. whatsapp-web.js answers 501.+ *+ * @param array<string,mixed> $body+ * @return array<string,mixed>+ */+ public function subscribePresence(string $sessionId, array $body): array+ {+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/presence/subscribe", [], $body);+ }++ /**+ * The last presence reported for a chat, or null when none has been — the chat was never+ * subscribed, or nothing has changed since. Held in memory, so a restart clears it.+ *+ * @return array<string,mixed>|null+ */+ public function getPresence(string $sessionId, string $chatId): ?array+ {+ return $this->http->request('GET', "/api/sessions/{$this->http->encodeSegment($sessionId)}/presence/{$this->http->encodeSegment($chatId)}");+ }+/*** @param array<string,mixed> $body* @return array<string,mixed>diff --git a/sdk/python/openwa/resources/chats.py b/sdk/python/openwa/resources/chats.pyindex ecf0733b9..7fcc05b28 100644--- a/sdk/python/openwa/resources/chats.py+++ b/sdk/python/openwa/resources/chats.py@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, TypedDictfrom .._http import quote_segmentfrom ..types import (+ ChatPresence,ArchiveChatRequest,ChatSummary,DeleteChatRequest,@@ -34,6 +35,28 @@ class ChatsResource:def list(self, session_id: str, query: ListChatsQuery | None = None) -> list[ChatSummary]:return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/chats", query=query)+ def subscribe_presence(self, session_id: str, body: MarkChatRequest) -> SuccessResult:+ """Subscribe to a chat's presence; updates arrive as presence.update events.++ Presence cannot be fetched from either engine, only received. The subscription belongs to+ the connection and does NOT survive a restart or an automatic reconnect, so re-issue it when+ the session comes back. Subscribe per chat: WhatsApp emits an update on every transition.+ whatsapp-web.js answers 501.+ """+ return self._http.request(+ "POST", f"/api/sessions/{quote_segment(session_id)}/presence/subscribe", body=body+ )++ def get_presence(self, session_id: str, chat_id: str) -> ChatPresence | None:+ """The last presence reported for a chat, or None when none has been.++ None means the chat was never subscribed, or nothing has changed since. Held in memory, so a+ restart clears it.+ """+ return self._http.request(+ "GET", f"/api/sessions/{quote_segment(session_id)}/presence/{quote_segment(chat_id)}"+ )+def mark_read(self, session_id: str, body: MarkChatRequest) -> SuccessResult:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/chats/read", body=body)diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex f5c29928b..5f0036248 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -30,7 +30,7 @@ BulkMessageType = Literal["text", "image", "video", "audio", "document"]WebhookEvent = Literal["message.received", "message.sent", "message.ack", "message.failed", "message.revoked","message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",- "session.disconnected", "session.reconnect_loop", "session.restriction",+ "session.disconnected", "session.reconnect_loop", "session.restriction", "presence.update","group.join", "group.leave", "group.update", "call.received", "status.received","*",]@@ -41,6 +41,27 @@ class SuccessResult(TypedDict, total=False):message: str+class ParticipantPresence(TypedDict, total=False):+ """One participant's presence within a chat."""++ id: str+ # 'composing'/'recording' mean actively typing or recording; 'paused' means they stopped.+ state: Literal["available", "unavailable", "composing", "recording", "paused"]+ # Unix SECONDS. Absent whenever the contact's privacy settings hide last-seen -- the common case.+ lastSeen: int+++class ChatPresence(TypedDict, total=False):+ """The last presence reported for a chat since it was subscribed."""++ chatId: str+ participants: list[ParticipantPresence]+ # Online member count, groups only.+ groupOnlineCount: int+ # When the gateway received the report -- NOT a WhatsApp timestamp.+ observedAt: str++# ── Session ───────────────────────────────────────────────────────diff --git a/src/core/agent-tools/tool-registry.spec.ts b/src/core/agent-tools/tool-registry.spec.tsindex 26ece2671..e20ae95a8 100644--- a/src/core/agent-tools/tool-registry.spec.ts+++ b/src/core/agent-tools/tool-registry.spec.ts@@ -53,6 +53,8 @@ describe('v1 tool surface snapshot', () => {'SessionFindOne','SessionGetChats','SessionGetStats',+ 'SessionSubscribePresence',+ 'SessionGetPresence','SessionMarkChatRead','SessionMarkChatUnread','SessionSendChatState',@@ -101,6 +103,6 @@ describe('v1 tool surface snapshot', () => {.sort();expect(actualNames).toEqual(expected);- expect(expected).toHaveLength(39);+ expect(expected).toHaveLength(41);});});diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex 14e23b906..9c57747bb 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -52,6 +52,37 @@ export function sessionTools(session: SessionService): ToolDescriptor[] {inputSchema: z.object({}),handler: (_input, apiKey) => session.getStats(apiKey.allowedSessions),},+ {+ name: 'SessionSubscribePresence',+ description:+ "Subscribe to a chat's presence (online / typing / recording). Updates then arrive as " ++ 'presence.update events; read the latest with SessionGetPresence. The subscription is lost on ' ++ 'a reconnect and must be re-issued. Not available on the whatsapp-web.js engine. Requires ' ++ 'OPERATOR role.',+ tier: 'write',+ requiredRole: ApiKeyRole.OPERATOR,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; chatId: string }) =>+ session.subscribeToPresence(input.sessionId, input.chatId).then(() => ({ success: true })),+ },+ {+ name: 'SessionGetPresence',+ description:+ 'The last presence reported for a chat, or null when none has been — the chat was never ' ++ 'subscribed, or nothing has changed since. Subscribe first with SessionSubscribePresence.',+ tier: 'read',+ requiredRole: ApiKeyRole.VIEWER,+ sessionScoped: true,+ inputSchema: z.object({+ sessionId,+ chatId: z.string().describe('Chat JID (e.g. [email protected])'),+ }),+ handler: (input: { sessionId: string; chatId: string }) => session.getPresence(input.sessionId, input.chatId),+ },{name: 'SessionMarkChatRead',description: 'Mark a chat as read (clears unread count). Requires OPERATOR role.',diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex d8b50d1fc..396414e7a 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -109,6 +109,7 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHostgetOnMessageAck: () => undefined,getOnGroupEvent: () => undefined,getOnCall: () => undefined,+ getOnPresenceUpdate: () => undefined,...overrides,};}diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex 756735984..c5230f1e9 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -5,6 +5,8 @@ import {EngineEventCallbacks,GroupEvent,IncomingCallEvent,+ ParticipantPresence,+ PresenceState,IncomingMessage,ReactionEvent,RevokedMessage,@@ -39,6 +41,26 @@ import { createSilentLogger } from './baileys-logger';* `rejectCall` as a thin forwarder (it is a public IWhatsAppEngine method), injecting this* narrow host surface via closures so the delegate never touches lifecycle state directly.*/+/** The slice of Baileys' PresenceData this adapter reads. */+interface RawPresence {+ lastKnownPresence?: PresenceState;+ lastSeen?: number;+ groupOnlineCount?: number;+}++/**+ * The states Baileys can report. Checked rather than trusted: the value crosses a library boundary+ * and lands straight in a public webhook payload, so an unknown state added upstream must be dropped+ * here rather than published as if this gateway understood it.+ */+const PRESENCE_STATES: ReadonlySet<PresenceState> = new Set<PresenceState>([+ 'available',+ 'unavailable',+ 'composing',+ 'recording',+ 'paused',+]);+export interface BaileysEventsHost {/** Live socket handle for media re-upload requests (inbound media download). */getSocket(): WASocket;@@ -77,6 +99,8 @@ export interface BaileysEventsHost {getOnGroupEvent(): EngineEventCallbacks['onGroupEvent'];/** The currently-registered onCall callback, if any (assigned at initialize()). */getOnCall(): EngineEventCallbacks['onCall'];+ /** The currently-registered onPresenceUpdate callback, if any (assigned at initialize()). */+ getOnPresenceUpdate(): EngineEventCallbacks['onPresenceUpdate'];}export class BaileysEvents {@@ -429,6 +453,46 @@ export class BaileysEvents {}}+ /**+ * Map Baileys' `presence.update` onto the neutral event.+ *+ * The payload is a per-participant map even for a 1:1 chat, where it holds the one contact — so+ * the shape is preserved rather than flattened, and a group reports everyone WhatsApp mentioned.+ * Ids are neutralized on both the chat and each participant, so a consumer never sees a raw+ * `@s.whatsapp.net` or a lid that the phone-dialect side of the API would not accept back.+ *+ * `lastSeen` is absent far more often than not: WhatsApp withholds it whenever the contact's+ * privacy settings do, which is the default for most accounts. That is not an error and is not+ * substituted with a guess.+ */+ handlePresenceUpdate(update: { id?: string; presences?: Record<string, RawPresence> }): void {+ const report = this.host.getOnPresenceUpdate();+ if (!report || !update?.id || !update.presences) return;++ const participants: ParticipantPresence[] = [];+ for (const [participant, data] of Object.entries(update.presences)) {+ const state = data?.lastKnownPresence;+ // An entry with no state says nothing; forwarding it as a guessed 'unavailable' would report+ // a contact offline on the strength of a malformed payload.+ if (!state || !PRESENCE_STATES.has(state)) continue;+ participants.push({+ id: this.host.toNeutralJid(participant),+ state,+ ...(typeof data.lastSeen === 'number' && Number.isFinite(data.lastSeen) ? { lastSeen: data.lastSeen } : {}),+ });+ }+ if (participants.length === 0) return;++ const groupOnlineCount = Object.values(update.presences).find(+ p => typeof p?.groupOnlineCount === 'number',+ )?.groupOnlineCount;+ this.host.getOnPresenceUpdate()?.({+ chatId: this.host.toNeutralJid(update.id),+ participants,+ ...(typeof groupOnlineCount === 'number' ? { groupOnlineCount } : {}),+ });+ }+/*** Cache a ringing call's raw caller JID for a later rejectCall(). Lazy expiry: inserting a new* call drops already-expired entries, so a session that receives calls but never rejects themdiff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.tsindex b8f48af25..1c82062e5 100644--- a/src/engine/adapters/baileys-lifecycle.ts+++ b/src/engine/adapters/baileys-lifecycle.ts@@ -82,6 +82,7 @@ export interface BaileysLifecycleHost {handleGroupParticipantsUpdate: BaileysEvents['handleGroupParticipantsUpdate'];handleGroupsUpdate: BaileysEvents['handleGroupsUpdate'];handleCallEvents: BaileysEvents['handleCallEvents'];+ handlePresenceUpdate: BaileysEvents['handlePresenceUpdate'];captureHistoryMessages: BaileysHistory['captureHistoryMessages'];/** Backfill names the initial sync skipped (runs on connection 'open'). */hydrateNames: BaileysHistory['hydrateNames'];@@ -223,6 +224,7 @@ export class BaileysLifecycle {previous.ev.removeAllListeners('group-participants.update');previous.ev.removeAllListeners('groups.update');previous.ev.removeAllListeners('call');+ previous.ev.removeAllListeners('presence.update');void previous.end(undefined);} catch {// end() may already have run from Baileys' own close handler — a safe no-op.@@ -321,6 +323,7 @@ export class BaileysLifecycle {// 'chats.phoneNumberShare' event, whose { lid, jid } payload this shape directly replaces).sock.ev.on('lid-mapping.update', ({ lid, pn }) => this.host.addLidMappings([{ lid, pn }]));sock.ev.on('call', calls => this.host.handleCallEvents(calls));+ sock.ev.on('presence.update', update => this.host.handlePresenceUpdate(update));}private handleConnectionUpdate(update: {diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex 3c424a03d..836b7c40f 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -129,6 +129,16 @@ export class BaileysMessaging {}}+ /**+ * 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+ * can never arrive. A failure surfaces so the caller can retry or stop expecting them.+ */+ async subscribeToPresence(chatId: string): Promise<void> {+ this.host.ensureReady();+ await this.sock().presenceSubscribe(await this.toDeliverableJid(chatId));+ }+/*** Send a native product card (#905). Baileys has no catalog-lookup-then-send helper, so the* adapter resolves the Product first; here it becomes a {product} message whose snapshot isdiff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 25c62b438..216d8ee45 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -62,6 +62,7 @@ class FakeSock extends EventEmitter {public newsletterFollow = jest.fn().mockResolvedValue(undefined);public newsletterUnfollow = jest.fn().mockResolvedValue(undefined);public rejectCall = jest.fn().mockResolvedValue(undefined);+ public presenceSubscribe = jest.fn().mockResolvedValue(undefined);// Baileys answers this by emitting its own connection.update carrying the result, so the default// mirrors that: resolving alone proves nothing reached the adapter.public fetchAccountReachoutTimelock = jest.fn().mockResolvedValue({ isActive: false });@@ -4245,3 +4246,115 @@ describe('BaileysAdapter account-restriction reporting', () => {expect(onError).not.toHaveBeenCalled();});});++// Presence is push-only after a subscription — it cannot be queried — so the mapping is the only+// place a wrong shape can be caught before it reaches a public webhook payload.+describe('BaileysAdapter presence', () => {+ beforeEach(() => {+ fakeSock.user = undefined;+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ });++ /** Subscribing is a live-socket operation, so the session has to be connected first. */+ const readyAdapter = async (callbacks = noopCallbacks({})) => {+ const adapter = newAdapter();+ await adapter.initialize(callbacks);+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ it('subscribes through the socket for the addressed chat', async () => {+ const adapter = await readyAdapter();++ await adapter.subscribeToPresence('[email protected]');++ expect(fakeSock.presenceSubscribe).toHaveBeenCalledTimes(1);+ });++ // Unlike the typing indicator next door, this one is NOT best-effort: the caller asked for a+ // subscription, and swallowing the failure would leave them waiting for updates that never come.+ it('surfaces a failed subscription instead of swallowing it', async () => {+ const adapter = await readyAdapter();+ fakeSock.presenceSubscribe.mockRejectedValueOnce(new Error('no LID for user'));++ await expect(adapter.subscribeToPresence('[email protected]')).rejects.toThrow('no LID for user');+ });++ it('maps a per-participant presence map onto the neutral event', async () => {+ const onPresenceUpdate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onPresenceUpdate }));++ fakeSock.fire('presence.update', {+ id: '[email protected]',+ presences: { '[email protected]': { lastKnownPresence: 'composing', lastSeen: 1786000000 } },+ });++ expect(onPresenceUpdate).toHaveBeenCalledWith({+ chatId: '[email protected]',+ participants: [{ id: '[email protected]', state: 'composing', lastSeen: 1786000000 }],+ });+ });++ // Most contacts hide last-seen, so its absence is the common case and must not become a guess.+ it('omits lastSeen rather than inventing one', async () => {+ const onPresenceUpdate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onPresenceUpdate }));++ fakeSock.fire('presence.update', {+ id: '[email protected]',+ presences: { '[email protected]': { lastKnownPresence: 'available' } },+ });++ const [event] = onPresenceUpdate.mock.calls[0] as [{ participants: Record<string, unknown>[] }];+ expect(event.participants[0]).not.toHaveProperty('lastSeen');+ });++ it('carries the group online count when the engine reports one', async () => {+ const onPresenceUpdate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onPresenceUpdate }));++ fakeSock.fire('presence.update', {+ id: '[email protected]',+ presences: { '[email protected]': { lastKnownPresence: 'available', groupOnlineCount: 4 } },+ });++ expect(onPresenceUpdate).toHaveBeenCalledWith(expect.objectContaining({ groupOnlineCount: 4 }));+ });++ // An unknown state crossing the library boundary lands straight in a public payload, so it is+ // dropped rather than published as if this gateway understood it.+ it('drops a participant whose state is unknown or missing', async () => {+ const onPresenceUpdate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onPresenceUpdate }));++ fakeSock.fire('presence.update', {+ id: '[email protected]',+ presences: {+ '[email protected]': { lastKnownPresence: 'telepathic' },+ '[email protected]': {},+ '[email protected]': { lastKnownPresence: 'available' },+ },+ });++ expect(onPresenceUpdate).toHaveBeenCalledWith(+ expect.objectContaining({ participants: [{ id: '[email protected]', state: 'available' }] }),+ );+ });++ it('emits nothing when no participant survives the mapping', async () => {+ const onPresenceUpdate = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onPresenceUpdate }));++ fakeSock.fire('presence.update', { id: '[email protected]', presences: { '[email protected]': {} } });+ fakeSock.fire('presence.update', { id: '[email protected]' });++ expect(onPresenceUpdate).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 8f7771b47..9f8462a1d 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -131,6 +131,7 @@ export class BaileysAdapter implements IWhatsAppEngine {getOnMessageAck: () => this.callbacks.onMessageAck,getOnGroupEvent: () => this.callbacks.onGroupEvent,getOnCall: () => this.callbacks.onCall,+ getOnPresenceUpdate: () => this.callbacks.onPresenceUpdate,});this.groups = new BaileysGroups({ensureReady: () => this.ensureReady(),@@ -211,6 +212,7 @@ export class BaileysAdapter implements IWhatsAppEngine {handleGroupParticipantsUpdate: event => this.events.handleGroupParticipantsUpdate(event),handleGroupsUpdate: updates => this.events.handleGroupsUpdate(updates),handleCallEvents: calls => this.events.handleCallEvents(calls),+ handlePresenceUpdate: update => this.events.handlePresenceUpdate(update),captureHistoryMessages: messages => this.history.captureHistoryMessages(messages),hydrateNames: () => this.history.hydrateNames(),getOnQRCode: () => this.callbacks.onQRCode,@@ -486,6 +488,10 @@ export class BaileysAdapter implements IWhatsAppEngine {return this.contacts.getChats();}+ async subscribeToPresence(chatId: string): Promise<void> {+ return this.messaging.subscribeToPresence(chatId);+ }+async sendSeen(chatId: string): Promise<boolean> {return this.contacts.sendSeen(chatId);}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex d9e75489f..f76c973d3 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5660,3 +5660,25 @@ describe('WhatsAppWebJsAdapter account-restriction reporting', () => {expect(onDisconnected).toHaveBeenCalledWith(WAState.TOS_BLOCK);});});++// whatsapp-web.js can publish the account's OWN presence but cannot observe anyone else's, and+// emits no presence event at all. The refusal is declared inline on the adapter rather than in a+// delegate so the parity gate — which reads method bodies off the prototype — can actually see it.+describe('WhatsAppWebJsAdapter presence', () => {+ it('refuses to subscribe, with the method named', async () => {+ const adapter = new WhatsAppWebJsAdapter({+ sessionId: 'sess-1',+ sessionDataPath: './data/sessions',+ puppeteer: {},+ });++ await expect(adapter.subscribeToPresence('[email protected]')).rejects.toThrow(/subscribeToPresence/);+ });++ it('declares the refusal inline, where the parity gate can read it', () => {+ const body = Object.getOwnPropertyDescriptor(WhatsAppWebJsAdapter.prototype, 'subscribeToPresence')+ ?.value as () => unknown;++ expect(String(body)).toMatch(/EngineNotSupportedError/);+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 3be9036bc..1a176cc8b 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -43,6 +43,7 @@ import {IncomingCallEvent,AccountRestriction,} from '../interfaces/whatsapp-engine.interface';+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { resolveWebVersionPin } from '../wa-web-version';import { resolveAuthTimeoutMs } from '../engine-init-timeout';import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chromium-profile-hygiene';@@ -627,6 +628,20 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin});}+ /**+ * whatsapp-web.js exposes no way to observe another party's presence: WAWebPresenceChatAction+ * offers only sendPresenceAvailable/sendPresenceUnavailable, which publish the ACCOUNT's own+ * presence, and the library surfaces no presence event at all.+ *+ * Declared here inline rather than in a delegate on purpose. The parity gate reads method bodies+ * off the prototype, so a throw hidden behind a delegate call is invisible to it and the+ * `not-available` matrix row would go unverified; inline, the gate checks it.+ */+ // eslint-disable-next-line @typescript-eslint/require-await, @typescript-eslint/no-unused-vars+ async subscribeToPresence(_chatId: string): Promise<void> {+ throw new EngineNotSupportedError('subscribeToPresence');+ }+/*** Map a whatsapp-web.js GroupNotification (`group_join` / `group_leave` / `group_update`) to the* neutral GroupEvent and forward it. wwebjs ids are already in the neutral dialect (@c.us/@g.us),diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.tsindex edb22c2c5..99aee7447 100644--- a/src/engine/engine-capability-matrix.ts+++ b/src/engine/engine-capability-matrix.ts@@ -255,6 +255,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {'baileys AnyRegularMessageContent {product: WASendableProduct} (Types/Message.d.ts:203) — adapter resolves the product via getCatalog then sends the snapshot with businessOwnerJid=self (adapters/baileys-messaging.ts; #905); wwjs no Client.sendProduct — Product/Order are inbound-only parsers',},sendSeen: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },+ subscribeToPresence: {+ wwjs: { status: 'not-available', rootCause: 'library-limitation' },+ baileys: { status: 'supported' },+ evidence:+ "baileys presenceSubscribe(toJid) (Socket/chats.d.ts:39) + the 'presence.update' event carrying a per-participant PresenceData map (Types/Events.d.ts:50-55, Types/Chat.d.ts:20-24); whatsapp-web.js 1.34.7 has only sendPresenceAvailable/sendPresenceUnavailable (index.d.ts:230,233), which publish the ACCOUNT's own presence — it exposes no subscribe and emits no presence event",+ },sendStickerMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendTextMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },sendVideoMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex f8017590b..752acbfe0 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -535,6 +535,35 @@ export interface AccountRestriction {expiresAt?: number;}+/**+ * Neutral presence states, matching what WhatsApp itself distinguishes: whether the contact is+ * reachable, and whether they are actively typing or recording in the chat being watched.+ */+export type PresenceState = 'available' | 'unavailable' | 'composing' | 'recording' | 'paused';++/** One participant's presence within a chat. */+export interface ParticipantPresence {+ /** Neutral participant id. In a 1:1 chat this is the chat's own id. */+ id: string;+ state: PresenceState;+ /**+ * Unix SECONDS the contact was last seen, when WhatsApp discloses it. Absent for contacts whose+ * privacy settings hide last-seen — which is the common case, not an error.+ */+ lastSeen?: number;+}++/**+ * Presence in one chat. A group reports every participant WhatsApp chose to tell us about, so this+ * is a list rather than a single state even for a 1:1 chat, where it holds exactly one entry.+ */+export interface PresenceUpdateEvent {+ chatId: string;+ participants: ParticipantPresence[];+ /** How many group members are online, when the engine reports it (groups only). */+ groupOnlineCount?: number;+}+export interface EngineEventCallbacks {onQRCode?: (qr: string) => void;onReady?: (phone: string, pushName: string) => void;@@ -593,6 +622,12 @@ export interface EngineEventCallbacks {* Consumers decide what a restriction is worth.*/onAccountRestriction?: (restriction: AccountRestriction | null) => void;+ /**+ * Fired when WhatsApp reports presence for a chat this session subscribed to. Push-only and+ * unsolicited after the subscription: there is no way to ask for a contact's presence on demand,+ * which is why consumers keep the last reported state rather than querying for it.+ */+ onPresenceUpdate?: (event: PresenceUpdateEvent) => void;/*** Fired on a terminal initialization/authentication failure (e.g. Chromium* could not launch, or WhatsApp rejected the stored credentials). The engine@@ -879,4 +914,16 @@ export interface IWhatsAppEngine {* Engine-agnostic and best-effort: engines without a presence concept should no-op.*/sendChatState(chatId: string, state: ChatState): Promise<void>;+ /**+ * Ask WhatsApp to start reporting a chat's presence, delivered through `onPresenceUpdate`.+ *+ * Deliberately per chat rather than a blanket subscribe-all: WhatsApp emits a presence update on+ * every transition — each time someone starts and stops typing — so subscribing to everything+ * turns an idle account into a firehose. The subscription lasts for the life of the connection and+ * has to be re-established after a reconnect.+ *+ * There is no matching read: presence cannot be queried, only received, which is why the gateway+ * serves the last reported state rather than fetching it.+ */+ subscribeToPresence(chatId: string): Promise<void>;}diff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex 1b5569648..89a6ceb8b 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -28,6 +28,7 @@ export const SUBSCRIBABLE_EVENTS = ['group.update','call.received','status.received',+ 'presence.update',] as const;export type SubscribableEvent = (typeof SUBSCRIBABLE_EVENTS)[number] | '*';diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 3d281a02a..98c5efd01 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -539,6 +539,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'session.disconnected', data);}+ /**+ * Emit a presence update. Socket-subscribable as well as webhook-delivered because presence is the+ * one event whose whole value is being live — a webhook round-trip to render a typing indicator+ * has usually expired by the time it arrives. Only actual changes reach here (see the wiring).+ */+ emitPresenceUpdate(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'presence.update', data);+ }+/*** Emit QR code update for a session*/diff --git a/src/modules/session/dto/index.ts b/src/modules/session/dto/index.tsindex fd280f220..e2e090a6f 100644--- a/src/modules/session/dto/index.ts+++ b/src/modules/session/dto/index.ts@@ -6,3 +6,4 @@ export * from './delete-chat.dto';export * from './send-chat-state.dto';export * from './request-pairing-code.dto';export * from './chat-summary.dto';+export * from './presence.dto';diff --git a/src/modules/session/dto/presence.dto.ts b/src/modules/session/dto/presence.dto.tsnew file mode 100644index 000000000..84fb4ca6f--- /dev/null+++ b/src/modules/session/dto/presence.dto.ts@@ -0,0 +1,61 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';+import { IsNotEmpty, IsString, Matches } from 'class-validator';++export class SubscribePresenceDto {+ @ApiProperty({+ description: "Chat ID in the active engine's native format (e.g. [email protected] on whatsapp-web.js)",+ example: '[email protected]',+ })+ @IsString()+ @IsNotEmpty()+ // Same engine-neutral structural check the other chat-scoped DTOs use: localpart@host, no+ // whitespace, so a different engine's JID scheme is accepted and the adapter normalises further.+ @Matches(/^[^\s@]+@[^\s@]+$/, {+ message: 'chatId must be a valid chat JID in the form localpart@host',+ })+ chatId: string;+}++export class ParticipantPresenceDto {+ @ApiProperty({ description: 'Participant id. In a 1:1 chat this is the chat itself.', example: '[email protected]' })+ id: string;++ @ApiProperty({+ enum: ['available', 'unavailable', 'composing', 'recording', 'paused'],+ description:+ '`composing` and `recording` mean actively typing or recording in this chat; `paused` means ' ++ 'they stopped without sending. `available`/`unavailable` describe reachability.',+ example: 'composing',+ })+ state: string;++ @ApiPropertyOptional({+ type: Number,+ description:+ "Unix SECONDS the contact was last seen. Absent whenever the contact's privacy settings hide " ++ 'last-seen — the common case, and not an error.',+ example: 1786000000,+ })+ lastSeen?: number;+}++export class ChatPresenceResponseDto {+ @ApiProperty({ example: '[email protected]' })+ chatId: string;++ @ApiProperty({ type: [ParticipantPresenceDto] })+ participants: ParticipantPresenceDto[];++ @ApiPropertyOptional({ type: Number, description: 'Online member count, groups only.', example: 3 })+ groupOnlineCount?: number;++ @ApiProperty({+ type: String,+ format: 'date-time',+ description:+ 'When this gateway received the report — NOT a WhatsApp timestamp. Presence is short-lived, so ' ++ 'an old `observedAt` means the state is stale rather than steady.',+ example: '2026-08-03T12:00:00Z',+ })+ observedAt: Date;+}diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.tsindex 3f7f3e8be..e4a0c55e2 100644--- a/src/modules/session/logout-teardown-race.spec.ts+++ b/src/modules/session/logout-teardown-race.spec.ts@@ -7,6 +7,7 @@ import { SessionService } from './session.service';import { SessionEngineLifecycle } from './session-engine-lifecycle.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { EngineFactory } from '../../engine/engine.factory';@@ -98,6 +99,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {SessionEngineLifecycle,SessionErrorStore,SessionRestrictionStore,+ PresenceStore,{ provide: getRepositoryToken(Session, 'data'), useValue: repository },{ provide: getRepositoryToken(Message, 'data'), useValue: messageRepository },{ provide: getDataSourceToken('data'), useValue: dataSource },diff --git a/src/modules/session/presence-store.service.spec.ts b/src/modules/session/presence-store.service.spec.tsnew file mode 100644index 000000000..d7bc127f2--- /dev/null+++ b/src/modules/session/presence-store.service.spec.ts@@ -0,0 +1,165 @@+import { PresenceStore } from './presence-store.service';+import type { PresenceUpdateEvent } from '../../engine/interfaces/whatsapp-engine.interface';++const event = (over: Partial<PresenceUpdateEvent> = {}): PresenceUpdateEvent => ({+ chatId: '[email protected]',+ participants: [{ id: '[email protected]', state: 'composing' }],+ ...over,+});++describe('PresenceStore', () => {+ let store: PresenceStore;++ beforeEach(() => {+ store = new PresenceStore();+ });++ describe('change detection', () => {+ // The load-bearing behaviour. WhatsApp reports presence on every transition and repeats itself+ // freely; without suppression one watched chat with an active typist buries every other event a+ // consumer subscribes to.+ it('reports the first observation as a change', () => {+ expect(store.record('s1', event())).toBe(true);+ });++ it('suppresses an identical repeat', () => {+ store.record('s1', event());++ expect(store.record('s1', event())).toBe(false);+ expect(store.record('s1', event())).toBe(false);+ });++ it('reports a state transition', () => {+ store.record('s1', event({ participants: [{ id: '[email protected]', state: 'composing' }] }));++ expect(store.record('s1', event({ participants: [{ id: '[email protected]', state: 'paused' }] }))).toBe(true);+ });++ it('reports a participant appearing or disappearing', () => {+ store.record('s1', event({ participants: [{ id: '[email protected]', state: 'available' }] }));++ expect(+ store.record(+ 's1',+ event({+ participants: [+ { id: '[email protected]', state: 'available' },+ { id: '[email protected]', state: 'available' },+ ],+ }),+ ),+ ).toBe(true);+ });++ // The engines build the participant list by iterating an object, so ordering is incidental.+ // Treating a reordering as news would defeat the suppression on exactly the busy group chats+ // where it matters most.+ it('ignores participant ordering', () => {+ const participants = [+ { id: '[email protected]', state: 'available' as const },+ { id: '[email protected]', state: 'composing' as const },+ ];+ store.record('s1', event({ participants }));++ expect(store.record('s1', event({ participants: [...participants].reverse() }))).toBe(false);+ });++ // lastSeen advances continuously while nothing observable happens; if it counted as a change the+ // suppression would never suppress anything.+ it('ignores lastSeen drift on an unchanged state', () => {+ store.record('s1', event({ participants: [{ id: '[email protected]', state: 'available', lastSeen: 1000 }] }));++ expect(store.record('s1', event({ participants: [{ id: '[email protected]', state: 'available', lastSeen: 2000 }] }))).toBe(+ false,+ );+ });++ it('ignores groupOnlineCount drift on an unchanged state', () => {+ store.record('s1', event({ groupOnlineCount: 3 }));++ expect(store.record('s1', event({ groupOnlineCount: 9 }))).toBe(false);+ });++ it('tracks chats and sessions independently', () => {+ store.record('s1', event({ chatId: '[email protected]' }));++ expect(store.record('s1', event({ chatId: '[email protected]' }))).toBe(true);+ expect(store.record('s2', event({ chatId: '[email protected]' }))).toBe(true);+ });+ });++ describe('reads', () => {+ it('serves the last report with when it arrived', () => {+ store.record('s1', event({ groupOnlineCount: 2 }), 1_700_000_000_000);++ expect(store.get('s1', '[email protected]')).toEqual({+ chatId: '[email protected]',+ participants: [{ id: '[email protected]', state: 'composing' }],+ groupOnlineCount: 2,+ observedAt: 1_700_000_000_000,+ });+ });++ // A suppressed repeat still refreshes what is served, so a read never reports a state as older+ // than it really is just because it stopped changing.+ it('refreshes the stored report even when the change was suppressed', () => {+ store.record('s1', event(), 1000);+ store.record('s1', event(), 5000);++ expect(store.get('s1', '[email protected]')?.observedAt).toBe(5000);+ });++ // "Nothing reported yet" is a normal state — subscribed but quiet — not a missing resource.+ it('returns null for a chat nothing was reported for', () => {+ expect(store.get('s1', '[email protected]')).toBeNull();+ });++ it('returns null for an unknown session', () => {+ expect(store.get('nobody', '[email protected]')).toBeNull();+ });+ });++ describe('clearing', () => {+ it('drops everything for the session', () => {+ store.record('s1', event({ chatId: '[email protected]' }));+ store.record('s1', event({ chatId: '[email protected]' }));+ store.record('s2', event({ chatId: '[email protected]' }));++ store.clear('s1');++ expect(store.get('s1', '[email protected]')).toBeNull();+ expect(store.get('s1', '[email protected]')).toBeNull();+ // …and leaves other sessions alone.+ expect(store.get('s2', '[email protected]')).not.toBeNull();+ });++ // After a clear the next report is news 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());+ store.clear('s1');++ expect(store.record('s1', event())).toBe(true);+ });+ });++ // 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', () => {+ for (let i = 0; i < 501; i++) store.record('s1', event({ chatId: `chat-${i}@c.us` }), 1000 + i);++ expect(store.get('s1', '[email protected]')).toBeNull();+ expect(store.get('s1', '[email protected]')).not.toBeNull();+ });++ it('keeps a chat alive by re-observing it', () => {+ store.record('s1', event({ chatId: '[email protected]' }), 1);+ for (let i = 0; i < 499; i++) store.record('s1', event({ chatId: `chat-${i}@c.us` }), 100 + i);+ // Re-observing moves it to the newest position, so the next eviction takes something else.+ store.record('s1', event({ chatId: '[email protected]', participants: [{ id: '[email protected]', state: 'paused' }] }), 9000);+ store.record('s1', event({ chatId: '[email protected]' }), 9001);++ expect(store.get('s1', '[email protected]')).not.toBeNull();+ expect(store.get('s1', '[email protected]')).toBeNull();+ });+});diff --git a/src/modules/session/presence-store.service.ts b/src/modules/session/presence-store.service.tsnew file mode 100644index 000000000..4f9bd4e0f--- /dev/null+++ b/src/modules/session/presence-store.service.ts@@ -0,0 +1,83 @@+import { Injectable } from '@nestjs/common';+import type { ParticipantPresence, PresenceUpdateEvent } from '../../engine/interfaces/whatsapp-engine.interface';++/** What `GET /presence/:chatId` serves: the last report, with when it arrived. */+export interface ChatPresence {+ chatId: string;+ participants: ParticipantPresence[];+ groupOnlineCount?: number;+ /** Unix ms this gateway received the report — NOT a WhatsApp timestamp. */+ observedAt: number;+}++/**+ * Bound on how many chats one session keeps presence for. Presence is only reported for chats that+ * were explicitly subscribed, so this is already caller-bounded; the cap exists so a client that+ * subscribes in a loop cannot grow the map without limit. Eviction is oldest-observed-first.+ */+const MAX_CHATS_PER_SESSION = 500;++/**+ * The last presence WhatsApp reported for each subscribed chat.+ *+ * In memory because presence IS ephemeral — "typing, three seconds ago" has no meaning after a+ * restart, and persisting it would serve confident answers about a state that expired long before.+ * It is also the only thing that can answer a read at all: presence cannot be queried from either+ * library, only received after a subscription, so a `GET` has nothing to fetch and everything to+ * remember.+ */+@Injectable()+export class PresenceStore {+ private readonly bySession = new Map<string, Map<string, ChatPresence>>();++ /**+ * Record a report. Returns whether it CHANGED anything a consumer would care about — WhatsApp+ * re-sends the same state freely, and dispatching a webhook per repeat would make presence the+ * loudest event in the system by a wide margin for no added information.+ *+ * `lastSeen` and `groupOnlineCount` drifting on their own do not count as a change: they move+ * continuously while nothing observable happens, and treating them as news would defeat the+ * suppression entirely.+ */+ record(sessionId: string, event: PresenceUpdateEvent, at = Date.now()): boolean {+ const chats = this.bySession.get(sessionId) ?? new Map<string, ChatPresence>();+ this.bySession.set(sessionId, chats);++ const previous = chats.get(event.chatId);+ const next: ChatPresence = {+ chatId: event.chatId,+ participants: event.participants,+ ...(event.groupOnlineCount === undefined ? {} : { groupOnlineCount: event.groupOnlineCount }),+ observedAt: at,+ };+ // Re-insert so the map stays ordered by recency and the eviction below drops the stalest chat.+ chats.delete(event.chatId);+ chats.set(event.chatId, next);+ while (chats.size > MAX_CHATS_PER_SESSION) {+ const oldest = chats.keys().next().value;+ if (oldest === undefined) break;+ chats.delete(oldest);+ }+ return !samePresence(previous?.participants, event.participants);+ }++ /** The last known presence for a chat, or null if none was ever reported. */+ get(sessionId: string, chatId: string): ChatPresence | null {+ return this.bySession.get(sessionId)?.get(chatId) ?? null;+ }++ /** Drop everything for a session — it stopped, was deleted, or its engine was replaced. */+ clear(sessionId: string): void {+ this.bySession.delete(sessionId);+ }+}++/**+ * Whether two participant lists say the same thing. Order is not significant — the engines build the+ * list by iterating an object, so a reordering is not a presence change and must not read as one.+ */+function samePresence(before: ParticipantPresence[] | undefined, after: ParticipantPresence[]): boolean {+ if (!before || before.length !== after.length) return false;+ const previous = new Map(before.map(participant => [participant.id, participant.state]));+ return after.every(participant => previous.get(participant.id) === participant.state);+}diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex faa02f25f..98b508f2b 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -11,6 +11,7 @@ import { EngineFactory } from '../../engine/engine.factory';import { EngineRegistry } from '../../engine/engine-registry.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { type createLogger } from '../../common/services/logger.service';import { HookManager } from '../../core/hooks';import { SessionLifecycleFences } from './session-lifecycle-fences';@@ -45,6 +46,7 @@ export interface SessionEngineControlsHost {engines: EngineRegistry;sessionErrors: SessionErrorStore;sessionRestrictions: SessionRestrictionStore;+ presence: PresenceStore;hookManager: HookManager;configService?: ConfigService;logger: ReturnType<typeof createLogger>;@@ -82,6 +84,7 @@ export class SessionEngineControls {private readonly engines: EngineRegistry;private readonly sessionErrors: SessionErrorStore;private readonly sessionRestrictions: SessionRestrictionStore;+ private readonly presence: PresenceStore;private readonly hookManager: HookManager;private readonly configService?: ConfigService;private readonly logger: ReturnType<typeof createLogger>;@@ -98,6 +101,7 @@ export class SessionEngineControls {this.engines = host.engines;this.sessionErrors = host.sessionErrors;this.sessionRestrictions = host.sessionRestrictions;+ this.presence = host.presence;this.hookManager = host.hookManager;this.configService = host.configService;this.logger = host.logger;@@ -514,6 +518,9 @@ export class SessionEngineControls {// Same unbounded-growth argument for the restriction entry, and the gauge it feeds must not// keep counting an account whose session no longer exists.this.sessionRestrictions.clear(id);+ // Presence is per-connection state that the deleted session can never receive again, and it+ // is keyed by an id that will never be read.+ this.presence.clear(id);// The stuck-auth recovery budget is keyed by id; a committed delete frees it (and a recreated// session under the same name gets a fresh UUID + fresh budget). Left only on a committed// delete so a failed/409 delete — the session still exists — keeps the budget intact.diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex a476d5bc8..1922224dd 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -2,6 +2,7 @@ import { SessionStatus } from './entities/session.entity';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { EventsGateway } from '../events/events.gateway';@@ -13,6 +14,7 @@ import {IWhatsAppEngine,IncomingCallEvent,AccountRestriction,+ PresenceUpdateEvent,} from '../../engine/interfaces/whatsapp-engine.interface';import { type createLogger } from '../../common/services/logger.service';import { SessionEngineLeafEvents } from './session-engine-leaf-events';@@ -48,6 +50,7 @@ export interface SessionEngineWiringHost {messages: MessageProjector;sessionErrors: SessionErrorStore;sessionRestrictions: SessionRestrictionStore;+ presence: PresenceStore;/** @Global AuditService; absent only in the standalone constructions specs build. */auditService?: AuditService;webhookService: WebhookService;@@ -217,6 +220,17 @@ export class SessionEngineEventWiring {host.sessionErrors.set(id, reason);void host.hookManager.execute('session:error', { reason }, { sessionId: id, source: 'Engine' });},+ onPresenceUpdate: (event: PresenceUpdateEvent): void => {+ if (!host.isLiveEngine(id, engine)) return;+ // WhatsApp reports presence on every transition and freely repeats itself, so only an actual+ // change is published. Without this, one watched chat with an active typist produces a+ // continuous stream of identical events — enough to drown every other webhook a consumer+ // subscribes to. The store is the only thing that knows the previous state, so it decides.+ if (!host.presence.record(id, event)) return;+ const payload: Record<string, unknown> = { sessionId: id, ...event };+ host.eventsGateway.emitPresenceUpdate(id, payload);+ void host.webhookService.dispatch(id, 'presence.update', payload);+ },onAccountRestriction: (restriction: AccountRestriction | null): void => {if (!host.isLiveEngine(id, engine)) return;diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex aaf0ebd95..16b790af4 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -10,6 +10,7 @@ import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveEngineInitTimeoutMs } from '../../engine/engine-init-timeout';@@ -213,6 +214,7 @@ export class SessionEngineLifecycle {private readonly messages: MessageProjector,private readonly sessionErrors: SessionErrorStore,private readonly sessionRestrictions: SessionRestrictionStore,+ private readonly presence: PresenceStore,private readonly eventsGateway: EventsGateway,private readonly webhookService: WebhookService,private readonly hookManager: HookManager,@@ -284,6 +286,7 @@ export class SessionEngineLifecycle {messages: this.messages,sessionErrors: this.sessionErrors,sessionRestrictions: this.sessionRestrictions,+ presence: this.presence,auditService: this.auditService,webhookService: this.webhookService,eventsGateway: this.eventsGateway,@@ -301,6 +304,7 @@ export class SessionEngineLifecycle {engines: this.engineRegistry,sessionErrors: this.sessionErrors,sessionRestrictions: this.sessionRestrictions,+ presence: this.presence,hookManager: this.hookManager,configService: this.configService,logger: this.logger,@@ -435,6 +439,9 @@ export class SessionEngineLifecycle {proxyType: session.proxyType || undefined,});this.engines.set(id, engine);+ // Presence subscriptions live on the socket, so a fresh engine has none — whatever the previous+ // connection last reported is now unverifiable and would be served as if it were current.+ this.presence.clear(id);// Clear any prior failure reason before a fresh start. A recorded account restriction is// deliberately NOT cleared here: it describes the account, not this attempt, so a restart does// not resolve it — and clearing it per attempt would make it flicker off and on through adiff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex 11aad87e4..8de810a6c 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -6,6 +6,8 @@ import {SessionResponseDto,QRCodeResponseDto,MarkChatReadDto,+ SubscribePresenceDto,+ ChatPresenceResponseDto,ArchiveChatDto,DeleteChatDto,SendChatStateDto,@@ -345,6 +347,58 @@ export class SessionController {return { success };}+ @Post(':id/presence/subscribe')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({+ summary: "Subscribe to a chat's presence",+ description:+ 'Asks WhatsApp to start reporting who is online or typing in this chat. Updates arrive as the ' ++ '`presence.update` webhook and socket event — there is no synchronous answer, because presence ' ++ 'cannot be queried from either engine, only received.\n\n' ++ 'The subscription belongs to the connection: it does **not** survive a restart or an automatic ' ++ 'reconnect, and must be re-issued. Subscribe per chat rather than to everything — WhatsApp emits ' ++ 'an update on every transition, so a broad subscription is a firehose.\n\n' ++ 'whatsapp-web.js cannot do this at all (it exposes no presence subscribe and emits no presence ' ++ 'event) and answers `501`.',+ })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiResponse({ status: 200, description: 'Subscribed; updates now arrive as presence.update events' })+ @ApiResponse({ status: 400, description: 'Session not started' })+ @ApiResponse({ status: 404, description: 'Session not found' })+ @ApiResponse({ status: 501, description: 'The active engine cannot observe presence (whatsapp-web.js)' })+ async subscribeToPresence(+ @Param('id', ParseUUIDPipe) id: string,+ @Body() dto: SubscribePresenceDto,+ ): Promise<{ success: boolean }> {+ await this.sessionService.subscribeToPresence(id, dto.chatId);+ return { success: true };+ }++ @Get(':id/presence/:chatId')+ @RequireRole(ApiKeyRole.VIEWER)+ @ApiOperation({+ summary: "Read a chat's last reported presence",+ 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\n' ++ 'Held in memory and never persisted: presence is short-lived, and answering "typing" from ' ++ 'before a restart would be worse than answering nothing.',+ })+ @ApiParam({ name: 'id', description: 'Session ID' })+ @ApiParam({ name: 'chatId', description: 'Chat ID as subscribed' })+ @ApiResponse({ status: 200, description: 'Last reported presence, or null', type: ChatPresenceResponseDto })+ @ApiResponse({ status: 404, description: 'Session not found' })+ async getPresence(+ @Param('id', ParseUUIDPipe) id: string,+ @Param('chatId') chatId: string,+ ): Promise<ChatPresenceResponseDto | null> {+ const presence = await this.sessionService.getPresence(id, chatId);+ return presence ? { ...presence, observedAt: new Date(presence.observedAt) } : null;+ }+@Post(':id/chats/unread')@RequireRole(ApiKeyRole.OPERATOR)@HttpCode(HttpStatus.OK)diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex 1eed92026..f0314c31f 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -9,6 +9,7 @@ import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { SessionController } from './session.controller';import { WebhookModule } from '../webhook/webhook.module';import { StatusStoreModule } from '../status-store/status-store.module';@@ -24,6 +25,7 @@ import { ChatMediaModule } from '../chat-media/chat-media.module';SessionEngineLifecycle,SessionErrorStore,SessionRestrictionStore,+ PresenceStore,SessionLidResolver,SessionLivenessWatchdog,MessageProjector,diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 4822f1b14..836099164 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1,5 +1,6 @@import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore } from './presence-store.service';import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';import { Repository, DataSource, In } from 'typeorm';@@ -161,6 +162,7 @@ describe('SessionService', () => {emitSessionStatus: jest.fn(),emitSessionAuthenticated: jest.fn(),emitSessionDisconnected: jest.fn(),+ emitPresenceUpdate: jest.fn(),emitMessage: jest.fn(),emitMessageSent: jest.fn(),emitMessageAck: jest.fn(),@@ -206,6 +208,7 @@ describe('SessionService', () => {SessionEngineLifecycle,SessionErrorStore,SessionRestrictionStore,+ PresenceStore,{ provide: AuditService, useValue: auditService },{provide: getRepositoryToken(Session, 'data'),@@ -2205,6 +2208,78 @@ describe('SessionService', () => {});});+ // Presence is the noisiest thing WhatsApp reports — an update per transition, repeated freely — so+ // the suppression is what keeps it from drowning every other event a consumer subscribes to.+ describe('engine presence updates', () => {+ const presence = (state: 'composing' | 'paused') => ({+ chatId: '[email protected]',+ participants: [{ id: '[email protected]', state }],+ });++ const startAndCapture = async (): Promise<EngineEventCallbacks> => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];+ return calls[0][0];+ };++ it('publishes a change to both the socket and webhook subscribers', async () => {+ const callbacks = await startAndCapture();+ (webhookService.dispatch as jest.Mock).mockClear();++ callbacks.onPresenceUpdate?.(presence('composing'));++ const payload = { sessionId: 'sess-uuid-1', ...presence('composing') };+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'presence.update', payload);+ expect(eventsGateway.emitPresenceUpdate).toHaveBeenCalledWith('sess-uuid-1', payload);+ });++ it('publishes nothing when the reported state has not changed', async () => {+ const callbacks = await startAndCapture();+ callbacks.onPresenceUpdate?.(presence('composing'));+ (webhookService.dispatch as jest.Mock).mockClear();+ (eventsGateway.emitPresenceUpdate as jest.Mock).mockClear();++ callbacks.onPresenceUpdate?.(presence('composing'));+ callbacks.onPresenceUpdate?.(presence('composing'));++ expect(webhookService.dispatch).not.toHaveBeenCalled();+ expect(eventsGateway.emitPresenceUpdate).not.toHaveBeenCalled();+ });++ it('publishes again once the state actually changes', async () => {+ const callbacks = await startAndCapture();+ callbacks.onPresenceUpdate?.(presence('composing'));+ (webhookService.dispatch as jest.Mock).mockClear();++ callbacks.onPresenceUpdate?.(presence('paused'));++ expect(webhookService.dispatch).toHaveBeenCalledWith(+ 'sess-uuid-1',+ 'presence.update',+ expect.objectContaining({ participants: [{ id: '[email protected]', state: 'paused' }] }),+ );+ });++ it('serves the last report back through the read model', async () => {+ const callbacks = await startAndCapture();+ callbacks.onPresenceUpdate?.(presence('composing'));++ await expect(service.getPresence('sess-uuid-1', '[email protected]')).resolves.toMatchObject({+ chatId: '[email protected]',+ participants: [{ id: '[email protected]', state: 'composing' }],+ });+ });++ // Subscribed but quiet is a normal state, not a missing resource.+ it('reports null for a chat nothing was reported for', async () => {+ await startAndCapture();++ await expect(service.getPresence('sess-uuid-1', '[email protected]')).resolves.toBeNull();+ });+ });+// ── engine-identity guard: stale-callback isolation ───────────────// A callback can fire after its engine was torn down (post-stop) or after a newer engine// replaced it for the same id (post-restart / reconnect). Such a stale callback must notdiff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 449b23814..b1b45a2f0 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -19,6 +19,7 @@ import { SessionLidResolver } from './session-lid-resolver.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { PresenceStore, type ChatPresence } from './presence-store.service';import { SessionEngineLifecycle } from './session-engine-lifecycle.service';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';@@ -72,6 +73,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatprivate readonly watchdog: SessionLivenessWatchdog,private readonly sessionErrors: SessionErrorStore,private readonly sessionRestrictions: SessionRestrictionStore,+ private readonly presence: PresenceStore,private readonly hookManager: HookManager,private readonly engineLifecycle: SessionEngineLifecycle,@Optional()@@ -340,6 +342,36 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn paginate(chats, opts.limit, opts.offset);}+ /**+ * Ask WhatsApp to start reporting a chat's presence. Updates arrive as `presence.update` events;+ * there is no synchronous answer to give here, because presence cannot be queried from either+ * library — only received.+ *+ * The subscription belongs to the connection, so it does not survive a restart or an automatic+ * reconnect and has to be re-issued. That is the engine's contract, not a gateway choice, and the+ * API documents it rather than pretending otherwise by silently replaying subscriptions.+ */+ async subscribeToPresence(id: string, chatId: string): Promise<void> {+ await this.findOne(id);+ const engine = this.engines.get(id);++ if (!engine) {+ throw new BadRequestException('Session is not started');+ }++ return engine.subscribeToPresence(chatId);+ }++ /**+ * 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.+ * Deliberately not an error: "nothing reported yet" is a normal state, not a missing resource.+ */+ async getPresence(id: string, chatId: string): Promise<ChatPresence | null> {+ await this.findOne(id);+ return this.presence.get(id, chatId);+ }+async sendSeen(id: string, chatId: string): Promise<boolean> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex 646a70ab9..a2d1bfdc5 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -49,6 +49,7 @@ export const WEBHOOK_EVENTS = ['session.disconnected','session.reconnect_loop','session.restriction',+ 'presence.update','group.join','group.leave','group.update',diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex 4cba9ae1c..c0628d426 100644--- a/src/modules/webhook/utils/idempotency.util.ts+++ b/src/modules/webhook/utils/idempotency.util.ts@@ -96,6 +96,13 @@ export function generateIdempotencyKey(event: string, data: Record<string, unkno// would dedupe exactly that.return `restr_${toStr(data.sessionId)}_${toStr(data.kind)}_${toStr(data.active)}${occurrence}`;+ case 'presence.update':+ // Keyed on the chat and salted per occurrence. Only genuine state CHANGES are dispatched, and+ // a contact who types, stops, and types again produces the same payload each time — content+ // hashing would collapse that back into one delivery and hide the very transitions the event+ // exists to report.+ return `pres_${toStr(data.sessionId)}_${toStr(data.chatId)}${occurrence}`;+case 'group.join':// A membership change carries no unique id and repeats with identical content (the same user// leaves and rejoins the same group). Key on the affected participants and salt with