Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): hand a takeover back when its plugin is uninstalled

Yudhi Armyndharis97f7796dab7f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37e98406b..b80b2d947 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -48,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Answer `400` for a send route's `chatId` or a bulk `batchId` over 255 characters, where PostgreSQL answered `500` once the value passed its index entry limit.
- MCP tools refuse a `chatId`, `fromChatId` or `toChatId` over 255 characters, as the send routes do, where PostgreSQL answered an internal tool error.
- A start that fails while another start of the same session is in flight leaves the claim to that start, so its engine is no longer left on a row no node holds.
+- Uninstalling a plugin hands the chats it had taken over back to the bot, so other plugins are no longer silent there.
- Index ingress dead letters by delivery id, so the reconciler's per-delivery checks stop scanning every dead letter of an instance; the first boot builds the index.
- Replay stranded ingress events past one whose stored payload is not valid JSON, instead of failing every sweep on it.
- 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.
diff --git a/src/core/plugins/plugin-host-ports.ts b/src/core/plugins/plugin-host-ports.ts
index 9b9e6a050..fefd38c27 100644
--- a/src/core/plugins/plugin-host-ports.ts
+++ b/src/core/plugins/plugin-host-ports.ts
@@ -78,6 +78,8 @@ export interface PluginConversationMappingPort {
sessionId: string,
chatId: string,
): Promise<{ pluginId: string; handoverState: HandoverState } | null>;
+ /** Hand every chat a plugin took over back to the bot, once the plugin is gone and nothing can. */
+ releaseTakeovers(pluginId: string): Promise<void>;
}
/** A provisioned instance of an adapter plugin, as the instance-allowlist and ingress dispatch read it. */
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index eaf7be187..18ded31e3 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -240,6 +240,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
this.pluginsDir,
pluginId => this.lifecycle.unloadPlugin(pluginId),
this.legacyPluginsDir,
+ pluginId => this.hostServices.getConversationMappingPort().releaseTakeovers(pluginId),
);
}
diff --git a/src/core/plugins/plugin-uninstaller.spec.ts b/src/core/plugins/plugin-uninstaller.spec.ts
index add302653..5d22b1a08 100644
--- a/src/core/plugins/plugin-uninstaller.spec.ts
+++ b/src/core/plugins/plugin-uninstaller.spec.ts
@@ -14,7 +14,12 @@ import { PluginInstance, PluginStatus, PluginType } from './plugin.interfaces';
* uninstallPlugin actually reads. The unload seam is the callback the lifecycle would provide; every
* assertion is unchanged.
*/
-const makeUninstaller = (config: ConfigService, storage: PluginStorageService, pluginsDir: string) => {
+const makeUninstaller = (
+ config: ConfigService,
+ storage: PluginStorageService,
+ pluginsDir: string,
+ releaseTakeovers?: (pluginId: string) => Promise<void>,
+) => {
const plugins = new Map<string, PluginInstance>();
const uninstaller = new PluginUninstaller(
createLogger('PluginLoaderService'),
@@ -26,6 +31,8 @@ const makeUninstaller = (config: ConfigService, storage: PluginStorageService, p
plugins.delete(pluginId);
return Promise.resolve();
},
+ null,
+ releaseTakeovers,
);
return { uninstaller, plugins };
};
@@ -159,6 +166,31 @@ describe('PluginUninstaller — uninstall', () => {
seedEntry(storage, 'core-engine', true);
await expect(uninstaller.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);
});
+
+ // A takeover the plugin held would keep every other plugin silent on that chat for good.
+ it('hands the takeovers of the plugin back once it is gone, and survives that failing', async () => {
+ const dir = writeUserPlugin('relay');
+ seedEntry(storage, 'relay');
+ const release = jest.fn().mockResolvedValue(undefined);
+ const config = { get: (k: string) => (k === 'plugins.dir' ? pluginsDir : tmpDir) } as unknown as ConfigService;
+ const withRelease = makeUninstaller(config, storage, pluginsDir, release);
+ withRelease.plugins.set('relay', loadedUserPlugin('relay', dir));
+
+ await withRelease.uninstaller.uninstallPlugin('relay');
+
+ expect(release).toHaveBeenCalledWith('relay');
+ expect(fs.existsSync(dir)).toBe(false);
+
+ const dir2 = writeUserPlugin('relay2');
+ seedEntry(storage, 'relay2');
+ const failing = makeUninstaller(config, storage, pluginsDir, () => {
+ throw new Error('mapping store unavailable');
+ });
+ failing.plugins.set('relay2', loadedUserPlugin('relay2', dir2));
+
+ await expect(failing.uninstaller.uninstallPlugin('relay2')).resolves.toBeUndefined();
+ expect(fs.existsSync(dir2)).toBe(false);
+ });
});
describe('PluginUninstaller — uninstall cleans up split-dir plugin storage', () => {
diff --git a/src/core/plugins/plugin-uninstaller.ts b/src/core/plugins/plugin-uninstaller.ts
index 12a6c13bc..78514e8da 100644
--- a/src/core/plugins/plugin-uninstaller.ts
+++ b/src/core/plugins/plugin-uninstaller.ts
@@ -31,6 +31,8 @@ export class PluginUninstaller {
private readonly unload: (pluginId: string) => Promise<void>,
/** The legacy plugin tree the boot scan also loads from, or null when PLUGINS_DIR is set. */
private readonly legacyPluginsDir: string | null = null,
+ /** Hands the chats the plugin took over back to the bot; the conversation store is not this file's. */
+ private readonly releaseTakeovers?: (pluginId: string) => Promise<void>,
) {}
/** <root>/<id> for an id with no loaded package, or null if the id escapes that root. */
@@ -85,6 +87,18 @@ export class PluginUninstaller {
// Best-effort, and strictly that one plugin's directory.
this.pluginStorage.deletePluginData(pluginId);
+ // A takeover the plugin held keeps every other plugin silent on that chat, and nothing is left to
+ // hand it back. Best-effort: the plugin is gone either way.
+ try {
+ await this.releaseTakeovers?.(pluginId);
+ } catch (error) {
+ this.logger.warn(`Could not release the takeovers of uninstalled plugin ${pluginId}`, {
+ pluginId,
+ action: 'plugin_takeover_release_failed',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+
this.logger.log(`Plugin uninstalled: ${pluginId}`, { pluginId, action: 'plugin_uninstalled' });
}
}
diff --git a/src/modules/integration/conversation-mapping.service.spec.ts b/src/modules/integration/conversation-mapping.service.spec.ts
index 8a67bb117..9548f9091 100644
--- a/src/modules/integration/conversation-mapping.service.spec.ts
+++ b/src/modules/integration/conversation-mapping.service.spec.ts
@@ -232,6 +232,23 @@ describe('ConversationMappingService', () => {
});
});
+ it('releaseTakeovers hands a plugin back its chats and leaves the mappings and other plugins alone', async () => {
+ await service.upsert(key, 'conv-1', { handoverState: 'human' });
+ await service.upsert({ ...key, chatId: 'chat-2' }, 'conv-2', { handoverState: 'closed' });
+ await service.upsert({ ...key, pluginId: 'other', chatId: 'chat-3' }, 'conv-3', { handoverState: 'human' });
+ expect(await service.findHandoverForChat('sess-1', 'chat-1')).toMatchObject({ handoverState: 'human' });
+
+ await service.releaseTakeovers('chatwoot');
+
+ expect(await service.findHandoverForChat('sess-1', 'chat-1')).toBeNull();
+ expect(await service.findHandoverForChat('sess-1', 'chat-2')).toBeNull();
+ expect((await service.get(key))?.providerConversationId).toBe('conv-1');
+ expect(await service.findHandoverForChat('sess-1', 'chat-3')).toMatchObject({
+ pluginId: 'other',
+ handoverState: 'human',
+ });
+ });
+
// SQLite serves every repository from one connection, so a transaction the insert opens is shared with
// the writes made while it is open, and the rollback of the conflict it expects would undo them too.
it('does not undo a write made while an upsert is refused for a bound conversation', async () => {
diff --git a/src/modules/integration/conversation-mapping.service.ts b/src/modules/integration/conversation-mapping.service.ts
index 4cc7420a8..4fbc4218c 100644
--- a/src/modules/integration/conversation-mapping.service.ts
+++ b/src/modules/integration/conversation-mapping.service.ts
@@ -97,6 +97,14 @@ export class ConversationMappingService implements PluginConversationMappingPort
}
}
+ /**
+ * A takeover is scoped to the chat, not to the plugin, and silences every other plugin there. The
+ * mappings stay, so a plugin installed again keeps its provider conversations; only the takeovers go.
+ */
+ async releaseTakeovers(pluginId: string): Promise<void> {
+ await this.repo.update({ pluginId, handoverState: In(['human', 'closed']) }, { handoverState: 'bot' });
+ }
+
get(key: MappingKey): Promise<ConversationMapping | null> {
return this.repo.findOne({ where: key });
}