Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): release a deleted instance's takeover of a chat
Yudhi Armyndharis5a7fb22fa3d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b0b882497..223838aa0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Hand a chat back to the bot when the plugin instance that took it over is deleted, instead of silencing every other plugin on it.- Keep the sessions of a plugin's other enabled instances active when creating, disabling or deleting a session-scoped instance retires an operator-set `*`.- Omit the name, push name, caption, background colour and font of a received status that has none from `GET /status` instead of returning `null`, as the schema declares.- Bound the inbound media a PostgreSQL session holds before storing it to `INBOUND_MEDIA_CONCURRENCY` payloads, keeping each chat's arrival order.diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.tsindex f4e17a4da..f5351be69 100644--- a/src/modules/integration/plugin-instance.service.spec.ts+++ b/src/modules/integration/plugin-instance.service.spec.ts@@ -1,5 +1,7 @@import { DataSource } from 'typeorm';import { PluginInstance } from './entities/plugin-instance.entity';+import { ConversationMapping } from './entities/conversation-mapping.entity';+import { ConversationMappingService } from './conversation-mapping.service';import { PluginInstanceService, InstanceExistsError } from './plugin-instance.service';import { AddIntegrationFabric1781900000000 } from '../../database/migrations/1781900000000-AddIntegrationFabric';import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';@@ -118,7 +120,12 @@ describe('PluginInstanceService provisioning', () => {let ds: DataSource;let service: PluginInstanceService;beforeEach(async () => {- ds = new DataSource({ type: 'better-sqlite3', database: ':memory:', entities: [PluginInstance], migrations: [] });+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [PluginInstance, ConversationMapping],+ migrations: [],+ });await ds.initialize();const runner = ds.createQueryRunner();await new AddIntegrationFabric1781900000000().up(runner);@@ -151,6 +158,36 @@ describe('PluginInstanceService provisioning', () => {expect(rotated?.secret).not.toBe(created.secret);});+ it('releases the takeover a deleted instance held, so other plugins are no longer silenced on that chat', async () => {+ const mappings = ds.getRepository(ConversationMapping);+ const mapping = (pluginId: string, instanceId: string, chatId: string, handoverState: 'human' | 'closed') =>+ mappings.save(+ mappings.create({+ sessionId: 'sess-1',+ chatId,+ pluginId,+ instanceId,+ providerConversationId: `${instanceId}-${chatId}`,+ handoverState,+ }),+ );+ await mapping('chatwoot', 'acct1', '[email protected]', 'human');+ await mapping('chatwoot', 'acct1', '[email protected]', 'closed');+ await mapping('chatwoot', 'acct2', '[email protected]', 'human');+ const lookup = new ConversationMappingService(mappings);+ expect(await lookup.findHandoverForChat('sess-1', '[email protected]')).toMatchObject({ handoverState: 'human' });++ await service.create('chatwoot', 'acct1', {});+ await service.remove('chatwoot', 'acct1');++ expect(await lookup.findHandoverForChat('sess-1', '[email protected]')).toBeNull();+ expect(await lookup.findHandoverForChat('sess-1', '[email protected]')).toBeNull();+ // The rows stay, so the same instance provisioned again keeps its provider conversations; another+ // instance's takeover is untouched.+ expect((await mappings.findOneByOrFail({ chatId: '[email protected]' })).providerConversationId).toBe('[email protected]');+ expect(await lookup.findHandoverForChat('sess-1', '[email protected]')).toMatchObject({ handoverState: 'human' });+ });+it('update patches enabled/scope/config in one write; remove deletes', async () => {await service.create('chatwoot', 'acct1', { sessionScope: 'a' });const repo = ds.getRepository(PluginInstance);diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.tsindex e278740f7..06a4a01df 100644--- a/src/modules/integration/plugin-instance.service.ts+++ b/src/modules/integration/plugin-instance.service.ts@@ -1,8 +1,9 @@import { randomBytes } from 'node:crypto';import { BadRequestException, Injectable } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { QueryDeepPartialEntity, Repository } from 'typeorm';+import { In, QueryDeepPartialEntity, Repository } from 'typeorm';import { PluginInstance } from './entities/plugin-instance.entity';+import { ConversationMapping } from './entities/conversation-mapping.entity';import { isUniqueViolation } from '../../common/utils/db-errors';import type { PluginConfigSchema } from '../../core/plugins/plugin.interfaces';import { redactSecretConfig, restoreSecretConfig, SECRET_SENTINEL } from '../plugins/redact-config';@@ -139,7 +140,18 @@ export class PluginInstanceService implements PluginInstancePort {}async remove(pluginId: string, instanceId: string): Promise<boolean> {- const result = await this.repo.delete({ id: `${pluginId}:${instanceId}` });- return (result.affected ?? 0) > 0;+ return this.repo.manager.transaction(async manager => {+ const result = await manager.delete(PluginInstance, { id: `${pluginId}:${instanceId}` });+ // Its conversation mappings stay, so the same instance provisioned again keeps its provider+ // conversations. A takeover they hold does not: it is scoped to the chat, not to the plugin, and+ // with the instance gone nothing can hand the chat back, so it would keep every other plugin+ // silent there for good.+ await manager.update(+ ConversationMapping,+ { pluginId, instanceId, handoverState: In(['human', 'closed']) },+ { handoverState: 'bot' },+ );+ return (result.affected ?? 0) > 0;+ });}}