Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Merge remote-tracking branch 'origin/main' into fix/baileys-chatmodify-keys

Rezk Jörg Sebening17d964c11d88
diff --cc CHANGELOG.md
index 9aebba6d8,c25c62e87..4da43b07b
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -77,12 -102,296 +102,298 @@@ and this project adheres to [Semantic V
- Read a list of lid allowlist entries from the database in one query instead of one per unseen entry first.
- Keep a plugin hook handler that outlives the hook timeout inside the re-entrancy guard, so its late sends no longer re-fire the event and dispatch the handler again.
- Complete a data import on PostgreSQL when clearing a large messages table outlasts the statement timeout.
- - Create the built-in PostgreSQL container with the saved `DATABASE_PASSWORD`, so a custom password saved with the built-in database no longer fails the next boot.
+ - Create the built-in PostgreSQL container with the saved `DATABASE_PASSWORD`, so a custom password saved with the built-in database no longer fails the next boot; a data volume that already exists keeps the role password it was created with.
- Serialize a plugin upload with an uninstall or update of the same plugin id.
- Show hours for a session active within the last day on the Sessions page, as the Dashboard does.
- - Index Baileys clear, delete, archive and unread changes by the same chat jid as their message key, and send an own group message's key without its participant, so the phone applies a clear or delete instead of ignoring it (#1891). Thanks @rjsebening.
- - Key Baileys chat writes and read receipts to the gateway's stored newest message of a chat with no message since the session started, and archive or mark unread a known chat with no message at all, while an unknown id still answers `false`; clear and delete still decline then (#1891). Thanks @rjsebening.
- - List a whatsapp-web.js contact held under both its LID and its phone once in the contacts and blocked lists, with the phone as `number`, instead of twice with the LID's digits.
++- Index a Baileys clear, delete, archive or unread by the same chat jid as its message key, so the phone applies it (#1891). Thanks @rjsebening.
++- Key Baileys chat writes and read receipts to the gateway's newest stored message when the session holds none in memory (#1891). Thanks @rjsebening.
+ - List a whatsapp-web.js contact held under both its LID and its phone once in the contacts and blocked lists, and give it the phone as `number` in the contacts list and by id, where the first copy carried the LID digits.
+ - Clear both entries when unblocking a whatsapp-web.js contact blocked under its phone number and its LID; it stayed in the blocked list after a successful unblock.
+ - Show a localized edited indicator in Chats for observed edits before or after storage, including after reload; deleted messages retain their placeholder (#1905). Thanks @yederlv.
+ - Store messages delivered already deleted as empty tombstones and clear earlier history and search content; suppress repeated content in hooks and events when a stored tombstone can be read.
+ - Answer 409 to a start of a session whose delete is still running; it started an engine that stayed registered for the deleted session.
+ - Preserve a pending session delete's lease fields when another stop arrives.
+ - Stop an older delete before its next removal transaction after ownership changes; a failed claim write answers 503 without removing data.
+ - Keep a session create, a session delete and a plugin instance delete on SQLite out of another request's open transaction, whose rollback could undo a write already answered as done and bring a deleted session back after a `204`; each waits up to 10 s for that transaction to end.
+ - Stop two session creates or plugin instance deletes at the same moment on SQLite from leaving every later data import refused with `409` until a restart.
+ - Save a webhook or automation rule without a transaction, so on SQLite one that fails because its session was just deleted no longer undoes the writes other requests made meanwhile.
+ - Preserve pending start retries when a session delete is refused before removal, while retaining independent operator stops.
+ - Prevent in-flight session starts and expired-owner renewals from undoing an accepted stop.
+ - Prevent overlapping session reconnects from leaking engines or retiring their replacements.
+ - Commit successful expired-owner batch cleanup with the ownership transition, so delayed cleanup cannot fail a later owner's new batches.
+ - Remove the auth directories a deleted session's name keyed before 0.23.5 on PostgreSQL too; a failed id lookup left the old WhatsApp login on the volume.
+ - List a Baileys contact blocked under both its LID and its phone once in the blocked list, as whatsapp-web.js does.
+ - Hold a queued ingress delivery and a reconciler replay for a plugin still restoring after startup without spending a retry attempt, instead of dead-lettering it; held deliveries wake together, which keeps their order apart from the limits docs/25 states.
+ - Answer 400 for a `GET /api/search` `dateFrom` or `dateTo` outside the safe integer range and publish that range in the schema; on PostgreSQL a value past about 9.2e21 answered 500.
+ - Answer an empty page instead of 500 for a list `offset` of 2^63 or more on the audit, session, webhook, delivery failure and message lists.
+ - Stop a Redis that stops answering or answers slowly from making the WebSocket publish client hold every event in memory: a connection silent for 10 s is dropped, events raised while it is down and during its reconnect backoff of up to 5 s are dropped for clients on other replicas instead of replayed late, and a slow Redis is held to about 12,000 unanswered events plus roughly 2 s of traffic.
+ - Ping the Redis subscriber connection of the multi-replica WebSocket fan-out every 15 s and replace it after 30 s without an answer, so a connection a proxy holds open after Redis stopped answering costs other replicas' events for about 45 s at most instead of until it closes.
+ - Count in `GET /api/infra/storage/files/count` only the keys the export carries, leaving out S3 folder placeholders and unsafe keys.
+ - Fall back to the 5000 ms default for a negative `SIMULATE_TYPING_MAX_MS`, which cut the typing pause to about 1 ms.
+ - Never fail a log call on metadata that holds a circular reference, a BigInt or a throwing getter, and redact secret-named keys at any depth instead of the first five levels, including on an object with its own `toJSON`.
+ - Bound the copy of log metadata: below the fifth level at most 1000 more objects and arrays are written and an array or object that does not fit what is left of that budget is written as `[Truncated]`; an array, Map or Set of more than 1,000,000 entries is `[Truncated]` at any level.
+ - Bound one copy of log metadata to 2,000,000 entries (object keys and array lengths, three to a Map's pair) and 2^26 characters (string values, key names and BigInt text, a digit counted sixteen times), a shared value counted at every use, and write what does not fit as `[Truncated]`; a few references to one large value expanded into a copy or a line of unbounded size.
+ - Write an Error in log metadata as its name, message and stack, a Date as its ISO text, a boxed string, number or boolean as its value, a Map or Set as an array of its entries and a Buffer or typed array as its type and length; they were written as `{}` or one field per byte or character.
+ - Redact credentials at any depth in the Baileys wire log (`BAILEYS_LOG_LEVEL`) and copy nested errors before they are written.
+ - Leave functions out of log lines; a function with its own `toJSON` used to be written.
+ - Write a plugin log call whose meta is a string, array, boxed string, typed array, Map, Date, Error or class instance as one `meta` field instead of one field per character or index.
+ - Measure the log metadata of a sandboxed plugin as the logger writes it, a credential value as `[REDACTED]` included, and replace one that exceeds 8192 values and characters by the size marker without building its text first, so it can no longer pass the cap and a large or heavily shared object no longer blocks the host.
+ - Relay a non-string log message of a sandboxed plugin as `[non-string log message]`.
+ - Stop `ctx.logger.error` called without an error from writing the trace `undefined`.
+ - Stop an in-process plugin's `ctx.logger` call from throwing on a message, error or meta it cannot read, such as a Symbol, a revoked Proxy or a throwing `toString`; the line is written with `[Unprintable]` or `[Unreadable]` in its place.
+ - Apply a delete for everyone, an edit or a reaction that reaches a whatsapp-web.js message on SQLite while its contact or media is still being fetched, instead of hooking, storing and announcing the message with its deleted or unedited content.
+ - Store a Baileys reaction to a message that is still downloading its media with the message on SQLite, as on PostgreSQL, and announce it and an edit of the same window once the gateway has the message.
+ - Keep Baileys chat pin, mute and archive state from reverting, or coming back for a deleted or unlinked chat, or reading as defaults for a lid-addressed contact, when a restore, a session start or a chat-list read overlaps a change; a change written under a contact's lid while its state is merged onto the phone number, or in the same millisecond as the phone entry, is no longer lost.
+ - Refuse a chat id that is not in the form `localpart@host` in the MCP tools `SessionSubscribePresence`, `SessionMarkChatRead`, `SessionMarkChatUnread` and `SessionSendChatState`, as their REST routes do.
+ - Send the method of a raw `client.Do` (Go) or `client.request` (JavaScript) call in upper case, so a lowercase verb no longer reaches the gateway as `patch` and answers 400, from SDK 0.7.0.
+ - Refuse every spelling of `/` (`//`, `/.`, `/..`, a link to `/`, `<link to />/..`) for `OPENWA_DATA_DIR`, the state directories, `MAIN_DATABASE_NAME`, `DATABASE_NAME` and `BOOTSTRAP_KEY_FILE` in `scripts/restore.sh`, and resolve `..` after a symlink as the kernel does; run as root, its safety snapshot could copy the filesystem into itself.
+ - Describe the 400 of `POST /api/sessions/{id}/messages/react` and `/delete` as `Session not active or invalid request` in the OpenAPI schema; a missing message answers 404.
+ - Keep the Infrastructure page from reverting a database, Redis, queue or storage switch that was saved and awaits a restart, and from deleting the stored credentials of the backend it switched away from, on the next save.
+ - Seed the Use Built-in toggles of the Infrastructure page from the saved configuration, add a pending-restart note per card and warn in the restart dialog for a switch between a bundled and an external service or to another S3 bucket or endpoint; settings typed beside a switch awaiting a restart were discarded on save.
+ - Stop a save of the Infrastructure page from writing an untouched database type, storage type or Redis switch that the environment pins over the stored choice.
+ - Treat a host that reaches a bundled container by its container name, another letter case or a trailing dot as that container in `GET /api/infra/status` and on the Infrastructure page, whose Use Built-in toggles, notes and switch warnings follow it.
+ - Preserve saved bundled database and S3 connection details beneath host pins, including PostgreSQL TLS when the built-in choice is omitted.
+ - Disable PostgreSQL TLS when an Infrastructure save selects the bundled database for the next boot.
+ - Keep saved PostgreSQL and S3 credentials with their selected service host; inactive SQLite and local-storage settings no longer seed a newly selected service.
+ - Clear supported legacy S3 credential aliases when switching to local storage.
+ - Start a built-in container at boot only for a datastore in use whose host the environment does not pin elsewhere; a restart from the Infrastructure page, whose dialog names each container it stops, stops the built-in Redis when Redis is switched off and neither the queue nor the cache uses it, and a container the dashboard created whose host the environment now pins to another server. A leftover flag started a container nothing used.
+ - Allow saving the Infrastructure page with the PostgreSQL pool size field emptied, which sent null and answered 400.
+ - Allow saving a plugin config whose secret field declares a pattern, which the stored mask failed.
+ - Stop the Webhooks and Templates pages from sending operator-only reads with a viewer key.
+ - Stop the Sessions and Plugins pages from showing "No sessions found" or "No plugins installed" under the error banner when the first list read failed.
+ - Keep the dashboard chat thread where the reader is: reopen a chat left at the bottom at its newest message, keep a saved position while images decode, scroll to new messages the account sent elsewhere, and key the saved position by session and chat.
+ - Keep a dashboard chat reader on their message when several images above it decode at once, when images decode above it while older messages load, and when they open another chat and come back while those messages load or after they arrived.
+ - Scroll a message sent while its chat or an older page is still loading into view, keep a reader at the bottom of the chat when an image decodes as their sent message is confirmed, and open a chat at its own saved position when an image of the previous chat was still decoding.
+ - Keep keyboard focus on the Copy button after a copy where the Clipboard API is missing (plain HTTP), on the API keys, webhooks, templates, plugins and Infrastructure pages.
+ - Fix the dashboard layout on phones, short and half-screen windows: the Dashboard sessions table, Sessions cards, login screen, API key names, install dialog header, webhook filter rows and popover, Infrastructure, Plugins and Templates columns, page headers, Infrastructure card titles and the Chats search scope in longer languages, the Plugins rail and its config dialog's tab strip, the Templates session select, the closed navigation drawer's edge, the language menu, icons at larger text sizes and the page height under a phone browser toolbar.
+ - Improve dashboard keyboard focus, text contrast and right-to-left layouts, and honor reduced motion.
+ - Stop the Message Tester multi-group send when the session is not running or the gateway cannot be reached, instead of recording one failure per remaining group.
+ - Read phone numbers typed in native digits in the Message Tester, bulk list, webhook filter, pairing field, the chat, channel and status searches, the status recipient search and the chat access list of an API key.
+ - Keep the database, Redis and S3 secret fields of the Infrastructure page from being filled by a browser's password manager with the saved dashboard key.
+ - Keep an error toast above an open image in Chats; it was painted under the lightbox backdrop.
+ - Style the Instances tab of the Plugins page: its action buttons, the delete dialog and rows that wrap.
+ - Colour the status pill of the session details dialog for every session status.
+ - Fix the phone navigation drawer: it no longer shows icons only after the sidebar was collapsed on a wider window or covers its close button, it closes with Escape and leaves the tab order while closed, and its menu button announces Close and its expanded state.
+ - Keep icons from shrinking in flex rows at a larger browser text size.
+ - Release the database connection of a data import on PostgreSQL when its transaction cannot begin.
+ - Answer 400 instead of 500 for a template or bulk variable that has no text form.
+ - Report as `message.ack` a delivery or read of a one-to-one message the account sent, or a server rejection, that Baileys folds into the message's own upsert when the two land within about 100 ms of each other; it was dropped and left the message at `sent`.
+ - Send the stored author as the sender of a Baileys group read receipt for a message the engine no longer holds, and leave out an id with no known author; such a receipt carried no sender and still answered `success: true`.
+ - Read a Baileys inbound poll sent under the `pollCreationMessageV4` or `pollCreationMessageV5` content key as a poll with its question and options instead of an empty unknown message.
+ - Stop whatsapp-web.js from announcing `message.edited` and overwriting the stored caption when WhatsApp Web only replaces a media thumbnail or a location preview.
+ - Retry a whatsapp-web.js profile picture asked for by phone id under the contact's LID when the phone form answers nothing or fails, for a contact WhatsApp keys by LID.
+ - Stop a session that cannot see a contact's number from erasing the number another session stored for that contact's lid, so a key restricted to that number keeps the chat; the number is cleared by the session that stored it, or by any session once that one is deleted, logged out or unlinked.
+ - Retry failed LID mapping writes on fresh observations without replaying cached answers as new reports (#1058).
+ - Keep LID lookup expiry independent of system clock changes.
+ - Refresh cached missing LID numbers on the first message after five minutes.
+ - Use shared reported LID mappings consistently for single-chat and chat-list access checks, and withhold stale local aliases after a failed identity change.
+ - Preserve LIDs as message and listing IDs, with display phone numbers separate.
+ - Require an engine-reported LID/phone pair for alias matching in routing, filters and message changes; distinct LIDs remain separate.
+ - Wait for the message writes still in flight for the sessions a data import removes, so no message row is left for a removed session; an import that does not commit fails the unfinished bulk batches of those sessions.
+ - Name each font in the dashboard status composer (System, System text, Script, Bold, Morning Breeze, Calistoga, Exo 2, Courier Prime) instead of its number, offer only ids 0 to 7 on whatsapp-web.js, which posts 8 to 10 in the default font, and draw a received status with font 1 in the system face instead of a serif one.
+ - Throw `OpenWATimeoutException` from the PHP SDK on a host without ext-curl when the gateway stays silent past `timeout`, instead of a Guzzle exception, from PHP SDK 0.7.0.
+ - Keep a reopened proxy editor open on the Sessions page when an earlier save of the same session answers late.
+ - Keep a template draft and a newer delete confirmation on the Templates page when an earlier delete answers late.
+ - Keep a new-session draft on the Sessions page when an earlier create answers late.
+ - Keep a pasted phone number whole in the pairing field of the Sessions page; a native 15-character cap cut "+62 812-3456-7890" and could request a code for the wrong account. A paste with more than 15 digits, or with text other than digits, a plus and phone separators, is refused with the field error instead of requesting a code.
+ - Keep Shift+Tab inside a dashboard dialog when focus is on the dialog itself.
+ - Announce a refused sign-in and a failed first load of the Dashboard to screen readers.
+ - Count the sessions on the Dashboard from the session list while the statistics are unavailable, where the overview read "Showing 3 of 0 sessions" and the Connected Sessions card read 0.
+ - Show a failed session read on the Chats page with a Retry button instead of "No connected sessions".
+ - Keep a banner with a Retry button on the Chats page when the chat list cannot be read, instead of "No chats".
+ - Fix a slow API key save closing the editor of another key opened meanwhile.
+ - Fix a single number check answering after sign-out, a key change or leaving the page.
+ - Name a pinned `REDIS_TLS` or `REDIS_USERNAME` on the Redis card of the Infrastructure page.
+ - List in the restart dialog the bundled containers a disabled datastore leaves behind when its host is pinned to the bundled name.
+ - Fix the Number Checker joining a tab-separated index column into the number.
+ - Fix the Plugins page showing install state from an older catalog read.
+ - Stop a bulk number check at the first 403 instead of failing every number.
+ - Fix the restart dialog staying on the waiting screen when the readiness request never answers.
+ - Fix an old QR reply replacing a newer code or closing a reopened pairing dialog.
+ - Fix the reading position jumping after a chat switch while images were still loading.
+ - Fix quoted chat ids in an uploaded recipients CSV being dropped from a bulk send.
+ - Retry a hung readiness check during a restart and report a restart request that never answers within five minutes as outcome unknown.
+ - Check the plugin instance secret in the dashboard against the 16 to 512 character bounds of the API, counting characters rather than UTF-16 units.
+ - Fix a backup restore continuing under a different API key after sign-out.
+ - Show the Portuguese dashboard to browsers set to European or generic Portuguese.
+ - Remove the hidden field of the clipboard fallback and return focus when copying throws.
+ - Keep Tab inside a dialog that has no focusable control, such as the restart progress view.
+ - Rebuild the SQLite message search index when it no longer matches `messages`, so a search stops returning other messages.
+ - Bound the PostgreSQL UTC session setup with the connection timeout, so a database that accepts a connection and then stalls fails the connection instead of hanging the boot.
+ - Keep chat mute, archive and pin state with its session when the re-key migration meets a session named after another session's id.
+ - Fix Baileys chat mute, pin and archive state being lost after a failed database write.
+ - Fix a Baileys contact lookup answering with a contact of another identity kind that shares the same digits.
+ - Fix Baileys replies carried by contact cards, polls, live locations and orders, and history messages, losing their quoted message and mentions.
+ - Fix the Baileys chat list previewing the first of two messages sent in the same second.
+ - Fix Baileys call outcomes being lost or misreported when a call ended while its rejection was pending.
+ - Stop a Baileys session stopped or deleted while the library loads from creating its auth directory again.
+ - Keep phone and LID identities apart when Baileys finds the account's own row in a group, so a member whose LID digits read like the account's number no longer decides `isAdmin` and `isReadOnly`.
+ - Fix two label changes to one chat made at the same time undoing each other on whatsapp-web.js.
+ - Fix a page reload during a liveness probe closing the reload grace window early on whatsapp-web.js.
+ - Fix a failed phone-to-LID mapping write on whatsapp-web.js not being retried until restart.
+ - Answer 409 instead of 503 for a whatsapp-web.js message or group picture write that races a session stop.
+ - Fix `GET /api/sessions/{sessionId}/channels/{channelId}/messages` answering 404 on whatsapp-web.js for a channel whose id the channel list spells another way.
+ - Stop reading a link preview body at its byte cap, so a title past the cap no longer becomes the preview.
+ - Stop the batch profile-picture lookup after one times out, so no more than five engine lookups run at once; the ids it skips are left out of the answer.
+ - Refuse a boolean `startTime` on `POST /api/sessions/{sessionId}/calls/link` instead of reading it as 1.
+ - Fix approving or rejecting group join requests acting on every pending request when the body was a JSON list or was sent with a content type other than JSON or form encoding; both now answer 400.
+ - Fix saving a contact with a null last name sending the null to WhatsApp Web on whatsapp-web.js.
+ - Fix creating a channel with a null description answering a null description on whatsapp-web.js.
+ - Fix a group add or create charging a bare number and its `@c.us` form as two new contacts against the daily cold allowance.
+ - Keep the SQLite database file path when the Infrastructure page saves SQLite.
+ - Write `data/.env.generated` through a staged file and a rename, so a failed save keeps the previous configuration; where a rename cannot replace the file, or the directory refuses the staged file, such as on a single-file mount or in a directory the app cannot write, it is written in place, and a symlink is written through to its target.
+ - Refuse a configuration save that the next boot would reject, with the boot validation message, instead of persisting it.
+ - Reset `REDIS_TLS` and clear `REDIS_USERNAME` when the Infrastructure page selects the built-in Redis.
+ - Stop a bundled container on restart once its datastore is switched off, even when a pinned host still names it.
+ - Prepare the storage export directory before starting the archive and destroy the archive on every failure path.
+ - Count the template variables a bulk media field names in the data export media budget.
+ - Restore a data backup onto a PostgreSQL schema that lacks an optional table instead of failing with a 500.
+ - Start the selected built-in containers once Docker answers after a failed first connection, and report an unreachable Docker inventory as unknown.
+ - Bound the Docker image and container inspections with the deadline of the other short calls, and pull an image only when the daemon says it is absent.
+ - Wait at most 2 s for the database statistics in a metrics scrape; a late read is kept and served for up to 5 minutes, and the series are omitted only when a read failed or none is recent.
+ - Record a `session_stopped` audit log entry for each session an import with `stopOrphans` stops, including when the import does not commit.
+ - Fix the Python SDK raising `ValueError` instead of the API error when a response carries an oversized numeric `Retry-After`, from SDK 0.7.0.
+ - Fix the Python SDK API and timeout errors failing to unpickle or copy, so they survive a worker process boundary, from SDK 0.7.0.
+ - Ignore a `Retry-After` beyond the number range in the JavaScript SDK, which read it as Infinity seconds, from SDK 0.7.0.
+ - Cap an oversized `Retry-After` in the Go and PHP SDKs instead of wrapping to a short or negative wait, from SDK 0.7.0.
+ - Keep the API error in the Java SDK when a `Retry-After` date is out of range, where an `ArithmeticException` replaced it, from SDK 0.7.0.
+ - Treat a final 1xx response as an error in the Python, Go and PHP SDKs instead of returning it as a success, from SDK 0.7.0.
+ - Keep the query values of a raw path that carries a fragment in the Go, Java and PHP SDKs, where they were sent inside the fragment, from SDK 0.7.0.
+ - Send the `Idempotency-Key` on a Go SDK raw send path that carries a query or a fragment, from Go SDK 0.7.0.
+ - Fix the Go SDK treating a 429 whose body could not be read as retryable, and reporting a stalled 429 body as an API error instead of a timeout, from Go SDK 0.7.0.
+ - Fix the PHP SDK sending template variables, bulk variables and bulk options as a JSON list when the map has numeric keys or is empty, from PHP SDK 0.7.0.
+ - Fix the PHP SDK failing with a `TypeError` when the gateway answers a typed call with a body that is not JSON; it now throws `OpenWAException`, from PHP SDK 0.7.0.
+ - Read the response of a PHP SDK injected client that sets `stream` to `true` inside the timeout handling, so a stalled body is a timeout, from PHP SDK 0.7.0.
+ - Stop media conversion from starting new ffmpeg work once shutdown has begun.
+ - Fall back to `url` in `POST /api/sessions/{sessionId}/media/convert/*` when `base64` holds only a data URI prefix.
+ - Use the saved proxy for media conversion by URL in a restored session whose id is not a UUID.
+ - Drop media supplied through `variables` from finished bulk batches.
+ - Accept a placeholder in `content.mentions` of `send-bulk` and validate the rendered WIDs per item.
+ - Keep send admissions counted across UTC midnight, including bulk and product sends still waiting on the engine.
+ - Hold the typing pause to `SIMULATE_TYPING_MAX_MS`, jitter included.
+ - Drop expired statistics memo entries as new results are stored, so the memo no longer grows with every deleted session.
+ - Update only the supplied fields on `PUT /api/sessions/{sessionId}/templates/{id}` and answer 404 for a template deleted meanwhile, where an overlapping edit was undone or the template came back.
+ - Report a status whose row was removed while its media was written as not stored, and delete its file.
+ - Accept an empty `url` next to `base64` in status posts and media conversion.
+ - Write each dependency file the postinstall scripts rewrite, except the whatsapp-web.js diff patch, to a temporary file and rename it over the original, so a write that fails part-way, such as on a full disk, leaves the file unchanged; a best-effort patch is then skipped, and any other install fails instead of keeping a truncated file.
+ - Keep the `latest` and `X.Y` image tags from moving to an older release when an older tag is released or re-run.
+ - Create the GitHub Release from a notes file, so a CHANGELOG section containing a line that is exactly `EOF` no longer breaks it.
+ - Mirror the PHP SDK to `openwa-php` only from `main` and only while its content matches `main`, so a manual run from another branch or a re-run of an older push no longer replaces a newer mirror.
+ - Tell numeric from string enum members in the SDK shape check.
+ - Remove the temporary directory of `npm run openapi:export` after a usage error or a failed bootstrap.
+ - Forward `S3_ACCESS_KEY` and `S3_SECRET_KEY` in `docker-compose.dev.yml`, as `docker-compose.yml` does, so an older `.env` keeps its storage credentials.
+ - Fix deleting a session on PostgreSQL removing the login of another session whose imported id equals the deleted name.
+ - Fix a session start that was waiting for its claim relaunching the session after a logout.
+ - Fix a stopped or deleted session announcing INITIALIZING after its stop when the first status write replied late.
+ - Fix a start that timed out on engine initialization overwriting the status of the engine a restart launched meanwhile.
+ - Fix a delete during a reconnect leaving the re-created auth directory of the deleted session on disk.
+ - Fix the liveness watchdog recycling an engine that left READY while a probe was in flight.
+ - Fix requests for imported sessions with non-UUID ids not being forwarded to the node that runs them.
+ - Fix `PUT /api/sessions/{sessionId}/presence` re-applying its value on the replacement engine when the call outlived the engine it published to.
+ - Fix a reconnect that found its session stopped keeping the session counted as running, so its lease was renewed and its `MAX_CONCURRENT_SESSIONS` slot stayed taken.
+ - Fix a message that arrived while its session was being deleted surviving the delete.
+ - Stop sending `status.received` for a status that expired before it was stored.
+ - Fix a revoke event without a readable message id erasing an unrelated message that was still arriving.
+ - Fix a message reaction not reaching webhooks and the socket when its stored copy could not be written.
+ - Cap the receipt deliveries of one session to a quarter of the shared webhook dispatch slots in total, however many of its webhooks name `message.receipt`.
+ - Read an ingress route's `conversationId` JSON pointer by RFC 6901 tokens: `~1` and `~0` escapes, empty keys and array indexes only.
+ - Store the `webhook-signature` header of a Standard Webhooks ingress delivery as `[redacted]` in events, queue jobs and dead letters.
+ - Stop a WebSocket subscribe overtaken by an unsubscribe from joining its rooms afterwards; it answers `SUBSCRIPTION_CANCELLED`.
+ - Rank a webhook delivery-failure redrive that a plugin cancels behind untried rows, so it no longer heads every batch; the row keeps its payload.
+ - Dead-letter a queue job as stall exhaustion only when BullMQ failed it for stalling, not for any handler error that carries the stall text.
+ - Retry an ingress delivery whose dispatch error reads `bullmq:rateLimitExceeded` within its attempt budget instead of re-running it without limit.
+ - Bound the wait for the queue producer when ingress dead-letter recovery re-queues a job.
+ - End the idempotency key of recurring webhook events (edits, reactions, session and group changes) in a per-dispatch id instead of a timestamp, so two occurrences in one millisecond no longer share a key.
+ - Refund the WebSocket handshake attempt that succeeded, not the newest attempt of its address.
+ - Fix archived and status media keys embedding Object constructor source text when a sender used the mimetype subtype "constructor".
+ - Fix the production default-secret check refusing a built-in PostgreSQL or MinIO addressed by its container name, another letter case or a trailing dot.
+ - Keep API key usage counts when a use is recorded while the shutdown flush awaits its write.
+ - Fix the storage export skipping its import-limit warnings for files whose size the store does not report.
+ - Stop an MCP MessageHistory read when the client disconnects or cancels.
+ - Accept base64 media with an empty or non-http `url` on the MCP media send tools, as the REST routes do.
+ - Offload MCP tool results larger than 4 KB of UTF-8, not 4096 UTF-16 units.
+ - Accept a fractional `timeoutMs` in a plugin's `net.fetch`.
+ - Honor an error returned with data from a sandboxed hook handler, as the host chain does.
+ - Give hook registrations made in the same millisecond separate ids.
+ - Keep plugin storage keys apart: a legacy key spelled like another key's encoded filename no longer reads or deletes that key, and `list()` returns only keys that `get`, `set` and `delete` accept.
+ - Keep a plugin's registry entry until its uninstall has removed its files, so a failed uninstall can be repeated.
+ - Carry a plugin's stored data into the new tree before an update swaps it in.
+ - Refuse a plugin catalog entry whose id, name, version or text fields are not text, and accept null in its optional fields.
+ - Log at start the position and reason of each `SSRF_ALLOWED_HOSTS` entry that never matches a host: a scheme, credentials, port, path or wildcard, or an IP address not written as the URL parser prints it (`127.0.0.1`, not `127.1`); at most 20 entries are listed, and a value the URL parser rejects is named as such.
+ - Run every `message:sending` handler, a moderation veto included, for a send that a hook handler schedules after its own call has ended; it was skipped as re-entrant.
+ - Redrive only the dead letters written under an ingress instance's current session binding.
+ - Drop a null optional field from plugin catalog entries instead of answering it.
+ - Fix the JavaScript SDK raw requests with a fragment in the path dropping their query parameters.
+ - Cap the JavaScript SDK `retryAfterSeconds` at 2147483 seconds, the longest delay `setTimeout` accepts once multiplied by 1000.
+ - Report the database name to the Infrastructure form only under PostgreSQL, and drop a stored SQLite file path when a PostgreSQL save sends no name.
+ - The message list no longer answers an empty page when its `after` row is deleted while the page is being read.
+ - The message list reads its page rows by primary key on SQLite, which cuts a 100 row read of a 300k row session from about 70 ms to 5 ms.
+ - Fix the PHP SDK reading a `Retry-After` header of 309 or more digits as 0 seconds; it is now capped like a smaller oversized value.
+ - Do not mark a patch release on an older line as the GitHub Latest release, which the update check reads.
+ - Answer a body over `BODY_SIZE_LIMIT`, malformed JSON, a body nested past the bound and an undecodable path parameter under `/api` and `/mcp` with 413 or 400 when the bundled dashboard is served, where they answered `404 Cannot POST` ([#1921](https://github.com/rmyndharis/OpenWA/issues/1921)). Thanks @ScalingMBA for the report.
+ - Answer a `chatId` that is not `localpart@host` on a send or message-action body, and on the MCP message tools, with `400` instead of `500`; a bare phone number reached the engine, and every such request counted against the session's send breaker.
+
+ ### Dependencies
+
+ - `body-parser` 2.3.0 to 2.4.0 for safe compressed-request error handling in the HTTP server.
+ - `i18next` 26.4.2 to 26.4.4 in the dashboard tree, closing a regular-expression denial of service in its nested-translation parser. It ships in the dashboard bundle.
+ - The image's Node.js 22.23.3 to 22.23.4, a security release for the `http`, `dns`, `tls`, `permission` and `crypto` modules.
+ - The image's npm CLI 12.1.0 to 12.2.1, clearing CVE-2026-102276, CVE-2026-102278 (brace-expansion) and CVE-2026-19534 (undici) in its own bundled tree; npm only runs for the documented migration commands, and the three Trivy exceptions for them are gone.
+ - The amd64 image's Chrome for Testing 153.0.8010.36 to 156.0.8078.47, picking up the browser security fixes released since; the arm64 image keeps the chromium package Debian ships.
+
+ ### Upgrade notes (behavior changes)
+
+ - Source installs using Puppeteer's downloaded browser move from Chrome 146 to 156; back up `SESSION_DATA_PATH` (default `data/sessions/`) before starting and restore it before downgrading Chrome. An explicit `PUPPETEER_EXECUTABLE_PATH` keeps selecting that browser.
+ - ⚠️ **Breaking (config).** A production boot refuses a `METRICS_TOKEN` that is the `.env.example` placeholder or a known weak value such as `test` or `change-me`, since the scrape endpoint is public; set a long random token, or leave it unset to keep the endpoint disabled.
+ - The HTTP port now opens after at most 60 s of plugin restore. Until a plugin still restoring is up, the hooks it owns (a send moderation veto, for one) do not run, an enable, disable, update, uninstall or reinstall of it answers `409`, an ingress route with a response contract answers `503` with `Retry-After`, and other ingress deliveries are held and dispatched once it is up (with the queue off, by the reconciler after `INGRESS_RECONCILE_GRACE_MS`); do not rely on a plugin veto for requests in the first minute after a boot with slow plugins.
+ - An explicit `null` for a secret field of a plugin config removes the stored secret, where 0.25.0 kept it; a client that sends `null` for "not provided" must leave the key out.
+ - A client that connects to the Socket.IO root namespace `/` is refused; connect to `/events`.
+ - Baileys group sends reuse a cached participant list for up to 5 minutes; set `BAILEYS_GROUP_METADATA_CACHE_TTL_MS=0` to query for every send as before.
+ - `GET /info` through the bundled Docker socket proxy is refused; a client of your own that reads it needs `INFO: 1` on the proxy.
+ - Changing `QUEUE_PREFIX` on a live deployment leaves the jobs queued under the old prefix unprocessed.
+ - The first boot on PostgreSQL converts the legacy message types in one statement inside the boot transaction, about 1 minute per million legacy rows while the port stays closed; raise `startupProbe.failureThreshold` or run the migrations first (docs/14, section 14.5).
+ - Session deletion commits bounded batches before the final transaction. Earlier removals survive a later failure; repeat DELETE to finish, or explicitly start the remaining session. Size client and proxy timeouts for large histories (docs/14, section 14.5).
+ - During rolling upgrades, 0.25.0 nodes can explicitly start or take over sessions marked `deleting` or `deleting-stopped` without clearing those records. Upgrade every node before relying on delete holds, removal fences or serialized batch cleanup.
+ - LID mappings inherited from older versions or backups without report-origin data no longer authorize phone aliases until an engine reports the pair. Upgrade every reader together; Baileys now returns LIDs with display phone numbers separate.
+ - On SQLite, `POST /api/sessions`, `DELETE /api/sessions/{sessionId}` and `DELETE /api/integration/plugins/{pluginId}/instances/{instanceId}` wait for another open database transaction and answer `503` when it stays open for 10 s: the create stores nothing and the instance delete deletes nothing; a session delete may already have committed earlier batches. Retry after the transaction ends.
+ - A storage export or file count now answers 409 on a symbolic link inside the local storage directory (replace it with the real directory or a bind mount), on a directory the app cannot read and on one nested 20 levels deep.
+ - Request validation is stricter: a JSON boolean or object in a string field, an object for a list or an array for an object, a body nested over 100 levels and a `muteUntil` above 9007199254740991 answer `400` where they were accepted or answered `500`; a client that posts a number for a string field is unaffected.
+ - ⚠️ **Breaking (SDK types only, no gateway change).** From SDK 0.7.0, the JavaScript, Python and Go SDKs type the response fields the gateway always sends as required and no longer allow the `null` it never sends, the Go response fields marked required no longer leave a zero value out when marshaled, `ParticipantsResult` no longer extends `SuccessResult` in the JavaScript and Python SDKs, and the key validation `role` is typed `admin`, `operator` or `viewer` in both; code that builds these objects by hand or tests those fields for `null` needs updating.
+ - From SDK 0.7.0, the PHP SDK throws from the constructor for an empty list as a `defaultHeaders` value, which 0.6.0 accepted; use `''` for an empty header value.
+ - `restore.sh` stops before it copies anything, naming the key, when a path from the archive's own `.env.generated` leads out of the data directory, passes through a link that does not resolve, or lies inside or around another directory the restore refills; set that key in the environment or `./.env` to restore there. The default paths and a leftover `./uploads` restore as before.
+ - The amd64 image moves from Chrome for Testing 153 to 156, so an amd64 rollback to 0.25.0 or earlier crosses a browser major and deletes the stored whatsapp-web.js logins unless `sessions/` is restored from a backup taken before the first start on the new image (see `docs/11-operational-runbooks.md`); Baileys sessions are unaffected.
+ - A `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` flag starts its container at boot only while the datastore is in use (PostgreSQL selected; Redis, the queue or the cache on; S3 storage) and its host is not pinned to another server; a container nothing used is no longer started, and a restart from the Infrastructure page stops one the dashboard created whose host is pinned elsewhere.
+ - `envPinned` of `GET /api/infra/status` can list any of the 31 settings a save of the Infrastructure page writes, where 0.25.0 listed eight; a client that reads it must expect the database, Redis and S3 keys and the built-in flags too.
+ - The dashboard status composer offers only fonts 0 to 7 on whatsapp-web.js, which posts 8 to 10 in the default font; the API still accepts every font id.
+ - A boot with `REDIS_TLS=true` or a named `REDIS_USERNAME` beside the built-in Redis (`REDIS_BUILTIN=true` with the bundled host) is refused; set `REDIS_TLS=false` and clear the username, or use an external Redis.
+ - A boot with `STORAGE_TYPE=s3` and an `S3_ENDPOINT` without `http://` or `https://` (for example `minio:9000`) still starts, on the local media directory, and logs an error; add the scheme.
+ - `POST /api/sessions/{sessionId}/groups/{groupId}/membership-requests/approve` and `/reject` answer `400` for a JSON list body or a content type other than JSON or form encoding; they used to act on every pending request. Send `{}` or no body for that.
+ - On whatsapp-web.js, `POST /api/sessions/{sessionId}/pairing-code` answers `409` for a number that is the stored phone of another session of the gateway.
+ - On SQLite the first boot checks the message search index against all stored text and rebuilds it when they differ, so a large database starts more slowly while the port is closed.
+ - The idempotency key of recurring webhook events ends in a random id minted per dispatch instead of an ISO timestamp; a receiver that reads its last segment as a time must dedupe on the whole key.
+ - An ingress route's `conversationId` JSON pointer is read by RFC 6901 tokens, so a trailing or doubled slash names an empty key; a delivery such a pointer no longer resolves takes the per-instance lane.
+ - A boot with `DATABASE_SSL=true` beside the built-in PostgreSQL (`POSTGRES_BUILTIN=true` with the bundled host) is refused; set `DATABASE_SSL=false`, or use an external PostgreSQL.
+ - `GET /api/sessions/{sessionId}/contacts/profile-pictures` leaves out an id it skipped after another lookup timed out, where an id without a picture or with a failed lookup stays `null`; a client that indexes the answer by every requested id must handle a missing key.
+ - A plugin catalog with an entry whose `id`, `name`, `version` or text field is not text is refused with `400`, naming the entry; the default catalog is unaffected, and a private `PLUGIN_CATALOG_URL` catalog must correct the entry.
+ - `POST /api/integration/instances/{pluginId}/{instanceId}/redrive` replays and counts only the dead letters written under the instance's current session binding; rows of an earlier binding stay in the dead-letter table.
+ - A per-session plugin config or an integration instance that sets a `net.allowConfigHosts` key (for example `baseUrl`) to another origin than the layer beneath no longer inherits that layer's `secret` fields, and a list holding one is not inherited either; put the secret in that config or instance, or the plugin reaches the new host without it. A deployment that shared one token across per-session hosts must copy the token to each. A host key that holds a list, an object or a number counts as another origin, and a write to an override or an instance that moves a host key to another origin no longer gets the stored secret back for `***` or an empty string; send the secret with it. An instance row loses its own secrets while a per-session override has moved a host key the row leaves unset away from the base config, and a config `PATCH` of an instance whose plugin is not loaded answers `409`.
+ - A send or message-action body whose `chatId`, `fromChatId` or `toChatId` has no domain (`6281234567890` instead of `[email protected]`), or is a JSON number, answers `400`; it answered `500` before and never sent.
+
+ ### Security
+
+ - `scripts/restore.sh` refuses, before it copies anything and naming the key, a path from the archive's own `.env.generated` that leads out of the data directory, passes through a link that does not resolve, or lies inside or around another directory the restore refills; an archive someone else built or altered could make it replace directories and files outside the data directory. A key set in the environment or `./.env` is honored as before.
+ - Template and bulk sends measure the rendered length before building the text: a template send past `TEMPLATE_RENDER_MAX_CHARS` answers `400`, a bulk item whose text or caption would pass it fails, and a bulk media item that would render past the media size limit is refused; a placeholder repeated through the text made the server build the whole text first, which could exhaust its memory.
+ - Socket.IO connections to the root namespace `/` are refused, where an unauthenticated client stayed connected outside the handshake and per-key socket limits; only `/events` accepts clients.
+ - An object sent for `allowedChats`, `allowedSessions` or `allowedIps` when an API key is created or updated answers `400`; it was stored as an empty list, which means no restriction, so the key reached every chat, session or address.
+ - The secrets of a wildcard integration instance are removed from the plugin config when the instance is deleted, disabled, moved to one session or saved without them; they stayed in use after that.
+ - A pairing code request on whatsapp-web.js for a number that is the stored phone of another session answers `409`; a key restricted to one session could have WhatsApp revoke the login of another through it. The refusal also tells such a key that a number it tries is held by another session.
+ - A session-restricted ADMIN key that creates, moves, disables or deletes an integration instance no longer retires the plugin's all-sessions activation, which silenced the plugin on sessions the key cannot see.
+ - A queued or replayed ingress delivery keeps the verified flag recorded when it was accepted, so a plugin update that makes an unsigned route sign no longer labels a payload nobody authenticated as verified.
+ - An ingress delivery admitted for one session fails when its instance moved to another session while it waited, where it reached the handler with the other session's config.
+ - Disconnect a WebSocket whose API key's stored expiry stops parsing, as REST already refuses it.
+ - The message list no longer returns a row that was replaced between page selection and read and no longer matches the requested chat, time window, direction or type; for a chat-restricted key it could be another chat's message.
+ - `scripts/restore.sh` also refuses an archive configuration that puts the admin key file, `.env.generated` or `database.sql` on a directory the restore refills, where a link planted in the archive made the copy write outside the data directory.
+ - A per-session plugin config or an integration instance that points a `net.allowConfigHosts` key at another origin than the layer beneath no longer receives that layer's secrets, where a session-restricted admin key could send the operator's stored tokens to a host of its choosing.
## [0.25.0] - 2026-10-15
diff --cc docs/06-api-specification.md
index bf2a204ac,a7cb7b34b..1e9b4946d
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@@ -986,7 -992,7 +992,7 @@@ Mark a chat as read/seen
| `chatId` | string | Yes | `@IsString`; `@IsNotEmpty`; `@MaxLength(255)`; `@Matches(/^[^\s@]+@[^\s@]+$/)` (localpart@host, no whitespace) | Engine-native JID, e.g. `[email protected]` (wwebjs) or `[email protected]` (Baileys) |
| `messageIds` | string[] | No | `@IsArray`; `@ArrayNotEmpty`; `@ArrayMaxSize(100)`; each a non-empty token with no whitespace | Messages to acknowledge. Omit the field to acknowledge only the newest received message; an empty array is rejected. |
- Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message gets a receipt: the one the engine holds in memory, else, for a session restarted since it arrived, the newest received message the gateway stored. A burst therefore leaves its earlier messages unread. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.
-Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message the engine still holds in memory gets a receipt, so a burst leaves its earlier messages unread and a session restarted since the message arrived has nothing to acknowledge at all. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. An id the store never held (history backfill) in a group takes its `participant` from the author the gateway stored for that message; one with no stored author is left out of the receipt, and the route answers `{ "success": false }` when none of the ids could be named. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.
++Baileys acknowledges individual messages rather than chats, and the receipt enumerates ids instead of carrying a read-up-to watermark. Without `messageIds` only the newest received message gets a receipt: the one the engine holds in memory, else, for a session restarted since it arrived, the newest received message the gateway stored. A burst therefore leaves its earlier messages unread. Each supplied id is resolved through the message store, which is what carries the `participant` a group receipt needs. An id the store never held (history backfill) in a group takes its `participant` from the author the gateway stored for that message; one with no stored author is left out of the receipt, and the route answers `{ "success": false }` when none of the ids could be named. Ignored by whatsapp-web.js, whose own `sendSeen` is chat-level.
```json
{ "chatId": "[email protected]", "messageIds": ["3EB0C767D26B8A3F1A2B", "3EB0C767D26B8A3F1A2C"] }
diff --cc docs/29-engine-capability-matrix.md
index d31c61a3a,9499f1bce..f3296835d
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@@ -964,22 -964,21 +964,29 @@@ adapter boundary — none silently stub
return a code, but on whatsapp-web.js the request runs in the shared WhatsApp Web page and checks
no precondition: measured twice, a request for a number that already had a linked session was
followed within about a minute by WhatsApp revoking that device, whatsapp-web.js deleting its
- credentials and the session returning to `qr_ready`. Baileys writes only its own credentials and
- showed no such effect. Link by QR when the session of that number must stay up.
+ credentials and the session returning to `qr_ready`. The gateway now answers `409` on whatsapp-web.js
+ for a number that is the stored phone of another of its sessions (the mobile-marker spellings of a
+ Brazilian, Mexican or Argentine number count as one), but it cannot see a link made on another gateway
+ or only on the phone. Baileys writes only its own credentials, showed no such effect and is not
+ refused. Link by QR when the session of that number must stay up.
- **`archiveChat` / `clearChatMessages` / `deleteChat` / `sendSeen` / `markUnread` (baileys).** The
- four `chatModify` actions (archive, clear, delete, unread) need the chat's last known message, which
- the patch carries. `sendSeen` without message ids is `readMessages([key])` for the newest _received_
- (not `fromMe`) message, since Baileys drops own keys from a receipt. A chat with no such message
- resolves `false` rather than throwing, so a chat the session has seen no message in, or one holding
- only this account's own sends, answers `POST chats/read` with `{"success": false}`, where
- whatsapp-web.js marks it read from the page-side chat object without needing any local history.
+ four `chatModify` actions (archive, clear, delete, unread) are keyed to the chat's newest message:
+ the one the session holds in memory, else the newest one the gateway stored (#1891). The patch is
+ indexed by the same jid as that message's key: a message in memory under the jid it arrived with,
- a stored one under the chat's lid when the persisted mapping holds one, else its phone jid; an own
- group message goes without its participant. With no message at all, clear and delete resolve
- `false`, and archive and unread are sent without a range for a chat the session knows (a chat
- record, a persisted state row or a stored message) and resolve `false` otherwise; unread also
- resolves `false` for an archived chat, which the phone leaves unmarked without a range. `sendSeen`
++ a stored one under the lid its row is filed under, or the chat's only reported lid, else its phone
++ jid; an own group message goes without its participant. A key that does not belong to the chat is
++ not used. With no usable message, clear and delete resolve `false`, and archive and unread are sent
++ without a range for a chat the session knows (a chat record, a persisted state row or a stored
++ message) whose jid belongs to it, and resolve `false` otherwise; unread also resolves `false` for an
++ archived chat, which the phone leaves unmarked without a range. `sendSeen`
+ without message ids is `readMessages([key])` for the newest _received_ (not `fromMe`) message, in
+ memory or stored, since Baileys drops own keys from a receipt. A chat with no such message resolves
+ `false`, so one holding only this account's own sends answers `POST chats/read` with
+ `{"success": false}`, where whatsapp-web.js marks it read from the page-side chat object without
+ needing any local history.
+ With message ids, a group id the message store never held (history backfill) takes its receipt's
+ participant from the author the gateway stored for it; one with no stored author is left out of the
+ receipt, and the answer is `false` when no id could be named.
- **`setProfileName` / `setProfilePicture` / `deleteProfilePicture` refusals (baileys).**
whatsapp-web.js reads a page-side verdict for all three (`setDisplayName` and `setProfilePicture`
resolve `false`, `deleteProfilePicture` resolves an explicit `false`) and raises a `403`. The
diff --cc sdk/go/chats.go
index 1941dad14,1941dad14..90556170b
--- a/sdk/go/chats.go
+++ b/sdk/go/chats.go
@@@ -61,7 -61,7 +61,8 @@@ func (s *ChatsService) Delete(ctx conte
}
// Archive archives or unarchives a chat. A false Success means the engine
--// declined — on Baileys a chat with no known history cannot be archived.
++// declined — on Baileys an id the session knows no chat for. A known chat with
++// no message in memory or stored is archived without one.
func (s *ChatsService) Archive(ctx context.Context, sessionID string, body ArchiveChatRequest) (*SuccessResult, error) {
return s.post(ctx, sessionID, "/archive", body)
}
@@@ -84,7 -84,7 +85,7 @@@ func (s *ChatsService) Mute(ctx context
// ClearMessages deletes every message in a chat, keeping the chat itself. A
// false Success means the engine declined — an unknown chat, or on Baileys a
--// chat with no known history. On success the gateway also deletes its stored
++// chat with no message in memory or stored. On success the gateway also deletes its stored
// copy of the chat's messages (rows, inline and archived media, search
// entries); export the history first if you need it.
func (s *ChatsService) ClearMessages(ctx context.Context, sessionID, chatID string) (*SuccessResult, error) {
diff --cc sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
index f1eeb3f0e,f1eeb3f0e..87a88c13c
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ChatsResource.java
@@@ -100,8 -100,8 +100,9 @@@ public final class ChatsResource
}
/**
-- * Archive or unarchive a chat. A false success means the engine declined — on Baileys a chat
-- * with no known history cannot be archived.
++ * Archive or unarchive a chat. A false success means the engine declined — on Baileys an id the
++ * session knows no chat for. A known chat with no message in memory or stored is archived without
++ * one.
*/
public SuccessResult archive(String sessionId, ArchiveChatRequest body) {
return client.request(
diff --cc sdk/javascript/src/resources/chats.ts
index 3cba796cd,3cba796cd..eac984aa4
--- a/sdk/javascript/src/resources/chats.ts
+++ b/sdk/javascript/src/resources/chats.ts
@@@ -87,8 -87,8 +87,8 @@@ export class ChatsResource
}
/**
-- * Archive or unarchive a chat. `success: false` means the engine declined — on Baileys a chat
-- * with no known history cannot be archived.
++ * Archive or unarchive a chat. `success: false` means the engine declined — on Baileys an id the
++ * session knows no chat for. A known chat with no message in memory or stored is archived without one.
*/
archive(sessionId: string, body: ArchiveChatRequest): Promise<SuccessResult> {
return this.client.request<SuccessResult>({
@@@ -127,7 -127,7 +127,7 @@@
/**
* Delete every message in a chat, keeping the chat itself. `success: false` means the engine
-- * declined — an unknown chat, or on Baileys a chat with no known history. On success the gateway
++ * declined — an unknown chat, or on Baileys a chat with no message in memory or stored. On success the gateway
* also deletes its stored copy of the chat's messages (rows, inline and archived media, search
* entries); export the history first if you need it.
*/
diff --cc sdk/php/src/Resources/ChatsResource.php
index 55cf2e967,55cf2e967..6c6abc927
--- a/sdk/php/src/Resources/ChatsResource.php
+++ b/sdk/php/src/Resources/ChatsResource.php
@@@ -85,8 -85,8 +85,9 @@@ class ChatsResourc
}
/**
-- * Archive or unarchive a chat. A false `success` means the engine declined — on Baileys a chat
-- * with no known history cannot be archived.
++ * Archive or unarchive a chat. A false `success` means the engine declined — on Baileys an id
++ * the session knows no chat for. A known chat with no message in memory or stored is archived
++ * without one.
*
* @param array<string,mixed> $body chatId and archive (bool).
* @return array<string,mixed>
diff --cc src/core/agent-tools/tools/session.tools.ts
index 18652a09f,f22d62b06..87e7129fd
--- a/src/core/agent-tools/tools/session.tools.ts
+++ b/src/core/agent-tools/tools/session.tools.ts
@@@ -117,7 -121,7 +121,8 @@@ export function sessionTools(session: S
.optional()
.describe(
'Specific message IDs to acknowledge. Baileys acknowledges individual messages, so without ' +
-- 'this only the newest received message still held in memory gets a receipt.',
++ 'this only the newest received message gets a receipt: the one held in memory, else the ' +
++ 'newest received one the gateway stored.',
),
}),
handler: input =>
diff --cc src/engine/adapters/baileys-contacts.ts
index 8e57ea93e,efeece4a1..f0ae8beb0
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@@ -1,11 -1,8 +1,14 @@@
+ import type * as BaileysLib from '@whiskeysockets/baileys';
+ import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
+ import { queryLidPhone } from './baileys-identity-query';
import type { WAMessage, WAMessageKey, WASocket } from '@whiskeysockets/baileys';
-import { ChatSummary, Contact, MediaInput } from '../interfaces/whatsapp-engine.interface';
+import {
+ ChatSummary,
+ Contact,
+ MediaInput,
+ type StoredChatMessage,
+ type StoredChatMessageLookup,
+} from '../interfaces/whatsapp-engine.interface';
import { assertReadableImage, resolveMediaBuffer } from './baileys-messaging';
import { type createLogger } from '../../common/services/logger.service';
import { BAILEYS_QUERY_BUDGET_MS, confirmedWrite, withQueryDeadline } from './baileys-query-deadline';
@@@ -378,9 -383,10 +391,15 @@@ export class BaileysContacts
return this.host.listChats();
}
- async sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean> {
- async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {
++ async sendSeen(
++ chatId: string,
++ messageIds?: string[],
++ authors?: ReadonlyMap<string, string>,
++ stored?: StoredChatMessageLookup,
++ ): Promise<boolean> {
this.host.ensureReady();
- const keys = await this.receiptKeys(chatId, messageIds, stored);
+ const socket = this.sock();
- const keys = await this.receiptKeys(socket, chatId, messageIds, authors);
++ const keys = await this.receiptKeys(socket, chatId, messageIds, authors, stored);
if (keys.length === 0) {
return false; // nothing known to mark read
}
@@@ -406,25 -412,24 +425,30 @@@
* sender; its hardcoded `fromMe: false` is wrong for an id that belongs to an outbound message;
* and its jid is whichever dialect the caller happened to send. The stored key has all three
* right. Ids the store has never seen — history backfill is emitted but not persisted — keep the
- * synthesised key, which is what the 1:1 case ran on before.
+ * synthesised key in a 1:1 chat, which is what that case ran on before. A group receipt that names
+ * no sender cannot be attributed, so there the key takes `authors` (message id to the stored poster,
+ * which the gateway keeps for every group message), and an id with no known author is left out of
+ * the receipt rather than sent as one WhatsApp may ignore.
*/
private async receiptKeys(
+ socket: WASocket,
chatId: string,
messageIds?: string[],
+ authors?: ReadonlyMap<string, string>,
+ storedLast?: StoredChatMessageLookup,
): Promise<WAMessageKey[]> {
// null as well as undefined: the REST body rejects an explicit null, but this is the engine
// boundary and an internal caller reaching it with one used to dereference it below as a 500.
if (messageIds === undefined || messageIds === null) {
// The newest RECEIVED message, not the preview: after an API reply the preview is an own key,
// which Baileys drops from the receipt, so the call would answer true having sent nothing.
+ // After a restart memory holds none until the next one arrives; the gateway's stored copy
+ // stands in, rebuilt the way a chat write keys it.
const last = this.host.lastInboundMessage(chatId);
- if (last) return [last.key];
- return last && (await this.matchesChat(last.key, chatId, socket)) ? [last.key] : [];
++ if (last && (await this.matchesChat(last.key, chatId, socket))) return [last.key];
+ const row = await this.readStored(chatId, storedLast);
+ const received = row && !row.fromMe ? this.storedTarget(chatId, row) : null;
- return received ? [received.key] : [];
++ return received && (await this.matchesChat(received.key, chatId, socket)) ? [received.key] : [];
}
if (messageIds.length === 0) {
return []; // an explicit empty list asks for nothing to be acknowledged, not for the newest
@@@ -440,141 -445,94 +464,174 @@@
// lid to its phone user-part through the session's lid mapping, so both spellings of one chat
// still meet. Anything that still differs falls back to the synthesised key for the ADDRESSED
// chat, which is exactly what every id ran on before stored keys existed.
- const keyById = new Map(
- stored
- .filter(
- msg => msg.key?.id && msg.key.remoteJid && storedKeyInChat(msg.key, chatId, j => this.host.toNeutralJid(j)),
- )
- .map(msg => [msg.key.id as string, msg.key]),
- );
- return messageIds.map(id => keyById.get(id) ?? { remoteJid, id, fromMe: false });
+ const keyById = new Map<string, WAMessageKey>();
+ for (const msg of stored) {
+ if (msg.key?.id && msg.key.remoteJid && (await this.matchesChat(msg.key, chatId, socket))) {
+ keyById.set(msg.key.id, msg.key);
+ }
+ }
+ const inGroup = chatKind(remoteJid) === 'group';
+ return messageIds.flatMap((id): WAMessageKey[] => {
+ const key = keyById.get(id);
+ if (key) return [key];
+ if (!inGroup) return [{ remoteJid, id, fromMe: false }];
+ const author = authors?.get(id);
+ return author ? [{ remoteJid, id, fromMe: false, participant: this.host.toEngineJid(author) }] : [];
+ });
+ }
+
+ private async matchesChat(key: WAMessageKey, chatId: string, expected?: WASocket): Promise<boolean> {
+ const socket = this.sock(expected);
+ const persisted = await storedKeyInChatPersisted(key, chatId, jid => this.host.findPersistedLidPhone(jid));
+ this.sock(socket);
+ if (persisted) return true;
+ const requested = parseWaId(chatId);
+ const stored = parseWaId(key.remoteJid ?? '');
+ if (!((requested.kind === 'user' && stored.kind === 'lid') || (requested.kind === 'lid' && stored.kind === 'user')))
+ return false;
+ const phone = requested.kind === 'user' ? requested.userPart : stored.userPart;
+ const lid = requested.kind === 'lid' ? requested.userPart : stored.userPart;
+ if (typeof socket.executeUSyncQuery !== 'function' || !this.host.loadLib) return false;
+ const library = await this.host.loadLib();
+ this.sock(socket);
+ const confirmed = await queryLidPhone(socket, library, phone, lid, this.queryBudgetMs);
+ this.sock(socket);
+ if (confirmed) this.host.recordLidMapping(`${lid}@lid`, `${phone}@s.whatsapp.net`);
+ return confirmed;
+ }
+
+ async confirmedChatJid(chatId: string): Promise<string> {
+ const jid = this.host.chatJid(chatId);
+ if (!(await this.matchesChat({ remoteJid: jid }, chatId))) throw new RecipientUnreachableError(chatId);
+ return jid;
}
- async markUnread(chatId: string): Promise<boolean> {
- this.host.ensureReady();
- const socket = this.sock();
+ /**
+ * The message a chat write is keyed to, and the jid that indexes the patch, made to agree (#1891).
+ *
+ * The phone applies a clear or delete only when both name the chat the way it holds it. A message
+ * this session holds in memory carries that form itself: the patch is indexed by the jid the
+ * message arrived under, its lid on a lid-addressed chat and its phone jid otherwise. Indexing it by
+ * the listed phone jid instead named two different chats, which the server accepted and the phone
+ * ignored. A stored message carries no addressing, so it is keyed by the chat's lid whenever one is
- * known (the stored row brings the one the persisted mapping holds), else by the phone jid.
++ * known (the stored row brings the one the engine reported for its phone), else by the phone jid.
+ *
+ * An own group message carries no `participant` (the phone ignores the range with one); a received
+ * one needs its sender, which Baileys requires.
+ *
+ * The message is the newest one in memory, else (none, or one that yields no usable key) the newest
- * the gateway stored. `known` tells whether the session knows the chat at all: a message in memory or
- * stored, or a chat record or state row the listing holds.
++ * the gateway stored. Either key must belong to the chat ({@link matchesChat}), else it is not used.
++ * With neither, `rangeless()` allows a patch without a range: it is indexed by the chat's jid, and
++ * only for a chat the session knows (a message in memory or stored, or a chat record or state row
++ * the listing holds) whose jid passes the same check. Otherwise the answer is null.
+ */
+ private async chatWriteRange(
++ socket: WASocket,
+ chatId: string,
- stored?: StoredChatMessageLookup,
- ): Promise<{ range: ChatWriteRange | null; known: boolean }> {
++ stored: StoredChatMessageLookup | undefined,
++ rangeless: () => boolean = () => false,
++ ): Promise<ChatWriteRange | null> {
const last = this.host.lastMessage(chatId);
- if (!last || !(await this.matchesChat(last.key, chatId))) {
- return false; // Baileys' unread toggle needs the last message; can't synthesize it
+ const inMemory = last ? this.memoryTarget(chatId, last.key, last.timestamp) : null;
- if (inMemory) return { range: toRange(inMemory), known: true };
++ if (inMemory && (await this.matchesChat(inMemory.key, chatId, socket))) return toRange(inMemory);
+ const row = await this.readStored(chatId, stored);
+ const fromStore = row ? this.storedTarget(chatId, row) : null;
- return {
- range: fromStore ? toRange(fromStore) : null,
- known: Boolean(last || row) || this.listedChat(chatId) !== undefined,
- };
++ if (fromStore && (await this.matchesChat(fromStore.key, chatId, socket))) return toRange(fromStore);
++ if (!rangeless() || !(last || row || this.listedChat(chatId))) return null;
++ const jid = this.host.chatJid(chatId);
++ return (await this.matchesChat({ remoteJid: jid }, chatId, socket)) ? { jid, lastMessages: [] } : null;
+ }
+
+ private async readStored(
+ chatId: string,
+ stored: StoredChatMessageLookup | undefined,
+ ): Promise<StoredChatMessage | null> {
+ if (!stored) return null;
+ try {
+ return await stored();
+ } catch (err) {
+ this.host.logger.warn('Could not read the stored last message of a chat', {
+ chatId,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return null;
}
+ }
+
+ /** A message held in memory, keyed under the jid it arrived with; null when it cannot be used. */
+ private memoryTarget(chatId: string, key: WAMessageKey, timestamp: number): WriteTarget | null {
+ if (!key.id || !timestamp) return null;
+ const chatJid = this.host.chatJid(chatId);
+ const group = parseWaId(chatJid).kind === 'group';
+ const fromMe = key.fromMe === true;
+ if (group && !fromMe && !key.participant) return null;
+ const jid = group ? chatJid : this.host.toEngineJid(key.remoteJid ?? chatJid);
+ return target(jid, key.id, fromMe, group && !fromMe ? (key.participant ?? undefined) : undefined, timestamp);
+ }
+
+ /** A stored message, keyed by the chat's lid whenever one is known; null when it cannot be used. */
+ private storedTarget(chatId: string, row: StoredChatMessage): WriteTarget | null {
+ if (!row.id || !row.timestamp) return null;
+ const chatJid = this.host.chatJid(chatId);
+ const group = parseWaId(chatJid).kind === 'group';
+ if (group && !row.fromMe && !row.author) return null;
+ const jid = group ? chatJid : (row.lid ?? this.host.lidOf(chatJid) ?? this.host.toEngineJid(chatJid));
+ const participant =
+ group && !row.fromMe && row.author
+ ? (row.authorLid ?? this.host.lidOf(row.author) ?? this.host.toEngineJid(row.author))
+ : undefined;
+ return target(jid, row.id, row.fromMe, participant, row.timestamp);
+ }
+
+ /** The chat as the session lists it (a chat record or a persisted state row), if it does. */
+ private listedChat(chatId: string): ChatSummary | undefined {
+ const id = this.host.toNeutralJid(this.host.chatJid(chatId));
+ return this.host.listChats().find(chat => chat.id === id);
+ }
+
+ /**
+ * Without a known message the mark goes out with no range, which the phone applies to a chat in the
+ * list. It is reported as not done for an archived chat, which the phone leaves unmarked then, and
- * for a chat the session does not know.
++ * for a chat the session does not know or whose jid does not check out.
+ */
+ async markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ this.host.ensureReady();
- const { range, known } = await this.chatWriteRange(chatId, stored);
- if (!range && (!known || this.listedChat(chatId)?.archived === true)) return false;
++ const socket = this.sock();
++ const range = await this.chatWriteRange(socket, chatId, stored, () => this.listedChat(chatId)?.archived !== true);
++ if (!range) return false;
await this.confirmed(
- this.sock().chatModify(
- { markRead: false, lastMessages: range?.lastMessages ?? [] },
- range?.jid ?? this.host.chatJid(chatId),
- this.sock(socket).chatModify(
- { markRead: false, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
-- ),
++ this.sock(socket).chatModify({ markRead: false, lastMessages: range.lastMessages }, range.jid),
'the unread mark',
);
return true;
}
- async clearChatMessages(chatId: string): Promise<boolean> {
+ async clearChatMessages(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const { range } = await this.chatWriteRange(chatId, stored);
+ const socket = this.sock();
- const last = this.host.lastMessage(chatId);
- if (!last || !(await this.matchesChat(last.key, chatId))) {
- return false; // Baileys' clear needs the last message; can't synthesize it
++ const range = await this.chatWriteRange(socket, chatId, stored);
+ if (!range) {
+ return false; // the clear removes messages up to the one it is keyed to; never guess one
}
await this.confirmed(
- this.sock().chatModify({ clear: true, lastMessages: range.lastMessages }, range.jid),
- this.sock(socket).chatModify(
- { clear: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
- ),
++ this.sock(socket).chatModify({ clear: true, lastMessages: range.lastMessages }, range.jid),
'the chat clear',
);
return true;
}
- async archiveChat(chatId: string, archive: boolean): Promise<boolean> {
+ /**
+ * Without a known message the change goes out with no range, which WhatsApp applies as well, but
- * only for a chat the session knows. Baileys replays its own patch locally, so archiving an id the
- * account has no chat with would list that chat from then on.
++ * only for a chat the session knows and whose jid checks out. Baileys replays its own patch locally,
++ * so archiving an id the account has no chat with would list that chat from then on.
+ */
+ async archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const { range, known } = await this.chatWriteRange(chatId, stored);
- if (!range && !known) return false;
+ const socket = this.sock();
- const last = this.host.lastMessage(chatId);
- if (!last || !(await this.matchesChat(last.key, chatId))) {
- return false; // Baileys' archive toggle needs the last message; can't synthesize it
- }
++ const range = await this.chatWriteRange(socket, chatId, stored, () => true);
++ if (!range) return false;
await this.confirmed(
- this.sock().chatModify(
- { archive, lastMessages: range?.lastMessages ?? [] },
- range?.jid ?? this.host.chatJid(chatId),
- this.sock(socket).chatModify(
- { archive, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
-- ),
++ this.sock(socket).chatModify({ archive, lastMessages: range.lastMessages }, range.jid),
'the archive change',
);
return true;
@@@ -597,14 -559,18 +658,15 @@@
return true;
}
- async deleteChat(chatId: string): Promise<boolean> {
+ async deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
this.host.ensureReady();
- const { range } = await this.chatWriteRange(chatId, stored);
+ const socket = this.sock();
- const last = this.host.lastMessage(chatId);
- if (!last || !(await this.matchesChat(last.key, chatId))) {
- return false; // Baileys' delete needs the last message; can't synthesize it
++ const range = await this.chatWriteRange(socket, chatId, stored);
+ if (!range) {
+ return false; // the delete removes messages up to the one it is keyed to; never guess one
}
await this.confirmed(
- this.sock().chatModify({ delete: true, lastMessages: range.lastMessages }, range.jid),
- this.sock(socket).chatModify(
- { delete: true, lastMessages: [{ key: last.key, messageTimestamp: last.timestamp }] },
- last.jid,
- ),
++ this.sock(socket).chatModify({ delete: true, lastMessages: range.lastMessages }, range.jid),
'the chat delete',
);
return true;
diff --cc src/engine/adapters/baileys.adapter.spec.ts
index 6d7620736,570bb88a8..b2e71c3c1
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@@ -7387,273 -8067,6 +8078,344 @@@ describe('BaileysAdapter sendSeen + mar
});
});
+// #1891: the phone applies a chat write only when the patch index and the range key name the chat the
+// way it holds it, and a chat with no traffic since the session started is keyed to the gateway's
+// stored copy of its newest message. Each case below was checked against a phone.
+describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {
+ beforeEach(() => {
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ });
+
- const ready = async (): Promise<BaileysAdapter> => {
- const adapter = newAdapter();
++ // A lid counts as the chat's only once the engine reported its mapping, which the persisted table
++ // answers through findPhoneForLid; a `lid-mapping.update` alone fills the cache and no more.
++ const reported = (pairs: Record<string, string> = {}) => ({
++ getCached: jest.fn((): string | null | undefined => undefined),
++ resolveLid: jest.fn(() => null),
++ lidsForPhone: jest.fn((): string[] => []),
++ remember: jest.fn(() => Promise.resolve(true)),
++ rememberIfUnknown: jest.fn(() => Promise.resolve(true)),
++ findPhoneForLid: jest.fn((lid: string): Promise<string | null> => Promise.resolve(pairs[lid] ?? null)),
++ });
++ const ready = async (lidMappingStore?: ReturnType<typeof reported>): Promise<BaileysAdapter> => {
++ const adapter = lidMappingStore
++ ? new BaileysAdapter({
++ sessionId: 'sess-1',
++ dbSessionId: 'db-uuid-1',
++ authDir: './data/baileys',
++ messageStore: fakeStore,
++ lidMappingStore,
++ })
++ : newAdapter();
+ await adapter.initialize({});
+ fakeSock.fire('connection.update', { connection: 'open' });
+ return adapter;
+ };
+ const upsert = async (key: Record<string, unknown>, messageTimestamp = 1700000020): Promise<void> => {
+ fakeSock.fire('messages.upsert', {
+ type: 'notify',
+ messages: [{ key, message: { conversation: 'hi' }, messageTimestamp }],
+ });
+ await new Promise(r => setImmediate(r));
+ };
+ const lookup = (row: StoredChatMessage | null) => jest.fn(() => Promise.resolve(row));
+
+ it.each([
+ ['clearChatMessages', (a: BaileysAdapter) => a.clearChatMessages('[email protected]')],
+ ['deleteChat', (a: BaileysAdapter) => a.deleteChat('[email protected]')],
+ ['markUnread', (a: BaileysAdapter) => a.markUnread('[email protected]')],
+ ['archiveChat', (a: BaileysAdapter) => a.archiveChat('[email protected]', true)],
+ ])('%s indexes a phone-keyed chat by the lid its message is keyed by', async (_n, act) => {
- const adapter = await ready();
++ const adapter = await ready(reported({ '484848@lid': '628111' }));
+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await upsert({ remoteJid: '484848@lid', remoteJidAlt: '[email protected]', fromMe: false, id: 'M1' });
+
+ await expect(act(adapter)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: false, id: 'M1' }, messageTimestamp: 1700000020 }],
+ }),
+ '484848@lid',
+ );
+ });
+
+ it('keys an own group message without its participant, and a received one with its sender', async () => {
+ const adapter = await ready();
+ await upsert({ remoteJid: '[email protected]', fromMe: true, id: 'OWN', participant: '777@lid' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '[email protected]', fromMe: true, id: 'OWN' }, messageTimestamp: 1700000020 }],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'IN', participant: '555@lid' }, 1700000030);
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN', participant: '555@lid' },
+ messageTimestamp: 1700000030,
+ },
+ ],
+ },
+ );
+ });
+
+ it('falls back to the stored message when the one in memory is a received group message without its sender', async () => {
+ const adapter = await ready();
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'ANON' });
+ await expect(
+ adapter.clearChatMessages('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '[email protected]', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ );
+ });
+
+ it('keys a chat with no message in memory to the stored one, and asks the store only then', async () => {
+ const adapter = await ready();
+ const stored = lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 });
+ await expect(adapter.clearChatMessages('[email protected]', stored)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'S1' }, messageTimestamp: 1690000000 },
+ ],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'M1' });
+ stored.mockClear();
+ await adapter.deleteChat('[email protected]', stored);
+ expect(stored).not.toHaveBeenCalled();
+ });
+
+ it('keys a stored message by the lid of a lid-migrated chat, and a stored group message by its sender', async () => {
- const adapter = await ready();
++ const adapter = await ready(reported({ '484848@lid': '628111' }));
+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
+ await adapter.deleteChat('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 }));
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ delete: true,
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ '484848@lid',
+ );
+
+ await adapter.markUnread(
+ lookup({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000001 }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ markRead: false,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'G1', participant: '[email protected]' },
+ messageTimestamp: 1690000001,
+ },
+ ],
+ },
+ );
+ });
+
+ it.each([
+ ['nothing stored', () => lookup(null)],
+ ['a lookup that fails', () => jest.fn(() => Promise.reject(new Error('db down')))],
+ ])(
+ 'with %s, clear and delete decline, and archive goes out without a range only for a listed chat',
+ async (_n, make) => {
+ const adapter = await ready();
+ await expect(adapter.clearChatMessages('[email protected]', make())).resolves.toBe(false);
+ await expect(adapter.deleteChat('[email protected]', make())).resolves.toBe(false);
+ await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(false);
+ await expect(adapter.markUnread('[email protected]', make())).resolves.toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await expect(adapter.clearChatMessages('[email protected]', make())).resolves.toBe(false);
+ await expect(adapter.archiveChat('[email protected]', false, make())).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: false, lastMessages: [] }, '[email protected]');
+ },
+ );
+
+ it('archives a chat known only by a stored message without a range, and the store makes the chat known', async () => {
+ const adapter = await ready();
+ // A stored received group message without its sender gives no usable key, but the chat exists.
+ const stored = lookup({ id: 'G1', fromMe: false, timestamp: 1690000000 });
+ await expect(adapter.archiveChat('[email protected]', true, stored)).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith({ archive: true, lastMessages: [] }, '[email protected]');
+ });
+
+ it('keys a stored message by the lid the stored row brings when the session cache holds no mapping', async () => {
- const adapter = await ready();
++ const adapter = await ready(reported({ '484848@lid': '628111' }));
+ await adapter.clearChatMessages(
+ lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: '484848@lid' }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [{ key: { remoteJid: '484848@lid', fromMe: false, id: 'S1' }, messageTimestamp: 1690000000 }],
+ },
+ '484848@lid',
+ );
+
+ await adapter.clearChatMessages(
+ lookup({ id: 'G1', fromMe: false, author: '[email protected]', authorLid: '555@lid', timestamp: 1690000001 }),
+ );
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'G1', participant: '555@lid' },
+ messageTimestamp: 1690000001,
+ },
+ ],
+ },
+ );
+ });
+
+ it('keys a message held in memory under the jid it arrived with, even when a lid is known for the chat', async () => {
+ const adapter = await ready();
+ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'PN1' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'PN1' }, messageTimestamp: 1700000020 },
+ ],
+ },
+ );
+
+ await upsert({ remoteJid: '[email protected]', fromMe: false, id: 'GPN', participant: '[email protected]' });
+ await adapter.clearChatMessages('[email protected]');
+ expect(fakeSock.chatModify).toHaveBeenLastCalledWith(
+ {
+ clear: true,
+ lastMessages: [
+ {
+ key: { remoteJid: '[email protected]', fromMe: false, id: 'GPN', participant: '[email protected]' },
+ messageTimestamp: 1700000020,
+ },
+ ],
+ },
+ );
+ });
+
+ it('marks an archived chat unread only with a known message, since the phone ignores it without one', async () => {
+ const adapter = await ready();
+ fakeSock.fire('chats.upsert', [{ id: '[email protected]', archived: true }]);
+ await expect(adapter.markUnread('[email protected]', lookup(null))).resolves.toBe(false);
+ expect(fakeSock.chatModify).not.toHaveBeenCalled();
+
+ await expect(
+ adapter.markUnread('[email protected]', lookup({ id: 'S1', fromMe: true, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.chatModify).toHaveBeenCalledWith(
+ {
+ markRead: false,
+ lastMessages: [
+ { key: { remoteJid: '[email protected]', fromMe: true, id: 'S1' }, messageTimestamp: 1690000000 },
+ ],
+ },
+ );
+ });
+
+ it('acknowledges the newest stored received message when memory holds none, never an own one', async () => {
+ const adapter = await ready();
+ await expect(
- adapter.sendSeen('[email protected]', undefined, lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 })),
++ adapter.sendSeen('[email protected]', undefined, undefined, lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 })),
+ ).resolves.toBe(true);
+ expect(fakeSock.readMessages).toHaveBeenCalledWith([
+ { remoteJid: '[email protected]', fromMe: false, id: 'S1' },
+ ]);
+
+ fakeSock.readMessages.mockClear();
+ await expect(
- adapter.sendSeen('[email protected]', undefined, lookup({ id: 'S2', fromMe: true, timestamp: 1690000001 })),
++ adapter.sendSeen('[email protected]', undefined, undefined, lookup({ id: 'S2', fromMe: true, timestamp: 1690000001 })),
+ ).resolves.toBe(false);
+ expect(fakeSock.readMessages).not.toHaveBeenCalled();
+ });
++
++ it('uses neither the message in memory nor the stored one when its key does not belong to the chat', async () => {
++ const adapter = await ready(reported());
++ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
++ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
++ await upsert({ remoteJid: '484848@lid', fromMe: false, id: 'M1' });
++ const stored = lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: '484848@lid' });
++
++ await expect(adapter.clearChatMessages('[email protected]', stored)).resolves.toBe(false);
++ await expect(adapter.deleteChat('[email protected]', stored)).resolves.toBe(false);
++ expect(stored).toHaveBeenCalled();
++ await expect(adapter.sendSeen('[email protected]', undefined, undefined, stored)).resolves.toBe(false);
++ expect(fakeSock.chatModify).not.toHaveBeenCalled();
++ expect(fakeSock.readMessages).not.toHaveBeenCalled();
++ });
++
++ it('keys a write to the stored message when the one in memory does not belong to the chat', async () => {
++ const adapter = await ready(reported({ '777@lid': '628111' }));
++ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
++ fakeSock.fire('chats.upsert', [{ id: '[email protected]' }]);
++ await upsert({ remoteJid: '484848@lid', fromMe: false, id: 'M1' });
++
++ await expect(
++ adapter.clearChatMessages(
++ lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: '777@lid' }),
++ ),
++ ).resolves.toBe(true);
++ expect(fakeSock.chatModify).toHaveBeenCalledWith(
++ {
++ clear: true,
++ lastMessages: [{ key: { remoteJid: '777@lid', fromMe: false, id: 'S1' }, messageTimestamp: 1690000000 }],
++ },
++ '777@lid',
++ );
++ });
++
++ it.each([
++ ['archiveChat', (a: BaileysAdapter) => a.archiveChat('[email protected]', true, lookup(null)), { archive: true }],
++ ['markUnread', (a: BaileysAdapter) => a.markUnread('[email protected]', lookup(null)), { markRead: false }],
++ ])('%s without a range answers false when the chat jid does not belong to the chat', async (_n, act, change) => {
++ const declined = await ready(reported());
++ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
++ fakeSock.fire('chats.upsert', [{ id: '484848@lid' }]);
++ await expect(act(declined)).resolves.toBe(false);
++ expect(fakeSock.chatModify).not.toHaveBeenCalled();
++
++ const confirmed = await ready(reported({ '484848@lid': '628111' }));
++ fakeSock.fire('lid-mapping.update', { lid: '484848@lid', pn: '[email protected]' });
++ fakeSock.fire('chats.upsert', [{ id: '484848@lid' }]);
++ await expect(act(confirmed)).resolves.toBe(true);
++ expect(fakeSock.chatModify).toHaveBeenCalledWith({ ...change, lastMessages: [] }, '484848@lid');
++ });
+});
+
describe('BaileysAdapter status posting', () => {
beforeEach(() => {
fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
diff --cc src/engine/adapters/baileys.adapter.ts
index 39766d134,586196156..7cf880204
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@@ -547,16 -555,16 +557,21 @@@ export class BaileysAdapter implements
return this.messaging.subscribeToPresence(chatId);
}
- async sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean> {
- return this.contacts.sendSeen(chatId, messageIds, stored);
- async sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean> {
- return this.contacts.sendSeen(chatId, messageIds, authors);
++ async sendSeen(
++ chatId: string,
++ messageIds?: string[],
++ authors?: ReadonlyMap<string, string>,
++ stored?: StoredChatMessageLookup,
++ ): Promise<boolean> {
++ return this.contacts.sendSeen(chatId, messageIds, authors, stored);
}
- async markUnread(chatId: string): Promise<boolean> {
- return this.contacts.markUnread(chatId);
+ async markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.markUnread(chatId, stored);
}
- async deleteChat(chatId: string): Promise<boolean> {
- return this.contacts.deleteChat(chatId);
+ async deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean> {
+ return this.contacts.deleteChat(chatId, stored);
}
async muteChat(chatId: string, muteUntil: number | null): Promise<void> {
diff --cc src/engine/interfaces/whatsapp-engine.interface.ts
index 8e58716a2,2874fddc1..c1099c669
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@@ -1613,30 -1630,24 +1661,38 @@@ export interface ChatCapability
/**
* `messageIds` names exactly which messages to acknowledge. Engines that acknowledge per
- * message (Baileys) need it to mark a burst, or anything at all after a restart; engines with a
- * chat-level receipt (whatsapp-web.js) ignore it.
+ * message (Baileys) need it to mark a burst; without it they acknowledge the newest received
+ * message they know, else the newest received one `stored` finds. Engines with a chat-level
+ * receipt (whatsapp-web.js) ignore both.
+ *
+ * `authors` maps a message id to who posted it, for a group: a receipt names its sender, and an id the
+ * engine never kept (history backfill) has no key to read it from. An id with neither is not acknowledged.
*/
- sendSeen(chatId: string, messageIds?: string[], stored?: StoredChatMessageLookup): Promise<boolean>;
- sendSeen(chatId: string, messageIds?: string[], authors?: ReadonlyMap<string, string>): Promise<boolean>;
++ sendSeen(
++ chatId: string,
++ messageIds?: string[],
++ authors?: ReadonlyMap<string, string>,
++ stored?: StoredChatMessageLookup,
++ ): Promise<boolean>;
- markUnread(chatId: string): Promise<boolean>;
+ /**
+ * Resolves false when the engine cannot act. On Baileys an archived chat needs a known message to
+ * key the mark to; a chat that is not archived is marked without one if the session knows it.
+ */
+ markUnread(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
- deleteChat(chatId: string): Promise<boolean>;
+ /**
+ * Resolves false when the engine cannot act — on Baileys a chat with no known message at all, since
+ * the delete removes the messages up to the one it is keyed to and guessing that is not safe.
+ */
+ deleteChat(chatId: string, stored?: StoredChatMessageLookup): Promise<boolean>;
/**
- * Archive or unarchive a chat. Resolves false when the engine cannot act — on Baileys the
- * archive is an app-state modification keyed to the chat's last message, so a chat with no known
- * history cannot be archived at all. Same shape as deleteChat/markUnread, which share that limit.
+ * Archive or unarchive a chat. Baileys keys the change to a known message of the chat and sends it
+ * without one when none is known, which WhatsApp applies as well, but only for a chat the session
+ * knows (a chat record, a persisted state row or a stored message); otherwise it resolves false.
*/
- archiveChat(chatId: string, archive: boolean): Promise<boolean>;
+ archiveChat(chatId: string, archive: boolean, stored?: StoredChatMessageLookup): Promise<boolean>;
/**
* Pin or unpin a chat at the top of the chat list. Chat-level — distinct from `pinMessage`, which
diff --cc src/modules/session/session.service.spec.ts
index 2728659d6,fce5e33c3..81252291d
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@@ -3,8 -3,7 +3,8 @@@ import { SessionRestrictionStore } fro
import { PresenceStore } from './presence-store.service';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
- import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, QueryFailedError } from 'typeorm';
+ import { Repository, DataSource, In, IsNull, LessThanOrEqual, Not, Or, QueryFailedError } from 'typeorm';
+import type { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import {
NotFoundException,
ConflictException,
@@@ -8189,8 -8981,8 +8983,9 @@@ describe('SessionService', () =>
const result = await service.sendSeen('sess-uuid-1', '[email protected]');
// Second argument is the optional messageIds, absent here — the engine falls back to the
- // newest message it still holds, else to the stored lookup it is handed.
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined, expect.any(Function));
- // newest message it still holds.
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined, undefined);
++ // newest message it still holds, else to the stored lookup it is handed. The third, the senders
++ // of a group's named messages, is absent too.
++ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', undefined, undefined, expect.any(Function));
expect(result).toBe(true);
});
@@@ -8204,7 -8996,63 +8999,63 @@@
await service.sendSeen('sess-uuid-1', '[email protected]', ['M1', 'M2']);
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2'], expect.any(Function));
+ // A one to one receipt needs no sender, so the rows are not read.
- expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2'], undefined);
++ expect(mockEngine.sendSeen).toHaveBeenCalledWith('[email protected]', ['M1', 'M2'], undefined, expect.any(Function));
+ expect(messageRepository.find).not.toHaveBeenCalled();
+ });
+
+ describe('in a group', () => {
+ const GROUP = '[email protected]';
+ const start = async (): Promise<void> => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ mockEngine.sendSeen.mockResolvedValue(true);
+ };
+
+ it('hands the engine who posted each named message, from the rows the gateway stored', async () => {
+ await start();
+ (messageRepository.find as jest.Mock).mockResolvedValue([
+ { waMessageId: 'M1', author: '[email protected]' },
+ { waMessageId: 'M2', author: '9988@lid' },
+ { waMessageId: 'M3', author: null },
+ ]);
+
+ await service.sendSeen('sess-uuid-1', GROUP, ['M1', 'M2', 'M3']);
+
+ expect(messageRepository.find).toHaveBeenCalledWith(
+ expect.objectContaining({
+ where: expect.objectContaining({
+ sessionId: 'sess-uuid-1',
+ chatId: GROUP,
+ direction: MessageDirection.INCOMING,
+ }) as unknown,
+ }),
+ );
+ const [, , authors] = mockEngine.sendSeen.mock.calls[0] as [string, string[], ReadonlyMap<string, string>];
+ expect([...authors]).toEqual([
+ ['M1', '[email protected]'],
+ ['M2', '9988@lid'],
+ ]);
+ });
+
+ it('reads no rows when it names no message', async () => {
+ await start();
+
+ await service.sendSeen('sess-uuid-1', GROUP);
+
+ expect(messageRepository.find).not.toHaveBeenCalled();
- expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, undefined, undefined);
++ expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, undefined, undefined, expect.any(Function));
+ });
+
+ it('still reads the chat when the rows cannot be read', async () => {
+ await start();
+ (messageRepository.find as jest.Mock).mockRejectedValue(new Error('database is locked'));
+
+ await expect(service.sendSeen('sess-uuid-1', GROUP, ['M1'])).resolves.toBe(true);
+
- expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, ['M1'], undefined);
++ expect(mockEngine.sendSeen).toHaveBeenCalledWith(GROUP, ['M1'], undefined, expect.any(Function));
+ });
});
it('should throw BadRequestException when session is not started', async () => {
@@@ -8422,35 -9270,6 +9273,36 @@@
expect(deletedHooks()).toHaveLength(0);
});
+ // #1891: the engine can key a write to the stored newest message, and still decline or fail.
+ it.each([
+ ['clearChatMessages', 'declines', (id: string, chat: string) => service.clearChatMessages(id, chat)],
+ ['deleteChat', 'fails', (id: string, chat: string) => service.deleteChat(id, chat)],
+ ] as const)(
+ '%s keeps the stored rows when the engine read the stored message and then %s',
+ async (method, outcome, run) => {
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'S1',
++ chatId: '[email protected]',
+ direction: MessageDirection.INCOMING,
+ timestamp: 1690000000,
+ });
+ mockEngine[method].mockImplementationOnce(async (_chat: string, stored?: StoredChatMessageLookup) => {
+ await stored?.();
+ if (outcome === 'fails') throw new Error('timed out');
+ return false;
+ });
+
+ const call = run('sess-uuid-1', '[email protected]');
+ if (outcome === 'fails') await expect(call).rejects.toThrow('timed out');
+ else await expect(call).resolves.toBe(false);
+
+ expect(messageRepository.findOne).toHaveBeenCalled();
+ expect(messageRepository.find).not.toHaveBeenCalled();
+ expect(messageRepository.delete).not.toHaveBeenCalled();
+ expect(deletedHooks()).toHaveLength(0);
+ },
+ );
+
it('a failed removal after the engine succeeded is logged and the call still succeeds', async () => {
(messageRepository.find as jest.Mock).mockRejectedValueOnce(new Error('db down'));
const logError = jest.spyOn((service as unknown as { logger: { error: jest.Mock } }).logger, 'error');
@@@ -8465,162 -9284,6 +9317,202 @@@
});
});
+ // ── the stored newest message a chat write falls back to (#1891) ──
+
+ describe('stored last message lookup', () => {
+ beforeEach(async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ });
+
+ /** The lookup the service handed the engine for `run`, called once. */
+ const lookupOf = async (
+ method: 'markUnread' | 'clearChatMessages' | 'deleteChat' | 'sendSeen',
+ run: () => Promise<unknown>,
+ ): Promise<unknown> => {
+ mockEngine[method].mockResolvedValueOnce(false);
+ await run();
+ const calls = mockEngine[method].mock.calls as unknown[][];
+ const lookup = calls[calls.length - 1].find(arg => typeof arg === 'function') as StoredChatMessageLookup;
+ return lookup();
+ };
+ const whereOf = (): unknown =>
+ ((messageRepository.findOne as jest.Mock).mock.calls as [{ where: unknown }][])[0][0].where;
+
+ it("reads a 1:1 chat's newest stored message under every id form of it", async () => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockResolvedValue(['999']);
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'S1',
++ chatId: '[email protected]',
+ direction: MessageDirection.OUTGOING,
+ author: null,
+ timestamp: 1690000000,
+ });
+
+ // The chat's lid comes from the table-backed lookup, which the engine's cache can lack.
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
+ id: 'S1',
+ fromMe: true,
+ timestamp: 1690000000,
+ lid: '999@lid',
+ });
+ const base = {
+ sessionId: 'sess-uuid-1',
+ chatId: In(['[email protected]', '[email protected]', '999@lid']),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ expect(whereOf()).toEqual([base]);
+ expect(messageRepository.findOne).toHaveBeenCalledWith(
+ expect.objectContaining({ order: { timestamp: 'DESC', createdAt: 'DESC' } }),
+ );
+ });
+
+ it('in a group, takes an own message or a received one with its sender, and its lid from the table', async () => {
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
+ Promise.resolve(phone === '628222' ? ['555'] : []),
+ );
+ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce({
+ waMessageId: 'G1',
++ chatId: '[email protected]',
+ direction: MessageDirection.INCOMING,
+ author: '[email protected]',
+ timestamp: 1690000001,
+ });
+
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toEqual({
+ id: 'G1',
+ fromMe: false,
+ author: '[email protected]',
+ authorLid: '555@lid',
+ timestamp: 1690000001,
+ });
+ expect(lidMappingStore.findLidsForPhone).toHaveBeenCalledWith('628222');
+ const base = {
+ sessionId: 'sess-uuid-1',
+ chatId: In(['[email protected]']),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ expect(whereOf()).toEqual([
+ { ...base, direction: MessageDirection.INCOMING, author: Not(IsNull()) },
+ { ...base, direction: MessageDirection.OUTGOING },
+ ]);
+ });
+
++ it('takes the lid the row is filed under when the table maps the phone to two, and none from a phone row', async () => {
++ (lidMappingStore.findLidsForPhone as jest.Mock).mockResolvedValue(['998', '999']);
++ const row = (chatId: string) => ({
++ waMessageId: 'S1',
++ chatId,
++ direction: MessageDirection.INCOMING,
++ author: null,
++ timestamp: 1690000000,
++ });
++ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce(row('999@lid'));
++ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
++ id: 'S1',
++ fromMe: false,
++ timestamp: 1690000000,
++ lid: '999@lid',
++ });
++
++ // Filed under the phone, the row names neither lid, so the engine gets none to guess from.
++ (messageRepository.findOne as jest.Mock).mockResolvedValueOnce(row('[email protected]'));
++ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
++ id: 'S1',
++ fromMe: false,
++ timestamp: 1690000000,
++ });
++ });
++
+ it('for a read receipt, takes only a received message', async () => {
+ await expect(lookupOf('sendSeen', () => service.sendSeen('sess-uuid-1', '[email protected]'))).resolves.toBeNull();
+ expect(whereOf()).toEqual([expect.objectContaining({ direction: MessageDirection.INCOMING })]);
+ });
+
+ // The query itself, on a real database: the id-form `In`, the group sender rule and the ordering.
+ describe('against a real database', () => {
+ let db: DataSource;
+ let messages: Repository<Message>;
+
+ beforeAll(async () => {
+ db = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [Message], synchronize: true });
+ await db.initialize();
+ messages = db.getRepository(Message);
+ const row = (
+ chatId: string,
+ waMessageId: string | null,
+ direction: MessageDirection,
+ timestamp: number,
+ author?: string,
+ ) => ({ sessionId: 'sess-uuid-1', chatId, waMessageId, direction, timestamp, author, from: 'a', to: 'b' });
+ await messages.insert([
+ row('[email protected]', 'OUT', MessageDirection.OUTGOING, 100),
+ row('999@lid', 'IN', MessageDirection.INCOMING, 200),
+ row('[email protected]', null, MessageDirection.INCOMING, 300),
+ row('[email protected]', 'OTHER', MessageDirection.INCOMING, 400),
+ row('[email protected]', 'G-ANON', MessageDirection.INCOMING, 500),
+ row('[email protected]', 'G-OWN', MessageDirection.OUTGOING, 300),
+ row('[email protected]', 'G-IN', MessageDirection.INCOMING, 250, '[email protected]'),
++ row('[email protected]', 'TWO-OLD', MessageDirection.OUTGOING, 100),
++ row('462@lid', 'TWO-NEW', MessageDirection.INCOMING, 200),
++ row('461@lid', 'TWO-OLDER', MessageDirection.INCOMING, 50),
+ ] as QueryDeepPartialEntity<Message>[]);
+ });
+
+ afterAll(async () => {
+ await db.destroy();
+ });
+
+ beforeEach(() => {
+ Object.assign(service as unknown as Record<string, unknown>, { messageRepository: messages });
+ (lidMappingStore.findLidsForPhone as jest.Mock).mockImplementation((phone: string) =>
- Promise.resolve(phone === '123' ? ['999'] : []),
++ Promise.resolve(phone === '123' ? ['999'] : phone === '456' ? ['461', '462'] : []),
+ );
+ });
+
+ it("finds a 1:1 chat's newest message under its lid twin and skips rows without an id", async () => {
+ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
+ id: 'IN',
+ fromMe: false,
+ timestamp: 200,
+ lid: '999@lid',
+ });
+ });
+
++ it('takes the lid the newest row is filed under when the phone maps to two', async () => {
++ await expect(lookupOf('markUnread', () => service.markUnread('sess-uuid-1', '[email protected]'))).resolves.toEqual({
++ id: 'TWO-NEW',
++ fromMe: false,
++ timestamp: 200,
++ lid: '462@lid',
++ });
++ });
++
+ it('in a group, skips a received message without its sender, and a receipt takes only a received one', async () => {
+ await expect(
+ lookupOf('clearChatMessages', () => service.clearChatMessages('sess-uuid-1', '[email protected]')),
+ ).resolves.toMatchObject({ id: 'G-OWN', fromMe: true, timestamp: 300 });
+ await expect(lookupOf('sendSeen', () => service.sendSeen('sess-uuid-1', '[email protected]'))).resolves.toMatchObject({
+ id: 'G-IN',
+ fromMe: false,
+ author: '[email protected]',
+ timestamp: 250,
+ });
+ });
+ });
+
+ it('is not read until the engine asks for it', async () => {
+ mockEngine.deleteChat.mockResolvedValueOnce(false);
+ await service.deleteChat('sess-uuid-1', '[email protected]');
+ expect(messageRepository.findOne).not.toHaveBeenCalled();
+ });
+ });
+
// ── sendChatState (typing/recording/paused) ───────────────────────
describe('sendChatState', () => {
diff --cc src/modules/session/session.service.ts
index b3cbe757e,3bf3ed438..5cba2eebf
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@@ -49,22 -50,20 +50,25 @@@ import
} from './session-engine-lifecycle.service';
import { SessionOwnershipService } from './session-ownership.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
+ import { ListingMemo } from '../../common/utils/listing-memo';
import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';
+ import { awaitNoOpenTransaction } from '../../common/utils/shared-connection';
import { resolveFeatureFlags } from '../../config/feature-flags';
-import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces/whatsapp-engine.interface';
+import {
+ IWhatsAppEngine,
+ ChatSummary,
+ ChatState,
+ type StoredChatMessageLookup,
+} from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { ShutdownService } from '../../common/services/shutdown.service';
import { HookManager } from '../../core/hooks';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { resolveJidCandidates } from '../../engine/identity/jid-candidates';
- import { parseWaId } from '../../engine/identity/wa-id';
-import { chatKind } from '../../engine/identity/wa-id';
++import { chatKind, parseWaId } from '../../engine/identity/wa-id';
import { Message, MessageDirection } from '../message/entities/message.entity';
import { ServerShuttingDownException, SessionStoppedException } from './session-engine-controls';
+ import { phoneKey } from './message-mutation-guard';
// Type-only: the module binds this class to PLUGIN_SESSION_PORT with a `useExisting` alias, which
// TypeScript does not check, so `implements` is what keeps the two in step.
import type { PluginSessionPort } from '../../core/plugins/plugin-host-ports';
@@@ -1133,76 -1467,42 +1472,109 @@@ export class SessionService implements
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.sendSeen(chatId, messageIds, this.storedLastMessage(id, chatId, { receivedOnly: true }));
+ const authors = await this.groupAuthors(id, chatId, messageIds);
- return engine.sendSeen(chatId, messageIds, authors).finally(() => this.chatListings.drop(id));
++ return engine
++ .sendSeen(chatId, messageIds, authors, this.storedLastMessage(id, chatId, { receivedOnly: true }))
++ .finally(() => this.chatListings.drop(id));
+ }
+
+ /**
+ * Who posted each named message of a group, from the rows the gateway stored. A group read receipt
+ * names the sender, and for a message the engine never kept (history backfill) these rows are the only
+ * place it is recorded. Best-effort: a read that cannot learn them still acknowledges what the engine
+ * can name on its own.
+ */
+ private async groupAuthors(
+ sessionId: string,
+ chatId: string,
+ messageIds?: string[],
+ ): Promise<ReadonlyMap<string, string> | undefined> {
+ if (!messageIds?.length || chatKind(chatId) !== 'group') return undefined;
+ try {
+ const rows = await this.messageRepository.find({
+ where: { sessionId, chatId, waMessageId: In(messageIds), direction: MessageDirection.INCOMING },
+ select: { waMessageId: true, author: true },
+ });
+ return new Map(rows.flatMap(row => (row.waMessageId && row.author ? [[row.waMessageId, row.author]] : [])));
+ } catch (error) {
+ this.logger.warn('Could not read who posted the messages a read names; sending the read without them', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return undefined;
+ }
}
async markUnread(id: string, chatId: string): Promise<boolean> {
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.markUnread(chatId, this.storedLastMessage(id, chatId));
- return engine.markUnread(chatId).finally(() => this.chatListings.drop(id));
++ return engine.markUnread(chatId, this.storedLastMessage(id, chatId)).finally(() => this.chatListings.drop(id));
+ }
+
+ /**
+ * The newest message the gateway stored for a chat, for an engine that keys chat writes to one and
+ * holds none for the chat itself (Baileys after a restart, #1891). The lookup runs only when the
+ * engine calls it, and covers every id form of the chat (the GET messages filter's rules).
+ *
+ * A received group message counts only with its sender, which the key needs; `receivedOnly` asks
+ * for the newest received message, the one a read receipt acknowledges.
+ */
+ private storedLastMessage(
+ sessionId: string,
+ chatId: string,
+ { receivedOnly = false }: { receivedOnly?: boolean } = {},
+ ): StoredChatMessageLookup {
+ return async () => {
+ const expanded = await resolveJidCandidates(chatId, {
+ resolveLid: lid => this.lidMappingStore.findPhoneForLid(lid),
+ lidsForPhone: phone => this.lidMappingStore.findLidsForPhone(phone),
+ });
+ const base = {
+ sessionId,
+ chatId: In([...new Set([chatId, ...expanded])]),
+ waMessageId: Not(IsNull()),
+ timestamp: Not(IsNull()),
+ };
+ const received = { ...base, direction: MessageDirection.INCOMING };
+ const where: FindOptionsWhere<Message>[] =
+ parseWaId(chatId).kind === 'group'
+ ? [
+ { ...received, author: Not(IsNull()) },
+ ...(receivedOnly ? [] : [{ ...base, direction: MessageDirection.OUTGOING }]),
+ ]
+ : [receivedOnly ? received : base];
+ const row = await this.messageRepository.findOne({
+ where,
+ order: { timestamp: 'DESC', createdAt: 'DESC' },
- select: { id: true, waMessageId: true, direction: true, author: true, timestamp: true },
++ select: { id: true, waMessageId: true, chatId: true, direction: true, author: true, timestamp: true },
+ });
+ if (!row) return null;
- // The lids the engine keys a lid-migrated chat by, read from the persisted mapping: the engine's
- // own cache can lack them (#1901).
- const lid = expanded.find(candidate => parseWaId(candidate).kind === 'lid');
++ // The lid the engine keys a lid-migrated chat by, read from the persisted mapping: the engine's
++ // own cache can lack it (#1901). A phone can map to more than one lid, so the lid the row is
++ // filed under wins; a row filed under the phone takes the table's lid only when it lists one.
++ const filed = parseWaId(row.chatId);
++ const lids = expanded.filter(candidate => parseWaId(candidate).kind === 'lid');
++ const lid = filed.kind === 'lid' ? `${filed.userPart}@lid` : lids.length === 1 ? lids[0] : undefined;
+ const authorLid = row.author ? await this.persistedLidOf(row.author) : undefined;
+ return {
+ id: row.waMessageId,
+ fromMe: row.direction === MessageDirection.OUTGOING,
+ ...(row.author ? { author: row.author } : {}),
+ timestamp: row.timestamp,
+ ...(lid ? { lid } : {}),
+ ...(authorLid ? { authorLid } : {}),
+ };
+ };
+ }
+
+ /** The `<lid>@lid` the persisted mapping holds for a person, or undefined. */
+ private async persistedLidOf(jid: string): Promise<string | undefined> {
+ const parsed = parseWaId(jid);
+ if (parsed.kind === 'lid') return `${parsed.userPart}@lid`;
+ if (parsed.kind !== 'user') return undefined;
+ const [lid] = await this.lidMappingStore.findLidsForPhone(parsed.userPart);
+ return lid ? `${lid}@lid` : undefined;
}
/**
@@@ -1215,7 -1515,7 +1587,9 @@@
const engine = this.requireEngine(id);
const cutoff = new Date();
- const ok = await engine.clearChatMessages(chatId, this.storedLastMessage(id, chatId));
- const ok = await engine.clearChatMessages(chatId).finally(() => this.chatListings.drop(id));
++ const ok = await engine
++ .clearChatMessages(chatId, this.storedLastMessage(id, chatId))
++ .finally(() => this.chatListings.drop(id));
if (ok) await this.purgeStoredChat(id, chatId, cutoff);
return ok;
}
@@@ -1229,7 -1529,7 +1603,9 @@@
await this.findOne(id); // Verify session exists
const engine = this.requireEngine(id);
- return engine.archiveChat(chatId, archive, this.storedLastMessage(id, chatId));
- return engine.archiveChat(chatId, archive).finally(() => this.chatListings.drop(id));
++ return engine
++ .archiveChat(chatId, archive, this.storedLastMessage(id, chatId))
++ .finally(() => this.chatListings.drop(id));
}
/**
@@@ -1261,7 -1561,7 +1637,9 @@@
const engine = this.requireEngine(id);
const cutoff = new Date();
- const ok = await engine.deleteChat(chatId, this.storedLastMessage(id, chatId));
- const ok = await engine.deleteChat(chatId).finally(() => this.chatListings.drop(id));
++ const ok = await engine
++ .deleteChat(chatId, this.storedLastMessage(id, chatId))
++ .finally(() => this.chatListings.drop(id));
if (ok) await this.purgeStoredChat(id, chatId, cutoff);
return ok;
}