Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix: AI Commands toggle now updates immediately in UI. Related to #952

rcourtmanfd1f94babff7
diff --git a/internal/ai/alert_adapter_test.go b/internal/ai/alert_adapter_test.go
index ffb0bab421..9132627147 100644
--- a/internal/ai/alert_adapter_test.go
+++ b/internal/ai/alert_adapter_test.go
@@ -26,6 +26,12 @@ func TestAlertManagerAdapter_NilManager(t *testing.T) {
if got := a.GetRecentlyResolved(30); got != nil {
t.Fatalf("GetRecentlyResolved = %+v, want nil", got)
}
+ if got := a.GetAlertsByResource("resource"); got != nil {
+ t.Fatalf("GetAlertsByResource = %+v, want nil", got)
+ }
+ if got := a.GetAlertHistory("resource", 10); got != nil {
+ t.Fatalf("GetAlertHistory = %+v, want nil", got)
+ }
}
func TestAlertManagerAdapter_ConvertsAndFilters(t *testing.T) {
@@ -177,4 +183,12 @@ func TestFormatDuration(t *testing.T) {
}
}
+func TestAlertConversions_Nil(t *testing.T) {
+ if info := convertAlertFromManager(nil); info.ID != "" {
+ t.Fatalf("expected empty AlertInfo from nil manager alert, got %+v", info)
+ }
+ if info := convertAlertFromModels(nil); info.ID != "" {
+ t.Fatalf("expected empty AlertInfo from nil models alert, got %+v", info)
+ }
+}
diff --git a/internal/ai/alert_provider_test.go b/internal/ai/alert_provider_test.go
index 8bbd661cc2..b7cbfe5c4b 100644
--- a/internal/ai/alert_provider_test.go
+++ b/internal/ai/alert_provider_test.go
@@ -113,6 +113,43 @@ func TestService_buildAlertContext_Empty(t *testing.T) {
}
}
+func TestService_buildAlertContext_NoActiveWithResolved(t *testing.T) {
+ now := time.Now()
+ resolved := make([]ResolvedAlertInfo, 0, 6)
+ for i := 0; i < 6; i++ {
+ resolved = append(resolved, ResolvedAlertInfo{
+ AlertInfo: AlertInfo{
+ ID: "r" + string(rune('a'+i)),
+ Type: "disk",
+ Level: "warning",
+ ResourceID: "storage:local",
+ ResourceName: "local",
+ Message: "disk ok",
+ Duration: "10 mins",
+ },
+ ResolvedTime: now.Add(-time.Duration(i) * time.Minute),
+ Duration: "10 mins",
+ })
+ }
+
+ s := &Service{}
+ s.SetAlertProvider(&stubAlertProvider{
+ active: nil,
+ resolved: resolved,
+ })
+
+ ctx := s.buildAlertContext()
+ if !strings.Contains(ctx, "No Active Alerts") {
+ t.Fatalf("expected no active alerts section, got: %s", ctx)
+ }
+ if !strings.Contains(ctx, "Recently Resolved") {
+ t.Fatalf("expected recently resolved section, got: %s", ctx)
+ }
+ if !strings.Contains(ctx, "... and 1 more") {
+ t.Fatalf("expected overflow line for resolved alerts, got: %s", ctx)
+ }
+}
+
func TestService_buildTargetAlertContext(t *testing.T) {
s := &Service{}
s.SetAlertProvider(&stubAlertProvider{
@@ -131,17 +168,45 @@ func TestService_buildTargetAlertContext(t *testing.T) {
}
}
+func TestService_buildTargetAlertContext_Empty(t *testing.T) {
+ s := &Service{}
+ if got := s.buildTargetAlertContext("node:pve1"); got != "" {
+ t.Fatalf("expected empty string with no provider, got: %q", got)
+ }
+
+ s.SetAlertProvider(&stubAlertProvider{
+ active: []AlertInfo{
+ {ID: "a1", Level: "critical", Type: "cpu", ResourceID: "node:pve1", ResourceName: "pve1"},
+ },
+ })
+ if got := s.buildTargetAlertContext(""); got != "" {
+ t.Fatalf("expected empty string for empty resource ID, got: %q", got)
+ }
+ if got := s.buildTargetAlertContext("node:missing"); got != "" {
+ t.Fatalf("expected empty string for missing resource, got: %q", got)
+ }
+}
+
func TestFormatTimeAgo(t *testing.T) {
now := time.Now()
if got := formatTimeAgo(now.Add(-10 * time.Second)); got != "just now" {
t.Fatalf("formatTimeAgo(<1m) = %q", got)
}
+ if got := formatTimeAgo(now.Add(-1 * time.Minute)); got != "1 minute" {
+ t.Fatalf("formatTimeAgo(1m) = %q", got)
+ }
if got := formatTimeAgo(now.Add(-2 * time.Minute)); got != "2 minutes" {
t.Fatalf("formatTimeAgo(2m) = %q", got)
}
+ if got := formatTimeAgo(now.Add(-1 * time.Hour)); got != "1 hour" {
+ t.Fatalf("formatTimeAgo(1h) = %q", got)
+ }
if got := formatTimeAgo(now.Add(-2 * time.Hour)); got != "2 hours" {
t.Fatalf("formatTimeAgo(2h) = %q", got)
}
+ if got := formatTimeAgo(now.Add(-24 * time.Hour)); got != "1 day" {
+ t.Fatalf("formatTimeAgo(1d) = %q", got)
+ }
if got := formatTimeAgo(now.Add(-48 * time.Hour)); got != "2 days" {
t.Fatalf("formatTimeAgo(2d) = %q", got)
}
@@ -164,4 +229,3 @@ func TestGenerateAlertInvestigationPrompt(t *testing.T) {
t.Fatalf("unexpected prompt: %s", out)
}
}
-
diff --git a/internal/ai/demo_test.go b/internal/ai/demo_test.go
new file mode 100644
index 0000000000..12e1bb493a
--- /dev/null
+++ b/internal/ai/demo_test.go
@@ -0,0 +1,121 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestIsDemoMode(t *testing.T) {
+ t.Setenv("PULSE_MOCK_MODE", "true")
+ if !IsDemoMode() {
+ t.Fatal("expected demo mode true when PULSE_MOCK_MODE=true")
+ }
+
+ t.Setenv("PULSE_MOCK_MODE", "false")
+ if IsDemoMode() {
+ t.Fatal("expected demo mode false when PULSE_MOCK_MODE=false")
+ }
+}
+
+func TestIsMockResource(t *testing.T) {
+ t.Setenv("PULSE_MOCK_MODE", "false")
+ if !IsMockResource("node/pve1", "", "") {
+ t.Fatal("expected mock resource to be detected for pattern match")
+ }
+ if IsMockResource("node/prod1", "production", "node1") {
+ t.Fatal("expected non-mock resource to return false")
+ }
+
+ t.Setenv("PULSE_MOCK_MODE", "true")
+ if IsMockResource("node/pve1", "", "") {
+ t.Fatal("expected demo mode to bypass mock filtering")
+ }
+}
+
+func TestPatrolService_InjectDemoFindings(t *testing.T) {
+ service := NewPatrolService(nil, nil)
+ if service.findings == nil || service.runHistoryStore == nil {
+ t.Fatal("expected findings and run history to be initialized")
+ }
+
+ service.InjectDemoFindings()
+
+ findings := service.findings.GetAll(nil)
+ if len(findings) != 5 {
+ t.Fatalf("expected 5 demo findings, got %d", len(findings))
+ }
+ if service.runHistoryStore.Count() != 13 {
+ t.Fatalf("expected 13 demo run history entries, got %d", service.runHistoryStore.Count())
+ }
+}
+
+func TestPatrolService_InjectDemoFindings_NoStore(t *testing.T) {
+ service := &PatrolService{}
+ service.InjectDemoFindings()
+}
+
+func TestPatrolService_InjectDemoRunHistory_NoStore(t *testing.T) {
+ service := &PatrolService{}
+ service.injectDemoRunHistory()
+}
+
+func TestGenerateDemoAIResponse(t *testing.T) {
+ tests := []struct {
+ name string
+ prompt string
+ expected string
+ }{
+ {"patrol", "Analyze the infrastructure for issues", "ZFS pool 'local-zfs' is 94% full"},
+ {"disk", "disk is full", "Disk Usage Analysis"},
+ {"memory", "memory pressure", "Memory Analysis"},
+ {"backup", "pbs backup status", "Backup Status Review"},
+ {"cpu", "cpu load is high", "CPU/Performance Analysis"},
+ {"hello", "hello there", "Pulse AI Assistant"},
+ {"default", "tell me something", "This Demo Shows"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ resp := GenerateDemoAIResponse(tt.prompt)
+ if resp == nil {
+ t.Fatal("expected response")
+ }
+ if !strings.Contains(resp.Content, tt.expected) {
+ t.Fatalf("expected response to contain %q, got %q", tt.expected, resp.Content)
+ }
+ if resp.Model == "" {
+ t.Fatal("expected model to be set")
+ }
+ })
+ }
+}
+
+func TestGenerateDemoAIStream(t *testing.T) {
+ var content strings.Builder
+ done := false
+
+ resp, err := GenerateDemoAIStream("disk usage", func(event StreamEvent) {
+ switch event.Type {
+ case "content":
+ chunk, ok := event.Data.(string)
+ if !ok {
+ t.Fatalf("expected string content chunk, got %T", event.Data)
+ }
+ content.WriteString(chunk)
+ case "done":
+ done = true
+ }
+ })
+ if err != nil {
+ t.Fatalf("GenerateDemoAIStream failed: %v", err)
+ }
+ if resp == nil {
+ t.Fatal("expected response")
+ }
+ if !done {
+ t.Fatal("expected done event")
+ }
+ if content.String() != resp.Content {
+ t.Fatal("expected streamed content to match response content")
+ }
+}
diff --git a/internal/ai/findings_persistence_test.go b/internal/ai/findings_persistence_test.go
index b8e4c29a6c..58456ddb42 100644
--- a/internal/ai/findings_persistence_test.go
+++ b/internal/ai/findings_persistence_test.go
@@ -1,6 +1,8 @@
package ai
import (
+ "os"
+ "path/filepath"
"testing"
"time"
@@ -133,6 +135,21 @@ func TestFindingsPersistenceAdapter_SaveEmpty(t *testing.T) {
}
}
+func TestFindingsPersistenceAdapter_LoadError(t *testing.T) {
+ tmp := t.TempDir()
+ persistence := config.NewConfigPersistence(tmp)
+ adapter := NewFindingsPersistenceAdapter(persistence)
+
+ badPath := filepath.Join(tmp, "ai_findings.json")
+ if err := os.Mkdir(badPath, 0700); err != nil {
+ t.Fatalf("failed to create directory at %s: %v", badPath, err)
+ }
+
+ if _, err := adapter.LoadFindings(); err == nil {
+ t.Fatal("expected error when findings path is a directory")
+ }
+}
+
func TestFindingsPersistenceAdapter_PreservesAllFields(t *testing.T) {
tmp := t.TempDir()
persistence := config.NewConfigPersistence(tmp)
@@ -346,4 +363,3 @@ func TestFindingsPersistenceAdapter_PreservesDismissals(t *testing.T) {
t.Error("suppressed finding should not be active")
}
}
-
diff --git a/internal/ai/patrol_history_persistence_test.go b/internal/ai/patrol_history_persistence_test.go
index ccc4110f9e..5298519207 100644
--- a/internal/ai/patrol_history_persistence_test.go
+++ b/internal/ai/patrol_history_persistence_test.go
@@ -1,8 +1,13 @@
package ai
import (
+ "errors"
+ "os"
+ "path/filepath"
"testing"
"time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
)
// mockPatrolHistoryPersistence implements PatrolHistoryPersistence for testing
@@ -226,6 +231,18 @@ func TestPatrolRunHistoryStore_SetPersistence_TrimToMax(t *testing.T) {
}
}
+func TestPatrolRunHistoryStore_SetPersistence_LoadError(t *testing.T) {
+ store := NewPatrolRunHistoryStore(10)
+ mockPersistence := &mockPatrolHistoryPersistence{
+ loadErr: errors.New("load failed"),
+ }
+
+ err := store.SetPersistence(mockPersistence)
+ if err == nil {
+ t.Fatal("expected error from SetPersistence when load fails")
+ }
+}
+
func TestPatrolRunHistoryStore_FlushPersistence(t *testing.T) {
store := NewPatrolRunHistoryStore(10)
@@ -277,6 +294,62 @@ func TestPatrolRunHistoryStore_ScheduleSave(t *testing.T) {
}
}
+func TestPatrolRunHistoryStore_ScheduleSave_StopsExistingTimer(t *testing.T) {
+ store := NewPatrolRunHistoryStore(10)
+ store.saveDebounce = 50 * time.Millisecond
+
+ mockPersistence := &mockPatrolHistoryPersistence{}
+ store.SetPersistence(mockPersistence)
+ mockPersistence.saveCalls = 0
+
+ store.Add(PatrolRunRecord{ID: "run-1"})
+ store.Add(PatrolRunRecord{ID: "run-2"})
+
+ time.Sleep(120 * time.Millisecond)
+
+ if mockPersistence.saveCalls != 1 {
+ t.Errorf("expected 1 save call after reschedule, got %d", mockPersistence.saveCalls)
+ }
+}
+
+func TestPatrolRunHistoryStore_ScheduleSave_Cancelled(t *testing.T) {
+ store := NewPatrolRunHistoryStore(10)
+ store.saveDebounce = 50 * time.Millisecond
+
+ mockPersistence := &mockPatrolHistoryPersistence{}
+ store.SetPersistence(mockPersistence)
+ mockPersistence.saveCalls = 0
+
+ store.Add(PatrolRunRecord{ID: "run-1"})
+
+ store.mu.Lock()
+ store.savePending = false
+ store.mu.Unlock()
+
+ time.Sleep(120 * time.Millisecond)
+
+ if mockPersistence.saveCalls != 0 {
+ t.Errorf("expected no save calls after cancellation, got %d", mockPersistence.saveCalls)
+ }
+}
+
+func TestPatrolRunHistoryStore_ScheduleSave_Error(t *testing.T) {
+ store := NewPatrolRunHistoryStore(10)
+ store.saveDebounce = 50 * time.Millisecond
+
+ mockPersistence := &mockPatrolHistoryPersistence{saveErr: errors.New("save failed")}
+ store.SetPersistence(mockPersistence)
+ mockPersistence.saveCalls = 0
+
+ store.Add(PatrolRunRecord{ID: "run-1"})
+
+ time.Sleep(120 * time.Millisecond)
+
+ if mockPersistence.saveCalls < 1 {
+ t.Errorf("expected save to be attempted, got %d calls", mockPersistence.saveCalls)
+ }
+}
+
func TestPatrolRunHistoryStore_ScheduleSave_NoPersistence(t *testing.T) {
store := NewPatrolRunHistoryStore(10)
@@ -288,3 +361,71 @@ func TestPatrolRunHistoryStore_ScheduleSave_NoPersistence(t *testing.T) {
// No error or panic is success
}
+
+func TestPatrolHistoryPersistenceAdapter_SaveAndLoad(t *testing.T) {
+ tmp := t.TempDir()
+ persistence := config.NewConfigPersistence(tmp)
+
+ adapter := NewPatrolHistoryPersistenceAdapter(persistence)
+ if adapter == nil {
+ t.Fatal("expected adapter to be created")
+ }
+
+ runs := []PatrolRunRecord{
+ {
+ ID: "run-1",
+ StartedAt: time.Now().Add(-2 * time.Minute),
+ CompletedAt: time.Now().Add(-1 * time.Minute),
+ Duration: time.Minute,
+ Type: "manual",
+ ResourcesChecked: 10,
+ NodesChecked: 2,
+ GuestsChecked: 5,
+ DockerChecked: 1,
+ StorageChecked: 1,
+ HostsChecked: 0,
+ PBSChecked: 0,
+ NewFindings: 1,
+ ExistingFindings: 2,
+ ResolvedFindings: 1,
+ AutoFixCount: 0,
+ FindingsSummary: "summary",
+ FindingIDs: []string{"f1", "f2"},
+ ErrorCount: 0,
+ Status: "ok",
+ AIAnalysis: "analysis",
+ InputTokens: 100,
+ OutputTokens: 200,
+ },
+ }
+
+ if err := adapter.SavePatrolRunHistory(runs); err != nil {
+ t.Fatalf("save failed: %v", err)
+ }
+
+ loaded, err := adapter.LoadPatrolRunHistory()
+ if err != nil {
+ t.Fatalf("load failed: %v", err)
+ }
+ if len(loaded) != 1 || loaded[0].ID != "run-1" {
+ t.Fatalf("unexpected loaded runs: %+v", loaded)
+ }
+ if loaded[0].Duration != runs[0].Duration {
+ t.Fatalf("expected duration %v, got %v", runs[0].Duration, loaded[0].Duration)
+ }
+}
+
+func TestPatrolHistoryPersistenceAdapter_LoadError(t *testing.T) {
+ tmp := t.TempDir()
+ persistence := config.NewConfigPersistence(tmp)
+ adapter := NewPatrolHistoryPersistenceAdapter(persistence)
+
+ badPath := filepath.Join(tmp, "ai_patrol_runs.json")
+ if err := os.Mkdir(badPath, 0700); err != nil {
+ t.Fatalf("failed to create directory at %s: %v", badPath, err)
+ }
+
+ if _, err := adapter.LoadPatrolRunHistory(); err == nil {
+ t.Fatal("expected error when patrol runs path is a directory")
+ }
+}
diff --git a/internal/models/models.go b/internal/models/models.go
index 8afb08220b..f312f3ebfb 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -2164,6 +2164,25 @@ func (s *State) TouchHost(hostID string, ts time.Time) bool {
return false
}
+// SetHostCommandsEnabled updates the CommandsEnabled flag for a host.
+// This allows the UI to immediately reflect config changes without waiting for agent confirmation.
+func (s *State) SetHostCommandsEnabled(hostID string, enabled bool) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ for i, host := range s.Hosts {
+ if host.ID == hostID {
+ if host.CommandsEnabled != enabled {
+ host.CommandsEnabled = enabled
+ s.Hosts[i] = host
+ s.LastUpdate = time.Now()
+ }
+ return true
+ }
+ }
+ return false
+}
+
// UpdateStorage updates the storage in the state
func (s *State) UpdateStorage(storage []Storage) {
s.mu.Lock()
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 2bbe3a3a6e..5a5361016a 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1299,6 +1299,12 @@ func (m *Monitor) UpdateHostAgentConfig(hostID string, commandsEnabled *bool) er
return fmt.Errorf("failed to save host config: %w", err)
}
+ // Also update the Host model in state for immediate UI feedback
+ // The agent will confirm on its next report, but this provides instant feedback
+ if commandsEnabled != nil {
+ m.state.SetHostCommandsEnabled(hostID, *commandsEnabled)
+ }
+
log.Info().
Str("hostId", hostID).
Interface("commandsEnabled", commandsEnabled).