Files
Redflag/aggregator-web/src/components/AgentScanners.tsx
Fimeg 3690472396 feat: granular subsystem commands with parallel scanner execution
Split monolithic scan_updates into individual subsystems (updates/storage/system/docker).
Scanners now run in parallel via goroutines - cuts scan time roughly in half, maybe more.

Agent changes:
- Orchestrator pattern for scanner management
- New scanners: storage (disk metrics), system (cpu/mem/processes)
- New commands: scan_storage, scan_system, scan_docker
- Wrapped existing scanners (APT/DNF/Docker/Windows/Winget) with common interface
- Version bump to 0.1.20

Server changes:
- Migration 015: agent_subsystems table with trigger for auto-init
- Subsystem CRUD: enable/disable, interval (5min-24hr), auto-run toggle
- API routes: /api/v1/agents/:id/subsystems/* (9 endpoints)
- Stats tracking per subsystem

Web UI changes:
- ChatTimeline shows subsystem-specific labels and icons
- AgentScanners got interactive toggles, interval dropdowns, manual trigger buttons
- TypeScript types added for subsystems

Backward compatible with legacy scan_updates - for now. Bugs probably exist somewhere.
2025-11-01 21:34:26 -04:00

348 lines
14 KiB
TypeScript

import React, { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
MonitorPlay,
RefreshCw,
Settings,
Activity,
Clock,
CheckCircle,
XCircle,
Play,
Square,
Database,
Shield,
Search,
HardDrive,
Cpu,
Container,
Package,
} from 'lucide-react';
import { formatRelativeTime } from '@/lib/utils';
import { agentApi } from '@/lib/api';
import toast from 'react-hot-toast';
import { cn } from '@/lib/utils';
import { AgentSubsystem } from '@/types';
interface AgentScannersProps {
agentId: string;
}
// Map subsystem types to icons and display names
const subsystemConfig: Record<string, { icon: React.ReactNode; name: string; description: string; category: string }> = {
updates: {
icon: <Package className="h-4 w-4" />,
name: 'Package Update Scanner',
description: 'Scans for available package updates (APT, DNF, Windows Update, etc.)',
category: 'system',
},
storage: {
icon: <HardDrive className="h-4 w-4" />,
name: 'Disk Usage Reporter',
description: 'Reports disk usage metrics and storage availability',
category: 'storage',
},
system: {
icon: <Cpu className="h-4 w-4" />,
name: 'System Metrics Scanner',
description: 'Reports CPU, memory, processes, and system uptime',
category: 'system',
},
docker: {
icon: <Container className="h-4 w-4" />,
name: 'Docker Image Scanner',
description: 'Scans Docker containers for available image updates',
category: 'system',
},
};
export function AgentScanners({ agentId }: AgentScannersProps) {
const queryClient = useQueryClient();
// Fetch subsystems from API
const { data: subsystems = [], isLoading, refetch } = useQuery({
queryKey: ['subsystems', agentId],
queryFn: async () => {
const data = await agentApi.getSubsystems(agentId);
return data;
},
refetchInterval: 30000, // Refresh every 30 seconds
});
// Toggle subsystem enabled/disabled
const toggleSubsystemMutation = useMutation({
mutationFn: async ({ subsystem, enabled }: { subsystem: string; enabled: boolean }) => {
if (enabled) {
return await agentApi.enableSubsystem(agentId, subsystem);
} else {
return await agentApi.disableSubsystem(agentId, subsystem);
}
},
onSuccess: (data, variables) => {
toast.success(`${subsystemConfig[variables.subsystem]?.name || variables.subsystem} ${variables.enabled ? 'enabled' : 'disabled'}`);
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
},
onError: (error: any, variables) => {
toast.error(`Failed to ${variables.enabled ? 'enable' : 'disable'} subsystem: ${error.response?.data?.error || error.message}`);
},
});
// Update subsystem interval
const updateIntervalMutation = useMutation({
mutationFn: async ({ subsystem, intervalMinutes }: { subsystem: string; intervalMinutes: number }) => {
return await agentApi.setSubsystemInterval(agentId, subsystem, intervalMinutes);
},
onSuccess: (data, variables) => {
toast.success(`Interval updated to ${variables.intervalMinutes} minutes`);
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
},
onError: (error: any) => {
toast.error(`Failed to update interval: ${error.response?.data?.error || error.message}`);
},
});
// Toggle auto-run
const toggleAutoRunMutation = useMutation({
mutationFn: async ({ subsystem, autoRun }: { subsystem: string; autoRun: boolean }) => {
return await agentApi.setSubsystemAutoRun(agentId, subsystem, autoRun);
},
onSuccess: (data, variables) => {
toast.success(`Auto-run ${variables.autoRun ? 'enabled' : 'disabled'}`);
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
},
onError: (error: any) => {
toast.error(`Failed to toggle auto-run: ${error.response?.data?.error || error.message}`);
},
});
// Trigger manual scan
const triggerScanMutation = useMutation({
mutationFn: async (subsystem: string) => {
return await agentApi.triggerSubsystem(agentId, subsystem);
},
onSuccess: (data, subsystem) => {
toast.success(`${subsystemConfig[subsystem]?.name || subsystem} scan triggered`);
queryClient.invalidateQueries({ queryKey: ['subsystems', agentId] });
},
onError: (error: any) => {
toast.error(`Failed to trigger scan: ${error.response?.data?.error || error.message}`);
},
});
const handleToggleEnabled = (subsystem: string, currentEnabled: boolean) => {
toggleSubsystemMutation.mutate({ subsystem, enabled: !currentEnabled });
};
const handleIntervalChange = (subsystem: string, intervalMinutes: number) => {
updateIntervalMutation.mutate({ subsystem, intervalMinutes });
};
const handleToggleAutoRun = (subsystem: string, currentAutoRun: boolean) => {
toggleAutoRunMutation.mutate({ subsystem, autoRun: !currentAutoRun });
};
const handleTriggerScan = (subsystem: string) => {
triggerScanMutation.mutate(subsystem);
};
const frequencyOptions = [
{ value: 5, label: '5 min' },
{ value: 15, label: '15 min' },
{ value: 30, label: '30 min' },
{ value: 60, label: '1 hour' },
{ value: 240, label: '4 hours' },
{ value: 720, label: '12 hours' },
{ value: 1440, label: '24 hours' },
];
const getFrequencyLabel = (frequency: number) => {
if (frequency < 60) return `${frequency}m`;
if (frequency < 1440) return `${frequency / 60}h`;
return `${frequency / 1440}d`;
};
const enabledCount = subsystems.filter(s => s.enabled).length;
const autoRunCount = subsystems.filter(s => s.auto_run && s.enabled).length;
return (
<div className="space-y-6">
{/* Compact Summary */}
<div className="card">
<div className="flex items-center justify-between text-sm">
<div className="flex items-center space-x-6">
<div>
<span className="text-gray-600">Enabled:</span>
<span className="ml-2 font-medium text-green-600">{enabledCount}/{subsystems.length}</span>
</div>
<div>
<span className="text-gray-600">Auto-Run:</span>
<span className="ml-2 font-medium text-blue-600">{autoRunCount}</span>
</div>
</div>
<button
onClick={() => refetch()}
disabled={isLoading}
className="flex items-center space-x-1 px-3 py-1 text-xs text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded transition-colors"
>
<RefreshCw className={cn('h-3 w-3', isLoading && 'animate-spin')} />
<span>Refresh</span>
</button>
</div>
</div>
{/* Subsystem Configuration Table */}
<div className="card">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-gray-900">Subsystem Configuration</h3>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<RefreshCw className="h-6 w-6 animate-spin text-gray-400" />
<span className="ml-2 text-gray-600">Loading subsystems...</span>
</div>
) : subsystems.length === 0 ? (
<div className="text-center py-12">
<Activity className="mx-auto h-12 w-12 text-gray-400" />
<h3 className="mt-2 text-sm font-medium text-gray-900">No subsystems found</h3>
<p className="mt-1 text-sm text-gray-500">
Subsystems will be created automatically when the agent checks in.
</p>
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full text-sm">
<thead>
<tr className="border-b border-gray-200">
<th className="text-left py-2 pr-4 font-medium text-gray-700">Subsystem</th>
<th className="text-left py-2 pr-4 font-medium text-gray-700">Category</th>
<th className="text-center py-2 pr-4 font-medium text-gray-700">Enabled</th>
<th className="text-center py-2 pr-4 font-medium text-gray-700">Auto-Run</th>
<th className="text-center py-2 pr-4 font-medium text-gray-700">Interval</th>
<th className="text-right py-2 pr-4 font-medium text-gray-700">Last Run</th>
<th className="text-right py-2 pr-4 font-medium text-gray-700">Next Run</th>
<th className="text-center py-2 font-medium text-gray-700">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{subsystems.map((subsystem: AgentSubsystem) => {
const config = subsystemConfig[subsystem.subsystem] || {
icon: <Activity className="h-4 w-4" />,
name: subsystem.subsystem,
description: 'Custom subsystem',
category: 'system',
};
return (
<tr key={subsystem.id} className="hover:bg-gray-50">
{/* Subsystem Name */}
<td className="py-3 pr-4 text-gray-900">
<div className="flex items-center space-x-2">
<span className="text-gray-600">{config.icon}</span>
<div>
<div className="font-medium">{config.name}</div>
<div className="text-xs text-gray-500">{config.description}</div>
</div>
</div>
</td>
{/* Category */}
<td className="py-3 pr-4 text-gray-600 capitalize text-xs">{config.category}</td>
{/* Enabled Toggle */}
<td className="py-3 pr-4 text-center">
<button
onClick={() => handleToggleEnabled(subsystem.subsystem, subsystem.enabled)}
disabled={toggleSubsystemMutation.isPending}
className={cn(
'px-3 py-1 rounded text-xs font-medium transition-colors',
subsystem.enabled
? 'bg-green-100 text-green-700 hover:bg-green-200'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
)}
>
{subsystem.enabled ? 'ON' : 'OFF'}
</button>
</td>
{/* Auto-Run Toggle */}
<td className="py-3 pr-4 text-center">
<button
onClick={() => handleToggleAutoRun(subsystem.subsystem, subsystem.auto_run)}
disabled={!subsystem.enabled || toggleAutoRunMutation.isPending}
className={cn(
'px-3 py-1 rounded text-xs font-medium transition-colors',
!subsystem.enabled ? 'bg-gray-50 text-gray-400 cursor-not-allowed' :
subsystem.auto_run
? 'bg-blue-100 text-blue-700 hover:bg-blue-200'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
)}
>
{subsystem.auto_run ? 'AUTO' : 'MANUAL'}
</button>
</td>
{/* Interval Selector */}
<td className="py-3 pr-4 text-center">
{subsystem.enabled ? (
<select
value={subsystem.interval_minutes}
onChange={(e) => handleIntervalChange(subsystem.subsystem, parseInt(e.target.value))}
disabled={updateIntervalMutation.isPending}
className="px-2 py-1 text-xs border border-gray-300 rounded hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
{frequencyOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
) : (
<span className="text-xs text-gray-400">-</span>
)}
</td>
{/* Last Run */}
<td className="py-3 pr-4 text-right text-xs text-gray-600">
{subsystem.last_run_at ? formatRelativeTime(subsystem.last_run_at) : '-'}
</td>
{/* Next Run */}
<td className="py-3 pr-4 text-right text-xs text-gray-600">
{subsystem.next_run_at && subsystem.auto_run ? formatRelativeTime(subsystem.next_run_at) : '-'}
</td>
{/* Actions */}
<td className="py-3 text-center">
<button
onClick={() => handleTriggerScan(subsystem.subsystem)}
disabled={!subsystem.enabled || triggerScanMutation.isPending}
className={cn(
'px-3 py-1 rounded text-xs font-medium transition-colors inline-flex items-center space-x-1',
!subsystem.enabled
? 'bg-gray-50 text-gray-400 cursor-not-allowed'
: 'bg-blue-100 text-blue-700 hover:bg-blue-200'
)}
title="Trigger manual scan"
>
<Play className="h-3 w-3" />
<span>Scan</span>
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
{/* Compact note */}
<div className="text-xs text-gray-500">
Subsystems report specific metrics to the server on scheduled intervals. Enable auto-run to schedule automatic scans, or trigger manual scans as needed.
</div>
</div>
);
}