Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): stop a bundled container a pinned host leaves unused
Yudhi Armyndharis8390740d7e8b
diff --git a/dashboard/src/hooks/useConfigSave.ts b/dashboard/src/hooks/useConfigSave.tsindex 614904675..e88e07757 100644--- a/dashboard/src/hooks/useConfigSave.ts+++ b/dashboard/src/hooks/useConfigSave.ts@@ -5,8 +5,11 @@ import { useToast } from './useToast';export interface UseConfigSaveArgs {buildPayload: () => SaveConfigPayload;- /** Called with the profile list from a successful save and the payload it sent. One-way: this hook never reads restart state. */- onSaved: (profiles: string[], payload: SaveConfigPayload) => void;+ /**+ * Called with the profile list from a successful save and the payload it sent. One-way: this hook never reads+ * restart state. The save stays in flight until a returned promise settles.+ */+ onSaved: (profiles: string[], payload: SaveConfigPayload) => void | Promise<void>;}export interface ConfigSave {@@ -30,7 +33,7 @@ export function useConfigSave({ buildPayload, onSaved }: UseConfigSaveArgs): Conconst payload = buildPayload();const result = await infraApi.saveConfig(payload);if (result.saved) {- onSaved(result.profiles || [], payload);+ await onSaved(result.profiles || [], payload);} else {toast.error(t('infrastructure.toasts.saveFailed'), result.message);}diff --git a/dashboard/src/hooks/useRestartFlow.ts b/dashboard/src/hooks/useRestartFlow.tsindex 7d2ae894c..d40a4cca2 100644--- a/dashboard/src/hooks/useRestartFlow.ts+++ b/dashboard/src/hooks/useRestartFlow.ts@@ -8,7 +8,7 @@ export type RestartStatus = 'idle' | 'restarting' | 'waiting' | 'success' | 'errexport interface RestartOpenRequest {profiles: string[];- // The built-in profiles running now; the restart stops each one the new config no longer needs.+ // The built-in profiles to stop: the restart stops each one the new config does not start.running: string[];dbSwitch: boolean;storageSwitch: boolean;@@ -26,6 +26,8 @@ export interface RestartFlow {restartWarnings: string[];pendingProfiles: string[];runningProfiles: string[];+ /** What Restart Now asks the server to stop: the running profiles the new config does not start. */+ profilesToRemove: string[];dbSwitch: boolean;storageSwitch: boolean;open: (req: RestartOpenRequest) => void;@@ -142,13 +144,13 @@ export function useRestartFlow(): RestartFlow {schedulePollTimeout(check, 3000);};+ const profilesToRemove = profiles.running.filter(p => !profiles.pending.includes(p));+const start = async () => {setRestartStatus('restarting');setRestartCountdown(30);setRestartTotal(30);- const profilesToRemove = profiles.running.filter(p => !profiles.pending.includes(p));-// Kept outside the try: the poll deadline is derived from it, and the restart call is expected to// fail sometimes (the server may go down before it answers).let estimatedTime: number | undefined;@@ -211,6 +213,7 @@ export function useRestartFlow(): RestartFlow {restartWarnings,pendingProfiles: profiles.pending,runningProfiles: profiles.running,+ profilesToRemove,dbSwitch,storageSwitch,open,diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 46876f906..8ff156e87 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -1248,6 +1248,7 @@"successTitle": "✅ الخادم جاهز","errorTitle": "❌ فشلت إعادة التشغيل","idleDesc": "تم حفظ الإعدادات في <code>.env.generated</code>.<br/>يلزم إعادة تشغيل الخادم لتطبيق التغييرات.",+ "stopsContainers": "ستوقف إعادة التشغيل أيضًا هذه الحاويات المدمجة: {{names}}. تبقى محفوظة مع بياناتها ولا تُحذف.","later": "إعادة التشغيل لاحقاً","now": "إعادة التشغيل الآن","restartingMsg": "جارٍ إعادة تشغيل الخادم... {{count}} ثانية",diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.jsonindex 911f3b835..06c135752 100644--- a/dashboard/src/i18n/locales/de.json+++ b/dashboard/src/i18n/locales/de.json@@ -1233,6 +1233,7 @@"successTitle": "Server bereit","errorTitle": "Neustart fehlgeschlagen","idleDesc": "Die Konfiguration wurde in <code>.env.generated</code> gespeichert.<br/>Ein Serverneustart ist erforderlich, um die Änderungen anzuwenden.",+ "stopsContainers": "Der Neustart stoppt außerdem diese integrierten Container: {{names}}. Sie bleiben mit ihren Daten erhalten und werden nicht gelöscht.","later": "Später neu starten","now": "Jetzt neu starten","restartingMsg": "Server wird neu gestartet... {{count}} s",diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex a4021ed54..33f41bd21 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -1233,6 +1233,7 @@"successTitle": "Server ready","errorTitle": "Restart failed","idleDesc": "Configuration has been saved to <code>.env.generated</code>.<br/>A server restart is required to apply the changes.",+ "stopsContainers": "The restart also stops these built-in containers: {{names}}. They are kept with their data, not deleted.","later": "Restart Later","now": "Restart Now","restartingMsg": "Server restarting... {{count}}s",diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex b96a3f423..6b2c88137 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -1220,6 +1220,7 @@"successTitle": "✅ Servidor listo","errorTitle": "❌ Error al reiniciar","idleDesc": "La configuración se ha guardado en <code>.env.generated</code>.<br/>Es necesario reiniciar el servidor para aplicar los cambios.",+ "stopsContainers": "El reinicio también detendrá estos contenedores integrados: {{names}}. Se conservan con sus datos; no se eliminan.","later": "Reiniciar más tarde","now": "Reiniciar ahora","restartingMsg": "Reiniciando servidor... {{count}}s",diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 015961055..ba6008a9b 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -1220,6 +1220,7 @@"successTitle": "✅ Serveur prêt","errorTitle": "❌ Échec du redémarrage","idleDesc": "La configuration a été enregistrée dans <code>.env.generated</code>.<br/>Un redémarrage du serveur est nécessaire pour appliquer les modifications.",+ "stopsContainers": "Le redémarrage arrêtera aussi ces conteneurs intégrés : {{names}}. Ils sont conservés avec leurs données, pas supprimés.","later": "Redémarrer plus tard","now": "Redémarrer maintenant","restartingMsg": "Redémarrage du serveur... {{count}}s",diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 5633b6399..b9113d461 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -1230,6 +1230,7 @@"successTitle": "✅ השרת מוכן","errorTitle": "❌ האתחול נכשל","idleDesc": "התצורה נשמרה ל-<code>.env.generated</code>.<br/>נדרש אתחול שרת כדי להחיל את השינויים.",+ "stopsContainers": "האתחול יעצור גם את הקונטיינרים המובנים האלה: {{names}}. הם נשמרים עם הנתונים שלהם ואינם נמחקים.","later": "אתחול מאוחר יותר","now": "אתחול עכשיו","restartingMsg": "השרת מתאתחל... {{count}} שניות",diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.jsonindex 83ee2a60c..4c60388aa 100644--- a/dashboard/src/i18n/locales/hi.json+++ b/dashboard/src/i18n/locales/hi.json@@ -1233,6 +1233,7 @@"successTitle": "सर्वर तैयार है","errorTitle": "पुनरारंभ विफल","idleDesc": "कॉन्फ़िगरेशन <code>.env.generated</code> में सहेज लिया गया है।<br/>परिवर्तनों को लागू करने के लिए एक सर्वर पुनरारंभ आवश्यक है।",+ "stopsContainers": "पुनरारंभ इन अंतर्निहित कंटेनरों को भी रोक देगा: {{names}}। वे अपने डेटा के साथ रखे जाते हैं, हटाए नहीं जाते।","later": "बाद में पुनरारंभ करें","now": "अभी पुनरारंभ करें","restartingMsg": "सर्वर पुनरारंभ हो रहा है... {{count}}s",diff --git a/dashboard/src/i18n/locales/id.json b/dashboard/src/i18n/locales/id.jsonindex 4e953993c..24d025b8b 100644--- a/dashboard/src/i18n/locales/id.json+++ b/dashboard/src/i18n/locales/id.json@@ -1233,6 +1233,7 @@"successTitle": "Server siap","errorTitle": "Restart gagal","idleDesc": "Konfigurasi telah disimpan ke <code>.env.generated</code>.<br/>Restart server diperlukan untuk menerapkan perubahan.",+ "stopsContainers": "Restart juga akan menghentikan container bawaan berikut: {{names}}. Container tetap disimpan beserta datanya, tidak dihapus.","later": "Restart Nanti","now": "Restart Sekarang","restartingMsg": "Me-restart server... {{count}}d",diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex f0e4ea6ca..5c94d202a 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -1220,6 +1220,7 @@"successTitle": "✅ Server Pronto","errorTitle": "❌ Riavvio Fallito","idleDesc": "La configurazione è stata salvata in <code>.env.generated</code>.<br/>È richiesto un riavvio del server per applicare le modifiche.",+ "stopsContainers": "Il riavvio arresterà anche questi container integrati: {{names}}. Vengono conservati con i loro dati, non eliminati.","later": "Riavvia Più Tardi","now": "Riavvia Ora","restartingMsg": "Riavvio del server... {{count}}s",diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.jsonindex def8be777..0688bbb57 100644--- a/dashboard/src/i18n/locales/ko.json+++ b/dashboard/src/i18n/locales/ko.json@@ -1233,6 +1233,7 @@"successTitle": "서버 준비 완료","errorTitle": "재시작 실패","idleDesc": "설정이 <code>.env.generated</code>에 저장되었습니다.<br/>변경 사항을 적용하려면 서버를 재시작해야 합니다.",+ "stopsContainers": "재시작하면 다음 내장 컨테이너도 중지됩니다: {{names}}. 컨테이너는 데이터와 함께 보존되며 삭제되지 않습니다.","later": "나중에 재시작","now": "지금 재시작","restartingMsg": "서버를 재시작하는 중... {{count}}초",diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.jsonindex 165458f8f..d2452f6f4 100644--- a/dashboard/src/i18n/locales/pt-BR.json+++ b/dashboard/src/i18n/locales/pt-BR.json@@ -1220,6 +1220,7 @@"successTitle": "✅ Servidor pronto","errorTitle": "❌ Erro ao reiniciar","idleDesc": "A configuração foi salva em <code>.env.generated</code>.<br/>É necessário reiniciar o servidor para aplicar as alterações.",+ "stopsContainers": "A reinicialização também vai parar estes contêineres integrados: {{names}}. Eles são mantidos com seus dados, não excluídos.","later": "Reiniciar depois","now": "Reiniciar agora","restartingMsg": "Reiniciando servidor... {{count}}s",diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex a8137a298..3012e1706 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -1211,6 +1211,7 @@"successTitle": "✅ సర్వర్ సిద్ధంగా ఉంది","errorTitle": "❌ రీస్టార్ట్ విఫలమైంది","idleDesc": "కాన్ఫిగరేషన్ <code>.env.generated</code> కు సేవ్ చేయబడింది.<br/>మార్పులను వర్తింపజేయడానికి సర్వర్ రీస్టార్ట్ అవసరం.",+ "stopsContainers": "రీస్టార్ట్ ఈ ఇన్-బిల్ట్ కంటైనర్లను కూడా ఆపుతుంది: {{names}}. అవి వాటి డేటాతో అలాగే ఉంచబడతాయి, తొలగించబడవు.","later": "తర్వాత రీస్టార్ట్ చేయి","now": "ఇప్పుడే రీస్టార్ట్ చేయి","restartingMsg": "సర్వర్ రీస్టార్ట్ అవుతోంది... {{count}}సెకన్లు",diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.jsonindex dc28c8100..7c25efc76 100644--- a/dashboard/src/i18n/locales/tr.json+++ b/dashboard/src/i18n/locales/tr.json@@ -1233,6 +1233,7 @@"successTitle": "Sunucu hazır","errorTitle": "Yeniden başlatma başarısız","idleDesc": "Yapılandırma <code>.env.generated</code> dosyasına kaydedildi.<br/>Değişikliklerin uygulanması için sunucunun yeniden başlatılması gerekir.",+ "stopsContainers": "Yeniden başlatma şu dahili konteynerleri de durdurur: {{names}}. Verileriyle birlikte saklanırlar, silinmezler.","later": "Daha Sonra Yeniden Başlat","now": "Şimdi Yeniden Başlat","restartingMsg": "Sunucu yeniden başlatılıyor... {{count}}s",diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex ae03a361d..4f012a4dc 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -1211,6 +1211,7 @@"successTitle": "✅ 服务器就绪","errorTitle": "❌ 重启失败","idleDesc": "配置已保存到 <code>.env.generated</code>。<br/>需要重启服务器才能应用更改。",+ "stopsContainers": "重启还会停止以下内置容器:{{names}}。它们会连同数据一起保留,不会被删除。","later": "稍后重启","now": "立即重启","restartingMsg": "服务器正在重启... {{count}} 秒",diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex 9b7146616..f450c300a 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -1211,6 +1211,7 @@"successTitle": "✅ 伺服器就緒","errorTitle": "❌ 重新啟動失敗","idleDesc": "設定已儲存到 <code>.env.generated</code>。<br/>需要重新啟動伺服器才能套用變更。",+ "stopsContainers": "重新啟動亦會停止以下內置容器:{{names}}。它們會連同數據一併保留,不會被刪除。","later": "稍後重新啟動","now": "立即重新啟動","restartingMsg": "伺服器正在重新啟動... {{count}} 秒",diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.tsindex 08327acee..b38532a95 100644--- a/dashboard/src/pages/Infrastructure.test.ts+++ b/dashboard/src/pages/Infrastructure.test.ts@@ -95,6 +95,8 @@ const CURRENT_ENGINE = { engineType: 'whatsapp-web.js' };let overrides: {status?: InfraStatus;saved?: SavedConfig;+ // What /config reports once a save went through (the file that save wrote), when it differs from `saved`.+ savedAfterSave?: SavedConfig;savedFails?: boolean;statusFails?: boolean;currentEngine?: { engineType: string };@@ -170,6 +172,9 @@ function installFetchStub(): void {}if (method === 'GET' && path === '/api/infra/config') {if (overrides.savedFails) return Promise.resolve(jsonResponse({ message: 'boom' }, 500));+ if (overrides.savedAfterSave && findFetchCall('PUT', '/api/infra/config')) {+ return Promise.resolve(jsonResponse(overrides.savedAfterSave));+ }return Promise.resolve(jsonResponse(overrides.saved ?? SAVED_CONFIG));}if (method === 'GET' && path === '/api/infra/engines') return Promise.resolve(jsonResponse(ENGINES));@@ -805,6 +810,7 @@ test('a switch from bundled to external services is warned of and stops the bund};assert.deepEqual([body.database?.builtIn, body.redis?.builtIn, body.storage?.builtIn], [false, false, false]);+ within(dialog).getByText(STOPS_ALL_THREE);fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));assert.deepEqual(findFetchCall('POST', '/api/infra/restart')!.body, {@@ -813,6 +819,9 @@ test('a switch from bundled to external services is warned of and stops the bund});});+const STOPS_ALL_THREE =+ 'The restart also stops these built-in containers: openwa-postgres, openwa-redis, openwa-minio. They are kept with their data, not deleted.';+const PENDING_BUILT_IN_NOTE ='Saved, but not applied yet: the server runs with an external service now, and a restart switches it to the built-in container.';const PENDING_EXTERNAL_NOTE =@@ -1843,6 +1852,17 @@ test('turning a running built-in Redis off asks the restart to stop its containe...SAVED_CONFIG,redis: { enabled: true, builtIn: true, builtInSet: true, host: 'redis', port: '6379', passwordSet: false },},+ savedAfterSave: {+ ...SAVED_CONFIG,+ redis: {+ enabled: true,+ builtIn: false,+ builtInSet: true,+ host: 'cache.example.com',+ port: '6379',+ passwordSet: false,+ },+ },};const { container } = renderInfrastructure();@@ -1851,9 +1871,11 @@ test('turning a running built-in Redis off asks the restart to stop its containeconst builtInRedis = toggleInput(container, 'Use Built-in Redis Container');await waitFor(() => assert.equal(builtInRedis.checked, true));fireEvent.click(builtInRedis);+ fireEvent.change(fieldInput(card(container, 'Redis'), 'Host'), { target: { value: 'cache.example.com' } });fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));const dialog = await screen.findByRole('dialog');+ within(dialog).getByText(/stops these built-in containers: openwa-redis\./);fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));@@ -1862,6 +1884,162 @@ test('turning a running built-in Redis off asks the restart to stop its containeassert.deepEqual(findFetchCall('POST', '/api/infra/restart')!.body, { profiles: [], profilesToRemove: ['redis'] });});+function card(container: HTMLElement, heading: string): HTMLElement {+ const found = Array.from(container.querySelectorAll<HTMLElement>('.infra-card')).find(+ c => c.querySelector('h2')?.textContent === heading,+ );+ if (!found) throw new Error(`no card headed "${heading}"`);+ return found;+}++// The restart never stops a container the next boot still reaches, read from the file the save wrote, so the page+// asks for and names only the others.+test('a built-in Redis switched off but left on the bundled host is neither stopped nor named', async () => {+ const { screen, waitFor, fireEvent, within } = rtl;+ resetFetchCalls();+ const redis = { enabled: true, builtIn: true, builtInSet: true, host: 'redis', port: '6379', passwordSet: false };+ overrides = {+ status: { ...INFRA_STATUS, redis: { enabled: true, connected: true, host: 'redis', port: 6379, builtIn: true } },+ saved: { ...SAVED_CONFIG, redis },+ savedAfterSave: { ...SAVED_CONFIG, redis: { ...redis, builtIn: false } },+ };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitConfigHydrated(container);+ const builtInRedis = toggleInput(container, 'Use Built-in Redis Container');+ await waitFor(() => assert.equal(builtInRedis.checked, true));+ fireEvent.click(builtInRedis);+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));++ const dialog = await screen.findByRole('dialog');+ assert.doesNotMatch(dialog.textContent ?? '', /openwa-/);+ fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));+ assert.deepEqual(findFetchCall('POST', '/api/infra/restart')!.body, { profiles: [], profilesToRemove: [] });+});++test('bundled containers the environment pins the hosts to are neither stopped nor named', async () => {+ const { screen, waitFor, fireEvent, within } = rtl;+ resetFetchCalls();+ overrides = {+ status: { ...RUNNING_BUNDLED, envPinned: ['DATABASE_HOST', 'REDIS_HOST', 'S3_ENDPOINT'] },+ saved: {+ ...SAVED_CONFIG,+ database: { ...SAVED_CONFIG.database, builtIn: true, builtInSet: false, host: 'postgres' },+ redis: { enabled: true, builtIn: true, builtInSet: false, host: 'redis', port: '6379', passwordSet: false },+ storage: {+ ...SAVED_CONFIG.storage,+ type: 's3',+ builtIn: true,+ builtInSet: false,+ s3Endpoint: 'http://minio:9000',+ },+ },+ };+ const { container } = renderInfrastructure();++ await screen.findByText('Database Configuration');+ await awaitSeeded(container);+ fireEvent.click(toggleInput(container, 'Headless Mode'));+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));++ const dialog = await screen.findByRole('dialog');+ assert.doesNotMatch(dialog.textContent ?? '', /openwa-/);+ fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));+ assert.deepEqual(findFetchCall('POST', '/api/infra/restart')!.body, { profiles: [], profilesToRemove: [] });+});++// Containers the dashboard created, then the environment pinned the three hosts to external services: the next boot+// uses none of them, and the save still asks for the profiles of the stored built-in flags.+const PINNED_AWAY: InfraStatus = {+ ...INFRA_STATUS,+ database: { connected: true, type: 'postgres', host: 'db.ext.example', builtIn: false, running: true },+ redis: { enabled: true, connected: true, host: 'cache.ext.example', port: 6379, builtIn: false, running: true },+ storage: {+ type: 's3',+ bucket: 'media',+ endpoint: 'https://s3.ext.example',+ builtIn: false,+ running: true,+ s3Available: true,+ },+ envPinned: ['DATABASE_TYPE', 'DATABASE_HOST', 'REDIS_ENABLED', 'REDIS_HOST', 'STORAGE_TYPE', 'S3_ENDPOINT'],+};+const PINNED_AWAY_SAVED: SavedConfig = {+ ...SAVED_CONFIG,+ database: { ...SAVED_CONFIG.database, builtIn: false, builtInSet: false, host: 'db.ext.example' },+ redis: {+ enabled: true,+ builtIn: false,+ builtInSet: false,+ host: 'cache.ext.example',+ port: '6379',+ passwordSet: false,+ },+ storage: {+ ...SAVED_CONFIG.storage,+ type: 's3',+ builtIn: false,+ builtInSet: false,+ s3Bucket: 'media',+ s3Endpoint: 'https://s3.ext.example',+ },+};++async function saveAndRestart(): Promise<{ dialogText: string; body: unknown }> {+ const { screen, waitFor, fireEvent, within } = rtl;+ const { container } = renderInfrastructure();+ await screen.findByText('Database Configuration');+ await awaitSeeded(container);+ fireEvent.click(toggleInput(container, 'Headless Mode'));+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));+ const dialog = await screen.findByRole('dialog');+ const dialogText = dialog.textContent ?? '';+ fireEvent.click(within(dialog).getByRole('button', { name: 'Restart Now' }));+ await waitFor(() => assert.ok(findFetchCall('POST', '/api/infra/restart'), 'expected the restart POST'));+ return { dialogText, body: findFetchCall('POST', '/api/infra/restart')!.body };+}++test('a bundled container OpenWA created whose host the environment pins elsewhere is stopped and named', async () => {+ resetFetchCalls();+ overrides = { status: PINNED_AWAY, saved: PINNED_AWAY_SAVED, saveProfiles: ['postgres', 'redis', 'minio'] };++ const { dialogText, body } = await saveAndRestart();++ assert.ok(dialogText.includes(STOPS_ALL_THREE), dialogText);+ assert.deepEqual(body, { profiles: [], profilesToRemove: ['postgres', 'redis', 'minio'] });+});++test('a bundled container Docker Compose created is left alone under a host pinned elsewhere', async () => {+ resetFetchCalls();+ const compose = {+ ...PINNED_AWAY,+ database: { ...PINNED_AWAY.database, running: false },+ redis: { ...PINNED_AWAY.redis, running: false },+ storage: { ...PINNED_AWAY.storage, running: false },+ };+ overrides = { status: compose, saved: PINNED_AWAY_SAVED, saveProfiles: ['postgres', 'redis', 'minio'] };++ const { dialogText, body } = await saveAndRestart();++ assert.doesNotMatch(dialogText, /openwa-/);+ assert.deepEqual(body, { profiles: ['postgres', 'redis', 'minio'], profilesToRemove: [] });+});++test('a host pinned to the container name still reaches the container, which is kept', async () => {+ resetFetchCalls();+ const status = { ...PINNED_AWAY, database: { ...PINNED_AWAY.database, host: 'OpenWA-Postgres' } };+ const saved = { ...PINNED_AWAY_SAVED, database: { ...PINNED_AWAY_SAVED.database, host: 'OpenWA-Postgres' } };+ overrides = { status, saved, saveProfiles: ['postgres', 'redis', 'minio'] };++ const { dialogText, body } = await saveAndRestart();++ assert.ok(dialogText.includes('stops these built-in containers: openwa-redis, openwa-minio.'), dialogText);+ assert.deepEqual(body, { profiles: ['postgres'], profilesToRemove: ['redis', 'minio'] });+});+// ── Restart-flow timer cleanup on unmount ────────────────────────────────────test('unmounting mid-restart cancels the health poll and countdown timers', { timeout: 10_000 }, async () => {diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex b3cf7b378..25d8feed3 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -14,7 +14,7 @@ import {Download,Upload,} from 'lucide-react';-import { API_BASE_URL, type SavedConfig } from '../services/api';+import { API_BASE_URL, infraApi, type SavedConfig } from '../services/api';import { copyToClipboard } from '../utils/clipboard';import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useInfraStatusQuery, useInfraConfigQuery, useEnginesQuery, useCurrentEngineQuery } from '../hooks/queries';@@ -38,6 +38,36 @@ interface QueueStats {failed: number;}+// The container each managed profile runs, as the restart dialog names it.+const CONTAINER_OF: Record<string, string> = {+ postgres: 'openwa-postgres',+ redis: 'openwa-redis',+ minio: 'openwa-minio',+};++/**+ * Whether a host (for minio, the host of an S3 endpoint) reaches the profile's bundled container: its network alias+ * (the profile name) or its container name, in any letter case, with or without a trailing dot. The same rule as the+ * server's namesBundledContainer, which never lets a restart stop such a container.+ */+function namesBundledContainer(profile: string, value: string | undefined): boolean {+ if (!CONTAINER_OF[profile] || value === undefined) return false;+ let host = value.trim();+ if (profile === 'minio') {+ try {+ host = new URL(host).hostname;+ } catch {+ return false;+ }+ }+ host = host.toLowerCase().replace(/\.$/, '');+ return host === profile || host === CONTAINER_OF[profile];+}++/** The host the next boot dials for a profile, as GET /config reports it: the environment's, else the saved one. */+const nextBootHost = (profile: string, config: SavedConfig): string =>+ profile === 'postgres' ? config.database.host : profile === 'redis' ? config.redis.host : config.storage.s3Endpoint;+export function Infrastructure() {const { t } = useTranslation();useDocumentTitle(t('infrastructure.title'));@@ -64,7 +94,7 @@ export function Infrastructure() {// to open — the one-way edge between the save and restart hooks.const configSave = useConfigSave({buildPayload: configForm.buildSavePayload,- onSaved: (profiles, sent) => {+ onSaved: async (profiles, sent) => {// Flag a backend switch so the restart modal can warn about the empty-database / orphaned-media data// move before it happens. A switch is a next boot that connects somewhere else than the server does// now: another type, host, port or database name, or another S3 endpoint or bucket. The next boot@@ -109,9 +139,32 @@ export function Infrastructure() {infraStatus?.redis.builtIn && 'redis',infraStatus?.storage.type === 's3' && infraStatus.storage.builtIn && 'minio',].filter((p): p is string => typeof p === 'string');- restartFlow.open({ profiles, running, dbSwitch, storageSwitch });+ // A bundled container OpenWA created that no boot uses while the environment pins its host elsewhere: the+ // restart stops it. The server starts nothing for that host whatever the save asked, so it is no start either.+ const pinnedAway = (+ [+ ['postgres', infraStatus?.database.running, pinned('DATABASE_HOST')?.database.host],+ ['redis', infraStatus?.redis.running, pinned('REDIS_HOST')?.redis.host],+ ['minio', infraStatus?.storage.running, pinned('S3_ENDPOINT')?.storage.s3Endpoint],+ ] as const+ )+ .filter(([profile, up, host]) => up && host !== undefined && !namesBundledContainer(profile, host))+ .map(([profile]): string => profile);+ // The server never stops a container the next boot still reaches, read from the file this save wrote, so the+ // page reads that file back and asks for (and names) only the others. Without the read, the server decides.// The form is seeded once, so the refetch keeps any edit in progress.- void queryClient.invalidateQueries({ queryKey: ['infra', 'config'] });+ const saved = await queryClient+ .fetchQuery({ queryKey: ['infra', 'config'], queryFn: infraApi.getConfig, staleTime: 0 })+ .catch(() => undefined);+ const toStop = [...running, ...pinnedAway].filter(+ profile => !saved || !namesBundledContainer(profile, nextBootHost(profile, saved)),+ );+ restartFlow.open({+ profiles: profiles.filter(p => !pinnedAway.includes(p)),+ running: toStop,+ dbSwitch,+ storageSwitch,+ });},});@@ -906,6 +959,13 @@ export function Infrastructure() {<p className="restart-idle-desc"><Trans i18nKey="infrastructure.restart.idleDesc" components={{ code: <code />, br: <br /> }} /></p>+ {restartFlow.profilesToRemove.length > 0 && (+ <p className="restart-idle-desc">+ {t('infrastructure.restart.stopsContainers', {+ names: restartFlow.profilesToRemove.map(p => CONTAINER_OF[p] ?? p).join(', '),+ })}+ </p>+ )}{(restartFlow.dbSwitch || restartFlow.storageSwitch) && (<div className="migration-warning"><AlertTriangle size={18} />