Просмотр исходного кода

feat(agents): fleet section with live upgrade progress, queued upgrades and devices/clients rename (#286)

* feat(i18n): rename routers nav label to devices and devices to clients

- ES nav: "Routers" -> "Dispositivos", "Dispositivos" -> "Clientes"
- EN nav: "Routers" -> "Devices", "Devices" -> "Clients"
- labels only: routes /routers and /devices keep their URLs and all
  entity names, code identifiers and other strings are untouched
- page headers follow automatically (they render the nav.* keys)

Part of #284

* feat(agents): move the fleet view into the routers page as a section

- relocate the standalone Agents page content (#245) to the end of
  /routers as a delimited section: registered agents plus agent-only
  routers without agent, status badge, last-seen, rearm, reinstall and
  copy install command (relocation, admin gating preserved)
- add the per-agent upgrade action (AgentUpgradeButton, POST
  /api/agents/{slug}/upgrade) to the section actions
- drop the Agents nav entry; /agents now redirects to /routers so old
  links keep working
- i18n: drop unused nav.agents, add routers.agents.title

Part of #284

* feat(upgrade): live agent upgrade progress reporting

Server:
- new POST /api/agents/{slug}/upgrade-progress endpoint (agent-token
  auth, same trust model as upgrade-result) accepting step reports:
  downloading with percent (clamped 0-100), swapping, restarting
- in-memory upgradeTracker keeps the last step + timestamp per slug
  (TTL 3 min); handleAgentUpgrade and upgrade-all seed "requested"
  when the SSE command is sent; upgrade-result transitions to
  restarting (ok) or failed (error)
- GET /api/agents exposes the active step per agent as `upgrade`
- RequireAuth exempts the new suffix (agent Bearer auth inside)

Agent:
- handleUpgrade reports downloading (0), each 10% boundary of the
  download (progressReader over Content-Length), swapping and
  restarting before the final upgrade-result POST
- reports are fire-and-forget (best-effort, logged on failure)

UI:
- AgentInfo gains `upgrade` (step/pct/error/ts); DataProvider polls
  /api/agents every 2 s while any upgrade is active (30 s at rest)
  and exposes refreshAgents to fast-chain after sending a command
- AgentUpgradeButton shows the live step + elapsed seconds instead of
  a frozen busy state, a green flash when updateAvailable flips
  false, and the agent-reported error on failure; upgrade-all panel
  rows show the same live step text and the timeout now acts as a
  stall detector (no news for 25 s), benefiting legacy agents too
- i18n ES+EN for the step labels

Closes #284

* fix(i18n): align command palette, hero stat and settings labels with the devices/clients rename

* feat(upgrade): queue upgrades for offline agents and add a step timeline

- sseclient: reset the reconnect backoff after an established stream;
  it used to grow to 5 min forever, leaving agents off-hub for most of
  the time after server restarts
- server: upgrade and upgrade-all now QUEUE the command when the agent
  has no SSE stream (202 status "queued") instead of failing with 409;
  the hub flushes queued upgrades on agent (re)connect
- tracker: keeps a per-step history with timestamps exposed as
  upgrade.steps in GET /api/agents, so the UI can show the full
  timeline even when the upgrade takes seconds on a LAN
- UI: fleet section renders the step timeline (times + current step)
  under each upgrading agent; queued state shown on the button

* feat(upgrade): finer live steps, integrity check and consistent queued tracking

- agent: download progress every 5% (all crossed boundaries), new
  "verifying" step that checks the downloaded binary sha256 against the
  X-Checksum-Sha256 header served by the server before swapping
- server: GET /api/agents/{slug}/binary sends X-Checksum-Sha256 of the
  embedded asset (cached digest); upgrade-progress accepts "verifying"
- fleet panel: queued agents are now tracked alongside sent ones with a
  10 min timeout, so the panel stays visible and consistent until every
  agent resolves; queued rows read "esperando conexion" with elapsed
- agents section: step timeline lingers 5 min and shows elapsed seconds
  on the running step, so there is always visible movement

* feat(upgrade): sample fast fleet upgrades and summarize the run

- upgrade-all fires an immediate agents refresh so the provider's fast
  poll (2s) engages right away; without it a LAN fleet upgrade finishes
  entirely between two idle 30s polls and the panel shows no steps
- resolved rows and the timeline summarize steps and total duration,
  keeping fast runs informative

* fix(upgrade): guard indexed access in run summaries for noUncheckedIndexedAccess

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 месяцев назад
Родитель
Сommit
c08004d0ef

+ 113 - 14
agent/cmd/netpulse-agent/upgrade.go

@@ -10,6 +10,8 @@ package main
 
 import (
 	"context"
+	"crypto/sha256"
+	"encoding/hex"
 	"encoding/json"
 	"errors"
 	"fmt"
@@ -50,51 +52,86 @@ func netpulseArch(goarch string) string {
 
 // currentBinPath devuelve la ruta del binario del agente en marcha, para
 // intercambiarlo en el sitio correcto (resuelve la variante --tmp en RAM).
-func currentBinPath() string {
+// Es una var para poder redirigirla en tests.
+var currentBinPath = func() string {
 	if exe, err := os.Executable(); err == nil && exe != "" {
 		return exe
 	}
 	return defaultBinPath
 }
 
+// progressReader cuenta los bytes leídos y dispara onPct al cruzar cada
+// frontera del 5% del total (100% incluido). Los reportes son síncronos:
+// el callback hace el POST del paso desde el hilo de la copia (#284: 5%
+// para que la timeline muestre movimiento incluso en descargas rápidas).
+type progressReader struct {
+	r        io.Reader
+	total    int64
+	done     int64
+	boundary int // última frontera del 5% reportada
+	onPct    func(pct int)
+}
+
+func (p *progressReader) Read(buf []byte) (int, error) {
+	n, err := p.r.Read(buf)
+	p.done += int64(n)
+	if p.total > 0 && p.onPct != nil {
+		// Emitir TODAS las fronteras del 5% cruzadas en esta lectura (una
+		// Read grande puede saltarse varias).
+		for b := int(p.done * 20 / p.total); p.boundary < b; p.boundary++ {
+			p.onPct((p.boundary + 1) * 5)
+		}
+	}
+	return n, err
+}
+
 // downloadBinary descarga el binario desde url (con Bearer token) y lo deja
 // en dest con permisos 0755. Error si la petición no es 200 o el cuerpo está
-// vacío. Extraída a función propia para poder testearla con httptest.
-func downloadBinary(ctx context.Context, hc *http.Client, url, token, dest string) error {
+// vacío. onPct (opcional) recibe el progreso 0-100 de la descarga (#284).
+// Devuelve el valor de la cabecera X-Checksum-Sha256 (vacía si el server no
+// la manda) para que el llamante verifique la integridad.
+// Extraída a función propia para poder testearla con httptest.
+func downloadBinary(ctx context.Context, hc *http.Client, url, token, dest string, onPct func(pct int)) (string, error) {
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 	if err != nil {
-		return err
+		return "", err
 	}
 	req.Header.Set("Authorization", "Bearer "+token)
 
 	res, err := hc.Do(req)
 	if err != nil {
-		return err
+		return "", err
 	}
 	defer res.Body.Close()
 	if res.StatusCode != http.StatusOK {
-		return fmt.Errorf("binario no disponible (HTTP %d)", res.StatusCode)
+		return "", fmt.Errorf("binario no disponible (HTTP %d)", res.StatusCode)
+	}
+	digest := strings.TrimSpace(strings.TrimPrefix(res.Header.Get("X-Checksum-Sha256"), "sha256:"))
+
+	var body io.Reader = res.Body
+	if onPct != nil && res.ContentLength > 0 {
+		body = &progressReader{r: res.Body, total: res.ContentLength, onPct: onPct}
 	}
 
 	f, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
 	if err != nil {
-		return err
+		return "", err
 	}
-	n, copyErr := io.Copy(f, res.Body)
+	n, copyErr := io.Copy(f, body)
 	closeErr := f.Close()
 	if copyErr != nil {
-		return copyErr
+		return "", copyErr
 	}
 	if closeErr != nil {
-		return closeErr
+		return "", closeErr
 	}
 	if n == 0 {
-		return errors.New("binario vacío")
+		return "", errors.New("binario vacío")
 	}
 	if err := os.Chmod(dest, 0o755); err != nil {
-		return err
+		return "", err
 	}
-	return nil
+	return digest, nil
 }
 
 // swapBinary intercambia atómicamente src por dst. Si src y dst están en
@@ -130,6 +167,52 @@ func restartService() error {
 	return nil
 }
 
+// verifySha256 comprueba que el fichero descargado coincide con el digest
+// esperado (hex, sin prefijo). Vacío o distinto → error (#284).
+func verifySha256(path, want string) error {
+	if want == "" {
+		return errors.New("el servidor no publicó digest de integridad")
+	}
+	f, err := os.Open(path)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		return err
+	}
+	got := hex.EncodeToString(h.Sum(nil))
+	if !strings.EqualFold(got, want) {
+		return fmt.Errorf("sha256 no coincide (esperado %s, descargado %s)", want, got)
+	}
+	return nil
+}
+
+// reportUpgradeProgress POSTea un paso intermedio del upgrade al servidor
+// (#284: progreso en vivo). Fire-and-forget: un fallo se loguea y se sigue
+// (el progreso es best-effort; el resultado final sí es fiable).
+func reportUpgradeProgress(cfg config, transport http.RoundTripper, step string, pct int) {
+	m := map[string]any{"slug": cfg.slug, "step": step}
+	if pct > 0 {
+		m["pct"] = pct
+	}
+	body, _ := json.Marshal(m)
+	req, err := http.NewRequest("POST", cfg.server+"/api/agents/"+cfg.slug+"/upgrade-progress", strings.NewReader(string(body)))
+	if err != nil {
+		return
+	}
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+cfg.token)
+	hc := &http.Client{Transport: transport, Timeout: 5 * time.Second}
+	resp, err := hc.Do(req)
+	if err != nil {
+		slog.Warn("[netpulse-agent] upgrade: progress POST falló", "step", step, "err", err)
+		return
+	}
+	resp.Body.Close()
+}
+
 // reportUpgradeResult POSTea el resultado del upgrade al servidor.
 func reportUpgradeResult(cfg config, transport http.RoundTripper, ok bool, errMsg string) {
 	m := map[string]any{"slug": cfg.slug, "ok": ok}
@@ -171,13 +254,28 @@ func handleUpgrade(cfg config, transport http.RoundTripper, data string) {
 	url := cfg.server + "/api/agents/" + cfg.slug + "/binary?arch=" + arch
 	hc := &http.Client{Transport: transport, Timeout: 2 * time.Minute}
 
-	if err := downloadBinary(context.Background(), hc, url, cfg.token, tmpBinPath); err != nil {
+	reportUpgradeProgress(cfg, transport, "downloading", 0)
+	digest, err := downloadBinary(context.Background(), hc, url, cfg.token, tmpBinPath, func(pct int) {
+		reportUpgradeProgress(cfg, transport, "downloading", pct)
+	})
+	if err != nil {
 		slog.Error("[netpulse-agent] upgrade: descarga falló", "err", err)
 		reportUpgradeResult(cfg, transport, false, err.Error())
 		return
 	}
 
+	// Integridad (#284): sha256 contra la cabecera del servidor, ANTES del swap.
+	if digest != "" {
+		reportUpgradeProgress(cfg, transport, "verifying", 0)
+		if err := verifySha256(tmpBinPath, digest); err != nil {
+			slog.Error("[netpulse-agent] upgrade: verificación falló", "err", err)
+			reportUpgradeResult(cfg, transport, false, err.Error())
+			return
+		}
+	}
+
 	dst := currentBinPath()
+	reportUpgradeProgress(cfg, transport, "swapping", 0)
 	if err := swapBinary(tmpBinPath, dst); err != nil {
 		slog.Error("[netpulse-agent] upgrade: swap falló", "err", err, "dst", dst)
 		reportUpgradeResult(cfg, transport, false, err.Error())
@@ -185,6 +283,7 @@ func handleUpgrade(cfg config, transport http.RoundTripper, data string) {
 	}
 
 	slog.Info("[netpulse-agent] upgrade: binario intercambiado, reiniciando servicio", "dst", dst)
+	reportUpgradeProgress(cfg, transport, "restarting", 0)
 	// Reportar ANTES de reiniciar: el reinicio mata este proceso.
 	reportUpgradeResult(cfg, transport, true, "")
 	if err := restartService(); err != nil {

+ 111 - 8
agent/cmd/netpulse-agent/upgrade_test.go

@@ -1,21 +1,24 @@
 // upgrade_test.go — Fase 6.3 (issue #243): tests de la lógica de self-update
 // del agente (mapeo de arquitectura, descarga+verificación y swap atómico).
+// #284: progreso de descarga y pasos reportados al servidor.
 package main
 
 import (
+	"encoding/json"
 	"net/http"
 	"net/http/httptest"
 	"os"
 	"path/filepath"
+	"sync"
 	"testing"
 )
 
 func TestNetpulseArch(t *testing.T) {
 	cases := map[string]string{
-		"amd64":  "amd64",
-		"arm64":  "arm64",
-		"arm":    "armv7", // GOARCH arm (GOARM=7) → sufijo de binario embebido
-		"mips":   "mips",  // desconocido: se conserva
+		"amd64": "amd64",
+		"arm64": "arm64",
+		"arm":   "armv7", // GOARCH arm (GOARM=7) → sufijo de binario embebido
+		"mips":  "mips",  // desconocido: se conserva
 	}
 	for in, want := range cases {
 		if got := netpulseArch(in); got != want {
@@ -51,7 +54,7 @@ func TestDownloadBinaryOK(t *testing.T) {
 
 	dest := filepath.Join(t.TempDir(), "agent.new")
 	hc := &http.Client{}
-	if err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "tok", dest); err != nil {
+	if _, err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "tok", dest, nil); err != nil {
 		t.Fatalf("downloadBinary: %v", err)
 	}
 	data, err := os.ReadFile(dest)
@@ -78,15 +81,15 @@ func TestDownloadBinaryAuth404Empty(t *testing.T) {
 	hc := &http.Client{}
 
 	// Token inválido → 401 → error.
-	if err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "wrong", dest); err == nil {
+	if _, err := downloadBinary(t.Context(), hc, srv.URL+"/binary", "wrong", dest, nil); err == nil {
 		t.Fatal("token inválido: quiero error")
 	}
 	// 404 → error.
-	if err := downloadBinary(t.Context(), hc, srv.URL+"/missing", "tok", dest); err == nil {
+	if _, err := downloadBinary(t.Context(), hc, srv.URL+"/missing", "tok", dest, nil); err == nil {
 		t.Fatal("404: quiero error")
 	}
 	// Cuerpo vacío → error (verificación de no-vacío).
-	if err := downloadBinary(t.Context(), hc, srv.URL+"/empty", "tok", dest); err == nil {
+	if _, err := downloadBinary(t.Context(), hc, srv.URL+"/empty", "tok", dest, nil); err == nil {
 		t.Fatal("body vacío: quiero error")
 	}
 }
@@ -117,3 +120,103 @@ func TestSwapBinary(t *testing.T) {
 		t.Fatal("src debe desaparecer tras el swap")
 	}
 }
+
+// TestDownloadBinaryProgress: el callback de progreso dispara al cruzar cada
+// frontera del 10% del total (100% incluido) y termina en el 100 (#284).
+// El payload es 10x el buffer de io.Copy (32 KiB) para que cada lectura cruce
+// exactamente una frontera; con payloads pequeños una sola Read puede saltar
+// varias fronteras de golpe (comportamiento aceptable en producción).
+func TestDownloadBinaryProgress(t *testing.T) {
+	payload := make([]byte, 320_000)
+	for i := range payload {
+		payload[i] = byte('A' + i%26)
+	}
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+		w.Header().Set("Content-Length", "320000")
+		_, _ = w.Write(payload)
+	}))
+	defer srv.Close()
+
+	var got []int
+	dest := filepath.Join(t.TempDir(), "agent.new")
+	if _, err := downloadBinary(t.Context(), &http.Client{}, srv.URL+"/binary", "tok", dest, func(pct int) {
+		got = append(got, pct)
+	}); err != nil {
+		t.Fatalf("downloadBinary: %v", err)
+	}
+	want := []int{5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100}
+	if len(got) != len(want) {
+		t.Fatalf("progreso: got %v, want %v", got, want)
+	}
+	for i := range want {
+		if got[i] != want[i] {
+			t.Fatalf("progreso[%d]: got %d, want %d (full: %v)", i, got[i], want[i], got)
+		}
+	}
+}
+
+// TestReportUpgradeProgressSteps: handleUpgrade informa los pasos
+// downloading/swapping/restarting al servidor antes del resultado final.
+// El reinicio real no ocurre (no hay init script en el entorno de test),
+// así que el flujo para en restartService y el test observa los POSTs.
+func TestReportUpgradeProgressSteps(t *testing.T) {
+	var mu sync.Mutex
+	var steps []string
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/api/agents/patio/upgrade-progress":
+			var body struct {
+				Step string `json:"step"`
+				Pct  int    `json:"pct"`
+			}
+			_ = json.NewDecoder(r.Body).Decode(&body)
+			mu.Lock()
+			steps = append(steps, body.Step)
+			mu.Unlock()
+			w.WriteHeader(http.StatusOK)
+		case "/api/agents/patio/binary":
+			data := make([]byte, 64)
+			w.Header().Set("Content-Length", "64")
+			_, _ = w.Write(data)
+		case "/api/agents/patio/upgrade-result":
+			w.WriteHeader(http.StatusOK)
+		default:
+			w.WriteHeader(http.StatusNotFound)
+		}
+	}))
+	defer srv.Close()
+
+	// Binario "en marcha" en un temp dir: el swap cae al fallback de copia
+	// (distinto filesystem) y funciona sin permisos de root.
+	exe := filepath.Join(t.TempDir(), "netpulse-agent")
+	if err := os.WriteFile(exe, []byte("viejo"), 0o755); err != nil {
+		t.Fatalf("WriteFile exe: %v", err)
+	}
+	oldPath := currentBinPath
+	currentBinPath = func() string { return exe }
+	defer func() { currentBinPath = oldPath }()
+
+	cfg := config{server: srv.URL, slug: "patio", token: "tok"}
+	handleUpgrade(cfg, nil, "")
+
+	mu.Lock()
+	defer mu.Unlock()
+	if len(steps) < 3 {
+		t.Fatalf("pasos reportados: %v, quiero al menos downloading+swapping+restarting", steps)
+	}
+	if steps[0] != "downloading" {
+		t.Fatalf("primer paso: %q, want downloading", steps[0])
+	}
+	hasSwapping, hasRestarting := false, false
+	for _, s := range steps {
+		if s == "swapping" {
+			hasSwapping = true
+		}
+		if s == "restarting" {
+			hasRestarting = true
+		}
+	}
+	if !hasSwapping || !hasRestarting {
+		t.Fatalf("pasos incompletos: %v", steps)
+	}
+}

+ 11 - 5
agent/internal/sseclient/sseclient.go

@@ -51,15 +51,21 @@ func New(serverURL, slug, token string, hc *http.Client, onEvent func(Event)) *C
 func (c *Client) SetLogger(f func(string, ...any)) { c.logf = f }
 
 // Run conecta al SSE y llama a onEvent por cada comando. Bloquea hasta que
-// ctx se cancele. Se reconecta automáticamente si la conexión cae.
+// ctx se cancele. Se reconecta automáticamente si la conexión cae. El backoff
+// se RESETEA tras una conexión que llegó a establecerse: solo crece mientras
+// los intentos fallan (si no, un agente que sobrevive a varios reinicios del
+// server acaba reintentando cada 5 min para siempre, #284).
 func (c *Client) Run(ctx context.Context) {
 	retry := c.minRetry
 	for {
-		if err := c.connect(ctx); err != nil {
-			if ctx.Err() != nil {
-				return
-			}
+		err := c.connect(ctx)
+		if ctx.Err() != nil {
+			return
+		}
+		if err != nil {
 			c.logf("[netpulse-agent] SSE desconectado (%v), reintentando en %s", err, retry)
+		} else {
+			retry = c.minRetry
 		}
 		select {
 		case <-ctx.Done():

+ 23 - 10
app/public/locales/en/translation.json

@@ -83,7 +83,7 @@
     "empty": "No results.",
     "pages": "Pages",
     "placeholder": "Jump to a page, router or device…",
-    "routers": "Routers"
+    "routers": "Devices"
   },
   "common": {
     "ago": {
@@ -226,7 +226,7 @@
     "weakChip": "{{count}} with weak signal"
   },
   "home": {
-    "devices": "Devices",
+    "devices": "Clients",
     "download": "Download",
     "greetingAfternoon": "Good afternoon",
     "greetingEvening": "Good evening",
@@ -298,7 +298,7 @@
   },
   "nav": {
     "alerts": "Alerts",
-    "devices": "Devices",
+    "devices": "Clients",
     "installApp": "Install app",
     "installFromSettings": "Available from Settings",
     "mainNav": "Main navigation",
@@ -308,7 +308,7 @@
     "reports": "Reports",
     "roaming": "WiFi roaming",
     "routerDetail": "Router detail",
-    "routers": "Routers",
+    "routers": "Devices",
     "settings": "Settings",
     "settingsDesc": "Theme, units and installation",
     "theme": "Theme",
@@ -316,8 +316,7 @@
     "topologyDesc": "Visual network map",
     "collapse": "Collapse menu",
     "expand": "Expand menu",
-    "orchestration": "Orchestration",
-    "agents": "Agents"
+    "orchestration": "Orchestration"
   },
   "roaming": {
     "subtitle": "Roaming and WiFi mesh status",
@@ -541,7 +540,19 @@
       "downBanner": "Agent is down — reinstall it from the router detail",
       "notInstalled": "Agent not installed",
       "notInstalledTip": "This router is configured to run agent-only, but the agent is not installed. Reinstall it from the router detail.",
-      "notInstalledBanner": "Agent not installed — reinstall it from the router detail"
+      "notInstalledBanner": "Agent not installed — reinstall it from the router detail",
+      "stepRequested": "Command sent",
+      "stepDownloading": "Downloading {{pct}}%",
+      "stepSwapping": "Installing binary",
+      "stepRestarting": "Restarting agent",
+      "upgraded": "Upgraded",
+      "stepQueued": "waiting for connection",
+      "upgradeQueued": "Queued",
+      "upgradeQueuedTip": "The agent is offline: the upgrade will be sent when it reconnects",
+      "timeline": "Upgrade",
+      "timelineDone": "completed",
+      "stepVerifying": "Verifying integrity",
+      "timelineSummary": "· {{count}} steps · {{secs}} s"
     },
     "colClients": "Clients",
     "colCpu": "CPU",
@@ -602,8 +613,10 @@
       "copyCmd": "Copy command",
       "copyCmdTip": "Generates the manual install one-liner (fallback for routers without SSH). The token rotates on every generation.",
       "copied": "Command copied",
-      "cmdFail": "Could not generate the command"
-    }
+      "cmdFail": "Could not generate the command",
+      "title": "Agents"
+    },
+    "upgradeUpdatedDetail": "Updated · {{count}} steps · {{secs}} s"
   },
   "reports": {
     "availability": "Availability",
@@ -885,7 +898,7 @@
     "reduceMotion": "Reduce animations",
     "reduceMotionCaption": "Disables pulses, tweens and staggered entrances",
     "routers": {
-      "title": "Routers",
+      "title": "Devices",
       "caption": "The gateway is auto-detected on boot; add the rest manually",
       "empty": "No routers configured yet. The gateway is auto-detected when the server boots; if it's missing, add it here.",
       "host": "IP or hostname",

+ 23 - 10
app/public/locales/es/translation.json

@@ -83,7 +83,7 @@
     "empty": "Sin resultados.",
     "pages": "Páginas",
     "placeholder": "Saltar a una página, router o dispositivo…",
-    "routers": "Routers"
+    "routers": "Dispositivos"
   },
   "common": {
     "ago": {
@@ -226,7 +226,7 @@
     "weakChip": "{{count}} con señal débil"
   },
   "home": {
-    "devices": "Dispositivos",
+    "devices": "Clientes",
     "download": "Descarga",
     "greetingAfternoon": "Buenas tardes",
     "greetingEvening": "Buenas noches",
@@ -298,7 +298,7 @@
   },
   "nav": {
     "alerts": "Alertas",
-    "devices": "Dispositivos",
+    "devices": "Clientes",
     "installApp": "Instalar app",
     "installFromSettings": "Disponible desde Ajustes",
     "mainNav": "Navegación principal",
@@ -308,7 +308,7 @@
     "reports": "Informes",
     "roaming": "Roaming WiFi",
     "routerDetail": "Detalle de router",
-    "routers": "Routers",
+    "routers": "Dispositivos",
     "settings": "Ajustes",
     "settingsDesc": "Tema, unidades e instalación",
     "theme": "Tema",
@@ -316,8 +316,7 @@
     "topologyDesc": "Mapa visual de la red",
     "collapse": "Plegar menú",
     "expand": "Desplegar menú",
-    "orchestration": "Orquestación",
-    "agents": "Agentes"
+    "orchestration": "Orquestación"
   },
   "roaming": {
     "subtitle": "Estado del roaming y la malla WiFi",
@@ -541,7 +540,19 @@
       "downBanner": "Agente caído — reinstálalo desde el detalle",
       "notInstalled": "Agente no instalado",
       "notInstalledTip": "El router está configurado para funcionar solo con agente, pero el agente no está instalado. Reinstálalo desde el detalle.",
-      "notInstalledBanner": "Agente no instalado — reinstálalo desde el detalle"
+      "notInstalledBanner": "Agente no instalado — reinstálalo desde el detalle",
+      "stepRequested": "Comando enviado",
+      "stepDownloading": "Descargando {{pct}} %",
+      "stepSwapping": "Instalando binario",
+      "stepRestarting": "Reiniciando agente",
+      "upgraded": "Actualizado",
+      "stepQueued": "esperando conexión",
+      "upgradeQueued": "En cola",
+      "upgradeQueuedTip": "El agente no está conectado: la actualización se enviará cuando vuelva a conectar",
+      "timeline": "Actualización",
+      "timelineDone": "completado",
+      "stepVerifying": "Comprobando integridad",
+      "timelineSummary": "· {{count}} pasos · {{secs}} s"
     },
     "colClients": "Clientes",
     "colCpu": "CPU",
@@ -602,8 +613,10 @@
       "copyCmd": "Copiar comando",
       "copyCmdTip": "Genera el one-liner de instalación manual (fallback para routers sin SSH). El token se rota en cada generación.",
       "copied": "Comando copiado",
-      "cmdFail": "No se pudo generar el comando"
-    }
+      "cmdFail": "No se pudo generar el comando",
+      "title": "Agentes"
+    },
+    "upgradeUpdatedDetail": "Actualizado · {{count}} pasos · {{secs}} s"
   },
   "reports": {
     "availability": "Disponibilidad",
@@ -885,7 +898,7 @@
     "reduceMotion": "Reducir animaciones",
     "reduceMotionCaption": "Desactiva pulsos, tweens y entradas escalonadas",
     "routers": {
-      "title": "Routers",
+      "title": "Dispositivos",
       "caption": "La puerta de enlace se autodetecta en el arranque; añade el resto a mano",
       "empty": "Sin routers configurados todavía. La puerta de enlace se autodetecta al arrancar el servidor; si no aparece, añádela aquí.",
       "host": "IP o hostname",

+ 4 - 2
app/src/App.tsx

@@ -1,4 +1,5 @@
 import { Route, Routes } from 'react-router'
+import { Navigate } from 'react-router'
 import { AuthGate } from '@/components/AuthGate'
 import Layout from '@/components/Layout'
 import { DataProvider } from '@/data/DataProvider'
@@ -6,7 +7,6 @@ import Home from '@/pages/Home'
 import Login from '@/pages/Login'
 import Routers from '@/pages/Routers'
 import RouterDetail from '@/pages/RouterDetail'
-import Agents from '@/pages/Agents'
 import Devices from '@/pages/Devices'
 import Topology from '@/pages/Topology'
 import Alerts from '@/pages/Alerts'
@@ -37,7 +37,9 @@ export default function App() {
         <Route index element={<Home />} />
         <Route path="routers" element={<Routers />} />
         <Route path="routers/:id" element={<RouterDetail />} />
-        <Route path="agents" element={<Agents />} />
+        {/* La vista de agentes vive ahora como sección de /routers (#284):
+         * el route legacy redirige para no romper enlaces antiguos. */}
+        <Route path="agents" element={<Navigate to="/routers" replace />} />
         <Route path="devices" element={<Devices />} />
         <Route path="topology" element={<Topology />} />
         <Route path="alerts" element={<Alerts />} />

+ 0 - 3
app/src/components/Layout.tsx

@@ -9,7 +9,6 @@ import {
   ArrowLeft,
   BarChart3,
   Bell,
-  Bot,
   Bug,
   ChevronsLeft,
   ChevronsRight,
@@ -54,7 +53,6 @@ interface NavItem {
 const NAV_ITEMS: NavItem[] = [
   { to: '/', labelKey: 'nav.overview', icon: LayoutDashboard, end: true },
   { to: '/routers', labelKey: 'nav.routers', icon: RouterIcon },
-  { to: '/agents', labelKey: 'nav.agents', icon: Bot },
   { to: '/devices', labelKey: 'nav.devices', icon: MonitorSmartphone },
   { to: '/topology', labelKey: 'nav.topology', icon: Waypoints },
   { to: '/roaming', labelKey: 'nav.roaming', icon: Wifi },
@@ -74,7 +72,6 @@ const PAGE_TITLE_KEYS: [RegExp, string][] = [
   [/^\/$/, 'nav.overview'],
   [/^\/routers\/[^/]+/, 'nav.routerDetail'],
   [/^\/routers/, 'nav.routers'],
-  [/^\/agents/, 'nav.agents'],
   [/^\/devices/, 'nav.devices'],
   [/^\/topology/, 'nav.topology'],
   [/^\/roaming/, 'nav.roaming'],

+ 101 - 13
app/src/components/routers/AgentUpgradeButton.tsx

@@ -1,9 +1,9 @@
-import { useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Loader2 } from 'lucide-react'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
-import type { AgentInfo } from '@/data/types'
+import type { AgentInfo, AgentUpgradeProgress } from '@/data/types'
 import { cn } from '@/lib/utils'
 
 interface AgentUpgradeButtonProps {
@@ -11,7 +11,46 @@ interface AgentUpgradeButtonProps {
   className?: string
 }
 
-type UpgradeState = 'idle' | 'busy' | 'sent' | 'not_connected' | 'fail'
+type UpgradeState = 'idle' | 'busy' | 'sent' | 'queued' | 'not_connected' | 'fail'
+
+type StepT = (key: string, opts?: Record<string, unknown>) => string
+
+/** Ventana que considera "vivo" un reporte de progreso (segundos, #284). */
+export const UPGRADE_LIVE_WINDOW_S = 120
+
+/** Upgrade en marcha: paso no terminal con reporte fresco (#284). */
+export function activeUpgrade(agent: AgentInfo | undefined, nowSec: number): AgentUpgradeProgress | undefined {
+  const u = agent?.upgrade
+  if (!u || u.step === 'failed') return undefined
+  if (u.step === 'queued') return u
+  if (nowSec - u.ts > UPGRADE_LIVE_WINDOW_S) return undefined
+  return u
+}
+
+/** Texto del paso para el botón y el panel de flota (#284). */
+export function upgradeStepText(u: { step: AgentUpgradeProgress['step']; pct?: number }, t: StepT): string {
+  switch (u.step) {
+    case 'requested':
+      return t('routers.agent.stepRequested')
+    case 'downloading':
+      return t('routers.agent.stepDownloading', { pct: u.pct ?? 0 })
+    case 'verifying':
+      return t('routers.agent.stepVerifying')
+    case 'swapping':
+      return t('routers.agent.stepSwapping')
+    case 'restarting':
+      return t('routers.agent.stepRestarting')
+    case 'queued':
+      return t('routers.agent.stepQueued')
+    default:
+      return t('routers.agent.upgrading')
+  }
+}
+
+/** Sufijo de segundos transcurridos desde el último reporte. */
+export function upgradeElapsed(u: AgentUpgradeProgress, nowSec: number): string {
+  return `${Math.max(0, nowSec - u.ts)}s`
+}
 
 /**
  * Botón «Actualizar agente» (Fase 6.3, issue #243): solo aparece si el agente
@@ -23,29 +62,77 @@ type UpgradeState = 'idle' | 'busy' | 'sent' | 'not_connected' | 'fail'
  *   not_connected → 409, el agente no está conectado por SSE
  *   fail          → petición fallida (red, 4xx/5xx)
  * El estado sent/not_connected/fail dura 6 s y vuelve a idle.
+ *
+ * #284: mientras el agente reporta pasos (downloading con porcentaje,
+ * swapping, restarting) el botón muestra el paso en vivo y los segundos
+ * transcurridos, en vez de quedarse congelado en "Enviando". El flash
+ * final "Actualizado" aparece cuando updateAvailable pasa a false.
  */
 export function AgentUpgradeButton({ agent, className }: AgentUpgradeButtonProps) {
   const { t } = useTranslation()
-  const { upgradeAgent } = useNetPulse()
+  const { upgradeAgent, refreshAgents } = useNetPulse()
   const auth = useAuth()
   const [state, setState] = useState<UpgradeState>('idle')
+  const [nowSec, setNowSec] = useState(() => Math.floor(Date.now() / 1000))
+  const [justDone, setJustDone] = useState(false)
+  const wasAvailable = useRef(false)
+
+  const live = agent ? activeUpgrade(agent, nowSec) : undefined
+  const liveActive = live !== undefined
+  const liveFailed = agent?.upgrade?.step === 'failed' && nowSec - (agent.upgrade?.ts ?? 0) < 60
+
+  // Tick de 1 s mientras hay progreso en vivo (para los segundos transcurridos).
+  useEffect(() => {
+    if (!liveActive) return
+    const timer = window.setInterval(() => setNowSec(Math.floor(Date.now() / 1000)), 1000)
+    return () => window.clearInterval(timer)
+  }, [liveActive])
+
+  // Flash final: updateAvailable true → false significa binario nuevo en
+  // marcha. El effect es idempotente (solo actúa en la transición, guardado
+  // por wasAvailable) para tolerar los re-renders del poll de agentes.
+  useEffect(() => {
+    if (!agent || agent.updateAvailable) {
+      if (agent?.updateAvailable) wasAvailable.current = true
+      return
+    }
+    if (!wasAvailable.current) return
+    wasAvailable.current = false
+    setState('idle')
+    setJustDone(true)
+  }, [agent, agent?.updateAvailable])
+
+  // El timer del flash vive en su propio effect (clave: el booleano), para
+  // que los re-renders del poll no lo cancelen a medias.
+  useEffect(() => {
+    if (!justDone) return
+    const timer = window.setTimeout(() => setJustDone(false), 4000)
+    return () => window.clearTimeout(timer)
+  }, [justDone])
 
-  if (!agent || !agent.updateAvailable) return null
   if (auth?.role !== 'admin') return null
+  if (!agent) return null
+  if (!agent.updateAvailable && !justDone) return null
 
   const label =
     state === 'busy' ? t('routers.agent.upgrading')
+    : live ? `${upgradeStepText(live, t)} · ${upgradeElapsed(live, nowSec)}`
+    : justDone ? t('routers.agent.upgraded')
     : state === 'sent' ? t('routers.agent.upgradeSent')
+    : state === 'queued' ? t('routers.agent.upgradeQueued')
     : state === 'not_connected' ? t('routers.agent.upgradeNotConnected')
-    : state === 'fail' ? t('routers.agent.upgradeFail')
+    : state === 'fail' || liveFailed ? t('routers.agent.upgradeFail')
     : t('routers.agent.upgrade')
 
   const onClick = async () => {
-    if (state === 'busy') return
+    if (state === 'busy' || live) return
     setState('busy')
     const res = await upgradeAgent(agent.slug)
-    const next: UpgradeState = res === 'sent' ? 'sent' : res === 'not_connected' ? 'not_connected' : 'fail'
+    const next: UpgradeState =
+      res === 'sent' ? 'sent' : res === 'queued' ? 'queued' : res === 'not_connected' ? 'not_connected' : 'fail'
     setState(next)
+    // Traer el paso "requested"/"queued" cuanto antes: encadena el sondeo rápido.
+    if (next === 'sent' || next === 'queued') void refreshAgents()
     window.setTimeout(() => setState('idle'), 6000)
   }
 
@@ -53,17 +140,18 @@ export function AgentUpgradeButton({ agent, className }: AgentUpgradeButtonProps
     <button
       type="button"
       onClick={onClick}
-      disabled={state === 'busy'}
-      title={t('routers.agent.upgradeTip', { version: agent.version ?? '?' })}
+      disabled={state === 'busy' || live !== undefined}
+      title={liveFailed ? agent.upgrade?.error || t('routers.agent.upgradeFail') : live?.step === 'queued' ? t('routers.agent.upgradeQueuedTip') : t('routers.agent.upgradeTip', { version: agent.version ?? '?' })}
       className={cn(
         'inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[11px] font-semibold transition-opacity hover:opacity-90 disabled:opacity-50',
-        state === 'sent' ? 'bg-ok text-canvas'
-        : state === 'fail' || state === 'not_connected' ? 'bg-danger text-canvas'
+        state === 'sent' || justDone ? 'bg-ok text-canvas'
+        : state === 'queued' ? 'bg-accent-soft text-accent'
+        : state === 'fail' || state === 'not_connected' || liveFailed ? 'bg-danger text-canvas'
         : 'bg-accent text-canvas',
         className,
       )}
     >
-      {state === 'busy' && <Loader2 className="h-3 w-3 animate-spin" />}
+      {(state === 'busy' || live !== undefined) && <Loader2 className="h-3 w-3 animate-spin" />}
       {label}
     </button>
   )

+ 115 - 61
app/src/pages/Agents.tsx → app/src/components/routers/AgentsSection.tsx

@@ -1,23 +1,25 @@
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { Link } from 'react-router'
-import { Check, Clipboard, RotateCcw } from 'lucide-react'
-import { motion, useReducedMotion } from 'framer-motion'
+import { Check, Clipboard, Clock, Loader2, RotateCcw } from 'lucide-react'
+import { motion } from 'framer-motion'
 import { useNetPulse } from '@/data/DataProvider'
 import { useAuth } from '@/data/AuthContext'
 import type { AgentInfo, Router } from '@/data/types'
 import { relTimeFromTs } from '@/i18n'
 import { AgentBadge } from '@/components/routers/AgentBadge'
 import { AgentRearmButton } from '@/components/routers/AgentRearmButton'
+import { AgentUpgradeButton, activeUpgrade, upgradeStepText } from '@/components/routers/AgentUpgradeButton'
 import { cn } from '@/lib/utils'
 
 /**
- * Página `/agents` — vista de agentes nativos (issue #245: recuperar un
- * agente caído desde la app). Lista cada agente registrado con su estado
- * (fresco / caído-stale / no instalado) y last-seen, y para admin expone las
- * acciones de recuperación:
+ * Sección de agentes nativos (issue #245, reubicada en /routers por #284):
+ * lista cada agente registrado con su estado (fresco / caído-stale / no
+ * instalado) y last-seen, y para admin expone las acciones de recuperación:
+ *   - Actualizar (POST /api/agents/{slug}/upgrade, #243): self-update del
+ *     agente descargando el binario embebido, con progreso en vivo.
  *   - Rearmar (canal rearm existente): preferente cuando el proceso vive pero
- *     no reporta (heartbeat stale) — NO reinstala en seco.
+ *     no reporta (heartbeat stale) - NO reinstala en seco.
  *   - Reinstalar (POST /api/agents/{slug}/reinstall, #246): despliega el
  *     agente vía SSH desde el server, con estados de progreso.
  *   - Copiar comando de instalación: one-liner manual como fallback para
@@ -56,6 +58,15 @@ async function copyText(text: string): Promise<boolean> {
 type ReinstallState = 'idle' | 'busy' | 'done' | 'fail'
 type CopyState = 'idle' | 'busy' | 'done' | 'fail'
 
+/** Hora HH:MM:SS local desde unix segundos (timeline de upgrade, #284). */
+function hhmmss(ts: number): string {
+  return new Date(ts * 1000).toLocaleTimeString(undefined, {
+    hour: '2-digit',
+    minute: '2-digit',
+    second: '2-digit',
+  })
+}
+
 /** Fila de un agente con sus acciones de recuperación (estado local). */
 function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undefined }) {
   const { t } = useTranslation()
@@ -64,6 +75,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
   const [reinstallState, setReinstallState] = useState<ReinstallState>('idle')
   const [reinstallMsg, setReinstallMsg] = useState('')
   const [copyState, setCopyState] = useState<CopyState>('idle')
+  const [nowSec, setNowSec] = useState(() => Math.floor(Date.now() / 1000))
 
   const isOpenWrt = isOpenWrtType(router?.type)
   const isStale = agent !== undefined && !agent.fresh
@@ -72,6 +84,22 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
 
   const slug = agent?.slug ?? router?.id ?? ''
   const lastSeen = agent?.lastSeen ? relTimeFromTs(agent.lastSeen) ?? t('routers.agents.never') : t('routers.agents.never')
+  const live = agent ? activeUpgrade(agent, nowSec) : undefined
+
+  // Tick de 1 s mientras hay upgrade en marcha (elapsed de la timeline).
+  const ticking = live !== undefined
+  useEffect(() => {
+    if (!ticking) return
+    const timer = window.setInterval(() => setNowSec(Math.floor(Date.now() / 1000)), 1000)
+    return () => window.clearInterval(timer)
+  }, [ticking])
+
+  // Timeline visible mientras el upgrade está en marcha o hasta 5 min después
+  // del último paso: el recorrido completo queda visible aunque vaya rápido
+  // y sobrevive al parpadeo del poll de agentes (#284).
+  const up = agent?.upgrade
+  const showTimeline =
+    up !== undefined && (live !== undefined || (up.step !== 'queued' && nowSec - up.ts < 300))
 
   const reinstall = async () => {
     if (reinstallState === 'busy') return
@@ -99,6 +127,7 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
   }
 
   return (
+    <>
     <motion.tr
       initial={{ opacity: 0, y: 6 }}
       animate={{ opacity: 1, y: 0 }}
@@ -127,10 +156,12 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
         <span className="font-mono text-caption text-text-secondary">{lastSeen}</span>
       </td>
       <td className="py-3 pr-3">
-        <span className="font-mono text-caption text-text-secondary">{agent?.version ? `v${agent.version}` : '—'}</span>
+        <span className="font-mono text-caption text-text-secondary">{agent?.version ? `v${agent.version}` : '-'}</span>
       </td>
       <td className="py-3">
         <div className="flex flex-wrap items-center gap-2">
+          {/* Actualizar: self-update del agente con progreso en vivo (#243) */}
+          <AgentUpgradeButton agent={agent} className="h-8" />
           {/* Rearm: canal preferente para heartbeat stale (proceso vivo) */}
           {agent && <AgentRearmButton agent={agent} />}
           {canRecover && (
@@ -192,13 +223,57 @@ function AgentRow({ agent, router }: { agent?: AgentInfo; router: Router | undef
         )}
       </td>
     </motion.tr>
+    {showTimeline && up && (
+      <motion.tr
+        initial={{ opacity: 0 }}
+        animate={{ opacity: 1 }}
+        transition={{ duration: 0.2 }}
+        className="border-b border-border/60 last:border-0"
+      >
+        <td colSpan={5} className="pb-3">
+          <div className="flex flex-wrap items-center gap-x-4 gap-y-1.5 rounded-xl bg-surface px-3.5 py-2.5">
+            <span className="inline-flex items-center gap-1.5 text-label font-medium uppercase text-text-muted">
+              <Clock className="h-3.5 w-3.5" strokeWidth={1.75} aria-hidden="true" />
+              {t('routers.agent.timeline')}
+              {(() => {
+                const h = up.steps ?? []
+                const first = h[0]
+                const last = h[h.length - 1]
+                if (!first || !last || h.length < 2) return null
+                const dur = Math.max(1, last.ts - first.ts)
+                return <span className="font-mono normal-case">{t('routers.agent.timelineSummary', { count: h.length, secs: dur })}</span>
+              })()}
+            </span>
+            {(up.steps ?? []).map((s, i) => {
+              const isCurrent = i === (up.steps?.length ?? 0) - 1 && live !== undefined
+              return (
+                <span key={`${s.step}-${s.ts}`} className="inline-flex items-center gap-1.5 text-caption">
+                  {isCurrent ? (
+                    <Loader2 className="h-3 w-3 animate-spin text-accent" strokeWidth={2} aria-hidden="true" />
+                  ) : (
+                    <Check className="h-3 w-3 text-ok" strokeWidth={2} aria-hidden="true" />
+                  )}
+                  <span className={isCurrent ? 'font-medium text-text-primary' : 'text-text-secondary'}>
+                    {upgradeStepText(s, t)}
+                    {isCurrent && s.step !== 'queued' ? ` · ${Math.max(0, nowSec - s.ts)}s` : ''}
+                  </span>
+                  <span className="font-mono text-text-muted">{hhmmss(s.ts)}</span>
+                </span>
+              )
+            })}
+            {live === undefined && <span className="text-caption text-ok">{t('routers.agent.timelineDone')}</span>}
+          </div>
+        </td>
+      </motion.tr>
+    )}
+    </>
   )
 }
 
-/** Vista de agentes (issue #245): registrados + routers agent-only sin agente. */
-export default function Agents() {
+/** Sección de flota de agentes (issue #245): registrados + routers agent-only
+ * sin agente. Vive al final de la página /routers (#284). */
+export function AgentsSection() {
   const { t } = useTranslation()
-  const reduce = useReducedMotion()
   const { agents, routers } = useNetPulse()
 
   // Filas: agentes registrados (por slug) + routers agent-only sin agente.
@@ -221,54 +296,33 @@ export default function Agents() {
   const total = rows.length
 
   return (
-    <div className="space-y-4 md:space-y-5">
-      <header>
-        <motion.nav
-          initial={reduce ? false : { opacity: 0, y: 12 }}
-          animate={{ opacity: 1, y: 0 }}
-          transition={{ duration: 0.25, ease: 'easeOut' }}
-          aria-label={t('common.breadcrumb')}
-          className="font-mono text-caption text-text-muted"
-        >
-          <Link to="/" className="transition-colors hover:text-accent">{t('common.home')}</Link>
-          <span className="mx-1.5">/</span>
-          <span className="text-text-secondary">{t('nav.agents')}</span>
-        </motion.nav>
-        <motion.div
-          initial={reduce ? false : { opacity: 0, y: 12 }}
-          animate={{ opacity: 1, y: 0 }}
-          transition={{ duration: 0.25, ease: 'easeOut', delay: 0.06 }}
-          className="mt-1.5"
-        >
-          <h1 className="font-display text-h1 text-text-primary">{t('nav.agents')}</h1>
-          <p className="text-caption text-text-muted">{t('routers.agents.subtitle', { total, down })}</p>
-        </motion.div>
-      </header>
-
-      <section className="rounded-2xl border border-border bg-surface p-5 md:p-6">
-        {rows.length === 0 ? (
-          <p className="py-8 text-center text-sm text-text-secondary">{t('routers.agents.empty')}</p>
-        ) : (
-          <div className="overflow-x-auto">
-            <table className="w-full text-left text-sm">
-              <thead>
-                <tr className="border-b border-border">
-                  <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colDevice')}</th>
-                  <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colStatus')}</th>
-                  <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colLastSeen')}</th>
-                  <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colVersion')}</th>
-                  <th className="pb-2.5 text-label font-medium uppercase text-text-muted">{t('routers.agents.colActions')}</th>
-                </tr>
-              </thead>
-              <tbody>
-                {rows.map(({ agent, router }) => (
-                  <AgentRow key={agent?.slug ?? router?.id ?? ''} agent={agent} router={router} />
-                ))}
-              </tbody>
-            </table>
-          </div>
-        )}
-      </section>
-    </div>
+    <section className="rounded-2xl border border-border bg-surface p-5 md:p-6" aria-labelledby="agents-section-title">
+      <div className="mb-4">
+        <h2 id="agents-section-title" className="font-display text-h2 text-text-primary">{t('routers.agents.title')}</h2>
+        <p className="text-caption text-text-muted">{t('routers.agents.subtitle', { total, down })}</p>
+      </div>
+      {rows.length === 0 ? (
+        <p className="py-8 text-center text-sm text-text-secondary">{t('routers.agents.empty')}</p>
+      ) : (
+        <div className="overflow-x-auto">
+          <table className="w-full text-left text-sm">
+            <thead>
+              <tr className="border-b border-border">
+                <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colDevice')}</th>
+                <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colStatus')}</th>
+                <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colLastSeen')}</th>
+                <th className="pb-2.5 pr-3 text-label font-medium uppercase text-text-muted">{t('routers.agents.colVersion')}</th>
+                <th className="pb-2.5 text-label font-medium uppercase text-text-muted">{t('routers.agents.colActions')}</th>
+              </tr>
+            </thead>
+            <tbody>
+              {rows.map(({ agent, router }) => (
+                <AgentRow key={agent?.slug ?? router?.id ?? ''} agent={agent} router={router} />
+              ))}
+            </tbody>
+          </table>
+        </div>
+      )}
+    </section>
   )
 }

+ 42 - 7
app/src/data/DataProvider.tsx

@@ -114,6 +114,9 @@ export interface NetPulseApi extends NetPulseData {
    * honesto — no se mockean agentes). Se refresca cada ~30 s en live.
    */
   agents: AgentInfo[]
+  /** Re-pide `/api/agents` cuanto antes (live; #284: encadena el sondeo
+   * rápido si hay upgrades en marcha). En demo es no-op. */
+  refreshAgents: () => Promise<void>
   /** true = sin backend: dataset local del mockup con tick simulado */
   isDemo: boolean
   /** Re-pide `/api/overview` (live); en demo es no-op */
@@ -153,7 +156,7 @@ export interface NetPulseApi extends NetPulseData {
    * que se actualice con el binario embebido del servidor. Resuelve el estado
    * del envío; null si la petición falló (demo siempre null).
    */
-  upgradeAgent: (slug: string) => Promise<'sent' | 'not_connected' | null>
+  upgradeAgent: (slug: string) => Promise<'sent' | 'queued' | 'not_connected' | null>
   /**
    * #251: POST /api/agents/upgrade-all — envía el upgrade a todos los agentes
    * con versión desactualizada. Devuelve el resumen por slug; null si falló.
@@ -394,6 +397,11 @@ const POLL_MS = 15000
 const DEMO_TICK_MS = 3000
 // Refresco del estado de agentes (fresh cambia solo en el backend, TTL ~90 s)
 const AGENTS_POLL_MS = 30000
+// #284: mientras algún agente tiene un self-update en marcha se sondea cada
+// 2 s para que la UI muestre el paso en vivo (downloading/swapping/...).
+const AGENTS_FAST_POLL_MS = 2000
+// Ventana que considera "activo" un upgrade reportado (segundos).
+const UPGRADE_ACTIVE_WINDOW_S = 120
 
 // ---------------------------------------------------------------------------
 // Provider
@@ -422,6 +430,10 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
   const modeRef = useRef<'boot' | 'live' | 'demo'>('boot')
   // Se sincroniza en applyAlertsConfig y en el fetch del boot (nunca en render)
   const configRef = useRef(alertsConfig)
+  // fetchAgents vive dentro del effect de boot; este ref lo expone como
+  // refreshAgents estable (#284: forzar una tanda tras enviar un upgrade).
+  const refreshAgentsRef = useRef<() => Promise<void>>(async () => {})
+  const refreshAgents = useCallback(() => refreshAgentsRef.current(), [])
 
   const applyOverview = useCallback((o: OverviewBundle) => {
     // SPEC-65 D65-4/D65-9 B3: view-model versionado. Un `vm` mayor que el
@@ -572,7 +584,9 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
     }
 
     // Agentes nativos (Fase 3): no forman parte del overview; se sondean
-    // aparte cada ~30 s. Sin agentes registrados → [] (sin badges).
+    // aparte cada ~30 s (2 s mientras hay upgrades en marcha, #284). Sin
+    // agentes registrados → [] (sin badges).
+    let upgradesActive = false
     const fetchAgents = async (): Promise<void> => {
       try {
         const res = await fetchJson('/api/agents')
@@ -580,10 +594,27 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
         const json = (await res.json()) as { agents?: AgentInfo[] } | AgentInfo[]
         const list = Array.isArray(json) ? json : (json.agents ?? [])
         if (!disposed) setAgents(list)
+        const nowSec = Math.floor(Date.now() / 1000)
+        upgradesActive = list.some(
+          (a) =>
+            a.upgrade &&
+            a.upgrade.step !== 'failed' &&
+            nowSec - a.upgrade.ts < UPGRADE_ACTIVE_WINDOW_S,
+        )
       } catch {
         /* sin agentes: se mantiene el último estado conocido */
       }
     }
+    refreshAgentsRef.current = fetchAgents
+
+    // Auto-programación del sondeo: rápido con upgrades activos, lento en
+    // reposo (#284). El delay se decide tras cada tanda con la respuesta.
+    const scheduleAgentsPoll = (delay: number) => {
+      agentsPollId = window.setTimeout(async () => {
+        await fetchAgents()
+        if (!disposed) scheduleAgentsPoll(upgradesActive ? AGENTS_FAST_POLL_MS : AGENTS_POLL_MS)
+      }, delay)
+    }
 
     const startLive = async () => {
       modeRef.current = 'live'
@@ -599,7 +630,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
         setConnectionStatus('reconnecting')
         pollId = window.setInterval(() => void fetchOverview(), POLL_MS)
       }
-      agentsPollId = window.setInterval(() => void fetchAgents(), AGENTS_POLL_MS)
+      scheduleAgentsPoll(AGENTS_POLL_MS)
       startSse()
     }
 
@@ -632,7 +663,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       stopPolling()
       window.clearTimeout(reconnectId)
       window.clearInterval(tickId)
-      window.clearInterval(agentsPollId)
+      window.clearTimeout(agentsPollId)
     }
   }, [applyOverview])
 
@@ -802,7 +833,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
    * red/4xx-5xx/demo. Tras enviarlo, el agente se reinicia solo; el próximo
    * poll de agentes (~30 s) refleja la versión nueva y updateAvailable=false.
    */
-  const upgradeAgent = useCallback(async (slug: string): Promise<'sent' | 'not_connected' | null> => {
+  const upgradeAgent = useCallback(async (slug: string): Promise<'sent' | 'queued' | 'not_connected' | null> => {
     if (modeRef.current !== 'live') return null
     try {
       const res = await fetch(`/api/agents/${encodeURIComponent(slug)}/upgrade`, {
@@ -812,7 +843,10 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       if (res.status === 401) redirectLogin()
       if (res.status === 409) return 'not_connected'
       if (!res.ok) return null
-      return 'sent'
+      // 202: el comando salió por SSE o quedó encolado hasta que el
+      // agente vuelva a conectar (#284).
+      const body = (await res.json().catch(() => null)) as { status?: string } | null
+      return body?.status === 'queued' ? 'queued' : 'sent'
     } catch {
       return null
     }
@@ -960,6 +994,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       ...bundle,
       connectionStatus,
       agents,
+      refreshAgents,
       isDemo,
       refresh,
       lastSnapshotAt,
@@ -977,7 +1012,7 @@ export function DataProvider({ children }: { children: React.ReactNode }) {
       reinstallAgent,
       createAgentInstall,
     }),
-    [bundle, connectionStatus, agents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, createAgentInstall],
+    [bundle, connectionStatus, agents, refreshAgents, isDemo, refresh, lastSnapshotAt, requestServerRefresh, getRouterDetail, getDevices, getAlerts, alertsConfig, setAlertConfig, markAlertsRead, markAllAlertsRead, rearmAgent, upgradeAgent, upgradeAllAgents, reinstallAgent, createAgentInstall],
   )
 
   return <NetPulseContext.Provider value={value}>{children}</NetPulseContext.Provider>

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

@@ -382,6 +382,26 @@ export interface AgentInfo {
    * (Fase 6.3, issue #243): hay upgrade disponible vía POST /api/agents/{slug}/upgrade.
    */
   updateAvailable?: boolean
+  /**
+   * Progreso en vivo del self-update (#284): último paso reportado por el
+   * agente (o sembrado por el server al enviar el comando). Ausente si no
+   * hay actividad reciente.
+   */
+  upgrade?: AgentUpgradeProgress
+}
+
+/** Paso de progreso del self-update de un agente (GET /api/agents, #284). */
+export interface AgentUpgradeProgress {
+  /** requested | downloading | verifying | swapping | restarting | failed | queued */
+  step: 'requested' | 'downloading' | 'verifying' | 'swapping' | 'restarting' | 'failed' | 'queued'
+  /** 0-100, solo en "downloading" */
+  pct?: number
+  /** mensaje de error, solo en "failed" */
+  error?: string
+  /** Unix SEGUNDOS del último reporte */
+  ts: number
+  /** Historia de pasos recorridos con sus timestamps (timeline, #284). */
+  steps?: { step: AgentUpgradeProgress['step']; pct?: number; ts: number }[]
 }
 
 /** Respuesta paginada (`GET /api/devices`, `GET /api/alerts`). */

+ 62 - 21
app/src/pages/Routers.tsx

@@ -4,8 +4,10 @@ import { Link } from 'react-router'
 import { RefreshCw, Rocket } from 'lucide-react'
 import { motion, useReducedMotion } from 'framer-motion'
 import { useNetPulse } from '@/data/DataProvider'
+import { AgentsSection } from '@/components/routers/AgentsSection'
 import { FleetCard } from '@/components/routers/FleetCard'
 import { FleetTable } from '@/components/routers/FleetTable'
+import { activeUpgrade, upgradeElapsed, upgradeStepText } from '@/components/routers/AgentUpgradeButton'
 import {
   AlertDialog,
   AlertDialogAction,
@@ -18,26 +20,29 @@ import {
 } from '@/components/ui/alert-dialog'
 import { cn } from '@/lib/utils'
 
-/** Tiempo máximo de espera por agente antes de marcarlo como fallido (ms).
+/** Tiempo máximo SIN NOTICIAS por agente antes de marcarlo como fallido (ms).
  * El self-update real tarda ~10-20 s (descarga + swap + restart + primer push);
- * 25 s cubre ese ciclo con margen. Un agente que no marca updateAvailable=false
- * en ese plazo no entiende el comando "upgrade" (versión previa a #243) y
- * requiere un reinstall. El poll de agentes (30 s) fuerza el render que lo
- * marca como fallido. */
+ * con los pasos en vivo (#284) cada reporte renueva la ventana, así que el
+ * timeout actúa solo como detector de parón: un agente que no reporta nada
+ * (versión previa a #284, con "requested" sembrado por el server) o que no
+ * marca updateAvailable=false en ese plazo requiere un reinstall. El poll de
+ * agentes (2 s durante upgrades) fuerza el render que lo marca. */
 const UPGRADE_TIMEOUT_MS = 25_000
 
 /** Página `/routers` — vista de flota (routers.md) */
 export default function Routers() {
   const { t } = useTranslation()
   const reduce = useReducedMotion()
-  const { routers, agents, upgradeAllAgents } = useNetPulse()
+  const { routers, agents, upgradeAllAgents, refreshAgents } = useNetPulse()
   const [refreshKey, setRefreshKey] = useState(0)
   const [spinning, setSpinning] = useState(false)
   const [upgrading, setUpgrading] = useState(false)
   const [confirmOpen, setConfirmOpen] = useState(false)
   const [upgradeMsg, setUpgradeMsg] = useState<string | null>(null)
   /** Slugs en seguimiento del upgrade de flota con su instante de inicio. */
-  const [upgradeTrack, setUpgradeTrack] = useState<{ slug: string; startedAt: number }[]>([])
+  const [upgradeTrack, setUpgradeTrack] = useState<{ slug: string; startedAt: number; queued: boolean }[]>([])
+
+  const QUEUED_TIMEOUT_MS = 600_000
 
   function handleRefresh() {
     setRefreshKey((k) => k + 1)
@@ -57,25 +62,52 @@ export default function Routers() {
     setUpgrading(false)
     if (res) {
       setUpgradeMsg(res.message)
-      // Seguimiento: los "sent" quedan en el panel hasta que el poll de
-      // agentes los marque al día (updateAvailable=false) o expire el timeout.
-      const sent = res.agents.filter((a) => a.status === 'sent').map((a) => a.slug)
-      setUpgradeTrack(sent.map((slug) => ({ slug, startedAt: Date.now() })))
-      if (sent.length === 0) window.setTimeout(() => setUpgradeMsg(null), 5000)
+      // Seguimiento: los "sent" Y los "queued" quedan en el panel hasta que
+      // el poll de agentes los marque al día (updateAvailable=false) o
+      // expire su timeout (los encolados esperan la reconexión del SSE,
+      // que con el backoff legacy puede tardar minutos).
+      const tracked = res.agents.filter((a) => a.status === 'sent' || a.status === 'queued')
+      setUpgradeTrack(tracked.map((a) => ({ slug: a.slug, startedAt: Date.now(), queued: a.status === 'queued' })))
+      // Tanda inmediata: encadena el sondeo rápido del provider (2 s mientras
+      // haya upgrades activos) en vez de esperar al ciclo lento de reposo -
+      // sin esto, un upgrade de flota en LAN (sub-segundo por agente) ocurre
+      // entero entre dos polls y el panel no muestrea ni un paso (#284).
+      void refreshAgents()
+      if (tracked.length === 0) window.setTimeout(() => setUpgradeMsg(null), 5000)
     } else {
       setUpgradeMsg(t('routers.upgradeAllFail'))
       window.setTimeout(() => setUpgradeMsg(null), 5000)
     }
   }
 
-  // Progreso en vivo: por slug, 'done' (al día), 'waiting' (en curso) o
-  // 'failed' (timeout sin respuesta del agente).
-  const upgradeProgress = upgradeTrack.map(({ slug, startedAt }) => {
+  // Progreso en vivo (#284): por slug, 'done' (al día), 'waiting' (en curso,
+  // con el paso que reporta el agente y los segundos transcurridos) o
+  // 'failed' (error reportado, parón sin noticias o "requested" que nunca
+  // arrancó = agente que no entiende el comando).
+  const nowSec = Math.floor(Date.now() / 1000)
+  const upgradeProgress = upgradeTrack.map(({ slug, startedAt, queued }) => {
     const agent = agents.find((a) => a.slug === slug)
     const done = agent ? !agent.updateAvailable : false
-    const timedOut = !done && Date.now() - startedAt >= UPGRADE_TIMEOUT_MS
-    const status = done ? 'done' : timedOut ? 'failed' : 'waiting'
-    return { slug, status, version: agent?.version ?? '…' }
+    const step = activeUpgrade(agent, nowSec)
+    const reportedFail = agent?.upgrade?.step === 'failed'
+    // "requested" sin reportes del agente tras el timeout: agente legacy o
+    // colgado (los agentes con #284 reportan "downloading" enseguida).
+    const staleRequested =
+      !queued && step?.step === 'requested' && nowSec - step.ts >= UPGRADE_TIMEOUT_MS / 1000
+    const lastNewsMs = Math.max(startedAt, (agent?.upgrade?.ts ?? 0) * 1000)
+    // Los encolados esperan la reconexión del SSE del agente (backoff legacy
+    // hasta 5 min): su timeout es generoso, no los 25 s de un envío directo.
+    const timedOut =
+      !done && !reportedFail && !step && Date.now() - lastNewsMs >= (queued ? QUEUED_TIMEOUT_MS : UPGRADE_TIMEOUT_MS)
+    const status = done ? 'done' : reportedFail || staleRequested || timedOut ? 'failed' : 'waiting'
+    // Resumen del recorrido (pasos + duración total) para las filas ya
+    // resueltas: en LAN el upgrade es sub-segundo y el panel en vivo no
+    // alcanza a muestrear los pasos; el resumen sí informa (#284).
+    const hist = agent?.upgrade?.steps ?? []
+    const first = hist[0]
+    const last = hist[hist.length - 1]
+    const durSec = first && last && hist.length > 1 && done ? Math.max(1, last.ts - first.ts) : 0
+    return { slug, status, version: agent?.version ?? '…', step, reportedFail, stepCount: hist.length, durSec }
   })
   const upgradeDone = upgradeProgress.filter((p) => p.status === 'done').length
   const upgradeFailed = upgradeProgress.filter((p) => p.status === 'failed').length
@@ -222,10 +254,16 @@ export default function Routers() {
                 <span className="min-w-0 flex-1 truncate font-mono text-caption text-text-secondary">{p.slug}</span>
                 <span className={cn('text-caption', p.status === 'done' ? 'text-ok' : p.status === 'failed' ? 'text-danger' : 'text-text-muted')}>
                   {p.status === 'done'
-                    ? t('routers.upgradeUpdated')
+                    ? p.stepCount > 1
+                      ? t('routers.upgradeUpdatedDetail', { count: p.stepCount, secs: p.durSec })
+                      : t('routers.upgradeUpdated')
                     : p.status === 'failed'
-                      ? t('routers.upgradeFailed')
-                      : t('routers.upgradeWaiting')}
+                      ? p.reportedFail
+                        ? t('routers.agent.upgradeFail')
+                        : t('routers.upgradeFailed')
+                      : p.step
+                        ? `${upgradeStepText(p.step, t)} · ${upgradeElapsed(p.step, nowSec)}`
+                        : t('routers.upgradeWaiting')}
                 </span>
               </li>
             ))}
@@ -243,6 +281,9 @@ export default function Routers() {
       {/* ③ Tabla comparativa */}
       <FleetTable refreshKey={refreshKey} />
 
+      {/* ④ Flota de agentes nativos (#245, reubicada aquí por #284) */}
+      <AgentsSection />
+
       {/* Confirmación in-app del upgrade de flota */}
       <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
         <AlertDialogContent>

+ 33 - 1
server-go/internal/agentbin/agentbin.go

@@ -10,12 +10,16 @@
 package agentbin
 
 import (
+	"crypto/sha256"
 	"embed"
+	"encoding/hex"
+	"io"
 	"io/fs"
+	"sync"
 )
 
 // EmbeddedAgentVersion es la versión del binario de agente que el servidor
-// embebe y sirve por GET /api/agents/{slug}/binary. Se usa para calcular el
+// embebe y sirve por GET /api/agents/{slug}/binary?arch=.... Se usa para calcular el
 // campo updateAvailable de GET /api/agents: un agente cuya versión reportada
 // difiere de esta versión tiene una actualización pendiente.
 //
@@ -26,6 +30,34 @@ import (
 // En desarrollo (sin ldflags) queda en el default 0.1.0.
 var EmbeddedAgentVersion = "0.1.0"
 
+// digestCache: sha256 por arquitectura. Los binarios son embebidos (no
+// cambian en runtime), así que se calcula una vez (#284: verificación de
+// integridad del upgrade del agente).
+var (
+	digestMu    sync.Mutex
+	digestCache = map[string]string{}
+)
+
+// Digest devuelve el sha256 (hex) del binario embebido para arch, o "" si no
+// existe o no se puede leer. Cacheado.
+func Digest(arch string) string {
+	digestMu.Lock()
+	defer digestMu.Unlock()
+	if d, ok := digestCache[arch]; ok {
+		return d
+	}
+	d := ""
+	if f, err := Open(arch); err == nil {
+		h := sha256.New()
+		if _, err := io.Copy(h, f); err == nil {
+			d = hex.EncodeToString(h.Sum(nil))
+		}
+		f.Close()
+	}
+	digestCache[arch] = d
+	return d
+}
+
 //go:embed agents/*
 var agentsFS embed.FS
 

+ 3 - 3
server-go/internal/auth/middleware.go

@@ -49,15 +49,15 @@ func WriteError(w http.ResponseWriter, status int, code string, message ...strin
 // de equipo), /api/agents/pair (pairing token de un solo uso, Fase 9 R3),
 // /api/agents/{slug}/binary (auth Bearer por token de agente,
 // Fase 6.2), /api/agents/{slug}/stream (SSE bidireccional, Fase 7.3),
-// /api/agents/{slug}/apply-result y /api/agents/{slug}/upgrade-result
-// (reporte del agente, auth Bearer).
+// /api/agents/{slug}/apply-result, /api/agents/{slug}/upgrade-result y
+// /api/agents/{slug}/upgrade-progress (reportes del agente, auth Bearer).
 // Fallo → 401 {error:'unauthorized'}.
 func RequireAuth(d *db.DB, secret string, next http.Handler) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		path := r.URL.Path
 		if !strings.HasPrefix(path, "/api/") || path == "/api/health" || path == "/api/auth/login" ||
 			path == "/api/ingest/agent" || path == "/api/agents/pair" ||
-			(strings.HasPrefix(path, "/api/agents/") && (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") || strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result"))) {
+			(strings.HasPrefix(path, "/api/agents/") && (strings.HasSuffix(path, "/binary") || strings.HasSuffix(path, "/stream") || strings.HasSuffix(path, "/apply-result") || strings.HasSuffix(path, "/upgrade-result") || strings.HasSuffix(path, "/upgrade-progress"))) {
 			next.ServeHTTP(w, r)
 			return
 		}

+ 34 - 0
server-go/internal/httpapi/agent.go

@@ -269,6 +269,11 @@ func (s *server) handleAgentBinary(w http.ResponseWriter, r *http.Request) {
 	}
 	w.Header().Set("Content-Type", "application/octet-stream")
 	w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="netpulse-agent-%s"`, arch))
+	// #284: sha256 del binario embebido para que el agente verifique la
+	// integridad de la descarga antes de hacer el swap.
+	if d := agentbin.Digest(arch); d != "" {
+		w.Header().Set("X-Checksum-Sha256", d)
+	}
 	http.ServeContent(w, r, st.Name(), st.ModTime(), rs)
 }
 
@@ -352,6 +357,26 @@ type agentListItem struct {
 	// SOLO se marca para routers OpenWrt (type openwrt/glinet): los de tipo
 	// managed-switch/external son scrapers que no usan el agente nativo.
 	UpdateAvailable bool `json:"updateAvailable"`
+	// Upgrade: último paso del self-update en marcha (requested/downloading/
+	// swapping/restarting/failed) con su marca de tiempo. null si no hay
+	// actividad reciente (#284: progreso en vivo para la UI).
+	Upgrade *agentUpgradeInfo `json:"upgrade,omitempty"`
+}
+
+// agentUpgradeStep es un paso de la historia (timeline de la UI, #284).
+type agentUpgradeStep struct {
+	Step string `json:"step"`
+	Pct  int    `json:"pct,omitempty"`
+	Ts   int64  `json:"ts"` // unix segundos
+}
+
+// agentUpgradeInfo es el paso de progreso expuesto en GET /api/agents.
+type agentUpgradeInfo struct {
+	Step  string            `json:"step"`
+	Pct   int               `json:"pct,omitempty"` // 0-100 en "downloading"
+	Error string            `json:"error,omitempty"`
+	Ts    int64             `json:"ts"` // unix segundos del último reporte
+	Steps []agentUpgradeStep `json:"steps,omitempty"` // historia de pasos (#284)
 }
 
 // agentUpgradeable: ¿un agente de un router con este type es actualizable?
@@ -417,6 +442,15 @@ func (s *server) handleAgentsList(w http.ResponseWriter, _ *http.Request) {
 					}
 					_, item.Fresh = s.agents.Fresh(slug)
 				}
+				// Progreso en vivo del upgrade (#284), si hay actividad reciente.
+				if st, ok := s.upgrades.snapshot(slug); ok {
+					ts := st.Ts.Unix()
+					info := &agentUpgradeInfo{Step: st.Step, Pct: st.Pct, Error: st.Error, Ts: ts}
+					for _, e := range st.History {
+						info.Steps = append(info.Steps, agentUpgradeStep{Step: e.Step, Pct: e.Pct, Ts: e.Ts.Unix()})
+					}
+					item.Upgrade = info
+				}
 				out = append(out, item)
 			}
 		}

+ 12 - 0
server-go/internal/httpapi/server.go

@@ -102,6 +102,10 @@ type server struct {
 	// Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
 	ingestLimit *ipRateLimit
 
+	// Progreso en vivo de los self-updates de agentes (#284): último paso
+	// por slug en memoria, expuesto en GET /api/agents.
+	upgrades *upgradeTracker
+
 	// Ventana de frescura del `ts` del agente (anti-replay, auditoría #2).
 	maxTsDrift time.Duration
 }
@@ -115,6 +119,7 @@ func NewHandler(d Deps) http.Handler {
 		agentHub:    d.AgentHub,
 		serverFP:    d.ServerFP,
 		ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
+		upgrades:    newUpgradeTracker(),
 	}
 	// Rearmer compartido entre el endpoint manual y el supervisor de
 	// auto-rearme (cmd/netpulse lo construye y lo pasa para que ambos
@@ -138,6 +143,11 @@ func NewHandler(d Deps) http.Handler {
 	if d.Config != nil && d.Config.MaxTsDriftSec > 0 {
 		s.maxTsDrift = time.Duration(d.Config.MaxTsDriftSec) * time.Second
 	}
+	// #284: upgrades encolados se envían cuando el agente (re)conecta su
+	// stream SSE (flush on-connect del hub).
+	if s.agentHub != nil {
+		s.agentHub.SetOnConnect(s.FlushQueuedUpgrade)
+	}
 	mode := d.Adapter.Mode()
 
 	mux := http.NewServeMux()
@@ -198,6 +208,8 @@ func NewHandler(d Deps) http.Handler {
 	// Fase 6.3 (issue #243): el agente reporta el resultado del self-upgrade.
 	// Auth por token de agente (Bearer), igual que binary/apply-result.
 	mux.HandleFunc("POST /api/agents/{slug}/upgrade-result", s.handleAgentUpgradeResult)
+	// #284: pasos intermedios del self-update (auth por token de agente).
+	mux.HandleFunc("POST /api/agents/{slug}/upgrade-progress", s.handleAgentUpgradeProgress)
 	// #251: upgrade masivo de todos los agentes con versión desactualizada.
 	mux.Handle("POST /api/agents/upgrade-all", auth.RequireAdmin(http.HandlerFunc(s.handleAgentsUpgradeAll)))
 	// Fase 7.3: SSE bidireccional agente↔servidor. El agente mantiene una

+ 228 - 23
server-go/internal/httpapi/upgrade.go

@@ -1,16 +1,20 @@
-// upgrade.go — Fase 6.3 (issue #243): self-update del agente usando el binario
+// upgrade.go - Fase 6.3 (issue #243): self-update del agente usando el binario
 // que ya sirve el servidor (GET /api/agents/{slug}/binary).
 //
-//	POST /api/agents/{slug}/upgrade        — admin: envía el comando "upgrade"
-//	                                         al agente vía SSE para que descargue
-//	                                         el binario embebido, lo intercambie
-//	                                         y reinicie su servicio procd.
-//	POST /api/agents/{slug}/upgrade-result — el agente reporta el resultado
-//	                                         (auth por token de agente).
-//	POST /api/agents/upgrade-all           — admin (#251): envía "upgrade" a
-//	                                         todos los agentes con update
-//	                                         disponible y devuelve el resultado
-//	                                         por slug.
+//	POST /api/agents/{slug}/upgrade          - admin: envía el comando "upgrade"
+//	                                          al agente vía SSE para que descargue
+//	                                          el binario embebido, lo intercambie
+//	                                          y reinicie su servicio procd.
+//	POST /api/agents/{slug}/upgrade-progress - el agente reporta pasos
+//	                                          intermedios (downloading con
+//	                                          porcentaje, swapping, restarting).
+//	                                          Auth por token de agente (#284).
+//	POST /api/agents/{slug}/upgrade-result   - el agente reporta el resultado
+//	                                          (auth por token de agente).
+//	POST /api/agents/upgrade-all             - admin (#251): envía "upgrade" a
+//	                                          todos los agentes con update
+//	                                          disponible y devuelve el resultado
+//	                                          por slug.
 package httpapi
 
 import (
@@ -18,10 +22,132 @@ import (
 	"log"
 	"net/http"
 	"strings"
+	"sync"
+	"time"
 
 	"github.com/gnacho/netpulse/server-go/internal/agentbin"
 )
 
+// Pasos del progreso de upgrade (los intermedios los envía el agente; los
+// terminales los fija el server a partir de upgrade-result).
+const (
+	upgradeStepRequested   = "requested"   // comando enviado por SSE
+	upgradeStepDownloading = "downloading" // descargando el binario (con pct)
+	upgradeStepVerifying   = "verifying"   // comprobando sha256 de la descarga
+	upgradeStepSwapping    = "swapping"    // intercambio atómico del binario
+	upgradeStepRestarting  = "restarting"  // swap ok, reinicio del servicio
+	upgradeStepFailed      = "failed"      // upgrade-result con error
+	upgradeStepQueued      = "queued"      // en cola hasta que el agente conecte
+)
+
+// upgradeStateTTL: cuánto se expone un paso sin actividad antes de dejar de
+// incluirlo en GET /api/agents. Cubre el ciclo completo (descarga + swap +
+// reinicio + primer push) con margen amplio. El estado "queued" vive más:
+// el agente puede tardar minutos en re-conectar su stream (backoff SSE).
+const (
+	upgradeStateTTL  = 3 * time.Minute
+	upgradeQueuedTTL = 30 * time.Minute
+	upgradeHistoryCap = 16
+)
+
+// upgradeStepEntry es un paso de la historia del upgrade (timeline de la UI).
+type upgradeStepEntry struct {
+	Step string
+	Pct  int
+	Ts   time.Time
+}
+
+// upgradeState es el último paso conocido del self-update de un agente, con
+// la historia de pasos recorridos (para la timeline aunque vayan rápido).
+type upgradeState struct {
+	Step    string
+	Pct     int    // 0-100, solo tiene sentido en "downloading"
+	Error   string // solo en "failed"
+	Ts      time.Time
+	History []upgradeStepEntry
+}
+
+// upgradeTracker mantiene en memoria el último paso por slug (no se persiste:
+// es estado efímero de una operación en marcha). El server lo alimenta desde
+// los comandos upgrade/upgrade-all y los reportes del agente, y lo expone en
+// GET /api/agents para que la UI muestre progreso en vivo (#284). Además
+// guarda los slugs con upgrade ENCOLA (agente sin stream SSE): se envían
+// cuando el agente vuelve a conectar (flush on-connect).
+type upgradeTracker struct {
+	mu      sync.Mutex
+	states  map[string]upgradeState
+	pending map[string]bool
+	now     func() time.Time // inyectable en tests
+}
+
+func newUpgradeTracker() *upgradeTracker {
+	return &upgradeTracker{states: map[string]upgradeState{}, pending: map[string]bool{}, now: time.Now}
+}
+
+// set registra un paso del slug y lo añade a la historia (mismo paso
+// consecutivo → refresca pct/ts del último entry en vez de duplicar).
+func (u *upgradeTracker) set(slug, step string, pct int, errMsg string) {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	u.setLocked(slug, step, pct, errMsg)
+}
+
+func (u *upgradeTracker) setLocked(slug, step string, pct int, errMsg string) {
+	st := u.states[slug]
+	ts := u.now()
+	if n := len(st.History); n > 0 && st.History[n-1].Step == step {
+		st.History[n-1].Pct = pct
+		st.History[n-1].Ts = ts
+	} else {
+		st.History = append(st.History, upgradeStepEntry{Step: step, Pct: pct, Ts: ts})
+		if len(st.History) > upgradeHistoryCap {
+			st.History = st.History[len(st.History)-upgradeHistoryCap:]
+		}
+	}
+	st.Step, st.Pct, st.Error, st.Ts = step, pct, errMsg, ts
+	u.states[slug] = st
+	if step != upgradeStepQueued {
+		delete(u.pending, slug)
+	}
+}
+
+// queue marca un upgrade como pendiente para cuando el agente reconecte.
+func (u *upgradeTracker) queue(slug string) {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	u.pending[slug] = true
+	u.setLocked(slug, upgradeStepQueued, 0, "")
+}
+
+// takeQueued devuelve true (una sola vez) si el slug tenía upgrade en cola.
+func (u *upgradeTracker) takeQueued(slug string) bool {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	if !u.pending[slug] {
+		return false
+	}
+	delete(u.pending, slug)
+	return true
+}
+
+// snapshot devuelve el paso del slug si no ha caducado.
+func (u *upgradeTracker) snapshot(slug string) (upgradeState, bool) {
+	u.mu.Lock()
+	defer u.mu.Unlock()
+	st, ok := u.states[slug]
+	if !ok {
+		return upgradeState{}, false
+	}
+	ttl := upgradeStateTTL
+	if st.Step == upgradeStepQueued {
+		ttl = upgradeQueuedTTL
+	}
+	if u.now().Sub(st.Ts) > ttl {
+		return upgradeState{}, false
+	}
+	return st, true
+}
+
 // upgradeResult es el cuerpo que el agente envía a upgrade-result tras
 // intentar el auto-upgrade.
 type upgradeResult struct {
@@ -30,6 +156,14 @@ type upgradeResult struct {
 	Error string `json:"error,omitempty"`
 }
 
+// upgradeProgress es el cuerpo que el agente envía a upgrade-progress en cada
+// paso intermedio del self-update (#284).
+type upgradeProgress struct {
+	Slug string `json:"slug"`
+	Step string `json:"step"`
+	Pct  int    `json:"pct,omitempty"`
+}
+
 // handleAgentUpgrade (admin): ordena a un agente conectado que se actualice
 // descargando el binario embebido del propio servidor.
 //
@@ -51,13 +185,72 @@ func (s *server) handleAgentUpgrade(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 	// El agente conoce su propia arquitectura (runtime.GOARCH); no hace falta
-	// pasársela. Data vacía {}.
-	if !s.agentHub.Send(slug, "upgrade", map[string]any{}) {
-		writeError(w, http.StatusConflict, "agent_not_connected",
-			"el agente "+slug+" no está conectado por SSE")
+	// pasársela. Data vacía {}. Si no está conectado por SSE, el upgrade se
+	// ENCOLA y se enviará en cuanto vuelva a conectar (#284).
+	status := s.sendOrQueueUpgrade(slug)
+	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true, "status": status})
+}
+
+// sendOrQueueUpgrade envía el comando upgrade por SSE; si el agente no está
+// conectado, lo encola para el flush on-connect del hub. Devuelve el estado.
+func (s *server) sendOrQueueUpgrade(slug string) string {
+	if s.agentHub.Send(slug, "upgrade", map[string]any{}) {
+		// Paso inicial del progreso en vivo (#284): el comando salió.
+		s.upgrades.set(slug, upgradeStepRequested, 0, "")
+		return "sent"
+	}
+	s.upgrades.queue(slug)
+	return "queued"
+}
+
+// FlushQueuedUpgrade envía el upgrade pendiente de un agente que acaba de
+// conectar su stream SSE (#284). Lo invoca el hub on-connect; si el envío
+// vuelve a fallar (carrera), re-encola para el próximo reintento.
+func (s *server) FlushQueuedUpgrade(slug string) {
+	if s.agentHub == nil {
+		return
+	}
+	if !s.agentTokenExists(slug) || !s.upgrades.takeQueued(slug) {
 		return
 	}
-	writeJSON(w, http.StatusAccepted, map[string]any{"ok": true})
+	if s.agentHub.Send(slug, "upgrade", map[string]any{}) {
+		s.upgrades.set(slug, upgradeStepRequested, 0, "")
+	} else {
+		s.upgrades.queue(slug)
+	}
+}
+
+// handleAgentUpgradeProgress: el agente reporta un paso intermedio del
+// self-update (downloading/swapping/restarting). Auth por token de agente
+// (Bearer), igual que upgrade-result (#284).
+func (s *server) handleAgentUpgradeProgress(w http.ResponseWriter, r *http.Request) {
+	slug := r.PathValue("slug")
+	token := bearerToken(r)
+	if !s.checkAgentToken(slug, token) {
+		writeError(w, http.StatusUnauthorized, "unauthorized")
+		return
+	}
+	var body upgradeProgress
+	if st := readJSONBody(w, r, &body); st != 0 {
+		writeBodyError(w, st, "invalid_body", "")
+		return
+	}
+	switch body.Step {
+	case upgradeStepDownloading, upgradeStepVerifying, upgradeStepSwapping, upgradeStepRestarting:
+	default:
+		writeError(w, http.StatusBadRequest, "invalid_body",
+			"step debe ser downloading, verifying, swapping o restarting")
+		return
+	}
+	pct := body.Pct
+	if pct < 0 {
+		pct = 0
+	}
+	if pct > 100 {
+		pct = 100
+	}
+	s.upgrades.set(slug, body.Step, pct, "")
+	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
 }
 
 // handleAgentUpgradeResult: el agente reporta el resultado del auto-upgrade.
@@ -76,8 +269,12 @@ func (s *server) handleAgentUpgradeResult(w http.ResponseWriter, r *http.Request
 	}
 	if body.OK {
 		log.Printf("[netpulse] upgrade: agente %s actualizado correctamente", slug)
+		// El agente reporta el ok ANTES de reiniciarse: el paso visible pasa
+		// a ser "restarting" hasta que el binario nuevo empuje su versión.
+		s.upgrades.set(slug, upgradeStepRestarting, 0, "")
 	} else {
 		log.Printf("[netpulse] upgrade: agente %s falló: %s", slug, body.Error)
+		s.upgrades.set(slug, upgradeStepFailed, 0, body.Error)
 	}
 	writeJSON(w, http.StatusOK, map[string]any{"ok": true})
 }
@@ -127,12 +324,10 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 				if !s.routerUpgradeable(slug) {
 					item.Status = "not_openwrt"
 				} else if version != "" && version != agentbin.EmbeddedAgentVersion {
-					if s.agentHub.Send(slug, "upgrade", map[string]any{}) {
-						item.Status = "sent"
-						item.Upgraded = true
+					item.Status = s.sendOrQueueUpgrade(slug)
+					item.Upgraded = item.Status == "sent"
+					if item.Status == "sent" {
 						sent++
-					} else {
-						item.Status = "not_connected"
 					}
 				} else {
 					item.Status = "up_to_date"
@@ -145,12 +340,22 @@ func (s *server) handleAgentsUpgradeAll(w http.ResponseWriter, r *http.Request)
 		}
 		out = append(out, item)
 	}
-	log.Printf("[netpulse] upgrade-all: %d/%d agentes con upgrade enviado", sent, len(out))
+	queued := 0
+	for _, it := range out {
+		if it.Status == "queued" {
+			queued++
+		}
+	}
+	log.Printf("[netpulse] upgrade-all: %d/%d enviados, %d en cola", sent, len(out), queued)
+	msg := fmt.Sprintf("upgrade enviado a %d de %d agentes", sent, len(out))
+	if queued > 0 {
+		msg += fmt.Sprintf(", %d en cola hasta que conecten", queued)
+	}
 	writeJSON(w, http.StatusOK, map[string]any{
 		"agents":  out,
 		"sent":    sent,
 		"total":   len(out),
-		"message": fmt.Sprintf("upgrade enviado a %d de %d agentes", sent, len(out)),
+		"message": msg,
 	})
 }
 

+ 38 - 9
server-go/internal/httpapi/upgrade_api_test.go

@@ -209,15 +209,44 @@ func TestUpgradeSlugDesconocido404(t *testing.T) {
 	}
 }
 
-func TestUpgradeNoConectado409(t *testing.T) {
+// TestUpgradeNoConectadoEncola — #284: sin stream SSE el upgrade NO da 409;
+// se encola (202 status "queued") para el flush on-connect.
+func TestUpgradeNoConectadoEncola(t *testing.T) {
 	ts := makeUpgradeTestServer(t)
-	if st, _ := createUpgradeToken(t, ts, "patio"); st != 201 {
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 || tok == "" {
 		t.Fatalf("create: %d", st)
 	}
 	status, body := postUpgrade(t, ts, "patio", ts.cookie)
-	if status != 409 || body["error"] != "agent_not_connected" {
+	if status != 202 || body["status"] != "queued" {
 		t.Fatalf("no conectado: got %d %v", status, body)
 	}
+	// Al conectar el stream, el upgrade encolado se envía (flush on-connect)
+	// y el estado pasa a "requested" en GET /api/agents.
+	cancel, done := openStream(t, ts, "patio", tok)
+	defer func() { cancel(); <-done }()
+	deadline := time.Now().Add(5 * time.Second)
+	ok := false
+	for time.Now().Before(deadline) && !ok {
+		res := doReq(t, "GET", ts.URL+"/api/agents", ts.cookie, "")
+		if res.StatusCode == 200 {
+			for _, a := range readJSON(t, res)["agents"].([]any) {
+				m, isMap := a.(map[string]any)
+				if !isMap || m["slug"] != "patio" {
+					continue
+				}
+				if up, has := m["upgrade"].(map[string]any); has && up["step"] == "requested" {
+					ok = true
+				}
+			}
+		}
+		if !ok {
+			time.Sleep(100 * time.Millisecond)
+		}
+	}
+	if !ok {
+		t.Fatalf("el upgrade encolado no se envió al conectar el stream")
+	}
 }
 
 func TestUpgradeConectado202(t *testing.T) {
@@ -229,10 +258,10 @@ func TestUpgradeConectado202(t *testing.T) {
 	cancel, done := openStream(t, ts, "patio", tok)
 
 	status, body := postUpgrade(t, ts, "patio", ts.cookie)
-	if status != 202 || body["ok"] != true {
+	if status != 202 || body["ok"] != true || body["status"] != "sent" {
 		t.Fatalf("conectado: got %d %v", status, body)
 	}
-	if len(body) != 1 {
+	if len(body) != 2 {
 		t.Fatalf("body con claves extra: %v", body)
 	}
 	cancel()
@@ -319,7 +348,7 @@ func TestAgentsListUpdateAvailable(t *testing.T) {
 // TestAgentsUpgradeAll — #251: POST /api/agents/upgrade-all.
 //   - 403 sin admin.
 //   - Con un agente conectado y desactualizado → status "sent".
-//   - Con un agente desconectado → status "not_connected".
+//   - Con un agente desconectado → status "queued" (flush on-connect, #284).
 //   - Con un agente al día (versión == embebida) → status "up_to_date".
 func TestAgentsUpgradeAll(t *testing.T) {
 	ts := makeUpgradeTestServer(t)
@@ -339,7 +368,7 @@ func TestAgentsUpgradeAll(t *testing.T) {
 	cancel, done := openStream(t, ts, "patio", tok)
 	defer func() { cancel(); <-done }()
 
-	// "otro" desactualizado pero SIN conectar → not_connected.
+	// "otro" desactualizado pero SIN conectar → queued (se envía al conectar).
 	if st, tokO := createUpgradeToken(t, ts, "otro"); st != 201 {
 		t.Fatalf("create otro: %d", st)
 	} else {
@@ -365,8 +394,8 @@ func TestAgentsUpgradeAll(t *testing.T) {
 	if bySlug["patio"] != "sent" {
 		t.Fatalf("patio debería ser sent: %v", bySlug)
 	}
-	if bySlug["otro"] != "not_connected" {
-		t.Fatalf("otro debería ser not_connected: %v", bySlug)
+	if bySlug["otro"] != "queued" {
+		t.Fatalf("otro debería ser queued: %v", bySlug)
 	}
 	if bySlug["aldia"] != "up_to_date" {
 		t.Fatalf("al_dia debería ser up_to_date: %v", bySlug)

+ 55 - 0
server-go/internal/httpapi/upgrade_internal_test.go

@@ -0,0 +1,55 @@
+// upgrade_internal_test.go — #284: tests internos del upgradeTracker (TTL y
+// concurrencia básica set/snapshot). Paquete interno para acceder a la API
+// no exportada.
+package httpapi
+
+import (
+	"sync"
+	"testing"
+	"time"
+)
+
+func TestUpgradeTrackerTTL(t *testing.T) {
+	tr := newUpgradeTracker()
+	base := time.Now()
+	tr.now = func() time.Time { return base }
+
+	// Paso caducado (TTL 3 min) → no se expone.
+	tr.states["patio"] = upgradeState{Step: upgradeStepDownloading, Pct: 40, Ts: base.Add(-upgradeStateTTL - time.Second)}
+	if _, ok := tr.snapshot("patio"); ok {
+		t.Fatal("paso caducado no debe exponerse")
+	}
+
+	// Paso reciente → se expone tal cual.
+	tr.states["patio"] = upgradeState{Step: upgradeStepDownloading, Pct: 40, Ts: base.Add(-time.Second)}
+	st, ok := tr.snapshot("patio")
+	if !ok {
+		t.Fatal("paso reciente debe exponerse")
+	}
+	if st.Step != upgradeStepDownloading || st.Pct != 40 {
+		t.Fatalf("snapshot: %+v, want downloading/40", st)
+	}
+
+	// Slug desconocido → no hay snapshot.
+	if _, ok := tr.snapshot("nadie"); ok {
+		t.Fatal("slug sin estado no debe exponerse")
+	}
+}
+
+// TestUpgradeTrackerConcurrent: set y snapshot en paralelo no corren (guardado
+// por mutex; -race lo pillaría).
+func TestUpgradeTrackerConcurrent(t *testing.T) {
+	tr := newUpgradeTracker()
+	var wg sync.WaitGroup
+	for i := 0; i < 8; i++ {
+		wg.Add(1)
+		go func(i int) {
+			defer wg.Done()
+			for j := 0; j < 100; j++ {
+				tr.set("patio", upgradeStepDownloading, j%100, "")
+				tr.snapshot("patio")
+			}
+		}(i)
+	}
+	wg.Wait()
+}

+ 145 - 0
server-go/internal/httpapi/upgrade_progress_test.go

@@ -0,0 +1,145 @@
+// upgrade_progress_test.go — #284: progreso en vivo del self-update.
+// Contrato de POST /api/agents/{slug}/upgrade-progress (Bearer del agente),
+// la semilla "requested" al enviar el comando upgrade/upgrade-all, la
+// transición a restarting/failed desde upgrade-result y la exposición del
+// campo `upgrade` en GET /api/agents.
+package httpapi_test
+
+import (
+	"io"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// postProgress hace POST /api/agents/{slug}/upgrade-progress con el Bearer dado.
+func postProgress(t *testing.T, ts *upgradeTestServer, slug, token, body string) int {
+	t.Helper()
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents/"+slug+"/upgrade-progress", strings.NewReader(body))
+	req.Header.Set("Content-Type", "application/json")
+	if token != "" {
+		req.Header.Set("Authorization", "Bearer "+token)
+	}
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("upgrade-progress: %v", err)
+	}
+	defer res.Body.Close()
+	_, _ = io.Copy(io.Discard, res.Body)
+	return res.StatusCode
+}
+
+// agentUpgradeField devuelve el campo `upgrade` del slug en GET /api/agents
+// (nil si no viene).
+func agentUpgradeField(t *testing.T, ts *upgradeTestServer, slug string) map[string]any {
+	t.Helper()
+	res := get(t, ts.URL, "/api/agents", ts.cookie)
+	body := readJSON(t, res)
+	for _, a := range body["agents"].([]any) {
+		m, _ := a.(map[string]any)
+		if m["slug"] == slug {
+			u, _ := m["upgrade"].(map[string]any)
+			return u
+		}
+	}
+	t.Fatalf("%s ausente en /api/agents: %v", slug, body)
+	return nil
+}
+
+// TestUpgradeProgressAuth: 401 sin token o con token inválido; 200 con el
+// token del agente; 400 con step desconocido.
+func TestUpgradeProgressAuth(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 || tok == "" {
+		t.Fatalf("create: %d", st)
+	}
+
+	if got := postProgress(t, ts, "patio", "", `{"step":"downloading"}`); got != 401 {
+		t.Fatalf("sin token: got %d want 401", got)
+	}
+	if got := postProgress(t, ts, "patio", "deadbeef", `{"step":"downloading"}`); got != 401 {
+		t.Fatalf("token malo: got %d want 401", got)
+	}
+	if got := postProgress(t, ts, "patio", tok, `{"step":"nonsense"}`); got != 400 {
+		t.Fatalf("step inválido: got %d want 400", got)
+	}
+	if got := postProgress(t, ts, "patio", tok, `not-json`); got != 400 {
+		t.Fatalf("body roto: got %d want 400", got)
+	}
+	if got := postProgress(t, ts, "patio", tok, `{"step":"downloading","pct":42}`); got != 200 {
+		t.Fatalf("válido: got %d want 200", got)
+	}
+}
+
+// TestUpgradeProgressExposedInAgentsList: el comando upgrade siembra
+// "requested", los reportes del agente actualizan el paso y upgrade-result
+// transita a restarting (ok) o failed (error). El campo caduca por TTL.
+func TestUpgradeProgressExposedInAgentsList(t *testing.T) {
+	ts := makeUpgradeTestServer(t)
+	st, tok := createUpgradeToken(t, ts, "patio")
+	if st != 201 {
+		t.Fatalf("create: %d", st)
+	}
+	cancel, done := openStream(t, ts, "patio", tok)
+	defer func() { cancel(); <-done }()
+
+	// Comando enviado → paso "requested".
+	status, _ := postUpgrade(t, ts, "patio", ts.cookie)
+	if status != 202 {
+		t.Fatalf("upgrade: got %d want 202", status)
+	}
+	u := agentUpgradeField(t, ts, "patio")
+	if u["step"] != "requested" {
+		t.Fatalf("tras upgrade: step %v, want requested", u["step"])
+	}
+
+	// Paso intermedio del agente → downloading con pct.
+	if got := postProgress(t, ts, "patio", tok, `{"step":"downloading","pct":40}`); got != 200 {
+		t.Fatalf("progress: got %d want 200", got)
+	}
+	u = agentUpgradeField(t, ts, "patio")
+	if u["step"] != "downloading" {
+		t.Fatalf("step: %v, want downloading", u["step"])
+	}
+	if u["pct"].(float64) != 40 {
+		t.Fatalf("pct: %v, want 40", u["pct"])
+	}
+
+	// pct fuera de rango → se clampea a 100.
+	if got := postProgress(t, ts, "patio", tok, `{"step":"downloading","pct":250}`); got != 200 {
+		t.Fatalf("progress clamp: got %d want 200", got)
+	}
+	u = agentUpgradeField(t, ts, "patio")
+	if u["pct"].(float64) != 100 {
+		t.Fatalf("pct clamp: %v, want 100", u["pct"])
+	}
+
+	// Resultado ok → restarting (el agente se dispone a reiniciarse).
+	req, _ := http.NewRequest("POST", ts.URL+"/api/agents/patio/upgrade-result", strings.NewReader(`{"ok":true}`))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+tok)
+	res, _ := http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 200 {
+		t.Fatalf("upgrade-result: got %d want 200", res.StatusCode)
+	}
+	u = agentUpgradeField(t, ts, "patio")
+	if u["step"] != "restarting" {
+		t.Fatalf("tras ok: step %v, want restarting", u["step"])
+	}
+
+	// Resultado con error → failed con el mensaje.
+	req, _ = http.NewRequest("POST", ts.URL+"/api/agents/patio/upgrade-result", strings.NewReader(`{"ok":false,"error":"swap failed"}`))
+	req.Header.Set("Content-Type", "application/json")
+	req.Header.Set("Authorization", "Bearer "+tok)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	u = agentUpgradeField(t, ts, "patio")
+	if u["step"] != "failed" {
+		t.Fatalf("tras error: step %v, want failed", u["step"])
+	}
+	if u["error"] != "swap failed" {
+		t.Fatalf("error: %v, want swap failed", u["error"])
+	}
+}

+ 23 - 0
server-go/internal/sse/agenthub.go

@@ -19,6 +19,10 @@ type AgentHub struct {
 
 	mu    sync.Mutex
 	conns map[string]*agentConn // slug → conexión activa
+	// onConnect se llama (en su propia goroutine) cuando un agente conecta
+	// su stream; lo usa httpapi para enviar upgrades encolados (#284).
+	onConnectMu sync.Mutex
+	onConnect   func(slug string)
 }
 
 type agentConn struct {
@@ -35,6 +39,22 @@ func NewAgentHub(checkToken func(string, string) bool) *AgentHub {
 	return &AgentHub{checkToken: checkToken, conns: map[string]*agentConn{}}
 }
 
+// SetOnConnect registra el callback de conexión de agente (#284).
+func (h *AgentHub) SetOnConnect(f func(slug string)) {
+	h.onConnectMu.Lock()
+	h.onConnect = f
+	h.onConnectMu.Unlock()
+}
+
+func (h *AgentHub) fireOnConnect(slug string) {
+	h.onConnectMu.Lock()
+	f := h.onConnect
+	h.onConnectMu.Unlock()
+	if f != nil {
+		go f(slug)
+	}
+}
+
 // ConnectedSlugs devuelve los slugs con agente conectado vía SSE.
 func (h *AgentHub) ConnectedSlugs() []string {
 	h.mu.Lock()
@@ -152,6 +172,9 @@ func (h *AgentHub) HandleStream(w http.ResponseWriter, r *http.Request) {
 	// Enviar evento "connected" al agente (confirmación)
 	_ = c.write("event: connected\ndata: {}\n\n")
 
+	// Upgrade encolado mientras el agente estaba fuera (#284).
+	h.fireOnConnect(slug)
+
 	// Heartbeat cada 30s
 	heartbeat := time.NewTicker(30 * time.Second)
 	defer heartbeat.Stop()