Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): persist Baileys chat mute, archive and pin across reconnects
Yudhi Armyndharis126c2442a44a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 781400c9c..a136c4448 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -76,6 +76,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Baileys chat `muted`, `archived` and `pinned` state now survives a session reconnect or process+ restart. WhatsApp does not re-deliver it on reconnect, so it is persisted per chat and rehydrated on+ boot; a muted chat no longer reads unmuted after the session reconnects.- Paged lists now tiebreak on `id`, so a walk returns every row exactly once. Neither `createdAt` nora search relevance score is unique, and on PostgreSQL two identical statements could sort one tiegroup differently, silently repeating some rows and omitting others: a 5000-row message list lostdiff --git a/openapi.json b/openapi.jsonindex ca5232bfc..0ce7cd735 100644--- a/openapi.json+++ b/openapi.json@@ -13870,6 +13870,12 @@"type": "object"}},+ "chatStates": {+ "type": "array",+ "items": {+ "type": "object"+ }+ },"pluginInstances": {"type": "array","items": {@@ -13927,6 +13933,7 @@"templates","baileysStoredMessages","lidMappings",+ "chatStates","pluginInstances","conversationMappings","ingressEvents",@@ -13968,6 +13975,10 @@"type": "number","example": 64},+ "chatStates": {+ "type": "number",+ "example": 40+ },"pluginInstances": {"type": "number","example": 12@@ -14009,6 +14020,7 @@"templates","baileysStoredMessages","lidMappings",+ "chatStates","pluginInstances","conversationMappings","ingressEvents",@@ -14116,6 +14128,9 @@"lidMappings": {"type": "array"},+ "chatStates": {+ "type": "array"+ },"pluginInstances": {"type": "array"},diff --git a/src/database/migrations/1786400000000-AddChatStates.ts b/src/database/migrations/1786400000000-AddChatStates.tsnew file mode 100644index 000000000..c6619453f--- /dev/null+++ b/src/database/migrations/1786400000000-AddChatStates.ts@@ -0,0 +1,33 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Creates `chat_states`, the persisted per-session mute/archive/pin table on the `data` connection.+ * Baileys cannot re-deliver these on a reconnect, so they are persisted and rehydrated on boot. Hand+ * authored because `synchronize` is off for `data` on Postgres (and optional on SQLite); the `hasTable`+ * guard keeps it idempotent on a DB where synchronize already created it.+ */+export class AddChatStates1786400000000 implements MigrationInterface {+ name = 'AddChatStates1786400000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (await queryRunner.hasTable('chat_states')) return;+ const isPostgres = queryRunner.dataSource.options.type === 'postgres';++ // The DDL matches what TypeORM synchronize would generate from the ChatState entity byte for byte,+ // so the migration-drift gate sees no difference (bare inline PRIMARY KEY, boolean columns, the+ // DEFAULT forms each dialect emits).+ if (isPostgres) {+ await queryRunner.query(+ `CREATE TABLE "chat_states" ("sessionId" varchar NOT NULL, "chatId" varchar NOT NULL, "muteEndTime" bigint, "archived" boolean NOT NULL DEFAULT false, "pinned" boolean NOT NULL DEFAULT false, "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), PRIMARY KEY ("sessionId", "chatId"))`,+ );+ } else {+ await queryRunner.query(+ `CREATE TABLE "chat_states" ("sessionId" varchar NOT NULL, "chatId" varchar NOT NULL, "muteEndTime" bigint, "archived" boolean NOT NULL DEFAULT (0), "pinned" boolean NOT NULL DEFAULT (0), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), PRIMARY KEY ("sessionId", "chatId"))`,+ );+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP TABLE IF EXISTS "chat_states"`);+ }+}diff --git a/src/database/migrations/__tests__/1786400000000-AddChatStates.spec.ts b/src/database/migrations/__tests__/1786400000000-AddChatStates.spec.tsnew file mode 100644index 000000000..215f689a2--- /dev/null+++ b/src/database/migrations/__tests__/1786400000000-AddChatStates.spec.ts@@ -0,0 +1,56 @@+import { DataSource } from 'typeorm';+import { AddChatStates1786400000000 } from '../1786400000000-AddChatStates';++describe('AddChatStates migration', () => {+ let ds: DataSource;++ beforeEach(async () => {+ ds = new DataSource({ type: 'better-sqlite3', database: ':memory:' });+ await ds.initialize();+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('creates and drops the table', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddChatStates1786400000000();++ await migration.up(runner);+ expect(await runner.hasTable('chat_states')).toBe(true);++ await migration.down(runner);+ expect(await runner.hasTable('chat_states')).toBe(false);++ await runner.release();+ });++ it('up() is idempotent when the table already exists (hasTable guard)', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddChatStates1786400000000();++ await migration.up(runner);+ await expect(migration.up(runner)).resolves.not.toThrow();+ expect(await runner.hasTable('chat_states')).toBe(true);++ await runner.release();+ });++ it('stores a row keyed by (sessionId, chatId)', async () => {+ const runner = ds.createQueryRunner();+ const migration = new AddChatStates1786400000000();+ await migration.up(runner);++ await runner.query(+ `INSERT INTO "chat_states" ("sessionId", "chatId", "muteEndTime", "archived", "pinned") VALUES ('s1', '[email protected]', 1788000000000, 0, 1)`,+ );+ const rows = (await runner.query(+ `SELECT "muteEndTime", "pinned" FROM "chat_states" WHERE "sessionId" = 's1'`,+ )) as Array<{ muteEndTime: number; pinned: number }>;+ expect(rows).toHaveLength(1);+ expect(Number(rows[0].muteEndTime)).toBe(1788000000000);++ 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.tsnew file mode 100644index 000000000..a56607a62--- /dev/null+++ b/src/engine/adapters/baileys-chat-state-store.service.spec.ts@@ -0,0 +1,101 @@+import { Repository } from 'typeorm';+import { ChatStateStoreService } from './baileys-chat-state-store.service';+import { ChatState } from './baileys-chat-state.entity';++const KEY = (s: string, c: string): string => `${s}\u0000${c}`;++function makeRepo(initial: Partial<ChatState>[] = []) {+ const rows = new Map<string, ChatState>();+ for (const r of initial) {+ rows.set(KEY(r.sessionId!, r.chatId!), {+ muteEndTime: null,+ archived: false,+ pinned: false,+ updatedAt: new Date(),+ ...r,+ } as ChatState);+ }+ const repo = {+ rows,+ find: jest.fn(() => Promise.resolve([...rows.values()])),+ findOne: jest.fn(({ where }: { where: { sessionId: string; chatId: string } }) =>+ Promise.resolve(rows.get(KEY(where.sessionId, where.chatId))),+ ),+ upsert: jest.fn((v: ChatState) => {+ rows.set(KEY(v.sessionId, v.chatId), { ...v });+ return Promise.resolve(undefined);+ }),+ };+ return repo;+}++const svcWith = (repo: ReturnType<typeof makeRepo>) =>+ new ChatStateStoreService(repo as unknown as Repository<ChatState>);++const tick = () => new Promise(resolve => setImmediate(resolve));++describe('ChatStateStoreService', () => {+ const ENV = 'BAILEYS_CHAT_STATE_CACHE_MAX';+ const orig = process.env[ENV];+ afterEach(() => {+ if (orig === undefined) delete process.env[ENV];+ else process.env[ENV] = orig;+ });++ 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 });+ });++ it('returns undefined for an unknown chat', () => {+ expect(svcWith(makeRepo()).get('s', 'nope')).toBeUndefined();+ });++ it('merges a partial patch: mute then archive both survive', async () => {+ 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 });+ });++ it('skips a no-op identical write', async () => {+ const repo = makeRepo();+ const svc = svcWith(repo);+ await svc.remember('s', 'c', { archived: true });+ await svc.remember('s', 'c', { archived: true });+ expect(repo.upsert).toHaveBeenCalledTimes(1);+ });++ it('evicts the least-recently-used entry over the cap', async () => {+ process.env[ENV] = '2';+ const svc = svcWith(makeRepo());+ await svc.remember('s', 'a', { archived: true });+ await svc.remember('s', 'b', { archived: true });+ await svc.remember('s', 'c', { archived: true }); // evicts 'a'+ expect(svc.get('s', 'a')).toBeUndefined();+ expect(svc.get('s', 'b')).toBeDefined();+ expect(svc.get('s', 'c')).toBeDefined();+ });++ 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.+ expect(svc.get('s', 'c')).toBeUndefined();+ await tick();+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: 5, 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(),+ upsert: jest.fn(() => Promise.reject(new Error('no such table'))),+ };+ 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 in-memory mirror still updated even though the write failed+ expect(svc.get('s', 'c')).toEqual({ muteEndTime: null, archived: true, pinned: false });+ });+});diff --git a/src/engine/adapters/baileys-chat-state-store.service.ts b/src/engine/adapters/baileys-chat-state-store.service.tsnew file mode 100644index 000000000..8f436599e--- /dev/null+++ b/src/engine/adapters/baileys-chat-state-store.service.ts@@ -0,0 +1,148 @@+import { Injectable, OnModuleInit } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { ChatState } from './baileys-chat-state.entity';+import { createLogger } from '../../common/services/logger.service';+import { resolveNonNegativeIntEnv } from '../../config/configuration';++/** 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 };++/**+ * Narrow read/write port over the persisted `chat_states` table. The Baileys session store depends on+ * this (a sync read on the chat-list hot path plus write-through), on the interface not the concrete+ * service, so the store stays unit-testable with a fake (mirrors {@link LidMappingStore}).+ */+export 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>;+ /** (Re)load the in-memory mirror from the table (boot, and after a full-replace restore). */+ reload(): Promise<void>;+}++const DEFAULT_STATE: ChatStateValue = { muteEndTime: null, archived: false, pinned: false };+const SEP = '\u0000'; // a null byte never appears in a session name or JID, so the join cannot collide++// 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.+export const CHAT_STATE_CACHE_DEFAULT = 5000;++/**+ * Backs the Baileys `muted`/`archived`/`pinned` chat fields with the persisted {@link ChatState} table.+ * The read is synchronous (the chat list cannot await a query), so the table is loaded into an in-memory+ * map on boot and kept warm by write-through. Live `chats.update` mutations update it (an unmute arrives+ * as `muteEndTime: null` and correctly clears); a fresh process rehydrates from the table, which is why+ * a chat muted before a restart still reads muted afterwards.+ */+@Injectable()+export class ChatStateStoreService implements ChatStateStore, OnModuleInit {+ private readonly logger = createLogger('ChatStateStore');+ private readonly states = new Map<string, ChatStateValue>();+ /** Repository fallbacks in flight, one per key, so a hot miss path can't stack duplicate queries. */+ private readonly pendingLookups = new Set<string>();+ private readonly maxEntries: number;++ constructor(+ @InjectRepository(ChatState, 'data')+ private readonly repo: Repository<ChatState>,+ ) {+ this.maxEntries = resolveNonNegativeIntEnv(process.env.BAILEYS_CHAT_STATE_CACHE_MAX, CHAT_STATE_CACHE_DEFAULT);+ }++ async onModuleInit(): Promise<void> {+ await this.reload();+ }++ async reload(): Promise<void> {+ try {+ const rows = await this.repo.find({+ order: { updatedAt: 'DESC' },+ take: this.maxEntries > 0 ? this.maxEntries : undefined,+ });+ this.states.clear();+ for (const row of rows) {+ this.index(this.key(row.sessionId, row.chatId), {+ muteEndTime: row.muteEndTime,+ archived: row.archived,+ pinned: row.pinned,+ });+ }+ this.logger.log(+ `Loaded ${rows.length} chat states into cache${this.maxEntries ? ` (cap ${this.maxEntries})` : ''}`,+ );+ } catch (err) {+ this.logger.warn(`Could not preload chat states: ${err instanceof Error ? err.message : String(err)}`);+ }+ }++ get(sessionId: string, chatId: string): ChatStateValue | undefined {+ const k = this.key(sessionId, chatId);+ if (this.states.has(k)) {+ const value = this.states.get(k)!;+ this.states.delete(k); // LRU touch: re-insert at the most-recent end+ this.states.set(k, value);+ return value;+ }+ this.warmFromTable(k, sessionId, chatId);+ return undefined;+ }++ 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;+ 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);+ try {+ await this.repo.upsert({ sessionId, chatId, ...next, updatedAt: new Date() }, ['sessionId', 'chatId']);+ } catch (err) {+ this.logger.warn(+ `Failed to persist chat state for ${chatId}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ }++ /** Warm a cache miss from the table. This lookup still returns undefined (the read cannot await); the next hits. */+ private warmFromTable(k: string, sessionId: string, chatId: string): void {+ if (this.pendingLookups.has(k)) return;+ this.pendingLookups.add(k);+ void this.repo+ .findOne({ where: { sessionId, chatId } })+ .then(row => {+ if (row && !this.states.has(k)) {+ this.index(k, { muteEndTime: row.muteEndTime, archived: row.archived, pinned: row.pinned });+ }+ })+ .catch(() => undefined)+ .finally(() => this.pendingLookups.delete(k));+ }++ private index(k: string, value: ChatStateValue): void {+ this.states.delete(k); // re-insert so the entry moves to the most-recent end even on update+ this.states.set(k, value);+ this.evictIfOverCap();+ }++ private evictIfOverCap(): void {+ if (!this.maxEntries) return; // unbounded+ while (this.states.size > this.maxEntries) {+ const oldest = this.states.keys().next().value;+ if (oldest === undefined) break;+ this.states.delete(oldest);+ }+ }++ private key(sessionId: string, chatId: string): string {+ return `${sessionId}${SEP}${chatId}`;+ }+}diff --git a/src/engine/adapters/baileys-chat-state.entity.ts b/src/engine/adapters/baileys-chat-state.entity.tsnew file mode 100644index 000000000..3055a0324--- /dev/null+++ b/src/engine/adapters/baileys-chat-state.entity.ts@@ -0,0 +1,42 @@+import { Column, Entity, PrimaryColumn, UpdateDateColumn } from 'typeorm';++/**+ * Persisted per-session chat app-state (mute / archive / pin) on the `data` connection. Baileys cannot+ * re-deliver these on a reconnect: history sync is skipped once paired and `resyncAppState` only ships+ * mutations newer than the persisted version, so an already-applied mute is never re-emitted, and the+ * library keeps no queryable copy (only LTHash MACs). Measured live: after a reconnect, 0 of the synced+ * chats carried `muteEndTime`. So the value is persisted here and rehydrated on boot; live `chats.update`+ * events (including an unmute, which arrives as `muteEndTime = null`) keep it current.+ *+ * One row per (session, chat). `sessionId` is the session NAME used elsewhere in the engine surface,+ * provenance rather than a foreign key, so the row can outlive a single run. `muteEndTime` is stored as+ * canonical epoch MILLISECONDS (or null when unmuted); the numeric transformer keeps it a JS number+ * rather than the string a bigint column otherwise reads back as.+ */+@Entity('chat_states')+export class ChatState {+ /** Session name that owns this chat state. */+ @PrimaryColumn()+ sessionId!: string;++ /** Chat id in the engine's stored (raw Baileys) dialect, the same key `upsertChats` uses. */+ @PrimaryColumn()+ chatId!: string;++ /** Epoch MILLISECONDS the mute ends, or null when the chat is not muted. */+ @Column({+ type: 'bigint',+ nullable: true,+ transformer: { to: (v: number | null) => v, from: (v: string | null) => (v == null ? null : Number(v)) },+ })+ muteEndTime!: number | null;++ @Column({ type: 'boolean', default: false })+ archived!: boolean;++ @Column({ type: 'boolean', default: false })+ pinned!: boolean;++ @UpdateDateColumn()+ updatedAt!: Date;+}diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 29b6b13f2..4bfcaa097 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -1,7 +1,27 @@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 { 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 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 });+ return Promise.resolve();+ }+ reload(): Promise<void> {+ return Promise.resolve();+ }+}+describe('BaileysSessionStore', () => {let store: BaileysSessionStore;beforeEach(() => {@@ -82,12 +102,14 @@ describe('BaileysSessionStore', () => {expect(chatFor({}).muted).toBe(false);});- it('reads the end time as milliseconds, the unit the mute round-trip is measured at', () => {- // chat-mute.spec.ts records the measurement: a seconds-scale value sent through- // chatModify({ mute }) left the chat unmuted, because that instant had already passed in- // 1970. Reading it back the same way keeps the write and the read on one unit — a- // seconds-scale stamp is an instant in 1970 here too, so it reads as expired.- expect(chatFor({ muteEndTime: Math.floor(Date.now() / 1000) + 3600 }).muted).toBe(false);+ it('reads both units: epoch ms from an app-state write and epoch seconds from history sync', () => {+ // A chatModify({ mute }) write echoes back the epoch-MS value the gateway passed; a history-sync+ // Conversation.muteEndTime is epoch SECONDS (like conversationTimestamp on the same record). Both+ // must read as muted while ahead, else a synced mute reads unmuted.+ const nowS = Math.floor(Date.now() / 1000);+ expect(chatFor({ muteEndTime: (nowS + 3600) * 1000 }).muted).toBe(true); // ms, still ahead+ expect(chatFor({ muteEndTime: nowS + 3600 }).muted).toBe(true); // seconds, still ahead+ expect(chatFor({ muteEndTime: nowS - 3600 }).muted).toBe(false); // seconds, already past});it('accepts a Long, which is what the proto actually hands over', () => {@@ -96,6 +118,58 @@ describe('BaileysSessionStore', () => {});});+ describe('chat-state persistence (survives a reconnect Baileys cannot resync)', () => {+ const SID = 'sess-1';+ const CHAT = '[email protected]';+ let fake: FakeChatStateStore;+ beforeEach(() => {+ fake = new FakeChatStateStore();+ });+ // A fresh store sharing the SAME fake models a process restart: this.chats is empty and rebuilds+ // from history sync, but the persisted state is retained.+ const newStore = () => new BaileysSessionStore(undefined, SID, fake);+ const chatOn = (s: BaileysSessionStore, over: Record<string, unknown>) => {+ s.upsertChats([{ id: CHAT, name: 'Alice', ...over }]);+ return s.listChats()[0];+ };++ it('persists a mute and reads it back as muted', () => {+ expect(chatOn(newStore(), { muteEndTime: Date.now() + 60 * 60 * 1000 }).muted).toBe(true);+ expect(fake.rows.size).toBe(1);+ });++ it('a fresh process reads a mute set before the restart, though history sync omits muteEndTime', () => {+ chatOn(newStore(), { muteEndTime: Date.now() + 60 * 60 * 1000 });+ // Restart: this.chats is rebuilt from a history-sync record with NO muteEndTime key.+ expect(chatOn(newStore(), { name: 'Alice' }).muted).toBe(true);+ });++ it('a live unmute (muteEndTime: null) persists and reads unmuted, across a restart', () => {+ const s = newStore();+ chatOn(s, { muteEndTime: Date.now() + 3_600_000 });+ expect(chatOn(s, { muteEndTime: null }).muted).toBe(false);+ expect(chatOn(newStore(), { name: 'Alice' }).muted).toBe(false);+ });++ it('archived and pinned persist and survive a restart', () => {+ chatOn(newStore(), { archived: true, pinned: 2 });+ expect(chatOn(newStore(), { name: 'Alice' })).toMatchObject({ archived: true, pinned: true });+ });++ it('a partial update lacking the keys does not clobber persisted state', () => {+ const s = newStore();+ chatOn(s, { muteEndTime: Date.now() + 3_600_000, archived: true });+ expect(chatOn(s, { name: 'Renamed' })).toMatchObject({ muted: true, archived: true });+ });++ it('normalizes a seconds-scale muteEndTime to ms on persist', () => {+ const nowS = Math.floor(Date.now() / 1000);+ chatOn(newStore(), { muteEndTime: nowS + 3600 });+ expect(fake.get(SID, CHAT)?.muteEndTime).toBe((nowS + 3600) * 1000);+ expect(chatOn(newStore(), { name: 'Alice' }).muted).toBe(true);+ });+ });+it('records the newest message per chat and surfaces it in getChats', () => {store.upsertChats([{ id: '[email protected]', name: 'Alice', unreadCount: 2 }]);store.recordMessage({diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex e27c834d2..2eed2abeb 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -2,6 +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 { resolveNonNegativeIntEnv } from '../../config/configuration';interface LastMessage {@@ -90,13 +91,17 @@ export class BaileysSessionStore {private readonly ephemeralByChat: LruMap<string, number>;/**- * @param lidStore optional persisted, cross-session lid->phone table that backs resolution beyond- * this session's in-memory map (survives restarts, shared across sessions).- * @param sessionId provenance recorded on rows this session writes to the table.+ * @param lidStore optional persisted, cross-session lid->phone table that backs resolution beyond+ * this session's in-memory map (survives restarts, shared across sessions).+ * @param sessionId provenance recorded on rows this session writes to the persisted tables.+ * @param chatStateStore optional persisted per-session mute/archive/pin, so those chat fields survive a+ * reconnect Baileys cannot resync (it only re-emits mutations newer than the+ * persisted app-state version, never an already-applied one).*/constructor(private readonly lidStore?: LidMappingStore,private readonly sessionId?: string,+ private readonly chatStateStore?: ChatStateStore,) {// Mirrors LidMappingStoreService: a finite default, 0 opts back into unbounded, garbage falls back.const maxEntries = resolveNonNegativeIntEnv(@@ -137,6 +142,7 @@ export class BaileysSessionStore {}const existing = this.chats.get(r.id) ?? { id: r.id };this.chats.set(r.id, { ...existing, ...r });+ this.persistChatState(r.id, r);}}@@ -380,6 +386,9 @@ export class BaileysSessionStore {// is provably keyed by a real id.const id = c.id!;const last = this.lastMessages.get(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;return {id: this.toNeutralJid(id),name: c.name ?? this.resolveContactName(id),@@ -388,30 +397,55 @@ export class BaileysSessionStore {unreadCount: c.unreadCount ?? 0,timestamp: last?.timestamp ?? this.toUnixSeconds(c.conversationTimestamp),lastMessage: last?.text,- archived: c.archived ?? false,- // Baileys reports a pin as an ORDER, not a flag — 0/absent means unpinned.- pinned: Boolean(c.pinned),- muted: this.isMuted(c.muteEndTime),+ archived: st ? st.archived : (c.archived ?? false),+ // Baileys reports a pin as an ORDER, not a flag: 0/absent means unpinned.+ pinned: st ? st.pinned : Boolean(c.pinned),+ muted: this.isMuted(st ? st.muteEndTime : c.muteEndTime),};}/*** Whether a Baileys `muteEndTime` is still in the future.*- * The stamp is epoch MILLISECONDS, and that is measured rather than inferred: `chat-mute.spec.ts`- * records that a seconds-scale value sent through `chatModify({ mute })` left the chat unmuted —- * the instant had already passed in 1970 — while the same instant in milliseconds muted it to- * the expected minute. `mute-chat.dto.ts` documents the same unit on the way in. Only the proto's- * unsuffixed `muteEndTime` suggests otherwise, beside fields it does spell `…Ms`, and it is- * wrong.+ * The value arrives in two units. An app-state `chatModify({ mute })` write echoes the epoch+ * MILLISECONDS this gateway passed (measured in `chat-mute.spec.ts`, documented in `mute-chat.dto.ts`).+ * A history-sync `Conversation.muteEndTime` is a Long in the proto's own unit, seconds like the+ * `conversationTimestamp` beside it. So it is normalised by magnitude: below 1e12 is seconds (an+ * epoch-ms stamp below 1e12 is a date before 2001-09) and is scaled to ms. The current state survives a+ * reconnect via {@link persistChatState}, because Baileys re-emits only app-state mutations newer than+ * the persisted version, never an already-applied mute.*/private isMuted(muteEndTime: number | { toNumber(): number } | null | undefined): boolean {- // toUnixSeconds unwraps Long → number and nothing else; the unit is whatever was passed in.- const endMs = this.toUnixSeconds(muteEndTime);- if (!endMs) return false;+ const raw = this.toUnixSeconds(muteEndTime);+ if (!raw) return false;+ const endMs = raw < 1e12 ? raw * 1000 : raw;return endMs > Date.now();}+ /**+ * Write mute/archive/pin through to the persisted store when a chat update carries them. Key presence,+ * not truthiness, is the trigger: a history-sync or name-hydration partial that omits these keys must+ * not overwrite persisted state, and a live unmute arrives as `muteEndTime: null` (key present) that+ * must persist as null. A no-op when this session has no store wired (unit tests, wwjs).+ */+ private persistChatState(id: string, r: Partial<Chat>): void {+ if (!this.chatStateStore || !this.sessionId) return;+ const patch: Partial<ChatStateValue> = {};+ if ('muteEndTime' in r) patch.muteEndTime = this.normalizeMuteEndTime(r.muteEndTime);+ if ('archived' in r) patch.archived = Boolean(r.archived);+ if ('pinned' in r) patch.pinned = Boolean(r.pinned);+ if (Object.keys(patch).length) {+ void this.chatStateStore.remember(this.sessionId, id, patch);+ }+ }++ /** Normalise a raw muteEndTime to canonical epoch ms, or null (0/absent = unmuted). See {@link isMuted}. */+ private normalizeMuteEndTime(v: number | { toNumber(): number } | null | undefined): number | null {+ const n = this.toUnixSeconds(v);+ if (!n) return null;+ return n < 1e12 ? n * 1000 : n;+ }+/*** Best-known display name for a chat id when Baileys gave the chat no title (#369). Prefers the saved* contact name, then verifiedName, then pushName (`notify`); for a @lid chat it also tries the contactdiff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex a86d1238e..dc6083374 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -113,7 +113,7 @@ export class BaileysAdapter implements IWhatsAppEngine {constructor(private readonly config: BaileysAdapterConfig) {// Isolate each session's auth state under its own subdirectory of the shared auth dir.this.authPath = path.join(config.authDir, config.sessionId);- this.sessionStore = new BaileysSessionStore(config.lidMappingStore, config.sessionId);+ this.sessionStore = new BaileysSessionStore(config.lidMappingStore, config.sessionId, config.chatStateStore);// Constructed before messaging: the messaging delegate's own-send echo maps through// events.mapMessage (and the lifecycle delegate clears that same live-call cache on teardown).// One host literal for every delegate (the wwebjs-host pattern): a new cross-cutting memberdiff --git a/src/engine/builtin/baileys/index.ts b/src/engine/builtin/baileys/index.tsindex a935b4ffe..cd48e23eb 100644--- a/src/engine/builtin/baileys/index.ts+++ b/src/engine/builtin/baileys/index.ts@@ -8,6 +8,7 @@ import { IWhatsAppEngine } from '../../interfaces/whatsapp-engine.interface';import { BaileysAdapter } from '../../adapters/baileys.adapter';import { BaileysMessageStore } from '../../types/baileys.types';import { LidMappingStore } from '../../identity/lid-mapping-store.service';+import { ChatStateStore } from '../../adapters/baileys-chat-state-store.service';export class BaileysPlugin implements IEnginePlugin {type = PluginType.ENGINE as const;@@ -20,6 +21,7 @@ export class BaileysPlugin implements IEnginePlugin {private readonly messageStore?: BaileysMessageStore,private readonly registeredConfig?: Record<string, unknown>,private readonly lidMappingStore?: LidMappingStore,+ private readonly chatStateStore?: ChatStateStore,) {}onLoad(context: PluginContext): Promise<void> {@@ -58,6 +60,7 @@ export class BaileysPlugin implements IEnginePlugin {proxyType,messageStore: this.messageStore,lidMappingStore: this.lidMappingStore,+ chatStateStore: this.chatStateStore,});}diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex ae0be3d7a..16a369daa 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -6,6 +6,7 @@ import { ConfigService } from '@nestjs/config';import { PluginLoaderService, PluginType } from '../core/plugins';import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';import { LidMappingStoreService } from './identity/lid-mapping-store.service';+import { ChatStateStoreService } from './adapters/baileys-chat-state-store.service';describe('EngineFactory', () => {const engineBlob = {@@ -36,12 +37,25 @@ describe('EngineFactory', () => {remember: jest.fn().mockResolvedValue(undefined),}) as unknown as LidMappingStoreService;+ const buildChatStateStore = (): ChatStateStoreService =>+ ({+ get: jest.fn(),+ remember: jest.fn().mockResolvedValue(undefined),+ reload: jest.fn().mockResolvedValue(undefined),+ }) as unknown as ChatStateStoreService;+it('refuses to create an engine for an unsafe session name (path-traversal into the auth dir)', () => {const createEngine = jest.fn().mockReturnValue({});const pluginLoader = {getPlugin: jest.fn().mockReturnValue({ instance: { type: PluginType.ENGINE, createEngine } }),} as unknown as PluginLoaderService;- const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());+ const factory = new EngineFactory(+ buildConfigService(),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );expect(() => factory.create({ sessionId: '../../etc', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);expect(() => factory.create({ sessionId: 'a/b', dbSessionId: 'db-1' })).toThrow(/unsafe session name/i);@@ -55,7 +69,13 @@ describe('EngineFactory', () => {getPlugin: jest.fn().mockReturnValue({ instance: pluginInstance }),} as unknown as PluginLoaderService;- const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());+ const factory = new EngineFactory(+ buildConfigService(),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );factory.create({ sessionId: 'sess-1', dbSessionId: 'db-1', proxyUrl: 'http://p', proxyType: 'http' });// Plain-object (not objectContaining) assertion: any browser key (headless/puppeteerArgs/@@ -76,7 +96,13 @@ describe('EngineFactory', () => {getPlugin: jest.fn(),} as unknown as PluginLoaderService;- const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());+ const factory = new EngineFactory(+ buildConfigService(),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );await factory.onModuleInit();expect(registerBuiltInPlugin).toHaveBeenCalledWith(@@ -94,7 +120,13 @@ describe('EngineFactory', () => {getPlugin: jest.fn(),} as unknown as PluginLoaderService;- const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());+ const factory = new EngineFactory(+ buildConfigService(),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );await factory.onModuleInit();const registeredIds = registerBuiltInPlugin.mock.calls.map(call => (call as [{ id: string }])[0].id);@@ -107,7 +139,13 @@ describe('EngineFactory', () => {getPlugin: jest.fn().mockReturnValue(undefined),} as unknown as PluginLoaderService;- const factory = new EngineFactory(buildConfigService(), pluginLoader, buildMessageStore(), buildLidStore());+ const factory = new EngineFactory(+ buildConfigService(),+ pluginLoader,+ buildMessageStore(),+ buildLidStore(),+ buildChatStateStore(),+ );expect(() => factory.create({ sessionId: 'sess-2', dbSessionId: 'db-2' })).not.toThrow();});@@ -123,6 +161,7 @@ describe('EngineFactory', () => {pluginLoader,buildMessageStore(),buildLidStore(),+ buildChatStateStore(),);expect(() => factory.create({ sessionId: 'sess-b', dbSessionId: 'db-b' })).toThrow(/baileys/i);});@@ -158,6 +197,7 @@ describe('EngineFactory', () => {pluginLoader,buildMessageStore(),buildLidStore(),+ buildChatStateStore(),);return {factory,@@ -200,6 +240,7 @@ describe('EngineFactory', () => {noPluginLoader(),buildMessageStore(),buildLidStore(),+ buildChatStateStore(),);return { factory, wwjsDir: path.join(sessionDataPath, 'session-alice'), baileysDir: path.join(authDir, 'alice') };};diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex e81784e84..8eb60afe6 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -10,6 +10,7 @@ import { BaileysPlugin } from './builtin/baileys';import { createLogger } from '../common/services/logger.service';import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';import { LidMappingStoreService } from './identity/lid-mapping-store.service';+import { ChatStateStoreService } from './adapters/baileys-chat-state-store.service';import { isSafeSessionName } from '../common/utils/path-safety';import { ensurePrivateDir } from '../common/utils/private-dir.util';@@ -32,6 +33,7 @@ export class EngineFactory implements OnModuleInit {private readonly pluginLoader: PluginLoaderService,private readonly baileysMessageStore: BaileysMessageStoreService,private readonly lidMappingStore: LidMappingStoreService,+ private readonly chatStateStore: ChatStateStoreService,) {this.engineType = this.configService.get<string>('engine.type') ?? 'whatsapp-web.js';}@@ -75,7 +77,7 @@ export class EngineFactory implements OnModuleInit {};this.pluginLoader.registerBuiltInPlugin(baileysManifest,- new BaileysPlugin(this.baileysMessageStore, engineConfig, this.lidMappingStore),+ new BaileysPlugin(this.baileysMessageStore, engineConfig, this.lidMappingStore, this.chatStateStore),engineConfig,);diff --git a/src/engine/engine.module.ts b/src/engine/engine.module.tsindex 57bd674c7..416771a4f 100644--- a/src/engine/engine.module.ts+++ b/src/engine/engine.module.ts@@ -5,15 +5,17 @@ import { BaileysStoredMessage } from './adapters/baileys-stored-message.entity';import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';import { LidMapping } from './identity/lid-mapping.entity';import { LidMappingStoreService } from './identity/lid-mapping-store.service';+import { ChatState } from './adapters/baileys-chat-state.entity';+import { ChatStateStoreService } from './adapters/baileys-chat-state-store.service';import { EngineRegistry } from './engine-registry.service';@Global()@Module({- imports: [TypeOrmModule.forFeature([BaileysStoredMessage, LidMapping], 'data')],+ imports: [TypeOrmModule.forFeature([BaileysStoredMessage, LidMapping, ChatState], 'data')],// EngineRegistry is exported from this @Global module so the feature services that only need a// live engine can inject it directly, instead of importing SessionModule to reach the lifecycle// owner. It is a singleton by DI, which is what makes it a safe single source of truth.- providers: [EngineFactory, BaileysMessageStoreService, LidMappingStoreService, EngineRegistry],- exports: [EngineFactory, LidMappingStoreService, EngineRegistry],+ providers: [EngineFactory, BaileysMessageStoreService, LidMappingStoreService, ChatStateStoreService, EngineRegistry],+ exports: [EngineFactory, LidMappingStoreService, ChatStateStoreService, EngineRegistry],})export class EngineModule {}diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.tsindex dfa2d11ce..47a21d49b 100644--- a/src/engine/types/baileys.types.ts+++ b/src/engine/types/baileys.types.ts@@ -1,5 +1,6 @@import type { WAMessage } from '@whiskeysockets/baileys';import type { LidMappingStore } from '../identity/lid-mapping-store.service';+import type { ChatStateStore } from '../adapters/baileys-chat-state-store.service';/*** Persistence boundary for the Baileys engine's message store. The adapter depends on this narrow@@ -36,6 +37,8 @@ export interface BaileysAdapterConfig {messageStore?: BaileysMessageStore;/** Persisted, cross-session lid->phone resolution table. Backs lid resolution beyond the in-memory map. */lidMappingStore?: LidMappingStore;+ /** Persisted per-session mute/archive/pin, so those chat fields survive a reconnect Baileys cannot resync. */+ chatStateStore?: ChatStateStore;}/**diff --git a/src/modules/infra/dto/infra-response.dto.ts b/src/modules/infra/dto/infra-response.dto.tsindex 1f6f2f597..53a6d996b 100644--- a/src/modules/infra/dto/infra-response.dto.ts+++ b/src/modules/infra/dto/infra-response.dto.ts@@ -384,6 +384,7 @@ export class MigrationTablesDto {@ApiProperty({ type: [Object] }) templates!: object[];@ApiProperty({ type: [Object] }) baileysStoredMessages!: object[];@ApiProperty({ type: [Object] }) lidMappings!: object[];+ @ApiProperty({ type: [Object] }) chatStates!: object[];@ApiProperty({ type: [Object] }) pluginInstances!: object[];@ApiProperty({ type: [Object] }) conversationMappings!: object[];@ApiProperty({ type: [Object] }) ingressEvents!: object[];@@ -403,6 +404,7 @@ export class TableCountsDto {@ApiProperty({ example: 3 }) templates!: number;@ApiProperty({ example: 512 }) baileysStoredMessages!: number;@ApiProperty({ example: 64 }) lidMappings!: number;+ @ApiProperty({ example: 40 }) chatStates!: number;@ApiProperty({ example: 12 }) pluginInstances!: number;@ApiProperty({ example: 8 }) conversationMappings!: number;@ApiProperty({ example: 40 }) ingressEvents!: number;diff --git a/src/modules/infra/export-tables.ts b/src/modules/infra/export-tables.tsindex cd5364e7c..9c86628aa 100644--- a/src/modules/infra/export-tables.ts+++ b/src/modules/infra/export-tables.ts@@ -240,6 +240,11 @@ export const EXPORT_TABLES: AnyExportTable[] = [// or a backup→restore into a fresh DB loses the whole cache (it self-heals, but lossily).defineExportTable({ key: 'lidMappings', table: 'lid_mappings', optional: true }),+ // Persisted per-session mute/archive/pin. Like lid_mappings it is not a FK to sessions, so the+ // import's `DELETE FROM sessions` never clears it; WhatsApp does not re-deliver it on reconnect,+ // so a backup that omits it would show a muted chat as unmuted after a restore.+ defineExportTable({ key: 'chatStates', table: 'chat_states', optional: true }),+// Integration Fabric + both DLQs: none carry an FK constraint to sessions (sessionId is// provenance), so the import clears them explicitly before the sessions DELETE to keep the// replace-semantics complete.diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 67642fb8a..5272d0026 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -34,6 +34,7 @@ import { MessageBatch, BatchStatus } from '../message/entities/message-batch.entimport { Template } from '../template/entities/template.entity';import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-message.entity';import { LidMapping } from '../../engine/identity/lid-mapping.entity';+import { ChatState } from '../../engine/adapters/baileys-chat-state.entity';import { PluginInstance } from '../integration/entities/plugin-instance.entity';import { ConversationMapping } from '../integration/entities/conversation-mapping.entity';import { IngressEvent } from '../integration/entities/ingress-event.entity';@@ -71,6 +72,7 @@ describe('InfraDataController.importData round-trips export-data (no silent messTemplate,BaileysStoredMessage,LidMapping,+ ChatState,PluginInstance,ConversationMapping,IngressEvent,@@ -1211,6 +1213,7 @@ describe('InfraDataController.import/export preserves every data-DB table', () =Template,BaileysStoredMessage,LidMapping,+ ChatState,PluginInstance,ConversationMapping,IngressEvent,@@ -1475,6 +1478,7 @@ describe('InfraDataController audit trail — import emits only on a committed rTemplate,BaileysStoredMessage,LidMapping,+ ChatState,PluginInstance,ConversationMapping,IngressEvent,@@ -1620,6 +1624,7 @@ describe('InfraDataController.importData status_updates + runtime reconciliationTemplate,BaileysStoredMessage,LidMapping,+ ChatState,PluginInstance,ConversationMapping,IngressEvent,diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.tsindex af6922fa2..ab83b1da5 100644--- a/src/modules/infra/migration-tables.types.ts+++ b/src/modules/infra/migration-tables.types.ts@@ -115,6 +115,16 @@ export interface LidMappingRow {updatedAt: string;}+export interface ChatStateRow {+ sessionId: string;+ chatId: string;+ muteEndTime: number | null;+ // boolean on Postgres, 0/1 on SQLite; carried through as-is like PluginInstanceRow.enabled.+ archived: boolean | number;+ pinned: boolean | number;+ updatedAt: string;+}+export interface PluginInstanceRow {id: string;pluginId: string;@@ -250,6 +260,7 @@ export interface MigrationTables {templates: TemplateRow[];baileysStoredMessages: BaileysStoredMessageRow[];lidMappings: LidMappingRow[];+ chatStates: ChatStateRow[];pluginInstances: PluginInstanceRow[];conversationMappings: ConversationMappingRow[];ingressEvents: IngressEventRow[];diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.tsindex 77bfc9e56..e5d20de95 100644--- a/src/modules/infra/table-importers.ts+++ b/src/modules/infra/table-importers.ts@@ -8,6 +8,7 @@ import type {TemplateRow,BaileysStoredMessageRow,LidMappingRow,+ ChatStateRow,PluginInstanceRow,ConversationMappingRow,IngressEventRow,@@ -221,6 +222,15 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [map: (lm: LidMappingRow) => [lm.lid, lm.phone ?? null, lm.sessionId ?? null, lm.updatedAt],}),+ // Import chat states (optional; not a FK, restored as a standalone per-session cache table)+ defineTableImporter({+ key: 'chatStates',+ label: 'chat state',+ sql: `INSERT INTO chat_states ("sessionId", "chatId", "muteEndTime", archived, pinned, "updatedAt") VALUES ($1, $2, $3, $4, $5, $6)`,+ id: (cs: ChatStateRow) => `${cs.sessionId}/${cs.chatId}`,+ map: (cs: ChatStateRow) => [cs.sessionId, cs.chatId, cs.muteEndTime ?? null, cs.archived, cs.pinned, cs.updatedAt],+ }),+// Import plugin instances (Integration Fabric config + ingress HMAC secret)defineTableImporter({key: 'pluginInstances',@@ -419,6 +429,7 @@ const EXPECTED_TABLE_KEYS: ReadonlyArray<keyof MigrationTables> = ['templates','baileysStoredMessages','lidMappings',+ 'chatStates','pluginInstances','conversationMappings','ingressEvents',