Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(plugins): per-session activation + config UI (dashboard) (#445)
Yudhi Armyndharise37e33feed9d
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.jsonindex 37ad1977a..0157f0ef6 100644--- a/dashboard/src/i18n/locales/ar.json+++ b/dashboard/src/i18n/locales/ar.json@@ -648,7 +648,9 @@"browserArgs": "مُعطيات المتصفح","noOptions": "لا توجد خيارات إعداد لهذه الإضافة","save": "حفظ الإعدادات",- "addItem": "إضافة"+ "addItem": "إضافة",+ "tabConfig": "الإعدادات",+ "tabSessions": "الجلسات"},"rail": {"engine": "المحرك النشط",@@ -676,6 +678,19 @@"installFailed": "فشل التثبيت","uninstalled": "تمت إزالة الإضافة","uninstallFailed": "فشلت الإزالة"+ },+ "sessions": {+ "activationTitle": "التشغيل لـ",+ "activationDesc": "اختر الجلسات التي يعمل عليها هذا الملحق.",+ "allSessions": "جميع الجلسات",+ "specificSessions": "جلسات محددة",+ "noSessions": "لا توجد جلسات بعد.",+ "saveActivation": "حفظ التفعيل",+ "perSessionTitle": "إعدادات لكل جلسة",+ "perSessionDesc": "تجاوز الإعدادات العامة لجلسة معينة؛ الحقول غير المعدّلة ترث القيمة العامة.",+ "selectSession": "اختر جلسة…",+ "saveOverride": "حفظ التجاوز",+ "clearOverride": "مسح التجاوز"}}}diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.jsonindex 0f774cb2d..d4c26295b 100644--- a/dashboard/src/i18n/locales/en.json+++ b/dashboard/src/i18n/locales/en.json@@ -648,7 +648,9 @@"browserArgs": "Browser Arguments","noOptions": "No configuration options available for this plugin","save": "Save Configuration",- "addItem": "Add"+ "addItem": "Add",+ "tabConfig": "Configuration",+ "tabSessions": "Sessions"},"rail": {"engine": "Active engine",@@ -676,6 +678,19 @@"installFailed": "Install failed","uninstalled": "Plugin uninstalled","uninstallFailed": "Uninstall failed"+ },+ "sessions": {+ "activationTitle": "Run for",+ "activationDesc": "Choose which sessions this plugin runs for.",+ "allSessions": "All sessions",+ "specificSessions": "Specific sessions",+ "noSessions": "No sessions yet.",+ "saveActivation": "Save activation",+ "perSessionTitle": "Per-session config",+ "perSessionDesc": "Override the global config for a session; untouched fields inherit the global value.",+ "selectSession": "Select a session…",+ "saveOverride": "Save override",+ "clearOverride": "Clear override"}}}diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.jsonindex 6a1b01e23..8411fdc8c 100644--- a/dashboard/src/i18n/locales/es.json+++ b/dashboard/src/i18n/locales/es.json@@ -648,7 +648,9 @@"browserArgs": "Argumentos del navegador","noOptions": "No hay opciones de configuración disponibles para este plugin","save": "Guardar configuración",- "addItem": "Añadir"+ "addItem": "Añadir",+ "tabConfig": "Configuración",+ "tabSessions": "Sesiones"},"rail": {"engine": "Motor activo",@@ -676,6 +678,19 @@"installFailed": "Error en la instalación","uninstalled": "Plugin desinstalado","uninstallFailed": "Error al desinstalar"+ },+ "sessions": {+ "activationTitle": "Ejecutar para",+ "activationDesc": "Elige para qué sesiones se ejecuta este complemento.",+ "allSessions": "Todas las sesiones",+ "specificSessions": "Sesiones específicas",+ "noSessions": "Aún no hay sesiones.",+ "saveActivation": "Guardar activación",+ "perSessionTitle": "Configuración por sesión",+ "perSessionDesc": "Anula la configuración global para una sesión; los campos sin modificar heredan el valor global.",+ "selectSession": "Selecciona una sesión…",+ "saveOverride": "Guardar anulación",+ "clearOverride": "Borrar anulación"}}}diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.jsonindex 044b6e7e0..c5c064946 100644--- a/dashboard/src/i18n/locales/fr.json+++ b/dashboard/src/i18n/locales/fr.json@@ -648,7 +648,9 @@"browserArgs": "Arguments du navigateur","noOptions": "Aucune option de configuration disponible pour ce plugin","save": "Enregistrer la configuration",- "addItem": "Ajouter"+ "addItem": "Ajouter",+ "tabConfig": "Configuration",+ "tabSessions": "Sessions"},"rail": {"engine": "Moteur actif",@@ -676,6 +678,19 @@"installFailed": "Échec de l'installation","uninstalled": "Plugin désinstallé","uninstallFailed": "Échec de la désinstallation"+ },+ "sessions": {+ "activationTitle": "Exécuter pour",+ "activationDesc": "Choisissez les sessions pour lesquelles ce plugin s'exécute.",+ "allSessions": "Toutes les sessions",+ "specificSessions": "Sessions spécifiques",+ "noSessions": "Aucune session pour le moment.",+ "saveActivation": "Enregistrer l'activation",+ "perSessionTitle": "Configuration par session",+ "perSessionDesc": "Remplacez la configuration globale pour une session ; les champs non modifiés héritent de la valeur globale.",+ "selectSession": "Sélectionnez une session…",+ "saveOverride": "Enregistrer le remplacement",+ "clearOverride": "Effacer le remplacement"}}}diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.jsonindex 2be44e809..4dcd14ba4 100644--- a/dashboard/src/i18n/locales/he.json+++ b/dashboard/src/i18n/locales/he.json@@ -648,7 +648,9 @@"browserArgs": "ארגומנטים של הדפדפן","noOptions": "אין אפשרויות הגדרה זמינות עבור תוסף זה","save": "שמירת תצורה",- "addItem": "הוספה"+ "addItem": "הוספה",+ "tabConfig": "הגדרות",+ "tabSessions": "Sessions"},"rail": {"engine": "מנוע פעיל",@@ -676,6 +678,19 @@"installFailed": "ההתקנה נכשלה","uninstalled": "התוסף הוסר","uninstallFailed": "ההסרה נכשלה"+ },+ "sessions": {+ "activationTitle": "הפעלה עבור",+ "activationDesc": "בחרו עבור אילו sessions תוסף זה יפעל.",+ "allSessions": "כל ה-Sessions",+ "specificSessions": "Sessions מסוימים",+ "noSessions": "אין Sessions עדיין.",+ "saveActivation": "שמירת הפעלה",+ "perSessionTitle": "הגדרות לכל Session",+ "perSessionDesc": "דריסת ההגדרות הגלובליות עבור session; שדות שלא שונו יורשים את הערך הגלובלי.",+ "selectSession": "בחירת session…",+ "saveOverride": "שמירת דריסה",+ "clearOverride": "ניקוי דריסה"}}}diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.jsonindex f5f9a6012..73478cb16 100644--- a/dashboard/src/i18n/locales/it.json+++ b/dashboard/src/i18n/locales/it.json@@ -648,7 +648,9 @@"browserArgs": "Argomenti del Browser","noOptions": "Nessuna opzione di configurazione disponibile per questo plugin","save": "Salva Configurazione",- "addItem": "Aggiungi"+ "addItem": "Aggiungi",+ "tabConfig": "Configurazione",+ "tabSessions": "Sessioni"},"rail": {"engine": "Motore attivo",@@ -676,6 +678,19 @@"installFailed": "Installazione non riuscita","uninstalled": "Plugin disinstallato","uninstallFailed": "Disinstallazione non riuscita"+ },+ "sessions": {+ "activationTitle": "Esegui per",+ "activationDesc": "Scegli per quali sessioni viene eseguito questo plugin.",+ "allSessions": "Tutte le sessioni",+ "specificSessions": "Sessioni specifiche",+ "noSessions": "Nessuna sessione ancora.",+ "saveActivation": "Salva attivazione",+ "perSessionTitle": "Configurazione per sessione",+ "perSessionDesc": "Sostituisci la configurazione globale per una sessione; i campi non modificati ereditano il valore globale.",+ "selectSession": "Seleziona una sessione…",+ "saveOverride": "Salva override",+ "clearOverride": "Rimuovi override"}}}diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.jsonindex 7afe053fe..a12dfa69d 100644--- a/dashboard/src/i18n/locales/te.json+++ b/dashboard/src/i18n/locales/te.json@@ -648,7 +648,9 @@"browserArgs": "బ్రౌజర్ ఆర్గుమెంట్స్","noOptions": "ఈ ప్లగిన్ కోసం ఎలాంటి కాన్ఫిగరేషన్ ఆప్షన్లు అందుబాటులో లేవు","save": "కాన్ఫిగరేషన్ను సేవ్ చేయి",- "addItem": "జోడించు"+ "addItem": "జోడించు",+ "tabConfig": "కాన్ఫిగరేషన్",+ "tabSessions": "సెషన్లు"},"rail": {"engine": "యాక్టివ్ ఇంజిన్",@@ -676,6 +678,19 @@"installFailed": "ఇన్స్టాల్ విఫలమైంది","uninstalled": "ప్లగిన్ అన్ఇన్స్టాల్ చేయబడింది","uninstallFailed": "అన్ఇన్స్టాల్ విఫలమైంది"+ },+ "sessions": {+ "activationTitle": "దీని కోసం రన్ చేయండి",+ "activationDesc": "ఈ ప్లగిన్ ఏ సెషన్ల కోసం రన్ అవుతుందో ఎంచుకోండి.",+ "allSessions": "అన్ని సెషన్లు",+ "specificSessions": "నిర్దిష్ట సెషన్లు",+ "noSessions": "ఇంకా సెషన్లు లేవు.",+ "saveActivation": "యాక్టివేషన్ను సేవ్ చేయండి",+ "perSessionTitle": "సెషన్-వారీ కాన్ఫిగ్",+ "perSessionDesc": "ఒక సెషన్ కోసం గ్లోబల్ కాన్ఫిగ్ను ఓవర్రైడ్ చేయండి; మార్చని ఫీల్డ్లు గ్లోబల్ విలువను వారసత్వంగా పొందుతాయి.",+ "selectSession": "ఒక సెషన్ను ఎంచుకోండి…",+ "saveOverride": "ఓవర్రైడ్ను సేవ్ చేయండి",+ "clearOverride": "ఓవర్రైడ్ను క్లియర్ చేయండి"}}}diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.jsonindex 500c54483..97bd9f2f2 100644--- a/dashboard/src/i18n/locales/zh-CN.json+++ b/dashboard/src/i18n/locales/zh-CN.json@@ -648,7 +648,9 @@"browserArgs": "浏览器参数","noOptions": "此插件没有可用配置项","save": "保存配置",- "addItem": "添加"+ "addItem": "添加",+ "tabConfig": "配置",+ "tabSessions": "会话"},"rail": {"engine": "活动引擎",@@ -676,6 +678,19 @@"installFailed": "安装失败","uninstalled": "插件已卸载","uninstallFailed": "卸载失败"+ },+ "sessions": {+ "activationTitle": "运行范围",+ "activationDesc": "选择此插件运行的会话。",+ "allSessions": "所有会话",+ "specificSessions": "指定会话",+ "noSessions": "暂无会话。",+ "saveActivation": "保存启用设置",+ "perSessionTitle": "单会话配置",+ "perSessionDesc": "为某个会话覆盖全局配置;未修改的字段将沿用全局值。",+ "selectSession": "选择一个会话…",+ "saveOverride": "保存覆盖配置",+ "clearOverride": "清除覆盖配置"}}}diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.jsonindex c368c358a..dc951dd31 100644--- a/dashboard/src/i18n/locales/zh-HK.json+++ b/dashboard/src/i18n/locales/zh-HK.json@@ -648,7 +648,9 @@"browserArgs": "瀏覽器參數","noOptions": "此外掛沒有可用設定選項","save": "儲存設定",- "addItem": "新增"+ "addItem": "新增",+ "tabConfig": "設定",+ "tabSessions": "工作階段"},"rail": {"engine": "使用中的引擎",@@ -676,6 +678,19 @@"installFailed": "安裝失敗","uninstalled": "外掛已解除安裝","uninstallFailed": "解除安裝失敗"+ },+ "sessions": {+ "activationTitle": "執行對象",+ "activationDesc": "選擇此外掛程式要為哪些工作階段執行。",+ "allSessions": "所有工作階段",+ "specificSessions": "指定工作階段",+ "noSessions": "尚無工作階段。",+ "saveActivation": "儲存啟用設定",+ "perSessionTitle": "個別工作階段設定",+ "perSessionDesc": "為某個工作階段覆寫全域設定;未變更的欄位會沿用全域數值。",+ "selectSession": "選擇工作階段…",+ "saveOverride": "儲存覆寫",+ "clearOverride": "清除覆寫"}}}diff --git a/dashboard/src/pages/Plugins.css b/dashboard/src/pages/Plugins.cssindex f3c626a38..b9bc5222e 100644--- a/dashboard/src/pages/Plugins.css+++ b/dashboard/src/pages/Plugins.css@@ -957,6 +957,103 @@border-bottom-color: var(--primary, #25d366);}+/* Config modal tabs (Configuration / Sessions) */+.config-modal .modal-tabs {+ display: flex;+ gap: 4px;+ padding: 0 1.5rem;+ border-bottom: 1px solid var(--border);+}++.config-modal .modal-tab {+ padding: 0.625rem 0.9rem;+ background: none;+ border: none;+ border-bottom: 2px solid transparent;+ color: var(--text-secondary);+ font-size: 0.875rem;+ font-weight: 600;+ cursor: pointer;+}++.config-modal .modal-tab.active {+ color: var(--text-primary);+ border-bottom-color: var(--primary);+}++/* Sessions tab */+.sessions-tab {+ display: flex;+ flex-direction: column;+ gap: 1.5rem;+}++.sessions-section > h3 {+ font-size: 0.9375rem;+ font-weight: 600;+ color: var(--text-primary);+ margin: 0 0 0.25rem;+}++.sessions-section > small {+ display: block;+ color: var(--text-muted);+ font-size: 0.75rem;+ margin-bottom: 0.75rem;+}++.sessions-radio {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.35rem 0;+ font-size: 0.875rem;+ color: var(--text-primary);+ cursor: pointer;+}++.sessions-checklist {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ margin: 0.25rem 0 0.75rem 1.5rem;+ max-height: 180px;+ overflow-y: auto;+}++.sessions-check {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ font-size: 0.875rem;+ color: var(--text-secondary);+ cursor: pointer;+}++.sessions-empty {+ margin: 0.25rem 0 0.75rem 1.5rem;+ font-size: 0.8125rem;+ color: var(--text-muted);+}++.sessions-select {+ width: 100%;+ padding: 0.6rem 0.85rem;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--bg-light);+ font-size: 0.9375rem;+ margin-bottom: 1rem;+ box-sizing: border-box;+}++.sessions-override-actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.5rem;+ margin-top: 0.5rem;+}+.catalog-empty {display: flex;align-items: center;diff --git a/dashboard/src/pages/Plugins.tsx b/dashboard/src/pages/Plugins.tsxindex 7ddd5a604..f5a1128ff 100644--- a/dashboard/src/pages/Plugins.tsx+++ b/dashboard/src/pages/Plugins.tsx@@ -31,6 +31,7 @@ import {useEnginesQuery,useCurrentEngineQuery,useInfraStatusQuery,+ useSessionsQuery,queryKeys,} from '../hooks/queries';import { PageHeader } from '../components/PageHeader';@@ -75,6 +76,40 @@ function emptyForField(field: PluginConfigField): unknown {}}+/**+ * Build a sparse per-session config override from a full edited config: include only non-secret keys+ * whose value differs from the Global base (so untouched keys keep inheriting Global), plus every+ * TOP-LEVEL secret key (the backend restores an untouched `***` to the stored per-session value, or+ * drops it → the host's deep-merge then re-inherits it from Global). A key absent from the base whose+ * value is just the empty default is skipped, so an untouched optional field never creates a spurious+ * override. With no schema, the input is returned as-is.+ *+ * Inheritance of untouched secrets holds for top-level secret keys and secrets nested in an OBJECT+ * (deep-merged). It does NOT hold for a `secret` column inside an array-of-rows: arrays are replaced+ * wholesale at resolve time, so a first-time per-session override that edits any cell of such an array+ * loses the untouched rows' secrets (they redact to `***`, the dashboard can't resend the real value).+ * No bundled plugin ships that shape; a plugin needing per-session array secrets should re-enter them.+ */+function sparseSessionOverride(full: Record<string, unknown>, plugin: Plugin): Record<string, unknown> {+ const props = plugin.configSchema?.properties;+ if (!props) return full;+ const out: Record<string, unknown> = {};+ for (const [key, field] of Object.entries(props)) {+ if (!(key in full)) continue;+ const val = full[key];+ if (field.secret) {+ out[key] = val;+ continue;+ }+ if (JSON.stringify(val) === JSON.stringify(plugin.config[key])) continue; // unchanged → inherit Global+ if (plugin.config[key] === undefined && JSON.stringify(val) === JSON.stringify(emptyForField(field))) {+ continue; // untouched optional field with no Global value → don't pin a spurious empty override+ }+ out[key] = val;+ }+ return out;+}+/*** Renders one config field from a plugin's schema and reports edits via `onChange`. Recurses for* nested objects and array-of-rows. Module-scope (stable identity) so inputs keep focus across@@ -250,7 +285,7 @@ function ConfigField({* The host makes the authenticated PUT (secret redact/restore applies); the iframe only ever sees the* already-redacted config.*/-function PluginConfigUi({ plugin }: { plugin: Plugin }) {+function PluginConfigUi({ plugin, sessionId }: { plugin: Plugin; sessionId?: string }) {const { t } = useTranslation();const toast = useToast();const queryClient = useQueryClient();@@ -283,15 +318,25 @@ function PluginConfigUi({ plugin }: { plugin: Plugin }) {// Only expose schema-DECLARED fields (already secret-redacted by the API). An undeclared key// may hold a secret the host can't mask, so it never reaches the untrusted iframe; with no// schema there is nothing safe to send. The plugin must declare its fields to pre-fill them.+ // For a per-session editor (sessionId set), expose the resolved slice: the session's override+ // value where set, else the base value.const props = plugin.configSchema?.properties;+ const override = sessionId ? (plugin.sessionConfig?.[sessionId] ?? {}) : {};const safeConfig = props- ? Object.fromEntries(Object.keys(props).flatMap(k => (k in plugin.config ? [[k, plugin.config[k]]] : [])))+ ? Object.fromEntries(+ Object.keys(props).flatMap(k => {+ if (sessionId && k in override) return [[k, override[k]]];+ return k in plugin.config ? [[k, plugin.config[k]]] : [];+ }),+ ): {};post({ type: 'config:value', config: safeConfig, schema: plugin.configSchema });} else if (msg?.type === 'config:save') {void (async () => {try {- await pluginsApi.updateConfig(plugin.id, msg.config ?? {});+ if (sessionId)+ await pluginsApi.updateSessionConfig(plugin.id, sessionId, sparseSessionOverride(msg.config ?? {}, plugin));+ else await pluginsApi.updateConfig(plugin.id, msg.config ?? {});void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });post({ type: 'config:saved' });toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));@@ -305,7 +350,7 @@ function PluginConfigUi({ plugin }: { plugin: Plugin }) {};window.addEventListener('message', onMessage);return () => window.removeEventListener('message', onMessage);- }, [plugin, queryClient, t, toast]);+ }, [plugin, sessionId, queryClient, t, toast]);if (error) return <div className="config-ui-status config-ui-error">{error}</div>;if (html === null)@@ -326,6 +371,175 @@ function PluginConfigUi({ plugin }: { plugin: Plugin }) {);}+/**+ * The config modal's "Sessions" tab for a session-scoped plugin: set which sessions it runs for+ * (activation), and optionally a per-session config OVERRIDE on top of the Global (`'*'`) config.+ * Activation → PUT /plugins/:id/sessions; overrides → PUT /plugins/:id/config/:sessionId.+ */+function SessionsTab({ plugin }: { plugin: Plugin }) {+ const { t, i18n } = useTranslation();+ const toast = useToast();+ const queryClient = useQueryClient();+ const { data: sessions = [] } = useSessionsQuery();++ // ── Activation ────────────────────────────────────────────────────────────+ const [mode, setMode] = useState<'all' | 'specific'>(plugin.activeSessions.includes('*') ? 'all' : 'specific');+ const [picked, setPicked] = useState<Set<string>>(new Set(plugin.activeSessions.filter(s => s !== '*')));+ const [savingAct, setSavingAct] = useState(false);++ const saveActivation = async () => {+ setSavingAct(true);+ try {+ await pluginsApi.setSessions(plugin.id, mode === 'all' ? ['*'] : Array.from(picked));+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });+ toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));+ } catch (err) {+ toast.error(t('plugins.toasts.saveFailed'), err instanceof Error ? err.message : t('common.unknownError'));+ } finally {+ setSavingAct(false);+ }+ };++ // ── Per-session config override ───────────────────────────────────────────+ const hasSchema = !!plugin.configSchema && Object.keys(plugin.configSchema.properties).length > 0;+ const hasUi = !!plugin.configUi;+ const lzProps = localizePlugin(plugin, i18n.language).configSchema?.properties;+ const [selSession, setSelSession] = useState<string>('');+ const [overrideCfg, setOverrideCfg] = useState<Record<string, unknown>>({});+ const [savingOverride, setSavingOverride] = useState(false);++ // Seed the override form from the resolved slice (the session's override value where set, else base).+ // Keyed on selSession + plugin.id (NOT the plugin object): `configPlugin` is derived from the live+ // query, so it gets a new reference on every refetch (refetchOnWindowFocus) — re-running on that+ // would wipe the operator's in-progress edits. Reseed only when the selected session/plugin changes.+ useEffect(() => {+ const props = plugin.configSchema?.properties;+ if (!selSession || !props) {+ setOverrideCfg({});+ return;+ }+ const ov = plugin.sessionConfig?.[selSession] ?? {};+ const seeded: Record<string, unknown> = {};+ for (const [key, field] of Object.entries(props)) {+ seeded[key] = key in ov ? ov[key] : (plugin.config[key] ?? emptyForField(field));+ }+ setOverrideCfg(seeded);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [selSession, plugin.id]);++ const saveOverride = async () => {+ if (!selSession || !plugin.configSchema?.properties) return;+ setSavingOverride(true);+ try {+ await pluginsApi.updateSessionConfig(plugin.id, selSession, sparseSessionOverride(overrideCfg, plugin));+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });+ toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));+ } catch (err) {+ toast.error(t('plugins.toasts.saveFailed'), err instanceof Error ? err.message : t('common.unknownError'));+ } finally {+ setSavingOverride(false);+ }+ };++ const clearOverride = async () => {+ if (!selSession) return;+ setSavingOverride(true);+ try {+ await pluginsApi.updateSessionConfig(plugin.id, selSession, {});+ void queryClient.invalidateQueries({ queryKey: queryKeys.plugins });+ toast.success(t('plugins.toasts.savedTitle'), t('plugins.toasts.savedDesc'));+ } catch (err) {+ toast.error(t('plugins.toasts.saveFailed'), err instanceof Error ? err.message : t('common.unknownError'));+ } finally {+ setSavingOverride(false);+ }+ };++ const hasOverride = (sid: string): boolean => Object.keys(plugin.sessionConfig?.[sid] ?? {}).length > 0;++ return (+ <div className="sessions-tab">+ <section className="sessions-section">+ <h3>{t('plugins.sessions.activationTitle')}</h3>+ <small>{t('plugins.sessions.activationDesc')}</small>+ <label className="sessions-radio">+ <input type="radio" name="activation" checked={mode === 'all'} onChange={() => setMode('all')} />+ <span>{t('plugins.sessions.allSessions')}</span>+ </label>+ <label className="sessions-radio">+ <input type="radio" name="activation" checked={mode === 'specific'} onChange={() => setMode('specific')} />+ <span>{t('plugins.sessions.specificSessions')}</span>+ </label>+ {mode === 'specific' &&+ (sessions.length === 0 ? (+ <p className="sessions-empty">{t('plugins.sessions.noSessions')}</p>+ ) : (+ <div className="sessions-checklist">+ {sessions.map(s => (+ <label key={s.id} className="sessions-check">+ <input+ type="checkbox"+ checked={picked.has(s.id)}+ onChange={e => {+ const next = new Set(picked);+ if (e.target.checked) next.add(s.id);+ else next.delete(s.id);+ setPicked(next);+ }}+ />+ <span>{s.name || s.id}</span>+ </label>+ ))}+ </div>+ ))}+ <button className="btn-primary" onClick={() => void saveActivation()} disabled={savingAct}>+ {savingAct ? <Loader2 size={16} className="animate-spin" /> : t('plugins.sessions.saveActivation')}+ </button>+ </section>++ {(hasSchema || hasUi) && (+ <section className="sessions-section">+ <h3>{t('plugins.sessions.perSessionTitle')}</h3>+ <small>{t('plugins.sessions.perSessionDesc')}</small>+ <select className="sessions-select" value={selSession} onChange={e => setSelSession(e.target.value)}>+ <option value="">{t('plugins.sessions.selectSession')}</option>+ {sessions.map(s => (+ <option key={s.id} value={s.id}>+ {(s.name || s.id) + (hasOverride(s.id) ? ' ●' : '')}+ </option>+ ))}+ </select>+ {selSession && hasUi ? (+ <PluginConfigUi key={selSession} plugin={plugin} sessionId={selSession} />+ ) : selSession && plugin.configSchema ? (+ <>+ <div className="config-form">+ {Object.entries(lzProps ?? plugin.configSchema.properties).map(([key, field]) => (+ <ConfigField+ key={key}+ field={field}+ label={field.title || key}+ value={overrideCfg[key]}+ onChange={v => setOverrideCfg({ ...overrideCfg, [key]: v })}+ />+ ))}+ </div>+ <div className="sessions-override-actions">+ <button className="btn-secondary" onClick={() => void clearOverride()} disabled={savingOverride}>+ {t('plugins.sessions.clearOverride')}+ </button>+ <button className="btn-primary" onClick={() => void saveOverride()} disabled={savingOverride}>+ {savingOverride ? <Loader2 size={16} className="animate-spin" /> : t('plugins.sessions.saveOverride')}+ </button>+ </div>+ </>+ ) : null}+ </section>+ )}+ </div>+ );+}+export default function Plugins() {const { t, i18n } = useTranslation();useDocumentTitle(t('plugins.title'));@@ -341,7 +555,11 @@ export default function Plugins() {const [actionLoading, setActionLoading] = useState<string | null>(null);const [showConfigModal, setShowConfigModal] = useState(false);- const [configPlugin, setConfigPlugin] = useState<Plugin | null>(null);+ const [configPluginId, setConfigPluginId] = useState<string | null>(null);+ // Derive the open plugin from the LIVE query so the modal (esp. the Sessions tab) reflects the+ // latest activeSessions/sessionConfig after a save + invalidate — not a stale open-time snapshot.+ const configPlugin = configPluginId ? (plugins.find(p => p.id === configPluginId) ?? null) : null;+ const [configTab, setConfigTab] = useState<'config' | 'sessions'>('config');const [engineConfig, setEngineConfig] = useState<EngineConfig>({type: infraStatus?.engine?.type || 'whatsapp-web.js',headless: infraStatus?.engine?.headless ?? true,@@ -399,7 +617,8 @@ export default function Plugins() {};const handleOpenConfig = (plugin: Plugin) => {- setConfigPlugin(plugin);+ setConfigPluginId(plugin.id);+ setConfigTab('config');// Seed the schema form from the plugin's saved config, falling back to each field's default.if (plugin.configSchema?.properties) {const initial: Record<string, unknown> = {};@@ -929,6 +1148,8 @@ export default function Plugins() {{showConfigModal && configPlugin && (() => {const lz = localizePlugin(configPlugin, i18n.language);+ // Session-scoped, non-engine plugins get a Configuration/Sessions tab split; others keep one body.+ const showTabs = configPlugin.type !== 'engine' && configPlugin.sessionScoped !== false;return (<div className="modal-overlay" onClick={() => setShowConfigModal(false)}><div className="modal config-modal" onClick={e => e.stopPropagation()}>@@ -939,8 +1160,27 @@ export default function Plugins() {</button></div>+ {showTabs && (+ <div className="modal-tabs">+ <button+ className={`modal-tab ${configTab === 'config' ? 'active' : ''}`}+ onClick={() => setConfigTab('config')}+ >+ {t('plugins.config.tabConfig')}+ </button>+ <button+ className={`modal-tab ${configTab === 'sessions' ? 'active' : ''}`}+ onClick={() => setConfigTab('sessions')}+ >+ {t('plugins.config.tabSessions')}+ </button>+ </div>+ )}+<div className="modal-body">- {configPlugin.type === 'engine' ? (+ {showTabs && configTab === 'sessions' ? (+ <SessionsTab plugin={configPlugin} />+ ) : configPlugin.type === 'engine' ? (<><div className="config-info-banner"><AlertCircle size={16} />@@ -1017,9 +1257,10 @@ export default function Plugins() {<div className="modal-footer"><button className="btn-secondary" onClick={() => setShowConfigModal(false)}>- {t('common.cancel')}+ {t('common.close')}</button>- {configPlugin.type === 'engine' ? (+ {/* The Sessions tab has its own Save/Clear actions; the footer Save is config-tab only. */}+ {showTabs && configTab === 'sessions' ? null : configPlugin.type === 'engine' ? (<button className="btn-primary" onClick={handleSaveConfig} disabled={savingConfig}>{savingConfig ? <Loader2 size={16} className="animate-spin" /> : t('plugins.config.save')}</button>diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex becf577f1..3ec6482b9 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -650,6 +650,12 @@ export interface Plugin {configSchema?: PluginConfigSchema;/** When set, the plugin ships a sandboxed-iframe config editor (preferred over configSchema). */configUi?: { entry: string; height?: number };+ /** Whether the plugin is scoped to specific sessions (false = global, always runs). */+ sessionScoped: boolean;+ /** Sessions the plugin is activated for; ['*'] = all numbers. */+ activeSessions: string[];+ /** Per-session config overrides, keyed by sessionId (secrets redacted per slice). */+ sessionConfig?: Record<string, Record<string, unknown>>;loadedAt?: string;enabledAt?: string;error?: string;@@ -706,6 +712,15 @@ export const pluginsApi = {method: 'PUT',body: JSON.stringify({ config }),}),+ /** Set which sessions a session-scoped plugin is activated for (['*'] = all). */+ setSessions: (id: string, sessions: string[]) =>+ request<Plugin>(`/plugins/${id}/sessions`, { method: 'PUT', body: JSON.stringify({ sessions }) }),+ /** Set (or clear, with an empty object) a plugin's config override for one session. */+ updateSessionConfig: (id: string, sessionId: string, config: Record<string, unknown>) =>+ request<{ success: boolean; message: string }>(`/plugins/${id}/config/${encodeURIComponent(sessionId)}`, {+ method: 'PUT',+ body: JSON.stringify({ config }),+ }),healthCheck: (id: string) => request<{ healthy: boolean; message?: string }>(`/plugins/${id}/health`),install: (file: File) => {const form = new FormData();diff --git a/docs/superpowers/specs/2026-06-23-plugin-per-session-dashboard-design.md b/docs/superpowers/specs/2026-06-23-plugin-per-session-dashboard-design.mdnew file mode 100644index 000000000..38fbc99b9--- /dev/null+++ b/docs/superpowers/specs/2026-06-23-plugin-per-session-dashboard-design.md@@ -0,0 +1,47 @@+# Per-session plugin dashboard UI (v0.7)++Status: approved 2026-06-23. Dashboard-only; all backend APIs already exist.++## Goal++Surface, in the dashboard, the two per-session capabilities whose backends shipped without UI:++- **Activation (#438):** which sessions a session-scoped plugin runs for — `activeSessions` = `['*']` (all) or an explicit set. API: `PUT /plugins/:id/sessions`.+- **Per-session config (#441):** a per-session config override on top of the base (`'*'`) config — `sessionConfig[sessionId]`. API: `PUT /plugins/:id/config/:sessionId` (empty body clears the override).++The DTO already returns `sessionScoped`, `activeSessions`, `sessionConfig` (secrets redacted per slice). No backend change.++## Design++### 1. API client (`dashboard/src/services/api.ts`)+- Extend `Plugin`: `sessionScoped: boolean`, `activeSessions: string[]`, `sessionConfig?: Record<string, Record<string, unknown>>`.+- `pluginsApi.setSessions(id, sessions: string[])` → `PUT /plugins/:id/sessions` (body `{ sessions }`).+- `pluginsApi.updateSessionConfig(id, sessionId, config)` → `PUT /plugins/:id/config/:sessionId` (body `{ config }`); empty `config` clears.++### 2. Tabbed config modal (`dashboard/src/pages/Plugins.tsx`)+- Tabs render only for a **session-scoped, non-engine** plugin (`type !== 'engine' && sessionScoped !== false`): `[ Configuration ] [ Sessions ]`. Otherwise the modal body is unchanged (no tabs).+- **Configuration tab** = today's base config exactly (B-lite `ConfigField` form / B-full iframe / no-config). Unchanged.+- **Sessions tab** (uses `useSessionsQuery()`):+ - *Activation:* radio **All sessions** (`['*']`) / **Specific** → a checklist of sessions. **Save** → `setSessions(['*'])` or the checked ids. Empty specific set = active for none.+ - *Per-session config* (only if the plugin has `configSchema` or `configUi`): a session `<select>` (all sessions from the query) → edits that session's override:+ - **B-lite:** the existing recursive `ConfigField` form, seeded from the **resolved slice** (base ⊕ override). **Save** PUTs only the top-level keys that **differ from base** (sparse override). **Clear override** PUTs `{}`.+ - **B-full:** reuse `PluginConfigUi` with a new optional `sessionId` prop → bridge `config:get` returns that session's redacted slice (`sessionConfig[sid]` merged over base), `config:save` → `updateSessionConfig(id, sid, cfg)`.++### 3. i18n+New keys (tabs, activation labels, per-session labels, clear-override) added to all 9 locales — the parity gate (`dashboard/scripts/check-i18n-parity.mjs`) must pass.++### 4. CSS (`Plugins.css`)+Tab bar + Sessions-tab sections (activation radio/checklist, per-session picker), matching the existing modal styling.++## Key decisions++- **Sparse overrides (diff-on-save):** the per-session B-lite editor stores only keys that differ from the base, so later base-config edits still propagate to a session's untouched fields. An untouched secret shows `***` (== base) → not in the diff → inherits; a newly-typed secret is stored via the backend's `restoreSecretConfig`.+- **Picker lists ALL sessions** (not just activated ones): overriding config for a session is harmless when inactive (the override only applies while the plugin is active for it), and it works when `activeSessions = ['*']` (no explicit list to pick from).+- **Engine / global plugins:** no Sessions tab.++## Out of scope / YAGNI+- Per-field "inherit vs override" tri-state UI (the sparse diff-on-save covers inheritance without per-field toggles).+- Bulk per-session config (set the same override across many sessions at once).++## Verification+Dashboard `npm run build` (tsc) + `npm run lint` + i18n parity. No jest (the dashboard has no test framework, per project convention); the API-client + render logic are exercised via build typecheck + manual trace. Adversarial review of the diff before merge.diff --git a/src/core/plugins/plugin-activation.spec.ts b/src/core/plugins/plugin-activation.spec.tsindex ccde9856c..a55592770 100644--- a/src/core/plugins/plugin-activation.spec.ts+++ b/src/core/plugins/plugin-activation.spec.ts@@ -43,6 +43,21 @@ describe('resolvePluginConfig', () => {});});+ it('deep-merges a nested object override, inheriting untouched nested keys (e.g. a nested secret)', () => {+ const b = { smtp: { host: 'mail.x', password: 'real' }, lang: 'en' };+ const sc = { 'sess-1': { smtp: { host: 'mail.y' } } };+ expect(resolvePluginConfig(b, sc, 'sess-1', true)).toEqual({+ smtp: { host: 'mail.y', password: 'real' },+ lang: 'en',+ });+ });++ it('replaces arrays wholesale on override (no element-wise merge)', () => {+ const b = { items: [1, 2, 3] };+ const sc = { 'sess-1': { items: [9] } };+ expect(resolvePluginConfig(b, sc, 'sess-1', true)).toEqual({ items: [9] });+ });+it('ignores overrides for a global (non-session-scoped) plugin', () => {expect(resolvePluginConfig(base, { 'sess-1': { lang: 'he' } }, 'sess-1', false)).toEqual(base);});diff --git a/src/core/plugins/plugin-activation.ts b/src/core/plugins/plugin-activation.tsindex b5bd33076..d04431a26 100644--- a/src/core/plugins/plugin-activation.ts+++ b/src/core/plugins/plugin-activation.ts@@ -17,11 +17,29 @@ export function isPluginActiveForSession(return activeSessions.includes(sessionId);}+const isPlainObject = (v: unknown): v is Record<string, unknown> =>+ typeof v === 'object' && v !== null && !Array.isArray(v);++/**+ * Recursively merge `override` over `base`: nested plain objects merge key-by-key so an override that+ * sets only some keys inherits the rest from the base (incl. nested secrets); arrays and scalars are+ * replaced wholesale. Returns fresh objects; never mutates the inputs.+ */+function deepMerge(base: Record<string, unknown>, override: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = { ...base };+ for (const [key, value] of Object.entries(override)) {+ const baseValue = out[key];+ out[key] = isPlainObject(baseValue) && isPlainObject(value) ? deepMerge(baseValue, value) : value;+ }+ return out;+}+/**- * Resolve the config a plugin sees for a given session: the per-session override (if any) shallow-- * merged over the base ('*') config, so an override wins per top-level key. A global plugin and a- * non-session-attributed event (no sessionId) always get the base unchanged. Returns a fresh object- * on merge; never mutates the inputs.+ * Resolve the config a plugin sees for a given session: the per-session override (if any) deep-merged+ * over the base ('*') config, so an override only changes the keys it specifies (at any depth) and+ * inherits the rest from the base — a sparse override can't drop a base key (e.g. a nested secret) it+ * didn't touch. A global plugin and a non-session-attributed event (no sessionId) get the base+ * unchanged. Returns a fresh object on merge; never mutates the inputs.*/export function resolvePluginConfig(base: Record<string, unknown>,@@ -31,5 +49,5 @@ export function resolvePluginConfig(): Record<string, unknown> {if (!sessionScoped || sessionId === undefined || !sessionConfig) return base;const override = sessionConfig[sessionId];- return override ? { ...base, ...override } : base;+ return override ? deepMerge(base, override) : base;}