Engine pluggability: decouple whatsapp-web.js specifics from the engine-neutral layer
Context
OpenWA has a pluggable engine architecture β the seam is IWhatsAppEngine (neutral types), and only the adapter layer (src/engine/adapters/*, src/plugins/engines/whatsapp-web-js/*) should know whatsapp-web.js. A code audit found several places outside that seam that assume whatsapp-web.js specifics and would break (or silently misbehave) under a different engine (e.g. Baileys, which uses @s.whatsapp.net JIDs and a different ack/presence/type model).
PR #264 already addressed the lightweight items (engine-neutral typing via sendChatState, mark-chat-read JID validation relaxed, real engine library version surfaced). This issue tracks the remaining, larger decouplings β each is its own PR to keep regression surface contained.
Findings (ranked)
π΄ High β delivery ack scale leaks whatsapp-web.js integers end-to-end
The raw wwebjs MessageAck integer (-1..4) flows through the neutral interface (MessageResult.ack, onMessageAck(id, ack: number)), is interpreted in message-status.util.ts (ackToMessageStatus) and session.service.ts (ack < 0 β message.failed), embedded in webhook payloads + idempotency keys, re-emitted by events.gateway.ts, and re-mapped again in the dashboard (Chats.tsx statusMap, useWebSocket.ts). Baileys uses a different/offset integer scale β every delivery/read state would mis-map.
- Fix: introduce a neutral
DeliveryStatusenum (pending|sent|delivered|read|played|failed) at the seam; each adapter maps its native codes; services/webhook/ws/dashboard consume the neutral string.
π΄ High β IncomingMessage.type is the raw wwebjs MessageTypes string
message-mapper.ts assigns type: msg.type (chat/ptt/voice/revoked/β¦) directly; the dashboard switches on those tokens (Chats.tsx media render, 'ptt'/'voice', and a latent 'chat' vs 'text' mismatch to verify).
- Fix: normalize to a neutral
MessageTypeunion/enum at the adapter boundary ('chat' β 'text','ptt'/'voice' β 'voice', β¦); consumers switch on the neutral type.
π Medium β JID construction outside the adapter
contact.controller.tsbuilds${number}@c.usin the check-number response.dashboard/MessageTester.tsxbuildsβ¦@c.usclient-side.session.service.tshardcodesstatus@broadcast.- Fix: let the engine canonicalize numbers β JIDs (
checkNumberExistsreturns the resolved id); surface anisStatusBroadcast/chatTypeflag instead of string-matching.
π Medium β Puppeteer/browser config baked into the neutral engine contract
infra.controller.ts, EngineCreateOptions, and plugin.createEngine pass headless/puppeteerArgs/executablePath to every engine β meaningless for a non-browser engine.
- Fix: pass only neutral fields generically; deliver engine-specific config via each plugin's own (declared) config schema (opaque bag).
π Medium β EngineFactory hard-registers only the wwebjs plugin
registerBuiltInEngines() registers a single engine and create() resolves by type, but there's no real registry for a second engine.
- Fix: a registry (
Map<engineType, IEnginePlugin>) seeded by each built-in engine module, selectable by config.
Notes
- Audit verified: there are zero raw
import 'whatsapp-web.js'statements outside the adapter layer β the leaks are semantic (values/shapes/JIDs), not direct imports. - Swagger example strings using
@c.usare documentation-only (low priority; genericize opportunistically).
Item 1 done β #268 (open): the raw whatsapp-web.js ack integer no longer leaks past the engine adapter. Neutral DeliveryStatus flows through the interface/services/webhooks/ws/dashboard; message.ack/message.failed gain a neutral status (legacy ack kept, deprecated); dashboard delivery ticks now update live over ws (that path was dead). Behaviour byte-identical; 445 tests; adversarially reviewed.
Remaining:
- [ ]
MessageTypesβ neutral message-type enum (mapper + interface + dashboard; incl. the latentchat-vs-textissue) - [ ] JID canonicalization via engine (contact.controller / MessageTester
@c.us;status@broadcastflag) - [ ] Engine registry (register/select a 2nd engine)
- [ ] Opaque per-engine config (Puppeteer out of the neutral contract)
Item 2 done β #270 (open): raw whatsapp-web.js MessageTypes tokens no longer leak past the adapter. Neutral MessageType enum on IncomingMessage.type; mapWwebjsMessageType is the sole translation point (chatβtext, pttβvoice, vcardβcontact, β¦). Incoming live/history/persisted + message.received/message.sent webhooks are now neutral and consistent with outgoing. Includes a backfill migration (the dashboard reads persisted rows via GET /messages, and stats group by type β so old rows must be normalized) and fixes the latent chat-vs-text dashboard bug. 449 tests; migration SQL verified; adversarially reviewed.
Remaining:
- [ ] JID canonicalization via engine (contact.controller / MessageTester
@c.us;status@broadcastflag) - [ ] Engine registry (register/select a 2nd engine)
- [ ] Opaque per-engine config (Puppeteer out of the neutral contract)
β Item 3 (Medium β JID construction outside the adapter) β PR #271
Two of the three sub-items shipped:
contact.controller.ts${number}@c.usβ removed. AddedIWhatsAppEngine.getNumberId(number); the controller now returns the engine-resolved canonicalwhatsappId. β οΈ Observable change: the value is the engine's normalized id and may differ from the input (e.g.@lid) β live-verified, documented in CHANGELOG + docs/06/07.session.service.tsstatus@broadcastβ replaced with a neutralisStatusBroadcastflag set by the message-mapper. The literal is now confined to the adapter.
Still deferred (this sub-item): dashboard/.../MessageTester.tsx builds β¦@c.us client-side. It needs a dashboard checkNumber API call + an i18n error path, so it's a separate dashboard-side follow-up.
Adversarial review verdict: holds (getNumberId-contract) / exact equivalence (status flag). 439 tests, build + lint clean.
Roadmap status:
- π΄ ack scale β
DeliveryStatusβ β #268 - π΄
IncomingMessage.typeβ neutralMessageTypeβ β #270 - π JID construction β β #271 (MessageTester deferred)
- π Puppeteer config in neutral contract β β³ next
- π
EngineFactoryregistry β β³ next
Deep review of the three open decoupling PRs β done; all green
Ran a source-traced adversarial review (incl. a real 3-way merge simulation) across #268, #270, #271. Outcome:
#268 (DeliveryStatus) β fixed:
- Dashboard tick downgrade guard added (
mergeDeliveryStatusmirrors backendackStatusTransitionFromexactly; the live WS ack fires on every receipt and can arrive out of order/replayed). docs/06message.ackpayload + idempotency-key examples corrected.- CI lint fix (two pre-existing eslint errors in the original commit).
#270 (MessageType) β fixed:
- The backfill migration never ran in the default SQLite (
synchronize:true β migrationsRun:false). Replaced with an idempotentMessageTypeBackfillServicethat runs on bootstrap in every DB mode (+3 tests).
#271 (JID) β clean, no changes.
Cross-PR: only CHANGELOG.md conflicts (trivial). Merge order #268 β #270 β #271.
Release note: #270's webhook type change (chatβtext, pttβvoice, vcardβcontact) is a breaking contract change for webhook consumers β minor version bump required, not a patch.
CI status: all three PRs green (Lint/Test/Build/Dashboard). Roadmap remaining after these land: π Puppeteer config in the neutral contract, π EngineFactory registry.
Shipped in v0.2.8 π
Three roadmap items merged & released in v0.2.8:
- π΄ ack scale β neutral
DeliveryStatusβ #268 - π΄
IncomingMessage.typeβ neutralMessageType(+ startup backfill) β #270 - π JID construction β engine (
getNumberId+isStatusBroadcast) β #271
Also shipped the related @lid β phone resolution (#263 β #277), which added the neutral resolveContactPhone engine method.
Remaining (next):
- π Puppeteer/browser config baked into the neutral engine contract β opaque per-engine config
- π
EngineFactoryβ real engine registry (Map<engineType, plugin>) - π Frontend leak:
dashboard/.../MessageTester.tsxstill buildsβ¦@c.usclient-side
v0.2.9 (non-breaking) progress + scope decision
- π Frontend JID leak (MessageTester
@c.us) β PR #279. It now resolves a personal recipient via the engine (GET /contacts/check/:numberβ canonicalwhatsappId) instead of hand-building@c.us. This removes the last engine-neutral-layer JID construction. - π
EngineFactoryregistry β deferring (YAGNI). A plugin registry already exists βPluginLoaderService(registerBuiltInPlugin/getPlugin/enablePlugin), selectable byengine.typeconfig. Adding a second engine is essentially one moreregisterBuiltInPlugincall. Building the "array-of-built-ins" abstraction now (with only one engine) is speculative; better to shape it against the real second engine (Baileys, v1.0) so it actually fits. No coupling blocker today.
Remaining for this issue:
- π Puppeteer/browser config in the neutral engine contract β opaque per-engine config. This one is breaking (changes
EngineCreateOptions/infra config shape), so it's a v0.3.0 item (per the new SemVer policy), bundled with the deployment-simplification batch (#275/#276).
So after #279 merges, #265's non-breaking work is done; the only substantive item left (Puppeteer opaque-config) is breaking β v0.3.0.
β Closing β all roadmap items shipped
Every finding in this tracker is now resolved past the engine-neutral seam:
| Finding | PR | Released |
|---|---|---|
π΄ ack scale β neutral DeliveryStatus |
#268 | v0.2.8 |
π΄ IncomingMessage.type β neutral MessageType (+ startup backfill) |
#270 | v0.2.8 |
π JID construction β engine (getNumberId + isStatusBroadcast; MessageTester) |
#271, #279 | v0.2.8 / v0.2.9 |
| π Puppeteer/browser config out of the neutral contract β opaque per-engine config | #296 | v0.3.0 |
π EngineFactory β real engine registry |
Baileys engine stack (#299β#312) | v0.3.0 |
The last two items were intentionally deferred until v0.3.0: the opaque-config change was breaking (EngineCreateOptions/infra shape), and the registry was held until a real second engine existed to shape it against (YAGNI). Both conditions were met in v0.3.0 β EngineFactory now registers whatsapp-web.js and Baileys as built-in plugins, each receiving an opaque engine.* config blob, selectable by engine.type. There is no Puppeteer/browser config in the engine-neutral interfaces.
The original audit invariant still holds: zero raw whatsapp-web.js imports outside the adapter layer. Closing as completed.