Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(pacing): gate forwards, stop counting answered chats as cold, and tag bulk pacing refusals
Yudhi Armyndharis75bec8d23855
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dd040a1f4..cf6e158f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.+- **Send pacing accounting:** forwards now pass through the cold-reachout gate (they were ungated while still draining the budget), replying to someone who wrote first today no longer spends the cold budget, and a pacing 429 inside a bulk batch is recorded as `SEND_PACING_LIMITED` instead of a generic `SEND_FAILED`.- **Multi-node: a session claim could outlive its engine and pin the session to one node forever.** A failed start, a logout, a force-kill or an exhausted reconnect kept the ownership claim, and the heartbeat renewed it indefinitely — the session could not be started on any peer and the takeover sweep never saw it. Claims are now released on every teardown path, and the heartbeat only renews claims that still cover a live engine, an in-flight start or a pending reconnect. Starting a nonexistent session also answers 404 again instead of a misleading 409 "running on another node".- Corrected column names in `docs/05-database-design.md`.diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 0c355c8b1..8bb31e16b 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -224,6 +224,15 @@ describe('sanitizeBatchError', () => {const result = sanitizeBatchError(new Error('Session is not active'));expect(result).toEqual({ code: 'SEND_FAILED', message: 'Session is not active' });});++ it('keeps the pacing code, so a policy 429 is distinguishable from an engine refusal', () => {+ const refusal = new HttpException(+ { statusCode: 429, message: 'Daily send allowance of 20 reached', code: 'SEND_PACING_LIMITED' },+ 429,+ );+ const result = sanitizeBatchError(refusal);+ expect(result).toEqual({ code: 'SEND_PACING_LIMITED', message: 'Daily send allowance of 20 reached' });+ });});describe('BulkMessageService.processBatch', () => {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex 75cdc3288..ec0a00844 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -20,7 +20,7 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';import { MessageStatus } from './entities/message.entity';import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageService } from './message.service';-import { SendPacingService, isPacingLimitedError } from './send-pacing.service';+import { SendPacingService, isPacingLimitedError, SEND_PACING_LIMITED } from './send-pacing.service';import { SessionOwnershipService } from '../session/session-ownership.service';import { HookManager } from '../../core/hooks';import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';@@ -59,12 +59,16 @@ export function resolveFinalBatchStatus(/*** Build the error stored on a batch result. An SSRF block names the internal host/IP it refused, so* it must never be persisted/returned verbatim — it would be readable via GET batch status. Map it to- * a generic, code-tagged message; ordinary errors keep their (non-sensitive) message.+ * a generic, code-tagged message; a pacing refusal keeps its own code so batch results distinguish+ * policy 429s from engine refusals; ordinary errors keep their (non-sensitive) message.*/export function sanitizeBatchError(error: unknown): { code: string; message: string } {if (error instanceof SsrfBlockedError) {return { code: 'SEND_BLOCKED', message: SSRF_BLOCKED_CLIENT_MESSAGE };}+ if (isPacingLimitedError(error)) {+ return { code: SEND_PACING_LIMITED, message: error instanceof Error ? error.message : String(error) };+ }return { code: 'SEND_FAILED', message: error instanceof Error ? error.message : String(error) };}diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 8fd32d7f3..723b98f71 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1188,6 +1188,20 @@ describe('MessageService', () => {}),);});++ it('gates the forward against pacing by its destination chat', async () => {+ // ForwardMessageDto has no `chatId` — the gate must fall back to `toChatId`, or forwards skip+ // the cold-reachout rule entirely while their persisted row still drains the cold budget.+ const { assertSendAllowed } = (service as unknown as { pacing: { assertSendAllowed: jest.Mock } }).pacing;++ await service.forward('sess-1', {+ fromChatId: '[email protected]',+ toChatId: '[email protected]',+ messageId: 'wa-msg-to-fwd',+ });++ expect(assertSendAllowed).toHaveBeenCalledWith('sess-1', '[email protected]');+ });});// ── saveIncomingMessage ───────────────────────────────────────────diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 17fcb5be7..ba211d5f9 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -171,9 +171,12 @@ export class MessageService {// not going to be sent. The consequence is deliberate and documented in the hook contract: a// paced-out send fires no `message:sending`, so a plugin cannot observe it. Refusals are a 429// carrying `code: SEND_PACING_LIMITED`; a plugin veto stays a 400.- // Every gated sender's DTO carries `chatId` except `edit`, which addresses a message rather than- // a chat — and editing is never a reachout, so having no chatId there is exactly right.- await this.pacing.assertSendAllowed(sessionId, (input as { chatId?: string }).chatId);+ // Every gated sender's DTO addresses its destination as `chatId` except forward, which uses+ // `toChatId` — without the fallback a forward skipped the cold-reachout gate entirely, while+ // its persisted row still drained the cold budget. Edit carries a chatId too; the edited+ // message's own row already makes that chat warm, so the gate is a no-op there.+ const target = input as { chatId?: string; toChatId?: string };+ await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');}diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.tsindex 83d1bbc11..7b787f8d6 100644--- a/src/modules/message/send-pacing-cold-query.spec.ts+++ b/src/modules/message/send-pacing-cold-query.spec.ts@@ -88,6 +88,25 @@ describe('cold-reachout counting against a real database', () => {await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();});+ // The class rule — answering someone who wrote first is not a reachout — must hold for the+ // AGGREGATE too, not just the per-send probe. A reply to a chat whose first-ever message arrived+ // today used to inflate the count and spend budget the account never used.+ it('does not count a reply to someone who wrote first today toward the cold budget', async () => {+ // They wrote first this morning; we answered. A new chat, but an answered one.+ await addMessage('[email protected]', '2026-08-03T08:00:00.000Z', MessageDirection.INCOMING);+ await addMessage('[email protected]', TODAY);+ // Genuine reachouts: we wrote first — one even got a reply, which keeps it OUR reachout.+ await addMessage('[email protected]', TODAY);+ await addMessage('[email protected]', TODAY);+ await addMessage('[email protected]', '2026-08-03T10:00:00.000Z', MessageDirection.INCOMING);++ // Two of three used: the answered chat did not count, the replied-to reachout still does.+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();++ await addMessage('[email protected]', TODAY);+ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });+ });+it("does not count another session's reachouts", async () => {await ds.query(`INSERT INTO "messages" ("id","sessionId","chatId","from","to","type","direction","createdAt")diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 8e2b77b07..450a7f7a0 100644--- a/src/modules/message/send-pacing.service.ts+++ b/src/modules/message/send-pacing.service.ts@@ -361,9 +361,11 @@ export class SendPacingService {}/**- * Distinct chats this session started today: it sent to them today, and nothing in the chat- * predates today. Expressed as a NOT EXISTS rather than a `MIN(createdAt)` group-by so it stays on- * the `(sessionId, createdAt)` and `chatId` indexes instead of grouping the whole table.+ * Distinct chats this session started today: it sent to them today, nothing in the chat predates+ * today, and nobody wrote to it first — a chat whose counterpart messaged earlier the same day is+ * an answered conversation, not a reachout (the "cold" rule above), however new the chat is.+ * Expressed as NOT EXISTS probes so the outer query stays on the `(sessionId, createdAt)` and+ * `chatId` indexes; the only aggregate is a per-chat MIN over today's outgoing rows.*/private countColdReachoutsToday(sessionId: string, dayStart: Date): Promise<number> {return (@@ -379,6 +381,12 @@ export class SendPacingService {.andWhere('NOT EXISTS (SELECT 1 FROM "messages" p WHERE p."sessionId" = :sessionId AND p."chatId" = m."chatId" AND p."createdAt" < :dayStart)',)+ // They wrote first: an incoming row strictly earlier than today's first outgoing one makes+ // the chat an answered conversation, not a cold start. A tie stays cold (conservative).+ .andWhere(+ 'NOT EXISTS (SELECT 1 FROM "messages" i WHERE i."sessionId" = :sessionId AND i."chatId" = m."chatId" AND i."direction" = :incoming AND i."createdAt" < (SELECT MIN(o."createdAt") FROM "messages" o WHERE o."sessionId" = :sessionId AND o."chatId" = m."chatId" AND o."direction" = :direction AND o."createdAt" >= :dayStart))',+ { incoming: MessageDirection.INCOMING },+ ).getRawOne<{ count: string | number }>().then(row => Number(row?.count ?? 0)));