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(ui): update patrol interface with new tiering and status indicators

rcourtman70169f087f00
diff --git a/frontend-modern/src/App.tsx b/frontend-modern/src/App.tsx
index d34d822cf6..e24cf340a2 100644
--- a/frontend-modern/src/App.tsx
+++ b/frontend-modern/src/App.tsx
@@ -54,7 +54,6 @@ import type { UpdateStatus } from './api/updates';
import { AIChat } from './components/AI/Chat';
import { AIStatusIndicator } from './components/AI/AIStatusIndicator';
import { aiChatStore } from './stores/aiChat';
-import { getPatrolStatus } from './api/patrol';
import { useResourcesAsLegacy } from './hooks/useResources';
import { updateSystemSettingsFromResponse, markSystemSettingsLoadedWithDefaults } from './stores/systemSettings';
import { initKioskMode, isKioskMode, setKioskMode, subscribeToKioskMode } from './utils/url';
@@ -1043,17 +1042,6 @@ function AppLayout(props: {
const navigate = useNavigate();
const location = useLocation();
- // Track patrol license status for Pro badge
- const [patrolLicenseRequired, setPatrolLicenseRequired] = createSignal(false);
- onMount(async () => {
- try {
- const status = await getPatrolStatus();
- setPatrolLicenseRequired(status.license_required ?? false);
- } catch {
- // Ignore errors - default to not showing badge
- }
- });
-
const readSeenPlatforms = (): Record<string, boolean> => {
if (typeof window === 'undefined') return {};
try {
@@ -1265,7 +1253,7 @@ function AppLayout(props: {
label: 'Patrol',
route: '/ai',
tooltip: 'Pulse Patrol monitoring and analysis',
- badge: patrolLicenseRequired() ? 'pro' : null,
+ badge: null, // Patrol is free with BYOK; auto-fix is Pro
count: undefined,
breakdown: undefined,
icon: <PulsePatrolLogo class="w-4 h-4 shrink-0" />,
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 5f9cf2935d..2353bf0d09 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -242,24 +242,6 @@ export async function reinvestigateFinding(findingId: string): Promise<{ success
});
}
-/**
- * Approve and execute a proposed fix
- */
-export async function approveFix(approvalId: string): Promise<{ success: boolean; message: string; output?: string }> {
- return apiFetchJSON(`/api/ai/approvals/${approvalId}/approve`, {
- method: 'POST',
- });
-}
-
-/**
- * Deny/skip a proposed fix
- */
-export async function denyFix(approvalId: string): Promise<{ success: boolean; message: string }> {
- return apiFetchJSON(`/api/ai/approvals/${approvalId}/deny`, {
- method: 'POST',
- });
-}
-
/**
* Severity color mapping for UI
*/
diff --git a/frontend-modern/src/components/AI/AIStatusIndicator.tsx b/frontend-modern/src/components/AI/AIStatusIndicator.tsx
index 68b501c8c7..09cb89ea69 100644
--- a/frontend-modern/src/components/AI/AIStatusIndicator.tsx
+++ b/frontend-modern/src/components/AI/AIStatusIndicator.tsx
@@ -43,9 +43,9 @@ export function AIStatusIndicator() {
// Count anomalies by severity
const anomalyCounts = createMemo(() => {
const anomalies = anomalyData.anomalies();
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
+ const counts: Record<string, number> = { critical: 0, high: 0, medium: 0, low: 0 };
for (const a of anomalies) {
- counts[a.severity]++;
+ counts[a.severity] = (counts[a.severity] || 0) + 1;
}
return counts;
});
@@ -94,9 +94,9 @@ export function AIStatusIndicator() {
const tooltipText = createMemo(() => {
const parts: string[] = [];
- // Patrol status
+ // Patrol status — show findings whenever patrol is enabled (not just when running)
const s = status();
- if (s?.enabled && s?.running) {
+ if (s?.enabled) {
if (s.error_count && s.error_count > 0) parts.push(`${s.error_count} patrol errors`);
if (s.summary.critical > 0) parts.push(`${s.summary.critical} critical findings`);
if (s.summary.warning > 0) parts.push(`${s.summary.warning} warnings`);
@@ -139,15 +139,6 @@ export function AIStatusIndicator() {
}
return 'Pulse Baseline Learning active';
}
- if (s?.license_required) {
- if (s.license_status === 'active') {
- return 'Pulse Patrol is not included in this license tier';
- }
- if (s.license_status === 'expired') {
- return 'Pulse Patrol license expired';
- }
- return 'Pulse Patrol requires Pulse Pro';
- }
return 'Pulse: All systems healthy';
}
diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsx
index 45a2e524f8..534df20b6c 100644
--- a/frontend-modern/src/components/AI/FindingsPanel.tsx
+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx
@@ -90,6 +90,9 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const [lastHashScrolled, setLastHashScrolled] = createSignal<string | null>(null);
const [editingNoteId, setEditingNoteId] = createSignal<string | null>(null);
const [noteText, setNoteText] = createSignal('');
+ const [dismissingId, setDismissingId] = createSignal<string | null>(null);
+ const [dismissReason, setDismissReason] = createSignal<'not_an_issue' | 'expected_behavior' | 'will_fix_later'>('will_fix_later');
+ const [dismissNote, setDismissNote] = createSignal('');
// Legacy remediation plans (generic plans without real execution)
const [remediationPlans, setRemediationPlans] = createSignal<RemediationPlan[]>([]);
@@ -177,7 +180,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
if (filter() === 'active') {
findings = findings.filter(f => f.status === 'active');
} else if (filter() === 'resolved') {
- findings = findings.filter(f => f.status === 'resolved' || f.status === 'dismissed');
+ findings = findings.filter(f => f.status === 'resolved' || f.status === 'dismissed' || f.status === 'snoozed');
} else if (filter() === 'attention') {
const attentionIds = new Set(aiIntelligenceStore.findingsNeedingAttention.map(f => f.id));
findings = findings.filter(f => attentionIds.has(f.id));
@@ -195,8 +198,10 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
// Outcome priority: findings needing attention sort first
const outcomeOrder: Record<string, number> = {
fix_verification_failed: 0,
+ fix_failed: 0,
timed_out: 1,
needs_attention: 1,
+ cannot_fix: 1,
fix_queued: 2,
};
@@ -279,12 +284,20 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
}
};
- const handleDismiss = async (finding: UnifiedFinding, reason: 'not_an_issue' | 'expected_behavior' | 'will_fix_later', e: Event) => {
+ const handleStartDismiss = (finding: UnifiedFinding, reason: 'not_an_issue' | 'expected_behavior' | 'will_fix_later', e: Event) => {
e.stopPropagation();
- const note = window.prompt('Add an optional note (for learning context):', '') ?? '';
- setActionLoading(finding.id);
- const ok = await aiIntelligenceStore.dismissFinding(finding.id, reason, note);
+ setDismissReason(reason);
+ setDismissNote('');
+ setDismissingId(finding.id);
+ setExpandedId(finding.id);
+ };
+
+ const handleConfirmDismiss = async (findingId: string, e: Event) => {
+ e.stopPropagation();
+ setActionLoading(findingId);
+ const ok = await aiIntelligenceStore.dismissFinding(findingId, dismissReason(), dismissNote());
setActionLoading(null);
+ setDismissingId(null);
if (ok) {
notificationStore.success('Finding dismissed');
} else {
@@ -292,6 +305,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
}
};
+ const handleCancelDismiss = (e: Event) => {
+ e.stopPropagation();
+ setDismissingId(null);
+ };
+
const handleSnooze = async (finding: UnifiedFinding, durationHours: number, e: Event) => {
e.stopPropagation();
setActionLoading(finding.id);
@@ -340,6 +358,18 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
const date = new Date(isoString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
+
+ // Future dates (e.g. snoozedUntil)
+ if (diffMs < 0) {
+ const futureMins = Math.floor(Math.abs(diffMs) / 60000);
+ const futureHours = Math.floor(Math.abs(diffMs) / 3600000);
+ const futureDays = Math.floor(Math.abs(diffMs) / 86400000);
+ if (futureMins < 60) return `in ${futureMins}m`;
+ if (futureHours < 24) return `in ${futureHours}h`;
+ if (futureDays < 7) return `in ${futureDays}d`;
+ return date.toLocaleDateString();
+ }
+
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
@@ -395,12 +425,18 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
return `Fix applied by Patrol ${resolvedTime}`;
case 'resolved':
return `Resolved by Patrol ${resolvedTime}`;
+ case 'fix_failed':
+ return `Resolved after fix failed ${resolvedTime}`;
+ case 'fix_queued':
+ return `Resolved while fix was pending ${resolvedTime}`;
case 'fix_verification_failed':
return `Resolved after failed verification ${resolvedTime}`;
case 'timed_out':
return `Resolved after investigation timeout ${resolvedTime}`;
case 'cannot_fix':
return `Resolved manually ${resolvedTime}`;
+ case 'needs_attention':
+ return `Resolved after manual review ${resolvedTime}`;
default:
return `Issue no longer detected ${resolvedTime}`;
}
@@ -436,9 +472,11 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
<span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${
finding.status === 'resolved'
? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'
+ : finding.status === 'snoozed'
+ ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300'
: 'bg-gray-200 text-gray-600 dark:bg-gray-600 dark:text-gray-300'
}`}>
- {finding.status === 'resolved' ? 'Resolved' : 'Dismissed'}
+ {finding.status === 'resolved' ? 'Resolved' : finding.status === 'snoozed' ? 'Snoozed' : 'Dismissed'}
</span>
</Show>
{/* Source badge - only show when requested */}
@@ -474,8 +512,8 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
class={`px-1.5 py-0.5 text-[10px] font-medium rounded flex items-center gap-1 ${investigationStatusColors[finding.investigationStatus!]}`}
title={`Investigation: ${investigationStatusLabels[finding.investigationStatus!]}`}
>
- <Show when={finding.investigationStatus === 'running'}>
- <span class="h-2 w-2 border border-current border-t-transparent rounded-full animate-spin" />
+ <Show when={finding.investigationStatus === 'running' || finding.investigationStatus === 'pending'}>
+ <span class={`h-2 w-2 rounded-full ${finding.investigationStatus === 'running' ? 'border border-current border-t-transparent animate-spin' : 'bg-current animate-pulse'}`} />
</Show>
{investigationStatusLabels[finding.investigationStatus!]}
</span>
@@ -508,6 +546,16 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
({finding.dismissedReason?.replace(/_/g, ' ')})
</span>
</Show>
+ <Show when={finding.status === 'snoozed' && finding.snoozedUntil}>
+ <span class="ml-2 text-blue-500 dark:text-blue-400">
+ snoozed until {formatTime(finding.snoozedUntil!)}
+ </span>
+ </Show>
+ <Show when={finding.acknowledgedAt && finding.status === 'active'}>
+ <span class="ml-2 text-gray-400 dark:text-gray-500">
+ acknowledged {formatTime(finding.acknowledgedAt!)}
+ </span>
+ </Show>
<Show when={finding.status === 'active' && finding.lastInvestigatedAt}>
<span class="ml-2 text-gray-400 dark:text-gray-500">
last investigated {formatTime(finding.lastInvestigatedAt!)}
@@ -542,9 +590,9 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
<button
type="button"
- onClick={(e) => handleDismiss(finding, 'will_fix_later', e)}
+ onClick={(e) => handleStartDismiss(finding, 'will_fix_later', e)}
class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
- title="Dismiss (Will fix later)"
+ title="Dismiss"
disabled={actionLoading() === finding.id}
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -698,7 +746,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
<button
type="button"
- onClick={(e) => handleDismiss(finding, 'not_an_issue', e)}
+ onClick={(e) => handleStartDismiss(finding, 'not_an_issue', e)}
class="px-2 py-1 rounded border border-red-200 text-red-700 dark:border-red-700 dark:text-red-300 hover:bg-red-50 dark:hover:bg-red-900/30"
disabled={actionLoading() === finding.id}
>
@@ -706,7 +754,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
<button
type="button"
- onClick={(e) => handleDismiss(finding, 'expected_behavior', e)}
+ onClick={(e) => handleStartDismiss(finding, 'expected_behavior', 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}
>
@@ -714,7 +762,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</button>
<button
type="button"
- onClick={(e) => handleDismiss(finding, 'will_fix_later', e)}
+ onClick={(e) => handleStartDismiss(finding, 'will_fix_later', 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}
>
@@ -722,6 +770,41 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {
</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">
+ <div class="flex items-center gap-2 mb-1.5">
+ <span class="text-xs font-medium text-red-700 dark:text-red-300">
+ Dismiss as: {dismissReason().replace(/_/g, ' ')}
+ </span>
+ </div>
+ <textarea
+ class="w-full text-xs px-2 py-1.5 rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 resize-none focus:outline-none focus:ring-1 focus:ring-red-400"
+ rows={2}
+ placeholder="Optional note (for learning context)..."
+ value={dismissNote()}
+ onInput={(e) => setDismissNote(e.currentTarget.value)}
+ onClick={(e) => e.stopPropagation()}
+ />
+ <div class="flex items-center gap-2 mt-1.5">
+ <button
+ type="button"
+ onClick={(e) => handleConfirmDismiss(finding.id, e)}
+ disabled={actionLoading() === finding.id}
+ class="px-2.5 py-1 text-xs font-medium text-white bg-red-600 hover:bg-red-700 disabled:bg-red-400 rounded transition-colors"
+ >
+ Confirm Dismiss
+ </button>
+ <button
+ type="button"
+ onClick={handleCancelDismiss}
+ class="px-2.5 py-1 text-xs font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </Show>
<Show when={finding.correlatedFindingIds && finding.correlatedFindingIds.length > 0}>
<div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
Related findings: {finding.correlatedFindingIds?.length}
diff --git a/frontend-modern/src/components/Settings/UnifiedAgents.tsx b/frontend-modern/src/components/Settings/UnifiedAgents.tsx
index 57b5336149..a0bcd85438 100644
--- a/frontend-modern/src/components/Settings/UnifiedAgents.tsx
+++ b/frontend-modern/src/components/Settings/UnifiedAgents.tsx
@@ -976,7 +976,7 @@ export const UnifiedAgents: Component = () => {
/>
Skip TLS certificate verification (self-signed certs; not recommended)
</label>
- <label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer" title="Allow Pulse Patrol to execute diagnostic and fix commands on this agent (requires Pulse Pro)">
+ <label class="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer" title="Allow Pulse Patrol to execute diagnostic and fix commands on this agent (auto-fix requires Pulse Pro)">
<input
type="checkbox"
checked={enableCommands()}
diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsx
index ba0eca47c2..4f7be68522 100644
--- a/frontend-modern/src/components/patrol/ApprovalSection.tsx
+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx
@@ -27,12 +27,12 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
) ?? null;
});
- // Load investigation details for expired approvals (to show proposed fix info)
+ // Load investigation details when outcome indicates a fix was proposed/executed
+ const fixRelatedOutcomes = new Set(['fix_queued', 'fix_executed', 'fix_failed', 'fix_verified', 'fix_verification_failed']);
const [investigation] = createResource(
- () => props.findingId,
- async (findingId) => {
- // Only load if outcome indicates a fix was queued but no pending approval
- if (props.investigationOutcome !== 'fix_queued' && props.investigationOutcome !== 'fix_executed' && props.investigationOutcome !== 'fix_failed' && props.investigationOutcome !== 'fix_verified' && props.investigationOutcome !== 'fix_verification_failed') {
+ () => ({ findingId: props.findingId, outcome: props.investigationOutcome }),
+ async ({ findingId, outcome }) => {
+ if (!outcome || !fixRelatedOutcomes.has(outcome)) {
return null;
}
try {
@@ -83,6 +83,8 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
} else {
notificationStore.error(result.error || 'Fix execution failed');
}
+ } else {
+ notificationStore.error('Failed to execute fix — no response from server');
}
} catch (err) {
notificationStore.error((err as Error).message || 'Failed to execute fix');
@@ -117,6 +119,8 @@ export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {
} else {
notificationStore.error(execResult.error || 'Fix execution failed');
}
+ } else {
+ notificationStore.error('Failed to execute fix — no response from server');
}
} catch (err) {
notificationStore.error((err as Error).message || 'Failed to execute fix');
diff --git a/frontend-modern/src/components/patrol/InvestigationMessages.tsx b/frontend-modern/src/components/patrol/InvestigationMessages.tsx
index 0c9cc61d8e..2678744daf 100644
--- a/frontend-modern/src/components/patrol/InvestigationMessages.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationMessages.tsx
@@ -14,7 +14,7 @@ interface InvestigationMessagesProps {
/** Returns true if a message has no displayable content */
function isEmptyMessage(msg: ChatMessage): boolean {
- return !msg.content && !msg.tool_calls?.length && !msg.tool_result;
+ return !msg.content && !msg.reasoning_content && !msg.tool_calls?.length && !msg.tool_result;
}
export const InvestigationMessages: Component<InvestigationMessagesProps> = (props) => {
@@ -58,6 +58,18 @@ export const InvestigationMessages: Component<InvestigationMessagesProps> = (pro
? 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 text-xs'
: 'bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200'
}`}>
+ {/* Reasoning content (extended thinking) */}
+ <Show when={msg.reasoning_content}>
+ <details class="mb-1">
+ <summary class="text-[10px] text-purple-600 dark:text-purple-400 cursor-pointer hover:underline">
+ Show reasoning
+ </summary>
+ <div class="mt-1 text-[10px] text-gray-500 dark:text-gray-400 whitespace-pre-wrap break-words border-l-2 border-purple-200 dark:border-purple-800 pl-2">
+ {msg.reasoning_content}
+ </div>
+ </details>
+ </Show>
+
{/* Text content */}
<Show when={msg.content}>
<div class="text-xs whitespace-pre-wrap break-words">{msg.content}</div>
diff --git a/frontend-modern/src/components/patrol/InvestigationSection.tsx b/frontend-modern/src/components/patrol/InvestigationSection.tsx
index f788485a77..70cdddf2eb 100644
--- a/frontend-modern/src/components/patrol/InvestigationSection.tsx
+++ b/frontend-modern/src/components/patrol/InvestigationSection.tsx
@@ -68,7 +68,7 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
const inv = investigation();
if (!inv) return true; // No investigation yet
if (inv.status === 'running') return false;
- return inv.status === 'failed' || inv.status === 'needs_attention' || inv.outcome === 'cannot_fix' || inv.outcome === 'timed_out' || inv.outcome === 'fix_verification_failed';
+ return inv.status === 'failed' || inv.status === 'needs_attention' || inv.outcome === 'cannot_fix' || inv.outcome === 'timed_out' || inv.outcome === 'fix_verification_failed' || inv.outcome === 'fix_failed';
};
const handleReinvestigate = async (e: Event) => {
@@ -148,6 +148,13 @@ export const InvestigationSection: Component<InvestigationSectionProps> = (props
<Show when={!investigation.loading && investigation()}>
{(inv) => (
<div class="space-y-2">
+ {/* Error message for failed investigations */}
+ <Show when={inv().error && (inv().status === 'failed' || inv().outcome === 'timed_out' || inv().outcome === 'fix_failed' || inv().outcome === 'fix_verification_failed' || inv().outcome === 'needs_attention' || inv().outcome === 'cannot_fix')}>
+ <div class="text-xs text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded p-2">
+ {inv().error}
+ </div>
+ </Show>
+
{/* Summary */}
<Show when={inv().summary}>
<div class="text-sm text-gray-600 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50 rounded p-2">
diff --git a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
index 93cd81f730..b3f6d7dbd1 100644
--- a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
+++ b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
@@ -7,8 +7,10 @@
import { Component, createResource, createMemo, Show } from 'solid-js';
import { getPatrolRunHistory, type PatrolRunRecord } from '@/api/patrol';
+import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import CheckCircleIcon from 'lucide-solid/icons/check-circle';
import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
+import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
interface PatrolStatusBarProps {
enabled?: boolean;
@@ -75,10 +77,29 @@ export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {
};
});
+ const circuitBreaker = () => aiIntelligenceStore.circuitBreakerStatus;
+
return (
<Show when={!runs.loading && stats()}>
{(s) => (
<div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-2">
+ {/* Circuit breaker warning */}
+ <Show when={circuitBreaker()?.state === 'open'}>
+ <div class="flex items-center gap-1.5 mb-1.5 pb-1.5 border-b border-red-200 dark:border-red-800">
+ <AlertTriangleIcon class="w-3.5 h-3.5 text-red-500" />
+ <span class="text-red-600 dark:text-red-400 font-medium text-xs">
+ AI circuit breaker tripped — Patrol paused after {circuitBreaker()!.consecutive_failures} consecutive failures
+ </span>
+ </div>
+ </Show>
+ <Show when={circuitBreaker()?.state === 'half-open'}>
+ <div class="flex items-center gap-1.5 mb-1.5 pb-1.5 border-b border-amber-200 dark:border-amber-800">
+ <AlertCircleIcon class="w-3.5 h-3.5 text-amber-500" />
+ <span class="text-amber-600 dark:text-amber-400 font-medium text-xs">
+ AI circuit breaker recovering — testing with next patrol run
+ </span>
+ </div>
+ </Show>
<div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
{/* Status */}
<div class="flex items-center gap-1.5">
diff --git a/frontend-modern/src/components/patrol/RemediationStatus.tsx b/frontend-modern/src/components/patrol/RemediationStatus.tsx
index 328257ab56..20fe01e91e 100644
--- a/frontend-modern/src/components/patrol/RemediationStatus.tsx
+++ b/frontend-modern/src/components/patrol/RemediationStatus.tsx
@@ -1,7 +1,8 @@
/**
* RemediationStatus
*
- * Post-execution display: shows command output, exit code, and rollback button.
+ * Post-execution display: shows success/failure status, command output,
+ * exit code, error details, and server message.
*/
import { Component, Show, createSignal } from 'solid-js';
@@ -42,6 +43,10 @@ export const RemediationStatus: Component<RemediationStatusProps> = (props) => {
<div class="text-red-600 dark:text-red-400 mt-1">{props.result.error}</div>
</Show>
+ <Show when={props.result.message && props.result.message !== props.result.error}>
+ <div class="text-gray-600 dark:text-gray-400 mt-1">{props.result.message}</div>
+ </Show>
+
<Show when={props.result.output}>
<button
type="button"
diff --git a/frontend-modern/src/components/patrol/RunToolCallTrace.tsx b/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
index 8440c612ff..10e9cddde7 100644
--- a/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
+++ b/frontend-modern/src/components/patrol/RunToolCallTrace.tsx
@@ -17,14 +17,19 @@ export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {
const [expanded, setExpanded] = createSignal(false);
const [expandedCall, setExpandedCall] = createSignal<string | null>(null);
- // Lazy-load tool calls when expanded
+ // Lazy-load tool calls when expanded — fetch small batch since the run is likely recent
const [toolCalls] = createResource(
() => expanded() ? props.runId : null,
async (runId) => {
if (!runId) return [];
try {
- const runs = await getPatrolRunHistoryWithToolCalls(50);
- const run = runs.find(r => r.id === runId);
+ // Start with a small fetch; if not found, widen the search
+ let runs = await getPatrolRunHistoryWithToolCalls(10);
+ let run = runs.find(r => r.id === runId);
+ if (!run) {
+ runs = await getPatrolRunHistoryWithToolCalls(50);
+ run = runs.find(r => r.id === runId);
+ }
return run?.tool_calls || [];
} catch {
return [];
diff --git a/frontend-modern/src/hooks/usePatrolStream.ts b/frontend-modern/src/hooks/usePatrolStream.ts
index 0d0b14dd16..840753e0ad 100644
--- a/frontend-modern/src/hooks/usePatrolStream.ts
+++ b/frontend-modern/src/hooks/usePatrolStream.ts
@@ -3,6 +3,7 @@
*
* Opens an EventSource to /api/ai/patrol/stream while the patrol is running,
* exposing reactive signals for the current phase, active tool, and token count.
+ * Automatically reconnects with exponential backoff on connection drops.
*/
import { createSignal, createEffect, onCleanup, type Accessor } from 'solid-js';
@@ -31,6 +32,10 @@ export interface PatrolStreamState {
errorMessage: Accessor<string>;
}
+const MAX_RECONNECT_ATTEMPTS = 5;
+const INITIAL_RECONNECT_DELAY_MS = 1000;
+const MAX_RECONNECT_DELAY_MS = 15000;
+
export function usePatrolStream(opts: UsePatrolStreamOptions): PatrolStreamState {
const [phase, setPhase] = createSignal('');
const [currentTool, setCurrentTool] = createSignal('');
@@ -39,8 +44,21 @@ export function usePatrolStream(opts: UsePatrolStreamOptions): PatrolStreamState
const [errorMessage, setErrorMessage] = createSignal('');
let es: EventSource | undefined;
+ let reconnectTimer: ReturnType<typeof setTimeout> | undefined;
+ let reconnectAttempts = 0;
+ // Whether the close was intentional (complete/error event or running=false)
+ let intentionalClose = false;
+
+ function clearReconnectTimer() {
+ if (reconnectTimer !== undefined) {
+ clearTimeout(reconnectTimer);
+ reconnectTimer = undefined;
+ }
+ }
function close() {
+ intentionalClose = true;
+ clearReconnectTimer();
if (es) {
es.close();
es = undefined;
@@ -48,14 +66,46 @@ export function usePatrolStream(opts: UsePatrolStreamOptions): PatrolStreamState
setIsStreaming(false);
}
+ function scheduleReconnect() {
+ if (intentionalClose || !opts.running()) {
+ return;
+ }
+ if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
+ logger.warn(`[PatrolStream] Max reconnect attempts (${MAX_RECONNECT_ATTEMPTS}) reached, giving up`);
+ opts.onError?.();
+ return;
+ }
+ const delay = Math.min(
+ INITIAL_RECONNECT_DELAY_MS * Math.pow(2, reconnectAttempts),
+ MAX_RECONNECT_DELAY_MS,
+ );
+ reconnectAttempts++;
+ logger.info(`[PatrolStream] Reconnecting in ${delay}ms (attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
+ clearReconnectTimer();
+ reconnectTimer = setTimeout(() => {
+ if (opts.running()) {
+ open();
+ }
+ }, delay);
+ }
+
function open() {
- close();
+ // Close existing connection without triggering intentionalClose
+ clearReconnectTimer();
+ if (es) {
+ es.close();
+ es = undefined;
+ }
+ setIsStreaming(false);
+ intentionalClose = false;
+
try {
es = new EventSource('/api/ai/patrol/stream');
es.onopen = () => {
logger.info('[PatrolStream] SSE connected');
setIsStreaming(true);
+ reconnectAttempts = 0; // Reset on successful connection
};
es.onmessage = (msg) => {
@@ -102,25 +152,41 @@ export function usePatrolStream(opts: UsePatrolStreamOptions): PatrolStreamState
setTokens(event.tokens);
}
} catch {
- // Ignore malformed events
+ logger.warn('[PatrolStream] Failed to parse SSE event');
}
};
es.onerror = () => {
- // Silently close on error — polling continues as fallback
- logger.warn('[PatrolStream] SSE error, closing');
- close();
- opts.onError?.();
+ logger.warn('[PatrolStream] SSE connection error');
+ if (es) {
+ es.close();
+ es = undefined;
+ }
+ setIsStreaming(false);
+ // Only reconnect if the close wasn't intentional and patrol is still running
+ if (!intentionalClose && opts.running()) {
+ scheduleReconnect();
+ } else {
+ opts.onError?.();
+ }
};
} catch {
// EventSource constructor can throw in some environments
- close();
+ if (es) {
+ es.close();
+ es = undefined;
+ }
+ setIsStreaming(false);
+ if (!intentionalClose && opts.running()) {
+ scheduleReconnect();
+ }
}
}
// Reactively open/close based on running state
createEffect(() => {
if (opts.running()) {
+ reconnectAttempts = 0;
open();
} else {
close();
diff --git a/frontend-modern/src/pages/AIIntelligence.tsx b/frontend-modern/src/pages/AIIntelligence.tsx
index e3d5050b8d..171ae9e382 100644
--- a/frontend-modern/src/pages/AIIntelligence.tsx
+++ b/frontend-modern/src/pages/AIIntelligence.tsx
@@ -18,6 +18,7 @@ import {
type PatrolRunRecord,
} from '@/api/patrol';
import { apiFetchJSON } from '@/utils/apiClient';
+import { notificationStore } from '@/stores/notifications';
import { renderMarkdown } from '@/components/AI/aiChatUtils';
interface ModelInfo {
@@ -164,18 +165,27 @@ export function AIIntelligence() {
}
});
+ // Detect when saved patrol model is no longer in the available models list
+ const patrolModelStale = createMemo(() => {
+ const model = patrolModel();
+ const models = availableModels();
+ if (!model || models.length === 0) return false;
+ return !models.some(m => m.id === model);
+ });
+
+ // Same check for auto-fix model
+ const autoFixModelStale = createMemo(() => {
+ const model = autoFixModel();
+ const models = availableModels();
+ if (!model || models.length === 0) return false;
+ return !models.some(m => m.id === model);
+ });
+
// License feature gates
const alertAnalysisLocked = createMemo(() => !hasFeature('ai_alerts'));
const autoFixLocked = createMemo(() => !hasFeature('ai_autofix'));
const [selectedRun, setSelectedRun] = createSignal<PatrolRunRecord | null>(null);
const [showRunAnalysis, setShowRunAnalysis] = createSignal(true);
- // TODO: Wire up scope context and token usage display in patrol run details
- // const scopeContext = createMemo(() => splitScopeContext(selectedRun()?.scope_context));
- // const runTokenUsage = createMemo(() => formatTokenUsage(selectedRun()));
- // TODO: Wire up selected run findings display
- // const selectedRunFindings = createMemo(() => { ... });
- // TODO: Wire up scope drift detection in patrol run details
- // const scopeDrift = createMemo(() => { ... });
const scheduleOptions = createMemo(() => {
const current = patrolInterval();
@@ -206,6 +216,7 @@ export function AIIntelligence() {
async function loadAISettings() {
try {
const data = await apiFetchJSON<AISettings>('/api/settings/ai');
+ if (!data) return;
setPatrolModel(data.patrol_model || '');
setDefaultModel(data.model || '');
setPatrolInterval(data.patrol_interval_minutes ?? 360);
@@ -241,6 +252,8 @@ export function AIIntelligence() {
}
} catch (err) {
console.error('Failed to toggle patrol:', err);
+ setPatrolEnabledLocal(!newValue); // Rollback
+ notificationStore.error('Failed to toggle patrol');
} finally {
setIsTogglingPatrol(false);
}
@@ -255,6 +268,7 @@ export function AIIntelligence() {
const safetyTimer = setTimeout(() => {
if (manualRunRequested() && !patrolStream.isStreaming()) {
setManualRunRequested(false);
+ notificationStore.error('Patrol run did not start — connection timed out');
loadAllData();
}
}, 15000);
@@ -265,8 +279,9 @@ export function AIIntelligence() {
} catch (err) {
console.error('Failed to trigger patrol run:', err);
setManualRunRequested(false);
- clearTimeout(safetyTimer);
+ notificationStore.error('Failed to start patrol run');
} finally {
+ clearTimeout(safetyTimer);
setIsTriggeringPatrol(false);
}
}
@@ -283,6 +298,7 @@ export function AIIntelligence() {
setPatrolModel(modelId);
} catch (err) {
console.error('Failed to update patrol model:', err);
+ notificationStore.error('Failed to update patrol model');
} finally {
setIsUpdatingSettings(false);
}
@@ -301,6 +317,7 @@ export function AIIntelligence() {
setPatrolEnabledLocal(minutes > 0);
} catch (err) {
console.error('Failed to update patrol interval:', err);
+ notificationStore.error('Failed to update patrol schedule');
} finally {
setIsUpdatingSettings(false);
}
@@ -320,6 +337,7 @@ export function AIIntelligence() {
} catch (err) {
console.error('Failed to update alert-triggered analysis:', err);
setAlertTriggeredAnalysis(previous);
+ notificationStore.error('Failed to update alert analysis setting');
} finally {
setIsUpdatingSettings(false);
}
@@ -339,6 +357,7 @@ export function AIIntelligence() {
} catch (err) {
console.error('Failed to update auto-fix mode:', err);
setPatrolAutoFix(previous);
+ notificationStore.error('Failed to update auto-fix setting');
} finally {
setIsUpdatingSettings(false);
}
@@ -356,6 +375,7 @@ export function AIIntelligence() {
setAutoFixModel(modelId);
} catch (err) {
console.error('Failed to update auto-fix model:', err);
+ notificationStore.error('Failed to update auto-fix model');
} finally {
setIsUpdatingSettings(false);
}
@@ -452,7 +472,7 @@ export function AIIntelligence() {
}
- // Fetch patrol status to check license
+ // Fetch patrol status (license_required reflects auto-fix, not patrol access)
const [patrolStatus, { refetch: refetchPatrolStatus }] = createResource<PatrolStatus | null>(async () => {
try {
return await getPatrolStatus();
@@ -533,6 +553,7 @@ export function AIIntelligence() {
async function loadAutonomySettings() {
try {
const settings = await getPatrolAutonomySettings();
+ if (!settings) return;
setAutonomyLevel(settings.autonomy_level);
setFullModeUnlocked(settings.full_mode_unlocked);
setInvestigationBudget(settings.investigation_budget);
@@ -559,6 +580,7 @@ export function AIIntelligence() {
} catch (err) {
console.error('Failed to update autonomy:', err);
setAutonomyLevel(previousLevel); // Rollback on error
+ notificationStore.error((err as Error).message || 'Failed to update autonomy level');
} finally {
setIsUpdatingAutonomy(false);
}
@@ -582,6 +604,7 @@ export function AIIntelligence() {
setShowAdvancedSettings(false);
} catch (err) {
console.error('Failed to save advanced settings:', err);
+ notificationStore.error('Failed to save advanced settings');
} finally {
setIsSavingAdvanced(false);
}
@@ -591,22 +614,39 @@ export function AIIntelligence() {
await Promise.all([loadAllData(), loadAutonomySettings(), loadModels(), loadAISettings()]);
});
+ // Polling intervals — paused when tab is hidden to save resources
let refreshInterval: ReturnType<typeof setInterval>;
- onMount(() => {
- refreshInterval = setInterval(() => {
- loadAllData();
- }, 60000);
- });
- onCleanup(() => clearInterval(refreshInterval));
-
- // Approval polling: 10s interval for 5-min expiry approvals
let approvalPollInterval: ReturnType<typeof setInterval>;
+
+ function startPolling() {
+ clearInterval(refreshInterval);
+ clearInterval(approvalPollInterval);
+ refreshInterval = setInterval(() => loadAllData(), 60000);
+ // Approval polling: 10s interval for 5-min expiry approvals
+ approvalPollInterval = setInterval(() => aiIntelligenceStore.loadPendingApprovals(), 10000);
+ }
+
+ function stopPolling() {
+ clearInterval(refreshInterval);
+ clearInterval(approvalPollInterval);
+ }
+
onMount(() => {
- approvalPollInterval = setInterval(() => {
- aiIntelligenceStore.loadPendingApprovals();
- }, 10000);
+ startPolling();
+
+ const handleVisibility = () => {
+ if (document.hidden) {
+ stopPolling();
+ } else {
+ // Refresh immediately on tab return, then resume polling
+ loadAllData();
+ startPolling();
+ }
+ };
+ document.addEventListener('visibilitychange', handleVisibility);
+ onCleanup(() => document.removeEventListener('visibilitychange', handleVisibility));
});
- onCleanup(() => clearInterval(approvalPollInterval));
+ onCleanup(() => stopPolling());
async function loadAllData() {
setIsRefreshing(true);
@@ -631,13 +671,12 @@ export function AIIntelligence() {
f.source !== 'threshold' && !f.isThreshold && !f.alertId
);
const activeFindings = patrolFindings.filter(f => f.status === 'active');
- const resolvedFindings = patrolFindings.filter(f => f.status === 'resolved');
const criticalCount = activeFindings.filter(f => f.severity === 'critical').length;
const warningCount = activeFindings.filter(f => f.severity === 'warning').length;
const watchCount = activeFindings.filter(f => f.severity === 'watch').length;
const infoCount = activeFindings.filter(f => f.severity === 'info').length;
- const investigatingCount = patrolFindings.filter(f => f.investigationStatus === 'running').length;
+ const investigatingCount = patrolFindings.filter(f => f.investigationStatus === 'running' || f.investigationStatus === 'pending').length;
const totalActive = activeFindings.length;
const fixedCount = patrolFindings.filter(f =>
f.investigationOutcome === 'fix_verified' ||
@@ -734,9 +773,15 @@ export function AIIntelligence() {
value={patrolModel()}
onChange={(e) => handleModelChange(e.currentTarget.value)}
disabled={isUpdatingSettings() || !patrolEnabledLocal()}
- class="text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded-md py-1 pl-2 pr-6 text-gray-700 dark:text-gray-300 focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
+ class={`text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded-md py-1 pl-2 pr-6 text-gray-700 dark:text-gray-300 focus:ring-1 focus:ring-blue-500 disabled:opacity-50 ${patrolModelStale() ? 'ring-1 ring-amber-400' : ''}`}
+ title={patrolModelStale() ? `Model "${patrolModel()}" is no longer available. Select a new model.` : ''}
>
<option value="">Default ({defaultModel().split(':').pop() || 'not set'})</option>
+ <Show when={patrolModelStale()}>
+ <option value={patrolModel()} disabled>
+ {patrolModel().split(':').pop()} (unavailable)
+ </option>
+ </Show>
{Array.from(groupModelsByProvider(availableModels()).entries()).map(([provider, models]) => (
<optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>
{models.map((model) => (
@@ -757,7 +802,7 @@ export function AIIntelligence() {
<select
value={patrolInterval()}
onChange={(e) => handleIntervalChange(parseInt(e.currentTarget.value))}
- disabled={isUpdatingSettings() || !patrolEnabledLocal() || licenseRequired()}
+ disabled={isUpdatingSettings() || !patrolEnabledLocal()}
class="text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded-md py-1 pl-2 pr-6 text-gray-700 dark:text-gray-300 focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
>
<For each={scheduleOptions()}>
@@ -777,18 +822,19 @@ export function AIIntelligence() {
<For each={(['monitor', 'approval', 'assisted', 'full'] as PatrolAutonomyLevel[])}>
{(level) => {
const isFullLocked = () => level === 'full' && !fullModeUnlocked();
- const isDisabled = () => !patrolEnabledLocal() || isFullLocked();
+ const isProLocked = () => autoFixLocked() && (level === 'assisted' || level === 'full');
+ const isDisabled = () => !patrolEnabledLocal() || isFullLocked() || isProLocked();
return (
<button
onClick={() => handleAutonomyChange(level)}
disabled={isDisabled()}
- title={isFullLocked() ? 'Enable in Advanced Settings (⚙️) first' : undefined}
+ title={isProLocked() ? 'Upgrade to Pulse Pro for auto-fix' : isFullLocked() ? 'Enable in Advanced Settings (⚙️) first' : undefined}
class={`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${
autonomyLevel() === level
? level === 'full'
? 'bg-red-500 dark:bg-red-600 text-white shadow-sm'
: 'bg-white dark:bg-gray-600 text-gray-900 dark:text-white shadow-sm'
- : isFullLocked()
+ : isFullLocked() || isProLocked()
? 'text-gray-400 dark:text-gray-500'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white'
} ${isDisabled() ? 'opacity-50 cursor-not-allowed' : ''}`}
@@ -946,9 +992,15 @@ export function AIIntelligence() {
value={autoFixModel()}
onChange={(e) => handleAutoFixModelChange(e.currentTarget.value)}
disabled={isUpdatingSettings()}
- class="mt-1 w-full text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded-md py-1.5 pl-2 pr-6 text-gray-700 dark:text-gray-300 focus:ring-1 focus:ring-blue-500 disabled:opacity-50"
+ class={`mt-1 w-full text-xs bg-gray-100 dark:bg-gray-700 border-0 rounded-md py-1.5 pl-2 pr-6 text-gray-700 dark:text-gray-300 focus:ring-1 focus:ring-blue-500 disabled:opacity-50 ${autoFixModelStale() ? 'ring-1 ring-amber-400' : ''}`}
+ title={autoFixModelStale() ? `Model "${autoFixModel()}" is no longer available. Select a new model.` : ''}
>
<option value="">Use patrol model</option>
+ <Show when={autoFixModelStale()}>
+ <option value={autoFixModel()} disabled>
+ {autoFixModel().split(':').pop()} (unavailable)
+ </option>
+ </Show>
{Array.from(groupModelsByProvider(availableModels()).entries()).map(([provider, models]) => (
<optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>
{models.map((model) => (
@@ -1007,35 +1059,12 @@ export function AIIntelligence() {
</Show>
<Show when={licenseRequired() && !showBlockedBanner()}>
- <div class="flex-shrink-0 bg-blue-50 dark:bg-blue-900/20 border-b border-blue-200 dark:border-blue-800 px-4 py-3">
- <div class="flex flex-wrap items-center justify-between gap-3">
- <div class="flex items-start gap-3">
- <div class="flex-shrink-0 p-1.5 bg-blue-100 dark:bg-blue-900/40 rounded-lg">
- <SparklesIcon class="w-4 h-4 text-blue-600 dark:text-blue-400" />
- </div>
- <div>
- <p class="text-sm font-semibold text-blue-900 dark:text-blue-100">
- Pulse Patrol requires Pulse Pro
- </p>
- <p class="text-xs text-blue-700 dark:text-blue-300">
- Upgrade to enable AI analysis, investigations, and auto-fix.
- </p>
- </div>
- </div>
- <div class="flex items-center gap-3">
- <a
- href={upgradeUrl()}
- target="_blank"
- rel="noopener noreferrer"
- class="inline-flex items-center justify-center gap-2 px-4 py-2 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors"
- >
- <SparklesIcon class="w-3.5 h-3.5" />
- Upgrade to Pulse Pro
- </a>
- <span class="text-[10px] text-blue-700 dark:text-blue-300">
- Already licensed? Activate in Settings → License.
- </span>
- </div>
+ <div class="flex-shrink-0 bg-blue-50 dark:bg-blue-900/20 border-b border-blue-200 dark:border-blue-800 px-3 py-2">
+ <div class="flex flex-wrap items-center justify-between gap-2">
+ <p class="text-xs text-blue-700 dark:text-blue-300">
+ <a class="text-indigo-600 dark:text-indigo-400 font-semibold hover:underline" href={upgradeUrl()} target="_blank" rel="noopener noreferrer">Upgrade to Pro</a>
+ {' '}to unlock Assisted and Full autonomy (auto-fix).
+ </p>
</div>
</div>
</Show>
@@ -1131,11 +1160,11 @@ export function AIIntelligence() {
onScrollToFinding={(findingId) => {
setActiveTab('findings');
setFindingsFilterOverride('approvals');
- // Scroll to the finding after tab switch and filter change
- requestAnimationFrame(() => {
+ // Allow SolidJS to re-render with new filter before scrolling
+ setTimeout(() => {
const el = document.getElementById(`finding-${findingId}`);
el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
- });
+ }, 100);
}}
/>
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index b6e7f84159..226a98764c 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -19,6 +19,38 @@ import type {
} from '@/api/ai';
import { logger } from '@/utils/logger';
+// ============================================
+// Enum validation helpers
+// ============================================
+
+const VALID_INVESTIGATION_STATUSES = new Set<string>(['pending', 'running', 'completed', 'failed', 'needs_attention']);
+const VALID_INVESTIGATION_OUTCOMES = new Set<string>([
+ 'resolved', 'fix_queued', 'fix_executed', 'fix_failed',
+ 'needs_attention', 'cannot_fix', 'timed_out', 'fix_verified', 'fix_verification_failed',
+]);
+const VALID_SEVERITIES = new Set<string>(['critical', 'warning', 'info', 'watch']);
+const VALID_SOURCES = new Set<string>(['threshold', 'ai-patrol', 'ai-chat', 'anomaly', 'correlation', 'forecast']);
+
+function validateInvestigationStatus(value: string | undefined): UnifiedFinding['investigationStatus'] {
+ if (!value) return undefined;
+ return VALID_INVESTIGATION_STATUSES.has(value) ? value as UnifiedFinding['investigationStatus'] : undefined;
+}
+
+function validateInvestigationOutcome(value: string | undefined): UnifiedFinding['investigationOutcome'] {
+ if (!value) return undefined;
+ return VALID_INVESTIGATION_OUTCOMES.has(value) ? value as UnifiedFinding['investigationOutcome'] : undefined;
+}
+
+function validateSeverity(value: string | undefined): UnifiedFinding['severity'] {
+ if (value && VALID_SEVERITIES.has(value)) return value as UnifiedFinding['severity'];
+ return 'info';
+}
+
+function validateSource(value: string | undefined): UnifiedFinding['source'] {
+ if (value && VALID_SOURCES.has(value)) return value as UnifiedFinding['source'];
+ return 'ai-patrol';
+}
+
// ============================================
// Unified Findings
// ============================================
@@ -64,12 +96,14 @@ const [findingsError, setFindingsError] = createSignal<string | null>(null);
const [remediationPlans, setRemediationPlans] = createSignal<RemediationPlan[]>([]);
const [plansLoading, setPlansLoading] = createSignal(false);
+const [plansError, setPlansError] = createSignal<string | null>(null);
// ============================================
// Pending Approvals
// ============================================
const [pendingApprovals, setPendingApprovals] = createSignal<ApprovalRequest[]>([]);
+const [approvalsError, setApprovalsError] = createSignal<string | null>(null);
// ============================================
// Circuit Breaker
@@ -93,6 +127,7 @@ export const aiIntelligenceStore = {
setFindingsError(null);
try {
const resp = await AIAPI.getUnifiedFindings({ includeResolved: true });
+ if (!resp) return;
const now = Date.now();
const findings = (resp.findings || []).map((item: UnifiedFindingRecord): UnifiedFinding => {
@@ -111,14 +146,14 @@ export const aiIntelligenceStore = {
return {
id: item.id,
- source: (item.source as UnifiedFinding['source']) || 'ai-patrol',
+ source: validateSource(item.source),
resourceId: item.resource_id,
resourceName: item.resource_name || item.resource_id,
resourceType: item.resource_type || 'unknown',
alertId: item.alert_id,
isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
category: item.category || 'general',
- severity: (item.severity as UnifiedFinding['severity']) || 'info',
+ severity: validateSeverity(item.severity),
title: item.title,
description: item.description,
recommendation: item.recommendation,
@@ -132,8 +167,8 @@ export const aiIntelligenceStore = {
correlatedFindingIds: item.correlated_ids,
remediationPlanId: item.remediation_id,
investigationSessionId: item.investigation_session_id || '',
- investigationStatus: item.investigation_status as UnifiedFinding['investigationStatus'],
- investigationOutcome: item.investigation_outcome as UnifiedFinding['investigationOutcome'],
+ investigationStatus: validateInvestigationStatus(item.investigation_status),
+ investigationOutcome: validateInvestigationOutcome(item.investigation_outcome),
lastInvestigatedAt: item.last_investigated_at || undefined,
investigationAttempts: item.investigation_attempts || 0,
};
@@ -151,15 +186,18 @@ export const aiIntelligenceStore = {
// Remediation Plans
get remediationPlans() { return remediationPlans(); },
get plansLoading() { return plansLoading(); },
+ get plansError() { return plansError(); },
remediationPlansSignal: remediationPlans,
async loadRemediationPlans() {
setPlansLoading(true);
+ setPlansError(null);
try {
const resp = await AIAPI.getRemediationPlans();
- setRemediationPlans(resp.plans || []);
+ setRemediationPlans(resp?.plans || []);
} catch (e) {
logger.error('Failed to load remediation plans:', e);
+ setPlansError(e instanceof Error ? e.message : 'Failed to load remediation plans');
} finally {
setPlansLoading(false);
}
@@ -251,6 +289,7 @@ export const aiIntelligenceStore = {
// Pending Approvals
get pendingApprovals() { return pendingApprovals(); },
+ get approvalsError() { return approvalsError(); },
pendingApprovalsSignal: pendingApprovals,
get pendingApprovalCount() {
@@ -264,7 +303,7 @@ export const aiIntelligenceStore = {
},
get findingsNeedingAttention() {
- const actionableOutcomes = new Set(['fix_verification_failed', 'timed_out', 'needs_attention', 'cannot_fix']);
+ const actionableOutcomes = new Set(['fix_verification_failed', 'fix_failed', 'timed_out', 'needs_attention', 'cannot_fix']);
return unifiedFindings().filter(f =>
f.status === 'active' && f.investigationOutcome && actionableOutcomes.has(f.investigationOutcome)
);
@@ -275,11 +314,13 @@ export const aiIntelligenceStore = {
},
async loadPendingApprovals() {
+ setApprovalsError(null);
try {
const approvals = await AIAPI.getPendingApprovals();
setPendingApprovals(approvals);
} catch (e) {
logger.error('Failed to load pending approvals:', e);
+ setApprovalsError(e instanceof Error ? e.message : 'Failed to load approvals');
}
},
@@ -299,6 +340,7 @@ export const aiIntelligenceStore = {
try {
await AIAPI.denyInvestigationFix(approvalId, reason);
await this.loadPendingApprovals();
+ await this.loadFindings();
return true;
} catch (e) {
logger.error('Failed to deny fix:', e);
diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.ts
index f59d77fd81..5baf8aa843 100644
--- a/frontend-modern/src/types/ai.ts
+++ b/frontend-modern/src/types/ai.ts
@@ -30,6 +30,7 @@ export interface AISettings {
patrol_schedule_preset?: string; // DEPRECATED: use patrol_interval_minutes
patrol_interval_minutes?: number; // Patrol interval in minutes (0 = disabled, minimum 10)
alert_triggered_analysis?: boolean; // true if AI should analyze when alerts fire
+ patrol_auto_fix?: boolean; // true if Patrol can auto-fix without approval
available_models?: ModelInfo[]; // DEPRECATED: use /api/ai/models endpoint
// Multi-provider configuration
anthropic_configured: boolean; // true if Anthropic API key or OAuth is set
@@ -73,6 +74,7 @@ export interface AISettingsUpdateRequest {
patrol_schedule_preset?: string; // DEPRECATED: use patrol_interval_minutes
patrol_interval_minutes?: number; // Custom interval in minutes (0 = disabled, minimum 10)
alert_triggered_analysis?: boolean; // true if AI should analyze when alerts fire
+ patrol_auto_fix?: boolean; // true if Patrol can auto-fix without approval
// Multi-provider credentials
anthropic_api_key?: string; // Set Anthropic API key
openai_api_key?: string; // Set OpenAI API key
diff --git a/frontend-modern/src/types/aiIntelligence.ts b/frontend-modern/src/types/aiIntelligence.ts
index 7d9c630258..bcb4889c14 100644
--- a/frontend-modern/src/types/aiIntelligence.ts
+++ b/frontend-modern/src/types/aiIntelligence.ts
@@ -1,327 +1,44 @@
/**
- * AI Intelligence Store
+ * AI Intelligence Types
*
- * Central store for managing AI intelligence state:
- * - Unified findings (alerts + AI findings)
- * - Remediation plans
- * - Circuit breaker status
+ * Shared type definitions for AI intelligence features:
+ * - Anomaly detection (baseline deviation)
+ * - Learning status (baseline progress)
+ *
+ * Store logic lives in @/stores/aiIntelligence.ts
*/
-import { createSignal } from 'solid-js';
-import { AIAPI } from '@/api/ai';
-import { acknowledgeFinding, snoozeFinding, dismissFinding, setFindingNote } from '@/api/patrol';
-import type {
- RemediationPlan,
- CircuitBreakerStatus,
- UnifiedFindingRecord,
- ApprovalRequest,
- ApprovalExecutionResult,
-} from '@/api/ai';
-import { logger } from '@/utils/logger';
-
// ============================================
-// Unified Findings
+// Anomaly Detection Types
// ============================================
-export interface UnifiedFinding {
- id: string;
- source: 'threshold' | 'ai-patrol' | 'ai-chat' | 'anomaly' | 'correlation' | 'forecast';
- resourceId: string;
- resourceName: string;
- resourceType: string;
- alertId?: string;
- alertType?: string;
- isThreshold?: boolean;
- category: string;
- severity: 'critical' | 'warning' | 'info' | 'watch';
- title: string;
+export interface AnomalyReport {
+ resource_id: string;
+ resource_name: string;
+ resource_type: string;
+ metric: string;
+ current_value: number;
+ baseline_mean: number;
+ baseline_std_dev: number;
+ z_score: number;
+ severity: string;
description: string;
- recommendation?: string;
- detectedAt: string;
- resolvedAt?: string;
- acknowledgedAt?: string;
- snoozedUntil?: string;
- dismissedReason?: string;
- userNote?: string;
- status: 'active' | 'resolved' | 'dismissed' | 'snoozed';
- correlatedFindingIds?: string[];
- remediationPlanId?: string;
- // Investigation fields (Patrol Autonomy)
- investigationSessionId?: string;
- investigationStatus?: 'pending' | 'running' | 'completed' | 'failed' | 'needs_attention';
- investigationOutcome?: 'resolved' | 'fix_queued' | 'fix_executed' | 'fix_failed' | 'needs_attention' | 'cannot_fix' | 'timed_out' | 'fix_verified' | 'fix_verification_failed';
- lastInvestigatedAt?: string;
- investigationAttempts?: number;
}
-const [unifiedFindings, setUnifiedFindings] = createSignal<UnifiedFinding[]>([]);
-const [findingsLoading, setFindingsLoading] = createSignal(false);
-const [findingsError, setFindingsError] = createSignal<string | null>(null);
-
-// ============================================
-// Remediation Plans
-// ============================================
-
-const [remediationPlans, setRemediationPlans] = createSignal<RemediationPlan[]>([]);
-const [plansLoading, setPlansLoading] = createSignal(false);
-
-// ============================================
-// Pending Approvals
-// ============================================
-
-const [pendingApprovals, setPendingApprovals] = createSignal<ApprovalRequest[]>([]);
-
-// ============================================
-// Circuit Breaker
-// ============================================
-
-const [circuitBreakerStatus, setCircuitBreakerStatus] = createSignal<CircuitBreakerStatus | null>(null);
+export interface AnomaliesResponse {
+ anomalies: AnomalyReport[];
+ message?: string;
+}
// ============================================
-// Store API
+// Learning Status Types
// ============================================
-export const aiIntelligenceStore = {
- // Unified Findings
- get findings() { return unifiedFindings(); },
- get findingsLoading() { return findingsLoading(); },
- get findingsError() { return findingsError(); },
- findingsSignal: unifiedFindings,
-
- async loadFindings() {
- setFindingsLoading(true);
- setFindingsError(null);
- try {
- const resp = await AIAPI.getUnifiedFindings({ includeResolved: true });
- const now = Date.now();
-
- const findings = (resp.findings || []).map((item: UnifiedFindingRecord): UnifiedFinding => {
- let status = item.status as UnifiedFinding['status'] | undefined;
- if (!status) {
- if (item.resolved_at) {
- status = 'resolved';
- } else if (item.snoozed_until && new Date(item.snoozed_until).getTime() > now) {
- status = 'snoozed';
- } else if (item.dismissed_reason || item.suppressed) {
- status = 'dismissed';
- } else {
- status = 'active';
- }
- }
-
- return {
- id: item.id,
- source: (item.source as UnifiedFinding['source']) || 'ai-patrol',
- resourceId: item.resource_id,
- resourceName: item.resource_name || item.resource_id,
- resourceType: item.resource_type || 'unknown',
- alertId: item.alert_id,
- isThreshold: Boolean(item.is_threshold || item.source === 'threshold'),
- category: item.category || 'general',
- severity: (item.severity as UnifiedFinding['severity']) || 'info',
- title: item.title,
- description: item.description,
- recommendation: item.recommendation,
- detectedAt: item.detected_at,
- resolvedAt: item.resolved_at,
- acknowledgedAt: item.acknowledged_at,
- snoozedUntil: item.snoozed_until,
- dismissedReason: item.dismissed_reason,
- userNote: item.user_note,
- status,
- correlatedFindingIds: item.correlated_ids,
- remediationPlanId: item.remediation_id,
- investigationSessionId: item.investigationSessionId || '',
- investigationStatus: item.investigationStatus as UnifiedFinding['investigationStatus'],
- investigationOutcome: item.investigationOutcome as UnifiedFinding['investigationOutcome'],
- lastInvestigatedAt: item.lastInvestigatedAt || undefined,
- investigationAttempts: item.investigationAttempts || 0,
- };
- });
-
- setUnifiedFindings(findings);
- } catch (e) {
- logger.error('Failed to load unified findings:', e);
- setFindingsError(e instanceof Error ? e.message : 'Failed to load findings');
- } finally {
- setFindingsLoading(false);
- }
- },
-
- // Remediation Plans
- get remediationPlans() { return remediationPlans(); },
- get plansLoading() { return plansLoading(); },
- remediationPlansSignal: remediationPlans,
-
- async loadRemediationPlans() {
- setPlansLoading(true);
- try {
- const resp = await AIAPI.getRemediationPlans();
- setRemediationPlans(resp.plans || []);
- } catch (e) {
- logger.error('Failed to load remediation plans:', e);
- } finally {
- setPlansLoading(false);
- }
- },
-
- async approvePlan(planId: string) {
- try {
- await AIAPI.approveRemediationPlan(planId);
- await this.loadRemediationPlans();
- return true;
- } catch (e) {
- logger.error('Failed to approve plan:', e);
- return false;
- }
- },
-
- async executePlan(planId: string) {
- try {
- const result = await AIAPI.executeRemediationPlan(planId);
- await this.loadRemediationPlans();
- return result;
- } catch (e) {
- logger.error('Failed to execute plan:', e);
- throw e;
- }
- },
-
- async rollbackPlan(executionId: string) {
- try {
- await AIAPI.rollbackRemediationPlan(executionId);
- await this.loadRemediationPlans();
- return true;
- } catch (e) {
- logger.error('Failed to rollback plan:', e);
- return false;
- }
- },
-
- async acknowledgeFinding(findingId: string) {
- try {
- await acknowledgeFinding(findingId);
- await this.loadFindings();
- return true;
- } catch (e) {
- logger.error('Failed to acknowledge finding:', e);
- return false;
- }
- },
-
- async snoozeFinding(findingId: string, durationHours: number) {
- try {
- await snoozeFinding(findingId, durationHours);
- await this.loadFindings();
- return true;
- } catch (e) {
- logger.error('Failed to snooze finding:', e);
- return false;
- }
- },
-
- async dismissFinding(
- findingId: string,
- reason: 'not_an_issue' | 'expected_behavior' | 'will_fix_later',
- note?: string,
- ) {
- try {
- await dismissFinding(findingId, reason, note);
- await this.loadFindings();
- return true;
- } catch (e) {
- logger.error('Failed to dismiss finding:', e);
- return false;
- }
- },
-
- async setFindingNote(findingId: string, note: string) {
- try {
- await setFindingNote(findingId, note);
- // Update local state immediately for responsiveness
- setUnifiedFindings(prev =>
- prev.map(f => f.id === findingId ? { ...f, userNote: note } : f),
- );
- return true;
- } catch (e) {
- logger.error('Failed to set finding note:', e);
- return false;
- }
- },
-
- // Pending Approvals
- get pendingApprovals() { return pendingApprovals(); },
- pendingApprovalsSignal: pendingApprovals,
-
- get pendingApprovalCount() {
- return pendingApprovals().filter(a => a.status === 'pending').length;
- },
-
- get findingsWithPendingApprovals() {
- const approvals = pendingApprovals().filter(a => a.status === 'pending');
- const findingIds = new Set(approvals.filter(a => a.toolId === 'investigation_fix').map(a => a.targetId));
- return unifiedFindings().filter(f => findingIds.has(f.id));
- },
-
- async loadPendingApprovals() {
- try {
- const approvals = await AIAPI.getPendingApprovals();
- setPendingApprovals(approvals);
- } catch (e) {
- logger.error('Failed to load pending approvals:', e);
- }
- },
-
- async approveInvestigationFix(approvalId: string): Promise<ApprovalExecutionResult | null> {
- try {
- const result = await AIAPI.approveInvestigationFix(approvalId);
- await this.loadPendingApprovals();
- await this.loadFindings();
- return result;
- } catch (e) {
- logger.error('Failed to approve fix:', e);
- return null;
- }
- },
-
- async denyInvestigationFix(approvalId: string, reason?: string) {
- try {
- await AIAPI.denyInvestigationFix(approvalId, reason);
- await this.loadPendingApprovals();
- return true;
- } catch (e) {
- logger.error('Failed to deny fix:', e);
- return false;
- }
- },
-
- // Circuit Breaker
- get circuitBreakerStatus() { return circuitBreakerStatus(); },
- circuitBreakerStatusSignal: circuitBreakerStatus,
-
- async loadCircuitBreakerStatus() {
- try {
- const status = await AIAPI.getCircuitBreakerStatus();
- setCircuitBreakerStatus(status);
- } catch (e) {
- logger.error('Failed to load circuit breaker status:', e);
- }
- },
-
- // Initialize - load all data
- async initialize() {
- await Promise.all([
- this.loadFindings(),
- this.loadRemediationPlans(),
- this.loadCircuitBreakerStatus(),
- this.loadPendingApprovals(),
- ]);
- },
-
- // Refresh all data
- async refresh() {
- await this.initialize();
- },
-};
-
-export default aiIntelligenceStore;
+export interface LearningStatusResponse {
+ resources_baselined: number;
+ total_metrics: number;
+ metric_breakdown: Record<string, number>;
+ status: 'waiting' | 'learning' | 'active';
+ message: string;
+ license_required: boolean;
+}