Browse Source

feat(update): multi-step update wizard with progress bar (#283)

* feat(update): multi-step update wizard with progress bar

- update.sh: finer steps (fetch/download/verify/install/restart) with
  PROGRESS milestones and sha256 verification against the GitHub asset
  digest before swapping the binary in
- updater: per-step progress weights, PROGRESS parsing (clamped) and an
  SSE broadcaster for state changes
- httpapi: GET /api/update/stream (admin, SSE) streams the update status
  on every step/progress change with a 15s heartbeat
- app: UpdateDialog wizard (confirm, steps, restarting, reload) used by
  both the update banner and Settings; SSE with polling fallback, adopts
  in-flight updates and reloads only when a fresh process answers

Closes #280

* feat(update): changelog in confirm step and downtime acknowledgment

- updater: expose latestBody (commit body in rolling mode, release notes in
  stable mode) in the status payload
- app: show the changelog as a bullet list in the wizard confirm phase and
  require an explicit 'service will be down' checkbox before enabling the
  update button (Pulse-style)

Closes #280 (iteration 2)

* fix(update): filter git trailers out of the wizard changelog

* fix(update): hide empty changelog section when only git trailers remain

---------

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 3 tháng trước cách đây
mục cha
commit
55db71a2be

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

@@ -1092,11 +1092,14 @@
     "dismiss": "Dismiss notice",
     "step": {
       "start": "starting",
-      "fetch": "downloading code",
+      "fetch": "fetching code",
       "server-deps": "updating backend",
       "frontend-build": "building the UI",
       "restart": "restarting the service",
-      "done": "done, reloading"
+      "done": "done, reloading",
+      "download": "downloading binary",
+      "verify": "verifying integrity",
+      "install": "installing"
     },
     "checks": {
       "title": "Pre-flight checks",
@@ -1122,6 +1125,20 @@
       "success": "Success",
       "failed": "Failed",
       "running": "Running"
+    },
+    "dialog": {
+      "title": "Update NetPulse",
+      "desc": "The update runs in several steps and takes a few minutes.",
+      "start": "Update now",
+      "cancel": "Cancel",
+      "close": "Close",
+      "restarting": "Restarting the service…",
+      "reloadSoon": "The app will reload automatically in a few seconds",
+      "failed": "The update failed",
+      "hideHint": "You can close this window: the update continues on the server",
+      "progressLabel": "Update progress",
+      "changelogTitle": "What's new",
+      "downNotice": "The service will be down while it restarts"
     }
   },
   "demo": {

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

@@ -1092,11 +1092,14 @@
     "dismiss": "Descartar aviso",
     "step": {
       "start": "iniciando",
-      "fetch": "descargando código",
+      "fetch": "obteniendo código",
       "server-deps": "actualizando backend",
       "frontend-build": "compilando la interfaz",
       "restart": "reiniciando el servicio",
-      "done": "completado, recargando"
+      "done": "completado, recargando",
+      "download": "descargando binario",
+      "verify": "verificando integridad",
+      "install": "instalando"
     },
     "checks": {
       "title": "Comprobaciones previas",
@@ -1122,6 +1125,20 @@
       "success": "Correcto",
       "failed": "Falló",
       "running": "En curso"
+    },
+    "dialog": {
+      "title": "Actualizar NetPulse",
+      "desc": "La actualización se aplica en varios pasos y tarda unos minutos.",
+      "start": "Actualizar ahora",
+      "cancel": "Cancelar",
+      "close": "Cerrar",
+      "restarting": "Reiniciando el servicio…",
+      "reloadSoon": "La app se recargará automáticamente en unos segundos",
+      "failed": "La actualización falló",
+      "hideHint": "Puedes cerrar esta ventana: la actualización continúa en el servidor",
+      "progressLabel": "Progreso de la actualización",
+      "changelogTitle": "Novedades",
+      "downNotice": "El servicio estará caído mientras se reinicia"
     }
   },
   "demo": {

+ 19 - 81
app/src/components/UpdateBanner.tsx

@@ -1,15 +1,16 @@
 /**
  * UpdateBanner — franja horizontal que avisa cuando hay versión nueva en
- * GitHub (solo admin). Comprueba al montar y cada 30 min; al pulsar
- * "Actualizar" sigue el progreso (fetch → build → restart) y recarga la app
- * cuando el backend vuelve.
+ * GitHub (solo admin). Comprueba al montar y con cadencia semanal; al pulsar
+ * "Actualizar" abre el asistente multi-paso (UpdateDialog, issue #280) que
+ * sigue el progreso por pasos y recarga la app cuando el backend vuelve.
  */
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useEffect, useState } from 'react'
 import { useTranslation } from 'react-i18next'
 import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
 import { DownloadCloud, ExternalLink, Loader2, X } from 'lucide-react'
 import { useAuth } from '@/data/AuthContext'
 import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
+import { UpdateDialog } from '@/components/UpdateDialog'
 
 function normalizeVersion(s: string) {
   return s.trim().toLowerCase().replace(/^v/, '')
@@ -19,11 +20,12 @@ interface UpdateStatus {
   current: string
   latest: string | null
   latestMsg: string | null
+  latestBody?: string | null
   updateAvailable: boolean
   canApply: boolean
   mode: string
   repo: string
-  updating: false | { step: string }
+  updating: false | { step: string; progress?: number }
   hasToken: boolean
   readiness?: UpdateReadiness | null
 }
@@ -31,8 +33,6 @@ interface UpdateStatus {
 const POLL_MS = 60 * 60 * 1000
 const WEEK_MS = 7 * 24 * 60 * 60 * 1000
 const CHECK_KEY = 'netpulse-last-update-check'
-const APPLY_POLL_MS = 2500
-const APPLY_TIMEOUT_MS = 90_000
 
 export function UpdateBanner() {
   const { t } = useTranslation()
@@ -40,17 +40,7 @@ export function UpdateBanner() {
   const auth = useAuth()
   const [status, setStatus] = useState<UpdateStatus | null>(null)
   const [dismissed, setDismissed] = useState<string | null>(null)
-  const applyingRef = useRef(false)
-  // Id del poll de progreso del apply: en un ref para limpiarlo en unmount
-  // (#226).
-  const applyPollRef = useRef<number | null>(null)
-  const clearApplyPoll = () => {
-    if (applyPollRef.current !== null) {
-      window.clearInterval(applyPollRef.current)
-      applyPollRef.current = null
-    }
-  }
-  useEffect(() => clearApplyPoll, [])
+  const [dialogOpen, setDialogOpen] = useState(false)
 
   const fetchStatus = useCallback(async () => {
     try {
@@ -91,68 +81,15 @@ export function UpdateBanner() {
     return () => window.clearInterval(id)
   }, [auth?.role, fetchStatus])
 
-  // 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) {
-          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… */
-      }
-    }, 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. Tope de 90 s: si el backend
-      // se queda en 'updating' sin llegar a 'done', se abandona el poll en vez
-      // de seguir sondeando para siempre (#226). El id vive en un ref para
-      // limpiarlo si el banner se desmonta.
-      const deadline = Date.now() + APPLY_TIMEOUT_MS
-      applyPollRef.current = window.setInterval(async () => {
-        const s = await fetchStatus()
-        if (s && s.updating && s.updating.step === 'done') {
-          clearApplyPoll()
-          waitAndReload(uptimeBefore)
-        } else if ((s && !s.updating) || Date.now() > deadline) {
-          clearApplyPoll()
-          applyingRef.current = false
-        }
-      }, APPLY_POLL_MS)
-    } catch {
-      applyingRef.current = false
-    }
-  }
+  // Al cerrar el asistente: refrescar (si la actualización sigue en curso,
+  // el banner pasa a mostrar "Actualizando…" con su spinner).
+  const handleDialogChange = useCallback(
+    (open: boolean) => {
+      setDialogOpen(open)
+      if (!open) void fetchStatus()
+    },
+    [fetchStatus],
+  )
 
   if (auth?.role !== 'admin') return null
   if (!status || !status.updateAvailable || !status.latest || dismissed === status.latest) return null
@@ -193,7 +130,7 @@ export function UpdateBanner() {
               {status.canApply ? (
                 <button
                   type="button"
-                  onClick={() => void apply()}
+                  onClick={() => setDialogOpen(true)}
                   disabled={!ready}
                   className="flex shrink-0 items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-xs font-semibold text-canvas transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
                 >
@@ -230,6 +167,7 @@ export function UpdateBanner() {
         {!updating && status.canApply && status.readiness && (
           <ReadinessPanel readiness={status.readiness} compact className="mx-0.5" />
         )}
+        <UpdateDialog open={dialogOpen} onOpenChange={handleDialogChange} initialStatus={status} />
       </motion.div>
     </AnimatePresence>
   )

+ 416 - 0
app/src/components/UpdateDialog.tsx

@@ -0,0 +1,416 @@
+/**
+ * UpdateDialog — asistente de actualización multi-paso con barra de progreso
+ * (issue #280): confirmación → pasos (fetch → download → verify → install →
+ * restart) → reinicio → recarga. Patrón tipo Pulse: estado por SSE
+ * (/api/update/stream) con fallback a polling, y recarga solo cuando responde
+ * un proceso DISTINTO (uptimeSec menor que el baseline previo al apply).
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import {
+  AlertTriangle,
+  ArrowRight,
+  Check,
+  Circle,
+  DownloadCloud,
+  Loader2,
+} from 'lucide-react'
+import {
+  Dialog,
+  DialogContent,
+  DialogDescription,
+  DialogFooter,
+  DialogHeader,
+  DialogTitle,
+} from '@/components/ui/dialog'
+import { Progress } from '@/components/ui/progress'
+import { Button } from '@/components/ui/button'
+import { Checkbox } from '@/components/ui/checkbox'
+import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
+
+export interface UpdateStatusInfo {
+  current: string
+  latest: string | null
+  latestMsg: string | null
+  /** Cuerpo del commit (rolling) o notas del release (estable): changelog. */
+  latestBody?: string | null
+  updateAvailable: boolean
+  canApply: boolean
+  repo: string
+  updating: false | { step: string; progress?: number }
+  error?: string | null
+  readiness?: UpdateReadiness | null
+}
+
+/** Pasos visibles del asistente (el "done" se refleja solo en la barra). */
+const STEP_ORDER = ['fetch', 'download', 'verify', 'install', 'restart'] as const
+
+/** Mapa legado: pasos de scripts viejos → paso visible equivalente. */
+const STEP_ALIAS: Record<string, string> = {
+  start: 'fetch',
+  binary: 'download', // legado: download+install juntos
+  done: 'restart',
+}
+
+type Phase = 'confirm' | 'progress' | 'restarting' | 'error'
+
+interface UpdateDialogProps {
+  open: boolean
+  onOpenChange: (open: boolean) => void
+  /** Estado inicial (del banner/Ajustes); si no, se consulta al abrir. */
+  initialStatus?: UpdateStatusInfo | null
+}
+
+export function UpdateDialog({ open, onOpenChange, initialStatus }: UpdateDialogProps) {
+  const { t } = useTranslation()
+  const [phase, setPhase] = useState<Phase>('confirm')
+  const [status, setStatus] = useState<UpdateStatusInfo | null>(initialStatus ?? null)
+  const [step, setStep] = useState<string>('start')
+  const [pct, setPct] = useState<number>(0)
+  const [errorCode, setErrorCode] = useState<string | null>(null)
+  // Confirmación explícita de la caída del servicio (patrón Pulse): sin
+  // marcarla, el botón de actualizar no se habilita.
+  const [ackDowntime, setAckDowntime] = useState(false)
+
+  const esRef = useRef<EventSource | null>(null)
+  const pollRef = useRef<number | null>(null)
+  const uptimeRef = useRef<number>(Number.MAX_SAFE_INTEGER)
+  const phaseRef = useRef<Phase>('confirm')
+  const fetchFailRef = useRef(0)
+
+  const setPhaseBoth = (p: Phase) => {
+    phaseRef.current = p
+    setPhase(p)
+  }
+
+  const closeStream = useCallback(() => {
+    if (esRef.current) {
+      esRef.current.close()
+      esRef.current = null
+    }
+    if (pollRef.current !== null) {
+      window.clearInterval(pollRef.current)
+      pollRef.current = null
+    }
+  }, [])
+
+  useEffect(() => closeStream, [closeStream])
+
+  // Recarga cuando responde un proceso distinto (uptimeSec menor). Tope de
+  // 90 s por si el restart se atasca (misma regla que el banner, #226/#241).
+  const waitAndReload = useCallback(() => {
+    if (phaseRef.current === 'restarting') return
+    setPhaseBoth('restarting')
+    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) {
+          const j = (await res.json().catch(() => null)) as { uptimeSec?: number } | null
+          const fresh = j != null && typeof j.uptimeSec === 'number' && j.uptimeSec < uptimeRef.current
+          if (fresh || Date.now() > deadline) {
+            window.clearInterval(id)
+            window.location.reload()
+          }
+        }
+      } catch {
+        /* reiniciando… */
+      }
+    }, 1500)
+  }, [])
+
+  // Reacción central al estado que llega por SSE o polling.
+  const handleStatus = useCallback(
+    (st: UpdateStatusInfo) => {
+      setStatus(st)
+      fetchFailRef.current = 0
+      if (st.error) {
+        setErrorCode(st.error)
+        setPhaseBoth('error')
+        closeStream()
+        return
+      }
+      if (st.updating) {
+        // Adoptar una actualización ya en curso (otra pestaña/admin): el
+        // asistente pasa directamente a la fase de progreso.
+        if (phaseRef.current === 'confirm') setPhaseBoth('progress')
+        setStep(st.updating.step)
+        setPct(st.updating.progress ?? 0)
+        if (st.updating.step === 'done') {
+          // El script terminó: el reinicio real tarda unos segundos (el
+          // proceso viejo sigue respondiendo un rato).
+          closeStream()
+          waitAndReload()
+        }
+      } else if (phaseRef.current === 'progress') {
+        // updating=false tras haber arrancado: el apply terminó en error
+        // (el updater limpia el paso) o ya reinició sin ver el done.
+        closeStream()
+        waitAndReload()
+      }
+    },
+    [closeStream, waitAndReload],
+  )
+
+  // Fallback a polling si el SSE no está disponible (proxy, etc.).
+  const startPolling = useCallback(() => {
+    if (pollRef.current !== null) return
+    const poll = async () => {
+      try {
+        const res = await fetch('/api/update/status', { signal: AbortSignal.timeout(3000) })
+        if (!res.ok) throw new Error(String(res.status))
+        handleStatus((await res.json()) as UpdateStatusInfo)
+      } catch {
+        // Sin conexión durante el update: casi seguro reiniciando.
+        fetchFailRef.current += 1
+        if (fetchFailRef.current >= 2 && phaseRef.current === 'progress') {
+          closeStream()
+          waitAndReload()
+        }
+      }
+    }
+    void poll()
+    pollRef.current = window.setInterval(poll, 2000)
+  }, [closeStream, handleStatus, waitAndReload])
+
+  const startStream = useCallback(() => {
+    try {
+      const es = new EventSource('/api/update/stream')
+      esRef.current = es
+      es.addEventListener('update', (ev) => {
+        try {
+          handleStatus(JSON.parse((ev as MessageEvent).data) as UpdateStatusInfo)
+        } catch {
+          /* payload corrupto: sigue esperando el próximo */
+        }
+      })
+      es.onerror = () => {
+        // El stream MUERE con el proceso durante el reinicio final.
+        if (phaseRef.current === 'restarting') return
+        if (step === 'restart' || step === 'done') {
+          closeStream()
+          waitAndReload()
+          return
+        }
+        closeStream()
+        startPolling()
+      }
+    } catch {
+      startPolling()
+    }
+  }, [closeStream, handleStatus, startPolling, waitAndReload, step])
+
+  // Al abrir: reset + estado fresco; al cerrar: cortar stream/poll.
+  useEffect(() => {
+    if (open) {
+      setPhaseBoth('confirm')
+      setStep('start')
+      setPct(0)
+      setErrorCode(null)
+      setAckDowntime(false)
+      fetchFailRef.current = 0
+      if (!initialStatus) {
+        void fetch('/api/update/status')
+          .then((r) => (r.ok ? r.json() : null))
+          .then((j) => {
+            if (!j) return
+            setStatus(j as UpdateStatusInfo)
+            // Ya hay un update en curso: adoptarlo (fase progreso + stream).
+            if ((j as UpdateStatusInfo).updating) {
+              setPhaseBoth('progress')
+              startStream()
+            }
+          })
+          .catch(() => undefined)
+      } else {
+        setStatus(initialStatus)
+        if (initialStatus.updating) {
+          setPhaseBoth('progress')
+          startStream()
+        }
+      }
+    } else {
+      closeStream()
+    }
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [open])
+
+  const apply = async () => {
+    // Baseline de uptime ANTES de aplicar: la recarga exige proceso nuevo.
+    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') uptimeRef.current = j.uptimeSec
+      }
+    } catch {
+      /* sin baseline: el primer OK tras el corte recarga */
+    }
+    try {
+      const res = await fetch('/api/update/apply', { method: 'POST' })
+      if (!res.ok) {
+        setErrorCode(res.status === 409 ? 'already_updating' : 'update_failed')
+        setPhaseBoth('error')
+        return
+      }
+      setPhaseBoth('progress')
+      startStream()
+    } catch {
+      setErrorCode('network')
+      setPhaseBoth('error')
+    }
+  }
+
+  const visibleStep = STEP_ALIAS[step] ?? step
+  const activeIdx = STEP_ORDER.indexOf(visibleStep as (typeof STEP_ORDER)[number])
+  const busy = phase === 'progress' || phase === 'restarting'
+
+  // Changelog visible: líneas del body sin trailers de git. Si no queda
+  // ninguna (p. ej. squash cuyo body son solo trailers), la sección
+  // "Novedades" no se renderiza.
+  const changelogLines = useMemo(
+    () =>
+      (status?.latestBody ?? '')
+        .split('\n')
+        .map((l) => l.trim())
+        .filter((l) => l && !/^(co-authored-by|signed-off-by|reviewed-by):/i.test(l)),
+    [status?.latestBody],
+  )
+
+  return (
+    <Dialog open={open} onOpenChange={(o) => !busy && onOpenChange(o)}>
+      <DialogContent className="max-w-md">
+        <DialogHeader>
+          <DialogTitle className="flex items-center gap-2">
+            <DownloadCloud className="h-5 w-5 text-accent" strokeWidth={1.75} aria-hidden="true" />
+            {t('update.dialog.title')}
+          </DialogTitle>
+          {phase === 'confirm' && <DialogDescription>{t('update.dialog.desc')}</DialogDescription>}
+        </DialogHeader>
+
+        {phase === 'confirm' && (
+          <div className="flex flex-col gap-4">
+            <div className="flex items-center justify-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
+              <span className="font-mono text-sm text-text-secondary">{status?.current ?? '—'}</span>
+              <ArrowRight className="h-4 w-4 text-text-muted" strokeWidth={1.75} aria-hidden="true" />
+              <span className="font-mono text-sm font-semibold text-accent">
+                {status?.latest ?? '—'}
+              </span>
+            </div>
+            {status?.latestMsg && (
+              <p className="text-center text-caption text-text-muted">{status.latestMsg}</p>
+            )}
+            {/* Changelog (issue #280): cuerpo del commit (rolling) o notas
+                del release (estable), línea a línea con scroll. Los trailers
+                de git (Co-authored-by, Signed-off-by…) son ruido: fuera. */}
+            {changelogLines.length > 0 && (
+              <div className="flex flex-col gap-1.5">
+                <p className="text-xs font-semibold uppercase tracking-wider text-text-muted">
+                  {t('update.dialog.changelogTitle')}
+                </p>
+                <div className="max-h-44 overflow-y-auto rounded-xl border border-border bg-surface px-3.5 py-2.5">
+                  <ul className="flex flex-col gap-1">
+                    {changelogLines.map((l, i) => (
+                        <li key={i} className="flex items-start gap-2 text-caption leading-snug text-text-secondary">
+                          <span className="mt-1 h-1 w-1 shrink-0 rounded-full bg-text-muted/60" aria-hidden="true" />
+                          {l.replace(/^[-*]\s+/, '')}
+                        </li>
+                      ))}
+                  </ul>
+                </div>
+              </div>
+            )}
+            {status?.readiness && <ReadinessPanel readiness={status.readiness} compact />}
+            <label className="flex cursor-pointer items-start gap-2.5 rounded-xl bg-warn/10 px-3.5 py-2.5 text-caption leading-snug text-warn">
+              <Checkbox
+                checked={ackDowntime}
+                onCheckedChange={(v) => setAckDowntime(v === true)}
+                className="mt-0.5"
+                aria-label={t('update.dialog.downNotice')}
+              />
+              <span>{t('update.dialog.downNotice')}</span>
+            </label>
+            <DialogFooter>
+              <Button variant="outline" onClick={() => onOpenChange(false)}>
+                {t('update.dialog.cancel')}
+              </Button>
+              <Button
+                onClick={() => void apply()}
+                disabled={
+                  !ackDowntime ||
+                  !status?.canApply ||
+                  (status?.readiness ? !status.readiness.ready : false)
+                }
+              >
+                <DownloadCloud className="h-4 w-4" strokeWidth={1.75} aria-hidden="true" />
+                {t('update.dialog.start')}
+              </Button>
+            </DialogFooter>
+          </div>
+        )}
+
+        {phase === 'progress' && (
+          <div className="flex flex-col gap-4" role="status">
+            <ul className="flex flex-col gap-2.5">
+              {STEP_ORDER.map((s, i) => {
+                const done = activeIdx > i || step === 'done'
+                const active = activeIdx === i && step !== 'done'
+                return (
+                  <li key={s} className="flex items-center gap-2.5 text-sm">
+                    {done ? (
+                      <Check className="h-4 w-4 shrink-0 text-ok" strokeWidth={2} aria-hidden="true" />
+                    ) : active ? (
+                      <Loader2
+                        className="h-4 w-4 shrink-0 animate-spin text-accent"
+                        strokeWidth={2}
+                        aria-hidden="true"
+                      />
+                    ) : (
+                      <Circle className="h-4 w-4 shrink-0 text-text-muted/40" strokeWidth={2} aria-hidden="true" />
+                    )}
+                    <span className={done ? 'text-text-secondary' : active ? 'text-text-primary font-medium' : 'text-text-muted'}>
+                      {t(`update.step.${s}`)}
+                    </span>
+                  </li>
+                )
+              })}
+            </ul>
+            <div className="flex flex-col gap-1.5">
+              <Progress value={pct} aria-label={t('update.dialog.progressLabel')} />
+              <div className="flex items-center justify-between text-caption text-text-muted">
+                <span>{t(`update.step.${visibleStep}`)}…</span>
+                <span className="font-mono">{pct}%</span>
+              </div>
+            </div>
+            <p className="text-center text-caption text-text-muted">{t('update.dialog.hideHint')}</p>
+          </div>
+        )}
+
+        {phase === 'restarting' && (
+          <div className="flex flex-col items-center gap-3 py-4" role="status">
+            <Loader2 className="h-10 w-10 animate-spin text-accent" strokeWidth={1.5} aria-hidden="true" />
+            <p className="text-sm font-medium text-text-primary">{t('update.dialog.restarting')}</p>
+            <p className="text-caption text-text-muted">{t('update.dialog.reloadSoon')}</p>
+          </div>
+        )}
+
+        {phase === 'error' && (
+          <div className="flex flex-col gap-4">
+            <div className="flex items-start gap-3 rounded-xl bg-danger/10 px-4 py-3">
+              <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-danger" strokeWidth={1.75} aria-hidden="true" />
+              <div className="min-w-0">
+                <p className="text-sm font-medium text-danger">{t('update.dialog.failed')}</p>
+                {errorCode && <p className="mt-0.5 font-mono text-caption text-text-muted">{errorCode}</p>}
+              </div>
+            </div>
+            <DialogFooter>
+              <Button variant="outline" onClick={() => onOpenChange(false)}>
+                {t('update.dialog.close')}
+              </Button>
+            </DialogFooter>
+          </div>
+        )}
+      </DialogContent>
+    </Dialog>
+  )
+}

+ 14 - 12
app/src/pages/Settings.tsx

@@ -47,6 +47,7 @@ import { KnownMacsManager } from '@/components/KnownMacsManager'
 import { SegmentedControl } from '@/components/SegmentedControl'
 import { TopologyOverridesManager } from '@/components/topology/TopologyOverridesManager'
 import { ReadinessPanel, type UpdateReadiness } from '@/components/UpdateReadiness'
+import { UpdateDialog } from '@/components/UpdateDialog'
 import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'
 import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
 import { Slider } from '@/components/ui/slider'
@@ -2094,6 +2095,7 @@ interface NetPulseUpdateStatus {
   current: string
   latest: string | null
   latestMsg: string | null
+  latestBody?: string | null
   updateAvailable: boolean
   canApply: boolean
   repo: string
@@ -2106,6 +2108,7 @@ function UpdateCheckInline() {
   const [status, setStatus] = useState<NetPulseUpdateStatus | null>(null)
   const [busy, setBusy] = useState(false)
   const [error, setError] = useState(false)
+  const [dialogOpen, setDialogOpen] = useState(false)
 
   const check = async () => {
     setBusy(true)
@@ -2121,16 +2124,14 @@ function UpdateCheckInline() {
     }
   }
 
-  const apply = async () => {
-    setBusy(true)
-    try {
-      await fetch('/api/update/apply', { method: 'POST' })
-    } catch {
-      setError(true)
-    } finally {
-      setBusy(false)
-    }
-  }
+  // Al cerrar el asistente: refrescar el estado (issue #280).
+  const handleDialogChange = useCallback(
+    (open: boolean) => {
+      setDialogOpen(open)
+      if (!open) void check()
+    },
+    [],
+  )
 
   const ready = status?.readiness ? status.readiness.ready : true
 
@@ -2140,8 +2141,8 @@ function UpdateCheckInline() {
         status.canApply ? (
           <button
             type="button"
-            onClick={() => void apply()}
-            disabled={busy || !ready}
+            onClick={() => setDialogOpen(true)}
+            disabled={!ready}
             className="inline-flex h-9 shrink-0 items-center gap-1.5 rounded-xl border border-accent bg-accent-soft px-3 text-[13px] font-medium text-accent transition-colors hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-60"
           >
             <Download className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden="true" />
@@ -2185,6 +2186,7 @@ function UpdateCheckInline() {
           <ReadinessPanel readiness={status.readiness} compact />
         </div>
       )}
+      <UpdateDialog open={dialogOpen} onOpenChange={handleDialogChange} initialStatus={status} />
     </div>
   )
 }

+ 35 - 13
deploy/update.sh

@@ -2,9 +2,10 @@
 # NetPulse — script de actualización (lo lanza el updater del backend, corre
 # como netpulse). Único flujo soportado: Go.
 #   - Go   (/opt/netpulse/server-go/netpulse): git pull → binario precompilado
-#          de CI (go-latest) → swap atómico → reinicio diferido.
-# El backend Node legado fue eliminado; solo existe el flujo Go (decisión
-# 5-Ago-2026).
+#          de CI (go-latest) → verificación sha256 → swap atómico → reinicio
+#          diferido.
+# Progreso (issue #280): cada paso emite STEP:<nombre> y los hitos largos
+# PROGRESS:<0-100>; el updater los reenvía al frontend vía SSE.
 set -e
 cd /opt/netpulse
 
@@ -15,36 +16,57 @@ SHA=$(git rev-parse HEAD)
 
 if [ -f /opt/netpulse/server-go/netpulse ]; then
   # ---------------- Flujo Go ----------------
-  echo "STEP:binary"
+  echo "STEP:download"
   ARCH=$(uname -m)
   case "$ARCH" in
     x86_64)  ARCH=amd64 ;;
     aarch64) ARCH=arm64 ;;
     *) echo "arquitectura no soportada: $ARCH"; exit 1 ;;
   esac
-  URL="https://github.com/gnacho/netpulse/releases/download/go-latest/netpulse-server-$SHA-linux-$ARCH.tar.gz"
+  ASSET="netpulse-server-$SHA-linux-$ARCH.tar.gz"
   rm -rf /opt/netpulse/server-go/pkg.new
   mkdir -p /opt/netpulse/server-go/pkg.new
+  # Metadatos de la prerelease go-latest: fallback de asset + digest sha256
+  # para el paso verify. Si la llamada falla, el flujo sigue (fallback solo
+  # con el asset exacto del commit).
+  RELEASE_JSON=/tmp/netpulse-go-release.json
+  curl -fsSL -m 30 https://api.github.com/repos/gnacho/netpulse/releases/tags/go-latest -o "$RELEASE_JSON" || rm -f "$RELEASE_JSON"
   # 1) asset exacto del commit; 2) si no existe (commit sin cambios en
   #    server-go/ ni app/), el asset más reciente de esta arquitectura.
-  if curl -fsSL -m 300 "$URL" -o /tmp/netpulse-go.tgz && tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new; then
-    echo "binario precompilado descargado de CI ($SHA)"
-  else
-    ASSET=$(curl -fsSL -m 30 https://api.github.com/repos/gnacho/netpulse/releases/tags/go-latest \
-      | grep -oP '"name":\s*"\Knetpulse-server-[0-9a-f]+-linux-'"$ARCH"'\.tar\.gz' | head -1)
-    if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz \
-      && tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new; then
+  if ! curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
+    ASSET=$(grep -oP '"name":\s*"\Knetpulse-server-[0-9a-f]+-linux-'"$ARCH"'\.tar\.gz' "$RELEASE_JSON" 2>/dev/null | head -1)
+    if [ -n "$ASSET" ] && curl -fsSL -m 300 "https://github.com/gnacho/netpulse/releases/download/go-latest/$ASSET" -o /tmp/netpulse-go.tgz; then
       echo "binario de CI más reciente disponible ($ASSET)"
     else
       echo "ERROR: sin binario en CI para $ARCH (el CT no puede compilar Go)"
       exit 1
     fi
   fi
+  echo "PROGRESS:55"
+
+  echo "STEP:verify"
+  # Digest sha256 del asset publicado por la API de GitHub. Si el campo no
+  # viene (release sin digest), se avisa y continúa; si viene y NO coincide,
+  # aborta (el tarball no es el publicado por CI).
+  DIGEST=""
+  if [ -s "$RELEASE_JSON" ]; then
+    DIGEST=$(awk -v want="\"$ASSET\"" '$0 ~ "\"name\": *" want {f=1} f && /"digest"/ {print; exit}' "$RELEASE_JSON" | grep -oE 'sha256:[0-9a-f]+')
+  fi
+  if [ -n "$DIGEST" ]; then
+    echo "verificando $ASSET contra $DIGEST"
+    echo "${DIGEST#sha256:}  /tmp/netpulse-go.tgz" | sha256sum -c - || { echo "ERROR: sha256 del asset no coincide"; exit 1; }
+  else
+    echo "aviso: la API no publicó digest para $ASSET; verificación omitida"
+  fi
+  tar xzf /tmp/netpulse-go.tgz -C /opt/netpulse/server-go/pkg.new
+  echo "PROGRESS:75"
+
+  echo "STEP:install"
   # Swap atómico del binario: si algo falló antes, el anterior queda intacto
   chmod +x /opt/netpulse/server-go/pkg.new/netpulse
   mv /opt/netpulse/server-go/netpulse /opt/netpulse/server-go/netpulse.old
   mv /opt/netpulse/server-go/pkg.new/netpulse /opt/netpulse/server-go/netpulse
-  rm -rf /opt/netpulse/server-go/pkg.new /opt/netpulse/server-go/netpulse.old /tmp/netpulse-go.tgz
+  rm -rf /opt/netpulse/server-go/pkg.new /opt/netpulse/server-go/netpulse.old /tmp/netpulse-go.tgz "$RELEASE_JSON"
 
   echo "STEP:restart"
   # Reinicio vía unidad systemd.path del CT (netpulse-go-restart.path vigila

+ 43 - 0
server-go/internal/httpapi/update.go

@@ -4,12 +4,15 @@
 //	GET  /api/update/status          → estado actual (incl. readiness + pendingApply)
 //	POST /api/update/check           → fuerza un chequeo contra GitHub
 //	POST /api/update/apply           → aplica la actualización (202 | 409)
+//	GET  /api/update/stream          → SSE con el estado en cada cambio (issue #280)
 //	GET  /api/updates/history        → historial de updates (issue #159)
 //	POST /api/update/pending-confirm → descarta la confirmación post-update (issue #161)
 package httpapi
 
 import (
 	"context"
+	"encoding/json"
+	"fmt"
 	"net/http"
 	"time"
 
@@ -22,6 +25,46 @@ func (s *server) registerUpdateRoutes(mux *http.ServeMux, u *updater.Updater) {
 	mux.Handle("GET /api/update/status", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		writeJSON(w, http.StatusOK, u.Status())
 	})))
+	// Stream SSE del estado del update (issue #280): evento inicial con el
+	// estado completo, luego un evento por cambio de paso/progreso. El
+	// heartbeat de 15 s mantiene la conexión viva; el stream MUERE con el
+	// proceso durante el reinicio final (el cliente debe tratarlo como
+	// fase "restarting" y sondear /api/health).
+	mux.Handle("GET /api/update/stream", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		flusher, ok := w.(http.Flusher)
+		if !ok {
+			writeError(w, http.StatusInternalServerError, "streaming_unsupported")
+			return
+		}
+		w.Header().Set("Content-Type", "text/event-stream")
+		w.Header().Set("Cache-Control", "no-cache")
+		w.Header().Set("X-Accel-Buffering", "no")
+		ch, cancel := u.Subscribe()
+		defer cancel()
+		writeEvent := func(st updater.Status) {
+			raw, err := json.Marshal(st)
+			if err != nil {
+				return
+			}
+			fmt.Fprintf(w, "event: update\ndata: %s\n\n", raw)
+			flusher.Flush()
+		}
+		writeEvent(u.Status())
+		heartbeat := time.NewTicker(15 * time.Second)
+		defer heartbeat.Stop()
+		for {
+			select {
+			case <-r.Context().Done():
+				return
+			case <-heartbeat.C:
+				// Comentario SSE: mantiene viva la conexión sin evento.
+				fmt.Fprint(w, ": ping\n\n")
+				flusher.Flush()
+			case st := <-ch:
+				writeEvent(st)
+			}
+		}
+	})))
 	mux.Handle("POST /api/update/check", auth.RequireAdmin(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
 		defer cancel()

+ 109 - 0
server-go/internal/httpapi/update_stream_test.go

@@ -0,0 +1,109 @@
+// update_stream_test.go — GET /api/update/stream (issue #280): SSE con el
+// estado del update en cada cambio de paso/progreso.
+package httpapi_test
+
+import (
+	"bufio"
+	"context"
+	"io"
+	"net/http"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+)
+
+func TestUpdateStreamSSE(t *testing.T) {
+	if !gitAvailable() {
+		t.Skip("git no disponible")
+	}
+	root := t.TempDir()
+	if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	// Script con retardo: permite observar el evento del paso intermedio.
+	script := "#!/bin/bash\necho STEP:fetch\nsleep 2\necho STEP:done\ntrue\n"
+	if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
+		t.Fatal(err)
+	}
+	writeGitHead(t, root)
+	ts := makeTestServerWithUpdater(t, root)
+	cookie := adminCookie(t, ts)
+
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	req, _ := http.NewRequestWithContext(ctx, "GET", ts.URL+"/api/update/stream", nil)
+	req.Header.Set("Cookie", "session="+cookie)
+	res, err := http.DefaultClient.Do(req)
+	if err != nil {
+		t.Fatalf("stream: %v", err)
+	}
+	defer res.Body.Close()
+	if res.StatusCode != 200 {
+		t.Fatalf("status: %d", res.StatusCode)
+	}
+	if ct := res.Header.Get("Content-Type"); ct != "text/event-stream" {
+		t.Fatalf("content-type: %s", ct)
+	}
+
+	// Lectura con timeout: cada evento termina en línea vacía.
+	br := bufio.NewReader(res.Body)
+	readEvent := func() string {
+		evt := ""
+		ch := make(chan string, 1)
+		go func() {
+			for {
+				line, err := br.ReadString('\n')
+				evt += line
+				if line == "\n" || line == "" || err != nil {
+					ch <- evt
+					return
+				}
+			}
+		}()
+		select {
+		case <-ch:
+			return evt
+		case <-time.After(5 * time.Second):
+			t.Fatal("timeout leyendo evento SSE")
+			return ""
+		}
+	}
+
+	// Evento inicial: estado completo (idle, sin updating).
+	ev1 := readEvent()
+	if !strings.Contains(ev1, "event: update") {
+		t.Fatalf("evento inicial: %q", ev1)
+	}
+
+	// Disparar el apply y observar el evento del paso por el stream.
+	req2, _ := http.NewRequestWithContext(ctx, "POST", ts.URL+"/api/update/apply", nil)
+	req2.Header.Set("Cookie", "session="+cookie)
+	res2, err := http.DefaultClient.Do(req2)
+	if err != nil {
+		t.Fatalf("apply: %v", err)
+	}
+	io.Copy(io.Discard, res2.Body)
+	res2.Body.Close()
+	if res2.StatusCode != 202 {
+		t.Fatalf("apply status: %d", res2.StatusCode)
+	}
+
+	// El apply puede emitir varios eventos seguidos (start → fetch): leer
+	// hasta el del paso fetch (con su peso #280).
+	deadline := time.Now().Add(5 * time.Second)
+	for {
+		ev := readEvent()
+		if strings.Contains(ev, `"step":"fetch"`) {
+			if !strings.Contains(ev, `"progress":12`) {
+				t.Fatalf("progreso de fetch: %q", ev)
+			}
+			break
+		}
+		if time.Now().After(deadline) {
+			t.Fatalf("sin evento fetch: %q", ev)
+		}
+	}
+	cancel()
+}

+ 151 - 40
server-go/internal/updater/updater.go

@@ -38,11 +38,31 @@ var APIBase = "https://api.github.com"
 var BuildCommit string
 
 type progress struct {
-	Step string `json:"step"`
+	Step     string `json:"step"`
+	Progress int    `json:"progress"` // 0-100
 }
 
-// Status es la respuesta de /api/update/status (shape literal de updater.js:
-// updating es false | {step}; lastLog son los últimos 800 chars).
+// stepWeight: porcentaje mostrado MIENTRAS el paso está en ejecución
+// (issue #280). Pasos del update.sh actual + los legados (binary,
+// server-deps, frontend-build) para compatibilidad con scripts viejos.
+var stepWeight = map[string]int{
+	"start":          3,
+	"fetch":          12,
+	"binary":         40, // legado: download+install juntos
+	"download":       40,
+	"verify":         68,
+	"install":        84,
+	"restart":        94,
+	"done":           100,
+	"server-deps":    30, // legado flujo Node
+	"frontend-build": 60, // legado flujo Node
+}
+
+const stepDefaultWeight = 50
+
+// Status es la respuesta de /api/update/status (extiende el shape histórico
+// updater.js): updating es false | {step, progress 0-100}; lastLog son los
+// últimos 800 chars.
 type Status struct {
 	Current         string  `json:"current"`
 	Latest          *string `json:"latest"`
@@ -51,11 +71,14 @@ type Status struct {
 	CanApply        bool    `json:"canApply"`
 	Mode            string  `json:"mode"`
 	LastCheck       *int64  `json:"lastCheck"`
-	Updating        any     `json:"updating"` // false | {"step": ...}
-	Error           *string `json:"error"`
-	LastLog         *string `json:"lastLog"`
-	Repo            string  `json:"repo"`
-	HasToken        bool    `json:"hasToken"`
+	// LatestBody: cuerpo del commit (rolling) o notas del release (estable)
+	// mostrado como changelog en el asistente (issue #280).
+	LatestBody    *string `json:"latestBody,omitempty"`
+	Updating      any     `json:"updating"` // false | {"step": ...}
+	Error         *string `json:"error"`
+	LastLog       *string `json:"lastLog"`
+	Repo          string  `json:"repo"`
+	HasToken      bool    `json:"hasToken"`
 	// Readiness: pre-flight checks del apply (issue #160). Null en layout
 	// estable (sin auto-apply) o hasta el primer Status().
 	Readiness *Readiness `json:"readiness,omitempty"`
@@ -80,13 +103,19 @@ type Updater struct {
 	current      string
 	latest       *string
 	latestMsg    *string
+	latestBody   *string // cuerpo del commit/notas del release (changelog #280)
 	updateAvail  bool
 	lastCheck    *int64
 	updatingStep *string // nil = no actualizando
+	updatingPct  int     // 0-100 (issue #280); peso del paso o PROGRESS explícito
 	updatingLog  string
 	lastLog      *string
 	err          *string
 
+	// Suscriptores del stream /api/update/stream (issue #280). Notificados
+	// en cada cambio de paso/porcentaje o fin de actualización.
+	subs map[chan Status]struct{}
+
 	// readiness cacheado (issue #160): el network check toca red y no debe
 	// bloquear el polling de status.
 	readiness   *Readiness
@@ -120,6 +149,7 @@ func New(repoRoot, repo, token, version string, db *sql.DB) *Updater {
 		mode:     mode,
 		db:       db,
 		current:  "desconocido",
+		subs:     make(map[chan Status]struct{}),
 		stopCh:   make(chan struct{}),
 	}
 	// Issue #161: procesar el marcador pendiente (confirmación post-update)
@@ -148,12 +178,13 @@ func gitShort(repoRoot string) string {
 }
 
 // fetchLatestCommit consulta el último commit de main (modo rolling).
-// Errores → {error: ...}.
-func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg string, errCode string) {
+// Errores → {error: ...}. El body (líneas tras el subject) se devuelve como
+// changelog del asistente.
+func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg, body, errCode string) {
 	req, err := http.NewRequestWithContext(ctx, "GET",
 		fmt.Sprintf("%s/repos/%s/commits/main", APIBase, u.repo), nil)
 	if err != nil {
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	req.Header.Set("Accept", "application/vnd.github+json")
 	req.Header.Set("User-Agent", "netpulse-updater")
@@ -165,19 +196,19 @@ func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg string, errCo
 	res, err := client.Do(req)
 	if err != nil {
 		if ctx.Err() != nil {
-			return "", "", "timeout"
+			return "", "", "", "timeout"
 		}
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	defer res.Body.Close()
 	if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
 		if u.token != "" {
-			return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+			return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
 		}
-		return "", "", "no_token"
+		return "", "", "", "no_token"
 	}
 	if res.StatusCode != 200 {
-		return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+		return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
 	}
 	var data struct {
 		SHA    string `json:"sha"`
@@ -186,13 +217,14 @@ func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg string, errCo
 		} `json:"commit"`
 	}
 	if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	sha = data.SHA
 	if len(sha) > 7 {
 		sha = sha[:7]
 	}
 	msg = strings.Split(data.Commit.Message, "\n")[0]
+	body = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(data.Commit.Message), msg))
 	// JS slice(0, 80) corta por UNIDADES UTF-16 (un astral = 2 unidades),
 	// no por bytes: replicar ese cómputo (sin dejar surrogates partidos).
 	units, cut := 0, len(msg)
@@ -208,16 +240,17 @@ func (u *Updater) fetchLatestCommit(ctx context.Context) (sha, msg string, errCo
 		units += w
 	}
 	msg = msg[:cut]
-	return sha, msg, ""
+	return sha, msg, body, ""
 }
 
 // fetchLatestRelease consulta el último release tag (modo stable). Devuelve
-// tag_name (ej. "v2.7.3") y el nombre del release. Errores → {error: ...}.
-func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name string, errCode string) {
+// tag_name (ej. "v2.7.3"), el nombre del release y sus notas (body) para el
+// changelog del asistente. Errores → {error: ...}.
+func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name, body, errCode string) {
 	req, err := http.NewRequestWithContext(ctx, "GET",
 		fmt.Sprintf("%s/repos/%s/releases/latest", APIBase, u.repo), nil)
 	if err != nil {
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	req.Header.Set("Accept", "application/vnd.github+json")
 	req.Header.Set("User-Agent", "netpulse-updater")
@@ -229,33 +262,34 @@ func (u *Updater) fetchLatestRelease(ctx context.Context) (tag, name string, err
 	res, err := client.Do(req)
 	if err != nil {
 		if ctx.Err() != nil {
-			return "", "", "timeout"
+			return "", "", "", "timeout"
 		}
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	defer res.Body.Close()
 	if res.StatusCode == 401 || res.StatusCode == 403 || res.StatusCode == 404 {
 		if u.token != "" {
-			return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+			return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
 		}
-		return "", "", "no_token"
+		return "", "", "", "no_token"
 	}
 	if res.StatusCode != 200 {
-		return "", "", fmt.Sprintf("github_%d", res.StatusCode)
+		return "", "", "", fmt.Sprintf("github_%d", res.StatusCode)
 	}
 	var data struct {
 		TagName string `json:"tag_name"`
 		Name    string `json:"name"`
+		Body    string `json:"body"`
 	}
 	if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&data); err != nil {
-		return "", "", "network"
+		return "", "", "", "network"
 	}
 	tag = data.TagName
 	name = data.Name
 	if name == "" {
 		name = tag
 	}
-	return tag, name, ""
+	return tag, name, strings.TrimSpace(data.Body), ""
 }
 
 // compareSemver compara dos strings semver (con o sin prefijo "v").
@@ -291,20 +325,20 @@ func parseSemver(s string) [3]int {
 // rolling compara contra el último commit de main; en modo estable contra
 // el último release tag (semver).
 func (u *Updater) Check(ctx context.Context) Status {
-	var current, latest, latestMsg, errCode string
+	var current, latest, latestMsg, latestBody, errCode string
 
 	if u.mode == "stable" {
 		current = u.version
 		if current == "" {
 			current = "desconocido"
 		}
-		latest, latestMsg, errCode = u.fetchLatestRelease(ctx)
+		latest, latestMsg, latestBody, errCode = u.fetchLatestRelease(ctx)
 	} else {
 		current = gitShort(u.repoRoot)
 		if current == "" {
 			current = "desconocido"
 		}
-		latest, latestMsg, errCode = u.fetchLatestCommit(ctx)
+		latest, latestMsg, latestBody, errCode = u.fetchLatestCommit(ctx)
 	}
 
 	now := time.Now().UnixMilli()
@@ -320,6 +354,7 @@ func (u *Updater) Check(ctx context.Context) Status {
 	u.err = nil
 	u.latest = &latest
 	u.latestMsg = &latestMsg
+	u.latestBody = &latestBody
 	if u.mode == "stable" {
 		u.updateAvail = latest != "" && current != "desconocido" && compareSemver(latest, current) > 0
 	} else {
@@ -331,7 +366,47 @@ func (u *Updater) Check(ctx context.Context) Status {
 	return u.statusLocked()
 }
 
-var stepRe = regexp.MustCompile(`STEP:(\w+)`)
+var (
+	stepRe     = regexp.MustCompile(`STEP:(\w+)`)
+	progressRe = regexp.MustCompile(`PROGRESS:(\d{1,3})`)
+)
+
+// setStepLocked fija el paso activo y su porcentaje base (issue #280).
+func (u *Updater) setStepLocked(step string) {
+	u.updatingStep = &step
+	if w, ok := stepWeight[step]; ok {
+		u.updatingPct = w
+	} else {
+		u.updatingPct = stepDefaultWeight
+	}
+}
+
+// Subscribe registra un canal para recibir el Status en cada cambio del
+// update en curso (issue #280). El cancel devuelto lo retira.
+func (u *Updater) Subscribe() (<-chan Status, func()) {
+	ch := make(chan Status, 8)
+	u.mu.Lock()
+	u.subs[ch] = struct{}{}
+	u.mu.Unlock()
+	cancel := func() {
+		u.mu.Lock()
+		delete(u.subs, ch)
+		u.mu.Unlock()
+	}
+	return ch, cancel
+}
+
+// broadcastLocked emite el estado a todos los suscriptores sin bloquear
+// (un cliente lento pierde el evento; el siguiente lo corrige). Llamar con mu.
+func (u *Updater) broadcastLocked() {
+	st := u.statusLocked()
+	for ch := range u.subs {
+		select {
+		case ch <- st:
+		default:
+		}
+	}
+}
 
 // Apply lanza update.sh en segundo plano (iniciado manualmente desde la UI,
 // rol admin). Devuelve false si ya hay una actualización en curso (→ 409
@@ -348,9 +423,10 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 		u.mu.Unlock()
 		return false
 	}
-	startStep := "start"
-	u.updatingStep = &startStep
+	u.setStepLocked("start")
+	u.updatingPct = 0
 	u.updatingLog = ""
+	u.broadcastLocked()
 	u.mu.Unlock()
 
 	// Historial + marcador: version_from es el commit actual, version_to el
@@ -380,6 +456,7 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 		u.updatingStep = nil
 		code := "update_copy_failed"
 		u.err = &code
+		u.broadcastLocked()
 		u.mu.Unlock()
 		u.finishHistory(historyID, "failed", code, time.Since(startedAt))
 		fmt.Printf("[netpulse] no se pudo copiar update.sh: %v\n", err)
@@ -392,6 +469,7 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 	if err != nil {
 		u.mu.Lock()
 		u.updatingStep = nil
+		u.broadcastLocked()
 		u.mu.Unlock()
 		u.finishHistory(historyID, "failed", "update_pipe_failed", time.Since(startedAt))
 		return false
@@ -400,6 +478,7 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 	if err := cmd.Start(); err != nil {
 		u.mu.Lock()
 		u.updatingStep = nil
+		u.broadcastLocked()
 		u.mu.Unlock()
 		u.finishHistory(historyID, "failed", "update_start_failed", time.Since(startedAt))
 		return false
@@ -422,8 +501,7 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 		u.mu.Lock()
 		defer u.mu.Unlock()
 		if waitErr == nil {
-			step := "done"
-			u.updatingStep = &step
+			u.setStepLocked("done")
 			log := u.updatingLog
 			u.lastLog = &log
 			u.updateAvail = false
@@ -444,19 +522,47 @@ func (u *Updater) ApplyBy(initiatedBy string) bool {
 			// Issue #161: el apply falló → sin confirmación post-update.
 			u.clearPendingApply()
 		}
+		u.broadcastLocked()
 	}()
 	return true
 }
 
-// appendLog acumula el log (tail 4000) y extrae STEP:xxx del stdout.
+// appendLog acumula el log (tail 4000) y extrae STEP:xxx y PROGRESS:nn del
+// stdout. Solo hace broadcast cuando el paso o el porcentaje CAMBIAN (no en
+// cada línea de log) para no saturar el stream (issue #280).
 func (u *Updater) appendLog(text string, parseStep bool) {
 	u.mu.Lock()
 	defer u.mu.Unlock()
 	u.updatingLog = tail(u.updatingLog+text, logTail)
 	if parseStep {
+		before := ""
+		if u.updatingStep != nil {
+			before = *u.updatingStep
+		}
+		beforePct := u.updatingPct
 		if m := stepRe.FindStringSubmatch(text); m != nil {
-			step := m[1]
-			u.updatingStep = &step
+			u.setStepLocked(m[1])
+		}
+		if m := progressRe.FindStringSubmatch(text); m != nil && u.updatingStep != nil {
+			// El progreso explícito no puede bajar del peso del paso activo
+			// ni superar el 99 (done se reserva al final del script).
+			n, err := strconv.Atoi(m[1])
+			if err == nil {
+				if n < u.updatingPct {
+					n = u.updatingPct
+				}
+				if n > 99 {
+					n = 99
+				}
+				u.updatingPct = n
+			}
+		}
+		after := ""
+		if u.updatingStep != nil {
+			after = *u.updatingStep
+		}
+		if after != before || u.updatingPct != beforePct {
+			u.broadcastLocked()
 		}
 		fmt.Printf("[netpulse:update] %s\n", strings.TrimSpace(text))
 	}
@@ -490,7 +596,11 @@ func (u *Updater) Status() Status {
 func (u *Updater) statusLocked() Status {
 	var updating any = false
 	if u.updatingStep != nil {
-		updating = progress{Step: *u.updatingStep}
+		pct := u.updatingPct
+		if *u.updatingStep == "done" {
+			pct = 100
+		}
+		updating = progress{Step: *u.updatingStep, Progress: pct}
 	}
 	var lastLog *string
 	if u.updatingStep != nil {
@@ -504,6 +614,7 @@ func (u *Updater) statusLocked() Status {
 		Current:         u.current,
 		Latest:          u.latest,
 		LatestMsg:       u.latestMsg,
+		LatestBody:      u.latestBody,
 		UpdateAvailable: u.updateAvail,
 		CanApply:        u.canApply,
 		Mode:            u.mode,

+ 90 - 0
server-go/internal/updater/updater_test.go

@@ -50,6 +50,10 @@ func TestCheckUpdateAvailable(t *testing.T) {
 	if st.LatestMsg == nil || *st.LatestMsg != "feat: algo" {
 		t.Fatalf("latestMsg: %v", st.LatestMsg)
 	}
+	// Issue #280: el body del commit llega como changelog del asistente.
+	if st.LatestBody == nil || *st.LatestBody != "body" {
+		t.Fatalf("latestBody: %v", st.LatestBody)
+	}
 	if !st.UpdateAvailable {
 		t.Fatalf("debería haber update: %+v", st)
 	}
@@ -258,3 +262,89 @@ func TestCanApplyDetection(t *testing.T) {
 		t.Fatal("con deploy/update.sh debería ser rolling/canApply")
 	}
 }
+
+// Issue #280: pesos por paso, PROGRESS explícito (clamp) y shape del status.
+func TestProgressWeightsAndClamp(t *testing.T) {
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
+	pctOf := func() int {
+		t.Helper()
+		m, ok := u.Status().Updating.(progress)
+		if !ok {
+			t.Fatal("debería estar updating")
+		}
+		return m.Progress
+	}
+	u.appendLog("STEP:start\n", true)
+	if p := pctOf(); p != stepWeight["start"] {
+		t.Fatalf("start: %d", p)
+	}
+	u.appendLog("STEP:fetch\n", true)
+	if p := pctOf(); p != stepWeight["fetch"] {
+		t.Fatalf("fetch: %d", p)
+	}
+	u.appendLog("STEP:download\n", true)
+	if p := pctOf(); p != stepWeight["download"] {
+		t.Fatalf("download: %d", p)
+	}
+	// PROGRESS por debajo del peso del paso no retrocede.
+	u.appendLog("PROGRESS:5\n", true)
+	if p := pctOf(); p != stepWeight["download"] {
+		t.Fatalf("progreso no puede bajar del peso: %d", p)
+	}
+	// PROGRESS dentro del paso avanza.
+	u.appendLog("PROGRESS:55\n", true)
+	if p := pctOf(); p != 55 {
+		t.Fatalf("55: %d", p)
+	}
+	// PROGRESS absurdo se recorta a 99 (100 solo con done).
+	u.appendLog("PROGRESS:150\n", true)
+	if p := pctOf(); p != 99 {
+		t.Fatalf("150 → 99: %d", p)
+	}
+	// done siempre 100.
+	u.appendLog("STEP:done\n", true)
+	if p := pctOf(); p != 100 {
+		t.Fatalf("done: %d", p)
+	}
+	// Paso legado (script viejo) sin PROGRESS: peso por defecto del mapa.
+	u.appendLog("STEP:binary\n", true)
+	if p := pctOf(); p != stepWeight["binary"] {
+		t.Fatalf("binary legado: %d", p)
+	}
+}
+
+// Issue #280: el broadcaster notifica cambios de paso y el cancel retira.
+func TestSubscribeBroadcast(t *testing.T) {
+	u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
+	ch, cancel := u.Subscribe()
+	defer cancel()
+	u.appendLog("STEP:download\n", true)
+	select {
+	case st := <-ch:
+		m, ok := st.Updating.(progress)
+		if !ok || m.Step != "download" || m.Progress != stepWeight["download"] {
+			t.Fatalf("evento: %+v", st.Updating)
+		}
+	case <-time.After(2 * time.Second):
+		t.Fatal("sin evento tras STEP")
+	}
+	// Un segundo evento (cambio de pct) y luego la baja no bloquea.
+	u.appendLog("PROGRESS:50\n", true)
+	select {
+	case st := <-ch:
+		m, _ := st.Updating.(progress)
+		if m.Progress != 50 {
+			t.Fatalf("progreso: %d", m.Progress)
+		}
+	case <-time.After(2 * time.Second):
+		t.Fatal("sin evento tras PROGRESS")
+	}
+	cancel()
+	// Tras cancel, broadcast no entrega ni bloquea.
+	u.appendLog("STEP:verify\n", true)
+	select {
+	case <-ch:
+		t.Fatal("no debería llegar tras cancel")
+	default:
+	}
+}