Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): report which environment variable pins a setting

Yudhi Armyndharis1bb1da7656f8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 009ac8625..c0dc2f580 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
- **A whatsapp-web.js session failing with `Execution context was destroyed` showed a bare Puppeteer error with no next step** — the advisory naming the likely stale browser profile went only to the server log, so the session card now carries a short form of it too.
+- **Infrastructure reported "Pinned by an environment variable" for any unapplied change, without naming the variable** — the gateway now reports which settings a higher-precedence layer actually supplies, so a real pin names its variable, a saved-but-not-restarted change says so instead, and the Engine card gained the notice it never had.
## [0.14.1] - 2026-08-05
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index c83146cc8..0ecebbbe0 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -782,7 +782,8 @@
"toasts": {
"saveFailed": "فشل الحفظ"
},
- "envPinNote": "مُثبَّت عبر متغيّر بيئة — هذه هي القيمة قيد التشغيل؛ لن تُطبَّق تغييرات لوحة التحكّم حتى يُلغى هذا المتغيّر.",
+ "envPinNote": "مُثبَّت عبر متغيّر البيئة {{name}} — هذه هي القيمة قيد التشغيل؛ لن تُطبَّق تغييرات لوحة التحكّم حتى يُلغى هذا المتغيّر.",
+ "pendingRestartNote": "تم الحفظ ولكن لم يُطبَّق بعد — أعد تشغيل الخادم ليصبح هذا التغيير ساريًا.",
"migration": {
"title": "تنبيه — هذا يُغيِّر خلفية البيانات",
"dbWarning": "تبدأ قاعدة البيانات الجديدة فارغة. نزِّل نسخة احتياطية من بياناتك الحالية الآن (وأنت لا تزال على قاعدة البيانات القديمة)، ثم استعدها بعد إعادة التشغيل.",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index 6ce11373d..474dd6fbc 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -748,7 +748,8 @@
"disconnected": "Getrennt",
"disabled": "Deaktiviert"
},
- "envPinNote": "Durch eine Umgebungsvariable festgelegt — dies ist der aktuell verwendete Wert. Änderungen im Dashboard werden erst angewendet, wenn diese Variable entfernt wurde.",
+ "envPinNote": "Durch die Umgebungsvariable {{name}} festgelegt — dies ist der aktuell verwendete Wert. Änderungen im Dashboard werden erst wirksam, wenn diese Variable entfernt wird.",
+ "pendingRestartNote": "Gespeichert, aber noch nicht übernommen — starten Sie den Server neu, damit diese Änderung wirksam wird.",
"migration": {
"title": "Achtung — dadurch wird das Daten-Backend geändert",
"dbWarning": "Die neue Datenbank ist zunächst leer. Lade jetzt eine Sicherung deiner aktuellen Daten herunter, solange noch die alte Datenbank aktiv ist, und stelle sie nach dem Neustart wieder her.",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index b79c9e222..6be949090 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -748,7 +748,8 @@
"disconnected": "Disconnected",
"disabled": "Disabled"
},
- "envPinNote": "Pinned by an environment variable — this is the running value; dashboard changes won't apply until that variable is unset.",
+ "envPinNote": "Pinned by the environment variable {{name}} — this is the running value; dashboard changes won't apply until that variable is unset.",
+ "pendingRestartNote": "Saved, but not applied yet — restart the server for this change to take effect.",
"migration": {
"title": "Heads up — this changes the data backend",
"dbWarning": "The new database starts empty. Download a backup of your current data now (while still on the old database), then restore it after the restart.",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index f6bacfca7..ea56f0b61 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "Error al guardar"
},
- "envPinNote": "Fijado por una variable de entorno: este es el valor en ejecución; los cambios del panel no se aplicarán hasta que esa variable se elimine.",
+ "envPinNote": "Fijado por la variable de entorno {{name}}: este es el valor en ejecución; los cambios del panel no se aplicarán hasta que esa variable se elimine.",
+ "pendingRestartNote": "Guardado, pero aún no aplicado: reinicia el servidor para que este cambio surta efecto.",
"migration": {
"title": "Atención: esto cambia el backend de datos",
"dbWarning": "La nueva base de datos comienza vacía. Descarga ahora una copia de seguridad de tus datos actuales (mientras sigues en la base de datos anterior) y luego restáurala después del reinicio.",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index e0208be24..f018021d0 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "Échec de l'enregistrement"
},
- "envPinNote": "Défini par une variable d'environnement — c'est la valeur en cours d'exécution ; les modifications du tableau de bord ne s'appliqueront pas tant que cette variable ne sera pas supprimée.",
+ "envPinNote": "Défini par la variable d'environnement {{name}} — c'est la valeur en cours d'exécution ; les modifications du tableau de bord ne s'appliqueront pas tant que cette variable n'est pas supprimée.",
+ "pendingRestartNote": "Enregistré, mais pas encore appliqué — redémarrez le serveur pour que cette modification prenne effet.",
"migration": {
"title": "Attention — cela change le backend de données",
"dbWarning": "La nouvelle base de données démarre vide. Téléchargez dès maintenant une sauvegarde de vos données actuelles (tant que vous êtes encore sur l'ancienne base de données), puis restaurez-la après le redémarrage.",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 33e492103..05a66cba8 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -776,7 +776,8 @@
"toasts": {
"saveFailed": "השמירה נכשלה"
},
- "envPinNote": "מקובע על ידי משתנה סביבה — זהו הערך הפעיל; שינויים בלוח הבקרה לא ייכנסו לתוקף עד שמשתנה זה יבוטל.",
+ "envPinNote": "מקובע על ידי משתנה הסביבה {{name}} — זהו הערך הפעיל; שינויים בלוח הבקרה לא ייכנסו לתוקף עד שמשתנה זה יבוטל.",
+ "pendingRestartNote": "נשמר, אך טרם הוחל — הפעילו מחדש את השרת כדי שהשינוי ייכנס לתוקף.",
"migration": {
"title": "שימו לב — פעולה זו משנה את מנגנון אחסון הנתונים",
"dbWarning": "מסד הנתונים החדש מתחיל ריק. הורידו עכשיו גיבוי של הנתונים הנוכחיים (בעודכם עדיין על מסד הנתונים הישן), ולאחר מכן שחזרו אותו לאחר ההפעלה מחדש.",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 5ef76583e..0632e4fe8 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "Salvataggio Fallito"
},
- "envPinNote": "Fissato da una variabile d'ambiente: questo è il valore in esecuzione; le modifiche dalla dashboard non avranno effetto finché la variabile non viene rimossa.",
+ "envPinNote": "Fissato dalla variabile d'ambiente {{name}}: questo è il valore in esecuzione; le modifiche dalla dashboard non verranno applicate finché quella variabile non viene rimossa.",
+ "pendingRestartNote": "Salvato, ma non ancora applicato: riavvia il server perché questa modifica abbia effetto.",
"migration": {
"title": "Attenzione: questa operazione cambia il backend dei dati",
"dbWarning": "Il nuovo database parte vuoto. Scarica ora un backup dei tuoi dati attuali (mentre sei ancora sul vecchio database), poi ripristinalo dopo il riavvio.",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 05001cc70..50d2709de 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -748,7 +748,8 @@
"disconnected": "연결 끊김",
"disabled": "사용 안 함"
},
- "envPinNote": "환경 변수로 고정됨 — 현재 실행 중인 값이며, 해당 변수를 해제해야 대시보드 변경 사항이 적용됩니다.",
+ "envPinNote": "환경 변수 {{name}}(으)로 고정됨 — 현재 실행 중인 값이며, 해당 변수를 해제해야 대시보드 변경 사항이 적용됩니다.",
+ "pendingRestartNote": "저장되었지만 아직 적용되지 않았습니다 — 이 변경 사항을 적용하려면 서버를 다시 시작하세요.",
"migration": {
"title": "주의 — 데이터 백엔드가 변경됩니다",
"dbWarning": "새 데이터베이스는 비어 있는 상태로 시작됩니다. 지금(기존 데이터베이스에 있는 동안) 현재 데이터를 백업한 후 재시작이 끝나면 복원하세요.",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index a7edae498..74bd60c85 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "Erro ao salvar"
},
- "envPinNote": "Fixado por uma variável de ambiente: este é o valor em execução; as alterações do painel não serão aplicadas até que essa variável seja removida.",
+ "envPinNote": "Fixado pela variável de ambiente {{name}}: este é o valor em execução; as alterações do painel não serão aplicadas até que essa variável seja removida.",
+ "pendingRestartNote": "Salvo, mas ainda não aplicado: reinicie o servidor para que esta alteração tenha efeito.",
"migration": {
"title": "Atenção: isso altera o backend de dados",
"dbWarning": "O novo banco de dados começa vazio. Baixe agora um backup dos seus dados atuais (enquanto ainda estiver no banco de dados anterior) e restaure-o após reiniciar.",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 585d3a91f..90e523423 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "సేవ్ చేయడం విఫలమైంది"
},
- "envPinNote": "ఒక ఎన్విరాన్‌మెంట్ వేరియబుల్ ద్వారా పిన్ చేయబడింది — ఇది ప్రస్తుతం అమలులో ఉన్న విలువ; ఆ వేరియబుల్‌ను తీసివేసే వరకు డ్యాష్‌బోర్డ్ మార్పులు వర్తించవు.",
+ "envPinNote": "{{name}} ఎన్విరాన్‌మెంట్ వేరియబుల్ ద్వారా పిన్ చేయబడింది — ఇది ప్రస్తుతం అమలులో ఉన్న విలువ; ఆ వేరియబుల్‌ను తొలగించే వరకు డాష్‌బోర్డ్ మార్పులు వర్తించవు.",
+ "pendingRestartNote": "సేవ్ చేయబడింది, కానీ ఇంకా వర్తించలేదు — ఈ మార్పు అమలులోకి రావడానికి సర్వర్‌ను పునఃప్రారంభించండి.",
"migration": {
"title": "గమనిక — ఇది డేటా బ్యాకెండ్‌ను మారుస్తుంది",
"dbWarning": "కొత్త డేటాబేస్ ఖాళీగా ప్రారంభమవుతుంది. ఇప్పుడే (ఇంకా పాత డేటాబేస్‌లో ఉన్నప్పుడే) మీ ప్రస్తుత డేటా బ్యాకప్‌ను డౌన్‌లోడ్ చేయండి, ఆపై రీస్టార్ట్ తర్వాత దాన్ని పునరుద్ధరించండి.",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 04892153a..c43ae5d2d 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "保存失败"
},
- "envPinNote": "已由环境变量锁定 —— 此为当前运行值;在取消该变量之前,仪表盘的更改不会生效。",
+ "envPinNote": "已由环境变量 {{name}} 锁定 —— 此为当前运行值;在取消该变量之前,仪表盘的更改不会生效。",
+ "pendingRestartNote": "已保存,但尚未生效 —— 请重启服务器以应用此更改。",
"migration": {
"title": "请注意 —— 此操作将更改数据后端",
"dbWarning": "新数据库将从空白状态开始。请立即(在仍使用旧数据库时)下载当前数据的备份,然后在重启后恢复。",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index d2db8878d..dccaa589c 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -767,7 +767,8 @@
"toasts": {
"saveFailed": "儲存失敗"
},
- "envPinNote": "已由環境變數鎖定 — 這是正在運行的值;在取消設定該變數之前,儀表板的變更不會生效。",
+ "envPinNote": "已由環境變數 {{name}} 鎖定 — 這是正在運行的值;在取消設定該變數之前,儀表板的變更不會生效。",
+ "pendingRestartNote": "已儲存,但尚未生效 — 請重新啟動伺服器以套用此變更。",
"migration": {
"title": "請注意 — 此操作會更改資料後端",
"dbWarning": "新資料庫會以空白狀態啟動。請立即下載目前資料的備份(趁仍在舊資料庫時),然後在重新啟動後還原。",
diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsx
index a0069c862..1d713b194 100644
--- a/dashboard/src/pages/Infrastructure.tsx
+++ b/dashboard/src/pages/Infrastructure.tsx
@@ -124,27 +124,29 @@ export function Infrastructure() {
);
}
- // A setting whose RUNNING value (/status) differs from the SAVED file (/config) is being pinned by a
- // host/.env environment variable, which wins at runtime — so a dashboard change to it won't apply
- // until that variable is unset. Surface that honestly instead of letting the control look effective.
- const dbPinnedByEnv =
- !configSave.savePending &&
- !!infraStatus &&
- !!savedConfig &&
- infraStatus.database.type !== savedConfig.database.type;
- const redisPinnedByEnv =
- !configSave.savePending &&
- !!infraStatus &&
- !!savedConfig &&
- infraStatus.redis.enabled !== savedConfig.redis.enabled;
- const storagePinnedByEnv =
- !configSave.savePending && !!infraStatus && !!savedConfig && infraStatus.storage.type !== savedConfig.storage.type;
- const envPinNote = (pinned: boolean) =>
- pinned ? (
+ // A control here can be ineffective for two different reasons, and they need OPPOSITE advice:
+ // - an environment variable (or a project .env) supplies the value, so it outranks anything saved
+ // here until the deployment changes — the gateway reports this in `envPinned`;
+ // - the value WAS saved and the server has not been restarted yet — a restart applies it.
+ // Both look identical as "running differs from saved", which is why drift alone used to be reported
+ // as an environment pin even on a stock stack with no variable set anywhere (#1082).
+ const settingNote = (envKey: string, running: unknown, saved: unknown) => {
+ if (infraStatus?.envPinned?.includes(envKey)) {
+ return (
+ <p className="env-pin-note">
+ <AlertTriangle size={14} /> {t('infrastructure.envPinNote', { name: envKey })}
+ </p>
+ );
+ }
+ // savePending suppresses the note only while the request is in flight; afterwards the saved value
+ // genuinely differs from the running one until a restart, and saying so is the whole point.
+ const pendingRestart = !configSave.savePending && !!infraStatus && !!savedConfig && running !== saved;
+ return pendingRestart ? (
<p className="env-pin-note">
- <AlertTriangle size={14} /> {t('infrastructure.envPinNote')}
+ <AlertTriangle size={14} /> {t('infrastructure.pendingRestartNote')}
</p>
) : null;
+ };
return (
<div className="infrastructure-page">
@@ -162,7 +164,7 @@ export function Infrastructure() {
● {configForm.dbConfig.type === 'postgres' ? 'PostgreSQL' : 'SQLite'}
</span>
</div>
- {envPinNote(dbPinnedByEnv)}
+ {settingNote('DATABASE_TYPE', infraStatus.database.type, savedConfig?.database.type)}
<div className="radio-group">
<label className={`radio-option ${configForm.dbConfig.type === 'sqlite' ? 'selected' : ''}`}>
@@ -364,6 +366,9 @@ export function Infrastructure() {
</div>
<span className="status-indicator connected">● {currentEngine || configForm.engineConfig.type}</span>
</div>
+ {/* The radio re-seeds from the RUNNING engine, so without this a pinned engine silently
+ snapped back after a restart and read as "the save did nothing" (#1082). */}
+ {settingNote('ENGINE_TYPE', infraStatus.engine.type, savedConfig?.engine.type)}
<div className="radio-group">
{engines.map(engine => (
@@ -463,7 +468,7 @@ export function Infrastructure() {
: t('infrastructure.statusLabels.disabled')}
</span>
</div>
- {envPinNote(redisPinnedByEnv)}
+ {settingNote('REDIS_ENABLED', infraStatus.redis.enabled, savedConfig?.redis.enabled)}
<div
className="toggle-row"
@@ -634,7 +639,7 @@ export function Infrastructure() {
);
})()}
</div>
- {envPinNote(storagePinnedByEnv)}
+ {settingNote('STORAGE_TYPE', infraStatus.storage.type, savedConfig?.storage.type)}
<div className="radio-group">
<label className={`radio-option ${configForm.storageConfig.type === 'local' ? 'selected' : ''}`}>
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 1ddf020e6..3cd3f4a5d 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -451,6 +451,15 @@ export interface InfraStatus {
webVersion?: string | null;
webVersionSource?: 'pinned' | 'auto' | 'native';
};
+ /**
+ * Editable settings supplied by a layer above `data/.env.generated` (the container environment or a
+ * project `.env`), which therefore cannot be changed from this page until that layer is. Reported by
+ * the gateway rather than inferred from a running-vs-saved mismatch, because that mismatch is also
+ * what an unrestarted save looks like and the two need opposite advice (#1082).
+ *
+ * Optional only because a dashboard can be served by a gateway that predates the field.
+ */
+ envPinned?: string[];
}
// Saved infrastructure config (from data/.env.generated) used to hydrate the form.
diff --git a/src/config/env-precedence.spec.ts b/src/config/env-precedence.spec.ts
index 0e3eb4e57..659b89c07 100644
--- a/src/config/env-precedence.spec.ts
+++ b/src/config/env-precedence.spec.ts
@@ -2,7 +2,7 @@ import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as dotenv from 'dotenv';
-import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';
+import { clearBlankEnv, BLANK_SHADOWED_ENV_KEYS, recordPinnedEnvKeys, isEnvPinned } from './env-precedence';
import { computeFeatureFlags } from './feature-flags';
describe('clearBlankEnv', () => {
@@ -21,6 +21,40 @@ describe('clearBlankEnv', () => {
});
});
+// #1082: the dashboard used to INFER an environment pin from "running value != saved value", which is
+// also true right after a save that has not been restarted yet. This snapshot is the real signal.
+describe('isEnvPinned — does a layer above data/.env.generated supply this key?', () => {
+ it('counts a key present before the saved file is merged, and not one the file supplies', () => {
+ // Mirrors load-env's order: the snapshot is taken after process.env and .env, before the file.
+ const env: NodeJS.ProcessEnv = { ENGINE_TYPE: 'whatsapp-web.js' };
+ recordPinnedEnvKeys(env);
+ env.REDIS_ENABLED = 'true'; // supplied by data/.env.generated afterwards
+
+ expect(isEnvPinned('ENGINE_TYPE')).toBe(true);
+ expect(isEnvPinned('REDIS_ENABLED')).toBe(false);
+ });
+
+ // The load-bearing case: the bundled compose forwards `- ENGINE_TYPE=${ENGINE_TYPE:-}`, which renders
+ // blank when the operator sets nothing. clearBlankEnv deletes it BEFORE the snapshot, so a stock stack
+ // must not be told an environment variable is pinning anything.
+ it('does not count a blank compose forward as a pin', () => {
+ const env: NodeJS.ProcessEnv = { ENGINE_TYPE: '', REDIS_ENABLED: ' ' };
+ clearBlankEnv(env, BLANK_SHADOWED_ENV_KEYS);
+ recordPinnedEnvKeys(env);
+
+ expect(isEnvPinned('ENGINE_TYPE')).toBe(false);
+ expect(isEnvPinned('REDIS_ENABLED')).toBe(false);
+ });
+
+ it('counts a real value that merely repeats the default — the case BLANK_SHADOWED_ENV_KEYS cannot cover', () => {
+ const env: NodeJS.ProcessEnv = { ENGINE_TYPE: 'whatsapp-web.js' };
+ clearBlankEnv(env, BLANK_SHADOWED_ENV_KEYS);
+ recordPinnedEnvKeys(env);
+
+ expect(isEnvPinned('ENGINE_TYPE')).toBe(true);
+ });
+});
+
describe('engine-selection env precedence (ENGINE_TYPE)', () => {
// Mirrors main.ts: process.env > .env > data/.env.generated. A compose `- ENGINE_TYPE=${ENGINE_TYPE:-}`
// line forwards a blank value when the operator sets nothing; that blank must be treated as unset so
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index 481b09162..ea8b3f66a 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -143,3 +143,35 @@ export function recordOsEnvKeys(env: NodeJS.ProcessEnv = process.env): void {
export function isOsProvidedEnv(key: string): boolean {
return osEnvKeys === null || osEnvKeys.has(key);
}
+
+/**
+ * Keys already present when `data/.env.generated` is about to be merged — i.e. supplied by the host
+ * OR by the project `.env`, both of which load with `override: false` and therefore win over the
+ * dashboard-saved file for good.
+ *
+ * Distinct from `osEnvKeys` on purpose. That snapshot answers "may this value win over the file being
+ * WRITTEN?" for the save-config guard, where only a host value counts. This one answers "can the
+ * dashboard change this setting at all?", and there a project `.env` pins exactly as hard as an
+ * orchestrator variable does.
+ */
+let pinnedEnvKeys: Set<string> | null = null;
+
+/** Snapshot the shadowing layers. Called by load-env immediately before `data/.env.generated` loads. */
+export function recordPinnedEnvKeys(env: NodeJS.ProcessEnv = process.env): void {
+ pinnedEnvKeys = new Set(Object.keys(env));
+}
+
+/**
+ * True when `key` is supplied by a layer above `data/.env.generated`, so saving it from the dashboard
+ * cannot take effect until that layer is changed.
+ *
+ * Defaults to FALSE with no snapshot taken (a unit test that never boots), the opposite of
+ * `isOsProvidedEnv`. Each default is the safe one for its caller: the save guard must assume an
+ * override it cannot see, while this drives a user-facing warning that must never be invented.
+ *
+ * Note `clearBlankEnv` runs BEFORE the snapshot, so a blank compose forward (`- KEY=${KEY:-}` with
+ * nothing set) is already gone and correctly does not count as a pin.
+ */
+export function isEnvPinned(key: string): boolean {
+ return pinnedEnvKeys !== null && pinnedEnvKeys.has(key);
+}
diff --git a/src/config/load-env.ts b/src/config/load-env.ts
index cc5831816..2ef9fc6cf 100644
--- a/src/config/load-env.ts
+++ b/src/config/load-env.ts
@@ -2,7 +2,7 @@ import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';
import { writeSecretFile } from '../common/utils/secret-file';
-import { clearBlankEnv, recordOsEnvKeys, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';
+import { clearBlankEnv, recordOsEnvKeys, recordPinnedEnvKeys, BLANK_SHADOWED_ENV_KEYS } from './env-precedence';
/**
* Load configuration into process.env BEFORE any application module is imported.
@@ -60,6 +60,12 @@ export function loadEnvironment(): void {
dotenv.config({ path: userEnvPath, override: false });
}
+ // Snapshot the layers that will SHADOW the dashboard-saved file — process env plus the .env just
+ // merged above. Taken here rather than reconstructed later because once the file is merged in, all
+ // three layers are indistinguishable inside process.env, and the Infrastructure page needs to tell
+ // "an environment variable pins this" apart from "saved, pending a restart" (#1082).
+ recordPinnedEnvKeys(process.env);
+
// 3. Dashboard-saved config (does not override .env or process env)
if (fs.existsSync(generatedEnvPath)) {
console.log('[Bootstrap] Loading saved configuration from:', generatedEnvPath);
diff --git a/src/modules/infra/infra-status.controller.spec.ts b/src/modules/infra/infra-status.controller.spec.ts
index 4531fb0f9..1d8894c3d 100644
--- a/src/modules/infra/infra-status.controller.spec.ts
+++ b/src/modules/infra/infra-status.controller.spec.ts
@@ -21,6 +21,7 @@ jest.mock('fs', () => {
});
import { InfraStatusController } from './infra-status.controller';
+import { recordPinnedEnvKeys } from '../../config/env-precedence';
describe('InfraStatusController.getStatus DB health (active SELECT 1 probe, not just isInitialized)', () => {
const build = (query: jest.Mock) => {
@@ -180,3 +181,45 @@ describe('InfraStatusController.getStatus storage (reads the real storage.localP
expect(status.storage.bucket).toBeUndefined();
});
});
+
+// #1082: the Infrastructure page used to INFER an environment pin from "running != saved", which also
+// describes a save that has not been restarted yet. getStatus now reports the real thing.
+describe('InfraStatusController.getStatus envPinned', () => {
+ const savedWebVer = process.env.WWEBJS_WEB_VERSION;
+ beforeAll(() => (process.env.WWEBJS_WEB_VERSION = 'off'));
+ afterAll(() => {
+ if (savedWebVer === undefined) delete process.env.WWEBJS_WEB_VERSION;
+ else process.env.WWEBJS_WEB_VERSION = savedWebVer;
+ });
+
+ const buildController = () => {
+ const config = { get: (_key: string, def?: unknown) => def };
+ const ds = { isInitialized: true, query: jest.fn().mockResolvedValue([{ '1': 1 }]) };
+ return new InfraStatusController(
+ config as never,
+ ds as never,
+ ds as never,
+ {} as never,
+ { isDockerAvailable: () => false } as never,
+ { isAvailable: () => Promise.resolve(false) } as never,
+ { isS3Available: () => false, refreshS3Availability: () => Promise.resolve(false) } as never,
+ );
+ };
+
+ it('reports only the editable selection keys a shadowing layer supplies', async () => {
+ // Snapshot as load-env does: ENGINE_TYPE comes from the host/.env, REDIS_ENABLED from the file.
+ recordPinnedEnvKeys({ ENGINE_TYPE: 'whatsapp-web.js', PATH: '/usr/bin' });
+
+ const status = await buildController().getStatus();
+
+ expect(status.envPinned).toEqual(['ENGINE_TYPE']);
+ // PATH is shadowing too but has no control on the page — naming it would be noise.
+ expect(status.envPinned).not.toContain('PATH');
+ });
+
+ it('reports an empty list when nothing above data/.env.generated supplies a selection key', async () => {
+ recordPinnedEnvKeys({});
+
+ expect((await buildController().getStatus()).envPinned).toEqual([]);
+ });
+});
diff --git a/src/modules/infra/infra-status.controller.ts b/src/modules/infra/infra-status.controller.ts
index 03288efa1..4a85cdc65 100644
--- a/src/modules/infra/infra-status.controller.ts
+++ b/src/modules/infra/infra-status.controller.ts
@@ -15,6 +15,7 @@ import { CacheService } from '../../common/cache/cache.service';
import { StorageService } from '../../common/storage/storage.service';
import { createLogger } from '../../common/services/logger.service';
import { readGeneratedEnv } from './generated-env';
+import { isEnvPinned } from '../../config/env-precedence';
interface InfraStatus {
// `builtIn` reflects whether OpenWA's own bundled container is actually running and backing this
@@ -37,8 +38,19 @@ interface InfraStatus {
webVersion?: string | null;
webVersionSource?: 'pinned' | 'auto' | 'native';
};
+ // Which of the settings this page can edit are supplied by a layer ABOVE data/.env.generated (the
+ // container environment or a project .env) and therefore cannot be changed from the dashboard until
+ // that layer is. Reported rather than inferred: a running-vs-saved mismatch is also what a save that
+ // has not been restarted yet looks like, and the two need opposite advice (#1082).
+ envPinned: string[];
}
+/**
+ * The keys behind the Infrastructure page's four editable selections, in card order. Only these are
+ * reported: the page has no control for anything else, so naming other variables would be noise.
+ */
+const DASHBOARD_SELECTION_ENV_KEYS = ['DATABASE_TYPE', 'REDIS_ENABLED', 'STORAGE_TYPE', 'ENGINE_TYPE'];
+
@ApiTags('infrastructure')
@Controller('infra')
// Every route here is deployment-global (data export/import, infra config, service orchestration),
@@ -204,6 +216,7 @@ export class InfraStatusController {
browserArgs,
...(engineType === 'whatsapp-web.js' ? { webVersion, webVersionSource } : {}),
},
+ envPinned: DASHBOARD_SELECTION_ENV_KEYS.filter(isEnvPinned),
};
}