Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): preserve unpatched chat-state fields and back up chat_states
Yudhi Armyndharis0bd4da1508fe
diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex a56607a62..d2d753d85 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -78,6 +78,25 @@ describe('ChatStateStoreService', () => {expect(svc.get('s', 'c')).toBeDefined();});+ it('preserves persisted siblings when a partial patch lands on a cache-missed chat', async () => {+ // A muted + archived chat whose row is persisted but NOT in the in-memory cache (evicted, or an+ // old row outside the newest-maxEntries reload window). A partial `chats.update` carrying only+ // `{ pinned }` must merge onto the persisted row, not DEFAULT_STATE, or it silently wipes the mute.+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 999, archived: true, pinned: false }]);+ const svc = svcWith(repo); // no reload(): the row is on disk but absent from the cache+ await svc.remember('s', 'c', { pinned: true });+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: true });+ expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ muteEndTime: 999, archived: true, pinned: true });+ });++ it('does not churn a row when a cache-missed patch matches the persisted state', async () => {+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 999, archived: true, pinned: false }]);+ const svc = svcWith(repo);+ await svc.remember('s', 'c', { archived: true }); // already true on disk -> no write+ expect(repo.upsert).not.toHaveBeenCalled();+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: false });+ });+it('warms a cache miss from the table so the next read hits', async () => {const svc = svcWith(makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 5, archived: false, pinned: true }]));// No reload: the cache is empty, so the first read misses and schedules a background lookup.@@ -89,7 +108,7 @@ describe('ChatStateStoreService', () => {it('swallows a repo error on reload and remember (table may not exist yet)', async () => {const repo = {find: jest.fn(() => Promise.reject(new Error('no such table'))),- findOne: jest.fn(),+ findOne: jest.fn(() => Promise.reject(new Error('no such table'))),upsert: jest.fn(() => Promise.reject(new Error('no such table'))),};const svc = new ChatStateStoreService(repo as unknown as Repository<ChatState>);diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex 8f436599e..0ede30d7a 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -27,7 +27,8 @@ const SEP = '\u0000'; // a null byte never appears in a session name or JID, so// ponytail: one global LRU across all sessions, default 5000, matching the other engine maps. A// many-session deployment with large chat lists should raise BAILEYS_CHAT_STATE_CACHE_MAX; an evicted-// row stays persisted and warms back on the next read, so eviction costs a re-read, never data loss.+// row stays persisted and both paths read-through on a miss (the read warms lazily, the write merges+// the patch onto the persisted row), so eviction costs a re-read, never data loss.export const CHAT_STATE_CACHE_DEFAULT = 5000;/**@@ -92,15 +93,25 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {async remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void> {const k = this.key(sessionId, chatId);- const existing = this.states.get(k) ?? DEFAULT_STATE;+ // The merge base must be the CURRENT state, not DEFAULT_STATE, or a partial `chats.update` (Baileys+ // emits single-field patches, e.g. `{ pinned }` alone) would reset the columns it omits. On a cache+ // miss the persisted row is that base: the read path warms lazily, but the write path upserts every+ // column, so it has to read-through first or a lone pin update on an evicted muted chat wipes its+ // mute. A row absent from the table resolves to DEFAULT_STATE, which is the correct base for a chat+ // whose state has never been persisted.+ let existing = this.states.get(k);+ if (!existing) {+ const row = await this.repo.findOne({ where: { sessionId, chatId } }).catch(() => null);+ existing = row ? { muteEndTime: row.muteEndTime, archived: row.archived, pinned: row.pinned } : DEFAULT_STATE;+ }const next: ChatStateValue = { ...existing, ...patch };if (- this.states.has(k) &&existing.muteEndTime === next.muteEndTime &&existing.archived === next.archived &&existing.pinned === next.pinned) {- return; // no-op write would just churn updatedAt+ this.index(k, next); // warm the cache even on a no-op so the next read is a hit+ return; // nothing changed against the current state; skip the write that would just churn updatedAt}this.index(k, next);try {diff --git a/src/modules/infra/export-tables.parity.spec.ts b/src/modules/infra/export-tables.parity.spec.tsindex 5b3a15c80..0450a4583 100644--- a/src/modules/infra/export-tables.parity.spec.ts+++ b/src/modules/infra/export-tables.parity.spec.ts@@ -199,3 +199,16 @@ describe('InfraDataService.exportData validates the registry against live entityexpect(query).not.toHaveBeenCalled();});});++describe('the import clears every re-inserted table that DELETE FROM sessions cannot cascade', () => {+ it('clears the (sessionId, *) provenance tables (lid_mappings, chat_states) before the sessions delete', () => {+ const src = readFileSync(join(__dirname, 'infra-data.service.ts'), 'utf8');+ const cleared = new Set([...src.matchAll(/clearTable\('([a-z_]+)'\)/g)].map(m => m[1]));+ // These tables carry no FK to sessions (the sessionId is provenance, not a foreign key), so the+ // import's `DELETE FROM sessions` never reaches them. They are re-inserted from the archive, so+ // without an explicit clear a restore onto an instance that already holds their rows collides on+ // PK and the all-or-nothing gate rolls the whole import back (the exact restore-onto-self flow).+ expect(cleared).toContain('lid_mappings');+ expect(cleared).toContain('chat_states');+ });+});diff --git a/src/modules/infra/infra-data.service.ts b/src/modules/infra/infra-data.service.tsindex 8d19c8d62..021eb3f94 100644--- a/src/modules/infra/infra-data.service.ts+++ b/src/modules/infra/infra-data.service.ts@@ -596,6 +596,10 @@ export class InfraDataService {// lid_mappings is not a FK to sessions, so the sessions DELETE below won't clear it; clear it// explicitly so a restore replaces the cache rather than colliding on existing lid PKs.await clearTable('lid_mappings');+ // chat_states is the same case: PK (sessionId, chatId), no FK to sessions, so the sessions DELETE+ // does not reach it. Without this, a restore onto an instance that already holds chat_states rows+ // collides on those PKs and the all-or-nothing gate rolls the whole import back.+ await clearTable('chat_states');// Integration Fabric + both DLQs: none carry an FK constraint to sessions (sessionId is provenance),// so clearing them here before the sessions DELETE keeps the replace-semantics complete.await clearTable('plugin_instances');