Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): reset a cleared plugin instance scope to all sessions

Yudhi Armyndharisf24b558e469f
diff --git a/dashboard/src/components/PluginInstances.test.ts b/dashboard/src/components/PluginInstances.test.ts
new file mode 100644
index 000000000..c2901926f
--- /dev/null
+++ b/dashboard/src/components/PluginInstances.test.ts
@@ -0,0 +1,92 @@
+// Render test for the plugin instance manager under the bare `node --test` runner, on the ApiKeys.test.ts
+// harness: the edit modal's session scope and the view that shows a freshly minted instance.
+import '../test-helpers/register-hooks.ts';
+import { test, before, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { createElement } from 'react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+function jsonResponse(data: unknown, status = 200): Response {
+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+const BASE = '/api/integration/plugins/chatwoot/instances';
+
+const BOUND = {
+ id: 'i-1',
+ pluginId: 'chatwoot',
+ instanceId: 'acct1',
+ sessionScope: 'sess-a',
+ secret: '***',
+ verifyToken: null,
+ config: null,
+ enabled: true,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ ingressUrls: [],
+};
+
+const calls: { method: string; path: string; body?: unknown }[] = [];
+
+function installFetchStub(): void {
+ globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ const path = url.replace(/^https?:\/\/[^/]+/, '');
+ const method = init?.method ?? 'GET';
+ calls.push({ method, path, body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined });
+ if (method === 'GET' && path === BASE) return Promise.resolve(jsonResponse([BOUND]));
+ if (method === 'PATCH' && path === `${BASE}/acct1`) return Promise.resolve(jsonResponse(BOUND));
+ return Promise.resolve(jsonResponse({ message: `unstubbed ${method} ${path}` }, 404));
+ }) as typeof fetch;
+}
+
+let rtl: typeof import('@testing-library/react');
+let PluginInstances: (typeof import('./PluginInstances.tsx'))['PluginInstances'];
+let ToastProvider: (typeof import('./Toast.tsx'))['ToastProvider'];
+let queryClient: QueryClient | undefined;
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ installFetchStub();
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
+ rtl = await import('@testing-library/react');
+ ({ ToastProvider } = await import('./Toast.tsx'));
+ ({ PluginInstances } = await import('./PluginInstances.tsx'));
+});
+
+afterEach(() => {
+ rtl.cleanup();
+ queryClient?.clear();
+ queryClient = undefined;
+ calls.length = 0;
+});
+
+function renderInstances(): void {
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
+ rtl.render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(ToastProvider, null, createElement(PluginInstances, { pluginId: 'chatwoot' })),
+ ),
+ );
+}
+
+test('clearing a bound session scope saves the instance for all sessions', async () => {
+ const { screen, fireEvent, waitFor } = rtl;
+ renderInstances();
+
+ fireEvent.click(await screen.findByTitle('Edit'));
+ const scope = (await screen.findByLabelText('Session scope (optional)')) as HTMLInputElement;
+ assert.equal(scope.value, 'sess-a');
+ fireEvent.change(scope, { target: { value: '' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+
+ await waitFor(() => {
+ const patch = calls.find(c => c.method === 'PATCH');
+ assert.ok(patch, 'expected a PATCH');
+ assert.equal((patch.body as { sessionScope?: unknown }).sessionScope, null);
+ });
+});
diff --git a/dashboard/src/components/PluginInstances.tsx b/dashboard/src/components/PluginInstances.tsx
index 32f307a92..6a8c647d5 100644
--- a/dashboard/src/components/PluginInstances.tsx
+++ b/dashboard/src/components/PluginInstances.tsx
@@ -108,17 +108,11 @@ export function PluginInstances({ pluginId }: { pluginId: string }) {
setEditError(t('plugins.instances.errors.invalidJson'));
return;
}
- const scope = parseEditScope(editing.sessionScope, editForm.sessionScope);
- if (!scope.ok) {
- setEditError(t('plugins.instances.errors.scopeNotClearable'));
- return;
- }
try {
await updateM.mutateAsync({
instanceId: editing.instanceId,
- // Blank → omit (leave scope unchanged); mirrors create. Sending '' would corrupt an
- // all-sessions (null) instance into a literal empty scope the backend never clears.
- body: { sessionScope: scope.value, config: parsed.value ?? {} },
+ // Blank means all sessions (null, or omitted when already unscoped). Never '': the API rejects it.
+ body: { sessionScope: parseEditScope(editing.sessionScope, editForm.sessionScope), config: parsed.value ?? {} },
});
setEditing(null);
toast.success(t('plugins.instances.toasts.updated'), editing.instanceId);
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 10b2fe926..3abff01d4 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -1084,8 +1084,7 @@
"invalidId": "يجب أن يتكوّن معرّف المثيل من أحرف وأرقام وشرطات أو شرطات سفلية فقط (بحد أقصى 64 حرفًا).",
"invalidJson": "يجب أن يكون التكوين بصيغة JSON صحيحة.",
"invalidSecret": "يجب أن يتكون السر من 16 حرفًا على الأقل، أو اتركه فارغًا للتوليد التلقائي.",
- "duplicateId": "يوجد مثيل بهذا المعرّف مسبقًا.",
- "scopeNotClearable": "لا يمكن مسح نطاق الجلسة هنا. لخدمة كل الجلسات، احذف هذا المثيل وأنشئه مرة أخرى بدون نطاق."
+ "duplicateId": "يوجد مثيل بهذا المعرّف مسبقًا."
},
"toasts": {
"created": "تم إنشاء المثيل",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index beaa8c396..a9431a26d 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -1067,8 +1067,7 @@
"invalidId": "Die Instanz-ID darf nur Buchstaben, Zahlen, Bindestriche oder Unterstriche enthalten (max. 64).",
"invalidJson": "Die Konfiguration muss gültiges JSON enthalten.",
"invalidSecret": "Das Geheimnis muss mindestens 16 Zeichen lang sein. Alternativ leer lassen, um es automatisch zu erstellen.",
- "duplicateId": "Eine Instanz mit dieser ID existiert bereits.",
- "scopeNotClearable": "Ein Sitzungsbereich kann hier nicht geleert werden. Um alle Sitzungen zu bedienen, lösche diese Instanz und erstelle sie ohne Bereich neu."
+ "duplicateId": "Eine Instanz mit dieser ID existiert bereits."
},
"toasts": {
"created": "Instanz erstellt",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 7a3936215..3ff33a058 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -1066,8 +1066,7 @@
"invalidId": "Instance ID must be letters, numbers, hyphens or underscores (max 64).",
"invalidJson": "Config must be valid JSON.",
"invalidSecret": "Secret must be at least 16 characters, or leave blank to auto-generate.",
- "duplicateId": "An instance with that ID already exists.",
- "scopeNotClearable": "A session scope cannot be cleared here. To serve all sessions, delete this instance and create it again without a scope."
+ "duplicateId": "An instance with that ID already exists."
},
"toasts": {
"created": "Instance created",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index a8fc20218..031db37bb 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -1071,8 +1071,7 @@
"invalidId": "El ID de instancia debe contener letras, números, guiones o guiones bajos (máx. 64).",
"invalidJson": "La configuración debe ser JSON válido.",
"invalidSecret": "El secreto debe tener al menos 16 caracteres, o déjalo en blanco para generarlo automáticamente.",
- "duplicateId": "Ya existe una instancia con ese ID.",
- "scopeNotClearable": "El ámbito de sesión no se puede borrar aquí. Para atender todas las sesiones, elimina esta instancia y créala de nuevo sin ámbito."
+ "duplicateId": "Ya existe una instancia con ese ID."
},
"toasts": {
"created": "Instancia creada",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 2488c6c86..e870ba634 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -1071,8 +1071,7 @@
"invalidId": "L'ID de l'instance doit contenir des lettres, des chiffres, des tirets ou des underscores (64 max).",
"invalidJson": "La configuration doit être un JSON valide.",
"invalidSecret": "Le secret doit contenir au moins 16 caractères, ou laissez vide pour le générer automatiquement.",
- "duplicateId": "Une instance avec cet ID existe déjà.",
- "scopeNotClearable": "La portée de session ne peut pas être effacée ici. Pour couvrir toutes les sessions, supprimez cette instance et recréez-la sans portée."
+ "duplicateId": "Une instance avec cet ID existe déjà."
},
"toasts": {
"created": "Instance créée",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 56890a05a..5e840f1ca 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -1076,8 +1076,7 @@
"invalidId": "מזהה המופע חייב לכלול אותיות, מספרים, מקפים או קווים תחתונים (עד 64 תווים).",
"invalidJson": "התצורה חייבת להיות JSON תקין.",
"invalidSecret": "הסוד חייב להכיל לפחות 16 תווים, או השאר ריק ליצירה אוטומטית.",
- "duplicateId": "כבר קיים מופע עם מזהה זה.",
- "scopeNotClearable": "לא ניתן לנקות כאן את טווח הסשן. כדי לשרת את כל הסשנים, מחקו את המופע הזה וצרו אותו מחדש ללא טווח."
+ "duplicateId": "כבר קיים מופע עם מזהה זה."
},
"toasts": {
"created": "המופע נוצר",
diff --git a/dashboard/src/i18n/locales/hi.json b/dashboard/src/i18n/locales/hi.json
index 763a5fca1..3b302c782 100644
--- a/dashboard/src/i18n/locales/hi.json
+++ b/dashboard/src/i18n/locales/hi.json
@@ -1066,8 +1066,7 @@
"invalidId": "इंस्टेंस ID अक्षर, संख्याएँ, हाइफ़न या अंडरस्कोर होना चाहिए (अधिकतम 64)।",
"invalidJson": "कॉन्फ़िग मान्य JSON होना चाहिए।",
"invalidSecret": "सीक्रेट कम से कम 16 वर्णों का होना चाहिए, या स्वतः उत्पन्न करने के लिए खाली छोड़ दें।",
- "duplicateId": "उस ID वाला एक इंस्टेंस पहले से मौजूद है।",
- "scopeNotClearable": "सत्र दायरा यहाँ साफ़ नहीं किया जा सकता। सभी सत्रों के लिए, इस इंस्टेंस को हटाएँ और बिना दायरे के फिर से बनाएँ।"
+ "duplicateId": "उस ID वाला एक इंस्टेंस पहले से मौजूद है।"
},
"toasts": {
"created": "इंस्टेंस बनाया गया",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 74ea57e6d..7129ca650 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -1071,8 +1071,7 @@
"invalidId": "L'ID istanza deve contenere lettere, numeri, trattini o underscore (max 64).",
"invalidJson": "La configurazione deve essere un JSON valido.",
"invalidSecret": "Il segreto deve contenere almeno 16 caratteri, oppure lascia vuoto per generarlo automaticamente.",
- "duplicateId": "Esiste già un'istanza con questo ID.",
- "scopeNotClearable": "L'ambito della sessione non può essere svuotato qui. Per servire tutte le sessioni, elimina questa istanza e ricreala senza ambito."
+ "duplicateId": "Esiste già un'istanza con questo ID."
},
"toasts": {
"created": "Istanza creata",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 9e42ae5a4..786288b09 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -1067,8 +1067,7 @@
"invalidId": "인스턴스 ID는 영문자, 숫자, 하이픈, 밑줄만 사용할 수 있습니다 (최대 64자).",
"invalidJson": "구성은 유효한 JSON이어야 합니다.",
"invalidSecret": "시크릿은 최소 16자 이상이어야 합니다. 비워 두면 자동 생성됩니다.",
- "duplicateId": "이미 같은 ID의 인스턴스가 존재합니다.",
- "scopeNotClearable": "여기서는 세션 범위를 지울 수 없습니다. 모든 세션에 적용하려면 이 인스턴스를 삭제하고 범위 없이 다시 만드세요."
+ "duplicateId": "이미 같은 ID의 인스턴스가 존재합니다."
},
"toasts": {
"created": "인스턴스가 생성되었습니다",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 190444e4f..4bf86fc22 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -1071,8 +1071,7 @@
"invalidId": "O ID da instância deve conter letras, números, hífens ou sublinhados (máx. 64).",
"invalidJson": "A configuração deve ser um JSON válido.",
"invalidSecret": "O segredo deve ter pelo menos 16 caracteres, ou deixe em branco para gerar automaticamente.",
- "duplicateId": "Já existe uma instância com esse ID.",
- "scopeNotClearable": "O escopo de sessão não pode ser limpo aqui. Para atender todas as sessões, exclua esta instância e crie-a novamente sem escopo."
+ "duplicateId": "Já existe uma instância com esse ID."
},
"toasts": {
"created": "Instância criada",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 653919a09..e82ddaae3 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -1067,8 +1067,7 @@
"invalidId": "ఇన్‌స్టాన్స్ ఐడీలో అక్షరాలు, సంఖ్యలు, హైఫన్‌లు లేదా అండర్‌స్కోర్‌లు మాత్రమే ఉండాలి (గరిష్టంగా 64).",
"invalidJson": "కాన్ఫిగ్ చెల్లుబాటు అయ్యే JSON గా ఉండాలి.",
"invalidSecret": "రహస్యం కనీసం 16 అక్షరాలు ఉండాలి, లేదా ఆటోమేటిక్‌గా రూపొందించడానికి ఖాళీగా ఉంచండి.",
- "duplicateId": "ఆ ఐడీతో ఇన్‌స్టాన్స్ ఇప్పటికే ఉంది.",
- "scopeNotClearable": "సెషన్ స్కోప్‌ను ఇక్కడ తొలగించలేరు. అన్ని సెషన్‌లకు అందించడానికి, ఈ ఇన్‌స్టాన్స్‌ను తొలగించి స్కోప్ లేకుండా మళ్లీ సృష్టించండి."
+ "duplicateId": "ఆ ఐడీతో ఇన్‌స్టాన్స్ ఇప్పటికే ఉంది."
},
"toasts": {
"created": "ఇన్‌స్టాన్స్ సృష్టించబడింది",
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index f1ebb6b74..ebecd8f0e 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -1067,8 +1067,7 @@
"invalidId": "Örnek kimliği harf, sayı, tire veya alt çizgi içermelidir (maks 64).",
"invalidJson": "Yapılandırma geçerli bir JSON olmalıdır.",
"invalidSecret": "Gizli anahtar en az 16 karakter olmalıdır veya otomatik oluşturulması için boş bırakılmalıdır.",
- "duplicateId": "Bu kimliğe sahip bir örnek zaten var.",
- "scopeNotClearable": "Oturum kapsamı burada temizlenemez. Tüm oturumlara hizmet vermek için bu örneği silip kapsam olmadan yeniden oluşturun."
+ "duplicateId": "Bu kimliğe sahip bir örnek zaten var."
},
"toasts": {
"created": "Örnek oluşturuldu",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 86a430c90..62f780cce 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -1067,8 +1067,7 @@
"invalidId": "实例 ID 只能包含字母、数字、连字符或下划线(最多 64 个字符)。",
"invalidJson": "配置必须是有效的 JSON。",
"invalidSecret": "密钥至少 16 个字符,或留空以自动生成。",
- "duplicateId": "已存在具有该 ID 的实例。",
- "scopeNotClearable": "此处无法清除会话范围。如需服务所有会话,请删除此实例并在不设置范围的情况下重新创建。"
+ "duplicateId": "已存在具有该 ID 的实例。"
},
"toasts": {
"created": "实例已创建",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 00aa941dd..f865bbbee 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -1067,8 +1067,7 @@
"invalidId": "執行個體 ID 只能包含字母、數字、連字號或底線(最多 64 個字元)。",
"invalidJson": "設定必須是有效的 JSON。",
"invalidSecret": "密鑰至少 16 個字元,或留空以自動產生。",
- "duplicateId": "已存在使用該 ID 的執行個體。",
- "scopeNotClearable": "此處無法清除工作階段範圍。如需服務所有工作階段,請刪除此執行個體並在不設定範圍的情況下重新建立。"
+ "duplicateId": "已存在使用該 ID 的執行個體。"
},
"toasts": {
"created": "執行個體已建立",
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index c31411766..8fbb76485 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -1377,7 +1377,8 @@ export interface CreateInstanceInput {
export interface UpdateInstanceInput {
enabled?: boolean;
- sessionScope?: string;
+ /** null resets a scoped instance to all sessions; omit to leave the scope unchanged. */
+ sessionScope?: string | null;
config?: Record<string, unknown>;
}
diff --git a/dashboard/src/utils/instanceForm.test.ts b/dashboard/src/utils/instanceForm.test.ts
index d407d7065..49eea91f9 100644
--- a/dashboard/src/utils/instanceForm.test.ts
+++ b/dashboard/src/utils/instanceForm.test.ts
@@ -26,13 +26,13 @@ test('parseInstanceConfig: blank → undefined, object → parsed, invalid → n
assert.equal(parseInstanceConfig('[1,2]').ok, false); // array is not a config object
});
-test('parseEditScope: a bound scope cannot be blanked, since the API would keep it', () => {
- assert.deepEqual(parseEditScope('sess-a', ' sess-b '), { ok: true, value: 'sess-b' });
- assert.deepEqual(parseEditScope('sess-a', 'sess-a'), { ok: true, value: 'sess-a' });
- assert.deepEqual(parseEditScope(null, 'sess-b'), { ok: true, value: 'sess-b' });
+test('parseEditScope: a blank field resets a bound scope to all sessions', () => {
+ assert.equal(parseEditScope('sess-a', ' sess-b '), 'sess-b');
+ assert.equal(parseEditScope('sess-a', 'sess-a'), 'sess-a');
+ assert.equal(parseEditScope(null, 'sess-b'), 'sess-b');
// Blank on an all-sessions instance: omit, nothing changes.
- assert.deepEqual(parseEditScope(null, ' '), { ok: true, value: undefined });
- assert.deepEqual(parseEditScope('*', ''), { ok: true, value: undefined });
- // Blank on a bound instance: an omitted field leaves the binding in place, so refuse it.
- assert.equal(parseEditScope('sess-a', '').ok, false);
+ assert.equal(parseEditScope(null, ' '), undefined);
+ // Blank on a scoped instance: null, which PATCH reads as all sessions (an omitted field would keep it).
+ assert.equal(parseEditScope('sess-a', ''), null);
+ assert.equal(parseEditScope('*', ''), null);
});
diff --git a/dashboard/src/utils/instanceForm.ts b/dashboard/src/utils/instanceForm.ts
index 6c8d93200..a8299e91c 100644
--- a/dashboard/src/utils/instanceForm.ts
+++ b/dashboard/src/utils/instanceForm.ts
@@ -23,15 +23,12 @@ export function parseInstanceConfig(raw: string): ParseResult {
}
}
-type ScopeResult = { ok: true; value: string | undefined } | { ok: false };
-
/**
- * The edit form's session scope. Blank → omit (leave the scope unchanged), which is right for an
- * all-sessions instance. A bound scope cannot be blanked: PATCH reads an omitted field as unchanged
- * and rejects '', so the save would keep the old binding while reporting success.
+ * The edit form's session scope. Blank means all sessions: omitted when the instance already serves
+ * all sessions, and null when it is scoped, because PATCH reads an omitted field as unchanged.
*/
-export function parseEditScope(current: string | null, raw: string): ScopeResult {
+export function parseEditScope(current: string | null, raw: string): string | null | undefined {
const value = raw.trim();
- if (value) return { ok: true, value };
- return current && current !== '*' ? { ok: false } : { ok: true, value: undefined };
+ if (value) return value;
+ return current ? null : undefined;
}