Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): require real evidence before a session leaves ready or reports an unlink (#1003)
Yudhi Armyndharis20af3bdf8715
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 308533aec..a9562e48c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,20 +10,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- **The whatsapp-web.js engine auto-dismisses a new account's "What's new on WhatsApp Web" onboarding- modal** (#982). A freshly-linked account shows this modal after `ready`, and left unacknowledged it+ modal** (#982, #1003). A freshly-linked account shows this modal after `ready`, and left unacknowledged itgets the companion unlinked roughly five minutes later — surfacing as `disconnected: LOGOUT`.whatsapp-web.js exposes no API for the modal (its own #3550 is still open), so the adapter reaches- the underlying page directly and clicks Continue best-effort, matching by the visible button/modal- text (stable across WhatsApp Web builds, unlike class selectors). The watcher starts on `ready` and- self-terminates after a lifetime cap since the modal is one-shot per account. When the dismissal- cannot be performed — the selector has moved, the page is unreachable, or no Continue button was- found — the session moves to a new **`action_required`** status instead of being silently logged- out. That status carries a human-readable reason via `lastError` (relaxed from FAILED-only to also- cover ACTION_REQUIRED) and flows through the existing `session.status` webhook and WebSocket- channels, the dashboard status pill, and all five SDKs. The watcher's interval, lifetime cap, and- probe timeout are bounded and `.unref()`'d, and it is cleared on every teardown path.--- **`POST /sessions/:id/logout` unlinks the device from the WhatsApp account** (#984). Both engines+ the underlying page directly and clicks Continue best-effort, matching by visible text rather than+ class selectors, which WhatsApp Web rebuilds across releases. The watcher starts on `ready` and+ self-terminates after a lifetime cap since the modal is one-shot per account; its interval, cap and+ probe timeout are all bounded and `.unref()`'d, and it is cleared on every teardown path.++ Detection keys on the **Continue button**, within a bounded number of levels of an element that also+ carries the heading — not on the heading text alone. An element's text content includes all of its+ descendants, so a chat-list row previewing the words "what's new", an entirely ordinary English+ message, satisfies a heading-only test; a control whose exact label is "Continue" sitting inside+ that same subtree is a shape the chat list does not produce. The heading match accepts the+ typographic apostrophe WhatsApp Web actually renders as well as the ASCII one.++ A session leaves `ready` only when Continue has been clicked repeatedly and the modal is still+ there — evidence the click is not landing and a human has to acknowledge it on the phone. It then+ moves to a new **`action_required`** status carrying a human-readable reason via `lastError`+ (relaxed from FAILED-only to also cover this status), which flows through the existing+ `session.status` webhook and WebSocket channels, the dashboard status pill, and all five SDKs. A+ probe that cannot reach the page — a reload, a teardown, a timeout — is logged and otherwise+ ignored: it says nothing about the modal, and taking a working session out of `ready` blocks every+ send for a reason the operator cannot act on. The status is deliberately expensive to reach for+ that reason.++- **`POST /sessions/:id/logout` unlinks the device from the WhatsApp account** (#984, #1003). Both enginesalready implemented a real protocol-level unlink — whatsapp-web.js calls `WAWebSocketModel.Socket.logout()`and Baileys sends `<remove-companion-device reason="user_initiated"/>` — but the method had no caller,so it was unreachable over the API. `stop()` disconnects while keeping the stored credentials (a later@@ -35,11 +47,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0audit action so an intentional unlink is distinguishable from a plain stop or a WhatsApp-side eviction.The route requires a started session: with no engine loaded there is nothing to send the unlinkthrough, so it returns 400 instead of reporting an unlink that never happened (unlike `stop()`,- which treats an already-stopped session as a successful no-op). If the engine's logout does not- complete, the session is still torn down locally but the route returns 502 — the unlink was not- confirmed, no `SESSION_LOGGED_OUT` audit row is written, and the stored credentials survive so- the retry needs no QR scan (#993). It is additive: the stop, delete, and force-kill semantics- are unchanged.+ which treats an already-stopped session as a successful no-op). The engines enforce the same rule+ one level down — a loaded engine whose browser or socket has gone (a stuck-auth recovery, or a+ WhatsApp-side logout still inside its reconnect backoff) refuses the unlink rather than resolving+ as though it had sent one, which would have produced a success response and a `SESSION_LOGGED_OUT`+ audit row for a device still listed under Linked Devices.++ If the engine's logout does not complete, the session is still torn down locally but the route+ returns 502 — the unlink was not confirmed and no `SESSION_LOGGED_OUT` audit row is written+ (#993). Whether the retry needs a QR scan depends on how it failed: an engine that refused the+ logout sent and deleted nothing, so the credentials survive; an attempt that ran past the 10s+ teardown deadline is still running, and on whatsapp-web.js it ends in the profile deletion a+ successful unlink performs, so that session comes back with a fresh QR. `docs/06` spells both out.+ It is additive: the stop, delete, and force-kill semantics are unchanged.- **All five SDKs and the dashboard's API client gain the session logout operation** (#984). TheJavaScript, Python, Go, PHP, and Java SDKs each expose a `logout` method mirroring the neighbouring@@ -48,18 +68,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the audit-action enumeration in `docs/05`, the method tables in `docs/18` and `sdk/README.md`) nowinclude the route.-- **The dashboard's Sessions page gains an Unlink action** (#984). Wired to the logout endpoint, it+- **The dashboard's Sessions page gains an Unlink action** (#984, #1003). Wired to the logout endpoint, itis the only lifecycle button that tells WhatsApp anything: the device disappears from the accountholder's Linked Devices list, and reconnecting requires a fresh QR scan or pairing code. It islabelled "Unlink" rather than "Logout" so it cannot be confused with the sidebar's own- (authentication) logout, and it appears for exactly the states that have a live engine — the same- visibility as Stop. The confirmation dialog spells out both consequences (fresh QR to reconnect;+ (authentication) logout. Unlink and Stop now derive their visibility from one shared definition of+ "this session has a live engine", so the card can never offer an action the API rejects — and, in+ the other direction, never offers Start to a session that is already started, which answers 400 and+ then leaves a QR dialog open that cannot resolve. That definition now includes `authenticating`+ (the whatsapp-web.js engine can hold it for 90 seconds) and `action_required`, neither of which+ previously offered any working action. The confirmation dialog spells out both consequences (fresh QR to reconnect;delete the session separately if local data should go too), and the 502 case — session stoppedlocally but the unlink unconfirmed by WhatsApp — surfaces as a warning toast with retry guidanceinstead of a plain error. Localized across all twelve dashboard locales.### Fixed+- **`send-document` really sends a document on the whatsapp-web.js engine** (#989, #1003). Without an+ explicit document flag, WhatsApp Web classifies an attachment from its declared mimetype, so an+ `image/*`, `video/*` or `audio/*` payload posted to the document endpoint arrived as a photo, video+ or audio bubble — re-encoded, and with its filename dropped. Baileys has always forced the document+ form, so the two engines disagreed on the same request. The flag is withheld for `status@broadcast`+ and broadcast lists, where whatsapp-web.js refuses every recipient once it is set: setting it there+ would turn a working send into a failure rather than improve it, so those recipients keep the+ classification they have today. A document with no filename now defaults to `file` instead of+ reaching the recipient labelled literally `undefined`.++- **A remote-URL send keeps the mimetype and filename the caller declared.** Media fetched from a URL+ derived both from the response — content-type and URL basename — because that is all the fetch has+ to go on, and it overrode what the request actually said. The caller's values now win, matching what+ the Baileys engine already did; `application/octet-stream` is treated as the placeholder it is+ rather than a statement about the bytes, so omitting the mimetype still falls back to the response.++ Stickers are the one exception, and keep the fetched content-type. There the mimetype is not a label+ but an instruction: whatsapp-web.js picks the conversion from it and returns the media untouched once+ it reads as `image/webp`. A URL sticker declared `image/webp` over bytes that are not webp would+ therefore be sent unconverted. The response saw those bytes and the caller did not, so for that one+ decision it is the better source. A declared filename still wins everywhere — nothing branches on it.+- **A wedged logout can no longer delete a freshly re-paired profile** (#994). `teardownEngineSafely`races an engine teardown against a 10s deadline, but the losing promise kept running — and`logout()`'s ends in an `fs.rm` of the session's on-disk profile, the same deterministic path a@@ -70,7 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0window is logged.- **`npm install` from source no longer fails on native Windows, and the whatsapp-web.js backport- actually applies there** (#889). A unified diff's lines must begin with a space, `+`, `-` or `@`, so+ actually applies there** (#889, #1003). A unified diff's lines must begin with a space, `+`, `-` or `@`, soneither applier accepts one whose lines end CRLF — both stop at this patch's first empty contextline (`git apply`: "corrupt patch at line 7"; `patch`: "malformed patch at line 7"). Windows checksthe file out exactly that way whenever `core.autocrlf` is on, which is its default, so the `git@@ -79,8 +125,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0Three changes: the patch is normalized to LF before either applier sees it, which also repairsclones already on disk with CRLF; a `.gitattributes` rule keeps fresh clones on LF; and a refusal toparse the patch is now correctly treated as "nothing was written", so `--best-effort` degrades- instead of aborting the install. Only source installs on Windows were affected — the published- Docker image and every platform with the `patch` binary applied the backport normally.+ instead of aborting the install. That last one is matched on the messages `git apply` emits before+ it writes anything, not on its exit code alone — the code is shared with fatals raised part-way+ through writing results, and calling one of those a pristine tree would let `--best-effort` wave a+ half-patched dependency through as a clean skip, which is the one outcome it must never produce.+ Only source installs on Windows were affected — the published Docker image and every platform with+ the `patch` binary applied the backport normally.- **Native Windows and npm 12 source installs no longer fail during dependency setup.** Thewhatsapp-web.js backport now normalizes reject-file paths before comparing them, so Windows'diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex ba802de24..8ee5be022 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -314,7 +314,7 @@"disconnectedTitle": "ה-Session נותק","disconnectedDesc": "ה-Session של WhatsApp נותק","actionRequiredTitle": "נדרשת פעולה",- "actionRequiredDesc": "תקנת זו דורשת את תשומת לבך. פתח את התקנה כדי לראות מה לעשות.",+ "actionRequiredDesc": "ה-Session הזה דורש את תשומת לבך. פתחו את ה-Session כדי לראות מה לעשות.","failedTitle": "ה-Session נכשל","failedDesc": "ה-Session של WhatsApp נכשל באתחול. פתחו את ה-Session כדי לראות את הסיבה."},diff --git a/dashboard/src/pages/Sessions.css b/dashboard/src/pages/Sessions.cssindex a40854eaf..4f86f95f6 100644--- a/dashboard/src/pages/Sessions.css+++ b/dashboard/src/pages/Sessions.css@@ -645,9 +645,12 @@color: var(--info);}+/* Same amber token as the transient states above — a literal here was the only pill not on a theme+ variable, and it lost contrast on the dark card. The heavier tint is what separates "needs a human"+ from the in-progress amber, since the two must not read alike. */.sessions-page .status-pill.action_required {- background: rgba(245, 158, 11, 0.1);- color: #d97706;+ background: rgba(245, 158, 11, 0.22);+ color: var(--warning);}.sessions-page .status-pill.ready {diff --git a/dashboard/src/pages/Sessions.tsx b/dashboard/src/pages/Sessions.tsxindex be11e4b45..23360cd50 100644--- a/dashboard/src/pages/Sessions.tsx+++ b/dashboard/src/pages/Sessions.tsx@@ -18,7 +18,7 @@ import {import { sessionApi, type Session } from '../services/api';import { queryKeys } from '../hooks/queries';import { useDocumentTitle } from '../hooks/useDocumentTitle';-import { canUnlinkSession, classifyUnlinkError } from '../utils/sessionUnlink';+import { canUnlinkSession, classifyUnlinkError, isSessionStarted } from '../utils/sessionActions';import { useToast } from '../components/Toast';import { useWebSocket } from '../hooks/useWebSocket';import { useRole } from '../hooks/useRole';@@ -874,17 +874,17 @@ export function Sessions() {<Eye size={16} />{t('sessions.actions.view')}</button>- {canWrite &&- (session.status === 'created' || session.status === 'idle' || session.status === 'disconnected') ? (- <button className="btn-action" onClick={() => handleStart(session.id)}>- <Play size={16} />- {t('sessions.actions.start')}- </button>- ) : canWrite && ['ready', 'initializing', 'connecting', 'qr_ready'].includes(session.status) ? (+ {canWrite && isSessionStarted(session.status) ? (<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') ? (+ <button className="btn-action" onClick={() => handleStart(session.id)}>+ <Play size={16} />+ {t('sessions.actions.start')}+ </button>) : canWrite ? (<button className="btn-action" onClick={() => handleStart(session.id)}><RefreshCw size={16} />diff --git a/dashboard/src/utils/sessionActions.test.ts b/dashboard/src/utils/sessionActions.test.tsnew file mode 100644index 000000000..ae70d1193--- /dev/null+++ b/dashboard/src/utils/sessionActions.test.ts@@ -0,0 +1,54 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { canUnlinkSession, classifyUnlinkError, isSessionStarted } from './sessionActions.ts';++// 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);+ }+ for (const status of ['created', 'idle', 'disconnected', 'failed']) {+ assert.equal(isSessionStarted(status), 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 ['created', 'idle', 'disconnected', 'failed']) {+ assert.equal(canUnlinkSession(status, true), false, status);+ }+});++test('canUnlinkSession: a read-only role never sees the action, even for a started session', () => {+ assert.equal(canUnlinkSession('ready', false), false);+});++test('classifyUnlinkError: the gateway 502 means the unlink was unconfirmed, not a plain failure', () => {+ const err = new Error('Session was stopped locally, but WhatsApp did not confirm') as Error & {+ status?: number;+ };+ err.status = 502;+ assert.equal(classifyUnlinkError(err), 'unconfirmed');+});++// A reverse proxy answers 502 too, and then nothing was stopped — telling the operator to retry the+// unlink would be wrong. The API client's non-JSON fallback message is what distinguishes them.+test('classifyUnlinkError: a reverse-proxy 502 is generic, not unconfirmed', () => {+ const err = new Error('HTTP 502') as Error & { status?: number };+ err.status = 502;+ assert.equal(classifyUnlinkError(err), 'generic');+});++test('classifyUnlinkError: everything else is generic', () => {+ for (const status of [400, 401, 403, 404, 500, 503]) {+ const err = new Error('x') as Error & { status?: number };+ err.status = status;+ assert.equal(classifyUnlinkError(err), 'generic', String(status));+ }+ assert.equal(classifyUnlinkError(new Error('network down')), 'generic'); // no status at all+ assert.equal(classifyUnlinkError(undefined), 'generic');+});diff --git a/dashboard/src/utils/sessionActions.ts b/dashboard/src/utils/sessionActions.tsnew file mode 100644index 000000000..c74164528--- /dev/null+++ b/dashboard/src/utils/sessionActions.ts@@ -0,0 +1,43 @@+// Which lifecycle actions a session card offers, extracted for direct unit testing (dashboard tests+// cover pure utils only).++// 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 and Unlink — because they share one precondition: something+// live to act on. Keeping them on one set is what stops a card from offering an action the API+// rejects, and, just as importantly, 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).+//+// `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.+const STARTED_STATUSES = new Set([+ 'initializing',+ 'connecting',+ 'qr_ready',+ 'authenticating',+ 'ready',+ 'action_required',+]);++export function isSessionStarted(status: string): boolean {+ return STARTED_STATUSES.has(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);+}++// A 502 from the gateway is not a plain failure: the session DID stop locally, only WhatsApp's+// confirmation is missing — the device may still be listed under Linked Devices, and the operator+// should start the session and retry. Everything else (400/404/other 5xx) is a generic failure.+export function classifyUnlinkError(err: unknown): 'unconfirmed' | 'generic' {+ const e = err as { status?: number; message?: string } | null | undefined;+ if (e?.status !== 502) return 'generic';+ // A reverse proxy in front of the API answers 502 as well, and then the request never reached the+ // gateway at all — nothing was stopped, so the "we stopped it, now retry the unlink" guidance would+ // be actively wrong. The API client falls back to a literal `HTTP <status>` message when the body is+ // not JSON, which is precisely the proxy case; the gateway's own 502 carries a real message.+ return e.message && !/^HTTP \d+$/.test(e.message) ? 'unconfirmed' : 'generic';+}diff --git a/dashboard/src/utils/sessionUnlink.test.ts b/dashboard/src/utils/sessionUnlink.test.tsdeleted file mode 100644index 2b5fe4328..000000000--- a/dashboard/src/utils/sessionUnlink.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { test } from 'node:test';-import assert from 'node:assert/strict';-import { canUnlinkSession, classifyUnlinkError } from './sessionUnlink.ts';--test('canUnlinkSession: only started states are unlinkable (they have a live engine)', () => {- for (const status of ['ready', 'initializing', 'connecting', 'qr_ready']) {- assert.equal(canUnlinkSession(status, true), true, status);- }- for (const status of ['created', 'idle', 'disconnected', 'failed', 'action_required']) {- assert.equal(canUnlinkSession(status, true), false, status);- }-});--test('canUnlinkSession: a read-only role never sees the action, even for a started session', () => {- assert.equal(canUnlinkSession('ready', false), false);-});--test('classifyUnlinkError: 502 means the unlink was unconfirmed, not a plain failure', () => {- const err = new Error('Session was stopped locally, but WhatsApp did not confirm') as Error & {- status?: number;- };- err.status = 502;- assert.equal(classifyUnlinkError(err), 'unconfirmed');-});--test('classifyUnlinkError: everything else is generic', () => {- for (const status of [400, 401, 403, 404, 500]) {- const err = new Error('x') as Error & { status?: number };- err.status = status;- assert.equal(classifyUnlinkError(err), 'generic', String(status));- }- assert.equal(classifyUnlinkError(new Error('network down')), 'generic'); // no status at all- assert.equal(classifyUnlinkError(undefined), 'generic');-});diff --git a/dashboard/src/utils/sessionUnlink.ts b/dashboard/src/utils/sessionUnlink.tsdeleted file mode 100644index dec319f2e..000000000--- a/dashboard/src/utils/sessionUnlink.ts+++ /dev/null@@ -1,22 +0,0 @@-// Decision logic for the Sessions page Unlink action, extracted for direct unit testing-// (dashboard tests cover pure utils only). The action calls POST /sessions/:id/logout, which:-// - 400s when the session is not started — the unlink is a network round-trip that needs a-// live engine, so a stopped session is rejected rather than reported as a success, and-// - 502s when the session was stopped locally but WhatsApp did not confirm the unlink.--// Visibility mirrors Stop: only started states have a live engine to send the unlink through.-// A failed session is Kill Stuck's domain; a stopped session must be started before it can be-// unlinked (which is also what the API's 400 message tells the operator).-const UNLINKABLE_STATUSES = new Set(['ready', 'initializing', 'connecting', 'qr_ready']);--export function canUnlinkSession(status: string, canWrite: boolean): boolean {- return canWrite && UNLINKABLE_STATUSES.has(status);-}--// The 502 case is not a plain failure: the session DID stop locally, only the confirmation from-// WhatsApp is missing — the device may still be listed under Linked Devices, and the operator-// should start the session and retry. Everything else (400/404/5xx) is a generic failure.-export function classifyUnlinkError(err: unknown): 'unconfirmed' | 'generic' {- const status = (err as { status?: number } | null | undefined)?.status;- return status === 502 ? 'unconfirmed' : 'generic';-}diff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 3e8de32fd..63b52f396 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -219,6 +219,7 @@ export enum EngineStatus {QR_READY = 'qr_ready',AUTHENTICATING = 'authenticating',READY = 'ready',+ ACTION_REQUIRED = 'action_required',FAILED = 'failed',}```@@ -886,6 +887,7 @@ export enum EngineStatus {QR_READY = 'qr_ready',AUTHENTICATING = 'authenticating',READY = 'ready',+ ACTION_REQUIRED = 'action_required',FAILED = 'failed',}@@ -904,6 +906,7 @@ export interface EngineEventCallbacks {onHistoryMessages?: (messages: IncomingMessage[]) => void; // bulk initial sync; persist, don't dispatchonDisconnected?: (reason: string) => void; // recoverable -> reconnectonStateChanged?: (state: EngineStatus) => void;+ onActionRequired?: (reason: string) => void; // engine alive, but an operator must actonError?: (reason: string) => void; // terminal init/auth failure}diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex e58cc5d34..0c3ed0433 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -295,20 +295,30 @@ stateDiagram-v2authenticating --> ready: Auth successauthenticating --> failed: Auth failedready --> disconnected: Connection lost+ ready --> action_required: Needs an operator+ action_required --> disconnected: stop() / logout()disconnected --> initializing: reconnect()ready --> [*]: DELETEfailed --> [*]: DELETE```-| Status | Description |-| ---------------- | ---------------------------- |-| `created` | Session created, not started |-| `initializing` | Starting browser & WhatsApp |-| `qr_ready` | QR code ready for scanning |-| `authenticating` | QR scanned, authenticating |-| `ready` | Connected and ready |-| `disconnected` | Disconnected, can reconnect |-| `failed` | Failed, needs recreation |+| Status | Description |+| ----------------- | ----------------------------------------------------------------- |+| `created` | Session created, not started |+| `initializing` | Starting browser & WhatsApp |+| `qr_ready` | QR code ready for scanning |+| `authenticating` | QR scanned, authenticating |+| `ready` | Connected and ready |+| `disconnected` | Disconnected, can reconnect |+| `action_required` | Engine running, but it needs an operator before it can work again |+| `failed` | Failed, needs recreation |++`action_required` differs from `failed` in that the engine is still loaded and still holds its+WhatsApp connection — nothing is broken, but something outside the gateway has to change before the+session is usable. The reason is carried on `lastError`, and every engine-backed action (`stop`,+`logout`) still applies; sending is refused until the session returns to `ready`. Reaching it always+takes deliberate evidence, never a single failed probe, precisely because it stops sends. A restart+clears it, and so does a gateway restart.**Config Schema:**diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex d04192bc9..91344765c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -218,7 +218,7 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt]```-`lastError` is non-null only when `status` is `failed`. `config`/`proxyUrl`/`proxyType` are not present (stripped by `fromEntity`).+`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`).**Errors:** `401` missing/invalid `X-API-Key`@@ -514,12 +514,25 @@ protocol-level unlink and clear that session's stored credentials, so a later `sfresh QR scan or pairing code.The session must be running — the unlink is a network round-trip that needs a live engine, so a-stopped session is rejected rather than reported as a success that never reached WhatsApp. If the-engine's logout does not complete (socket already gone, teardown deadline hit), the session is-still torn down locally but the route returns `502`: the unlink was not confirmed, the device may-still be listed under Linked Devices, and no `session_logged_out` audit row is written. Start the-session again and retry to confirm the unlink — the stored credentials survive a failed attempt,-so the retry needs no QR scan.+stopped session is rejected rather than reported as a success that never reached WhatsApp. The same+applies one level down: a session whose engine is loaded but whose underlying browser or socket has+gone (a stuck-auth recovery, a WhatsApp-side logout still inside its reconnect backoff) also answers+`502` rather than reporting an unlink it never sent.++If the engine's logout does not complete, the session is still torn down locally but the route+returns `502`: the unlink was not confirmed, the device may still be listed under Linked Devices, and+no `session_logged_out` audit row is written. Start the session again and retry.++Whether that retry needs a QR scan depends on how the attempt failed, and the route cannot tell you+which happened:++- **The engine rejected the logout** (no live client, socket already gone). Nothing was sent and+ nothing was deleted, so the stored credentials survive and the retry reconnects without a QR.+- **The logout ran past the teardown deadline.** The 10s deadline bounds the *response*, not the+ work: on whatsapp-web.js the still-running attempt ends in `LocalAuth.logout()`, which deletes the+ profile directory. Once that lands the session comes back with a fresh QR, exactly as a successful+ unlink would. `start` waits for that cleanup to settle before re-creating the profile, so the+ outcome is consistent either way — but plan for a re-scan after a deadline-hit 502.**Auth:** API key (OPERATOR) · **Scope:** session-scopeddiff --git a/openapi.json b/openapi.jsonindex d8a2ecc0c..9a4ad3810 100644--- a/openapi.json+++ b/openapi.json@@ -6287,7 +6287,7 @@},"lastError": {"type": "string",- "description": "Human-readable reason for the most recent terminal engine failure (only set when status is FAILED).",+ "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}diff --git a/scripts/patch-wwebjs-201832.js b/scripts/patch-wwebjs-201832.jsindex 6ba8158ea..2f594b8ce 100644--- a/scripts/patch-wwebjs-201832.js+++ b/scripts/patch-wwebjs-201832.js@@ -147,6 +147,28 @@ function withLfPatch(patchFile, run) {}}+/**+ * `git apply` exit 128 is its generic "fatal", and only SOME fatals happen before anything is written.+ * It parses the whole patch up front, so a diff it cannot read — or a bad invocation — is refused with+ * the tree untouched; that is the case the Windows CRLF handling needs to degrade cleanly. A fatal+ * raised while writing results (read-only tree, full disk) leaves the files already written in place,+ * and classifying THAT as pristine lets `--best-effort` wave a half-patched dependency through with+ * exit 0 — which is exactly what the flag must never do, because a half-patched tree reads as healthy+ * afterwards. So match the messages git emits before it writes, not the exit code on its own.+ */+// Verified against the messages git actually emits: a CRLF patch gives "corrupt patch at line N" and a+// non-diff gives "No valid patches in input" (older builds: "unrecognized input"). Both are refusals+// raised while parsing, before a single file is touched.+const GIT_APPLY_REFUSED_INPUT =+ /corrupt patch|unrecognized input|no valid patches in input|only garbage|usage: git apply|not a git repository|No such file or directory/i;++/** True only when a `git apply` failure provably happened before anything was written. */+function gitApplyLeftTreeUntouched(e) {+ if (e.code === 'ENOENT') return true; // git never executed at all+ if (e.status !== 128) return false; // any other failure may have written+ return GIT_APPLY_REFUSED_INPUT.test(e.stderr ? String(e.stderr) : e.message || '');+}+function applyWithGit(wwjsDir, patchFile) {try {execFileSync('git', ['-c', 'core.autocrlf=false', 'apply', '-p1', '--reject', '--ignore-whitespace', patchFile], {@@ -159,10 +181,11 @@ function applyWithGit(wwjsDir, patchFile) {if (e.status === 1) return;const detail = e.stderr ? String(e.stderr).trim() : e.message;const err = new Error(`neither \`patch\` nor \`git apply\` could run (${e.code ?? `exit ${e.status}`}): ${detail}`);- // Neither of these touched a file, so the tree is untouched and degrading is still safe: ENOENT- // means git never executed, and 128 means it refused the input (bad usage, or a diff it could not- // parse) before applying anything. A partial write shows up as exit 1, which returned above.- throw e.code === 'ENOENT' || e.status === 128 ? err : partialTree(err);+ // Degrade only when nothing can have been written: ENOENT means git never executed at all, and a+ // 128 whose message is one of git's pre-write refusals means it rejected the input before applying+ // anything. Any other failure — including a 128 raised midway through writing results — has to be+ // treated as a partial tree. A rejected hunk is exit 1, which returned above.+ throw gitApplyLeftTreeUntouched(e) ? err : partialTree(err);}}@@ -296,4 +319,11 @@ if (require.main === module) {}}-module.exports = { applyBackport, normalizeArtifactPath, DEFAULT_WWJS, DEFAULT_PATCH, EXPECTED_REJECTS };+module.exports = {+ applyBackport,+ normalizeArtifactPath,+ gitApplyLeftTreeUntouched,+ DEFAULT_WWJS,+ DEFAULT_PATCH,+ EXPECTED_REJECTS,+};diff --git a/src/config/process-error-monitor.spec.ts b/src/config/process-error-monitor.spec.tsindex 8686bfb1e..50cdd2a05 100644--- a/src/config/process-error-monitor.spec.ts+++ b/src/config/process-error-monitor.spec.ts@@ -53,14 +53,15 @@ describe('registerUnhandledRejectionHandler', () => {const EVENT = 'unhandledRejection';const added: Array<(...args: unknown[]) => void> = [];- type Call = [string, string | undefined];- const register = (): { handler: (r: unknown) => void; errors: Call[]; warns: Call[] } => {- const errors: Call[] = [];- const warns: Call[] = [];+ type ErrorCall = [string, string | undefined];+ type WarnCall = [string, Record<string, unknown> | undefined];+ const register = (): { handler: (r: unknown) => void; errors: ErrorCall[]; warns: WarnCall[] } => {+ const errors: ErrorCall[] = [];+ const warns: WarnCall[] = [];const before = process.listeners(EVENT);registerUnhandledRejectionHandler({error: (m, d) => errors.push([m, d]),- warn: (m, d) => warns.push([m, d]),+ warn: (m, c) => warns.push([m, c]),});const fresh = process.listeners(EVENT).filter(l => !before.includes(l)) as Array<(...a: unknown[]) => void>;added.push(...fresh);@@ -84,13 +85,17 @@ describe('registerUnhandledRejectionHandler', () => {// It is expected and self-healing, and logging it as an error with a raw Puppeteer stack reads like a// crash. The actionable variant of this message (#708, a stale browser profile) is thrown from inside// initialize() and caught by the adapter, so it never reaches this handler.- it('downgrades the Puppeteer teardown rejection to a warning that explains it', () => {+ it('downgrades the Puppeteer page-context rejection to a warning that explains it', () => {const { handler, errors, warns } = register();handler(new Error('Execution context was destroyed'));expect(errors).toHaveLength(0);expect(warns).toHaveLength(1);- expect(warns[0][0]).toMatch(/engine teardown/i);- expect(warns[0][1]).toContain('Execution context was destroyed'); // nothing is hidden, only the severity drops+ expect(warns[0][0]).toMatch(/navigation or engine teardown/i);+ // Nothing is hidden, only the severity drops — and the stack goes in the CONTEXT object. Passed+ // positionally it would type-check and then replace the logger name for the whole line, which is+ // where a reader looks for the scope, not for a Puppeteer stack.+ expect(typeof warns[0][1]).toBe('object');+ expect(String(warns[0][1]?.reason)).toContain('Execution context was destroyed');});it('stringifies a non-Error rejection without throwing', () => {diff --git a/src/config/process-error-monitor.ts b/src/config/process-error-monitor.tsindex bdda32092..5fcc80983 100644--- a/src/config/process-error-monitor.ts+++ b/src/config/process-error-monitor.ts@@ -3,16 +3,26 @@ interface FatalLogger {error: (message: string, detail?: string) => void;}-/** As FatalLogger, plus the warn level the rejection handler downgrades to. */+/**+ * As FatalLogger, plus the warn level the rejection handler downgrades to.+ *+ * `warn` takes structured CONTEXT, not a trace string: unlike `error(message, trace, context)`, the+ * logger's second `warn` parameter is the context, and a string there replaces the logger name for the+ * whole line. Passing a stack positionally type-checks and then buries it where the scope should be.+ */interface RejectionLogger extends FatalLogger {- warn: (message: string, detail?: string) => void;+ warn: (message: string, context?: Record<string, unknown>) => void;}/*** Puppeteer raises this when an isolated world is disposed while an `evaluate` is still waiting for an- * execution context — i.e. the browser was closed underneath it.+ * execution context — i.e. the page went away underneath it.+ *+ * Deliberately duplicated from the whatsapp-web.js adapter's own predicate rather than imported: that+ * module pulls whatsapp-web.js in eagerly, and this one is loaded during bootstrap, where the engine+ * must stay lazy. Keep the two in sync.*/-const ENGINE_TEARDOWN_REJECTION = /execution context was destroyed/i;+const PAGE_CONTEXT_LOST_REJECTION = /execution context was destroyed/i;/*** Register an `uncaughtExceptionMonitor` that routes an otherwise-fatal uncaught exception through the@@ -47,11 +57,11 @@ export function registerUncaughtExceptionMonitor(logger: FatalLogger): void {* unhandled rejection by default; for a long-running self-hosted gateway we log it and stay up rather* than let one stray rejection kill every session.*- * One class is logged at WARN instead of ERROR: a Puppeteer context-disposal raised while an engine is- * being torn down. whatsapp-web.js re-runs `inject()` from an async `framenavigated` listener it never- * awaits, so after a LOGOUT — which navigates the page, then re-injects on the SAME browser — the- * lifecycle's teardown turns that still-pending page evaluate into a rejection with no owner (#982).- * It is expected and self-healing, and an ERROR with a raw Puppeteer stack reads like a crash.+ * One class is logged at WARN instead of ERROR: a Puppeteer rejection left behind when the page an+ * `evaluate` was waiting on goes away. whatsapp-web.js re-runs `inject()` from an async+ * `framenavigated` listener it never awaits, so a page navigation or an engine teardown turns that+ * still-pending evaluate into a rejection with no owner (#982). Either way the session recovers on its+ * own, and an ERROR with a raw Puppeteer stack reads like a crash.** Deliberately scoped so nothing actionable is muted: the ACTIONABLE variant of the same message — a* browser profile left stale by an upgrade that changed the Chromium binary (#663/#708) — is thrown@@ -62,11 +72,14 @@ export function registerUnhandledRejectionHandler(logger: RejectionLogger): voidprocess.on('unhandledRejection', (reason: unknown) => {const message = reason instanceof Error ? reason.message : String(reason);const detail = reason instanceof Error ? reason.stack : String(reason);- if (ENGINE_TEARDOWN_REJECTION.test(message)) {+ if (PAGE_CONTEXT_LOST_REJECTION.test(message)) {+ // The stack goes in the context object, not the second positional slot: `warn`'s second+ // parameter is the log context, and a string there becomes the line's scope name.logger.warn(- 'Puppeteer rejection during an engine teardown — expected; the session recovers on its own. ' +- "Check the session's own disconnect/failure logs for the outcome.",- detail,+ 'Puppeteer rejection after the page it was evaluating went away (navigation or engine ' ++ "teardown) — expected; the session recovers on its own. Check the session's own " ++ 'disconnect/failure logs for the outcome.',+ { reason: detail, action: 'page_context_lost_rejection' },);return;}diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 363bb55d7..92832e703 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -265,6 +265,25 @@ describe('BaileysAdapter lifecycle & status', () => {}});+ // With no socket the unlink cannot be sent, and an optional-chained call would resolve as though it+ // had been — reporting a confirmed unlink, writing the audit row, and wiping the credentials, all+ // while the device stayed linked server-side with nothing left to retry with. Reachable whenever the+ // socket is gone but the engine is still registered, e.g. inside a reconnect backoff.+ it('logout() rejects and keeps the on-disk auth dir when there is no socket at all', async () => {+ const rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);+ try {+ const adapter = newAdapter();+ await adapter.initialize(noopCallbacks({}));+ (adapter as unknown as { sock: unknown }).sock = null;++ await expect(adapter.logout()).rejects.toThrow(/no live whatsapp socket/i);+ expect(fakeSock.logout).not.toHaveBeenCalled();+ expect(rmSpy).not.toHaveBeenCalled();+ } finally {+ rmSpy.mockRestore();+ }+ });+it('on a recoverable close: reconnects (re-creates the socket) and does NOT fire onDisconnected', async () => {const onDisconnected = jest.fn();const adapter = newAdapter();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 2cd26a09a..bd610b5fd 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -552,8 +552,17 @@ export class BaileysAdapter implements IWhatsAppEngine {clearTimeout(this.reconnectTimer);this.reconnectTimer = undefined;}+ // Without a socket the unlink cannot be sent, and `this.sock?.logout()` would resolve as though it+ // had been — reporting a confirmed unlink, writing the audit row, and then wiping the on-disk+ // credentials below, leaving the device linked server-side with no way left to retry. Fail instead+ // so the caller surfaces it and the credentials survive. Reachable: a WhatsApp-side logout nulls+ // the socket while the engine stays registered for the whole reconnect backoff.+ if (!this.sock) {+ throw new Error('No live WhatsApp socket — the unlink was not sent');+ }+try {- await this.sock?.logout();+ await this.sock.logout();} catch (err) {// End the socket so the session still dies locally, but keep the on-disk creds: wiping// them now would leave the device linked server-side with no local way to retry thediff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex fb46ad0b9..c5115c2c7 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -8,6 +8,7 @@ import {isExecutionContextDestroyedError,buildProxyLaunchConfig,loadRemoteMedia,+ probeOnboardingModal,resolveAuthTimeoutMs,wwebjsAckToDeliveryStatus,extractWwebjsCall,@@ -1107,6 +1108,17 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {expect(adapter.getStatus()).toBe(EngineStatus.DISCONNECTED);});+ // The session layer's "is it started?" check only sees that an engine is registered. An engine can+ // outlive its client — a stuck-auth recovery nulls it and then waits out the reconnect backoff — and+ // resolving here would report a confirmed unlink for a request that never left the process, complete+ // with a SESSION_LOGGED_OUT audit row, while the device stayed listed under Linked Devices.+ it('logout() rejects when there is no live client rather than reporting a phantom unlink', async () => {+ const adapter = newAdapter();+ (adapter as unknown as { client: unknown }).client = null;++ await expect(adapter.logout()).rejects.toThrow(/no live whatsapp web client/i);+ });+it('disables ready reconciliation before destroy awaits client teardown', async () => {await expectNoReadyDuringTeardown((client, teardownWait) => {@@ -2710,6 +2722,92 @@ describe('outbound document mode (#989)', () => {await ready({ sendMessage }).sendImageMessage('[email protected]', { mimetype: 'image/png', data: bytes });expect(sendMessage).toHaveBeenCalledWith('[email protected]', expect.anything(), { caption: undefined });});++ // A URL fetch can only describe the bytes from the response — content-type and the URL basename —+ // so it used to overwrite whatever the request actually said. The caller knows better.+ describe('remote-URL sends honour the metadata the caller declared', () => {+ const remoteResponse = (headers: Record<string, string>) => ({+ ok: true,+ status: 200,+ headers: { get: (k: string) => headers[k.toLowerCase()] ?? null },+ body: {+ getReader: () => {+ let done = false;+ return {+ read: () =>+ done+ ? Promise.resolve({ done: true, value: undefined })+ : ((done = true), Promise.resolve({ done: false, value: new Uint8Array([1, 2]) })),+ cancel: () => Promise.resolve(),+ };+ },+ cancel: () => Promise.resolve(),+ },+ });++ beforeEach(() => {+ (undiciFetch as jest.Mock).mockReset();+ process.env.SSRF_ALLOWED_HOSTS = 'files.example.com';+ });+ afterEach(() => {+ (undiciFetch as jest.Mock).mockReset();+ delete process.env.SSRF_ALLOWED_HOSTS;+ });++ it('prefers the declared mimetype and filename over what the response advertised', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': 'image/jpeg' }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage }).sendDocumentMessage('[email protected]', {+ mimetype: 'application/pdf',+ filename: 'report.pdf',+ data: 'https://files.example.com/generated',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: 'application/pdf', filename: 'report.pdf' }),+ expect.objectContaining({ sendMediaAsDocument: true }),+ );+ });++ // A sticker's mimetype is an instruction, not a label: whatsapp-web.js returns the media+ // unconverted once it reads as webp, so trusting a declared image/webp over bytes that are not+ // webp ships raw bytes as a sticker. The response saw the bytes; the caller did not.+ it('keeps the fetched type for a sticker, where the mimetype selects the conversion', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': 'image/png' }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage }).sendStickerMessage('[email protected]', {+ mimetype: 'image/webp',+ data: 'https://files.example.com/not-really-a-webp',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: 'image/png' }),+ expect.objectContaining({ sendMediaAsSticker: true }),+ );+ });++ // The DTO fills this in when the client said nothing, so it is a placeholder rather than a claim+ // about the bytes — the response has to win, or every URL send would go out as a generic blob.+ it('lets the response win when the declared mimetype is the octet-stream placeholder', async () => {+ (undiciFetch as jest.Mock).mockResolvedValue(remoteResponse({ 'content-type': 'image/jpeg' }));+ const sendMessage = jest.fn().mockResolvedValue(sentMessage);++ await ready({ sendMessage }).sendImageMessage('[email protected]', {+ mimetype: 'application/octet-stream',+ data: 'https://files.example.com/photo.jpg',+ });++ expect(sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mimetype: 'image/jpeg' }),+ expect.anything(),+ );+ });+ });});describe('LID resolution for individual sends (#573 — WhatsApp @c.us → @lid migration)', () => {@@ -4311,7 +4409,7 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {}});- it('falls back to ACTION_REQUIRED when the modal is present but Continue cannot be clicked', async () => {+ it('only falls back to ACTION_REQUIRED once repeated clicks have failed to dismiss the modal', async () => {jest.useFakeTimers();try {const { adapter, evaluate, onActionRequired } = promoteToReady();@@ -4320,7 +4418,20 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {await jest.advanceTimersByTimeAsync(2100);expect(adapter.getStatus()).toBe(EngineStatus.READY);- evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: false } satisfies ModalProbe);+ // A modal that really goes away is clicked once, so a single click must NOT move the session:+ // the whole point of the threshold is that only a click which fails to land is evidence.+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);+ await jest.advanceTimersByTimeAsync(5100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onActionRequired).not.toHaveBeenCalled();++ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);+ await jest.advanceTimersByTimeAsync(5100);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onActionRequired).not.toHaveBeenCalled();++ // Third click on a modal that is still there — the click is not landing, a human must act.+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);await jest.advanceTimersByTimeAsync(5100);expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);@@ -4331,7 +4442,10 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {}});- it('falls back to ACTION_REQUIRED when the page evaluate rejects (selector moved / page closed)', async () => {+ // A rejected probe means the page went away (reload, teardown, timeout) — it says nothing about+ // the modal. Moving the session out of READY on that signal would block every send on a HEALTHY+ // session for a reason the operator cannot act on, so the probe failure must be inert.+ it('keeps the session READY when the page evaluate rejects', async () => {jest.useFakeTimers();try {const { adapter, evaluate, onActionRequired } = promoteToReady();@@ -4341,9 +4455,11 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {evaluate.mockRejectedValueOnce(new Error('Execution context was destroyed'));await jest.advanceTimersByTimeAsync(5100);+ evaluate.mockRejectedValueOnce(new Error('Target closed'));+ await jest.advanceTimersByTimeAsync(5100);- expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);- expect(onActionRequired).toHaveBeenCalledTimes(1);+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onActionRequired).not.toHaveBeenCalled();} finally {jest.useRealTimers();}@@ -4437,8 +4553,11 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {(client as EventEmitter).emit('authenticated');await jest.advanceTimersByTimeAsync(2100);- evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: false } satisfies ModalProbe);- await jest.advanceTimersByTimeAsync(5100);+ // Drive it to the fallback the only way that reaches it: clicks that keep failing to land.+ for (let i = 0; i < 3; i++) {+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);+ await jest.advanceTimersByTimeAsync(5100);+ }expect(adapter.getStatus()).toBe(EngineStatus.ACTION_REQUIRED);// A stray ready event must not resurrect READY from the action-required state.@@ -4451,3 +4570,118 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {});});});++// The in-page half of the onboarding watcher. Every other test in this file drives the watcher with a+// mocked `pupPage.evaluate`, which proves the loop but says nothing about the matching that runs+// inside the browser — the part that is actually fragile, and the part that decides whether a healthy+// session keeps working. `probeOnboardingModal` is a self-contained function precisely so it can be+// executed here against representative DOM shapes.+describe('probeOnboardingModal (in-page onboarding modal detection)', () => {+ type FakeEl = {+ tagName: string;+ textContent: string;+ parentElement: FakeEl | null;+ offsetParent: unknown;+ getBoundingClientRect: () => { width: number; height: number };+ matchesButton: boolean;+ click: jest.Mock;+ };++ const el = (textContent: string, opts: { button?: boolean; hidden?: boolean } = {}): FakeEl => ({+ tagName: opts.button ? 'BUTTON' : 'DIV',+ textContent,+ parentElement: null,+ offsetParent: opts.hidden ? null : {},+ getBoundingClientRect: () => (opts.hidden ? { width: 0, height: 0 } : { width: 200, height: 40 }),+ matchesButton: !!opts.button,+ click: jest.fn(),+ });++ /** Wire children to a parent and return the parent, so ancestor walks have something to walk. */+ const nest = (parent: FakeEl, ...children: FakeEl[]): FakeEl => {+ for (const child of children) child.parentElement = parent;+ return parent;+ };++ const install = (all: FakeEl[]): void => {+ (globalThis as unknown as { document: unknown }).document = {+ // The probe only ever queries for buttons, so honour that selector and ignore the rest.+ querySelectorAll: (selector: string) => (selector.includes('button') ? all.filter(e => e.matchesButton) : []),+ };+ };++ afterEach(() => {+ delete (globalThis as unknown as { document?: unknown }).document;+ });++ it('clicks Continue when it sits inside the onboarding modal', () => {+ const button = el('Continue', { button: true });+ nest(el("What's new on WhatsApp Web"), button);+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: true, dismissed: true });+ expect(button.click).toHaveBeenCalledTimes(1);+ });++ // WhatsApp Web renders the typographic apostrophe. Matching only the ASCII form meant the real+ // modal was never recognised — the fix silently doing nothing at all.+ it('recognises the typographic apostrophe as well as the ASCII one', () => {+ const button = el('Continue', { button: true });+ nest(el('What’s new on WhatsApp Web'), button);+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: true, dismissed: true });+ expect(button.click).toHaveBeenCalledTimes(1);+ });++ // The regression that matters: an element's text includes all of its descendants, so a chat row+ // previewing an ordinary message matches a heading-only test. Reporting a modal here took a healthy+ // session out of READY, which refuses every send.+ it.each([+ ['a chat preview of the message "What\'s new?"', "Alice12:34What's new?"],+ ['a chat preview without an apostrophe', 'Bob09:15whats new with you'],+ ['a group named after the phrase', "What's New at Acme 09:15 Hi team"],+ ['the typographic form in a message', 'Carol11:02What’s new?'],+ ])('reports no modal for %s', (_label, text) => {+ install([el(text)]); // a div, never a button — the chat list has no "Continue" control+ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ });++ it('ignores a Continue button that belongs to something other than the onboarding modal', () => {+ const button = el('Continue', { button: true });+ nest(el('Update your payment method'), button);+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ expect(button.click).not.toHaveBeenCalled();+ });++ it('ignores an offscreen Continue button', () => {+ const button = el('Continue', { button: true, hidden: true });+ nest(el("What's new on WhatsApp Web"), button);+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ expect(button.click).not.toHaveBeenCalled();+ });++ // The ancestor walk is bounded so a match against <body> — i.e. the words appearing anywhere on the+ // page — can never qualify a button that is nowhere near the modal.+ it('does not match a heading further up the tree than the bounded walk reaches', () => {+ const button = el('Continue', { button: true });+ let node = button;+ for (let i = 0; i < 9; i++) {+ node = nest(el('wrapper'), node);+ }+ node.textContent = "What's new on WhatsApp Web";+ install([button]);++ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ expect(button.click).not.toHaveBeenCalled();+ });++ it('reports no modal on a page with nothing to click', () => {+ install([]);+ expect(probeOnboardingModal()).toEqual({ modalPresent: false, dismissed: false });+ });+});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 0a46313d6..4c8713834 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -296,12 +296,53 @@ const READY_RECONCILE_TIMEOUT_MS = 90_000;// Onboarding-modal watcher (#982). A freshly-linked account shows a "What's new on WhatsApp Web"// modal with a Continue button that must be acknowledged, or WhatsApp unlinks the companion ~5m// later (surfacing as disconnected: LOGOUT). whatsapp-web.js exposes no API for this (#3550 open),-// so the watcher reaches the page directly, dismisses it best-effort, and falls back to-// ACTION_REQUIRED if that fails. The modal is one-shot per account, so the watcher self-terminates-// after the lifetime cap rather than polling forever.+// so the watcher reaches the page directly and clicks it best-effort. The modal is one-shot per+// account, so the watcher self-terminates after the lifetime cap rather than polling forever.const ONBOARDING_MODAL_INTERVAL_MS = 5_000;const ONBOARDING_MODAL_MAX_LIFETIME_MS = 5 * 60_000;const ONBOARDING_MODAL_PROBE_TIMEOUT_MS = 5_000;+// Clicking Continue dismisses the modal, so one click is the normal case and the next tick finds+// nothing. Repeated clicks mean the click is not landing — the only evidence that actually justifies+// asking a human to intervene.+const ONBOARDING_MODAL_MAX_DISMISS_CLICKS = 3;++/**+ * In-page probe for the onboarding modal: click its Continue 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.+ *+ * 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.+ */+export function probeOnboardingModal(): { 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;+ };+ // 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;+ for (let depth = 0; depth < 8 && scope; depth++, scope = scope.parentElement) {+ if (!heading.test(scope.textContent || '')) continue;+ (button as HTMLElement).click();+ return { modalPresent: true, dismissed: true };+ }+ }+ return { modalPresent: false, dismissed: false };+}// WhatsApp Web version resolution (the #488 auto-resolve) lives in a dependency-free module so infra// status can import it without loading whatsapp-web.js (engine lazy-loading). The adapter imports@@ -369,6 +410,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate onboardingWatcherTimer: ReturnType<typeof setTimeout> | null = null;private onboardingWatcherStartedAt = 0;private onboardingWatcherStarted = false;+ // How many times we have clicked the modal's Continue button. Not reset by clearOnboardingWatcher:+ // it counts for the engine's lifetime, which is what makes "the click is not landing" detectable.+ private onboardingDismissClicks = 0;/** How long a received call's handle stays rejectable. Calls ring for roughly a minute, so* two minutes covers the ringing window with margin without pinning dead calls for long. */private static readonly LIVE_CALL_TTL_MS = 2 * 60_000;@@ -1181,8 +1225,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin* has a Continue button that must be acknowledged or WhatsApp unlinks the companion ~5m later* (surfacing as disconnected: LOGOUT). whatsapp-web.js exposes no API for this (#3550 open), so the* watcher reaches the page directly. Idempotent and one-shot per engine: the modal appears once per- * account, so the loop self-terminates at the lifetime cap instead of polling forever. On any probe- * failure the session moves to ACTION_REQUIRED and surfaces the reason — never silently.+ * account, so the loop self-terminates at the lifetime cap instead of polling forever.+ *+ * The watcher only ever moves the session out of READY when it has clicked Continue repeatedly and+ * the modal is still there — real evidence a human must acknowledge it. A probe that cannot reach+ * the page, or a page with no such modal, leaves the session exactly where it was: blocking sends+ * over a best-effort DOM guess would be a worse outcome than the problem being guarded against.*/private startOnboardingWatcher(): void {if (this.onboardingWatcherStarted) return; // idempotent: ready event + reconcile path share one funnel@@ -1219,10 +1267,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}/**- * One watcher tick: detect the onboarding modal and click Continue. Returns/throws rather than- * mutating state directly so the loop stays the single owner of the ACTION_REQUIRED transition.- * `undefined` = no modal (nothing to do); the page evaluating to a click is the success path; any- * thrown/rejected evaluate (selector moved, page closed, timeout) is treated as "needs attention".+ * One watcher tick: click the onboarding modal's Continue button if it is on screen. Returns the+ * probe verdict rather than mutating state so the loop stays the single owner of the+ * ACTION_REQUIRED transition. A rejected evaluate is NOT an operator signal — see the catch.*/private async dismissOnboardingModalIfNeeded(): Promise<void> {if (!this.client) return;@@ -1231,25 +1278,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlet timeout: ReturnType<typeof setTimeout> | undefined;try {const result = await Promise.race([- page?.evaluate(() => {- // Match by visible text rather than class selectors — WhatsApp Web rebuilds its DOM across- // builds, but the button label ("Continue") and modal heading ("What's new") are stable.- const isVisible = (el: Element): boolean => {- const rect = (el as HTMLElement).getBoundingClientRect();- return rect.width > 0 && rect.height > 0 && (el as HTMLElement).offsetParent !== null;- };- const candidates = Array.from(document.querySelectorAll('button, [role="button"], div'));- const heading = candidates.some(- el => isVisible(el) && /what'?s new/i.test((el.textContent || '').trim().slice(0, 64)),- );- if (!heading) return { modalPresent: false, dismissed: false };- const button = candidates- .filter(el => isVisible(el) && (el.textContent || '').trim() === 'Continue')- .slice(-1)[0];- if (!button) return { modalPresent: true, dismissed: false };- (button as HTMLElement).click();- return { modalPresent: true, dismissed: true };- }),+ page?.evaluate(probeOnboardingModal),new Promise<never>((_, reject) => {timeout = setTimeout(() => reject(new Error('onboarding modal probe timed out')),@@ -1259,24 +1288,35 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}),]);- if (result?.modalPresent && !result.dismissed) {- // The modal is there but no clickable Continue was found — the account needs a human.+ if (!result?.dismissed) return;++ // We clicked. A modal that is really dismissed is gone by the next tick, so a click here is+ // normally a one-off. Repeated clicks mean the click is not taking effect (an overlay is+ // swallowing it, or WhatsApp keeps re-showing the modal) — that, and only that, is evidence a+ // human has to acknowledge it on the phone before the companion is unlinked.+ this.onboardingDismissClicks += 1;+ this.logger.log('Dismissed the WhatsApp Web onboarding modal', {+ sessionId: this.config.sessionId,+ attempt: this.onboardingDismissClicks,+ action: 'onboarding_modal_dismissed',+ });+ if (this.onboardingDismissClicks >= ONBOARDING_MODAL_MAX_DISMISS_CLICKS) {this.reportActionRequired(- 'WhatsApp is showing an onboarding modal ("What\'s new") that could not be dismissed ' +- "automatically. Acknowledge it (e.g. link a normal WhatsApp Web session on the phone's " +- 'number and click through) or the companion will be unlinked.',+ `WhatsApp is still showing its onboarding modal after ${this.onboardingDismissClicks} ` ++ "attempts to dismiss it. Open WhatsApp Web on the account holder's own browser and click " ++ 'through the "What\'s new" screen, or the companion device will be unlinked.',);}- } catch (error) {- // A page.evaluate failure after READY usually means the page navigated/closed mid-probe, but it- // also covers the modal having moved beyond recognition — surface ACTION_REQUIRED rather than- // letting the session be silently logged out at the five-minute mark.- this.reportActionRequired(- `Could not reach the WhatsApp Web page to dismiss the onboarding modal: ${- error instanceof Error ? error.message : String(error)- }. The session may be logged out shortly; acknowledge the onboarding on a normal WhatsApp Web ` +- 'session if the companion gets unlinked.',- );+ } catch {+ // The page navigated, closed, or the probe timed out. This is expected around a reload or a+ // teardown and says nothing about the modal, so it must not move the session: a status change+ // here would take a HEALTHY session out of READY, which blocks every send (ensureReady) for a+ // reason the operator cannot act on. A page that is genuinely gone surfaces through the+ // puppeteer lifecycle listeners as a disconnect, which is where that belongs.+ this.logger.debug('Onboarding modal probe could not reach the page; ignoring', {+ sessionId: this.config.sessionId,+ action: 'onboarding_modal_probe_skipped',+ });} finally {if (timeout) clearTimeout(timeout);}@@ -1489,7 +1529,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginasync logout(): Promise<void> {const client = this.beginClientTeardown();- if (!client) return;+ // 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 on+ // success, and the device would stay listed under the account holder's Linked Devices. The+ // session-level "is it started?" check cannot catch this: an engine stays registered while its+ // client is gone (a stuck-auth recovery nulls it, then waits out the reconnect backoff).+ if (!client) {+ throw new Error('No live WhatsApp Web client — the unlink was not sent');+ }try {// Logout clears session data - user will need to scan QR again@@ -1890,7 +1937,9 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// hits the same channel crash: for a channel wwjs drops the sticker form and runs processMediaData// with sendToChannel, which still ends at msg.avParams() (Utils.js:518). Guard it too (#673).this.ensureNotChannelRecipient(chatId);- const messageMedia = await this.toMessageMedia(media);+ // Keep the fetched content-type for a remote URL: here the mimetype selects the conversion, and+ // whatsapp-web.js returns the media unconverted once it reads as webp (Util.formatImageToWebpSticker).+ const messageMedia = await this.toMessageMedia(media, { trustDeclaredType: false });const msg = await this.sendResolved(chatId, to =>this.client!.sendMessage(to, messageMedia, {@@ -2824,15 +2873,25 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn this.toStatusResult(msg);}- /** Build a MessageMedia from a MediaInput (URL → fetched, base64/Buffer → wrapped). */- private async toMessageMedia(media: MediaInput): Promise<MessageMedia> {+ /**+ * Build a MessageMedia from a MediaInput (URL → fetched, base64/Buffer → wrapped).+ *+ * `trustDeclaredType: false` keeps the fetched response's content-type for a remote URL. Use it+ * wherever the mimetype is an INSTRUCTION rather than a label: whatsapp-web.js decides how to+ * convert a sticker from it, and `Util.formatImageToWebpSticker` returns the media untouched when it+ * already says webp. A caller that declares `image/webp` over bytes that are not webp would then+ * have raw bytes shipped as a sticker. The response describes bytes the caller never saw, so for+ * that one decision it is the better source. The declared filename still wins either way — that is+ * a label, and nothing branches on it.+ */+ private async toMessageMedia(media: MediaInput, opts?: { trustDeclaredType?: boolean }): Promise<MessageMedia> {if (typeof media.data === 'string' && isHttpUrl(media.data)) {const fetched = await loadRemoteMedia(media.data);// `loadRemoteMedia` derives both fields from the response (content-type, URL basename) because// that is all it has. The caller usually knows better, so let an explicit `mimetype`/`filename`// win — matching `resolveMediaBuffer` on the Baileys adapter, which already prefers the caller's.// `application/octet-stream` is the DTO's own placeholder, not a statement about the bytes.- if (media.mimetype && media.mimetype !== 'application/octet-stream') {+ if (opts?.trustDeclaredType !== false && media.mimetype && media.mimetype !== 'application/octet-stream') {fetched.mimetype = media.mimetype;}if (media.filename) {diff --git a/src/engine/adapters/wwebjs-backport-201832.spec.ts b/src/engine/adapters/wwebjs-backport-201832.spec.tsindex 1551234e4..ebe7505c6 100644--- a/src/engine/adapters/wwebjs-backport-201832.spec.ts+++ b/src/engine/adapters/wwebjs-backport-201832.spec.ts@@ -8,11 +8,13 @@ import * as path from 'path';const {applyBackport,normalizeArtifactPath,+ gitApplyLeftTreeUntouched,DEFAULT_PATCH: PATCH_FILE,// eslint-disable-next-line @typescript-eslint/no-require-imports} = require('../../../scripts/patch-wwebjs-201832') as {applyBackport: (wwjsDir: string, patchFile?: string) => { skipped: boolean; reason?: string; note?: string };normalizeArtifactPath: (rel: string) => string;+ gitApplyLeftTreeUntouched: (e: { code?: string; status?: number; stderr?: string; message?: string }) => boolean;DEFAULT_PATCH: string;};@@ -36,6 +38,33 @@ describe('patch-wwebjs-201832 (build-time backport of upstream #201832)', () =>expect(normalizeArtifactPath('src\\structures\\Contact.js.rej')).toBe('src/structures/Contact.js.rej');});+ // `git apply` uses exit 128 for every fatal, and only some of those happen before it writes. Treating+ // the code alone as "pristine" lets `--best-effort` report a clean skip over a HALF-patched tree,+ // which reads as healthy forever after. Only the refusals git emits before applying may degrade.+ describe('gitApplyLeftTreeUntouched', () => {+ it.each([+ ['git never executed', { code: 'ENOENT' as const, status: undefined }],+ ['a diff git could not parse', { status: 128, stderr: 'error: corrupt patch at line 7' }],+ ['input git did not recognise', { status: 128, stderr: 'error: unrecognized input' }],+ ['a non-diff file', { status: 128, stderr: 'error: No valid patches in input (allow with "--allow-empty")' }],+ ['a bad invocation', { status: 128, stderr: 'usage: git apply [<options>] [<patch>...]' }],+ ['a missing patch file', { status: 128, stderr: 'error: cannot open patch: No such file or directory' }],+ ['running outside a repo', { status: 128, stderr: 'fatal: not a git repository' }],+ ])('treats %s as untouched', (_label, e) => {+ expect(gitApplyLeftTreeUntouched(e)).toBe(true);+ });++ it.each([+ ['a fatal raised while writing results', { status: 128, stderr: 'fatal: unable to write file Base.js' }],+ ['a read-only checkout', { status: 128, stderr: 'error: Base.js: Permission denied' }],+ ['a full disk mid-write', { status: 128, stderr: 'fatal: write error: No space left on device' }],+ ['an unknown non-zero exit', { status: 2, stderr: 'something else entirely' }],+ ['a signal kill with no status', { status: undefined, message: 'Killed' }],+ ])('refuses to call %s untouched', (_label, e) => {+ expect(gitApplyLeftTreeUntouched(e)).toBe(false);+ });+ });+/*** A pristine (unpatched) copy of the installed whatsapp-web.js.*diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.tsindex 7c7a75a4e..9a35e3ee6 100644--- a/src/modules/session/dto/session-response.dto.ts+++ b/src/modules/session/dto/session-response.dto.ts@@ -32,7 +32,9 @@ export class SessionResponseDto {@ApiPropertyOptional({type: String,- description: 'Human-readable reason for the most recent terminal engine failure (only set when status is FAILED).',+ 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,})diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 6a440b490..69280b580 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -395,6 +395,40 @@ describe('SessionService', () => {}});+ // delete() purges the same on-disk dirs a losing logout teardown is still about to remove. Racing+ // them lets the purge run against a directory the stale rm then re-enters, so delete waits too.+ it('delete() waits for a logout teardown that lost its deadline race before purging', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),+ );+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ let releaseLogout!: () => void;+ const wedgedLogout = new Promise<void>(res => {+ releaseLogout = res;+ });+ enginesOf().set('sess-uuid-1', { logout: jest.fn().mockReturnValue(wedgedLogout) });++ jest.useFakeTimers();+ try {+ const logoutCall = service.logout('sess-uuid-1');+ await jest.advanceTimersByTimeAsync(10_000);+ await expect(logoutCall).rejects.toBeInstanceOf(BadGatewayException);+ expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(true);++ const deleteCall = service.delete('sess-uuid-1');+ await jest.advanceTimersByTimeAsync(1_000); // inside the bounded wait+ expect(engineFactory.purgeSessionData).not.toHaveBeenCalled();++ releaseLogout();+ await deleteCall;+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');+ expect(pendingTeardownsOf().has('sess-uuid-1')).toBe(false);+ } finally {+ jest.useRealTimers();+ }+ });+it('start() proceeds after the bounded wait when the teardown stays wedged', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });