Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): report engine state, track late logout cleanup, reach a localised modal
Yudhi Armyndharisa64221cf5f98
diff --git a/.env.example b/.env.exampleindex 6a9ae391f..6a9dde51f 100644--- a/.env.example+++ b/.env.example@@ -77,10 +77,20 @@ CORS_ORIGINS=*# Engine-specific settingsSESSION_DATA_PATH=./data/sessionsPUPPETEER_HEADLESS=true+# Browser flags, comma- or space-separated. NOTE: this REPLACES the default list rather than adding to+# it, so repeat the flags you still want — dropping --no-sandbox stops Chromium launching in a+# container. `--lang=en-US` is appended automatically unless you pass your own `--lang`: WhatsApp Web+# renders in the browser's language and the onboarding-modal handling below matches visible text.PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu# Path to a system Chromium/Chrome binary. Leave unset to use the bundled Puppeteer browser.# Required in the Docker image and on hosts without a bundled browser (e.g. Alpine/ARM).# PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium+# A freshly linked account is shown a "What's new on WhatsApp Web" modal that must be acknowledged or+# WhatsApp unlinks the companion a few minutes later. The whatsapp-web.js engine clicks it+# automatically, matching the English button label `Continue`. If your WhatsApp Web renders the modal+# in another language, add that label here (comma-separated) — an operator-supplied label is matched+# without the English heading check, which would otherwise reject the very modal it targets.+# WWEBJS_ONBOARDING_CONTINUE_LABELS=Continuar,Weiter,Lanjutkan# ── Container resource limits (docker-compose only) ───────────────────────────# These map to docker-compose `mem_limit` / `pids_limit` and only apply when running via thediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 00311753c..0a1996933 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **The session payload reports whether the gateway holds a live engine** (`engineLoaded`). This is the+ precondition the lifecycle routes actually enforce, and `status` was never a reliable proxy for it:+ `disconnected` means both "the engine is still registered while an automatic reconnect backs off,+ and `start` therefore answers 400" and "the session was stopped and has no engine, so `start` is+ exactly the right call". The dashboard now derives Stop, Unlink, Force-Kill and Start from the field+ instead of guessing from the status, which closes the case where a session dropped mid-reconnect+ offered only Start, got a 400, and then left a QR dialog open that could never resolve — and, in the+ other direction, hid Force-Kill from precisely the wedged engine that button exists for. Added to+ `openapi.json` and to the JavaScript, Python, Go and Java SDKs (the PHP SDK returns untyped arrays);+ it is a new optional field on the response, so existing clients are unaffected. A dashboard served+ by an older gateway falls back to the previous status-based rule rather than reading a missing field+ as "no engine".++- **The whatsapp-web.js onboarding modal can be dismissed on a non-English WhatsApp Web.** The detector+ matches the modal's visible confirm label, which is `Continue` only while the page renders in+ English. Two changes: Chromium is now launched with a pinned `--lang` so the page locale is+ deterministic across the amd64 and arm64 images (an explicit `--lang` in `PUPPETEER_ARGS` still+ wins, and the pin is applied even when that variable replaces the default flags — otherwise+ customising args for an unrelated reason would silently drop it); and+ `WWEBJS_ONBOARDING_CONTINUE_LABELS` accepts additional labels for a deployment whose modal is+ localised anyway. An operator-supplied label is matched without the English heading check, which+ would reject the very modal it targets; the default `Continue` keeps that check, so the+ out-of-the-box false-positive surface is unchanged.++### Fixed++- **A WhatsApp-initiated logout that arrives during an unrelated teardown no longer hides its+ credential removal.** whatsapp-web.js emits `disconnected: LOGOUT` and then runs+ `authStrategy.logout()` → `fs.rm` of the session's profile directory, and that removal happens+ regardless of what the adapter's listener does. The listener returned early whenever a teardown had+ already latched — which `stop()`, `destroy()` and `force-kill` all do — so in that window the+ in-flight removal was never registered, the name-keyed teardown fence saw nothing pending, and a+ following `start()` under the same name could have its freshly written credentials deleted by it.+ This is the same hazard the fence was built for, reached through a narrower window. The removal is+ now surfaced before the latch check, and skipped only when the adapter's own `logout()` started it —+ that path already registers the real `Client.logout()` promise, which covers the same removal.++- **The dashboard no longer fabricates a session status after a start.** It wrote a local+ `status: 'connecting'` — a value the gateway does not emit — while keeping every other field from+ before the request, and used the authoritative response for nothing. It now applies the response as+ returned, the same rule the stop and unlink paths already follow. A live status push also drops the+ stale engine answer that arrived with it, and a `disconnected` push refreshes, because that status+ alone cannot say which of its two meanings applies.++- Removed two session statuses from the dashboard that the gateway never emits (`connecting`, `idle`),+ along with the dead branches that tested for them.+## [0.12.0] - 2026-07-30The session-lifecycle security hardening release. Lifecycle endpoints, thediff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsxindex fb6929b3a..e4036bdbf 100644--- a/dashboard/src/pages/Dashboard.tsx+++ b/dashboard/src/pages/Dashboard.tsx@@ -159,7 +159,7 @@ export function Dashboard() {<button className="btn-sm" onClick={() => navigate('/sessions')}>{t('dashboard.view')}</button>- {['ready', 'initializing', 'connecting', 'qr_ready'].includes(session.status) && (+ {['ready', 'initializing', 'qr_ready'].includes(session.status) && (<button className="btn-sm danger" onClick={() => handleDisconnect(session.id)}>{t('dashboard.disconnect')}</button>diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex 0ae9ca909..e966a73e2 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -131,8 +131,16 @@ export function Sessions() {// and the failed-refresh don't fire on every redundant envelope. Update the ref synchronously so// a duplicate arriving in the same tick (before the sync effect runs) is also caught.if (prev && prev.status === event.status) return;+ // Drop `engineLoaded` alongside the status patch: it is server-owned live state the status+ // envelope does not carry, so keeping the previous value would pair a fresh status with a+ // stale engine answer and the card could offer Start to a running session (or Unlink to one+ // with no engine). Clearing it makes isSessionStarted fall back to the status set until an+ // authoritative response arrives — and for `disconnected`, where that fallback is knowingly+ // wrong, the branch below refetches.sessionsRef.current = sessionsRef.current.map(s =>- s.id === event.sessionId ? { ...s, status: event.status as Session['status'] } : s,+ s.id === event.sessionId+ ? { ...s, status: event.status as Session['status'], engineLoaded: undefined }+ : s,);setSessions(sessionsRef.current);// Mark the shared session queries stale so sibling views refetch — but ONLY on a real@@ -142,6 +150,11 @@ export function Sessions() {if (event.status === 'ready') {toast.success(t('sessions.toasts.readyTitle'), t('sessions.toasts.readyDesc'));} else if (event.status === 'disconnected') {+ // Refresh so the card picks up `engineLoaded` from the API. `disconnected` is the one status+ // that means two different things — an engine still registered through its automatic+ // reconnect backoff, or a session stopped with no engine at all — and only the server can+ // say which, so the offered actions must not be guessed from the status here.+ void fetchSessions();toast.warning(t('sessions.toasts.disconnectedTitle'), t('sessions.toasts.disconnectedDesc'));} else if (event.status === 'action_required') {// Refresh so the card picks up the lastError reason (what the operator must do) from the API.@@ -229,7 +242,7 @@ export function Sessions() {// instead of being torn down mid-pairing — it closes on the real 'ready'/'failed' transition.const updated = await sessionApi.get(sessionId).catch(() => null);const stillInitializing =- updated && ['initializing', 'connecting', 'qr_ready', 'authenticating'].includes(updated.status);+ updated && ['initializing', 'qr_ready', 'authenticating'].includes(updated.status);if (!stillInitializing) {setQrData(null);currentSessionName.current = '';@@ -325,14 +338,18 @@ export function Sessions() {const handleStart = async (id: string) => {const session = sessions.find(s => s.id === id);- if (session && ['initializing', 'connecting', 'qr_ready'].includes(session.status)) {+ if (session && ['initializing', 'qr_ready'].includes(session.status)) {handleShowQR(id);return;}try {- await sessionApi.start(id);- setSessions(current => current.map(s => (s.id === id ? { ...s, status: 'connecting' } : s)));+ // Use the authoritative response instead of fabricating a status. The old code wrote a local+ // `status: 'connecting'` — a value the gateway never emits — while keeping every other field+ // from before the start, which now includes `engineLoaded` and would leave the card offering+ // Start for a session that just acquired an engine.+ const started = await sessionApi.start(id);+ setSessions(current => replaceSession(current, started));await fetchSessions();handleShowQR(id);} catch (err) {@@ -458,9 +475,9 @@ export function Sessions() {statusFilter === 'all' ||(statusFilter === 'active' && s.status === 'ready') ||(statusFilter === 'inactive' &&- ['created', 'idle', 'disconnected', 'action_required', 'failed'].includes(s.status)) ||+ ['created', 'disconnected', 'action_required', 'failed'].includes(s.status)) ||(statusFilter === 'connecting' &&- ['initializing', 'connecting', 'authenticating', 'qr_ready'].includes(s.status));+ ['initializing', 'authenticating', 'qr_ready'].includes(s.status));return matchesSearch && matchesStatus;});@@ -891,7 +908,7 @@ export function Sessions() {<span className={`status-pill ${session.status}`}>{formatStatus(session.status)}</span></div>- {session.status === 'initializing' || session.status === 'connecting' || session.status === 'qr_ready' ? (+ {session.status === 'initializing' || session.status === 'qr_ready' ? (<div className="qr-placeholder"><QrCode size={80} className="qr-icon" /><p>{session.status === 'qr_ready' ? t('sessions.qr.scanToConnect') : t('sessions.qr.preparing')}</p>@@ -933,13 +950,13 @@ export function Sessions() {<Eye size={16} />{t('sessions.actions.view')}</button>- {canWrite && isSessionStarted(session.status) ? (+ {canWrite && isSessionStarted(session) ? (<button className="btn-action" onClick={() => handleStop(session.id)}><Square size={16} />{t('sessions.actions.stop')}</button>) : canWrite &&- (session.status === 'created' || session.status === 'idle' || session.status === 'disconnected') ? (+ (session.status === 'created' || session.status === 'disconnected') ? (<button className="btn-action" onClick={() => handleStart(session.id)}><Play size={16} />{t('sessions.actions.start')}@@ -950,7 +967,7 @@ export function Sessions() {{t('sessions.actions.reconnect')}</button>) : null}- {canUnlinkSession(session.status, canWrite) && (+ {canUnlinkSession(session, canWrite) && (<button className="btn-action danger" onClick={() => setUnlinkConfirmId(session.id)}><Unlink size={16} />{t('sessions.actions.unlink')}@@ -962,7 +979,7 @@ export function Sessions() {{t('sessions.actions.delete')}</button>)}- {canForceKillSession(session.status, canWrite) && (+ {canForceKillSession(session, canWrite) && (<button className="btn-action danger" onClick={() => setKillConfirmId(session.id)}><Skull size={16} />{t('sessions.actions.killStuck')}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex cf97d1f69..eb86b3317 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -27,15 +27,20 @@ export interface Session {name: string;status:| 'created'- | 'idle'| 'initializing'- | 'connecting'| 'authenticating'| 'qr_ready'| 'ready'| 'disconnected'| 'action_required'| 'failed';+ /**+ * Whether the gateway holds a live engine for this session right now. The precondition the+ * lifecycle routes enforce, and not derivable from `status`: `disconnected` covers both a session+ * mid automatic-reconnect (engine present, start 400s) and one stopped through stop() (no engine).+ * Optional only because a dashboard can be served by a gateway that predates the field.+ */+ engineLoaded?: boolean;phone?: string | null;pushName?: string | null;lastActive?: string | null;diff --git a/dashboard/src/utils/sessionActions.test.ts b/dashboard/src/utils/sessionActions.test.tsindex 8d3b8ba77..f7a49e256 100644--- a/dashboard/src/utils/sessionActions.test.ts+++ b/dashboard/src/utils/sessionActions.test.ts@@ -25,51 +25,75 @@ function makeSession(overrides: Partial<Session> = {}): Session {};}-// Every status with a live engine must be "started": the card picks Stop vs Start from this, and-// offering Start to a started session gets a 400 and then a QR modal that can never resolve.-test('isSessionStarted: every status that holds a live engine counts as started', () => {- for (const status of ['initializing', 'connecting', 'qr_ready', 'authenticating', 'ready', 'action_required']) {- assert.equal(isSessionStarted(status), true, status);+const ENGINE_BACKED_STATUSES = ['initializing', 'qr_ready', 'authenticating', 'ready', 'action_required'] as const;+const ENGINELESS_STATUSES = ['created', 'failed'] as const;++// The gateway's `engineLoaded` is authoritative: it is read from the live engine map per request, and+// it is the precondition the lifecycle routes actually enforce. Status is not a proxy for it.+test('isSessionStarted: engineLoaded decides, whatever the status says', () => {+ for (const status of [...ENGINE_BACKED_STATUSES, ...ENGINELESS_STATUSES, 'disconnected'] as Session['status'][]) {+ assert.equal(isSessionStarted(makeSession({ status, engineLoaded: true })), true, `${status} + engine`);+ assert.equal(isSessionStarted(makeSession({ status, engineLoaded: false })), false, `${status} + no engine`);}- for (const status of ['created', 'idle', 'disconnected', 'failed']) {- assert.equal(isSessionStarted(status), false, status);+});++// The case that was unrepresentable before: `disconnected` means BOTH "mid automatic-reconnect, engine+// still registered, start() answers 400" and "stopped, no engine, Start is the right action".+test('isSessionStarted: a disconnected session mid-reconnect is started, a stopped one is not', () => {+ const reconnecting = makeSession({ status: 'disconnected', engineLoaded: true });+ const stopped = makeSession({ status: 'disconnected', engineLoaded: false });++ assert.equal(isSessionStarted(reconnecting), true);+ assert.equal(isSessionStarted(stopped), false);+ // So the wedged one offers the recovery actions and does NOT offer Start.+ assert.equal(canForceKillSession(reconnecting, true), true);+ assert.equal(canUnlinkSession(reconnecting, true), true);+ assert.equal(canForceKillSession(stopped, true), false);+ assert.equal(canUnlinkSession(stopped, true), false);+});++// A gateway older than the field sends no engineLoaded; the helper must not read `undefined` as false+// and hide every action. It falls back to the historical status set instead.+test('isSessionStarted: falls back to the status set when the gateway omits engineLoaded', () => {+ for (const status of ENGINE_BACKED_STATUSES) {+ assert.equal(isSessionStarted(makeSession({ status, engineLoaded: undefined })), true, status);+ }+ for (const status of [...ENGINELESS_STATUSES, 'disconnected'] as Session['status'][]) {+ assert.equal(isSessionStarted(makeSession({ status, engineLoaded: undefined })), false, status);}});test('canUnlinkSession: unlinkable is exactly started — Stop and Unlink share one precondition', () => {- for (const status of ['initializing', 'connecting', 'qr_ready', 'authenticating', 'ready', 'action_required']) {- assert.equal(canUnlinkSession(status, true), true, status);- assert.equal(canUnlinkSession(status, true), isSessionStarted(status), `${status} must track Stop`);+ for (const status of ENGINE_BACKED_STATUSES) {+ const session = makeSession({ status, engineLoaded: true });+ assert.equal(canUnlinkSession(session, true), true, status);+ assert.equal(canUnlinkSession(session, true), isSessionStarted(session), `${status} must track Stop`);}- for (const status of ['created', 'idle', 'disconnected', 'failed']) {- assert.equal(canUnlinkSession(status, true), false, status);+ for (const status of ENGINELESS_STATUSES) {+ assert.equal(canUnlinkSession(makeSession({ status, engineLoaded: false }), true), false, status);}});test('canUnlinkSession: a read-only role never sees the action, even for a started session', () => {- assert.equal(canUnlinkSession('ready', false), false);+ assert.equal(canUnlinkSession(makeSession({ status: 'ready', engineLoaded: true }), false), false);});// Force-kill is the emergency hatch for a WEDGED engine, so it must be offered exactly when a live-// engine exists — never for FAILED (the engine is already gone, so there is nothing to kill).-test('canForceKillSession: offered for every engine-backed status, hidden for terminal FAILED', () => {- for (const status of [- 'initializing',- 'connecting',- 'qr_ready',- 'authenticating',- 'ready',- 'action_required',- ]) {- assert.equal(canForceKillSession(status, true), true, `${status} is engine-backed and should offer kill`);- }- for (const status of ['created', 'idle', 'disconnected', 'failed']) {- assert.equal(canForceKillSession(status, true), false, `${status} has no live engine to kill`);+// engine exists — never for FAILED, whose engine is evicted on the way to that status.+test('canForceKillSession: offered whenever an engine is loaded, hidden for terminal FAILED', () => {+ for (const status of ENGINE_BACKED_STATUSES) {+ assert.equal(+ canForceKillSession(makeSession({ status, engineLoaded: true }), true),+ true,+ `${status} is engine-backed and should offer kill`,+ );}+ assert.equal(canForceKillSession(makeSession({ status: 'failed', engineLoaded: false }), true), false);+ assert.equal(canForceKillSession(makeSession({ status: 'created', engineLoaded: false }), true), false);});test('canForceKillSession: a read-only role never sees the action, even for a started session', () => {- assert.equal(canForceKillSession('ready', false), false);+ assert.equal(canForceKillSession(makeSession({ status: 'ready', engineLoaded: true }), false), false);});// ── replaceSession ────────────────────────────────────────────────────────────diff --git a/dashboard/src/utils/sessionActions.ts b/dashboard/src/utils/sessionActions.tsindex 8ea4ebcf9..1e899c086 100644--- a/dashboard/src/utils/sessionActions.ts+++ b/dashboard/src/utils/sessionActions.ts@@ -3,48 +3,41 @@import type { Session } from '../services/api.ts';-// Statuses in which the API has an engine loaded for the session. This is the single source of truth-// for the engine-backed actions — Stop, Unlink, and Force-Kill — because they share one precondition:-// something live to act on. Keeping them on one set is what stops a card in one of these states from-// offering an action the API rejects, and from offering Start to a session that is already started-// (the API answers 400 and the page then opens a QR modal that can never resolve).+// Stop, Unlink and Force-Kill share one precondition: the gateway holds a live engine to act on.+// Start has the exact complement — it answers 400 while one exists. So all four derive from the+// gateway's own `engineLoaded`, which is read from the live engine map per request. Deriving them+// from `status` cannot be made correct: `disconnected` covers BOTH a session mid automatic-reconnect+// (engine registered, Start 400s) and one stopped through stop() (no engine, Start is the right+// action), and those are the same status.//-// `authenticating` and `action_required` belong here: both hold a live engine — the whatsapp-web.js-// adapter can sit in `authenticating` for 90 seconds, and `action_required` means the engine is-// running but something needs a human. Without them a card in either state offered only Start.-//-// KNOWN GAP (pre-existing, needs a server-side signal to close): `disconnected` is deliberately NOT-// here even though it can hold a live engine. handleEngineDisconnected writes DISCONNECTED and-// schedules a reconnect WITHOUT evicting the engine, so one stays registered for the whole backoff —-// and start() rejects with 400 "already started" while it is. But a session stopped via stop() is-// also `disconnected` and has no engine, and that one legitimately needs Start. The two are-// indistinguishable from status alone, so listing it here would break the stop/start path to fix the-// backoff path. Closing this properly needs the session payload to expose whether an engine is-// loaded; until then Stop over the API is the escape hatch for a session wedged mid-backoff.-const STARTED_STATUSES = new Set([+// The fallback below is for a dashboard talking to a gateway that predates the field. It reproduces+// the old status set, whose known wrong answer is exactly that `disconnected` case — a stale+// dashboard keeps the old behaviour instead of guessing differently.+const STARTED_STATUSES_FALLBACK = new Set(['initializing',- 'connecting','qr_ready','authenticating','ready','action_required',]);-export function isSessionStarted(status: string): boolean {- return STARTED_STATUSES.has(status);+export function isSessionStarted(session: Pick<Session, 'status' | 'engineLoaded'>): boolean {+ return session.engineLoaded ?? STARTED_STATUSES_FALLBACK.has(session.status);}// Unlink calls POST /sessions/:id/logout, which needs a live engine to send the unlink through — the// same precondition as Stop, and what the API's own 400 tells the operator.-export function canUnlinkSession(status: string, canWrite: boolean): boolean {- return canWrite && isSessionStarted(status);+export function canUnlinkSession(session: Pick<Session, 'status' | 'engineLoaded'>, canWrite: boolean): boolean {+ return canWrite && isSessionStarted(session);}// Force-kill is the emergency hatch for a WEDGED engine, so it is offered exactly when a live engine-// exists. It must NOT be offered for FAILED: a terminal failure already evicted the engine, so there-// is nothing left to kill — the card offers reconnect/manual start instead.-export function canForceKillSession(status: string, canWrite: boolean): boolean {- return canWrite && isSessionStarted(status);+// exists. That excludes FAILED: a terminal failure already evicted the engine, so there is nothing+// left to kill — the card offers reconnect/manual start instead. It now INCLUDES a `disconnected`+// session still holding an engine through its reconnect backoff, which is precisely the wedged case+// the button exists for and which the status-only rule used to hide.+export function canForceKillSession(session: Pick<Session, 'status' | 'engineLoaded'>, canWrite: boolean): boolean {+ return canWrite && isSessionStarted(session);}// Replace the row matching `updated.id` with the EXACT authoritative response object. The originaldiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 0d113b9f1..f650b0fa5 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -215,13 +215,16 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt"lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:01:55.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": true}]````lastError` is non-null only when `status` is `failed` or `action_required`; any other status clears it. `config`/`proxyUrl`/`proxyType` are not present (stripped by `fromEntity`).+`engineLoaded` reports whether the gateway holds a live engine for the session at the moment of the response. It is the precondition the lifecycle routes enforce, and **`status` is not a substitute for it**: `disconnected` covers both a session whose engine is still registered while an automatic reconnect backs off — where `POST /start` answers `400` — and one stopped through `POST /stop`, which has no engine and does need a start. When `engineLoaded` is `true`, `stop`, `logout` and `force-kill` can act; when it is `false`, `start` is the applicable route. The field is derived per request from live process state, so it is never persisted and never appears in historical/exported data.+**Errors:** `401` missing/invalid `X-API-Key`#### GET /api/sessions/:id@@ -249,7 +252,8 @@ Get a single session by ID."lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:01:55.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": true}```@@ -426,7 +430,8 @@ network cannot reach WhatsApp directly. Set `proxyUrl`/`proxyType` on the same r"lastActive": null,"createdAt": "2026-06-25T09:00:00.000Z","updatedAt": "2026-06-25T09:00:00.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": false}```@@ -461,7 +466,8 @@ No request body."lastActive": null,"createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:05:00.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": true}```@@ -496,7 +502,8 @@ No request body."lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:10:00.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": false}```@@ -562,7 +569,8 @@ No request body."lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:11:00.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": false}```@@ -599,7 +607,8 @@ No request body."lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z","updatedAt": "2026-06-25T09:12:00.000Z",- "lastError": null+ "lastError": null,+ "engineLoaded": false}```diff --git a/openapi.json b/openapi.jsonindex 68ee13153..0d79f4bb8 100644--- a/openapi.json+++ b/openapi.json@@ -6314,6 +6314,11 @@"description": "Human-readable reason carried while the status is FAILED (a terminal engine failure) or ACTION_REQUIRED (the engine is running but something needs a human). Cleared on any other status.","example": "Failed to launch the browser process: spawn /usr/bin/chromium ENOENT","nullable": true+ },+ "engineLoaded": {+ "type": "boolean",+ "description": "Whether the gateway currently holds a live engine for this session. This is the precondition the lifecycle routes actually enforce, and `status` alone does not imply it: a `disconnected` session keeps its engine for the duration of an automatic reconnect backoff, while a session stopped through `POST /sessions/:id/stop` carries the same status with no engine. When `true`, `stop`, `logout` and `force-kill` can act and `start` answers 400; when `false`, the reverse. Derived per request from live process state, so it is never persisted and never historical.",+ "example": true}},"required": [@@ -6321,7 +6326,8 @@"name","status","createdAt",- "updatedAt"+ "updatedAt",+ "engineLoaded"]},"QRCodeResponseDto": {diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goindex cdc94d183..85c2dd0db 100644--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -29,6 +29,11 @@ type SessionResponse struct {CreatedAt string `json:"createdAt,omitempty"`UpdatedAt string `json:"updatedAt,omitempty"`LastError *string `json:"lastError,omitempty"`+ // EngineLoaded reports whether the gateway holds a live engine for this session -- the+ // precondition stop/logout/force-kill require and start refuses. Not derivable from Status:+ // "disconnected" covers both a session mid automatic-reconnect (engine present) and one stopped+ // with no engine. Nil from a gateway that predates the field.+ EngineLoaded *bool `json:"engineLoaded,omitempty"`}// CreateSessionRequest is the body for creating a session. ProxyType is one of:diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.javaindex 6fec39b4b..abf339868 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java@@ -11,5 +11,12 @@ public record SessionResponse(String lastActive,String createdAt,String updatedAt,- /** Only present when {@code status == FAILED}. */- String lastError) {}+ /** Present when {@code status == FAILED} or {@code status == ACTION_REQUIRED}. */+ String lastError,+ /**+ * Whether the gateway holds a live engine for this session. The precondition the lifecycle+ * routes enforce; not derivable from {@code status}, since {@code DISCONNECTED} covers both a+ * session mid automatic-reconnect (engine present) and one stopped with no engine. {@code null}+ * from a gateway older than the field.+ */+ Boolean engineLoaded) {}diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.tsindex 16d6c03c8..e8e7f84eb 100644--- a/sdk/javascript/src/types.ts+++ b/sdk/javascript/src/types.ts@@ -50,6 +50,13 @@ export interface SessionResponse {updatedAt: string;/** Only present when `status === 'failed'` (terminal failure) or `status === 'action_required'` (operator must intervene). */lastError?: string | null;+ /**+ * Whether the gateway holds a live engine for this session right now — the precondition `stop`,+ * `logout` and `force-kill` require and `start` refuses. Not derivable from `status`:+ * `disconnected` covers both a session mid automatic-reconnect (engine present) and one stopped+ * with no engine. Absent from a gateway that predates the field.+ */+ engineLoaded?: boolean;}export interface CreateSessionRequest {diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex f281ff07c..efb9c7dd1 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -55,6 +55,11 @@ class SessionResponse(TypedDict, total=False):createdAt: strupdatedAt: strlastError: str | None+ # Whether the gateway holds a live engine for this session -- the precondition stop/logout/+ # force-kill require and start refuses. Not derivable from status: 'disconnected' covers both a+ # session mid automatic-reconnect (engine present) and one stopped with no engine. Absent from a+ # gateway that predates the field (the TypedDict is total=False).+ engineLoaded: boolclass CreateSessionRequest(TypedDict, total=False):diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.tsindex 948859310..26953dda6 100644--- a/src/config/configuration.spec.ts+++ b/src/config/configuration.spec.ts@@ -1,4 +1,8 @@-import configuration, { resolveNonNegativeIntEnv } from './configuration';+import configuration, {+ PINNED_BROWSER_LOCALE,+ resolveNonNegativeIntEnv,+ withPinnedBrowserLocale,+} from './configuration';describe('configuration — main DB synchronize', () => {const orig = process.env.MAIN_DATABASE_SYNCHRONIZE;@@ -48,12 +52,14 @@ describe('configuration — Puppeteer args delimiter', () => {// (a single glued token like "--no-sandbox --disable-gpu" silently neuters --no-sandbox).it('splits space-separated PUPPETEER_ARGS into discrete flags (dashboard-written form)', () => {process.env.PUPPETEER_ARGS = '--no-sandbox --disable-gpu';- expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--disable-gpu']);+ // The locale pin is appended after the split (see withPinnedBrowserLocale) — assert the split+ // itself, not the whole list, so this test keeps testing the delimiter and nothing else.+ expect(configuration().engine.puppeteer.args.slice(0, 2)).toEqual(['--no-sandbox', '--disable-gpu']);});it('still splits comma-separated PUPPETEER_ARGS (.env / docker-compose form)', () => {process.env.PUPPETEER_ARGS = '--no-sandbox,--disable-setuid-sandbox';- expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--disable-setuid-sandbox']);+ expect(configuration().engine.puppeteer.args.slice(0, 2)).toEqual(['--no-sandbox', '--disable-setuid-sandbox']);});it('defaults to the Docker-relevant sandbox flag set when unset', () => {@@ -63,6 +69,7 @@ describe('configuration — Puppeteer args delimiter', () => {'--disable-setuid-sandbox','--disable-dev-shm-usage','--disable-gpu',+ `--lang=${PINNED_BROWSER_LOCALE}`,]);});});@@ -307,3 +314,54 @@ describe('resolveNonNegativeIntEnv', () => {}});});++// WhatsApp Web renders its chrome in the BROWSER's language, and the onboarding-modal detector (#982)+// matches visible English text. Pinning the locale is what makes that match deterministic across the+// amd64 (Chrome for Testing) and arm64 (Debian chromium) images and any host install.+describe('withPinnedBrowserLocale', () => {+ it('appends the pin when the args carry no --lang', () => {+ expect(withPinnedBrowserLocale(['--no-sandbox'])).toEqual(['--no-sandbox', `--lang=${PINNED_BROWSER_LOCALE}`]);+ });++ it('leaves an operator-supplied --lang alone (theirs wins, and it is not duplicated)', () => {+ expect(withPinnedBrowserLocale(['--no-sandbox', '--lang=de-DE'])).toEqual(['--no-sandbox', '--lang=de-DE']);+ // `--lang` with no value, and the `--lang foo` spelling, both count as operator-supplied.+ expect(withPinnedBrowserLocale(['--lang'])).toEqual(['--lang']);+ });++ it('never mutates the input array', () => {+ // The resolved puppeteer args object is shared by every session; mutating it leaked one session's+ // proxy flag into the others once already (#840).+ const original = ['--no-sandbox'];+ const result = withPinnedBrowserLocale(original);+ expect(original).toEqual(['--no-sandbox']);+ expect(result).not.toBe(original);+ });+});++describe('configuration — puppeteer locale pin', () => {+ const orig = process.env.PUPPETEER_ARGS;++ afterEach(() => {+ if (orig === undefined) delete process.env.PUPPETEER_ARGS;+ else process.env.PUPPETEER_ARGS = orig;+ });++ it('pins the locale on the default args', () => {+ delete process.env.PUPPETEER_ARGS;+ expect(configuration().engine.puppeteer.args).toContain(`--lang=${PINNED_BROWSER_LOCALE}`);+ });++ // PUPPETEER_ARGS REPLACES the defaults, so applying the pin only to the default string would let any+ // deployment that customises args for an unrelated reason silently lose the onboarding detector.+ it('still pins the locale when the operator overrides PUPPETEER_ARGS', () => {+ process.env.PUPPETEER_ARGS = '--no-sandbox,--disable-gpu';+ const args = configuration().engine.puppeteer.args;+ expect(args).toEqual(['--no-sandbox', '--disable-gpu', `--lang=${PINNED_BROWSER_LOCALE}`]);+ });++ it('respects an explicit --lang inside PUPPETEER_ARGS', () => {+ process.env.PUPPETEER_ARGS = '--no-sandbox --lang=id-ID';+ expect(configuration().engine.puppeteer.args).toEqual(['--no-sandbox', '--lang=id-ID']);+ });+});diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 7a7368c9f..ee7a4f104 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -17,6 +17,29 @@ export function resolveNonNegativeIntEnv(raw: string | undefined, fallback: numbreturn Number(trimmed);}+/**+ * The UI locale Chromium is pinned to. WhatsApp Web renders its chrome — including the new-account+ * onboarding modal the whatsapp-web.js adapter dismisses (#982) — in the browser's language, and that+ * detector matches visible English text. Without a pin the language is whatever the launched binary+ * defaults to, which differs between the amd64 (Chrome for Testing) and arm64 (Debian chromium) images+ * and between host installs.+ */+export const PINNED_BROWSER_LOCALE = 'en-US';++/**+ * Append the locale pin unless the operator already set one. Deliberately applied AFTER the+ * PUPPETEER_ARGS override rather than baked into the default string: that variable REPLACES the+ * defaults, so a deployment that customises args for an unrelated reason would otherwise silently+ * lose the pin and the onboarding detector with it. An explicit `--lang` always wins.+ *+ * Returns a NEW array — never mutates the input — because the resolved args object is shared by every+ * session, and pushing per-session flags onto a shared array leaked proxy settings across sessions+ * once already (#840).+ */+export function withPinnedBrowserLocale(args: string[]): string[] {+ return args.some(arg => arg.startsWith('--lang')) ? [...args] : [...args, `--lang=${PINNED_BROWSER_LOCALE}`];+}+export default () => ({port: parseInt(process.env.PORT || '2785', 10),@@ -136,11 +159,11 @@ export default () => ({// Accept either delimiter: .env/compose use commas, the dashboard Infrastructure form// persists space-separated. Splitting on both keeps each flag a discrete argv token —// a single glued token like "--no-sandbox --disable-gpu" silently neuters --no-sandbox.- args: (- process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu'- )- .split(/[\s,]+/)- .filter(Boolean),+ args: withPinnedBrowserLocale(+ (process.env.PUPPETEER_ARGS || '--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--disable-gpu')+ .split(/[\s,]+/)+ .filter(Boolean),+ ),// Optional path to a system Chromium/Chrome binary. When unset, whatsapp-web.js// uses Puppeteer's bundled Chromium. Required on hosts where the bundled binary// is missing or incompatible (Alpine, ARM, custom base images).diff --git a/src/core/agent-tools/tools/session.tools.ts b/src/core/agent-tools/tools/session.tools.tsindex 5507a86df..14e23b906 100644--- a/src/core/agent-tools/tools/session.tools.ts+++ b/src/core/agent-tools/tools/session.tools.ts@@ -21,7 +21,7 @@ export function sessionTools(session: SessionService): ToolDescriptor[] {handler: (input: { limit?: number; offset?: number }, apiKey) =>session.findAll(apiKey.allowedSessions, { limit: input.limit, offset: input.offset })- .then(ss => ss.map(s => SessionResponseDto.fromEntity(s))),+ .then(ss => ss.map(s => SessionResponseDto.fromEntity(s, session.isActive(s.id)))),},{name: 'SessionFindOne',@@ -30,7 +30,7 @@ export function sessionTools(session: SessionService): ToolDescriptor[] {sessionScoped: true,inputSchema: z.object({ sessionId }),handler: (input: { sessionId: string }) =>- session.findOne(input.sessionId).then(s => SessionResponseDto.fromEntity(s)),+ session.findOne(input.sessionId).then(s => SessionResponseDto.fromEntity(s, session.isActive(s.id))),},{name: 'SessionGetChats',diff --git a/src/core/agent-tools/tools/tool-output-sanitisation.spec.ts b/src/core/agent-tools/tools/tool-output-sanitisation.spec.tsindex 2deb09d44..d42ff27e4 100644--- a/src/core/agent-tools/tools/tool-output-sanitisation.spec.ts+++ b/src/core/agent-tools/tools/tool-output-sanitisation.spec.ts@@ -126,6 +126,7 @@ describe('FIX 2: session tools strip config + proxyUrl', () => {it('SessionFindOne output has no config or proxyUrl keys', async () => {const sessionSvc = {findOne: jest.fn().mockResolvedValue(entity),+ isActive: jest.fn().mockReturnValue(false),} as unknown as SessionService;const tool = sessionTools(sessionSvc).find(t => t.name === 'SessionFindOne')!;@@ -140,6 +141,7 @@ describe('FIX 2: session tools strip config + proxyUrl', () => {it('SessionFindAll output items have no config or proxyUrl keys', async () => {const sessionSvc = {findAll: jest.fn().mockResolvedValue([entity]),+ isActive: jest.fn().mockReturnValue(false),} as unknown as SessionService;const tool = sessionTools(sessionSvc).find(t => t.name === 'SessionFindAll')!;@@ -160,6 +162,7 @@ describe('FIX 5: empty sessionId is rejected at validation', () => {it('a sessionScoped tool rejects sessionId: "" with BadRequestException', async () => {const sessionSvc = {findOne: jest.fn().mockResolvedValue(stubSessionEntity()),+ isActive: jest.fn().mockReturnValue(false),} as unknown as SessionService;const tool = sessionTools(sessionSvc).find(t => t.name === 'SessionFindOne')!;diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 5e68e39f7..142c50460 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -942,7 +942,18 @@ describe('WhatsAppWebJsAdapter credential-teardown observation', () => {return { client, onCredentialTeardownStarted };};+ // clearLocalAuth() really removes `<sessionDataPath>/session-<sessionId>`, and these tests assert+ // the registration contract rather than the removal itself. Stub the rm: unmocked, a developer whose+ // machine happens to hold a session named 'sess-1' would have its WhatsApp credentials deleted just+ // by running the suite — and force:true makes that silent.+ let rmSpy: jest.SpyInstance;++ beforeEach(() => {+ rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ });+afterEach(() => {+ rmSpy.mockRestore();jest.useRealTimers();});@@ -997,17 +1008,82 @@ describe('WhatsAppWebJsAdapter credential-teardown observation', () => {expect(onCredentialTeardownStarted).not.toHaveBeenCalled();});- it('does not register a credential teardown for a deliberate (tearingDown) LOGOUT — the caller already owns that cleanup', () => {- // client.logout() during adapter.logout() also fires disconnected:LOGOUT; the adapter must not- // double-track (the explicit logout() path already registered the promise).+ it('does not register a second credential teardown when THIS adapter started the logout', () => {+ // client.logout() during adapter.logout() also fires disconnected:LOGOUT. That path already+ // registered the real client.logout() promise, which covers the same rm, so the handler must not+ // add a redundant stand-in. Keyed on logoutInitiated — NOT on tearingDown, which every teardown+ // path sets (see the next test).const adapter = newAdapter();const { client, onCredentialTeardownStarted } = attach(adapter);+ (adapter as unknown as { logoutInitiated: boolean }).logoutInitiated = true;(adapter as unknown as { tearingDown: boolean }).tearingDown = true;client.emit('disconnected', 'LOGOUT');expect(onCredentialTeardownStarted).not.toHaveBeenCalled();});++ // The regression this pair guards: whatsapp-web.js runs authStrategy.logout() → fs.rm(userDataDir)+ // whatever our listener does. If a stop()/destroy() has already latched the finished flags, an+ // early return would hide that in-flight rm from the name fence, and a later start() under the same+ // session name could have its freshly written profile deleted by it.+ it('registers the credential teardown for a WhatsApp LOGOUT that lands after a stop/destroy set tearingDown', () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);+ // disconnect()/destroy()/forceDestroy() all set this WITHOUT owning a credential teardown.+ (adapter as unknown as { tearingDown: boolean }).tearingDown = true;++ client.emit('disconnected', 'LOGOUT');++ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ const [tracked] = onCredentialTeardownStarted.mock.calls[0] as [Promise<void>];+ expect(tracked).toBeInstanceOf(Promise);+ // The registered promise is the profile removal itself, not an unrelated resolved promise — and+ // asserting on the spy also proves the stub above is the fs call being made, not the real one.+ expect(rmSpy).toHaveBeenCalledWith(expect.stringContaining('session-sess-1'), {+ recursive: true,+ force: true,+ });+ });++ it('registers the credential teardown for a WhatsApp LOGOUT that lands after a disconnect was already reported', () => {+ const adapter = newAdapter();+ const { client, onCredentialTeardownStarted } = attach(adapter);+ // setStatus(DISCONNECTED) latches this on the first drop; a LOGOUT arriving afterwards still+ // means the library is deleting the profile.+ (adapter as unknown as { disconnectReported: boolean }).disconnectReported = true;++ client.emit('disconnected', 'LOGOUT');++ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ });++ it('still reports nothing else for a latched LOGOUT — no status change and no onDisconnected', () => {+ // Registering the rm must NOT resurrect the rest of the handler: a finished adapter still must+ // not drive a status transition or schedule a reconnect for its replacement.+ const adapter = newAdapter();+ const client = Object.assign(new EventEmitter(), {+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },+ }) as FakeClient;+ const onCredentialTeardownStarted = jest.fn();+ const onDisconnected = jest.fn();+ const onStateChanged = jest.fn();+ (adapter as unknown as { client: unknown }).client = client;+ (adapter as unknown as { callbacks: unknown }).callbacks = {+ onCredentialTeardownStarted,+ onDisconnected,+ onStateChanged,+ };+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();+ (adapter as unknown as { tearingDown: boolean }).tearingDown = true;++ client.emit('disconnected', 'LOGOUT');++ expect(onCredentialTeardownStarted).toHaveBeenCalledTimes(1);+ expect(onDisconnected).not.toHaveBeenCalled();+ expect(onStateChanged).not.toHaveBeenCalled();+ });});describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {@@ -5135,4 +5211,70 @@ describe('probeOnboardingModal (in-page onboarding modal detection)', () => {install([]);expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });});++ // ── Localised modal ─────────────────────────────────────────────────────────+ // The match is on visible text, so a WhatsApp Web rendering this modal in another language is+ // invisible to the English default. An operator can add their label; that path deliberately does not+ // also require the English heading, which would reject the very modal it is meant to reach.++ it('ignores a localised modal with the default English label — the pre-existing behaviour', () => {+ const button = el('Continuar', { button: true });+ nest(el('Novedades de WhatsApp Web'), button);+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ expect(button.click).not.toHaveBeenCalled();+ });++ it('clicks a localised confirm button when the operator supplied its label', () => {+ const button = el('Continuar', { button: true });+ nest(el('Novedades de WhatsApp Web'), button);+ install([button]);++ const result = probeOnboardingModal({+ labels: ['Continue', 'Continuar'],+ headingOptionalFor: ['Continuar'],+ });++ expect(result).toEqual({ modalPresent: true, dismissed: true });+ expect(button.click).toHaveBeenCalledTimes(1);+ });++ // The loosening is scoped to the operator's own labels: the default label keeps its heading guard, so+ // configuring an extra label cannot start matching stray "Continue" buttons elsewhere on the page.+ it('still requires the heading for the default label even when extra labels are configured', () => {+ const button = el('Continue', { button: true });+ nest(el('some unrelated panel'), button);+ install([button]);++ const result = probeOnboardingModal({+ labels: ['Continue', 'Continuar'],+ headingOptionalFor: ['Continuar'],+ });++ expect(result).toEqual({ modalPresent: false, dismissed: false });+ expect(button.click).not.toHaveBeenCalled();+ });++ it('never clicks a hidden localised button', () => {+ const button = el('Continuar', { button: true, hidden: true });+ install([button]);++ expect(probeOnboardingModal({ labels: ['Continue', 'Continuar'], headingOptionalFor: ['Continuar'] })).toEqual({+ modalPresent: false,+ dismissed: false,+ });+ expect(button.click).not.toHaveBeenCalled();+ });++ it('matches the label exactly, so a longer string containing it is not a confirm button', () => {+ const button = el('Continuar con la copia de seguridad', { button: true });+ install([button]);++ expect(probeOnboardingModal({ labels: ['Continue', 'Continuar'], headingOptionalFor: ['Continuar'] })).toEqual({+ modalPresent: false,+ dismissed: false,+ });+ expect(button.click).not.toHaveBeenCalled();+ });});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 02eed4893..485600c14 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -308,50 +308,78 @@ const ONBOARDING_MODAL_PROBE_TIMEOUT_MS = 5_000;// Five failed clicks still trips in ~25s — far inside the lifetime cap and the ~5m unlink deadline.const ONBOARDING_MODAL_MAX_DISMISS_CLICKS = 5;+/** The modal's confirm-button label on an English WhatsApp Web. */+const ONBOARDING_DEFAULT_CONTINUE_LABEL = 'Continue';++/**+ * Extra confirm-button labels for a deployment whose WhatsApp Web does not render this modal in+ * English, comma-separated (`WWEBJS_ONBOARDING_CONTINUE_LABELS=Continuar,Weiter`).+ *+ * Needed because the match is on visible text and WhatsApp controls those strings — we are not going+ * to carry its translation table. Read per probe, not cached, so an operator can correct a running+ * deployment through the infra config without a restart.+ *+ * Supplying labels also drops the heading requirement for THOSE labels: the English heading regex+ * would reject a localised modal anyway, so requiring both would make the setting useless. That is a+ * deliberate, operator-opted-in loosening — see {@link probeOnboardingModal}.+ */+function resolveOnboardingContinueLabels(): string[] {+ const extra = (process.env.WWEBJS_ONBOARDING_CONTINUE_LABELS ?? '')+ .split(',')+ .map(label => label.trim())+ .filter(Boolean);+ return [ONBOARDING_DEFAULT_CONTINUE_LABEL, ...extra];+}+/**- * In-page probe for the onboarding modal: click its Continue button if it is on screen.+ * In-page probe for the onboarding modal: click its confirm button if it is on screen.** Exported and self-contained on purpose. `page.evaluate` stringifies this into the browser, so it- * may not close over anything in this module — and being a plain function means the DOM matching can- * be unit-tested directly, rather than only through a mocked `evaluate` that proves nothing about the- * matching itself.+ * may not close over anything in this module — every input arrives as an argument — and being a plain+ * function means the DOM matching can be unit-tested directly, rather than only through a mocked+ * `evaluate` that proves nothing about the matching itself.** The BUTTON is the presence signal, never the heading text on its own. `textContent` on a `div`* concatenates every descendant, so a chat-list row previewing the words "what's new" — an ordinary* English message — satisfies a heading-only test. Treating that as a stuck modal would take a* perfectly healthy session out of READY and block every send. A visible control whose exact label is- * "Continue", sitting within a few levels of an element that also carries the heading, is a shape the- * chat list does not produce. The ancestor walk is bounded for the same reason: matching against- * `<body>` would just be the loose text test again.+ * the confirm label, sitting within a few levels of an element that also carries the heading, is a+ * shape the chat list does not produce. The ancestor walk is bounded for the same reason: matching+ * against `<body>` would just be the loose text test again.*- * ENGLISH-ONLY, by decision: both the button label and the heading are matched as English strings, so- * this only works while WhatsApp Web renders the modal in English. That language follows the browser- * locale — which nothing here sets (no `--lang` in the launch args, no `Accept-Language` override), so- * it is whatever the browser this deployment launches defaults to (`PUPPETEER_EXECUTABLE_PATH`, or- * Puppeteer's bundled Chromium when that is unset), NOT something derived from the linked account.- * Against a localised modal this returns `{modalPresent:false}` on every tick it runs: it is never- * dismissed and the watcher never escalates — it just ages out at the lifetime cap — so that- * deployment keeps the pre-#982 behaviour. Failing silent is- * deliberate — the alternative is carrying WhatsApp's translation table for two strings it controls,- * and a looser match (any visible button inside a dialog-ish container) would take healthy sessions- * out of READY, which is strictly worse than not fixing the modal. Limitation is in the CHANGELOG.+ * LANGUAGE. The default label and the heading are English, and the modal is rendered in whatever+ * language WhatsApp Web decides. Two things address that, both defaulting to today's behaviour:+ * the launch args pin `--lang` so the page has a deterministic locale, and an operator can add+ * their own labels (see {@link resolveOnboardingContinueLabels}). An operator-supplied label matches+ * WITHOUT the heading check — the English heading would reject a localised modal regardless, so+ * requiring both would make the setting inert. The default `Continue` keeps the heading requirement,+ * so the out-of-the-box false-positive surface is unchanged.*/-export function probeOnboardingModal(): { modalPresent: boolean; dismissed: boolean } {+export function probeOnboardingModal(options?: { labels?: string[]; headingOptionalFor?: string[] }): {+ modalPresent: boolean;+ dismissed: boolean;+} {const isVisible = (el: Element): boolean => {const rect = (el as HTMLElement).getBoundingClientRect();return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;};+ const labels = options?.labels?.length ? options.labels : ['Continue'];+ const headingOptional = new Set(options?.headingOptionalFor ?? []);// Both apostrophes: WhatsApp Web renders the typographic U+2019, and an ASCII quote appears in// older builds. Matching only the ASCII form means never recognising the real modal.const heading = /what[’']?s new/i;- const buttons = Array.from(document.querySelectorAll('button, [role="button"]')).filter(- el => isVisible(el) && (el.textContent || '').trim() === 'Continue',- );- for (const button of buttons.reverse()) {- let scope: Element | null = button;+ const candidates = Array.from(document.querySelectorAll('button, [role="button"]'))+ .map(el => ({ el, label: (el.textContent || '').trim() }))+ .filter(c => isVisible(c.el) && labels.includes(c.label));+ for (const { el, label } of candidates.reverse()) {+ if (headingOptional.has(label)) {+ (el as HTMLElement).click();+ return { modalPresent: true, dismissed: true };+ }+ let scope: Element | null = el;for (let depth = 0; depth < 8 && scope; depth++, scope = scope.parentElement) {if (!heading.test(scope.textContent || '')) continue;- (button as HTMLElement).click();+ (el as HTMLElement).click();return { modalPresent: true, dismissed: true };}}@@ -439,6 +467,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Set once teardown begins so a late 'authenticated' can't resurrect a disconnecting adapter. Not// reset — an adapter is single-use after teardown (the session creates a fresh one to reconnect).private tearingDown = false;+ // Set by logout() before it starts the native unlink, which itself registers the real+ // `client.logout()` promise as the credential teardown. The 'disconnected' LOGOUT handler consults+ // this to avoid registering a second, redundant stand-in for the same profile rm — while still+ // registering one for a WhatsApp-initiated logout, including one that lands after another teardown+ // path has already latched the flags below.+ private logoutInitiated = false;// Set once the adapter ACTIVELY transitions to DISCONNECTED (engine disconnect, puppeteer death,// stuck-auth recovery, teardown). Same single-use contract as `tearingDown`, but it latches earlier:// on LOGOUT whatsapp-web.js keeps the browser and re-runs inject(), while the lifecycle only replaces@@ -962,13 +996,28 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginthis.client.on('call', call => this.handleIncomingCall(call));this.client.on('disconnected', reason => {+ // A LOGOUT means whatsapp-web.js is ABOUT to delete this session's profile: `Client.logout()`+ // ends in `authStrategy.logout()` → `LocalAuth.logout()` → `fs.rm(userDataDir)`, and the+ // library emits this event BEFORE that await (Client.js: emit DISCONNECTED 'LOGOUT', then+ // `pupBrowser.close()`, then `authStrategy.logout()`). That rm happens whatever this listener+ // does, so it MUST be surfaced to the lifecycle before the latch check below can drop out —+ // otherwise a stop()/destroy() that latched first hides an in-flight rm, the name fence sees+ // nothing pending, and a later start() under the same name can have its freshly written+ // profile deleted by it (the #994 hazard, through a narrower window).+ //+ // Skipped only when THIS adapter's logout() started it: that path already registered the real+ // `client.logout()` promise, which covers the same rm and settles no earlier.+ if (reason === 'LOGOUT' && !this.logoutInitiated) {+ // Idempotent stand-in for the library's own rm, which we cannot get a handle on:+ // `fs.rm(force: true)` races it safely and gives the lifecycle something to await.+ this.callbacks.onCredentialTeardownStarted?.(this.clearLocalAuth());+ }// A deliberate teardown (logout/disconnect/destroy/forceDestroy via beginClientTeardown) also// raises this event: client.logout() triggers the in-page Cmd 'logout' → framenavigated →// DISCONNECTED 'LOGOUT' while we are still awaiting it. The unlink is already acknowledged by// the API response and the session service writes DISCONNECTED itself, so report nothing here- // (mirrors the puppeteer-death gate). The credential-teardown promise for that path was already- // registered by logout() itself, so do NOT double-register here. A WhatsApp-initiated unlink- // arrives with tearingDown=false and still flows through.+ // (mirrors the puppeteer-death gate). A WhatsApp-initiated unlink arrives with+ // tearingDown=false and still flows through to the status/callback below.//// setStatus(DISCONNECTED) below latches disconnectReported synchronously on the first event, so a// duplicate native 'disconnected' (whatsapp-web.js can fire it more than once for one drop) must@@ -976,21 +1025,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// onDisconnected re-run and the lifecycle schedules a second reconnect.if (this.tearingDown || this.disconnectReported) return;this.clearReadyReconcile();- // #982: LOGOUT is not a transient drop. whatsapp-web.js emits it when WhatsApp Web itself ran a- // logout (its in-page `Cmd` logout bus). The library emits `disconnected: LOGOUT` BEFORE it- // awaits `authStrategy.logout()` (LocalAuth.logout() → fs.rm of this session's profile dir), so- // at this moment the credentials are ABOUT to be removed, not already gone. The lifecycle's- // reconnect cannot restore the link; it can only come back with a fresh QR. Say that here rather- // than leaving the operator with an opaque engine token that reads like any other drop.+ // #982: LOGOUT is not a transient drop. The lifecycle's reconnect cannot restore the link; it+ // can only come back with a fresh QR. Say that here rather than leaving the operator with an+ // opaque engine token that reads like any other drop.if (reason === 'LOGOUT') {- // Surface the destructive credential cleanup to the lifecycle SYNCHRONOUSLY, before the event- // loop can run a start()/reconnect: the lib's authStrategy.logout() (the rm) is about to settle- // right after this handler returns. We can't grab the lib's internal promise, so the adapter- // runs its own idempotent clearLocalAuth() (fs.rm with force:true races the lib's rm safely) as- // the tracked operation. A concurrent start()/delete() under the SAME session name then sees the- // in-flight rm and waits for it instead of re-creating/purging credentials the rm is deleting.- const cleanup = this.clearLocalAuth();- this.callbacks.onCredentialTeardownStarted?.(cleanup);this.logger.warn('WhatsApp unlinked this device (LOGOUT). whatsapp-web.js is deleting the stored credentials ' +'for this session, so reconnecting cannot restore the link — the session comes back with a ' +@@ -1328,12 +1366,21 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin*/private async dismissOnboardingModalIfNeeded(): Promise<void> {if (!this.client) return;- const page = (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } }).pupPage;+ const page = (+ this.client as unknown as {+ pupPage?: { evaluate: <T, A>(fn: (arg: A) => T, arg: A) => Promise<T> };+ }+ ).pupPage;++ // Resolved out here, not inside the probe: the function body is stringified into the page, so it+ // cannot read process.env. Operator-supplied labels skip the English heading check (see the probe).+ const labels = resolveOnboardingContinueLabels();+ const headingOptionalFor = labels.filter(label => label !== ONBOARDING_DEFAULT_CONTINUE_LABEL);let timeout: ReturnType<typeof setTimeout> | undefined;try {const result = await Promise.race([- page?.evaluate(probeOnboardingModal),+ page?.evaluate(probeOnboardingModal, { labels, headingOptionalFor }),new Promise<never>((_, reject) => {timeout = setTimeout(() => reject(new Error('onboarding modal probe timed out')),@@ -1604,6 +1651,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}async logout(): Promise<void> {+ // Claim the LOGOUT credential registration before anything can emit 'disconnected': the native+ // unlink below registers the real promise, so the event handler must not add a stand-in for it.+ // Set even if there is no live client — the throw path sends nothing, so no event can arrive.+ this.logoutInitiated = true;const client = this.beginClientTeardown();// No live client means there is nothing to send the unlink through. Resolving here would report a// confirmed unlink for a request that never reached WhatsApp — the caller writes an audit row ondiff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 9a35e3ee6..0f7d9d0eb 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -40,12 +40,29 @@ export class SessionResponseDto {})lastError?: string | null;+ @ApiProperty({+ description:+ 'Whether the gateway currently holds a live engine for this session. This is the precondition ' ++ 'the lifecycle routes actually enforce, and `status` alone does not imply it: a `disconnected` ' ++ 'session keeps its engine for the duration of an automatic reconnect backoff, while a session ' ++ 'stopped through `POST /sessions/:id/stop` carries the same status with no engine. When `true`, ' ++ '`stop`, `logout` and `force-kill` can act and `start` answers 400; when `false`, the reverse. ' ++ 'Derived per request from live process state, so it is never persisted and never historical.',+ example: true,+ })+ engineLoaded: boolean;+/*** Map a Session entity to the public response shape, stripping sensitive* engine config fields (`config`, `proxyUrl`, `proxyType`) that must not* appear in any API response.+ *+ * `engineLoaded` is not on the entity — it is live process state owned by the session service, so+ * every caller must pass it in rather than letting it default. A required parameter is deliberate:+ * a default of `false` would silently tell clients "no engine" for whole surfaces (the MCP tools,+ * any future caller) and the dashboard would then offer Start to a running session.*/- static fromEntity(session: Session): SessionResponseDto {+ static fromEntity(session: Session, engineLoaded: boolean): SessionResponseDto {return {id: session.id,name: session.name,@@ -57,6 +74,7 @@ export class SessionResponseDto {createdAt: session.createdAt,updatedAt: session.updatedAt,lastError: session.lastError ?? null,+ engineLoaded,};}}diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.tsindex 8e29050ad..5a3300efe 100644--- a/src/modules/session/session.controller.spec.ts+++ b/src/modules/session/session.controller.spec.ts@@ -27,12 +27,14 @@ describe('SessionController — create() response contract', () => {updatedAt: new Date('2026-01-01T00:00:00Z'),};- let sessionService: { create: jest.Mock };+ let sessionService: { create: jest.Mock; isActive: jest.Mock };let auditService: { logInfo: jest.Mock };let controller: SessionController;beforeEach(() => {- sessionService = { create: jest.fn().mockResolvedValue({ ...entity }) };+ // transformSession reads live engine state for `engineLoaded`; a freshly created session has no+ // engine yet, which is what the response must say.+ sessionService = { create: jest.fn().mockResolvedValue({ ...entity }), isActive: jest.fn().mockReturnValue(false) };auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };controller = new SessionControllerClass(sessionService as unknown as SessionService,@@ -63,9 +65,21 @@ describe('SessionController — create() response contract', () => {createdAt: entity.createdAt,updatedAt: entity.updatedAt,lastError: null,+ engineLoaded: false,});});+ // engineLoaded is live process state, not an entity column, so the only thing that can get it wrong+ // is the wiring. Assert both answers come from the service rather than from the row's status.+ it('reports engineLoaded from the live engine map, not from the row status', async () => {+ sessionService.isActive.mockReturnValue(true);++ const result = await controller.create({ name: 'test-session' });++ expect(result.engineLoaded).toBe(true);+ expect(sessionService.isActive).toHaveBeenCalledWith(entity.id);+ });+it('still audits the creation with the session id and name', async () => {await controller.create({ name: 'test-session' });@@ -95,12 +109,12 @@ describe('SessionController — logout() audit + error forwarding contract', ()updatedAt: new Date('2026-01-01T00:00:00Z'),};- let sessionService: { logout: jest.Mock };+ let sessionService: { logout: jest.Mock; isActive: jest.Mock };let auditService: { logInfo: jest.Mock };let controller: SessionController;beforeEach(() => {- sessionService = { logout: jest.fn() };+ sessionService = { logout: jest.fn(), isActive: jest.fn().mockReturnValue(false) };auditService = { logInfo: jest.fn().mockResolvedValue(undefined) };controller = new SessionControllerClass(sessionService as unknown as SessionService,diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex cd4f10832..0f19d0126 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -31,7 +31,9 @@ export class SessionController {) {}private transformSession(session: Session): SessionResponseDto {- return SessionResponseDto.fromEntity(session);+ // isActive() is the engine map itself, so this is read at response time — a session that just+ // finished reconnecting reports the engine in the same response that reports its status.+ return SessionResponseDto.fromEntity(session, this.sessionService.isActive(session.id));}@Post()