Explorar o código

fix: labs order, tooltip theme and channel toggle sync (#1012-#1018) (#1019)

* fix(server): mirror channel enabled keys from the integrations toggle (#1016 #1017)

* refactor(settings): labs order, tooltip theme, tokens text, channel toggles and chips

- Labs services render before the integrations group (#1012)
- Tooltips use theme tokens, no more white background in dark mode (#1013)
- Tokens short description shown directly on the card (#1015)
- ntfy and Telegram lose the enable toggle inside their dialogs; the
  outer row is the single source of truth (#1016 #1017)
- Warning chip on enabled-but-misconfigured channels (#1017)
- 10px between the configure gear and the switch (#1018)
Nacho hai 2 meses
pai
achega
95337f1886

+ 4 - 2
app/public/locales/en/translation.json

@@ -1359,7 +1359,8 @@
       "soundOn": "On — plays a soft beep",
       "telegramCaption": "Notifications to the Telegram bot",
       "testSound": "Test alert beep",
-      "title": "Notifications"
+      "title": "Notifications",
+      "notConfigured": "Not configured"
     },
     "push": {
       "title": "Push notifications",
@@ -2230,7 +2231,8 @@
     "created": "Created",
     "expires": "Expires",
     "lastUsed": "Last used",
-    "revoke": "Revoke"
+    "revoke": "Revoke",
+    "descShort": "Tokens allow API access without a session."
   },
   "collector": {
     "title": "TCP Latency (collector)",

+ 4 - 2
app/public/locales/es/translation.json

@@ -1359,7 +1359,8 @@
       "soundOn": "Activado — suena un beep suave",
       "telegramCaption": "Notificaciones al bot de Telegram",
       "testSound": "Probar beep de alerta",
-      "title": "Notificaciones"
+      "title": "Notificaciones",
+      "notConfigured": "Sin configurar"
     },
     "push": {
       "title": "Notificaciones push",
@@ -2230,7 +2231,8 @@
     "created": "Creado",
     "expires": "Caduca",
     "lastUsed": "Último uso",
-    "revoke": "Revocar"
+    "revoke": "Revocar",
+    "descShort": "Los tokens permiten acceder a la API sin sesión."
   },
   "collector": {
     "title": "Latencia TCP (collector)",

+ 5 - 10
app/src/components/NtfyCard.tsx

@@ -55,7 +55,9 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
       const body: Record<string, unknown> = {
         server: cfg.server.trim() || 'https://ntfy.sh',
         topic: cfg.topic.trim(),
-        enabled: cfg.enabled,
+        // #1016: el enable se gobierna desde la fila exterior; al configurar
+        // aquí el canal queda listo (enabled=true) y el gate decide por evento.
+        enabled: true,
         urgentOnly: cfg.urgentOnly,
       }
       if (cfg.token.trim()) body.token = cfg.token.trim()
@@ -118,15 +120,8 @@ export default function NtfyCard({ onSaved, bare = true }: { onSaved: () => void
 
   const form = (
     <>
-      <div className="flex items-center justify-between gap-4 py-1">
-        <span className="text-sm font-medium text-text-primary">{t('settings.ntfy.enabled')}</span>
-        <Switch
-          checked={cfg.enabled}
-          onCheckedChange={(v) => setCfg((c) => ({ ...c, enabled: v }))}
-          aria-label={t('settings.ntfy.enabled')}
-        />
-      </div>
-
+      {/* #1016: sin toggle de activar aquí - el enable vive SOLO en la fila
+          de Notificaciones (integrationGate + espejo ntfy.enabled). */}
       <div className="flex items-center justify-between gap-4 py-1">
         <span className="flex items-center gap-1 text-sm font-medium text-text-primary">
           {t('settings.ntfy.urgentOnly')}

+ 7 - 14
app/src/components/TelegramCard.tsx

@@ -1,7 +1,6 @@
 import { useState, useEffect, useCallback } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Send, Loader2, Check, Eye, EyeOff, Bell } from 'lucide-react'
-import { Switch } from '@/components/ui/switch'
 import { InfoTip } from '@/components/InfoTip'
 
 type TelegramState = 'loading' | 'idle' | 'saving' | 'testing' | 'saved' | 'error'
@@ -59,7 +58,9 @@ export default function TelegramCard({ onSaved, bare = false }: { onSaved: () =>
         body: JSON.stringify({
           botToken: cfg.botToken,
           chatId: cfg.chatId,
-          enabled: cfg.enabled,
+          // #1017: el enable se gobierna desde la fila exterior; al configurar
+          // aquí el canal queda listo y el gate decide por evento.
+          enabled: true,
         }),
       })
       const data = await res.json().catch(() => null)
@@ -132,12 +133,8 @@ export default function TelegramCard({ onSaved, bare = false }: { onSaved: () =>
   if (bare) {
     return (
       <>
-        {/* Activar notificaciones como Switch (mismo patrón que las otras tarjetas) */}
-        <div className="flex items-center justify-between gap-4 py-1">
-          <span className="text-sm font-medium text-text-primary">{t('settings.telegram.enabled')}</span>
-          <Switch checked={cfg.enabled} onCheckedChange={(v) => setCfg((c) => ({ ...c, enabled: v }))} aria-label={t('settings.telegram.enabled')} />
-        </div>
-
+        {/* #1017: sin toggle de activar aquí - el enable vive SOLO en la
+            fila de Notificaciones (integrationGate + espejo telegram.enabled). */}
         <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
           {/* Bot token */}
           <div>
@@ -229,12 +226,8 @@ export default function TelegramCard({ onSaved, bare = false }: { onSaved: () =>
       {header}
 
       <div className="space-y-3">
-        {/* Enable toggle */}
-        <div className="flex items-center justify-between gap-4">
-          <span className="text-sm font-medium text-text-primary">{t('settings.telegram.enabled')}</span>
-          <Switch checked={cfg.enabled} onCheckedChange={(v) => setCfg((c) => ({ ...c, enabled: v }))} aria-label={t('settings.telegram.enabled')} />
-        </div>
-
+        {/* #1017: sin toggle de activar aquí tampoco; el enable vive solo en
+            la fila de Notificaciones. */}
         {/* Bot token + Chat ID en la misma fila */}
         <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
           <div>

+ 2 - 2
app/src/components/TokensManager.tsx

@@ -2,7 +2,6 @@ import { useCallback, useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Copy, KeyRound, Plus, Trash2 } from 'lucide-react'
 import { copyToClipboard } from '@/lib/utils'
-import { InfoTip } from '@/components/InfoTip'
 
 type TokenItem = {
   id: string
@@ -102,7 +101,8 @@ export function TokensManager() {
   return (
     <div>
       <div className="flex items-center justify-between">
-        <InfoTip text={t('tokens.desc')} />
+        {/* #1015: la descripción corta va directa en la tarjeta, sin (i). */}
+        <p className="text-sm text-text-secondary">{t('tokens.descShort')}</p>
         {!showForm && !created && (
           <button
             type="button"

+ 2 - 2
app/src/components/ui/tooltip.tsx

@@ -46,13 +46,13 @@ function TooltipContent({
         data-slot="tooltip-content"
         sideOffset={sideOffset}
         className={cn(
-          "bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
+          "bg-elevated text-text-primary border border-border-strong shadow-xl animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
           className
         )}
         {...props}
       >
         {children}
-        <TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
+        <TooltipPrimitive.Arrow className="bg-elevated fill-elevated z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
       </TooltipPrimitive.Content>
     </TooltipPrimitive.Portal>
   )

+ 79 - 44
app/src/pages/Settings.tsx

@@ -256,7 +256,8 @@ function SwitchRow({ icon: Icon, label, caption, checked, onCheckedChange, trail
           {caption && <div className="text-caption text-text-muted">{caption}</div>}
         </div>
       </div>
-      <div className="flex shrink-0 items-center gap-2">
+      {/* gap-2.5: 10px entre el icono de configurar (trailing) y el check (#1018) */}
+      <div className="flex shrink-0 items-center gap-2.5">
         {trailing}
         {/* danger: el acento rojo va en el CHECK (escribe en los routers),
             no en el texto de la fila. */}
@@ -3598,6 +3599,50 @@ function ServicesCard({
             }}
           />
         </div>
+
+        {/* Servicios de Labs (#1012): antes que las integraciones */}
+        {services.labs && (
+          <div className="mt-2 grid grid-cols-1 gap-x-6 gap-y-0 sm:grid-cols-2">
+            <div className="divide-y divide-border/60">
+              {/* Orquestación (opt-in del admin) */}
+              <SwitchRow
+                label={t('settings.admin.orchestration')}
+                caption={t('settings.services.orchestrationHint')}
+                checked={orchOn}
+                onCheckedChange={(v) => void toggleOrchestration(v)}
+                disabled={orchBusy || disabled}
+                danger
+              />
+              {/* Canales */}
+              <SwitchRow
+                label={t('settings.labs.canales')}
+                caption={t('settings.labs.canalesCaption')}
+                checked={services.canales}
+                disabled={disabled}
+                danger
+                onCheckedChange={(v) => {
+                  setService('canales', v)
+                  onSaved()
+                }}
+              />
+            </div>
+            <div className="divide-y divide-border/60">
+              {/* Actualizaciones */}
+              <SwitchRow
+                label={t('settings.labs.actualizaciones')}
+                caption={t('settings.labs.actualizacionesCaption')}
+                checked={services.actualizaciones}
+                disabled={disabled}
+                danger
+                onCheckedChange={(v) => {
+                  setService('actualizaciones', v)
+                  onSaved()
+                }}
+              />
+            </div>
+          </div>
+        )}
+
         <div className="pb-1 pt-4 text-label uppercase text-text-muted">{t('settings.services.integrationsGroup')}</div>
         <div className="divide-y divide-border/60">
           {integrationRows.map((row) => (
@@ -3617,48 +3662,6 @@ function ServicesCard({
         </div>
       </div>
 
-      {services.labs && (
-        <div className="mt-4 grid grid-cols-1 gap-x-6 gap-y-0 border-t border-border pt-4 sm:grid-cols-2">
-          <div className="divide-y divide-border/60">
-            {/* Orquestación (opt-in del admin) */}
-            <SwitchRow
-              label={t('settings.admin.orchestration')}
-              caption={t('settings.services.orchestrationHint')}
-              checked={orchOn}
-              onCheckedChange={(v) => void toggleOrchestration(v)}
-              disabled={orchBusy || disabled}
-              danger
-            />
-            {/* Canales */}
-            <SwitchRow
-              label={t('settings.labs.canales')}
-              caption={t('settings.labs.canalesCaption')}
-              checked={services.canales}
-              disabled={disabled}
-              danger
-              onCheckedChange={(v) => {
-                setService('canales', v)
-                onSaved()
-              }}
-            />
-          </div>
-          <div className="divide-y divide-border/60">
-            {/* Actualizaciones */}
-            <SwitchRow
-              label={t('settings.labs.actualizaciones')}
-              caption={t('settings.labs.actualizacionesCaption')}
-              checked={services.actualizaciones}
-              disabled={disabled}
-              danger
-              onCheckedChange={(v) => {
-                setService('actualizaciones', v)
-                onSaved()
-              }}
-            />
-          </div>
-        </div>
-      )}
-
       {/* Diálogos de configuración de integraciones (#968): los managers
           viven SOLO en diálogo (#977: las cards sueltas ya no están en el
           flujo). Título sr-only: el Card del manager ya lo muestra. */}
@@ -3701,6 +3704,25 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
   const { t } = useTranslation()
   const { integrations, setIntegration } = useIntegrations(!disabled)
   const [dialog, setDialog] = useState<'ntfy' | 'telegram' | null>(null)
+  // #1017: estado de configuración por canal para el chip "activado pero sin
+  // configurar" (ntfy sin topic; Telegram sin token o chat).
+  const [configured, setConfigured] = useState<{ ntfy: boolean; telegram: boolean } | null>(null)
+  useEffect(() => {
+    let alive = true
+    void Promise.all([
+      fetch('/api/settings/ntfy').then((r) => (r.ok ? r.json() : null)).catch(() => null),
+      fetch('/api/settings/telegram').then((r) => (r.ok ? r.json() : null)).catch(() => null),
+    ]).then(([n, g]) => {
+      if (!alive) return
+      setConfigured({
+        ntfy: !!(n && typeof n.topic === 'string' && n.topic.trim() !== ''),
+        telegram: !!(g && g.tokenSet && typeof g.chatId === 'string' && g.chatId.trim() !== ''),
+      })
+    })
+    return () => {
+      alive = false
+    }
+  }, [])
   const rows: { key: 'ntfy' | 'telegram'; label: string; caption: string }[] = [
     { key: 'ntfy', label: 'ntfy', caption: t('settings.notif.ntfyCaption') },
     { key: 'telegram', label: 'Telegram', caption: t('settings.notif.telegramCaption') },
@@ -3715,7 +3737,20 @@ function NotifChannels({ onSaved, disabled = false }: { onSaved: () => void; dis
             caption={row.caption}
             checked={integrations[row.key]}
             disabled={disabled}
-            trailing={<ConfigGear label={t('settings.services.configure', { name: row.label })} onClick={() => setDialog(row.key)} />}
+            trailing={
+              <span className="flex items-center gap-2.5">
+                {integrations[row.key] && configured && !configured[row.key] && (
+                  <button
+                    type="button"
+                    onClick={() => setDialog(row.key)}
+                    className="rounded-full bg-warn/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-warn transition-colors hover:bg-warn/20"
+                  >
+                    {t('settings.notif.notConfigured')}
+                  </button>
+                )}
+                <ConfigGear label={t('settings.services.configure', { name: row.label })} onClick={() => setDialog(row.key)} />
+              </span>
+            }
             onCheckedChange={(v) => {
               setIntegration(row.key, v)
               onSaved()

+ 14 - 3
server-go/internal/httpapi/settings.go

@@ -164,10 +164,15 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 		for _, p := range []struct {
 			flag *bool
 			key  string
+			// channelKey: clave "enabled" propia del canal (ntfy.enabled,
+			// telegram.enabled). El toggle de la fila es la ÚNICA fuente de
+			// verdad (#1016/#1017): se espeja aquí para que el path de envío
+			// (que lee la clave del canal) y el integrationGate nunca desincronicen.
+			channelKey string
 		}{
-			{body.Ntfy, integrationNtfyKey},
-			{body.Telegram, integrationTelegramKey},
-			{body.Proxmox, integrationProxmoxKey},
+			{body.Ntfy, integrationNtfyKey, "ntfy.enabled"},
+			{body.Telegram, integrationTelegramKey, "telegram.enabled"},
+			{body.Proxmox, integrationProxmoxKey, ""},
 		} {
 			if p.flag == nil {
 				continue
@@ -178,6 +183,12 @@ func (s *server) registerSettingsRoutes(mux *http.ServeMux) {
 				writeError(w, http.StatusInternalServerError, "kv_error")
 				return
 			}
+			if p.channelKey != "" {
+				if err := kvSetStr(s.db.DB, p.channelKey, strconv.FormatBool(*p.flag)); err != nil {
+					writeError(w, http.StatusInternalServerError, "kv_error")
+					return
+				}
+			}
 		}
 		if body.MQTT != nil {
 			if err := s.setMQTTEnabled(*body.MQTT); err != nil {

+ 39 - 0
server-go/internal/httpapi/settings_integrations_test.go

@@ -74,3 +74,42 @@ func TestIntegrationsPutIsPartialSafe(t *testing.T) {
 		t.Fatalf("PUT vacío: status %d, esperado 400", res.StatusCode)
 	}
 }
+
+// TestIntegrationsMirrorChannelEnabled (#1016/#1017): el toggle de la fila es
+// la única fuente de verdad - el PUT espeja ntfy.enabled/telegram.enabled
+// para que el path de envío y el integrationGate nunca desincronicen.
+func TestIntegrationsMirrorChannelEnabled(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test123456")
+	if cookie == "" {
+		t.Fatal("login no devolvió cookie")
+	}
+
+	kvVal := func(key string) string {
+		var v string
+		if err := srv.db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
+			return ""
+		}
+		return v
+	}
+
+	res, _ := wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"ntfy":false,"telegram":true}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT: status %d", res.StatusCode)
+	}
+	if v := kvVal("ntfy.enabled"); v != "false" {
+		t.Fatalf("ntfy.enabled espejo: %q, esperado false", v)
+	}
+	if v := kvVal("telegram.enabled"); v != "true" {
+		t.Fatalf("telegram.enabled espejo: %q, esperado true", v)
+	}
+
+	// Proxmox NO tiene clave de canal que espejar.
+	res, _ = wanSpeedRequest(t, "PUT", srv.URL, "/api/settings/integrations", cookie, `{"proxmox":false}`)
+	if res.StatusCode != http.StatusOK {
+		t.Fatalf("PUT proxmox: status %d", res.StatusCode)
+	}
+	if v := kvVal("ntfy.enabled"); v != "false" {
+		t.Fatalf("ntfy.enabled tras PUT de proxmox: %q, esperado false intacto", v)
+	}
+}