Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Preserve backup-age incidents across unknown success dates
pulse-triage[bot]208f0cbf1e74
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 0c9cd7247b..d43854cb27 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -15,6 +15,25 @@## Purpose+### Listed backups need an observed success date to resolve age warnings++The backup-age evaluator retains an existing subject's occurrence, severity,+acknowledgement and last trusted evidence when its still-listed rollup has no+success date, a zero date or a future date. Such a date supplies neither a new+age nor recovery. For multiple provider rollups of one subject, the newest+usable success date wins regardless of input order; an unobserved date cannot+hide an older valid breach or displace a valid recent recovery. A fresh valid+date still recovers normally. Explicit policy exclusions, disabled rules and+removal from the supplied complete inventory keep their existing semantics.++`TestCheckBackupsRequiresObservedSuccessDates` exercises the real manager with+PVE/PBS linked guests, PBS orphans and PMG subjects, occurrence/event retention,+provider ordering, same-VMID cross-instance isolation and policy/removal controls.+Its opt-in browser frames come from `CheckBackups` and `GetActiveAlerts`.+This is age-evidence handling only: no change to backup execution, source+inventory readiness, snapshot alerts, native freeze/thaw safety or notification+delivery, and no proof of a reported installation's recovery.+### Legacy alert-history compaction releases removed-row storageExpiry, duplicate-occurrence compaction and ID removal allocate backing storagediff --git a/frontend-modern/browser-tests/backup-date-observation.html b/frontend-modern/browser-tests/backup-date-observation.htmlnew file mode 100644index 0000000000..a826e7d6ee--- /dev/null+++ b/frontend-modern/browser-tests/backup-date-observation.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Backup-age observation evidence</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/browser-tests/backup-date-observation.tsx"></script>+ </body>+</html>diff --git a/frontend-modern/browser-tests/backup-date-observation.tsx b/frontend-modern/browser-tests/backup-date-observation.tsxnew file mode 100644index 0000000000..b3c474a862--- /dev/null+++ b/frontend-modern/browser-tests/backup-date-observation.tsx@@ -0,0 +1,60 @@+// Real active-alert adapter and Overview, fed only by the Go manager's frames.+import { createSignal, onMount } from 'solid-js';+import { render } from 'solid-js/web';+import { Route, Router } from '@solidjs/router';+import { AlertsAPI } from '../src/api/alerts';+import { OverviewTab } from '../src/features/alerts/OverviewTab';+import { DarkModeContext } from '../src/contexts/appRuntime';+import { syncAIRuntimeSettings } from '../src/stores/aiRuntimeState';+import type { Alert } from '../src/types/api';+import '../src/index.css';++syncAIRuntimeSettings({ discovery_enabled: false });++function Fixture() {+ const [active, setActive] = createSignal<Record<string, Alert>>({});+ const [showAcknowledged, setShowAcknowledged] = createSignal(true);+ const [generation, setGeneration] = createSignal(0);+ const reload = async () => {+ const alerts = await AlertsAPI.getActive();+ setActive(Object.fromEntries(alerts.map((alert) => [alert.id, alert])));+ setGeneration((value) => value + 1);+ };+ onMount(() => void reload());+ Object.assign(window, { __backupDate: { reload, active, generation } });+ return (+ <main class="mx-auto min-h-screen max-w-5xl space-y-4 bg-surface p-3 text-base-content">+ <h1 class="text-base font-semibold">Backup-age observations</h1>+ <p class="text-xs text-muted">Synthetic monitoring evidence. No backup or guest operation.</p>+ <button+ class="min-h-11 rounded-sm border border-border px-3 text-sm"+ onClick={() => void reload()}+ >+ Refresh monitoring evidence+ </button>+ <OverviewTab+ overrides={[]}+ activeAlerts={active()}+ updateAlert={(id, updates) =>+ setActive((previous) => ({ ...previous, [id]: { ...previous[id], ...updates } }))+ }+ showQuickTip={() => false}+ dismissQuickTip={() => {}}+ showAcknowledged={showAcknowledged}+ setShowAcknowledged={setShowAcknowledged}+ alertsDisabled={() => false}+ />+ </main>+ );+}++render(+ () => (+ <DarkModeContext.Provider value={() => document.documentElement.classList.contains('dark')}>+ <Router>+ <Route path="*" component={Fixture} />+ </Router>+ </DarkModeContext.Provider>+ ),+ document.getElementById('root')!,+);diff --git a/frontend-modern/browser-tests/build-backup-date-observation.mjs b/frontend-modern/browser-tests/build-backup-date-observation.mjsnew file mode 100644index 0000000000..6312d2e5fb--- /dev/null+++ b/frontend-modern/browser-tests/build-backup-date-observation.mjs@@ -0,0 +1,70 @@+// Compile the production consumer outside the bounded browser process tree.+import { build } from 'vite';+import solid from 'vite-plugin-solid';+import tailwindcss from '@tailwindcss/vite';+import { stop } from 'esbuild';+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';+import { fileURLToPath } from 'node:url';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const outDir = path.resolve(root, '../tmp/backup-date-static');+const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');+const sources = {};+const artifacts = {};++try {+ await build({+ root,+ base: '/',+ configFile: false,+ publicDir: false,+ resolve: { alias: { '@': path.join(root, 'src') } },+ plugins: [+ {+ name: 'bind-backup-date-consumer',+ generateBundle() {+ for (const id of this.getModuleIds()) {+ const file = id.split('?')[0];+ if (+ file.startsWith(root + '/') &&+ !file.includes('/node_modules/') &&+ fs.existsSync(file) &&+ fs.statSync(file).isFile()+ ) {+ sources[path.relative(root, file)] = hash(fs.readFileSync(file));+ }+ }+ },+ },+ tailwindcss(),+ solid(),+ ],+ build: {+ target: 'esnext',+ outDir,+ emptyOutDir: true,+ rollupOptions: { input: path.join(root, 'browser-tests/backup-date-observation.html') },+ },+ });+ const walk = (dir) => {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const file = path.join(dir, entry.name);+ if (entry.isDirectory()) walk(file);+ else artifacts[path.relative(outDir, file)] = hash(fs.readFileSync(file));+ }+ };+ walk(outDir);+ fs.writeFileSync(+ path.join(outDir, 'binding.json'),+ JSON.stringify({+ graph: hash(fs.readFileSync(path.join(root, 'package-lock.json'))),+ builder: hash(fs.readFileSync(fileURLToPath(import.meta.url))),+ sources,+ artifacts,+ }, null, 2) + '\n',+ );+} finally {+ stop();+}diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex a2bb13d132..a78ad933bd 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -1699,6 +1699,10 @@ func TestCheckSnapshotsForInstanceIncludesAgeAndSizeReasons(t *testing.T) {}}+func TestCheckBackupsRequiresObservedSuccessDates(t *testing.T) {+ testBackupDateObservations(t)+}+func TestCheckBackupsCreatesAndClearsAlerts(t *testing.T) {m := newTestManager(t)m.ClearActiveAlerts()diff --git a/internal/alerts/backup_date_observation_test.go b/internal/alerts/backup_date_observation_test.gonew file mode 100644index 0000000000..2620171845--- /dev/null+++ b/internal/alerts/backup_date_observation_test.go@@ -0,0 +1,227 @@+package alerts++import (+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts/eventlog"+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"+)++func backupDateManager(t *testing.T) *Manager {+ t.Helper()+ m := newEventLogManager(t)+ cfg := m.GetConfig()+ cfg.BackupDefaults = BackupAlertConfig{Enabled: true, WarningDays: 7, CriticalDays: 14}+ cfg.TimeThresholds = map[string]int{}+ m.UpdateConfig(cfg)+ return m+}++func backupDateFixture(kind string) (recovery.ProtectionRollup, map[string]GuestLookup, map[string][]GuestLookup) {+ r := recovery.ProtectionRollup{RollupID: "res:date-" + kind,+ LastSuccessAt: ptrTime(time.Now().Add(-16 * 24 * time.Hour)), LastOutcome: recovery.OutcomeSuccess,+ SubjectRef: &recovery.ExternalRef{Type: "proxmox-vm", ID: "east:pve:101", Namespace: "east", Name: "database", Class: "pve"},+ Providers: []recovery.Provider{recovery.ProviderProxmoxPVE}}+ guest := GuestLookup{ResourceID: "east:pve:101", Name: "database", Instance: "east", Node: "pve", VMID: 101, Type: "qemu"}+ guests := map[string]GuestLookup{guest.ResourceID: guest}+ byVMID := map[string][]GuestLookup{"101": {guest}}+ switch kind {+ case "pbs":+ r.Providers = []recovery.Provider{recovery.ProviderProxmoxPBS}+ case "orphan":+ r.Providers = []recovery.Provider{recovery.ProviderProxmoxPBS}+ r.SubjectRef.ID, r.SubjectRef.Namespace, r.SubjectRef.Name = "404", "pbs", "orphan-404"+ guests, byVMID = nil, nil+ case "pmg":+ r.Providers = []recovery.Provider{recovery.ProviderProxmoxPMG}+ r.SubjectRef = &recovery.ExternalRef{Type: "pmg", ID: "mail", Name: "mail-gateway"}+ guests, byVMID = nil, nil+ }+ return r, guests, byVMID+}++func backupDateJSON(t *testing.T, value any) []byte {+ t.Helper()+ data, err := json.Marshal(value)+ if err != nil {+ t.Fatal(err)+ }+ return data+}++func testBackupDateObservations(t *testing.T) {+ invalid := map[string]*time.Time{+ "missing": nil, "zero": ptrTime(time.Time{}), "future": ptrTime(time.Now().Add(24 * time.Hour)),+ }+ for _, kind := range []string{"pve", "pbs", "orphan", "pmg"} {+ for label, date := range invalid {+ t.Run(kind+"/"+label, func(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture(kind)+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ active := m.GetActiveAlerts()+ if len(active) != 1 || active[0].Level != AlertLevelCritical {+ t.Fatalf("stale observation must establish one critical incident: %+v", active)+ }+ id := active[0].ID+ if err := m.AcknowledgeAlert(id, "operator"); err != nil {+ t.Fatal(err)+ }+ before := backupDateJSON(t, m.GetActiveAlerts())+ r.LastSuccessAt = date+ for range 4 {+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ }+ if after := backupDateJSON(t, m.GetActiveAlerts()); !bytes.Equal(before, after) {+ t.Fatalf("unknown date changed occurrence/evidence/acknowledgement: before=%s after=%s", before, after)+ }+ if got := len(queryAlertEvents(t, m, eventlog.Filter{Types: []string{eventlog.TypeFired, eventlog.TypeRefired, eventlog.TypeResolved}})); got != 1 {+ t.Fatalf("unknown date invented a lifecycle transition: events=%d", got)+ }+ r.LastSuccessAt = ptrTime(time.Now().Add(-time.Hour))+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ if len(m.GetActiveAlerts()) != 0 || len(queryAlertEvents(t, m, eventlog.Filter{Types: []string{eventlog.TypeResolved}})) != 1 {+ t.Fatal("valid recent success must still resolve exactly once")+ }+ })+ }+ }++ t.Run("never-observed-does-not-fire", func(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture("pve")+ for _, date := range invalid {+ r.LastSuccessAt = date+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ }+ if len(m.GetActiveAlerts()) != 0 || len(queryAlertEvents(t, m, eventlog.Filter{Types: []string{eventlog.TypeFired, eventlog.TypeResolved}})) != 0 {+ t.Fatal("an unobserved date cannot establish age or recovery")+ }+ })++ for _, recent := range []bool{false, true} {+ for label, date := range invalid {+ for _, reverse := range []bool{false, true} {+ t.Run(fmt.Sprintf("multiple-providers/recent=%t/%s/reverse=%t", recent, label, reverse), func(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture("pve")+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ other := r+ other.RollupID, other.LastSuccessAt, other.Providers = "res:other-provider", date, []recovery.Provider{recovery.ProviderProxmoxPBS}+ if recent {+ r.LastSuccessAt = ptrTime(time.Now().Add(-time.Hour))+ }+ rollups := []recovery.ProtectionRollup{r, other}+ if reverse {+ rollups[0], rollups[1] = rollups[1], rollups[0]+ }+ m.CheckBackups(rollups, guests, byVMID)+ want := 1+ if recent {+ want = 0+ }+ if got := len(m.GetActiveAlerts()); got != want {+ t.Fatalf("invalid provider displaced the valid observation: active=%d want=%d", got, want)+ }+ })+ }+ }+ }++ for _, policy := range []string{"global-disabled", "guest-disabled", "backup-disabled", "ignored-vmid", "no-alerts-tag", "removed"} {+ t.Run("explicit-policy/"+policy, func(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture("pve")+ rollups := []recovery.ProtectionRollup{r}+ m.CheckBackups(rollups, guests, byVMID)+ if len(m.GetActiveAlerts()) != 1 {+ t.Fatal("control must start with a firing incident")+ }+ rollups[0].LastSuccessAt = nil+ cfg := m.GetConfig()+ switch policy {+ case "global-disabled":+ cfg.Enabled = false+ case "guest-disabled":+ cfg.Overrides = map[string]ThresholdConfig{"east:pve:101": {Disabled: true}}+ case "backup-disabled":+ cfg.BackupDefaults.Enabled = false+ case "ignored-vmid":+ cfg.BackupDefaults.IgnoreVMIDs = []string{"101"}+ case "no-alerts-tag":+ g := guests["east:pve:101"]+ g.Tags = []string{"pulse-no-alerts"}+ guests[g.ResourceID], byVMID["101"] = g, []GuestLookup{g}+ case "removed":+ rollups = nil+ }+ m.UpdateConfig(cfg)+ m.CheckBackups(rollups, guests, byVMID)+ if len(m.GetActiveAlerts()) != 0 {+ t.Fatal("missing date overrode explicit disablement, exclusion or authoritative removal")+ }+ })+ }++ t.Run("same-vmid-other-instance-recovers", func(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture("pve")+ other := r+ other.RollupID, other.SubjectRef = "res:west", &recovery.ExternalRef{Type: "proxmox-vm", ID: "west:pve:101", Name: "west-database", Namespace: "west", Class: "pve"}+ g := guests["east:pve:101"]+ g.ResourceID, g.Name, g.Instance = "west:pve:101", "west-database", "west"+ guests[g.ResourceID] = g+ byVMID["101"] = append(byVMID["101"], g)+ m.CheckBackups([]recovery.ProtectionRollup{r, other}, guests, byVMID)+ if len(m.GetActiveAlerts()) != 2 {+ t.Fatal("both instances must first establish independent incidents")+ }+ r.LastSuccessAt, other.LastSuccessAt = nil, ptrTime(time.Now().Add(-time.Hour))+ m.CheckBackups([]recovery.ProtectionRollup{r, other}, guests, byVMID)+ active := m.GetActiveAlerts()+ if len(active) != 1 || active[0].ResourceID != "east:pve:101" {+ t.Fatalf("unknown date prevented an independent recovery or leaked across instances: %+v", active)+ }+ })++ t.Run("browser-producer", testBackupDateBrowserProducer)+}++// The browser consumes these actual CheckBackups/GetActiveAlerts results, not+// independently invented alert props. Opt-in emission keeps normal CI concise.+func testBackupDateBrowserProducer(t *testing.T) {+ m := backupDateManager(t)+ r, guests, byVMID := backupDateFixture("pve")+ frames := map[string]json.RawMessage{}+ for _, phase := range []string{"stale", "missing", "future", "recovered"} {+ switch phase {+ case "missing":+ r.LastSuccessAt = nil+ case "future":+ r.LastSuccessAt = ptrTime(time.Now().Add(24 * time.Hour))+ case "recovered":+ r.LastSuccessAt = ptrTime(time.Now().Add(-time.Hour))+ }+ m.CheckBackups([]recovery.ProtectionRollup{r}, guests, byVMID)+ frames[phase] = backupDateJSON(t, m.GetActiveAlerts())+ want := 1+ if phase == "recovered" {+ want = 0+ }+ if len(m.GetActiveAlerts()) != want {+ t.Fatalf("phase %s: want %d active alerts", phase, want)+ }+ }+ if !bytes.Equal(frames["stale"], frames["missing"]) || !bytes.Equal(frames["stale"], frames["future"]) {+ t.Fatal("browser frames changed the retained occurrence across a date gap")+ }+ if os.Getenv("PULSE_BACKUP_DATE_FRAMES") == "1" {+ fmt.Printf("BACKUP_DATE_FRAMES=%s\n", backupDateJSON(t, frames))+ }+}diff --git a/internal/alerts/backup_snapshot.go b/internal/alerts/backup_snapshot.goindex c43c9f5714..ddd92e21a7 100644--- a/internal/alerts/backup_snapshot.go+++ b/internal/alerts/backup_snapshot.go@@ -184,6 +184,13 @@ type backupRecord struct {lastTime time.Time}+// A listed subject without a usable success date is not evidence of recovery.+// Future dates already cannot supply a backup age; they must not displace a+// valid observation from another provider for the same subject either.+func observedBackupTime(at, now time.Time) bool {+ return !at.IsZero() && !at.After(now)+}+// BackupInventoryScope carries monitoring-owned inventory readiness into backup// alert evaluation. It keeps orphan detection from racing ahead of Proxmox// guest/template discovery while preserving the direct CheckBackups API for@@ -665,6 +672,7 @@ func (m *Manager) CheckBackupsWithInventory(return}+ now := time.Now()records := make(map[string]*backupRecord)updateRecord := func(key string, candidate backupRecord) {@@ -672,7 +680,8 @@ func (m *Manager) CheckBackupsWithInventory(return}if existing, ok := records[key]; ok {- if candidate.lastTime.After(existing.lastTime) {+ if observedBackupTime(candidate.lastTime, now) &&+ (!observedBackupTime(existing.lastTime, now) || candidate.lastTime.After(existing.lastTime)) {*existing = candidate}return@@ -681,14 +690,12 @@ func (m *Manager) CheckBackupsWithInventory(records[key] = &record}- now := time.Now()-for _, rollup := range rollups {- if rollup.LastSuccessAt == nil || rollup.LastSuccessAt.IsZero() {- continue+ var lastTime time.Time+ if rollup.LastSuccessAt != nil {+ lastTime = rollup.LastSuccessAt.UTC()}- lastTime := rollup.LastSuccessAt.UTC()providers := append([]recovery.Provider(nil), rollup.Providers...)source := "Recovery"@@ -848,17 +855,6 @@ func (m *Manager) CheckBackupsWithInventory(validAlerts := make(map[string]struct{})for key, record := range records {- age := now.Sub(record.lastTime)- if age < 0 {- continue- }-- ageDays := age.Hours() / 24- if ageDays < 0 {- continue- }- ageDaysRounded := math.Round(ageDays*10) / 10-// A PBS subject without a guest VMID is a host/config backup// (PBS backup-type "host", keyed by the node name), not a guest// workload. The Backups overview already keeps these out of guest@@ -917,6 +913,23 @@ func (m *Manager) CheckBackupsWithInventory(continue}+ if !observedBackupTime(record.lastTime, now) {+ // Preserve only this subject's occurrence and last trusted evidence.+ // Policy exclusions above still clear normally; disappearance from+ // the supplied inventory remains authoritative removal below.+ resourceID := canonicalBackupSubjectResourceID(sanitizeAlertKey(key), *record)+ specID := resourceID + "-backup-age"+ validAlerts[buildCanonicalStateID(resourceID, specID)] = struct{}{}+ m.mu.Lock()+ for _, state := range m.mirrorStatesNoLock() {+ state.InterruptDiscreteRun(resourceID, specID)+ }+ m.mu.Unlock()+ continue+ }++ ageDays := now.Sub(record.lastTime).Hours() / 24+ ageDaysRounded := math.Round(ageDays*10) / 10var threshold intswitch {case currentBackupCfg.CriticalDays > 0 && ageDays >= float64(currentBackupCfg.CriticalDays):diff --git a/scripts/check-backup-date-observation.cjs b/scripts/check-backup-date-observation.cjsnew file mode 100644index 0000000000..09651f2a16--- /dev/null+++ b/scripts/check-backup-date-observation.cjs@@ -0,0 +1,141 @@+// Run from the assigned root with pulse-worker-browser. No external services.+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const http = require('node:http');+const crypto = require('node:crypto');+const { chromium, webkit } = require('playwright');++const root = '/workspace';+const compiled = path.join(root, 'tmp/backup-date-static');+const output = path.join(root, 'tmp/backup-date-browser');+const origin = 'http://127.0.0.1:5371';+const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');+const binding = JSON.parse(fs.readFileSync(path.join(compiled, 'binding.json')));+const producer = JSON.parse(fs.readFileSync(path.join(root, 'tmp/backup-date-producer.json')));+const frames = producer.frames;+const result = {+ result: 'incomplete',+ base: 'c67f8bd5002084fb4d75773893f85a448bf08534',+ producer,+ consumer: binding,+ harness: hash(fs.readFileSync(__filename)),+ playwright: require('playwright/package.json').version,+ cases: [],+ requests: [],+ captures: [],+ cleanup: { browser: false, server: false },+ limits: 'Real CheckBackups/GetActiveAlerts -> AlertsAPI -> Overview/card; synthetic rollups only. No installed recovery, guest action, backup execution, notification delivery or reporter acceptance.',+};+let server;+let browser;++(async () => {+ fs.mkdirSync(output, { recursive: true });+ assert.equal(result.playwright, JSON.parse(fs.readFileSync(path.join(root, 'tests/integration/package-lock.json'))).packages['node_modules/@playwright/test'].version);+ assert.equal(binding.graph, hash(fs.readFileSync(path.join(root, 'frontend-modern/package-lock.json'))));+ assert.equal(binding.builder, hash(fs.readFileSync(path.join(root, 'frontend-modern/browser-tests/build-backup-date-observation.mjs'))));+ assert.equal(producer.runtime_sha256, hash(fs.readFileSync(path.join(root, 'internal/alerts/backup_snapshot.go'))));+ assert.deepEqual(frames.stale, frames.missing);+ assert.deepEqual(frames.stale, frames.future);+ assert.equal(frames.stale.length, 1);+ assert.deepEqual(frames.recovered, []);+ for (const [file, digest] of Object.entries(binding.sources)) {+ assert.equal(hash(fs.readFileSync(path.join(root, 'frontend-modern', file))), digest, file);+ }+ for (const file of ['src/api/alerts.ts', 'src/features/alerts/OverviewTab.tsx', 'src/features/alerts/AlertOverviewAlertCard.tsx']) {+ assert(binding.sources[file], `real consumer not compiled: ${file}`);+ }+ const assets = new Map();+ for (const [file, digest] of Object.entries(binding.artifacts)) {+ const bytes = fs.readFileSync(path.join(compiled, file));+ assert.equal(hash(bytes), digest, file);+ assets.set('/' + file, bytes);+ }+ server = http.createServer((request, response) => {+ const pathname = new URL(request.url, origin).pathname;+ const bytes = assets.get(pathname);+ if (!bytes || request.method !== 'GET') {+ response.writeHead(404).end();+ return;+ }+ response.writeHead(200, { 'Content-Type': { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css' }[path.extname(pathname)] || 'application/octet-stream' });+ response.end(bytes);+ });+ await new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(5371, '127.0.0.1', resolve);+ });+ for (const [name, engine, width, height] of [+ ['desktop', chromium, 1280, 900],+ ['narrow', webkit, 320, 812],+ ]) {+ browser = await engine.launch(engine === chromium ? { headless: true, channel: 'chromium', args: ['--no-sandbox'] } : { headless: true });+ const page = await browser.newPage({ viewport: { width, height }, isMobile: width < 768, hasTouch: width < 768, locale: 'en-GB', timezoneId: 'UTC' });+ page.setDefaultTimeout(10000);+ const record = { name, width, height, browser: browser.version(), errors: [], phases: [] };+ page.on('pageerror', (error) => record.errors.push(error.message));+ let phase = 'stale';+ await page.route('**/*', async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ assert.equal(url.origin, origin, 'external request');+ assert.equal(request.method(), 'GET', 'unexpected mutation');+ if (!url.pathname.startsWith('/api/')) return route.continue();+ result.requests.push({ viewport: name, phase, path: url.pathname });+ let body;+ if (url.pathname === '/api/alerts/active') body = frames[phase];+ else if (url.pathname === '/api/alerts/delivery-diagnosis') body = [];+ else if (url.pathname === '/api/notifications/health') body = { queue: { status: 'unavailable' } };+ else if (url.pathname === '/api/alerts/incidents') body = null;+ else throw new Error(`unexpected API read: ${url.pathname}`);+ return route.fulfill({ json: body });+ });+ await page.goto(origin + '/browser-tests/backup-date-observation.html');+ await page.waitForFunction(() => window.__backupDate?.generation() === 1);+ for (phase of ['stale', 'missing', 'future', 'recovered']) {+ if (phase !== 'stale') {+ const previous = await page.evaluate(() => window.__backupDate.generation());+ await page.getByRole('button', { name: 'Refresh monitoring evidence', exact: true }).click();+ await page.waitForFunction((generation) => window.__backupDate.generation() > generation, previous);+ }+ const active = await page.evaluate(() => Object.values(window.__backupDate.active()));+ assert.deepEqual(active, frames[phase], `producer/consumer mismatch in ${name}/${phase}`);+ if (phase !== 'recovered') {+ await page.getByText(frames.stale[0].message, { exact: true }).waitFor();+ const more = page.getByRole('button', { name: 'More', exact: true });+ if (await more.count()) {+ await more.click();+ await page.getByRole('button', { name: 'Less', exact: true }).click();+ }+ } else {+ assert.equal(await page.getByText(frames.stale[0].message, { exact: true }).count(), 0);+ }+ await page.evaluate(async () => {+ await document.fonts.ready;+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ });+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth);+ assert.equal(overflow, false, `${name}/${phase} horizontal overflow`);+ const capture = `${name}-${phase}.png`;+ await page.screenshot({ path: path.join(output, capture), fullPage: true });+ result.captures.push({ file: capture, sha256: hash(fs.readFileSync(path.join(output, capture))) });+ record.phases.push({ phase, active: active.length, overflow });+ }+ assert.deepEqual(record.errors, []);+ result.cases.push(record);+ await browser.close();+ browser = undefined;+ }+ result.result = 'passed';+})().catch((error) => {+ result.result = 'failed';+ result.error = String(error.stack || error);+ process.exitCode = 1;+}).finally(async () => {+ if (browser) await browser.close();+ result.cleanup.browser = true;+ if (server) await new Promise((resolve) => server.close(resolve));+ result.cleanup.server = true;+ fs.writeFileSync(path.join(output, 'result.json'), JSON.stringify(result, null, 2) + '\n');+});