Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(wwjs): stop promoting sessions whose message bridge never attached
Yudhi Armyndharis905c3388999e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 783090f7c..977145b91 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,6 +24,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **whatsapp-web.js sessions could come up "ready" with a dead inbound pipeline after a warm+ restart, silently losing every incoming message.** whatsapp-web.js runs its whole post-auth+ pipeline — including attaching the page-to-Node message listeners — inside a callback fired only+ by the page's `change:hasSynced` *transition*. On a warm profile the page can restore to+ already-synced before that listener exists (the callback then never runs), and the listener+ attachment itself can fail partway with the rejection swallowed; in both cases `ready` never+ fires while sends keep working, and this gateway's readiness reconciliation then promoted the+ session, masking the loss. Confirmed live: messages visible in the WhatsApp store, never+ persisted, never dispatched to webhooks.++ A new postinstall patcher (`scripts/patch-wwebjs-ready-sync.js`, run fatally in the image build+ like its siblings) closes the missed-transition race by also firing the handler when the synced+ state has already been reached, and records completion of the listener attachment on the client.+ The adapter now refuses to promote a session whose message bridge never attached — on BOTH paths:+ the genuine `ready` event (whatsapp-web.js bare-re-emits it while the first run's listener+ attachment is still in flight, so a premature emit is ignored and the attach's own completion+ re-emit promotes instead) and the readiness reconciliation. When the bridge stays dead the+ reconciliation reloads the page once to reinject it (whatsapp-web.js reinjects on navigation),+ and — if it still never attaches — marks the session failed **without** deleting the saved+ credentials: the link itself is healthy, so a restart must be enough to recover, never a re-pair.+- **Status posting on the whatsapp-web.js engine, which current WhatsApp Web had broken outright.**whatsapp-web.js 1.34.7 builds every status message with`window.require('WAWebStatusGatingUtils').canCheckStatusRankingPosterGating()`. That helper nodiff --git a/Dockerfile b/Dockerfileindex cc33e86da..47d54de7b 100644--- a/Dockerfile+++ b/Dockerfile@@ -120,7 +120,7 @@ COPY package*.json ./# scripts/postinstall.js rides along: `npm ci` below runs the hook, which fails# when the file is missing. With the patcher present the hook applies it in# --best-effort mode; the explicit fatal run right after is the real gate.-COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js ./scripts/+COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js ./scripts/# Install production dependencies only, then apply the backports. The status patcher runs LAST:# its transforms were written against the tree the other two leave behind.@@ -128,6 +128,7 @@ RUN npm ci --omit=dev \&& node scripts/patch-wwebjs-201832.js \&& node scripts/patch-wwebjs-newsletter-preview.js \&& node scripts/patch-wwebjs-status.js \+ && node scripts/patch-wwebjs-ready-sync.js \&& npm cache clean --force# Replace the npm the base image bundles. npm is not on the request path — the entrypoint runsdiff --git a/package.json b/package.jsonindex 5c75a970e..20bdd1125 100644--- a/package.json+++ b/package.json@@ -34,7 +34,7 @@"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"","lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix","test": "jest",- "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js",+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js","test:watch": "jest --watch","test:cov": "jest --coverage","test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",diff --git a/scripts/check-dockerignore.mjs b/scripts/check-dockerignore.mjsindex bf62ba0e5..4d65246de 100644--- a/scripts/check-dockerignore.mjs+++ b/scripts/check-dockerignore.mjs@@ -145,6 +145,7 @@ const mustKeep = ['scripts/patch-wwebjs-201832.js','scripts/patch-wwebjs-newsletter-preview.js','scripts/patch-wwebjs-status.js',+ 'scripts/patch-wwebjs-ready-sync.js','scripts/wwebjs-201832.patch','docker-entrypoint.sh','docs/01-project-overview.md',diff --git a/scripts/patch-wwebjs-ready-sync.js b/scripts/patch-wwebjs-ready-sync.jsnew file mode 100644index 000000000..7695a4372--- /dev/null+++ b/scripts/patch-wwebjs-ready-sync.js@@ -0,0 +1,134 @@+/**+ * Make whatsapp-web.js readiness observable and race-free on warm session restores.+ *+ * whatsapp-web.js 1.34.7 runs its entire post-auth pipeline — LoadUtils, ClientInfo,+ * attachEventListeners (the page->Node message bridge), and the `ready` emit — inside a callback+ * fired by the page-side `change:hasSynced` EDGE. Two real failure modes follow, both observed live:+ *+ * 1. On a warm profile the page can reach hasSynced=true BEFORE the listener attaches; the edge+ * never comes again and the whole pipeline silently never runs.+ * 2. attachEventListeners can throw partway (a transient page evaluate failure); the rejection is+ * swallowed inside the exposed-function binding, `ready` never fires, and nothing records that+ * the message bridge is dead — while sends still work, so the session looks merely quiet.+ *+ * Three transforms, one group (all-or-nothing):+ * - initialize `eventsAttached = false` on the client, so the flag's absence (an unpatched tree)+ * is distinguishable from "attach has not completed";+ * - set `eventsAttached = true` only AFTER attachEventListeners resolves, giving the adapter a+ * truthful completion marker (the adapter treats `undefined` as "marker unsupported" and keeps+ * its old behaviour);+ * - after subscribing to `change:hasSynced`, fire the handler once when the level is already+ * true, closing the missed-edge race. A double fire is tolerated upstream: the callback's+ * `injected` check makes the second pass a bare re-emit of `ready`, which the adapter dedupes.+ *+ * The source transform is deliberately exact and self-disabling: an unknown shape fails the build+ * instead of silently shipping without the fix, matching the sibling patchers. The file is written+ * once, after the whole group resolves.+ */+'use strict';++const fs = require('fs');+const path = require('path');++const DEFAULT_WWJS = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js');+const CLIENT_PATH = path.join('src', 'Client.js');++const FLAG_INIT_FIND = ` this.currentIndexHtml = null;+ this.lastLoggedOut = false;`;++const FLAG_INIT_REPLACE = ` this.currentIndexHtml = null;+ this.lastLoggedOut = false;+ // Set true only after attachEventListeners() resolves; the message bridge is not+ // trustworthy before that, even when the page itself reports CONNECTED.+ this.eventsAttached = false;`;++const ATTACH_MARK_FIND = ` await this.attachEventListeners();+ }`;++const ATTACH_MARK_REPLACE = ` await this.attachEventListeners();+ this.eventsAttached = true;+ }`;++const HAS_SYNCED_FIND = ` window+ .require('WAWebSocketModel')+ .Socket.on('change:hasSynced', () => {+ window.onAppStateHasSyncedEvent();+ });`;++const HAS_SYNCED_REPLACE = ` window+ .require('WAWebSocketModel')+ .Socket.on('change:hasSynced', () => {+ window.onAppStateHasSyncedEvent();+ });+ // A warm profile can restore to hasSynced=true before this listener exists; the edge+ // then never fires again. Fire once on the already-reached level as well.+ if (window.require('WAWebSocketModel').Socket.hasSynced) {+ window.onAppStateHasSyncedEvent();+ }`;++const EDITS = [+ { find: FLAG_INIT_FIND, replace: FLAG_INIT_REPLACE },+ { find: ATTACH_MARK_FIND, replace: ATTACH_MARK_REPLACE },+ { find: HAS_SYNCED_FIND, replace: HAS_SYNCED_REPLACE },+];++function occurrences(source, needle) {+ return source.split(needle).length - 1;+}++function applyReadySyncPatch(wwjsDir = DEFAULT_WWJS) {+ const clientFile = path.join(wwjsDir, CLIENT_PATH);+ if (!fs.existsSync(clientFile)) {+ throw new Error(`whatsapp-web.js Client.js not found at ${clientFile}`);+ }++ let source = fs.readFileSync(clientFile, 'utf8');+ const replaces = EDITS.map(edit => occurrences(source, edit.replace));+ // Each replacement CONTAINS its find (the edits append lines), so a find counted on the raw+ // source would still be 1 after patching. Count finds with the replacements removed, so a+ // patched file reads as find=0/replace=1 and a genuinely half-patched one still refuses.+ const finds = EDITS.map(edit => occurrences(source.split(edit.replace).join(''), edit.find));++ if (finds.every(count => count === 0) && replaces.every(count => count === 1)) {+ return { skipped: true, reason: 'installed whatsapp-web.js already carries the ready-sync repair' };+ }+ if (finds.every(count => count === 1) && replaces.every(count => count === 0)) {+ for (const edit of EDITS) {+ source = source.replace(edit.find, edit.replace);+ }+ fs.writeFileSync(clientFile, source);+ return { skipped: false, note: 'readiness marker and hasSynced level-check applied' };+ }+ throw new Error(+ `unsupported Client.js shape (unpatched: ${finds.join(',')}, patched: ${replaces.join(',')}); ` ++ 're-evaluate the ready-sync repair against the installed whatsapp-web.js',+ );+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyReadySyncPatch();+ console.log(`patch-wwebjs-ready-sync: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-wwebjs-ready-sync: skipped — ${error.message}`);+ return;+ }+ console.error(`patch-wwebjs-ready-sync: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = {+ applyReadySyncPatch,+ EDITS,+ FLAG_INIT_FIND,+ FLAG_INIT_REPLACE,+ ATTACH_MARK_FIND,+ ATTACH_MARK_REPLACE,+ HAS_SYNCED_FIND,+ HAS_SYNCED_REPLACE,+};diff --git a/scripts/patch-wwebjs-ready-sync.spec.js b/scripts/patch-wwebjs-ready-sync.spec.jsnew file mode 100644index 000000000..d8d01078b--- /dev/null+++ b/scripts/patch-wwebjs-ready-sync.spec.js@@ -0,0 +1,121 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const {+ applyReadySyncPatch,+ FLAG_INIT_FIND,+ FLAG_INIT_REPLACE,+ ATTACH_MARK_FIND,+ ATTACH_MARK_REPLACE,+ HAS_SYNCED_FIND,+ HAS_SYNCED_REPLACE,+} = require('./patch-wwebjs-ready-sync');++/**+ * Same contract as the sibling patcher specs: the patcher rewrites a file this repository does not+ * own, so it must fire only on the exact shape it was written for, refuse loudly on anything else,+ * and never leave a half-patched tree — the three edits reference one another (the adapter reads+ * the flag the constructor initialises and the attach path sets).+ */++function fakeWwjs(clientSource) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-ready-'));+ fs.mkdirSync(path.join(dir, 'src'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'src', 'Client.js'), clientSource);+ return { dir, clientFile: path.join(dir, 'src', 'Client.js') };+}++const withSnippets = (flagInit, attachMark, hasSynced) =>+ `class Client {\n constructor() {\n${flagInit}\n }\n async inject() {\n${attachMark}\n${hasSynced}\n }\n}\n`;++const PRISTINE = withSnippets(FLAG_INIT_FIND, ATTACH_MARK_FIND, HAS_SYNCED_FIND);++test('applies all three edits to a pristine upstream tree', () => {+ const { dir, clientFile } = fakeWwjs(PRISTINE);++ const result = applyReadySyncPatch(dir);++ assert.equal(result.skipped, false);+ const patched = fs.readFileSync(clientFile, 'utf8');+ for (const replacement of [FLAG_INIT_REPLACE, ATTACH_MARK_REPLACE, HAS_SYNCED_REPLACE]) {+ assert.ok(patched.includes(replacement));+ }+});++test('is idempotent — a second run is a no-op, not a double patch', () => {+ const { dir, clientFile } = fakeWwjs(PRISTINE);+ applyReadySyncPatch(dir);+ const once = fs.readFileSync(clientFile, 'utf8');++ const result = applyReadySyncPatch(dir);++ assert.equal(result.skipped, true);+ assert.equal(fs.readFileSync(clientFile, 'utf8'), once);+});++test('refuses an upstream shape it does not recognise and leaves the file untouched', () => {+ const { dir, clientFile } = fakeWwjs(withSnippets(FLAG_INIT_FIND, ' somethingElse();', HAS_SYNCED_FIND));+ const before = fs.readFileSync(clientFile, 'utf8');++ assert.throws(() => applyReadySyncPatch(dir), /unsupported Client\.js shape/);+ assert.equal(fs.readFileSync(clientFile, 'utf8'), before);+});++test('refuses a tree containing both the unpatched and the patched form', () => {+ const { dir, clientFile } = fakeWwjs(withSnippets(`${FLAG_INIT_FIND}\n${FLAG_INIT_REPLACE}`, ATTACH_MARK_FIND, HAS_SYNCED_FIND));+ const before = fs.readFileSync(clientFile, 'utf8');++ assert.throws(() => applyReadySyncPatch(dir), /unsupported Client\.js shape/);+ assert.equal(fs.readFileSync(clientFile, 'utf8'), before);+});++test('reports a missing whatsapp-web.js rather than pretending to patch it', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-ready-empty-'));++ assert.throws(() => applyReadySyncPatch(dir), /Client\.js not found/);+});++test('CLI: unrecognised tree exits 1 bare and 0 under --best-effort', () => {+ const { spawnSync } = require('node:child_process');+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'wwjs-ready-cli-'));+ fs.mkdirSync(path.join(root, 'scripts'));+ const script = path.join(root, 'scripts', 'patch-wwebjs-ready-sync.js');+ fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-ready-sync.js'), script);+ const clientDir = path.join(root, 'node_modules', 'whatsapp-web.js', 'src');+ fs.mkdirSync(clientDir, { recursive: true });+ fs.writeFileSync(path.join(clientDir, 'Client.js'), 'class Client {}\n');++ const bare = spawnSync(process.execPath, [script], { encoding: 'utf8' });+ assert.equal(bare.status, 1, 'the production image build must fail on a tree the patcher cannot repair');+ assert.match(bare.stderr, /unsupported Client\.js shape/);++ const bestEffort = spawnSync(process.execPath, [script, '--best-effort'], { encoding: 'utf8' });+ assert.equal(bestEffort.status, 0, 'postinstall must not fail an install the patcher cannot help');+ assert.match(bestEffort.stderr, /skipped/);+});++/**+ * Shape assertions on the replacements themselves: the properties other code depends on. The+ * adapter's reconcile probe reads `eventsAttached === false` as "bridge not ready", so the flag+ * must start false and flip true only after the attach resolves; the level-check must call the+ * SAME handler the edge calls, guarded on the already-true level.+ */+test('replacements carry the contract the adapter relies on', () => {+ assert.ok(FLAG_INIT_REPLACE.includes('this.eventsAttached = false;'), 'flag starts false');+ assert.ok(+ ATTACH_MARK_REPLACE.indexOf('await this.attachEventListeners();') <+ ATTACH_MARK_REPLACE.indexOf('this.eventsAttached = true;'),+ 'flag flips true only after the attach resolves',+ );+ assert.ok(HAS_SYNCED_REPLACE.includes("if (window.require('WAWebSocketModel').Socket.hasSynced)"), 'level guard');+ assert.equal(+ HAS_SYNCED_REPLACE.split('window.onAppStateHasSyncedEvent()').length - 1,+ 2,+ 'level-check fires the same handler the edge fires',+ );+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 8691baa8e..237acbb54 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -1,7 +1,7 @@/*** Post-install hook (npm `postinstall`).*- * Four conditional steps, each skipped when its target is absent so the hook is a no-op where the+ * Five conditional steps, each skipped when its target is absent so the hook is a no-op where the* piece is missing (the Docker builder stage copies package*.json long before any source):** 1. `npm run dashboard:ci` when dashboard/ exists — the dashboard carries its own lockfile and@@ -17,6 +17,8 @@* Docker stage runs it again without best-effort, making dependency drift a build failure.* 4. `node scripts/patch-wwebjs-status.js --best-effort` when present — the status posting* repairs, gated the same way as step 3.+ * 5. `node scripts/patch-wwebjs-ready-sync.js --best-effort` when present — the readiness+ * marker + hasSynced level-check, gated the same way.** Structured like scripts/patch-wwebjs-201832.js: pure planning + injectable spawn, so the spec* (scripts/postinstall.spec.js, node:test) exercises every branch without a real npm run.@@ -66,6 +68,15 @@ function planSteps(root) {options: { stdio: 'inherit', cwd: root },});}+ const readySyncPatcher = path.join(root, 'scripts', 'patch-wwebjs-ready-sync.js');+ if (fs.existsSync(readySyncPatcher)) {+ steps.push({+ name: 'whatsapp-web.js ready-sync repair (scripts/patch-wwebjs-ready-sync.js --best-effort)',+ command: process.execPath,+ args: [readySyncPatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root },+ });+ }return steps;}diff --git a/scripts/postinstall.spec.js b/scripts/postinstall.spec.jsindex 40122c173..f95392036 100644--- a/scripts/postinstall.spec.js+++ b/scripts/postinstall.spec.js@@ -18,10 +18,16 @@ const { planSteps, failureReason, run } = require('./postinstall.js');const OK = { status: 0, signal: null, error: null };/** Bare temp dir optionally holding a dashboard/ and/or the patch scripts. */-function makeRoot({ dashboard = false, patcher = false, previewPatcher = false, statusPatcher = false } = {}) {+function makeRoot({+ dashboard = false,+ patcher = false,+ previewPatcher = false,+ statusPatcher = false,+ readySyncPatcher = false,+} = {}) {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-postinstall-'));if (dashboard) fs.mkdirSync(path.join(root, 'dashboard'));- if (patcher || previewPatcher || statusPatcher) {+ if (patcher || previewPatcher || statusPatcher || readySyncPatcher) {fs.mkdirSync(path.join(root, 'scripts'));}if (patcher) {@@ -33,6 +39,9 @@ function makeRoot({ dashboard = false, patcher = false, previewPatcher = false,if (statusPatcher) {fs.writeFileSync(path.join(root, 'scripts', 'patch-wwebjs-status.js'), '// stub\n');}+ if (readySyncPatcher) {+ fs.writeFileSync(path.join(root, 'scripts', 'patch-wwebjs-ready-sync.js'), '// stub\n');+ }return root;}@@ -90,13 +99,24 @@ test('planSteps: status patcher plans its own best-effort repair', () => {assert.deepEqual(steps[0].args.slice(1), ['--best-effort']);});+test('planSteps: ready-sync patcher plans its own best-effort repair', () => {+ const steps = planSteps(makeRoot({ readySyncPatcher: true }));+ assert.equal(steps.length, 1);+ assert.equal(steps[0].command, process.execPath);+ assert.match(steps[0].args[0], /patch-wwebjs-ready-sync\.js$/);+ assert.deepEqual(steps[0].args.slice(1), ['--best-effort']);+});+test('planSteps: dashboard and all patchers run in stable order', () => {- const steps = planSteps(makeRoot({ dashboard: true, patcher: true, previewPatcher: true, statusPatcher: true }));- assert.equal(steps.length, 4);+ const steps = planSteps(+ makeRoot({ dashboard: true, patcher: true, previewPatcher: true, statusPatcher: true, readySyncPatcher: true }),+ );+ assert.equal(steps.length, 5);assert.equal(steps[0].command, 'npm run dashboard:ci');assert.match(steps[1].args[0], /patch-wwebjs-201832\.js$/);assert.match(steps[2].args[0], /patch-wwebjs-newsletter-preview\.js$/);assert.match(steps[3].args[0], /patch-wwebjs-status\.js$/);+ assert.match(steps[4].args[0], /patch-wwebjs-ready-sync\.js$/);});test('run: nothing to do exits 0 and never spawns', () => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 67640f834..506376a31 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -1233,7 +1233,8 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {type FakeClient = EventEmitter & {info?: { wid?: { user?: string }; pushname?: string };getState: jest.Mock;- pupPage: { evaluate: jest.Mock };+ pupPage: { evaluate: jest.Mock; reload?: jest.Mock };+ eventsAttached?: boolean;destroy?: jest.Mock;logout?: jest.Mock;pupBrowser?: { process?: jest.Mock };@@ -1338,6 +1339,101 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {expect(jest.getTimerCount()).toBe(0);});+ // The patched whatsapp-web.js client carries `eventsAttached`: false until attachEventListeners+ // resolves. A runtime that reports CONNECTED with the flag still false is exactly the live+ // incident this guards against — sends work, but every inbound event is lost. Promoting such a+ // session to READY masks the loss; the probe must refuse it. An UNPATCHED client (flag+ // undefined) keeps the legacy behaviour — covered by the promotion tests above.+ it('does not promote while the runtime is connected but the event bridge never attached', async () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ const { client, onReady } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload: jest.fn().mockResolvedValue(undefined) },+ });++ client.emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100);++ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);+ expect(onReady).not.toHaveBeenCalled();++ client.emit('auth_failure', 'stop test timer');+ expect(jest.getTimerCount()).toBe(0);+ });++ it('reloads the page once — and only once — to reinject a dead event bridge, then promotes when it heals', async () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ const reload = jest.fn().mockResolvedValue(undefined);+ const { client, onReady } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload },+ });++ client.emit('authenticated');+ await jest.advanceTimersByTimeAsync(2100 * 3);++ expect(reload).toHaveBeenCalledTimes(1);+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);++ // The reload re-ran the injection and the bridge attached: the next probe promotes normally.+ client.eventsAttached = true;+ await jest.advanceTimersByTimeAsync(2100);++ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onReady).toHaveBeenCalledTimes(1);+ });++ it('a deadline hit while connected-but-bridge-dead fails WITHOUT clearing the credentials', async () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ const { client, onReady, onStateChanged } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload: jest.fn().mockResolvedValue(undefined) },+ });+ const onError = jest.fn();+ (adapter as unknown as { callbacks: unknown }).callbacks = { onReady, onStateChanged, onError };+ const clearLocalAuth = jest.fn();+ (adapter as unknown as { clearLocalAuth: unknown }).clearLocalAuth = clearLocalAuth;++ client.emit('authenticated');+ await jest.advanceTimersByTimeAsync(91_000);++ // The link itself is healthy — wiping the only copy of the credentials would trade a+ // restart-fixable fault for a forced re-pair. FAILED with the reason, auth left alone.+ expect(adapter.getStatus()).toBe(EngineStatus.FAILED);+ expect(clearLocalAuth).not.toHaveBeenCalled();+ expect(onError).toHaveBeenCalledWith(expect.stringContaining('event bridge'));+ expect(onReady).not.toHaveBeenCalled();+ expect(jest.getTimerCount()).toBe(0);+ });++ it('ignores a premature ready emitted before the bridge attached, then promotes on the real one', () => {+ jest.useFakeTimers();++ const adapter = newAdapter();+ const { client, onReady } = attachFakeClient(adapter, {+ eventsAttached: false,+ pupPage: { evaluate: jest.fn().mockResolvedValue(true), reload: jest.fn().mockResolvedValue(undefined) },+ });++ client.emit('authenticated');+ // The bare re-emit that races ahead of attachEventListeners (observed live): must not promote.+ client.emit('ready');+ expect(adapter.getStatus()).toBe(EngineStatus.AUTHENTICATING);+ expect(onReady).not.toHaveBeenCalled();++ // The attach completes and re-emits ready — this one counts.+ client.eventsAttached = true;+ client.emit('ready');+ expect(adapter.getStatus()).toBe(EngineStatus.READY);+ expect(onReady).toHaveBeenCalledTimes(1);+ });+it('deduplicates the genuine ready event after reconciliation promotes the adapter', async () => {jest.useFakeTimers();diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 3be1ce1c6..ae7bb0845 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -185,6 +185,10 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate readyReconcileTimer: ReturnType<typeof setTimeout> | null = null;private readyReconcileStartedAt = 0;private readyReconcileProbeInFlight = false;+ // What the last reconcile probe observed, driving the bridge-dead self-heal and the deadline+ // decision (a CONNECTED session must never have its credentials wiped).+ private lastProbeStateConnected = false;+ private readyReconcileReloadAttempted = false;// Onboarding-modal watcher handle (#982). Self-rescheduling setTimeout so a hung probe can't stall// the loop; cleared on teardown exactly like readyReconcileTimer.private onboardingWatcherTimer: ReturnType<typeof setTimeout> | null = null;@@ -557,6 +561,22 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin});this.client.on('ready', () => {+ // whatsapp-web.js can emit `ready` BEFORE its message listeners are attached: its post-auth+ // callback runs once per hasSynced trigger, and any run that finds `window.WWebJS` already+ // defined skips the attach and bare-emits `ready` — including while the first run's attach is+ // still in flight (observed live). Promoting on that premature emit binds READY to a session+ // whose inbound bridge may never come up. The patched client's `eventsAttached` flag+ // (scripts/patch-wwebjs-ready-sync.js) distinguishes the cases: `false` → ignore this emit+ // and let the attach's own completion re-emit `ready` (it always does), with the readiness+ // reconciliation as the backstop when the attach failed instead. `undefined` (unpatched+ // tree) keeps the legacy behaviour.+ if ((this.client as Client & { eventsAttached?: boolean }).eventsAttached === false) {+ this.logger.warn('Ignoring premature ready: the message event bridge is not attached yet', {+ sessionId: this.config.sessionId,+ action: 'premature_ready_ignored',+ });+ return;+ }this.markReadyFromClientInfo();});@@ -893,6 +913,29 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Deadline checked at the TOP of every tick (not after the probe) so a slow/hung getState() — a// wedged page can make it never resolve, the very #251/#273 condition — can't defeat the 90s ceiling.if (Date.now() - this.readyReconcileStartedAt >= READY_RECONCILE_TIMEOUT_MS) {+ // A CONNECTED page whose event bridge never attached (even after the one-shot reload) is a+ // different animal from a stuck-after-QR session: the link and the credentials are fine,+ // only this browser instance is broken. Wiping the only copy of the credentials would trade+ // a restart-fixable fault for a forced re-pair — fail loudly and keep the auth instead.+ const bridgeDead =+ this.lastProbeStateConnected &&+ (this.client as (Client & { eventsAttached?: boolean }) | null)?.eventsAttached === false;+ if (bridgeDead) {+ this.logger.error(+ 'WhatsApp Web stayed connected but its event bridge never attached within the readiness ' ++ 'deadline — inbound messages would be silently lost, so the session is marked failed. ' ++ 'The saved credentials were kept; restart the session to relaunch the browser.',+ undefined,+ { sessionId: this.config.sessionId, action: 'ready_reconcile_bridge_dead' },+ );+ this.clearReadyReconcile();+ this.setStatus(EngineStatus.FAILED);+ this.callbacks.onError?.(+ 'WhatsApp Web is connected but its event bridge never attached, so inbound messages would be ' ++ 'lost. The saved session was kept — restart the session to relaunch the browser.',+ );+ return;+ }this.logger.warn('Timed out waiting for WhatsApp Web runtime readiness after authentication — the saved session ' +'is stuck after the QR scan (usually the auto-selected WhatsApp Web build is incompatible). ' +@@ -922,6 +965,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginif (ready && this.client && this.status === EngineStatus.AUTHENTICATING) {this.logger.warn('WhatsApp Web ready event was missed; reconciling from connected runtime state');this.markReadyFromClientInfo();+ } else if (this.status === EngineStatus.AUTHENTICATING) {+ this.maybeReloadDeadBridge();}}).catch(error => this.logger.debug('Ready reconciliation probe failed', { error: String(error) }))@@ -941,6 +986,8 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin}this.readyReconcileStartedAt = 0;this.readyReconcileProbeInFlight = false;+ this.lastProbeStateConnected = false;+ this.readyReconcileReloadAttempted = false;}/**@@ -1138,9 +1185,18 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate async isClientRuntimeReady(): Promise<boolean> {if (!this.client) return false;- if ((await this.client.getState()) !== WAState.CONNECTED) return false;+ const connected = (await this.client.getState()) === WAState.CONNECTED;+ this.lastProbeStateConnected = connected;+ if (!connected) return false;if (!this.client.info?.wid?.user) return false;+ // The patched whatsapp-web.js client (scripts/patch-wwebjs-ready-sync.js) reports whether+ // attachEventListeners resolved. `false` means the page->Node message bridge is dead even+ // though the page reports CONNECTED — promoting that session to READY masks the loss of every+ // inbound event (the live incident this exists for). `undefined` is an unpatched tree: keep+ // the legacy checks rather than refusing readiness a tree cannot ever signal.+ if ((this.client as Client & { eventsAttached?: boolean }).eventsAttached === false) return false;+const page = (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } }).pupPage;const hasWWebJS = await page?.evaluate(() => typeof (window as unknown as { WWebJS?: unknown }).WWebJS !== 'undefined',@@ -1148,6 +1204,31 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn hasWWebJS === true;}+ /**+ * One-shot self-heal for a CONNECTED page whose event bridge never attached: reload the page.+ * whatsapp-web.js re-runs its injection on every `framenavigated`, and a fresh page walks the+ * whole auth->synced->attach pipeline again (with the level-check patch closing the missed-edge+ * race), so a reload is the cheapest full reinjection that keeps the saved session intact.+ */+ private maybeReloadDeadBridge(): void {+ if (this.readyReconcileReloadAttempted) return;+ if (!this.client || !this.lastProbeStateConnected) return;+ const client = this.client as Client & { eventsAttached?: boolean };+ if (client.eventsAttached !== false) return;+ this.readyReconcileReloadAttempted = true;+ this.logger.warn('WhatsApp Web is connected but its event bridge never attached; reloading the page to reinject', {+ sessionId: this.config.sessionId,+ action: 'event_bridge_reload',+ });+ const page = (client as unknown as { pupPage?: { reload?: () => Promise<unknown> } }).pupPage;+ void page?.reload?.()?.catch((error: unknown) =>+ this.logger.warn('Event-bridge reload failed', {+ sessionId: this.config.sessionId,+ error: String(error),+ }),+ );+ }+private setStatus(status: EngineStatus): void {// Latch before anything observes the transition. The constructor's initial DISCONNECTED is a field// initializer and never reaches here, so this only ever fires on a real transition — startup is