Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): keep a saved engine when an environment variable pins one
Yudhi Armyndharis75306238dc66
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex faf8cdab2..238be33e5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- **A reconnect now force-kills a wedged browser before relaunching** — when a Chromium that stopped responding also refused to shut down, the automatic reconnect launched its replacement against the same browser profile while the old process could still be holding it, so the retry could fail on the very condition it was recovering from.+- **Saving the Infrastructure page no longer overwrites a saved engine with the one an environment variable pins** — the engine radio seeded from the running engine even when `ENGINE_TYPE` pinned it, so saving any field on that page persisted the pinned value into `data/.env.generated` and unsetting the variable could no longer restore the engine the operator had chosen.- **A WhatsApp-initiated unlink now clears a session's stored credentials once rather than twice** — whatsapp-web.js can raise the logout event more than once for a single unlink and nothing deduplicated it, so the repeats raced each other and a still-open browser into the `ENOTEMPTY` failure the removal now carries the retry budget to survive.- **A reaction to a message the gateway never stored no longer vanishes** — the `message.reaction` webhook and the dashboard stream were both gated on the stored row, so a reaction to an ephemeral message, or to one that arrived before the session went live, was dropped with no error and no log.- **`MEDIA_DOWNLOAD_ENABLED` is now validated at boot** — it is read as "anything that is not `false`/`0`/`no`", so a typo left inbound media being decrypted and base64-inlined into every message row instead of disabling it. Only `true`/`false`/`1`/`0`/`yes`/`no` are accepted now, so a spelling like `on` that used to work will fail startup until it is changed.diff --git a/dashboard/src/hooks/useInfraConfigForm.ts b/dashboard/src/hooks/useInfraConfigForm.tsindex 089628809..38921fa48 100644--- a/dashboard/src/hooks/useInfraConfigForm.ts+++ b/dashboard/src/hooks/useInfraConfigForm.ts@@ -124,10 +124,10 @@ export function useInfraConfigForm(// operator's in-progress, unsaved edits. A successful save restarts → full page reload, re-arming it.const formHydrated = useRef(false);- // The engine radio seeds ONCE from the running engine (which honours a real ENGINE_TYPE env override- // over the saved .env.generated value — see the effect below), then is never re-stamped by a background- // refetch. `engineTouched` additionally wins over a late first resolution: if the operator clicked a- // different engine before /engines/current resolved, the delayed seed must not revert their selection (#735).+ // The engine radio seeds ONCE — from the running engine, or from the saved file when ENGINE_TYPE is+ // pinned (see the effect below) — then is never re-stamped by a background refetch. `engineTouched`+ // additionally wins over a late first resolution: if the operator clicked a different engine before+ // the seed resolved, the delayed seed must not revert their selection (#735).const engineHydrated = useRef(false);const engineTouched = useRef(false);@@ -209,15 +209,23 @@ export function useInfraConfigForm(if (infraStatus && savedConfig) formHydrated.current = true;}, [infraStatus, savedConfig]);- // The active engine reflects what's actually running (honours a real-env ENGINE_TYPE override),- // so seed the selected radio from it rather than the saved .env.generated value — but only ONCE, and- // never after the operator has touched it. Without this guard a background refetch (or a late first- // resolution racing an early click) re-stamps the running engine over an in-progress selection (#735).+ // The active engine reflects what's actually running, so seed the selected radio from it rather than+ // the saved .env.generated value — but only ONCE, and never after the operator has touched it. Without+ // that guard a background refetch (or a late first resolution racing an early click) re-stamps the+ // running engine over an in-progress selection (#735).+ //+ // When ENGINE_TYPE is PINNED by the environment the running engine is that pin, not a choice anyone+ // made here. Seeding from it would present the pin as the operator's own selection and then persist it+ // over their saved engine on the next save of any field on this page — so unsetting the variable could+ // no longer restore what they picked. A pinned deployment seeds from the saved file instead; the card+ // badge still reports what is actually running (#1082).useEffect(() => {- if (!currentEngine || engineHydrated.current || engineTouched.current) return;+ if (!infraStatus || engineHydrated.current || engineTouched.current) return;+ const seed = infraStatus.envPinned?.includes('ENGINE_TYPE') ? savedConfig?.engine.type : currentEngine;+ if (!seed) return;engineHydrated.current = true;- setEngineConfig(prev => (prev.type === currentEngine ? prev : { ...prev, type: currentEngine }));- }, [currentEngine]);+ setEngineConfig(prev => (prev.type === seed ? prev : { ...prev, type: seed }));+ }, [currentEngine, infraStatus, savedConfig]);const updateDbConfig = (key: keyof DatabaseConfig, value: string | number | boolean) =>setDbConfig(prev => ({ ...prev, [key]: value }));diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.tsindex 99145797e..489340160 100644--- a/dashboard/src/pages/Infrastructure.test.ts+++ b/dashboard/src/pages/Infrastructure.test.ts@@ -78,6 +78,18 @@ const ENGINES: Engine[] = [const CURRENT_ENGINE = { engineType: 'whatsapp-web.js' };+// Per-test fixture swaps for the three responses whose disagreement the engine-pin tests turn on+// (running engine vs saved engine vs whether ENGINE_TYPE is pinned). Reset in afterEach so the+// smoke tests above keep seeing the stock fixtures.+let overrides: { status?: InfraStatus; saved?: SavedConfig; currentEngine?: { engineType: string } } = {};++// ENGINE_TYPE supplied by the container environment, so the dashboard cannot change it.+const PINNED_STATUS: InfraStatus = { ...INFRA_STATUS, envPinned: ['ENGINE_TYPE'] };++// The operator's saved choice, deliberately DIFFERENT from the running engine — that disagreement is+// the whole subject of these tests, and the stock fixtures agree on whatsapp-web.js.+const SAVED_BAILEYS: SavedConfig = { ...SAVED_CONFIG, engine: { ...SAVED_CONFIG.engine, type: 'baileys' } };+function jsonResponse(data: unknown, status = 200): Response {return new Response(JSON.stringify(data), {status,@@ -123,10 +135,13 @@ function installFetchStub(): void {}fetchCalls.push({ method, path, body });- if (method === 'GET' && path === '/api/infra/status') return Promise.resolve(jsonResponse(INFRA_STATUS));- if (method === 'GET' && path === '/api/infra/config') return Promise.resolve(jsonResponse(SAVED_CONFIG));+ if (method === 'GET' && path === '/api/infra/status')+ return Promise.resolve(jsonResponse(overrides.status ?? INFRA_STATUS));+ if (method === 'GET' && path === '/api/infra/config')+ return Promise.resolve(jsonResponse(overrides.saved ?? SAVED_CONFIG));if (method === 'GET' && path === '/api/infra/engines') return Promise.resolve(jsonResponse(ENGINES));- if (method === 'GET' && path === '/api/infra/engines/current') return Promise.resolve(jsonResponse(CURRENT_ENGINE));+ if (method === 'GET' && path === '/api/infra/engines/current')+ return Promise.resolve(jsonResponse(overrides.currentEngine ?? CURRENT_ENGINE));if (method === 'PUT' && path === '/api/infra/config') {return Promise.resolve(jsonResponse({ message: 'Configuration saved', saved: true, envPath: '.env.generated', profiles: [] }),@@ -202,6 +217,7 @@ afterEach(() => {rtl.cleanup();queryClient?.clear();queryClient = undefined;+ overrides = {};});function renderInfrastructure(): { container: HTMLElement } {@@ -290,3 +306,73 @@ test('a successful save opens the restart modal', async () => {within(dialog).getByRole('button', { name: 'Restart Now' });within(dialog).getByRole('button', { name: 'Restart Later' });});++// ── The engine radio's seed source (#1082) ───────────────────────────────────+// ENGINES fixture order fixes the radio order: [0] whatsapp-web.js, [1] baileys.++function engineRadios(container: HTMLElement): HTMLInputElement[] {+ return Array.from(container.querySelectorAll('input[name="engineType"]'));+}++// Waits for the /config hydrate effect, which is the last of the two seeding effects to land. Uses a+// DATABASE field on purpose: the engine detail fields render only for whatsapp-web.js, so waiting on+// one of those would vanish the moment a test seeds the radio to baileys.+async function awaitConfigHydrated(container: HTMLElement): Promise<void> {+ await rtl.waitFor(() => assert.equal(fieldInput(container, 'Username').value, 'openwa_admin'));+}++test('the engine radio seeds from the running engine when ENGINE_TYPE is not pinned', async () => {+ const { screen } = rtl;+ resetFetchCalls();+ // Running and saved disagree, but nothing pins ENGINE_TYPE — the running engine still wins, because+ // a save IS able to change it and the radio should show what is actually in effect. Pins the+ // pre-existing behaviour, so an implementation that always seeded from the saved file would fail here.+ overrides = { saved: SAVED_BAILEYS };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitConfigHydrated(container);++ assert.equal(+ engineRadios(container)[0].checked,+ true,+ 'expected the running engine (whatsapp-web.js) to be selected',+ );+});++test('the engine radio seeds from the saved engine when ENGINE_TYPE is pinned', async () => {+ const { screen, waitFor } = rtl;+ resetFetchCalls();+ overrides = { status: PINNED_STATUS, saved: SAVED_BAILEYS };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitConfigHydrated(container);++ // The running engine is the PINNED value, not a choice the operator made, so showing it would+ // present the pin as their selection.+ await waitFor(() =>+ assert.equal(engineRadios(container)[1].checked, true, 'expected the saved engine (baileys) to be selected'),+ );+});++test('saving while ENGINE_TYPE is pinned does not write the running engine over the saved one', async () => {+ const { screen, waitFor, fireEvent } = rtl;+ resetFetchCalls();+ overrides = { status: PINNED_STATUS, saved: SAVED_BAILEYS };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitConfigHydrated(container);++ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));++ // The operator never touched the engine here. Persisting the pinned value would destroy the choice+ // held in data/.env.generated, so unsetting the variable later could not restore it.+ await waitFor(() => {+ const call = findFetchCall('PUT', '/api/infra/config');+ assert.ok(call, 'expected a PUT to /infra/config');+ const body = call!.body as { engine?: { type?: string } };+ assert.equal(body.engine?.type, 'baileys');+ });+});