Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): bound engine.initialize() with a 60s timeout to stop silent INITIALIZING wedges (#696)

Yudhi Armyndharisbbae7738c18b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f736e94e3..dce04642d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,8 @@ 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]
+
- **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).
- **PostgreSQL upgrade crash-loop for deployments formerly run with `DATABASE_SYNCHRONIZE=true`.** On the PostgreSQL data connection, migrations always run at boot (`migrationsRun: true`), so a schema previously bootstrapped with `DATABASE_SYNCHRONIZE=true` — whose `@PrimaryGeneratedColumn('uuid')` columns TypeORM created as native `uuid` — collides with a migration chain that assumes `varchar` ids and crash-loops the container on boot. A new guard migration (`NormalizeSynchronizeUuidColumns`), ordered before the first colliding migration, now converts those `uuid` id and foreign-key columns to `varchar` (dropping and recreating the dependent cascade foreign keys, and re-applying the `gen_random_uuid()::varchar` defaults), so affected deployments self-heal on the next restart. It is a single-probe no-op on SQLite and on already-`varchar` (healthy) PostgreSQL. For very large `messages` tables the conversion holds an exclusive lock, so run `npm run migration:run` against the stopped app during a maintenance window if needed; `DATABASE_SYNCHRONIZE=true` on PostgreSQL remains unsupported for production. Fixes #690.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 646356715..948d25bf4 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -3,7 +3,7 @@ import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
import { Repository, DataSource, In } from 'typeorm';
import { NotFoundException, ConflictException, BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
-import { SessionService, ACK_RECONCILE_DELAY_MS } from './session.service';
+import { SessionService, ACK_RECONCILE_DELAY_MS, EngineInitTimeoutError } from './session.service';
import { Session, SessionStatus } from './entities/session.entity';
import { Message, MessageStatus } from '../message/entities/message.entity';
import { MessageBatch } from '../message/entities/message-batch.entity';
@@ -656,6 +656,61 @@ describe('SessionService', () => {
});
});
+ // ── initializeEngine init-timeout race (#667 follow-up) ───────────
+ describe('initializeEngine init-timeout race', () => {
+ type Intern = {
+ engines: Map<string, unknown>;
+ sessionErrors: Map<string, string>;
+ };
+ const intern = () => service as unknown as Intern;
+
+ it('a REAL engine.initialize() rejection still becomes FAILED with the reason recorded (the timeout-scoped catch must NOT downgrade it to DISCONNECTED)', async () => {
+ // Regression guard for #600/#631 diagnosability: a real init failure (e.g. Chromium can't launch)
+ // must stay FAILED+reason. The catch inside initializeEngine handles ONLY the timeout case and
+ // rethrows everything else untouched, so start()'s catch still owns the FAILED+reason path.
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ mockEngine.initialize.mockRejectedValueOnce(new Error('chromium launch failed'));
+
+ await expect(service.start('sess-uuid-1')).rejects.toThrow('chromium launch failed');
+
+ expect(intern().engines.has('sess-uuid-1')).toBe(false); // evicted, not left wedged
+ expect(mockEngine.forceDestroy).toHaveBeenCalled();
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.FAILED });
+ expect(intern().sessionErrors.get('sess-uuid-1')).toBe('chromium launch failed');
+ });
+
+ it('a wedged engine.initialize() (never settles) is force-destroyed, evicted, marked DISCONNECTED, and rethrows after 60s', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ // The hang: initialize() neither resolves nor rejects.
+ mockEngine.initialize.mockReturnValue(new Promise<void>(() => undefined));
+
+ jest.useFakeTimers();
+ try {
+ const pending = service.start('sess-uuid-1');
+ // Attach the handler synchronously so the timeout rejection is never briefly unhandled
+ // during the fake-timer tick (which would otherwise fail the test for the wrong reason).
+ let caught: unknown;
+ const settled = pending.catch((e: unknown) => {
+ caught = e;
+ });
+ // Advance past the 60s init deadline (the async variant flushes microtasks so the
+ // teardown + status writes settle within the same advance).
+ await jest.advanceTimersByTimeAsync(60_000);
+ await settled;
+
+ expect(caught).toBeInstanceOf(EngineInitTimeoutError);
+ expect(String(caught)).toMatch(/timed out after 60000ms/i);
+ expect(mockEngine.forceDestroy).toHaveBeenCalled(); // wedged browser reaped
+ expect(intern().engines.has('sess-uuid-1')).toBe(false); // slot freed for retry
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { status: SessionStatus.DISCONNECTED });
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('scheduleReconnect (max attempts)', () => {
it('reports "auto-reconnect disabled" (not "failed after 0 attempts") when maxAttempts is 0', async () => {
const i = service as unknown as {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index d6e0deec6..ef8a8307e 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -98,6 +98,19 @@ export function resolveMaxConcurrentSessions(configService?: Pick<ConfigService,
return Math.floor(configured);
}
+/**
+ * Distinguishes a wedged-initialization timeout from a real engine.initialize() rejection. Only the
+ * timeout case is handled inside initializeEngine(); real rejections must propagate untouched so the
+ * caller's catch (start() → FAILED+reason, executeReconnect() → retry) keeps the behavior #600/#631
+ * established. See initializeEngine().
+ */
+export class EngineInitTimeoutError extends Error {
+ constructor(readonly timeoutMs: number) {
+ super(`engine.initialize() timed out after ${timeoutMs}ms`);
+ this.name = 'EngineInitTimeoutError';
+ }
+}
+
@Injectable()
export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicationBootstrap {
private readonly logger = createLogger('SessionService');
@@ -653,7 +666,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// initializes, so writing INITIALIZING afterwards would clobber that progress.
await this.updateStatus(id, SessionStatus.INITIALIZING);
- await engine.initialize({
+ const initPromise = engine.initialize({
onQRCode: (qr: string): void => {
if (!this.isLiveEngine(id, engine)) return;
this.logger.log('QR code generated', {
@@ -1137,6 +1150,46 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.evictAndForceDestroy(id, engine);
},
});
+
+ // engine.initialize() launches Chromium and navigates to WhatsApp Web with no internal timeout:
+ // whatsapp-web.js calls page.goto(..., { timeout: 0 }) and its web-version-cache fetch has none
+ // either. If the browser stalls under container memory pressure (observed in prod: a session
+ // wedged in INITIALIZING with no error logged and GET /sessions/:id/qr 400ing forever), this
+ // await never settles. Race it against a deadline so a wedged init fails fast instead.
+ //
+ // ONLY the timeout case mutates state here. A REAL rejection (e.g. Chromium can't launch) must
+ // 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;
+ // Promise.race can't cancel the losing promise, so swallow a late rejection from initPromise.
+ initPromise.catch(() => undefined);
+
+ let initTimer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ initPromise,
+ new Promise<never>((_, reject) => {
+ initTimer = setTimeout(() => reject(new EngineInitTimeoutError(engineInitTimeoutMs)), engineInitTimeoutMs);
+ }),
+ ]);
+ } catch (err) {
+ if (err instanceof EngineInitTimeoutError) {
+ this.logger.error(`Engine initialization timed out for session ${session.name}`, undefined, {
+ sessionId: id,
+ action: 'engine_init_timeout',
+ });
+ this.sessionErrors.set(id, err.message);
+ // 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;
+ } finally {
+ if (initTimer) clearTimeout(initTimer);
+ }
}
/**