Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): key no chat write to a message from before its deletion
Yudhi Armyndharisbeb84ec5d304
diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex d219176dd..ea62f0d37 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -728,7 +728,7 @@ The data connection also owns:- **`integration_delivery_failures`**: DLQ-of-record for failed inbound (ingress) deliveries, the rows the instance redrive replays; only the ingress path writes it, and only as `inbound`. A data import restores each row's `direction` as stored, and redrive replays only `inbound` rows (`src/modules/integration/entities/integration-delivery-failure.entity.ts`).- **`baileys_stored_messages`** — Baileys engine message store — the serialized WAMessage proto (`src/engine/adapters/baileys-stored-message.entity.ts`); present only when the Baileys engine is used. (Credentials live on the filesystem, not here.)- **`lid_mappings`** — LID↔phone-number identity mappings (`src/engine/identity/lid-mapping.entity.ts`).-- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. `chatId` is the person's phone JID (`<phone>@s.whatsapp.net`) whenever their lid resolves, so a state WhatsApp syncs under the lid and one set through the phone number land on the same row; it stays `<lid>@lid` while the lid is unresolved, and a row found under the lid later is folded onto the phone JID on the chat's next change (reads and the fold take each field from the newest row that observed it: `observed` lists the fields a row has seen, and null, on a row not written since the column was added, means the fields it holds a set value for; the next write that can read the row records the list). WhatsApp does not re-deliver that state, so it is kept in backups. A chat deleted on the phone or through the API loses its row, so a later message starts it clean.+- **`chat_states`** (engine): per-session mute, archive and pin state of each Baileys chat (`src/engine/adapters/baileys-chat-state.entity.ts`), keyed `(sessionId, chatId)`. `chatId` is the person's phone JID (`<phone>@s.whatsapp.net`) whenever their lid resolves, so a state WhatsApp syncs under the lid and one set through the phone number land on the same row; it stays `<lid>@lid` while the lid is unresolved, and a row found under the lid later is folded onto the phone JID on the chat's next change (reads and the fold take each field from the newest row that observed it: `observed` lists the fields a row has seen, and null, on a row not written since the column was added, means the fields it holds a set value for; the next write that can read the row records the list). WhatsApp does not re-deliver that state, so it is kept in backups. A chat deleted on the phone or through the API keeps its row with the state reset and `deletedAt` set (epoch ms): the gateway keeps the chat's stored messages, and one from before the deletion must neither key a chat write nor list the chat again. A later message re-creates the chat and the row goes, so it starts clean.`lid_mappings.isReported` distinguishes engine mapping reports from cache-only display data. Phone/LID alias authorization, candidate expansion and list filters use only reported mappings. A conflicting cached phone revokes alias trust without replacing the stored phone, and a later actual report restores it. The migration conservatively marks older mixed-origin rows as display data; backups carry the flag, and older backups restore with alias access disabled until a new report arrives.@@ -940,7 +940,8 @@ src/database/migrations/ # data connection (pluggable)├── 1791200000000-AddWebhookOutboxSessionIndex.ts # (sessionId) index for the per-session outbox delete├── 1791300000000-BackfillLegacyMessageTypes.ts # converts raw wwebjs message types to the neutral vocabulary, once├── 1791400000000-AddLidMappingReportSource.ts # distinguishes mapping reports from cached display data-└── 1791600000000-RepairSqliteMessageFts.ts # rebuilds the SQLite full-text index when it no longer matches messages+├── 1791600000000-RepairSqliteMessageFts.ts # rebuilds the SQLite full-text index when it no longer matches messages+└── 1791700000000-AddChatStateDeletedAt.ts # chat_states.deletedAt (when WhatsApp deleted the chat)```> [!NOTE]diff --git a/src/database/migrations/1791700000000-AddChatStateDeletedAt.ts b/src/database/migrations/1791700000000-AddChatStateDeletedAt.tsnew file mode 100644index 000000000..f5eb27efb--- /dev/null+++ b/src/database/migrations/1791700000000-AddChatStateDeletedAt.ts@@ -0,0 +1,27 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `chat_states.deletedAt`, the epoch ms WhatsApp deleted the chat. The gateway keeps a deleted+ * chat's stored messages, and a chat write keyed to one of them came back from Baileys as an update of+ * the chat, which listed it again. Existing rows keep null. Hand-authored because `synchronize` is off on+ * the `data` connection for Postgres; the `hasColumn` guard keeps it idempotent where synchronize already+ * added the column.+ */+export class AddChatStateDeletedAt1791700000000 implements MigrationInterface {+ name = 'AddChatStateDeletedAt1791700000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasTable('chat_states')) || (await queryRunner.hasColumn('chat_states', 'deletedAt'))) {+ return;+ }+ await queryRunner.query(`ALTER TABLE "chat_states" ADD COLUMN "deletedAt" bigint`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasColumn('chat_states', 'deletedAt'))) return;+ // Without the column such a row reads as a chat with a state, which an older reader lists; it kept no+ // row for a deleted chat.+ await queryRunner.query(`DELETE FROM "chat_states" WHERE "deletedAt" IS NOT NULL`);+ await queryRunner.query(`ALTER TABLE "chat_states" DROP COLUMN "deletedAt"`);+ }+}diff --git a/src/database/migrations/__tests__/1791700000000-AddChatStateDeletedAt.spec.ts b/src/database/migrations/__tests__/1791700000000-AddChatStateDeletedAt.spec.tsnew file mode 100644index 000000000..13fd188ab--- /dev/null+++ b/src/database/migrations/__tests__/1791700000000-AddChatStateDeletedAt.spec.ts@@ -0,0 +1,44 @@+import { DataSource } from 'typeorm';+import { AddChatStates1786400000000 } from '../1786400000000-AddChatStates';+import { AddChatStateDeletedAt1791700000000 } from '../1791700000000-AddChatStateDeletedAt';++describe('AddChatStateDeletedAt migration', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('adds the column, keeps existing rows as null, and drops it with the rows it marked', async () => {+ const runner = ds.createQueryRunner();+ await new AddChatStates1786400000000().up(runner);+ await runner.query(`INSERT INTO "chat_states" ("sessionId", "chatId", "pinned") VALUES ('s1', '[email protected]', 1)`);+ const migration = new AddChatStateDeletedAt1791700000000();++ await migration.up(runner);+ await migration.up(runner); // idempotent+ expect(await runner.query(`SELECT "deletedAt", "pinned" FROM "chat_states"`)).toEqual([+ { deletedAt: null, pinned: 1 },+ ]);++ await runner.query(+ `INSERT INTO "chat_states" ("sessionId", "chatId", "deletedAt") VALUES ('s1', '[email protected]', 1790000000000)`,+ );+ await migration.down(runner);+ expect(await runner.hasColumn('chat_states', 'deletedAt')).toBe(false);+ expect(await runner.query(`SELECT "chatId" FROM "chat_states"`)).toEqual([{ chatId: '[email protected]' }]);+ await runner.release();+ });++ it('is a no-op without the table', async () => {+ const runner = ds.createQueryRunner();+ await expect(new AddChatStateDeletedAt1791700000000().up(runner)).resolves.toBeUndefined();+ await expect(new AddChatStateDeletedAt1791700000000().down(runner)).resolves.toBeUndefined();+ await runner.release();+ });+});diff --git a/src/engine/adapters/baileys-chat-state-store.overlap.spec.ts b/src/engine/adapters/baileys-chat-state-store.overlap.spec.tsindex 0fa32380e..4d320a411 100644--- a/src/engine/adapters/baileys-chat-state-store.overlap.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.overlap.spec.ts@@ -438,7 +438,8 @@ describe('ChatStateStoreService under a seeded interleaving of loads and writes'else process.env[ENV] = orig;});- const FIELDS: ChatStateField[] = ['muteEndTime', 'archived', 'pinned'];+ // The ops below never mark a deletion, so the model leaves that field out.+ const FIELDS: Exclude<ChatStateField, 'deletedAt'>[] = ['muteEndTime', 'archived', 'pinned'];const SESSIONS = ['s1', 's2'];type Patch = { muteEndTime?: number | null; archived?: boolean; pinned?: boolean };diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex cf82f98e6..a9e16ec6c 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -748,6 +748,39 @@ describe('ChatStateStoreService', () => {expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);});+ it('resets the twin rows under a deletion mark, which outlives a restart', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: LID, pinned: true, observed: 'pinned', updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ await svc.fold('s', PHONE, [LID], { muteEndTime: null, archived: false, pinned: false, deletedAt: 5000 });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ const restarted = svcWith(repo);+ await restarted.reload();+ expect(restarted.get('s', PHONE)).toMatchObject({ pinned: false, deletedAt: 5000 });+ });++ it('keeps the mark of an older twin row that a newer one never saw, on a read and a fold', async () => {+ const marked = 'muteEndTime,archived,pinned,deletedAt';+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, pinned: true, observed: 'pinned', updatedAt: new Date(2000) },+ { sessionId: 's', chatId: LID, deletedAt: 5000, observed: marked, updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ await svc.reload();+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({+ pinned: true,+ deletedAt: 5000,+ });+ await svc.fold('s', PHONE, [LID], { archived: true });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ pinned: true, archived: true, deletedAt: 5000 });+ });++ it('reads a row written before the mark was kept as having seen no deletion', () => {+ expect(mergeTwinStates([{ muteEndTime: null, archived: true, pinned: false }])?.observed).toEqual(['archived']);+ });+it('neither a listing nor a later change brings back the older mute of a cached lid row', async () => {const repo = coldNewerPhone();const svc = svcWith(repo);diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex b9e45baef..21591d29e 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -6,11 +6,12 @@ import { createLogger } from '../../common/services/logger.service';import { resolveNonNegativeIntEnv } from '../../config/configuration';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';-export type ChatStateField = 'muteEndTime' | 'archived' | 'pinned';-const FIELDS: ChatStateField[] = ['muteEndTime', 'archived', 'pinned'];+export type ChatStateField = 'muteEndTime' | 'archived' | 'pinned' | 'deletedAt';+const FIELDS: ChatStateField[] = ['muteEndTime', 'archived', 'pinned', 'deletedAt'];/*** Durable chat app-state Baileys cannot re-deliver on reconnect. `muteEndTime` is canonical epoch ms.+ * `deletedAt` is the epoch ms WhatsApp deleted the chat, null (or absent) when it was not.* `updatedAt` (epoch ms) is when the row last changed, when known; it is read, never written by a patch.* `observed` lists the fields the row has seen a value for, the others holding their default; undefined* on a row written before the list was kept, which counts its set fields as seen. Like `updatedAt`, a@@ -20,6 +21,7 @@ export type ChatStateValue = {muteEndTime: number | null;archived: boolean;pinned: boolean;+ deletedAt?: number | null;updatedAt?: number;observed?: ChatStateField[];};@@ -58,19 +60,23 @@ export interface ChatStateStore {reload(): Promise<void>;/** Forget every chat state of one session (an unlink: the next account to link it starts clean). */clearSession(sessionId: string): Promise<void>;- /** Forget the named chats of one session (a deleted chat: one a later message re-creates starts clean). */+ /** Forget the named chats of one session (a deleted chat a later message re-creates: it starts clean). */forget(sessionId: string, chatIds: string[]): Promise<void>;/** Re-read one session's rows from the table (a start: another node may have written them since). */refreshSession(sessionId: string): Promise<void>;}-const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false };+const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false, deletedAt: null };++/** The field's value, an absent `deletedAt` (a row or patch from before it was kept) read as its default. */+const valueOf = (v: Partial<ChatStateValue>, field: ChatStateField) => v[field] ?? DEFAULT_STATE[field];function fromRow(row: ChatState): ChatStateValue {return {muteEndTime: row.muteEndTime,archived: row.archived,pinned: row.pinned,+ deletedAt: row.deletedAt ?? null,updatedAt: row.updatedAt?.getTime(),observed: row.observed == null ? undefined : (row.observed.split(',').filter(Boolean) as ChatStateField[]),};@@ -86,7 +92,7 @@ function fromRow(row: ChatState): ChatStateValue {* set value on a twin row.*/const saw = (v: ChatStateValue, field: ChatStateField): boolean =>- v.observed ? v.observed.includes(field) : v[field] !== DEFAULT_STATE[field];+ v.observed ? v.observed.includes(field) : valueOf(v, field) !== DEFAULT_STATE[field];/*** One chat's rows under several spellings, merged field by field: each field comes from the newest row@@ -447,7 +453,8 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {if (!existing) {// A patch that may not create a row and only restates defaults has nothing to write for a chat// with no row; the table and the absent set answer that without a query where they can.- const restatesDefaults = !create && FIELDS.every(f => !Object.hasOwn(patch, f) || patch[f] === DEFAULT_STATE[f]);+ const restatesDefaults =+ !create && FIELDS.every(f => !Object.hasOwn(patch, f) || valueOf(patch, f) === DEFAULT_STATE[f]);if (restatesDefaults && (this.completeSessions.has(sessionId) || this.absent.has(k))) return true;let row: ChatState | null;try {@@ -474,10 +481,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {const observed = FIELDS.filter(f => saw(existingRow, f) || Object.hasOwn(patch, f));const next: ChatStateValue = { ...existing, ...patch, updatedAt: existing.updatedAt, observed };if (- existing.muteEndTime === next.muteEndTime &&- existing.archived === next.archived &&- existing.pinned === next.pinned &&- FIELDS.every(f => saw(existingRow, f) === observed.includes(f))+ FIELDS.every(f => valueOf(existingRow, f) === valueOf(next, f) && saw(existingRow, f) === observed.includes(f))) {this.index(k, next); // warm the cache even on a no-op so the next read is a hitreturn true; // nothing changed against the current state; skip the write that would just churn updatedAtdiff --git a/src/engine/adapters/baileys-chat-state.entity.ts b/src/engine/adapters/baileys-chat-state.entity.tsindex 267b1498f..1e2ac1598 100644--- a/src/engine/adapters/baileys-chat-state.entity.ts+++ b/src/engine/adapters/baileys-chat-state.entity.ts@@ -52,6 +52,19 @@ export class ChatState {@Column({ type: 'varchar', nullable: true })observed!: string | null;+ /**+ * Epoch MILLISECONDS WhatsApp deleted the chat (on the phone, or through the API), else null. WhatsApp+ * keeps nothing of a deleted chat while the gateway keeps its stored messages, so the row stays with+ * its state reset and this set: a message from before it neither keys a chat write nor brings the chat+ * back. A later message re-creates the chat on WhatsApp, and the row goes.+ */+ @Column({+ type: 'bigint',+ nullable: true,+ transformer: { to: (v: number | null) => v, from: (v: string | null) => (v == null ? null : Number(v)) },+ })+ deletedAt!: number | null;+@UpdateDateColumn()updatedAt!: Date;}diff --git a/src/engine/adapters/baileys-contacts-identity.spec.ts b/src/engine/adapters/baileys-contacts-identity.spec.tsindex 9b61bfb5e..a364281f7 100644--- a/src/engine/adapters/baileys-contacts-identity.spec.ts+++ b/src/engine/adapters/baileys-contacts-identity.spec.ts@@ -145,6 +145,7 @@ describe.each(['persisted', 'fresh', 'library'] as const)('Chat identity preparetoEngineJid: (jid: string) => jid,lastMessage: () => ({ key, jid: '111@lid', timestamp: 1 }),lastInboundMessage: () => ({ key, timestamp: 1 }),+ chatDeletedAt: () => null,findContact: () => ({ id: '111@lid', number: '628111', isWAContact: true }),} as unknown as BaileysContactsHost;const contacts = new BaileysContacts(host);diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex 1663b0b96..79a03ef5c 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -53,6 +53,11 @@ export interface BaileysContactsHost {lidOf(jid: string): string | null;/** Every spelling of one chat the session can connect: the id, its engine form, and its lid or phone twin. */chatTwins(jid: string): string[];+ /**+ * When WhatsApp deleted the chat (epoch ms), under any of its spellings, or null when it did not or a+ * message has re-created it since.+ */+ chatDeletedAt(chatId: string): number | null;/*** Stored copies of the named messages, in whatever order the store returns them. Ids the store* has never seen are absent, so neither the length nor the order tracks the input. `undefined`@@ -446,10 +451,10 @@ export class BaileysContacts {// 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);+ const last = this.sinceDeletion(chatId, this.host.lastInboundMessage(chatId));if (last && (await this.matchesChat(last.key, chatId, socket))) return [last.key];if (!isEngineChatId(chatId)) return [];- const row = await this.readStored(chatId, storedLast);+ const row = this.sinceDeletion(chatId, await this.readStored(chatId, storedLast));const received = row && !row.fromMe ? this.storedTarget(chatId, row) : null;return received && (await this.matchesChat(received.key, chatId, socket)) ? [received.key] : [];}@@ -531,6 +536,9 @@ export class BaileysContacts {* Only the message in memory serves an id spelled any other way than the engine keys chats* ({@link isEngineChatId}): the stored lookup normalizes the id and finds the chat's rows, but the* patch would still be indexed by the misspelled id, which names no chat on the phone.+ *+ * A message, in memory or stored, sent at or before WhatsApp deleted the chat neither keys the write+ * nor shows the session knows the chat (see {@link sinceDeletion}).*/private async chatWriteRange(socket: WASocket,@@ -538,11 +546,11 @@ export class BaileysContacts {stored: StoredChatMessageLookup | undefined,rangeless: () => boolean = () => false,): Promise<ChatWriteRange | null> {- const last = this.host.lastMessage(chatId);+ const last = this.sinceDeletion(chatId, this.host.lastMessage(chatId));const inMemory = last ? this.memoryTarget(chatId, last.key, last.timestamp) : null;if (inMemory && (await this.matchesChat(inMemory.key, chatId, socket))) return toRange(inMemory);if (!isEngineChatId(chatId)) return null;- const row = await this.readStored(chatId, stored);+ const row = this.sinceDeletion(chatId, await this.readStored(chatId, stored));const fromStore = row ? this.storedTarget(chatId, row) : null;if (fromStore && (await this.matchesChat(fromStore.key, chatId, socket))) return toRange(fromStore);if (!rangeless() || !(last || row || this.listedChats(chatId).length)) return null;@@ -566,6 +574,17 @@ export class BaileysContacts {}}+ /**+ * The message, unless it was sent at or before WhatsApp deleted the chat. WhatsApp keeps nothing of a+ * deleted chat while the gateway keeps its stored messages: a write keyed to one names a message the+ * phone no longer holds, and Baileys applies its own patch locally all the same, so the deleted chat+ * would be listed again. Such a message does not show the chat exists either.+ */+ private sinceDeletion<T extends { timestamp: number }>(chatId: string, message: T | null): T | null {+ const deletedAt = this.host.chatDeletedAt(chatId);+ return message && (deletedAt === null || message.timestamp * 1000 > deletedAt) ? message : 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;diff --git a/src/engine/adapters/baileys-remaining-writes.spec.ts b/src/engine/adapters/baileys-remaining-writes.spec.tsindex f95e39cab..36fa57e9e 100644--- a/src/engine/adapters/baileys-remaining-writes.spec.ts+++ b/src/engine/adapters/baileys-remaining-writes.spec.ts@@ -24,6 +24,7 @@ function contacts(sock: Record<string, jest.Mock>, budgetMs: number): BaileysConresolvePhone: () => null,listChats: () => [],lastMessage: () => LAST,+ chatDeletedAt: () => null,toEngineJid: (j: string) => j,chatJid: (j: string) => j,lidOf: () => null,diff --git a/src/engine/adapters/baileys-send-seen.spec.ts b/src/engine/adapters/baileys-send-seen.spec.tsindex 1ada2c18d..2dd5e1faf 100644--- a/src/engine/adapters/baileys-send-seen.spec.ts+++ b/src/engine/adapters/baileys-send-seen.spec.ts@@ -34,6 +34,7 @@ function makeHost(overrides: Partial<Record<keyof BaileysContactsHost, unknown>>findPersistedLidPhone: () => Promise.resolve(null),listChats: () => [],lastInboundMessage: () => ({ key: { id: 'M1', remoteJid: '[email protected]' }, timestamp: 1 }),+ chatDeletedAt: () => null,getStoredMessages: () => Promise.resolve([]),toEngineJid,...overrides,diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 53c2d14b0..55b87ea82 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -50,7 +50,7 @@ class FakeChatStateStore implements ChatStateStore {const found = twins.filter(t => this.rows.has(this.key(s, t)));if (!found.length) return this.remember(s, c, patch, create);const merged = mergeTwinStates([c, ...found].flatMap(t => this.get(s, t) ?? []));- const fields: ChatStateField[] = ['muteEndTime', 'archived', 'pinned'];+ const fields: ChatStateField[] = ['muteEndTime', 'archived', 'pinned', 'deletedAt'];const base = merged? Object.fromEntries(fields.filter(f => !merged.observed || merged.observed.includes(f)).map(f => [f, merged[f]])): {};@@ -891,7 +891,7 @@ describe('BaileysSessionStore', () => {expect(store.listChats()[0].lastMessage).toBe('edited');});- it('removes a deleted chat, its preview and its chat state under every spelling', () => {+ it('removes a deleted chat and its preview under every spelling, and resets and marks its chat state', () => {const fake = new FakeChatStateStore();const s = new BaileysSessionStore(undefined, 'sess-1', fake);s.upsertChats([{ id: LID, name: 'Alice', pinned: 7 }]);@@ -903,10 +903,15 @@ describe('BaileysSessionStore', () => {expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]' })]);expect(s.lastMessage('[email protected]')).toBeNull();expect(s.lastInboundMessage('[email protected]')).toBeNull();- expect(fake.rows.size).toBe(0);- // A later message re-creates the chat without the pin the deleted one carried.- s.upsertChats([{ id: LID }]);+ expect([...fake.rows.keys()]).toEqual([`sess-1\u0000${PHONE}`]);+ expect(fake.get('sess-1', PHONE)).toMatchObject({ pinned: false, deletedAt: expect.any(Number) as number });+ expect(s.chatDeletedAt(LID)).toBe(fake.get('sess-1', PHONE)?.deletedAt);+ // A later message re-creates the chat without the pin the deleted one carried, and the mark goes.+ const later = Math.ceil(Date.now() / 1000) + 60;+ s.recordMessage(msg(LID, 'NEW', later));expect(s.listChats().find(c => c.id === LID)).toEqual(expect.objectContaining({ pinned: false }));+ expect(fake.rows.size).toBe(0);+ expect(s.chatDeletedAt('[email protected]')).toBeNull();});it('finds the lid twin through the persisted table as well', () => {@@ -1151,7 +1156,8 @@ describe('BaileysSessionStore', () => {expect(s.listChats()[0]).toMatchObject({ archived: true, pinned: true, muted: true });fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: true });s.removeChats([PHONE]);- expect(fake.rows.size).toBe(0);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(fake.get(SID, PHONE)).toMatchObject({ archived: false, pinned: false, muteEndTime: null });expect(s.listChats()).toEqual([]);});@@ -1177,22 +1183,26 @@ describe('BaileysSessionStore', () => {it.each([['the lid, with the state under the phone', LID, PHONE],['the phone, with the state under the lid', PHONE, LID],- ])('forgets a deleted chat named by %s when only the mapping table pairs them', async (_label, deleted, row) => {- fake.rows.set(K(row), { muteEndTime: null, archived: false, pinned: true });- const lidStore = {- getCached: jest.fn(() => undefined),- resolveLid: jest.fn(() => null),- lidsForPhone: jest.fn(() => []),- findPhoneForLid: jest.fn((jid: string) => Promise.resolve(jid.startsWith('484848') ? '628111' : null)),- findLidsForPhone: jest.fn((phone: string) => Promise.resolve(phone === '628111' ? ['484848'] : [])),- remember: jest.fn(() => Promise.resolve(true)),- };- const s = new BaileysSessionStore(lidStore, SID, fake);- s.removeChats([deleted]);- await flush();- expect(fake.rows.size).toBe(0);- expect(s.listChats()).toEqual([]);- });+ ])(+ 'marks a deleted chat named by %s and forgets the twin only the mapping table pairs',+ async (_label, deleted, row) => {+ fake.rows.set(K(row), { muteEndTime: null, archived: false, pinned: true });+ const lidStore = {+ getCached: jest.fn(() => undefined),+ resolveLid: jest.fn(() => null),+ lidsForPhone: jest.fn(() => []),+ findPhoneForLid: jest.fn((jid: string) => Promise.resolve(jid.startsWith('484848') ? '628111' : null)),+ findLidsForPhone: jest.fn((phone: string) => Promise.resolve(phone === '628111' ? ['484848'] : [])),+ remember: jest.fn(() => Promise.resolve(true)),+ };+ const s = new BaileysSessionStore(lidStore, SID, fake);+ s.removeChats([deleted]);+ await flush();+ expect([...fake.rows.keys()]).toEqual([K(deleted)]);+ expect(fake.get(SID, deleted)?.deletedAt).toEqual(expect.any(Number));+ expect(s.listChats()).toEqual([]);+ },+ );it('finds the lid through the persisted mapping table as well', () => {fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: false });@@ -1281,12 +1291,72 @@ describe('BaileysSessionStore', () => {expect(s.listChats().map(c => c.id)).toEqual(['[email protected]', '[email protected]', '999@lid', '[email protected]']);});- it('forgets the folded row when the chat is deleted under its lid', () => {+ it('resets and marks the folded row when the chat is deleted under its lid', () => {const s = newStore();s.upsertChats([{ id: PHONE, pinned: 2 }]);s.addLidMappings([{ lid: LID, pn: PHONE }]);s.removeChats([LID]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(fake.get(SID, PHONE)).toMatchObject({ pinned: false, deletedAt: expect.any(Number) as number });+ });++ it('marks each of several chats deleted at once with only its own twin rows folded in', () => {+ const OTHER = '[email protected]';+ const OTHER_LID = '515151@lid';+ const s = newStore();+ s.addLidMappings([+ { lid: LID, pn: PHONE },+ { lid: OTHER_LID, pn: OTHER },+ ]);+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: false });+ fake.rows.set(K(OTHER_LID), { muteEndTime: -1, archived: false, pinned: false });+ const fold = jest.spyOn(fake, 'fold');+ s.removeChats([PHONE, OTHER]);+ expect(fold.mock.calls.map(([, key, twins]) => [key, [...twins].sort()])).toEqual([+ [PHONE, [LID]],+ [OTHER, [OTHER_LID]],+ ]);+ expect([...fake.rows.keys()].sort()).toEqual([K(PHONE), K(OTHER)]);+ expect(s.chatDeletedAt('[email protected]')).toEqual(expect.any(Number));+ });++ it('takes no update for a deleted chat until one dated after the deletion re-creates it', () => {+ const s = newStore();+ s.upsertChats([{ id: PHONE, pinned: 2 }]);+ s.removeChats([PHONE]);+ // Baileys applies an own write locally, and a resync can bring a change from before the deletion.+ s.upsertChats([+ { id: PHONE, archived: true },+ { id: PHONE, conversationTimestamp: 100, unreadCount: 1 },+ ]);+ expect(fake.get(SID, PHONE)).toMatchObject({ archived: false, deletedAt: expect.any(Number) as number });+ expect(s.listChats()).toEqual([]);+ // The update a new message brings can arrive before the message itself.+ const later = Math.ceil(Date.now() / 1000) + 60;+ s.upsertChats([{ id: PHONE, conversationTimestamp: later, unreadCount: 1 }]);+ expect(fake.rows.size).toBe(0);+ expect(s.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', unreadCount: 1, timestamp: later, archived: false }),+ ]);+ });++ it('lists a deleted chat a newer message re-creates under any spelling, and clears its mark under the lid', () => {+ const s = newStore();+ // Deleted while its lid was not yet mapped, so the mark sits under the lid.+ s.removeChats([LID]);+ expect([...fake.rows.keys()]).toEqual([K(LID)]);+ // A mapping only this session holds is not read for every message, so this message leaves the mark.+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ const later = Math.ceil(Date.now() / 1000) + 60;+ s.recordMessage({ key: { remoteJid: PHONE, fromMe: false, id: 'NEW' }, messageTimestamp: later });+ expect([...fake.rows.keys()]).toEqual([K(LID)]);+ // The newer message still dates the chat after the deletion.+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', timestamp: later })]);+ expect(s.chatDeletedAt('[email protected]')).toBe(fake.get(SID, LID)?.deletedAt);+ // One under the lid, now filed under the phone, still reads the mark the lid row holds.+ s.recordMessage({ key: { remoteJid: LID, fromMe: false, id: 'NEXT' }, messageTimestamp: later + 1 });expect(fake.rows.size).toBe(0);+ expect(s.chatDeletedAt('[email protected]')).toBeNull();});it('lists a chat with a persisted state after a restart, before its next message', () => {diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 4ad0a6de5..85164d5ae 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -304,6 +304,12 @@ export class BaileysSessionStore {if (!r.id) {continue;}+ // A chat WhatsApp deleted takes no update until a message re-creates it: Baileys applies an own+ // write locally (a mute or pin is sent without a message), and a reconnect resyncs a deletion before+ // an archive or pin made ahead of it. Kept, either would show on the chat a later message re-creates.+ if (this.stillDeleted(r.id, this.toUnixSeconds(r.conversationTimestamp))) {+ continue;+ }const existing = this.chats.get(r.id) ?? { id: r.id };this.chats.set(r.id, { ...existing, ...r });this.persistChatState(r.id, r);@@ -331,8 +337,9 @@ export class BaileysSessionStore {* Drop chats Baileys reports deleted (`chats.delete`: an API delete replayed locally, or one made on* the phone), with their preview and last inbound message, under every spelling: the id comes from* the app-state index, which need not be the twin the chat or its messages are keyed under. The- * persisted mute/archive/pin goes too: a chat a later message re-creates is a new chat on WhatsApp,- * and the row would otherwise lay the deleted chat's state over it.+ * persisted mute/archive/pin is reset and the row marks the deletion ({@link chatDeletedAt}): WhatsApp+ * keeps nothing of the chat while the gateway keeps its stored messages, and a write keyed to one of+ * them comes back from Baileys as an update of the chat, which would list it again.*/removeChats(ids: string[] = []): void {const keys = new Set(ids.flatMap(id => this.chatTwins(id)));@@ -342,23 +349,38 @@ export class BaileysSessionStore {this.lastInbound.delete(key);}if (keys.size && this.chatStateStore && this.sessionId) {- void this.forgetChatState(this.chatStateStore, this.sessionId, ids, keys);+ void this.markDeleted(this.chatStateStore, this.sessionId, ids, keys);}}/**- * The in-memory mappings can lack the lid or phone twin after a restart, and a delete is never- * retried, so a row under that twin would outlive the chat and put it back in the listing. The- * known keys are forgotten first, queued ahead of any later write; the twins only the mapping- * table pairs follow.+ * The marked row is written under the chat's state key, folding the rows of the known twins onto it,+ * queued ahead of any later write. The in-memory mappings can lack the lid or phone twin after a+ * restart, and a delete is never retried, so the twins only the mapping table pairs are forgotten+ * after: a row there would outlive the deletion and put the chat back in the listing.+ *+ * Baileys reports a deletion by ids alone, so it is dated on arrival. One synced on a reconnect is+ * dated later than it happened: a message delivered in the same reconnect counts as older, and the+ * chat stays unlisted, its writes declined, until the next one.*/- private async forgetChatState(- store: ChatStateStore,- sessionId: string,- ids: string[],- keys: Set<string>,- ): Promise<void> {- const forgotten = store.forget(sessionId, [...keys]);+ private async markDeleted(store: ChatStateStore, sessionId: string, ids: string[], keys: Set<string>): Promise<void> {+ const reset = { muteEndTime: null, archived: false, pinned: false, deletedAt: Date.now() };+ // Each chat folds its own twins: one event can delete several chats.+ const twinsOf = new Map<string, Set<string>>();+ for (const id of ids) {+ const key = this.stateKey(id);+ twinsOf.set(key, new Set([...(twinsOf.get(key) ?? []), ...this.chatTwins(id)]));+ }+ const marked = Promise.all(+ [...twinsOf].map(([key, twins]) =>+ store.fold(+ sessionId,+ key,+ [...twins].filter(k => !twinsOf.has(k)),+ reset,+ ),+ ),+ );const extra = new Set<string>();for (const id of ids) {const parsed = parseWaId(id);@@ -373,11 +395,46 @@ export class BaileysSessionStore {// The table cannot be read; the keys the caches knew are already going.}}- await forgotten;- const missed = [...extra].filter(k => !keys.has(k));+ await marked;+ const missed = [...extra].filter(k => !keys.has(k) && !twinsOf.has(k));if (missed.length) await store.forget(sessionId, missed);}+ /**+ * When WhatsApp deleted the chat (epoch ms), read from its persisted state under any spelling, or+ * null when it did not, or a message has re-created the chat since. A message sent at or before it+ * belongs to the deleted chat.+ */+ chatDeletedAt(chatId: string): number | null {+ return this.chatState(chatId, this.chatTwins(chatId))?.deletedAt ?? null;+ }++ /**+ * Whether the chat is marked deleted for a message or chat update dated `timestamp` (epoch seconds, 0+ * for none). A message newer than the deletion re-creates the chat on WhatsApp, as a new chat, so its+ * marked row goes and the answer is false. Only the rows a mark can sit under are read, the state key+ * and the lids the jid and the persisted table name: an empty index skips the scan of this session's+ * mappings, too slow to run for each of the thousands of messages a first sync records.+ */+ private stillDeleted(jid: string, timestamp: number): boolean {+ const store = this.chatStateStore;+ const sid = this.sessionId;+ if (!store || !sid) return false;+ const key = this.stateKey(jid);+ const rows = [key, ...this.stateTwins([jid], key, new Map())].flatMap(k => {+ const value = store.get(sid, k);+ return value ? [{ k, value }] : [];+ });+ const deletedAt = mergeTwinStates(rows.map(r => r.value))?.deletedAt;+ if (!deletedAt) return false;+ if (timestamp * 1000 <= deletedAt) return true;+ void store.forget(+ sid,+ rows.map(r => r.k),+ );+ return false;+ }+addLidMappings(mappings: { lid?: string; pn?: string }[] = [], isReported = true): void {for (const m of mappings) {if (m.lid && m.pn) {@@ -446,6 +503,8 @@ export class BaileysSessionStore {// A received broadcast-list message previews in its sender's chat, where Baileys lists it.const key = this.toEngineJid(baileysChatJid(chatId, msg.key.participant, msg.key.fromMe === true));const timestamp = this.toUnixSeconds(msg.messageTimestamp);+ // Recorded either way: the readers skip a message from before the deletion, and a newer one clears it.+ this.stillDeleted(key, timestamp);if (!msg.key.fromMe) {const inbound = this.lastInbound.get(key);if (@@ -696,14 +755,14 @@ export class BaileysSessionStore {if (!byId.has(id)) byId.set(id, [{ id: key }]);}// A new engine starts with no chats (see the class comment), but a chat with a persisted state is- // known to exist: a deleted chat loses its row. So it is listed before its next message arrives.+ // known to exist, unless the row marks its deletion. So it is listed before its next message arrives.if (this.chatStateStore && this.sessionId) {for (const chatId of this.chatStateStore.chatIds(this.sessionId)) {const id = this.toNeutralJid(chatId);if (!byId.has(id)) byId.set(id, [{ id: chatId }]);}}- return [...byId].map(([id, records]) => this.toNeutralChat(id, records, previews.get(id), lidIndex));+ return [...byId].flatMap(([id, records]) => this.toNeutralChat(id, records, previews.get(id), lidIndex) ?? []);}/**@@ -847,14 +906,14 @@ export class BaileysSessionStore {/*** Project the records that share neutral `id` (usually one) into a row. `last` is the newest preview- * filed under any of their keys.+ * filed under any of their keys. Null for a chat WhatsApp deleted that no message has re-created since.*/private toNeutralChat(id: string,records: Chat[],last: LastMessage | undefined,lidIndex: Map<string, string[]>,- ): ChatSummary {+ ): ChatSummary | null {// Chat.id is nullable on Baileys' own type (it's the raw proto.IConversation field), but// upsertChats() only ever stores a record under a truthy r.id, so every value in `this.chats`// is provably keyed by a real id. Phone-keyed first, then the lower raw id: stable across calls.@@ -869,6 +928,11 @@ export class BaileysSessionStore {records.map(r => r.id!),lidIndex,);+ // Only a message newer than the deletion re-creates the chat: a record without one is a state update,+ // and a message sent before it, delivered late, is the deleted chat's.+ const active = () =>+ Math.max(last?.timestamp ?? 0, ...records.map(r => this.toUnixSeconds(r.conversationTimestamp)));+ if (st?.deletedAt && active() * 1000 <= st.deletedAt) return null;return {id,name: c.name ?? others.find(o => o.name)?.name ?? this.resolveContactName(rawId),@@ -980,7 +1044,7 @@ export class BaileysSessionStore {* are folded onto the state key on the chat's next change (see {@link persistChatState}). `recordIds`* are the raw ids of every chat record merged into the row, whose lids are twins too.*/- private chatState(rawId: string, recordIds: string[], lidIndex: Map<string, string[]>): ChatStateValue | undefined {+ private chatState(rawId: string, recordIds: string[], lidIndex?: Map<string, string[]>): ChatStateValue | undefined {const store = this.chatStateStore;const sid = this.sessionId;if (!store || !sid) return undefined;diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 1d1f56562..da6ed027a 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -13,6 +13,8 @@ import { Message, MessageDirection } from '../../modules/message/entities/messagimport { MessageProjector } from '../../modules/session/message-projector.service';import { SessionLidResolver } from '../../modules/session/session-lid-resolver.service';import { ChatScopeService } from '../../modules/auth/chat-scope.service';+import { ChatState } from './baileys-chat-state.entity';+import { ChatStateStoreService } from './baileys-chat-state-store.service';jest.mock('../../common/media/load-remote-media', () => ({loadRemoteMediaBuffer: jest.fn(),@@ -8540,6 +8542,180 @@ describe('BaileysAdapter chat writes keyed to a message (#1891)', () => {expect(fakeSock.chatModify).not.toHaveBeenCalled();});});++ // WhatsApp keeps nothing of a deleted chat while the gateway keeps its stored messages, and Baileys applies an own+ // patch locally: a write keyed to a message from before the deletion came back as an update of the chat, which+ // listed the deleted chat again, for good once the update had created a state row.+ describe('for a chat deleted on WhatsApp', () => {+ const PHONE = '[email protected]';+ const LID = '484848@lid';+ let db: DataSource;+ const newStore = () => new ChatStateStoreService(db.getRepository(ChatState));+ const now = () => Math.floor(Date.now() / 1000);+ // The store writes behind the events that feed it.+ const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise(r => setImmediate(r));+ };++ beforeEach(async () => {+ db = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [ChatState], synchronize: true });+ await db.initialize();+ // Baileys applies its own app-state patch as a chat update (emitOwnEvents).+ fakeSock.chatModify.mockImplementation((change: Record<string, unknown>, jid: string) => {+ if ('archive' in change) fakeSock.fire('chats.update', [{ id: jid, archived: change.archive }]);+ if ('markRead' in change) fakeSock.fire('chats.update', [{ id: jid, unreadCount: -1 }]);+ if ('delete' in change) fakeSock.fire('chats.delete', [jid]);+ return Promise.resolve();+ });+ });+ afterEach(async () => {+ fakeSock.chatModify.mockReset().mockResolvedValue(undefined);+ await db.destroy();+ });++ const started = async (+ chatStateStore: ChatStateStoreService,+ lidMappingStore?: ReturnType<typeof reported>,+ ): Promise<BaileysAdapter> => {+ await chatStateStore.reload();+ const adapter = new BaileysAdapter({+ sessionId: 'sess-1',+ dbSessionId: 'db-uuid-1',+ authDir: './data/baileys',+ messageStore: fakeStore,+ chatStateStore,+ ...(lidMappingStore ? { lidMappingStore } : {}),+ });+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };+ const deletedOnPhone = async (id = PHONE, lidMappingStore?: ReturnType<typeof reported>) => {+ const adapter = await started(newStore(), lidMappingStore);+ fakeSock.fire('chats.upsert', [{ id, pinned: 3 }]);+ fakeSock.fire('chats.delete', [id]);+ await settle();+ return adapter;+ };+ const before = () => lookup({ id: 'S1', fromMe: false, timestamp: 1690000000 });++ it('keys no write to a stored message from before the deletion, and the chat stays unlisted', async () => {+ const adapter = await deletedOnPhone();+ await expect(adapter.archiveChat('[email protected]', true, before())).resolves.toBe(false);+ await expect(adapter.markUnread('[email protected]', before())).resolves.toBe(false);+ await expect(adapter.clearChatMessages('[email protected]', before())).resolves.toBe(false);+ await expect(adapter.deleteChat('[email protected]', before())).resolves.toBe(false);+ await expect(adapter.sendSeen('[email protected]', undefined, undefined, before())).resolves.toBe(false);+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ expect(fakeSock.readMessages).not.toHaveBeenCalled();+ await settle();+ expect(await adapter.getChats()).toEqual([]);+ });++ it('still keys no write to it after a restart, and a state update the phone sends lists nothing', async () => {+ await deletedOnPhone();+ const adapter = await started(newStore());+ await expect(adapter.archiveChat('[email protected]', true, before())).resolves.toBe(false);+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ // An archive made before the deletion can be synced after it: the delete's collection resyncs first.+ fakeSock.fire('chats.update', [{ id: PHONE, archived: true }]);+ await settle();+ expect(await adapter.getChats()).toEqual([]);+ expect(await (await started(newStore())).getChats()).toEqual([]);+ });++ it('does not take a message from before the deletion delivered after it as the chat coming back', async () => {+ const adapter = await deletedOnPhone();+ // A reconnect can deliver a message the phone had before the chat was deleted after the deletion.+ await upsert({ remoteJid: PHONE, fromMe: false, id: 'OLD' }, 1700000020);+ fakeSock.fire('chats.update', [{ id: PHONE, conversationTimestamp: 1700000020, unreadCount: 1 }]);+ await settle();+ expect(await adapter.getChats()).toEqual([]);+ await expect(adapter.archiveChat('[email protected]', true, lookup(null))).resolves.toBe(false);+ await expect(adapter.sendSeen('[email protected]', undefined, undefined, lookup(null))).resolves.toBe(false);+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ expect(fakeSock.readMessages).not.toHaveBeenCalled();+ });++ it('lists and writes to the chat a later message re-creates, without the state of the deleted one', async () => {+ const adapter = await deletedOnPhone();+ // Synced after the deletion, from before it, and still to be dropped once the chat is new again.+ fakeSock.fire('chats.update', [{ id: PHONE, muteEndTime: -1 }]);+ const at = now() + 60;+ await upsert({ remoteJid: PHONE, fromMe: false, id: 'NEW' }, at);+ await settle();+ expect(await adapter.getChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', muted: false, pinned: false, archived: false }),+ ]);+ await expect(adapter.archiveChat('[email protected]', true, before())).resolves.toBe(true);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ {+ archive: true,+ lastMessages: [{ key: { remoteJid: PHONE, fromMe: false, id: 'NEW' }, messageTimestamp: at }],+ },+ PHONE,+ );+ await settle();+ // The archive outlives a restart, as for any chat.+ expect(await (await started(newStore())).getChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', archived: true }),+ ]);+ });++ it('keys a write to a stored message from after the deletion', async () => {+ const adapter = await deletedOnPhone();+ const at = now() + 60;+ await expect(+ adapter.clearChatMessages('[email protected]', lookup({ id: 'S2', fromMe: true, timestamp: at })),+ ).resolves.toBe(true);+ expect(fakeSock.chatModify).toHaveBeenCalledWith(+ { clear: true, lastMessages: [{ key: { remoteJid: PHONE, fromMe: true, id: 'S2' }, messageTimestamp: at }] },+ PHONE,+ );+ });++ it.each([+ ['its lid', LID],+ ['its phone', PHONE],+ ])('keys no write for a lid-keyed chat deleted under %s to a stored message from before', async (_n, id) => {+ const mappings = reported({ [LID]: '628111' });+ const adapter = await started(newStore(), mappings);+ fakeSock.fire('lid-mapping.update', { lid: LID, pn: PHONE });+ fakeSock.fire('chats.upsert', [{ id: LID }]);+ fakeSock.fire('chats.delete', [id]);+ await settle();+ const stored = lookup({ id: 'S1', fromMe: false, timestamp: 1690000000, lid: LID });+ for (const chatId of ['[email protected]', LID]) {+ await expect(adapter.archiveChat(chatId, true, stored)).resolves.toBe(false);+ await expect(adapter.sendSeen(chatId, undefined, undefined, stored)).resolves.toBe(false);+ }+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ expect(await adapter.getChats()).toEqual([]);+ });++ it('keys no write for a group deleted after leaving it to a stored message from before', async () => {+ const adapter = await deletedOnPhone('[email protected]');+ const stored = lookup({ id: 'G1', fromMe: false, author: '[email protected]', timestamp: 1690000000 });+ await expect(adapter.markUnread('[email protected]', stored)).resolves.toBe(false);+ // A received message without its sender keys nothing but used to show the chat exists.+ const anonymous = lookup({ id: 'G2', fromMe: false, timestamp: 1690000000 });+ await expect(adapter.archiveChat('[email protected]', true, anonymous)).resolves.toBe(false);+ expect(fakeSock.chatModify).not.toHaveBeenCalled();+ expect(await adapter.getChats()).toEqual([]);+ });++ it('lets a chat deleted through the API come back with its next message', async () => {+ const adapter = await started(newStore());+ await upsert({ remoteJid: PHONE, fromMe: false, id: 'M1' }, now() - 60);+ // Baileys replays the delete as chats.delete, as it does a phone's.+ await expect(adapter.deleteChat('[email protected]')).resolves.toBe(true);+ await settle();+ expect(await adapter.getChats()).toEqual([]);+ await upsert({ remoteJid: PHONE, fromMe: true, id: 'M2' }, now() + 60);+ await settle();+ expect(await adapter.getChats()).toEqual([expect.objectContaining({ id: '[email protected]' })]);+ });+ });});describe('BaileysAdapter status posting', () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex bdf4fd7ab..2c4808c8e 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -198,6 +198,7 @@ export class BaileysAdapter implements IWhatsAppEngine {lastInboundMessage: chatId => this.sessionStore.lastInboundMessage(chatId),lidOf: jid => this.sessionStore.lidOf(jid),chatTwins: jid => this.sessionStore.chatTwins(jid),+ chatDeletedAt: chatId => this.sessionStore.chatDeletedAt(chatId),upsertContacts: records => this.sessionStore.upsertContacts(records),upsertChats: records => this.sessionStore.upsertChats(records),removeChats: ids => this.sessionStore.removeChats(ids),diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 5f41e5f22..ed1522783 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -1636,6 +1636,31 @@ describe('InfraDataController.import/export preserves every data-DB table', () =expect((await lidRepo.findOneByOrFail({ lid: '111' })).isReported).toBe(false);});+ // The mark of a deleted chat outlives a restart because the stored messages it guards do, and a+ // restore brings both back.+ it('restores the deletion mark of a chat state, and reads an archive taken without one as none', async () => {+ await seedSession('s1');+ const repo = ds.getRepository(ChatState);+ await repo.save([+ repo.create({ sessionId: 's1', chatId: '[email protected]', deletedAt: 1790000000000 }),+ repo.create({ sessionId: 's1', chatId: '[email protected]', pinned: true }),+ ]);++ const dump = await controller.exportData();+ await repo.clear();+ const res = await controller.importData({ tables: dump.tables });++ expect(res.warnings).toEqual([]);+ expect(await repo.findOneByOrFail({ chatId: '[email protected]' })).toMatchObject({ deletedAt: 1790000000000 });+ expect(await repo.findOneByOrFail({ chatId: '[email protected]' })).toMatchObject({ pinned: true, deletedAt: null });++ const states = (dump.tables as unknown as { chatStates: { deletedAt?: number | null }[] }).chatStates;+ for (const state of states) delete state.deletedAt;+ const legacy = await controller.importData({ tables: dump.tables });+ expect(legacy.warnings).toEqual([]);+ expect((await repo.findOneByOrFail({ chatId: '[email protected]' })).deletedAt).toBeNull();+ });+// Restoring ONTO the instance that produced the archive is the rollback flow, and it is the one the// outbox broke. The table carries no FK to sessions, so the sessions DELETE never reached it, and// UNIQUE(webhookId, idempotencyKey) then collided on every row until the all-or-nothing gate rolleddiff --git a/src/modules/infra/infra-data.import.pg.spec.ts b/src/modules/infra/infra-data.import.pg.spec.tsindex 7e9867ee4..130bf15c6 100644--- a/src/modules/infra/infra-data.import.pg.spec.ts+++ b/src/modules/infra/infra-data.import.pg.spec.ts@@ -150,6 +150,15 @@ describePostgres('InfraDataController.importData (postgres)', () => {expect(await mappings.findOneBy({ lid: '111' })).toMatchObject({ phone: '628111', isReported: false });});+ // A bigint column the export reads back as a string.+ it('restores the deletion mark of a chat state', async () => {+ const states = ds.getRepository(ChatState);+ await states.insert([{ sessionId: 's1', chatId: '[email protected]', deletedAt: 1790000000000 }]);+ const dump = await controller.exportData();+ await expect(controller.importData(dump as never)).resolves.toMatchObject({ imported: true, warnings: [] });+ expect(await states.findOneBy({ chatId: '[email protected]' })).toMatchObject({ deletedAt: 1790000000000 });+ });+// The runtime pool cancels a statement that outlives statement_timeout (30 s by default), and the// clears of a replace-all import scale with the live tables, not with the archive. A slow trigger on// messages stands in for a table that has grown large: with the pool's timeout lowered below it, thediff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex a5ab6f30d..5dc0bb82d 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -128,6 +128,8 @@ export interface ChatStateRow {pinned: boolean | number;// Absent from an archive taken before the column existed; null reads as its set fields observed.observed?: string | null;+ // Epoch ms WhatsApp deleted the chat; absent from an archive taken before the column existed.+ deletedAt?: number | null;updatedAt: string;}diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 46cd88791..707dedd5c 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -342,7 +342,7 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [defineTableImporter({key: 'chatStates',label: 'chat state',- sql: `INSERT INTO chat_states ("sessionId", "chatId", "muteEndTime", archived, pinned, observed, "updatedAt") VALUES ($1, $2, $3, $4, $5, $6, $7)`,+ sql: `INSERT INTO chat_states ("sessionId", "chatId", "muteEndTime", archived, pinned, observed, "deletedAt", "updatedAt") VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,id: (cs: ChatStateRow) => `${cs.sessionId}/${cs.chatId}`,map: (cs: ChatStateRow) => [cs.sessionId,@@ -351,6 +351,7 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [cs.archived,cs.pinned,cs.observed ?? null,+ cs.deletedAt ?? null,cs.updatedAt,],}),