Pārlūkot izejas kodu

feat(adapters): let each unit declare its inventory mode (#1917) (#1922)

Nacho 4 nedēļas atpakaļ
vecāks
revīzija
8962834d65

+ 2 - 0
CHANGELOG.md

@@ -11,6 +11,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 Each unit now reports where its inventory came from and how old it is (#1917). The server already knew the difference internally: a unit without an agent is inventoried over SSH on every tick, and an SNMP switch comes from its own collector, but that detail never left the process, so a client list pushed by an agent a minute ago looked exactly like one read over SSH four hours ago. The router page now shows the source (agent, SSH, SNMP or an integration) next to the age of the last poll. It also matters for units that will never run an agent: a readable inventory is still useful, as long as the operator can see it is not live.
 
+An inventory mode per unit decides what NetPulse expects from it (#1917). `auto` behaves as before: the agent when it pushes, SSH when it does not. `agent` is the old "agent only, no SSH" flag. `ssh` is new: the unit is inventoried over SSH and a missing agent is not treated as an outage, which is what a unit that cannot run the agent needs. The setting replaces the boolean in the router form, and the server keeps the old column in sync so every existing check keeps working untouched.
+
 ### Fixed
 
 - A release reuses the agent binaries again when the agent did not change (#1916). The step that downloads the previous release runs inside a temporary directory, and `gh` resolves the repository through git, so every attempt died with "not a git repository", printed a warning and fell back to compiling five architectures that were already built. The download now names the repository explicitly, so the previous assets are really reused and the embedded agent stays bit for bit the published one. Reusing also writes the version stamp of #1914, which the compile path produces but this one did not, otherwise the guard that reads the stamp would disable agent self-upgrade on every release that reused the binaries.

+ 6 - 0
app/public/locales/en/translation.json

@@ -1811,6 +1811,12 @@
       "agentOnly": "Agent only (no SSH)",
       "agentOnlyHint": "Data arrives only from the NetPulse/NetGrip agent push. The server never uses SSH on this unit.",
       "agentOnlyBadge": "Agent only",
+      "inventoryMode": "Inventory mode",
+      "inventoryModeAuto": "Auto",
+      "inventoryModeAgent": "Agent only",
+      "inventoryModeSsh": "SSH only",
+      "inventoryModeSshBadge": "SSH only",
+      "inventoryModeHint": "Auto uses the agent when it pushes and falls back to SSH. Agent only never uses SSH. SSH only expects no agent: the inventory is read over SSH and a missing agent is not treated as an outage.",
       "edit": "Edit",
       "editTitle": "Edit {{id}}",
       "editHint": "Modify the router details. Saving hot-reloads the configuration.",

+ 6 - 0
app/public/locales/es/translation.json

@@ -1811,6 +1811,12 @@
       "agentOnly": "Solo agente (sin SSH)",
       "agentOnlyHint": "Los datos llegan solo del push del agente NetPulse/NetGrip. El servidor nunca usa SSH en esta unidad.",
       "agentOnlyBadge": "Solo agente",
+      "inventoryMode": "Modo de inventario",
+      "inventoryModeAuto": "Automático",
+      "inventoryModeAgent": "Solo agente",
+      "inventoryModeSsh": "Solo SSH",
+      "inventoryModeSshBadge": "Solo SSH",
+      "inventoryModeHint": "Automático usa el agente cuando empuja y cae a SSH. Solo agente nunca usa SSH. Solo SSH no espera agente: el inventario se lee por SSH y que el agente falte no cuenta como caída.",
       "edit": "Editar",
       "editTitle": "Editar {{id}}",
       "editHint": "Modifica los datos del router. Guardar actualiza la configuración en caliente.",

+ 3 - 0
app/src/data/types.ts

@@ -45,6 +45,9 @@ export interface Router {
   /** #1917: vía que produjo el inventario ("agent"|"external"|"snmp"|"ssh").
    *  Ausente si la unidad no tiene sondeo del que sacarlo. */
   inventorySource?: string
+  /** #1917: cómo está configurada la unidad. "auto" (default), "agent" (solo
+   *  agente, sin SSH) o "ssh" (nunca esperar agente). */
+  inventoryMode?: string
   /** #1917: epoch ms del sondeo que produjo ese inventario. */
   inventoryAt?: number
   status: Status

+ 39 - 15
app/src/pages/Settings.tsx

@@ -321,6 +321,8 @@ interface ConfigRouter {
   type: RouterType
   is_gateway: boolean
   agent_only: boolean
+  /** #1917: "auto" | "agent" | "ssh". El servidor deriva agent_only de aqui. */
+  inventory_mode?: string
   disabled: boolean
   firmware_target: string
   snmp_enabled: boolean
@@ -351,7 +353,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [name, setName] = useState('')
   const [type, setType] = useState<RouterType>('openwrt')
   const [gateway, setGateway] = useState(false)
-  const [agentOnly, setAgentOnly] = useState(false)
+  const [inventoryMode, setInventoryMode] = useState('auto')
   const [addSshPort, setAddSshPort] = useState(22)
   const [addSnmpEnabled, setAddSnmpEnabled] = useState(false)
   const [addSnmpCommunity, setAddSnmpCommunity] = useState('')
@@ -368,7 +370,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
   const [editName, setEditName] = useState('')
   const [editType, setEditType] = useState<RouterType>('openwrt')
   const [editGateway, setEditGateway] = useState(false)
-  const [editAgentOnly, setEditAgentOnly] = useState(false)
+  const [editInventoryMode, setEditInventoryMode] = useState('auto')
   const [editDisabled, setEditDisabled] = useState(false)
   const [editFirmwareTarget, setEditFirmwareTarget] = useState('')
   const [editSnmpEnabled, setEditSnmpEnabled] = useState(false)
@@ -520,7 +522,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           name: name.trim() || undefined,
           type,
           gateway,
-          agent_only: agentOnly,
+          inventory_mode: inventoryMode,
           ssh_port: addSshPort,
           snmp_enabled: addSnmpEnabled,
           snmp_community: addSnmpCommunity.trim() || undefined,
@@ -537,7 +539,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
       setName('')
       setType('openwrt')
       setGateway(false)
-      setAgentOnly(false)
+      setInventoryMode('auto')
       setAddSshPort(22)
       setAddSnmpEnabled(false)
       setAddSnmpCommunity('')
@@ -560,7 +562,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
     setEditName(r.name ?? '')
     setEditType(r.type)
     setEditGateway(r.is_gateway)
-    setEditAgentOnly(r.agent_only)
+    setEditInventoryMode(r.inventory_mode ?? (r.agent_only ? 'agent' : 'auto'))
     setEditDisabled(r.disabled ?? false)
     setEditFirmwareTarget(r.firmware_target ?? '')
     setEditSnmpEnabled(r.snmp_enabled ?? false)
@@ -589,7 +591,7 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
           name: editName.trim() || undefined,
           type: editType,
           gateway: editGateway,
-          agent_only: editAgentOnly,
+          inventory_mode: editInventoryMode,
           disabled: editDisabled,
           firmware_target: editFirmwareTarget.trim(),
           snmp_enabled: editSnmpEnabled,
@@ -691,6 +693,10 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                       <span className="rounded bg-accent-soft px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-accent">
                         {t('settings.routers.gatewayBadge')}
                       </span>
+                    ) : r.inventory_mode === 'ssh' ? (
+                      <span className="rounded bg-elevated px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-text-muted ring-1 ring-inset ring-border">
+                        {t('settings.routers.inventoryModeSshBadge')}
+                      </span>
                     ) : r.agent_only ? (
                       <span className="rounded bg-elevated px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-text-muted ring-1 ring-inset ring-border">
                         {t('settings.routers.agentOnlyBadge')}
@@ -850,10 +856,19 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
             <Switch checked={gateway} onCheckedChange={setGateway} />
             {t('settings.routers.gateway')}
           </label>
-          <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
-            <Switch checked={agentOnly} onCheckedChange={setAgentOnly} />
-            {t('settings.routers.agentOnly')}
-          </label>
+          <div className="flex items-center gap-2 text-sm text-text-secondary">
+            <span>{t('settings.routers.inventoryMode')}</span>
+            <SegmentedControl
+              options={[
+                { value: 'auto', label: t('settings.routers.inventoryModeAuto') },
+                { value: 'agent', label: t('settings.routers.inventoryModeAgent') },
+                { value: 'ssh', label: t('settings.routers.inventoryModeSsh') },
+              ]}
+              value={inventoryMode}
+              onChange={setInventoryMode}
+              ariaLabel={t('settings.routers.inventoryMode')}
+            />
+          </div>
           <button
             type="submit"
             disabled={submitting || !host.trim()}
@@ -1019,11 +1034,20 @@ function RoutersManager({ reduce, onSaved }: { reduce: boolean; onSaved: () => v
                   <Switch checked={editGateway} onCheckedChange={setEditGateway} />
                   {t('settings.routers.gateway')}
                 </label>
-                <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
-                  <Switch checked={editAgentOnly} onCheckedChange={setEditAgentOnly} />
-                  {t('settings.routers.agentOnly')}
-                  <InfoTip text={t('settings.routers.agentOnlyHint')} />
-                </label>
+                <div className="flex items-center gap-2 text-sm text-text-secondary">
+                  <span>{t('settings.routers.inventoryMode')}</span>
+                  <SegmentedControl
+                    options={[
+                      { value: 'auto', label: t('settings.routers.inventoryModeAuto') },
+                      { value: 'agent', label: t('settings.routers.inventoryModeAgent') },
+                      { value: 'ssh', label: t('settings.routers.inventoryModeSsh') },
+                    ]}
+                    value={editInventoryMode}
+                    onChange={setEditInventoryMode}
+                    ariaLabel={t('settings.routers.inventoryMode')}
+                  />
+                  <InfoTip text={t('settings.routers.inventoryModeHint')} />
+                </div>
                 {/* #1085: pausa la unidad sin borrarla ni perder histórico. */}
                 <label className="flex cursor-pointer items-center gap-2 text-sm text-text-secondary">
                   <Switch checked={editDisabled} onCheckedChange={setEditDisabled} />

+ 4 - 1
server-go/internal/adapters/agent.go

@@ -582,7 +582,10 @@ func (l *Live) pollRouterAgent(cfg RouterConfig) (bool, *routerPolled) {
 		confirm = reg.ExternalDownConfirm(slug, confirm)
 		if reg.StaleFor(slug, confirm) {
 			l.mu.Lock()
-			if !l.agentDown[cfg.ID] {
+			// #1917: en una unidad con inventory_mode "ssh" el agente no se
+			// espera nunca, asi que su ausencia no es un evento: nada de
+			// alerta, ni urgente ni warn.
+			if !l.agentDown[cfg.ID] && cfg.InventoryMode != "ssh" {
 				l.agentDown[cfg.ID] = true
 				name := agentName(cfg)
 				// #850: para routers agent-only el agente ES la única vía

+ 6 - 1
server-go/internal/adapters/inventory_source_1917_test.go

@@ -38,7 +38,7 @@ func TestBuildRouterPublishesInventoryOrigin(t *testing.T) {
 	l := NewLive(nil, nil, nil, nil)
 	polled := time.Now().Add(-7 * time.Minute).UnixMilli()
 	p := &routerPolled{
-		cfg:      RouterConfig{ID: "rt2", Name: "rt2", Host: "192.168.1.2"},
+		cfg:       RouterConfig{ID: "rt2", Name: "rt2", Host: "192.168.1.2", InventoryMode: "ssh"},
 		agentKind: "native",
 		polledAt:  polled,
 	}
@@ -51,4 +51,9 @@ func TestBuildRouterPublishesInventoryOrigin(t *testing.T) {
 	if r.InventoryAt != polled {
 		t.Fatalf("InventoryAt = %d, esperaba %d", r.InventoryAt, polled)
 	}
+	// El modo configurado viaja con la tarjeta: la UI lo necesita para no
+	// ofrecer acciones de agente en una unidad que se inventaria por SSH.
+	if r.InventoryMode != "ssh" {
+		t.Fatalf("InventoryMode = %q, esperaba ssh", r.InventoryMode)
+	}
 }

+ 3 - 0
server-go/internal/adapters/live.go

@@ -1689,6 +1689,9 @@ func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
 	// #1917: de dónde salió este inventario y de cuándo es. Se calcula aquí,
 	// donde ya se conoce el agentKind, para no exponer ese detalle interno.
 	r.InventorySource = p.inventorySource()
+	// #1917: el modo configurado viaja con la tarjeta para que la UI no ofrezca
+	// agente en una unidad que se inventaria por SSH.
+	r.InventoryMode = p.cfg.InventoryMode
 	r.InventoryAt = p.polledAt
 	// #1741: la serie de 24 h de una unidad sin throughput nativo (SNMP o
 	// pusher external) sale de sus puertos. Se decide aquí, donde se conoce el

+ 12 - 4
server-go/internal/adapters/types.go

@@ -193,9 +193,13 @@ type Router struct {
 	// InventoryAt (#1917): epoch ms del sondeo que produjo ese inventario,
 	// para que la UI pueda enseñar su antigüedad en vez de dar por bueno un
 	// dato de hace horas.
-	InventoryAt int64  `json:"inventoryAt,omitempty"`
-	Status      string `json:"status"` // "online"|"warn"|"offline"|"unreachable"
-	Health int        `json:"health"`
+	InventoryAt int64 `json:"inventoryAt,omitempty"`
+	// InventoryMode (#1917): "auto" | "agent" | "ssh", tal como esta
+	// configurada la unidad. La UI lo usa para no ofrecer acciones de agente
+	// en una unidad que nunca lo va a tener.
+	InventoryMode string `json:"inventoryMode,omitempty"`
+	Status        string `json:"status"` // "online"|"warn"|"offline"|"unreachable"
+	Health        int    `json:"health"`
 	// LatencyMs (#1384): latencia sondeada de la unidad (ping unidad→gateway
 	// en no-gateway; latencia WAN en el gateway). Null cuando la fuente no la
 	// sondea (agent-only/external/SNMP) - la tabla de enlaces pinta "—".
@@ -1022,7 +1026,11 @@ type RouterConfig struct {
 	Type      string `json:"type"` // "glinet"|"openwrt"|"managed-switch"|"external"
 	IsGateway bool   `json:"is_gateway"`
 	AgentOnly bool   `json:"agent_only"`
-	CreatedAt int64  `json:"created_at"` // epoch ms
+	// InventoryMode (#1917): "auto" (default), "agent" (solo agente, sin SSH)
+	// o "ssh" (nunca esperar agente: inventario por SSH, sin alerta de caida
+	// del agente). Derivado de agent_only cuando la fila es anterior.
+	InventoryMode string `json:"inventory_mode,omitempty"`
+	CreatedAt     int64  `json:"created_at"` // epoch ms
 	// FirmwareTarget: versión objetivo configurada por el admin (issue #241).
 	// "" = sin comprobar (el live no emite aviso de firmware).
 	FirmwareTarget string `json:"firmware_target,omitempty"`

+ 5 - 0
server-go/internal/db/db.go

@@ -662,6 +662,11 @@ func Open(dataDir string, opts ...OpenOption) (*DB, error) {
 	// SPEC-65 D65-5: nombre visible por usuario ("" = usar el username).
 	migrate(sqldb, "users", "display_name", "ALTER TABLE users ADD COLUMN display_name TEXT DEFAULT ''")
 	migrate(sqldb, "routers", "agent_only", "ALTER TABLE routers ADD COLUMN agent_only INTEGER NOT NULL DEFAULT 0")
+	// #1917: modo de inventario por unidad. ""/"auto" = comportamiento de
+	// siempre (agente si lo hay, SSH si no), "agent" = solo agente (el antiguo
+	// agent_only), "ssh" = nunca esperar agente: se inventaria por SSH y no
+	// alerta por la ausencia de un agente que no va a existir.
+	migrate(sqldb, "routers", "inventory_mode", "ALTER TABLE routers ADD COLUMN inventory_mode TEXT NOT NULL DEFAULT ''")
 	// issue #196: bridgeMAC persistido del router (exclusión de "desconocido").
 	migrate(sqldb, "routers", "mac", "ALTER TABLE routers ADD COLUMN mac TEXT")
 	// Ancho de canal de los vecinos (#1087), con el agente nuevo; 0 = viejo.

+ 41 - 6
server-go/internal/httpapi/config.go

@@ -93,12 +93,14 @@ func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
 // routerListItem es la vista HTTP de un router. Omite la comunidad SNMP,
 // que solo necesita el adapter para sondear, y expone si esta configurada.
 type routerListItem struct {
-	ID               string `json:"id"`
-	Name             string `json:"name"`
-	Host             string `json:"host"`
-	Type             string `json:"type"`
-	IsGateway        bool   `json:"is_gateway"`
-	AgentOnly        bool   `json:"agent_only"`
+	ID        string `json:"id"`
+	Name      string `json:"name"`
+	Host      string `json:"host"`
+	Type      string `json:"type"`
+	IsGateway bool   `json:"is_gateway"`
+	AgentOnly bool   `json:"agent_only"`
+	// InventoryMode (#1917): "auto" | "agent" | "ssh".
+	InventoryMode    string `json:"inventory_mode,omitempty"`
 	CreatedAt        int64  `json:"created_at"`
 	FirmwareTarget   string `json:"firmware_target,omitempty"`
 	SnmpEnabled      bool   `json:"snmp_enabled"`
@@ -119,6 +121,7 @@ func newRouterListItem(rt adapters.RouterConfig) routerListItem {
 		Type:             rt.Type,
 		IsGateway:        rt.IsGateway,
 		AgentOnly:        rt.AgentOnly,
+		InventoryMode:    rt.InventoryMode,
 		CreatedAt:        rt.CreatedAt,
 		FirmwareTarget:   rt.FirmwareTarget,
 		SnmpEnabled:      rt.SnmpEnabled,
@@ -148,6 +151,8 @@ type routerInput struct {
 	Type      string  `json:"type"`
 	Gateway   bool    `json:"gateway"`
 	AgentOnly bool    `json:"agent_only"`
+	// InventoryMode (#1917): "auto" | "agent" | "ssh". Manda sobre agent_only.
+	InventoryMode *string `json:"inventory_mode"`
 	// Disabled (issue #1085): pausa la unidad (nil = no tocar).
 	Disabled *bool `json:"disabled"`
 	// FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
@@ -183,6 +188,20 @@ func validateHost(host string) (string, string) {
 	return h, ""
 }
 
+// validateInventoryMode (#1917): "" se acepta y el store lo interpreta como
+// "auto" implicito (compatibilidad con clientes que no mandan el campo).
+func validateInventoryMode(v *string) (string, string) {
+	if v == nil {
+		return "", ""
+	}
+	m := strings.TrimSpace(*v)
+	switch m {
+	case "", "auto", "agent", "ssh":
+		return m, ""
+	}
+	return "", "Invalid enum value. Expected 'auto' | 'agent' | 'ssh'"
+}
+
 // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
 // host, puerto y mensaje de error.
 func validateAdGuardHost(host string) (string, int, string) {
@@ -289,8 +308,14 @@ func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
 		}
 		sshPort = p
 	}
+	invMode, invMsg := validateInventoryMode(in.InventoryMode)
+	if invMsg != "" {
+		writeError(w, http.StatusBadRequest, "invalid_input", invMsg)
+		return
+	}
 	created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
 		Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
+		InventoryMode:  invMode,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
 		SSHPort: sshPort,
@@ -389,6 +414,15 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 	}
 	gw := in.Gateway
 	ao := in.AgentOnly
+	var invMode *string
+	if in.InventoryMode != nil {
+		m, msg := validateInventoryMode(in.InventoryMode)
+		if msg != "" {
+			writeError(w, http.StatusBadRequest, "invalid_input", msg)
+			return
+		}
+		invMode = &m
+	}
 	var firmwareTarget *string
 	if in.FirmwareTarget != nil {
 		v := strings.TrimSpace(*in.FirmwareTarget)
@@ -438,6 +472,7 @@ func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request
 	updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
 		Name: name, Host: host, Type: typ,
 		IsGateway: &gw, AgentOnly: &ao,
+		InventoryMode:  invMode,
 		Disabled:       in.Disabled,
 		FirmwareTarget: firmwareTarget,
 		SnmpEnabled:    in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,

+ 85 - 0
server-go/internal/routerstore/inventory_mode_1917_test.go

@@ -0,0 +1,85 @@
+package routerstore
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/db"
+)
+
+// #1917: el modo de inventario es un ajuste por unidad. "ssh" dice que la
+// unidad se inventaria por SSH y que nunca se espera un agente, "agent" es el
+// antiguo agent_only, y agent_only se deriva del modo para que el codigo que
+// ya lo consultaba siga funcionando.
+func TestInventoryModeRoundTrip(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	cfg, err := AddRouter(d.DB, AddInput{Name: "cpe", Host: "192.168.1.20", Type: "openwrt", InventoryMode: "ssh"})
+	if err != nil {
+		t.Fatalf("add: %v", err)
+	}
+	if cfg.InventoryMode != "ssh" {
+		t.Fatalf("InventoryMode al crear = %q, esperaba ssh", cfg.InventoryMode)
+	}
+	if cfg.AgentOnly {
+		t.Fatal("una unidad en modo ssh no es agent-only: tiene que poder sondearse por SSH")
+	}
+
+	listed := ListRouters(d.DB)
+	if len(listed) != 1 || listed[0].InventoryMode != "ssh" || listed[0].AgentOnly {
+		t.Fatalf("ListRouters devolvio %+v", listed)
+	}
+
+	// Cambiar a "agent" deriva agent_only=1, que es lo que leen el poller y la UI.
+	agent := "agent"
+	upd, ok := UpdateRouter(d.DB, cfg.ID, UpdateInput{InventoryMode: &agent})
+	if !ok {
+		t.Fatal("UpdateRouter devolvio ok=false")
+	}
+	if upd.InventoryMode != "agent" || !upd.AgentOnly {
+		t.Fatalf("tras update a agent: mode=%q agentOnly=%v", upd.InventoryMode, upd.AgentOnly)
+	}
+
+	// Y volver a "auto" lo libera otra vez.
+	auto := "auto"
+	upd, _ = UpdateRouter(d.DB, cfg.ID, UpdateInput{InventoryMode: &auto})
+	if upd.InventoryMode != "auto" || upd.AgentOnly {
+		t.Fatalf("tras update a auto: mode=%q agentOnly=%v", upd.InventoryMode, upd.AgentOnly)
+	}
+
+	// Nil no toca el modo.
+	name := "cpe-renombrado"
+	upd, _ = UpdateRouter(d.DB, cfg.ID, UpdateInput{Name: &name})
+	if upd.InventoryMode != "auto" {
+		t.Fatalf("un update sin modo lo cambio a %q", upd.InventoryMode)
+	}
+}
+
+// #1917: las filas anteriores a la columna nueva llegan con agent_only y sin
+// modo. La lectura lo normaliza para que el frontend no vea un valor vacio.
+func TestInventoryModeLegacyRowsNormalise(t *testing.T) {
+	d, err := db.Open(t.TempDir())
+	if err != nil {
+		t.Fatalf("db: %v", err)
+	}
+	defer d.Close()
+
+	onlyAgent, err := AddRouter(d.DB, AddInput{Name: "nas", Host: "192.168.1.30", Type: "openwrt", AgentOnly: true})
+	if err != nil {
+		t.Fatalf("add agent-only: %v", err)
+	}
+	if onlyAgent.InventoryMode != "agent" || !onlyAgent.AgentOnly {
+		t.Fatalf("agent_only sin modo: mode=%q agentOnly=%v", onlyAgent.InventoryMode, onlyAgent.AgentOnly)
+	}
+
+	plain, err := AddRouter(d.DB, AddInput{Name: "rt2", Host: "192.168.1.31", Type: "openwrt"})
+	if err != nil {
+		t.Fatalf("add plain: %v", err)
+	}
+	if plain.InventoryMode != "auto" || plain.AgentOnly {
+		t.Fatalf("unidad normal sin modo: mode=%q agentOnly=%v", plain.InventoryMode, plain.AgentOnly)
+	}
+}

+ 44 - 5
server-go/internal/routerstore/routerstore.go

@@ -28,7 +28,7 @@ const probeTimeout = 4 * time.Second
 // ListRouters devuelve la tabla routers ordenada is_gateway DESC,
 // created_at ASC, con is_gateway como booleano.
 func ListRouters(db *sql.DB) []adapters.RouterConfig {
-	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, agent_interval, ssh_port, temp_threshold, console_polling, disabled FROM routers ORDER BY is_gateway DESC, created_at ASC")
+	rows, err := db.Query("SELECT id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, agent_interval, ssh_port, temp_threshold, console_polling, disabled, inventory_mode FROM routers ORDER BY is_gateway DESC, created_at ASC")
 	if err != nil {
 		return []adapters.RouterConfig{}
 	}
@@ -37,9 +37,9 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 	for rows.Next() {
 		var r adapters.RouterConfig
 		var gw, ao, snmpEn, snmpPort, snmpInterval, agentInterval, sshPort, consolePoll, disabled int
-		var name, ft, snmpComm sql.NullString
+		var name, ft, snmpComm, mode sql.NullString
 		var tt sql.NullInt64
-		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &agentInterval, &sshPort, &tt, &consolePoll, &disabled); err != nil {
+		if err := rows.Scan(&r.ID, &name, &r.Host, &r.Type, &gw, &ao, &ft, &r.CreatedAt, &snmpEn, &snmpComm, &snmpPort, &snmpInterval, &agentInterval, &sshPort, &tt, &consolePoll, &disabled, &mode); err != nil {
 			continue
 		}
 		// DEFAULT 1 de la migración, pero una fila insertada antes de la
@@ -51,6 +51,15 @@ func ListRouters(db *sql.DB) []adapters.RouterConfig {
 		r.FirmwareTarget = ft.String
 		r.IsGateway = gw == 1
 		r.AgentOnly = ao == 1
+		r.InventoryMode = mode.String
+		if r.InventoryMode == "" {
+			// Filas anteriores a la columna: el modo se deduce del flag viejo.
+			if r.AgentOnly {
+				r.InventoryMode = "agent"
+			} else {
+				r.InventoryMode = "auto"
+			}
+		}
 		r.SnmpEnabled = snmpEn == 1
 		r.SnmpCommunity = snmpComm.String
 		r.SnmpPort = snmpPort
@@ -137,6 +146,9 @@ type AddInput struct {
 	Type      string // default "openwrt"
 	IsGateway bool
 	AgentOnly bool
+	// InventoryMode (#1917): "auto" (default), "agent" (solo agente, sin SSH)
+	// o "ssh" (nunca esperar agente). Manda sobre AgentOnly cuando viene.
+	InventoryMode string
 	// FirmwareTarget: versión objetivo (issue #241). "" = sin comprobar.
 	FirmwareTarget string
 	// SNMP (issue #309): credenciales para sondeo SNMP.
@@ -185,6 +197,19 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 	if in.AgentOnly {
 		ao = 1
 	}
+	// #1917: el modo explicito manda sobre el booleano heredado.
+	mode := in.InventoryMode
+	if mode == "" {
+		if ao == 1 {
+			mode = "agent"
+		} else {
+			mode = "auto"
+		}
+	}
+	ao = 0
+	if mode == "agent" {
+		ao = 1
+	}
 	snmpEn := 0
 	if in.SnmpEnabled {
 		snmpEn = 1
@@ -206,8 +231,8 @@ func AddRouter(db *sql.DB, in AddInput) (adapters.RouterConfig, error) {
 		consolePoll = 0
 	}
 	if _, err := tx.Exec(
-		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, agent_interval, ssh_port, console_polling) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
-		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, in.AgentInterval, sshPort, consolePoll,
+		"INSERT INTO routers (id, name, host, type, is_gateway, agent_only, firmware_target, created_at, snmp_enabled, snmp_community, snmp_port, snmp_poll_interval, agent_interval, ssh_port, console_polling, inventory_mode) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+		id, name, in.Host, in.Type, gw, ao, in.FirmwareTarget, now, snmpEn, in.SnmpCommunity, snmpPort, snmpInterval, in.AgentInterval, sshPort, consolePoll, mode,
 	); err != nil {
 		return adapters.RouterConfig{}, err
 	}
@@ -240,6 +265,9 @@ type UpdateInput struct {
 	Type      *string
 	IsGateway *bool
 	AgentOnly *bool
+	// InventoryMode (#1917): "auto" | "agent" | "ssh". nil = no tocar. Cuando
+	// viene, deriva agent_only (solo "agent" deja la unidad sin SSH).
+	InventoryMode *string
 	// Disabled (issue #1085): nil = no tocar; true = pausar la unidad
 	// (sin sondeo ni alertas, insignia y fuera de desplegables).
 	Disabled *bool
@@ -313,6 +341,17 @@ func UpdateRouter(db *sql.DB, id string, in UpdateInput) (adapters.RouterConfig,
 		sets = append(sets, "agent_only = ?")
 		args = append(args, ao)
 	}
+	// #1917: el modo explicito se escribe despues y deriva agent_only, asi que
+	// gana si el cliente manda los dos campos.
+	if in.InventoryMode != nil {
+		mode := *in.InventoryMode
+		ao := 0
+		if mode == "agent" {
+			ao = 1
+		}
+		sets = append(sets, "inventory_mode = ?", "agent_only = ?")
+		args = append(args, mode, ao)
+	}
 	if in.Disabled != nil {
 		v := 0
 		if *in.Disabled {