Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): reap failed/abandoned engines instead of leaking Chromium + slots (#635)

Yudhi Armyndharis8cdfae5f13b7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f0399f1d2..121e84f6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **A terminally-failed or un-reinitializable session no longer strands its browser process or wedges at "already started".** When an engine reports a terminal error, and when a reconnect attempt's re-initialization throws, the dead or half-built engine is now evicted from the session registry and its Chromium process is force-killed instead of being left in place — previously it kept holding a concurrency slot and caused a later start to be rejected as already running. Deleting a session likewise force-kills its browser (rather than a graceful close that could hang on a wedged Chromium and orphan the process).
- **The dark theme now covers every dashboard surface.** A number of components used hardcoded colors instead of the theme's CSS variables, so several surfaces stayed light in dark mode — most visibly the Infrastructure "Database Migrations" card, plus status/severity badges, toasts, danger-hover states, and toggle tracks across most pages. They now use the theme tokens (and translucent semantic fills) so they follow the active theme in both light and dark. A new `--info` token themes the blue badges (permission, SQLite, info logs, qr-ready pill) that previously had no theme-aware color, and the root `<html>` background no longer stays white when the dark theme is selected on a light-OS device (visible on overscroll).
## [0.8.8] - 2026-07-05
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index c9c316bd6..06145001d 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -176,14 +176,14 @@ describe('SessionService', () => {
const enginesOf = () => (service as unknown as { engines: Map<string, unknown> }).engines;
const stoppingOf = () => (service as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
- it('delete() completes when engine.destroy() rejects — map reconciled, row removed, stop-mark cleared', async () => {
+ it('delete() completes when engine.forceDestroy() rejects — map reconciled, row removed, stop-mark cleared', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
- const engine = { destroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };
+ const engine = { forceDestroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };
enginesOf().set('sess-uuid-1', engine);
await expect(service.delete('sess-uuid-1')).resolves.toBeUndefined();
- expect(engine.destroy).toHaveBeenCalledTimes(1);
+ expect(engine.forceDestroy).toHaveBeenCalledTimes(1);
expect(enginesOf().has('sess-uuid-1')).toBe(false); // Map reconciled despite the failure
expect(stoppingOf().has('sess-uuid-1')).toBe(false); // stop-mark cleared (no wedge)
expect(hookManager.execute).toHaveBeenCalledWith('session:deleted', expect.anything(), expect.anything());
@@ -205,7 +205,7 @@ describe('SessionService', () => {
it('delete() still surfaces a real DB-removal failure (engine teardown is best-effort, DB is not)', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(dataSource.transaction as jest.Mock).mockRejectedValueOnce(new Error('db down'));
- enginesOf().set('sess-uuid-1', { destroy: jest.fn().mockResolvedValue(undefined) });
+ enginesOf().set('sess-uuid-1', { forceDestroy: jest.fn().mockResolvedValue(undefined) });
await expect(service.delete('sess-uuid-1')).rejects.toThrow('db down');
expect(stoppingOf().has('sess-uuid-1')).toBe(false); // mark still cleared on failure
@@ -480,7 +480,8 @@ describe('SessionService', () => {
// Now delete
await service.delete('sess-uuid-1');
- expect(mockEngine.destroy).toHaveBeenCalled();
+ // delete() reaps permanently, so it force-destroys (SIGKILL) rather than a graceful destroy().
+ expect(mockEngine.forceDestroy).toHaveBeenCalled();
});
it('removes the session messages and bulk batches in the same transaction (no orphaned rows)', async () => {
@@ -570,6 +571,48 @@ describe('SessionService', () => {
// ── engine onError / lastError surfacing (#219) ───────────────────
+ describe('terminal-failure engine eviction', () => {
+ interface I {
+ initializeEngine: (id: string, s: Session) => Promise<void>;
+ executeReconnect: (id: string, s: Session, st: unknown) => Promise<void>;
+ engines: Map<string, unknown>;
+ }
+ const intern = () => service as unknown as I;
+ const flush = () => new Promise(resolve => setImmediate(resolve));
+
+ it('onError evicts the failed engine and force-destroys it, so the slot frees and a restart is not blocked', async () => {
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await intern().initializeEngine('sess-uuid-1', createMockSession());
+ expect(intern().engines.get('sess-uuid-1')).toBe(mockEngine);
+
+ const callbacks = (mockEngine.initialize.mock.calls[0] as [EngineEventCallbacks])[0];
+ callbacks.onError?.('net::ERR_INVALID_AUTH_CREDENTIALS');
+ await flush();
+
+ expect(intern().engines.has('sess-uuid-1')).toBe(false);
+ expect(mockEngine.forceDestroy).toHaveBeenCalledTimes(1);
+ });
+
+ it('executeReconnect evicts and force-destroys the half-initialized engine when re-init fails (no orphan on reconnect-exhaustion)', async () => {
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ // initializeEngine registers the engine, then engine.initialize() rejects — the half-built engine
+ // must not be left in the map for the next start() to trip over as "already started".
+ mockEngine.initialize.mockRejectedValueOnce(new Error('chromium launch failed'));
+ // Suppress the real reconnect timer scheduled by the catch block.
+ jest
+ .spyOn(service as unknown as { scheduleReconnect: () => void }, 'scheduleReconnect')
+ .mockImplementation(() => undefined);
+ const state = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };
+
+ await intern().executeReconnect('sess-uuid-1', createMockSession(), state);
+ await flush();
+
+ expect(intern().engines.has('sess-uuid-1')).toBe(false);
+ expect(mockEngine.forceDestroy).toHaveBeenCalled();
+ });
+ });
+
describe('reconnect/stop race', () => {
interface Internals {
executeReconnect: (id: string, session: Session, state: unknown) => Promise<void>;
@@ -743,6 +786,12 @@ describe('SessionService', () => {
// …then a terminal failure arrives. It must cancel the pending reconnect so the timer
// can't resurrect a session the operator has to manually restart.
callbacks.onError?.('fatal browser crash');
+ // onError also evicts the engine; teardownEngineSafely schedules a transient timeout that is
+ // cleared once forceDestroy settles. Flush microtasks so only the reconnect-cancellation (the
+ // property under test) remains — the resurrection timer must be gone.
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
expect(jest.getTimerCount()).toBe(0);
} finally {
jest.clearAllTimers();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index f06f76081..fd1bf325d 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -266,6 +266,18 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /**
+ * Evict a terminally-failed or abandoned engine from the map and SIGKILL its browser process
+ * (best-effort, time-bounded via teardownEngineSafely). An engine left in the map keeps holding a
+ * concurrency slot and makes a later start() see the session as "already started"; forceDestroy()
+ * (not the graceful destroy()) is used because such an engine's browser/CDP connection is typically
+ * already broken, so a graceful close would only time out before the process is reaped.
+ */
+ private evictAndForceDestroy(id: string, engine: IWhatsAppEngine): void {
+ this.engines.delete(id);
+ void this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
+ }
+
async create(dto: CreateSessionDto): Promise<Session> {
// Check if session with same name exists
const existing = await this.sessionRepository.findOne({
@@ -360,11 +372,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
this.cancelReconnect(id);
try {
- // Stop engine if running — time-bounded + isolated so a stuck Chromium destroy() can't wedge
- // the delete; the Map is reconciled and the DB removal proceeds regardless of the outcome.
+ // Stop engine if running — time-bounded + isolated so a stuck Chromium can't wedge the delete;
+ // the Map is reconciled and the DB removal proceeds regardless of the outcome. Use forceDestroy()
+ // (SIGKILL) rather than a graceful destroy(): the session is being removed permanently, so there is
+ // no session state worth saving, and a wedged Chromium must be reaped, not left to time out.
const engine = this.engines.get(id);
if (engine) {
- await this.teardownEngineSafely(id, engine, e => e.destroy(), 'destroy');
+ await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
this.engines.delete(id);
}
@@ -1040,6 +1054,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
);
void this.updateStatus(id, SessionStatus.FAILED);
+
+ // onError is terminal (no reconnect is scheduled — re-scan is required). Evict the dead engine
+ // and SIGKILL its process: leaving it in the map would hold a concurrency slot indefinitely and
+ // make the next start() reject the session as "already started" instead of re-initializing it.
+ this.evictAndForceDestroy(id, engine);
},
});
}
@@ -1168,6 +1187,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
sessionId: id,
action: 'reconnect_error',
});
+ // initializeEngine registers the engine in the map BEFORE engine.initialize() runs, so a rejected
+ // re-init leaves a half-built engine behind. Evict + reap it: otherwise a reconnect that later
+ // exhausts its attempts strands an orphaned Chromium holding a concurrency slot, and the next
+ // start() sees the session as "already started".
+ const halfBuilt = this.engines.get(id);
+ if (halfBuilt) {
+ this.evictAndForceDestroy(id, halfBuilt);
+ }
// Schedule another attempt
this.scheduleReconnect(id, session);
}