Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): derive init-timeout deadline from auth wait + reorder teardown (#697)
Yudhi Armyndharisa9ea53266b9f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dce04642d..18bace334 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]-- **WhatsApp Web sessions no longer wedge silently in `INITIALIZING` forever.** `engine.initialize()` was awaited with no timeout, and neither whatsapp-web.js nor Puppeteer bounds the initial browser launch/navigation (`page.goto` is called with `timeout: 0` and the web-version-cache fetch carries no timeout). If Chromium stalled under container memory pressure — realistic at the documented 2 GB Standard profile — the await never resolved or rejected: the session sat in `INITIALIZING` indefinitely, `GET /sessions/:id/qr` 400'd forever, and nothing was logged. The #635 abandoned-engine reaper is reactive (terminal `onError` / rejected re-init only), so nothing recovered it. `initializeEngine()` now races `engine.initialize()` against a 60 s deadline; on timeout it force-kills the wedged browser, marks the session `DISCONNECTED` (retryable, so the existing reconnect backoff picks it up), and rethrows — surfacing the failure to a manual `POST /start` caller instead of hanging. The race's catch is scoped to the timeout only (`EngineInitTimeoutError`): a real init rejection (e.g. Chromium can't launch) propagates untouched so `start()`'s existing `FAILED`+reason diagnostics are preserved — handling both in one catch would downgrade real failures to `DISCONNECTED` and hide their reason. Thanks @INAPA-desarrolloTIC. [#667]+- **WhatsApp Web sessions no longer wedge silently in `INITIALIZING` forever.** `engine.initialize()` was awaited with no timeout, and neither whatsapp-web.js nor Puppeteer bounds the initial browser launch/navigation (`page.goto` is called with `timeout: 0` and the web-version-cache fetch carries no timeout). If Chromium stalled under container memory pressure — realistic at the documented 2 GB Standard profile — the await never resolved or rejected: the session sat in `INITIALIZING` indefinitely, `GET /sessions/:id/qr` 400'd forever, and nothing was logged. The #635 abandoned-engine reaper is reactive (terminal `onError` / rejected re-init only), so nothing recovered it. `initializeEngine()` now races `engine.initialize()` against a deadline derived from the configured auth wait (floor 60 s, or `WWEBJS_AUTH_TIMEOUT_MS` + 30 s when an operator has raised that for slow first boots) so a legitimate slow init is never cut short; on timeout it force-kills the wedged browser, marks the session `DISCONNECTED` (retryable, so the existing reconnect backoff picks it up), and rethrows — surfacing the failure to a manual `POST /start` caller instead of hanging. The race's catch is scoped to the timeout only (`EngineInitTimeoutError`): a real init rejection (e.g. Chromium can't launch) propagates untouched so `start()`'s existing `FAILED`+reason diagnostics are preserved — handling both in one catch would downgrade real failures to `DISCONNECTED` and hide their reason. Thanks @INAPA-desarrolloTIC. [#667]- **Dashboard primary buttons were invisible until hover in light mode.** A leftover Vite template rule — `:root:not([data-theme='dark']) button { background-color:#f9f9f9 }` inside `@media (prefers-color-scheme: light)` — carried specificity `(0,2,1)` (`:root` + the `:not([data-theme])` argument + `button`), higher than every page-scoped `.X-page .btn-primary` rule `(0,2,0)`. In light mode (the default) it overrode the green design-system background with a near-white `#f9f9f9`, leaving the buttons' white text invisible until the leftover Vite `button:hover { border-color:#646cff }` ring revealed them on hover; the same `(0,2,1)` rule also pushed `.btn-secondary` and `.btn-icon` off their intended backgrounds. Removed that rule (Create-session and other primary buttons are green again), and cleared the remaining Vite scaffolding brand-colors from `index.css` (`a { color:#646cff }`, the purple `a:hover`, `button { background-color:#1a1a1a }`, `button:hover { border-color:#646cff }`) that competed with the App.css design system on import-order tiebreaks; the structural button CSS (border-radius, padding, font, cursor) is retained. Plain `<button>` elements now render with the browser default instead of the dark `#1a1a1a`. The defect was invisible to anyone developing the dashboard in dark mode. Refs #684 (addresses the dashboard-button part; the QR-with-whatsapp-web.js report in the same issue is separate and still under investigation).diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 948d25bf4..a49bcd18e 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -687,6 +687,12 @@ describe('SessionService', () => {mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));jest.useFakeTimers();+ // A start()-path timeout must NOT auto-schedule a reconnect (reconnect is executeReconnect's+ // domain; a manual start that times out leaves the session DISCONNECTED for the operator).+ const scheduleReconnect = jest.spyOn(+ service as unknown as { scheduleReconnect: (...a: unknown[]) => void },+ 'scheduleReconnect',+ );try {const pending = service.start('sess-uuid-1');// Attach the handler synchronously so the timeout rejection is never briefly unhandled@@ -705,8 +711,43 @@ describe('SessionService', () => {expect(mockEngine.forceDestroy).toHaveBeenCalled(); // wedged browser reapedexpect(intern().engines.has('sess-uuid-1')).toBe(false); // slot freed for retryexpect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });+ expect(scheduleReconnect).not.toHaveBeenCalled(); // no auto-reconnect from a start() timeout+ } finally {+ jest.useRealTimers();+ }+ });++ it('extends the init deadline past 60s when WWEBJS_AUTH_TIMEOUT_MS is raised, so a legitimate slow auth wait is not cut short', async () => {+ // #353 slow-boot escape hatch: operators raise the auth wait because WA-Web's inject poll+ // legitimately takes longer on WSL2/low-resource containers. The init race must extend with+ // it, not SIGKILL the init at the 60s floor mid-auth.+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));+ process.env.WWEBJS_AUTH_TIMEOUT_MS = '120000'; // → derived deadline max(60s, 120s+30s) = 150s++ jest.useFakeTimers();+ try {+ const pending = service.start('sess-uuid-1');+ let caught: unknown;+ const settled = pending.catch((e: unknown) => {+ caught = e;+ });++ // At 60s the old hardcoded deadline would have fired and killed a healthy slow init; the+ // derived one must still be waiting.+ await jest.advanceTimersByTimeAsync(60_000);+ expect(caught).toBeUndefined();+ expect(mockEngine.forceDestroy).not.toHaveBeenCalled(); // NOT cut short mid-auth++ // Past the derived 150s deadline the race finally fires.+ await jest.advanceTimersByTimeAsync(90_000); // 60s + 90s = 150s+ await settled;+ expect(caught).toBeInstanceOf(EngineInitTimeoutError);+ expect(String(caught)).toMatch(/timed out after 150000ms/i);} finally {jest.useRealTimers();+ delete process.env.WWEBJS_AUTH_TIMEOUT_MS;}});});diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex ef8a8307e..53f037931 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -20,6 +20,7 @@ import { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { CreateSessionDto } from './dto';import { EngineFactory } from '../../engine/engine.factory';+import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { userPart } from '../../engine/identity/wa-id';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';@@ -1161,7 +1162,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// propagate untouched so start()'s catch keeps owning FAILED+reason (the diagnosability #600/#631// added) — pre-deleting the engine and writing DISCONNECTED here would make start()'s// `engines.get(id)` return undefined, skip its FAILED write, and hide the failure reason.- const engineInitTimeoutMs = 60_000;+ // The deadline MUST exceed the auth wait whatsapp-web.js runs INSIDE engine.initialize()+ // (authTimeoutMs — the inject() poll for WA Web's JS to bootstrap, raisable via+ // WWEBJS_AUTH_TIMEOUT_MS for slow first boots, e.g. WSL2/low-resource containers). A shorter+ // outer deadline would SIGKILL a legitimate slow init mid-auth. Floor 60s for the hang case;+ // otherwise give the configured auth window + 30s for launch/navigation/post-inject overhead.+ const engineInitTimeoutMs = Math.max(60_000, (resolveAuthTimeoutMs() ?? 30_000) + 30_000);// Promise.race can't cancel the losing promise, so swallow a late rejection from initPromise.initPromise.catch(() => undefined);@@ -1180,10 +1186,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicataction: 'engine_init_timeout',});this.sessionErrors.set(id, err.message);+ // Evict from the map BEFORE tearing down. forceDestroy() drives the adapter to+ // EngineStatus.DISCONNECTED, which fires onStateChanged synchronously; while the engine is+ // still in the map that callback would pass the isLiveEngine guard and run (and the same+ // window admits onError/onDisconnected, which could write FAILED or schedule a reconnect+ // against this path). Deleting first makes isLiveEngine return false so no teardown-induced+ // callback can race the DISCONNECTED write below — the canonical delete-before-teardown used+ // at evictAndForceDestroy(), start()'s catch, and stop().+ this.engines.delete(id);// Force-kill whatever got launched so a retry doesn't collide with an orphaned browser.// teardownEngineSafely is itself time-bound, so this can't wedge a second time.await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');- this.engines.delete(id);await this.updateStatus(id, SessionStatus.DISCONNECTED);}throw err;