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.

feat: add demo AI findings for mock mode

rcourtmanb75728922c23
diff --git a/internal/ai/demo.go b/internal/ai/demo.go
new file mode 100644
index 0000000000..fc309e356e
--- /dev/null
+++ b/internal/ai/demo.go
@@ -0,0 +1,231 @@
+package ai
+
+import (
+ "os"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// IsDemoMode returns true if mock/demo mode is enabled
+// This checks the same MOCK_ENABLED env var used by the mock data system
+func IsDemoMode() bool {
+ return os.Getenv("MOCK_ENABLED") == "true" || os.Getenv("MOCK_ENABLED") == "1"
+}
+
+// InjectDemoFindings populates the patrol service with realistic mock findings
+// This is used for demo instances to showcase AI features without actual AI API calls
+func (p *PatrolService) InjectDemoFindings() {
+ if p == nil || p.findings == nil {
+ return
+ }
+
+ log.Info().Msg("Demo mode: Injecting mock AI patrol findings")
+
+ now := time.Now()
+
+ // Create realistic demo findings
+ demoFindings := []*Finding{
+ {
+ ID: "demo-storage-critical",
+ Key: "storage:local-zfs:capacity",
+ Severity: FindingSeverityCritical,
+ Category: FindingCategoryCapacity,
+ Title: "ZFS pool 'local-zfs' is 94% full",
+ Description: "Storage pool local-zfs on pve1 has only 47GB remaining out of 750GB. At current growth rate, pool will be full in approximately 5 days.",
+ ResourceID: "storage/pve1/local-zfs",
+ ResourceName: "local-zfs",
+ ResourceType: "storage",
+ Node: "pve1",
+ Recommendation: `**Immediate actions:**
+1. Identify large files: ` + "`zfs list -o name,used,refer -t all | sort -k2 -h | tail -20`" + `
+2. Check for orphaned VM disks: ` + "`pvesm list local-zfs | grep -v 'vm-'`" + `
+3. Remove old snapshots: ` + "`zfs list -t snapshot -o name,used | sort -k2 -h`" + `
+
+**Long-term:**
+- Add additional storage or migrate VMs to other pools
+- Enable ZFS compression if not already enabled`,
+ DetectedAt: now.Add(-2 * time.Hour),
+ LastSeenAt: now.Add(-5 * time.Minute),
+ TimesRaised: 3,
+ Source: "patrol",
+ },
+ {
+ ID: "demo-memory-warning",
+ Key: "guest:vm-102:memory",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ Title: "VM 'jellyfin' memory usage at 91%",
+ Description: "jellyfin (VM 102) on pve2 is consistently using 14.5GB of its 16GB allocated memory. Swapping may occur under load, degrading performance.",
+ ResourceID: "qemu/102",
+ ResourceName: "jellyfin",
+ ResourceType: "qemu",
+ Node: "pve2",
+ Recommendation: `**Options to consider:**
+1. Increase VM memory allocation to 20GB if host has capacity
+2. Check for memory leaks in Jellyfin: restart the service
+3. Limit transcoding to reduce memory pressure
+4. Review Jellyfin cache settings in the dashboard`,
+ DetectedAt: now.Add(-6 * time.Hour),
+ LastSeenAt: now.Add(-10 * time.Minute),
+ TimesRaised: 5,
+ Source: "patrol",
+ },
+ {
+ ID: "demo-backup-warning",
+ Key: "guest:vm-105:backup",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryBackup,
+ Title: "Container 'postgres' hasn't been backed up in 8 days",
+ Description: "The postgres container (CT 105) last successful backup was 8 days ago. Your backup schedule targets daily backups.",
+ ResourceID: "lxc/105",
+ ResourceName: "postgres",
+ ResourceType: "lxc",
+ Node: "pve1",
+ Recommendation: `**Investigate:**
+1. Check PBS backup job status: ` + "`pvesh get /nodes/pve1/tasks --typefilter vzdump`" + `
+2. Verify PBS datastore connectivity
+3. Check for backup job errors in the Proxmox datacenter backup view
+
+**Manual backup:**
+` + "`vzdump 105 --storage pbs --mode snapshot`",
+ DetectedAt: now.Add(-24 * time.Hour),
+ LastSeenAt: now.Add(-15 * time.Minute),
+ TimesRaised: 2,
+ Source: "patrol",
+ },
+ {
+ ID: "demo-cpu-warning",
+ Key: "node:pve3:cpu",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryPerformance,
+ Title: "Node 'pve3' sustained high CPU (87%)",
+ Description: "Node pve3 has maintained CPU usage above 85% for the past 2 hours. This may indicate over-provisioning or a runaway process.",
+ ResourceID: "node/pve3",
+ ResourceName: "pve3",
+ ResourceType: "node",
+ Node: "pve3",
+ Recommendation: `**Diagnose:**
+1. Check top processes: ` + "`ssh pve3 'top -bn1 | head -20'`" + `
+2. Identify VM CPU usage: ` + "`pvesh get /nodes/pve3/qemu --output-format json | jq '.[] | {name, cpu}'`" + `
+
+**Consider:**
+- Live-migrate a VM to another node: ` + "`qm migrate <vmid> pve1 --online`" + `
+- Set CPU limits on high-usage VMs`,
+ DetectedAt: now.Add(-2 * time.Hour),
+ LastSeenAt: now.Add(-8 * time.Minute),
+ TimesRaised: 4,
+ Source: "patrol",
+ },
+ {
+ ID: "demo-docker-warning",
+ Key: "docker:portainer:container-restart",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryReliability,
+ Title: "Docker container 'uptime-kuma' restarting frequently",
+ Description: "The uptime-kuma container on docker-host-1 has restarted 7 times in the past 24 hours. This may indicate configuration issues or resource constraints.",
+ ResourceID: "docker/docker-host-1/uptime-kuma",
+ ResourceName: "uptime-kuma",
+ ResourceType: "docker_container",
+ Node: "docker-host-1",
+ Recommendation: `**Check logs:**
+` + "`docker logs uptime-kuma --tail 100`" + `
+
+**Common causes:**
+- OOM kills: check ` + "`docker stats uptime-kuma`" + `
+- Configuration errors in environment variables
+- Database corruption (check data volume)`,
+ DetectedAt: now.Add(-12 * time.Hour),
+ LastSeenAt: now.Add(-20 * time.Minute),
+ TimesRaised: 3,
+ Source: "patrol",
+ },
+ }
+
+ // Add findings to the store
+ for _, f := range demoFindings {
+ p.findings.Add(f)
+ }
+
+ // Also add some demo patrol run history
+ p.injectDemoRunHistory()
+
+ log.Info().Int("findings_count", len(demoFindings)).Msg("Demo mode: Mock findings injected")
+}
+
+// injectDemoRunHistory adds realistic patrol run history for the demo
+func (p *PatrolService) injectDemoRunHistory() {
+ if p.runHistoryStore == nil {
+ return
+ }
+
+ now := time.Now()
+
+ // Create a few historical patrol runs
+ demoRuns := []PatrolRunRecord{
+ {
+ ID: "demo-run-1",
+ StartedAt: now.Add(-15 * time.Minute),
+ CompletedAt: now.Add(-14*time.Minute - 30*time.Second),
+ Duration: 90 * time.Second,
+ Type: "patrol",
+ ResourcesChecked: 47,
+ NodesChecked: 5,
+ GuestsChecked: 32,
+ DockerChecked: 8,
+ StorageChecked: 6,
+ NewFindings: 1,
+ ExistingFindings: 4,
+ ResolvedFindings: 0,
+ FindingsSummary: "1 critical, 3 warnings",
+ FindingIDs: []string{"demo-storage-critical", "demo-memory-warning", "demo-backup-warning", "demo-cpu-warning"},
+ Status: "issues_found",
+ InputTokens: 4250,
+ OutputTokens: 890,
+ },
+ {
+ ID: "demo-run-2",
+ StartedAt: now.Add(-30 * time.Minute),
+ CompletedAt: now.Add(-29*time.Minute - 15*time.Second),
+ Duration: 75 * time.Second,
+ Type: "patrol",
+ ResourcesChecked: 47,
+ NodesChecked: 5,
+ GuestsChecked: 32,
+ DockerChecked: 8,
+ StorageChecked: 6,
+ NewFindings: 2,
+ ExistingFindings: 2,
+ ResolvedFindings: 1,
+ FindingsSummary: "1 critical, 2 warnings",
+ FindingIDs: []string{"demo-storage-critical", "demo-memory-warning", "demo-backup-warning"},
+ Status: "issues_found",
+ InputTokens: 4180,
+ OutputTokens: 720,
+ },
+ {
+ ID: "demo-run-3",
+ StartedAt: now.Add(-45 * time.Minute),
+ CompletedAt: now.Add(-44*time.Minute - 45*time.Second),
+ Duration: 45 * time.Second,
+ Type: "patrol",
+ ResourcesChecked: 47,
+ NodesChecked: 5,
+ GuestsChecked: 32,
+ DockerChecked: 8,
+ StorageChecked: 6,
+ NewFindings: 0,
+ ExistingFindings: 2,
+ ResolvedFindings: 0,
+ FindingsSummary: "2 warnings",
+ FindingIDs: []string{"demo-memory-warning", "demo-cpu-warning"},
+ Status: "issues_found",
+ InputTokens: 4100,
+ OutputTokens: 450,
+ },
+ }
+
+ for _, run := range demoRuns {
+ p.runHistoryStore.Add(run)
+ }
+}
diff --git a/internal/ai/findings.go b/internal/ai/findings.go
index 65213eb18f..38d2e6eeb6 100644
--- a/internal/ai/findings.go
+++ b/internal/ai/findings.go
@@ -365,8 +365,16 @@ func (s *FindingsStore) Unsnooze(id string) bool {
// Dismiss marks a finding as dismissed with a reason and optional note
// Reasons: "not_an_issue", "expected_behavior", "will_fix_later"
-// For "expected_behavior" and "not_an_issue", the finding is also suppressed
-// (creates a suppression rule) to prevent future alerts of the same type.
+//
+// Behavior by reason:
+// - "not_an_issue": Permanent suppression (true false positive in detection logic)
+// - "expected_behavior": Acknowledged only (finding stays visible but marked as accepted)
+// - "will_fix_later": Acknowledged only (user will address it later)
+//
+// Rationale: Only true false positives ("not_an_issue") should be permanently suppressed.
+// For "expected_behavior" and "will_fix_later", the finding stays visible (transparent)
+// but is marked as acknowledged so the user knows they've reviewed it.
+// Severity escalation will still clear the dismissal and reactivate the finding.
func (s *FindingsStore) Dismiss(id, reason, note string) bool {
s.mu.Lock()
@@ -380,15 +388,19 @@ func (s *FindingsStore) Dismiss(id, reason, note string) bool {
if note != "" {
f.UserNote = note
}
- // Also mark as acknowledged
+ // Mark as acknowledged for all dismiss reasons
now := time.Now()
f.AcknowledgedAt = &now
- // For "expected_behavior" and "not_an_issue", also create a suppression rule
- // This prevents the AI from re-raising similar findings for this resource+category
- if reason == "expected_behavior" || reason == "not_an_issue" {
+ // Only "not_an_issue" creates permanent suppression
+ // This is for true false positives where the detection logic is wrong
+ if reason == "not_an_issue" {
f.Suppressed = true
}
+ // For "expected_behavior" and "will_fix_later":
+ // - Finding stays visible (not suppressed, not snoozed)
+ // - But is marked as dismissed/acknowledged so user knows they've reviewed it
+ // - Severity escalation will clear DismissedReason and reactivate
s.mu.Unlock()
s.scheduleSave()
diff --git a/internal/ai/findings_test.go b/internal/ai/findings_test.go
index c6bcfdb75c..5a8dc91e0c 100644
--- a/internal/ai/findings_test.go
+++ b/internal/ai/findings_test.go
@@ -1030,3 +1030,101 @@ func TestFindingsStore_GetSuppressionRules_Empty(t *testing.T) {
}
}
+// TestFindingsStore_Dismiss_DifferentReasons tests the dismissal behavior based on reason:
+// - "not_an_issue": permanent suppression (true false positive)
+// - "expected_behavior": 30-day snooze (user accepts risk, but re-check later)
+// - "will_fix_later": just marked dismissed, no snooze or suppression
+func TestFindingsStore_Dismiss_DifferentReasons(t *testing.T) {
+ t.Run("not_an_issue creates permanent suppression", func(t *testing.T) {
+ store := NewFindingsStore()
+ f := &Finding{
+ ID: "f1",
+ ResourceID: "res-1",
+ Severity: FindingSeverityWarning,
+ Title: "False Positive",
+ Category: FindingCategoryPerformance,
+ }
+ store.Add(f)
+
+ store.Dismiss("f1", "not_an_issue", "Detection bug")
+
+ finding := store.Get("f1")
+ if !finding.Suppressed {
+ t.Error("Expected finding to be suppressed for 'not_an_issue'")
+ }
+ if finding.SnoozedUntil != nil {
+ t.Error("Should not set snooze for 'not_an_issue'")
+ }
+ if finding.DismissedReason != "not_an_issue" {
+ t.Errorf("Expected DismissedReason 'not_an_issue', got %s", finding.DismissedReason)
+ }
+ })
+
+ t.Run("expected_behavior acknowledges but stays visible", func(t *testing.T) {
+ store := NewFindingsStore()
+ f := &Finding{
+ ID: "f2",
+ ResourceID: "res-2",
+ Severity: FindingSeverityWarning,
+ Title: "Expected Behavior",
+ Category: FindingCategoryCapacity,
+ }
+ store.Add(f)
+
+ store.Dismiss("f2", "expected_behavior", "Disk fills during backup")
+
+ finding := store.Get("f2")
+ if finding.Suppressed {
+ t.Error("Should NOT set Suppressed for 'expected_behavior'")
+ }
+ if finding.SnoozedUntil != nil {
+ t.Error("Should NOT set snooze for 'expected_behavior' (just acknowledges)")
+ }
+ if finding.AcknowledgedAt == nil {
+ t.Error("Expected AcknowledgedAt to be set for 'expected_behavior'")
+ }
+ if finding.DismissedReason != "expected_behavior" {
+ t.Errorf("Expected DismissedReason 'expected_behavior', got %s", finding.DismissedReason)
+ }
+ if finding.UserNote != "Disk fills during backup" {
+ t.Errorf("Expected note to be saved, got %s", finding.UserNote)
+ }
+
+ // Finding is marked dismissed, so IsDismissed() returns true
+ if !finding.IsDismissed() {
+ t.Error("Finding should be marked as dismissed")
+ }
+ })
+
+ t.Run("will_fix_later acknowledges but stays visible", func(t *testing.T) {
+ store := NewFindingsStore()
+ f := &Finding{
+ ID: "f3",
+ ResourceID: "res-3",
+ Severity: FindingSeverityWarning,
+ Title: "Will Fix Later",
+ Category: FindingCategoryReliability,
+ }
+ store.Add(f)
+
+ store.Dismiss("f3", "will_fix_later", "Low priority")
+
+ finding := store.Get("f3")
+ if finding.Suppressed {
+ t.Error("Should NOT suppress for 'will_fix_later'")
+ }
+ if finding.SnoozedUntil != nil {
+ t.Error("Should NOT snooze for 'will_fix_later'")
+ }
+ if finding.AcknowledgedAt == nil {
+ t.Error("Expected AcknowledgedAt to be set")
+ }
+ if finding.DismissedReason != "will_fix_later" {
+ t.Errorf("Expected DismissedReason 'will_fix_later', got %s", finding.DismissedReason)
+ }
+ // Finding is marked dismissed
+ if !finding.IsDismissed() {
+ t.Error("Finding should be marked as dismissed")
+ }
+ })
+}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index d60c167240..b4c1a9b099 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -1433,7 +1433,9 @@ func (p *PatrolService) DismissFinding(findingID string, reason string, note str
return fmt.Errorf("finding not found: %s", findingID)
}
- // Dismiss the finding (this automatically creates a suppression rule for expected_behavior/not_an_issue)
+ // Dismiss the finding:
+ // - "not_an_issue" creates permanent suppression (true false positive)
+ // - "expected_behavior" and "will_fix_later" just acknowledge (stays visible but marked)
if !p.findings.Dismiss(findingID, reason, note) {
return fmt.Errorf("failed to dismiss finding: %s", findingID)
}
@@ -1442,7 +1444,7 @@ func (p *PatrolService) DismissFinding(findingID string, reason string, note str
Str("finding_id", findingID).
Str("reason", reason).
Str("note", note).
- Bool("suppressed", reason == "expected_behavior" || reason == "not_an_issue").
+ Bool("permanently_suppressed", reason == "not_an_issue").
Msg("AI dismissed finding")
return nil
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 31849cc5e2..67303537ce 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -489,6 +489,11 @@ func (s *Service) StartPatrol(ctx context.Context) {
Bool("enabled", enabled).
Msg("Alert-triggered AI analysis configured")
}
+
+ // In demo/mock mode, inject realistic AI findings for showcasing
+ if IsDemoMode() {
+ patrol.InjectDemoFindings()
+ }
}
// StopPatrol stops the background patrol service
@@ -544,6 +549,72 @@ func (s *Service) ReconfigurePatrol() {
}
}
+// enrichRequestFromFinding looks up a patrol finding by ID and enriches the request
+// with the finding's context (node, resource ID, resource type, etc.)
+// This ensures proper command routing when the AI helps fix a patrol finding.
+// The function modifies the request in place.
+func (s *Service) enrichRequestFromFinding(req *ExecuteRequest) {
+ if req.FindingID == "" {
+ return
+ }
+
+ s.mu.RLock()
+ patrol := s.patrolService
+ s.mu.RUnlock()
+
+ if patrol == nil {
+ log.Debug().Str("finding_id", req.FindingID).Msg("Cannot enrich request - patrol service not available")
+ return
+ }
+
+ findings := patrol.GetFindings()
+ if findings == nil {
+ log.Debug().Str("finding_id", req.FindingID).Msg("Cannot enrich request - findings store not available")
+ return
+ }
+
+ finding := findings.Get(req.FindingID)
+ if finding == nil {
+ log.Debug().Str("finding_id", req.FindingID).Msg("Cannot enrich request - finding not found")
+ return
+ }
+
+ // Ensure context map exists
+ if req.Context == nil {
+ req.Context = make(map[string]interface{})
+ }
+
+ // Inject finding context (only if not already set)
+ if _, ok := req.Context["node"]; !ok && finding.Node != "" {
+ req.Context["node"] = finding.Node
+ }
+ if _, ok := req.Context["guestName"]; !ok && finding.ResourceName != "" {
+ req.Context["guestName"] = finding.ResourceName
+ }
+ if req.TargetID == "" && finding.ResourceID != "" {
+ req.TargetID = finding.ResourceID
+ }
+ if req.TargetType == "" && finding.ResourceType != "" {
+ req.TargetType = finding.ResourceType
+ }
+
+ // Also store the finding details for reference in context
+ req.Context["finding_resource_id"] = finding.ResourceID
+ req.Context["finding_resource_name"] = finding.ResourceName
+ req.Context["finding_resource_type"] = finding.ResourceType
+ if finding.Node != "" {
+ req.Context["finding_node"] = finding.Node
+ }
+
+ log.Debug().
+ Str("finding_id", req.FindingID).
+ Str("node", finding.Node).
+ Str("resource_id", finding.ResourceID).
+ Str("resource_name", finding.ResourceName).
+ Str("resource_type", finding.ResourceType).
+ Msg("Enriched request with finding context")
+}
+
// GuestInfo contains information about a guest (VM or container) found by VMID lookup
type GuestInfo struct {
Node string
@@ -1078,6 +1149,9 @@ func (s *Service) Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResp
return nil, err
}
+ // Enrich request with finding context if this is a "help me fix" request
+ s.enrichRequestFromFinding(&req)
+
s.mu.RLock()
defaultProvider := s.provider
agentServer := s.agentServer
@@ -1271,6 +1345,9 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
return nil, err
}
+ // Enrich request with finding context if this is a "help me fix" request
+ s.enrichRequestFromFinding(&req)
+
s.mu.RLock()
defaultProvider := s.provider
agentServer := s.agentServer
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index b6d6f4754e..ae8c5b5daa 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -2591,3 +2591,234 @@ func TestService_GetDebugContext_Extended(t *testing.T) {
t.Error("Expected custom context preview to be truncated")
}
}
+
+func TestService_EnrichRequestFromFinding(t *testing.T) {
+ svc := NewService(nil, nil)
+
+ // Setup patrol service with a mock finding
+ mockState := &mockStateProvider{
+ state: models.StateSnapshot{},
+ }
+ svc.stateProvider = mockState
+ svc.patrolService = NewPatrolService(svc, mockState)
+
+ // Add a finding to the store
+ finding := &Finding{
+ ID: "test-finding-123",
+ Node: "minipc",
+ ResourceID: "delly:minipc:112",
+ ResourceName: "debian-go",
+ ResourceType: "container",
+ Title: "Test Finding",
+ Description: "Test description",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryCapacity,
+ }
+ svc.patrolService.GetFindings().Add(finding)
+
+ // Test 1: Enrich request with finding context
+ req := ExecuteRequest{
+ FindingID: "test-finding-123",
+ Prompt: "Help me fix this",
+ }
+ svc.enrichRequestFromFinding(&req)
+
+ if req.Context["node"] != "minipc" {
+ t.Errorf("Expected node 'minipc', got %v", req.Context["node"])
+ }
+ if req.Context["guestName"] != "debian-go" {
+ t.Errorf("Expected guestName 'debian-go', got %v", req.Context["guestName"])
+ }
+ if req.TargetID != "delly:minipc:112" {
+ t.Errorf("Expected TargetID 'delly:minipc:112', got %s", req.TargetID)
+ }
+ if req.TargetType != "container" {
+ t.Errorf("Expected TargetType 'container', got %s", req.TargetType)
+ }
+ if req.Context["finding_node"] != "minipc" {
+ t.Errorf("Expected finding_node 'minipc', got %v", req.Context["finding_node"])
+ }
+
+ // Test 2: Don't overwrite existing context
+ req2 := ExecuteRequest{
+ FindingID: "test-finding-123",
+ TargetID: "existing-target",
+ TargetType: "existing-type",
+ Context: map[string]interface{}{
+ "node": "existing-node",
+ "guestName": "existing-name",
+ },
+ }
+ svc.enrichRequestFromFinding(&req2)
+
+ if req2.Context["node"] != "existing-node" {
+ t.Errorf("Should not overwrite existing node, got %v", req2.Context["node"])
+ }
+ if req2.Context["guestName"] != "existing-name" {
+ t.Errorf("Should not overwrite existing guestName, got %v", req2.Context["guestName"])
+ }
+ if req2.TargetID != "existing-target" {
+ t.Errorf("Should not overwrite existing TargetID, got %s", req2.TargetID)
+ }
+ // But finding_* fields should still be added
+ if req2.Context["finding_node"] != "minipc" {
+ t.Errorf("Expected finding_node 'minipc', got %v", req2.Context["finding_node"])
+ }
+
+ // Test 3: No finding ID - should be a no-op
+ req3 := ExecuteRequest{
+ Prompt: "Just a question",
+ }
+ svc.enrichRequestFromFinding(&req3)
+ if req3.Context != nil && len(req3.Context) > 0 {
+ t.Error("Should not add context when no FindingID")
+ }
+
+ // Test 4: Non-existent finding ID - should be a no-op
+ req4 := ExecuteRequest{
+ FindingID: "non-existent",
+ Prompt: "Help",
+ }
+ svc.enrichRequestFromFinding(&req4)
+ if req4.Context != nil && len(req4.Context) > 0 {
+ t.Error("Should not add context when finding not found")
+ }
+}
+
+// TestService_FindingContextInSystemPrompt verifies that when a FindingID is provided,
+// the system prompt includes proper routing instructions derived from the finding's node.
+// This is the integration test that would have caught the original bug.
+func TestService_FindingContextInSystemPrompt(t *testing.T) {
+ tmpDir := t.TempDir()
+ persistence := config.NewConfigPersistence(tmpDir)
+ svc := NewService(persistence, nil)
+ svc.cfg = &config.AIConfig{Enabled: true}
+
+ // Setup patrol service with a finding that has node info
+ mockState := &mockStateProvider{
+ state: models.StateSnapshot{
+ Containers: []models.Container{
+ {VMID: 112, Node: "minipc", Name: "debian-go", Instance: "delly"},
+ },
+ },
+ }
+ svc.stateProvider = mockState
+ svc.patrolService = NewPatrolService(svc, mockState)
+
+ // Add a finding with node context
+ finding := &Finding{
+ ID: "disk-growth-finding",
+ Node: "minipc",
+ ResourceID: "delly:minipc:112",
+ ResourceName: "debian-go",
+ ResourceType: "container",
+ Title: "Container disk usage growing",
+ Description: "Disk growing at 4% per day",
+ Severity: FindingSeverityWarning,
+ Category: FindingCategoryCapacity,
+ }
+ svc.patrolService.GetFindings().Add(finding)
+
+ // Create a request like "Get Help" would - only FindingID provided
+ req := ExecuteRequest{
+ FindingID: "disk-growth-finding",
+ Prompt: "Help me fix this disk issue",
+ }
+
+ // Enrich the request (this is what Execute() does now)
+ svc.enrichRequestFromFinding(&req)
+
+ // Build the system prompt
+ prompt := svc.buildSystemPrompt(req)
+
+ // Verify the prompt includes routing context
+ if !strings.Contains(prompt, "minipc") {
+ t.Error("System prompt should include the node name 'minipc' for routing")
+ }
+ if !strings.Contains(prompt, "debian-go") {
+ t.Error("System prompt should include the resource name 'debian-go'")
+ }
+ if !strings.Contains(prompt, "target_host") || !strings.Contains(prompt, "minipc") {
+ t.Error("System prompt should include ROUTING instructions mentioning target_host=minipc")
+ }
+}
+
+// TestService_FindingContextCommandRouting verifies that commands route correctly
+// when ExecuteStream is called with a FindingID. This is an end-to-end test.
+func TestService_FindingContextCommandRouting(t *testing.T) {
+ // Track which agent the command was routed to
+ routedToAgent := ""
+
+ mockAgentServer := &mockAgentServer{
+ agents: []agentexec.ConnectedAgent{
+ {AgentID: "agent-delly", Hostname: "delly"},
+ {AgentID: "agent-minipc", Hostname: "minipc"},
+ },
+ executeFunc: func(ctx context.Context, agentID string, cmd agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ routedToAgent = agentID
+ return &agentexec.CommandResultPayload{
+ Success: true,
+ Stdout: "Command output",
+ }, nil
+ },
+ }
+
+ tmpDir := t.TempDir()
+ persistence := config.NewConfigPersistence(tmpDir)
+ svc := NewService(persistence, mockAgentServer)
+ svc.cfg = &config.AIConfig{Enabled: true}
+ svc.limits = executionLimits{
+ chatSlots: make(chan struct{}, 10),
+ patrolSlots: make(chan struct{}, 10),
+ }
+ svc.policy = &mockPolicy{decision: agentexec.PolicyAllow}
+
+ // Setup patrol service with finding
+ mockState := &mockStateProvider{
+ state: models.StateSnapshot{
+ Containers: []models.Container{
+ {VMID: 112, Node: "minipc", Name: "debian-go", Instance: "delly"},
+ },
+ },
+ }
+ svc.stateProvider = mockState
+ svc.patrolService = NewPatrolService(svc, mockState)
+
+ // Add finding on node "minipc"
+ finding := &Finding{
+ ID: "test-routing-finding",
+ Node: "minipc",
+ ResourceID: "delly:minipc:112",
+ ResourceName: "debian-go",
+ ResourceType: "container",
+ }
+ svc.patrolService.GetFindings().Add(finding)
+
+ // Create request with finding ID (like "Get Help" does)
+ req := ExecuteRequest{
+ FindingID: "test-routing-finding",
+ Prompt: "Check disk usage",
+ }
+
+ // Enrich the request
+ svc.enrichRequestFromFinding(&req)
+
+ // Now execute a command tool call - should route to minipc
+ tc := providers.ToolCall{
+ Name: "run_command",
+ Input: map[string]interface{}{
+ "command": "df -h",
+ },
+ }
+
+ result, exec := svc.executeTool(context.Background(), req, tc)
+
+ if !exec.Success {
+ t.Errorf("Command execution failed: %s", result)
+ }
+
+ // Verify it routed to the correct agent (minipc, not delly)
+ if routedToAgent != "agent-minipc" {
+ t.Errorf("Expected command to route to agent-minipc, but went to: %s", routedToAgent)
+ }
+}
diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.go
index da94f8d78e..a9068761c1 100644
--- a/internal/notifications/notifications_test.go
+++ b/internal/notifications/notifications_test.go
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
"time"
@@ -642,6 +643,7 @@ func TestRenderWebhookURL_SuccessCases(t *testing.T) {
func TestSendTestNotificationApprise(t *testing.T) {
nm := NewNotificationManager("")
+ defer nm.Stop() // Clean up background queue to prevent lingering callbacks
nm.SetEmailConfig(EmailConfig{Enabled: false})
// Test 1: Apprise not enabled should return error
@@ -660,6 +662,7 @@ func TestSendTestNotificationApprise(t *testing.T) {
// Test 2: Apprise enabled with CLI mode should invoke executor
done := make(chan struct{})
+ var once sync.Once
var capturedArgs []string
nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
@@ -667,7 +670,8 @@ func TestSendTestNotificationApprise(t *testing.T) {
t.Fatalf("expected CLI path 'apprise', got %q", path)
}
capturedArgs = append([]string(nil), args...)
- close(done)
+ // Use sync.Once to safely close channel even if callback is invoked multiple times
+ once.Do(func() { close(done) })
return []byte("success"), nil
}
@@ -717,11 +721,13 @@ func TestSendTestAppriseWithConfig(t *testing.T) {
}
done := make(chan struct{})
+ var once sync.Once
var cliPath string
nm.appriseExec = func(ctx context.Context, path string, args []string) ([]byte, error) {
cliPath = path
- close(done)
+ // Use sync.Once to safely close channel even if callback is invoked multiple times
+ once.Do(func() { close(done) })
return []byte("ok"), nil
}