OpenWA icon indicating copy to clipboard operation
OpenWA copied to clipboard

Engine pluggability: decouple whatsapp-web.js specifics from the engine-neutral layer

Open rmyndharis opened this issue 5 months ago β€’ 7 comments

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 DeliveryStatus enum (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 MessageType union/enum at the adapter boundary ('chat' β†’ 'text', 'ptt'/'voice' β†’ 'voice', …); consumers switch on the neutral type.

🟠 Medium β€” JID construction outside the adapter

  • contact.controller.ts builds ${number}@c.us in the check-number response.
  • dashboard/MessageTester.tsx builds …@c.us client-side.
  • session.service.ts hardcodes status@broadcast.
  • Fix: let the engine canonicalize numbers β†’ JIDs (checkNumberExists returns the resolved id); surface an isStatusBroadcast/chatType flag 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.us are documentation-only (low priority; genericize opportunistically).

rmyndharis avatar Jun 16 '26 15:06 rmyndharis

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 latent chat-vs-text issue)
  • [ ] JID canonicalization via engine (contact.controller / MessageTester @c.us; status@broadcast flag)
  • [ ] Engine registry (register/select a 2nd engine)
  • [ ] Opaque per-engine config (Puppeteer out of the neutral contract)

rmyndharis avatar Jun 16 '26 16:06 rmyndharis

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@broadcast flag)
  • [ ] Engine registry (register/select a 2nd engine)
  • [ ] Opaque per-engine config (Puppeteer out of the neutral contract)

rmyndharis avatar Jun 16 '26 17:06 rmyndharis

βœ… Item 3 (Medium β€” JID construction outside the adapter) β†’ PR #271

Two of the three sub-items shipped:

  • contact.controller.ts ${number}@c.us β€” removed. Added IWhatsAppEngine.getNumberId(number); the controller now returns the engine-resolved canonical whatsappId. ⚠️ 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.ts status@broadcast β€” replaced with a neutral isStatusBroadcast flag 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 β†’ neutral MessageType β€” βœ… #270
  • 🟠 JID construction β€” βœ… #271 (MessageTester deferred)
  • 🟠 Puppeteer config in neutral contract β€” ⏳ next
  • 🟠 EngineFactory registry β€” ⏳ next

rmyndharis avatar Jun 16 '26 18:06 rmyndharis

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 (mergeDeliveryStatus mirrors backend ackStatusTransitionFrom exactly; the live WS ack fires on every receipt and can arrive out of order/replayed).
  • docs/06 message.ack payload + 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 idempotent MessageTypeBackfillService that 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.

rmyndharis avatar Jun 17 '26 00:06 rmyndharis

Shipped in v0.2.8 πŸŽ‰

Three roadmap items merged & released in v0.2.8:

  • πŸ”΄ ack scale β†’ neutral DeliveryStatus β€” #268
  • πŸ”΄ IncomingMessage.type β†’ neutral MessageType (+ 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.tsx still builds …@c.us client-side

rmyndharis avatar Jun 17 '26 02:06 rmyndharis

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 β†’ canonical whatsappId) instead of hand-building @c.us. This removes the last engine-neutral-layer JID construction.
  • 🟠 EngineFactory registry β†’ deferring (YAGNI). A plugin registry already exists β€” PluginLoaderService (registerBuiltInPlugin/getPlugin/enablePlugin), selectable by engine.type config. Adding a second engine is essentially one more registerBuiltInPlugin call. 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.

rmyndharis avatar Jun 17 '26 02:06 rmyndharis

βœ… 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.

rmyndharis avatar Jun 18 '26 11:06 rmyndharis