Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(session): add reconnect-loop observability and orphaned-Chromium sweep (#800)

Yudhi Armyndharis7f15266c6a76
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ed7d9560..269b4f68c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+
+- Reconnect-loop observability: every scheduled reconnect attempt is counted in the new
+ `openwa_session_reconnect_attempts_total` Prometheus counter, and every fifth consecutive attempt
+ of an episode emits a `session.reconnect_loop` webhook event (`{ sessionId, attempts, nextDelayMs }`),
+ a structured warning log, and an `openwa_session_reconnect_loop_alerts_total` counter tick — a
+ session stuck in a reconnect loop is now visible to operators instead of retrying silently forever.
+ The episode streak re-arms after a stable connection, so recovered sessions do not keep alerting.
+- The whatsapp-web.js engine now sweeps orphaned Chromium processes before each (re)launch: browsers
+ are started with an `--openwa-session=<id>` marker arg, and any leftover browser process carrying
+ this session's marker from a previous process lifetime (e.g. after the gateway itself was killed)
+ is terminated before the new launch, alongside the existing stale Singleton-file cleanup.
+
### Fixed
- Long-lived sessions no longer die permanently after hours of uptime. A dead whatsapp-web.js
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 9b493bb6c..d3242f670 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -361,6 +361,7 @@ CREATE TABLE webhooks (
"session.qr",
"session.authenticated",
"session.disconnected",
+ "session.reconnect_loop",
"group.join",
"group.leave",
"group.update"
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 1143112a5..12e97c5ca 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -2932,7 +2932,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`, `group.join`, `group.leave`, `group.update`. The `group.*` events are **reserved** — accepted and validated but never dispatched (no engine emit source).
+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`, `group.join`, `group.leave`, `group.update`. The `group.*` events are **reserved** — accepted and validated but never dispatched (no engine emit source).
#### GET /api/sessions/:sessionId/webhooks
@@ -4675,6 +4675,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` (raw QR string) |
| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
| `session.disconnected` | The session disconnects | `{ 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 }` |
| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `failed` |
> **`STORE_EPHEMERAL_MESSAGES=false` affects `message.received`.** When `STORE_EPHEMERAL_MESSAGES` is set to `false`, incoming disappearing messages (those with `ephemeralDuration > 0`) are **not** persisted nor dispatched — no DB insert, no webhook delivery, and no websocket event. Downstream consumers and the dashboard both stop seeing them. Default is `true` (backward compatible — store and dispatch everything).
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 271323ea8..ee7b6384f 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -996,6 +996,7 @@ available_events:
- session.qr # New QR code generated
- session.authenticated # Session authenticated
- session.disconnected # Session disconnected
+ - session.reconnect_loop # Every 5th consecutive reconnect attempt (payload: sessionId, attempts, nextDelayMs)
# Groups (reserved but NOT currently emitted — accepted in events list, never delivered)
- group.join # reserved, not emitted
diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.md
index 58ff7eab9..718d5e00f 100644
--- a/docs/22-n8n-integration.md
+++ b/docs/22-n8n-integration.md
@@ -86,6 +86,7 @@ Start workflows when WhatsApp events occur.
| `session.qr` | QR code generated | Reconnection alerts |
| `session.authenticated` | Session logged in (phone available) | Startup notifications |
| `session.disconnected` | Session lost connection | Alert monitoring |
+| `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting |
> **Reserved:** `group.join`, `group.leave`, and `group.update` are accepted by the
> subscription API but are not emitted yet — don't depend on them until a release notes
diff --git a/openapi.json b/openapi.json
index b33752de1..8b5ad8124 100644
--- a/openapi.json
+++ b/openapi.json
@@ -5891,6 +5891,7 @@
"session.qr",
"session.authenticated",
"session.disconnected",
+ "session.reconnect_loop",
"group.join",
"group.leave",
"group.update",
@@ -6034,6 +6035,7 @@
"session.qr",
"session.authenticated",
"session.disconnected",
+ "session.reconnect_loop",
"group.join",
"group.leave",
"group.update",
diff --git a/src/common/metrics/session-reconnect-metrics.spec.ts b/src/common/metrics/session-reconnect-metrics.spec.ts
new file mode 100644
index 000000000..d1ed39b1f
--- /dev/null
+++ b/src/common/metrics/session-reconnect-metrics.spec.ts
@@ -0,0 +1,45 @@
+import {
+ incrementSessionReconnectAttempts,
+ getSessionReconnectAttemptsTotal,
+ incrementSessionReconnectLoopAlerts,
+ getSessionReconnectLoopAlertsTotal,
+} from './session-reconnect-metrics';
+
+describe('session-reconnect-metrics', () => {
+ it('monotonically increments the reconnect-attempts total', () => {
+ const before = getSessionReconnectAttemptsTotal();
+ incrementSessionReconnectAttempts();
+ incrementSessionReconnectAttempts();
+ expect(getSessionReconnectAttemptsTotal()).toBe(before + 2);
+ });
+
+ it('reconnect-attempts total never decreases', () => {
+ const a = getSessionReconnectAttemptsTotal();
+ incrementSessionReconnectAttempts();
+ const b = getSessionReconnectAttemptsTotal();
+ expect(b).toBeGreaterThan(a);
+ });
+
+ it('monotonically increments the loop-alerts total', () => {
+ const before = getSessionReconnectLoopAlertsTotal();
+ incrementSessionReconnectLoopAlerts();
+ incrementSessionReconnectLoopAlerts();
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(before + 2);
+ });
+
+ it('loop-alerts total never decreases', () => {
+ const a = getSessionReconnectLoopAlertsTotal();
+ incrementSessionReconnectLoopAlerts();
+ const b = getSessionReconnectLoopAlertsTotal();
+ expect(b).toBeGreaterThan(a);
+ });
+
+ it('tracks attempts and alerts independently', () => {
+ const attemptsBefore = getSessionReconnectAttemptsTotal();
+ const alertsBefore = getSessionReconnectLoopAlertsTotal();
+ incrementSessionReconnectAttempts();
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(alertsBefore);
+ incrementSessionReconnectLoopAlerts();
+ expect(getSessionReconnectAttemptsTotal()).toBe(attemptsBefore + 1);
+ });
+});
diff --git a/src/common/metrics/session-reconnect-metrics.ts b/src/common/metrics/session-reconnect-metrics.ts
new file mode 100644
index 000000000..d4f8eb8b9
--- /dev/null
+++ b/src/common/metrics/session-reconnect-metrics.ts
@@ -0,0 +1,30 @@
+/**
+ * Process-local monotonic counters for session reconnect observability, incremented one-for-one in
+ * `SessionService.scheduleReconnect`. Kept as plain in-process counters rather than a `COUNT(*)` over
+ * any persisted table because reconnect scheduling itself is not persisted at all — there is no
+ * durable source to count, and a pruned/rotated one would be non-monotonic and therefore invalid as a
+ * Prometheus `counter` (a prune would look like a counter reset to `rate()`/`increase()`). An
+ * in-process counter only resets on restart, which those functions already handle correctly.
+ */
+let reconnectAttemptsTotal = 0;
+let reconnectLoopAlertsTotal = 0;
+
+/** Record one scheduled reconnect attempt (any session). */
+export function incrementSessionReconnectAttempts(): void {
+ reconnectAttemptsTotal += 1;
+}
+
+/** Current process-lifetime total of scheduled reconnect attempts. */
+export function getSessionReconnectAttemptsTotal(): number {
+ return reconnectAttemptsTotal;
+}
+
+/** Record one emitted reconnect-loop alert (every Nth consecutive attempt of a session). */
+export function incrementSessionReconnectLoopAlerts(): void {
+ reconnectLoopAlertsTotal += 1;
+}
+
+/** Current process-lifetime total of emitted reconnect-loop alerts. */
+export function getSessionReconnectLoopAlertsTotal(): number {
+ return reconnectLoopAlertsTotal;
+}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index ff3138374..6cb45ecd6 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -39,6 +39,11 @@ jest.mock('qrcode', () => ({
toDataURL: jest.fn(() => Promise.resolve('data:image/png;base64,FAKEQR')),
}));
+// Spying on child_process.execFile must target the real module exports: the TypeScript __importStar
+// namespace wrapper that `import * as childProcess` yields has non-configurable members, so
+// jest.spyOn cannot redefine execFile on it. The adapter reads execFile live off this same object.
+const childProcess = jest.requireActual<typeof import('child_process')>('child_process');
+
describe('wwebjsAckToDeliveryStatus (engine ack-int -> neutral DeliveryStatus boundary, #265)', () => {
// Regression-locks the integer boundary the decoupling moved behaviour into, incl. the
// PLAYED(4) -> 'read' collapse that the old ackToMessageStatus(4) -> READ test used to cover.
@@ -2492,6 +2497,177 @@ describe('WhatsAppWebJsAdapter stale Singleton cleanup (pre-launch)', () => {
});
});
+describe('WhatsAppWebJsAdapter orphaned Chromium sweep (pre-launch)', () => {
+ const SESSION_ID = 'sess-orphan';
+ const newAdapter = (): WhatsAppWebJsAdapter =>
+ new WhatsAppWebJsAdapter({ sessionId: SESSION_ID, sessionDataPath: './data/sessions', puppeteer: {} });
+
+ type ExecFileCallback = (error: Error | null, stdout: string, stderr: string) => void;
+
+ let execFileSpy: jest.SpyInstance;
+ let killSpy: jest.SpyInstance;
+ let rmSpy: jest.SpyInstance;
+ let clientInitSpy: jest.SpyInstance;
+ let savedWebVersion: string | undefined;
+
+ // execFile is overloaded, so spy through a structural shape like the Client.prototype spies above.
+ // The adapter invokes it as execFile('ps', args, opts, callback); the callback is always last.
+ const mockPsResult = (result: { stdout?: string; error?: Error }): void => {
+ execFileSpy.mockImplementation((...args: unknown[]) => {
+ const cb = args[args.length - 1] as ExecFileCallback;
+ cb(result.error ?? null, result.stdout ?? '', '');
+ });
+ };
+ // `ps -eo pid=,args=` rows: leading whitespace, pid, then the full command line.
+ const psTable = (rows: [number, string][]): string => rows.map(([pid, args]) => ` ${pid} ${args}`).join('\n') + '\n';
+ const loggerLogSpy = (adapter: WhatsAppWebJsAdapter): jest.SpyInstance => {
+ const logger = (adapter as unknown as { logger: { log: (message: string, context?: unknown) => void } }).logger;
+ return jest.spyOn(logger, 'log').mockImplementation(() => undefined);
+ };
+
+ beforeEach(() => {
+ // Keep initialize() offline: 'off' skips the wa-version registry fetch in resolveWebVersionPin.
+ savedWebVersion = process.env.WWEBJS_WEB_VERSION;
+ process.env.WWEBJS_WEB_VERSION = 'off';
+ // Default: an empty process table (nothing to sweep); tests override via mockPsResult.
+ execFileSpy = jest
+ .spyOn(childProcess as unknown as { execFile: (...args: unknown[]) => void }, 'execFile')
+ .mockImplementation((...args: unknown[]) => {
+ (args[args.length - 1] as ExecFileCallback)(null, '', '');
+ });
+ // Never let a test signal a real process.
+ killSpy = jest.spyOn(process, 'kill').mockImplementation(() => true);
+ rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ // Stub Client.prototype.initialize so the real wwebjs Client is built but no browser launches.
+ clientInitSpy = jest
+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')
+ .mockResolvedValue(undefined);
+ });
+
+ afterEach(() => {
+ execFileSpy.mockRestore();
+ killSpy.mockRestore();
+ rmSpy.mockRestore();
+ clientInitSpy.mockRestore();
+ if (savedWebVersion === undefined) {
+ delete process.env.WWEBJS_WEB_VERSION;
+ } else {
+ process.env.WWEBJS_WEB_VERSION = savedWebVersion;
+ }
+ });
+
+ it('appends the --openwa-session marker to the puppeteer args handed to the Client', async () => {
+ const adapter = newAdapter();
+
+ await adapter.initialize({});
+
+ const client = (adapter as unknown as { client: { options: { puppeteer?: { args?: string[] } } } }).client;
+ expect(client.options.puppeteer?.args).toContain(`--openwa-session=${SESSION_ID}`);
+ });
+
+ it('SIGKILLs a Chromium process carrying this session marker and logs the sweep', async () => {
+ mockPsResult({
+ stdout: psTable([
+ [
+ 1501,
+ `/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --headless --openwa-session=${SESSION_ID}`,
+ ],
+ [1502, '/usr/bin/node dist/main.js'],
+ ]),
+ });
+ const adapter = newAdapter();
+ const logSpy = loggerLogSpy(adapter);
+
+ await adapter.initialize({});
+
+ expect(execFileSpy).toHaveBeenCalledTimes(1);
+ // No shell: ps is exec'd directly with an argv array, an options object, and a callback.
+ expect(execFileSpy).toHaveBeenCalledWith('ps', ['-eo', 'pid=,args='], expect.any(Object), expect.any(Function));
+ expect(killSpy).toHaveBeenCalledTimes(1);
+ expect(killSpy).toHaveBeenCalledWith(1501, 'SIGKILL');
+ expect(logSpy).toHaveBeenCalledWith(
+ 'Killed 1 orphaned Chromium process(es) left over from a previous process lifetime',
+ {
+ sessionId: SESSION_ID,
+ pids: [1501],
+ },
+ );
+ });
+
+ it('does NOT kill a non-browser process that merely carries the marker string', async () => {
+ mockPsResult({
+ stdout: psTable([
+ [1601, `/bin/grep --openwa-session=${SESSION_ID}`],
+ [1602, `/usr/bin/node scan-sessions.js --openwa-session=${SESSION_ID}`],
+ ]),
+ });
+
+ await newAdapter().initialize({});
+
+ expect(killSpy).not.toHaveBeenCalled();
+ });
+
+ it('does NOT kill a Chromium process belonging to a different session', async () => {
+ mockPsResult({
+ stdout: psTable([[1701, '/usr/lib/chromium/chromium --headless --no-sandbox --openwa-session=session-lain']]),
+ });
+
+ await newAdapter().initialize({});
+
+ expect(killSpy).not.toHaveBeenCalled();
+ });
+
+ it('skips the sweep on platforms other than darwin/linux (no ps, no kill)', async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform') as PropertyDescriptor;
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ try {
+ await newAdapter().initialize({});
+ } finally {
+ Object.defineProperty(process, 'platform', platform);
+ }
+
+ expect(execFileSpy).not.toHaveBeenCalled();
+ expect(killSpy).not.toHaveBeenCalled();
+ });
+
+ it('still initializes when ps fails (best-effort, never fails the start)', async () => {
+ mockPsResult({ error: new Error('spawn ps ENOENT') });
+
+ await expect(newAdapter().initialize({})).resolves.toBeUndefined();
+
+ expect(killSpy).not.toHaveBeenCalled();
+ expect(clientInitSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs the orphan sweep before the Singleton cleanup and client.initialize()', async () => {
+ const order: string[] = [];
+ execFileSpy.mockImplementation((...args: unknown[]) => {
+ order.push('ps');
+ (args[args.length - 1] as ExecFileCallback)(
+ null,
+ psTable([[1801, `/usr/bin/chromium --headless --openwa-session=${SESSION_ID}`]]),
+ '',
+ );
+ });
+ killSpy.mockImplementation(() => {
+ order.push('kill');
+ return true;
+ });
+ rmSpy.mockImplementation(() => {
+ order.push('rm');
+ return Promise.resolve(undefined);
+ });
+ clientInitSpy.mockImplementation(() => {
+ order.push('client.initialize');
+ return Promise.resolve(undefined);
+ });
+
+ await newAdapter().initialize({});
+
+ expect(order).toEqual(['ps', 'kill', 'rm', 'rm', 'rm', 'client.initialize']);
+ });
+});
+
describe('WhatsAppWebJsAdapter page transport error detection (wedged page fast-path, wwebjs #5728)', () => {
const readyAdapter = (client: unknown): { adapter: WhatsAppWebJsAdapter; onDisconnected: jest.Mock } => {
const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index db3183cf7..4d4380a07 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -4,6 +4,7 @@ import { Client, LocalAuth, MessageMedia, MessageTypes, WAState, type Message }
import * as qrcode from 'qrcode';
import * as path from 'path';
import * as fs from 'fs';
+import { execFile } from 'child_process';
import {
IWhatsAppEngine,
EngineStatus,
@@ -409,6 +410,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
}
}
+ // Marker arg: Chromium silently ignores unknown flags, so this exists purely as a label that
+ // lets killOrphanedChromiumProcesses() identify this session's browser processes in `ps`
+ // output later (after a hard kill of the OpenWA process orphaned them).
+ puppeteerArgs.push(`--openwa-session=${this.config.sessionId}`);
+
// Pin the WA-Web version when configured (fixes the 1.34.x "stuck at authenticating"
// hang on some setups, #251). Opt-in: unset leaves whatsapp-web.js to auto-select.
const versionPin = await resolveWebVersionPin();
@@ -458,6 +464,11 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.setStatus(EngineStatus.DISCONNECTED);
return;
}
+ // Kill any Chromium that survived a hard kill of a previous OpenWA process lifetime (its
+ // Puppeteer exit hook never ran, leaving an orphaned browser holding the profile). Safe here
+ // for the same reason as the Singleton cleanup below: this runs only at engine (re)start,
+ // before this lifetime's browser exists, so it cannot kill a live browser.
+ await this.killOrphanedChromiumProcesses();
// Clear stale Chromium Singleton* files left by a hard kill before launching — see
// removeStaleSingletonFiles. This runs only at engine (re)start, never while
// the browser is alive, so it cannot pull the files out from under a running Chromium.
@@ -911,6 +922,63 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
});
}
+ /**
+ * SIGKILL any Chromium orphaned by a previous lifetime of this process. When OpenWA dies hard
+ * (kill -9, crash, host reboot) Puppeteer's exit hook never runs, so the browser survives as an
+ * orphan — leaking memory and pinning the session profile dir. Orphans are identified by the
+ * `--openwa-session=<id>` marker arg appended to the puppeteer args at launch (Chromium ignores
+ * the unknown flag; it is purely a `ps` label). Best-effort: never throws — a `ps` failure only
+ * logs at debug, so the sweep can never block an engine start.
+ */
+ private async killOrphanedChromiumProcesses(): Promise<void> {
+ if (process.platform !== 'darwin' && process.platform !== 'linux') {
+ this.logger.debug(`Skipping orphaned Chromium sweep: unsupported platform ${process.platform}`);
+ return;
+ }
+ try {
+ // No shell: the args array is handed to ps verbatim, so nothing here is injectable.
+ // maxBuffer is raised because `ps -eo args` prints full command lines, which on a busy host
+ // (many Chromium renderers carrying dozens of flags each) can exceed the 1MB default.
+ const psOutput = await new Promise<string>((resolve, reject) => {
+ execFile('ps', ['-eo', 'pid=,args='], { maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
+ // The @types/node ExecFileException is an Omit<> of ErrnoException, which the type
+ // checker no longer recognises as an Error — narrow it explicitly for the reject.
+ if (error) reject(error instanceof Error ? error : new Error(error.message));
+ else resolve(stdout);
+ });
+ });
+ const marker = `--openwa-session=${this.config.sessionId}`;
+ const killedPids: number[] = [];
+ for (const line of psOutput.split('\n')) {
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
+ if (!match) continue;
+ const pid = Number(match[1]);
+ const args = match[2];
+ if (pid === process.pid || !args.includes(marker)) continue;
+ // Never kill a non-browser process that happens to carry the marker string
+ // (e.g. a `grep --openwa-session=…` probing the process table).
+ if (!/chrome|chromium|headless/i.test(args)) continue;
+ try {
+ process.kill(pid, 'SIGKILL');
+ killedPids.push(pid);
+ } catch (error) {
+ // ESRCH: the process exited between `ps` and the kill — nothing left to do.
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
+ this.logger.debug(`Could not SIGKILL orphaned Chromium pid ${pid}`, { error: String(error) });
+ }
+ }
+ }
+ if (killedPids.length > 0) {
+ this.logger.log(
+ `Killed ${killedPids.length} orphaned Chromium process(es) left over from a previous process lifetime`,
+ { sessionId: this.config.sessionId, pids: killedPids },
+ );
+ }
+ } catch (error) {
+ this.logger.debug('Could not enumerate processes for the orphaned Chromium sweep', { error: String(error) });
+ }
+ }
+
/**
* Remove Chromium's SingletonLock/SingletonSocket/SingletonCookie from the LocalAuth profile dir
* (same dir clearLocalAuth removes) before the browser launches. A hard-killed Chromium
diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.ts
index c2264fb41..097ecd6a7 100644
--- a/src/modules/metrics/metrics.service.spec.ts
+++ b/src/modules/metrics/metrics.service.spec.ts
@@ -3,6 +3,10 @@ import { ConfigService } from '@nestjs/config';
import { MetricsService, METRICS_RENDER_TTL_MS } from './metrics.service';
import { StatsService, OverviewStats } from '../stats/stats.service';
import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
+import {
+ getSessionReconnectAttemptsTotal,
+ getSessionReconnectLoopAlertsTotal,
+} from '../../common/metrics/session-reconnect-metrics';
describe('MetricsService', () => {
const overview: OverviewStats = {
@@ -62,6 +66,11 @@ describe('MetricsService', () => {
// Webhook terminal-failure counter is emitted with correct counter typing + current total.
expect(out).toContain('# TYPE openwa_webhook_delivery_failures_total counter');
expect(out).toContain(`openwa_webhook_delivery_failures_total ${getWebhookDeliveryFailuresTotal()}`);
+ // Reconnect observability counters are emitted with correct counter typing + current totals.
+ expect(out).toContain('# TYPE openwa_session_reconnect_attempts_total counter');
+ expect(out).toContain(`openwa_session_reconnect_attempts_total ${getSessionReconnectAttemptsTotal()}`);
+ expect(out).toContain('# TYPE openwa_session_reconnect_loop_alerts_total counter');
+ expect(out).toContain(`openwa_session_reconnect_loop_alerts_total ${getSessionReconnectLoopAlertsTotal()}`);
expect(out.endsWith('\n')).toBe(true);
});
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index e7e9f5e1c..a58ab6939 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -3,6 +3,10 @@ import { ConfigService } from '@nestjs/config';
import { timingSafeEqual } from 'crypto';
import { StatsService } from '../stats/stats.service';
import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
+import {
+ getSessionReconnectAttemptsTotal,
+ getSessionReconnectLoopAlertsTotal,
+} from '../../common/metrics/session-reconnect-metrics';
import { renderHttpRequestMetrics } from '../../common/metrics/request-metrics';
/**
@@ -105,6 +109,16 @@ export class MetricsService {
lines.push('# TYPE openwa_webhook_delivery_failures_total counter');
lines.push(`openwa_webhook_delivery_failures_total ${getWebhookDeliveryFailuresTotal()}`);
+ lines.push(
+ '# HELP openwa_session_reconnect_attempts_total Reconnect attempts scheduled across all sessions since process start.',
+ );
+ lines.push('# TYPE openwa_session_reconnect_attempts_total counter');
+ lines.push(`openwa_session_reconnect_attempts_total ${getSessionReconnectAttemptsTotal()}`);
+
+ lines.push('# HELP openwa_session_reconnect_loop_alerts_total Reconnect-loop alerts emitted since process start.');
+ lines.push('# TYPE openwa_session_reconnect_loop_alerts_total counter');
+ lines.push(`openwa_session_reconnect_loop_alerts_total ${getSessionReconnectLoopAlertsTotal()}`);
+
// HTTP RED metrics (request rate + duration per route), recorded by RequestMetricsInterceptor.
// Included in the same cached render — a few seconds of staleness is fine for Prometheus.
lines.push(...renderHttpRequestMetrics());
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index ed7ae113d..6c48a44ad 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -22,6 +22,10 @@ import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
import { IncomingMessage, EngineEventCallbacks, EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';
import { BaileysSessionStore } from '../../engine/adapters/baileys-session-store';
+import {
+ getSessionReconnectAttemptsTotal,
+ getSessionReconnectLoopAlertsTotal,
+} from '../../common/metrics/session-reconnect-metrics';
function createMockSession(overrides: Partial<Session> = {}): Session {
return {
@@ -910,6 +914,123 @@ describe('SessionService', () => {
});
});
+ describe('scheduleReconnect (reconnect-loop observability)', () => {
+ type LoopInternals = {
+ reconnectStates: Map<
+ string,
+ {
+ attempts: number;
+ timer: NodeJS.Timeout | null;
+ maxAttempts: number;
+ baseDelay: number;
+ lastAttemptAt?: number;
+ }
+ >;
+ scheduleReconnect: (id: string, session: Session) => void;
+ };
+ const internals = (): LoopInternals => service as unknown as LoopInternals;
+ const loopDispatches = (): unknown[][] =>
+ ((webhookService.dispatch as jest.Mock).mock.calls as unknown[][]).filter(c => c[1] === 'session.reconnect_loop');
+
+ it('counts every scheduled attempt but emits no loop alert on attempts 1..4', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ const state = { attempts: 0, timer: null, maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 5000 };
+ i.reconnectStates.set('sess-uuid-1', state);
+
+ const attemptsBefore = getSessionReconnectAttemptsTotal();
+ const alertsBefore = getSessionReconnectLoopAlertsTotal();
+
+ for (let k = 0; k < 4; k++) {
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ }
+
+ expect(state.attempts).toBe(4);
+ // One counter tick per scheduled attempt.
+ expect(getSessionReconnectAttemptsTotal()).toBe(attemptsBefore + 4);
+ // ...but the loop alert only arms at attempt 5 — no dispatch, no alert tick before that.
+ expect(loopDispatches()).toHaveLength(0);
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(alertsBefore);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('alerts on attempts 5 and 10 with the loop payload (one signal per 5 consecutive attempts)', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ const state = { attempts: 0, timer: null, maxAttempts: Number.POSITIVE_INFINITY, baseDelay: 5000 };
+ i.reconnectStates.set('sess-uuid-1', state);
+
+ const attemptsBefore = getSessionReconnectAttemptsTotal();
+ const alertsBefore = getSessionReconnectLoopAlertsTotal();
+
+ for (let k = 0; k < 10; k++) {
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ }
+
+ expect(getSessionReconnectAttemptsTotal()).toBe(attemptsBefore + 10);
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(alertsBefore + 2);
+
+ const calls = loopDispatches();
+ expect(calls).toHaveLength(2);
+ // Attempt 5: the delay was computed with attempts=4 → 5000*2^4 = 80s (+ <1s jitter).
+ expect(calls[0][0]).toBe('sess-uuid-1');
+ expect(calls[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 5 });
+ expect((calls[0][2] as { nextDelayMs: number }).nextDelayMs).toBeGreaterThanOrEqual(80_000);
+ expect((calls[0][2] as { nextDelayMs: number }).nextDelayMs).toBeLessThan(81_000);
+ // Attempt 10: computed with attempts=9 → 5000*2^9 = 2560s (+ <1s jitter).
+ expect(calls[1][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 10 });
+ expect((calls[1][2] as { nextDelayMs: number }).nextDelayMs).toBeGreaterThanOrEqual(2_560_000);
+ expect((calls[1][2] as { nextDelayMs: number }).nextDelayMs).toBeLessThan(2_561_000);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
+ it('re-arms the alert after a stability reset: the next alert waits 5 fresh attempts', () => {
+ jest.useFakeTimers();
+ try {
+ const i = internals();
+ // Four attempts already consumed, then the session stayed up ≥5 min — the budget resets.
+ const state = {
+ attempts: 4,
+ timer: null,
+ maxAttempts: Number.POSITIVE_INFINITY,
+ baseDelay: 5000,
+ lastAttemptAt: Date.now(),
+ };
+ i.reconnectStates.set('sess-uuid-1', state);
+
+ const alertsBefore = getSessionReconnectLoopAlertsTotal();
+
+ jest.advanceTimersByTime(300_000); // stability window elapses (no timer pending yet)
+ for (let k = 0; k < 4; k++) {
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ }
+ // Without the reset the very first of these would have been attempt 5 and alerted; instead the
+ // streak restarted at 0, so 4 fresh schedules reach only attempt 4 — still no alert.
+ expect(state.attempts).toBe(4);
+ expect(loopDispatches()).toHaveLength(0);
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(alertsBefore);
+
+ i.scheduleReconnect('sess-uuid-1', createMockSession()); // fresh attempt 5 → alert again
+ expect(state.attempts).toBe(5);
+ const calls = loopDispatches();
+ expect(calls).toHaveLength(1);
+ expect(calls[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', attempts: 5 });
+ expect(getSessionReconnectLoopAlertsTotal()).toBe(alertsBefore + 1);
+ } finally {
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('start() stale reconnect timer', () => {
it('cancels a pending reconnect timer before recreating the engine', async () => {
const i = service as unknown as {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 7335adf90..ddfdbbe38 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -40,6 +40,10 @@ import {
} from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { ShutdownService } from '../../common/services/shutdown.service';
+import {
+ incrementSessionReconnectAttempts,
+ incrementSessionReconnectLoopAlerts,
+} from '../../common/metrics/session-reconnect-metrics';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
@@ -72,6 +76,13 @@ const RECONNECT_DELAY_CAP_MS = 3_600_000;
* unrelated transient drops and one day wedge FAILED for no current reason.
*/
const RECONNECT_STABILITY_RESET_MS = 300_000;
+/**
+ * A reconnect-loop alert fires once per this many CONSECUTIVE attempts of a session — one signal per
+ * ongoing episode, not spam per attempt. A broken-forever setup retries without limit (by design), so
+ * the 5th/10th/15th… scheduled attempt is the operator-facing tell; the streak resets via the
+ * stability window above (or onReady), so a later episode re-arms the alert from attempt 5 again.
+ */
+const RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS = 5;
/**
* Session liveness watchdog. The engine layer is event-driven, so an engine that dies WITHOUT
* firing an event (a silent Chromium crash) is never noticed: the row sits READY forever and never
@@ -1564,6 +1575,27 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
},
);
+ incrementSessionReconnectAttempts();
+
+ // Loop alert every RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS consecutive attempts: with the default
+ // unlimited budget a permanently-broken setup retries forever, and this is the one operator-facing
+ // signal per ongoing episode (not per attempt). The streak resets via the stability window/onReady,
+ // so a fresh episode re-arms the alert instead of continuing an old cadence.
+ if (state.attempts > 0 && state.attempts % RECONNECT_LOOP_ALERT_INTERVAL_ATTEMPTS === 0) {
+ this.logger.warn(`Session is reconnect-looping: attempt ${state.attempts} scheduled`, {
+ sessionId: id,
+ attempts: state.attempts,
+ nextDelayMs: delay,
+ action: 'reconnect_loop',
+ });
+ incrementSessionReconnectLoopAlerts();
+ void this.webhookService.dispatch(id, 'session.reconnect_loop', {
+ sessionId: id,
+ attempts: state.attempts,
+ nextDelayMs: delay,
+ });
+ }
+
// Clear any timer a prior scheduleReconnect left pending so two back-to-back disconnects
// don't stack two timers (which would run executeReconnect twice and double-init the engine).
if (state.timer) clearTimeout(state.timer);
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index f0d273f08..ea4f14e55 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -44,6 +44,7 @@ export const WEBHOOK_EVENTS = [
'session.qr',
'session.authenticated',
'session.disconnected',
+ 'session.reconnect_loop',
...WEBHOOK_RESERVED_EVENTS,
] as const;