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): restore dismissed patrol findings and add regression tests

rcourtmana8e562034ec1
diff --git a/frontend-modern/src/api/__tests__/patrol.test.ts b/frontend-modern/src/api/__tests__/patrol.test.ts
new file mode 100644
index 0000000000..2c51492350
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/patrol.test.ts
@@ -0,0 +1,35 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+import { apiFetchJSON } from '@/utils/apiClient';
+import { dismissFinding, undismissFinding } from '@/api/patrol';
+
+describe('patrol api helpers', () => {
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ apiFetchJSONMock.mockResolvedValue({ success: true, message: 'ok' } as any);
+ });
+
+ it('dismissFinding calls dismiss endpoint', async () => {
+ await dismissFinding('finding-1', 'not_an_issue', 'false positive');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/dismiss', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-1', reason: 'not_an_issue', note: 'false positive' }),
+ });
+ });
+
+ it('undismissFinding calls undismiss endpoint', async () => {
+ await undismissFinding('finding-1');
+
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/undismiss', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: 'finding-1' }),
+ });
+ });
+});
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 835d017c4c..6733332a42 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -185,6 +185,17 @@ export async function dismissFinding(
});
}
+/**
+ * Restore a dismissed/suppressed finding back to active state.
+ * @param findingId The ID of the finding to restore
+ */
+export async function undismissFinding(findingId: string): Promise<{ success: boolean; message: string }> {
+ return apiFetchJSON('/api/ai/patrol/undismiss', {
+ method: 'POST',
+ body: JSON.stringify({ finding_id: findingId }),
+ });
+}
+
/**
* Set or update a user note on a finding
* Notes provide context that Patrol sees on future runs.
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index 29b534d190..bc5b7c5ba3 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -316,6 +316,18 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
setDismissingId(null);
};
+ const handleRestore = async (finding: UnifiedFinding, e: Event) => {
+ e.stopPropagation();
+ setActionLoading(finding.id);
+ const ok = await aiIntelligenceStore.restoreFinding(finding.id);
+ setActionLoading(null);
+ if (ok) {
+ notificationStore.success('Finding restored');
+ } else {
+ notificationStore.error('Failed to restore finding');
+ }
+ };
+
const handleSnooze = async (finding: UnifiedFinding, durationHours: number, e: Event) => {
e.stopPropagation();
setActionLoading(finding.id);
@@ -612,6 +624,19 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</svg>
</button>
</Show>
+ <Show when={finding.status === 'dismissed'}>
+ <button
+ type="button"
+ onClick={(e) => handleRestore(finding, e)}
+ class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
+ title="Restore"
+ disabled={actionLoading() === finding.id}
+ >
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h11M7 6l-4 4 4 4M21 14v4a2 2 0 01-2 2H9" />
+ </svg>
+ </button>
+ </Show>
{/* Expand indicator */}
<svg
class={`w-4 h-4 text-gray-400 transition-transform ${expandedId() === finding.id ? 'rotate-180' : ''}`}
@@ -784,6 +809,18 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
</div>
</Show>
+ <Show when={finding.status === 'dismissed'}>
+ <div class="mt-3 flex flex-wrap gap-2 text-xs">
+ <button
+ type="button"
+ onClick={(e) => handleRestore(finding, e)}
+ class="px-2 py-1 rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700"
+ disabled={actionLoading() === finding.id}
+ >
+ Restore
+ </button>
+ </div>
+ </Show>
{/* Inline dismiss confirmation */}
<Show when={dismissingId() === finding.id}>
<div class="mt-2 p-2 rounded border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20">
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index 226a98764c..f0adf6e4f6 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -9,7 +9,7 @@
import { createSignal } from 'solid-js';
import { AIAPI } from '@/api/ai';
-import { acknowledgeFinding, snoozeFinding, dismissFinding, setFindingNote } from '@/api/patrol';
+import { acknowledgeFinding, snoozeFinding, dismissFinding, undismissFinding, setFindingNote } from '@/api/patrol';
import type {
RemediationPlan,
CircuitBreakerStatus,
@@ -273,6 +273,17 @@ export const aiIntelligenceStore = {
}
},
+ async restoreFinding(findingId: string) {
+ try {
+ await undismissFinding(findingId);
+ await this.loadFindings();
+ return true;
+ } catch (e) {
+ logger.error('Failed to restore finding:', e);
+ return false;
+ }
+ },
+
async setFindingNote(findingId: string, note: string) {
try {
await setFindingNote(findingId, note);
diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.go
index 4a7e4ac56d..fee6f7c7c1 100644
--- a/internal/api/ai_handlers_patrol_actions_additional_test.go
+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go
@@ -15,14 +15,16 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
-func setupAIHandlerWithPatrol(t *testing.T) (*AISettingsHandler, *ai.PatrolService, *unified.UnifiedStore, *learning.LearningStore) {
+func setupAIHandlerWithPatrolAtPath(t *testing.T, dataPath string) (*AISettingsHandler, *ai.PatrolService, *unified.UnifiedStore, *learning.LearningStore, *config.ConfigPersistence) {
t.Helper()
- tmp := t.TempDir()
- cfg := &config.Config{DataPath: tmp}
- persistence := config.NewConfigPersistence(tmp)
+ cfg := &config.Config{DataPath: dataPath}
+ persistence := config.NewConfigPersistence(dataPath)
handler := newTestAISettingsHandler(cfg, persistence, nil)
handler.legacyAIService.SetStateProvider(&stubStateProvider{})
+ if err := handler.SetPatrolFindingsPersistence(ai.NewFindingsPersistenceAdapter(persistence)); err != nil {
+ t.Fatalf("set patrol findings persistence: %v", err)
+ }
patrol := handler.legacyAIService.GetPatrolService()
if patrol == nil {
@@ -35,6 +37,13 @@ func setupAIHandlerWithPatrol(t *testing.T) (*AISettingsHandler, *ai.PatrolServi
learningStore := learning.NewLearningStore(learning.LearningStoreConfig{})
handler.SetLearningStore(learningStore)
+ return handler, patrol, unifiedStore, learningStore, persistence
+}
+
+func setupAIHandlerWithPatrol(t *testing.T) (*AISettingsHandler, *ai.PatrolService, *unified.UnifiedStore, *learning.LearningStore) {
+ t.Helper()
+
+ handler, patrol, unifiedStore, learningStore, _ := setupAIHandlerWithPatrolAtPath(t, t.TempDir())
return handler, patrol, unifiedStore, learningStore
}
@@ -296,6 +305,110 @@ func TestHandleSuppressFinding_SetsSuppressed(t *testing.T) {
}
}
+func TestHandleUndismissFinding_RestoresDismissedState(t *testing.T) {
+ handler, patrol, unifiedStore, _ := setupAIHandlerWithPatrol(t)
+
+ detectedAt := time.Now().Add(-2 * time.Hour)
+ addPatrolFinding(t, patrol, "finding-undismiss", detectedAt)
+ addUnifiedFinding(unifiedStore, "finding-undismiss", detectedAt)
+
+ if !patrol.GetFindings().Dismiss("finding-undismiss", "not_an_issue", "false positive") {
+ t.Fatalf("expected patrol dismiss to succeed")
+ }
+ if !unifiedStore.Dismiss("finding-undismiss", "not_an_issue", "false positive") {
+ t.Fatalf("expected unified dismiss to succeed")
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/undismiss", strings.NewReader(`{"finding_id":"finding-undismiss"}`))
+ rec := httptest.NewRecorder()
+
+ handler.HandleUndismissFinding(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+
+ patrolFinding := patrol.GetFindings().Get("finding-undismiss")
+ if patrolFinding == nil {
+ t.Fatalf("expected patrol finding to exist")
+ }
+ if patrolFinding.DismissedReason != "" || patrolFinding.Suppressed {
+ t.Fatalf("expected patrol finding to be restored, got dismissed_reason=%q suppressed=%v", patrolFinding.DismissedReason, patrolFinding.Suppressed)
+ }
+
+ unifiedFinding := unifiedStore.Get("finding-undismiss")
+ if unifiedFinding == nil {
+ t.Fatalf("expected unified finding to exist")
+ }
+ if unifiedFinding.DismissedReason != "" || unifiedFinding.Suppressed {
+ t.Fatalf("expected unified finding to be restored, got dismissed_reason=%q suppressed=%v", unifiedFinding.DismissedReason, unifiedFinding.Suppressed)
+ }
+}
+
+func TestHandleUndismissFinding_NotFound(t *testing.T) {
+ handler, _, _, _ := setupAIHandlerWithPatrol(t)
+
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/undismiss", strings.NewReader(`{"finding_id":"missing"}`))
+ rec := httptest.NewRecorder()
+
+ handler.HandleUndismissFinding(rec, req)
+
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", rec.Code)
+ }
+}
+
+func TestHandleUndismissFinding_PersistsAcrossRestart(t *testing.T) {
+ dataPath := t.TempDir()
+ handler, patrol, unifiedStore, _, persistence := setupAIHandlerWithPatrolAtPath(t, dataPath)
+
+ detectedAt := time.Now().Add(-2 * time.Hour)
+ addPatrolFinding(t, patrol, "finding-restart", detectedAt)
+ addUnifiedFinding(unifiedStore, "finding-restart", detectedAt)
+
+ dismissBody := `{"finding_id":"finding-restart","reason":"not_an_issue","note":"false positive"}`
+ dismissReq := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/dismiss", strings.NewReader(dismissBody))
+ dismissRec := httptest.NewRecorder()
+ handler.HandleDismissFinding(dismissRec, dismissReq)
+ if dismissRec.Code != http.StatusOK {
+ t.Fatalf("dismiss status = %d, want 200", dismissRec.Code)
+ }
+
+ undismissReq := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/undismiss", strings.NewReader(`{"finding_id":"finding-restart"}`))
+ undismissRec := httptest.NewRecorder()
+ handler.HandleUndismissFinding(undismissRec, undismissReq)
+ if undismissRec.Code != http.StatusOK {
+ t.Fatalf("undismiss status = %d, want 200", undismissRec.Code)
+ }
+
+ if err := patrol.GetFindings().ForceSave(); err != nil {
+ t.Fatalf("force save: %v", err)
+ }
+
+ onDisk, err := persistence.LoadAIFindings()
+ if err != nil {
+ t.Fatalf("load on-disk findings: %v", err)
+ }
+ record := onDisk.Findings["finding-restart"]
+ if record == nil {
+ t.Fatalf("expected finding-restart to be on disk")
+ }
+ if record.DismissedReason != "" || record.Suppressed {
+ t.Fatalf("expected on-disk finding restored, got dismissed_reason=%q suppressed=%v", record.DismissedReason, record.Suppressed)
+ }
+
+ handlerAfterRestart, patrolAfterRestart, _, _, _ := setupAIHandlerWithPatrolAtPath(t, dataPath)
+ _ = handlerAfterRestart
+
+ reloaded := patrolAfterRestart.GetFindings().Get("finding-restart")
+ if reloaded == nil {
+ t.Fatalf("expected finding to reload after restart")
+ }
+ if reloaded.DismissedReason != "" || reloaded.Suppressed {
+ t.Fatalf("expected reloaded finding restored, got dismissed_reason=%q suppressed=%v", reloaded.DismissedReason, reloaded.Suppressed)
+ }
+}
+
func TestHandleGetFindingsHistory_StartTimeFilter(t *testing.T) {
handler, patrol, _, _ := setupAIHandlerWithPatrol(t)
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index b19f791ddc..dc78b098f3 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -12,6 +12,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"
)
func newTestConfigHandlers(t *testing.T, cfg *config.Config) *ConfigHandlers {
@@ -326,6 +327,7 @@ func TestIsPulseAgentToken(t *testing.T) {
}{
{"pulse-monitor@pam!pulse-1234567890", true},
{"pulse-monitor@pbs!pulse-1234567890", true},
+ {"pulse-monitor@pam!pulse-pulse-example-com", true},
{"pulse-monitor@pam!pulse-", true},
{"pulse-monitor@pam!token1", false},
{"root@pam!mytoken", false},
@@ -833,3 +835,136 @@ func TestAutoRegisterAgentDifferentHostsSameNameStaySeparate(t *testing.T) {
t.Fatalf("expected 2 PVE instances (different hosts), got %d", len(cfg.PVEInstances))
}
}
+
+func TestHandleAutoRegisterStoresFingerprintForNewPVE(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ originalDetectPVECluster := detectPVECluster
+ detectPVECluster = func(clientConfig proxmox.ClientConfig, nodeName string, existingEndpoints []config.ClusterEndpoint) (bool, string, []config.ClusterEndpoint) {
+ return false, "", nil
+ }
+ defer func() { detectPVECluster = originalDetectPVECluster }()
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ pveServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer pveServer.Close()
+
+ const authToken = "TEMP-TOKEN"
+ tokenHash := internalauth.HashAPIToken(authToken)
+ handler.codeMutex.Lock()
+ handler.setupCodes[tokenHash] = &SetupCode{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: pveServer.URL,
+ TokenID: "pulse-monitor@pam!pulse-1772387119",
+ TokenValue: "secret-token",
+ ServerName: "pve01",
+ Source: "agent",
+ AuthToken: authToken,
+ }
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAutoRegister(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("registration failed: status=%d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("expected 1 PVE instance, got %d", len(cfg.PVEInstances))
+ }
+
+ expectedFP, err := tlsutil.FetchFingerprint(pveServer.URL)
+ if err != nil {
+ t.Fatalf("failed to fetch expected fingerprint: %v", err)
+ }
+
+ if cfg.PVEInstances[0].Fingerprint == "" {
+ t.Fatalf("expected non-empty fingerprint on auto-registered node")
+ }
+ if cfg.PVEInstances[0].Fingerprint != expectedFP {
+ t.Fatalf("fingerprint mismatch: got %q want %q", cfg.PVEInstances[0].Fingerprint, expectedFP)
+ }
+}
+
+func TestHandleAutoRegisterUpdateDoesNotClearFingerprintWhenFetchFails(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ originalDetectPVECluster := detectPVECluster
+ detectPVECluster = func(clientConfig proxmox.ClientConfig, nodeName string, existingEndpoints []config.ClusterEndpoint) (bool, string, []config.ClusterEndpoint) {
+ return false, "", nil
+ }
+ defer func() { detectPVECluster = originalDetectPVECluster }()
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "pve01",
+ Host: "https://127.0.0.1:1", // Force FetchFingerprint to fail quickly
+ TokenName: "pulse-monitor@pam!pulse-1700000000",
+ TokenValue: "old-secret",
+ Fingerprint: "existing-fingerprint",
+ VerifySSL: true,
+ Source: "agent",
+ },
+ },
+ }
+ handler := newTestConfigHandlers(t, cfg)
+
+ const authToken = "TEMP-TOKEN"
+ tokenHash := internalauth.HashAPIToken(authToken)
+ handler.codeMutex.Lock()
+ handler.setupCodes[tokenHash] = &SetupCode{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://127.0.0.1:1",
+ TokenID: "pulse-monitor@pam!pulse-1700000001",
+ TokenValue: "new-secret",
+ ServerName: "pve01",
+ Source: "agent",
+ AuthToken: authToken,
+ }
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAutoRegister(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("re-registration failed: status=%d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("expected 1 PVE instance, got %d", len(cfg.PVEInstances))
+ }
+ if cfg.PVEInstances[0].Fingerprint != "existing-fingerprint" {
+ t.Fatalf("expected existing fingerprint to be preserved, got %q", cfg.PVEInstances[0].Fingerprint)
+ }
+}