Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(calls): publish what happened to a ringing call
Yudhi Armyndharis302085221724
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 29da2c05b..f80f7c5ae 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+- **Call outcomes: `call.accepted`, `call.rejected`, `call.missed`** — webhook and socket events for+ what happened to a ringing call, correlated to the preceding `call.received` by `callId`. Modelled+ in the JavaScript, Python, Go and Java SDKs.++ **Baileys only.** whatsapp-web.js hooks the insert into WhatsApp Web's call collection and receives+ no status at all, so it can announce a ring but never its outcome — there is nothing to wire.++ Three events rather than one carrying an outcome field, so a consumer that only cares about missed+ calls can subscribe to exactly that.++ Two things are reported honestly rather than guessed. The engines say *what* happened but not *who*+ did it — an accept can come from any of the account's linked devices — so nothing is attributed.+ And WhatsApp's `terminate` is deliberately left unmapped: it covers both a caller hanging up before+ the call was answered and either side ending an answered one, with nothing in the event to separate+ them, so publishing it as an outcome would be wrong about half the time.++ An outcome is only published for a call this session actually saw ring, and offline-replayed+ signalling — WhatsApp resends the traffic for calls that ended while a session was disconnected —+ is dropped, so a reconnect cannot announce last week's declined call as if it had just happened.+ The cached call handle is released at the same time, so a `reject` arriving after the call ended+ now reports not-found instead of acting on a dead call.+- **Channel administration: create, delete, mute.** `POST /api/sessions/:sessionId/channels`,`POST .../channels/:channelId/delete` and `POST .../channels/:channelId/mute`, in all five SDKs.diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsxindex a94c5af72..303a6ab48 100644--- a/dashboard/src/pages/Webhooks.tsx+++ b/dashboard/src/pages/Webhooks.tsx@@ -108,6 +108,9 @@ const availableEventNames = ['group.leave','group.update','call.received',+ 'call.accepted',+ 'call.rejected',+ 'call.missed','status.received','*',] as const;diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 970286cb9..528f8ffa9 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -400,7 +400,10 @@ CREATE TABLE webhooks ("group.join","group.leave","group.update",- "call.received"+ "call.received",+ "call.accepted",+ "call.rejected",+ "call.missed"]```diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex e9b8e6699..842f47160 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -3757,7 +3757,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`, `presence.update`, `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`, `call.accepted`, `call.rejected`, `call.missed`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by the engines.#### GET /api/sessions/:sessionId/webhooks@@ -5709,6 +5709,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve| `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` || `group.update` | Group metadata changes (subject, description, announce/locked settings) | `{ groupId, actorId?, participantIds, changes?, timestamp }` — `changes` carries only the fields that changed: `subject?`, `description?`, `announce?`, `locked?` || `call.received` | An incoming voice/video call starts ringing | `{ callId, from, isVideo, isGroup, timestamp }` — `callId` is the id to pass to `POST /sessions/:sessionId/calls/:callId/reject` |+| `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended — answered, declined, or never picked up. **Baileys only**: whatsapp-web.js hooks the call collection's insert and sees no status at all, so it can report the ring but never its outcome | `{ sessionId, callId, from, outcome, isVideo, isGroup, timestamp }` — `callId` matches the `call.received` that preceded it, so the pair can be correlated. The engines report *what* happened, never *who* did it: an accept can come from any linked device. An outcome is only sent for a call this session saw ring, and offline-replayed signalling for calls that ended while disconnected is dropped. WhatsApp's `terminate` is deliberately unmapped — it covers both a caller hanging up before answer and either side ending an answered call, with nothing to tell them apart || `status.received` | A contact posts a status/story (opt-in — see below) | `{ sessionId, statusId, contact: { id, name?, pushName? }, type, caption?, hasMedia, mediaOmitted, omitReason?, postedAt, expiresAt }` — `statusId` is the store's `id` (usable with the status endpoints below); `postedAt`/`expiresAt` are epoch **milliseconds** (unlike the epoch-seconds convention for message timestamps), matching the `GET /status` store's own `Date`-backed fields |> **`status.received` is opt-in and carries no media blob.** Unlike every other event above, `status.received` is only delivered to a webhook whose `events` list explicitly includes `"status.received"` (or `"*"`) — registering for other events does not implicitly subscribe you to it. The payload never embeds media bytes: when `hasMedia` is `true`, fetch the file separately via `GET /api/sessions/:sessionId/status/:statusId/media`. Your own posted statuses never trigger this event — only inbound stories from contacts (an own-send echo is dropped before ingest).diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 7f0261e80..99e02eb3e 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -1102,6 +1102,9 @@ available_events:- 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)+ - call.accepted # A ringing call was answered (Baileys only; payload: sessionId, callId, from, outcome, isVideo, isGroup, timestamp)+ - call.rejected # A ringing call was declined (Baileys only)+ - call.missed # A ringing call was never picked up (Baileys only)# Groups- group.join # Participant(s) added/joineddiff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.mdindex f06c67e13..e10986baa 100644--- a/docs/22-n8n-integration.md+++ b/docs/22-n8n-integration.md@@ -90,6 +90,7 @@ Start workflows when WhatsApp events occur.| `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 |+| `call.accepted` / `call.rejected` / `call.missed` | A ringing call ended | Missed-call follow-up, call logging || `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/openapi.json b/openapi.jsonindex 6d0dc8ffc..6b522d1a6 100644--- a/openapi.json+++ b/openapi.json@@ -7522,6 +7522,9 @@"group.leave","group.update","call.received",+ "call.accepted",+ "call.rejected",+ "call.missed","*"]}@@ -7670,6 +7673,9 @@"group.leave","group.update","call.received",+ "call.accepted",+ "call.rejected",+ "call.missed","*"]}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 1e82efaeb..5e47575d0 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -991,6 +991,9 @@ func TestWebhookEventWireValues(t *testing.T) {EventSessionReconnectLoop: "session.reconnect_loop",EventSessionRestriction: "session.restriction",EventPresenceUpdate: "presence.update",+ EventCallAccepted: "call.accepted",+ EventCallRejected: "call.rejected",+ EventCallMissed: "call.missed",EventGroupJoin: "group.join",EventGroupLeave: "group.leave",EventGroupUpdate: "group.update",diff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.goindex e8c670e10..f46ca86be 100644--- a/sdk/go/types_webhook.go+++ b/sdk/go/types_webhook.go@@ -23,6 +23,9 @@ const (EventSessionReconnectLoop WebhookEvent = "session.reconnect_loop"EventSessionRestriction WebhookEvent = "session.restriction"EventPresenceUpdate WebhookEvent = "presence.update"+ EventCallAccepted WebhookEvent = "call.accepted"+ EventCallRejected WebhookEvent = "call.rejected"+ EventCallMissed WebhookEvent = "call.missed"EventGroupJoin WebhookEvent = "group.join"EventGroupLeave WebhookEvent = "group.leave"EventGroupUpdate WebhookEvent = "group.update"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 ef3024cfd..5de83fe30 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@@ -36,6 +36,12 @@ public enum WebhookEvent {SESSION_RESTRICTION,@SerializedName("presence.update")PRESENCE_UPDATE,+ @SerializedName("call.accepted")+ CALL_ACCEPTED,+ @SerializedName("call.rejected")+ CALL_REJECTED,+ @SerializedName("call.missed")+ CALL_MISSED,@SerializedName("group.join")GROUP_JOIN,@SerializedName("group.leave")diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex d32f54e2b..b441dad95 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -650,6 +650,9 @@ export type WebhookEvent =| 'session.reconnect_loop'| 'session.restriction'| 'presence.update'+ | 'call.accepted'+ | 'call.rejected'+ | 'call.missed'| 'group.join'| 'group.leave'| 'group.update'diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex b3652b258..a78dc4ecc 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -32,6 +32,7 @@ WebhookEvent = Literal["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",+ "call.accepted", "call.rejected", "call.missed","*",]diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.tsindex 396414e7a..7c07ace13 100644--- a/src/engine/adapters/baileys-events.spec.ts+++ b/src/engine/adapters/baileys-events.spec.ts@@ -110,6 +110,7 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHostgetOnGroupEvent: () => undefined,getOnCall: () => undefined,getOnPresenceUpdate: () => undefined,+ getOnCallOutcome: () => undefined,...overrides,};}diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex c5230f1e9..8f6f85a94 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -7,6 +7,7 @@ import {IncomingCallEvent,ParticipantPresence,PresenceState,+ CallOutcome,IncomingMessage,ReactionEvent,RevokedMessage,@@ -41,6 +42,17 @@ 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 call statuses that mean something to a consumer. Everything else Baileys emits — `ringing`,+ * `preaccept`, `transport`, `relaylatency` — is transport chatter, and `terminate` is ambiguous+ * (see reportCallOutcome), so neither is mapped.+ */+const CALL_OUTCOMES: Readonly<Partial<Record<string, CallOutcome>>> = {+ accept: 'accepted',+ reject: 'rejected',+ timeout: 'missed',+};+/** The slice of Baileys' PresenceData this adapter reads. */interface RawPresence {lastKnownPresence?: PresenceState;@@ -101,6 +113,8 @@ export interface BaileysEventsHost {getOnCall(): EngineEventCallbacks['onCall'];/** The currently-registered onPresenceUpdate callback, if any (assigned at initialize()). */getOnPresenceUpdate(): EngineEventCallbacks['onPresenceUpdate'];+ /** The currently-registered onCallOutcome callback, if any (assigned at initialize()). */+ getOnCallOutcome(): EngineEventCallbacks['onCallOutcome'];}export class BaileysEvents {@@ -408,7 +422,14 @@ export class BaileysEvents {*/handleCallEvents(calls: WACallEvent[]): void {for (const call of Array.isArray(calls) ? calls : []) {- if (!call || call.status !== 'offer' || !call.id || !call.from) {+ if (!call || !call.id || !call.from) {+ continue;+ }+ // An ended call takes its own path and returns. It must never fall through to the offer+ // handling below: a declined call arriving there would be published as a fresh incoming call+ // and, with auto-reject enabled, answered as one.+ if (call.status !== 'offer') {+ this.reportCallOutcome(call);continue;}// Baileys replays offers for calls missed while disconnected with offline: true@@ -453,6 +474,48 @@ export class BaileysEvents {}}+ /**+ * Publish the end of a ringing call.+ *+ * Only the three statuses that mean something to a consumer are mapped. WhatsApp also sends+ * `ringing`, `preaccept`, `transport` and `relaylatency` — transport-level chatter with no+ * user-visible meaning — and `terminate`, which covers both a caller hanging up before the call+ * was answered and either side ending an answered one, with nothing in the event to tell them+ * apart. Publishing `terminate` as an outcome would therefore be wrong roughly half the time.+ *+ * The cached live-call handle is dropped here rather than left to expire: the call is over, and a+ * `rejectCall` arriving afterwards should report not-found instead of acting on a dead call.+ */+ private reportCallOutcome(call: WACallEvent): void {+ const outcome = CALL_OUTCOMES[call.status];+ if (!outcome) return;++ const live = this.liveCalls.get(call.id);+ this.liveCalls.delete(call.id);++ // Offline replay is the same hazard as on the offer path: WhatsApp resends the signalling for+ // calls that ended while this session was disconnected, and announcing those as fresh outcomes+ // would report last week's declined call as if it just happened.+ if (call.offline) return;++ // An outcome for a call this session never saw ring is not actionable — it belongs to another+ // device's conversation, or predates the connection — and would arrive with no caller identity+ // beyond the raw jid. Dropping it keeps the event stream to calls the consumer already knows.+ if (!live) return;++ this.host.getOnCallOutcome()?.({+ callId: call.id,+ from: this.host.toNeutralJid(call.callerPn ?? call.from),+ outcome,+ isVideo: call.isVideo === true,+ isGroup: call.isGroup === true,+ timestamp:+ call.date instanceof Date && !Number.isNaN(call.date.getTime())+ ? Math.floor(call.date.getTime() / 1000)+ : Math.floor(Date.now() / 1000),+ });+ }+/*** Map Baileys' `presence.update` onto the neutral event.*diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex a25ab2c0f..c4b631534 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4476,3 +4476,127 @@ describe('BaileysAdapter channel administration', () => {expect(fakeSock.newsletterUnmute).toHaveBeenCalledWith(CHANNEL);});});++// The load-bearing risk here is an ended call re-entering the incoming-call path: a decline would+// then be published as a fresh ring and, with auto-reject on, answered as one.+describe('BaileysAdapter call outcomes', () => {+ const CALL_ID = 'CALL-1';+ const CALLER = '[email protected]';++ beforeEach(() => {+ fakeSock.user = undefined;+ fakeSock.resetEmitter();+ jest.clearAllMocks();+ });++ /** Drive a ring first: an outcome for a call this session never saw is deliberately dropped. */+ const ringing = async (callbacks: Record<string, jest.Mock>) => {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks(callbacks));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.fire('connection.update', { connection: 'open' });+ fakeSock.fire('call', [+ {+ id: CALL_ID,+ from: CALLER,+ chatId: CALLER,+ status: 'offer',+ offline: false,+ date: new Date(1700000000000),+ isVideo: true,+ },+ ]);+ callbacks.onCall?.mockClear();+ return adapter;+ };++ it.each([+ ['accept', 'accepted'],+ ['reject', 'rejected'],+ ['timeout', 'missed'],+ ])('publishes %s as the %s outcome, and never as a new ring', async (status, outcome) => {+ const onCall = jest.fn();+ const onCallOutcome = jest.fn();+ await ringing({ onCall, onCallOutcome });++ fakeSock.fire('call', [+ {+ id: CALL_ID,+ from: CALLER,+ chatId: CALLER,+ status,+ offline: false,+ date: new Date(1700000060000),+ isVideo: true,+ },+ ]);++ expect(onCallOutcome).toHaveBeenCalledWith({+ callId: CALL_ID,+ from: '[email protected]',+ outcome,+ isVideo: true,+ isGroup: false,+ timestamp: 1700000060,+ });+ // The whole point: an ended call must not look like an incoming one.+ expect(onCall).not.toHaveBeenCalled();+ });++ // ringing/preaccept/transport/relaylatency are transport chatter, and `terminate` cannot be told+ // apart from a hang-up after answering — publishing either would be noise or a wrong claim.+ it.each(['ringing', 'preaccept', 'transport', 'relaylatency', 'terminate'])(+ 'publishes nothing for %s',+ async status => {+ const onCall = jest.fn();+ const onCallOutcome = jest.fn();+ await ringing({ onCall, onCallOutcome });++ fakeSock.fire('call', [{ id: CALL_ID, from: CALLER, chatId: CALLER, status, offline: false, date: new Date() }]);++ expect(onCallOutcome).not.toHaveBeenCalled();+ expect(onCall).not.toHaveBeenCalled();+ },+ );++ // WhatsApp replays signalling for calls that ended while the session was disconnected. Announcing+ // those would report last week's declined call as if it had just happened.+ it('drops an offline-replayed outcome', async () => {+ const onCallOutcome = jest.fn();+ await ringing({ onCall: jest.fn(), onCallOutcome });++ fakeSock.fire('call', [+ { id: CALL_ID, from: CALLER, chatId: CALLER, status: 'reject', offline: true, date: new Date() },+ ]);++ expect(onCallOutcome).not.toHaveBeenCalled();+ });++ // An outcome for a call this session never saw ring belongs to another device's conversation or+ // predates the connection, and carries no caller identity worth publishing.+ it('drops an outcome for a call that never rang here', async () => {+ const onCallOutcome = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({ onCall: jest.fn(), onCallOutcome }));+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ fakeSock.fire('connection.update', { connection: 'open' });++ fakeSock.fire('call', [+ { id: 'UNKNOWN', from: CALLER, chatId: CALLER, status: 'reject', offline: false, date: new Date() },+ ]);++ expect(onCallOutcome).not.toHaveBeenCalled();+ });++ // The call is over, so the handle rejectCall would act on must go with it — otherwise a late+ // reject would be attempted against a dead call instead of reporting not-found.+ it('drops the live-call handle, so a later reject reports not-found', async () => {+ const adapter = await ringing({ onCall: jest.fn(), onCallOutcome: jest.fn() });++ fakeSock.fire('call', [+ { id: CALL_ID, from: CALLER, chatId: CALLER, status: 'accept', offline: false, date: new Date() },+ ]);++ await expect(adapter.rejectCall(CALL_ID)).rejects.toThrow(/CALL-1/);+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 04caecd18..1c7be58c9 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -133,6 +133,7 @@ export class BaileysAdapter implements IWhatsAppEngine {getOnGroupEvent: () => this.callbacks.onGroupEvent,getOnCall: () => this.callbacks.onCall,getOnPresenceUpdate: () => this.callbacks.onPresenceUpdate,+ getOnCallOutcome: () => this.callbacks.onCallOutcome,});this.groups = new BaileysGroups({ensureReady: () => this.ensureReady(),diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex b417c89ba..b951d39fd 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -583,6 +583,35 @@ export interface PresenceUpdateEvent {groupOnlineCount?: number;}+/**+ * How a ringing call ended.+ *+ * `terminate` is deliberately NOT mapped to an outcome. WhatsApp uses it both for a caller hanging+ * up before the call was answered and for either side ending an answered one, and the event carries+ * nothing that separates the two — reporting it as either would be wrong half the time. Telling+ * those apart needs call-duration tracking, which is its own piece of work.+ */+export type CallOutcome = 'accepted' | 'rejected' | 'missed';++/**+ * A call that was ringing has ended.+ *+ * The engines report the outcome but not WHO caused it: an accept can come from any of the account's+ * linked devices, and a reject can equally be the account declining or WhatsApp giving up. So this+ * says what happened to the call, never who did it.+ */+export interface CallOutcomeEvent {+ /** The same id the matching `onCall` offer carried. */+ callId: string;+ /** Neutral caller id. */+ from: string;+ outcome: CallOutcome;+ isVideo: boolean;+ isGroup: boolean;+ /** Unix seconds the outcome was reported (engine timestamp). */+ timestamp: number;+}+export interface EngineEventCallbacks {onQRCode?: (qr: string) => void;onReady?: (phone: string, pushName: string) => void;@@ -647,6 +676,12 @@ export interface EngineEventCallbacks {* which is why consumers keep the last reported state rather than querying for it.*/onPresenceUpdate?: (event: PresenceUpdateEvent) => void;+ /**+ * Fired when a call that was ringing ends — answered, declined, or never picked up. Distinct from+ * `onCall`, which announces the ring itself: an outcome must never re-enter that path, or a call+ * being declined would look like a fresh incoming call and (with auto-reject on) be answered.+ */+ onCallOutcome?: (event: CallOutcomeEvent) => void;/*** Fired on a terminal initialization/authentication failure (e.g. Chromium* could not launch, or WhatsApp rejected the stored credentials). The enginediff --git a/src/modules/events/dto/ws-messages.dto.ts b/src/modules/events/dto/ws-messages.dto.tsindex 89a6ceb8b..68dd7e7df 100644--- a/src/modules/events/dto/ws-messages.dto.ts+++ b/src/modules/events/dto/ws-messages.dto.ts@@ -29,6 +29,9 @@ export const SUBSCRIBABLE_EVENTS = ['call.received','status.received','presence.update',+ 'call.accepted',+ 'call.rejected',+ 'call.missed',] 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 98c5efd01..fd8e3a0d4 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -539,6 +539,25 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.emitToRooms(sessionId, 'session.disconnected', data);}+ /**+ * The end of a ringing call, one method per outcome.+ *+ * Three methods rather than one taking the name as a parameter: the drift guard discovers emitters+ * by reflection and invokes each with an empty payload, so a parameterised name would leave the+ * event catalog unverifiable — exactly the drift the guard exists to catch.+ */+ emitCallAccepted(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'call.accepted', data);+ }++ emitCallRejected(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'call.rejected', data);+ }++ emitCallMissed(sessionId: string, data: Record<string, unknown>) {+ this.emitToRooms(sessionId, 'call.missed', 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 indicatordiff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 1922224dd..1dc0ddf72 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -15,6 +15,7 @@ import {IncomingCallEvent,AccountRestriction,PresenceUpdateEvent,+ CallOutcomeEvent,} from '../../engine/interfaces/whatsapp-engine.interface';import { type createLogger } from '../../common/services/logger.service';import { SessionEngineLeafEvents } from './session-engine-leaf-events';@@ -220,6 +221,28 @@ export class SessionEngineEventWiring {host.sessionErrors.set(id, reason);void host.hookManager.execute('session:error', { reason }, { sessionId: id, source: 'Engine' });},+ onCallOutcome: (event: CallOutcomeEvent): void => {+ if (!host.isLiveEngine(id, engine)) return;+ this.logger.log(`Call ${event.outcome}: ${event.callId}`, {+ sessionId: id,+ callId: event.callId,+ outcome: event.outcome,+ action: 'call_outcome',+ });+ const payload: Record<string, unknown> = { sessionId: id, ...event };+ // One event per outcome rather than a single call.ended carrying a field: a consumer that+ // only cares about missed calls should be able to subscribe to exactly that.+ if (event.outcome === 'accepted') {+ host.eventsGateway.emitCallAccepted(id, payload);+ void host.webhookService.dispatch(id, 'call.accepted', payload);+ } else if (event.outcome === 'rejected') {+ host.eventsGateway.emitCallRejected(id, payload);+ void host.webhookService.dispatch(id, 'call.rejected', payload);+ } else {+ host.eventsGateway.emitCallMissed(id, payload);+ void host.webhookService.dispatch(id, 'call.missed', payload);+ }+ },onPresenceUpdate: (event: PresenceUpdateEvent): void => {if (!host.isLiveEngine(id, engine)) return;// WhatsApp reports presence on every transition and freely repeats itself, so only an actualdiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 836099164..59fd63755 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -163,6 +163,9 @@ describe('SessionService', () => {emitSessionAuthenticated: jest.fn(),emitSessionDisconnected: jest.fn(),emitPresenceUpdate: jest.fn(),+ emitCallAccepted: jest.fn(),+ emitCallRejected: jest.fn(),+ emitCallMissed: jest.fn(),emitMessage: jest.fn(),emitMessageSent: jest.fn(),emitMessageAck: jest.fn(),@@ -2280,6 +2283,53 @@ describe('SessionService', () => {});});+ // Three events rather than one carrying an outcome field, so a consumer that only cares about+ // missed calls can subscribe to exactly that.+ describe('engine call outcomes', () => {+ const outcomeEvent = (outcome: 'accepted' | 'rejected' | 'missed') => ({+ callId: 'CALL-1',+ from: '[email protected]',+ outcome,+ isVideo: false,+ isGroup: false,+ timestamp: 1700000000,+ });++ 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.each([+ ['accepted', 'call.accepted', 'emitCallAccepted'],+ ['rejected', 'call.rejected', 'emitCallRejected'],+ ['missed', 'call.missed', 'emitCallMissed'],+ ])('publishes %s on its own event name', async (outcome, eventName, emitter) => {+ const callbacks = await startAndCapture();+ (webhookService.dispatch as jest.Mock).mockClear();++ callbacks.onCallOutcome?.(outcomeEvent(outcome as 'accepted'));++ const payload = { sessionId: 'sess-uuid-1', ...outcomeEvent(outcome as 'accepted') };+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', eventName, payload);+ expect(eventsGateway[emitter as 'emitCallAccepted']).toHaveBeenCalledWith('sess-uuid-1', payload);+ });++ // An outcome must never be published as a fresh ring — that is the bug the adapter split guards,+ // and this pins the host half of it.+ it('never publishes an outcome as call.received', async () => {+ const callbacks = await startAndCapture();+ (webhookService.dispatch as jest.Mock).mockClear();++ callbacks.onCallOutcome?.(outcomeEvent('rejected'));++ expect(webhookService.dispatch).not.toHaveBeenCalledWith('sess-uuid-1', 'call.received', expect.anything());+ });+ });+// ── 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/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex a2d1bfdc5..8a8d1a71a 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -54,6 +54,9 @@ export const WEBHOOK_EVENTS = ['group.leave','group.update','call.received',+ 'call.accepted',+ 'call.rejected',+ 'call.missed',...WEBHOOK_RESERVED_EVENTS,] as const;diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.tsindex c0628d426..c44800205 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 'call.accepted':+ case 'call.rejected':+ case 'call.missed':+ // A call id is unique per call and each call ends exactly once, so (session, call, outcome)+ // is already distinct — no occurrence salt, matching call.received's stable key.+ return `call_${toStr(data.sessionId)}_${toStr(data.callId)}_${toStr(data.outcome)}`;+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