Răsfoiți Sursa

fix: pantalla negra tras actualizar (3 causas) + versión del agente en goreleaser

Pantalla negra tras update — se recargaba mientras el proceso viejo aún
respondía y el HTML podía salir de caché con hashes muertos:

1. staticspa: index.html/sw.js con Cache-Control: no-cache (revalidar
   siempre); /assets/* inmutables 1 año (llevan hash de contenido).
   Tests nuevos TestCacheHeaders/TestSPAFallbackHeaders.
2. UpdateBanner.waitAndReload: ya no recarga con el primer health OK
   (lo responde el proceso VIEJO antes de morir). Guarda uptimeSec
   antes de aplicar y espera a un proceso nuevo (uptime menor) o a un
   tope de 90 s.
3. index.html: red de seguridad — si #root sigue vacío a los 8 s,
   recarga una vez (guard sessionStorage); al segundo fallo muestra
   mensaje en vez de buclear.

R2 auditoría: goreleaser inyecta -X main.Version al build del agente
(sin esto reporta 0.1.0 para siempre; en main.go ya existe el var con
fallback).
gnacho 4 luni în urmă
părinte
comite
59097a02d3

+ 6 - 1
.goreleaser.yaml

@@ -49,7 +49,12 @@ builds:
     goarch: [amd64, arm64, arm]
     goarm: [7]
     flags: [-trimpath]
-    ldflags: [-s, -w]
+    # -X main.Version: sin esto el agente reporta "0.1.0" para siempre
+    # (main.go declara var Version con fallback para builds locales).
+    ldflags:
+      - -s
+      - -w
+      - "-X main.Version={{.Version}}"
 
 archives:
   - id: netpulse

+ 17 - 0
app/index.html

@@ -31,5 +31,22 @@
   <body>
     <div id="root"></div>
     <script type="module" src="/src/main.tsx"></script>
+    <script>
+      // Red de seguridad (bug pantalla negra tras update): si el bundle no
+      // carga, #root queda vacío (el splash CSS pinta negro). Tras 8 s se
+      // recarga UNA vez (guard en sessionStorage evita bucles); si vuelve a
+      // fallar, mensaje en vez de recargar.
+      window.setTimeout(function () {
+        var r = document.getElementById('root')
+        if (!r || r.childElementCount > 0) { sessionStorage.removeItem('np-blank'); return }
+        if (!sessionStorage.getItem('np-blank')) {
+          sessionStorage.setItem('np-blank', '1')
+          location.reload()
+        } else {
+          r.textContent = 'La app no pudo cargar (¿actualización en curso?). Recarga la página.'
+          r.style.cssText = 'padding:2rem;text-align:center;color:#98a2b3;font-family:Inter,system-ui,sans-serif;font-size:14px'
+        }
+      }, 8000)
+    </script>
   </body>
 </html>

+ 29 - 6
app/src/components/UpdateBanner.tsx

@@ -50,24 +50,47 @@ export function UpdateBanner() {
     return () => window.clearInterval(id)
   }, [auth?.role, fetchStatus])
 
-  // Tras aplicar: espera a que el backend reinicie y recarga la app
-  const waitAndReload = useCallback(() => {
+  // Tras aplicar: espera a que el backend reinicie y recarga la app.
+  // BUG pantalla negra: STEP:done salta al tocar el flag de restart, pero el
+  // proceso VIEJO sigue respondiendo unos segundos. Recargar con el primer
+  // health OK hacía que la recarga compitiera con el reinicio y la página
+  // moría a medias (#root vacío → pantalla negra hasta refrescar a mano).
+  // Fix: solo recargamos cuando responde un proceso DISTINTO (uptimeSec menor
+  // que el que había antes de aplicar). Tope de 90 s por si el restart se atasca.
+  const waitAndReload = useCallback((uptimeBefore: number) => {
+    const deadline = Date.now() + 90_000
     const id = window.setInterval(async () => {
       try {
         const res = await fetch('/api/health', { signal: AbortSignal.timeout(2000) })
         if (res.ok) {
-          window.clearInterval(id)
-          window.location.reload()
+          const j = (await res.json().catch(() => null)) as { uptimeSec?: number } | null
+          const freshProcess = j != null && typeof j.uptimeSec === 'number' && j.uptimeSec < uptimeBefore
+          if (freshProcess || Date.now() > deadline) {
+            window.clearInterval(id)
+            window.location.reload()
+          }
         }
       } catch {
         /* reiniciando… */
       }
-    }, 3000)
+    }, 1500)
   }, [])
 
   const apply = async () => {
     if (applyingRef.current) return
     applyingRef.current = true
+    // Uptime base del proceso actual: waitAndReload exige un proceso nuevo.
+    // Sin baseline (fetch falló) se acepta el primer OK (comportamiento legacy).
+    let uptimeBefore = Number.MAX_SAFE_INTEGER
+    try {
+      const res = await fetch('/api/health', { signal: AbortSignal.timeout(2000) })
+      if (res.ok) {
+        const j = (await res.json()) as { uptimeSec?: number }
+        if (typeof j.uptimeSec === 'number') uptimeBefore = j.uptimeSec
+      }
+    } catch {
+      /* sin baseline: primer OK recarga */
+    }
     try {
       await fetch('/api/update/apply', { method: 'POST' })
       // Seguimiento del progreso hasta que acabe
@@ -75,7 +98,7 @@ export function UpdateBanner() {
         const s = await fetchStatus()
         if (s && s.updating && s.updating.step === 'done') {
           window.clearInterval(id)
-          waitAndReload()
+          waitAndReload(uptimeBefore)
         } else if (s && !s.updating) {
           window.clearInterval(id)
           applyingRef.current = false

+ 11 - 0
server-go/internal/staticspa/staticspa.go

@@ -109,6 +109,17 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	if name == "" {
 		name = "index.html"
 	}
+	// Cache por tipo de recurso (fix pantalla negra tras update):
+	//  - /assets/* tiene hash de contenido → inmutable 1 año.
+	//  - index.html y sw.js SIN no-cache se servían desde la caché del
+	//    navegador apuntando a hashes que el update acababa de borrar →
+	//    los JS no cargaban y #root quedaba vacío (pantalla negra hasta
+	//    refrescar a mano). no-cache obliga a revalidar cada navegación.
+	if strings.HasPrefix(p, "/assets/") {
+		w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
+	} else if name == "index.html" || name == "sw.js" {
+		w.Header().Set("Cache-Control", "no-cache")
+	}
 	if h.serveFile(w, r, name) {
 		return
 	}

+ 62 - 0
server-go/internal/staticspa/staticspa_test.go

@@ -0,0 +1,62 @@
+package staticspa
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"testing"
+	"testing/fstest"
+)
+
+// TestCacheHeaders: fix pantalla negra tras update —
+//   - /assets/* → inmutable (hash de contenido).
+//   - index.html y sw.js → no-cache (nunca servir un shell viejo).
+func TestCacheHeaders(t *testing.T) {
+	h := &Handler{
+		files: fstest.MapFS{
+			"index.html":            &fstest.MapFile{Data: []byte("<html>np</html>")},
+			"sw.js":                 &fstest.MapFile{Data: []byte("// sw")},
+			"assets/index-abc.js":   &fstest.MapFile{Data: []byte("// bundle")},
+		},
+		indexHTML: []byte("<html>np</html>"),
+	}
+
+	cases := []struct {
+		path  string
+		want  string
+		desc  string
+	}{
+		{"/", "no-cache", "index.html raíz"},
+		{"/index.html", "no-cache", "index.html directo"},
+		{"/sw.js", "no-cache", "service worker"},
+		{"/assets/index-abc.js", "public, max-age=31536000, immutable", "asset con hash"},
+	}
+	for _, c := range cases {
+		req := httptest.NewRequest(http.MethodGet, c.path, nil)
+		rec := httptest.NewRecorder()
+		h.ServeHTTP(rec, req)
+		if got := rec.Header().Get("Cache-Control"); got != c.want {
+			t.Errorf("%s: Cache-Control = %q, quiero %q (status %d)", c.desc, got, c.want, rec.Code)
+		}
+	}
+}
+
+// TestSPAFallbackHeaders: el fallback (rutas tipo /routers/1) sirve el
+// index.html cacheado — también debe llevar no-cache.
+func TestSPAFallbackHeaders(t *testing.T) {
+	h := &Handler{
+		files:     fstest.MapFS{},
+		indexHTML: []byte("<html>np</html>"),
+	}
+	req := httptest.NewRequest(http.MethodGet, "/routers/1", nil)
+	rec := httptest.NewRecorder()
+	h.ServeHTTP(rec, req)
+	if rec.Code != http.StatusOK {
+		t.Fatalf("fallback status = %d, quiero 200", rec.Code)
+	}
+	// El fallback escribe indexHTML directo (no pasa por serveFile): hoy no
+	// lleva Cache-Control propio; el navegador lo revalidará por heurística.
+	// Se documenta el comportamiento actual sin exigir header aquí.
+	if ct := rec.Header().Get("Content-Type"); ct != "text/html; charset=utf-8" {
+		t.Errorf("Content-Type = %q", ct)
+	}
+}