Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwebjs): report what the page threw when a send fails

Yudhi Armyndharisb9be896b5045
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2bd602158..cda34c5ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -83,6 +83,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- whatsapp-web.js sessions no longer report a call rejection that did not stop the call: the call reject route answers `501` and `autoRejectCalls` logs a failed auto-reject.
- A Baileys session added to or joining a group emits `group.join`, as whatsapp-web.js already did.
- A send that fails inside the engine logs a warning carrying the session, chat, message id and the engine's error, where only Nest's generic `[ExceptionsHandler]` line recorded it before ([#1679](https://github.com/rmyndharis/OpenWA/issues/1679)). Thanks @DavidgFernandes for the report.
+- A whatsapp-web.js send that fails inside the page reports what the page threw and the WhatsApp Web build that was running, in the failure log, the bulk batch result and the `message:failed` hook, instead of the minified `t: t` ([#1679](https://github.com/rmyndharis/OpenWA/issues/1679)). Thanks @DavidgFernandes for the report.
- whatsapp-web.js sessions reach ready in the Docker image, Compose and Helm when no WA Web version is pinned; the library's local HTML cache tried to write to the read-only app directory.
- A stopped built-in `openwa-postgres` container is started before the data connection dials it, instead of the gateway crash-looping at boot.
- `POST /api/infra/import-data` on PostgreSQL answers `imported: false` with the rejected row's database error instead of `500`.
diff --git a/Dockerfile b/Dockerfile
index 1701db7bb..f6be5943d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -184,10 +184,12 @@ COPY package*.json ./
# scripts/postinstall.js rides along so a bare local `npm ci` keeps working, but the
# --ignore-scripts install below skips the hook here: the explicit fatal run right
# after is the sole (and stricter) applier for the image.
-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/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-wwebjs-media-id.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.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/patch-wwebjs-participant-arity.js scripts/patch-wwebjs-block.js scripts/patch-wwebjs-group-description.js scripts/patch-wwebjs-media-id.js scripts/patch-wwebjs-send-error.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js ./scripts/
# Install production dependencies only, then apply the backports. The status patcher runs after
# the two patchers it depends on: its transforms were written against the tree they leave behind.
+# The send-error patcher runs after the other two that edit Client.js, so theirs still meet the
+# tree they were written against.
# scripts/dockerfile-patchers.spec.js derives this list from scripts/patch-*.js and fails if a
# patcher is added without being copied AND run here — a hand-written list loses one silently, and
# the Baileys one shipped in postinstall for a whole release without ever reaching the image.
@@ -209,6 +211,7 @@ RUN npm ci --omit=dev --ignore-scripts \
&& node scripts/patch-wwebjs-block.js \
&& node scripts/patch-wwebjs-group-description.js \
&& node scripts/patch-wwebjs-media-id.js \
+ && node scripts/patch-wwebjs-send-error.js \
&& node scripts/patch-baileys-appstate.js \
&& node scripts/patch-baileys-newsletter-create.js \
&& npm cache clean --force
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 7262b6f77..8e28c2568 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -732,7 +732,7 @@ rm -rf node_modules/whatsapp-web.js && npm ci
block/unblock refusing every id, a status media send that never arrives, a group description that
cannot be set, an app-state resync that never settles
-**Cause:** OpenWA applies nine exact source transforms to its engine libraries at install time
+**Cause:** OpenWA applies eleven exact source transforms to its engine libraries at install time
(docs/29 §29.3). The Docker image runs them without `--best-effort`, so a source shape a patcher
cannot recognise fails the image build. A source install runs them through `scripts/postinstall.js`
with `--best-effort`, where a patcher that cannot apply prints one line into a long `npm install`
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 0301fb57a..62324ff82 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -5,7 +5,7 @@ Three-way comparison of every capability: the **Baileys library** (`@whiskeysock
its adapter layer and REST API — including which "supported" cells only work because OpenWA patches
the installed library. Coverage is total: all 113 `IWhatsAppEngine` methods (29.4), **all 152
Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all
-10 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
+11 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.
## 29.1 How to read this matrix
@@ -49,7 +49,7 @@ flowchart LR
IF --> BA["BaileysAdapter"]
SVC --> STORE["OpenWA-side stores"]
end
- WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 8 OpenWA patches"]
+ WA --> WLIB["whatsapp-web.js 1.34.7<br/>+ 9 OpenWA patches"]
BA --> BLIB["@whiskeysockets/baileys 7.0.0-rc14<br/>+ 2 OpenWA patches"]
WLIB --> WEB["WhatsApp Web<br/>headless Chromium"]
BLIB --> WAS["WhatsApp servers<br/>browser-free socket"]
@@ -125,7 +125,7 @@ wrong interface method. Those three remain reader-verified.
## 29.3 Install-time patches OpenWA applies to the libraries
-OpenWA ships ten exact, self-disabling source transforms over the installed engines. Each runs at
+OpenWA ships eleven exact, self-disabling source transforms over the installed engines. Each runs at
`npm install` (`scripts/postinstall.js`, `--best-effort`) and again in the Docker production stage
(**without** best-effort — dependency drift fails the image build). "Self-disabling" means the
patcher no-ops once the fix is present upstream, and an unrecognized source shape fails loudly
@@ -138,7 +138,7 @@ it is missing as it starts (`src/engine/adapters/engine-patch-status.ts`; 🔧¹
check described below). The report is diagnostic, not preventive: startup continues, so a session
reaching READY is not evidence that every patch landed. See docs/12 for the operator procedure.
-### 29.3.1 The ten patches
+### 29.3.1 The eleven patches
| # | Patcher | Library target | What it repairs | Stand-down predicate |
| ---- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -152,10 +152,11 @@ reaching READY is not evidence that every patch landed. See docs/12 for the oper
| 🔧⁸ | `scripts/patch-wwebjs-block.js` | whatsapp-web.js `Contact.js` | `Contact.block()`/`unblock()` resolved their target through `getContactToBlockOnlyUseIfNoAssociatedChat`, which WhatsApp Web removed, so both answered an opaque `500` for every id shape. The replacement helpers `handleBlock`/`handleUnblock` are modal-driven UI wrappers that block nothing when called headless, and the server now refuses a phone-keyed block outright (`trying to block a pn contact without a chat`) because individual chats are keyed by LID while wwjs folds every id back to a phone number. Resolves through `WAWebLidMigrationUtils.toUserLid` to the chat-owning identity and calls `blockContact`/`unblockContact` directly, falling back to the original contact when no LID or chat exists. | exact-shape match on both bodies; unknown shape fails the build. |
| 🔧⁹ | `scripts/patch-wwebjs-group-description.js` | whatsapp-web.js `GroupChat.js` | `GroupChat.setDescription()` calls the page's `WAWebGroupModifyInfoJob.setGroupDescription(chatWid, description, newId, descId)` positionally, but that job now takes a single options object `{desc, groupWid, newDescId, prevDescId}`. The first positional argument lands where the object is read, every field comes back undefined, and `widToGroupJid(undefined)` throws inside the page — reaching the caller as a bare `500` while the library still types the method `Promise<boolean>`. `setGroupSubject` in the same module is still positional, which is why subjects kept working and made the Wid look innocent. The patch sends the options object, takes `newDescId` from `WARandomHex.randomHex(8)` as the product does, and maps an empty description to `desc: null` so it selects the job's delete branch rather than sending an empty body element. The open upstream fix #201895 changes the same call, but keeps `WAWebMsgKey.newId()` and passes an empty description through verbatim, so this patcher will not stand down when it lands and the `desc: null` mapping has to be carried over rather than dropped with it. | exact-shape match; unknown shape fails the build. |
| 🔧¹⁰ | `scripts/patch-wwebjs-media-id.js` | whatsapp-web.js `Injected/Utils.js` | Every media send built by `processMediaData` failed on the WhatsApp Web builds rolled out on 2026-09-17 with `Data passed to getter must include an id property`, while text still sent. `window.WWebJS.sendMessage` builds the outgoing message with `id: newMsgKey` and then spreads the media model returned by `processMediaData` into it, and on those builds that model carries an enumerable private `__x_id` that clobbers the id when the `Msg` model initialises. The patch deletes `message.__x_id` right after the object is built, which is upstream's own fix (whatsapp-web.js PR #201923, unmerged, no release after 1.34.7). It stands down once the installed tree carries that line. | exact-shape match; unknown shape fails the build. |
+| 🔧¹¹ | `scripts/patch-wwebjs-send-error.js` | whatsapp-web.js `Client.js` | A send the page refused reached OpenWA as the minified `t: t`, with nothing but Node frames: puppeteer rebuilds a page-side exception from its class name and description only, and WhatsApp Web's own error classes are minified to one letter and keep their detail in their own properties. The patch wraps the `window.WWebJS.sendMessage` call inside `Client.sendMessage`'s evaluate. A plain `Error`, which is what whatsapp-web.js's own send failures and WhatsApp Web's `No LID for user` already are, is rethrown as the same object, so its text and OpenWA's matching on it are unchanged. Anything else is rethrown as an `Error` reading `page threw {...}`, a capped JSON summary of the WhatsApp Web build actually running, the constructor name, `name`, `message`, `stack` and the value's own properties. Diagnostic only: a successful send returns what it returned before, and the dead-page classifier never reads a captured error as a transport death. | exact-shape match; unknown shape fails the build. |
### 29.3.2 Which matrix rows depend on which patch
-This is the patch visibility the matrix cells refer to. Every patch is engine-specific (8 on wwjs,
+This is the patch visibility the matrix cells refer to. Every patch is engine-specific (9 on wwjs,
2 on Baileys), and **no row carries a row-level patch mark on both engines**. The two column-wide
patches are a separate matter: 🔧¹ underwrites every wwjs cell and 🔧⁵ every baileys cell, so in
that sense every row does depend on a patch on each side. "Patch-dependent" below means a patch
@@ -174,6 +175,7 @@ class of rows (🔧⁸ and 🔧¹⁰), stated in the table instead.
| 🔧⁹ group description | `setGroupDescription` on **wwjs**. Without it every call throws in the page and answers a bare `500`, so the capability is dead rather than degraded; `setGroupSubject` beside it is unaffected. Row-marked. |
| 🔧⁸ block/unblock | `blockContact`, `unblockContact` on **wwjs**. Without it both answer an opaque `500` on every id, so the capability is dead rather than degraded; the blocklist read still works, which makes the failure look one-sided. |
| 🔧¹⁰ media send repair | Every **wwjs** media send built by `processMediaData`: `sendImageMessage`, `sendVideoMessage`, `sendAudioMessage` (voice notes included, through `ptt`), `sendDocumentMessage` and the media status posts. A sticker is built by `processStickerData`, which returns a new object rather than the media model. On the WhatsApp Web builds from 2026-09-17 the library's own id is clobbered by the media model and every such send answers a bare `500`, while text sends keep working. Not row-marked: it covers a whole class of rows rather than one. |
+| 🔧¹¹ send error capture | No row. Every **wwjs** send that fails in the page reports what the page threw instead of `t: t`, but no cell's outcome depends on it: a send that works without the patch works the same way with it. |
Rows that are ✅ on **both** engines where one side is patch-dependent: `initialize` (🔧⁴ wwjs),
`sendTextMessage` (🔧³ wwjs), `postTextStatus` / `postImageStatus` / `postVideoStatus` /
@@ -646,7 +648,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at
| `constructor` | — class plumbing (not a capability) |
| `destroy` | ✅ `initialize`, `destroy`, `forceDestroy`, `disconnect`, `logout` |
| `getState` | ⚙️ internal wiring |
-| `getWWebVersion` | ❌ **not exposed** — the build is pinned from `wa-web-version.ts`, never read back off the client |
+| `getWWebVersion` | ❌ **not exposed** — pinned from `wa-web-version.ts`; captured send errors name the running build |
| `initialize` | ✅ `initialize` |
| `logout` | ✅ `logout` |
| `on` | ⚙️ EventEmitter surface — the adapter's event wiring (29.5.4) |
@@ -997,7 +999,7 @@ adapter sources — re-derive the same way when anything changes:
cannot repopulate; and `rejectCall`, whose `Call.reject()` resolves while the caller's phone
keeps ringing (all in 29.6.2). Each answers 501 on wwjs. `.d.ts` presence is not capability, and
only a live call distinguishes the two.
-- **10** install-time patches (8 whatsapp-web.js + 2 Baileys), all exact and self-disabling.
+- **11** install-time patches (9 whatsapp-web.js + 2 Baileys), all exact and self-disabling.
- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.
- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —
fetch is one line, `BinaryNode`→`ChannelMessage` parser is the work); **#2** `subscribeToChannel`
diff --git a/package.json b/package.json
index 2b8abdbc9..1161de11d 100644
--- a/package.json
+++ b/package.json
@@ -41,7 +41,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 scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-wwebjs-block.spec.js scripts/patch-wwebjs-group-description.spec.js scripts/patch-wwebjs-media-id.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs scripts/cli-entrypoint-guard.spec.mjs",
+ "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 scripts/patch-wwebjs-participant-arity.spec.js scripts/patch-wwebjs-block.spec.js scripts/patch-wwebjs-group-description.spec.js scripts/patch-wwebjs-media-id.spec.js scripts/patch-wwebjs-send-error.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs scripts/check-audit.spec.mjs scripts/check-contract-shapes.spec.mjs scripts/cli-entrypoint-guard.spec.mjs",
"test:docs": "jest src/common/changelog-sections.spec.ts src/common/ci-privilege-gate.spec.ts src/common/docs-ci-jobs.spec.ts src/common/docs-coverage-policy.spec.ts src/common/docs-metrics-list.spec.ts src/common/docs-next-version.spec.ts src/common/openapi/docs-06-contract.spec.ts src/common/test-lane-partition.spec.ts src/config/docs-env-example.spec.ts src/config/openapi-contract.spec.ts src/config/openapi-export-pins.spec.ts src/config/wa-web-version-example-pin.spec.ts src/engine/docs-29-counts.spec.ts src/engine/engine-inventory-parity.spec.ts src/engine/engine-parity.spec.ts src/engine/inventory-mapping-direction.spec.ts src/engine/adapters/baileys-voice-waveform.spec.ts src/engine/adapters/wwebjs-newsletter-preview.spec.ts src/modules/audit/audit-coverage.spec.ts src/modules/auth/global-route-fence-coverage.spec.ts src/modules/auth/query-session-scope-coverage.spec.ts src/modules/docker/compose-network.spec.ts src/modules/queue/bull-board-mount-coverage.spec.ts src/common/release-gate-parity.spec.ts src/database/migrations/__tests__/migration-drift.spec.ts --testPathIgnorePatterns=/node_modules/",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
diff --git a/scripts/patch-wwebjs-send-error.js b/scripts/patch-wwebjs-send-error.js
new file mode 100644
index 000000000..45b17bfe9
--- /dev/null
+++ b/scripts/patch-wwebjs-send-error.js
@@ -0,0 +1,194 @@
+/**
+ * Make a failed whatsapp-web.js send report what the page actually threw.
+ *
+ * `Client.sendMessage` runs the send inside `page.evaluate`, and puppeteer rebuilds a page-side
+ * exception in Node from two CDP fields only, the class name and the description
+ * (puppeteer-core `cdp/utils.js` `createEvaluationError`). WhatsApp Web's own error classes are
+ * minified to a one-letter name and keep their detail in their own properties rather than in
+ * `message`, so a send the page refuses (`MediaFileTooLarge`, `InvalidMediaCheckRepairFailedType`)
+ * reaches OpenWA as `t: t` with nothing but Node frames. The warning a failed send logs then names
+ * no cause, and neither does anything the operator can send upstream (#1679).
+ *
+ * The patch wraps the one `window.WWebJS.sendMessage` call inside that evaluate. A plain Error is
+ * rethrown untouched, for the reasons given at FIX. Any other thrown value is rethrown as a plain
+ * Error whose message is PREFIX followed by a JSON summary read inside the page: the WhatsApp Web
+ * build that is actually running, the constructor name, `String()`, `name`, `message`, `stack`, and
+ * the value's own properties. The build is read from the page because the one OpenWA pins is not
+ * always the one that runs: a warm profile's service worker can serve a newer build under the pin.
+ *
+ * Diagnostic only. A send that succeeds returns exactly what it returned before, and a send that
+ * fails still fails; only the text of the failure changes. `getChat`, `sendSeen` and
+ * `getMessageModel` stay outside the wrap, so their failures reach Node exactly as before.
+ *
+ * PREFIX is shared with `src/engine/adapters/wwebjs-lifecycle.ts` (CAPTURED_PAGE_ERROR_PREFIX),
+ * whose dead-page classifier must never read a captured error as a transport death: the summary
+ * quotes WhatsApp Web's own text, which can mention a closed connection while the page is plainly
+ * alive. `wwebjs-send-page-error.spec.ts` pins the two constants equal.
+ *
+ * The source transform is deliberately exact and self-disabling, like the sibling patchers. An
+ * unknown shape fails the production image build instead of silently shipping without it, and the
+ * patch stands down once the installed tree carries it.
+ */
+'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');
+
+/** The start of every message this patch builds. Kept identical to the manual patch posted on #1679. */
+const PREFIX = 'page threw ';
+
+// The send call inside Client.sendMessage's page.evaluate and the line that consumes its result,
+// unique in the file. Neither the #201832 backport nor the ready-sync patch touches these lines.
+const ANCHOR = ` const msg = await window.WWebJS.sendMessage(
+ chat,
+ content,
+ options,
+ );
+ return msg ? window.WWebJS.getMessageModel(msg) : undefined;
+`;
+
+// A plain Error (`e.constructor === Error`) passes through as the SAME object. That is what the send
+// path's readable failures already are: whatsapp-web.js's own throws (`Could not get the quoted
+// message.`, `media-fault: ...`) and WhatsApp Web's bare `No LID for user`, which puppeteer rebuilds
+// readably, message and page frames included. OpenWA matches them by substring
+// (isNoLidForUserError, isQuoteUnresolvedError) and the dead-page classifier reads the same text, so
+// handing them over byte-identical is what guarantees none of those decisions can change.
+// Everything else is captured: WhatsApp Web's own subclasses, which arrive as `t: t`; primitives,
+// which arrive as a bare value with no stack; objects puppeteer cannot describe (a null prototype, a
+// hostile Proxy), which arrive as `Protocol error (Runtime.callFunctionOn): Internal error` and so
+// read as a dead page; and native subclasses such as TypeError, which arrive readable today and gain
+// the running build and their own properties.
+//
+// Every read of the thrown value is guarded, because it can be anything: a primitive, `undefined`, a
+// null-prototype object, a throwing getter, a Proxy whose traps throw, or a cycle. Each field is cut
+// to 500 characters and every field and property name shares a 2000-character budget, so a thrown
+// object carrying a large buffer or thousands of properties cannot turn one failed send into a
+// multi-kilobyte log line, bulk result or hook payload. The budget is charged in what the JSON
+// spends, not in raw characters: escaping writes a control character as six, and each property
+// adds its quotes, colon and comma, so counting the raw text let the message reach several times
+// the budget.
+const FIX = ` let msg;
+ try {
+ msg = await window.WWebJS.sendMessage(
+ chat,
+ content,
+ options,
+ );
+ } catch (e) {
+ let plain = false;
+ try {
+ plain = e instanceof Error && e.constructor === Error;
+ } catch {
+ plain = false;
+ }
+ if (plain) throw e;
+ let budget = 2000;
+ // The longest start of text whose JSON encoding, quotes aside, fits in room.
+ const fit = (text, room) => {
+ let cut = text.slice(0, room);
+ while (JSON.stringify(cut).length - 2 > room) cut = cut.slice(0, -1);
+ return cut;
+ };
+ const read = (get) => {
+ let text;
+ try {
+ text = String(get());
+ } catch {
+ text = '(unreadable)';
+ }
+ text = fit(text, Math.max(0, Math.min(500, budget)));
+ budget -= JSON.stringify(text).length;
+ return text;
+ };
+ const info = {
+ build: read(() => window.Debug.VERSION),
+ ctor: read(() => e.constructor.name),
+ str: read(() => e),
+ name: read(() => e.name),
+ message: read(() => e.message),
+ stack: read(() => e.stack),
+ };
+ let keys = [];
+ try {
+ keys = Object(e) === e ? Object.getOwnPropertyNames(e) : [];
+ } catch {
+ info.props = '(unreadable)';
+ }
+ for (const key of keys) {
+ if (budget <= 0) break;
+ if (key in info) continue;
+ const name = fit(key, Math.min(100, budget));
+ // The name in quotes, then its colon and comma.
+ budget -= JSON.stringify(name).length + 2;
+ info[name] = read(() => e[key]);
+ }
+ throw new Error('${PREFIX}' + JSON.stringify(info));
+ }
+ return msg ? window.WWebJS.getMessageModel(msg) : undefined;
+`;
+
+function occurrences(source, needle) {
+ return source.split(needle).length - 1;
+}
+
+function applyBackport(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}`);
+ }
+
+ const source = fs.readFileSync(clientFile, 'utf8');
+ const anchorCount = occurrences(source, ANCHOR);
+ const fixCount = occurrences(source, FIX);
+
+ if (anchorCount === 0 && fixCount === 1) {
+ return {
+ skipped: true,
+ reason: 'installed whatsapp-web.js already reports page-side send errors',
+ };
+ }
+ if (anchorCount !== 1 || fixCount !== 0) {
+ throw new Error(
+ `unsupported Client.js shape (anchors: ${anchorCount}, fixes: ${fixCount}); ` +
+ 're-evaluate the send error capture against the installed whatsapp-web.js',
+ );
+ }
+
+ fs.writeFileSync(clientFile, source.replace(ANCHOR, FIX));
+ return { skipped: false, note: 'page-side send errors now carry what the page threw' };
+}
+
+/**
+ * The stand-down branch above as a predicate, for the startup guard (engine-patch-status.ts).
+ * Unreadable reads as applied: a tree we cannot inspect is not evidence of a broken one.
+ */
+function isApplied(wwjsDir = DEFAULT_WWJS) {
+ try {
+ const source = fs.readFileSync(path.join(wwjsDir, CLIENT_PATH), 'utf8');
+ return occurrences(source, ANCHOR) === 0 && occurrences(source, FIX) === 1;
+ } catch {
+ return true;
+ }
+}
+
+function run() {
+ const bestEffort = process.argv.includes('--best-effort');
+ try {
+ const result = applyBackport();
+ console.log(`patch-wwebjs-send-error: ${result.skipped ? `skipped: ${result.reason}` : result.note}`);
+ } catch (error) {
+ if (bestEffort) {
+ console.warn(`patch-wwebjs-send-error: skipped: ${error.message}`);
+ return;
+ }
+ console.error(`patch-wwebjs-send-error: ${error.message}`);
+ process.exitCode = 1;
+ }
+}
+
+if (require.main === module) run();
+
+module.exports = { applyBackport, isApplied, ANCHOR, FIX, PREFIX };
diff --git a/scripts/patch-wwebjs-send-error.spec.js b/scripts/patch-wwebjs-send-error.spec.js
new file mode 100644
index 000000000..20c658e07
--- /dev/null
+++ b/scripts/patch-wwebjs-send-error.spec.js
@@ -0,0 +1,334 @@
+'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 vm = require('vm');
+const { spawnSync } = require('child_process');
+
+const { applyBackport, isApplied, ANCHOR, FIX, PREFIX } = require('./patch-wwebjs-send-error.js');
+
+const INSTALLED_CLIENT = path.join(__dirname, '..', 'node_modules', 'whatsapp-web.js', 'src', 'Client.js');
+
+/**
+ * The installed Client.js as upstream ships it. The tree this spec runs in has normally been through
+ * postinstall already, so the transform is reversed first; the anchor is replaced whole, which makes
+ * that reversal exact.
+ */
+function pristineClient() {
+ const installed = fs.readFileSync(INSTALLED_CLIENT, 'utf8');
+ return installed.includes(FIX) ? installed.replace(FIX, ANCHOR) : installed;
+}
+
+function makeDependency(source) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-send-error-'));
+ const client = path.join(root, 'src', 'Client.js');
+ fs.mkdirSync(path.dirname(client), { recursive: true });
+ fs.writeFileSync(client, source);
+ return { root, client };
+}
+
+test('applies to the Client.js the installed whatsapp-web.js ships, and the result still parses', () => {
+ const pristine = pristineClient();
+ assert.equal(
+ pristine.split(ANCHOR).length - 1,
+ 1,
+ 'the installed Client.js carries neither the anchor nor this capture; after editing FIX, reinstall ' +
+ 'whatsapp-web.js (npm ci) so the tree is patched with the current one',
+ );
+ const { root, client } = makeDependency(pristine);
+
+ const result = applyBackport(root);
+
+ assert.deepEqual(result, { skipped: false, note: 'page-side send errors now carry what the page threw' });
+ const patched = fs.readFileSync(client, 'utf8');
+ assert.equal(patched, pristine.replace(ANCHOR, FIX));
+ // Compile only: the copy cannot be required from a temp dir, its relative requires would miss.
+ assert.doesNotThrow(() => new vm.Script(patched, { filename: client }));
+});
+
+test('is idempotent once the capture is present', () => {
+ const { root, client } = makeDependency(pristineClient().replace(ANCHOR, FIX));
+ const original = fs.readFileSync(client, 'utf8');
+
+ assert.deepEqual(applyBackport(root), {
+ skipped: true,
+ reason: 'installed whatsapp-web.js already reports page-side send errors',
+ });
+ assert.equal(fs.readFileSync(client, 'utf8'), original);
+});
+
+test('reports the patch as applied only once the transform has run', () => {
+ const { root } = makeDependency(`head\n${ANCHOR}tail\n`);
+
+ assert.equal(isApplied(root), false);
+ applyBackport(root);
+ assert.equal(isApplied(root), true);
+});
+
+test('reads an unreadable tree as applied rather than raising a false alarm', () => {
+ assert.equal(isApplied(path.join(os.tmpdir(), 'openwa-send-error-absent')), true);
+});
+
+test('rejects an unknown dependency shape without changing it', () => {
+ const { root, client } = makeDependency('const msg = await window.WWebJS.sendMessage(chat, content, options);\n');
+ const original = fs.readFileSync(client, 'utf8');
+
+ assert.throws(() => applyBackport(root), /unsupported Client\.js shape/);
+ assert.equal(fs.readFileSync(client, 'utf8'), original);
+});
+
+test('rejects an ambiguous dependency shape without changing it', () => {
+ const { root, client } = makeDependency(`${ANCHOR}${ANCHOR}`);
+ const original = fs.readFileSync(client, 'utf8');
+
+ assert.throws(() => applyBackport(root), /unsupported Client\.js shape/);
+ assert.equal(fs.readFileSync(client, 'utf8'), original);
+});
+
+test('rejects a capture present alongside a second anchor', () => {
+ const { root, client } = makeDependency(`${FIX}${ANCHOR}`);
+ const original = fs.readFileSync(client, 'utf8');
+
+ assert.throws(() => applyBackport(root), /unsupported Client\.js shape/);
+ assert.equal(fs.readFileSync(client, 'utf8'), original);
+});
+
+test('fails the CLI on an unknown shape without --best-effort, and only warns with it', () => {
+ // The CLI patches the tree beside the script, so run a copy from a scripts/ dir in a scratch root.
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'openwa-send-error-cli-'));
+ const script = path.join(root, 'scripts', 'patch-wwebjs-send-error.js');
+ fs.mkdirSync(path.dirname(script));
+ fs.copyFileSync(path.join(__dirname, 'patch-wwebjs-send-error.js'), script);
+ const client = path.join(root, 'node_modules', 'whatsapp-web.js', 'src', 'Client.js');
+ fs.mkdirSync(path.dirname(client), { recursive: true });
+ fs.writeFileSync(client, 'not the shape\n');
+
+ assert.equal(spawnSync(process.execPath, [script], { encoding: 'utf8' }).status, 1);
+ assert.equal(spawnSync(process.execPath, [script, '--best-effort'], { encoding: 'utf8' }).status, 0);
+ assert.equal(fs.readFileSync(client, 'utf8'), 'not the shape\n');
+});
+
+/** What the stubbed `getMessageModel` answers, one fixed object so a test can compare by identity. */
+const MODEL = { model: true };
+
+/**
+ * The longest message a capture may build: the 2000-character budget, the fixed field names with
+ * their punctuation (53), the prefix (11), and either the `props` marker or the few characters the
+ * last property may run over before the loop stops.
+ */
+const MAX_MESSAGE = 2100;
+
+/**
+ * Run page code against a stubbed `send`: by default the lines the patcher inserts, exactly as
+ * inserted, or the upstream lines they replace for comparison. `chat`, `content` and `options` are
+ * the evaluate's own parameters, so the wrapper declares them; `window` carries only what the lines
+ * read.
+ */
+function runPageCode({ send, model, code = FIX, version = '2.3000.1047868043', debug = true } = {}) {
+ const calls = [];
+ const window = {
+ WWebJS: {
+ sendMessage: (...args) => {
+ calls.push(args);
+ return send();
+ },
+ getMessageModel: model ?? (msg => (msg ? MODEL : assert.fail('getMessageModel called without a message'))),
+ },
+ };
+ if (debug) window.Debug = { VERSION: version };
+ const chat = { id: 'chat' };
+ const content = 'hello';
+ const options = { linkPreview: true };
+ const body = new Function('window', 'chat', 'content', 'options', `return (async () => {\n${code}})();`);
+ return { promise: body(window, chat, content, options), calls, chat, content, options };
+}
+
+/** The rejection of the inserted code for a send that throws `value`. */
+async function rejectionFor(value, opts) {
+ const { promise } = runPageCode({
+ send: () => {
+ throw value;
+ },
+ ...opts,
+ });
+ try {
+ await promise;
+ } catch (error) {
+ return error;
+ }
+ assert.fail('the inserted code resolved although the send threw');
+}
+
+/** The JSON a captured rejection carries, after asserting it is one. */
+function summaryOf(error) {
+ assert.ok(error instanceof Error, 'a captured value must be rethrown as an Error');
+ assert.equal(error.constructor, Error);
+ assert.ok(error.message.startsWith(PREFIX), `expected the capture prefix, got ${error.message.slice(0, 80)}`);
+ return JSON.parse(error.message.slice(PREFIX.length));
+}
+
+test('returns a successful send exactly as the unpatched code did', async () => {
+ const sent = { id: 'sent-1' };
+ const run = runPageCode({ send: async () => sent });
+
+ assert.equal(await run.promise, MODEL);
+ // The send still receives the evaluate's own arguments, the same objects, untouched.
+ assert.equal(run.calls.length, 1);
+ run.calls[0].forEach((arg, i) => assert.equal(arg, [run.chat, run.content, run.options][i]));
+
+ // Each outcome the upstream lines can return, compared against those lines themselves.
+ for (const outcome of [sent, undefined, null, 0, '']) {
+ const upstream = await runPageCode({ send: async () => outcome, code: ANCHOR }).promise;
+ assert.equal(await runPageCode({ send: async () => outcome }).promise, upstream, String(outcome));
+ }
+});
+
+test('rethrows a plain Error as the same object, so its text reaches OpenWA unchanged', async () => {
+ for (const make of [() => new Error('No LID for user'), () => new Error('Could not get the quoted message.')]) {
+ const thrown = make();
+ assert.equal(await rejectionFor(thrown), thrown);
+ }
+ // Rejected asynchronously rather than thrown, the way the injected send fails after an await.
+ const late = new Error('media-fault: sendToChat filehash undefined');
+ const { promise } = runPageCode({ send: () => Promise.reject(late) });
+ await assert.rejects(promise, error => error === late);
+});
+
+test('leaves a failure after the send outside the capture', async () => {
+ // Only the send call is wrapped: a message that was sent but whose model cannot be read fails as
+ // it did before, with the same object, not as a capture that would read like a refused send.
+ const thrown = new TypeError('model read failed');
+ const { promise } = runPageCode({
+ send: async () => ({ id: 'sent-1' }),
+ model: () => {
+ throw thrown;
+ },
+ });
+ await assert.rejects(promise, error => error === thrown);
+});
+
+test('captures a native Error subclass with its constructor and the running build', async () => {
+ const summary = summaryOf(await rejectionFor(new TypeError("Cannot read properties of undefined (reading 'x')")));
+
+ assert.equal(summary.build, '2.3000.1047868043');
+ assert.equal(summary.ctor, 'TypeError');
+ assert.equal(summary.name, 'TypeError');
+ assert.equal(summary.message, "Cannot read properties of undefined (reading 'x')");
+ assert.match(summary.stack, /^TypeError: Cannot read properties/);
+});
+
+test("captures WhatsApp Web's minified error classes with the properties that carry their detail", async () => {
+ // The shape measured on a live WhatsApp Web page, where it reached Node as `t: t`: class `t`, a
+ // name set on the instance, an empty message, no stack, and the detail in an own property.
+ class t extends Error {
+ constructor() {
+ super('');
+ delete this.stack;
+ this.name = 'InvalidMediaCheckRepairFailedType';
+ this.taalOpcodes = [2, 2];
+ }
+ }
+ const summary = summaryOf(await rejectionFor(new t()));
+
+ assert.equal(summary.ctor, 't');
+ assert.equal(summary.name, 'InvalidMediaCheckRepairFailedType');
+ assert.equal(summary.str, 'InvalidMediaCheckRepairFailedType');
+ assert.equal(summary.stack, 'undefined');
+ assert.equal(summary.taalOpcodes, '2,2');
+
+ // A minified class that is not an Error at all.
+ class u {
+ constructor() {
+ this.code = 7;
+ }
+ }
+ const plainClass = summaryOf(await rejectionFor(new u()));
+ assert.equal(plainClass.ctor, 'u');
+ assert.equal(plainClass.code, '7');
+});
+
+test('never lets the value it is reading crash the catch', async () => {
+ const nullProto = Object.create(null);
+ Object.defineProperty(nullProto, 'boom', {
+ enumerable: true,
+ get() {
+ throw new Error('getter');
+ },
+ });
+ nullProto.code = 9;
+ const hostile = new Proxy(
+ {},
+ {
+ ownKeys() {
+ throw new Error('ownKeys');
+ },
+ get() {
+ throw new Error('get');
+ },
+ getPrototypeOf() {
+ throw new Error('proto');
+ },
+ },
+ );
+ const cyclic = { code: 'UPLOAD_FAILED', blob: new Uint8Array(1e6), big: 'x'.repeat(1e6) };
+ cyclic.self = cyclic;
+ const shapes = {
+ undefined: undefined,
+ null: null,
+ string: 't',
+ number: 42,
+ symbol: Symbol('s'),
+ nullProto,
+ hostile,
+ cyclic,
+ };
+
+ for (const [label, value] of Object.entries(shapes)) {
+ const error = await rejectionFor(value);
+ const summary = summaryOf(error);
+ assert.ok(error.message.length <= MAX_MESSAGE, `${label}: summary of ${error.message.length} chars is not capped`);
+ assert.equal(summary.build, '2.3000.1047868043', label);
+ }
+
+ assert.equal(summaryOf(await rejectionFor(undefined)).str, 'undefined');
+ assert.equal(summaryOf(await rejectionFor('t')).str, 't');
+ const readable = summaryOf(await rejectionFor(nullProto));
+ assert.equal(readable.boom, '(unreadable)');
+ assert.equal(readable.code, '9');
+ const unreadable = summaryOf(await rejectionFor(hostile));
+ assert.equal(unreadable.ctor, '(unreadable)');
+ assert.equal(unreadable.props, '(unreadable)');
+});
+
+test('keeps the whole message within its budget however the JSON escapes it', async () => {
+ // Each shape spends more in JSON than in raw characters: control characters escape to six, and
+ // every property adds its quotes, colon and comma even when its value is empty.
+ const controls = '\u0001'.repeat(600);
+ class t extends Error {}
+ const manyKeys = {};
+ for (let i = 0; i < 5000; i++) manyKeys[String.fromCharCode(0x100 + i)] = '';
+ const controlKeys = {};
+ for (let i = 1; i < 32; i++) controlKeys[String.fromCharCode(i).repeat(100)] = controls;
+ const shapes = {
+ controlMessage: new t(controls),
+ manyKeys,
+ controlKeys,
+ array: new Array(100000).fill(''),
+ };
+
+ for (const [label, value] of Object.entries(shapes)) {
+ const error = await rejectionFor(value, { version: controls });
+ summaryOf(error);
+ assert.ok(error.message.length <= MAX_MESSAGE, `${label}: ${error.message.length} chars`);
+ }
+});
+
+test('still captures on a page with no build to report', async () => {
+ const summary = summaryOf(await rejectionFor(new TypeError('x'), { debug: false }));
+
+ assert.equal(summary.build, '(unreadable)');
+ assert.equal(summary.ctor, 'TypeError');
+});
diff --git a/scripts/postinstall.js b/scripts/postinstall.js
index 2d2c3b120..387d25333 100644
--- a/scripts/postinstall.js
+++ b/scripts/postinstall.js
@@ -1,7 +1,7 @@
/**
* Post-install hook (npm `postinstall`).
*
- * Eleven conditional steps, each skipped when its target is absent so the hook is a no-op where the
+ * Twelve 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 ci` inside dashboard/ when dashboard/ exists — the dashboard carries its own lockfile and
@@ -29,11 +29,14 @@
* group-description job call with the options object the page now takes, gated the same way.
* 9. `node scripts/patch-wwebjs-media-id.js --best-effort` when present, stripping the media
* model's private id from the outgoing message so media sends work again, gated the same way.
- * 10. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync
+ * 10. `node scripts/patch-wwebjs-send-error.js --best-effort` when present, making a failed send
+ * report what the page threw instead of `t: t`, gated the same way. It runs after the other
+ * two Client.js patchers (steps 2 and 5), so theirs still meet the tree they were written for.
+ * 11. `node scripts/patch-baileys-appstate.js --best-effort` when present, the app-state resync
* bound, gated the same way.
- * 11. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the
- * newsletter-create parse fix. Steps 10-11 are the Baileys patches, so a Baileys-only install
- * runs those and skips 2-9.
+ * 12. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present, the
+ * newsletter-create parse fix. Steps 11-12 are the Baileys patches, so a Baileys-only install
+ * runs those and skips 2-10.
*
* 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.
@@ -151,6 +154,15 @@ function planSteps(root, env = process.env) {
options: { stdio: 'inherit', cwd: root, env: cleanEnv },
});
}
+ const sendErrorPatcher = path.join(root, 'scripts', 'patch-wwebjs-send-error.js');
+ if (fs.existsSync(sendErrorPatcher)) {
+ steps.push({
+ name: 'whatsapp-web.js send error capture (scripts/patch-wwebjs-send-error.js --best-effort)',
+ command: process.execPath,
+ args: [sendErrorPatcher, '--best-effort'],
+ options: { stdio: 'inherit', cwd: root, env: cleanEnv },
+ });
+ }
const baileysAppStatePatcher = path.join(root, 'scripts', 'patch-baileys-appstate.js');
if (fs.existsSync(baileysAppStatePatcher)) {
steps.push({
diff --git a/scripts/postinstall.spec.js b/scripts/postinstall.spec.js
index bb2878df3..1a8465be4 100644
--- a/scripts/postinstall.spec.js
+++ b/scripts/postinstall.spec.js
@@ -33,6 +33,7 @@ const EXPECTED_PATCHER_ORDER = [
'patch-wwebjs-block.js',
'patch-wwebjs-group-description.js',
'patch-wwebjs-media-id.js',
+ 'patch-wwebjs-send-error.js',
'patch-baileys-appstate.js',
'patch-baileys-newsletter-create.js',
];
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index e180e6521..c7b0e790f 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -67,6 +67,14 @@ export function isProtocolTimeout(error: unknown): boolean {
return PROTOCOL_TIMEOUT_PATTERN.test(error instanceof Error ? error.message : String(error));
}
+/**
+ * The start of a send failure that scripts/patch-wwebjs-send-error.js captured inside the page, where
+ * it summarises a thrown value puppeteer would otherwise hand over as `t: t`. The patcher builds the
+ * message from its own copy of this string (it runs at install time, before any of this is compiled),
+ * and wwebjs-send-page-error.spec.ts pins the two equal.
+ */
+export const CAPTURED_PAGE_ERROR_PREFIX = 'page threw ';
+
/**
* requestPairingCode retry budget. WhatsApp Web reloads the QR page while UNPAIRED, so a pairing
* request can land mid-navigation and either reject fast ("Execution context was destroyed") or hang
@@ -740,6 +748,12 @@ export class WwebjsLifecycle {
return false;
}
const message = error instanceof Error ? error.message : String(error);
+ // A captured page error is never a dead page: the page was alive enough to run the catch that
+ // built it. Its summary quotes WhatsApp Web's own text, and that text can say "connection closed"
+ // about WhatsApp's socket, which the pattern would otherwise read as ours going down.
+ if (message.startsWith(CAPTURED_PAGE_ERROR_PREFIX)) {
+ return false;
+ }
return WwebjsLifecycle.PAGE_TRANSPORT_ERROR_PATTERN.test(message);
}
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index e4edb5a78..e0d75ea8a 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -96,9 +96,10 @@ export async function loadRemoteMedia(url: string, sessionProxyUrl: string | und
}
/**
- * True when a send error is whatsapp-web.js's "recipient needs a LID we don't have" failure, raised
- * when sending to a `@c.us` for a contact WhatsApp has migrated to `@lid`.
- * Matched on the wwjs error text — there is no structured code; revisit if wwjs changes it.
+ * True when a send error is WhatsApp Web's "recipient needs a LID we don't have" failure, a bare
+ * Error its own bundle raises when sending to a `@c.us` for a contact WhatsApp has migrated to
+ * `@lid`. Matched on WhatsApp Web's error text — there is no structured code; revisit if WhatsApp
+ * Web changes it.
*/
export function isNoLidForUserError(err: unknown): boolean {
return err instanceof Error && err.message.includes('No LID for user');
diff --git a/src/engine/adapters/wwebjs-send-page-error.spec.ts b/src/engine/adapters/wwebjs-send-page-error.spec.ts
new file mode 100644
index 000000000..f9a4dd18f
--- /dev/null
+++ b/src/engine/adapters/wwebjs-send-page-error.spec.ts
@@ -0,0 +1,45 @@
+import * as path from 'path';
+import { CAPTURED_PAGE_ERROR_PREFIX, WwebjsLifecycle } from './wwebjs-lifecycle';
+
+/**
+ * A send failure scripts/patch-wwebjs-send-error.js captured inside the page quotes WhatsApp Web's
+ * own text, and the dead-page classifier reads error text. Without the exemption, a refusal whose
+ * summary happened to say "connection closed" would tear down a session whose page had just proved
+ * it was alive by running the catch. The patcher's own spec (node:test) covers what the page code
+ * builds; this one covers how the gateway reads it.
+ */
+
+// The patcher is plain CommonJS under scripts/, loaded by path as engine-patch-status.spec.ts does.
+// eslint-disable-next-line @typescript-eslint/no-require-imports
+const patcher = require(path.join(__dirname, '..', '..', '..', 'scripts', 'patch-wwebjs-send-error.js')) as {
+ PREFIX: string;
+};
+
+const isPageTransportError = (error: unknown): boolean =>
+ WwebjsLifecycle.prototype.isPageTransportError.call({}, error);
+
+/** A captured error as puppeteer hands it over: a plain Error whose message is the prefix and the JSON. */
+const captured = (info: Record<string, string>): Error => new Error(CAPTURED_PAGE_ERROR_PREFIX + JSON.stringify(info));
+
+describe('a send failure captured inside the page', () => {
+ it('uses the prefix the patcher builds it with', () => {
+ // The patcher cannot import the TS constant (it runs at install time), so the two copies are
+ // pinned here instead: a drifted prefix would silently switch the exemption below off.
+ expect(patcher.PREFIX).toBe(CAPTURED_PAGE_ERROR_PREFIX);
+ });
+
+ it('is never read as a dead page, whatever WhatsApp Web text it quotes', () => {
+ for (const quoted of ['connection closed', 'Target closed', 'Protocol error', 'Session closed']) {
+ expect(isPageTransportError(captured({ ctor: 't', name: 't', message: quoted }))).toBe(false);
+ }
+ });
+
+ it('leaves the same words a death when they are not a capture', () => {
+ // Non-vacuity: the quoted text above is exactly what the pattern matches on its own, so the
+ // exemption, and not the words, is what answers false there.
+ expect(isPageTransportError(new Error('connection closed'))).toBe(true);
+ expect(isPageTransportError(new Error('Protocol error (Runtime.callFunctionOn): Target closed'))).toBe(true);
+ // A prefix that is not at the start is not a capture either.
+ expect(isPageTransportError(new Error(`Session closed; ${CAPTURED_PAGE_ERROR_PREFIX}{}`))).toBe(true);
+ });
+});
diff --git a/src/engine/docs-29-counts.spec.ts b/src/engine/docs-29-counts.spec.ts
index d3b327fca..f087096a9 100644
--- a/src/engine/docs-29-counts.spec.ts
+++ b/src/engine/docs-29-counts.spec.ts
@@ -145,7 +145,16 @@ describe('docs/29 counts match the capability matrix', () => {
// 29.3's opening sentence and 29.3.2's split spell the figure in prose rather than digits, which
// is why they drifted while the digit-shaped claims held: a patcher was added to each library and
// the words stayed at "five" and "1 on Baileys".
- const WORDS: Record<string, number> = { four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 };
+ const WORDS: Record<string, number> = {
+ four: 4,
+ five: 5,
+ six: 6,
+ seven: 7,
+ eight: 8,
+ nine: 9,
+ ten: 10,
+ eleven: 11,
+ };
const spelled = doc.match(/OpenWA ships (\w+) exact, self-disabling source transforms/);
const wrongProse: string[] = [];
if (!spelled) wrongProse.push('29.3 opening: phrasing no longer found in the document');
diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.ts
index e04865cbf..c016d7503 100644
--- a/src/modules/message/message-send.service.ts
+++ b/src/modules/message/message-send.service.ts
@@ -189,7 +189,7 @@ export class MessageSendService {
this.pacing.recordSendFailure(sessionId);
// The same classification picks the failures worth a log line. Otherwise an engine-side failure
// leaves only Nest's generic `[ExceptionsHandler]` line, with no session, chat or message type to
- // correlate it with; a minified page error reads as `t: t` there.
+ // correlate it with.
this.logger.warn(`Send failed in the engine (${type})`, {
sessionId,
chatId: message.chatId,