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
Implement VMware alert history slice
rcourtmane0274b8e2ac6
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.mdindex 1b78ea1740..53f3f97af0 100644--- a/docs/release-control/v6/internal/subsystems/alerts.md+++ b/docs/release-control/v6/internal/subsystems/alerts.md@@ -498,3 +498,13 @@ canonical `agent` and `node` header boundary when reusing shared filterprimitives. Frontend alert tables may not drift back to ad hoc host-keygrouping or narrow filter key predicates that drop optional hostname valuesbefore alert group metadata is derived.+That same shared alert boundary now also owns provider-backed `resource-incident`+alerts beyond storage-only cases. `internal/alerts/alerts.go`,+`internal/alerts/unified_incidents.go`, and+`frontend-modern/src/utils/alertIncidentPresentation.ts` must treat VMware-+backed host and VM incidents as the same canonical `resource-incident`+vocabulary used everywhere else, with quiet-hours routing derived from the+shared incident category and provider context carried only as shared alert and+timeline metadata. Alert history may surface VMware alarm, task, and snapshot+context inside that shared model, but it must not fork into VMware-only alert+types, badges, or incident chrome.diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.mdindex 9cecc7f801..6c8602dbf3 100644--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md@@ -295,7 +295,12 @@ work extends shared components instead of creating new local variants.The frontend already has several guardrail tests. The next step is to keepturning repeated local patterns into explicit shared primitives with hard usage-bounds.+bounds, including provider-backed alert-history wording. `frontend-modern/src/features/alerts/helpers.ts`,+`frontend-modern/src/features/alerts/tabs/HistoryTab.tsx`, and+`frontend-modern/src/features/alerts/OverviewTab.tsx` must present VMware-+backed host and VM incidents with the shared `resource-incident` vocabulary+and existing alert-history shells instead of introducing VMware-only labels,+badges, or panel copy just because the underlying signal came from vSphere.The subsystem registry now also requires explicit proof-policy coverage for allshared runtime files, and shared-component guardrails fail if raw tablediff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex abb0679745..451228c8bc 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -398,3 +398,10 @@ poller/provider path also owns assistant-driven app start/stop, logs, andconfig refresh for those canonical workloads. Pulse does not promise aseparate TrueNAS runtime model, broader NAS administration, or agent-requiredbootstrap at this floor.+That same monitoring boundary now also owns VMware signal enrichment on the+canonical alert timeline. `internal/vmware/client_signals.go`,+`internal/vmware/provider.go`, and `internal/monitoring/monitor_alerts.go`+may collect VI JSON overall status, active alarms, recent tasks, and VM+snapshot counts, but they must project those reads onto shared canonical+resources plus shared alert/resource history metadata instead of persisting a+VMware-only signal cache, event log, or provider-specific incident timeline.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex 28869122d3..2421af0bbf 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -167,12 +167,19 @@ assembly branch.projections there before adding platform-local branches here, and runtimevariants such as `podman` must stay inside the owning platform contractinstead of becoming new top-level platforms or resource types.+8. Keep provider-backed signal metadata on shared canonical resource fields.+ VMware status, alarm, task, and snapshot signals must flow through shared+ `vmware` metadata plus shared `resource-incident` timeline entries on+ canonical `agent`, `vm`, and `storage` resources instead of creating+ provider-only resource kinds, identities, or history schemas.## Current StateThis subsystem now sits under the dedicated core monitoring runtime lane socanonical resource identity, discovery normalization, and platform-runtime-coverage stay governed as a first-class Pulse product surface.+coverage stay governed as a first-class Pulse product surface, including the+shared VMware signal-metadata and `resource-incident` timeline vocabulary that+canonical resources expose to alerts, AI, and frontend consumers.VMware vSphere now follows the same admission rule. If `vmware-vsphere`implementation starts, vCenter is the phase-1 connection authority but not atop-level unified resource: ESXi hosts must project as canonical `agent`diff --git a/frontend-modern/src/features/alerts/__tests__/helpers.test.ts b/frontend-modern/src/features/alerts/__tests__/helpers.test.tsindex c3dabbd147..8a7519a140 100644--- a/frontend-modern/src/features/alerts/__tests__/helpers.test.ts+++ b/frontend-modern/src/features/alerts/__tests__/helpers.test.ts@@ -195,6 +195,7 @@ describe('alerts helpers', () => {expect(alertTypeDisplayLabel('zfs-pool-errors')).toBe('Pool Errors');expect(alertTypeDisplayLabel('disk-health')).toBe('Disk Health');expect(alertTypeDisplayLabel('disk-wearout')).toBe('Disk Wearout');+ expect(alertTypeDisplayLabel('resource-incident')).toBe('Resource Health');});it('maps infrastructure alert types', () => {diff --git a/frontend-modern/src/features/alerts/helpers.ts b/frontend-modern/src/features/alerts/helpers.tsindex 35c4602039..658cf40fae 100644--- a/frontend-modern/src/features/alerts/helpers.ts+++ b/frontend-modern/src/features/alerts/helpers.ts@@ -310,6 +310,8 @@ export function alertTypeDisplayLabel(type: string): string {return 'Disk Wearout';case 'raid':return 'RAID';+ case 'resource-incident':+ return 'Resource Health';// Othercase 'pbs':diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.tsindex 01b2956e3a..bd46baa519 100644--- a/frontend-modern/src/types/__tests__/resource.test.ts+++ b/frontend-modern/src/types/__tests__/resource.test.ts@@ -11,6 +11,7 @@ import {getDiskPercent,type ResourceChangeKind,type ResourceProxmoxMeta,+ type ResourceVMwareMeta,type Resource,type ResourceType,} from '@/types/resource';@@ -105,6 +106,29 @@ describe('Resource Helper Functions', () => {});});+ describe('ResourceVMwareMeta', () => {+ it('accepts VMware signal metadata on canonical resources', () => {+ const vmware: ResourceVMwareMeta = {+ connectionId: 'vc-1',+ connectionName: 'Lab VC',+ vcenterHost: 'vc.lab.local',+ managedObjectId: 'vm-101',+ entityType: 'vm',+ overallStatus: 'yellow',+ activeAlarmCount: 2,+ activeAlarmSummary: 'CPU ready alarm; snapshot age warning',+ recentTaskCount: 1,+ recentTaskSummary: 'Clone VM task finished',+ snapshotCount: 3,+ };++ expect(vmware.overallStatus).toBe('yellow');+ expect(vmware.activeAlarmCount).toBe(2);+ expect(vmware.recentTaskSummary).toBe('Clone VM task finished');+ expect(vmware.snapshotCount).toBe(3);+ });+ });+describe('getPreferredResourceDisplayName', () => {it('returns displayName when set', () => {const resource = createResource({ name: 'machine-1', displayName: 'Production Server' });diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.tsindex 496f1cfeb0..4bfbd5d9e7 100644--- a/frontend-modern/src/types/resource.ts+++ b/frontend-modern/src/types/resource.ts@@ -410,9 +410,15 @@ export interface ResourceVMwareMeta {hostUuid?: string;connectionState?: string;powerState?: string;+ overallStatus?: string;cpuCount?: number;memorySizeMib?: number;datastoreType?: string;+ activeAlarmCount?: number;+ activeAlarmSummary?: string;+ recentTaskCount?: number;+ recentTaskSummary?: string;+ snapshotCount?: number;}/**diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.goindex 5d55366115..df3f1aa45b 100644--- a/internal/alerts/alerts.go+++ b/internal/alerts/alerts.go@@ -2424,6 +2424,11 @@ func quietHoursCategoryForAlert(alert *Alert) string {return "performance"case "usage", "disk-health", "disk-wearout", "zfs-pool-state", "zfs-pool-errors", "zfs-device", "storage-incident", "backup-storage-incident", "backup-posture-incident":return "storage"+ case "resource-incident":+ if metadataStringValue(alert.Metadata, "incidentCategory") == unifiedresources.IncidentCategoryAvailability {+ return "offline"+ }+ return "performance"case "connectivity", "offline", "powered-off", "docker-host-offline":return "offline"}@@ -7529,6 +7534,8 @@ func alertTypeSortRank(alert Alert) int {return 5case "storage-incident", "zfs-pool-state", "zfs-pool-errors":return 4+ case "resource-incident":+ return 4case "disk-health", "disk-wearout", "zfs-device":return 3case "offline", "connectivity", "powered-off", "docker-host-offline":@@ -7576,6 +7583,26 @@ func metadataIntValue(value interface{}) int {return 0}+func metadataStringValue(metadata map[string]interface{}, key string) string {+ if metadata == nil {+ return ""+ }+ value, ok := metadata[key]+ if !ok {+ return ""+ }+ switch v := value.(type) {+ case string:+ return strings.TrimSpace(v)+ case []byte:+ return strings.TrimSpace(string(v))+ case json.Number:+ return strings.TrimSpace(v.String())+ default:+ return strings.TrimSpace(fmt.Sprint(v))+ }+}+func metadataBoolValue(metadata map[string]interface{}, key string) bool {if metadata == nil {return falsediff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex 0b7a3142cb..d91fdc3799 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -16,6 +16,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/recovery""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/internal/utils""github.com/rcourtman/pulse-go-rewrite/pkg/proxmox")@@ -222,6 +223,28 @@ func TestCheckMetricClearsAlertWhenThresholdDisabled(t *testing.T) {}}+func TestQuietHoursCategoryForResourceIncidentUsesIncidentCategoryMetadata(t *testing.T) {+ availability := &Alert{+ Type: "resource-incident",+ Metadata: map[string]interface{}{+ "incidentCategory": unifiedresources.IncidentCategoryAvailability,+ },+ }+ if got := quietHoursCategoryForAlert(availability); got != "offline" {+ t.Fatalf("availability resource incident category = %q, want offline", got)+ }++ health := &Alert{+ Type: "resource-incident",+ Metadata: map[string]interface{}{+ "incidentCategory": unifiedresources.IncidentCategoryHealth,+ },+ }+ if got := quietHoursCategoryForAlert(health); got != "performance" {+ t.Fatalf("health resource incident category = %q, want performance", got)+ }+}+func TestCheckGuestSkipsAlertsWhenMetricDisabled(t *testing.T) {m := newTestManager(t)diff --git a/internal/alerts/unified_incidents.go b/internal/alerts/unified_incidents.goindex 593a56229b..3fdbc6d0b5 100644--- a/internal/alerts/unified_incidents.go+++ b/internal/alerts/unified_incidents.go@@ -228,6 +228,8 @@ func resourceSupportsUnifiedIncidentAlerts(resource unifiedresources.Resource) breturn truecase unifiedresources.ResourceTypeAgent:return len(resource.Incidents) > 0+ case unifiedresources.ResourceTypeVM:+ return len(resource.Incidents) > 0case unifiedresources.ResourceTypePBS:return len(resource.Incidents) > 0default:@@ -320,6 +322,8 @@ func unifiedIncidentInstance(resource unifiedresources.Resource) string {return "TrueNAS"case resource.PBS != nil:return "PBS"+ case resource.VMware != nil:+ return "VMware"case resource.Storage != nil && strings.TrimSpace(resource.Storage.Platform) != "":platform := strings.TrimSpace(resource.Storage.Platform)if platform == "" {@@ -351,7 +355,7 @@ func unifiedIncidentAlertType(resource unifiedresources.Resource, incident unifi}return "storage-incident"default:- return "storage-incident"+ return "resource-incident"}}@@ -716,6 +720,42 @@ func unifiedIncidentMetadata(resource unifiedresources.Resource, incident unifie}}+ if resource.VMware != nil {+ if connectionID := strings.TrimSpace(resource.VMware.ConnectionID); connectionID != "" {+ metadata["vmwareConnectionId"] = connectionID+ }+ if connectionName := strings.TrimSpace(resource.VMware.ConnectionName); connectionName != "" {+ metadata["vmwareConnectionName"] = connectionName+ }+ if vcenterHost := strings.TrimSpace(resource.VMware.VCenterHost); vcenterHost != "" {+ metadata["vmwareVcenterHost"] = vcenterHost+ }+ if entityType := strings.TrimSpace(resource.VMware.EntityType); entityType != "" {+ metadata["vmwareEntityType"] = entityType+ }+ if managedObjectID := strings.TrimSpace(resource.VMware.ManagedObjectID); managedObjectID != "" {+ metadata["vmwareManagedObjectId"] = managedObjectID+ }+ if overallStatus := strings.TrimSpace(resource.VMware.OverallStatus); overallStatus != "" {+ metadata["vmwareOverallStatus"] = overallStatus+ }+ if alarmCount := resource.VMware.ActiveAlarmCount; alarmCount > 0 {+ metadata["vmwareActiveAlarmCount"] = alarmCount+ }+ if summary := strings.TrimSpace(resource.VMware.ActiveAlarmSummary); summary != "" {+ metadata["vmwareActiveAlarmSummary"] = summary+ }+ if taskCount := resource.VMware.RecentTaskCount; taskCount > 0 {+ metadata["vmwareRecentTaskCount"] = taskCount+ }+ if summary := strings.TrimSpace(resource.VMware.RecentTaskSummary); summary != "" {+ metadata["vmwareRecentTaskSummary"] = summary+ }+ if snapshotCount := resource.VMware.SnapshotCount; snapshotCount > 0 {+ metadata["vmwareSnapshotCount"] = snapshotCount+ }+ }+return metadata}diff --git a/internal/alerts/unified_incidents_test.go b/internal/alerts/unified_incidents_test.goindex fbc67a5bc8..9417c1edf8 100644--- a/internal/alerts/unified_incidents_test.go+++ b/internal/alerts/unified_incidents_test.go@@ -142,6 +142,69 @@ func TestSyncUnifiedResourceIncidentsIncludesConsumerImpact(t *testing.T) {}}+func TestSyncUnifiedResourceIncidentsSupportsVMwareVMs(t *testing.T) {+ m := newTestManager(t)+ configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())++ resource := unifiedresources.Resource{+ ID: "vm:app-01",+ Type: unifiedresources.ResourceTypeVM,+ Name: "app-01",+ VMware: &unifiedresources.VMwareData{+ ConnectionID: "vc-1",+ ConnectionName: "Lab VC",+ VCenterHost: "vc.lab.local",+ EntityType: "vm",+ ManagedObjectID: "vm-201",+ OverallStatus: "red",+ ActiveAlarmCount: 1,+ ActiveAlarmSummary: "VM replication fault (red)",+ RecentTaskCount: 1,+ RecentTaskSummary: "Create snapshot (success)",+ SnapshotCount: 2,+ },+ Incidents: []unifiedresources.ResourceIncident{{+ Provider: "vmware",+ NativeID: "alarm-21",+ Code: "vmware_alarm_state",+ Severity: storagehealth.RiskCritical,+ Source: string(unifiedresources.SourceVMware),+ Summary: "VM vm-201 has VMware alarm VM replication fault (red)",+ }},+ }++ m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})++ alertID := unifiedIncidentAlertID(resource, resource.Incidents[0])+ assertAlertPresent(t, m, alertID)++ m.mu.RLock()+ alert := testRequireActiveAlert(t, m, alertID)+ m.mu.RUnlock()++ if alert.Type != "resource-incident" {+ t.Fatalf("alert type = %q, want resource-incident", alert.Type)+ }+ if alert.Message != "VM vm-201 has VMware alarm VM replication fault (red)" {+ t.Fatalf("message = %q", alert.Message)+ }+ if got := alert.Metadata["incidentLabel"]; got != "VM Health Issue" {+ t.Fatalf("incidentLabel = %v, want VM Health Issue", got)+ }+ if got := alert.Metadata["incidentAction"]; got != "Investigate resource health immediately" {+ t.Fatalf("incidentAction = %v, want Investigate resource health immediately", got)+ }+ if got := alert.Metadata["vmwareConnectionId"]; got != "vc-1" {+ t.Fatalf("vmwareConnectionId = %v, want vc-1", got)+ }+ if got := alert.Metadata["vmwareActiveAlarmSummary"]; got != "VM replication fault (red)" {+ t.Fatalf("vmwareActiveAlarmSummary = %v", got)+ }+ if got := alert.Metadata["vmwareSnapshotCount"]; got != 2 {+ t.Fatalf("vmwareSnapshotCount = %v, want 2", got)+ }+}+func TestSyncUnifiedResourceIncidentsMarksBackupTargetExposure(t *testing.T) {m := newTestManager(t)configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())diff --git a/internal/alerts/utility_test.go b/internal/alerts/utility_test.goindex 8f018ffffb..fa053aa548 100644--- a/internal/alerts/utility_test.go+++ b/internal/alerts/utility_test.go@@ -1326,6 +1326,26 @@ func TestQuietHoursCategoryForAlert(t *testing.T) {alert: &Alert{Type: "backup-posture-incident"},want: "storage",},+ {+ name: "resource-incident availability returns offline",+ alert: &Alert{+ Type: "resource-incident",+ Metadata: map[string]interface{}{+ "incidentCategory": "availability",+ },+ },+ want: "offline",+ },+ {+ name: "resource-incident health returns performance",+ alert: &Alert{+ Type: "resource-incident",+ Metadata: map[string]interface{}{+ "incidentCategory": "health",+ },+ },+ want: "performance",+ },// Offline metrics{diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 512007ca42..7aee09f6f5 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -130,6 +130,23 @@ func TestVMwarePollerUsesCanonicalSupplementalIngestOwnership(t *testing.T) {}}+func TestMonitorAlertTimelineWritesCanonicalAlertMetadata(t *testing.T) {+ data, err := os.ReadFile("monitor_alerts.go")+ if err != nil {+ t.Fatalf("failed to read monitor_alerts.go: %v", err)+ }+ source := string(data)+ requiredSnippets := []string{+ "change := unifiedresources.BuildAlertTimelineChange(",+ "AlertMetadata: alert.Metadata,",+ }+ for _, snippet := range requiredSnippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("monitor_alerts.go must contain %q", snippet)+ }+ }+}+func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {t.Parallel()diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.goindex 46409fe9fe..1df74f3d7d 100644--- a/internal/monitoring/monitor_alert_handling_test.go+++ b/internal/monitoring/monitor_alert_handling_test.go@@ -61,6 +61,10 @@ func TestMonitor_HandleAlertLifecycle_WritesCanonicalChanges(t *testing.T) {Threshold: 80,StartTime: startedAt,AckTime: &ackAt,+ Metadata: map[string]interface{}{+ "incidentCategory": "health",+ "vmwareConnectionId": "vc-1",+ },}m.handleAlertFired(alert)@@ -87,6 +91,12 @@ func TestMonitor_HandleAlertLifecycle_WritesCanonicalChanges(t *testing.T) {if got := changes[2].Metadata["alert_identifier"]; got != "alert-canonical-1" {t.Fatalf("alert_identifier = %#v, want alert-canonical-1", got)}+ if got := changes[2].Metadata["incidentCategory"]; got != "health" {+ t.Fatalf("incidentCategory = %#v, want health", got)+ }+ if got := changes[2].Metadata["vmwareConnectionId"]; got != "vc-1" {+ t.Fatalf("vmwareConnectionId = %#v, want vc-1", got)+ }}func TestMonitor_HandleAlertResolved_Detailed_Extra(t *testing.T) {diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.goindex eea65821a2..304f943c1c 100644--- a/internal/monitoring/monitor_alerts.go+++ b/internal/monitoring/monitor_alerts.go@@ -181,6 +181,7 @@ func (m *Monitor) recordAlertTimelineChange(alert *alerts.Alert, kind unifiedresAlertMessage: alert.Message,AlertValue: alert.Value,AlertThreshold: alert.Threshold,+ AlertMetadata: alert.Metadata,})if change == nil {returndiff --git a/internal/unifiedresources/adapter_coverage_test.go b/internal/unifiedresources/adapter_coverage_test.goindex 946207f0ec..9335b9e291 100644--- a/internal/unifiedresources/adapter_coverage_test.go+++ b/internal/unifiedresources/adapter_coverage_test.go@@ -6,6 +6,7 @@ import ("time""github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/storagehealth")func strPointer(v string) *string {@@ -453,6 +454,78 @@ func TestUnifiedAIAdapterGetTopByMetric(t *testing.T) {}}+func TestUnifiedAIAdapterIncludesVMwareCanonicalReadSurface(t *testing.T) {+ registry := testRegistry(+ Resource{+ ID: "vmware-host-1",+ Type: ResourceTypeAgent,+ Name: "esxi-01.lab.local",+ Status: StatusWarning,+ Sources: []DataSource{SourceVMware},+ VMware: &VMwareData{+ ConnectionID: "vc-1",+ EntityType: "host",+ ManagedObjectID: "host-101",+ OverallStatus: "yellow",+ ActiveAlarmCount: 1,+ ActiveAlarmSummary: "Host connection degraded (yellow)",+ },+ Incidents: []ResourceIncident{{+ Provider: "vmware",+ Code: "vmware_alarm_state",+ Severity: storagehealth.RiskWarning,+ Summary: "Host host-101 has VMware alarm Host connection degraded (yellow)",+ }},+ },+ Resource{+ ID: "vmware-vm-1",+ Type: ResourceTypeVM,+ Name: "app-01",+ Status: StatusWarning,+ Sources: []DataSource{SourceVMware},+ VMware: &VMwareData{+ ConnectionID: "vc-1",+ EntityType: "vm",+ ManagedObjectID: "vm-201",+ OverallStatus: "red",+ SnapshotCount: 2,+ RecentTaskSummary: "Create snapshot (success)",+ },+ },+ Resource{+ ID: "vmware-ds-1",+ Type: ResourceTypeStorage,+ Name: "nvme-primary",+ Status: StatusWarning,+ Sources: []DataSource{SourceVMware},+ VMware: &VMwareData{+ ConnectionID: "vc-1",+ EntityType: "datastore",+ ManagedObjectID: "datastore-11",+ OverallStatus: "yellow",+ RecentTaskSummary: "Refresh datastore (queued)",+ },+ },+ )++ adapter := NewUnifiedAIAdapter(registry)+ infrastructure := adapter.GetInfrastructure()+ if len(infrastructure) != 1 || infrastructure[0].ID != "vmware-host-1" {+ t.Fatalf("expected VMware host on infrastructure read path, got %#v", infrastructure)+ }+ workloads := adapter.GetWorkloads()+ if len(workloads) != 1 || workloads[0].ID != "vmware-vm-1" {+ t.Fatalf("expected VMware VM on workload read path, got %#v", workloads)+ }+ all := adapter.GetAll()+ if len(all) != 3 {+ t.Fatalf("expected all canonical VMware resources, got %d", len(all))+ }+ if all[0].VMware == nil && all[1].VMware == nil && all[2].VMware == nil {+ t.Fatal("expected VMware metadata on assistant read surface")+ }+}+func TestUnifiedAIAdapterGetRelated(t *testing.T) {registry := testRegistry(Resource{ID: "parent", Type: ResourceTypeAgent, Name: "parent-host"},diff --git a/internal/unifiedresources/canonical_identity_test.go b/internal/unifiedresources/canonical_identity_test.goindex 56dc426c00..3ab4d608d4 100644--- a/internal/unifiedresources/canonical_identity_test.go+++ b/internal/unifiedresources/canonical_identity_test.go@@ -241,6 +241,48 @@ func TestRefreshCanonicalIdentityIgnoresProxmoxPoolAsPlatformIdentity(t *testing}}+func TestRefreshCanonicalIdentityScopesVMwarePrimaryIDToConnection(t *testing.T) {+ resource := Resource{+ ID: "vm-1",+ Type: ResourceTypeVM,+ Name: "db-vm",+ VMware: &VMwareData{+ ConnectionID: "vc-1",+ ManagedObjectID: "vm-101",+ EntityType: "vm",+ HostUUID: "uuid-host-1",+ },+ Identity: ResourceIdentity{+ Hostnames: []string{"db-vm.lab.local"},+ },+ }++ RefreshCanonicalIdentity(&resource)++ if resource.Canonical == nil {+ t.Fatalf("expected canonical identity")+ }+ if got := resource.Canonical.PrimaryID; got != "vmware:vc-1:vm:vm-101" {+ t.Fatalf("primaryId = %q, want vmware:vc-1:vm:vm-101", got)+ }+ wantAliases := []string{+ "vmware:vc-1:vm:vm-101",+ "vm-101",+ "uuid-host-1",+ "db-vm",+ "db-vm.lab.local",+ "vm-1",+ }+ if len(resource.Canonical.Aliases) != len(wantAliases) {+ t.Fatalf("aliases len = %d, want %d (%v)", len(resource.Canonical.Aliases), len(wantAliases), resource.Canonical.Aliases)+ }+ for i, want := range wantAliases {+ if got := resource.Canonical.Aliases[i]; got != want {+ t.Fatalf("alias[%d] = %q, want %q", i, got, want)+ }+ }+}+func TestRefreshCanonicalIdentityScopesVMwareManagedObjectsByConnection(t *testing.T) {resource := Resource{ID: "vmware-host-1",diff --git a/internal/unifiedresources/change_presentation_test.go b/internal/unifiedresources/change_presentation_test.goindex 7727c65c4e..302805d775 100644--- a/internal/unifiedresources/change_presentation_test.go+++ b/internal/unifiedresources/change_presentation_test.go@@ -186,6 +186,10 @@ func TestBuildIncidentTimelineChanges(t *testing.T) {AlertMessage: "CPU normalized",AlertValue: 91.4,AlertThreshold: 80,+ AlertMetadata: map[string]any{+ "incidentCategory": "health",+ "canonicalSpecID": "alertspec:provider-incident:test",+ },})if alertChange == nil {t.Fatal("expected alert change")@@ -199,6 +203,12 @@ func TestBuildIncidentTimelineChanges(t *testing.T) {if got := alertChange.Metadata[MetadataAlertIdentifier]; got != "alert-1" {t.Fatalf("alert_identifier = %#v, want alert-1", got)}+ if got := alertChange.Metadata["incidentCategory"]; got != "health" {+ t.Fatalf("incidentCategory = %#v, want health", got)+ }+ if got := alertChange.Metadata["canonicalSpecID"]; got != "alertspec:provider-incident:test" {+ t.Fatalf("canonicalSpecID = %#v, want alertspec:provider-incident:test", got)+ }commandChange := BuildCommandExecutionChange("vm-1", "alert-1", "agent:pulse-assistant", "systemctl restart nginx", true, strings.Repeat("x", 700), map[string]any{"resource_type": "vm",diff --git a/internal/unifiedresources/incident_actions.go b/internal/unifiedresources/incident_actions.goindex b93ae9b4ff..edd350bbd4 100644--- a/internal/unifiedresources/incident_actions.go+++ b/internal/unifiedresources/incident_actions.go@@ -10,6 +10,7 @@ const ()func IncidentActionForResource(resource *Resource, incident ResourceIncident, category string) (string, string) {+ baseType := resourceBaseType(resource)switch category {case IncidentCategoryProtection:if incident.Severity == storagehealth.RiskCritical {@@ -37,11 +38,23 @@ func IncidentActionForResource(resource *Resource, incident ResourceIncident, ca}return IncidentUrgencyToday, "Investigate disk health and schedule replacement if degradation continues"case IncidentCategoryAvailability:+ if baseType == ResourceTypeAgent || baseType == ResourceTypeVM {+ if incident.Severity == storagehealth.RiskCritical {+ return IncidentUrgencyNow, "Restore resource availability immediately"+ }+ return IncidentUrgencyToday, "Investigate degraded resource availability"+ }if incident.Severity == storagehealth.RiskCritical {return IncidentUrgencyNow, "Restore storage availability immediately"}return IncidentUrgencyToday, "Investigate degraded storage availability"default:+ if baseType == ResourceTypeAgent || baseType == ResourceTypeVM {+ if incident.Severity == storagehealth.RiskCritical {+ return IncidentUrgencyToday, "Investigate resource health immediately"+ }+ return IncidentUrgencyPlan, "Review resource health and plan corrective action"+ }if incident.Severity == storagehealth.RiskCritical {return IncidentUrgencyToday, "Investigate storage health immediately"}diff --git a/internal/unifiedresources/incident_changes.go b/internal/unifiedresources/incident_changes.goindex bc065dfaf7..a31b112a02 100644--- a/internal/unifiedresources/incident_changes.go+++ b/internal/unifiedresources/incident_changes.go@@ -35,6 +35,7 @@ type AlertTimelineChange struct {AlertMessage stringAlertValue float64AlertThreshold float64+ AlertMetadata map[string]any}// BuildAlertTimelineChange constructs a canonical resource change for alert@@ -68,6 +69,12 @@ func BuildAlertTimelineChange(resourceID string, kind ChangeKind, occurredAt timMetadataAlertThreshold: alert.AlertThreshold,},}+ for key, value := range cloneChangeMetadata(alert.AlertMetadata) {+ if _, exists := change.Metadata[key]; exists {+ continue+ }+ change.Metadata[key] = value+ }if !occurredAt.IsZero() {change.OccurredAt = cloneTimePtr(&occurredAt)}diff --git a/internal/unifiedresources/incident_labels.go b/internal/unifiedresources/incident_labels.goindex cb03ebd3a9..5e64980e0c 100644--- a/internal/unifiedresources/incident_labels.go+++ b/internal/unifiedresources/incident_labels.go@@ -13,8 +13,29 @@ func IncidentLabelForResource(resource *Resource, incident ResourceIncident, catcase IncidentCategoryDiskHealth:return "Disk Health Risk"case IncidentCategoryAvailability:- return "Storage Availability Issue"+ switch resourceBaseType(resource) {+ case ResourceTypeAgent:+ return "Host Availability Issue"+ case ResourceTypeVM:+ return "VM Availability Issue"+ default:+ return "Availability Issue"+ }default:- return "Storage Health Issue"+ switch resourceBaseType(resource) {+ case ResourceTypeAgent:+ return "Host Health Issue"+ case ResourceTypeVM:+ return "VM Health Issue"+ default:+ return "Resource Health Issue"+ }}}++func resourceBaseType(resource *Resource) ResourceType {+ if resource == nil {+ return ""+ }+ return CanonicalResourceType(resource.Type)+}diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.goindex b986246d9c..4604ba2200 100644--- a/internal/unifiedresources/registry.go+++ b/internal/unifiedresources/registry.go@@ -1126,6 +1126,9 @@ func mergeVMwareData(existing *VMwareData, incoming *VMwareData) *VMwareData {if incoming.PowerState != "" {merged.PowerState = incoming.PowerState}+ if incoming.OverallStatus != "" {+ merged.OverallStatus = incoming.OverallStatus+ }if incoming.CPUCount > 0 {merged.CPUCount = incoming.CPUCount}@@ -1135,6 +1138,21 @@ func mergeVMwareData(existing *VMwareData, incoming *VMwareData) *VMwareData {if incoming.DatastoreType != "" {merged.DatastoreType = incoming.DatastoreType}+ if incoming.ActiveAlarmCount > 0 {+ merged.ActiveAlarmCount = incoming.ActiveAlarmCount+ }+ if incoming.ActiveAlarmSummary != "" {+ merged.ActiveAlarmSummary = incoming.ActiveAlarmSummary+ }+ if incoming.RecentTaskCount > 0 {+ merged.RecentTaskCount = incoming.RecentTaskCount+ }+ if incoming.RecentTaskSummary != "" {+ merged.RecentTaskSummary = incoming.RecentTaskSummary+ }+ if incoming.SnapshotCount > 0 {+ merged.SnapshotCount = incoming.SnapshotCount+ }return &merged}diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.goindex b4c0cebb26..e051bfa1c2 100644--- a/internal/unifiedresources/registry_test.go+++ b/internal/unifiedresources/registry_test.go@@ -201,6 +201,62 @@ func TestResourceRegistry_IngestsVMwareSourceAsCanonicalResources(t *testing.T)}}+func TestMergeVMwareDataMergesSignalFieldsWithoutDroppingExistingIdentity(t *testing.T) {+ existing := &VMwareData{+ ConnectionID: "vc-1",+ ConnectionName: "Lab VC",+ VCenterHost: "vc.lab.local",+ ManagedObjectID: "vm-101",+ EntityType: "vm",+ HostUUID: "uuid-host-1",+ ConnectionState: "connected",+ PowerState: "poweredOn",+ OverallStatus: "green",+ ActiveAlarmCount: 1,+ ActiveAlarmSummary: "old alarm",+ RecentTaskCount: 1,+ RecentTaskSummary: "old task",+ SnapshotCount: 1,+ }+ incoming := &VMwareData{+ OverallStatus: "yellow",+ ActiveAlarmCount: 3,+ ActiveAlarmSummary: "Host connection lost; datastore latency elevated",+ RecentTaskCount: 2,+ RecentTaskSummary: "vMotion task completed",+ SnapshotCount: 4,+ }++ merged := mergeVMwareData(existing, incoming)+ if merged == nil {+ t.Fatal("expected merged VMware metadata")+ }+ if got := merged.ConnectionID; got != "vc-1" {+ t.Fatalf("connection id = %q, want vc-1", got)+ }+ if got := merged.ManagedObjectID; got != "vm-101" {+ t.Fatalf("managed object id = %q, want vm-101", got)+ }+ if got := merged.OverallStatus; got != "yellow" {+ t.Fatalf("overall status = %q, want yellow", got)+ }+ if got := merged.ActiveAlarmCount; got != 3 {+ t.Fatalf("active alarm count = %d, want 3", got)+ }+ if got := merged.ActiveAlarmSummary; got != "Host connection lost; datastore latency elevated" {+ t.Fatalf("active alarm summary = %q", got)+ }+ if got := merged.RecentTaskCount; got != 2 {+ t.Fatalf("recent task count = %d, want 2", got)+ }+ if got := merged.RecentTaskSummary; got != "vMotion task completed" {+ t.Fatalf("recent task summary = %q", got)+ }+ if got := merged.SnapshotCount; got != 4 {+ t.Fatalf("snapshot count = %d, want 4", got)+ }+}+func TestResourceRegistryClonesCarryPolicyMetadata(t *testing.T) {rr := NewRegistry(nil)now := time.Date(2026, 3, 17, 12, 0, 0, 0, time.UTC)diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.goindex dcd553fd4a..1b10e9cf8e 100644--- a/internal/unifiedresources/types.go+++ b/internal/unifiedresources/types.go@@ -931,17 +931,23 @@ type PMGData struct {// VMwareData contains VMware vSphere metadata for canonical agent, vm, and// storage resources projected from one vCenter connection.type VMwareData struct {- ConnectionID string `json:"connectionId,omitempty"`- ConnectionName string `json:"connectionName,omitempty"`- VCenterHost string `json:"vcenterHost,omitempty"`- ManagedObjectID string `json:"managedObjectId,omitempty"`- EntityType string `json:"entityType,omitempty"`- HostUUID string `json:"hostUuid,omitempty"`- ConnectionState string `json:"connectionState,omitempty"`- PowerState string `json:"powerState,omitempty"`- CPUCount int `json:"cpuCount,omitempty"`- MemorySizeMiB int64 `json:"memorySizeMib,omitempty"`- DatastoreType string `json:"datastoreType,omitempty"`+ ConnectionID string `json:"connectionId,omitempty"`+ ConnectionName string `json:"connectionName,omitempty"`+ VCenterHost string `json:"vcenterHost,omitempty"`+ ManagedObjectID string `json:"managedObjectId,omitempty"`+ EntityType string `json:"entityType,omitempty"`+ HostUUID string `json:"hostUuid,omitempty"`+ ConnectionState string `json:"connectionState,omitempty"`+ PowerState string `json:"powerState,omitempty"`+ OverallStatus string `json:"overallStatus,omitempty"`+ CPUCount int `json:"cpuCount,omitempty"`+ MemorySizeMiB int64 `json:"memorySizeMib,omitempty"`+ DatastoreType string `json:"datastoreType,omitempty"`+ ActiveAlarmCount int `json:"activeAlarmCount,omitempty"`+ ActiveAlarmSummary string `json:"activeAlarmSummary,omitempty"`+ RecentTaskCount int `json:"recentTaskCount,omitempty"`+ RecentTaskSummary string `json:"recentTaskSummary,omitempty"`+ SnapshotCount int `json:"snapshotCount,omitempty"`}// TrueNASData contains TrueNAS-specific metadata for system host resources.diff --git a/internal/vmware/client.go b/internal/vmware/client.goindex 40dffa5a02..21fbb85972 100644--- a/internal/vmware/client.go+++ b/internal/vmware/client.go@@ -138,7 +138,7 @@ func (c *Client) Close() {// TestConnection validates both the Automation API and VI JSON API families and// returns a minimal inventory summary on success.func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error) {- inventory, err := c.CollectInventory(ctx)+ inventory, err := c.collectInventoryBase(ctx)if err != nil {return nil, err}@@ -146,7 +146,11 @@ func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error)if err != nil {return nil, err}- if err := c.loginVIJSON(ctx, release, sessionManagerMoID); err != nil {+ sessionID, err := c.loginVIJSON(ctx, release, sessionManagerMoID)+ if err != nil {+ return nil, err+ }+ if err := c.validateSignalFloor(ctx, release, sessionID, inventory); err != nil {return nil, err}return &InventorySummary{@@ -160,6 +164,26 @@ func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error)// CollectInventory fetches the phase-1 VMware inventory floor used by the// supplemental-ingest provider.func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, error) {+ inventory, err := c.collectInventoryBase(ctx)+ if err != nil {+ return nil, err+ }+ release, sessionManagerMoID, err := c.resolveVIJSONRelease(ctx)+ if err != nil {+ return nil, err+ }+ sessionID, err := c.loginVIJSON(ctx, release, sessionManagerMoID)+ if err != nil {+ return nil, err+ }+ if err := c.enrichInventorySnapshot(ctx, release, sessionID, inventory); err != nil {+ return nil, err+ }+ inventory.CollectedAt = time.Now().UTC()+ return inventory, nil+}++func (c *Client) collectInventoryBase(ctx context.Context) (*InventorySnapshot, error) {automationSessionID, err := c.createAutomationSession(ctx)if err != nil {return nil, err@@ -181,10 +205,9 @@ func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, erro}return &InventorySnapshot{- CollectedAt: time.Now().UTC(),- Hosts: hosts,- VMs: vms,- Datastores: datastores,+ Hosts: hosts,+ VMs: vms,+ Datastores: datastores,}, nil}@@ -353,37 +376,38 @@ func (c *Client) fetchSessionManagerMoID(ctx context.Context, release string) (sreturn moID, nil}-func (c *Client) loginVIJSON(ctx context.Context, release string, sessionManagerMoID string) error {+func (c *Client) loginVIJSON(ctx context.Context, release string, sessionManagerMoID string) (string, error) {body, err := json.Marshal(map[string]string{"userName": c.username,"password": c.password,})if err != nil {- return fmt.Errorf("marshal vi-json login request: %w", err)+ return "", fmt.Errorf("marshal vi-json login request: %w", err)}endpoint := fmt.Sprintf("%s/sdk/vim25/%s/SessionManager/%s/Login", c.baseURL.String(), release, sessionManagerMoID)req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(string(body)))if err != nil {- return fmt.Errorf("build vi-json login request: %w", err)+ return "", fmt.Errorf("build vi-json login request: %w", err)}req.Header.Set("Content-Type", "application/json")req.Header.Set("Accept", "application/json")resp, err := c.httpClient.Do(req)if err != nil {- return classifyTransportError("vi-json login", err)+ return "", classifyTransportError("vi-json login", err)}defer resp.Body.Close()_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))switch resp.StatusCode {case http.StatusOK:- if strings.TrimSpace(resp.Header.Get("vmware-api-session-id")) == "" {- return &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API login succeeded without returning a session id"}+ sessionID := strings.TrimSpace(resp.Header.Get("vmware-api-session-id"))+ if sessionID == "" {+ return "", &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API login succeeded without returning a session id"}}- return nil+ return sessionID, nilcase http.StatusUnauthorized, http.StatusForbidden:- return &ConnectionError{Category: "auth", Message: "VMware authentication failed while creating the VI JSON API session"}+ return "", &ConnectionError{Category: "auth", Message: "VMware authentication failed while creating the VI JSON API session"}default:- return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API login failed with HTTP %d", resp.StatusCode)}+ return "", &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API login failed with HTTP %d", resp.StatusCode)}}}diff --git a/internal/vmware/client_signals.go b/internal/vmware/client_signals.gonew file mode 100644index 0000000000..eea10e9577--- /dev/null+++ b/internal/vmware/client_signals.go@@ -0,0 +1,437 @@+package vmware++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "sort"+ "strings"+ "sync"+ "time"+)++const vmwareSignalEnrichmentConcurrency = 8++type viJSONReference struct {+ Type string `json:"type"`+ Value string `json:"value"`+}++type viJSONLocalizedMessage struct {+ LocalizedMessage string `json:"localizedMessage"`+ Message string `json:"message"`+ Key string `json:"key"`+}++type viJSONAlarmState struct {+ Alarm viJSONReference `json:"alarm"`+ OverallStatus string `json:"overallStatus"`+ Acknowledged bool `json:"acknowledged"`+ Time *time.Time `json:"time"`+}++type viJSONTaskInfo struct {+ Name *viJSONLocalizedMessage `json:"name"`+ DescriptionID string `json:"descriptionId"`+ State string `json:"state"`+ StartTime *time.Time `json:"startTime"`+ CompleteTime *time.Time `json:"completeTime"`+ Error *viJSONLocalizedMessage `json:"error"`+}++type viJSONSnapshotInfo struct {+ RootSnapshotList []viJSONSnapshotTree `json:"rootSnapshotList"`+}++type viJSONSnapshotTree struct {+ ChildSnapshotList []viJSONSnapshotTree `json:"childSnapshotList"`+}++type viJSONAlarmInfo struct {+ Name string `json:"name"`+}++type alarmNameCache struct {+ mu sync.Mutex+ names map[string]string+}++type entitySignals struct {+ OverallStatus string+ Alarms []InventoryAlarm+ RecentTasks []InventoryTask+}++func (c *Client) validateSignalFloor(ctx context.Context, release, sessionID string, snapshot *InventorySnapshot) error {+ if snapshot == nil {+ return nil+ }++ cache := &alarmNameCache{names: make(map[string]string)}+ if len(snapshot.Hosts) > 0 {+ host := snapshot.Hosts[0]+ if _, err := c.collectManagedEntitySignals(ctx, release, sessionID, "HostSystem", host.Host, cache, false); err != nil {+ return err+ }+ }+ if len(snapshot.VMs) > 0 {+ vm := snapshot.VMs[0]+ if _, err := c.collectManagedEntitySignals(ctx, release, sessionID, "VirtualMachine", vm.VM, cache, false); err != nil {+ return err+ }+ if _, err := c.collectVMSnapshotCount(ctx, release, sessionID, vm.VM); err != nil && !isVIJSONNotFound(err) {+ return err+ }+ }+ if len(snapshot.Datastores) > 0 {+ datastore := snapshot.Datastores[0]+ if _, err := c.collectManagedEntitySignals(ctx, release, sessionID, "Datastore", datastore.Datastore, cache, false); err != nil {+ return err+ }+ }+ return nil+}++func (c *Client) enrichInventorySnapshot(ctx context.Context, release, sessionID string, snapshot *InventorySnapshot) error {+ if snapshot == nil {+ return nil+ }++ cache := &alarmNameCache{names: make(map[string]string)}+ sem := make(chan struct{}, vmwareSignalEnrichmentConcurrency)+ var wg sync.WaitGroup+ var firstErr error+ var firstErrMu sync.Mutex++ run := func(fn func() error) {+ wg.Add(1)+ go func() {+ defer wg.Done()+ sem <- struct{}{}+ defer func() { <-sem }()++ if err := fn(); err != nil {+ firstErrMu.Lock()+ if firstErr == nil {+ firstErr = err+ }+ firstErrMu.Unlock()+ }+ }()+ }++ for i := range snapshot.Hosts {+ i := i+ run(func() error {+ signals, err := c.collectManagedEntitySignals(ctx, release, sessionID, "HostSystem", snapshot.Hosts[i].Host, cache, true)+ if err != nil {+ return err+ }+ snapshot.Hosts[i].OverallStatus = signals.OverallStatus+ snapshot.Hosts[i].TriggeredAlarms = signals.Alarms+ snapshot.Hosts[i].RecentTasks = signals.RecentTasks+ return nil+ })+ }++ for i := range snapshot.VMs {+ i := i+ run(func() error {+ signals, err := c.collectManagedEntitySignals(ctx, release, sessionID, "VirtualMachine", snapshot.VMs[i].VM, cache, true)+ if err != nil {+ return err+ }+ snapshot.VMs[i].OverallStatus = signals.OverallStatus+ snapshot.VMs[i].TriggeredAlarms = signals.Alarms+ snapshot.VMs[i].RecentTasks = signals.RecentTasks+ snapshot.VMs[i].SnapshotCount, err = c.collectVMSnapshotCount(ctx, release, sessionID, snapshot.VMs[i].VM)+ if err != nil && !isVIJSONNotFound(err) {+ return err+ }+ return nil+ })+ }++ for i := range snapshot.Datastores {+ i := i+ run(func() error {+ signals, err := c.collectManagedEntitySignals(ctx, release, sessionID, "Datastore", snapshot.Datastores[i].Datastore, cache, true)+ if err != nil {+ return err+ }+ snapshot.Datastores[i].OverallStatus = signals.OverallStatus+ snapshot.Datastores[i].TriggeredAlarms = signals.Alarms+ snapshot.Datastores[i].RecentTasks = signals.RecentTasks+ return nil+ })+ }++ wg.Wait()++ firstErrMu.Lock()+ defer firstErrMu.Unlock()+ return firstErr+}++func (c *Client) collectManagedEntitySignals(ctx context.Context, release, sessionID, managedType, managedObjectID string, cache *alarmNameCache, allowNotFound bool) (entitySignals, error) {+ managedObjectID = strings.TrimSpace(managedObjectID)+ if managedObjectID == "" {+ return entitySignals{}, nil+ }++ signals := entitySignals{}++ overallStatus, err := c.collectOverallStatus(ctx, release, sessionID, managedType, managedObjectID)+ if err != nil {+ if !allowNotFound || !isVIJSONNotFound(err) {+ return entitySignals{}, err+ }+ } else {+ signals.OverallStatus = overallStatus+ }++ alarms, err := c.collectTriggeredAlarms(ctx, release, sessionID, managedType, managedObjectID, cache)+ if err != nil {+ if !allowNotFound || !isVIJSONNotFound(err) {+ return entitySignals{}, err+ }+ } else {+ signals.Alarms = alarms+ }++ tasks, err := c.collectRecentTasks(ctx, release, sessionID, managedType, managedObjectID)+ if err != nil {+ if !allowNotFound || !isVIJSONNotFound(err) {+ return entitySignals{}, err+ }+ } else {+ signals.RecentTasks = tasks+ }++ return signals, nil+}++func (c *Client) collectOverallStatus(ctx context.Context, release, sessionID, managedType, managedObjectID string) (string, error) {+ var status string+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/overallStatus", release, managedType, managedObjectID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, managedType+" overall status", &status); err != nil {+ return "", err+ }+ return strings.TrimSpace(status), nil+}++func (c *Client) collectTriggeredAlarms(ctx context.Context, release, sessionID, managedType, managedObjectID string, cache *alarmNameCache) ([]InventoryAlarm, error) {+ var states []viJSONAlarmState+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/triggeredAlarmState", release, managedType, managedObjectID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, managedType+" triggered alarms", &states); err != nil {+ return nil, err+ }+ alarms := make([]InventoryAlarm, 0, len(states))+ for _, state := range states {+ alarmID := strings.TrimSpace(state.Alarm.Value)+ alarmName := alarmID+ if alarmID != "" {+ if resolvedName, err := c.resolveAlarmName(ctx, release, sessionID, alarmID, cache); err == nil && resolvedName != "" {+ alarmName = resolvedName+ } else if err != nil && !isVIJSONNotFound(err) {+ return nil, err+ }+ }+ var triggeredAt time.Time+ if state.Time != nil {+ triggeredAt = state.Time.UTC()+ }+ alarms = append(alarms, InventoryAlarm{+ Alarm: alarmID,+ Name: strings.TrimSpace(alarmName),+ OverallStatus: strings.TrimSpace(state.OverallStatus),+ Acknowledged: state.Acknowledged,+ TriggeredAt: triggeredAt,+ })+ }+ sort.SliceStable(alarms, func(i, j int) bool {+ left := inventoryAlarmSortTime(alarms[i])+ right := inventoryAlarmSortTime(alarms[j])+ if !left.Equal(right) {+ return left.After(right)+ }+ return vmwareSortKey(alarms[i].Alarm, alarms[i].Name) < vmwareSortKey(alarms[j].Alarm, alarms[j].Name)+ })+ return alarms, nil+}++func (c *Client) collectRecentTasks(ctx context.Context, release, sessionID, managedType, managedObjectID string) ([]InventoryTask, error) {+ var refs []viJSONReference+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/recentTask", release, managedType, managedObjectID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, managedType+" recent tasks", &refs); err != nil {+ return nil, err+ }+ if len(refs) == 0 {+ return nil, nil+ }++ limit := len(refs)+ if limit > 3 {+ limit = 3+ }+ tasks := make([]InventoryTask, 0, limit)+ for _, ref := range refs[:limit] {+ taskID := strings.TrimSpace(ref.Value)+ if taskID == "" {+ continue+ }+ info, err := c.collectTaskInfo(ctx, release, sessionID, taskID)+ if err != nil {+ if isVIJSONNotFound(err) {+ continue+ }+ return nil, err+ }+ tasks = append(tasks, info)+ }+ sort.SliceStable(tasks, func(i, j int) bool {+ left := inventoryTaskSortTime(tasks[i])+ right := inventoryTaskSortTime(tasks[j])+ if !left.Equal(right) {+ return left.After(right)+ }+ return vmwareSortKey(tasks[i].Task, tasks[i].Name) < vmwareSortKey(tasks[j].Task, tasks[j].Name)+ })+ return tasks, nil+}++func (c *Client) collectTaskInfo(ctx context.Context, release, sessionID, taskID string) (InventoryTask, error) {+ var payload viJSONTaskInfo+ path := fmt.Sprintf("/sdk/vim25/%s/Task/%s/info", release, taskID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, "vmware task info", &payload); err != nil {+ return InventoryTask{}, err+ }++ task := InventoryTask{+ Task: taskID,+ Name: strings.TrimSpace(localizedMessageText(payload.Name)),+ State: strings.TrimSpace(payload.State),+ DescriptionID: strings.TrimSpace(payload.DescriptionID),+ }+ if task.Name == "" {+ task.Name = task.DescriptionID+ }+ if payload.StartTime != nil {+ task.StartedAt = payload.StartTime.UTC()+ }+ if payload.CompleteTime != nil {+ task.CompletedAt = payload.CompleteTime.UTC()+ }+ task.ErrorMessage = strings.TrimSpace(localizedMessageText(payload.Error))+ return task, nil+}++func (c *Client) collectVMSnapshotCount(ctx context.Context, release, sessionID, managedObjectID string) (int, error) {+ var payload viJSONSnapshotInfo+ path := fmt.Sprintf("/sdk/vim25/%s/VirtualMachine/%s/snapshot", release, managedObjectID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, "vmware vm snapshot tree", &payload); err != nil {+ return 0, err+ }+ return countSnapshotTrees(payload.RootSnapshotList), nil+}++func (c *Client) resolveAlarmName(ctx context.Context, release, sessionID, alarmID string, cache *alarmNameCache) (string, error) {+ alarmID = strings.TrimSpace(alarmID)+ if alarmID == "" {+ return "", nil+ }+ if cache != nil {+ cache.mu.Lock()+ if name, ok := cache.names[alarmID]; ok {+ cache.mu.Unlock()+ return name, nil+ }+ cache.mu.Unlock()+ }++ var payload viJSONAlarmInfo+ path := fmt.Sprintf("/sdk/vim25/%s/Alarm/%s/info", release, alarmID)+ if err := c.getVIJSONJSON(ctx, sessionID, path, "vmware alarm info", &payload); err != nil {+ return "", err+ }+ name := strings.TrimSpace(payload.Name)+ if cache != nil {+ cache.mu.Lock()+ cache.names[alarmID] = name+ cache.mu.Unlock()+ }+ return name, nil+}++func (c *Client) getVIJSONJSON(ctx context.Context, sessionID, path, label string, target any) error {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL.String()+path, nil)+ if err != nil {+ return fmt.Errorf("build %s request: %w", label, err)+ }+ req.Header.Set("Accept", "application/json")+ req.Header.Set("vmware-api-session-id", sessionID)+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return classifyTransportError(label, err)+ }+ defer resp.Body.Close()+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, inventoryResponseLimitByte))+ if readErr != nil {+ return fmt.Errorf("read %s response: %w", label, readErr)+ }+ switch resp.StatusCode {+ case http.StatusOK:+ case http.StatusUnauthorized:+ return &ConnectionError{Category: "auth", Message: fmt.Sprintf("VMware authentication failed while reading %s", label)}+ case http.StatusForbidden:+ return &ConnectionError{Category: "permission", Message: fmt.Sprintf("VMware permissions are insufficient for %s", label)}+ case http.StatusNotFound:+ return &ConnectionError{Category: "not_found", Message: fmt.Sprintf("VMware %s endpoint is unavailable", label)}+ default:+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s request failed with HTTP %d", label, resp.StatusCode)}+ }+ if err := json.Unmarshal(body, target); err != nil {+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s response was not valid JSON", label)}+ }+ return nil+}++func isVIJSONNotFound(err error) bool {+ connectionErr, ok := err.(*ConnectionError)+ return ok && connectionErr.Category == "not_found"+}++func localizedMessageText(message *viJSONLocalizedMessage) string {+ if message == nil {+ return ""+ }+ return firstNonEmptyTrimmed(message.LocalizedMessage, message.Message, message.Key)+}++func inventoryAlarmSortTime(alarm InventoryAlarm) time.Time {+ if alarm.TriggeredAt.IsZero() {+ return time.Time{}+ }+ return alarm.TriggeredAt.UTC()+}++func inventoryTaskSortTime(task InventoryTask) time.Time {+ if !task.StartedAt.IsZero() {+ return task.StartedAt.UTC()+ }+ if !task.CompletedAt.IsZero() {+ return task.CompletedAt.UTC()+ }+ return time.Time{}+}++func countSnapshotTrees(roots []viJSONSnapshotTree) int {+ count := 0+ for _, root := range roots {+ count+++ count += countSnapshotTrees(root.ChildSnapshotList)+ }+ return count+}diff --git a/internal/vmware/client_test.go b/internal/vmware/client_test.gonew file mode 100644index 0000000000..5b75c52f4c--- /dev/null+++ b/internal/vmware/client_test.go@@ -0,0 +1,274 @@+package vmware++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"+)++func TestClientCollectInventoryEnrichesSignals(t *testing.T) {+ server := newVMwareTestServer(t, vmwareTestServerConfig{})+ defer server.Close()++ client, err := NewClient(ClientConfig{+ Host: server.URL,+ Username: "admin",+ Password: "secret",+ InsecureSkipVerify: true,+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("NewClient: %v", err)+ }++ snapshot, err := client.CollectInventory(context.Background())+ if err != nil {+ t.Fatalf("CollectInventory: %v", err)+ }+ if snapshot == nil {+ t.Fatal("expected inventory snapshot")+ }+ if len(snapshot.Hosts) != 1 || len(snapshot.VMs) != 1 || len(snapshot.Datastores) != 1 {+ t.Fatalf("unexpected inventory sizes: hosts=%d vms=%d datastores=%d", len(snapshot.Hosts), len(snapshot.VMs), len(snapshot.Datastores))+ }++ host := snapshot.Hosts[0]+ if host.OverallStatus != "yellow" {+ t.Fatalf("host overall status = %q, want yellow", host.OverallStatus)+ }+ if len(host.TriggeredAlarms) != 1 || host.TriggeredAlarms[0].Name != "Host connection degraded" {+ t.Fatalf("expected resolved host alarm metadata, got %+v", host.TriggeredAlarms)+ }+ if len(host.RecentTasks) != 1 || host.RecentTasks[0].Name != "Reconnect host" {+ t.Fatalf("expected host recent task summary, got %+v", host.RecentTasks)+ }++ vm := snapshot.VMs[0]+ if len(vm.TriggeredAlarms) != 1 || vm.TriggeredAlarms[0].OverallStatus != "red" {+ t.Fatalf("expected VM alarm signals, got %+v", vm.TriggeredAlarms)+ }+ if vm.SnapshotCount != 2 {+ t.Fatalf("vm snapshot count = %d, want 2", vm.SnapshotCount)+ }+ if len(vm.RecentTasks) != 1 || vm.RecentTasks[0].State != "success" {+ t.Fatalf("expected VM recent task info, got %+v", vm.RecentTasks)+ }++ datastore := snapshot.Datastores[0]+ if datastore.OverallStatus != "yellow" {+ t.Fatalf("datastore overall status = %q, want yellow", datastore.OverallStatus)+ }+ if len(datastore.RecentTasks) != 1 || datastore.RecentTasks[0].Name != "Refresh datastore" {+ t.Fatalf("expected datastore recent task info, got %+v", datastore.RecentTasks)+ }+}++func TestClientTestConnectionRequiresSignalFloor(t *testing.T) {+ server := newVMwareTestServer(t, vmwareTestServerConfig{+ omitHostOverallStatus: true,+ })+ defer server.Close()++ client, err := NewClient(ClientConfig{+ Host: server.URL,+ Username: "admin",+ Password: "secret",+ InsecureSkipVerify: true,+ Timeout: 5 * time.Second,+ })+ if err != nil {+ t.Fatalf("NewClient: %v", err)+ }++ _, err = client.TestConnection(context.Background())+ if err == nil {+ t.Fatal("expected signal-floor validation error")+ }+ connectionErr, ok := err.(*ConnectionError)+ if !ok {+ t.Fatalf("expected ConnectionError, got %T", err)+ }+ if connectionErr.Category != "not_found" {+ t.Fatalf("connection error category = %q, want not_found", connectionErr.Category)+ }+}++type vmwareTestServerConfig struct {+ omitHostOverallStatus bool+}++func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Server {+ t.Helper()++ mux := http.NewServeMux()++ writeJSON := func(w http.ResponseWriter, payload any) {+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(payload); err != nil {+ t.Fatalf("encode response: %v", err)+ }+ }++ mux.HandleFunc("/api/session", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost {+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ return+ }+ writeJSON(w, "automation-session")+ })++ mux.HandleFunc("/api/vcenter/host", func(w http.ResponseWriter, r *http.Request) {+ requireAutomationSession(t, r)+ writeJSON(w, []InventoryHost{{+ Host: "host-101",+ Name: "esxi-01.lab.local",+ ConnectionState: "CONNECTED",+ PowerState: "POWERED_ON",+ HostUUID: "uuid-host-1",+ }})+ })+ mux.HandleFunc("/api/vcenter/vm", func(w http.ResponseWriter, r *http.Request) {+ requireAutomationSession(t, r)+ writeJSON(w, []InventoryVM{{+ VM: "vm-201",+ Name: "app-01",+ PowerState: "POWERED_ON",+ CPUCount: 4,+ MemorySizeMiB: 8192,+ }})+ })+ mux.HandleFunc("/api/vcenter/datastore", func(w http.ResponseWriter, r *http.Request) {+ requireAutomationSession(t, r)+ writeJSON(w, []InventoryDatastore{{+ Datastore: "datastore-11",+ Name: "nvme-primary",+ Type: "VMFS",+ FreeSpace: 40,+ Capacity: 100,+ }})+ })++ mux.HandleFunc("/sdk/vim25/9.0.0.0/ServiceInstance/ServiceInstance/content", func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{+ "sessionManager": map[string]any{"value": "SessionManager"},+ })+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/SessionManager/SessionManager/Login", func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("vmware-api-session-id", "vi-session")+ writeJSON(w, map[string]any{"value": "ok"})+ })++ if !cfg.omitHostOverallStatus {+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/overallStatus", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, "yellow")+ })+ }+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/triggeredAlarmState", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{{+ "alarm": map[string]any{"type": "Alarm", "value": "alarm-11"},+ "overallStatus": "yellow",+ "acknowledged": false,+ "time": "2026-03-30T18:12:00Z",+ }})+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/recentTask", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{{"type": "Task", "value": "task-11"}})+ })++ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/overallStatus", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, "green")+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/triggeredAlarmState", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{{+ "alarm": map[string]any{"type": "Alarm", "value": "alarm-21"},+ "overallStatus": "red",+ "acknowledged": false,+ "time": "2026-03-30T18:13:00Z",+ }})+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/recentTask", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{{"type": "Task", "value": "task-21"}})+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/snapshot", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{+ "rootSnapshotList": []map[string]any{{+ "childSnapshotList": []map[string]any{{"childSnapshotList": []map[string]any{}}},+ }},+ })+ })++ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/overallStatus", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, "yellow")+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/triggeredAlarmState", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{})+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/recentTask", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, []map[string]any{{"type": "Task", "value": "task-31"}})+ })++ mux.HandleFunc("/sdk/vim25/9.0.0.0/Alarm/alarm-11/info", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{"name": "Host connection degraded"})+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Alarm/alarm-21/info", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{"name": "VM replication fault"})+ })++ mux.HandleFunc("/sdk/vim25/9.0.0.0/Task/task-11/info", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{+ "name": map[string]any{"localizedMessage": "Reconnect host"},+ "state": "running",+ "startTime": "2026-03-30T18:14:00Z",+ })+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Task/task-21/info", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{+ "name": map[string]any{"localizedMessage": "Create snapshot"},+ "state": "success",+ "descriptionId": "VirtualMachine.createSnapshot",+ "startTime": "2026-03-30T18:10:00Z",+ })+ })+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Task/task-31/info", func(w http.ResponseWriter, r *http.Request) {+ requireVISession(t, r)+ writeJSON(w, map[string]any{+ "name": map[string]any{"localizedMessage": "Refresh datastore"},+ "state": "queued",+ "startTime": "2026-03-30T18:11:00Z",+ })+ })++ return httptest.NewTLSServer(mux)+}++func requireAutomationSession(t *testing.T, r *http.Request) {+ t.Helper()+ if got := strings.TrimSpace(r.Header.Get("vmware-api-session-id")); got != "automation-session" {+ t.Fatalf("automation session header = %q, want automation-session", got)+ }+}++func requireVISession(t *testing.T, r *http.Request) {+ t.Helper()+ if got := strings.TrimSpace(r.Header.Get("vmware-api-session-id")); got != "vi-session" {+ t.Fatalf("vi-json session header = %q, want vi-session", got)+ }+}diff --git a/internal/vmware/provider.go b/internal/vmware/provider.goindex b42bab2707..7fada19d99 100644--- a/internal/vmware/provider.go+++ b/internal/vmware/provider.go@@ -8,37 +8,66 @@ import ("sync""time"+ "github.com/rcourtman/pulse-go-rewrite/internal/storagehealth""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources")+type InventoryAlarm struct {+ Alarm string `json:"alarm,omitempty"`+ Name string `json:"name,omitempty"`+ OverallStatus string `json:"overall_status,omitempty"`+ Acknowledged bool `json:"acknowledged,omitempty"`+ TriggeredAt time.Time `json:"triggered_at,omitempty"`+}++type InventoryTask struct {+ Task string `json:"task,omitempty"`+ Name string `json:"name,omitempty"`+ State string `json:"state,omitempty"`+ DescriptionID string `json:"description_id,omitempty"`+ StartedAt time.Time `json:"started_at,omitempty"`+ CompletedAt time.Time `json:"completed_at,omitempty"`+ ErrorMessage string `json:"error_message,omitempty"`+}+// InventoryHost is the canonical phase-1 host summary returned by the vCenter// Automation API list endpoint.type InventoryHost struct {- Host string `json:"host"`- Name string `json:"name"`- ConnectionState string `json:"connection_state"`- PowerState string `json:"power_state,omitempty"`- HostUUID string `json:"host_uuid,omitempty"`+ Host string `json:"host"`+ Name string `json:"name"`+ ConnectionState string `json:"connection_state"`+ PowerState string `json:"power_state,omitempty"`+ HostUUID string `json:"host_uuid,omitempty"`+ OverallStatus string `json:"overall_status,omitempty"`+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`}// InventoryVM is the canonical phase-1 VM summary returned by the vCenter// Automation API list endpoint.type InventoryVM struct {- VM string `json:"vm"`- Name string `json:"name"`- PowerState string `json:"power_state"`- CPUCount int `json:"cpu_count,omitempty"`- MemorySizeMiB int64 `json:"memory_size_mib,omitempty"`+ VM string `json:"vm"`+ Name string `json:"name"`+ PowerState string `json:"power_state"`+ CPUCount int `json:"cpu_count,omitempty"`+ MemorySizeMiB int64 `json:"memory_size_mib,omitempty"`+ OverallStatus string `json:"overall_status,omitempty"`+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`+ SnapshotCount int `json:"snapshot_count,omitempty"`}// InventoryDatastore is the canonical phase-1 datastore summary returned by// the vCenter Automation API list endpoint.type InventoryDatastore struct {- Datastore string `json:"datastore"`- Name string `json:"name"`- Type string `json:"type"`- FreeSpace int64 `json:"free_space,omitempty"`- Capacity int64 `json:"capacity,omitempty"`+ Datastore string `json:"datastore"`+ Name string `json:"name"`+ Type string `json:"type"`+ FreeSpace int64 `json:"free_space,omitempty"`+ Capacity int64 `json:"capacity,omitempty"`+ OverallStatus string `json:"overall_status,omitempty"`+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`}// InventorySnapshot captures the projected inventory floor for one vCenter@@ -222,22 +251,29 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {if name == "" {continue}+ incidents := hostIncidents(host)resource := unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent,Technology: "vmware",Name: name,- Status: hostStatus(host),+ Status: unifiedresources.IncidentsStatus(hostStatus(host), incidents),LastSeen: collectedAt,UpdatedAt: collectedAt,+ Incidents: incidents,VMware: &unifiedresources.VMwareData{- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),- ConnectionName: connectionName,- VCenterHost: vcenterHost,- ManagedObjectID: strings.TrimSpace(host.Host),- EntityType: "host",- HostUUID: strings.TrimSpace(host.HostUUID),- ConnectionState: strings.TrimSpace(host.ConnectionState),- PowerState: strings.TrimSpace(host.PowerState),+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),+ ConnectionName: connectionName,+ VCenterHost: vcenterHost,+ ManagedObjectID: strings.TrimSpace(host.Host),+ EntityType: "host",+ HostUUID: strings.TrimSpace(host.HostUUID),+ ConnectionState: strings.TrimSpace(host.ConnectionState),+ PowerState: strings.TrimSpace(host.PowerState),+ OverallStatus: strings.TrimSpace(host.OverallStatus),+ ActiveAlarmCount: len(host.TriggeredAlarms),+ ActiveAlarmSummary: vmwareAlarmSummary(host.TriggeredAlarms),+ RecentTaskCount: len(host.RecentTasks),+ RecentTaskSummary: vmwareRecentTaskSummary(host.RecentTasks),},Tags: filterNonEmptyStrings("vmware",@@ -265,22 +301,30 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {if name == "" {continue}+ incidents := vmIncidents(vm)resource := unifiedresources.Resource{Type: unifiedresources.ResourceTypeVM,Technology: "vmware",Name: name,- Status: vmStatus(vm),+ Status: unifiedresources.IncidentsStatus(vmStatus(vm), incidents),LastSeen: collectedAt,UpdatedAt: collectedAt,+ Incidents: incidents,VMware: &unifiedresources.VMwareData{- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),- ConnectionName: connectionName,- VCenterHost: vcenterHost,- ManagedObjectID: strings.TrimSpace(vm.VM),- EntityType: "vm",- PowerState: strings.TrimSpace(vm.PowerState),- CPUCount: vm.CPUCount,- MemorySizeMiB: vm.MemorySizeMiB,+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),+ ConnectionName: connectionName,+ VCenterHost: vcenterHost,+ ManagedObjectID: strings.TrimSpace(vm.VM),+ EntityType: "vm",+ PowerState: strings.TrimSpace(vm.PowerState),+ CPUCount: vm.CPUCount,+ MemorySizeMiB: vm.MemorySizeMiB,+ OverallStatus: strings.TrimSpace(vm.OverallStatus),+ ActiveAlarmCount: len(vm.TriggeredAlarms),+ ActiveAlarmSummary: vmwareAlarmSummary(vm.TriggeredAlarms),+ RecentTaskCount: len(vm.RecentTasks),+ RecentTaskSummary: vmwareRecentTaskSummary(vm.RecentTasks),+ SnapshotCount: vm.SnapshotCount,},Tags: filterNonEmptyStrings("vmware",@@ -306,13 +350,15 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {if used < 0 {used = 0}+ incidents := datastoreIncidents(datastore)resource := unifiedresources.Resource{Type: unifiedresources.ResourceTypeStorage,Technology: "vmware",Name: name,- Status: datastoreStatus(datastore),+ Status: unifiedresources.IncidentsStatus(datastoreStatus(datastore), incidents),LastSeen: collectedAt,UpdatedAt: collectedAt,+ Incidents: incidents,Metrics: &unifiedresources.ResourceMetrics{Disk: diskMetric(datastore.Capacity, used),},@@ -323,12 +369,17 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {Enabled: true,},VMware: &unifiedresources.VMwareData{- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),- ConnectionName: connectionName,- VCenterHost: vcenterHost,- ManagedObjectID: strings.TrimSpace(datastore.Datastore),- EntityType: "datastore",- DatastoreType: strings.TrimSpace(datastore.Type),+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),+ ConnectionName: connectionName,+ VCenterHost: vcenterHost,+ ManagedObjectID: strings.TrimSpace(datastore.Datastore),+ EntityType: "datastore",+ DatastoreType: strings.TrimSpace(datastore.Type),+ OverallStatus: strings.TrimSpace(datastore.OverallStatus),+ ActiveAlarmCount: len(datastore.TriggeredAlarms),+ ActiveAlarmSummary: vmwareAlarmSummary(datastore.TriggeredAlarms),+ RecentTaskCount: len(datastore.RecentTasks),+ RecentTaskSummary: vmwareRecentTaskSummary(datastore.RecentTasks),},Tags: filterNonEmptyStrings("vmware",@@ -368,12 +419,69 @@ func cloneInventorySnapshot(in *InventorySnapshot) *InventorySnapshot {return nil}out := *in- out.Hosts = append([]InventoryHost(nil), in.Hosts...)- out.VMs = append([]InventoryVM(nil), in.VMs...)- out.Datastores = append([]InventoryDatastore(nil), in.Datastores...)+ out.Hosts = cloneInventoryHosts(in.Hosts)+ out.VMs = cloneInventoryVMs(in.VMs)+ out.Datastores = cloneInventoryDatastores(in.Datastores)return &out}+func cloneInventoryHosts(in []InventoryHost) []InventoryHost {+ if in == nil {+ return nil+ }+ out := make([]InventoryHost, len(in))+ for i := range in {+ out[i] = in[i]+ out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)+ out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)+ }+ return out+}++func cloneInventoryVMs(in []InventoryVM) []InventoryVM {+ if in == nil {+ return nil+ }+ out := make([]InventoryVM, len(in))+ for i := range in {+ out[i] = in[i]+ out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)+ out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)+ }+ return out+}++func cloneInventoryDatastores(in []InventoryDatastore) []InventoryDatastore {+ if in == nil {+ return nil+ }+ out := make([]InventoryDatastore, len(in))+ for i := range in {+ out[i] = in[i]+ out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)+ out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)+ }+ return out+}++func cloneInventoryAlarms(in []InventoryAlarm) []InventoryAlarm {+ if in == nil {+ return nil+ }+ out := make([]InventoryAlarm, len(in))+ copy(out, in)+ return out+}++func cloneInventoryTasks(in []InventoryTask) []InventoryTask {+ if in == nil {+ return nil+ }+ out := make([]InventoryTask, len(in))+ copy(out, in)+ return out+}+func vmwareSourceID(connectionID, entityType, managedObjectID string) string {parts := filterNonEmptyStrings(strings.TrimSpace(connectionID), strings.TrimSpace(entityType), strings.TrimSpace(managedObjectID))return strings.Join(parts, ":")@@ -415,6 +523,160 @@ func datastoreStatus(datastore InventoryDatastore) unifiedresources.ResourceStatreturn unifiedresources.StatusOnline}+func hostIncidents(host InventoryHost) []unifiedresources.ResourceIncident {+ return appendVMwareAlarmsAndHealthIncidents("host", host.Host, strings.TrimSpace(host.OverallStatus), host.TriggeredAlarms)+}++func vmIncidents(vm InventoryVM) []unifiedresources.ResourceIncident {+ return appendVMwareAlarmsAndHealthIncidents("vm", vm.VM, strings.TrimSpace(vm.OverallStatus), vm.TriggeredAlarms)+}++func datastoreIncidents(datastore InventoryDatastore) []unifiedresources.ResourceIncident {+ return appendVMwareAlarmsAndHealthIncidents("datastore", datastore.Datastore, strings.TrimSpace(datastore.OverallStatus), datastore.TriggeredAlarms)+}++func appendVMwareAlarmsAndHealthIncidents(entityType, managedObjectID, overallStatus string, alarms []InventoryAlarm) []unifiedresources.ResourceIncident {+ incidents := make([]unifiedresources.ResourceIncident, 0, len(alarms)+1)+ for _, alarm := range alarms {+ severity, ok := vmwareRiskLevel(alarm.OverallStatus)+ if !ok {+ continue+ }+ nativeID := firstNonEmptyTrimmed(alarm.Alarm, alarm.Name, managedObjectID)+ summary := vmwareAlarmIncidentSummary(entityType, managedObjectID, alarm)+ startedAt := alarm.TriggeredAt+ incidents = append(incidents, unifiedresources.ResourceIncident{+ Provider: "vmware",+ NativeID: nativeID,+ Code: "vmware_alarm_state",+ Severity: severity,+ Source: string(unifiedresources.SourceVMware),+ Summary: summary,+ StartedAt: startedAt,+ })+ }+ if len(incidents) == 0 {+ if severity, ok := vmwareRiskLevel(overallStatus); ok {+ incidents = append(incidents, unifiedresources.ResourceIncident{+ Provider: "vmware",+ NativeID: firstNonEmptyTrimmed(managedObjectID, entityType),+ Code: "vmware_health_state",+ Severity: severity,+ Source: string(unifiedresources.SourceVMware),+ Summary: vmwareOverallStatusSummary(entityType, overallStatus),+ })+ }+ }+ return incidents+}++func vmwareRiskLevel(status string) (storagehealth.RiskLevel, bool) {+ switch strings.ToLower(strings.TrimSpace(status)) {+ case "red":+ return storagehealth.RiskCritical, true+ case "yellow":+ return storagehealth.RiskWarning, true+ default:+ return "", false+ }+}++func vmwareAlarmIncidentSummary(entityType, managedObjectID string, alarm InventoryAlarm) string {+ entityLabel := vmwareEntityLabel(entityType)+ alarmName := firstNonEmptyTrimmed(alarm.Name, alarm.Alarm)+ status := strings.ToLower(strings.TrimSpace(alarm.OverallStatus))+ if alarmName == "" {+ alarmName = "VMware alarm"+ }+ if status == "" {+ status = "active"+ }+ if ref := strings.TrimSpace(managedObjectID); ref != "" {+ return fmt.Sprintf("%s %s has VMware alarm %s (%s)", entityLabel, ref, alarmName, status)+ }+ return fmt.Sprintf("%s has VMware alarm %s (%s)", entityLabel, alarmName, status)+}++func vmwareOverallStatusSummary(entityType, overallStatus string) string {+ entityLabel := vmwareEntityLabel(entityType)+ status := strings.ToLower(strings.TrimSpace(overallStatus))+ if status == "" {+ status = "degraded"+ }+ return fmt.Sprintf("%s has VMware overall status %s", entityLabel, status)+}++func vmwareEntityLabel(entityType string) string {+ switch strings.ToLower(strings.TrimSpace(entityType)) {+ case "host":+ return "Host"+ case "vm":+ return "VM"+ case "datastore":+ return "Datastore"+ default:+ return "Resource"+ }+}++func vmwareAlarmSummary(alarms []InventoryAlarm) string {+ if len(alarms) == 0 {+ return ""+ }+ parts := make([]string, 0, len(alarms))+ for _, alarm := range alarms {+ name := firstNonEmptyTrimmed(alarm.Name, alarm.Alarm)+ if name == "" {+ continue+ }+ status := strings.ToLower(strings.TrimSpace(alarm.OverallStatus))+ if status == "" {+ parts = append(parts, name)+ continue+ }+ parts = append(parts, name+" ("+status+")")+ if len(parts) == 3 {+ break+ }+ }+ if len(parts) == 0 {+ return ""+ }+ if len(alarms) > len(parts) {+ return strings.Join(parts, ", ") + fmt.Sprintf(", and %d more", len(alarms)-len(parts))+ }+ return strings.Join(parts, ", ")+}++func vmwareRecentTaskSummary(tasks []InventoryTask) string {+ if len(tasks) == 0 {+ return ""+ }+ parts := make([]string, 0, len(tasks))+ for _, task := range tasks {+ name := firstNonEmptyTrimmed(task.Name, task.DescriptionID, task.Task)+ if name == "" {+ continue+ }+ state := strings.ToLower(strings.TrimSpace(task.State))+ if state == "" {+ parts = append(parts, name)+ } else {+ parts = append(parts, name+" ("+state+")")+ }+ if len(parts) == 3 {+ break+ }+ }+ if len(parts) == 0 {+ return ""+ }+ if len(tasks) > len(parts) {+ return strings.Join(parts, ", ") + fmt.Sprintf(", and %d more", len(tasks)-len(parts))+ }+ return strings.Join(parts, ", ")+}+func normalizeDatastoreType(value string) string {return strings.ToLower(strings.TrimSpace(value))}diff --git a/internal/vmware/provider_test.go b/internal/vmware/provider_test.goindex 30f42625af..9522443e71 100644--- a/internal/vmware/provider_test.go+++ b/internal/vmware/provider_test.go@@ -24,6 +24,19 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {ConnectionState: "CONNECTED",PowerState: "POWERED_ON",HostUUID: "uuid-host-1",+ OverallStatus: "yellow",+ TriggeredAlarms: []InventoryAlarm{{+ Alarm: "alarm-11",+ Name: "Host connection degraded",+ OverallStatus: "yellow",+ TriggeredAt: collectedAt.Add(-2 * time.Minute),+ }},+ RecentTasks: []InventoryTask{{+ Task: "task-11",+ Name: "Reconnect host",+ State: "running",+ StartedAt: collectedAt.Add(-1 * time.Minute),+ }},}},VMs: []InventoryVM{{VM: "vm-201",@@ -31,13 +44,34 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {PowerState: "POWERED_ON",CPUCount: 4,MemorySizeMiB: 8192,+ OverallStatus: "green",+ TriggeredAlarms: []InventoryAlarm{{+ Alarm: "alarm-21",+ Name: "VM replication fault",+ OverallStatus: "red",+ TriggeredAt: collectedAt.Add(-3 * time.Minute),+ }},+ RecentTasks: []InventoryTask{{+ Task: "task-21",+ Name: "Create snapshot",+ State: "success",+ StartedAt: collectedAt.Add(-5 * time.Minute),+ }},+ SnapshotCount: 2,}},Datastores: []InventoryDatastore{{- Datastore: "datastore-11",- Name: "nvme-primary",- Type: "VMFS",- FreeSpace: 40,- Capacity: 100,+ Datastore: "datastore-11",+ Name: "nvme-primary",+ Type: "VMFS",+ FreeSpace: 40,+ Capacity: 100,+ OverallStatus: "yellow",+ RecentTasks: []InventoryTask{{+ Task: "task-31",+ Name: "Refresh datastore",+ State: "queued",+ StartedAt: collectedAt.Add(-4 * time.Minute),+ }},}},})@@ -53,12 +87,21 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {if hostRecord.Resource.Type != unifiedresources.ResourceTypeAgent {t.Fatalf("host resource type = %q, want %q", hostRecord.Resource.Type, unifiedresources.ResourceTypeAgent)}- if hostRecord.Resource.Status != unifiedresources.StatusOnline {- t.Fatalf("host status = %q, want %q", hostRecord.Resource.Status, unifiedresources.StatusOnline)+ if hostRecord.Resource.Status != unifiedresources.StatusWarning {+ t.Fatalf("host status = %q, want %q", hostRecord.Resource.Status, unifiedresources.StatusWarning)}if hostRecord.Resource.VMware == nil || hostRecord.Resource.VMware.ManagedObjectID != "host-101" {t.Fatalf("expected VMware host metadata, got %+v", hostRecord.Resource.VMware)}+ if got := hostRecord.Resource.VMware.ActiveAlarmCount; got != 1 {+ t.Fatalf("host active alarm count = %d, want 1", got)+ }+ if got := hostRecord.Resource.VMware.RecentTaskSummary; got != "Reconnect host (running)" {+ t.Fatalf("host recent task summary = %q, want %q", got, "Reconnect host (running)")+ }+ if len(hostRecord.Resource.Incidents) != 1 || hostRecord.Resource.Incidents[0].Code != "vmware_alarm_state" {+ t.Fatalf("expected host VMware incident projection, got %+v", hostRecord.Resource.Incidents)+ }if hostRecord.Identity.DMIUUID != "uuid-host-1" {t.Fatalf("host identity DMI UUID = %q, want uuid-host-1", hostRecord.Identity.DMIUUID)}@@ -76,8 +119,17 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {if vmRecord.Resource.VMware == nil || vmRecord.Resource.VMware.CPUCount != 4 {t.Fatalf("expected VMware VM metadata with cpu count, got %+v", vmRecord.Resource.VMware)}- if vmRecord.Resource.Status != unifiedresources.StatusOnline {- t.Fatalf("vm status = %q, want %q", vmRecord.Resource.Status, unifiedresources.StatusOnline)+ if vmRecord.Resource.Status != unifiedresources.StatusWarning {+ t.Fatalf("vm status = %q, want %q", vmRecord.Resource.Status, unifiedresources.StatusWarning)+ }+ if got := vmRecord.Resource.VMware.ActiveAlarmSummary; got != "VM replication fault (red)" {+ t.Fatalf("vm active alarm summary = %q, want %q", got, "VM replication fault (red)")+ }+ if got := vmRecord.Resource.VMware.SnapshotCount; got != 2 {+ t.Fatalf("vm snapshot count = %d, want 2", got)+ }+ if len(vmRecord.Resource.Incidents) != 1 || vmRecord.Resource.Incidents[0].Code != "vmware_alarm_state" {+ t.Fatalf("expected VMware VM incident projection, got %+v", vmRecord.Resource.Incidents)}datastoreRecord := records[2]@@ -90,10 +142,19 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {if datastoreRecord.Resource.Storage == nil || datastoreRecord.Resource.Storage.Platform != "vmware-vsphere" {t.Fatalf("expected canonical VMware storage metadata, got %+v", datastoreRecord.Resource.Storage)}+ if datastoreRecord.Resource.Status != unifiedresources.StatusWarning {+ t.Fatalf("datastore status = %q, want %q", datastoreRecord.Resource.Status, unifiedresources.StatusWarning)+ }if datastoreRecord.Resource.Metrics == nil || datastoreRecord.Resource.Metrics.Disk == nil {t.Fatal("expected datastore disk metrics to be populated")}if got := datastoreRecord.Resource.Metrics.Disk.Percent; got != 60 {t.Fatalf("datastore disk usage percent = %v, want 60", got)}+ if len(datastoreRecord.Resource.Incidents) != 1 || datastoreRecord.Resource.Incidents[0].Code != "vmware_health_state" {+ t.Fatalf("expected VMware datastore health incident, got %+v", datastoreRecord.Resource.Incidents)+ }+ if got := datastoreRecord.Resource.VMware.RecentTaskSummary; got != "Refresh datastore (queued)" {+ t.Fatalf("datastore recent task summary = %q, want %q", got, "Refresh datastore (queued)")+ }}diff --git a/tests/integration/tests/36-vmware-alert-history-resource-incidents.spec.ts b/tests/integration/tests/36-vmware-alert-history-resource-incidents.spec.tsnew file mode 100644index 0000000000..12f9cd9aa6--- /dev/null+++ b/tests/integration/tests/36-vmware-alert-history-resource-incidents.spec.ts@@ -0,0 +1,197 @@+import { expect, test } from "@playwright/test";+const SCREENSHOT_PATH = "/tmp/vmware-alert-history-resource-incidents.png";++test.describe("VMware alert history resource incidents", () => {+ test.setTimeout(180_000);++ test("opens VMware resource incidents through the shared alert history surface", async ({+ page,+ }) => {+ await page.route("**/api/alerts/config", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ enabled: true,+ activationState: "active",+ }),+ });+ });++ await page.route("**/api/alerts/active", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([]),+ });+ });++ await page.route("**/api/alerts/history**", async (route) => {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([+ {+ id: "unified-incident-vm-app-01-vmware-alarm-21-vmware-alarm-state",+ type: "resource-incident",+ level: "critical",+ resourceId: "vm:app-01",+ resourceName: "app-01",+ node: "esxi-01.lab.local",+ nodeDisplayName: "ESXi 01",+ instance: "VMware",+ message: "VM vm-201 has VMware alarm VM replication fault (red)",+ value: 0,+ threshold: 0,+ startTime: "2026-03-30T18:13:00Z",+ lastSeen: "2026-03-30T18:15:00Z",+ acknowledged: false,+ metadata: {+ incidentCategory: "health",+ incidentLabel: "VM Health Issue",+ vmwareConnectionId: "vc-1",+ },+ },+ ]),+ });+ });++ await page.route("**/api/alerts/incidents**", async (route) => {+ const requestUrl = new URL(route.request().url());+ if (requestUrl.searchParams.get("resource_id") !== "vm:app-01") {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([]),+ });+ return;+ }++ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify([+ {+ id: "incident-1",+ alertIdentifier:+ "unified-incident-vm-app-01-vmware-alarm-21-vmware-alarm-state",+ alertType: "Resource Health",+ level: "critical",+ resourceId: "vm:app-01",+ resourceName: "app-01",+ resourceType: "vm",+ node: "esxi-01.lab.local",+ instance: "VMware",+ message: "VM vm-201 has VMware alarm VM replication fault (red)",+ status: "open",+ openedAt: "2026-03-30T18:13:00Z",+ acknowledged: false,+ events: [+ {+ id: "event-1",+ type: "alert_fired",+ timestamp: "2026-03-30T18:13:00Z",+ summary: "Alert fired",+ details: {+ vmwareConnectionId: "vc-1",+ },+ },+ ],+ },+ ]),+ });+ });++ await page.route("**/api/resources**", async (route) => {+ const requestUrl = new URL(route.request().url());+ if (requestUrl.pathname !== "/api/resources") {+ await route.continue();+ return;+ }++ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({+ data: [+ {+ id: "vm:app-01",+ type: "vm",+ name: "app-01",+ displayName: "app-01",+ platformId: "vm:app-01",+ platformType: "vmware-vsphere",+ sourceType: "api",+ sources: ["vmware"],+ status: "warning",+ lastSeen: "2026-03-30T18:15:00Z",+ vmware: {+ connectionId: "vc-1",+ connectionName: "Lab VC",+ vcenterHost: "vc.lab.local",+ managedObjectId: "vm-201",+ entityType: "vm",+ overallStatus: "red",+ activeAlarmCount: 1,+ activeAlarmSummary: "VM replication fault (red)",+ recentTaskCount: 1,+ recentTaskSummary: "Create snapshot (success)",+ snapshotCount: 2,+ },+ incidents: [+ {+ provider: "vmware",+ nativeId: "alarm-21",+ code: "vmware_alarm_state",+ severity: "critical",+ source: "vmware",+ summary:+ "VM vm-201 has VMware alarm VM replication fault (red)",+ startedAt: "2026-03-30T18:13:00Z",+ },+ ],+ },+ ],+ meta: {+ page: 1,+ limit: 200,+ total: 1,+ totalPages: 1,+ },+ }),+ });+ });++ await page.goto("http://127.0.0.1:5173/alerts/history", {+ waitUntil: "domcontentloaded",+ });++ const letsGoButton = page.getByRole("button", { name: "Let's go" });+ if (+ await letsGoButton+ .waitFor({ state: "visible", timeout: 3000 })+ .then(() => true)+ .catch(() => false)+ ) {+ await letsGoButton.click();+ }++ await expect(+ page.getByRole("heading", { name: "Alert History" }),+ ).toBeVisible();+ await expect(page.getByText("app-01")).toBeVisible();+ const historyRow = page.locator("tr").filter({ hasText: "app-01" }).first();+ await expect(historyRow).toContainText(+ "VM vm-201 has VMware alarm VM replication fault (red)",+ );+ await historyRow.getByRole("button", { name: "Resource" }).click();++ await expect(+ page.getByText("VM vm-201 has VMware alarm VM replication fault (red)"),+ ).toBeVisible();+ await expect(page.getByText("Resource incidents")).toBeVisible();+ await expect(page.getByText("Resource Health")).toBeVisible();++ await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });+ });+});