Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): keep an operator-enabled plugin enabled across a restart (#856) (#858)

Yudhi Armyndharis77c3f659afb3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 54ccba88a..eb88b1b09 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **Plugins you enabled stay enabled across a restart.** Every restart of the gateway — an upgrade, a
+ host reboot, a container restart policy — silently switched off every extension plugin, with nothing
+ written to the log and nothing shown in the dashboard. An integration such as the Chatwoot adapter
+ simply stopped relaying until someone noticed and turned it back on by hand. Your enable decision is
+ now remembered separately from whether the plugin happens to be running, and the plugins you had
+ enabled are started again once the gateway has finished coming up. A plugin that fails to start is
+ logged and left disabled rather than holding up the gateway. Enabling still runs the plugin's full
+ lifecycle, and a plugin you disabled stays disabled. Nothing to do on upgrade: a plugin that is
+ enabled when you upgrade is carried over automatically ([#856](https://github.com/rmyndharis/OpenWA/issues/856)).
+
- **The chat list no longer shows a stray `0` next to every conversation.** Each row in the Chats
sidebar rendered a literal `0` where the last message's time belongs, on every chat. A conversation
with no messages reports a timestamp of zero, and the check that was meant to hide the time in that
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index dd33822e4..649acc44a 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -417,8 +417,21 @@ sub-directory with a `manifest.json` it reads the manifest, validates the requir
entry — **without running any plugin code**. Persisted config and per-session activation/config are
read back so an operator's choices survive a restart. There is **no** version-compatibility check.
-> Loading a plugin from disk never auto-enables it. A previously-enabled plugin returns as `INSTALLED`
-> after a restart and must be re-enabled — enabling is always an explicit ADMIN action.
+> Loading a plugin from disk never runs it: a load always yields `INSTALLED`. Enabling is a separate
+> step that runs the lifecycle, and happens either on an explicit ADMIN action or — for a plugin the
+> operator had already enabled — at bootstrap (see **Restore on boot** below).
+
+**Restore on boot.** `status` describes where the runtime is, so it cannot carry the operator's
+decision across a restart; the decision is persisted separately as `enabledByOperator`. On
+`onApplicationBootstrap` — after the rest of the app is wired — the loader re-enables every non-built-in
+plugin carrying that flag, so an upgrade, host reboot or container restart no longer silently switches
+off every extension ([#856](https://github.com/rmyndharis/OpenWA/issues/856)). Restoring is best-effort
+and sequential: a plugin that fails is logged (`plugin_restore_failed`), left in `ERROR`, and never
+holds up startup. Built-ins are skipped — `EngineFactory` enables the engine named by `engine.type`.
+
+> The flag is written **only** by the operator-facing enable/disable, never by the loader.
+> `onModuleDestroy` disables every running plugin during a graceful shutdown, so a loader-side write
+> would erase the decision on the way out.
**Enable.** `enablePlugin(id)` runs the lifecycle by trust tier (a synchronous lock prevents a racing
double-enable, and engines must match the configured active engine):
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index ff7a4dbda..314677a14 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -213,7 +213,7 @@ describe('PluginLoaderService — enable/config persistence', () => {
expect(loader2.getPlugin('persist-test')?.config).toEqual({ execPath: '/new/chromium', headless: true });
});
- it('reports a re-registered plugin as installed after restart even if it was enabled (no boot auto-enable, no divergence)', () => {
+ it('reports a re-registered plugin as installed: registering never runs it, and the registry agrees', () => {
loader.registerBuiltInPlugin(manifest, {}, {});
storage.setPluginStatus('persist-test', PluginStatus.ENABLED); // operator enabled it
@@ -222,7 +222,9 @@ describe('PluginLoaderService — enable/config persistence', () => {
const loader2 = new PluginLoaderService(config, new HookManager(), storage2, {} as unknown as ModuleRef);
loader2.registerBuiltInPlugin(manifest, {}, {});
- // Runtime is INSTALLED (not auto-enabled) AND the registry agrees (no enabled/installed divergence).
+ // Runtime is INSTALLED (registering does not run the lifecycle) AND the registry agrees, so there
+ // is no enabled/installed divergence. Restoring an operator-enabled plugin is a separate step that
+ // happens at bootstrap and skips built-ins — see plugin-restore-on-boot.spec.ts (#856).
expect(loader2.getPlugin('persist-test')?.status).toBe(PluginStatus.INSTALLED);
expect(storage2.getPluginStatus('persist-test')).toBe(PluginStatus.INSTALLED);
});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index ffb8437e1..f65b7711e 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, OnModuleInit, OnModuleDestroy, Optional } from '@nestjs/common';
+import { Injectable, OnApplicationBootstrap, OnModuleInit, OnModuleDestroy, Optional } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ModuleRef } from '@nestjs/core';
import { toNeutralJid, userPart } from '../../engine/identity/wa-id';
@@ -167,7 +167,7 @@ export function seedConfigDefaults(
}
@Injectable()
-export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
+export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy {
private readonly logger = createLogger('PluginLoaderService');
private readonly plugins = new Map<string, PluginInstance>();
/** Plugin ids whose enable() is in flight — a synchronous lock so concurrent enables can't double-run. */
@@ -210,6 +210,37 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
});
}
+ /**
+ * Re-enable the plugins the operator had enabled (#856). `status` cannot carry that across a restart
+ * — it describes the runtime, and loading never runs a plugin — so the decision is read from the
+ * separately persisted `enabledByOperator`. Without this, every restart (an upgrade, a host reboot, a
+ * Docker restart policy) silently switched off every extension, and a relay simply stopped relaying.
+ *
+ * Runs at bootstrap rather than in onModuleInit so the rest of the app is wired before any plugin
+ * code executes. Built-ins are skipped: an engine is enabled by EngineFactory against the configured
+ * engine.type, and enabling a non-active engine here would be rejected anyway.
+ *
+ * Best-effort and sequential, like the shutdown teardown: a plugin that cannot come back is logged
+ * and left in ERROR, and never holds up the gateway.
+ */
+ async onApplicationBootstrap(): Promise<void> {
+ const restorable = this.getAllPlugins().filter(
+ p => !p.builtIn && this.pluginStorage.getPluginEntry(p.manifest.id)?.enabledByOperator === true,
+ );
+ for (const plugin of restorable) {
+ const pluginId = plugin.manifest.id;
+ try {
+ await this.enablePlugin(pluginId);
+ } catch (error) {
+ this.logger.error(
+ `Failed to restore plugin ${pluginId} on startup; it stays disabled until re-enabled`,
+ error instanceof Error ? error.message : String(error),
+ { pluginId, action: 'plugin_restore_failed' },
+ );
+ }
+ }
+ }
+
/**
* Graceful shutdown (SIGTERM → app.close()): run onDisable for every enabled plugin so it can flush
* buffers, close connections, and persist state. Previously onDisable only ran via the REST disable
@@ -341,13 +372,18 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
* load into a 500). Does NOT enable or run the plugin — boot never auto-executes plugin code.
*/
private ensureRegistryEntry(manifest: PluginManifest, builtIn: boolean): void {
- // Reconcile the persisted entry with the freshly-loaded runtime: the runtime always loads
- // INSTALLED and is never auto-enabled on boot (enabling must stay an explicit ADMIN action that
- // runs the lifecycle), so the entry's status is (re)set to INSTALLED to match — a previously
- // enabled plugin must be re-enabled after a restart. The operator's persisted config is preserved
- // so secrets/settings survive. Best-effort: saveRegistry swallows fs errors, so a disk failure
- // never turns a load into a 500.
+ // Reconcile the persisted entry with the freshly-loaded runtime: loading never runs the plugin, so
+ // the entry's status is (re)set to INSTALLED to match the runtime. Enabling is a separate step that
+ // runs the lifecycle — at bootstrap for a plugin the operator had enabled (see
+ // onApplicationBootstrap), or on an explicit ADMIN action. The operator's persisted config and
+ // enable decision are preserved so settings/secrets and the decision itself survive. Best-effort:
+ // saveRegistry swallows fs errors, so a disk failure never turns a load into a 500.
const existing = this.pluginStorage.getPluginEntry(manifest.id);
+ // The operator's standing enable decision (#856). `status` below is deliberately reset, so intent
+ // has to live in its own field or a restart loses it. A pre-#856 row has no such field: adopt it
+ // from a status of ENABLED, which can only have been written by an explicit enable since the last
+ // boot (every boot rewrites the status to INSTALLED), so it is a faithful record of the intent.
+ const enabledByOperator = existing?.enabledByOperator ?? existing?.status === PluginStatus.ENABLED;
this.pluginStorage.setPluginEntry({
id: manifest.id,
type: manifest.type,
@@ -364,9 +400,22 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
// carried over or every boot wipes them from disk (lost after the second restart).
activeSessions: existing?.activeSessions,
sessionConfig: existing?.sessionConfig,
+ enabledByOperator,
});
}
+ /**
+ * Record that the operator wants this plugin on (or off), so bootstrap can restore it (#856).
+ *
+ * Call this ONLY from an operator-facing action. In particular it must never be called from
+ * disablePlugin: onModuleDestroy disables every running plugin during a graceful shutdown, and
+ * treating that as "the operator turned it off" would erase the decision on the way out — which is
+ * the very bug this exists to fix, just moved somewhere harder to see.
+ */
+ setOperatorEnabled(pluginId: string, enabled: boolean): void {
+ this.pluginStorage.setPluginEnabledByOperator(pluginId, enabled);
+ }
+
async enablePlugin(pluginId: string): Promise<void> {
const plugin = this.plugins.get(pluginId);
if (!plugin) {
diff --git a/src/core/plugins/plugin-restore-on-boot.spec.ts b/src/core/plugins/plugin-restore-on-boot.spec.ts
new file mode 100644
index 000000000..29c2c3826
--- /dev/null
+++ b/src/core/plugins/plugin-restore-on-boot.spec.ts
@@ -0,0 +1,157 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { ConfigService } from '@nestjs/config';
+import { ModuleRef } from '@nestjs/core';
+import { PluginLoaderService } from './plugin-loader.service';
+import { PluginStorageService } from './plugin-storage.service';
+import { HookManager } from '../hooks';
+import { PluginStatus, PluginType, type PluginManifest } from './plugin.interfaces';
+
+// #856 — an operator's enable decision must survive a restart.
+//
+// Before this, `ensureRegistryEntry` rewrote the persisted status to INSTALLED on every load, so every
+// restart silently turned off every extension plugin and destroyed the only record that it had been on.
+// The intent is now persisted separately from the runtime status, and restored at bootstrap.
+//
+// The intent is written ONLY by the operator-facing enable/disable in PluginsService, never by the
+// loader — which is what keeps the shutdown teardown (onModuleDestroy disables every enabled plugin)
+// from wiping it on the way out. The last test here guards exactly that.
+
+const manifest: PluginManifest = {
+ id: 'ext-test',
+ name: 'Ext Test',
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+};
+
+describe('PluginLoaderService — restoring the operator enable decision across a restart (#856)', () => {
+ let tmpDir: string;
+ let config: ConfigService;
+ let storage: PluginStorageService;
+ let loader: PluginLoaderService;
+ let pluginDir: string;
+
+ const makeLoader = (s: PluginStorageService): PluginLoaderService =>
+ new PluginLoaderService(config, new HookManager(), s, {} as unknown as ModuleRef);
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-restore-'));
+ config = { get: (k: string) => (k === 'dataDir' ? tmpDir : undefined) } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ loader = makeLoader(storage);
+ // A plugin on disk is only a manifest as far as loadPlugin is concerned — the code itself runs in
+ // the sandbox worker, so no module is required here.
+ pluginDir = path.join(tmpDir, 'plugins', manifest.id);
+ fs.mkdirSync(pluginDir, { recursive: true });
+ fs.writeFileSync(path.join(pluginDir, 'manifest.json'), JSON.stringify(manifest));
+ });
+
+ afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ it('carries the operator enable decision across a reload, even though the runtime status resets', () => {
+ loader.loadPlugin(pluginDir);
+ storage.setPluginEnabledByOperator(manifest.id, true);
+
+ // Restart: fresh storage re-reads registry.json, fresh loader re-loads the plugin directory.
+ const storage2 = new PluginStorageService(config);
+ makeLoader(storage2).loadPlugin(pluginDir);
+
+ const entry = storage2.getPluginEntry(manifest.id);
+ // The runtime still comes up INSTALLED — enabling runs the lifecycle and must stay an explicit step.
+ expect(entry?.status).toBe(PluginStatus.INSTALLED);
+ // ...but the operator's intent is intact, which is what bootstrap acts on.
+ expect(entry?.enabledByOperator).toBe(true);
+ });
+
+ it('adopts a pre-#856 entry that is still recorded as ENABLED, so an upgrade does not lose the decision', () => {
+ // A registry written by an older build: status ENABLED (the operator enabled it after the last
+ // boot, so nothing has overwritten it yet) and no enabledByOperator field at all.
+ loader.loadPlugin(pluginDir);
+ const entry = storage.getPluginEntry(manifest.id)!;
+ delete (entry as { enabledByOperator?: boolean }).enabledByOperator;
+ entry.status = PluginStatus.ENABLED;
+ storage.setPluginEntry(entry);
+
+ // First boot on the new build.
+ const storage2 = new PluginStorageService(config);
+ makeLoader(storage2).loadPlugin(pluginDir);
+
+ expect(storage2.getPluginEntry(manifest.id)?.enabledByOperator).toBe(true);
+ });
+
+ it('leaves a plugin the operator never enabled alone', () => {
+ loader.loadPlugin(pluginDir);
+
+ const storage2 = new PluginStorageService(config);
+ makeLoader(storage2).loadPlugin(pluginDir);
+
+ expect(storage2.getPluginEntry(manifest.id)?.enabledByOperator).toBeFalsy();
+ });
+
+ it('enables the plugins the operator had enabled, at bootstrap', async () => {
+ loader.loadPlugin(pluginDir);
+ storage.setPluginEnabledByOperator(manifest.id, true);
+
+ const storage2 = new PluginStorageService(config);
+ const loader2 = makeLoader(storage2);
+ loader2.loadPlugin(pluginDir);
+ // Stub the real enable: the lifecycle spawns a sandbox worker, which is not what this asserts.
+ const enable = jest.spyOn(loader2, 'enablePlugin').mockResolvedValue(undefined);
+
+ await loader2.onApplicationBootstrap();
+
+ expect(enable).toHaveBeenCalledWith(manifest.id);
+ });
+
+ it('does not enable a plugin the operator had not enabled', async () => {
+ const storage2 = new PluginStorageService(config);
+ const loader2 = makeLoader(storage2);
+ loader2.loadPlugin(pluginDir);
+ const enable = jest.spyOn(loader2, 'enablePlugin').mockResolvedValue(undefined);
+
+ await loader2.onApplicationBootstrap();
+
+ expect(enable).not.toHaveBeenCalled();
+ });
+
+ it('keeps booting when one plugin fails to come back, and still restores the others', async () => {
+ const second: PluginManifest = { ...manifest, id: 'ext-two', name: 'Ext Two' };
+ const secondDir = path.join(tmpDir, 'plugins', second.id);
+ fs.mkdirSync(secondDir, { recursive: true });
+ fs.writeFileSync(path.join(secondDir, 'manifest.json'), JSON.stringify(second));
+
+ const storage2 = new PluginStorageService(config);
+ const loader2 = makeLoader(storage2);
+ loader2.loadPlugin(pluginDir);
+ loader2.loadPlugin(secondDir);
+ storage2.setPluginEnabledByOperator(manifest.id, true);
+ storage2.setPluginEnabledByOperator(second.id, true);
+
+ const enable = jest
+ .spyOn(loader2, 'enablePlugin')
+ .mockImplementation((id: string) => (id === manifest.id ? Promise.reject(new Error('boom')) : Promise.resolve()));
+
+ // A plugin that cannot come back must never hold up the gateway.
+ await expect(loader2.onApplicationBootstrap()).resolves.toBeUndefined();
+ expect(enable).toHaveBeenCalledWith(second.id);
+ });
+
+ it('does not treat the shutdown teardown as the operator disabling the plugin', async () => {
+ // The regression that makes this whole design fragile: onModuleDestroy disables every enabled
+ // plugin on the way out. If teardown cleared the intent, one graceful restart would erase it and
+ // the plugin would never come back — exactly the bug being fixed, just relocated.
+ loader.loadPlugin(pluginDir);
+ storage.setPluginEnabledByOperator(manifest.id, true);
+ const plugin = loader.getPlugin(manifest.id)!;
+ plugin.status = PluginStatus.ENABLED;
+ jest.spyOn(loader, 'disablePlugin').mockResolvedValue(undefined);
+
+ await loader.onModuleDestroy();
+
+ expect(storage.getPluginEntry(manifest.id)?.enabledByOperator).toBe(true);
+ });
+});
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index ea7a22b1d..7b63d5e07 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -146,6 +146,22 @@ export class PluginStorageService {
}
}
+ /**
+ * Record the operator's standing enable decision, which outlives the process (#856). Deliberately
+ * separate from setPluginStatus: `status` tracks where the runtime is right now and is reset on every
+ * load, so writing intent through it would lose it on the next boot. Call this only from the
+ * operator-facing enable/disable — never from the shutdown teardown, which disables every running
+ * plugin and would otherwise erase the decision on the way out.
+ */
+ setPluginEnabledByOperator(pluginId: string, enabled: boolean): void {
+ const entry = this.registry.get(pluginId);
+ if (entry) {
+ entry.enabledByOperator = enabled;
+ entry.updatedAt = new Date();
+ this.saveRegistry();
+ }
+ }
+
// ============================================================================
// Config Management
// ============================================================================
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index a63aa621e..ff09b545b 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -566,4 +566,11 @@ export interface PluginRegistryEntry {
activeSessions?: string[];
// Per-session config overrides (keyed by sessionId), merged over `config` per session at hook time.
sessionConfig?: Record<string, Record<string, unknown>>;
+ // The operator's standing decision, as opposed to `status`, which is where the runtime currently is.
+ // `status` is reset to INSTALLED on every load (enabling runs the lifecycle and is never inherited
+ // from a previous process), so it cannot carry intent across a restart — a restart used to silently
+ // turn every extension plugin off (#856). This field is what bootstrap restores from. Written only by
+ // the operator-facing enable/disable, never by the loader's own teardown. Absent on pre-#856 rows,
+ // which are adopted from a lingering ENABLED status on first load.
+ enabledByOperator?: boolean;
}
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index 557752643..84ccb4a67 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -129,11 +129,17 @@ export class PluginsService {
}
if (plugin.status === PluginStatus.ENABLED) {
+ // Converge the persisted decision even on the no-op path, so a plugin left running by an older
+ // build (which had no such field) is still restored after the next restart.
+ this.pluginLoader.setOperatorEnabled(id, true);
return { success: true, message: `Plugin ${id} is already enabled` };
}
try {
await this.pluginLoader.enablePlugin(id);
+ // Only after the lifecycle actually succeeded: a plugin that failed to enable must not be
+ // restored on every boot just to fail again.
+ this.pluginLoader.setOperatorEnabled(id, true);
return { success: true, message: `Plugin ${id} enabled successfully` };
} catch (error) {
return {
@@ -155,11 +161,15 @@ export class PluginsService {
}
if (plugin.status !== PluginStatus.ENABLED) {
+ // Clear the decision here too: a plugin sitting in ERROR after a failed restore is not ENABLED,
+ // and disabling it must stop the gateway retrying it on every boot.
+ this.pluginLoader.setOperatorEnabled(id, false);
return { success: true, message: `Plugin ${id} is not enabled` };
}
try {
await this.pluginLoader.disablePlugin(id);
+ this.pluginLoader.setOperatorEnabled(id, false);
return { success: true, message: `Plugin ${id} disabled successfully` };
} catch (error) {
return {