Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): list a lid-migrated chat once with its pin and mute
Yudhi Armyndharis727581268148
diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex 489894bb6..98a0a30f4 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -676,7 +676,7 @@ The data connection also owns:- **`integration_delivery_failures`** — DLQ-of-record for both inbound (ingress) and outbound (provider egress) delivery failures (`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)`. 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 loses its row, so a later message starts it clean.Additionally, the `AddMessagesFts` migration creates the full-text-search structures over `messages` (a FTS5 virtual table on SQLite, a generated `body_ts` `tsvector` column plus GIN index on PostgreSQL) that back the `/search` endpoint.diff --git a/src/database/migrations/1786650000000-AddChatStateObserved.ts b/src/database/migrations/1786650000000-AddChatStateObserved.tsnew file mode 100644index 000000000..791548468--- /dev/null+++ b/src/database/migrations/1786650000000-AddChatStateObserved.ts@@ -0,0 +1,24 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds `chat_states.observed`, the state fields a row has seen a value for. A row created by a lone+ * pin also stores a default mute and archive, so two rows of one chat could not tell an explicit unpin+ * from a field the row never saw, and merging them brought a cleared pin back. Existing rows keep null,+ * read as having observed their set fields. 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 AddChatStateObserved1786650000000 implements MigrationInterface {+ name = 'AddChatStateObserved1786650000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasTable('chat_states')) || (await queryRunner.hasColumn('chat_states', 'observed'))) {+ return;+ }+ await queryRunner.query(`ALTER TABLE "chat_states" ADD COLUMN "observed" varchar`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (!(await queryRunner.hasColumn('chat_states', 'observed'))) return;+ await queryRunner.query(`ALTER TABLE "chat_states" DROP COLUMN "observed"`);+ }+}diff --git a/src/database/migrations/__tests__/1786650000000-AddChatStateObserved.spec.ts b/src/database/migrations/__tests__/1786650000000-AddChatStateObserved.spec.tsnew file mode 100644index 000000000..b238fcc33--- /dev/null+++ b/src/database/migrations/__tests__/1786650000000-AddChatStateObserved.spec.ts@@ -0,0 +1,39 @@+import { DataSource } from 'typeorm';+import { AddChatStates1786400000000 } from '../1786400000000-AddChatStates';+import { AddChatStateObserved1786650000000 } from '../1786650000000-AddChatStateObserved';++describe('AddChatStateObserved 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 again', 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 AddChatStateObserved1786650000000();++ await migration.up(runner);+ await migration.up(runner); // idempotent+ expect(await runner.query(`SELECT "observed", "pinned" FROM "chat_states"`)).toEqual([+ { observed: null, pinned: 1 },+ ]);++ await migration.down(runner);+ expect(await runner.hasColumn('chat_states', 'observed')).toBe(false);+ await runner.release();+ });++ it('is a no-op without the table', async () => {+ const runner = ds.createQueryRunner();+ await expect(new AddChatStateObserved1786650000000().up(runner)).resolves.toBeUndefined();+ await runner.release();+ });+});diff --git a/src/engine/adapters/baileys-chat-state-store.service.spec.ts b/src/engine/adapters/baileys-chat-state-store.service.spec.tsindex 5a106067f..067f08c9c 100644--- a/src/engine/adapters/baileys-chat-state-store.service.spec.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -1,6 +1,7 @@import { Repository } from 'typeorm';-import { ChatStateStoreService } from './baileys-chat-state-store.service';+import { ChatStateStoreService, mergeTwinStates } from './baileys-chat-state-store.service';import { ChatState } from './baileys-chat-state.entity';+import { BaileysSessionStore } from './baileys-session-store';const KEY = (s: string, c: string): string => `${s}\u0000${c}`;@@ -32,6 +33,26 @@ function makeRepo(initial: Partial<ChatState>[] = []) {rows.set(KEY(v.sessionId, v.chatId), { ...rows.get(KEY(v.sessionId, v.chatId)), ...v });return Promise.resolve(undefined);}),+ update: jest.fn(({ sessionId, chatId }: { sessionId: string; chatId: string }, v: Partial<ChatState>) => {+ const row = rows.get(KEY(sessionId, chatId));+ if (row) rows.set(KEY(sessionId, chatId), { ...row, ...v });+ return Promise.resolve({ affected: row ? 1 : 0 });+ }),+ // Only the insert-or-ignore chain the service builds: a row already on the key is left alone.+ createQueryBuilder: jest.fn(() => {+ let values: Partial<ChatState> & Pick<ChatState, 'sessionId' | 'chatId'>;+ const qb = {+ insert: () => qb,+ values: (v: typeof values) => ((values = v), qb),+ orIgnore: () => qb,+ execute: () => {+ const k = KEY(values.sessionId, values.chatId);+ if (!rows.has(k)) rows.set(k, { muteEndTime: null, archived: false, pinned: false, ...values } as ChatState);+ return Promise.resolve(undefined);+ },+ };+ return qb;+ }),delete: jest.fn(({ sessionId, chatId }: { sessionId: string; chatId?: string }) => {for (const [k, r] of rows)if (r.sessionId === sessionId && (chatId === undefined || r.chatId === chatId)) rows.delete(k);@@ -57,7 +78,7 @@ describe('ChatStateStoreService', () => {it('reloads the table into the cache on boot', async () => {const svc = svcWith(makeRepo([{ sessionId: 's', chatId: 'c', muteEndTime: 123, archived: true, pinned: false }]));await svc.reload();- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 123, archived: true, pinned: false });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: 123, archived: true, pinned: false });});it('clearSession drops one session from the table and the cache, and leaves the others', async () => {@@ -70,7 +91,34 @@ describe('ChatStateStoreService', () => {await svc.clearSession('s');expect([...repo.rows.values()].map(r => r.sessionId)).toEqual(['t']);expect(svc.get('s', 'c')).toBeUndefined();- expect(svc.get('t', 'c')).toEqual({ muteEndTime: null, archived: false, pinned: true });+ expect(svc.get('t', 'c')).toMatchObject({ muteEndTime: null, archived: false, pinned: true });+ });++ describe('reports when each state last changed', () => {+ it('reads the stamp from the row on reload, refresh and a read-through', async () => {+ const at = new Date(5000);+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', pinned: true, updatedAt: at }]);+ const svc = svcWith(repo);+ await svc.reload();+ expect(svc.get('s', 'c')?.updatedAt).toBe(5000);+ await svc.refreshSession('s');+ expect(svc.get('s', 'c')?.updatedAt).toBe(5000);+ const cold = svcWith(repo);+ cold.get('s', 'c');+ await tick();+ expect(cold.get('s', 'c')?.updatedAt).toBe(5000);+ });++ it('stamps a change with the instant it persists, and keeps the stamp on a no-op', async () => {+ const repo = makeRepo([{ sessionId: 's', chatId: 'c', pinned: true, updatedAt: new Date(5000) }]);+ const svc = svcWith(repo);+ await svc.remember('s', 'c', { pinned: true, updatedAt: 1 });+ expect(svc.get('s', 'c')?.updatedAt).toBe(5000);+ await svc.remember('s', 'c', { archived: true });+ const stamp = svc.get('s', 'c')?.updatedAt;+ expect(stamp).toBeGreaterThan(5000);+ expect(repo.rows.get(KEY('s', 'c'))?.updatedAt.getTime()).toBe(stamp);+ });});it('returns undefined for an unknown chat', () => {@@ -81,7 +129,7 @@ describe('ChatStateStoreService', () => {const svc = svcWith(makeRepo());await svc.remember('s', 'c', { muteEndTime: 999 });await svc.remember('s', 'c', { archived: true });- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: false });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: 999, archived: true, pinned: false });});it('skips a no-op identical write', async () => {@@ -130,7 +178,7 @@ describe('ChatStateStoreService', () => {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 cacheawait svc.remember('s', 'c', { pinned: true });- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: true });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: 999, archived: true, pinned: true });expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ muteEndTime: 999, archived: true, pinned: true });});@@ -143,7 +191,7 @@ describe('ChatStateStoreService', () => {// Nothing guessed is cached: the next read warms from the table.expect(svc.get('s', 'c')).toBeUndefined();await tick();- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: true });+ expect(svc.get('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 () => {@@ -151,7 +199,7 @@ describe('ChatStateStoreService', () => {const svc = svcWith(repo);await svc.remember('s', 'c', { archived: true }); // already true on disk -> no writeexpect(repo.upsert).not.toHaveBeenCalled();- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 999, archived: true, pinned: false });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: 999, archived: true, pinned: false });});it('warms a cache miss from the table so the next read hits', async () => {@@ -159,7 +207,7 @@ describe('ChatStateStoreService', () => {// No reload: the cache is empty, so the first read misses and schedules a background lookup.expect(svc.get('s', 'c')).toBeUndefined();await tick();- expect(svc.get('s', 'c')).toEqual({ muteEndTime: 5, archived: false, pinned: true });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: 5, archived: false, pinned: true });});it('does not query again for a chat the table has no row for', async () => {@@ -181,7 +229,7 @@ describe('ChatStateStoreService', () => {await svc.remember('s', 'd', { pinned: true }); // cap 1: evicts 'c' from the cacheexpect(svc.get('s', 'c')).toBeUndefined();await tick();- expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: false });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: null, archived: true, pinned: false });});describe('refreshSession (a start: another node may have written the rows since)', () => {@@ -374,7 +422,7 @@ describe('ChatStateStoreService', () => {const repo = makeRepo();const svc = svcWith(repo);await Promise.all([svc.remember('s', 'c', { archived: true }), svc.remember('s', 'c', { pinned: true })]);- expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: true });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: null, archived: true, pinned: true });expect(repo.rows.get(KEY('s', 'c'))).toMatchObject({ archived: true, pinned: true });});@@ -382,22 +430,227 @@ describe('ChatStateStoreService', () => {const repo = makeRepo();const svc = svcWith(repo);await Promise.all([svc.remember('s', 'c', { pinned: true }), svc.remember('s', 'c', { archived: false })]);- expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: false, pinned: true });+ expect(svc.get('s', 'c')).toMatchObject({ muteEndTime: null, archived: false, pinned: true });});- 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(() => Promise.reject(new Error('no such table'))),- upsert: jest.fn(() => Promise.reject(new Error('no such table'))),+ describe('fold (a chat state filed under more than one spelling)', () => {+ const PHONE = '[email protected]';+ const LID = '484848@lid';+ const NEW_END = Date.now() + 3_600_000;+ const OLD_END = Date.now() + 7_200_000;+ // The phone row is newer and only on disk; the older lid row is the one the cache holds.+ const coldNewerPhone = () =>+ makeRepo([+ { sessionId: 's', chatId: PHONE, muteEndTime: NEW_END, updatedAt: new Date(2000) },+ { sessionId: 's', chatId: LID, muteEndTime: OLD_END, updatedAt: new Date(1000) },+ ]);+ const warm = async (svc: ChatStateStoreService, chatId: string) => {+ svc.get('s', chatId);+ await tick();};++ it('merges onto the newest row read from the table, not the one the cache holds', async () => {+ const repo = coldNewerPhone();+ const svc = svcWith(repo);+ await warm(svc, LID);+ await svc.fold('s', PHONE, [LID], { archived: true });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ muteEndTime: NEW_END, archived: true });+ expect(svc.get('s', PHONE)).toMatchObject({ muteEndTime: NEW_END, archived: true });+ });++ it('keeps a field only the older row observed, so a pin and a mute on split rows both survive', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, muteEndTime: NEW_END, observed: 'muteEndTime', updatedAt: new Date(2000) },+ { sessionId: 's', chatId: LID, pinned: true, observed: 'pinned', updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ await svc.fold('s', PHONE, [LID], { muteEndTime: -1 });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ // The archive neither row saw stays unobserved, so a twin found later can still supply it.+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({+ muteEndTime: -1,+ pinned: true,+ archived: false,+ observed: 'muteEndTime,pinned',+ });+ });++ it('lets a newer unpin on a row that observed it outweigh an older pin, on a read and a fold', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, pinned: false, observed: 'pinned', updatedAt: new Date(2000) },+ { sessionId: 's', chatId: LID, pinned: true, updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ await svc.reload();+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({ pinned: false });+ await svc.fold('s', PHONE, [LID], { muteEndTime: -1 });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ pinned: false, muteEndTime: -1 });+ });++ it.each([+ [1000, 2000],+ [2000, 1000],+ ])(+ 'keeps a pin, an archive and a mute split across two rows written before rows kept what they observed (lid at %i, phone at %i)',+ async (lidAt, phoneAt) => {+ const repo = makeRepo([+ { sessionId: 's', chatId: LID, pinned: true, archived: true, observed: null, updatedAt: new Date(lidAt) },+ { sessionId: 's', chatId: PHONE, muteEndTime: -1, observed: null, updatedAt: new Date(phoneAt) },+ ]);+ const svc = svcWith(repo);+ await svc.reload();+ const kept = { pinned: true, archived: true, muteEndTime: -1 };+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject(kept);+ await svc.fold('s', PHONE, [LID], { muteEndTime: -1 });+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject(kept);+ },+ );++ it('records a clear written onto a row from before rows kept what they observed, so an older pin stays cleared', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: LID, pinned: true, observed: null, updatedAt: new Date(1000) },+ { sessionId: 's', chatId: PHONE, muteEndTime: -1, observed: null, updatedAt: new Date(2000) },+ ]);+ const svc = svcWith(repo);+ await svc.reload();+ await svc.remember('s', PHONE, { pinned: false });+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ muteEndTime: -1, observed: 'muteEndTime,pinned' });+ await svc.reload();+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({+ pinned: false,+ muteEndTime: -1,+ });+ });++ it('keeps what a newer twin observed when folding onto a row from before rows kept it', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, muteEndTime: -1, observed: null, updatedAt: new Date(1000) },+ { sessionId: 's', chatId: LID, pinned: false, observed: 'pinned', updatedAt: new Date(2000) },+ { sessionId: 's', chatId: 'older@lid', pinned: true, observed: null, updatedAt: new Date(500) },+ ]);+ const svc = svcWith(repo);+ await svc.fold('s', PHONE, [LID], { archived: true });+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ observed: 'muteEndTime,archived,pinned' });+ await svc.reload();+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', 'older@lid')!])).toMatchObject({ pinned: false });+ });++ it('writes a lone unpin for a chat with no row, so it can outweigh a pin on a twin row', async () => {+ const repo = makeRepo();+ const svc = svcWith(repo);+ await svc.remember('s', LID, { pinned: false });+ expect(repo.rows.get(KEY('s', LID))).toMatchObject({ pinned: false, observed: 'pinned' });+ await svc.remember('s', LID, { pinned: false });+ expect(repo.upsert).toHaveBeenCalledTimes(1);+ });++ it('writes no row for a patch that may not create one and only restates defaults', async () => {+ const repo = makeRepo([{ sessionId: 's', chatId: 'archived', archived: true, observed: 'archived' }]);+ const svc = svcWith(repo);+ await svc.remember('s', PHONE, { archived: false }, false);+ await svc.fold('s', PHONE, [LID], { archived: false, pinned: false }, false);+ expect(repo.findOne).toHaveBeenCalledTimes(2); // the phone key once, then known absent; the lid twin+ await svc.remember('s', 'archived', { archived: false }, false);+ expect([...repo.rows.keys()]).toEqual([KEY('s', 'archived')]);+ expect(repo.rows.get(KEY('s', 'archived'))).toMatchObject({ archived: false });+ });++ it('records what a patch carried on a row created after a failed read, so an unpin outweighs an older pin', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: LID, pinned: true, observed: 'pinned', updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ repo.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ await svc.remember('s', PHONE, { pinned: false });+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ pinned: false, observed: 'pinned' });+ await svc.reload();+ expect(mergeTwinStates([svc.get('s', PHONE)!, svc.get('s', LID)!])).toMatchObject({ pinned: false });+ });++ it('adds no row after a failed read for a patch that may not create one', async () => {+ const repo = makeRepo();+ const svc = svcWith(repo);+ repo.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ await svc.remember('s', PHONE, { archived: false }, false);+ expect(repo.rows.size).toBe(0);+ });++ it('carries a newer twin row onto the key and drops the twin', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, pinned: false, updatedAt: new Date(1000) },+ { sessionId: 's', chatId: LID, pinned: true, muteEndTime: -1, updatedAt: new Date(2000) },+ ]);+ const svc = svcWith(repo);+ 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, muteEndTime: -1, archived: true });+ });++ it('applies only the patch and keeps the twin when a row cannot be read', async () => {+ const repo = coldNewerPhone();+ const svc = svcWith(repo);+ repo.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ await svc.fold('s', PHONE, [LID], { archived: true });+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ muteEndTime: NEW_END, archived: true });+ expect(repo.rows.get(KEY('s', LID))).toMatchObject({ muteEndTime: OLD_END });+ });++ it('keeps the twin when the merged row cannot be written', async () => {+ const repo = makeRepo([{ sessionId: 's', chatId: LID, pinned: true, updatedAt: new Date(1000) }]);+ const svc = svcWith(repo);+ repo.upsert.mockRejectedValueOnce(new Error('SQLITE_BUSY'));+ await svc.fold('s', PHONE, [LID], { archived: true });+ expect(repo.rows.get(KEY('s', LID))).toMatchObject({ pinned: true });+ expect(repo.delete).not.toHaveBeenCalled();+ });++ it('folds a twin that already equals the row on the key without writing it again', async () => {+ const repo = makeRepo([+ { sessionId: 's', chatId: PHONE, pinned: true, updatedAt: new Date(2000) },+ { sessionId: 's', chatId: LID, pinned: true, updatedAt: new Date(1000) },+ ]);+ const svc = svcWith(repo);+ await svc.fold('s', PHONE, [LID], { pinned: true });+ expect(repo.upsert).not.toHaveBeenCalled();+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ });++ 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);+ await warm(svc, LID);+ const store = new BaileysSessionStore(undefined, 's', svc);+ store.addLidMappings([{ lid: LID, pn: PHONE }]);+ store.upsertChats([{ id: PHONE, name: 'Alice' }]);+ store.listChats();+ await tick();+ expect(repo.upsert).not.toHaveBeenCalled();+ expect(repo.delete).not.toHaveBeenCalled();+ expect(store.listChats()[0].muteExpiration).toBe(NEW_END); // the phone row has warmed by now+ store.upsertChats([{ id: PHONE, archived: true }]);+ await tick();+ await tick();+ expect([...repo.rows.keys()]).toEqual([KEY('s', PHONE)]);+ expect(repo.rows.get(KEY('s', PHONE))).toMatchObject({ muteEndTime: NEW_END, archived: true });+ expect(store.listChats()[0]).toMatchObject({ muteExpiration: NEW_END, archived: true });+ });+ });++ it('swallows a repo error on reload and remember (table may not exist yet)', async () => {+ const fail = () => Promise.reject(new Error('no such table'));+ const values = jest.fn();+ const qb = { insert: () => qb, values: (v: unknown) => (values(v), qb), orIgnore: () => qb, execute: fail };+ const repo = { find: jest.fn(fail), findOne: jest.fn(fail), update: jest.fn(fail), createQueryBuilder: () => qb };const svc = new ChatStateStoreService(repo as unknown as Repository<ChatState>);await expect(svc.reload()).resolves.toBeUndefined();await expect(svc.remember('s', 'c', { archived: true })).resolves.toBeUndefined();// The read failed too, so there is no merge base: only the patched column is written, and no// guessed state is cached (the chat reads from its live record until the table answers).- const [written] = repo.upsert.mock.calls[0] as unknown as [Record<string, unknown>];- expect(written).toMatchObject({ sessionId: 's', chatId: 'c', archived: true });+ const [written] = values.mock.calls[0] as [Record<string, unknown>];+ expect(written).toMatchObject({ sessionId: 's', chatId: 'c', archived: true, observed: 'archived' });expect(written).not.toHaveProperty('muteEndTime');expect(written).not.toHaveProperty('pinned');expect(svc.get('s', 'c')).toBeUndefined();diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsindex 22595a5f7..9aa4ad4d1 100644--- a/src/engine/adapters/baileys-chat-state-store.service.ts+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -6,8 +6,23 @@ import { createLogger } from '../../common/services/logger.service';import { resolveNonNegativeIntEnv } from '../../config/configuration';import { KeyedMutationQueue } from '../../common/utils/keyed-mutation-queue';-/** Durable chat app-state Baileys cannot re-deliver on reconnect. `muteEndTime` is canonical epoch ms. */-export type ChatStateValue = { muteEndTime: number | null; archived: boolean; pinned: boolean };+export type ChatStateField = 'muteEndTime' | 'archived' | 'pinned';+const FIELDS: ChatStateField[] = ['muteEndTime', 'archived', 'pinned'];++/**+ * Durable chat app-state Baileys cannot re-deliver on reconnect. `muteEndTime` is canonical epoch ms.+ * `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+ * patch never sets it.+ */+export type ChatStateValue = {+ muteEndTime: number | null;+ archived: boolean;+ pinned: boolean;+ updatedAt?: number;+ observed?: ChatStateField[];+};/*** Narrow read/write port over the persisted `chat_states` table. The Baileys session store depends on@@ -17,8 +32,25 @@ export type ChatStateValue = { muteEndTime: number | null; archived: boolean; piexport interface ChatStateStore {/** Sync read from the in-memory mirror; undefined = no persisted state for this chat (defaults apply). */get(sessionId: string, chatId: string): ChatStateValue | undefined;- /** Write-through, last-write-wins: merge the patch into the stored state and persist. */- remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void>;+ /**+ * Write-through, last-write-wins: merge the patch into the stored state and persist. With `create`+ * false, a patch that only restates defaults writes nothing for a chat with no row (an update that+ * merely carries the field, like the unarchive every message brings, must not add a row per chat).+ */+ remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>, create?: boolean): Promise<void>;+ /**+ * Like {@link remember}, but first folds the rows filed under `twins` (other spellings of the chat)+ * onto `chatId`: all the rows, read from the table and merged by {@link mergeTwinStates}, are the+ * merge base, and the twin rows are deleted once the result is written. `create` applies as in+ * {@link remember} when no twin row is found.+ */+ fold(+ sessionId: string,+ chatId: string,+ twins: string[],+ patch: Partial<ChatStateValue>,+ create?: boolean,+ ): Promise<void>;/** (Re)load the in-memory mirror from the table (boot, and after a full-replace restore). */reload(): Promise<void>;/** Forget every chat state of one session (an unlink: the next account to link it starts clean). */@@ -30,6 +62,48 @@ export interface ChatStateStore {}const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false };++function fromRow(row: ChatState): ChatStateValue {+ return {+ muteEndTime: row.muteEndTime,+ archived: row.archived,+ pinned: row.pinned,+ updatedAt: row.updatedAt?.getTime(),+ observed: row.observed == null ? undefined : (row.observed.split(',').filter(Boolean) as ChatStateField[]),+ };+}++/**+ * Whether a row saw a value for the field. A row written before `observed` was kept saw its set fields+ * only: such a row was created by the first patch that set something, so a default there almost always+ * means the field never reached it. Reading every field of it as seen let a legacy row holding only a+ * mute outweigh an older legacy pin. The first patch written onto a legacy row after it has been read+ * records its observed list (a blind write, made when the row could not be read, does not), so the+ * cost is limited to a clear made before the column existed or written blind: it loses to an older+ * set value on a twin row.+ */+const saw = (v: ChatStateValue, field: ChatStateField): boolean =>+ v.observed ? v.observed.includes(field) : v[field] !== DEFAULT_STATE[field];++/**+ * One chat's rows under several spellings, merged field by field: each field comes from the newest row+ * that observed it (see {@link saw}), else from the newest row. A row created by a lone pin carries a+ * default mute it never saw, so taking the newest row whole would drop a mute kept on the other;+ * favouring any set value instead would bring back a pin the newer row explicitly cleared. The result+ * observed what any of the rows did.+ */+export function mergeTwinStates(rows: ChatStateValue[]): ChatStateValue | undefined {+ if (!rows.length) return undefined;+ const sorted = [...rows].sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));+ const out: ChatStateValue = { ...sorted[0] };+ for (const field of FIELDS) {+ const from = sorted.find(r => saw(r, field));+ if (from) Object.assign(out, { [field]: from[field] });+ }+ out.observed = FIELDS.filter(f => sorted.some(r => saw(r, f)));+ return out;+}+const SEP = '\u0000'; // a null byte never appears in a session name or JID, so the join cannot collide// One global LRU across all sessions, default 5000, matching the other engine maps. A@@ -100,11 +174,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {// Oldest first, so the newest row ends at the most-recent end of the LRU rather than the first// one evicted (the query is DESC only so `take` keeps the newest rows).for (const row of [...rows].reverse()) {- this.index(this.key(row.sessionId, row.chatId), {- muteEndTime: row.muteEndTime,- archived: row.archived,- pinned: row.pinned,- });+ this.index(this.key(row.sessionId, row.chatId), fromRow(row));}if (this.loadWasWhole(rows.length, seq)) {for (const row of rows) this.completeSessions.add(row.sessionId);@@ -133,29 +203,97 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {* Serialized per chat: the caller does not await, so two patches for an uncached chat would otherwise* both merge onto the same pre-change row and the later full-row write would drop the earlier patch.*/- remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>): Promise<void> {+ remember(sessionId: string, chatId: string, patch: Partial<ChatStateValue>, create = true): Promise<void> {const k = this.key(sessionId, chatId);return new Promise<void>((resolve, reject) =>- this.writes.enqueue(k, () => this.applyPatch(k, sessionId, chatId, patch).then(resolve, reject)),+ this.writes.enqueue(k, () => this.applyPatch(k, sessionId, chatId, patch, create).then(() => resolve(), reject)),);}- private async applyPatch(+ fold(+ sessionId: string,+ chatId: string,+ twins: string[],+ patch: Partial<ChatStateValue>,+ create = true,+ ): Promise<void> {+ const k = this.key(sessionId, chatId);+ return new Promise<void>((resolve, reject) =>+ this.writes.enqueue(k, () => this.applyFold(k, sessionId, chatId, twins, patch, create).then(resolve, reject)),+ );+ }++ /**+ * The rows merge by {@link mergeTwinStates}, and each row is read from the table when the cache does+ * not hold it: a key the cache lacks may still have a newer row on disk, so a cached twin alone must+ * not win. When a read fails the merge cannot be told, so only the patch is applied and the twins stay;+ * they stay too when the merged row could not be written, or they would be its only copy on disk.+ */+ private async applyFold(k: string,sessionId: string,chatId: string,+ twins: string[],patch: Partial<ChatStateValue>,+ create: boolean,): Promise<void> {+ const rows: ChatStateValue[] = [];+ const found: string[] = [];+ try {+ const own = await this.peek(k, sessionId, chatId);+ if (own) rows.push(own);+ for (const twin of twins) {+ const v = await this.peek(this.key(sessionId, twin), sessionId, twin);+ if (!v) continue;+ found.push(twin);+ rows.push(v);+ }+ } catch {+ await this.applyPatch(k, sessionId, chatId, patch, create);+ return;+ }+ if (!found.length) {+ await this.applyPatch(k, sessionId, chatId, patch, create);+ return;+ }+ // Only the fields some row observed are carried, so the folded row still tells them from defaults.+ const merged = mergeTwinStates(rows)!;+ const base = Object.fromEntries(FIELDS.filter(f => saw(merged, f)).map(f => [f, merged[f]]));+ if (await this.applyPatch(k, sessionId, chatId, { ...base, ...patch })) {+ await this.forget(sessionId, found);+ }+ }++ /** The row as the table holds it: the cache when it has the key or knows it absent, else a query. */+ private async peek(k: string, sessionId: string, chatId: string): Promise<ChatStateValue | undefined> {+ const cached = this.states.get(k);+ if (cached || this.completeSessions.has(sessionId) || this.absent.has(k)) return cached;+ const row = await this.repo.findOne({ where: { sessionId, chatId } });+ return row ? fromRow(row) : undefined;+ }++ /** True once the table holds the result: written, or already equal to it. */+ private async applyPatch(+ k: string,+ sessionId: string,+ chatId: string,+ patch: Partial<ChatStateValue>,+ create = true,+ ): Promise<boolean> {// 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. A read that FAILS is not an absent row: with no base to- // merge onto, only the patched columns are written (upsert leaves the others as persisted) and the- // cache stays cold, so the next read warms from the table instead of from a guess.+ // merge onto, only the patched columns are written (see persistBlind) and the cache stays cold, so+ // the next read warms from the table instead of from a guess.let existing = this.states.get(k);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]);+ if (restatesDefaults && (this.completeSessions.has(sessionId) || this.absent.has(k))) return true;let row: ChatState | null;try {row = await this.repo.findOne({ where: { sessionId, chatId } });@@ -163,33 +301,86 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {// Persisted but not indexed, so the session's cache no longer holds all of its rows.this.writeSeq++;this.completeSessions.delete(sessionId);- await this.persist(sessionId, chatId, patch);+ const ok = await this.persistBlind(sessionId, chatId, patch, !restatesDefaults);this.absent.delete(k);- return;+ return ok;}- existing = row ? { muteEndTime: row.muteEndTime, archived: row.archived, pinned: row.pinned } : DEFAULT_STATE;+ if (!row && restatesDefaults) {+ this.markAbsent(k);+ return true;+ }+ existing = row ? fromRow(row) : { ...DEFAULT_STATE, observed: [] };}- const next: ChatStateValue = { ...existing, ...patch };+ // Every patched field is recorded as observed, on a new row and on a legacy one alike, so a lone+ // unpin still writes: it has to outweigh an older pin on a twin row of the chat.+ const existingRow = existing;+ 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+ existing.pinned === next.pinned &&+ FIELDS.every(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 hit- return; // nothing changed against the current state; skip the write that would just churn updatedAt+ return true; // nothing changed against the current state; skip the write that would just churn updatedAt}+ const at = new Date();+ next.updatedAt = at.getTime();this.writeSeq++;this.index(k, next);- await this.persist(sessionId, chatId, next);+ return this.persist(sessionId, chatId, next, at);+ }++ private async persist(+ sessionId: string,+ chatId: string,+ values: Partial<ChatStateValue>,+ at = new Date(),+ ): Promise<boolean> {+ const columns: Record<string, unknown> = { ...values, observed: values.observed?.join(',') };+ delete columns.updatedAt;+ try {+ await this.repo.upsert({ sessionId, chatId, ...columns, updatedAt: at }, ['sessionId', 'chatId']);+ return true;+ } catch (err) {+ this.logger.warn(+ `Failed to persist chat state for ${chatId}: ${err instanceof Error ? err.message : String(err)}`,+ );+ return false;+ }}- private async persist(sessionId: string, chatId: string, values: Partial<ChatStateValue>): Promise<void> {+ /**+ * Writes the patched columns when the row could not be read. A new row records what the patch+ * carried, like any new row, or its unset columns would read as observed defaults; an existing row+ * keeps its own observed list. `create` false only updates a row that exists.+ */+ private async persistBlind(+ sessionId: string,+ chatId: string,+ patch: Partial<ChatStateValue>,+ create: boolean,+ ): Promise<boolean> {+ const carried = FIELDS.filter(f => Object.hasOwn(patch, f));+ const columns = Object.fromEntries(carried.map(f => [f, patch[f]]));+ const updatedAt = new Date();try {- await this.repo.upsert({ sessionId, chatId, ...values, updatedAt: new Date() }, ['sessionId', 'chatId']);+ if (create) {+ await this.repo+ .createQueryBuilder()+ .insert()+ .values({ sessionId, chatId, ...columns, observed: carried.join(','), updatedAt })+ .orIgnore()+ .execute();+ }+ await this.repo.update({ sessionId, chatId }, { ...columns, updatedAt });+ return true;} catch (err) {this.logger.warn(`Failed to persist chat state for ${chatId}: ${err instanceof Error ? err.message : String(err)}`,);+ return false;}}@@ -257,11 +448,7 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {}for (const row of [...rows].reverse()) {// Oldest first, as in reload.- this.index(this.key(sessionId, row.chatId), {- muteEndTime: row.muteEndTime,- archived: row.archived,- pinned: row.pinned,- });+ this.index(this.key(sessionId, row.chatId), fromRow(row));}// Marked after the loop: indexing these rows can evict other sessions' keys, never this one's.if (this.loadWasWhole(rows.length, seq)) this.completeSessions.add(sessionId);@@ -284,19 +471,20 @@ export class ChatStateStoreService implements ChatStateStore, OnModuleInit {.findOne({ where: { sessionId, chatId } }).then(row => {if (this.states.has(k)) return;- if (row) {- this.index(k, { muteEndTime: row.muteEndTime, archived: row.archived, pinned: row.pinned });- } else {- this.absent.add(k);- if (this.maxEntries && this.absent.size > this.maxEntries) {- this.absent.delete(this.absent.values().next().value!);- }- }+ if (row) this.index(k, fromRow(row));+ else this.markAbsent(k);}).catch(() => undefined).finally(() => this.pendingLookups.delete(k));}+ private markAbsent(k: string): void {+ this.absent.add(k);+ if (this.maxEntries && this.absent.size > this.maxEntries) {+ this.absent.delete(this.absent.values().next().value!);+ }+ }+private index(k: string, value: ChatStateValue): void {this.absent.delete(k);this.states.delete(k); // re-insert so the entry moves to the most-recent end even on updatediff --git a/src/engine/adapters/baileys-chat-state.entity.ts b/src/engine/adapters/baileys-chat-state.entity.tsindex 936e91cad..267b1498f 100644--- a/src/engine/adapters/baileys-chat-state.entity.ts+++ b/src/engine/adapters/baileys-chat-state.entity.ts@@ -19,7 +19,12 @@ export class ChatState {@PrimaryColumn()sessionId!: string;- /** Chat id in the engine's stored (raw Baileys) dialect, the same key `upsertChats` uses. */+ /**+ * Chat id in the raw Baileys dialect, one row per conversation: `<phone>@s.whatsapp.net` for a person+ * (also when WhatsApp synced the state under their lid, once the lid resolves), `<lid>@lid` while it+ * does not, and a group's own id. A row filed under a lid twin is folded onto the phone JID on the+ * chat's next change.+ */@PrimaryColumn()chatId!: string;@@ -37,6 +42,16 @@ export class ChatState {@Column({ type: 'boolean', default: false })pinned!: boolean;+ /**+ * The state fields this row has observed, comma-separated (`muteEndTime`, `archived`, `pinned`); the+ * others hold their default only because the row was created by a patch that did not carry them.+ * Null on a row written before this column existed, read as having observed its set fields. Lets two+ * rows of one chat merge field by field without mistaking an explicit unpin, unarchive or unmute for+ * "not seen".+ */+ @Column({ type: 'varchar', nullable: true })+ observed!: string | null;+@UpdateDateColumn()updatedAt!: Date;}diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 8bd4b7c97..8ced7cf7b 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -1,20 +1,39 @@import { BaileysSessionStore } from './baileys-session-store';import type { LidMappingStore } from '../identity/lid-mapping-store.service';-import type { ChatStateStore, ChatStateValue } from './baileys-chat-state-store.service';+import {+ mergeTwinStates,+ type ChatStateField,+ type ChatStateStore,+ type ChatStateValue,+} from './baileys-chat-state-store.service';import { userPart } from '../identity/wa-id';/** In-memory ChatStateStore for tests: remember() applies synchronously so a following read sees it. */class FakeChatStateStore implements ChatStateStore {readonly rows = new Map<string, ChatStateValue>();+ private clock = 1_000_000;private key(s: string, c: string): string {return `${s}\u0000${c}`;}get(s: string, c: string): ChatStateValue | undefined {return this.rows.get(this.key(s, c));}- remember(s: string, c: string, patch: Partial<ChatStateValue>): Promise<void> {- const existing = this.rows.get(this.key(s, c)) ?? { muteEndTime: null, archived: false, pinned: false };- this.rows.set(this.key(s, c), { ...existing, ...patch });+ remember(s: string, c: string, patch: Partial<ChatStateValue>, create = true): Promise<void> {+ // Same bookkeeping as the real store: a new row observes only what the patch carries, and a patch+ // that may not create one writes nothing when it only restates defaults.+ const defaults: Partial<ChatStateValue> = { muteEndTime: null, archived: false, pinned: false };+ const restates = (Object.keys(patch) as ChatStateField[]).every(f => patch[f] === defaults[f]);+ if (!create && restates && !this.rows.has(this.key(s, c))) return Promise.resolve();+ const existing = this.rows.get(this.key(s, c)) ?? {+ muteEndTime: null,+ archived: false,+ pinned: false,+ observed: [],+ };+ const observed = existing.observed && [+ ...new Set([...existing.observed, ...(Object.keys(patch) as ChatStateField[])]),+ ];+ this.rows.set(this.key(s, c), { ...existing, ...patch, observed, updatedAt: ++this.clock });return Promise.resolve();}reload(): Promise<void> {@@ -23,6 +42,18 @@ class FakeChatStateStore implements ChatStateStore {clearSession(): Promise<void> {return Promise.resolve();}+ /** Same contract as the real store: the rows merged field by field are the base, the twin rows go. */+ fold(s: string, c: string, twins: string[], patch: Partial<ChatStateValue>, create = true): Promise<void> {+ 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 base = merged+ ? Object.fromEntries(fields.filter(f => !merged.observed || merged.observed.includes(f)).map(f => [f, merged[f]]))+ : {};+ for (const t of found) this.rows.delete(this.key(s, t));+ return this.remember(s, c, { ...base, ...patch });+ }forget(s: string, chatIds: string[]): Promise<void> {for (const c of chatIds) this.rows.delete(this.key(s, c));return Promise.resolve();@@ -298,7 +329,7 @@ describe('BaileysSessionStore', () => {s.upsertChats([historyChat({})]);expect(s.listChats()[0]).toMatchObject({ muted: true, archived: true, pinned: true });}- expect(fake.get(SID, CHAT)).toEqual({ muteEndTime: -1, archived: true, pinned: true });+ expect(fake.get(SID, CHAT)).toMatchObject({ muteEndTime: -1, archived: true, pinned: true });});it('a history chat that omits the fields writes no row for a chat never seen', () => {@@ -308,7 +339,7 @@ describe('BaileysSessionStore', () => {it('a history chat that carries a field on the wire still persists it', () => {newStore().upsertChats([historyChat({ pinned: 5 })]);- expect(fake.get(SID, CHAT)).toEqual({ muteEndTime: null, archived: false, pinned: true });+ expect(fake.get(SID, CHAT)).toMatchObject({ muteEndTime: null, archived: false, pinned: true });});it('normalizes a seconds-scale muteEndTime to ms on persist', () => {@@ -752,6 +783,313 @@ describe('BaileysSessionStore', () => {});});+ describe('one chat known under both its phone number and its lid', () => {+ const SID = 'sess-1';+ const PHONE = '[email protected]';+ const LID = '484848@lid';+ const K = (c: string) => `${SID}\u0000${c}`;+ let fake: FakeChatStateStore;+ beforeEach(() => {+ fake = new FakeChatStateStore();+ });+ const newStore = () => new BaileysSessionStore(undefined, SID, fake);+ const flush = () => new Promise(resolve => setImmediate(resolve));+ // A decoded proto.Conversation: the fields default to null on the prototype.+ const historyChat = (id: string) =>+ Object.assign(Object.create({ archived: null, pinned: null, muteEndTime: null }) as object, {+ id,+ name: 'Alice',+ }) as Record<string, unknown>;++ it('lists one row and keeps a state WhatsApp syncs under the lid, across a restart', () => {+ const s = newStore();+ s.upsertChats([historyChat(PHONE)]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ s.upsertChats([+ { id: LID, pinned: 1700000000 },+ { id: LID, archived: true },+ { id: LID, muteEndTime: -1 },+ ]);+ const expected = { id: '[email protected]', name: 'Alice', pinned: true, archived: true, muted: true };+ expect(s.listChats()).toEqual([expect.objectContaining(expected)]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);++ const restarted = newStore();+ restarted.addLidMappings([{ lid: LID, pn: PHONE }]);+ restarted.upsertChats([historyChat(PHONE)]);+ expect(restarted.listChats()).toEqual([expect.objectContaining(expected)]);+ });++ it('reads a state filed under the lid before the mapping was known, and folds it on the next change', async () => {+ const s = newStore();+ s.upsertChats([{ id: LID, pinned: 3 }]);+ expect([...fake.rows.keys()]).toEqual([K(LID)]);+ s.upsertChats([{ id: PHONE, name: 'Alice' }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', name: 'Alice', pinned: true })]);+ await flush();+ expect([...fake.rows.keys()]).toEqual([K(LID)]); // a listing writes nothing+ // A later mute through either spelling folds the lid row onto the phone row.+ s.upsertChats([{ id: LID, muteEndTime: -1 }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ pinned: true, muted: true });+ });++ it('adds no row for the unarchive a message carries, and still clears an archived chat with it', () => {+ const s = newStore();+ const G = '[email protected]';+ s.upsertChats([{ id: G, archived: true }]);+ const message = { archived: false, readOnly: false, conversationTimestamp: 60, unreadCount: 1 };+ s.upsertChats([+ { id: PHONE, ...message },+ { id: G, ...message },+ ]);+ expect([...fake.rows.keys()]).toEqual([K(G)]);+ expect(fake.get(SID, G)).toMatchObject({ archived: false });+ s.upsertChats([{ id: LID, pinned: null }]);+ expect(fake.get(SID, LID)).toMatchObject({ pinned: false, observed: ['pinned'] });+ });++ it('finds the lid twin of one state update without indexing every mapping', () => {+ const s = newStore();+ s.upsertChats([{ id: LID, pinned: 3 }]);+ s.addLidMappings([+ { lid: LID, pn: PHONE },+ { lid: '515151@lid', pn: '[email protected]' },+ ]);+ const index = jest.spyOn(s as unknown as { lidsByPhone(): Map<string, string[]> }, 'lidsByPhone');+ s.upsertChats([+ { id: '[email protected]', archived: false },+ { id: PHONE, muteEndTime: -1 },+ ]);+ expect(index).not.toHaveBeenCalled();+ expect([...fake.rows.keys()].sort()).toEqual([K('[email protected]'), K(PHONE)]);+ expect(fake.get(SID, PHONE)).toMatchObject({ pinned: true, muteEndTime: -1 });+ });++ const HOUR = 3_600_000;+ const soon = Date.now() + HOUR;+ const later = Date.now() + 2 * HOUR;++ it.each([+ [1000, 2000, later],+ [2000, 1000, soon],+ ])('lets the newer of two rows already on disk win (phone at %i, lid at %i)', async (phoneAt, lidAt, end) => {+ fake.rows.set(K(PHONE), { muteEndTime: soon, archived: false, pinned: false, updatedAt: phoneAt });+ fake.rows.set(K(LID), { muteEndTime: later, archived: false, pinned: false, updatedAt: lidAt });+ const s = newStore();+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ s.upsertChats([historyChat(PHONE)]);+ expect(s.listChats()[0].muteExpiration).toBe(end);+ await flush();+ expect([...fake.rows.keys()]).toEqual([K(PHONE), K(LID)]);+ s.upsertChats([{ id: PHONE, archived: true }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(fake.get(SID, PHONE)).toMatchObject({ muteEndTime: end, archived: true });+ });++ it('keeps a pin on the older row when the newer row of the chat holds only a mute', () => {+ const [mute, pin] = [['muteEndTime'], ['pinned']] as ChatStateField[][];+ fake.rows.set(K(PHONE), { muteEndTime: later, archived: false, pinned: false, updatedAt: 2000, observed: mute });+ fake.rows.set(K(LID), { muteEndTime: null, archived: false, pinned: true, updatedAt: 1000, observed: pin });+ const s = newStore();+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ s.upsertChats([historyChat(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ pinned: true, muted: true, muteExpiration: later });+ s.upsertChats([{ id: PHONE, archived: true }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(fake.get(SID, PHONE)).toMatchObject({ muteEndTime: later, pinned: true, archived: true });+ });++ it('lets a later unpin synced under the unresolved lid outweigh the pin on the phone row', () => {+ const s = newStore();+ s.upsertChats([{ id: PHONE, pinned: 2 }]);+ s.upsertChats([{ id: LID, pinned: 0 }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', pinned: false })]);+ s.upsertChats([{ id: PHONE, muteEndTime: -1 }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ pinned: false, muted: true });+ });++ it('keeps a pin on the older of two rows written before rows kept what they observed', () => {+ fake.rows.set(K(PHONE), { muteEndTime: -1, archived: false, pinned: false, updatedAt: 2000 });+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: true, updatedAt: 1000 });+ const s = newStore();+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ s.upsertChats([historyChat(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ pinned: true, archived: true, muted: true });+ s.upsertChats([{ id: PHONE, muteEndTime: -1 }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ pinned: true, archived: true, muted: true });+ });++ it('writes nothing while listing a chat that still has a lid twin row', () => {+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: false });+ const s = newStore();+ s.upsertChats([{ id: PHONE }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ const writes = ['remember', 'fold', 'forget'].map(m => jest.spyOn(fake, m as 'remember'));+ expect(s.listChats()[0].archived).toBe(true);+ for (const w of writes) expect(w).not.toHaveBeenCalled();+ });++ it('reads the own lid row of a lid-keyed chat whose phone only its contact record knows', () => {+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: true });+ const s = newStore();+ s.upsertContacts([{ id: LID, phoneNumber: PHONE }]);+ s.upsertChats([{ id: LID }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true, pinned: true })]);+ s.upsertChats([{ id: LID, muteEndTime: -1 }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ expect(s.listChats()[0]).toMatchObject({ archived: true, pinned: true, muted: true });+ });++ it.each([+ ['a phone-keyed chat record', [PHONE]],+ ['both chat records, the phone one first', [PHONE, LID]],+ ])('reads, folds and forgets a lid row that only a lid-keyed contact maps, with %s', (_label, ids) => {+ fake.rows.set(K(LID), { muteEndTime: null, archived: true, pinned: true });+ const s = newStore();+ s.upsertContacts([{ id: LID, phoneNumber: PHONE }]);+ s.upsertChats(ids.map(id => ({ id })));+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', archived: true, pinned: true })]);+ s.upsertChats([{ id: PHONE, muteEndTime: -1 }]);+ expect([...fake.rows.keys()]).toEqual([K(PHONE)]);+ 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(s.listChats()).toEqual([]);+ });++ it('reads the lid record row of a merged chat once the lid mapping is evicted', () => {+ const cap = process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES;+ process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES = '2';+ try {+ fake.rows.set(K(LID), { muteEndTime: null, archived: false, pinned: true });+ const s = newStore();+ s.upsertContacts([{ id: LID, phoneNumber: PHONE, name: 'Alice' }]);+ s.addLidMappings([+ { lid: '1@lid', pn: '[email protected]' },+ { lid: '2@lid', pn: '[email protected]' },+ ]);+ s.upsertChats([{ id: PHONE }, { id: LID }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', pinned: true })]);+ } finally {+ if (cap === undefined) delete process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES;+ else process.env.BAILEYS_SESSION_STORE_MAX_ENTRIES = cap;+ }+ });++ 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()),+ };+ const s = new BaileysSessionStore(lidStore, SID, fake);+ s.removeChats([deleted]);+ await flush();+ expect(fake.rows.size).toBe(0);+ 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 });+ const lidStore = {+ getCached: jest.fn((lid: string) => (lid === '484848' ? '628111' : undefined)),+ resolveLid: jest.fn(() => null),+ lidsForPhone: jest.fn((phone: string) => (phone === '628111' ? ['484848'] : [])),+ remember: jest.fn(() => Promise.resolve()),+ };+ const s = new BaileysSessionStore(lidStore, SID, fake);+ s.upsertChats([{ id: PHONE }]);+ expect(s.listChats()[0].archived).toBe(true);+ });++ it('writes nothing while listing a chat that has no twin row', () => {+ const s = newStore();+ s.upsertChats([{ id: PHONE, pinned: 2 }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ const remember = jest.spyOn(fake, 'remember');+ const forget = jest.spyOn(fake, 'forget');+ s.listChats();+ expect(remember).not.toHaveBeenCalled();+ expect(forget).not.toHaveBeenCalled();+ });++ it.each([+ ['phone first', [PHONE, LID]],+ ['lid first', [LID, PHONE]],+ ])('merges the two records into one row, whichever arrived first (%s)', (_order, ids) => {+ const s = new BaileysSessionStore();+ for (const id of ids) {+ s.upsertChats([id === LID ? { id, name: 'Alice', unreadCount: 2, conversationTimestamp: 50 } : { id }]);+ }+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', name: 'Alice', unreadCount: 2, timestamp: 50 }),+ ]);+ });++ it('takes the unread count from the more recently active of the two records', () => {+ const s = new BaileysSessionStore();+ s.upsertChats([+ { id: PHONE, name: 'Alice', unreadCount: 0, conversationTimestamp: 10 },+ { id: LID, unreadCount: 2, conversationTimestamp: 50 },+ ]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([expect.objectContaining({ id: '[email protected]', unreadCount: 2, timestamp: 50 })]);+ });++ it('shows a preview filed under the lid before the mapping on the merged row, newest first', () => {+ const s = new BaileysSessionStore();+ const msg = (remoteJid: string, id: string, ts: number) => ({+ key: { remoteJid, fromMe: false, id },+ message: { conversation: id },+ messageTimestamp: ts,+ });+ s.upsertChats([{ id: PHONE }]);+ s.recordMessage(msg(LID, 'VIA_LID', 100));+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.listChats()).toEqual([+ expect.objectContaining({ id: '[email protected]', timestamp: 100, lastMessage: 'VIA_LID' }),+ ]);+ s.recordMessage(msg(PHONE, 'VIA_PHONE', 50));+ expect(s.listChats()[0]).toMatchObject({ timestamp: 100, lastMessage: 'VIA_LID' });+ });++ it('keeps distinct chats apart', () => {+ const s = new BaileysSessionStore();+ s.upsertChats([{ id: PHONE }, { id: '[email protected]' }, { id: '999@lid' }, { id: '[email protected]' }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ 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', () => {+ const s = newStore();+ s.upsertChats([{ id: PHONE, pinned: 2 }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ s.removeChats([LID]);+ expect(fake.rows.size).toBe(0);+ });++ it('finds the disappearing timer a lid-keyed chat record carries from the @c.us id', () => {+ const s = new BaileysSessionStore();+ s.upsertChats([{ id: LID, ephemeralExpiration: 86400 }]);+ s.addLidMappings([{ lid: LID, pn: PHONE }]);+ expect(s.getEphemeralExpiration('[email protected]')).toBe(86400);+ });+ });+describe('persistent lid->phone table', () => {const makeFakeLidStore = () => {const map = new Map<string, string | null>();diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex b8352434c..9c923257c 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -2,7 +2,7 @@ import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey } from '@import { ChatSummary, Contact } from '../interfaces/whatsapp-engine.interface';import { chatKind, parseWaId, toNeutralJid as canonicalizeWaId, userPart } from '../identity/wa-id';import type { LidMappingStore } from '../identity/lid-mapping-store.service';-import type { ChatStateStore, ChatStateValue } from './baileys-chat-state-store.service';+import { mergeTwinStates, type ChatStateStore, type ChatStateValue } from './baileys-chat-state-store.service';import { resolveNonNegativeIntEnv } from '../../config/configuration';interface LastMessage {@@ -254,10 +254,12 @@ export class BaileysSessionStore {// Capture a lid->phone pair from the merged record (lid + phone can arrive in separate updates).// `phoneNumber` is the authoritative PN field; fall back to `id` itself only when it's already// in the phone dialect (a lid-only contact's `id` is `<lid>@lid`, which is not a usable phone).+ // A record keyed by its lid carries the lid side in `id` and usually has no `lid` field.const phone = merged.phoneNumber ?? (merged.id.endsWith('@s.whatsapp.net') ? merged.id : undefined);- if (merged.lid && phone) {- this.lidToPn.set(merged.lid, phone);- this.persistLidMapping(merged.lid, phone);+ const lid = merged.lid ?? (parseWaId(merged.id).kind === 'lid' ? merged.id : undefined);+ if (lid && phone) {+ this.lidToPn.set(lid, phone);+ this.persistLidMapping(lid, phone);}}}@@ -311,10 +313,42 @@ export class BaileysSessionStore {this.lastInbound.delete(key);}if (keys.size && this.chatStateStore && this.sessionId) {- void this.chatStateStore.forget(this.sessionId, [...keys]);+ void this.forgetChatState(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.+ */+ private async forgetChatState(+ store: ChatStateStore,+ sessionId: string,+ ids: string[],+ keys: Set<string>,+ ): Promise<void> {+ const forgotten = store.forget(sessionId, [...keys]);+ const extra = new Set<string>();+ for (const id of ids) {+ const parsed = parseWaId(id);+ try {+ if (parsed.kind === 'lid') {+ const phone = await this.lidStore?.findPhoneForLid?.(id);+ if (phone) extra.add(`${userPart(phone)}@s.whatsapp.net`);+ } else if (parsed.kind === 'user') {+ for (const lid of (await this.lidStore?.findLidsForPhone?.(parsed.userPart)) ?? []) extra.add(`${lid}@lid`);+ }+ } catch {+ // The table cannot be read; the keys the caches knew are already going.+ }+ }+ await forgotten;+ const missed = [...extra].filter(k => !keys.has(k));+ if (missed.length) await store.forget(sessionId, missed);+ }+addLidMappings(mappings: { lid?: string; pn?: string }[] = []): void {for (const m of mappings) {if (m.lid && m.pn) {@@ -543,8 +577,32 @@ export class BaileysSessionStore {return unnamed ? this.toNeutralContact(unnamed) : null;}+ /**+ * One row per conversation. A contact WhatsApp migrated to a lid can hold two records, one keyed by+ * phone and one by lid (Baileys files an update under whichever id its source carried, and a record+ * created before the lid->phone mapping was learned stays where it is), and both project to the same+ * neutral id; listing each put two rows sharing one id into the answer. They fold like contacts do:+ * the phone-keyed record is primary, the twin {@link chatJid} routes app-state writes to, and a field+ * the primary lacks comes from the other. The preview is the newest message filed under any key that+ * projects to the row, indexed in one pass rather than a twin scan per chat.+ *+ * Every loop is over a SNAPSHOT: projecting an id resolves a lid through maps whose read moves the+ * entry to the most-recent end, so a live iterator would hand the same entry back forever.+ */listChats(): ChatSummary[] {- return [...this.chats.values()].map(c => this.toNeutralChat(c));+ const lidIndex = this.lidsByPhone();+ const previews = new Map<string, LastMessage>();+ for (const [key, m] of [...this.lastMessages.entries()]) {+ const id = this.toNeutralJid(key);+ const seen = previews.get(id);+ if (!seen || m.timestamp > seen.timestamp) previews.set(id, m);+ }+ const byId = new Map<string, Chat[]>();+ for (const c of [...this.chats.values()]) {+ const id = this.toNeutralJid(c.id!);+ byId.set(id, [...(byId.get(id) ?? []), c]);+ }+ return [...byId].map(([id, records]) => this.toNeutralChat(id, records, previews.get(id), lidIndex));}/**@@ -601,7 +659,10 @@ export class BaileysSessionStore {}// Fallback to the chat object's own timer for sessions/engines that do surface it on `chats.*`.const chat =- this.chats.get(chatId) ?? this.chats.get(this.toEngineJid(chatId)) ?? this.chats.get(this.toNeutralJid(chatId));+ this.chats.get(chatId) ??+ this.chats.get(this.toEngineJid(chatId)) ??+ this.chats.get(this.toNeutralJid(chatId)) ??+ this.chats.get(this.chatKey(chatId));const exp = chat?.ephemeralExpiration;return typeof exp === 'number' && exp > 0 ? exp : undefined;}@@ -674,22 +735,43 @@ export class BaileysSessionStore {};}- private toNeutralChat(c: Chat): ChatSummary {+ /**+ * Project the records that share neutral `id` (usually one) into a row. `last` is the newest preview+ * filed under any of their keys.+ */+ private toNeutralChat(+ id: string,+ records: Chat[],+ last: LastMessage | undefined,+ lidIndex: Map<string, string[]>,+ ): ChatSummary {// 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.- const id = c.id!;- const last = this.lastMessages.get(id);+ // is provably keyed by a real id. Phone-keyed first, then the lower raw id: stable across calls.+ const [c, ...others] = [...records].sort((a, b) =>+ isPhoneKeyed(a.id!) !== isPhoneKeyed(b.id!) ? (isPhoneKeyed(a.id!) ? -1 : 1) : a.id! < b.id! ? -1 : 1,+ );+ const rawId = c.id!;// Mute/archive/pin come from the persisted store when it has this chat (it survives a reconnect- // Baileys cannot resync), else from the live record. A `null` muteEndTime there means unmuted.- const st = this.sessionId ? this.chatStateStore?.get(this.sessionId, id) : undefined;+ // Baileys cannot resync), else from the primary's live record. A `null` muteEndTime means unmuted.+ const st = this.chatState(+ rawId,+ records.map(r => r.id!),+ lidIndex,+ );return {- id: this.toNeutralJid(id),- name: c.name ?? this.resolveContactName(id),- isGroup: id.endsWith('@g.us'),- kind: chatKind(this.toNeutralJid(id)),- unreadCount: c.unreadCount ?? 0,- timestamp: last?.timestamp ?? this.toUnixSeconds(c.conversationTimestamp),+ id,+ name: c.name ?? others.find(o => o.name)?.name ?? this.resolveContactName(rawId),+ isGroup: rawId.endsWith('@g.us'),+ kind: chatKind(id),+ // From the most recently active record that has one: new messages to a lid-migrated contact+ // count on the lid record while the phone one keeps a stale 0.+ unreadCount:+ [c, ...others]+ .filter(r => r.unreadCount != null)+ .sort((a, b) => this.toUnixSeconds(b.conversationTimestamp) - this.toUnixSeconds(a.conversationTimestamp))[0]+ ?.unreadCount ?? 0,+ timestamp: last?.timestamp ?? Math.max(...records.map(r => this.toUnixSeconds(r.conversationTimestamp))),lastMessage: last?.text,archived: st ? st.archived : (c.archived ?? false),// Baileys reports a pin as an ORDER, not a flag: 0/absent means unpinned.@@ -748,8 +830,85 @@ export class BaileysSessionStore {if (Object.hasOwn(r, 'archived')) patch.archived = Boolean(r.archived);if (Object.hasOwn(r, 'pinned')) patch.pinned = Boolean(r.pinned);if (Object.keys(patch).length) {- void this.chatStateStore.remember(this.sessionId, id, patch);+ // A row still filed under a lid twin is folded onto the state key here, on a real change, never+ // on a read: the store picks the newest row from the table, so a twin the cache happens to hold+ // cannot overwrite a newer row it does not.+ const key = this.stateKey(id);+ const twins = this.stateTwins([id], key);+ // Only an app-state action (the update holds the state fields alone) may create a row to hold a+ // default, like an unpin that must outweigh a pin on a twin row. A message carries `archived:+ // false` when the account unarchives on new messages, and a history chat carries its other fields+ // too; a default in either creating a row would leave one row per chat ever messaged.+ const create = Object.keys(r).every(f => f === 'id' || f === 'conditional' || Object.hasOwn(patch, f));+ void (twins.length+ ? this.chatStateStore.fold(this.sessionId, key, twins, patch, create)+ : this.chatStateStore.remember(this.sessionId, key, patch, create));+ }+ }++ /**+ * The one key a chat's persisted state lives under, whatever spelling the update carried: the phone+ * JID once the lid resolves, else the device-stripped lid, and anything else (a group) as is.+ * WhatsApp syncs a lid-migrated contact's pin, mute and archive under the lid while the chat record+ * may be keyed by phone, so keying the row by the raw id split one chat's state across two rows and+ * the listing read the one that never changed.+ */+ private stateKey(id: string): string {+ const parsed = parseWaId(id);+ if (parsed.kind === 'lid') {+ const phone = this.resolvePhone(id);+ return phone ? `${phone}@s.whatsapp.net` : `${parsed.userPart}@lid`;+ }+ return this.toEngineJid(id);+ }++ /**+ * The chat's persisted state. A row may still sit under a lid twin of the state key: written before+ * the mapping was learned, or by an earlier version that keyed rows by the raw id. The rows merge+ * field by field, as the fold does (see {@link mergeTwinStates}). A read never writes: the twin rows+ * 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 {+ const store = this.chatStateStore;+ const sid = this.sessionId;+ if (!store || !sid) return undefined;+ const key = this.stateKey(rawId);+ return mergeTwinStates([key, ...this.stateTwins(recordIds, key, lidIndex)].flatMap(k => store.get(sid, k) ?? []));+ }++ /**+ * The lid spellings of a phone-keyed state key: the lids among the chat's own record ids, and the+ * ones this session's mappings and the persisted table pair with the phone. The own lids matter when+ * only the contact record resolves them, which neither mapping source holds.+ */+ private stateTwins(rawIds: string[], key: string, lidIndex?: Map<string, string[]>): string[] {+ const parsed = parseWaId(key);+ if (parsed.kind !== 'user') return [];+ // A single update scans the mappings for this one phone; building the whole index per update+ // blocked the event loop for seconds when a first sync carried thousands of state fields.+ const twins = new Set(lidIndex?.get(parsed.userPart));+ if (!lidIndex) {+ for (const [lid, pn] of this.lidToPn.entries()) {+ if (userPart(pn) === parsed.userPart) twins.add(`${userPart(lid)}@lid`);+ }+ }+ for (const lid of this.lidStore?.lidsForPhone(parsed.userPart) ?? []) twins.add(`${lid}@lid`);+ for (const rawId of rawIds) {+ const raw = parseWaId(rawId);+ if (raw.kind === 'lid') twins.add(`${raw.userPart}@lid`);+ }+ return [...twins];+ }++ /** Phone digits to the lid JIDs this session maps to them, built once per listing. */+ private lidsByPhone(): Map<string, string[]> {+ const index = new Map<string, string[]>();+ for (const [lid, pn] of [...this.lidToPn.entries()]) {+ const phone = userPart(pn);+ index.set(phone, [...(index.get(phone) ?? []), `${userPart(lid)}@lid`]);}+ return index;}/**diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex d7bdcebb7..c4a531da4 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4780,6 +4780,7 @@ describe('BaileysAdapter store-backed ops', () => {const chatStateStore = {get: jest.fn(),remember: jest.fn().mockResolvedValue(undefined),+ fold: jest.fn().mockResolvedValue(undefined),reload: jest.fn().mockResolvedValue(undefined),clearSession: jest.fn(),forget: jest.fn().mockResolvedValue(undefined),diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.tsindex e325951c1..09f9264a4 100644--- a/src/engine/identity/lid-mapping-store.service.ts+++ b/src/engine/identity/lid-mapping-store.service.ts@@ -45,6 +45,10 @@ export interface LidMappingStore {resolveLid(jid: string): string | null;/** Sync reverse lookup: the lids currently mapped to this phone (used by the message from-filter). */lidsForPhone(phone: string): string[];+ /** The phone the table holds for a lid JID, read from the database; null when none is stored. */+ findPhoneForLid?(jid: string): Promise<string | null>;+ /** The lids the table maps to these phone digits, read from the database. */+ findLidsForPhone?(phone: string): Promise<string[]>;/** Write-through, last-write-wins: update the cache + persist. A `null` phone records a negative result. */remember(lid: string, phone: string | null, sessionId?: string): Promise<void>;}diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex ab83b1da5..83360fd4a 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -122,6 +122,8 @@ export interface ChatStateRow {// boolean on Postgres, 0/1 on SQLite; carried through as-is like PluginInstanceRow.enabled.archived: boolean | number;pinned: boolean | number;+ // Absent from an archive taken before the column existed; null reads as its set fields observed.+ observed?: string | null;updatedAt: string;}diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 45f0c6bab..1ecc9082c 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -231,9 +231,17 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [defineTableImporter({key: 'chatStates',label: 'chat state',- sql: `INSERT INTO chat_states ("sessionId", "chatId", "muteEndTime", archived, pinned, "updatedAt") VALUES ($1, $2, $3, $4, $5, $6)`,+ sql: `INSERT INTO chat_states ("sessionId", "chatId", "muteEndTime", archived, pinned, observed, "updatedAt") VALUES ($1, $2, $3, $4, $5, $6, $7)`,id: (cs: ChatStateRow) => `${cs.sessionId}/${cs.chatId}`,- map: (cs: ChatStateRow) => [cs.sessionId, cs.chatId, cs.muteEndTime ?? null, cs.archived, cs.pinned, cs.updatedAt],+ map: (cs: ChatStateRow) => [+ cs.sessionId,+ cs.chatId,+ cs.muteEndTime ?? null,+ cs.archived,+ cs.pinned,+ cs.observed ?? null,+ cs.updatedAt,+ ],}),// Import plugin instances (Integration Fabric config + ingress HMAC secret)