Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(dashboard): show failed template and webhook reads as errors

Yudhi Armyndharise5020596b7f7
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index c1e5afc88..1a57514e9 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -533,7 +533,10 @@
"title": "لا توجد قوالب محفوظة",
"description": "أنشئ قالبًا قابلًا لإعادة الاستخدام لتسريع الردود والإشعارات الشائعة.",
"noSessionsTitle": "لا توجد جلسات متاحة",
- "noSessionsDesc": "أنشئ جلسة WhatsApp قبل إضافة القوالب."
+ "noSessionsDesc": "أنشئ جلسة WhatsApp قبل إضافة القوالب.",
+ "loadErrorTitle": "تعذر تحميل القوالب",
+ "forbiddenTitle": "لا يوجد وصول إلى القوالب",
+ "forbiddenDesc": "تتطلب القوالب مفتاح API بدور المشغل أو المسؤول."
},
"toasts": {
"created": "تم إنشاء القالب بنجاح",
diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json
index dcaa73d14..36a154b8d 100644
--- a/dashboard/src/i18n/locales/de.json
+++ b/dashboard/src/i18n/locales/de.json
@@ -518,7 +518,10 @@
"title": "Keine Vorlagen gespeichert",
"description": "Erstelle eine wiederverwendbare Vorlage, um häufige Antworten und Benachrichtigungen schneller zu versenden.",
"noSessionsTitle": "Keine Sitzungen verfügbar",
- "noSessionsDesc": "Erstelle eine WhatsApp-Sitzung, bevor du Vorlagen hinzufügst."
+ "noSessionsDesc": "Erstelle eine WhatsApp-Sitzung, bevor du Vorlagen hinzufügst.",
+ "loadErrorTitle": "Vorlagen konnten nicht geladen werden",
+ "forbiddenTitle": "Kein Zugriff auf Vorlagen",
+ "forbiddenDesc": "Vorlagen erfordern einen API-Schlüssel mit der Rolle Operator oder Admin."
},
"toasts": {
"created": "Vorlage wurde erfolgreich erstellt",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 7eb9b5768..7b7e55bbc 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -518,7 +518,10 @@
"title": "No templates saved",
"description": "Create a reusable template to speed up common replies and notifications.",
"noSessionsTitle": "No sessions available",
- "noSessionsDesc": "Create a WhatsApp session before adding templates."
+ "noSessionsDesc": "Create a WhatsApp session before adding templates.",
+ "loadErrorTitle": "Could not load templates",
+ "forbiddenTitle": "No access to templates",
+ "forbiddenDesc": "Templates require an API key with the operator or admin role."
},
"toasts": {
"created": "Template created successfully",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 6bbf1b00c..2dde5473d 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -707,7 +707,10 @@
"title": "No hay plantillas guardadas",
"description": "Crea una plantilla reutilizable para agilizar respuestas y notificaciones habituales.",
"noSessionsTitle": "No hay sesiones disponibles",
- "noSessionsDesc": "Crea una sesión de WhatsApp antes de añadir plantillas."
+ "noSessionsDesc": "Crea una sesión de WhatsApp antes de añadir plantillas.",
+ "loadErrorTitle": "No se pudieron cargar las plantillas",
+ "forbiddenTitle": "Sin acceso a las plantillas",
+ "forbiddenDesc": "Las plantillas requieren una clave API con el rol de operador o administrador."
},
"toasts": {
"created": "Plantilla creada correctamente",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 544f3439b..71979b553 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -518,7 +518,10 @@
"title": "Aucun template enregistré",
"description": "Créez un template réutilisable pour accélérer vos réponses et notifications courantes.",
"noSessionsTitle": "Aucune session disponible",
- "noSessionsDesc": "Créez une session WhatsApp avant d'ajouter des templates."
+ "noSessionsDesc": "Créez une session WhatsApp avant d'ajouter des templates.",
+ "loadErrorTitle": "Impossible de charger les templates",
+ "forbiddenTitle": "Aucun accès aux templates",
+ "forbiddenDesc": "Les templates nécessitent une clé API avec le rôle opérateur ou administrateur."
},
"toasts": {
"created": "Template créé avec succès",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index f29b786d1..4a5fdae7c 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -527,7 +527,10 @@
"title": "אין תבניות שמורות",
"description": "צרו תבנית לשימוש חוזר כדי לזרז תשובות והתראות נפוצות.",
"noSessionsTitle": "אין סשנים זמינים",
- "noSessionsDesc": "צרו סשן WhatsApp לפני הוספת תבניות."
+ "noSessionsDesc": "צרו סשן WhatsApp לפני הוספת תבניות.",
+ "loadErrorTitle": "לא ניתן לטעון את התבניות",
+ "forbiddenTitle": "אין גישה לתבניות",
+ "forbiddenDesc": "תבניות דורשות מפתח API עם תפקיד מפעיל או מנהל."
},
"toasts": {
"created": "התבנית נוצרה בהצלחה",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index fbbf35804..fcf56622b 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -518,7 +518,10 @@
"title": "Nessun modello salvato",
"description": "Crea un modello riutilizzabile per velocizzare le risposte e le notifiche più comuni..",
"noSessionsTitle": "Nessuna sessione disponibile",
- "noSessionsDesc": "Crea una sessione WhatsApp prima di aggiungere i modelli."
+ "noSessionsDesc": "Crea una sessione WhatsApp prima di aggiungere i modelli.",
+ "loadErrorTitle": "Impossibile caricare i modelli",
+ "forbiddenTitle": "Nessun accesso ai modelli",
+ "forbiddenDesc": "I modelli richiedono una chiave API con ruolo operatore o amministratore."
},
"toasts": {
"created": "Modello creato con successo",
diff --git a/dashboard/src/i18n/locales/ko.json b/dashboard/src/i18n/locales/ko.json
index 1bdc37b00..90f3d7220 100644
--- a/dashboard/src/i18n/locales/ko.json
+++ b/dashboard/src/i18n/locales/ko.json
@@ -518,7 +518,10 @@
"title": "저장된 템플릿이 없습니다",
"description": "자주 쓰는 답장이나 알림을 빠르게 보내려면 재사용 가능한 템플릿을 만드세요.",
"noSessionsTitle": "사용 가능한 세션이 없습니다",
- "noSessionsDesc": "템플릿을 추가하기 전에 WhatsApp 세션을 만드세요."
+ "noSessionsDesc": "템플릿을 추가하기 전에 WhatsApp 세션을 만드세요.",
+ "loadErrorTitle": "템플릿을 불러올 수 없습니다",
+ "forbiddenTitle": "템플릿에 접근할 수 없습니다",
+ "forbiddenDesc": "템플릿을 사용하려면 운영자 또는 관리자 역할의 API 키가 필요합니다."
},
"toasts": {
"created": "템플릿이 생성되었습니다",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index 2a469cf1d..4c670f5f0 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -707,7 +707,10 @@
"title": "Nenhum modelo salvo",
"description": "Crie um modelo reutilizável para agilizar respostas e notificações habituais.",
"noSessionsTitle": "Nenhuma sessão disponível",
- "noSessionsDesc": "Crie uma sessão do WhatsApp antes de adicionar modelos."
+ "noSessionsDesc": "Crie uma sessão do WhatsApp antes de adicionar modelos.",
+ "loadErrorTitle": "Não foi possível carregar os modelos",
+ "forbiddenTitle": "Sem acesso aos modelos",
+ "forbiddenDesc": "Os modelos exigem uma chave de API com a função de operador ou administrador."
},
"toasts": {
"created": "Modelo criado com sucesso",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index ab2ee6b7a..d3130e230 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -518,7 +518,10 @@
"title": "టెంప్లేట్‌లు ఏవీ సేవ్ కాలేదు",
"description": "సాధారణ ప్రత్యుత్తరాలు మరియు నోటిఫికేషన్‌లను వేగవంతం చేయడానికి పునర్వినియోగ టెంప్లేట్‌ను సృష్టించండి.",
"noSessionsTitle": "సెషన్‌లు అందుబాటులో లేవు",
- "noSessionsDesc": "టెంప్లేట్‌లను జోడించే ముందు WhatsApp సెషన్‌ను సృష్టించండి."
+ "noSessionsDesc": "టెంప్లేట్‌లను జోడించే ముందు WhatsApp సెషన్‌ను సృష్టించండి.",
+ "loadErrorTitle": "టెంప్లేట్‌లను లోడ్ చేయడం సాధ్యం కాలేదు",
+ "forbiddenTitle": "టెంప్లేట్‌లకు యాక్సెస్ లేదు",
+ "forbiddenDesc": "టెంప్లేట్‌లకు ఆపరేటర్ లేదా అడ్మిన్ పాత్ర ఉన్న API కీ అవసరం."
},
"toasts": {
"created": "టెంప్లేట్ విజయవంతంగా సృష్టించబడింది",
diff --git a/dashboard/src/i18n/locales/tr.json b/dashboard/src/i18n/locales/tr.json
index f862c97ba..a53d3bd24 100644
--- a/dashboard/src/i18n/locales/tr.json
+++ b/dashboard/src/i18n/locales/tr.json
@@ -518,7 +518,10 @@
"title": "Kayıtlı şablon yok",
"description": "Sık kullanılan yanıtları ve bildirimleri hızlandırmak için yeniden kullanılabilir bir şablon oluşturun.",
"noSessionsTitle": "Kullanılabilir oturum yok",
- "noSessionsDesc": "Şablon eklemeden önce bir WhatsApp oturumu oluşturun."
+ "noSessionsDesc": "Şablon eklemeden önce bir WhatsApp oturumu oluşturun.",
+ "loadErrorTitle": "Şablonlar yüklenemedi",
+ "forbiddenTitle": "Şablonlara erişim yok",
+ "forbiddenDesc": "Şablonlar, operatör veya yönetici rolüne sahip bir API anahtarı gerektirir."
},
"toasts": {
"created": "Şablon başarıyla oluşturuldu",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 7d9a658e7..4d719efb6 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -518,7 +518,10 @@
"title": "暂无已保存的模板",
"description": "创建可复用的模板,加快处理常见回复和通知。",
"noSessionsTitle": "暂无可用会话",
- "noSessionsDesc": "添加模板前请先创建 WhatsApp 会话。"
+ "noSessionsDesc": "添加模板前请先创建 WhatsApp 会话。",
+ "loadErrorTitle": "无法加载模板",
+ "forbiddenTitle": "无权访问模板",
+ "forbiddenDesc": "模板需要具有操作员或管理员角色的 API 密钥。"
},
"toasts": {
"created": "模板创建成功",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 006375988..65cbca474 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -518,7 +518,10 @@
"title": "未儲存任何範本",
"description": "建立可重用的範本,加快常用回覆和通知的速度。",
"noSessionsTitle": "沒有可用的工作階段",
- "noSessionsDesc": "請先建立 WhatsApp 工作階段,才能新增範本。"
+ "noSessionsDesc": "請先建立 WhatsApp 工作階段,才能新增範本。",
+ "loadErrorTitle": "無法載入範本",
+ "forbiddenTitle": "無權存取範本",
+ "forbiddenDesc": "範本需要具有操作員或管理員角色的 API 金鑰。"
},
"toasts": {
"created": "範本建立成功",
diff --git a/dashboard/src/pages/Dashboard.test.ts b/dashboard/src/pages/Dashboard.test.ts
new file mode 100644
index 000000000..93677b3c0
--- /dev/null
+++ b/dashboard/src/pages/Dashboard.test.ts
@@ -0,0 +1,88 @@
+// Render test for the Dashboard stat cards under the bare `node --test` runner, on the Sessions.test.ts
+// harness. GET /webhooks and GET /stats/overview both reject a viewer key; each card must then show
+// the unavailable placeholder rather than a count the gateway never returned.
+import '../test-helpers/register-hooks.ts';
+import { test, before, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { createElement } from 'react';
+import { MemoryRouter } from 'react-router-dom';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+let webhooksStatus = 403;
+
+function jsonResponse(data: unknown, status = 200): Response {
+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+function installFetchStub(): void {
+ globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ const path = url.replace(/^https?:\/\/[^/]+/, '');
+ if (path === '/api/sessions') return Promise.resolve(jsonResponse([]));
+ if (path === '/api/webhooks') {
+ return webhooksStatus === 200
+ ? Promise.resolve(jsonResponse([]))
+ : Promise.resolve(jsonResponse({ message: 'Insufficient permissions. Required: operator' }, webhooksStatus));
+ }
+ // Everything else, the admin-only overview included, is refused.
+ return Promise.resolve(jsonResponse({ message: 'Insufficient permissions. Required: admin' }, 403));
+ }) as typeof fetch;
+}
+
+let rtl: typeof import('@testing-library/react');
+let Dashboard: (typeof import('./Dashboard.tsx'))['Dashboard'];
+let queryClient: QueryClient | undefined;
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ // recharts' ResponsiveContainer observes its box; jsdom ships no ResizeObserver.
+ (globalThis as Record<string, unknown>).ResizeObserver = class {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ };
+ installFetchStub();
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
+ rtl = await import('@testing-library/react');
+ ({ Dashboard } = await import('./Dashboard.tsx'));
+});
+
+afterEach(() => {
+ rtl.cleanup();
+ queryClient?.clear();
+ queryClient = undefined;
+});
+
+function renderDashboard(): void {
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
+ rtl.render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(MemoryRouter, null, createElement(Dashboard)),
+ ),
+ );
+}
+
+function statValue(label: string): string {
+ const card = rtl.screen.getByText(label).closest('.stat-card');
+ return card?.querySelector('.stat-value')?.textContent ?? '';
+}
+
+test('a refused webhook read shows the unavailable placeholder, not zero webhooks', async () => {
+ webhooksStatus = 403;
+ renderDashboard();
+ await rtl.screen.findByText('Webhooks Configured');
+ // The overview card is refused too, so its placeholder is the one the webhook card must match.
+ await rtl.waitFor(() => assert.equal(statValue('Webhooks Configured'), statValue('Messages Today')));
+ assert.notEqual(statValue('Webhooks Configured'), '0');
+});
+
+test('a successful empty webhook read still counts zero', async () => {
+ webhooksStatus = 200;
+ renderDashboard();
+ await rtl.screen.findByText('Webhooks Configured');
+ await rtl.waitFor(() => assert.equal(statValue('Webhooks Configured'), '0'));
+});
diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx
index e4036bdbf..71d8fb12f 100644
--- a/dashboard/src/pages/Dashboard.tsx
+++ b/dashboard/src/pages/Dashboard.tsx
@@ -24,17 +24,19 @@ export function Dashboard() {
const navigate = useNavigate();
const { data: sessions = [], isLoading: loadingSessions, error: sessionsError } = useSessionsQuery();
const { data: stats } = useSessionStatsQuery();
- const { data: webhooks = [] } = useWebhooksQuery();
+ const { data: webhooks = [], isError: webhooksFailed } = useWebhooksQuery();
// /stats/overview is ADMIN-only; for a non-admin key it 403s → overview stays undefined and the
// message cards fall back to '—' without breaking the (un-gated) session cards.
const { data: overview } = useStatsOverviewQuery();
const stopMutation = useStopSessionMutation();
- const messagesToday = overview ? overview.messages.today.sent + overview.messages.today.received : '—';
- const totalMessages = overview ? overview.messages.sent + overview.messages.received : '—';
+ const unavailable = '—';
+ const messagesToday = overview ? overview.messages.today.sent + overview.messages.today.received : unavailable;
+ const totalMessages = overview ? overview.messages.sent + overview.messages.received : unavailable;
const loading = loadingSessions;
const error =
sessionsError instanceof Error ? sessionsError.message : sessionsError ? t('dashboard.loadError') : null;
- const webhookCount = webhooks.length;
+ // GET /webhooks is OPERATOR-only, so a viewer key always fails it: a failed read is not zero webhooks.
+ const webhookCount = webhooksFailed ? unavailable : webhooks.length;
const handleDisconnect = async (id: string) => {
try {
diff --git a/dashboard/src/pages/Templates.test.ts b/dashboard/src/pages/Templates.test.ts
new file mode 100644
index 000000000..c5c7272a3
--- /dev/null
+++ b/dashboard/src/pages/Templates.test.ts
@@ -0,0 +1,100 @@
+// Render test for the Templates page under the bare `node --test` runner, on the Sessions.test.ts
+// harness. The template list route is OPERATOR-only, so a viewer key always gets 403 there; a failed
+// read must say so instead of rendering the "no templates saved" empty state.
+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';
+
+let templatesStatus = 200;
+
+function jsonResponse(data: unknown, status = 200): Response {
+ return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+function installFetchStub(): void {
+ globalThis.fetch = ((input: RequestInfo | URL): Promise<Response> => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ const path = url.replace(/^https?:\/\/[^/]+/, '');
+ if (path === '/api/sessions') {
+ return Promise.resolve(
+ jsonResponse([
+ {
+ id: 'sess-1',
+ name: 'billing-bot',
+ status: 'ready',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ },
+ ]),
+ );
+ }
+ if (path === '/api/sessions/sess-1/templates') {
+ if (templatesStatus === 403) {
+ return Promise.resolve(jsonResponse({ message: 'Insufficient permissions. Required: operator' }, 403));
+ }
+ if (templatesStatus !== 200)
+ return Promise.resolve(jsonResponse({ message: 'database offline' }, templatesStatus));
+ return Promise.resolve(jsonResponse([]));
+ }
+ return Promise.resolve(jsonResponse({ message: `unstubbed ${path}` }, 404));
+ }) as typeof fetch;
+}
+
+let rtl: typeof import('@testing-library/react');
+let Templates: (typeof import('./Templates.tsx'))['Templates'];
+let RoleProvider: (typeof import('../components/RoleProvider.tsx'))['RoleProvider'];
+let ToastProvider: (typeof import('../components/Toast.tsx'))['ToastProvider'];
+let queryClient: QueryClient | undefined;
+
+before(async () => {
+ const { installJsdomGlobals } = await import('../test-helpers/jsdom.ts');
+ await installJsdomGlobals();
+ installFetchStub();
+ window.localStorage.setItem('openwa_user_role', 'viewer');
+ const { i18nReady } = await import('../i18n/index.ts');
+ await i18nReady;
+ rtl = await import('@testing-library/react');
+ ({ RoleProvider } = await import('../components/RoleProvider.tsx'));
+ ({ ToastProvider } = await import('../components/Toast.tsx'));
+ ({ Templates } = await import('./Templates.tsx'));
+});
+
+afterEach(() => {
+ rtl.cleanup();
+ queryClient?.clear();
+ queryClient = undefined;
+});
+
+function renderTemplates(): void {
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 1_000 } } });
+ rtl.render(
+ createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(RoleProvider, null, createElement(ToastProvider, null, createElement(Templates))),
+ ),
+ );
+}
+
+test('a 403 on the template list shows a permission state, not an empty library', async () => {
+ templatesStatus = 403;
+ renderTemplates();
+ await rtl.screen.findByText('No access to templates');
+ assert.equal(rtl.screen.queryByText('No templates saved') === null, true);
+});
+
+test('any other failed read shows the error, not an empty library', async () => {
+ templatesStatus = 500;
+ renderTemplates();
+ await rtl.screen.findByText('Could not load templates');
+ rtl.screen.getByText('database offline');
+ assert.equal(rtl.screen.queryByText('No templates saved') === null, true);
+});
+
+test('a successful empty read still shows the empty state', async () => {
+ templatesStatus = 200;
+ renderTemplates();
+ await rtl.screen.findByText('No templates saved');
+});
diff --git a/dashboard/src/pages/Templates.tsx b/dashboard/src/pages/Templates.tsx
index d87cf485f..1ae06cadf 100644
--- a/dashboard/src/pages/Templates.tsx
+++ b/dashboard/src/pages/Templates.tsx
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Copy, FileText, Loader2, Plus, Search, Trash2 } from 'lucide-react';
+import { AlertCircle, Copy, FileText, Loader2, Plus, Search, Trash2 } from 'lucide-react';
import { type MessageTemplate, type TemplatePayload } from '../services/api';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
@@ -65,10 +65,11 @@ export function Templates() {
const [previewValues, setPreviewValues] = useState<Record<string, string>>({});
const [searchTerm, setSearchTerm] = useState('');
- const { data: templates = [], isLoading: loadingTemplates } = useTemplatesQuery(
- selectedSessionId,
- !!selectedSessionId,
- );
+ const {
+ data: templates = [],
+ isLoading: loadingTemplates,
+ error: templatesError,
+ } = useTemplatesQuery(selectedSessionId, !!selectedSessionId);
const createMutation = useCreateTemplateMutation();
const updateMutation = useUpdateTemplateMutation();
const deleteMutation = useDeleteTemplateMutation();
@@ -236,6 +237,23 @@ export function Templates() {
<div className="templates-loading-inline">
<Loader2 className="animate-spin" size={24} />
</div>
+ ) : templatesError && templates.length === 0 ? (
+ // A failed read is not an empty library: a viewer key always gets 403 here (the route is
+ // OPERATOR-only), and a gateway error would otherwise read as "no templates saved".
+ <div className="templates-empty-list" role="alert">
+ <AlertCircle size={40} strokeWidth={1} />
+ {(templatesError as { status?: number }).status === 403 ? (
+ <>
+ <h3>{t('templates.empty.forbiddenTitle')}</h3>
+ <p>{t('templates.empty.forbiddenDesc')}</p>
+ </>
+ ) : (
+ <>
+ <h3>{t('templates.empty.loadErrorTitle')}</h3>
+ <p>{templatesError.message}</p>
+ </>
+ )}
+ </div>
) : templates.length === 0 ? (
<div className="templates-empty-list">
<FileText size={40} strokeWidth={1} />