Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
feat(frontend): implement AI Patrol, Investigation, and Findings UI
rcourtman29f65ac33ff6
diff --git a/frontend-modern/src/api/ai.ts b/frontend-modern/src/api/ai.tsindex 1098041436..92913d2226 100644--- a/frontend-modern/src/api/ai.ts+++ b/frontend-modern/src/api/ai.ts@@ -342,6 +342,12 @@ export interface UnifiedFindingRecord {ai_confidence?: number;enhanced_by_ai?: boolean;ai_enhanced_at?: string;+ // Investigation fields (camelCase from API)+ investigationSessionId?: string;+ investigationStatus?: string;+ investigationOutcome?: string;+ lastInvestigatedAt?: string;+ investigationAttempts?: number;detected_at: string;last_seen_at?: string;resolved_at?: string;diff --git a/frontend-modern/src/api/aiChat.ts b/frontend-modern/src/api/aiChat.tsindex c9c6e2a75c..cbc890ebc8 100644--- a/frontend-modern/src/api/aiChat.ts+++ b/frontend-modern/src/api/aiChat.ts@@ -175,17 +175,23 @@ export class AIChatAPI {sessionId: string | undefined,model: string | undefined,onEvent: (event: StreamEvent) => void,- signal?: AbortSignal+ signal?: AbortSignal,+ mentions?: Array<{ id: string; name: string; type: string; node?: string }>): Promise<void> {logger.debug('[AI Chat] Starting chat stream', { prompt: prompt.substring(0, 50) });+ const body: Record<string, unknown> = {+ prompt,+ session_id: sessionId,+ model,+ };+ if (mentions && mentions.length > 0) {+ body.mentions = mentions;+ }+const response = await apiFetch(`${this.baseUrl}/chat`, {method: 'POST',- body: JSON.stringify({- prompt,- session_id: sessionId,- model,- }),+ body: JSON.stringify(body),headers: {'Content-Type': 'application/json','Accept': 'text/event-stream',diff --git a/frontend-modern/src/api/monitoring.ts b/frontend-modern/src/api/monitoring.tsindex 2ac60d36a7..59ea448f61 100644--- a/frontend-modern/src/api/monitoring.ts+++ b/frontend-modern/src/api/monitoring.ts@@ -1,4 +1,4 @@-import type { State, Performance, Stats, DockerHostCommand, HostLookupResponse, StorageConfigEntry } from '@/types/api';+import type { State, Performance, Stats, DockerHostCommand, HostLookupResponse } from '@/types/api';import { apiFetch, apiFetchJSON } from '@/utils/apiClient';export class MonitoringAPI {@@ -21,21 +21,6 @@ export class MonitoringAPI {return response.blob();}- static async getStorageConfig(params?: {- instance?: string;- node?: string;- storageId?: string;- }): Promise<StorageConfigEntry[]> {- const query = new URLSearchParams();- if (params?.instance) query.set('instance', params.instance);- if (params?.node) query.set('node', params.node);- if (params?.storageId) query.set('storage_id', params.storageId);- const qs = query.toString();- const url = `${this.baseUrl}/storage/config${qs ? `?${qs}` : ''}`;- const resp = await apiFetchJSON(url) as { storages?: StorageConfigEntry[] };- return resp?.storages ?? [];- }-static async deleteDockerHost(hostId: string,options: { hide?: boolean; force?: boolean } = {}diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.tsindex 1517b991ba..57539e2463 100644--- a/frontend-modern/src/api/patrol.ts+++ b/frontend-modern/src/api/patrol.ts@@ -90,9 +90,24 @@ export interface ChatMessage {id: string;role: 'user' | 'assistant' | 'system';content: string;+ reasoning_content?: string;+ tool_calls?: ChatToolCall[];+ tool_result?: ChatToolResult;timestamp: string;}+export interface ChatToolCall {+ id: string;+ name: string;+ input: Record<string, unknown>;+}++export interface ChatToolResult {+ tool_use_id: string;+ content: string;+ is_error?: boolean;+}+export interface FindingsSummary {critical: number;warning: number;@@ -106,7 +121,6 @@ export interface PatrolStatus {running: boolean;enabled: boolean;last_patrol_at?: string;- last_deep_analysis_at?: string;next_patrol_at?: string;last_duration_ms: number;resources_checked: number;@@ -171,6 +185,19 @@ export async function dismissFinding(});}+/**+ * Set or update a user note on a finding+ * Notes provide context that Patrol sees on future runs.+ * @param findingId The ID of the finding+ * @param note The note text (empty string to clear)+ */+export async function setFindingNote(findingId: string, note: string): Promise<{ success: boolean; message: string }> {+ return apiFetchJSON('/api/ai/patrol/findings/note', {+ method: 'POST',+ body: JSON.stringify({ finding_id: findingId, note }),+ });+}+// =============================================================================// Patrol Autonomy APIs// =============================================================================@@ -290,6 +317,17 @@ export const investigationOutcomeLabels: Record<InvestigationOutcome, string> =export type PatrolRunStatus = 'healthy' | 'issues_found' | 'critical' | 'error';+export interface ToolCallRecord {+ id: string;+ tool_name: string;+ input: string;+ output: string;+ success: boolean;+ start_time: number;+ end_time: number;+ duration_ms: number;+}+export interface PatrolRunRecord {id: string;started_at: string;@@ -299,7 +337,6 @@ export interface PatrolRunRecord {trigger_reason?: string;scope_resource_ids?: string[];scope_resource_types?: string[];- scope_depth?: string;scope_context?: string;alert_id?: string;finding_id?: string;@@ -313,6 +350,7 @@ export interface PatrolRunRecord {kubernetes_checked: number;new_findings: number;existing_findings: number;+ rejected_findings: number;resolved_findings: number;auto_fix_count: number;findings_summary: string;@@ -322,6 +360,8 @@ export interface PatrolRunRecord {ai_analysis?: string;input_tokens?: number;output_tokens?: number;+ tool_calls?: ToolCallRecord[];+ tool_call_count: number;}/**@@ -333,6 +373,28 @@ export async function getPatrolRunHistory(limit: number = 30): Promise<PatrolRunreturn runs || [];}+/**+ * Get patrol run history with tool calls included+ * @param limit Maximum number of runs to return (default: 30)+ */+export async function getPatrolRunHistoryWithToolCalls(limit: number = 30): Promise<PatrolRunRecord[]> {+ const runs = await apiFetchJSON<PatrolRunRecord[]>(`/api/ai/patrol/runs?include=tool_calls&limit=${limit}`);+ return runs || [];+}++/** SSE event from /api/ai/patrol/stream */+export interface PatrolStreamEvent {+ type: 'start' | 'content' | 'phase' | 'complete' | 'error' | 'tool_start' | 'tool_end';+ content?: string;+ phase?: string;+ tokens?: number;+ tool_id?: string;+ tool_name?: string;+ tool_input?: string;+ tool_output?: string;+ tool_success?: boolean;+}+/*** Trigger a manual patrol run*/diff --git a/frontend-modern/src/components/AI/Chat/ModelSelector.tsx b/frontend-modern/src/components/AI/Chat/ModelSelector.tsxindex 060b9a38e8..07da4e890b 100644--- a/frontend-modern/src/components/AI/Chat/ModelSelector.tsx+++ b/frontend-modern/src/components/AI/Chat/ModelSelector.tsx@@ -40,11 +40,11 @@ export const ModelSelector: Component<ModelSelectorProps> = (props) => {return props.models.length - notable.length;});- // Apply search filter on top of notable filter+ // Apply search filter - search ALL models (not just notable) when there's a queryconst filteredModels = createMemo(() => {const query = searchQuery().trim().toLowerCase();- const baseModels = notableFilteredModels();- if (!query) return baseModels;+ if (!query) return notableFilteredModels();+ const baseModels = props.models;return baseModels.filter((model) => {const provider = getProviderFromModelId(model.id);const providerName = PROVIDER_DISPLAY_NAMES[provider] || provider;diff --git a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts b/frontend-modern/src/components/AI/Chat/hooks/useChat.tsindex 44923831de..58b3a12d43 100644--- a/frontend-modern/src/components/AI/Chat/hooks/useChat.ts+++ b/frontend-modern/src/components/AI/Chat/hooks/useChat.ts@@ -306,7 +306,7 @@ export function useChat(options: UseChatOptions = {}) {};// Send a message - allows sending mid-stream (aborts current response like Pulse AI TUI)- const sendMessage = async (prompt: string) => {+ const sendMessage = async (prompt: string, mentions?: Array<{ id: string; name: string; type: string; node?: string }>) => {if (!prompt.trim()) return;// If already streaming, abort the current request first@@ -374,7 +374,8 @@ export function useChat(options: UseChatOptions = {}) {(event: StreamEvent) => {processEvent(assistantId, event);},- abortControllerRef?.signal+ abortControllerRef?.signal,+ mentions);} catch (error) {if (error instanceof Error && error.name === 'AbortError') {diff --git a/frontend-modern/src/components/AI/Chat/index.tsx b/frontend-modern/src/components/AI/Chat/index.tsxindex 62fe8400d9..0055918ae4 100644--- a/frontend-modern/src/components/AI/Chat/index.tsx+++ b/frontend-modern/src/components/AI/Chat/index.tsx@@ -49,6 +49,7 @@ export const AIChat: Component<AIChatProps> = (props) => {const [mentionQuery, setMentionQuery] = createSignal('');const [mentionStartIndex, setMentionStartIndex] = createSignal(0);const [mentionResources, setMentionResources] = createSignal<MentionResource[]>([]);+ const [accumulatedMentions, setAccumulatedMentions] = createSignal<MentionResource[]>([]);let textareaRef: HTMLTextAreaElement | undefined;const loadModelSelections = (): Record<string, string> => {@@ -252,6 +253,16 @@ export const AIChat: Component<AIChatProps> = (props) => {}});+ // Pre-fill input when opened with an initialPrompt (e.g., "Discuss with Assistant" from findings)+ createEffect(() => {+ const ctx = aiChatStore.context;+ if (ctx.initialPrompt && isOpen()) {+ setInput(ctx.initialPrompt);+ // Clear so it doesn't re-fire on subsequent opens+ aiChatStore.clearInitialPrompt?.();+ }+ });+// Compute current status for displayconst currentStatus = createMemo(() => {if (!chat.isLoading()) return null;@@ -393,8 +404,10 @@ export const AIChat: Component<AIChatProps> = (props) => {if (chat.isLoading()) return;const prompt = input().trim();if (!prompt) return;- chat.sendMessage(prompt);+ const mentions = accumulatedMentions();+ chat.sendMessage(prompt, mentions.length > 0 ? mentions : undefined);setInput('');+ setAccumulatedMentions([]);setMentionActive(false);};@@ -441,6 +454,13 @@ export const AIChat: Component<AIChatProps> = (props) => {setInput(newValue);setMentionActive(false);+ // Accumulate the structured mention data so we can send it with the prompt+ setAccumulatedMentions(prev => {+ // Deduplicate by id+ if (prev.some(m => m.id === resource.id)) return prev;+ return [...prev, resource];+ });+// Focus textarea and set cursor position after the inserted namesetTimeout(() => {if (textareaRef) {diff --git a/frontend-modern/src/components/AI/FindingsPanel.tsx b/frontend-modern/src/components/AI/FindingsPanel.tsxindex 53ea9649ba..deb7af951b 100644--- a/frontend-modern/src/components/AI/FindingsPanel.tsx+++ b/frontend-modern/src/components/AI/FindingsPanel.tsx@@ -5,6 +5,9 @@* - Pulse Patrol Findings (AI-discovered insights)* - Threshold Alerts (user-configured rules)* Each section has severity-based sorting and quick actions+ *+ * Investigation and approval details are shown inline via+ * InvestigationSection and ApprovalSection components.*/import { Component, createSignal, createEffect, Show, For, createMemo } from 'solid-js';@@ -12,9 +15,10 @@ import { useLocation } from '@solidjs/router';import { Card } from '@/components/shared/Card';import { aiIntelligenceStore, type UnifiedFinding } from '@/stores/aiIntelligence';import { notificationStore } from '@/stores/notifications';-import { InvestigationDrawer } from './InvestigationDrawer';+import { aiChatStore } from '@/stores/aiChat';+import { InvestigationSection, ApprovalSection } from '@/components/patrol';import { investigationStatusLabels, investigationOutcomeLabels, type InvestigationStatus } from '@/api/patrol';-import { AIAPI, type RemediationPlan, type ApprovalRequest, type ApprovalExecutionResult, type InvestigationSession } from '@/api/ai';+import { AIAPI, type RemediationPlan } from '@/api/ai';// Severity priority for sorting (lower number = higher priority)const severityOrder: Record<string, number> = {@@ -66,7 +70,7 @@ interface FindingsPanelProps {showResolved?: boolean;maxItems?: number;onFindingClick?: (finding: UnifiedFinding) => void;- filterOverride?: 'all' | 'active' | 'resolved';+ filterOverride?: 'all' | 'active' | 'resolved' | 'approvals';filterFindingIds?: string[];showControls?: boolean;nextPatrolAt?: string;@@ -79,111 +83,19 @@ interface FindingsPanelProps {export const FindingsPanel: Component<FindingsPanelProps> = (props) => {const location = useLocation();- const [filter, setFilter] = createSignal<'all' | 'active' | 'resolved'>(props.filterOverride ?? 'active');+ const [filter, setFilter] = createSignal<'all' | 'active' | 'resolved' | 'approvals'>(props.filterOverride ?? 'active');const [sortBy, setSortBy] = createSignal<'severity' | 'time'>('severity');const [expandedId, setExpandedId] = createSignal<string | null>(null);const [actionLoading, setActionLoading] = createSignal<string | null>(null);const [lastHashScrolled, setLastHashScrolled] = createSignal<string | null>(null);+ const [editingNoteId, setEditingNoteId] = createSignal<string | null>(null);+ const [noteText, setNoteText] = createSignal('');- // Investigation drawer state- const [investigationDrawerOpen, setInvestigationDrawerOpen] = createSignal(false);- const [selectedFindingForInvestigation, setSelectedFindingForInvestigation] = createSignal<UnifiedFinding | null>(null);-- // Investigation fix approvals state (real fixes that can be executed)- const [pendingApprovals, setPendingApprovals] = createSignal<ApprovalRequest[]>([]);- const [approvalActionLoading, setApprovalActionLoading] = createSignal<string | null>(null);- // Store execution results by approval ID so we can display them- const [executionResults, setExecutionResults] = createSignal<Map<string, ApprovalExecutionResult>>(new Map());-- // Approve and execute an investigation fix- const handleApproveInvestigationFix = async (approval: ApprovalRequest, e: Event) => {- e.stopPropagation();- setApprovalActionLoading(approval.id);- try {- const result = await AIAPI.approveInvestigationFix(approval.id);-- // Store the execution result- setExecutionResults(prev => {- const newMap = new Map(prev);- newMap.set(approval.id, result);- return newMap;- });-- if (result.success) {- notificationStore.success('Fix executed successfully');- } else {- notificationStore.error(result.error || 'Fix execution failed');- }-- // Reload approvals to get updated status- const approvals = await AIAPI.getPendingApprovals();- setPendingApprovals(approvals);- // Reload findings in case status changed- aiIntelligenceStore.loadFindings();- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to execute fix');- } finally {- setApprovalActionLoading(null);- }- };-- const handleDenyInvestigationFix = async (approval: ApprovalRequest, e: Event) => {- e.stopPropagation();- setApprovalActionLoading(approval.id);- try {- await AIAPI.denyInvestigationFix(approval.id);- notificationStore.success('Fix denied');- // Reload approvals- const approvals = await AIAPI.getPendingApprovals();- setPendingApprovals(approvals);- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to deny fix');- } finally {- setApprovalActionLoading(null);- }- };-- // Investigation details cache (for showing proposed fixes when approval expired)- const [investigationDetails, setInvestigationDetails] = createSignal<Map<string, InvestigationSession>>(new Map());- const [reapproveLoading, setReapproveLoading] = createSignal<string | null>(null);-- // Handle re-approve for expired approvals- const handleReapproveAndExecute = async (findingId: string, e: Event) => {- e.stopPropagation();- setReapproveLoading(findingId);- try {- // Create a new approval- const result = await AIAPI.reapproveInvestigationFix(findingId);- // Now approve and execute it- const execResult = await AIAPI.approveInvestigationFix(result.approval_id);-- // Store the execution result- setExecutionResults(prev => {- const newMap = new Map(prev);- newMap.set(result.approval_id, execResult);- return newMap;- });-- if (execResult.success) {- notificationStore.success('Fix executed successfully');- } else {- notificationStore.error(execResult.error || 'Fix execution failed');- }-- // Reload findings in case status changed- aiIntelligenceStore.loadFindings();- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to execute fix');- } finally {- setReapproveLoading(null);- }- };-- // Keep remediation plans for backwards compatibility (generic plans without real execution)+ // Legacy remediation plans (generic plans without real execution)const [remediationPlans, setRemediationPlans] = createSignal<RemediationPlan[]>([]);const [planActionLoading, setPlanActionLoading] = createSignal<string | null>(null);- // Remediation plan actions (legacy - these don't actually execute anything real)+ // Remediation plan actions (legacy)const handleApprovePlan = async (plan: RemediationPlan, e: Event) => {e.stopPropagation();setPlanActionLoading(plan.id);@@ -218,24 +130,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {notificationStore.success('Remediation plan dismissed');};- const openInvestigationDrawer = (finding: UnifiedFinding, e: Event) => {- e.stopPropagation();- setSelectedFindingForInvestigation(finding);- setInvestigationDrawerOpen(true);- };-- // Map of finding_id -> pending approval (investigation fixes)- const approvalsByFindingId = createMemo(() => {- const map = new Map<string, ApprovalRequest>();- for (const approval of pendingApprovals()) {- // Investigation fix approvals have targetId = finding ID- if (approval.toolId === 'investigation_fix') {- map.set(approval.targetId, approval);- }- }- return map;- });-// Map of finding_id -> remediation plan (legacy plans)const plansByFindingId = createMemo(() => {const map = new Map<string, RemediationPlan>();@@ -245,45 +139,15 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {return map;});- // Load findings, pending approvals, and remediation plans on mount+ // Load findings and remediation plans on mountcreateEffect(() => {aiIntelligenceStore.loadFindings();- // Fetch real investigation fix approvals- AIAPI.getPendingApprovals()- .then(approvals => setPendingApprovals(approvals))- .catch(() => {}); // Silently ignore errors// Fetch legacy remediation plansAIAPI.getRemediationPlans().then((response: { plans: RemediationPlan[] }) => setRemediationPlans(response.plans)).catch(() => {}); // Silently ignore errors});- // Fetch investigation details for findings with fix_queued outcome but no pending approval- createEffect(() => {- const findings = aiIntelligenceStore.findings;- const approvals = approvalsByFindingId();-- // Find findings that have fix_queued but no pending approval- const findingsNeedingDetails = findings.filter(f =>- f.investigationOutcome === 'fix_queued' &&- !approvals.has(f.id) &&- !investigationDetails().has(f.id)- );-- // Fetch investigation details for each- for (const finding of findingsNeedingDetails) {- AIAPI.getInvestigation(finding.id).then(inv => {- if (inv?.proposed_fix) {- setInvestigationDetails(prev => {- const newMap = new Map(prev);- newMap.set(finding.id, inv);- return newMap;- });- }- }).catch(() => {});- }- });-createEffect(() => {if (props.filterOverride) {setFilter(props.filterOverride);@@ -304,6 +168,9 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {findings = findings.filter(f => f.status === 'active');} else if (filter() === 'resolved') {findings = findings.filter(f => f.status === 'resolved' || f.status === 'dismissed');+ } else if (filter() === 'approvals') {+ const approvalFindingIds = new Set(aiIntelligenceStore.findingsWithPendingApprovals.map(f => f.id));+ findings = findings.filter(f => approvalFindingIds.has(f.id));}// Filter by specific finding IDs if provided@@ -315,12 +182,10 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {// Sortfindings.sort((a, b) => {if (sortBy() === 'severity') {- // Sort by urgency: critical (0) first, then warning (1), watch (2), info (3)const aPriority = severityOrder[a.severity] ?? 4;const bPriority = severityOrder[b.severity] ?? 4;if (aPriority !== bPriority) return aPriority - bPriority;}- // Secondary sort by time (most recent first)return new Date(b.detectedAt).getTime() - new Date(a.detectedAt).getTime();});@@ -413,6 +278,38 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {}};+ const handleStartEditNote = (finding: UnifiedFinding, e: Event) => {+ e.stopPropagation();+ setEditingNoteId(finding.id);+ setNoteText(finding.userNote || '');+ };++ const handleSaveNote = async (finding: UnifiedFinding, e: Event) => {+ e.stopPropagation();+ setActionLoading(finding.id);+ const ok = await aiIntelligenceStore.setFindingNote(finding.id, noteText());+ setActionLoading(null);+ if (ok) {+ setEditingNoteId(null);+ notificationStore.success('Note saved');+ } else {+ notificationStore.error('Failed to save note');+ }+ };++ const handleCancelNote = (e: Event) => {+ e.stopPropagation();+ setEditingNoteId(null);+ };++ const handleDiscussWithAssistant = (finding: UnifiedFinding, e: Event) => {+ e.stopPropagation();+ aiChatStore.openWithPrompt(+ `I'd like to discuss this Patrol finding: "${finding.title}" on ${finding.resourceName}.\n\n${finding.description}`,+ { targetType: finding.resourceType, targetId: finding.resourceId, findingId: finding.id },+ );+ };+const formatTime = (isoString: string) => {const date = new Date(isoString);const now = new Date();@@ -444,7 +341,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {const getResolutionReason = (finding: UnifiedFinding): string => {const resolvedTime = finding.resolvedAt ? formatTime(finding.resolvedAt) : '';- // For threshold alerts, provide specific reasons based on alert typeif (finding.isThreshold || finding.source === 'threshold') {const alertType = finding.alertType || '';switch (alertType) {@@ -465,16 +361,14 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {}}- // For AI patrol findingsif (finding.source === 'ai-patrol') {return `Issue no longer detected ${resolvedTime}`;}- // Generic fallbackreturn `Resolved ${resolvedTime}`;};- // Render a single finding item (shared between both sections)+ // Render a single finding itemconst renderFindingItem = (finding: UnifiedFinding, showSourceBadge: boolean = false) => (<divid={`finding-${finding.id}`}@@ -612,19 +506,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</svg></button></Show>- {/* Investigation button - show for findings with investigation data */}- <Show when={finding.investigationSessionId}>- <button- type="button"- onClick={(e) => openInvestigationDrawer(finding, e)}- class="p-1 text-purple-500 hover:text-purple-700 dark:hover:text-purple-300"- title="View investigation"- >- <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="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />- </svg>- </button>- </Show>{/* Expand indicator */}<svgclass={`w-4 h-4 text-gray-400 transition-transform ${expandedId() === finding.id ? 'rotate-180' : ''}`}@@ -644,7 +525,7 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</div>);- // Render expanded content for a finding (extracted for reuse)+ // Render expanded content for a findingconst renderExpandedContent = (finding: UnifiedFinding) => (<div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700"><Show when={finding.alertId}>@@ -660,6 +541,81 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {<span class="font-medium">Recommendation:</span> {finding.recommendation}</p></Show>++ {/* User note display / editor */}+ <Show when={editingNoteId() === finding.id}>+ <div class="mt-3 p-2 rounded border border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-900/20" onClick={(e) => e.stopPropagation()}>+ <textarea+ class="w-full text-sm rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 px-2 py-1.5 resize-none focus:outline-none focus:ring-1 focus:ring-blue-500"+ rows={3}+ value={noteText()}+ onInput={(e) => setNoteText(e.currentTarget.value)}+ placeholder="Add context for Patrol (e.g., 'PBS server was decommissioned last week')"+ />+ <div class="flex gap-2 mt-2">+ <button+ type="button"+ onClick={(e) => handleSaveNote(finding, e)}+ class="px-3 py-1 text-xs font-medium rounded bg-blue-600 hover:bg-blue-700 text-white disabled:opacity-50"+ disabled={actionLoading() === finding.id}+ >+ Save+ </button>+ <button+ type="button"+ onClick={handleCancelNote}+ class="px-3 py-1 text-xs font-medium rounded border border-gray-300 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700"+ >+ Cancel+ </button>+ </div>+ </div>+ </Show>+ <Show when={editingNoteId() !== finding.id && finding.userNote}>+ <div class="mt-3 p-2 rounded border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50 flex items-start gap-2">+ <svg class="w-4 h-4 text-gray-400 dark:text-gray-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />+ </svg>+ <p class="text-sm text-gray-600 dark:text-gray-400 flex-1">{finding.userNote}</p>+ <button+ type="button"+ onClick={(e) => handleStartEditNote(finding, e)}+ class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 flex-shrink-0"+ title="Edit note"+ >+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />+ </svg>+ </button>+ </div>+ </Show>++ {/* Add Note / Discuss with Assistant buttons */}+ <div class="mt-3 flex flex-wrap gap-2 text-xs">+ <Show when={editingNoteId() !== finding.id && !finding.userNote}>+ <button+ type="button"+ onClick={(e) => handleStartEditNote(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 flex items-center gap-1"+ >+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />+ </svg>+ Add Note+ </button>+ </Show>+ <button+ type="button"+ onClick={(e) => handleDiscussWithAssistant(finding, e)}+ class="px-2 py-1 rounded border border-blue-300 dark:border-blue-700 text-blue-700 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/30 flex items-center gap-1"+ >+ <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />+ </svg>+ Discuss with Assistant+ </button>+ </div>+<Show when={finding.status === 'active'}><div class="mt-3 flex flex-wrap gap-2 text-xs"><button@@ -725,161 +681,30 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {Related findings: {finding.correlatedFindingIds?.length}</div></Show>- {/* Investigation Fix Approval - real fixes that can be executed */}- <Show when={finding.status === 'active' && approvalsByFindingId().get(finding.id)}>- {(approval) => {- const result = () => executionResults().get(approval().id);- return (- <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">- <div class="flex items-center gap-2 mb-2">- <svg class="w-4 h-4 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />- </svg>- <span class="text-sm font-medium text-gray-900 dark:text-gray-100">Fix Available</span>- <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${- approval().riskLevel === 'high' ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' :- approval().riskLevel === 'medium' ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' :- 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'- }`}>- {approval().riskLevel} risk- </span>- </div>- <div class="space-y-2 text-sm">- <div class="text-gray-600 dark:text-gray-400">- {approval().context}- </div>- <div class="bg-gray-50 dark:bg-gray-800 rounded p-2 font-mono text-xs text-gray-700 dark:text-gray-300 break-all">- {approval().command}- </div>- </div>-- {/* Show execution result if available */}- <Show when={result()}>- {(res) => (- <div class={`mt-2 p-2 rounded text-xs ${- res().success- ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300'- : 'bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-300'- }`}>- <div class="font-medium mb-1">{res().success ? 'Fix executed successfully' : 'Fix failed'}</div>- <Show when={res().output}>- <div class="bg-white dark:bg-gray-900 rounded p-2 font-mono mt-1 max-h-32 overflow-auto whitespace-pre-wrap">- {res().output}- </div>- </Show>- <Show when={res().error}>- <div class="text-red-600 dark:text-red-400 mt-1">{res().error}</div>- </Show>- </div>- )}- </Show>-- {/* Action buttons */}- <Show when={!result()}>- <div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">- <button- type="button"- onClick={(e) => handleApproveInvestigationFix(approval(), e)}- disabled={approvalActionLoading() === approval().id}- class="flex-1 px-3 py-1.5 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-xs font-medium rounded flex items-center justify-center gap-1.5"- >- <Show when={approvalActionLoading() === approval().id}>- <span class="h-3 w-3 border-2 border-white border-t-transparent rounded-full animate-spin" />- </Show>- <Show when={approvalActionLoading() !== approval().id}>- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />- </svg>- </Show>- Approve & Execute- </button>- <button- type="button"- onClick={(e) => handleDenyInvestigationFix(approval(), e)}- disabled={approvalActionLoading() === approval().id}- class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-600 dark:text-gray-400 text-xs font-medium rounded"- >- Deny- </button>- </div>- </Show>- </div>- );- }}+ {/* Inline Investigation Section (replaces drawer) */}+ <Show when={finding.investigationSessionId}>+ <InvestigationSection+ findingId={finding.id}+ investigationStatus={finding.investigationStatus}+ investigationOutcome={finding.investigationOutcome}+ /></Show>- {/* Proposed Fix from Investigation (when approval expired) */}- <Show when={- finding.status === 'active' &&- finding.investigationOutcome === 'fix_queued' &&- !approvalsByFindingId().get(finding.id) &&- investigationDetails().get(finding.id)?.proposed_fix- }>- {(() => {- const inv = () => investigationDetails().get(finding.id)!;- const fix = () => inv().proposed_fix!;- return (- <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">- <div class="flex items-center gap-2 mb-2">- <svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />- </svg>- <span class="text-sm font-medium text-gray-900 dark:text-gray-100">Fix Pending Approval</span>- <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${- fix().risk_level === 'high' || fix().risk_level === 'critical' ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300' :- fix().risk_level === 'medium' ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' :- 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'- }`}>- {fix().risk_level || 'unknown'} risk- </span>- <span class="px-1.5 py-0.5 text-[10px] font-medium rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300">- approval expired- </span>- </div>-- <div class="space-y-2 text-sm">- <div class="text-gray-600 dark:text-gray-400">- {fix().description || 'Proposed fix from investigation'}- </div>- <Show when={fix().commands && fix().commands!.length > 0}>- <div class="bg-gray-50 dark:bg-gray-800 rounded p-2 font-mono text-xs text-gray-700 dark:text-gray-300 break-all">- {fix().commands![0]}- </div>- </Show>- <Show when={fix().target_host}>- <div class="text-xs text-gray-500 dark:text-gray-400">- Target: {fix().target_host}- </div>- </Show>- </div>-- {/* Action buttons */}- <div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">- <button- type="button"- onClick={(e) => handleReapproveAndExecute(finding.id, e)}- disabled={reapproveLoading() === finding.id}- class="flex-1 px-3 py-1.5 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-xs font-medium rounded flex items-center justify-center gap-1.5"- >- <Show when={reapproveLoading() === finding.id}>- <span class="h-3 w-3 border-2 border-white border-t-transparent rounded-full animate-spin" />- </Show>- <Show when={reapproveLoading() !== finding.id}>- <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />- </svg>- </Show>- Approve & Execute- </button>- </div>- </div>- );- })()}+ {/* Inline Approval Section (replaces manual approval JSX) */}+ <Show when={finding.status === 'active' && (+ finding.investigationOutcome === 'fix_queued' ||+ finding.investigationOutcome === 'fix_executed' ||+ finding.investigationOutcome === 'fix_failed'+ )}>+ <ApprovalSection+ findingId={finding.id}+ investigationOutcome={finding.investigationOutcome}+ /></Show>- {/* Legacy Remediation Plan - only shown if no investigation fix approval exists */}- <Show when={finding.status === 'active' && !approvalsByFindingId().get(finding.id) && !investigationDetails().get(finding.id)?.proposed_fix && plansByFindingId().get(finding.id)}>+ {/* Legacy Remediation Plan - only shown if no investigation fix exists */}+ <Show when={finding.status === 'active' && !finding.investigationOutcome && plansByFindingId().get(finding.id)}>{(plan) => (<div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700"><div class="flex items-center gap-2 mb-2">@@ -917,7 +742,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</For></div>- {/* Action buttons for pending plans */}<Show when={plan().status === 'pending'}><div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700"><button@@ -947,7 +771,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</div></Show>- {/* Status indicators for non-pending plans */}<Show when={plan().status === 'executing'}><div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700 text-amber-600 dark:text-amber-400"><span class="h-3 w-3 border-2 border-current border-t-transparent rounded-full animate-spin" />@@ -975,24 +798,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</div>)}</Show>- {/* Investigation link */}- <Show when={finding.investigationSessionId}>- <div class="mt-2">- <button- type="button"- onClick={(e) => openInvestigationDrawer(finding, e)}- class="text-xs text-purple-600 dark:text-purple-400 hover:underline flex items-center gap-1"- >- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />- </svg>- View investigation details- <Show when={finding.investigationStatus === 'running'}>- <span class="ml-1 h-2 w-2 border border-purple-400 border-t-transparent rounded-full animate-spin" />- </Show>- </button>- </div>- </Show></div>);@@ -1025,13 +830,25 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {<buttontype="button"onClick={() => setFilter('resolved')}- class={`px-2 py-1 rounded-r border ${filter() === 'resolved'+ class={`px-2 py-1 border ${filter() === 'resolved'? 'bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 border-blue-300 dark:border-blue-700': 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700'- }`}+ } ${aiIntelligenceStore.pendingApprovalCount > 0 ? '' : 'rounded-r'}`}>Resolved</button>+ <Show when={aiIntelligenceStore.pendingApprovalCount > 0}>+ <button+ type="button"+ onClick={() => setFilter('approvals')}+ class={`px-2 py-1 rounded-r border ${filter() === 'approvals'+ ? 'bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300 border-amber-300 dark:border-amber-700'+ : 'border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700'+ }`}+ >+ Approvals ({aiIntelligenceStore.pendingApprovalCount})+ </button>+ </Show></div><selectvalue={sortBy()}@@ -1134,23 +951,6 @@ export const FindingsPanel: Component<FindingsPanelProps> = (props) => {</div></Card></Show>-- {/* Investigation Drawer */}- <InvestigationDrawer- open={investigationDrawerOpen()}- onClose={() => {- setInvestigationDrawerOpen(false);- setSelectedFindingForInvestigation(null);- }}- findingId={selectedFindingForInvestigation()?.id}- findingTitle={selectedFindingForInvestigation()?.title}- findingSeverity={selectedFindingForInvestigation()?.severity as 'critical' | 'warning' | 'watch' | 'info'}- resourceName={selectedFindingForInvestigation()?.resourceName}- resourceType={selectedFindingForInvestigation()?.resourceType}- onReinvestigate={() => {- aiIntelligenceStore.loadFindings();- }}- /></div>);};diff --git a/frontend-modern/src/components/AI/InvestigationDrawer.tsx b/frontend-modern/src/components/AI/InvestigationDrawer.tsxdeleted file mode 100644index 0970feea11..0000000000--- a/frontend-modern/src/components/AI/InvestigationDrawer.tsx+++ /dev/null@@ -1,535 +0,0 @@-/**- * InvestigationDrawer - Slide-out drawer showing investigation details- *- * Displays:- * - Finding summary header- * - Investigation status badge- * - Full chat thread (read-only)- * - Proposed fix with approve/skip buttons (if pending)- * - Re-investigate button (if failed or needs attention)- */--import { Component, createSignal, createEffect, Show, For } from 'solid-js';-import { Portal } from 'solid-js/web';-import {- type Investigation,- type ChatMessage,- type FindingSeverity,- getInvestigation,- getInvestigationMessages,- reinvestigateFinding,- approveFix,- denyFix,- investigationStatusLabels,- investigationOutcomeLabels,- severityColors,- formatTimestamp,-} from '@/api/patrol';-import { notificationStore } from '@/stores/notifications';--interface InvestigationDrawerProps {- open: boolean;- onClose: () => void;- findingId?: string;- findingTitle?: string;- findingSeverity?: FindingSeverity;- resourceName?: string;- resourceType?: string;- onReinvestigate?: () => void;- onFixApproved?: () => void;-}--// Status badge colors-const statusColors: Record<string, string> = {- pending: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',- running: 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300',- completed: 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300',- failed: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300',- needs_attention: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',-};--// Outcome badge colors-const outcomeColors: Record<string, string> = {- resolved: 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300',- fix_queued: 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300',- fix_executed: 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300',- fix_failed: 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300',- needs_attention: 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300',- cannot_fix: 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300',-};--export const InvestigationDrawer: Component<InvestigationDrawerProps> = (props) => {- const [investigation, setInvestigation] = createSignal<Investigation | null>(null);- const [messages, setMessages] = createSignal<ChatMessage[]>([]);- const [loading, setLoading] = createSignal(false);- const [error, setError] = createSignal<string | null>(null);- const [reinvestigating, setReinvestigating] = createSignal(false);- const [approvingFix, setApprovingFix] = createSignal(false);- const [denyingFix, setDenyingFix] = createSignal(false);- const toolsAvailable = () => investigation()?.tools_available ?? [];- const toolsUsed = () => investigation()?.tools_used ?? [];- const evidenceIDs = () => investigation()?.evidence_ids ?? [];-- const handleCopyEvidence = async () => {- if (!evidenceIDs().length) return;- const payload = evidenceIDs().join('\n');- try {- await navigator.clipboard.writeText(payload);- notificationStore.success('Evidence IDs copied');- } catch (_err) {- notificationStore.error('Failed to copy evidence IDs');- }- };-- // Load investigation data when drawer opens- createEffect(async () => {- if (!props.open || !props.findingId) {- setInvestigation(null);- setMessages([]);- return;- }-- setLoading(true);- setError(null);-- try {- const [inv, msgs] = await Promise.all([- getInvestigation(props.findingId),- getInvestigationMessages(props.findingId),- ]);- setInvestigation(inv);- setMessages(msgs.messages || []);- } catch (err) {- setError((err as Error).message || 'Failed to load investigation');- } finally {- setLoading(false);- }- });-- const handleReinvestigate = async () => {- if (!props.findingId) return;-- setReinvestigating(true);- try {- await reinvestigateFinding(props.findingId);- notificationStore.success('Re-investigation started');- // Reload investigation data- const inv = await getInvestigation(props.findingId);- setInvestigation(inv);- // Notify parent to reload findings- props.onReinvestigate?.();- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to start re-investigation');- } finally {- setReinvestigating(false);- }- };-- const handleApproveFix = async () => {- const inv = investigation();- if (!inv?.approval_id) return;-- setApprovingFix(true);- try {- const result = await approveFix(inv.approval_id);- if (result.success) {- notificationStore.success(result.message || 'Fix executed successfully');- } else {- // Fix was executed but failed (non-zero exit code)- notificationStore.error(result.message || 'Fix execution failed');- }- // Reload investigation data- if (props.findingId) {- const updatedInv = await getInvestigation(props.findingId);- setInvestigation(updatedInv);- }- // Notify parent to reload findings- props.onFixApproved?.();- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to execute fix');- } finally {- setApprovingFix(false);- }- };-- const handleDenyFix = async () => {- const inv = investigation();- if (!inv?.approval_id) return;-- setDenyingFix(true);- try {- await denyFix(inv.approval_id);- notificationStore.success('Fix skipped');- // Reload investigation data- if (props.findingId) {- const updatedInv = await getInvestigation(props.findingId);- setInvestigation(updatedInv);- }- } catch (err) {- notificationStore.error((err as Error).message || 'Failed to skip fix');- } finally {- setDenyingFix(false);- }- };-- const hasPendingApproval = () => {- const inv = investigation();- return inv?.outcome === 'fix_queued' && inv?.approval_id;- };-- const canReinvestigate = () => {- const inv = investigation();- if (!props.findingId) return false;- if (inv?.status === 'running') return false;- // Can reinvestigate if failed, needs attention, or completed with cannot_fix outcome- const status = inv?.status;- const outcome = inv?.outcome;- return status === 'failed' || status === 'needs_attention' || outcome === 'cannot_fix';- };-- return (- <Portal>- {/* Backdrop */}- <Show when={props.open}>- <div- class="fixed inset-0 bg-black/50 z-40 transition-opacity"- onClick={props.onClose}- />- </Show>-- {/* Drawer */}- <div- class={`fixed inset-y-0 right-0 w-full max-w-xl bg-white dark:bg-gray-900 shadow-xl z-50 transform transition-transform duration-300 ${- props.open ? 'translate-x-0' : 'translate-x-full'- }`}- >- {/* Header */}- <div class="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700 bg-gradient-to-r from-blue-50 to-blue-100 dark:from-blue-900/20 dark:to-blue-900/30">- <div class="flex items-center gap-2">- <svg class="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />- </svg>- <span class="font-medium text-gray-900 dark:text-gray-100">Investigation</span>- </div>- <button- type="button"- onClick={props.onClose}- class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"- >- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />- </svg>- </button>- </div>-- {/* Content */}- <div class="h-full overflow-y-auto pb-20">- <Show when={loading()}>- <div class="p-4 flex items-center justify-center">- <span class="h-5 w-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />- <span class="ml-2 text-gray-500">Loading...</span>- </div>- </Show>-- <Show when={error()}>- <div class="p-4 text-red-600 dark:text-red-400">{error()}</div>- </Show>-- <Show when={!loading() && !error() && props.findingId}>- {/* Finding Summary */}- <div class="p-4 border-b border-gray-200 dark:border-gray-700">- <div class="flex items-start gap-2">- {/* Severity indicator */}- <div- class="w-1 h-16 rounded-full"- style={{- 'background-color': props.findingSeverity ? (severityColors[props.findingSeverity]?.text || '#9ca3af') : '#9ca3af',- }}- />- <div class="flex-1">- <div class="flex items-center gap-2 flex-wrap">- <Show when={props.findingSeverity}>- <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded uppercase ${- props.findingSeverity === 'critical' ? 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300' :- props.findingSeverity === 'warning' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300' :- 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'- }`}>- {props.findingSeverity}- </span>- </Show>- <Show when={investigation()?.status}>- <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${- statusColors[investigation()!.status] || statusColors.pending- }`}>- {investigationStatusLabels[investigation()!.status] || investigation()!.status}- </span>- </Show>- <Show when={investigation()?.outcome}>- <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${- outcomeColors[investigation()!.outcome!] || outcomeColors.needs_attention- }`}>- {investigationOutcomeLabels[investigation()!.outcome!] || investigation()!.outcome}- </span>- </Show>- </div>- <h3 class="font-medium text-gray-900 dark:text-gray-100 mt-1">- {props.findingTitle || 'Investigation Details'}- </h3>- <p class="text-sm text-gray-500 dark:text-gray-400">- {props.resourceName} ({props.resourceType})- </p>- </div>- </div>- </div>-- {/* Investigation Stats */}- <Show when={investigation()}>- <div class="p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/50">- <div class="grid grid-cols-3 gap-4 text-center">- <div>- <div class="text-2xl font-bold text-gray-900 dark:text-gray-100">- {investigation()!.turn_count}- </div>- <div class="text-xs text-gray-500 dark:text-gray-400">Turns Used</div>- </div>- <div>- <div class="text-2xl font-bold text-gray-900 dark:text-gray-100">- 1- </div>- <div class="text-xs text-gray-500 dark:text-gray-400">Attempt</div>- </div>- <div>- <div class="text-sm font-medium text-gray-900 dark:text-gray-100">- {investigation()!.started_at ? formatTimestamp(investigation()!.started_at) : '-'}- </div>- <div class="text-xs text-gray-500 dark:text-gray-400">Started</div>- </div>- </div>- </div>- </Show>-- {/* Summary */}- <Show when={investigation()?.summary}>- <div class="p-4 border-b border-gray-200 dark:border-gray-700">- <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Summary</h4>- <div class="text-sm text-gray-600 dark:text-gray-400 whitespace-pre-wrap bg-gray-50 dark:bg-gray-800/50 rounded p-3">- {investigation()!.summary}- </div>- </div>- </Show>-- {/* Tools & Evidence */}- <Show when={toolsUsed().length || toolsAvailable().length || evidenceIDs().length}>- <div class="p-4 border-b border-gray-200 dark:border-gray-700">- <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Tools & Evidence</h4>-- <Show when={toolsUsed().length}>- <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">Tools used</div>- <div class="flex flex-wrap gap-1 mb-3">- <For each={toolsUsed()}>- {(tool) => (- <span class="px-1.5 py-0.5 rounded bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 text-[10px] font-medium">- {tool}- </span>- )}- </For>- </div>- </Show>-- <Show when={toolsAvailable().length}>- <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">Tools available</div>- <div class="flex flex-wrap gap-1 mb-3 max-h-20 overflow-y-auto">- <For each={toolsAvailable()}>- {(tool) => (- <span class="px-1.5 py-0.5 rounded bg-gray-50 text-gray-600 dark:bg-gray-800/70 dark:text-gray-300 text-[10px]">- {tool}- </span>- )}- </For>- </div>- </Show>-- <Show when={evidenceIDs().length}>- <div class="flex items-center justify-between mb-1">- <div class="text-xs text-gray-500 dark:text-gray-400">Evidence IDs</div>- <button- type="button"- onClick={handleCopyEvidence}- class="text-[10px] px-2 py-0.5 rounded border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 hover:border-gray-300 dark:hover:border-gray-600 transition-colors"- >- Copy- </button>- </div>- <div class="flex flex-wrap gap-1">- <For each={evidenceIDs()}>- {(id) => (- <span class="px-1.5 py-0.5 rounded bg-gray-900 text-green-300 text-[10px] font-mono">- {id}- </span>- )}- </For>- </div>- </Show>- </div>- </Show>-- {/* Proposed Fix */}- <Show when={investigation()?.proposed_fix}>- <div class="p-4 border-b border-gray-200 dark:border-gray-700">- <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">Proposed Fix</h4>- <div class="bg-gray-50 dark:bg-gray-800/50 rounded p-3">- <p class="text-sm text-gray-600 dark:text-gray-400 mb-2">- {investigation()!.proposed_fix!.description}- </p>- <Show when={investigation()!.proposed_fix!.commands?.length}>- <div class="font-mono text-xs bg-gray-900 text-green-400 p-2 rounded mt-2 overflow-x-auto">- <For each={investigation()!.proposed_fix!.commands}>- {(cmd) => <div>$ {cmd}</div>}- </For>- </div>- </Show>- <div class="flex items-center gap-2 mt-2 text-xs">- <Show when={investigation()!.proposed_fix!.risk_level}>- <span class={`px-1.5 py-0.5 rounded ${- investigation()!.proposed_fix!.risk_level === 'critical' ? 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300' :- investigation()!.proposed_fix!.risk_level === 'high' ? 'bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300' :- investigation()!.proposed_fix!.risk_level === 'medium' ? 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300' :- 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300'- }`}>- {investigation()!.proposed_fix!.risk_level} risk- </span>- </Show>- <Show when={investigation()!.proposed_fix!.destructive}>- <span class="px-1.5 py-0.5 rounded bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300">- Destructive- </span>- </Show>- </div>-- {/* Approve/Skip buttons when fix is pending approval */}- <Show when={hasPendingApproval()}>- <div class="flex items-center gap-2 mt-4 pt-3 border-t border-gray-200 dark:border-gray-700">- <button- type="button"- onClick={handleApproveFix}- disabled={approvingFix() || denyingFix()}- class="flex-1 px-3 py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-sm font-medium rounded-lg flex items-center justify-center gap-2"- >- <Show when={approvingFix()}>- <span class="h-4 w-4 border-2 border-white border-t-transparent rounded-full animate-spin" />- </Show>- <Show when={!approvingFix()}>- <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="M5 13l4 4L19 7" />- </svg>- </Show>- Approve & Execute- </button>- <button- type="button"- onClick={handleDenyFix}- disabled={approvingFix() || denyingFix()}- class="px-3 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-700 dark:text-gray-300 text-sm font-medium rounded-lg flex items-center justify-center gap-2"- >- <Show when={denyingFix()}>- <span class="h-4 w-4 border-2 border-gray-500 border-t-transparent rounded-full animate-spin" />- </Show>- Skip- </button>- </div>- </Show>-- {/* Show if fix was already executed successfully */}- <Show when={investigation()?.outcome === 'resolved' || investigation()?.outcome === 'fix_executed'}>- <div class="mt-4 pt-3 border-t border-gray-200 dark:border-gray-700">- <div class="flex items-center gap-2 text-green-600 dark:text-green-400">- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />- </svg>- <span class="text-sm font-medium">Fix executed successfully</span>- </div>- </div>- </Show>-- {/* Show if fix execution failed */}- <Show when={investigation()?.outcome === 'fix_failed'}>- <div class="mt-4 pt-3 border-t border-gray-200 dark:border-gray-700">- <div class="flex items-center gap-2 text-red-600 dark:text-red-400">- <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />- </svg>- <span class="text-sm font-medium">Fix execution failed</span>- </div>- </div>- </Show>- </div>- </div>- </Show>-- {/* Chat Messages */}- <Show when={messages().length > 0}>- <div class="p-4">- <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">Investigation Thread</h4>- <div class="space-y-3">- <For each={messages()}>- {(msg) => (- <div class={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>- <div class={`max-w-[85%] rounded-lg px-3 py-2 ${- msg.role === 'user'- ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-900 dark:text-blue-100'- : msg.role === 'system'- ? 'bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400 text-xs'- : 'bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-gray-200'- }`}>- <div class="text-sm whitespace-pre-wrap">{msg.content}</div>- <div class="text-[10px] text-gray-500 dark:text-gray-500 mt-1">- {formatTimestamp(msg.timestamp)}- </div>- </div>- </div>- )}- </For>- </div>- </div>- </Show>-- {/* No Investigation */}- <Show when={!investigation()}>- <div class="p-4 text-center text-gray-500 dark:text-gray-400">- <svg class="w-12 h-12 mx-auto mb-2 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />- </svg>- <p class="text-sm">No investigation data available.</p>- <p class="text-xs mt-1">Enable patrol autonomy to automatically investigate findings.</p>- </div>- </Show>- </Show>- </div>-- {/* Footer Actions */}- <Show when={props.findingId && canReinvestigate()}>- <div class="absolute bottom-0 left-0 right-0 p-4 bg-white dark:bg-gray-900 border-t border-gray-200 dark:border-gray-700">- <button- type="button"- onClick={handleReinvestigate}- disabled={reinvestigating()}- class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg font-medium flex items-center justify-center gap-2"- >- <Show when={reinvestigating()}>- <span class="h-4 w-4 border-2 border-white border-t-transparent rounded-full animate-spin" />- </Show>- <Show when={!reinvestigating()}>- <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="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />- </svg>- </Show>- Re-investigate- </button>- </div>- </Show>- </div>- </Portal>- );-};--export default InvestigationDrawer;diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsxindex 2dde3da2db..1761668d83 100644--- a/frontend-modern/src/components/Settings/AISettings.tsx+++ b/frontend-modern/src/components/Settings/AISettings.tsx@@ -118,13 +118,11 @@ export const AISettings: Component = () => {// Per-provider test stateconst [testingProvider, setTestingProvider] = createSignal<string | null>(null);const [providerTestResult, setProviderTestResult] = createSignal<{ provider: string; success: boolean; message: string } | null>(null);- const hasAlertAnalysisFeature = createMemo(() => hasFeature('ai_alerts'));const hasAutoFixFeature = createMemo(() => hasFeature('ai_autofix'));- const alertAnalysisLocked = createMemo(() => !hasAlertAnalysisFeature());const autoFixLocked = createMemo(() => !hasAutoFixFeature());// Auto-fix acknowledgement state (not persisted - must acknowledge each session)- const [autoFixAcknowledged, setAutoFixAcknowledged] = createSignal(false);+ // Note: autoFixAcknowledged removed — auto-fix UI moved to Patrol page// First-time setup modal stateconst [showSetupModal, setShowSetupModal] = createSignal(false);@@ -135,7 +133,7 @@ export const AISettings: Component = () => {// UI state for collapsible sections - START COLLAPSED for compact viewconst [showAdvancedModels, setShowAdvancedModels] = createSignal(false);- const [showPatrolSettings, setShowPatrolSettings] = createSignal(false);+ // Note: showPatrolSettings removed — patrol settings section moved to Patrol pageconst [showDiscoverySettings, setShowDiscoverySettings] = createSignal(false);const [showChatMaintenance, setShowChatMaintenance] = createSignal(false);@@ -1363,185 +1361,6 @@ export const AISettings: Component = () => {</div></div>- {/* Pulse Patrol & Efficiency Settings - Collapsible */}- <div class="border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">- <button- type="button"- class="w-full px-3 py-2 flex items-center justify-between bg-blue-50 dark:bg-blue-900/20 hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors text-left"- onClick={() => setShowPatrolSettings(!showPatrolSettings())}- >- <div class="flex items-center gap-2">- <svg class="w-4 h-4 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />- </svg>- <span class="text-sm font-medium text-gray-700 dark:text-gray-300">Pulse Patrol Settings</span>- {/* Summary badges */}- <Show when={form.patrolIntervalMinutes > 0}>- <span class="px-1.5 py-0.5 text-[10px] font-medium bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 rounded">- {form.patrolIntervalMinutes >= 60 ? `${Math.floor(form.patrolIntervalMinutes / 60)}h` : `${form.patrolIntervalMinutes}m`}- </span>- </Show>- <Show when={form.patrolAutoFix}>- <span class="px-1.5 py-0.5 text-[10px] font-semibold bg-amber-100 dark:bg-amber-800 text-amber-700 dark:text-amber-300 rounded">Auto-Fix</span>- </Show>- </div>- <svg class={`w-4 h-4 text-gray-500 transition-transform ${showPatrolSettings() ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />- </svg>- </button>- <Show when={showPatrolSettings()}>- <div class="px-3 py-3 bg-white dark:bg-gray-800/50 border-t border-gray-200 dark:border-gray-700 space-y-3">- {/* Patrol Interval - Compact */}- <div class="flex flex-col gap-1">- <div class="flex items-center gap-3">- <label class="text-xs font-medium text-gray-600 dark:text-gray-400 w-32 flex-shrink-0">Patrol Interval</label>- <input- type="number"- class={`w-20 px-2 py-1 text-sm border rounded bg-white dark:bg-gray-700 ${form.patrolIntervalMinutes > 0 && form.patrolIntervalMinutes < 10- ? 'border-red-300 dark:border-red-600'- : 'border-gray-300 dark:border-gray-600'- }`}- value={form.patrolIntervalMinutes}- onInput={(e) => {- const value = parseInt(e.currentTarget.value, 10);- if (!isNaN(value)) setForm('patrolIntervalMinutes', Math.max(0, value));- }}- min={0}- max={10080}- step={15}- disabled={saving()}- />- <span class="text-xs text-gray-500">min (0=off, 10+ to enable)</span>- </div>- <Show when={form.patrolIntervalMinutes > 0 && form.patrolIntervalMinutes < 10}>- <p class="text-xs text-red-500 ml-32 pl-3">Minimum interval is 10 minutes</p>- </Show>- </div>-- {/* Alert Analysis Toggle - Compact */}- <div class="flex items-center justify-between gap-2">- <label class="text-xs font-medium text-gray-600 dark:text-gray-400 flex items-center gap-1.5">- Alert-Triggered Analysis- <span class="px-1 py-0.5 text-[9px] font-medium bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 rounded">Efficient</span>- </label>- <Toggle- checked={form.alertTriggeredAnalysis}- onChange={(event) => setForm('alertTriggeredAnalysis', event.currentTarget.checked)}- disabled={saving() || alertAnalysisLocked()}- />- </div>- <Show when={alertAnalysisLocked()}>- <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">- <a- class="text-indigo-600 dark:text-indigo-400 font-medium hover:underline"- href="https://pulserelay.pro/"- target="_blank"- rel="noreferrer"- >- Upgrade to Pro- </a>{' '}- to enable alert-triggered analysis.- </p>- </Show>-- {/* Auto-Fix Toggle - Compact with inline warning */}- <div class="pt-2 border-t border-gray-200 dark:border-gray-700">- <div class="flex items-center justify-between gap-2">- <label class="text-xs font-medium text-gray-600 dark:text-gray-400 flex items-center gap-1.5">- Auto-Fix Mode- <span class="px-1 py-0.5 text-[9px] font-medium bg-amber-100 dark:bg-amber-900 text-amber-700 dark:text-amber-300 rounded">Advanced</span>- </label>- <Show when={autoFixAcknowledged() || form.patrolAutoFix}>- <Toggle- checked={form.patrolAutoFix}- onChange={(event) => setForm('patrolAutoFix', event.currentTarget.checked)}- disabled={saving() || autoFixLocked()}- />- </Show>- <Show when={!autoFixAcknowledged() && !form.patrolAutoFix}>- <button- type="button"- onClick={() => {- setAutoFixAcknowledged(true);- setForm('patrolAutoFix', true);- }}- disabled={saving() || autoFixLocked()}- class="px-2 py-1 text-xs bg-amber-100 dark:bg-amber-900 text-amber-700 dark:text-amber-300 rounded hover:bg-amber-200 dark:hover:bg-amber-800 disabled:opacity-60 disabled:cursor-not-allowed"- >- Enable- </button>- </Show>- </div>- <Show when={autoFixLocked()}>- <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">- <a- class="text-indigo-600 dark:text-indigo-400 font-medium hover:underline"- href="https://pulserelay.pro/"- target="_blank"- rel="noreferrer"- >- Upgrade to Pro- </a>{' '}- to enable auto-fix.- </p>- </Show>- <Show when={!autoFixLocked() && !form.patrolAutoFix && !autoFixAcknowledged()}>- <p class="text-[10px] text-amber-600 dark:text-amber-400 mt-1">- ⚠️ Pulse Patrol will execute fixes without approval. Enable with caution.- </p>- </Show>- <Show when={!autoFixLocked() && form.patrolAutoFix}>- <p class="text-[10px] text-red-600 dark:text-red-400 mt-1 flex items-center gap-1">- <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />- </svg>- Auto-Fix is ON. Pulse Patrol will attempt automatic remediation.- </p>- </Show>- </div>-- {/* Auto-Fix Model - Only when enabled */}- <Show when={form.patrolAutoFix && !autoFixLocked()}>- <div class="flex items-center gap-3 pt-2 border-t border-gray-200 dark:border-gray-700">- <label class="text-xs font-medium text-gray-600 dark:text-gray-400 w-32 flex-shrink-0">Fix Model</label>- <Show when={availableModels().length > 0} fallback={- <input- type="text"- value={form.autoFixModel}- onInput={(e) => setForm('autoFixModel', e.currentTarget.value)}- placeholder="Use patrol model"- class="flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"- disabled={saving()}- />- }>- <select- value={form.autoFixModel}- onChange={(e) => setForm('autoFixModel', e.currentTarget.value)}- class="flex-1 px-2 py-1 text-sm border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700"- disabled={saving()}- >- <option value="">Use patrol model</option>- <For each={Array.from(groupModelsByProvider(availableModels()).entries())}>- {([provider, models]) => (- <optgroup label={PROVIDER_DISPLAY_NAMES[provider] || provider}>- <For each={models}>- {(model) => (- <option value={model.id}>- {model.name || model.id.split(':').pop()}- </option>- )}- </For>- </optgroup>- )}- </For>- </select>- </Show>- </div>- </Show>- </div>- </Show>- </div>-{/* Discovery Settings - Collapsible */}<div class="rounded-lg border border-cyan-200 dark:border-cyan-800 overflow-hidden"><buttondiff --git a/frontend-modern/src/components/patrol/ApprovalBanner.tsx b/frontend-modern/src/components/patrol/ApprovalBanner.tsxnew file mode 100644index 0000000000..443591b65d--- /dev/null+++ b/frontend-modern/src/components/patrol/ApprovalBanner.tsx@@ -0,0 +1,160 @@+/**+ * ApprovalBanner+ *+ * Sticky amber banner at top of page content area.+ * Surfaces pending investigation fix approvals (5-min expiry).+ * - Hidden when no pending approvals+ * - Single approval: inline approve/deny+ * - Multiple: count + "Review" button to scroll to first finding+ */++import { Component, Show, createMemo } from 'solid-js';+import { aiIntelligenceStore } from '@/stores/aiIntelligence';+import { notificationStore } from '@/stores/notifications';+import type { ApprovalRequest } from '@/api/ai';+import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';+import CheckIcon from 'lucide-solid/icons/check';+import XIcon from 'lucide-solid/icons/x';+import { createSignal } from 'solid-js';++interface ApprovalBannerProps {+ onScrollToFinding?: (findingId: string) => void;+}++export const ApprovalBanner: Component<ApprovalBannerProps> = (props) => {+ const [actionLoading, setActionLoading] = createSignal<string | null>(null);++ const pending = createMemo(() =>+ aiIntelligenceStore.pendingApprovals.filter((a: ApprovalRequest) => a.status === 'pending')+ );++ const firstApproval = createMemo(() => pending()[0] ?? null);++ const timeRemaining = (expiresAt: string) => {+ const diff = new Date(expiresAt).getTime() - Date.now();+ if (diff <= 0) return 'expired';+ const mins = Math.floor(diff / 60000);+ const secs = Math.floor((diff % 60000) / 1000);+ if (mins > 0) return `${mins}m ${secs}s`;+ return `${secs}s`;+ };++ const riskBadgeColor = (level: string) => {+ switch (level) {+ case 'high': return 'bg-red-200 text-red-800 dark:bg-red-900/50 dark:text-red-300';+ case 'medium': return 'bg-amber-200 text-amber-800 dark:bg-amber-900/50 dark:text-amber-300';+ default: return 'bg-green-200 text-green-800 dark:bg-green-900/50 dark:text-green-300';+ }+ };++ const handleApprove = async (approval: ApprovalRequest) => {+ setActionLoading(approval.id);+ try {+ const result = await aiIntelligenceStore.approveInvestigationFix(approval.id);+ if (result?.success) {+ notificationStore.success('Fix executed successfully');+ } else {+ notificationStore.error(result?.error || 'Fix execution failed');+ }+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to execute fix');+ } finally {+ setActionLoading(null);+ }+ };++ const handleDeny = async (approval: ApprovalRequest) => {+ setActionLoading(approval.id);+ try {+ await aiIntelligenceStore.denyInvestigationFix(approval.id);+ notificationStore.success('Fix denied');+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to deny fix');+ } finally {+ setActionLoading(null);+ }+ };++ const handleReview = () => {+ const findings = aiIntelligenceStore.findingsWithPendingApprovals;+ if (findings.length > 0) {+ props.onScrollToFinding?.(findings[0].id);+ }+ };++ return (+ <Show when={pending().length > 0}>+ <div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg px-4 py-3">+ <div class="flex items-center justify-between gap-3 flex-wrap">+ <div class="flex items-center gap-3">+ <div class="flex-shrink-0 p-1.5 bg-amber-100 dark:bg-amber-900/40 rounded-lg">+ <ShieldAlertIcon class="w-4 h-4 text-amber-600 dark:text-amber-400" />+ </div>+ <div>+ <Show when={pending().length === 1 && firstApproval()}>+ <div class="flex items-center gap-2 flex-wrap">+ <span class="text-sm font-medium text-amber-900 dark:text-amber-100">+ Fix awaiting approval+ </span>+ <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${riskBadgeColor(firstApproval()!.riskLevel)}`}>+ {firstApproval()!.riskLevel} risk+ </span>+ <span class="text-xs text-amber-700 dark:text-amber-300">+ expires {timeRemaining(firstApproval()!.expiresAt)}+ </span>+ </div>+ <p class="text-xs text-amber-700 dark:text-amber-300 mt-0.5 max-w-xl truncate">+ {firstApproval()!.context}+ </p>+ </Show>+ <Show when={pending().length > 1}>+ <span class="text-sm font-medium text-amber-900 dark:text-amber-100">+ {pending().length} fixes awaiting your approval+ </span>+ </Show>+ </div>+ </div>++ <div class="flex items-center gap-2">+ <Show when={pending().length === 1 && firstApproval()}>+ <button+ type="button"+ onClick={() => handleApprove(firstApproval()!)}+ disabled={actionLoading() === firstApproval()!.id}+ class="flex items-center gap-1.5 px-3 py-1.5 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-xs font-medium rounded-md transition-colors"+ >+ <Show when={actionLoading() === firstApproval()!.id}>+ <span class="h-3 w-3 border-2 border-white border-t-transparent rounded-full animate-spin" />+ </Show>+ <Show when={actionLoading() !== firstApproval()!.id}>+ <CheckIcon class="w-3.5 h-3.5" />+ </Show>+ Approve & Execute+ </button>+ <button+ type="button"+ onClick={() => handleDeny(firstApproval()!)}+ disabled={actionLoading() === firstApproval()!.id}+ class="flex items-center gap-1.5 px-3 py-1.5 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-700 dark:text-gray-300 text-xs font-medium rounded-md transition-colors"+ >+ <XIcon class="w-3.5 h-3.5" />+ Deny+ </button>+ </Show>+ <Show when={pending().length > 1}>+ <button+ type="button"+ onClick={handleReview}+ class="flex items-center gap-1.5 px-3 py-1.5 bg-amber-600 hover:bg-amber-700 text-white text-xs font-medium rounded-md transition-colors"+ >+ Review+ </button>+ </Show>+ </div>+ </div>+ </div>+ </Show>+ );+};++export default ApprovalBanner;diff --git a/frontend-modern/src/components/patrol/ApprovalSection.tsx b/frontend-modern/src/components/patrol/ApprovalSection.tsxnew file mode 100644index 0000000000..33645843cc--- /dev/null+++ b/frontend-modern/src/components/patrol/ApprovalSection.tsx@@ -0,0 +1,264 @@+/**+ * ApprovalSection+ *+ * Shows when investigation has a proposed fix.+ * States: Pending, Expired, Executed, Denied, Failed.+ */++import { Component, Show, createSignal, createResource, createMemo } from 'solid-js';+import { aiIntelligenceStore } from '@/stores/aiIntelligence';+import { notificationStore } from '@/stores/notifications';+import { AIAPI, type ApprovalRequest, type ApprovalExecutionResult } from '@/api/ai';+import { RemediationStatus } from './RemediationStatus';++interface ApprovalSectionProps {+ findingId: string;+ investigationOutcome?: string;+}++export const ApprovalSection: Component<ApprovalSectionProps> = (props) => {+ const [actionLoading, setActionLoading] = createSignal<string | null>(null);+ const [executionResult, setExecutionResult] = createSignal<ApprovalExecutionResult | null>(null);++ // Find the pending approval for this finding from the store+ const pendingApproval = createMemo(() => {+ return aiIntelligenceStore.pendingApprovals.find(+ (a: ApprovalRequest) => a.toolId === 'investigation_fix' && a.targetId === props.findingId && a.status === 'pending'+ ) ?? null;+ });++ // Load investigation details for expired approvals (to show proposed fix info)+ 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') {+ return null;+ }+ try {+ return await AIAPI.getInvestigation(findingId);+ } catch {+ return null;+ }+ }+ );++ // Determine state+ const isExpired = createMemo(() =>+ !pendingApproval() &&+ props.investigationOutcome === 'fix_queued' &&+ investigation()?.proposed_fix+ );++ const isExecuted = createMemo(() =>+ props.investigationOutcome === 'fix_executed' || executionResult()?.success+ );++ const isFailed = createMemo(() =>+ props.investigationOutcome === 'fix_failed' || (executionResult() && !executionResult()!.success)+ );++ // Show section only when there's something to display+ const shouldShow = createMemo(() =>+ pendingApproval() || isExpired() || isExecuted() || isFailed() || executionResult()+ );++ const riskBadgeColor = (level?: string) => {+ switch (level) {+ case 'high': case 'critical': return 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300';+ case 'medium': return 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300';+ default: return 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300';+ }+ };++ const handleApprove = async (approval: ApprovalRequest, e: Event) => {+ e.stopPropagation();+ setActionLoading(approval.id);+ try {+ const result = await aiIntelligenceStore.approveInvestigationFix(approval.id);+ if (result) {+ setExecutionResult(result);+ if (result.success) {+ notificationStore.success('Fix executed successfully');+ } else {+ notificationStore.error(result.error || 'Fix execution failed');+ }+ }+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to execute fix');+ } finally {+ setActionLoading(null);+ }+ };++ const handleDeny = async (approval: ApprovalRequest, e: Event) => {+ e.stopPropagation();+ setActionLoading(approval.id);+ try {+ await aiIntelligenceStore.denyInvestigationFix(approval.id);+ notificationStore.success('Fix denied');+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to deny fix');+ } finally {+ setActionLoading(null);+ }+ };++ const handleReapprove = async (e: Event) => {+ e.stopPropagation();+ setActionLoading('reapprove');+ try {+ const result = await AIAPI.reapproveInvestigationFix(props.findingId);+ const execResult = await aiIntelligenceStore.approveInvestigationFix(result.approval_id);+ if (execResult) {+ setExecutionResult(execResult);+ if (execResult.success) {+ notificationStore.success('Fix executed successfully');+ } else {+ notificationStore.error(execResult.error || 'Fix execution failed');+ }+ }+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to execute fix');+ } finally {+ setActionLoading(null);+ }+ };++ return (+ <Show when={shouldShow()}>+ <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">+ {/* Pending approval */}+ <Show when={pendingApproval() && !executionResult()}>+ {(() => {+ const approval = pendingApproval()!;+ return (+ <>+ <div class="flex items-center gap-2 mb-2">+ <svg class="w-4 h-4 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />+ </svg>+ <span class="text-sm font-medium text-gray-900 dark:text-gray-100">Fix Available</span>+ <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${riskBadgeColor(approval.riskLevel)}`}>+ {approval.riskLevel} risk+ </span>+ </div>+ <div class="space-y-2 text-sm">+ <div class="text-gray-600 dark:text-gray-400">{approval.context}</div>+ <div class="bg-gray-50 dark:bg-gray-800 rounded p-2 font-mono text-xs text-gray-700 dark:text-gray-300 break-all">+ {approval.command}+ </div>+ </div>+ <div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">+ <button+ type="button"+ onClick={(e) => handleApprove(approval, e)}+ disabled={actionLoading() === approval.id}+ class="flex-1 px-3 py-1.5 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-xs font-medium rounded flex items-center justify-center gap-1.5"+ >+ <Show when={actionLoading() === approval.id}>+ <span class="h-3 w-3 border-2 border-white border-t-transparent rounded-full animate-spin" />+ </Show>+ <Show when={actionLoading() !== approval.id}>+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />+ </svg>+ </Show>+ Approve & Execute+ </button>+ <button+ type="button"+ onClick={(e) => handleDeny(approval, e)}+ disabled={actionLoading() === approval.id}+ class="px-3 py-1.5 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 disabled:opacity-50 text-gray-600 dark:text-gray-400 text-xs font-medium rounded"+ >+ Deny+ </button>+ </div>+ </>+ );+ })()}+ </Show>++ {/* Expired approval - show re-approve */}+ <Show when={isExpired() && !executionResult()}>+ {(() => {+ const fix = investigation()!.proposed_fix!;+ return (+ <>+ <div class="flex items-center gap-2 mb-2">+ <svg class="w-4 h-4 text-amber-600 dark:text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />+ </svg>+ <span class="text-sm font-medium text-gray-900 dark:text-gray-100">Fix Pending Approval</span>+ <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${riskBadgeColor(fix.risk_level)}`}>+ {fix.risk_level || 'unknown'} risk+ </span>+ <span class="px-1.5 py-0.5 text-[10px] font-medium rounded bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300">+ approval expired+ </span>+ </div>+ <div class="space-y-2 text-sm">+ <div class="text-gray-600 dark:text-gray-400">{fix.description}</div>+ <Show when={fix.commands && fix.commands.length > 0}>+ <div class="bg-gray-50 dark:bg-gray-800 rounded p-2 font-mono text-xs text-gray-700 dark:text-gray-300 break-all">+ {fix.commands![0]}+ </div>+ </Show>+ <Show when={fix.target_host}>+ <div class="text-xs text-gray-500 dark:text-gray-400">Target: {fix.target_host}</div>+ </Show>+ </div>+ <div class="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">+ <button+ type="button"+ onClick={handleReapprove}+ disabled={actionLoading() === 'reapprove'}+ class="flex-1 px-3 py-1.5 bg-amber-600 hover:bg-amber-700 disabled:bg-amber-400 text-white text-xs font-medium rounded flex items-center justify-center gap-1.5"+ >+ <Show when={actionLoading() === 'reapprove'}>+ <span class="h-3 w-3 border-2 border-white border-t-transparent rounded-full animate-spin" />+ </Show>+ <Show when={actionLoading() !== 'reapprove'}>+ <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />+ </svg>+ </Show>+ Re-approve & Execute+ </button>+ </div>+ </>+ );+ })()}+ </Show>++ {/* Execution result */}+ <Show when={executionResult()}>+ <RemediationStatus result={executionResult()!} />+ </Show>++ {/* Executed (from backend state, no local result) */}+ <Show when={isExecuted() && !executionResult()}>+ <div class="flex items-center gap-2 text-green-600 dark:text-green-400">+ <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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />+ </svg>+ <span class="text-sm font-medium">Fix executed successfully</span>+ </div>+ </Show>++ {/* Failed (from backend state, no local result) */}+ <Show when={isFailed() && !executionResult()}>+ <div class="flex items-center gap-2 text-red-600 dark:text-red-400">+ <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="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />+ </svg>+ <span class="text-sm font-medium">Fix execution failed</span>+ </div>+ </Show>+ </div>+ </Show>+ );+};++export default ApprovalSection;diff --git a/frontend-modern/src/components/patrol/InvestigationMessages.tsx b/frontend-modern/src/components/patrol/InvestigationMessages.tsxnew file mode 100644index 0000000000..0c9cc61d8e--- /dev/null+++ b/frontend-modern/src/components/patrol/InvestigationMessages.tsx@@ -0,0 +1,118 @@+/**+ * InvestigationMessages+ *+ * Collapsible chat thread for an investigation.+ * Lazy-loads messages when rendered.+ */++import { Component, createResource, Show, For } from 'solid-js';+import { getInvestigationMessages, formatTimestamp, type ChatMessage } from '@/api/patrol';++interface InvestigationMessagesProps {+ findingId: string;+}++/** Returns true if a message has no displayable content */+function isEmptyMessage(msg: ChatMessage): boolean {+ return !msg.content && !msg.tool_calls?.length && !msg.tool_result;+}++export const InvestigationMessages: Component<InvestigationMessagesProps> = (props) => {+ const [messages] = createResource(+ () => props.findingId,+ async (findingId) => {+ try {+ const result = await getInvestigationMessages(findingId);+ return result.messages || [];+ } catch {+ return [];+ }+ }+ );++ return (+ <div class="mt-2">+ <Show when={messages.loading}>+ <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400 py-2">+ <span class="h-3 w-3 border-2 border-current border-t-transparent rounded-full animate-spin" />+ Loading messages...+ </div>+ </Show>++ <Show when={!messages.loading && (!messages() || messages()!.length === 0)}>+ <p class="text-xs text-gray-500 dark:text-gray-400 py-1">No investigation messages available.</p>+ </Show>++ <Show when={!messages.loading && messages() && messages()!.length > 0}>+ <div class="space-y-2 max-h-80 overflow-y-auto rounded border border-gray-200 dark:border-gray-700 p-2 bg-gray-50 dark:bg-gray-800/50">+ <For each={messages()}>+ {(msg: ChatMessage) => {+ if (isEmptyMessage(msg)) return null;++ return (+ <div class={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>+ <div class={`max-w-[85%] rounded-lg px-3 py-2 ${+ msg.role === 'user'+ ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-900 dark:text-blue-100'+ : msg.role === 'system'+ ? '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'+ }`}>+ {/* Text content */}+ <Show when={msg.content}>+ <div class="text-xs whitespace-pre-wrap break-words">{msg.content}</div>+ </Show>++ {/* Tool calls (assistant requesting tool use) */}+ <Show when={msg.tool_calls && msg.tool_calls.length > 0}>+ <div class="space-y-1">+ <For each={msg.tool_calls}>+ {(tc) => (+ <div class="text-xs rounded border border-indigo-200 dark:border-indigo-800 bg-indigo-50 dark:bg-indigo-900/30 px-2 py-1">+ <span class="font-semibold text-indigo-700 dark:text-indigo-300">{tc.name}</span>+ <Show when={tc.input && Object.keys(tc.input).length > 0}>+ <pre class="mt-1 text-[10px] text-gray-600 dark:text-gray-400 overflow-x-auto max-h-24 overflow-y-auto">+ {JSON.stringify(tc.input, null, 2)}+ </pre>+ </Show>+ </div>+ )}+ </For>+ </div>+ </Show>++ {/* Tool result (tool output returned to assistant) */}+ <Show when={msg.tool_result}>+ <div class={`text-xs rounded border px-2 py-1 ${+ msg.tool_result!.is_error+ ? 'border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/30'+ : 'border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-900/30'+ }`}>+ <span class={`font-semibold text-[10px] ${+ msg.tool_result!.is_error+ ? 'text-red-700 dark:text-red-300'+ : 'text-green-700 dark:text-green-300'+ }`}>+ {msg.tool_result!.is_error ? 'Error' : 'Result'}+ </span>+ <pre class="mt-1 text-[10px] text-gray-600 dark:text-gray-400 overflow-x-auto max-h-32 overflow-y-auto whitespace-pre-wrap break-words">+ {msg.tool_result!.content}+ </pre>+ </div>+ </Show>++ <div class="text-[10px] text-gray-500 dark:text-gray-500 mt-1">+ {formatTimestamp(msg.timestamp)}+ </div>+ </div>+ </div>+ );+ }}+ </For>+ </div>+ </Show>+ </div>+ );+};++export default InvestigationMessages;diff --git a/frontend-modern/src/components/patrol/InvestigationSection.tsx b/frontend-modern/src/components/patrol/InvestigationSection.tsxnew file mode 100644index 0000000000..64d028ed2a--- /dev/null+++ b/frontend-modern/src/components/patrol/InvestigationSection.tsx@@ -0,0 +1,206 @@+/**+ * InvestigationSection+ *+ * Inline investigation details within expanded finding.+ * Replaces the drawer. Shows status, summary, tools used, and+ * a collapsible investigation thread.+ */++import { Component, createSignal, createResource, createEffect, onCleanup, Show, For } from 'solid-js';+import {+ getInvestigation,+ reinvestigateFinding,+ investigationStatusLabels,+ investigationOutcomeLabels,+ formatTimestamp,+} from '@/api/patrol';+import { InvestigationMessages } from './InvestigationMessages';+import { notificationStore } from '@/stores/notifications';+import { aiIntelligenceStore } from '@/stores/aiIntelligence';+import RefreshCwIcon from 'lucide-solid/icons/refresh-cw';++interface InvestigationSectionProps {+ findingId: string;+ investigationStatus?: string;+ investigationOutcome?: string;+}++const statusColors: Record<string, string> = {+ pending: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',+ running: 'bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300',+ completed: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',+ failed: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',+ needs_attention: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',+};++const outcomeColors: Record<string, string> = {+ resolved: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',+ fix_queued: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',+ fix_executed: 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300',+ fix_failed: 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300',+ needs_attention: 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300',+ cannot_fix: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',+};++export const InvestigationSection: Component<InvestigationSectionProps> = (props) => {+ const [showThread, setShowThread] = createSignal(false);+ const [reinvestigating, setReinvestigating] = createSignal(false);+ const [cooldownUntil, setCooldownUntil] = createSignal(0);++ const [investigation, { refetch }] = createResource(+ () => props.findingId,+ async (findingId) => {+ try {+ return await getInvestigation(findingId);+ } catch {+ return null;+ }+ }+ );++ // Auto-poll while investigation is active+ createEffect(() => {+ const inv = investigation();+ const isActive = inv?.status === 'running' || inv?.status === 'pending'+ || props.investigationStatus === 'running';+ if (!isActive) return;++ const interval = setInterval(() => refetch(), 5000);+ onCleanup(() => clearInterval(interval));+ });++ const canReinvestigate = () => {+ if (Date.now() < cooldownUntil()) return false;+ 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';+ };++ const handleReinvestigate = async (e: Event) => {+ e.stopPropagation();+ setReinvestigating(true);+ try {+ await reinvestigateFinding(props.findingId);+ notificationStore.success('Re-investigation started');+ setCooldownUntil(Date.now() + 60000);+ refetch();+ aiIntelligenceStore.loadFindings();+ } catch (err) {+ notificationStore.error((err as Error).message || 'Failed to start re-investigation');+ } finally {+ setReinvestigating(false);+ }+ };++ return (+ <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">+ {/* Header */}+ <div class="flex items-center justify-between mb-2">+ <div class="flex items-center gap-2">+ <span class="text-sm font-medium text-gray-900 dark:text-gray-100">Investigation</span>+ <Show when={investigation()?.status}>+ <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${statusColors[investigation()!.status] || statusColors.pending}`}>+ {investigationStatusLabels[investigation()!.status] || investigation()!.status}+ </span>+ </Show>+ <Show when={investigation()?.outcome}>+ <span class={`px-1.5 py-0.5 text-[10px] font-medium rounded ${outcomeColors[investigation()!.outcome!] || outcomeColors.needs_attention}`}>+ {investigationOutcomeLabels[investigation()!.outcome!] || investigation()!.outcome}+ </span>+ </Show>+ </div>+ <Show when={canReinvestigate()}>+ <button+ type="button"+ onClick={handleReinvestigate}+ disabled={reinvestigating()}+ class="flex items-center gap-1 px-2 py-1 text-xs font-medium text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded transition-colors disabled:opacity-50"+ >+ <RefreshCwIcon class={`w-3 h-3 ${reinvestigating() ? 'animate-spin' : ''}`} />+ Re-investigate+ </button>+ </Show>+ <Show when={!canReinvestigate() && Date.now() < cooldownUntil()}>+ <span class="text-xs text-gray-500 dark:text-gray-400">Re-investigation started</span>+ </Show>+ </div>++ {/* Loading */}+ <Show when={investigation.loading}>+ <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400 py-2">+ <span class="h-3 w-3 border-2 border-current border-t-transparent rounded-full animate-spin" />+ Loading investigation...+ </div>+ </Show>++ {/* No investigation data */}+ <Show when={!investigation.loading && !investigation()}>+ <p class="text-xs text-gray-500 dark:text-gray-400 py-1">+ No investigation data available. Enable patrol autonomy to investigate findings.+ </p>+ </Show>++ {/* Investigation details */}+ <Show when={!investigation.loading && investigation()}>+ {(inv) => (+ <div class="space-y-2">+ {/* 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">+ {inv().summary}+ </div>+ </Show>++ {/* Tools used + turn count */}+ <div class="flex items-center gap-2 flex-wrap">+ <Show when={inv().tools_used && inv().tools_used!.length > 0}>+ <div class="flex items-center gap-1 flex-wrap">+ <For each={inv().tools_used}>+ {(tool) => (+ <span class="px-1.5 py-0.5 rounded bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300 text-[10px] font-medium">+ {tool}+ </span>+ )}+ </For>+ </div>+ </Show>+ <span class="text-[10px] text-gray-500 dark:text-gray-400">+ {inv().turn_count} turn{inv().turn_count === 1 ? '' : 's'}+ </span>+ <Show when={inv().started_at}>+ <span class="text-[10px] text-gray-500 dark:text-gray-400">+ started {formatTimestamp(inv().started_at)}+ </span>+ </Show>+ </div>++ {/* Show thread toggle */}+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); setShowThread(!showThread()); }}+ class="text-xs text-purple-600 dark:text-purple-400 hover:underline flex items-center gap-1"+ >+ {showThread() ? 'Hide investigation thread' : 'Show investigation thread'}+ <svg+ class={`w-3 h-3 transition-transform ${showThread() ? 'rotate-90' : ''}`}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />+ </svg>+ </button>++ {/* Investigation messages (lazy loaded) */}+ <Show when={showThread()}>+ <InvestigationMessages findingId={props.findingId} />+ </Show>+ </div>+ )}+ </Show>+ </div>+ );+};++export default InvestigationSection;diff --git a/frontend-modern/src/components/patrol/PatrolActivitySection.tsx b/frontend-modern/src/components/patrol/PatrolActivitySection.tsxdeleted file mode 100644index 9bf4c2bd16..0000000000--- a/frontend-modern/src/components/patrol/PatrolActivitySection.tsx+++ /dev/null@@ -1,368 +0,0 @@-/**- * PatrolActivitySection Component- *- * Displays patrol activity in a sysadmin-friendly format.- * Clear, scannable text stats instead of abstract visualizations.- */--import { createResource, createMemo, Show, Component, For } from 'solid-js';-import { getPatrolRunHistory, type PatrolRunRecord } from '@/api/patrol';-import CheckCircleIcon from 'lucide-solid/icons/check-circle';-import AlertCircleIcon from 'lucide-solid/icons/alert-circle';-import TrendingDownIcon from 'lucide-solid/icons/trending-down';-import TrendingUpIcon from 'lucide-solid/icons/trending-up';-import MinusIcon from 'lucide-solid/icons/minus';-import ClockIcon from 'lucide-solid/icons/clock';-import ActivityIcon from 'lucide-solid/icons/activity';-import WrenchIcon from 'lucide-solid/icons/wrench';--interface PatrolActivitySectionProps {- enabled?: boolean;- refreshTrigger?: number;-}--export const PatrolActivitySection: Component<PatrolActivitySectionProps> = (props) => {- const formatRelativeTime = (date: Date): string => {- const now = new Date();- const diffMs = now.getTime() - date.getTime();- const diffMins = Math.floor(diffMs / 60000);- const diffHours = Math.floor(diffMs / 3600000);- const diffDays = Math.floor(diffMs / 86400000);-- if (diffMins < 1) return 'just now';- if (diffMins < 60) return `${diffMins}m ago`;- if (diffHours < 24) return `${diffHours}h ago`;- return `${diffDays}d ago`;- };-- const formatTrigger = (reason?: string) => {- switch (reason) {- case 'scheduled':- return 'Scheduled';- case 'manual':- return 'Manual';- case 'startup':- return 'Startup';- case 'alert_fired':- return 'Alert fired';- case 'alert_cleared':- return 'Alert cleared';- case 'anomaly':- return 'Anomaly';- case 'user_action':- return 'User action';- case 'config_changed':- return 'Config change';- default:- return reason ? reason.replace(/_/g, ' ') : '';- }- };-- const formatScope = (run?: PatrolRunRecord) => {- if (!run) return '';- const idCount = run.scope_resource_ids?.length ?? 0;- if (idCount > 0) {- return `Scoped to ${idCount} resource${idCount === 1 ? '' : 's'}`;- }- const types = run.scope_resource_types ?? [];- if (types.length > 0) {- return `Scoped to ${types.join(', ')}`;- }- if (run.type === 'scoped') {- return 'Scoped';- }- return '';- };-- const formatContext = (run?: PatrolRunRecord) => {- if (!run?.scope_context) return '';- const trimmed = run.scope_context.trim();- if (!trimmed) return '';- return trimmed.length > 48 ? `${trimmed.slice(0, 45)}…` : trimmed;- };-- const formatDuration = (ms?: number) => {- if (!ms || ms <= 0) return '';- if (ms < 1000) return `${ms}ms`;- const seconds = Math.round(ms / 1000);- if (seconds < 60) return `${seconds}s`;- const minutes = Math.round(seconds / 60);- return `${minutes}m`;- };-- const shortId = (id?: string) => {- if (!id) return '';- return id.length > 8 ? id.slice(0, 8) : id;- };-- // Fetch patrol run history- const [runs] = createResource(- () => props.refreshTrigger ?? 0,- async (_trigger): Promise<PatrolRunRecord[]> => {- try {- return await getPatrolRunHistory(100); // Get more for weekly stats- } catch (err) {- console.error('Failed to fetch patrol run history:', err);- return [];- }- }- );-- // Calculate stats- const stats = createMemo(() => {- const allRuns = runs() || [];- if (allRuns.length === 0) {- return null;- }-- const now = new Date();- const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());- const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);- const twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000);-- // Today's runs- const todayRuns = allRuns.filter(r => new Date(r.started_at) >= todayStart);- const runsToday = todayRuns.length;- const newFindingsToday = todayRuns.reduce((sum, r) => sum + (r.new_findings || 0), 0);-- // This week's runs- const thisWeekRuns = allRuns.filter(r => new Date(r.started_at) >= weekAgo);- const lastWeekRuns = allRuns.filter(r => {- const date = new Date(r.started_at);- return date >= twoWeeksAgo && date < weekAgo;- });-- // Weekly trend calculation- const thisWeekFindings = thisWeekRuns.reduce((sum, r) => sum + (r.new_findings || 0) + (r.existing_findings || 0), 0);- const lastWeekFindings = lastWeekRuns.reduce((sum, r) => sum + (r.new_findings || 0) + (r.existing_findings || 0), 0);-- let weeklyTrend: 'improving' | 'stable' | 'worsening' = 'stable';- let weeklyTrendPercent = 0;-- if (lastWeekFindings > 0) {- const change = ((thisWeekFindings - lastWeekFindings) / lastWeekFindings) * 100;- weeklyTrendPercent = Math.abs(Math.round(change));- if (change < -10) {- weeklyTrend = 'improving';- } else if (change > 10) {- weeklyTrend = 'worsening';- }- } else if (thisWeekFindings > 0) {- weeklyTrend = 'worsening';- }-- // Auto-resolved this week- const autoResolvedThisWeek = thisWeekRuns.reduce((sum, r) => sum + (r.resolved_findings || 0), 0);- const autoFixedThisWeek = thisWeekRuns.reduce((sum, r) => sum + (r.auto_fix_count || 0), 0);-- // Last run info- const lastRun = allRuns[0];- const lastRunTime = lastRun ? new Date(lastRun.started_at) : null;- const lastRunStatus = lastRun?.status || 'unknown';- const lastRunHadErrors = lastRun?.error_count > 0;- const lastRunTrigger = lastRun?.trigger_reason;-- const lastRunMetaParts = [- formatTrigger(lastRunTrigger),- formatScope(lastRun),- formatContext(lastRun),- ].filter(Boolean);- const lastRunMeta = lastRunMetaParts.join(' • ');-- // Format relative time- return {- runsToday,- newFindingsToday,- lastRunTime: lastRunTime ? formatRelativeTime(lastRunTime) : null,- lastRunStatus,- lastRunHadErrors,- lastRunMeta,- weeklyTrend,- weeklyTrendPercent,- autoResolvedThisWeek,- autoFixedThisWeek,- totalRuns: allRuns.length,- };- });-- const recentRuns = createMemo(() => {- const allRuns = runs() || [];- return allRuns.slice(0, 5);- });-- const isHealthy = () => {- const s = stats();- return s && !s.lastRunHadErrors && s.lastRunStatus !== 'error';- };-- return (- <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4">- {/* Loading State */}- <Show when={runs.loading}>- <div class="animate-pulse flex items-center gap-4">- <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-32" />- <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-48" />- <div class="h-4 bg-gray-200 dark:bg-gray-700 rounded w-40" />- </div>- </Show>-- {/* Empty State */}- <Show when={!runs.loading && (!runs() || runs()!.length === 0)}>- <div class="text-sm text-gray-500 dark:text-gray-400">- No patrol runs yet. Patrol will start monitoring automatically.- </div>- </Show>-- {/* Stats Display */}- <Show when={!runs.loading && stats()}>- {(s) => (- <div class="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm">- {/* Status */}- <div class="flex items-center gap-2">- <Show- when={isHealthy()}- fallback={- <>- <AlertCircleIcon class="w-4 h-4 text-amber-500" />- <span class="text-amber-600 dark:text-amber-400 font-medium">Issues detected</span>- </>- }- >- <CheckCircleIcon class="w-4 h-4 text-green-500" />- <span class="text-green-600 dark:text-green-400 font-medium">Running normally</span>- </Show>- </div>-- <div class="hidden sm:block h-4 w-px bg-gray-200 dark:bg-gray-700" />-- {/* Last Run */}- <Show when={s().lastRunTime}>- <div class="flex items-center gap-1.5 text-gray-600 dark:text-gray-400">- <ClockIcon class="w-3.5 h-3.5" />- <span>- Last run: {s().lastRunTime}- <Show when={s().lastRunMeta}>- <span class="text-gray-500 dark:text-gray-500"> • {s().lastRunMeta}</span>- </Show>- </span>- </div>- </Show>-- <div class="hidden sm:block h-4 w-px bg-gray-200 dark:bg-gray-700" />-- {/* Today's Activity */}- <div class="flex items-center gap-1.5 text-gray-600 dark:text-gray-400">- <ActivityIcon class="w-3.5 h-3.5" />- <span>- Today: {s().runsToday} {s().runsToday === 1 ? 'run' : 'runs'}- <Show when={s().newFindingsToday > 0}>- <span class="text-amber-600 dark:text-amber-400">- , {s().newFindingsToday} new {s().newFindingsToday === 1 ? 'finding' : 'findings'}- </span>- </Show>- </span>- </div>-- <div class="hidden lg:block h-4 w-px bg-gray-200 dark:bg-gray-700" />-- {/* Weekly Trend */}- <div class="hidden lg:flex items-center gap-1.5">- <Show when={s().weeklyTrend === 'improving'}>- <TrendingDownIcon class="w-3.5 h-3.5 text-green-500" />- <span class="text-green-600 dark:text-green-400">- {s().weeklyTrendPercent}% fewer findings this week- </span>- </Show>- <Show when={s().weeklyTrend === 'worsening'}>- <TrendingUpIcon class="w-3.5 h-3.5 text-red-500" />- <span class="text-red-600 dark:text-red-400">- {s().weeklyTrendPercent}% more findings this week- </span>- </Show>- <Show when={s().weeklyTrend === 'stable'}>- <MinusIcon class="w-3.5 h-3.5 text-gray-400" />- <span class="text-gray-500 dark:text-gray-400">- Findings stable this week- </span>- </Show>- </div>-- {/* Auto-resolved */}- <Show when={s().autoResolvedThisWeek > 0 || s().autoFixedThisWeek > 0}>- <div class="hidden lg:block h-4 w-px bg-gray-200 dark:bg-gray-700" />- <div class="hidden lg:flex items-center gap-1.5 text-green-600 dark:text-green-400">- <WrenchIcon class="w-3.5 h-3.5" />- <span>- <Show when={s().autoResolvedThisWeek > 0}>- {s().autoResolvedThisWeek} resolved- </Show>- <Show when={s().autoResolvedThisWeek > 0 && s().autoFixedThisWeek > 0}>, </Show>- <Show when={s().autoFixedThisWeek > 0}>- {s().autoFixedThisWeek} auto-fixed- </Show>- {' '}this week- </span>- </div>- </Show>- </div>- )}- </Show>-- <Show when={!runs.loading && recentRuns().length > 0}>- <div class="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">- <div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">Recent runs</div>- <div class="space-y-1">- <For each={recentRuns()}>- {(run) => {- const runMeta = [- formatTrigger(run.trigger_reason),- formatScope(run),- formatContext(run),- ].filter(Boolean).join(' • ');- const duration = formatDuration(run.duration_ms);- return (- <div class="flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">- <span class="text-gray-700 dark:text-gray-300">- {formatRelativeTime(new Date(run.started_at))}- </span>- <span class={`px-1.5 py-0.5 rounded ${- run.status === 'critical'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : run.status === 'issues_found'- ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'- : run.status === 'error'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'- }`}>- {run.status.replace(/_/g, ' ')}- </span>- <Show when={runMeta}>- <span>{runMeta}</span>- </Show>- <Show when={duration}>- <span>• {duration}</span>- </Show>- <Show when={run.resources_checked}>- <span>• {run.resources_checked} resources</span>- </Show>- <Show when={run.error_count && run.error_count > 0}>- <span class="text-red-600 dark:text-red-400">• {run.error_count} error{run.error_count === 1 ? '' : 's'}</span>- </Show>- <Show when={run.alert_id}>- <span class="text-amber-600 dark:text-amber-400">• Alert {shortId(run.alert_id)}</span>- </Show>- <Show when={run.finding_id}>- <span class="text-blue-600 dark:text-blue-400">• Finding {shortId(run.finding_id)}</span>- </Show>- </div>- );- }}- </For>- </div>- </div>- </Show>- </div>- );-};--export default PatrolActivitySection;diff --git a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx b/frontend-modern/src/components/patrol/PatrolStatusBar.tsxnew file mode 100644index 0000000000..93cd81f730--- /dev/null+++ b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx@@ -0,0 +1,129 @@+/**+ * PatrolStatusBar+ *+ * One-line status bar replacing the Activity tab.+ * Shows: Running status, last run time + trigger, today's run count + new findings.+ */++import { Component, createResource, createMemo, Show } from 'solid-js';+import { getPatrolRunHistory, type PatrolRunRecord } from '@/api/patrol';+import CheckCircleIcon from 'lucide-solid/icons/check-circle';+import AlertCircleIcon from 'lucide-solid/icons/alert-circle';++interface PatrolStatusBarProps {+ enabled?: boolean;+ refreshTrigger?: number;+}++export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {+ const formatRelativeTime = (date: Date): string => {+ const now = new Date();+ const diffMs = now.getTime() - date.getTime();+ const diffMins = Math.floor(diffMs / 60000);+ const diffHours = Math.floor(diffMs / 3600000);+ const diffDays = Math.floor(diffMs / 86400000);++ if (diffMins < 1) return 'just now';+ if (diffMins < 60) return `${diffMins}m ago`;+ if (diffHours < 24) return `${diffHours}h ago`;+ return `${diffDays}d ago`;+ };++ const formatTrigger = (reason?: string) => {+ switch (reason) {+ case 'scheduled': return 'Scheduled';+ case 'manual': return 'Manual';+ case 'startup': return 'Startup';+ case 'alert_fired': return 'Alert fired';+ case 'alert_cleared': return 'Alert cleared';+ case 'anomaly': return 'Anomaly';+ case 'user_action': return 'User action';+ case 'config_changed': return 'Config change';+ default: return reason ? reason.replace(/_/g, ' ') : '';+ }+ };++ const [runs] = createResource(+ () => props.refreshTrigger ?? 0,+ async (): Promise<PatrolRunRecord[]> => {+ try {+ return await getPatrolRunHistory(100);+ } catch {+ return [];+ }+ }+ );++ const stats = createMemo(() => {+ const allRuns = runs() || [];+ if (allRuns.length === 0) return null;++ const now = new Date();+ const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());+ const todayRuns = allRuns.filter(r => new Date(r.started_at) >= todayStart);++ const lastRun = allRuns[0];+ const lastRunTime = lastRun ? new Date(lastRun.started_at) : null;+ const lastRunHadErrors = lastRun?.error_count > 0;++ return {+ runsToday: todayRuns.length,+ newFindingsToday: todayRuns.reduce((sum, r) => sum + (r.new_findings || 0), 0),+ lastRunTime: lastRunTime ? formatRelativeTime(lastRunTime) : null,+ lastRunTrigger: formatTrigger(lastRun?.trigger_reason),+ isHealthy: !lastRunHadErrors && lastRun?.status !== 'error',+ };+ });++ 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">+ <div class="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">+ {/* Status */}+ <div class="flex items-center gap-1.5">+ <Show+ when={s().isHealthy}+ fallback={+ <>+ <AlertCircleIcon class="w-3.5 h-3.5 text-amber-500" />+ <span class="text-amber-600 dark:text-amber-400 font-medium text-xs">Issues detected</span>+ </>+ }+ >+ <CheckCircleIcon class="w-3.5 h-3.5 text-green-500" />+ <span class="text-green-600 dark:text-green-400 font-medium text-xs">Running normally</span>+ </Show>+ </div>++ <span class="hidden sm:inline text-gray-300 dark:text-gray-600">|</span>++ {/* Last run */}+ <Show when={s().lastRunTime}>+ <span class="text-xs text-gray-600 dark:text-gray-400">+ Last run: {s().lastRunTime}+ <Show when={s().lastRunTrigger}>+ <span class="text-gray-500 dark:text-gray-500"> ({s().lastRunTrigger})</span>+ </Show>+ </span>+ </Show>++ <span class="hidden sm:inline text-gray-300 dark:text-gray-600">|</span>++ {/* Today */}+ <span class="text-xs text-gray-600 dark:text-gray-400">+ Today: {s().runsToday} run{s().runsToday === 1 ? '' : 's'}+ <Show when={s().newFindingsToday > 0}>+ <span class="text-amber-600 dark:text-amber-400">+ , {s().newFindingsToday} new finding{s().newFindingsToday === 1 ? '' : 's'}+ </span>+ </Show>+ </span>+ </div>+ </div>+ )}+ </Show>+ );+};++export default PatrolStatusBar;diff --git a/frontend-modern/src/components/patrol/RemediationStatus.tsx b/frontend-modern/src/components/patrol/RemediationStatus.tsxnew file mode 100644index 0000000000..328257ab56--- /dev/null+++ b/frontend-modern/src/components/patrol/RemediationStatus.tsx@@ -0,0 +1,63 @@+/**+ * RemediationStatus+ *+ * Post-execution display: shows command output, exit code, and rollback button.+ */++import { Component, Show, createSignal } from 'solid-js';+import type { ApprovalExecutionResult } from '@/api/ai';++interface RemediationStatusProps {+ result: ApprovalExecutionResult;+}++export const RemediationStatus: Component<RemediationStatusProps> = (props) => {+ const [showOutput, setShowOutput] = createSignal(false);++ return (+ <div class={`mt-2 p-2 rounded text-xs ${+ props.result.success+ ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'+ : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'+ }`}>+ <div class="flex items-center gap-2">+ <Show when={props.result.success}>+ <svg class="w-4 h-4 text-green-600 dark:text-green-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />+ </svg>+ <span class="font-medium text-green-700 dark:text-green-300">Fix executed successfully</span>+ </Show>+ <Show when={!props.result.success}>+ <svg class="w-4 h-4 text-red-600 dark:text-red-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />+ </svg>+ <span class="font-medium text-red-700 dark:text-red-300">Fix failed</span>+ </Show>+ <Show when={props.result.exit_code !== undefined}>+ <span class="text-gray-500 dark:text-gray-400">exit code: {props.result.exit_code}</span>+ </Show>+ </div>++ <Show when={props.result.error}>+ <div class="text-red-600 dark:text-red-400 mt-1">{props.result.error}</div>+ </Show>++ <Show when={props.result.output}>+ <button+ type="button"+ onClick={(e) => { e.stopPropagation(); setShowOutput(!showOutput()); }}+ class="text-[10px] text-gray-500 dark:text-gray-400 hover:underline mt-1"+ >+ {showOutput() ? 'Hide output' : 'Show output'}+ </button>+ <Show when={showOutput()}>+ <div class="bg-white dark:bg-gray-900 rounded p-2 font-mono mt-1 max-h-32 overflow-auto whitespace-pre-wrap text-[11px] text-gray-700 dark:text-gray-300">+ {props.result.output}+ </div>+ </Show>+ </Show>+ </div>+ );+};++export default RemediationStatus;diff --git a/frontend-modern/src/components/patrol/RunToolCallTrace.tsx b/frontend-modern/src/components/patrol/RunToolCallTrace.tsxnew file mode 100644index 0000000000..8440c612ff--- /dev/null+++ b/frontend-modern/src/components/patrol/RunToolCallTrace.tsx@@ -0,0 +1,134 @@+/**+ * RunToolCallTrace+ *+ * Collapsible tool call list for a patrol run.+ * Lazy-loads tool call details when expanded.+ */++import { Component, createSignal, createResource, Show, For } from 'solid-js';+import { getPatrolRunHistoryWithToolCalls, type ToolCallRecord } from '@/api/patrol';++interface RunToolCallTraceProps {+ runId: string;+ toolCallCount: number;+}++export const RunToolCallTrace: Component<RunToolCallTraceProps> = (props) => {+ const [expanded, setExpanded] = createSignal(false);+ const [expandedCall, setExpandedCall] = createSignal<string | null>(null);++ // Lazy-load tool calls when expanded+ 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);+ return run?.tool_calls || [];+ } catch {+ return [];+ }+ }+ );++ const truncate = (text: string, max: number = 200) =>+ text.length <= max ? text : text.slice(0, max - 1) + '...';++ return (+ <Show when={props.toolCallCount > 0}>+ <div class="mt-3 pt-3 border-t border-gray-200 dark:border-gray-700">+ <button+ type="button"+ onClick={() => setExpanded(!expanded())}+ class="flex items-center gap-2 text-xs font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100"+ >+ <svg+ class={`w-3 h-3 transition-transform ${expanded() ? 'rotate-90' : ''}`}+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ >+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />+ </svg>+ Tool calls ({props.toolCallCount})+ </button>++ <Show when={expanded()}>+ <Show when={toolCalls.loading}>+ <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400 py-2 mt-2">+ <span class="h-3 w-3 border-2 border-current border-t-transparent rounded-full animate-spin" />+ Loading tool calls...+ </div>+ </Show>++ <Show when={!toolCalls.loading && toolCalls() && toolCalls()!.length > 0}>+ <div class="mt-2 space-y-1">+ <For each={toolCalls()}>+ {(call: ToolCallRecord, index) => (+ <div class="border border-gray-200 dark:border-gray-700 rounded">+ <button+ type="button"+ onClick={() => setExpandedCall(expandedCall() === call.id ? null : call.id)}+ class="w-full flex items-center justify-between gap-2 px-2 py-1.5 text-xs hover:bg-gray-50 dark:hover:bg-gray-800/50"+ >+ <div class="flex items-center gap-2 min-w-0">+ <span class="text-gray-400 dark:text-gray-500 font-mono w-5 text-right flex-shrink-0">+ {index() + 1}.+ </span>+ <span class="font-medium text-gray-800 dark:text-gray-200 font-mono truncate">+ {call.tool_name}+ </span>+ </div>+ <div class="flex items-center gap-2 flex-shrink-0">+ <span class={`px-1.5 py-0.5 rounded text-[10px] font-medium ${+ call.success+ ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'+ : 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'+ }`}>+ {call.success ? 'success' : 'failed'}+ </span>+ <span class="text-gray-400 dark:text-gray-500 font-mono">+ {call.duration_ms}ms+ </span>+ </div>+ </button>++ <Show when={expandedCall() === call.id}>+ <div class="border-t border-gray-200 dark:border-gray-700 p-2 space-y-2">+ <Show when={call.input}>+ <div>+ <div class="text-[10px] font-medium text-gray-500 dark:text-gray-400 mb-1">Input</div>+ <pre class="text-[11px] font-mono bg-gray-50 dark:bg-gray-900 rounded p-2 max-h-32 overflow-auto whitespace-pre-wrap text-gray-700 dark:text-gray-300">+ {truncate(call.input, 500)}+ </pre>+ </div>+ </Show>+ <Show when={call.output}>+ <div>+ <div class="text-[10px] font-medium text-gray-500 dark:text-gray-400 mb-1">Output</div>+ <pre class="text-[11px] font-mono bg-gray-50 dark:bg-gray-900 rounded p-2 max-h-32 overflow-auto whitespace-pre-wrap text-gray-700 dark:text-gray-300">+ {truncate(call.output, 500)}+ </pre>+ </div>+ </Show>+ </div>+ </Show>+ </div>+ )}+ </For>+ </div>+ </Show>++ <Show when={!toolCalls.loading && (!toolCalls() || toolCalls()!.length === 0)}>+ <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">+ Tool call details not available for this run.+ </p>+ </Show>+ </Show>+ </div>+ </Show>+ );+};++export default RunToolCallTrace;diff --git a/frontend-modern/src/components/patrol/index.ts b/frontend-modern/src/components/patrol/index.tsindex 6b0c4977ba..c859b06d8f 100644--- a/frontend-modern/src/components/patrol/index.ts+++ b/frontend-modern/src/components/patrol/index.ts@@ -1 +1,7 @@-export { PatrolActivitySection } from './PatrolActivitySection';+export { ApprovalBanner } from './ApprovalBanner';+export { ApprovalSection } from './ApprovalSection';+export { InvestigationSection } from './InvestigationSection';+export { InvestigationMessages } from './InvestigationMessages';+export { RemediationStatus } from './RemediationStatus';+export { RunToolCallTrace } from './RunToolCallTrace';+export { PatrolStatusBar } from './PatrolStatusBar';diff --git a/frontend-modern/src/components/shared/Toggle.tsx b/frontend-modern/src/components/shared/Toggle.tsxindex a704293937..6b21c6426c 100644--- a/frontend-modern/src/components/shared/Toggle.tsx+++ b/frontend-modern/src/components/shared/Toggle.tsx@@ -94,7 +94,7 @@ interface LabeledToggleProps extends BaseToggleProps {export function Toggle(props: LabeledToggleProps) {const size = props.size ?? 'md';return (- <label class={`flex items-center gap-3 ${props.containerClass ?? ''}`.trim()}>+ <div class={`flex items-center gap-3 ${props.containerClass ?? ''}`.trim()}><TogglePrimitive {...props} size={size} />{(props.label || props.description) && (<span class="flex flex-col text-sm text-gray-700 dark:text-gray-300">@@ -104,7 +104,7 @@ export function Toggle(props: LabeledToggleProps) {)}</span>)}- </label>+ </div>);}diff --git a/frontend-modern/src/hooks/usePatrolStream.ts b/frontend-modern/src/hooks/usePatrolStream.tsnew file mode 100644index 0000000000..0d0b14dd16--- /dev/null+++ b/frontend-modern/src/hooks/usePatrolStream.ts@@ -0,0 +1,137 @@+/**+ * SolidJS hook for consuming live patrol SSE events.+ *+ * 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.+ */++import { createSignal, createEffect, onCleanup, type Accessor } from 'solid-js';+import type { PatrolStreamEvent } from '@/api/patrol';+import { logger } from '@/utils/logger';++export interface UsePatrolStreamOptions {+ /** Reactive boolean – stream is only open while this returns true. */+ running: Accessor<boolean>;+ /** Called when a 'complete' event is received. */+ onComplete?: () => void;+ /** Called when an 'error' event is received or the SSE connection fails. */+ onError?: () => void;+}++export interface PatrolStreamState {+ /** Current phase text (e.g. "Analyzing resources…"). */+ phase: Accessor<string>;+ /** Name of the tool currently executing, or empty. */+ currentTool: Accessor<string>;+ /** Cumulative token count reported by the backend. */+ tokens: Accessor<number>;+ /** True while the EventSource is connected. */+ isStreaming: Accessor<boolean>;+ /** Error message from the last error event, or empty. */+ errorMessage: Accessor<string>;+}++export function usePatrolStream(opts: UsePatrolStreamOptions): PatrolStreamState {+ const [phase, setPhase] = createSignal('');+ const [currentTool, setCurrentTool] = createSignal('');+ const [tokens, setTokens] = createSignal(0);+ const [isStreaming, setIsStreaming] = createSignal(false);+ const [errorMessage, setErrorMessage] = createSignal('');++ let es: EventSource | undefined;++ function close() {+ if (es) {+ es.close();+ es = undefined;+ }+ setIsStreaming(false);+ }++ function open() {+ close();+ try {+ es = new EventSource('/api/ai/patrol/stream');++ es.onopen = () => {+ logger.info('[PatrolStream] SSE connected');+ setIsStreaming(true);+ };++ es.onmessage = (msg) => {+ try {+ const event: PatrolStreamEvent = JSON.parse(msg.data);++ switch (event.type) {+ case 'start':+ setPhase('Starting patrol…');+ setCurrentTool('');+ setTokens(0);+ setErrorMessage('');+ break;+ case 'phase':+ if (event.phase) setPhase(event.phase);+ break;+ case 'content':+ // Content events carry incremental text; phase stays as-is+ break;+ case 'tool_start':+ if (event.tool_name) setCurrentTool(event.tool_name);+ break;+ case 'tool_end':+ setCurrentTool('');+ break;+ case 'complete':+ setPhase('');+ setCurrentTool('');+ setErrorMessage('');+ if (event.tokens) setTokens(event.tokens);+ close();+ opts.onComplete?.();+ break;+ case 'error':+ setPhase('');+ setCurrentTool('');+ setErrorMessage(event.content || 'Patrol encountered an error');+ close();+ opts.onError?.();+ break;+ }++ if (event.tokens && event.type !== 'complete') {+ setTokens(event.tokens);+ }+ } catch {+ // Ignore malformed events+ }+ };++ es.onerror = () => {+ // Silently close on error — polling continues as fallback+ logger.warn('[PatrolStream] SSE error, closing');+ close();+ opts.onError?.();+ };+ } catch {+ // EventSource constructor can throw in some environments+ close();+ }+ }++ // Reactively open/close based on running state+ createEffect(() => {+ if (opts.running()) {+ open();+ } else {+ close();+ // Reset signals when patrol stops+ setPhase('');+ setCurrentTool('');+ setTokens(0);+ }+ });++ onCleanup(() => close());++ return { phase, currentTool, tokens, isStreaming, errorMessage };+}diff --git a/frontend-modern/src/pages/AIIntelligence.tsx b/frontend-modern/src/pages/AIIntelligence.tsxindex 0ed640a0f2..9a3444b918 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 { renderMarkdown } from '@/components/AI/aiChatUtils';interface ModelInfo {id: string;@@ -31,6 +32,9 @@ interface AISettings {patrol_interval_minutes?: number;patrol_enabled?: boolean;model?: string;+ alert_triggered_analysis?: boolean;+ patrol_auto_fix?: boolean;+ auto_fix_model?: string;}// Local patrol enabled state (synced with AI settings)@@ -46,9 +50,23 @@ import FlaskConicalIcon from 'lucide-solid/icons/flask-conical';import SparklesIcon from 'lucide-solid/icons/sparkles';import CheckCircleIcon from 'lucide-solid/icons/check-circle';import SettingsIcon from 'lucide-solid/icons/settings';+import ServerIcon from 'lucide-solid/icons/server';+import MonitorIcon from 'lucide-solid/icons/monitor';+import BoxIcon from 'lucide-solid/icons/box';+import HardDriveIcon from 'lucide-solid/icons/hard-drive';+import GlobeIcon from 'lucide-solid/icons/globe';+import DatabaseIcon from 'lucide-solid/icons/database';+import SearchIcon from 'lucide-solid/icons/search';+import WrenchIcon from 'lucide-solid/icons/wrench';+import ClockIcon from 'lucide-solid/icons/clock';+import ZapIcon from 'lucide-solid/icons/zap';+import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';+import FilterXIcon from 'lucide-solid/icons/filter-x';import { PulsePatrolLogo } from '@/components/Brand/PulsePatrolLogo';import { TogglePrimitive, Toggle } from '@/components/shared/Toggle';-import { PatrolActivitySection } from '@/components/patrol';+import { ApprovalBanner, PatrolStatusBar, RunToolCallTrace } from '@/components/patrol';+import { usePatrolStream } from '@/hooks/usePatrolStream';+import { hasFeature } from '@/stores/license';const INFO_BANNER_DISMISSED_KEY = 'patrol-info-banner-dismissed';@@ -65,7 +83,7 @@ const SCHEDULE_PRESETS = [{ value: 1440, label: '24 hours' },];-type PatrolTab = 'findings' | 'activity' | 'history';+type PatrolTab = 'findings' | 'history';export function AIIntelligence() {const [activeTab, setActiveTab] = createSignal<PatrolTab>('findings');@@ -78,6 +96,22 @@ export function AIIntelligence() {// Trigger to refresh patrol activity visualizationsconst [activityRefreshTrigger, setActivityRefreshTrigger] = createSignal(0);+ // Optimistic running state — set immediately on "Run Patrol" click to avoid race with backend+ const [manualRunRequested, setManualRunRequested] = createSignal(false);++ // Live patrol streaming+ const patrolStream = usePatrolStream({+ running: () => (patrolStatus()?.running ?? false) || manualRunRequested(),+ onComplete: () => {+ setManualRunRequested(false);+ loadAllData();+ },+ onError: () => {+ setManualRunRequested(false);+ loadAllData();+ },+ });+// Advanced autonomy settingsconst [investigationBudget, setInvestigationBudget] = createSignal(15);const [investigationTimeout, setInvestigationTimeout] = createSignal(300);@@ -85,6 +119,7 @@ export function AIIntelligence() {const [isSavingAdvanced, setIsSavingAdvanced] = createSignal(false);const [fullModeUnlocked, setFullModeUnlocked] = createSignal(false);let advancedSettingsRef: HTMLDivElement | undefined;+ let patrolModelSelectRef: HTMLSelectElement | undefined;// Close popover when clicking outsideconst handleClickOutside = (e: MouseEvent) => {@@ -114,8 +149,25 @@ export function AIIntelligence() {const [isUpdatingSettings, setIsUpdatingSettings] = createSignal(false);const [isTogglingPatrol, setIsTogglingPatrol] = createSignal(false);const [isTriggeringPatrol, setIsTriggeringPatrol] = createSignal(false);+ const [alertTriggeredAnalysis, setAlertTriggeredAnalysis] = createSignal<boolean>(true);+ const [patrolAutoFix, setPatrolAutoFix] = createSignal<boolean>(false);+ const [autoFixModel, setAutoFixModel] = createSignal<string>('');++ // Re-apply patrol model select value when models load after settings+ // (select value is ignored by the browser if no matching option exists yet)+ createEffect(() => {+ const model = patrolModel();+ const models = availableModels();+ if (patrolModelSelectRef && models.length > 0 && model) {+ patrolModelSelectRef.value = 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(false);+ 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()));@@ -143,7 +195,7 @@ export function AIIntelligence() {async function loadModels() {try {const data = await apiFetchJSON<{ models: ModelInfo[] }>('/api/ai/models');- setAvailableModels(data.models || []);+ setAvailableModels(data?.models || []);} catch (err) {console.error('Failed to load models:', err);}@@ -157,6 +209,9 @@ export function AIIntelligence() {setDefaultModel(data.model || '');setPatrolInterval(data.patrol_interval_minutes ?? 360);setPatrolEnabledLocal(data.patrol_enabled ?? true);+ setAlertTriggeredAnalysis(data.alert_triggered_analysis !== false);+ setPatrolAutoFix(data.patrol_auto_fix ?? false);+ setAutoFixModel(data.auto_fix_model || '');} catch (err) {console.error('Failed to load AI settings:', err);}@@ -168,7 +223,7 @@ export function AIIntelligence() {setIsTogglingPatrol(true);const newValue = !patrolEnabledLocal();try {- const data = await apiFetchJSON<AISettings>('/api/settings/ai', {+ const data = await apiFetchJSON<AISettings>('/api/settings/ai/update', {method: 'PUT',body: JSON.stringify({ patrol_enabled: newValue }),});@@ -191,13 +246,25 @@ export function AIIntelligence() {}async function handleRunPatrol() {- if (isTriggeringPatrol() || !canTriggerPatrol()) return;+ if (isTriggeringPatrol() || !canTriggerPatrol() || manualRunRequested() || patrolStream.isStreaming()) return;setIsTriggeringPatrol(true);+ setManualRunRequested(true);++ // Safety timeout: if SSE never connects within 15s, clear optimistic state+ const safetyTimer = setTimeout(() => {+ if (manualRunRequested() && !patrolStream.isStreaming()) {+ setManualRunRequested(false);+ loadAllData();+ }+ }, 15000);+try {await triggerPatrolRun();await loadAllData();} catch (err) {console.error('Failed to trigger patrol run:', err);+ setManualRunRequested(false);+ clearTimeout(safetyTimer);} finally {setIsTriggeringPatrol(false);}@@ -208,7 +275,7 @@ export function AIIntelligence() {if (isUpdatingSettings()) return;setIsUpdatingSettings(true);try {- await apiFetchJSON('/api/settings/ai', {+ await apiFetchJSON('/api/settings/ai/update', {method: 'PUT',body: JSON.stringify({ patrol_model: modelId }),});@@ -225,7 +292,7 @@ export function AIIntelligence() {if (isUpdatingSettings()) return;setIsUpdatingSettings(true);try {- await apiFetchJSON('/api/settings/ai', {+ await apiFetchJSON('/api/settings/ai/update', {method: 'PUT',body: JSON.stringify({ patrol_interval_minutes: minutes }),});@@ -238,6 +305,70 @@ export function AIIntelligence() {}}+ // Toggle alert-triggered analysis+ async function handleAlertTriggeredAnalysisChange(enabled: boolean) {+ if (isUpdatingSettings()) return;+ setIsUpdatingSettings(true);+ const previous = alertTriggeredAnalysis();+ setAlertTriggeredAnalysis(enabled);+ try {+ await apiFetchJSON('/api/settings/ai/update', {+ method: 'PUT',+ body: JSON.stringify({ alert_triggered_analysis: enabled }),+ });+ } catch (err) {+ console.error('Failed to update alert-triggered analysis:', err);+ setAlertTriggeredAnalysis(previous);+ } finally {+ setIsUpdatingSettings(false);+ }+ }++ // Toggle auto-fix mode+ async function handleAutoFixChange(enabled: boolean) {+ if (isUpdatingSettings()) return;+ setIsUpdatingSettings(true);+ const previous = patrolAutoFix();+ setPatrolAutoFix(enabled);+ try {+ await apiFetchJSON('/api/settings/ai/update', {+ method: 'PUT',+ body: JSON.stringify({ patrol_auto_fix: enabled }),+ });+ } catch (err) {+ console.error('Failed to update auto-fix mode:', err);+ setPatrolAutoFix(previous);+ } finally {+ setIsUpdatingSettings(false);+ }+ }++ // Update auto-fix model+ async function handleAutoFixModelChange(modelId: string) {+ if (isUpdatingSettings()) return;+ setIsUpdatingSettings(true);+ try {+ await apiFetchJSON('/api/settings/ai/update', {+ method: 'PUT',+ body: JSON.stringify({ auto_fix_model: modelId }),+ });+ setAutoFixModel(modelId);+ } catch (err) {+ console.error('Failed to update auto-fix model:', err);+ } finally {+ setIsUpdatingSettings(false);+ }+ }++ // Strip leaked provider tool-call markup (e.g. DeepSeek DSML) from AI analysis text+ function sanitizeAnalysis(text: string | undefined): string {+ if (!text) return '';+ // Remove DeepSeek DSML blocks: <|DSML|...>...</|DSML|...>+ return text.replace(/<|DSML|[^>]*>[\s\S]*?<\/|DSML|[^>]*>/g, '')+ .replace(/<|DSML|[^>]*>/g, '')+ .trim();+ }+// Group models by providerfunction groupModelsByProvider(models: ModelInfo[]) {const groups = new Map<string, ModelInfo[]>();@@ -319,11 +450,6 @@ export function AIIntelligence() {return `${minutes}m`;}- function truncateText(text?: string, maxLen: number = 500): string {- if (!text) return '';- if (text.length <= maxLen) return text;- return `${text.slice(0, maxLen - 1)}…`;- }// Fetch patrol status to check licenseconst [patrolStatus, { refetch: refetchPatrolStatus }] = createResource<PatrolStatus | null>(async () => {@@ -351,8 +477,6 @@ export function AIIntelligence() {const blockedReason = createMemo(() => patrolStatus()?.blocked_reason?.trim() ?? '');const blockedAt = createMemo(() => patrolStatus()?.blocked_at);const showBlockedBanner = createMemo(() => patrolEnabledLocal() && !!blockedReason());- const errorCount = createMemo(() => patrolStatus()?.error_count ?? 0);- const showErrorBanner = createMemo(() => !showBlockedBanner() && errorCount() > 0);const canTriggerPatrol = createMemo(() => patrolEnabledLocal() && !showBlockedBanner());const triggerPatrolDisabledReason = createMemo(() => {if (!patrolEnabledLocal()) return 'Patrol is disabled';@@ -366,9 +490,42 @@ export function AIIntelligence() {return run.finding_ids;});- createEffect(() => {- selectedRun();- setShowRunAnalysis(false);+ // Live in-progress run entry for history list+ const liveRunRecord = createMemo<PatrolRunRecord | null>(() => {+ if (!patrolStream.isStreaming() && !manualRunRequested()) return null;+ return {+ id: '__live__',+ started_at: new Date().toISOString(),+ completed_at: '',+ duration_ms: 0,+ type: 'full',+ trigger_reason: 'manual',+ resources_checked: 0,+ nodes_checked: 0,+ guests_checked: 0,+ docker_checked: 0,+ storage_checked: 0,+ hosts_checked: 0,+ pbs_checked: 0,+ kubernetes_checked: 0,+ new_findings: 0,+ existing_findings: 0,+ rejected_findings: 0,+ resolved_findings: 0,+ auto_fix_count: 0,+ findings_summary: '',+ finding_ids: [],+ error_count: 0,+ status: 'healthy',+ tool_call_count: 0,+ };+ });++ // Combined run history: live entry (if any) prepended to real history+ const displayRunHistory = createMemo(() => {+ const live = liveRunRecord();+ const history = patrolRunHistory() || [];+ return live ? [live, ...history] : history;});// Load autonomy settings@@ -441,15 +598,25 @@ export function AIIntelligence() {});onCleanup(() => clearInterval(refreshInterval));+ // Approval polling: 10s interval for 5-min expiry approvals+ let approvalPollInterval: ReturnType<typeof setInterval>;+ onMount(() => {+ approvalPollInterval = setInterval(() => {+ aiIntelligenceStore.loadPendingApprovals();+ }, 10000);+ });+ onCleanup(() => clearInterval(approvalPollInterval));+async function loadAllData() {setIsRefreshing(true);try {await Promise.all([aiIntelligenceStore.loadFindings(),aiIntelligenceStore.loadCircuitBreakerStatus(),+ aiIntelligenceStore.loadPendingApprovals(),refetchPatrolStatus(),]);- // Trigger refresh of patrol activity visualizations+ // Trigger refresh of patrol status barsetActivityRefreshTrigger(prev => prev + 1);} finally {setIsRefreshing(false);@@ -516,12 +683,12 @@ export function AIIntelligence() {{/* Run Patrol Button */}<buttononClick={() => handleRunPatrol()}- disabled={isTriggeringPatrol() || !canTriggerPatrol()}+ disabled={isTriggeringPatrol() || !canTriggerPatrol() || manualRunRequested() || patrolStream.isStreaming()}title={triggerPatrolDisabledReason()}class="flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 disabled:bg-gray-300 dark:disabled:bg-gray-600 disabled:text-gray-500 rounded-md transition-colors">- <PlayIcon class={`w-4 h-4 ${isTriggeringPatrol() ? 'animate-pulse' : ''}`} />- {isTriggeringPatrol() ? 'Running…' : 'Run Patrol'}+ <PlayIcon class={`w-4 h-4 ${(isTriggeringPatrol() || manualRunRequested() || patrolStream.isStreaming()) ? 'animate-pulse' : ''}`} />+ {isTriggeringPatrol() ? 'Starting…' : (manualRunRequested() || patrolStream.isStreaming()) ? 'Running…' : 'Run Patrol'}</button>{/* Refresh Button */}@@ -558,25 +725,22 @@ export function AIIntelligence() {<div class="flex items-center gap-2"><span class="text-xs text-gray-500 dark:text-gray-400">Model:</span><select+ ref={patrolModelSelectRef}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"><option value="">Default ({defaultModel().split(':').pop() || 'not set'})</option>- <For each={Array.from(groupModelsByProvider(availableModels()).entries())}>- {([provider, models]) => (- <optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>- <For each={models}>- {(model) => (- <option value={model.id}>- {model.name || model.id.split(':').pop()}- </option>- )}- </For>- </optgroup>- )}- </For>+ {Array.from(groupModelsByProvider(availableModels()).entries()).map(([provider, models]) => (+ <optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>+ {models.map((model) => (+ <option value={model.id}>+ {model.name || model.id.split(':').pop()}+ </option>+ ))}+ </optgroup>+ ))}</select></div>@@ -673,7 +837,7 @@ export function AIIntelligence() {<Show when={showAdvancedSettings()}><div class="absolute right-0 top-8 z-50 w-72 p-4 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700"><div class="flex items-center justify-between mb-3">- <h4 class="text-sm font-semibold text-gray-900 dark:text-white">Investigation Limits</h4>+ <h4 class="text-sm font-semibold text-gray-900 dark:text-white">Advanced Settings</h4><buttononClick={() => setShowAdvancedSettings(false)}class="p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"@@ -683,46 +847,8 @@ export function AIIntelligence() {</div><div class="space-y-4">- {/* Turn Budget */}- <div>- <div class="flex items-center justify-between mb-1">- <label class="text-xs text-gray-600 dark:text-gray-400">Turn Budget</label>- <span class="text-xs font-medium text-gray-700 dark:text-gray-300">{investigationBudget()} turns</span>- </div>- <input- type="range"- min="5"- max="30"- step="1"- value={investigationBudget()}- onInput={(e) => setInvestigationBudget(parseInt(e.currentTarget.value, 10))}- disabled={isSavingAdvanced()}- class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"- />- <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-1">Max tool calls per investigation</p>- </div>-- {/* Timeout */}- <div>- <div class="flex items-center justify-between mb-1">- <label class="text-xs text-gray-600 dark:text-gray-400">Timeout</label>- <span class="text-xs font-medium text-gray-700 dark:text-gray-300">{Math.round(investigationTimeout() / 60)} min</span>- </div>- <input- type="range"- min="60"- max="1800"- step="60"- value={investigationTimeout()}- onInput={(e) => setInvestigationTimeout(parseInt(e.currentTarget.value, 10))}- disabled={isSavingAdvanced()}- class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"- />- <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-1">Max time per investigation (1-30 min)</p>- </div>-{/* Full Mode Unlock */}- <div class="pt-3 border-t border-gray-200 dark:border-gray-700">+ <div><div class="flex items-start justify-between gap-3"><div class="flex-1"><label class="text-xs font-medium text-red-600 dark:text-red-400">Enable Full Mode</label>@@ -749,7 +875,89 @@ export function AIIntelligence() {</Show></div>- {/* Save Button */}+ {/* Alert-Triggered Analysis */}+ <div class="pt-3 border-t border-gray-200 dark:border-gray-700">+ <div class="flex items-center justify-between gap-3">+ <div class="flex-1">+ <label class="text-xs font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1.5">+ Alert-Triggered Analysis+ <span class="px-1 py-0.5 text-[9px] font-medium bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 rounded">Efficient</span>+ </label>+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5">+ Analyze infrastructure when alerts fire.+ </p>+ </div>+ <Toggle+ checked={alertTriggeredAnalysis()}+ onChange={(e) => handleAlertTriggeredAnalysisChange(e.currentTarget.checked)}+ disabled={isUpdatingSettings() || alertAnalysisLocked()}+ />+ </div>+ <Show when={alertAnalysisLocked()}>+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-1">+ <a class="text-indigo-600 dark:text-indigo-400 font-medium hover:underline" href="https://pulserelay.pro/" target="_blank" rel="noreferrer">Upgrade to Pro</a>+ {' '}to enable alert-triggered analysis.+ </p>+ </Show>+ </div>++ {/* Auto-Fix Mode */}+ <div class="pt-3 border-t border-gray-200 dark:border-gray-700">+ <div class="flex items-center justify-between gap-3">+ <div class="flex-1">+ <label class="text-xs font-medium text-gray-700 dark:text-gray-300 flex items-center gap-1.5">+ Auto-Fix+ <span class="px-1 py-0.5 text-[9px] font-medium bg-amber-100 dark:bg-amber-900 text-amber-700 dark:text-amber-300 rounded">Advanced</span>+ </label>+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-0.5">+ Allow Patrol to execute fixes automatically.+ </p>+ </div>+ <Toggle+ checked={patrolAutoFix()}+ onChange={(e) => handleAutoFixChange(e.currentTarget.checked)}+ disabled={isUpdatingSettings() || autoFixLocked()}+ />+ </div>+ <Show when={autoFixLocked()}>+ <p class="text-[10px] text-gray-500 dark:text-gray-400 mt-1">+ <a class="text-indigo-600 dark:text-indigo-400 font-medium hover:underline" href="https://pulserelay.pro/" target="_blank" rel="noreferrer">Upgrade to Pro</a>+ {' '}to enable auto-fix.+ </p>+ </Show>+ <Show when={!autoFixLocked() && patrolAutoFix()}>+ <p class="text-[10px] text-red-600 dark:text-red-400 mt-1 flex items-center gap-1">+ <AlertTriangleIcon class="w-3 h-3 flex-shrink-0" />+ Auto-Fix is ON. Patrol will attempt automatic remediation.+ </p>+ </Show>+ </div>++ {/* Auto-Fix Model - only when auto-fix is enabled */}+ <Show when={patrolAutoFix() && !autoFixLocked()}>+ <div>+ <label class="text-xs text-gray-600 dark:text-gray-400">Fix Model</label>+ <select+ 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"+ >+ <option value="">Use patrol model</option>+ {Array.from(groupModelsByProvider(availableModels()).entries()).map(([provider, models]) => (+ <optgroup label={provider.charAt(0).toUpperCase() + provider.slice(1)}>+ {models.map((model) => (+ <option value={model.id}>+ {model.name || model.id.split(':').pop()}+ </option>+ ))}+ </optgroup>+ ))}+ </select>+ </div>+ </Show>++ {/* Save Button (for investigation limits + full mode unlock) */}<buttononClick={saveAdvancedSettings}disabled={isSavingAdvanced()}@@ -768,44 +976,27 @@ export function AIIntelligence() {</div></div>- <Show when={showErrorBanner()}>- <div class="flex-shrink-0 bg-red-50 dark:bg-red-900/20 border-b border-red-200 dark:border-red-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-red-100 dark:bg-red-900/40 rounded-lg">- <ShieldAlertIcon class="w-4 h-4 text-red-600 dark:text-red-400" />- </div>- <div>- <p class="text-sm font-semibold text-red-900 dark:text-red-100">- Patrol hit errors in the last run- </p>- <p class="text-xs text-red-700 dark:text-red-300">- {errorCount()} error{errorCount() === 1 ? '' : 's'} reported. Check your AI provider settings and try again.- </p>- <Show when={patrolStatus()?.last_patrol_at}>- <p class="text-[10px] text-red-700/80 dark:text-red-300/80">- Last run {formatRelativeTime(patrolStatus()?.last_patrol_at)}- </p>- </Show>- </div>- </div>+ {/* Live patrol streaming status bar */}+ <Show when={patrolStream.isStreaming()}>+ <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-2">+ <div class="flex items-center gap-3 text-sm"><div class="flex items-center gap-2">- <a- href="/settings/system-ai"- class="inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold text-red-900 dark:text-red-100 bg-red-100 dark:bg-red-900/40 border border-red-200 dark:border-red-700 rounded-lg hover:bg-red-200/70 dark:hover:bg-red-900/60 transition-colors"- >- <SettingsIcon class="w-3.5 h-3.5" />- Open AI Settings- </a>- <button- type="button"- onClick={() => loadAllData()}- class="inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold text-white bg-red-600 hover:bg-red-700 rounded-lg transition-colors"- >- <RefreshCwIcon class="w-3.5 h-3.5" />- Refresh- </button>+ <div class="w-2 h-2 rounded-full bg-blue-500 animate-pulse" />+ <span class="font-medium text-blue-800 dark:text-blue-200">Patrol running</span></div>+ <Show when={patrolStream.phase()}>+ <span class="text-blue-700 dark:text-blue-300">{patrolStream.phase()}</span>+ </Show>+ <Show when={patrolStream.currentTool()}>+ <span class="text-blue-600 dark:text-blue-400 font-mono text-xs bg-blue-100 dark:bg-blue-900/40 px-1.5 py-0.5 rounded">+ {patrolStream.currentTool()}+ </span>+ </Show>+ <Show when={patrolStream.tokens() > 0}>+ <span class="text-blue-500 dark:text-blue-400 text-xs ml-auto">+ {patrolStream.tokens().toLocaleString()} tokens+ </span>+ </Show></div></div></Show>@@ -929,6 +1120,24 @@ export function AIIntelligence() {{/* Content */}<div class={`flex-1 overflow-auto p-4 transition-opacity ${!patrolEnabledLocal() ? 'opacity-50 pointer-events-none' : ''}`}><div class="space-y-4">+ {/* Approval Banner */}+ <ApprovalBanner+ onScrollToFinding={(findingId) => {+ setActiveTab('findings');+ // Scroll to the finding after tab switch+ requestAnimationFrame(() => {+ const el = document.getElementById(`finding-${findingId}`);+ el?.scrollIntoView({ behavior: 'smooth', block: 'start' });+ });+ }}+ />++ {/* Status Bar (replaces Activity tab) */}+ <PatrolStatusBar+ enabled={patrolEnabledLocal()}+ refreshTrigger={activityRefreshTrigger()}+ />+{/* Summary Cards */}<div class="grid grid-cols-2 lg:grid-cols-5 gap-3">{/* Critical */}@@ -1014,28 +1223,32 @@ export function AIIntelligence() {</div></div>- {/* Watch + Info (lower severity) */}- <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-3">+ {/* Awaiting Approval */}+ <div class={`rounded-lg border p-3 ${+ aiIntelligenceStore.pendingApprovalCount > 0+ ? 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-700'+ : 'bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700'+ }`}><div class="flex items-center gap-2"><div class={`p-1.5 rounded ${- (summaryStats().watchFindings + summaryStats().infoFindings) > 0- ? 'bg-blue-100 dark:bg-blue-900/30'+ aiIntelligenceStore.pendingApprovalCount > 0+ ? 'bg-amber-100 dark:bg-amber-900/30': 'bg-gray-100 dark:bg-gray-700'}`}>- <ActivityIcon class={`w-4 h-4 ${- (summaryStats().watchFindings + summaryStats().infoFindings) > 0- ? 'text-blue-600 dark:text-blue-400'+ <ShieldAlertIcon class={`w-4 h-4 ${+ aiIntelligenceStore.pendingApprovalCount > 0+ ? 'text-amber-600 dark:text-amber-400 animate-pulse': 'text-gray-400 dark:text-gray-500'}`} /></div><div>- <p class="text-xs text-gray-500 dark:text-gray-400">Watch / Info</p>+ <p class="text-xs text-gray-500 dark:text-gray-400">Awaiting Approval</p><p class={`text-lg font-bold ${- (summaryStats().watchFindings + summaryStats().infoFindings) > 0- ? 'text-blue-600 dark:text-blue-400'+ aiIntelligenceStore.pendingApprovalCount > 0+ ? 'text-amber-600 dark:text-amber-400': 'text-gray-400 dark:text-gray-500'}`}>- {summaryStats().watchFindings + summaryStats().infoFindings}+ {aiIntelligenceStore.pendingApprovalCount}</p></div></div>@@ -1091,17 +1304,6 @@ export function AIIntelligence() {</span></Show></button>- <button- type="button"- onClick={() => setActiveTab('activity')}- class={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${- activeTab() === 'activity'- ? 'border-blue-500 text-blue-600 dark:text-blue-400'- : 'border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- Activity- </button><buttontype="button"onClick={() => setActiveTab('history')}@@ -1112,9 +1314,9 @@ export function AIIntelligence() {}`}>Run History- <Show when={(patrolRunHistory() || []).length > 0}>+ <Show when={displayRunHistory().length > 0}><span class="ml-1.5 px-1.5 py-0.5 text-xs rounded-full bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300">- {(patrolRunHistory() || []).length}+ {displayRunHistory().length}</span></Show></button>@@ -1151,25 +1353,6 @@ export function AIIntelligence() {/></Show>- <Show when={activeTab() === 'activity'}>- <Show- when={summaryStats().hasAnyPatrolFindings || patrolStatus()?.last_patrol_at}- fallback={- <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-8 text-center">- <ActivityIcon class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3" />- <p class="text-sm text-gray-500 dark:text-gray-400">- No patrol activity yet. Run a patrol to see activity data.- </p>- </div>- }- >- <PatrolActivitySection- enabled={patrolEnabledLocal()}- refreshTrigger={activityRefreshTrigger()}- />- </Show>- </Show>-<Show when={activeTab() === 'history'}><div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4"><div class="flex items-center justify-between mb-4">@@ -1194,7 +1377,7 @@ export function AIIntelligence() {<div class="text-xs text-gray-500 dark:text-gray-400">Loading run history…</div></Show>- <Show when={!patrolRunHistory.loading && (patrolRunHistory() || []).length === 0}>+ <Show when={!patrolRunHistory.loading && displayRunHistory().length === 0}><div class="text-center py-8"><RefreshCwIcon class="w-12 h-12 mx-auto text-gray-300 dark:text-gray-600 mb-3" /><p class="text-sm text-gray-500 dark:text-gray-400">@@ -1203,135 +1386,296 @@ export function AIIntelligence() {</div></Show>- <Show when={!patrolRunHistory.loading && (patrolRunHistory() || []).length > 0}>+ <Show when={!patrolRunHistory.loading && displayRunHistory().length > 0}><div class="space-y-2">- <For each={patrolRunHistory() || []}>+ <For each={displayRunHistory()}>{(run) => {+ // Live in-progress entry+ if (run.id === '__live__') {+ const hasError = () => !!patrolStream.errorMessage();+ return (+ <div class={`rounded-md border transition-colors ${+ hasError()+ ? 'border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-900/20'+ : 'border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20'+ }`}>+ <div class="px-3 py-2">+ <div class="flex flex-wrap items-center gap-2 text-xs">+ <Show when={!hasError()}>+ <span class="relative flex h-2.5 w-2.5">+ <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />+ <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-blue-500" />+ </span>+ <span class="font-medium text-blue-800 dark:text-blue-200">Running now</span>+ </Show>+ <Show when={hasError()}>+ <ShieldAlertIcon class="w-3.5 h-3.5 text-red-500" />+ <span class="font-medium text-red-800 dark:text-red-200">Error</span>+ </Show>+ <Show when={!hasError() && patrolStream.phase()}>+ <span class="text-blue-700 dark:text-blue-300">{patrolStream.phase()}</span>+ </Show>+ <Show when={!hasError() && patrolStream.currentTool()}>+ <span class="font-mono text-[11px] bg-blue-100 dark:bg-blue-900/40 text-blue-600 dark:text-blue-400 px-1.5 py-0.5 rounded">+ {patrolStream.currentTool()}+ </span>+ </Show>+ <Show when={!hasError() && patrolStream.tokens() > 0}>+ <span class="text-blue-500 dark:text-blue-400 ml-auto">+ {patrolStream.tokens().toLocaleString()} tokens+ </span>+ </Show>+ </div>+ <Show when={hasError()}>+ <p class="mt-1.5 text-xs text-red-700 dark:text-red-300">+ {patrolStream.errorMessage()}+ </p>+ </Show>+ </div>+ </div>+ );+ }const scopeSummary = formatScope(run);const duration = formatDurationMs(run.duration_ms);const isSelected = () => selectedRun()?.id === run.id;return (- <button- type="button"- onClick={() => {- setSelectedRun(isSelected() ? null : run);- if (!isSelected()) setActiveTab('findings');- }}- class={`w-full text-left px-3 py-2 rounded-md border transition-colors ${- isSelected()- ? 'border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20'- : 'border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700/40'- }`}- >- <div class="flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">- <span class="text-gray-900 dark:text-gray-100 font-medium">- {formatRelativeTime(run.started_at)}- </span>- <span class={`px-1.5 py-0.5 rounded ${- run.status === 'critical'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : run.status === 'issues_found'- ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'- : run.status === 'error'- ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'- : 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'- }`}>- {run.status.replace(/_/g, ' ')}- </span>- <span>{formatTriggerReason(run.trigger_reason)}</span>- <Show when={scopeSummary}>- <span>• {scopeSummary}</span>- </Show>- <Show when={duration}>- <span>• {duration}</span>- </Show>- <Show when={run.resources_checked}>- <span>• {run.resources_checked} resources</span>- </Show>- <Show when={run.new_findings}>- <span>• {run.new_findings} new</span>- </Show>- </div>- </button>- );- }}- </For>- </div>- </Show>-- <Show when={selectedRun()}>- {(run) => (- <div class="mt-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/40 p-3">- <div class="flex items-start justify-between gap-3">- <div>- <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-100">Run details</h3>- <p class="text-xs text-gray-500 dark:text-gray-400">- {formatRelativeTime(run().started_at)} • {formatTriggerReason(run().trigger_reason)}- </p>- </div>- <button- type="button"- onClick={() => setSelectedRun(null)}- class="text-xs font-medium text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"- >- Close- </button>- </div>-- <div class="mt-3 grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-gray-600 dark:text-gray-400">- <div><span class="font-medium text-gray-700 dark:text-gray-300">Status:</span> {run().status.replace(/_/g, ' ')}</div>- <div><span class="font-medium text-gray-700 dark:text-gray-300">Duration:</span> {formatDurationMs(run().duration_ms) || '—'}</div>- <div><span class="font-medium text-gray-700 dark:text-gray-300">Resources:</span> {run().resources_checked || 0}</div>- <div><span class="font-medium text-gray-700 dark:text-gray-300">Findings:</span> {run().new_findings || 0} new</div>- <Show when={run().input_tokens || run().output_tokens}>- <div class="col-span-2">- <span class="font-medium text-gray-700 dark:text-gray-300">Tokens:</span>{' '}- {run().input_tokens || 0} in / {run().output_tokens || 0} out- </div>- </Show>- </div>-- <Show when={run().ai_analysis}>- <div class="mt-3">- <div class="flex items-center justify-between">- <span class="text-xs font-medium text-gray-700 dark:text-gray-300">AI analysis</span>+ <div class={`rounded-md border transition-colors ${+ isSelected()+ ? 'border-blue-300 dark:border-blue-700 bg-blue-50 dark:bg-blue-900/20'+ : 'border-gray-200 dark:border-gray-700'+ }`}><buttontype="button"- onClick={() => setShowRunAnalysis(!showRunAnalysis())}- class="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"+ onClick={() => setSelectedRun(isSelected() ? null : run)}+ class={`w-full text-left px-3 py-2 rounded-md transition-colors ${+ !isSelected() ? 'hover:bg-gray-50 dark:hover:bg-gray-700/40' : ''+ }`}>- {showRunAnalysis() ? 'Hide' : 'Show'}+ <div class="flex flex-wrap items-center gap-2 text-xs text-gray-500 dark:text-gray-400">+ <span class="text-gray-900 dark:text-gray-100 font-medium">+ {formatRelativeTime(run.started_at)}+ </span>+ <span class={`px-1.5 py-0.5 rounded ${+ run.status === 'critical'+ ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'+ : run.status === 'issues_found'+ ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300'+ : run.status === 'error'+ ? 'bg-red-100 text-red-700 dark:bg-red-900/40 dark:text-red-300'+ : 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300'+ }`}>+ {run.status.replace(/_/g, ' ')}+ </span>+ <span>{formatTriggerReason(run.trigger_reason)}</span>+ <Show when={scopeSummary}>+ <span>• {scopeSummary}</span>+ </Show>+ <Show when={duration}>+ <span>• {duration}</span>+ </Show>+ <Show when={run.resources_checked}>+ <span>• {run.resources_checked} resources</span>+ </Show>+ <Show when={run.new_findings}>+ <span>• {run.new_findings} new</span>+ </Show>+ <Show when={run.rejected_findings}>+ <span class="text-gray-400 dark:text-gray-500">• {run.rejected_findings} rejected</span>+ </Show>+ </div></button>- </div>- <Show when={showRunAnalysis()}>- <pre class="mt-2 p-2 rounded bg-white dark:bg-gray-900 text-[11px] text-gray-700 dark:text-gray-200 whitespace-pre-wrap max-h-48 overflow-auto">- {run().ai_analysis}- </pre>- </Show>- <Show when={!showRunAnalysis()}>- <div class="mt-2 text-[11px] text-gray-500 dark:text-gray-400">- {truncateText(run().ai_analysis, 200)}- </div>- </Show>- </div>- </Show>- <div class="mt-3">- <button- type="button"- onClick={() => setActiveTab('findings')}- class="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"- >- View findings from this run →- </button>- </div>- </div>- )}+ {/* Inline expansion details */}+ <Show when={isSelected()}>+ <div class="px-3 pb-3 border-t border-blue-200 dark:border-blue-800 mt-0">++ {/* Section 1: Narrative Summary */}+ <div class="mt-3 flex items-start gap-2 text-sm text-gray-700 dark:text-gray-200">+ <SparklesIcon class="w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0" />+ <p>+ {run.resources_checked > 0+ ? <>Scanned <strong>{run.resources_checked}</strong> resource{run.resources_checked !== 1 ? 's' : ''}{' '}+ {formatDurationMs(run.duration_ms) ? <>in <strong>{formatDurationMs(run.duration_ms)}</strong></> : ''}{' '}+ {run.tool_call_count > 0 ? <>using <strong>{run.tool_call_count}</strong> tool call{run.tool_call_count !== 1 ? 's' : ''}</> : ''}.{' '}+ </>+ : <>Patrol completed{formatDurationMs(run.duration_ms) ? <> in <strong>{formatDurationMs(run.duration_ms)}</strong></> : ''}.{' '}</>+ }+ {run.new_findings > 0+ ? <>Found <strong>{run.new_findings}</strong> new issue{run.new_findings !== 1 ? 's' : ''}{run.auto_fix_count > 0 ? <>, auto-fixed <strong>{run.auto_fix_count}</strong></> : ''}.</>+ : <span class="text-green-600 dark:text-green-400">All clear — no new issues.</span>+ }+ </p>+ </div>++ {/* Section 2: Resources Scanned */}+ <Show when={run.resources_checked > 0}>+ <div class="mt-3">+ <div class="flex items-center gap-1.5 mb-2">+ <SearchIcon class="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" />+ <span class="text-[10px] font-semibold tracking-wider uppercase text-gray-500 dark:text-gray-400">+ Resources Scanned ({run.resources_checked})+ </span>+ </div>+ <div class="flex flex-wrap gap-1.5">+ <Show when={run.nodes_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300">+ <ServerIcon class="w-3 h-3" /> {run.nodes_checked} node{run.nodes_checked !== 1 ? 's' : ''}+ </span>+ </Show>+ <Show when={run.guests_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-purple-50 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300">+ <MonitorIcon class="w-3 h-3" /> {run.guests_checked} VM{run.guests_checked !== 1 ? 's' : ''}+ </span>+ </Show>+ <Show when={run.docker_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-cyan-50 text-cyan-700 dark:bg-cyan-900/30 dark:text-cyan-300">+ <BoxIcon class="w-3 h-3" /> {run.docker_checked} container{run.docker_checked !== 1 ? 's' : ''}+ </span>+ </Show>+ <Show when={run.storage_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-50 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">+ <HardDriveIcon class="w-3 h-3" /> {run.storage_checked} storage+ </span>+ </Show>+ <Show when={run.hosts_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-300">+ <GlobeIcon class="w-3 h-3" /> {run.hosts_checked} host{run.hosts_checked !== 1 ? 's' : ''}+ </span>+ </Show>+ <Show when={run.pbs_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300">+ <DatabaseIcon class="w-3 h-3" /> {run.pbs_checked} PBS+ </span>+ </Show>+ <Show when={run.kubernetes_checked > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-sky-50 text-sky-700 dark:bg-sky-900/30 dark:text-sky-300">+ <ActivityIcon class="w-3 h-3" /> {run.kubernetes_checked} K8s+ </span>+ </Show>+ </div>+ </div>+ </Show>++ {/* Section 3: Outcomes */}+ <div class="mt-3">+ <div class="flex items-center gap-1.5 mb-2">+ <ShieldAlertIcon class="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" />+ <span class="text-[10px] font-semibold tracking-wider uppercase text-gray-500 dark:text-gray-400">+ Outcomes+ </span>+ </div>+ <div class="flex flex-wrap gap-1.5">+ <Show when={run.new_findings > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300">+ <AlertTriangleIcon class="w-3 h-3" /> {run.new_findings} new+ </span>+ </Show>+ <Show when={run.existing_findings > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300">+ <ActivityIcon class="w-3 h-3" /> {run.existing_findings} existing+ </span>+ </Show>+ <Show when={run.resolved_findings > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300">+ <CheckCircleIcon class="w-3 h-3" /> {run.resolved_findings} resolved+ </span>+ </Show>+ <Show when={run.auto_fix_count > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300">+ <WrenchIcon class="w-3 h-3" /> {run.auto_fix_count} auto-fixed+ </span>+ </Show>+ <Show when={run.rejected_findings > 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-50 text-gray-400 dark:bg-gray-800 dark:text-gray-500">+ <FilterXIcon class="w-3 h-3" /> {run.rejected_findings} rejected+ </span>+ </Show>+ <Show when={run.status === 'healthy' && run.new_findings === 0}>+ <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300">+ <CheckCircleIcon class="w-3 h-3" /> All clear+ </span>+ </Show>+ </div>+ </div>++ {/* Section 4: AI Effort Bar */}+ <div class="mt-3 flex flex-wrap items-center gap-3 px-3 py-2 rounded-md bg-gray-50 dark:bg-gray-900/50 text-xs text-gray-500 dark:text-gray-400">+ <Show when={formatDurationMs(run.duration_ms)}>+ <span class="inline-flex items-center gap-1">+ <ClockIcon class="w-3.5 h-3.5" /> {formatDurationMs(run.duration_ms)}+ </span>+ </Show>+ <Show when={run.tool_call_count > 0}>+ <span class="inline-flex items-center gap-1">+ <ZapIcon class="w-3.5 h-3.5" /> {run.tool_call_count} tool call{run.tool_call_count !== 1 ? 's' : ''}+ </span>+ </Show>+ <Show when={(run.input_tokens || 0) + (run.output_tokens || 0) > 0}>+ <span class="inline-flex items-center gap-1">+ <BrainCircuitIcon class="w-3.5 h-3.5" /> {((run.input_tokens || 0) + (run.output_tokens || 0)).toLocaleString()} tokens+ </span>+ </Show>+ <Show when={run.type === 'scoped'}>+ <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 text-[10px] font-medium">+ {formatScope(run) || 'Scoped'}+ </span>+ </Show>+ </div>++ {/* Section 5: Patrol Analysis */}+ <Show when={run.ai_analysis}>+ <div class="mt-3">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-1.5">+ <BrainCircuitIcon class="w-3.5 h-3.5 text-gray-400 dark:text-gray-500" />+ <span class="text-[10px] font-semibold tracking-wider uppercase text-gray-500 dark:text-gray-400">+ Patrol Analysis+ </span>+ </div>+ <button+ type="button"+ onClick={() => setShowRunAnalysis(!showRunAnalysis())}+ class="text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"+ >+ {showRunAnalysis() ? 'Collapse' : 'Expand'}+ </button>+ </div>+ <Show when={showRunAnalysis()}>+ <div+ class="mt-2 p-3 rounded bg-white dark:bg-gray-900 text-sm leading-relaxed text-gray-700 dark:text-gray-200 max-h-64 overflow-auto prose prose-sm dark:prose-invert prose-headings:text-sm prose-headings:mt-2 prose-headings:mb-1 prose-p:my-1 prose-ul:my-1 prose-li:my-0"+ innerHTML={renderMarkdown(sanitizeAnalysis(run.ai_analysis))}+ />+ </Show>+ </div>+ </Show>++ {/* Section 6: Tool Call Trace */}+ <RunToolCallTrace runId={run.id} toolCallCount={run.tool_call_count} />++ {/* Section 7: Inline Findings */}+ <Show when={run.finding_ids?.length}>+ <div class="mt-3 pt-3 border-t border-blue-200 dark:border-blue-800">+ <FindingsPanel+ filterFindingIds={run.finding_ids}+ filterOverride="all"+ showControls={false}+ />+ </div>+ </Show>+ </div>+ </Show>+ </div>+ );+ }}+ </For>+ </div></Show>+</div></Show></div></div>+</div>);}diff --git a/frontend-modern/src/stores/aiChat.ts b/frontend-modern/src/stores/aiChat.tsindex 097075c030..44a999f73f 100644--- a/frontend-modern/src/stores/aiChat.ts+++ b/frontend-modern/src/stores/aiChat.ts@@ -412,6 +412,15 @@ export const aiChatStore = {setIsAIChatOpen(true);},+ // Clear the initialPrompt so it doesn't re-fire on subsequent opens+ clearInitialPrompt() {+ setAIChatContext(prev => {+ if (!prev.initialPrompt) return prev;+ const { initialPrompt: _, ...rest } = prev;+ return rest;+ });+ },+// Register the AI input element (called by AIChat component)registerInput(ref: HTMLTextAreaElement | null) {aiInputRef = ref;diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.tsindex 709237e6ec..17df79b2bf 100644--- a/frontend-modern/src/stores/aiIntelligence.ts+++ b/frontend-modern/src/stores/aiIntelligence.ts@@ -9,11 +9,13 @@import { createSignal } from 'solid-js';import { AIAPI } from '@/api/ai';-import { acknowledgeFinding, snoozeFinding, dismissFinding } from '@/api/patrol';+import { acknowledgeFinding, snoozeFinding, dismissFinding, setFindingNote } from '@/api/patrol';import type {RemediationPlan,CircuitBreakerStatus,UnifiedFindingRecord,+ ApprovalRequest,+ ApprovalExecutionResult,} from '@/api/ai';import { logger } from '@/utils/logger';@@ -47,7 +49,7 @@ export interface UnifiedFinding {// Investigation fields (Patrol Autonomy)investigationSessionId?: string;investigationStatus?: 'pending' | 'running' | 'completed' | 'failed' | 'needs_attention';- investigationOutcome?: 'resolved' | 'fix_queued' | 'needs_attention' | 'cannot_fix';+ investigationOutcome?: 'resolved' | 'fix_queued' | 'fix_executed' | 'fix_failed' | 'needs_attention' | 'cannot_fix';lastInvestigatedAt?: string;investigationAttempts?: number;}@@ -63,6 +65,12 @@ const [findingsError, setFindingsError] = createSignal<string | null>(null);const [remediationPlans, setRemediationPlans] = createSignal<RemediationPlan[]>([]);const [plansLoading, setPlansLoading] = createSignal(false);+// ============================================+// Pending Approvals+// ============================================++const [pendingApprovals, setPendingApprovals] = createSignal<ApprovalRequest[]>([]);+// ============================================// Circuit Breaker// ============================================@@ -123,6 +131,11 @@ export const aiIntelligenceStore = {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,};});@@ -222,6 +235,66 @@ export const aiIntelligenceStore = {}},+ 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 Breakerget circuitBreakerStatus() { return circuitBreakerStatus(); },circuitBreakerStatusSignal: circuitBreakerStatus,@@ -241,6 +314,7 @@ export const aiIntelligenceStore = {this.loadFindings(),this.loadRemediationPlans(),this.loadCircuitBreakerStatus(),+ this.loadPendingApprovals(),]);},diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.tsindex ad10f1543f..f59d77fd81 100644--- a/frontend-modern/src/types/ai.ts+++ b/frontend-modern/src/types/ai.ts@@ -30,7 +30,6 @@ export interface AISettings {patrol_schedule_preset?: string; // DEPRECATED: use patrol_interval_minutespatrol_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 attempt automatic remediationavailable_models?: ModelInfo[]; // DEPRECATED: use /api/ai/models endpoint// Multi-provider configurationanthropic_configured: boolean; // true if Anthropic API key or OAuth is set@@ -74,7 +73,6 @@ export interface AISettingsUpdateRequest {patrol_schedule_preset?: string; // DEPRECATED: use patrol_interval_minutespatrol_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 attempt automatic remediation// Multi-provider credentialsanthropic_api_key?: string; // Set Anthropic API keyopenai_api_key?: string; // Set OpenAI API keydiff --git a/frontend-modern/src/types/aiIntelligence.ts b/frontend-modern/src/types/aiIntelligence.tsindex 969c50e8bd..17df79b2bf 100644--- a/frontend-modern/src/types/aiIntelligence.ts+++ b/frontend-modern/src/types/aiIntelligence.ts@@ -1,278 +1,327 @@-// AI Intelligence types for patterns, predictions, and correlations--export interface FailurePattern {- key: string;- resource_id: string;- event_type: string;- occurrences: number;- average_interval: string;- average_duration: string;- last_occurrence: string;- confidence: number;+/**+ * AI Intelligence Store+ *+ * Central store for managing AI intelligence state:+ * - Unified findings (alerts + AI findings)+ * - Remediation plans+ * - Circuit breaker status+ */++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+// ============================================++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;+ 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';+ lastInvestigatedAt?: string;+ investigationAttempts?: number;}-export interface FailurePrediction {- resource_id: string;- resource_name?: string;- resource_type?: string;- event_type: string;- predicted_at: string;- days_until: number;- confidence: number;- basis: string;- is_overdue: boolean;-}--export interface ResourceCorrelation {- source_id: string;- source_name: string;- source_type: string;- target_id: string;- target_name: string;- target_type: string;- event_pattern: string;- occurrences: number;- avg_delay: string;- confidence: number;- last_seen: string;- description: string;-}--export interface InfrastructureChange {- id: string;- resource_id: string;- resource_name: string;- resource_type: string;- change_type: string;- before: unknown;- after: unknown;- detected_at: string;- description: string;-}--export interface ResourceBaseline {- key: string;- resource_id: string;- metric: string;- mean: number;- std_dev: number;- min: number;- max: number;- samples: number;- last_update: string;-}--export interface RemediationRecord {- id: string;- timestamp: string;- resource_id: string;- resource_type: string;- resource_name: string;- finding_id?: string;- problem: string;- summary?: string; // AI-generated summary of what was achieved- action: string;- output?: string;- outcome: string;- duration_ms?: number;- note?: string;- automatic: boolean;-}--export interface RemediationStats {- total: number;- resolved: number;- partial: number;- failed: number;- unknown: number;- automatic: number;- manual: number;-}--// API response types-interface LicenseGatedResponse {- license_required?: boolean;- upgrade_url?: string;- message?: string;-}--export interface PatternsResponse extends LicenseGatedResponse {- patterns: FailurePattern[];- count: number;-}--export interface PredictionsResponse extends LicenseGatedResponse {- predictions: FailurePrediction[];- count: number;-}--export interface CorrelationsResponse extends LicenseGatedResponse {- correlations: ResourceCorrelation[];- count: number;-}--export interface ChangesResponse extends LicenseGatedResponse {- changes: InfrastructureChange[];- count: number;- hours: number;-}--export interface BaselinesResponse extends LicenseGatedResponse {- baselines: ResourceBaseline[];- count: number;-}--export interface RemediationsResponse extends LicenseGatedResponse {- remediations: RemediationRecord[];- count: number;- stats?: RemediationStats;-}--// Real-time anomaly detection types-export type AnomalySeverity = 'low' | 'medium' | 'high' | 'critical';--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: AnomalySeverity;- description: string;-}--export interface AnomaliesResponse extends LicenseGatedResponse {- anomalies: AnomalyReport[];- count: number;- severity_counts: {- critical: number;- high: number;- medium: number;- low: number;- };-}--// Learning/baseline status for showing system intelligence state-export type LearningStatus = 'waiting' | 'learning' | 'active';--export interface LearningStatusResponse {- resources_baselined: number;- total_metrics: number;- metric_breakdown: {- cpu?: number;- memory?: number;- disk?: number;- };- status: LearningStatus;- message: string;- license_required: boolean;-}---// ============================================================================-// Unified Intelligence Types (for /api/ai/intelligence endpoint)-// ============================================================================--export type HealthGrade = 'A' | 'B' | 'C' | 'D' | 'F';-export type HealthTrend = 'improving' | 'stable' | 'declining';--export interface HealthFactor {- name: string;- impact: number; // -1 to 1, negative is bad, positive is good- description: string;- category: string; // "finding", "prediction", "baseline", "learning"-}--export interface HealthScore {- score: number; // 0-100- grade: HealthGrade;- trend: HealthTrend;- factors: HealthFactor[];- prediction?: string; // AI-predicted future state-}--export interface FindingsCounts {- total: number;- critical: number;- warning: number;- watch: number;- info: number;-}--export interface LearningStats {- resources_with_knowledge: number;- total_notes: number;- resources_with_baselines: number;- patterns_detected: number;- correlations_learned: number;- incidents_tracked: number;-}--export interface ResourceRiskSummary {- resource_id: string;- resource_name: string;- resource_type: string;- health: HealthScore;- top_issue: string;-}--// System-wide intelligence summary-export interface IntelligenceSummary {- timestamp: string;- overall_health: HealthScore;-- // Findings overview- findings_count: FindingsCounts;- top_findings?: unknown[]; // Top N findings by severity-- // Predictions overview- predictions_count: number;- upcoming_risks?: FailurePrediction[];-- // Recent activity- recent_changes_count: number;- recent_remediations?: RemediationRecord[];-- // Learning progress- learning: LearningStats;-- // Resources needing attention- resources_at_risk?: ResourceRiskSummary[];-}--// Per-resource intelligence-export interface ResourceIntelligence {- resource_id: string;- resource_name: string;- resource_type: string;-- // Health score for this resource- health: HealthScore;-- // Active findings for this resource- active_findings?: unknown[];-- // Predictions for this resource- predictions?: FailurePrediction[];-- // Correlations involving this resource- correlations?: ResourceCorrelation[];- dependencies?: string[]; // Resources this depends on- dependents?: string[]; // Resources that depend on this-- // Baselines for this resource- baselines?: Record<string, ResourceBaseline>;-- // Current anomalies- anomalies?: AnomalyReport[];-- // Recent incidents- recent_incidents?: unknown[];-- // Knowledge/notes- knowledge?: unknown;- note_count: 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);++// ============================================+// Store API+// ============================================++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;diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.tsindex d0bdb02891..29c7851ed5 100644--- a/frontend-modern/src/types/api.ts+++ b/frontend-modern/src/types/api.ts@@ -599,19 +599,6 @@ export interface Storage {zfsPool?: ZFSPool;}-export interface StorageConfigEntry {- id: string;- name: string;- instance?: string;- type?: string;- content?: string;- nodes?: string[];- path?: string;- shared: boolean;- enabled: boolean;- active: boolean;-}-export interface CephCluster {id: string;instance: string;